arkgate 4.8.17 → 4.8.18

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.
@@ -15,4 +15,4 @@ ${n}`),this.name="PolicyViolationError",this.violations=e}};var _=class{static{s
15
15
  `;for(let i of o)r+=` ${this.safeId(i)}[${i}]
16
16
  `;r+=` end
17
17
  `}for(let i of this.edges){let a=i.kind?`|${i.kind}|`:"";r+=` ${this.safeId(i.from)} -->${a} ${this.safeId(i.to)}
18
- `}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 c of this.edges)e.has(c.from)||e.set(c.from,[]),e.get(c.from).push(c.to);let n=[],r=new Set,o=[],i=s(c=>{r.add(c),o.push(c);for(let d of e.get(c)||[])if(!r.has(d))i(d);else if(o.includes(d)){let l=o.indexOf(d),u=o.slice(l).concat(d);n.push(u)}o.pop()},"dfs");for(let c of e.keys())r.has(c)||i(c);let a=new Set(n.map(c=>c.join("->")));return Array.from(a).map(c=>c.split("->"))}safeId(e){return e.replace(/[^a-zA-Z0-9_]/g,"_")}};function rt(){return new Se}s(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"))}s(ot,"syncRegistryToGraph");var ce=class{static{s(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=s(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 as=new ce;function it(){return new ce}s(it,"createIntentRegistry");var D={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},cn={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...D,default:[]},kernelRoots:{...D},managedLayers:{...D,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},dn={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...D,default:[]},managedLayers:{...D,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...D,default:[]},appliesTo:{...D,default:[]}}};var ln="1.3",Vr=["public","auth","admin","internal"];var un="https://unpkg.com/arkgate@4/schemas/ark.config.schema.json",pn=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Ur=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Wr(){let t=[];for(let e of pn)for(let n of pn)e===n||Ur.has(`${e}->${n}`)||t.push({from:e,to:n,allowed:!1});return t}s(Wr,"createDefaultRules");var st=Wr();var w={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},vs={$schema:"https://json-schema.org/draft/2020-12/schema",$id:un,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:un,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:ln,default:ln},name:{type:"string",minLength:1},include:{...w,minItems:1,default:["src"]},exclude:{...w,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:st,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...w,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},coverage:{$ref:"#/$defs/coverage"},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},arkRun:{$ref:"#/$defs/arkRun"},arkOrder:{$ref:"#/$defs/arkOrder"},stewards:{...w,default:[]},requireLayerOwners:{type:"boolean"}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...w,minItems:1},exclude:w,intentPrefixes:w,description:{type:"string",minLength:1},trustBoundary:{type:"string",enum:[...Vr]},owners:{...w,minItems:1},forbiddenGlobals:w,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:{...w,minItems:1},sharedRoots:{...w,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}}}}}},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:{...w,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:{...w,minItems:1}}},arkRun:cn,arkOrder:dn}};function qr(t){return t.endsWith(".")?t:`${t}.`}s(qr,"normalizePrefix");function zr(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}s(zr,"byLongestPrefix");function fn(t){let e=t.layers.map(o=>({...o,prefixes:o.prefixes.map(qr)})),n=[...e].sort(zr),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(a=>o.startsWith(a)))?.name}}}s(fn,"createArchitectureProfile");var Jr=[{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}],at=fn({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:Jr,rules:st.map(t=>({...t}))});var gn="4.8.17";function Xr(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}s(Xr,"policyId");var ct=class{constructor(e){this.data=e}data;static{s(this,"ArkManifestImpl")}toJSON(){return{...this.data}}};function dt(t={}){let e=t.registry,n=t.policyEngine,r=t.metadata,o=t.graph,i=t.profile,a=t.projections,c=t.eventContracts,d=t.observability,l=e?e.list().map(m=>({name:m.name,dependencies:e.getDependencies(m.name),productions:e.getProductions(m.name)})):[],u=e?e.getAllRelationships():[],y=n?n.getPolicies().map(m=>({id:Xr(m.name),name:m.name,severity:m.severity,tags:m.tags?[...m.tags]:void 0,owner:m.owner,version:m.version,rationale:m.rationale,enforcementMode:m.enforcementMode,deprecated:m.deprecated,replacedBy:m.replacedBy,description:m.tags?.includes("layer")?"Enforces clean-architecture layer dependency rules on declared relationships.":void 0})):[],f=r?r.toJSON():[],g=o?o.toJSON():{nodes:[],edges:[]},h=f.filter(m=>(m.emits?.length??0)>0||(m.consumes?.length??0)>0).map(m=>({entity:m.name,emits:m.emits,consumes:m.consumes})),p=a?a.list().map(m=>({name:m.name,sourceIntents:m.sourceIntents,checkpoint:a.getCheckpoint(m.name)})):[],B={schemaVersion:"1.0",version:gn,exportedAt:new Date().toISOString(),intents:l,relationships:u,policies:y,entities:f,graph:g,architecture:i?{profile:i.name,layers:i.layers,rules:i.rules}:void 0,projections:p,eventContracts:c?.list()??[],observability:d?.report(),links:{entityIntents:h}};return new ct(B)}s(dt,"createArkManifest");var xe=class{static{s(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 lt(){return new xe}s(lt,"createMetadataRegistry");function ut(t){return`${t.from}->${t.to}`}s(ut,"flowKey");function yn(t){let e=new Set,n=[];for(let r of t){let o=ut(r);e.has(o)||(e.add(o),n.push(r))}return n}s(yn,"uniqueFlows");function hn(t,e){let n=new Set(e.map(ut));return t.filter(r=>!n.has(ut(r)))}s(hn,"difference");function pt(t){let e=t.registry,n=t.eventBus,r=t.graph;return{report(){let o=e?e.getAllRelationships().filter(p=>p.kind==="produces").map(p=>({from:p.from,to:p.to})):[],i=o.length>0||!r?[]:r.getEdges().filter(p=>p.kind==="produces").map(p=>({from:p.from,to:p.to})),a=n?.getHistory().map(p=>({from:p.event.metadata.source,to:p.event.intent}))??[],c=a.length>0||!r?[]:r.getEdges().filter(p=>p.kind==="observed").map(p=>({from:p.from,to:p.to})),d=yn([...o,...i]),l=yn([...a,...c]),u=l.filter(p=>!p.from||p.from==="unknown"),y=e?Array.from(new Set(l.map(p=>p.from).filter(p=>p&&p!=="unknown"&&!e.has(p)))):[],f=e?Array.from(new Set(l.map(p=>p.to).filter(p=>!e.has(p)))):[],g=new Set(l.flatMap(p=>[p.from,p.to])),h=e?e.list().map(p=>p.name).filter(p=>!g.has(p)):[];return{generatedAt:new Date().toISOString(),declaredProductions:d,observedProductions:l,declaredButUnobserved:hn(d,l),observedButUndeclared:hn(l.filter(p=>p.from!=="unknown"),d),unknownSources:u,unregisteredObservedSources:y,unregisteredObservedIntents:f,registeredButNeverObserved:h}}}}s(pt,"createObservabilityReporter");var kn=0;function Zr(){return kn+=1,`outbox-${Date.now()}-${kn}`}s(Zr,"nextOutboxId");function wn(t){return{...t,event:{...t.event,metadata:{...t.event.metadata}}}}s(wn,"cloneRecord");var de=class{static{s(this,"InMemoryEventBuffer")}records=new Map;async enqueue(e){let n=new Date().toISOString(),r={id:Zr(),event:e,status:"pending",attempts:0,createdAt:n,updatedAt:n};return this.records.set(r.id,r),wn(r)}async markDispatched(e){let n=this.records.get(e);n&&(n.status="dispatched",n.updatedAt=new Date().toISOString())}async markFailed(e,n){let r=this.records.get(e);r&&(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(wn)}async clear(){this.records.clear()}};var Ee=class{static{s(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 Yr(t){return typeof t.initialState=="function"?t.initialState():t.initialState}s(Yr,"initialState");var Pe=class{static{s(this,"ProjectionRegistryImpl")}definitions=new Map;checkpoints=new Map;store;auditTrail;constructor(e={}){this.store=e.store??new Ee,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)??Yr(r),i=await r.project(e,o);await this.store.save(r.name,i);let a=this.checkpoints.get(r.name);this.checkpoints.set(r.name,{projection:r.name,appliedCount:(a?.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 ft(t){return new Pe(t)}s(ft,"createProjectionRegistry");var Rn=0;function eo(t){return Rn+=1,`${t}-${Date.now()}-${Rn}`}s(eo,"createWorkflowId");function gt(t){return t instanceof Error?t.message:String(t)}s(gt,"errorMessage");function to(t){return new Promise(e=>{setTimeout(e,t)})}s(to,"sleep");async function no(t,e,n){let r=new AbortController;if(e===void 0)return t(r.signal);let o,i=new Promise((a,c)=>{o=setTimeout(()=>{let d=new Error(`Workflow step "${n}" timed out after ${e}ms.`);r.abort(d),c(d)},e)});try{return await Promise.race([t(r.signal),i])}finally{o&&clearTimeout(o)}}s(no,"withTimeout");var ve=class{static{s(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 a=i.expiresAt?new Date(i.expiresAt).getTime()<o:!0;if(!i.ownerId||a){i.ownerId=e,i.expiresAt=new Date(o+n).toISOString();let c=(i.version??0)+1;return i.version=c,this.snapshots.set(i.id,{...i,context:{...i.context}}),{...i,context:{...i.context}}}}}clear(){this.snapshots.clear()}},mt=class{constructor(e,n={}){this.bus=e;this.options=n;this.store=n.store??new ve}bus;options;static{s(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(),a={id:r.id??eo(e),version:0,workflowName:e,status:"running",context:{...n},completedSteps:[],attempts:{},startedAt:i,updatedAt:i};return await this.store.save(a,r.tx),await this.audit("workflow.started",a,{workflowName:e}),this.executeSnapshot(a,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=gt(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 a=1;a<=i;a+=1){e.attempts[n.name]=a,await this.store.save(e,r);let c;try{c=await no(d=>Promise.resolve(n.execute(e.context,this.bus,d)),n.timeoutMs,n.name)}catch(d){if(a<i){o.delayMs&&await to(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:a,error:gt(d)}),d}c&&Object.assign(e.context,c),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:a});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(a=>e.completedSteps.includes(a.name));for(let a=i.length-1;a>=0;a-=1){let c=i[a];if(c.compensate)try{await Promise.resolve(c.compensate(e.context,this.bus,r)),await this.audit("workflow.compensation.completed",e,{step:c.name})}catch(d){await this.audit("workflow.step.failed",e,{step:c.name,compensation:!0,error:gt(d)})}}}async audit(e,n,r){await this.options.auditTrail?.record({type:e,source:"Kernel.WorkflowEngine",subject:n.id,details:r})}};function yt(t,e){return new mt(t,e)}s(yt,"createWorkflowEngine");H();var ro=new Set(["singleton","transient"]);function An(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}s(An,"cloneComponent");function oo(t){if(t===void 0)return"singleton";if(typeof t=="string"&&ro.has(t))return t;throw new Error('ArkRun component lifetime must be "singleton" or "transient".')}s(oo,"closedLifetime");function In(){let t=new Map,e=new Map,n=new Set;function r(a){let c=t.get(a);if(!c)throw new Error(`ArkRun component "${a}" is not registered.`);return c}s(r,"mustRecord");function o(a,c){if(!c.factory)throw new Error(`ArkRun component "${a}" has no factory; declarations-only registrations cannot be resolved.`);if(n.has(a))throw new Error(`ArkRun component "${a}" has a circular resolve.`);n.add(a);try{return c.factory()}finally{n.delete(a)}}s(o,"instantiate");function i(a,c){if(e.has(a))return e.get(a);let d=o(a,c);return e.set(a,d),d}return s(i,"singleton"),{register(a){let c=typeof a?.id=="string"?a.id.trim():"";if(!c)throw new Error("ArkRun component id must be a non-empty string.");if(t.has(c))throw new Error(`ArkRun component "${c}" is already registered.`);let d=oo(a.lifetime),l=Me({id:c,lifetime:d,uses:a.uses,reactsTo:a.reactsTo,raises:a.raises,sends:a.sends,extendedInfo:a.extendedInfo});if(!l)throw new Error("ArkRun component id must be a non-empty string.");let u=typeof a.factory=="function"?a.factory:void 0;return t.set(c,{component:l,factory:u}),An(l)},resolve(a){let c=r(a);return c.component.lifetime==="transient"?o(a,c):i(a,c)},resolveSingleton(a){let c=r(a);if(c.component.lifetime==="transient")throw new Error(`ArkRun component "${a}" is transient; resolveSingleton requires lifetime "singleton".`);return i(a,c)},snapshotComponents(){return[...t.values()].map(a=>An(a.component))}}}s(In,"createComponentRegistry");ke();async function xn(t,e={}){let n=Ue({host:e.host,port:e.port,nodeEnv:e.nodeEnv,processNodeEnv:process.env.NODE_ENV}),{listenArkRunInspector:r}=await Promise.resolve().then(()=>(Sn(),bn));return r(t,{bind:n,sseIntervalMs:e.sseIntervalMs})}s(xn,"startArkRunInspector");ge();function fo(t){let e={...t.metadata??{}};if(t.source===void 0)return e;if(e.source&&e.source!==t.source)throw new N(t.source,e.source);return e.source=t.source,e}s(fo,"stampMetadata");function go(){}s(go,"ignoreDetachedFailure");async function ht(t,e,n,r={}){let o=Nt({transport:r.transport,ephemeral:r.ephemeral??t.defaultEphemeral,brokerBound:typeof t.broker?.send=="function"}),i=fo(r),a=await t.eventBus.dispatch(e,n,i,{notifySubscribers:o.notifySubscribers,awaitHandlers:o.awaitHandlers});if(o.deliveredVia==="broker"&&t.broker){let c=Promise.resolve(t.broker.send(a));o.awaitHandoff?await c:c.then(void 0,go)}return o}s(ht,"sendOnArkRunTransport");var mo=1e3,En=0;function yo(){return En+=1,`ark-kernel-${Date.now()}-${En}`}s(yo,"nextKernelInstanceId");function Pn(t,e){let n=t.constructor?.name;return typeof n=="string"&&n.length>0?n:e}s(Pn,"portConstructorId");function vn(t={}){let e=t.strict??!0,n=t.instanceId??yo(),r=t.profile??at,o=t.maxHistorySize??mo,i=it(),a=rt(),c=t.metadata??lt(),d=t.auditTrail===void 0,l=t.auditTrail??ze({maxRecords:o}),u=t.eventContracts??nt(),y=t.eventBuffer===void 0&&t.outbox===void 0,f=t.eventBuffer??t.outbox??new de,g=t.projections??ft({auditTrail:l}),h=new _([Qe(r),...t.policies??[]]),p=s(()=>{ot(i,a,{requireRegisteredTargets:!0})},"syncGraph"),B=t.ephemeral??!0,m=t.broker,T=new ae({intentRegistry:i,dependencyGraph:a,policyEngine:h,strictRegistry:!0,validateIntentNaming:!0,auditTrail:l,eventContracts:u,strictEventContracts:t.strictEventContracts??e,requireKnownSource:t.requireKnownSource??!0,architectureProfile:r,enforceObservedLayerFlow:t.enforceObservedLayerFlow??(e?"hard":"off"),eventBuffer:f,instanceId:n,maxHistorySize:o,onPublish:t.autoApplyProjections===!1?void 0:async k=>{await g.apply(k)}}),kt=yt(T,{auditTrail:l}),Ce=pt({registry:i,eventBus:T,graph:a}),M=In(),Cn=typeof m?.send=="function",On=y?"InMemoryEventBuffer":Pn(f,"EventBufferStore"),Nn=d?"InMemoryAuditStore":Pn(l,"AuditTrail"),Dn=We({stores:[Q(On,"outbox"),Q(Nn,"audit"),Q("InMemoryWorkflowStore","workflow")]}),Oe={instanceId:n,profile:r,registry:i,graph:a,metadata:c,auditTrail:l,eventContracts:u,eventBuffer:f,outbox:f,projections:g,policyEngine:h,eventBus:T,workflowEngine:kt,observability:Ce,publisher(k){let L=T.createPublisher(k);return{source:L.source,publish:L.publish,send(S,Ne,Tn={}){return ht({eventBus:T,broker:m,defaultEphemeral:B},S,Ne,{...Tn,source:L.source})}}},send(k,L,S={}){return ht({eventBus:T,broker:m,defaultEphemeral:B},k,L,S)},register(k){return M.register(k)},resolve(k){return M.resolve(k)},resolveSingleton(k){return M.resolveSingleton(k)},getDependencyInformationPackage(){return v({kernelInstanceId:n,components:M.snapshotComponents()})},requestGraph(k){return Ot({kernelInstanceId:n,components:M.snapshotComponents()},k)},getInspectorSnapshot(k){return _t({kernelInstanceId:n,host:k?.host,port:k?.port,package:{kernelInstanceId:n,components:M.snapshotComponents()},observability:Ce.report(),ephemeralDefault:B,brokerBound:Cn,hardening:Dn})},startInspector(k){return xn({getInspectorSnapshot:s(S=>Oe.getInspectorSnapshot(S),"getInspectorSnapshot"),requestGraph:s(S=>Oe.requestGraph(S),"requestGraph"),async listInspectorOutbox(){let[S,Ne]=await Promise.all([f.list("pending"),f.list("failed")]);return X([...S,...Ne],{sampleLimit:A})},async listInspectorWorkflows(){return Z(await kt.list(),{sampleLimit:A})}},k)},syncGraph:p,manifest(){return p(),dt({registry:i,policyEngine:h,metadata:c,graph:a,profile:r,projections:g,eventContracts:u,observability:Ce})}};return Oe}s(vn,"createArkKernel");var le=Symbol("ARK_KERNEL"),oc=s(()=>ho(le),"InjectArk"),P=class{static forRoot(e){let n=e&&"registry"in e?e:vn(e);return{module:P,global:!0,providers:[{provide:le,useValue:n}],exports:[le]}}static forRootAsync(e){return{module:P,global:!0,providers:[{provide:le,useFactory:e.useFactory,inject:e.inject??[]}],exports:[le]}}};s(P,"ArkModule"),P=wt([ko({})],P);export{le as ARK_KERNEL,P as ArkModule,oc as InjectArk};
18
+ `}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 c of this.edges)e.has(c.from)||e.set(c.from,[]),e.get(c.from).push(c.to);let n=[],r=new Set,o=[],i=s(c=>{r.add(c),o.push(c);for(let d of e.get(c)||[])if(!r.has(d))i(d);else if(o.includes(d)){let l=o.indexOf(d),u=o.slice(l).concat(d);n.push(u)}o.pop()},"dfs");for(let c of e.keys())r.has(c)||i(c);let a=new Set(n.map(c=>c.join("->")));return Array.from(a).map(c=>c.split("->"))}safeId(e){return e.replace(/[^a-zA-Z0-9_]/g,"_")}};function rt(){return new Se}s(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"))}s(ot,"syncRegistryToGraph");var ce=class{static{s(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=s(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 as=new ce;function it(){return new ce}s(it,"createIntentRegistry");var D={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},cn={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...D,default:[]},kernelRoots:{...D},managedLayers:{...D,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},dn={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...D,default:[]},managedLayers:{...D,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...D,default:[]},appliesTo:{...D,default:[]}}};var ln="1.3",Vr=["public","auth","admin","internal"];var un="https://unpkg.com/arkgate@4/schemas/ark.config.schema.json",pn=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Ur=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Wr(){let t=[];for(let e of pn)for(let n of pn)e===n||Ur.has(`${e}->${n}`)||t.push({from:e,to:n,allowed:!1});return t}s(Wr,"createDefaultRules");var st=Wr();var w={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},vs={$schema:"https://json-schema.org/draft/2020-12/schema",$id:un,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:un,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:ln,default:ln},name:{type:"string",minLength:1},include:{...w,minItems:1,default:["src"]},exclude:{...w,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:st,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...w,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},coverage:{$ref:"#/$defs/coverage"},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},arkRun:{$ref:"#/$defs/arkRun"},arkOrder:{$ref:"#/$defs/arkOrder"},stewards:{...w,default:[]},requireLayerOwners:{type:"boolean"}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...w,minItems:1},exclude:w,intentPrefixes:w,description:{type:"string",minLength:1},trustBoundary:{type:"string",enum:[...Vr]},owners:{...w,minItems:1},forbiddenGlobals:w,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:{...w,minItems:1},sharedRoots:{...w,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}}}}}},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:{...w,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:{...w,minItems:1}}},arkRun:cn,arkOrder:dn}};function qr(t){return t.endsWith(".")?t:`${t}.`}s(qr,"normalizePrefix");function zr(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}s(zr,"byLongestPrefix");function fn(t){let e=t.layers.map(o=>({...o,prefixes:o.prefixes.map(qr)})),n=[...e].sort(zr),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(a=>o.startsWith(a)))?.name}}}s(fn,"createArchitectureProfile");var Jr=[{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}],at=fn({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:Jr,rules:st.map(t=>({...t}))});var gn="4.8.18";function Xr(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}s(Xr,"policyId");var ct=class{constructor(e){this.data=e}data;static{s(this,"ArkManifestImpl")}toJSON(){return{...this.data}}};function dt(t={}){let e=t.registry,n=t.policyEngine,r=t.metadata,o=t.graph,i=t.profile,a=t.projections,c=t.eventContracts,d=t.observability,l=e?e.list().map(m=>({name:m.name,dependencies:e.getDependencies(m.name),productions:e.getProductions(m.name)})):[],u=e?e.getAllRelationships():[],y=n?n.getPolicies().map(m=>({id:Xr(m.name),name:m.name,severity:m.severity,tags:m.tags?[...m.tags]:void 0,owner:m.owner,version:m.version,rationale:m.rationale,enforcementMode:m.enforcementMode,deprecated:m.deprecated,replacedBy:m.replacedBy,description:m.tags?.includes("layer")?"Enforces clean-architecture layer dependency rules on declared relationships.":void 0})):[],f=r?r.toJSON():[],g=o?o.toJSON():{nodes:[],edges:[]},h=f.filter(m=>(m.emits?.length??0)>0||(m.consumes?.length??0)>0).map(m=>({entity:m.name,emits:m.emits,consumes:m.consumes})),p=a?a.list().map(m=>({name:m.name,sourceIntents:m.sourceIntents,checkpoint:a.getCheckpoint(m.name)})):[],B={schemaVersion:"1.0",version:gn,exportedAt:new Date().toISOString(),intents:l,relationships:u,policies:y,entities:f,graph:g,architecture:i?{profile:i.name,layers:i.layers,rules:i.rules}:void 0,projections:p,eventContracts:c?.list()??[],observability:d?.report(),links:{entityIntents:h}};return new ct(B)}s(dt,"createArkManifest");var xe=class{static{s(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 lt(){return new xe}s(lt,"createMetadataRegistry");function ut(t){return`${t.from}->${t.to}`}s(ut,"flowKey");function yn(t){let e=new Set,n=[];for(let r of t){let o=ut(r);e.has(o)||(e.add(o),n.push(r))}return n}s(yn,"uniqueFlows");function hn(t,e){let n=new Set(e.map(ut));return t.filter(r=>!n.has(ut(r)))}s(hn,"difference");function pt(t){let e=t.registry,n=t.eventBus,r=t.graph;return{report(){let o=e?e.getAllRelationships().filter(p=>p.kind==="produces").map(p=>({from:p.from,to:p.to})):[],i=o.length>0||!r?[]:r.getEdges().filter(p=>p.kind==="produces").map(p=>({from:p.from,to:p.to})),a=n?.getHistory().map(p=>({from:p.event.metadata.source,to:p.event.intent}))??[],c=a.length>0||!r?[]:r.getEdges().filter(p=>p.kind==="observed").map(p=>({from:p.from,to:p.to})),d=yn([...o,...i]),l=yn([...a,...c]),u=l.filter(p=>!p.from||p.from==="unknown"),y=e?Array.from(new Set(l.map(p=>p.from).filter(p=>p&&p!=="unknown"&&!e.has(p)))):[],f=e?Array.from(new Set(l.map(p=>p.to).filter(p=>!e.has(p)))):[],g=new Set(l.flatMap(p=>[p.from,p.to])),h=e?e.list().map(p=>p.name).filter(p=>!g.has(p)):[];return{generatedAt:new Date().toISOString(),declaredProductions:d,observedProductions:l,declaredButUnobserved:hn(d,l),observedButUndeclared:hn(l.filter(p=>p.from!=="unknown"),d),unknownSources:u,unregisteredObservedSources:y,unregisteredObservedIntents:f,registeredButNeverObserved:h}}}}s(pt,"createObservabilityReporter");var kn=0;function Zr(){return kn+=1,`outbox-${Date.now()}-${kn}`}s(Zr,"nextOutboxId");function wn(t){return{...t,event:{...t.event,metadata:{...t.event.metadata}}}}s(wn,"cloneRecord");var de=class{static{s(this,"InMemoryEventBuffer")}records=new Map;async enqueue(e){let n=new Date().toISOString(),r={id:Zr(),event:e,status:"pending",attempts:0,createdAt:n,updatedAt:n};return this.records.set(r.id,r),wn(r)}async markDispatched(e){let n=this.records.get(e);n&&(n.status="dispatched",n.updatedAt=new Date().toISOString())}async markFailed(e,n){let r=this.records.get(e);r&&(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(wn)}async clear(){this.records.clear()}};var Ee=class{static{s(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 Yr(t){return typeof t.initialState=="function"?t.initialState():t.initialState}s(Yr,"initialState");var Pe=class{static{s(this,"ProjectionRegistryImpl")}definitions=new Map;checkpoints=new Map;store;auditTrail;constructor(e={}){this.store=e.store??new Ee,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)??Yr(r),i=await r.project(e,o);await this.store.save(r.name,i);let a=this.checkpoints.get(r.name);this.checkpoints.set(r.name,{projection:r.name,appliedCount:(a?.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 ft(t){return new Pe(t)}s(ft,"createProjectionRegistry");var Rn=0;function eo(t){return Rn+=1,`${t}-${Date.now()}-${Rn}`}s(eo,"createWorkflowId");function gt(t){return t instanceof Error?t.message:String(t)}s(gt,"errorMessage");function to(t){return new Promise(e=>{setTimeout(e,t)})}s(to,"sleep");async function no(t,e,n){let r=new AbortController;if(e===void 0)return t(r.signal);let o,i=new Promise((a,c)=>{o=setTimeout(()=>{let d=new Error(`Workflow step "${n}" timed out after ${e}ms.`);r.abort(d),c(d)},e)});try{return await Promise.race([t(r.signal),i])}finally{o&&clearTimeout(o)}}s(no,"withTimeout");var ve=class{static{s(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 a=i.expiresAt?new Date(i.expiresAt).getTime()<o:!0;if(!i.ownerId||a){i.ownerId=e,i.expiresAt=new Date(o+n).toISOString();let c=(i.version??0)+1;return i.version=c,this.snapshots.set(i.id,{...i,context:{...i.context}}),{...i,context:{...i.context}}}}}clear(){this.snapshots.clear()}},mt=class{constructor(e,n={}){this.bus=e;this.options=n;this.store=n.store??new ve}bus;options;static{s(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(),a={id:r.id??eo(e),version:0,workflowName:e,status:"running",context:{...n},completedSteps:[],attempts:{},startedAt:i,updatedAt:i};return await this.store.save(a,r.tx),await this.audit("workflow.started",a,{workflowName:e}),this.executeSnapshot(a,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=gt(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 a=1;a<=i;a+=1){e.attempts[n.name]=a,await this.store.save(e,r);let c;try{c=await no(d=>Promise.resolve(n.execute(e.context,this.bus,d)),n.timeoutMs,n.name)}catch(d){if(a<i){o.delayMs&&await to(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:a,error:gt(d)}),d}c&&Object.assign(e.context,c),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:a});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(a=>e.completedSteps.includes(a.name));for(let a=i.length-1;a>=0;a-=1){let c=i[a];if(c.compensate)try{await Promise.resolve(c.compensate(e.context,this.bus,r)),await this.audit("workflow.compensation.completed",e,{step:c.name})}catch(d){await this.audit("workflow.step.failed",e,{step:c.name,compensation:!0,error:gt(d)})}}}async audit(e,n,r){await this.options.auditTrail?.record({type:e,source:"Kernel.WorkflowEngine",subject:n.id,details:r})}};function yt(t,e){return new mt(t,e)}s(yt,"createWorkflowEngine");H();var ro=new Set(["singleton","transient"]);function An(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}s(An,"cloneComponent");function oo(t){if(t===void 0)return"singleton";if(typeof t=="string"&&ro.has(t))return t;throw new Error('ArkRun component lifetime must be "singleton" or "transient".')}s(oo,"closedLifetime");function In(){let t=new Map,e=new Map,n=new Set;function r(a){let c=t.get(a);if(!c)throw new Error(`ArkRun component "${a}" is not registered.`);return c}s(r,"mustRecord");function o(a,c){if(!c.factory)throw new Error(`ArkRun component "${a}" has no factory; declarations-only registrations cannot be resolved.`);if(n.has(a))throw new Error(`ArkRun component "${a}" has a circular resolve.`);n.add(a);try{return c.factory()}finally{n.delete(a)}}s(o,"instantiate");function i(a,c){if(e.has(a))return e.get(a);let d=o(a,c);return e.set(a,d),d}return s(i,"singleton"),{register(a){let c=typeof a?.id=="string"?a.id.trim():"";if(!c)throw new Error("ArkRun component id must be a non-empty string.");if(t.has(c))throw new Error(`ArkRun component "${c}" is already registered.`);let d=oo(a.lifetime),l=Me({id:c,lifetime:d,uses:a.uses,reactsTo:a.reactsTo,raises:a.raises,sends:a.sends,extendedInfo:a.extendedInfo});if(!l)throw new Error("ArkRun component id must be a non-empty string.");let u=typeof a.factory=="function"?a.factory:void 0;return t.set(c,{component:l,factory:u}),An(l)},resolve(a){let c=r(a);return c.component.lifetime==="transient"?o(a,c):i(a,c)},resolveSingleton(a){let c=r(a);if(c.component.lifetime==="transient")throw new Error(`ArkRun component "${a}" is transient; resolveSingleton requires lifetime "singleton".`);return i(a,c)},snapshotComponents(){return[...t.values()].map(a=>An(a.component))}}}s(In,"createComponentRegistry");ke();async function xn(t,e={}){let n=Ue({host:e.host,port:e.port,nodeEnv:e.nodeEnv,processNodeEnv:process.env.NODE_ENV}),{listenArkRunInspector:r}=await Promise.resolve().then(()=>(Sn(),bn));return r(t,{bind:n,sseIntervalMs:e.sseIntervalMs})}s(xn,"startArkRunInspector");ge();function fo(t){let e={...t.metadata??{}};if(t.source===void 0)return e;if(e.source&&e.source!==t.source)throw new N(t.source,e.source);return e.source=t.source,e}s(fo,"stampMetadata");function go(){}s(go,"ignoreDetachedFailure");async function ht(t,e,n,r={}){let o=Nt({transport:r.transport,ephemeral:r.ephemeral??t.defaultEphemeral,brokerBound:typeof t.broker?.send=="function"}),i=fo(r),a=await t.eventBus.dispatch(e,n,i,{notifySubscribers:o.notifySubscribers,awaitHandlers:o.awaitHandlers});if(o.deliveredVia==="broker"&&t.broker){let c=Promise.resolve(t.broker.send(a));o.awaitHandoff?await c:c.then(void 0,go)}return o}s(ht,"sendOnArkRunTransport");var mo=1e3,En=0;function yo(){return En+=1,`ark-kernel-${Date.now()}-${En}`}s(yo,"nextKernelInstanceId");function Pn(t,e){let n=t.constructor?.name;return typeof n=="string"&&n.length>0?n:e}s(Pn,"portConstructorId");function vn(t={}){let e=t.strict??!0,n=t.instanceId??yo(),r=t.profile??at,o=t.maxHistorySize??mo,i=it(),a=rt(),c=t.metadata??lt(),d=t.auditTrail===void 0,l=t.auditTrail??ze({maxRecords:o}),u=t.eventContracts??nt(),y=t.eventBuffer===void 0&&t.outbox===void 0,f=t.eventBuffer??t.outbox??new de,g=t.projections??ft({auditTrail:l}),h=new _([Qe(r),...t.policies??[]]),p=s(()=>{ot(i,a,{requireRegisteredTargets:!0})},"syncGraph"),B=t.ephemeral??!0,m=t.broker,T=new ae({intentRegistry:i,dependencyGraph:a,policyEngine:h,strictRegistry:!0,validateIntentNaming:!0,auditTrail:l,eventContracts:u,strictEventContracts:t.strictEventContracts??e,requireKnownSource:t.requireKnownSource??!0,architectureProfile:r,enforceObservedLayerFlow:t.enforceObservedLayerFlow??(e?"hard":"off"),eventBuffer:f,instanceId:n,maxHistorySize:o,onPublish:t.autoApplyProjections===!1?void 0:async k=>{await g.apply(k)}}),kt=yt(T,{auditTrail:l}),Ce=pt({registry:i,eventBus:T,graph:a}),M=In(),Cn=typeof m?.send=="function",On=y?"InMemoryEventBuffer":Pn(f,"EventBufferStore"),Nn=d?"InMemoryAuditStore":Pn(l,"AuditTrail"),Dn=We({stores:[Q(On,"outbox"),Q(Nn,"audit"),Q("InMemoryWorkflowStore","workflow")]}),Oe={instanceId:n,profile:r,registry:i,graph:a,metadata:c,auditTrail:l,eventContracts:u,eventBuffer:f,outbox:f,projections:g,policyEngine:h,eventBus:T,workflowEngine:kt,observability:Ce,publisher(k){let L=T.createPublisher(k);return{source:L.source,publish:L.publish,send(S,Ne,Tn={}){return ht({eventBus:T,broker:m,defaultEphemeral:B},S,Ne,{...Tn,source:L.source})}}},send(k,L,S={}){return ht({eventBus:T,broker:m,defaultEphemeral:B},k,L,S)},register(k){return M.register(k)},resolve(k){return M.resolve(k)},resolveSingleton(k){return M.resolveSingleton(k)},getDependencyInformationPackage(){return v({kernelInstanceId:n,components:M.snapshotComponents()})},requestGraph(k){return Ot({kernelInstanceId:n,components:M.snapshotComponents()},k)},getInspectorSnapshot(k){return _t({kernelInstanceId:n,host:k?.host,port:k?.port,package:{kernelInstanceId:n,components:M.snapshotComponents()},observability:Ce.report(),ephemeralDefault:B,brokerBound:Cn,hardening:Dn})},startInspector(k){return xn({getInspectorSnapshot:s(S=>Oe.getInspectorSnapshot(S),"getInspectorSnapshot"),requestGraph:s(S=>Oe.requestGraph(S),"requestGraph"),async listInspectorOutbox(){let[S,Ne]=await Promise.all([f.list("pending"),f.list("failed")]);return X([...S,...Ne],{sampleLimit:A})},async listInspectorWorkflows(){return Z(await kt.list(),{sampleLimit:A})}},k)},syncGraph:p,manifest(){return p(),dt({registry:i,policyEngine:h,metadata:c,graph:a,profile:r,projections:g,eventContracts:u,observability:Ce})}};return Oe}s(vn,"createArkKernel");var le=Symbol("ARK_KERNEL"),oc=s(()=>ho(le),"InjectArk"),P=class{static forRoot(e){let n=e&&"registry"in e?e:vn(e);return{module:P,global:!0,providers:[{provide:le,useValue:n}],exports:[le]}}static forRootAsync(e){return{module:P,global:!0,providers:[{provide:le,useFactory:e.useFactory,inject:e.inject??[]}],exports:[le]}}};s(P,"ArkModule"),P=wt([ko({})],P);export{le as ARK_KERNEL,P as ArkModule,oc as InjectArk};
@@ -2,7 +2,7 @@
2
2
  `)}function Xd(e,t,n){let r=new Set(e.keys());if(Qo(n.include)&&(r=new Set([...r].filter(l=>{let c=e.get(l);return c!==void 0&&va(c,n.include)}))),Qo(n.exclude))for(let l of[...r]){let c=e.get(l);c&&va(c,n.exclude)&&r.delete(l)}let o=t.filter(l=>r.has(l.from)&&r.has(l.to));n.nodeIds.length>0&&(r=qd(r,n.nodeIds,n.degreesOfSeparation,zd(o)));let s=[...r].sort(Dn).map(l=>e.get(l)).filter(l=>!!l),a=o.filter(l=>r.has(l.from)&&r.has(l.to)).sort((l,c)=>Dn(l.from,c.from)||Dn(l.kind,c.kind)||Dn(l.to,c.to));return{nodes:s,edges:a}}function $n(e={},t={}){let n=jd(e),r=Fn(t),o=Wd(n.components,r.slice),s=Xd(o.nodes,o.edges,r),a={schemaVersion:xr,kernelInstanceId:n.kernelInstanceId,slice:r.slice,query:r,nodes:s.nodes,edges:s.edges,mermaid:""};return a.mermaid=_r(a),a}var xr,Or,Pr,es,ts,ns,J,Hd,Gd,Ud,Tr=jt(()=>{"use strict";Ot();xr="1.0",Or="process",Pr=["process","technical"],es=["component","interaction"],ts=["raises","reactsTo","sends"],ns=["uses"],J=class extends Error{static{i(this,"InvalidArkRunGraphQueryError")}option;constructor(t,n){super(n??(t==="slice"?'ArkRun graph slice must be "process" or "technical".':t==="degreesOfSeparation"?"ArkRun graph degreesOfSeparation must be a non-negative integer.":`ArkRun graph ${t} is not a closed query.`)),this.name="InvalidArkRunGraphQueryError",this.option=t}},Hd=new Set(Pr),Gd=new Set(["slice","nodeIds","degreesOfSeparation","include","exclude"]),Ud=new Set(["ids","labels","tags","groups","architectureKinds"]);i(Dn,"compare");i(Jo,"uniqueSorted");i(Ia,"emptyMatch");i(Qo,"matchHasCriteria");i(me,"nameList");i(Sa,"globMatch");i(Tn,"anyGlob");i(wa,"closedSlice");i(Ca,"closedDegrees");i(ba,"closedMatch");i(Fn,"closeArkRunGraphQuery");i(Mn,"arkRunGraphQueryFromSearchParams");i(Vd,"nodeFields");i(va,"nodeMatches");i(jd,"asPackage");i(Bd,"componentNode");i(wr,"interactionNode");i(Nn,"addNode");i(Cr,"addEdge");i(Wd,"buildSlice");i(zd,"adjacency");i(qd,"neighborhood");i(Ln,"mermaidSafeId");i(Ea,"mermaidLabel");i(Yd,"uniqueMermaidIds");i(_r,"formatArkRunGraphMermaid");i(Xd,"filterGraph");i($n,"requestArkRunGraph")});function Nr(e){if(e===void 0)return"local";if(typeof e=="string"&&Zd.has(e))return e;throw new st("transport")}function Dr(e){if(e===void 0)return!0;if(e===!0||e===!1)return e;throw new st("ephemeral")}function Kn(e){let t=Nr(e.transport),n=Dr(e.ephemeral),r=t==="broker"&&e.brokerBound!==!0,o=t==="broker"&&!r?"broker":"local",s=t==="localBlocking";return{transport:t,ephemeral:n,deliveredVia:o,fallbackToLocal:r,notifySubscribers:o==="local",awaitHandlers:s,awaitHandoff:n||s}}var Pt,it,Zd,st,Hn=jt(()=>{"use strict";Pt=["local","localBlocking","broker"],it=!0,Zd=new Set(Pt),st=class extends Error{static{i(this,"InvalidArkRunSendOptionError")}option;constructor(t){super(t==="transport"?'ArkRun transport must be "local", "localBlocking", or "broker".':"ArkRun ephemeral must be a boolean."),this.name="InvalidArkRunSendOptionError",this.option=t}};i(Nr,"closedArkRunTransportKind");i(Dr,"closedArkRunEphemeral");i(Kn,"resolveArkRunSendPlan")});function Un(e){return e==="production"}function Qd(e){let t=e.split(".");if(t.length!==4)return;let n=[];for(let r of t){if(!/^\d{1,3}$/.test(r))return;let o=Number(r);if(o>255)return;n.push(o)}return n}function xa(e){if(e.startsWith("[::ffff:")&&e.endsWith("]"))return e.slice(8,-1);if(e.startsWith("::ffff:"))return e.slice(7)}function lt(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();if(t==="localhost"||t==="::1"||t==="[::1]")return!0;let n=xa(t);if(n)return lt(n);let r=Qd(t);return r!==void 0&&r[0]===127}function Oa(e){if(e===void 0)return Gn;if(typeof e!="string")throw new ie(String(e));let t=e.trim();if(Jd.has(t.toLowerCase())||!lt(t))throw new ie(t);let n=t.toLowerCase();if(n==="localhost")return Gn;if(n==="[::1]")return"::1";let r=xa(n);return r?Oa(r):n}function eu(e){if(e===void 0)return Fr;if(typeof e!="number"||!Number.isInteger(e)||e<0||e>65535)throw new ie(`port:${String(e)}`);return e}function Ft(e={}){if(Un(e.nodeEnv)||Un(e.processNodeEnv))throw new at;return{host:Oa(e.host),port:eu(e.port)}}function ye(e,t,n){return`http://${e.includes(":")?`[${e}]`:e}:${t}${n}`}function tu(e){if(e!==void 0)try{return JSON.parse(JSON.stringify(e))}catch{return}}function nu(e){return{kinds:[...Pt],ephemeralDefault:e.ephemeralDefault===!1?!1:!0,brokerBound:e.brokerBound===!0,cloudSdksShipped:!1,fallback:$r}}function Le(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function ru(e){let t=Le(e);if(!t||typeof t.id!="string")return;let n=t.status;if(n!=="pending"&&n!=="failed")return;let r=Le(t.event),o=r&&typeof r.intent=="string"?r.intent:typeof t.intent=="string"?t.intent:void 0,s={id:t.id,status:n,attempts:typeof t.attempts=="number"&&Number.isFinite(t.attempts)?t.attempts:0};return o&&(s.intent=o),typeof t.error=="string"&&t.error.length>0&&(s.error=t.error),typeof t.updatedAt=="string"&&(s.updatedAt=t.updatedAt),s}function Kr(e){if(typeof e!="number"||!Number.isFinite(e))return ne;let t=Math.trunc(e);return t<0?0:t>ne?ne:t}function $e(e,t){let n=typeof e=="string"&&e.trim().length>0?e.trim():e&&typeof e=="object"&&"constructor"in e?String(e.constructor?.name??t):t,r=/^InMemory/i.test(n)?"memory":"durable";return{role:t,id:n,kind:r}}function Mt(e={}){let t=Le(e),n=Le(t?.durability)??t,r=Array.isArray(n?.stores)?n.stores:Array.isArray(t?.stores)?t.stores:[],o=[];for(let s of r){let a=Le(s);if(!a)continue;let l=a.role;if(l!=="outbox"&&l!=="audit"&&l!=="workflow")continue;let c=typeof a.id=="string"?a.id:typeof a.name=="string"?a.name:void 0;if(!c)continue;let p=a.kind==="memory"||a.kind==="durable"?a.kind:$e(c,l).kind;o.push({role:l,id:c,kind:p})}return{durability:{stores:o}}}function Ke(e=[],t={}){let n=Kr(t.sampleLimit),r=Array.isArray(e)?e:[],o=[],s=[];for(let a of r){let l=ru(a);l&&(l.status==="pending"?o.push(l):s.push(l))}return{available:!0,pendingCount:o.length,failedCount:s.length,pending:o.slice(0,n),failed:s.slice(0,n),sampleLimit:n}}function Fe(){return{available:!1,pendingCount:0,failedCount:0,pending:[],failed:[],sampleLimit:ne}}function ou(e){let t=Le(e);if(!t||typeof t.id!="string")return;let n=typeof t.workflowName=="string"?t.workflowName:typeof t.name=="string"?t.name:void 0;if(!n)return;let r={id:t.id,name:n,status:typeof t.status=="string"?t.status:"unknown"};return typeof t.currentStep=="string"&&(r.currentStep=t.currentStep),typeof t.error=="string"&&t.error.length>0&&(r.error=t.error),r}function su(e){return e==="idle"||e==="waiting"}function He(e=[],t={}){let n=Kr(t.sampleLimit),r=Array.isArray(e)?e:[],o=[],s=0,a=0,l=0,c=0;for(let p of r){let f=ou(p);f&&(o.push(f),f.status==="running"?s+=1:f.status==="compensating"?a+=1:f.status==="failed"?l+=1:su(f.status)&&(c+=1))}return{available:!0,total:o.length,runningCount:s,compensatingCount:a,failedCount:l,pendingCount:c,workflows:o.slice(0,n),sampleLimit:n}}function Me(){return{available:!1,total:0,runningCount:0,compensatingCount:0,failedCount:0,pendingCount:0,workflows:[],sampleLimit:ne}}function iu(e){if(e===void 0)return;let t=Le(e);if(!t||t.available===!1)return Fe();let n=Kr(t.sampleLimit);if(Array.isArray(t.pending)||Array.isArray(t.failed)||Array.isArray(t.records)){let r=[...Array.isArray(t.pending)?t.pending:[],...Array.isArray(t.failed)?t.failed:[],...Array.isArray(t.records)?t.records:[]],o=Ke(r,{sampleLimit:n}),s=typeof t.pendingCount=="number"&&Number.isFinite(t.pendingCount)?Math.max(0,Math.trunc(t.pendingCount)):o.pendingCount,a=typeof t.failedCount=="number"&&Number.isFinite(t.failedCount)?Math.max(0,Math.trunc(t.failedCount)):o.failedCount;return{...o,pendingCount:s,failedCount:a,sampleLimit:n}}return Fe()}function au(e){if(e===void 0)return;let t=Le(e);if(!t||t.available===!1)return Me();let n=Kr(t.sampleLimit);if(Array.isArray(t.workflows)){let r=He(t.workflows,{sampleLimit:n}),o=typeof t.total=="number"&&Number.isFinite(t.total)?Math.max(0,Math.trunc(t.total)):r.total,s=typeof t.runningCount=="number"&&Number.isFinite(t.runningCount)?Math.max(0,Math.trunc(t.runningCount)):r.runningCount,a=typeof t.compensatingCount=="number"&&Number.isFinite(t.compensatingCount)?Math.max(0,Math.trunc(t.compensatingCount)):r.compensatingCount,l=typeof t.failedCount=="number"&&Number.isFinite(t.failedCount)?Math.max(0,Math.trunc(t.failedCount)):r.failedCount,c=typeof t.pendingCount=="number"&&Number.isFinite(t.pendingCount)?Math.max(0,Math.trunc(t.pendingCount)):r.pendingCount;return{...r,total:o,runningCount:s,compensatingCount:a,failedCount:l,pendingCount:c,sampleLimit:n}}return Me()}function Vn(e={}){let t=Ft({host:e.host,port:e.port}),n=ge({kernelInstanceId:e.kernelInstanceId,components:e.package&&typeof e.package=="object"&&!Array.isArray(e.package)&&Array.isArray(e.package.components)?e.package.components:[]}),r=iu(e.outbox),o=au(e.workflows),s={schemaVersion:Lr,kernelInstanceId:typeof e.kernelInstanceId=="string"?e.kernelInstanceId:n.kernelInstanceId,bind:{host:t.host,port:t.port,loopback:!0},package:{...n,schemaVersion:"1.0"},transport:nu(e),observability:tu(e.observability)??{},hardening:Mt(e.hardening)};return r&&(s.outbox=r),o&&(s.workflows=o),s}function $t(e){return`event: ${Mr}
3
3
  data: ${JSON.stringify(e)}
4
4
 
5
- `}var Lr,Gn,Fr,_t,Tt,Nt,Dt,Lt,Mr,$r,ne,at,ie,Jd,jn=jt(()=>{"use strict";Ot();Hn();Lr="1.0",Gn="127.0.0.1",Fr=0,_t="/snapshot",Tt="/events",Nt="/graph",Dt="/outbox",Lt="/workflows",Mr="snapshot",$r="in-process-local",ne=32,at=class extends Error{static{i(this,"ArkRunInspectorProductionError")}constructor(){super("ArkRun inspector refuses to start when NODE_ENV=production."),this.name="ArkRunInspectorProductionError"}},ie=class extends Error{static{i(this,"ArkRunInspectorBindError")}constructor(t){super(`ArkRun inspector binds loopback only (default 127.0.0.1). Public host "${t}" is rejected.`),this.name="ArkRunInspectorBindError"}},Jd=new Set(["","*","0","0.0.0.0","::","::0","[::]","[::0]","::ffff:0.0.0.0","[::ffff:0.0.0.0]"]);i(Un,"isArkRunInspectorProductionEnv");i(Qd,"ipv4Octets");i(xa,"unwrapIpv4Mapped");i(lt,"isArkRunInspectorLoopbackHost");i(Oa,"closedHost");i(eu,"closedPort");i(Ft,"resolveArkRunInspectorBind");i(ye,"arkRunInspectorUrl");i(tu,"jsonClone");i(nu,"closedTransportFacts");i(Le,"asRecord");i(ru,"closedOutboxSummary");i(Kr,"closedSampleLimit");i($e,"classifyArkRunInspectorStoreDurability");i(Mt,"buildArkRunInspectorHardening");i(Ke,"buildArkRunInspectorOutboxMonitor");i(Fe,"unavailableArkRunInspectorOutboxMonitor");i(ou,"closedWorkflowSummary");i(su,"isPendingWorkflowStatus");i(He,"buildArkRunInspectorWorkflowsMonitor");i(Me,"unavailableArkRunInspectorWorkflowsMonitor");i(iu,"closedOutboxMonitor");i(au,"closedWorkflowsMonitor");i(Vn,"buildArkRunInspectorSnapshot");i($t,"formatArkRunInspectorSseEvent")});var Pa={};ds(Pa,{listenArkRunInspector:()=>gu});function lu(){return{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}}function cu(){return{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-store",connection:"keep-alive","x-accel-buffering":"no"}}function du(e){let t=e&&e.length>0?e:"/";return new URL(t,"http://127.0.0.1")}function Ge(e,t,n){if(!(e.writableEnded||e.destroyed))try{e.writeHead(t,lu()),e.end(JSON.stringify(n))}catch{}}function uu(e,t){let n=e.address();if(n===null||typeof n=="string")throw new ie(t.host);if(!lt(n.address))throw new ie(n.address);return{host:t.host,port:n.port}}async function pu(e){if(typeof e.listInspectorOutbox=="function")return e.listInspectorOutbox();let t=e.outbox??e.eventBuffer;if(!t||typeof t.list!="function")return Fe();let[n,r]=await Promise.all([t.list("pending"),t.list("failed")]);return Ke([...n??[],...r??[]],{sampleLimit:ne})}async function fu(e){return typeof e.listInspectorWorkflows=="function"?e.listInspectorWorkflows():!e.workflowEngine||typeof e.workflowEngine.list!="function"?Me():He(await e.workflowEngine.list(),{sampleLimit:ne})}async function gu(e,t){let n=await import("http"),r=new Set,o=new Set,s=typeof t.sseIntervalMs=="number"&&Number.isFinite(t.sseIntervalMs)?Math.max(0,t.sseIntervalMs):1e3,a=t.bind,l=i(()=>e.getInspectorSnapshot(a),"snapshot"),c=n.createServer((p,f)=>{let y=du(p.url),u=y.pathname;if(p.method==="GET"&&(u==="/"||u===_t)){Ge(f,200,l());return}if(p.method==="GET"&&u===Nt){try{Ge(f,200,e.requestGraph(Mn({slice:y.searchParams.get("slice"),nodeIds:y.searchParams.get("nodeIds"),degreesOfSeparation:y.searchParams.get("degreesOfSeparation"),include:y.searchParams.get("include"),exclude:y.searchParams.get("exclude")})))}catch(g){if(g instanceof J){Ge(f,400,{error:g.message,option:g.option});return}throw g}return}if(p.method==="GET"&&u===Dt){pu(e).then(g=>Ge(f,200,g)).catch(g=>{Ge(f,500,{error:g instanceof Error?g.message:"outbox monitor failed"})});return}if(p.method==="GET"&&u===Lt){fu(e).then(g=>Ge(f,200,g)).catch(g=>{Ge(f,500,{error:g instanceof Error?g.message:"workflows monitor failed"})});return}if(p.method==="GET"&&u===Tt){f.writeHead(200,cu()),f.flushHeaders(),f.write($t(l())),r.add(f);let g=s>0?setInterval(()=>{f.write($t(l()))},s):void 0;g&&o.add(g);let d=i(()=>{r.delete(f),g&&(clearInterval(g),o.delete(g))},"drop");p.on("close",d),f.on("close",d);return}Ge(f,404,{error:"not found"})});try{await new Promise((p,f)=>{let y=i(u=>f(u),"onError");c.once("error",y),c.listen({host:t.bind.host,port:t.bind.port},()=>{c.off("error",y);try{a=uu(c,t.bind),p()}catch(u){f(u instanceof Error?u:new ie(t.bind.host))}})})}catch(p){throw await new Promise(f=>{c.close(()=>f())}),p}return{host:a.host,port:a.port,url:ye(a.host,a.port,"/"),snapshotUrl:ye(a.host,a.port,_t),eventsUrl:ye(a.host,a.port,Tt),graphUrl:ye(a.host,a.port,Nt),outboxUrl:ye(a.host,a.port,Dt),workflowsUrl:ye(a.host,a.port,Lt),close(){for(let p of o)clearInterval(p);o.clear();for(let p of r)p.end();return r.clear(),new Promise((p,f)=>{c.close(y=>{y?f(y):p()})})}}}var _a=jt(()=>{"use strict";Tr();jn();i(lu,"jsonHeaders");i(cu,"sseHeaders");i(du,"requestUrl");i(Ge,"writeJson");i(uu,"boundAddress");i(pu,"resolveOutboxMonitor");i(fu,"resolveWorkflowsMonitor");i(gu,"listenArkRunInspector")});var ku={};ds(ku,{ANALYSIS_IR_SCHEMA_VERSION:()=>pr,ARK_ANALYSIS_RESULT_SCHEMA:()=>jr,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>Bt,ARK_DESIGN_DELTA_SCHEMA_VERSION:()=>ma,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION:()=>ga,ARK_RUN_COMPONENT_LIFETIMES:()=>Er,ARK_RUN_EPHEMERAL_DEFAULT:()=>it,ARK_RUN_GRAPH_DEFAULT_SLICE:()=>Or,ARK_RUN_GRAPH_NODE_KINDS:()=>es,ARK_RUN_GRAPH_PROCESS_EDGE_KINDS:()=>ts,ARK_RUN_GRAPH_SCHEMA_VERSION:()=>xr,ARK_RUN_GRAPH_SLICES:()=>Pr,ARK_RUN_GRAPH_TECHNICAL_EDGE_KINDS:()=>ns,ARK_RUN_INFORMATION_PACKAGE_SCHEMA_VERSION:()=>_n,ARK_RUN_INSPECTOR_DEFAULT_HOST:()=>Gn,ARK_RUN_INSPECTOR_DEFAULT_PORT:()=>Fr,ARK_RUN_INSPECTOR_EVENTS_PATH:()=>Tt,ARK_RUN_INSPECTOR_GRAPH_PATH:()=>Nt,ARK_RUN_INSPECTOR_MONITOR_SAMPLE_LIMIT:()=>ne,ARK_RUN_INSPECTOR_OUTBOX_PATH:()=>Dt,ARK_RUN_INSPECTOR_SCHEMA_VERSION:()=>Lr,ARK_RUN_INSPECTOR_SNAPSHOT_PATH:()=>_t,ARK_RUN_INSPECTOR_SSE_EVENT:()=>Mr,ARK_RUN_INSPECTOR_TRANSPORT_FALLBACK:()=>$r,ARK_RUN_INSPECTOR_WORKFLOWS_PATH:()=>Lt,ARK_RUN_TRANSPORT_KINDS:()=>Pt,ArkRunInspectorBindError:()=>ie,ArkRunInspectorProductionError:()=>at,DEFAULT_MAX_HISTORY_SIZE:()=>Hr,DIAGNOSTIC_CATALOG:()=>Sn,DIAGNOSTIC_CATALOG_SCHEMA_VERSION:()=>ia,DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>br,DIAGNOSTIC_RULE_IDS:()=>aa,EventContractRegistryImpl:()=>mt,EventContractViolationError:()=>qe,InMemoryAuditStore:()=>yt,InMemoryEventBuffer:()=>Pe,InMemoryOutboxStore:()=>to,InMemoryReadModelStore:()=>wt,InMemoryWorkflowStore:()=>Ct,IntentRegistry:()=>Ve,InvalidArkRunGraphQueryError:()=>J,InvalidArkRunSendOptionError:()=>st,InvalidIntentNameError:()=>We,LayerPolicyContextError:()=>ze,MANIFEST_SCHEMA_VERSION:()=>xn,ObservedLayerFlowViolationError:()=>Ye,POLICY_DELTA_SCHEMA_VERSION:()=>gr,PolicyEngine:()=>xe,PolicyViolationError:()=>Re,RESOLVED_CANDIDATE_FACTS_SCHEMA:()=>ur,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION:()=>Te,SourceMetadataOverrideError:()=>Ae,UnknownEventSourceError:()=>Oe,UnregisteredIntentError:()=>Be,analyzeArchitectureConvergence:()=>nt,analyzeChange:()=>vn,analyzePolicyDelta:()=>No,analyzeProject:()=>vt,analyzeResolvedProject:()=>St,appendDecisionTape:()=>qo,architecturalPolicies:()=>Zn,arkRunGraphQueryFromSearchParams:()=>Mn,arkRunInspectorUrl:()=>ye,buildArkRunInspectorHardening:()=>Mt,buildArkRunInspectorOutboxMonitor:()=>Ke,buildArkRunInspectorSnapshot:()=>Vn,buildArkRunInspectorWorkflowsMonitor:()=>He,buildDependencyInformationPackage:()=>ge,buildPublishPolicyContext:()=>Zt,catalogFixForRuleId:()=>pa,catalogWhyForRuleId:()=>fa,checkAdapterGovernance:()=>ar,checkContract:()=>uo,classifyArkPolicyDelta:()=>mr,classifyArkRunInspectorStoreDurability:()=>$e,closeArkRunGraphQuery:()=>Fn,closedArkRunEphemeral:()=>Dr,closedArkRunTransportKind:()=>Nr,collectAnalysisConfigWarnings:()=>En,collectForbiddenCapabilityUses:()=>et,compareInformationPackages:()=>Sr,createAICodeGate:()=>wo,createAdapter:()=>co,createAdapterResult:()=>fs,createArchitectureProfile:()=>cn,createArchitectureProfileFromArkConfig:()=>dn,createArkKernel:()=>Kt,createArkKernelFromConfig:()=>ss,createArkManifest:()=>On,createArkTestHarness:()=>ro,createAuditTrail:()=>rn,createDependencyGraph:()=>on,createElevenLayerArkConfig:()=>ao,createEventBus:()=>eo,createEventContractRegistry:()=>tn,createIntentRegistry:()=>Wt,createLenientArkKernel:()=>Ur,createLenientArkKernelFromConfig:()=>as,createMetadataRegistry:()=>un,createObservabilityReporter:()=>nn,createProjectionRegistry:()=>Cn,createResolvedCandidateFacts:()=>dr,createSaga:()=>jo,createStrictArkKernel:()=>Gr,createStrictArkKernelFromConfig:()=>is,createWorkflowEngine:()=>xt,defaultIntentRegistry:()=>qr,defineArchitectureProfilePolicy:()=>Xt,defineIntent:()=>zr,defineLayerPolicy:()=>qt,definePolicy:()=>je,definePort:()=>lo,definePublishPolicy:()=>Yr,detectArchitectureCycles:()=>Rr,deterministicHash:()=>z,diagnosticDocsFragment:()=>Ho,diagnosticDocsPath:()=>da,elevenLayerProfile:()=>Je,evaluateArchitectureGraph:()=>ot,explainViolation:()=>Do,extractSemanticDependencies:()=>Qe,formatArkRunGraphMermaid:()=>_r,formatArkRunInspectorSseEvent:()=>$t,getDiagnosticCatalogEntry:()=>wn,isArkRunInspectorLoopbackHost:()=>lt,isArkRunInspectorProductionEnv:()=>Un,isCataloguedOrArkRuleFamily:()=>ca,isKnownDiagnosticCode:()=>la,isLayerPolicy:()=>Yt,loadContract:()=>bn,loadResolvedCandidateFacts:()=>Ee,policyDeltaAcknowledgementMatches:()=>yr,preflightChange:()=>Mo,preflightResolvedChange:()=>$o,replayInformationPackages:()=>Zo,requestArkRunGraph:()=>$n,resolveArkRunInspectorBind:()=>Ft,resolveArkRunSendPlan:()=>Kn,resolvedFactsEvidenceRequirementsHash:()=>bt,serializeDiagnosticCatalog:()=>ua,shadowInformationPackage:()=>Xo,stableSerialize:()=>M,startArkRunInspector:()=>Bn,syncRegistryToGraph:()=>sn,toAdapterDiagnostic:()=>Xn,unavailableArkRunInspectorOutboxMonitor:()=>Fe,unavailableArkRunInspectorWorkflowsMonitor:()=>Me,validateIntentName:()=>zt,version:()=>zn});module.exports=Ua(ku);var zn="4.8.17";var Va=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,ja=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,Ba=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function Wa(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),o=String(t?.toLayer??"");return Va.test(n)?"pure-shared":r==="PersistenceAdapters"&&(ja.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${o} ${n}`))?"kernel-emit":Ba.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&o==="PersistenceAdapters"?"use-case":"unknown"}i(Wa,"classifyLayerImportKind");function za(e){if(e.typeOnly||e.targetTypeOnlyExports||e.namedBindingsTypeOnly)return"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.";if(e.peerIsolation)return"Extract the shared dependency to a shared layer, test at the public interface, then preflight again.";let t=Wa(typeof e.target=="string"?e.target:"",{fromLayer:typeof e.fromLayer=="string"?e.fromLayer:void 0,toLayer:typeof e.toLayer=="string"?e.toLayer:void 0});return t==="pure-shared"?"Adopt the imported constants/types/pure module into DomainModel or SharedKernel (do not inject a port). Then preflight again.":t==="kernel-emit"?"Persistence must not emit. Inject a port or move the event map to SharedTypes; do not import kernel/events/bootstrap from a repository. Then preflight again.":t==="use-case"||e.portProofEligible?`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, test at the public interface, then preflight again.`:"Classify the import: if it is constants/types/pure, adopt into DomainModel or SharedKernel; define a port only if the target is a real use-case. Then preflight again."}i(za,"layerImportNextAction");function qa(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}i(qa,"arkRunCallSiteName");function Ya(e){let t=qa(e),n=typeof e.fromLayer=="string"&&e.fromLayer.length>0?e.fromLayer:void 0;switch(e.ruleId){case"ARKRUN_MISSING_ROOT":return t?`Import createStrictArkKernel from arkgate/runtime and call it in composition root ${t} listed in arkRun.compositionRoots, then preflight again.`:"Import createStrictArkKernel from arkgate/runtime (same npm package; @arkgate/runtime is deprecated) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKRUN_KERNEL_IN_DOMAIN":return t?`Move the kernel import of ${t} out of ${n??"the Domain-role layer"} into a composition root or adapter. Import from arkgate/runtime, then preflight again.`:"Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from arkgate/runtime (same npm package; @arkgate/runtime is deprecated), then preflight again. Never mechanical-safe.";case"ARKRUN_DIRECT_NEW":return t?`Resolve ${t} from the kernel instead of constructing it with new, then preflight again.`:"Resolve the type from the kernel instead of constructing it with new, then preflight again. Never mechanical-safe \u2014 rewiring construction is a design decision.";case"ARKRUN_UNDECLARED_EMIT":return t?`Add ${t} to raises or sends on the managed component, then preflight again.`:"Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment.";case"ARKRUN_UNDECLARED_HANDLE":return t?`Add ${t} to reactsTo on the managed component, then preflight again.`:"Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment.";case"ARKRUN_UNDECLARED_DEPEND":return t?`Add ${t} to uses on the managed component, then preflight again.`:"Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment.";case"ARKRUN_TRANSPORT_BYPASS":return t?`Send through the ArkRun kernel transport instead of importing ${t}, then preflight again.`:"Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe \u2014 homemade buses stay judgment.";default:return`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(Ya,"arkRunNextAction");function fe(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return za(e);case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, test at the public interface, then preflight again.`;case"CAPABILITY_VIOLATION":return`Define a ${String(e.capability??"capability")} port in ${e.fromLayer??"the walled layer"}, bind the implementation outside it, test at the public interface, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, test at the public interface, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"LITERAL_PATH_DRIFT":return typeof e.target=="string"&&e.target.length>0?`Rewrite the literal to ${e.target}, or run \`arkgate-check --path-drift --base-ref <ref> --write\` to apply every anchored replacement.`:"Rewrite the literal to the rename destination, or run `arkgate-check --path-drift --base-ref <ref> --write` to apply every anchored replacement.";case"LITERAL_PATH_UNRESOLVED":return"Read the candidate and decide: fix the path, or leave it. Advisory \u2014 with no rename to anchor it there is no destination to propose, so --write never touches it.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";case"INVARIANT_COVERAGE_OUTSIDE_ROOTS":return"Move the covering test under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json, then run Ark again.";case"INVARIANT_CATALOG_EMPTY":return typeof e.file=="string"&&e.file.length>0?`Add 1\u20132 short phrases to invariants[] in ${e.file}, then run ark-check --doctor. Starters show the shape.`:"Add 1\u20132 short phrases to invariants[] in arkrules/<Domain>.json, then run ark-check --doctor. Starters show the shape.";case"INVARIANT_TESTS_PATH_MISSING":return"Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present.";case"INVARIANT_COVERAGE_ROOTS_MISSING":return"Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. An enforced invariant fails closed until that path is present.";case"ARKRULE_STRUCTURE":case"ARKRULE_INVARIANT":case"INVARIANT_UNCOVERED":return`Fix the structure or invariant for ${typeof e.arkruleId=="string"&&e.arkruleId.length>0?e.arkruleId:"the ArkRule"} (declared in ${typeof e.arkruleSource=="string"&&e.arkruleSource.length>0?e.arkruleSource:"arkrules/<Layer>.json"}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`;case"ARKRUN_MISSING_ROOT":case"ARKRUN_KERNEL_IN_DOMAIN":case"ARKRUN_DIRECT_NEW":case"ARKRUN_UNDECLARED_EMIT":case"ARKRUN_UNDECLARED_HANDLE":case"ARKRUN_UNDECLARED_DEPEND":case"ARKRUN_TRANSPORT_BYPASS":return Ya(e);case"ARKORDER_MISSING_PLANE":return typeof e.target=="string"&&e.target.length>0?`Import createOrderPlane from arkgate/order and call it in plane root ${e.target} listed in arkOrder.planeRoots, then preflight again.`:"Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKORDER_KERNEL_IN_DOMAIN":return"Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe.";case"ARKORDER_GENERIC_UPDATE":return"Don't use a generic update. First freeze with release(). Later, propose the change, then apply it.";case"ARKORDER_TOO_MANY_PARAMS":return"Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe.";case"ARKORDER_INGEST_WRITES_XI":return"Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe.";case"ARKORDER_XI_FIELD_WRITE":return typeof e.target=="string"&&e.target.length>0?`Don't write ${e.target} from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.`:"Don't write a named product choice from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.";case"ARKORDER_UNVALVED_RELEASE":return"Change the choice with proposeRelease then apply. release() is only the first freeze. Never mechanical-safe.";default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(fe,"deterministicNextAction");var Bt="1.5",Vr="docs/diagnostics.md",jr={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","mode","valid","completeness","completenessReasons","diagnostics"],allOf:[{if:{properties:{completeness:{enum:["partial","unavailable"]}},required:["completeness"]},then:{properties:{valid:{const:!1}}}},{if:{properties:{mode:{const:"resolved-candidate-facts"},completeness:{enum:["complete","partial"]}},required:["mode","completeness"]},then:{required:["policyHash","resolverIdentity","factsHash","candidateTreeHash"]}},{if:{properties:{completeness:{const:"complete"}},required:["completeness"]},then:{properties:{completenessReasons:{maxItems:0}}},else:{properties:{completenessReasons:{minItems:1}}}}],properties:{schemaVersion:{const:"1.5"},mode:{enum:["lexical-compatibility","resolved-candidate-facts"]},valid:{type:"boolean"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:{type:"string",minLength:1},message:{type:"string",minLength:1},file:{type:"string",minLength:1}}}},policyHash:{type:"string",minLength:1},resolverIdentity:{type:"string",minLength:1},factsHash:{type:"string",minLength:1},candidateTreeHash:{type:"string",minLength:1},diagnostics:{type:"array",items:{type:"object",additionalProperties:!1,required:["ruleId","severity","message","location","evidence"],properties:{ruleId:{type:"string",minLength:1},severity:{enum:["error","warning"]},message:{type:"string",minLength:1},location:{type:"object",additionalProperties:!1,required:["file","line","column"],properties:{file:{type:"string",minLength:1},line:{type:"integer",minimum:1},column:{type:"integer",minimum:1}}},evidence:{type:"object",additionalProperties:!1,properties:{target:{type:"string"},fromLayer:{type:"string"},toLayer:{type:"string"},typeOnly:{type:"boolean"},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"},peerIsolation:{type:"boolean"},capability:{type:"string",minLength:1},edgeKind:{type:"string",minLength:1},arkruleId:{type:"string",minLength:1},arkruleSource:{type:"string",minLength:1}}},nextAction:{type:"string",minLength:1},findingRef:{type:"string",minLength:1,pattern:"^fnv1a-[0-9a-f]{8}$"},targetKey:{type:"string",minLength:1},docsCodePath:{type:"string",minLength:1}}}}}};function qn(e){let t=typeof e.ruleId=="string"?e.ruleId:typeof e.code=="string"?e.code:void 0,n=typeof e.file=="string"?e.file:void 0,r=typeof e.fromLayer=="string"?e.fromLayer:void 0,o=typeof e.toLayer=="string"?e.toLayer:void 0,s=typeof e.target=="string"?e.target:void 0;return[t,n,r??"",o??"",s??""].join("|")}i(qn,"adapterFindingTargetKey");function Yn(e){let t=new Map;return e.map(n=>{let r=qn(n),o=(t.get(r)??0)+1;return t.set(r,o),o===1?r:`${r}#${o}`})}i(Yn,"adapterFindingOccurrenceTargetKeys");function Br(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}i(Br,"adapterFindingRefFromTargetKey");function Wr(e){return`${Vr}#${e}`}i(Wr,"adapterDocsCodePath");function O(e){return typeof e=="string"&&e.length>0?e:void 0}i(O,"text");function ps(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}i(ps,"positiveInteger");function Xa(e,t,n){return fe({ruleId:e,target:O(t.target)??O(n.target)??void 0,fromLayer:O(t.fromLayer)??void 0,toLayer:O(t.toLayer)??void 0,typeOnly:t.typeOnly===!0,targetTypeOnlyExports:t.targetTypeOnlyExports===!0,namedBindingsTypeOnly:t.namedBindingsTypeOnly===!0,portProofEligible:t.portProofEligible===!0,peerIsolation:t.peerIsolation===!0,sourcePureTypeModule:t.sourcePureTypeModule===!0,edgeKind:O(t.edgeKind)??void 0,capability:O(t.capability)??O(n.capability)??void 0,arkruleId:O(t.arkruleId)??void 0,arkruleSource:O(t.arkruleSource)??void 0})}i(Xa,"nextActionForDiagnostic");function Xn(e,t="error",n){let r=O(e.ruleId)??O(e.code)??"ARK_UNKNOWN",o=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,s={...O(e.target)?{target:O(e.target)}:{},...O(e.fromLayer)?{fromLayer:O(e.fromLayer)}:{},...O(e.toLayer)?{toLayer:O(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{},...typeof e.targetTypeOnlyExports=="boolean"?{targetTypeOnlyExports:e.targetTypeOnlyExports}:{},...typeof e.sourcePureTypeModule=="boolean"?{sourcePureTypeModule:e.sourcePureTypeModule}:{},...typeof e.namedBindingsTypeOnly=="boolean"?{namedBindingsTypeOnly:e.namedBindingsTypeOnly}:{},...typeof e.portProofEligible=="boolean"?{portProofEligible:e.portProofEligible}:{},...typeof e.peerIsolation=="boolean"?{peerIsolation:e.peerIsolation}:{},...O(e.capability)?{capability:O(e.capability)}:{},...O(e.edgeKind)?{edgeKind:O(e.edgeKind)}:{},...O(e.arkruleId)?{arkruleId:O(e.arkruleId)}:{},...O(e.arkruleSource)?{arkruleSource:O(e.arkruleSource)}:{}},a=n??qn(e),l=Br(a);return{ruleId:r,severity:o,message:O(e.message)??r,location:{file:O(e.file)??"<unknown>",line:ps(e.line,1),column:ps(e.column,1)},evidence:s,nextAction:O(e.nextAction)??Xa(r,s,e),findingRef:l,targetKey:a,docsCodePath:Wr(r)}}i(Xn,"toAdapterDiagnostic");function fs(e){let t=e.completeness??"complete",n=e.mode??"lexical-compatibility";if(t==="complete"&&(e.completenessReasons?.length??0)>0)throw new Error("completenessReasons must be empty when completeness is complete.");let r=t==="complete"?[]:e.completenessReasons&&e.completenessReasons.length>0?e.completenessReasons.map(y=>({code:O(y.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:O(y.message)??`Analysis ${t}: required evidence is incomplete.`,...O(y.file)?{file:O(y.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],o={...O(e.policyHash)?{policyHash:O(e.policyHash)}:{},...O(e.resolverIdentity)?{resolverIdentity:O(e.resolverIdentity)}:{},...O(e.factsHash)?{factsHash:O(e.factsHash)}:{},...O(e.candidateTreeHash)?{candidateTreeHash:O(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let y of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!o[y])throw new Error(`${y} is required for resolved ${t} adapter evidence.`)}let s=e.violations??[],a=e.warnings??[],l=Yn(s),c=Yn(a),p=[...s.map((y,u)=>Xn(y,"error",l[u])),...a.map((y,u)=>Xn(y,"warning",c[u]))],f={schemaVersion:"1.5",completenessReasons:r,diagnostics:p};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...f,mode:n,valid:!1,completeness:t,...o};let y={policyHash:o.policyHash,resolverIdentity:o.resolverIdentity,factsHash:o.factsHash,candidateTreeHash:o.candidateTreeHash};return t==="complete"?{...f,mode:n,valid:e.valid,completeness:t,...y}:{...f,mode:n,valid:!1,completeness:t,...y}}return t==="complete"?{...f,mode:n,valid:e.valid,completeness:t,...o}:{...f,mode:n,valid:!1,completeness:t,...o}}i(fs,"createAdapterResult");var Ve=class{static{i(this,"IntentRegistry")}intents=new Map;dependencies=new Map;productions=new Map;define(t,n){if(this.intents.has(t))throw new Error(`Intent "${t}" is already registered. Intent names must be unique within a registry.`);let r=i(s=>({intent:t,payload:s,metadata:{occurredAt:new Date().toISOString(),source:"unknown"}}),"fn");Object.defineProperty(r,"name",{value:t,enumerable:!0,configurable:!1,writable:!1});let o=r;if(this.intents.set(t,o),n?.dependsOn)for(let s of n.dependsOn)this.declareDependency(t,s);if(n?.produces)for(let s of n.produces)this.declareProduction(t,s);return o}declareDependency(t,n){this.dependencies.has(t)||this.dependencies.set(t,new Set),this.dependencies.get(t).add(n)}declareProduction(t,n){this.productions.has(t)||this.productions.set(t,new Set),this.productions.get(t).add(n)}get(t){return this.intents.get(t)}list(){return Array.from(this.intents.values())}getDependencies(t){let n=this.dependencies.get(t);return n?Array.from(n):[]}getProductions(t){let n=this.productions.get(t);return n?Array.from(n):[]}getAllRelationships(){let t=[];for(let[n,r]of this.dependencies.entries())for(let o of r)t.push({from:n,to:o,kind:"dependsOn"});for(let[n,r]of this.productions.entries())for(let o of r)t.push({from:n,to:o,kind:"produces"});return t}has(t){return this.intents.has(t)}clear(){this.intents.clear(),this.dependencies.clear(),this.productions.clear()}};var gs=new Ve;function zr(e,t){return gs.define(e,t)}i(zr,"defineIntent");function Wt(){return new Ve}i(Wt,"createIntentRegistry");var qr=gs;var ms=["Domain.","Application.","Adapter.","Workflow.","Job.","Presentation.","Reporting.","Metadata.","Security.","Audit.","Observability.","Kernel."];function zt(e){if(!e||typeof e!="string")return{valid:!1,reason:"Intent name must be a non-empty string"};if(!ms.some(n=>e.startsWith(n)))return{valid:!1,reason:`Intent "${e}" must start with one of: ${ms.join(", ")}`};let t=e.slice(e.indexOf(".")+1);return!t||!/^[A-Za-z][A-Za-z0-9_.]*$/.test(t)?{valid:!1,reason:`Intent "${e}" has an invalid segment after the layer prefix`}:{valid:!0}}i(zt,"validateIntentName");var Re=class extends Error{static{i(this,"PolicyViolationError")}violations;constructor(t){let n=t.map(r=>`- ${r.policyName}: ${r.message}`).join(`
5
+ `}var Lr,Gn,Fr,_t,Tt,Nt,Dt,Lt,Mr,$r,ne,at,ie,Jd,jn=jt(()=>{"use strict";Ot();Hn();Lr="1.0",Gn="127.0.0.1",Fr=0,_t="/snapshot",Tt="/events",Nt="/graph",Dt="/outbox",Lt="/workflows",Mr="snapshot",$r="in-process-local",ne=32,at=class extends Error{static{i(this,"ArkRunInspectorProductionError")}constructor(){super("ArkRun inspector refuses to start when NODE_ENV=production."),this.name="ArkRunInspectorProductionError"}},ie=class extends Error{static{i(this,"ArkRunInspectorBindError")}constructor(t){super(`ArkRun inspector binds loopback only (default 127.0.0.1). Public host "${t}" is rejected.`),this.name="ArkRunInspectorBindError"}},Jd=new Set(["","*","0","0.0.0.0","::","::0","[::]","[::0]","::ffff:0.0.0.0","[::ffff:0.0.0.0]"]);i(Un,"isArkRunInspectorProductionEnv");i(Qd,"ipv4Octets");i(xa,"unwrapIpv4Mapped");i(lt,"isArkRunInspectorLoopbackHost");i(Oa,"closedHost");i(eu,"closedPort");i(Ft,"resolveArkRunInspectorBind");i(ye,"arkRunInspectorUrl");i(tu,"jsonClone");i(nu,"closedTransportFacts");i(Le,"asRecord");i(ru,"closedOutboxSummary");i(Kr,"closedSampleLimit");i($e,"classifyArkRunInspectorStoreDurability");i(Mt,"buildArkRunInspectorHardening");i(Ke,"buildArkRunInspectorOutboxMonitor");i(Fe,"unavailableArkRunInspectorOutboxMonitor");i(ou,"closedWorkflowSummary");i(su,"isPendingWorkflowStatus");i(He,"buildArkRunInspectorWorkflowsMonitor");i(Me,"unavailableArkRunInspectorWorkflowsMonitor");i(iu,"closedOutboxMonitor");i(au,"closedWorkflowsMonitor");i(Vn,"buildArkRunInspectorSnapshot");i($t,"formatArkRunInspectorSseEvent")});var Pa={};ds(Pa,{listenArkRunInspector:()=>gu});function lu(){return{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}}function cu(){return{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-store",connection:"keep-alive","x-accel-buffering":"no"}}function du(e){let t=e&&e.length>0?e:"/";return new URL(t,"http://127.0.0.1")}function Ge(e,t,n){if(!(e.writableEnded||e.destroyed))try{e.writeHead(t,lu()),e.end(JSON.stringify(n))}catch{}}function uu(e,t){let n=e.address();if(n===null||typeof n=="string")throw new ie(t.host);if(!lt(n.address))throw new ie(n.address);return{host:t.host,port:n.port}}async function pu(e){if(typeof e.listInspectorOutbox=="function")return e.listInspectorOutbox();let t=e.outbox??e.eventBuffer;if(!t||typeof t.list!="function")return Fe();let[n,r]=await Promise.all([t.list("pending"),t.list("failed")]);return Ke([...n??[],...r??[]],{sampleLimit:ne})}async function fu(e){return typeof e.listInspectorWorkflows=="function"?e.listInspectorWorkflows():!e.workflowEngine||typeof e.workflowEngine.list!="function"?Me():He(await e.workflowEngine.list(),{sampleLimit:ne})}async function gu(e,t){let n=await import("http"),r=new Set,o=new Set,s=typeof t.sseIntervalMs=="number"&&Number.isFinite(t.sseIntervalMs)?Math.max(0,t.sseIntervalMs):1e3,a=t.bind,l=i(()=>e.getInspectorSnapshot(a),"snapshot"),c=n.createServer((p,f)=>{let y=du(p.url),u=y.pathname;if(p.method==="GET"&&(u==="/"||u===_t)){Ge(f,200,l());return}if(p.method==="GET"&&u===Nt){try{Ge(f,200,e.requestGraph(Mn({slice:y.searchParams.get("slice"),nodeIds:y.searchParams.get("nodeIds"),degreesOfSeparation:y.searchParams.get("degreesOfSeparation"),include:y.searchParams.get("include"),exclude:y.searchParams.get("exclude")})))}catch(g){if(g instanceof J){Ge(f,400,{error:g.message,option:g.option});return}throw g}return}if(p.method==="GET"&&u===Dt){pu(e).then(g=>Ge(f,200,g)).catch(g=>{Ge(f,500,{error:g instanceof Error?g.message:"outbox monitor failed"})});return}if(p.method==="GET"&&u===Lt){fu(e).then(g=>Ge(f,200,g)).catch(g=>{Ge(f,500,{error:g instanceof Error?g.message:"workflows monitor failed"})});return}if(p.method==="GET"&&u===Tt){f.writeHead(200,cu()),f.flushHeaders(),f.write($t(l())),r.add(f);let g=s>0?setInterval(()=>{f.write($t(l()))},s):void 0;g&&o.add(g);let d=i(()=>{r.delete(f),g&&(clearInterval(g),o.delete(g))},"drop");p.on("close",d),f.on("close",d);return}Ge(f,404,{error:"not found"})});try{await new Promise((p,f)=>{let y=i(u=>f(u),"onError");c.once("error",y),c.listen({host:t.bind.host,port:t.bind.port},()=>{c.off("error",y);try{a=uu(c,t.bind),p()}catch(u){f(u instanceof Error?u:new ie(t.bind.host))}})})}catch(p){throw await new Promise(f=>{c.close(()=>f())}),p}return{host:a.host,port:a.port,url:ye(a.host,a.port,"/"),snapshotUrl:ye(a.host,a.port,_t),eventsUrl:ye(a.host,a.port,Tt),graphUrl:ye(a.host,a.port,Nt),outboxUrl:ye(a.host,a.port,Dt),workflowsUrl:ye(a.host,a.port,Lt),close(){for(let p of o)clearInterval(p);o.clear();for(let p of r)p.end();return r.clear(),new Promise((p,f)=>{c.close(y=>{y?f(y):p()})})}}}var _a=jt(()=>{"use strict";Tr();jn();i(lu,"jsonHeaders");i(cu,"sseHeaders");i(du,"requestUrl");i(Ge,"writeJson");i(uu,"boundAddress");i(pu,"resolveOutboxMonitor");i(fu,"resolveWorkflowsMonitor");i(gu,"listenArkRunInspector")});var ku={};ds(ku,{ANALYSIS_IR_SCHEMA_VERSION:()=>pr,ARK_ANALYSIS_RESULT_SCHEMA:()=>jr,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>Bt,ARK_DESIGN_DELTA_SCHEMA_VERSION:()=>ma,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION:()=>ga,ARK_RUN_COMPONENT_LIFETIMES:()=>Er,ARK_RUN_EPHEMERAL_DEFAULT:()=>it,ARK_RUN_GRAPH_DEFAULT_SLICE:()=>Or,ARK_RUN_GRAPH_NODE_KINDS:()=>es,ARK_RUN_GRAPH_PROCESS_EDGE_KINDS:()=>ts,ARK_RUN_GRAPH_SCHEMA_VERSION:()=>xr,ARK_RUN_GRAPH_SLICES:()=>Pr,ARK_RUN_GRAPH_TECHNICAL_EDGE_KINDS:()=>ns,ARK_RUN_INFORMATION_PACKAGE_SCHEMA_VERSION:()=>_n,ARK_RUN_INSPECTOR_DEFAULT_HOST:()=>Gn,ARK_RUN_INSPECTOR_DEFAULT_PORT:()=>Fr,ARK_RUN_INSPECTOR_EVENTS_PATH:()=>Tt,ARK_RUN_INSPECTOR_GRAPH_PATH:()=>Nt,ARK_RUN_INSPECTOR_MONITOR_SAMPLE_LIMIT:()=>ne,ARK_RUN_INSPECTOR_OUTBOX_PATH:()=>Dt,ARK_RUN_INSPECTOR_SCHEMA_VERSION:()=>Lr,ARK_RUN_INSPECTOR_SNAPSHOT_PATH:()=>_t,ARK_RUN_INSPECTOR_SSE_EVENT:()=>Mr,ARK_RUN_INSPECTOR_TRANSPORT_FALLBACK:()=>$r,ARK_RUN_INSPECTOR_WORKFLOWS_PATH:()=>Lt,ARK_RUN_TRANSPORT_KINDS:()=>Pt,ArkRunInspectorBindError:()=>ie,ArkRunInspectorProductionError:()=>at,DEFAULT_MAX_HISTORY_SIZE:()=>Hr,DIAGNOSTIC_CATALOG:()=>Sn,DIAGNOSTIC_CATALOG_SCHEMA_VERSION:()=>ia,DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>br,DIAGNOSTIC_RULE_IDS:()=>aa,EventContractRegistryImpl:()=>mt,EventContractViolationError:()=>qe,InMemoryAuditStore:()=>yt,InMemoryEventBuffer:()=>Pe,InMemoryOutboxStore:()=>to,InMemoryReadModelStore:()=>wt,InMemoryWorkflowStore:()=>Ct,IntentRegistry:()=>Ve,InvalidArkRunGraphQueryError:()=>J,InvalidArkRunSendOptionError:()=>st,InvalidIntentNameError:()=>We,LayerPolicyContextError:()=>ze,MANIFEST_SCHEMA_VERSION:()=>xn,ObservedLayerFlowViolationError:()=>Ye,POLICY_DELTA_SCHEMA_VERSION:()=>gr,PolicyEngine:()=>xe,PolicyViolationError:()=>Re,RESOLVED_CANDIDATE_FACTS_SCHEMA:()=>ur,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION:()=>Te,SourceMetadataOverrideError:()=>Ae,UnknownEventSourceError:()=>Oe,UnregisteredIntentError:()=>Be,analyzeArchitectureConvergence:()=>nt,analyzeChange:()=>vn,analyzePolicyDelta:()=>No,analyzeProject:()=>vt,analyzeResolvedProject:()=>St,appendDecisionTape:()=>qo,architecturalPolicies:()=>Zn,arkRunGraphQueryFromSearchParams:()=>Mn,arkRunInspectorUrl:()=>ye,buildArkRunInspectorHardening:()=>Mt,buildArkRunInspectorOutboxMonitor:()=>Ke,buildArkRunInspectorSnapshot:()=>Vn,buildArkRunInspectorWorkflowsMonitor:()=>He,buildDependencyInformationPackage:()=>ge,buildPublishPolicyContext:()=>Zt,catalogFixForRuleId:()=>pa,catalogWhyForRuleId:()=>fa,checkAdapterGovernance:()=>ar,checkContract:()=>uo,classifyArkPolicyDelta:()=>mr,classifyArkRunInspectorStoreDurability:()=>$e,closeArkRunGraphQuery:()=>Fn,closedArkRunEphemeral:()=>Dr,closedArkRunTransportKind:()=>Nr,collectAnalysisConfigWarnings:()=>En,collectForbiddenCapabilityUses:()=>et,compareInformationPackages:()=>Sr,createAICodeGate:()=>wo,createAdapter:()=>co,createAdapterResult:()=>fs,createArchitectureProfile:()=>cn,createArchitectureProfileFromArkConfig:()=>dn,createArkKernel:()=>Kt,createArkKernelFromConfig:()=>ss,createArkManifest:()=>On,createArkTestHarness:()=>ro,createAuditTrail:()=>rn,createDependencyGraph:()=>on,createElevenLayerArkConfig:()=>ao,createEventBus:()=>eo,createEventContractRegistry:()=>tn,createIntentRegistry:()=>Wt,createLenientArkKernel:()=>Ur,createLenientArkKernelFromConfig:()=>as,createMetadataRegistry:()=>un,createObservabilityReporter:()=>nn,createProjectionRegistry:()=>Cn,createResolvedCandidateFacts:()=>dr,createSaga:()=>jo,createStrictArkKernel:()=>Gr,createStrictArkKernelFromConfig:()=>is,createWorkflowEngine:()=>xt,defaultIntentRegistry:()=>qr,defineArchitectureProfilePolicy:()=>Xt,defineIntent:()=>zr,defineLayerPolicy:()=>qt,definePolicy:()=>je,definePort:()=>lo,definePublishPolicy:()=>Yr,detectArchitectureCycles:()=>Rr,deterministicHash:()=>z,diagnosticDocsFragment:()=>Ho,diagnosticDocsPath:()=>da,elevenLayerProfile:()=>Je,evaluateArchitectureGraph:()=>ot,explainViolation:()=>Do,extractSemanticDependencies:()=>Qe,formatArkRunGraphMermaid:()=>_r,formatArkRunInspectorSseEvent:()=>$t,getDiagnosticCatalogEntry:()=>wn,isArkRunInspectorLoopbackHost:()=>lt,isArkRunInspectorProductionEnv:()=>Un,isCataloguedOrArkRuleFamily:()=>ca,isKnownDiagnosticCode:()=>la,isLayerPolicy:()=>Yt,loadContract:()=>bn,loadResolvedCandidateFacts:()=>Ee,policyDeltaAcknowledgementMatches:()=>yr,preflightChange:()=>Mo,preflightResolvedChange:()=>$o,replayInformationPackages:()=>Zo,requestArkRunGraph:()=>$n,resolveArkRunInspectorBind:()=>Ft,resolveArkRunSendPlan:()=>Kn,resolvedFactsEvidenceRequirementsHash:()=>bt,serializeDiagnosticCatalog:()=>ua,shadowInformationPackage:()=>Xo,stableSerialize:()=>M,startArkRunInspector:()=>Bn,syncRegistryToGraph:()=>sn,toAdapterDiagnostic:()=>Xn,unavailableArkRunInspectorOutboxMonitor:()=>Fe,unavailableArkRunInspectorWorkflowsMonitor:()=>Me,validateIntentName:()=>zt,version:()=>zn});module.exports=Ua(ku);var zn="4.8.18";var Va=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,ja=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,Ba=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function Wa(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),o=String(t?.toLayer??"");return Va.test(n)?"pure-shared":r==="PersistenceAdapters"&&(ja.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${o} ${n}`))?"kernel-emit":Ba.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&o==="PersistenceAdapters"?"use-case":"unknown"}i(Wa,"classifyLayerImportKind");function za(e){if(e.typeOnly||e.targetTypeOnlyExports||e.namedBindingsTypeOnly)return"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.";if(e.peerIsolation)return"Extract the shared dependency to a shared layer, test at the public interface, then preflight again.";let t=Wa(typeof e.target=="string"?e.target:"",{fromLayer:typeof e.fromLayer=="string"?e.fromLayer:void 0,toLayer:typeof e.toLayer=="string"?e.toLayer:void 0});return t==="pure-shared"?"Adopt the imported constants/types/pure module into DomainModel or SharedKernel (do not inject a port). Then preflight again.":t==="kernel-emit"?"Persistence must not emit. Inject a port or move the event map to SharedTypes; do not import kernel/events/bootstrap from a repository. Then preflight again.":t==="use-case"||e.portProofEligible?`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, test at the public interface, then preflight again.`:"Classify the import: if it is constants/types/pure, adopt into DomainModel or SharedKernel; define a port only if the target is a real use-case. Then preflight again."}i(za,"layerImportNextAction");function qa(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}i(qa,"arkRunCallSiteName");function Ya(e){let t=qa(e),n=typeof e.fromLayer=="string"&&e.fromLayer.length>0?e.fromLayer:void 0;switch(e.ruleId){case"ARKRUN_MISSING_ROOT":return t?`Import createStrictArkKernel from arkgate/runtime and call it in composition root ${t} listed in arkRun.compositionRoots, then preflight again.`:"Import createStrictArkKernel from arkgate/runtime (same npm package; @arkgate/runtime is deprecated) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKRUN_KERNEL_IN_DOMAIN":return t?`Move the kernel import of ${t} out of ${n??"the Domain-role layer"} into a composition root or adapter. Import from arkgate/runtime, then preflight again.`:"Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from arkgate/runtime (same npm package; @arkgate/runtime is deprecated), then preflight again. Never mechanical-safe.";case"ARKRUN_DIRECT_NEW":return t?`Resolve ${t} from the kernel instead of constructing it with new, then preflight again.`:"Resolve the type from the kernel instead of constructing it with new, then preflight again. Never mechanical-safe \u2014 rewiring construction is a design decision.";case"ARKRUN_UNDECLARED_EMIT":return t?`Add ${t} to raises or sends on the managed component, then preflight again.`:"Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment.";case"ARKRUN_UNDECLARED_HANDLE":return t?`Add ${t} to reactsTo on the managed component, then preflight again.`:"Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment.";case"ARKRUN_UNDECLARED_DEPEND":return t?`Add ${t} to uses on the managed component, then preflight again.`:"Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment.";case"ARKRUN_TRANSPORT_BYPASS":return t?`Send through the ArkRun kernel transport instead of importing ${t}, then preflight again.`:"Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe \u2014 homemade buses stay judgment.";default:return`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(Ya,"arkRunNextAction");function fe(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return za(e);case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, test at the public interface, then preflight again.`;case"CAPABILITY_VIOLATION":return`Define a ${String(e.capability??"capability")} port in ${e.fromLayer??"the walled layer"}, bind the implementation outside it, test at the public interface, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, test at the public interface, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"LITERAL_PATH_DRIFT":return typeof e.target=="string"&&e.target.length>0?`Rewrite the literal to ${e.target}, or run \`arkgate-check --path-drift --base-ref <ref> --write\` to apply every anchored replacement.`:"Rewrite the literal to the rename destination, or run `arkgate-check --path-drift --base-ref <ref> --write` to apply every anchored replacement.";case"LITERAL_PATH_UNRESOLVED":return"Read the candidate and decide: fix the path, or leave it. Advisory \u2014 with no rename to anchor it there is no destination to propose, so --write never touches it.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";case"INVARIANT_COVERAGE_OUTSIDE_ROOTS":return"Move the covering test under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json, then run Ark again.";case"INVARIANT_CATALOG_EMPTY":return typeof e.file=="string"&&e.file.length>0?`Add 1\u20132 short phrases to invariants[] in ${e.file}, then run ark-check --doctor. Starters show the shape.`:"Add 1\u20132 short phrases to invariants[] in arkrules/<Domain>.json, then run ark-check --doctor. Starters show the shape.";case"INVARIANT_TESTS_PATH_MISSING":return"Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present.";case"INVARIANT_COVERAGE_ROOTS_MISSING":return"Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. An enforced invariant fails closed until that path is present.";case"ARKRULE_STRUCTURE":case"ARKRULE_INVARIANT":case"INVARIANT_UNCOVERED":return`Fix the structure or invariant for ${typeof e.arkruleId=="string"&&e.arkruleId.length>0?e.arkruleId:"the ArkRule"} (declared in ${typeof e.arkruleSource=="string"&&e.arkruleSource.length>0?e.arkruleSource:"arkrules/<Layer>.json"}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`;case"ARKRUN_MISSING_ROOT":case"ARKRUN_KERNEL_IN_DOMAIN":case"ARKRUN_DIRECT_NEW":case"ARKRUN_UNDECLARED_EMIT":case"ARKRUN_UNDECLARED_HANDLE":case"ARKRUN_UNDECLARED_DEPEND":case"ARKRUN_TRANSPORT_BYPASS":return Ya(e);case"ARKORDER_MISSING_PLANE":return typeof e.target=="string"&&e.target.length>0?`Import createOrderPlane from arkgate/order and call it in plane root ${e.target} listed in arkOrder.planeRoots, then preflight again.`:"Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKORDER_KERNEL_IN_DOMAIN":return"Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe.";case"ARKORDER_GENERIC_UPDATE":return"Don't use a generic update. First freeze with release(). Later, propose the change, then apply it.";case"ARKORDER_TOO_MANY_PARAMS":return"Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe.";case"ARKORDER_INGEST_WRITES_XI":return"Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe.";case"ARKORDER_XI_FIELD_WRITE":return typeof e.target=="string"&&e.target.length>0?`Don't write ${e.target} from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.`:"Don't write a named product choice from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.";case"ARKORDER_UNVALVED_RELEASE":return"Change the choice with proposeRelease then apply. release() is only the first freeze. Never mechanical-safe.";default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(fe,"deterministicNextAction");var Bt="1.5",Vr="docs/diagnostics.md",jr={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","mode","valid","completeness","completenessReasons","diagnostics"],allOf:[{if:{properties:{completeness:{enum:["partial","unavailable"]}},required:["completeness"]},then:{properties:{valid:{const:!1}}}},{if:{properties:{mode:{const:"resolved-candidate-facts"},completeness:{enum:["complete","partial"]}},required:["mode","completeness"]},then:{required:["policyHash","resolverIdentity","factsHash","candidateTreeHash"]}},{if:{properties:{completeness:{const:"complete"}},required:["completeness"]},then:{properties:{completenessReasons:{maxItems:0}}},else:{properties:{completenessReasons:{minItems:1}}}}],properties:{schemaVersion:{const:"1.5"},mode:{enum:["lexical-compatibility","resolved-candidate-facts"]},valid:{type:"boolean"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:{type:"string",minLength:1},message:{type:"string",minLength:1},file:{type:"string",minLength:1}}}},policyHash:{type:"string",minLength:1},resolverIdentity:{type:"string",minLength:1},factsHash:{type:"string",minLength:1},candidateTreeHash:{type:"string",minLength:1},diagnostics:{type:"array",items:{type:"object",additionalProperties:!1,required:["ruleId","severity","message","location","evidence"],properties:{ruleId:{type:"string",minLength:1},severity:{enum:["error","warning"]},message:{type:"string",minLength:1},location:{type:"object",additionalProperties:!1,required:["file","line","column"],properties:{file:{type:"string",minLength:1},line:{type:"integer",minimum:1},column:{type:"integer",minimum:1}}},evidence:{type:"object",additionalProperties:!1,properties:{target:{type:"string"},fromLayer:{type:"string"},toLayer:{type:"string"},typeOnly:{type:"boolean"},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"},peerIsolation:{type:"boolean"},capability:{type:"string",minLength:1},edgeKind:{type:"string",minLength:1},arkruleId:{type:"string",minLength:1},arkruleSource:{type:"string",minLength:1}}},nextAction:{type:"string",minLength:1},findingRef:{type:"string",minLength:1,pattern:"^fnv1a-[0-9a-f]{8}$"},targetKey:{type:"string",minLength:1},docsCodePath:{type:"string",minLength:1}}}}}};function qn(e){let t=typeof e.ruleId=="string"?e.ruleId:typeof e.code=="string"?e.code:void 0,n=typeof e.file=="string"?e.file:void 0,r=typeof e.fromLayer=="string"?e.fromLayer:void 0,o=typeof e.toLayer=="string"?e.toLayer:void 0,s=typeof e.target=="string"?e.target:void 0;return[t,n,r??"",o??"",s??""].join("|")}i(qn,"adapterFindingTargetKey");function Yn(e){let t=new Map;return e.map(n=>{let r=qn(n),o=(t.get(r)??0)+1;return t.set(r,o),o===1?r:`${r}#${o}`})}i(Yn,"adapterFindingOccurrenceTargetKeys");function Br(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}i(Br,"adapterFindingRefFromTargetKey");function Wr(e){return`${Vr}#${e}`}i(Wr,"adapterDocsCodePath");function O(e){return typeof e=="string"&&e.length>0?e:void 0}i(O,"text");function ps(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}i(ps,"positiveInteger");function Xa(e,t,n){return fe({ruleId:e,target:O(t.target)??O(n.target)??void 0,fromLayer:O(t.fromLayer)??void 0,toLayer:O(t.toLayer)??void 0,typeOnly:t.typeOnly===!0,targetTypeOnlyExports:t.targetTypeOnlyExports===!0,namedBindingsTypeOnly:t.namedBindingsTypeOnly===!0,portProofEligible:t.portProofEligible===!0,peerIsolation:t.peerIsolation===!0,sourcePureTypeModule:t.sourcePureTypeModule===!0,edgeKind:O(t.edgeKind)??void 0,capability:O(t.capability)??O(n.capability)??void 0,arkruleId:O(t.arkruleId)??void 0,arkruleSource:O(t.arkruleSource)??void 0})}i(Xa,"nextActionForDiagnostic");function Xn(e,t="error",n){let r=O(e.ruleId)??O(e.code)??"ARK_UNKNOWN",o=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,s={...O(e.target)?{target:O(e.target)}:{},...O(e.fromLayer)?{fromLayer:O(e.fromLayer)}:{},...O(e.toLayer)?{toLayer:O(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{},...typeof e.targetTypeOnlyExports=="boolean"?{targetTypeOnlyExports:e.targetTypeOnlyExports}:{},...typeof e.sourcePureTypeModule=="boolean"?{sourcePureTypeModule:e.sourcePureTypeModule}:{},...typeof e.namedBindingsTypeOnly=="boolean"?{namedBindingsTypeOnly:e.namedBindingsTypeOnly}:{},...typeof e.portProofEligible=="boolean"?{portProofEligible:e.portProofEligible}:{},...typeof e.peerIsolation=="boolean"?{peerIsolation:e.peerIsolation}:{},...O(e.capability)?{capability:O(e.capability)}:{},...O(e.edgeKind)?{edgeKind:O(e.edgeKind)}:{},...O(e.arkruleId)?{arkruleId:O(e.arkruleId)}:{},...O(e.arkruleSource)?{arkruleSource:O(e.arkruleSource)}:{}},a=n??qn(e),l=Br(a);return{ruleId:r,severity:o,message:O(e.message)??r,location:{file:O(e.file)??"<unknown>",line:ps(e.line,1),column:ps(e.column,1)},evidence:s,nextAction:O(e.nextAction)??Xa(r,s,e),findingRef:l,targetKey:a,docsCodePath:Wr(r)}}i(Xn,"toAdapterDiagnostic");function fs(e){let t=e.completeness??"complete",n=e.mode??"lexical-compatibility";if(t==="complete"&&(e.completenessReasons?.length??0)>0)throw new Error("completenessReasons must be empty when completeness is complete.");let r=t==="complete"?[]:e.completenessReasons&&e.completenessReasons.length>0?e.completenessReasons.map(y=>({code:O(y.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:O(y.message)??`Analysis ${t}: required evidence is incomplete.`,...O(y.file)?{file:O(y.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],o={...O(e.policyHash)?{policyHash:O(e.policyHash)}:{},...O(e.resolverIdentity)?{resolverIdentity:O(e.resolverIdentity)}:{},...O(e.factsHash)?{factsHash:O(e.factsHash)}:{},...O(e.candidateTreeHash)?{candidateTreeHash:O(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let y of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!o[y])throw new Error(`${y} is required for resolved ${t} adapter evidence.`)}let s=e.violations??[],a=e.warnings??[],l=Yn(s),c=Yn(a),p=[...s.map((y,u)=>Xn(y,"error",l[u])),...a.map((y,u)=>Xn(y,"warning",c[u]))],f={schemaVersion:"1.5",completenessReasons:r,diagnostics:p};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...f,mode:n,valid:!1,completeness:t,...o};let y={policyHash:o.policyHash,resolverIdentity:o.resolverIdentity,factsHash:o.factsHash,candidateTreeHash:o.candidateTreeHash};return t==="complete"?{...f,mode:n,valid:e.valid,completeness:t,...y}:{...f,mode:n,valid:!1,completeness:t,...y}}return t==="complete"?{...f,mode:n,valid:e.valid,completeness:t,...o}:{...f,mode:n,valid:!1,completeness:t,...o}}i(fs,"createAdapterResult");var Ve=class{static{i(this,"IntentRegistry")}intents=new Map;dependencies=new Map;productions=new Map;define(t,n){if(this.intents.has(t))throw new Error(`Intent "${t}" is already registered. Intent names must be unique within a registry.`);let r=i(s=>({intent:t,payload:s,metadata:{occurredAt:new Date().toISOString(),source:"unknown"}}),"fn");Object.defineProperty(r,"name",{value:t,enumerable:!0,configurable:!1,writable:!1});let o=r;if(this.intents.set(t,o),n?.dependsOn)for(let s of n.dependsOn)this.declareDependency(t,s);if(n?.produces)for(let s of n.produces)this.declareProduction(t,s);return o}declareDependency(t,n){this.dependencies.has(t)||this.dependencies.set(t,new Set),this.dependencies.get(t).add(n)}declareProduction(t,n){this.productions.has(t)||this.productions.set(t,new Set),this.productions.get(t).add(n)}get(t){return this.intents.get(t)}list(){return Array.from(this.intents.values())}getDependencies(t){let n=this.dependencies.get(t);return n?Array.from(n):[]}getProductions(t){let n=this.productions.get(t);return n?Array.from(n):[]}getAllRelationships(){let t=[];for(let[n,r]of this.dependencies.entries())for(let o of r)t.push({from:n,to:o,kind:"dependsOn"});for(let[n,r]of this.productions.entries())for(let o of r)t.push({from:n,to:o,kind:"produces"});return t}has(t){return this.intents.has(t)}clear(){this.intents.clear(),this.dependencies.clear(),this.productions.clear()}};var gs=new Ve;function zr(e,t){return gs.define(e,t)}i(zr,"defineIntent");function Wt(){return new Ve}i(Wt,"createIntentRegistry");var qr=gs;var ms=["Domain.","Application.","Adapter.","Workflow.","Job.","Presentation.","Reporting.","Metadata.","Security.","Audit.","Observability.","Kernel."];function zt(e){if(!e||typeof e!="string")return{valid:!1,reason:"Intent name must be a non-empty string"};if(!ms.some(n=>e.startsWith(n)))return{valid:!1,reason:`Intent "${e}" must start with one of: ${ms.join(", ")}`};let t=e.slice(e.indexOf(".")+1);return!t||!/^[A-Za-z][A-Za-z0-9_.]*$/.test(t)?{valid:!1,reason:`Intent "${e}" has an invalid segment after the layer prefix`}:{valid:!0}}i(zt,"validateIntentName");var Re=class extends Error{static{i(this,"PolicyViolationError")}violations;constructor(t){let n=t.map(r=>`- ${r.policyName}: ${r.message}`).join(`
6
6
  `);super(`Hard policy violation(s) detected:
7
7
  ${n}`),this.name="PolicyViolationError",this.violations=t}};var xe=class{static{i(this,"PolicyEngine")}policies=[];constructor(t=[]){for(let n of t)this.add(n)}add(t){if(this.policies.some(n=>n.name===t.name))throw new Error(`Policy "${t.name}" is already registered in this engine.`);this.policies.push(t)}getPolicies(){return[...this.policies]}evaluate(t){let n=[];for(let s of this.policies){let a=s.check(t);if(a!==!0){if(a===!1){n.push({policyName:s.name,severity:s.severity,message:`Policy "${s.name}" was violated.`});continue}if(Array.isArray(a))for(let l of a)n.push({policyName:s.name,severity:s.severity,message:l.message,details:l.details});else n.push({policyName:s.name,severity:s.severity,message:a.message,details:a.details})}}let r=n.filter(s=>s.severity==="hard"),o=n.filter(s=>s.severity==="soft");return{passed:n.length===0,violations:n,hardViolations:r,softViolations:o}}enforce(t){let n=this.evaluate(t);if(n.hardViolations.length>0)throw new Re(n.hardViolations);return n}clear(){this.policies.length=0}};function je(e){let t=e.severity??"soft";return{name:e.name,severity:t,tags:e.tags,owner:e.owner,version:e.version,rationale:e.rationale,enforcementMode:e.enforcementMode,deprecated:e.deprecated,replacedBy:e.replacedBy,check:e.check}}i(je,"definePolicy");function Za(e){let t=e.indexOf(".");return t>=0?e.slice(0,t):e}i(Za,"defaultLayerOf");function ys(e,t){return t.resolveLayer?.(e)??Za(e)}i(ys,"resolveLayer");function Ja(e,t,n){return e===n.from&&t===n.to}i(Ja,"matchesRule");function qt(e){let t=e.name??"Layer isolation",n=e.severity??"hard";return je({name:t,severity:n,tags:["layer"],check:i(r=>{let o=[...(r.edges??[]).filter(a=>a.kind==="declared"||a.kind==="produces").map(a=>({from:a.from,to:a.to})),...(r.relationships??[]).filter(a=>a.kind==="dependsOn").map(a=>({from:a.from,to:a.to}))],s=[];for(let a of o){let l=ys(a.from,e),c=ys(a.to,e);for(let p of e.rules)!p.allowed&&Ja(l,c,p)&&s.push({policyName:t,severity:n,message:p.message??`Layer violation: ${a.from} (${l}) must not relate to ${a.to} (${c})`})}return s.length>0?s:!0},"check")})}i(qt,"defineLayerPolicy");function Yt(e){return e.tags?.includes("layer")??!1}i(Yt,"isLayerPolicy");var Zn={layerIsolation(){return Zn.cleanArchitectureMatrix()},cleanArchitectureMatrix(){return qt({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 Xt(e,t={}){return qt({name:t.name??`${e.name} layer policy`,severity:t.severity??"hard",rules:e.rules,resolveLayer:e.resolveLayer})}i(Xt,"defineArchitectureProfilePolicy");function Zt(e){return t=>({event:t,relationships:e.intentRegistry?.getAllRelationships(),edges:e.dependencyGraph?.getEdges()})}i(Zt,"buildPublishPolicyContext");function Yr(e){return je(e)}i(Yr,"definePublishPolicy");var Be=class extends Error{static{i(this,"UnregisteredIntentError")}intentName;constructor(t){super(`Intent "${t}" is not registered. Register it with IntentRegistry.define() before publish/subscribe, including metadata.source producer intents in strict mode.`),this.name="UnregisteredIntentError",this.intentName=t}},We=class extends Error{static{i(this,"InvalidIntentNameError")}intentName;reason;constructor(t,n){super(`Invalid intent name "${t}": ${n}`),this.name="InvalidIntentNameError",this.intentName=t,this.reason=n}},ze=class extends Error{static{i(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"}},qe=class extends Error{static{i(this,"EventContractViolationError")}intentName;issues;constructor(t,n){super(`Event contract violation for "${t}". Register a matching event contract/version or fix the payload before publishing.`),this.name="EventContractViolationError",this.intentName=t,this.issues=n}},Oe=class extends Error{static{i(this,"UnknownEventSourceError")}intentName;source;constructor(t,n){super(n?`Event "${t}" metadata.source "${n}" is not registered. Register the producer intent or publish from a known source.`:`Event "${t}" must include metadata.source. Strict Ark uses source to enforce observed layer flow.`),this.name="UnknownEventSourceError",this.intentName=t,this.source=n}},Ae=class extends Error{static{i(this,"SourceMetadataOverrideError")}boundSource;attemptedSource;constructor(t,n){super(`Source-bound publisher for "${t}" cannot publish with metadata.source "${n}". Create a publisher for the intended source instead.`),this.name="SourceMetadataOverrideError",this.boundSource=t,this.attemptedSource=n}},Ye=class extends Error{static{i(this,"ObservedLayerFlowViolationError")}source;intentName;fromLayer;toLayer;constructor(t,n,r,o,s){super(s??`Observed layer violation: "${t}" (${r}) must not produce "${n}" (${o}). Route this through an allowed layer or adjust the architecture profile rule.`),this.name="ObservedLayerFlowViolationError",this.source=t,this.intentName=n,this.fromLayer=r,this.toLayer=o}};function Jt(e,t){if(!(!t.strictRegistry&&!t.validateIntentNaming)){if(t.validateIntentNaming){let n=zt(e);if(!n.valid)throw new We(e,n.reason)}if(t.strictRegistry&&t.intentRegistry&&!t.intentRegistry.has(e))throw new Be(e)}}i(Jt,"assertIntentAllowed");function hs(e,t){if(t.requireKnownSource){if(!e.metadata.source||e.metadata.source==="unknown")throw new Oe(e.intent);if(t.intentRegistry&&!t.intentRegistry.has(e.metadata.source))throw new Oe(e.intent,e.metadata.source)}}i(hs,"assertSourceAllowed");function Qt(e,t){if(!t.eventContracts)return;let n=t.eventContracts.validate(e);if(!n.ok&&(t.strictEventContracts||n.contract))throw new qe(e.intent,n.issues)}i(Qt,"assertContractAllowed");function dt(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}i(dt,"isPlainRecord");function ut(e){return Array.isArray(e)?e.map(ut):dt(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,ut(n)])):e}i(ut,"clonePatchValue");function Xr(e,t,n="payload"){let r={...e};for(let[o,s]of Object.entries(t)){let a=`${n}.${o}`;if(!(o in r)||r[o]===void 0){r[o]=ut(s);continue}if(dt(r[o])&&dt(s)){r[o]=Xr(r[o],s,a);continue}if(Array.isArray(r[o])&&Array.isArray(s)){r[o]=Zr(r[o],s,a);continue}throw new Error(`Interceptor patch cannot overwrite existing ${a}.`)}return r}i(Xr,"mergeRecordPatch");function Zr(e,t,n="payload"){let r=[...e];return t.forEach((o,s)=>{let a=`${n}[${s}]`;if(s>=r.length||r[s]===void 0){r[s]=ut(o);return}if(dt(r[s])&&dt(o)){r[s]=Xr(r[s],o,a);return}if(Array.isArray(r[s])&&Array.isArray(o)){r[s]=Zr(r[s],o,a);return}throw new Error(`Interceptor patch cannot overwrite existing ${a}.`)}),r}i(Zr,"mergeArrayPatch");function Rs(e,t){if(Array.isArray(t)){if(e===void 0)return ut(t);if(!Array.isArray(e))throw new Error("Array interceptor patch requires an array payload.");return Zr(e,t)}if(e===void 0)return ut(t);if(!dt(e))throw new Error("Object interceptor patch requires an object payload.");return Xr(e,t)}i(Rs,"applyPayloadPatch");async function As(e,t){if(e.metadata.allowInterception===!1)return e;let n=[...t.interceptorsForIntent(e.intent)],r=e;for(let o of n){let s=[];try{if(await Promise.resolve(o.interceptor({event:r,intercept:i(c=>{s.push(c)},"intercept")})),s.length===0)continue;let a=new Date().toISOString(),l={...r,metadata:{...r.metadata,interceptions:[...r.metadata.interceptions??[],{interceptorId:o.interceptorId,timestamp:a}]}};for(let c of s)l={...l,payload:Rs(l.payload,c),metadata:{...l.metadata}};Qt(l,{eventContracts:t.eventContracts,strictEventContracts:t.strictEventContracts}),r=l,o.lastInterceptedAt=a,t.appendTrace({type:"event.intercepted",timestamp:a,intent:r.intent,correlationId:r.metadata.correlationId,traceId:r.metadata.traceId,spanId:r.metadata.spanId,details:{registrationId:o.registrationId,interceptorId:o.interceptorId,patchesApplied:s.length}}),await t.recordAudit("event.intercepted",r,{registrationId:o.registrationId,interceptorId:o.interceptorId,patchesApplied:s.length})}catch(a){await Qa(o,r,a,t)}}return r}i(As,"applyInterceptors");async function Qa(e,t,n,r){let o=n instanceof Error?n.message:String(n);r.appendTrace({type:"interceptor.error",timestamp:new Date().toISOString(),intent:t.intent,correlationId:t.metadata.correlationId,traceId:t.metadata.traceId,spanId:t.metadata.spanId,details:{registrationId:e.registrationId,interceptorId:e.interceptorId,error:o}}),await r.recordAudit("interceptor.error",t,{registrationId:e.registrationId,interceptorId:e.interceptorId,error:o})}i(Qa,"recordInterceptorError");var ks=new Map;function Is(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(Is,"escapeLiteral");function Jn(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let o=e[n+1];if("*?{}[],".includes(o)||o==="\\"){t+="\\"+o,n+=1;continue}t+="/";continue}t+=r}return t}i(Jn,"normalizeGlobSeparators");function el(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="{")t+=1;else if(r==="}"&&(t-=1,t<0))return!1}return t===0}i(el,"bracesBalanced");function ke(e){let t=ks.get(e);if(t)return t;let n=Jn(e),r=el(n),o="",s=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(o+=Is(n[l+1]),l+=1):c==="*"?n[l+1]==="*"?n[l+2]==="/"?(o+="(?:.*/)?",l+=2):(o+=".*",l+=1):o+="[^/]*":c==="?"?o+="[^/]":c==="{"&&r?(o+="(?:",s+=1):c==="}"&&r&&s>0?(o+=")",s-=1):c===","&&r&&s>0?o+="|":o+=Is(c)}let a=new RegExp(`^${o}$`);return ks.set(e,a),a}i(ke,"globToRegExp");function tl(e){return Jn(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}i(tl,"concreteGlobSegments");function Jr(e,t){let n=Jn(String(e)),r=tl(n),o=n.replace(/\*/g,"").length,s=r.length*1e4+o;if(t==null||t==="")return s;let a=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return o;let l=0,c=-1;for(let p of r){let f=-1;for(let y=l;y<a.length;y+=1)if(a[y]===p){f=y;break}if(f<0)return s;c=f,l=f+1}return(c+1)*1e6+r.length*1e4+o}i(Jr,"patternSpecificity");function de(e,t){let n=String(e).split(/[/\\]/).join("/"),r,o=-1;for(let s of t??[])if(!(s.exclude??[]).some(a=>ke(a).test(n))){for(let a of s.patterns??[])if(ke(a).test(n)){let l=Jr(a,n);l>o&&(o=l,r=s.name)}}return r}i(de,"layerForRelativePath");function bs(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),r=new Set(t.map(o=>String(o).toLowerCase()));for(let o=0;o<n.length-1;o+=1)if(r.has(n[o].toLowerCase()))return`${n[o].toLowerCase()}/${n[o+1].toLowerCase()}`}i(bs,"sliceIdForPath");function nl(e){let t=new Set;for(let n of e??[]){let o=Jn(String(n)).split("/").filter(Boolean);for(let s=0;s<o.length;s+=1){let a=o[s];if((a==="**"||a==="*")&&s>0){let l=o[s-1];l&&!l.includes("*")&&!l.includes("{")&&!l.includes("}")&&t.add(l)}}}return[...t]}i(nl,"inferSliceFoldersFromPatterns");function rl(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(o=>typeof o=="string"&&o.length>0);let r=(n??[]).find(o=>o.name===t);return nl(r?.patterns)}i(rl,"resolveSliceFolders");function vs(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}i(vs,"normalizeSegments");function ws(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}i(ws,"trimTrailingSlashes");var ol=["src","app"];function sl(e){let t=ws(e.replace(/^[./]+/,""));return t==="*"||t==="**"}i(sl,"isBlanketRoot");function Es(e,t){if(!e||!t?.length)return!1;let n=String(e).split(/[/\\]/).join("/"),r=n.toLowerCase(),o=vs(n);for(let s of t){if(typeof s!="string"||s.length===0||sl(s))continue;if(s.includes("*")){let c=ws(s.toLowerCase());if(ke(c).test(r)||ke(`${c}/**`).test(r))return!0;continue}let a=vs(s);if(a.length===0)continue;let l=ol.includes(o[0])&&a[0]!==o[0]?[0,1]:[0];for(let c of l){if(c+a.length>o.length)continue;let p=!0;for(let f=0;f<a.length;f+=1)if(o[c+f]!==a[f]){p=!1;break}if(p)return!0}}return!1}i(Es,"pathUnderSharedRoot");function Ss(e,t){let n=String(e).split(/[/\\]/).filter(Boolean).join("/").toLowerCase();if(!n)return!1;let r=t.toLowerCase();return n===r?!0:!n.includes("/")&&r.endsWith(`/${n}`)}i(Ss,"sliceMatchesDeclaration");function il(e,t,n){return!e?.length||!t||!n?!1:e.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&Ss(r.from,t)&&Ss(r.to,n))}i(il,"crossSliceEdgeAllowed");function al(e){if(!e.fromPath)return{denied:!0,reason:"missing-path"};if(e.folderCount<=0)return{denied:!0,reason:"no-slice-folders"};let t=!!e.fromSlice||e.fromShared===!0;if(!e.toPath)return t?e.fromSlice?{denied:!0,reason:"missing-path"}:{denied:!1}:{denied:!0,reason:"unclassifiable-path"};let n=!!e.toSlice||e.toShared===!0;return!t||!n?{denied:!0,reason:"unclassifiable-path"}:!e.fromSlice||!e.toSlice?{denied:!1}:e.fromSlice===e.toSlice?{denied:!1}:e.crossSliceAllowed?{denied:!1}:{denied:!0,reason:"cross-slice"}}i(al,"peerIsolationDecision");function pt(e,t){switch(e){case"cross-slice":return`cross-slice edge ${t.fromSlice??"?"} \u2192 ${t.toSlice??"?"}. Extract the shared code, use events/ports across slices, or declare the edge in the rule's allowedCrossSlice.`;case"unclassifiable-path":{let n=[t.fromSlice?void 0:t.fromPath,t.toSlice?void 0:t.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."}}i(pt,"peerIsolationDenyExplanation");function ft(e,t,n,r){return Xe(e,t,n,r)?.rule}i(ft,"findDeniedEdgeRule");function Xe(e,t,n,r){for(let o of e??[])if(!(o.from!==t||o.to!==n)&&o.allowed===!1){if(o.peerIsolation){let s=r?.fromPath,a=r?.toPath,l=rl(o,t,r?.layers),c=s?bs(s,l):void 0,p=a?bs(a,l):void 0,f=al({fromPath:s,toPath:a,folderCount:l.length,fromSlice:c,toSlice:p,fromShared:!c&&Es(s,o.sharedRoots),toShared:!p&&Es(a,o.sharedRoots),crossSliceAllowed:il(o.allowedCrossSlice,c,p)});if(f.denied)return{rule:o,peerIsolationReason:f.reason,fromSlice:c,toSlice:p};continue}if(t!==n)return{rule:o}}}i(Xe,"findDeniedEdgeDecision");async function Cs(e,t){if(t.mode==="off"||!t.architectureProfile)return;let n=e.metadata.source;if(!n||n==="unknown")return;let r=t.architectureProfile,o=r.resolveLayer(n),s=r.resolveLayer(e.intent);if(!o||!s)return;let a=ft(r.rules,o,s);if(!a)return;let l=t.mode,c=a.message??`Observed layer violation: "${n}" (${o}) must not produce "${e.intent}" (${s}).`,p={source:n,intent:e.intent,fromLayer:o,toLayer:s,severity:l,message:c,rule:a};if(t.appendTrace({type:"layer.observedViolation",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:p}),await t.recordAudit("layer.observedViolation",e,p),l==="hard")throw new Ye(n,e.intent,o,s,c)}i(Cs,"assertObservedLayerFlowAllowed");async function xs(e,t){let n=t.getPolicyContext(e),r;try{r=t.policyEngine.enforce(n)}catch(o){throw o instanceof Re&&(t.appendTrace({type:"policy.hardViolation",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:{violations:o.violations}}),await t.recordAudit("policy.hardViolation",e,{violations:o.violations})),o}r.softViolations.length>0&&(t.appendTrace({type:"policy.softViolation",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:{violations:r.softViolations}}),await t.recordAudit("policy.softViolation",e,{violations:r.softViolations}),t.onSoftViolation&&await t.safeHook(()=>t.onSoftViolation(r,e),"onSoftViolation",e))}i(xs,"enforcePublishPolicy");function ll(e,t){e.history.push(t),e.maxHistorySize!==void 0&&e.history.length>e.maxHistorySize&&e.history.splice(0,e.history.length-e.maxHistorySize)}i(ll,"appendHistory");function en(e,t){e.trace.push(t),e.maxHistorySize!==void 0&&e.trace.length>e.maxHistorySize&&e.trace.splice(0,e.trace.length-e.maxHistorySize);for(let n of e.traceSinks)try{n(t)}catch{}}i(en,"appendTrace");async function Qn(e,t,n,r){if(e.auditTrail)try{await e.auditTrail.record({type:t,source:n.metadata.source,intent:n.intent,correlationId:n.metadata.correlationId,causationId:n.metadata.causationId,subject:n.intent,details:r})}catch(o){en(e,{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)}})}}i(Qn,"recordAudit");async function Os(e,t){let n={intent:t.intent,source:t.metadata.source,suggestion:"Publish through a registered intent creator so strict registry, contracts, and agent tooling share one source of truth."};en(e,{type:"event.rawPublish",timestamp:new Date().toISOString(),intent:t.intent,correlationId:t.metadata.correlationId,traceId:t.metadata.traceId,spanId:t.metadata.spanId,details:n}),await Qn(e,"event.rawPublish",t,n)}i(Os,"recordRawPublishDiagnostic");async function Ps(e,t,n,r){let o={event:t,publishedAt:new Date().toISOString(),subscribersNotified:n};return ll(e,o),await e.eventBuffer?.enqueue(t,r),en(e,{type:"event.published",timestamp:o.publishedAt,intent:t.intent,correlationId:t.metadata.correlationId,traceId:t.metadata.traceId,spanId:t.metadata.spanId,details:{subscribersNotified:n}}),await Qn(e,"event.published",t,{subscribersNotified:n}),o}i(Ps,"recordSuccessfulPublish");function Qr(e,t,n){return{...e,...t,occurredAt:t.occurredAt||e.occurredAt||new Date().toISOString(),source:t.source||e.source||"unknown",kernelInstanceId:t.kernelInstanceId??e.kernelInstanceId??n,eventVersion:t.eventVersion??e.eventVersion,schemaVersion:t.schemaVersion??e.schemaVersion,allowInterception:t.allowInterception??e.allowInterception,interceptions:t.interceptions??e.interceptions,correlationId:t.correlationId??e.correlationId,causationId:t.causationId??e.causationId,traceId:t.traceId??e.traceId,spanId:t.spanId??e.spanId,parentSpanId:t.parentSpanId??e.parentSpanId}}i(Qr,"enrichMetadata");var _s=0;function cl(){return _s+=1,`interceptor-${Date.now()}-${_s}`}i(cl,"nextInterceptorRegistrationId");var gt=class{static{i(this,"EventBusImpl")}subscriptions=[];subscriptionsByIntent=new Map;interceptors=[];interceptorsByIntent=new Map;recording;onPublish;onSoftViolation;onHandlerError;eventContracts;strictEventContracts;requireKnownSource;architectureProfile;enforceObservedLayerFlowMode;rethrowHandlerErrors;policyEngine;getPolicyContext;intentRegistry;dependencyGraph;strictRegistry;validateIntentNaming;constructor(t={}){if(this.onPublish=t.onPublish,this.onSoftViolation=t.onSoftViolation,this.onHandlerError=t.onHandlerError,this.eventContracts=t.eventContracts,this.strictEventContracts=t.strictEventContracts??!1,this.requireKnownSource=t.requireKnownSource??!1,this.architectureProfile=t.architectureProfile,this.enforceObservedLayerFlowMode=t.enforceObservedLayerFlow??"off",this.rethrowHandlerErrors=t.rethrowHandlerErrors??!1,this.intentRegistry=t.intentRegistry,this.dependencyGraph=t.dependencyGraph,this.strictRegistry=t.strictRegistry??t.intentRegistry!==void 0,this.validateIntentNaming=t.validateIntentNaming??this.strictRegistry,this.recording={history:[],trace:[],maxHistorySize:t.maxHistorySize,traceSinks:[...t.traceSinks??[]],auditTrail:t.auditTrail,eventBuffer:t.eventBuffer??t.outbox,instanceId:t.instanceId},t.policyEngine?this.policyEngine=t.policyEngine:t.policies&&t.policies.length>0&&(this.policyEngine=new xe(t.policies)),(this.policyEngine?.getPolicies()??t.policies??[]).some(Yt)&&!t.intentRegistry&&!t.dependencyGraph&&!t.getPolicyContext)throw new ze;t.getPolicyContext?this.getPolicyContext=t.getPolicyContext:t.intentRegistry||t.dependencyGraph?this.getPolicyContext=Zt({intentRegistry:t.intentRegistry,dependencyGraph:t.dependencyGraph}):this.getPolicyContext=r=>({event:r})}async publish(t,n,r,o){await this.dispatch(t,n,r,o)}async dispatch(t,n,r,o={}){let s=o.notifySubscribers!==!1,a=o.awaitHandlers!==!1,l=o.runOnPublish!==!1,c,p=typeof t!="function";if(p){let u=t,g=r??n??{};c={...u,metadata:Qr(u.metadata,g,this.recording.instanceId)}}else{let u=t,g=n,d=r??{},m=u(g);c={...m,metadata:Qr(m.metadata,d,this.recording.instanceId)}}p&&this.strictRegistry&&await Os(this.recording,c),Jt(c.intent,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),hs(c,{requireKnownSource:this.requireKnownSource,intentRegistry:this.intentRegistry}),Qt(c,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),c=await As(c,{interceptorsForIntent:i(u=>this.interceptorsByIntent.get(u)??[],"interceptorsForIntent"),eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts,appendTrace:i(u=>this.appendTrace(u),"appendTrace"),recordAudit:i((u,g,d)=>this.recordAudit(u,g,d),"recordAudit")}),Qt(c,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),await Cs(c,{mode:this.enforceObservedLayerFlowMode,architectureProfile:this.architectureProfile,appendTrace:i(u=>this.appendTrace(u),"appendTrace"),recordAudit:i((u,g,d)=>this.recordAudit(u,g,d),"recordAudit")}),this.dependencyGraph?.registerEventFlow(c.metadata.source,c.intent);let f=[...this.subscriptionsByIntent.get(c.intent)??[]];this.policyEngine&&await xs(c,{policyEngine:this.policyEngine,getPolicyContext:this.getPolicyContext,appendTrace:i(u=>this.appendTrace(u),"appendTrace"),recordAudit:i((u,g,d)=>this.recordAudit(u,g,d),"recordAudit"),onSoftViolation:this.onSoftViolation,safeHook:i((u,g,d)=>this.safeHook(u,g,d),"safeHook")}),await Ps(this.recording,c,s?f.length:0,o.tx);let y=(async()=>{s&&await Promise.all(f.map(u=>this.invokeHandler(u,c))),l&&this.onPublish&&await this.safeHook(()=>this.onPublish(c),"onPublish",c)})();return a?await y:y.then(void 0,()=>{}),c}createPublisher(t){let n=typeof t=="string"?t:t.name;return Jt(n,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),{source:n,publish:i(async(r,o,s={},a)=>{if(s.source&&s.source!==n)throw new Ae(n,s.source);await this.publish(r,o,{...s,source:n},a)},"publish")}}subscribe(t,n){let r=typeof t=="string"?t:t.name;Jt(r,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let o={intentName:r,handler:n};this.subscriptions.push(o);let s=this.subscriptionsByIntent.get(r)??[];return s.push(o),this.subscriptionsByIntent.set(r,s),()=>{let a=this.subscriptions.indexOf(o);a>=0&&this.subscriptions.splice(a,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(t,n,r){let o=typeof t=="string"?t:t.name;Jt(o,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let s={registrationId:cl(),interceptorId:r??o,intentName:o,interceptor:n,createdAt:new Date().toISOString()};this.interceptors.push(s);let a=this.interceptorsByIntent.get(o)??[];return a.push(s),this.interceptorsByIntent.set(o,a),s.registrationId}unregisterInterceptor(t){let n=this.interceptors.find(s=>s.registrationId===t);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 s=o.indexOf(n);s>=0&&o.splice(s,1),o.length===0&&this.interceptorsByIntent.delete(n.intentName)}return!0}listInterceptors(t){return this.interceptors.filter(n=>!t||n.intentName===t).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(t){en(this.recording,t)}async recordAudit(t,n,r){await Qn(this.recording,t,n,r)}async invokeHandler(t,n){try{await Promise.resolve(t.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:t.intentName,error:r instanceof Error?r.message:String(r)}),this.onHandlerError&&await this.safeHook(()=>this.onHandlerError(r,n,t.intentName),"onHandlerError",n),this.rethrowHandlerErrors)throw r}}async safeHook(t,n,r){try{await Promise.resolve(t())}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 eo(e){return new gt(e)}i(eo,"createEventBus");function dl(e){if(!(!e||e.length===0))return e.map(t=>typeof t=="object"&&t!==null&&"key"in t?String(t.key):String(t)).join(".")}i(dl,"formatStandardSchemaPath");function ul(e){if(Array.isArray(e))return"array";if(e===null)return"object";let t=typeof e;return t==="string"||t==="number"||t==="boolean"||t==="object"?t:"unknown"}i(ul,"actualType");function pl(e,t){return e?`${e}.${t}`:t}i(pl,"formatPath");function Ts(e,t,n,r,o){let s=ul(e);if(t.type!=="unknown"&&s!==t.type){o.push({intent:r.intent,version:r.version,field:n,message:`Expected ${t.type}, received ${s}.`});return}if(t.enum&&!t.enum.some(a=>Object.is(a,e))&&o.push({intent:r.intent,version:r.version,field:n,message:"Value is not allowed by event contract enum."}),t.type==="object"&&t.fields){if(e===null||typeof e!="object"||Array.isArray(e)){o.push({intent:r.intent,version:r.version,field:n,message:"Nested object field must be a non-array object."});return}Ns(e,t.fields,r,o,n)}t.type==="array"&&t.items&&Array.isArray(e)&&e.forEach((a,l)=>{Ts(a,t.items,`${n}[${l}]`,r,o)})}i(Ts,"validateSchemaField");function Ns(e,t,n,r,o){for(let[s,a]of Object.entries(t)){let l=pl(o,s),c=e[s];if(c===void 0){a.required&&r.push({intent:n.intent,version:n.version,field:l,message:"Required field is missing."});continue}Ts(c,a,l,n,r)}}i(Ns,"validateObjectSchema");var mt=class{static{i(this,"EventContractRegistryImpl")}contracts=new Map;register(t){let n=this.key(t.intent,t.version);if(this.contracts.has(n))throw new Error(`Event contract "${n}" is already registered.`);this.contracts.set(n,{allowAdditionalFields:!0,...t})}get(t,n){return n?this.contracts.get(this.key(t,n)):this.list(t).at(-1)}list(t){return Array.from(this.contracts.values()).filter(n=>!t||n.intent===t)}validate(t){let n=t.metadata.eventVersion,r=this.get(t.intent,n),o=[];if(!r)return{ok:!1,issues:[{intent:t.intent,version:n,message:n?`No event contract registered for version "${n}".`:"No event contract registered for intent."}]};r.deprecated&&o.push({intent:t.intent,version:r.version,message:typeof r.deprecated=="string"?r.deprecated:"Event contract is deprecated."});let s=t.payload!=null&&typeof t.payload=="object"?t.payload:void 0;if(r.schema){if(!s)o.push({intent:t.intent,version:r.version,message:"Payload must be an object for schema validation."});else if(Ns(s,r.schema,r,o),r.allowAdditionalFields===!1)for(let a of Object.keys(s))r.schema[a]||o.push({intent:t.intent,version:r.version,field:a,message:"Additional field is not allowed by event contract."})}if(r.standardSchema){let a=r.standardSchema["~standard"].validate(t.payload);if(a instanceof Promise)o.push({intent:t.intent,version:r.version,message:"Standard Schema validator returned a Promise; event contract validation is synchronous."});else if(a.issues)for(let l of a.issues)o.push({intent:t.intent,version:r.version,field:dl(l.path),message:l.message})}return{ok:o.length===0,contract:r,issues:o}}clear(){this.contracts.clear()}key(t,n){return`${t}@${n}`}};function tn(){return new mt}i(tn,"createEventContractRegistry");var Ds=0;function fl(){return Ds+=1,`outbox-${Date.now()}-${Ds}`}i(fl,"nextOutboxId");function Ls(e){return{...e,event:{...e.event,metadata:{...e.event.metadata}}}}i(Ls,"cloneRecord");var Pe=class{static{i(this,"InMemoryEventBuffer")}records=new Map;async enqueue(t){let n=new Date().toISOString(),r={id:fl(),event:t,status:"pending",attempts:0,createdAt:n,updatedAt:n};return this.records.set(r.id,r),Ls(r)}async markDispatched(t){let n=this.records.get(t);n&&(n.status="dispatched",n.updatedAt=new Date().toISOString())}async markFailed(t,n){let r=this.records.get(t);r&&(r.status="failed",r.attempts+=1,r.error=n instanceof Error?n.message:String(n),r.updatedAt=new Date().toISOString())}async list(t){return Array.from(this.records.values()).filter(n=>!t||n.status===t).map(Ls)}async clear(){this.records.clear()}},to=Pe;function no(e){return`${e.from}->${e.to}`}i(no,"flowKey");function Fs(e){let t=new Set,n=[];for(let r of e){let o=no(r);t.has(o)||(t.add(o),n.push(r))}return n}i(Fs,"uniqueFlows");function Ms(e,t){let n=new Set(t.map(no));return e.filter(r=>!n.has(no(r)))}i(Ms,"difference");function nn(e){let t=e.registry,n=e.eventBus,r=e.graph;return{report(){let o=t?t.getAllRelationships().filter(m=>m.kind==="produces").map(m=>({from:m.from,to:m.to})):[],s=o.length>0||!r?[]:r.getEdges().filter(m=>m.kind==="produces").map(m=>({from:m.from,to:m.to})),a=n?.getHistory().map(m=>({from:m.event.metadata.source,to:m.event.intent}))??[],l=a.length>0||!r?[]:r.getEdges().filter(m=>m.kind==="observed").map(m=>({from:m.from,to:m.to})),c=Fs([...o,...s]),p=Fs([...a,...l]),f=p.filter(m=>!m.from||m.from==="unknown"),y=t?Array.from(new Set(p.map(m=>m.from).filter(m=>m&&m!=="unknown"&&!t.has(m)))):[],u=t?Array.from(new Set(p.map(m=>m.to).filter(m=>!t.has(m)))):[],g=new Set(p.flatMap(m=>[m.from,m.to])),d=t?t.list().map(m=>m.name).filter(m=>!g.has(m)):[];return{generatedAt:new Date().toISOString(),declaredProductions:c,observedProductions:p,declaredButUnobserved:Ms(c,p),observedButUndeclared:Ms(p.filter(m=>m.from!=="unknown"),c),unknownSources:f,unregisteredObservedSources:y,unregisteredObservedIntents:u,registeredButNeverObserved:d}}}}i(nn,"createObservabilityReporter");function ro(e){return{events(t){return e.eventBus.getHistory().map(n=>n.event).filter(n=>!t||n.intent===t)},traces(t){return e.eventBus.getTrace().filter(n=>!t||n.type===t)},audit(t){return e.auditTrail.query(t)},outbox(t){return e.outbox.list(t)},observability(){return e.syncGraph(),e.observability.report()},async snapshot(){return{events:this.events(),traces:this.traces(),audit:await this.audit(),outbox:await this.outbox(),observability:this.observability()}},async clear(){e.eventBus.clearHistory(),e.eventBus.clearTrace(),await e.auditTrail.clear(),await e.outbox.clear()}}}i(ro,"createArkTestHarness");var $s=0;function gl(){return $s+=1,`audit-${Date.now()}-${$s}`}i(gl,"createAuditId");function ml(e,t){return!(t.type&&e.type!==t.type||t.intent&&e.intent!==t.intent||t.correlationId&&e.correlationId!==t.correlationId||t.subject&&e.subject!==t.subject||t.since&&e.timestamp<t.since||t.until&&e.timestamp>t.until)}i(ml,"matchesQuery");var yt=class{constructor(t){this.maxRecords=t}maxRecords;static{i(this,"InMemoryAuditStore")}records=[];append(t){this.records.push(t),this.maxRecords!==void 0&&this.records.length>this.maxRecords&&this.records.splice(0,this.records.length-this.maxRecords)}query(t={}){let n=this.records.filter(r=>ml(r,t));return t.limit===void 0?[...n]:n.slice(-t.limit)}clear(){this.records.length=0}},er=class{constructor(t){this.store=t}store;static{i(this,"AuditTrailImpl")}async record(t){let n={id:gl(),timestamp:t.timestamp??new Date().toISOString(),type:t.type,source:t.source,actor:t.actor,intent:t.intent,correlationId:t.correlationId,causationId:t.causationId,subject:t.subject,details:t.details};return await this.store.append(n),n}async query(t){return this.store.query(t)}async clear(){await this.store.clear()}};function rn(e={}){return new er(e.store??new yt(e.maxRecords))}i(rn,"createAuditTrail");var tr=class{static{i(this,"DependencyGraphImpl")}nodes=new Map;edges=[];registerDependency(t,n,r="declared"){this.ensureNode(t),this.ensureNode(n),this.addEdge({from:t,to:n,kind:r})}registerEventFlow(t,n){this.ensureNode(t),this.ensureNode(n),this.addEdge({from:t,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 t=`flowchart TD
8
8
  `;for(let r of this.edges){let o=r.kind?`|${r.kind}|`:"";t+=` ${this.safeId(r.from)} -->${o} ${this.safeId(r.to)}
@@ -1,4 +1,4 @@
1
- export { n as AICodeGate, o as AICodeGateContext, p as AICodeGateOptions, q as AICodeGateResult, r as AICodeGateViolation, s as AIGateExtension, t as ANALYSIS_IR_SCHEMA_VERSION, u as ARK_ANALYSIS_RESULT_SCHEMA, v as ARK_ANALYSIS_RESULT_SCHEMA_VERSION, w as ARK_DESIGN_DELTA_SCHEMA_VERSION, x as ARK_ENFORCEMENT_STATE_SCHEMA_VERSION, y as AdapterCompletenessReason, z as AdapterDiagnostic, B as AdapterResult, C as AdapterSeverity, A as AdapterViolationInput, D as AnalysisCapabilityUse, F as AnalysisCompilerOptions, G as AnalysisCompleteness, H as AnalysisContract, I as AnalysisEvidence, J as AnalysisFile, K as AnalysisFileChange, L as AnalysisFileInput, M as AnalysisImportEdge, N as AnalysisIr, O as AnalysisMode, P as AnalysisResult, Q as AnalysisViolation, S as AnalyzeArchitectureConvergenceInput, T as AnalyzeChangeInput, U as AnalyzePolicyDeltaInput, V as AnalyzeProjectInput, W as AnalyzeResolvedProjectInput, X as ArchitectureActualChange, Y as ArchitectureChangeMap, Z as ArchitectureChangeMapContract, _ as ArchitectureChangeMapDependency, $ as ArchitectureChangeMapFile, a0 as ArchitectureChangeOperation, a1 as ArchitectureConvergenceClassification, a2 as ArchitectureConvergenceFinding, a3 as ArchitectureConvergenceResult, a4 as ArchitectureDependency, a5 as ArchitectureEngineEdge, a6 as ArchitectureEngineResult, a7 as ArchitectureEngineViolation, a8 as ArkDesignDeltaResult, a9 as ArkEnforcementHost, aa as ArkEnforcementState, ac as ChangePreflightResult, ae as CollectAnalysisConfigWarningsInput, af as DIAGNOSTIC_CATALOG, ag as DIAGNOSTIC_CATALOG_SCHEMA_VERSION, ah as DIAGNOSTIC_DOCS_RELATIVE_PATH, ai as DIAGNOSTIC_RULE_IDS, aj as DesignDeltaChange, ak as DesignDeltaEnforcementScope, al as DesignDeltaIdentity, am as DesignSmellEvidence, an as DesignSmellFinding, ao as DesignSmellId, ap as DiagnosticCatalogEntry, aq as DiagnosticCategory, ar as EnforcementBoundaryState, as as EnforcementEvidence, at as EnforcementEvidenceField, au as EnforcementVerification, av as EvaluateArchitectureGraphInput, aw as ForbiddenCapabilityUse, ay as POLICY_DELTA_SCHEMA_VERSION, az as PolicyDelta, aA as PolicyDeltaAcknowledgement, aB as PolicyDeltaAnalysis, aC as PolicyDeltaClassification, aD as PolicyDeltaFinding, aE as PreflightResolvedChangeInput, aF as PreparedChangeFile, aG as RESOLVED_CANDIDATE_FACTS_SCHEMA, aH as RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION, aI as ResolvedAmbientFact, aJ as ResolvedAnalysisFile, aK as ResolvedAnalysisIr, aL as ResolvedAnalysisResult, f as ResolvedArkRunCompositionRootHitFact, b as ResolvedArkRunDeclarationFact, c as ResolvedArkRunKernelCallFact, R as ResolvedArkRunKernelCallKind, d as ResolvedArkRunManagedNewFact, aM as ResolvedCandidateFacts, aN as ResolvedCandidateFactsInput, aO as ResolvedCapability, aP as ResolvedCapabilityFact, aQ as ResolvedChangePreflightResult, e as ResolvedDependencyFact, aR as ResolvedDependencyKind, aS as ResolvedDependencyState, aT as ResolvedFactsCompleteness, g as ResolvedFactsReason, aU as ResolvedFileFact, aV as ResolvedIntentReferenceFact, aW as ResolvedPublishFact, aX as ResolvedSafetyFact, aY as ResolvedSafetyKind, aZ as ResolvedSafetyReport, a_ as SemanticDependency, a$ as SemanticDependencyKind, b0 as analyzeArchitectureConvergence, b1 as analyzeChange, b2 as analyzePolicyDelta, b3 as analyzeProject, b4 as analyzeResolvedProject, b7 as catalogFixForRuleId, b8 as catalogWhyForRuleId, b9 as classifyArkPolicyDelta, ba as collectAnalysisConfigWarnings, bc as collectForbiddenCapabilityUses, bd as createAICodeGate, be as createAdapterResult, bf as createArchitectureProfile, bg as createArchitectureProfileFromArkConfig, bh as createElevenLayerArkConfig, bi as createResolvedCandidateFacts, bk as detectArchitectureCycles, bl as deterministicHash, bm as diagnosticDocsFragment, bn as diagnosticDocsPath, bo as elevenLayerProfile, bp as evaluateArchitectureGraph, bs as explainViolation, bu as extractSemanticDependencies, bv as getDiagnosticCatalogEntry, bw as isCataloguedOrArkRuleFamily, bx as isKnownDiagnosticCode, by as loadContract, bz as loadResolvedCandidateFacts, bA as policyDeltaAcknowledgementMatches, bB as preflightChange, bC as preflightResolvedChange, bD as resolvedFactsEvidenceRequirementsHash, bE as serializeDiagnosticCatalog, bF as stableSerialize, bG as toAdapterDiagnostic, bH as version } from '../diagnosticCatalog-DVABouBV.js';
1
+ export { n as AICodeGate, o as AICodeGateContext, p as AICodeGateOptions, q as AICodeGateResult, r as AICodeGateViolation, s as AIGateExtension, t as ANALYSIS_IR_SCHEMA_VERSION, u as ARK_ANALYSIS_RESULT_SCHEMA, v as ARK_ANALYSIS_RESULT_SCHEMA_VERSION, w as ARK_DESIGN_DELTA_SCHEMA_VERSION, x as ARK_ENFORCEMENT_STATE_SCHEMA_VERSION, y as AdapterCompletenessReason, z as AdapterDiagnostic, B as AdapterResult, C as AdapterSeverity, A as AdapterViolationInput, D as AnalysisCapabilityUse, F as AnalysisCompilerOptions, G as AnalysisCompleteness, H as AnalysisContract, I as AnalysisEvidence, J as AnalysisFile, K as AnalysisFileChange, L as AnalysisFileInput, M as AnalysisImportEdge, N as AnalysisIr, O as AnalysisMode, P as AnalysisResult, Q as AnalysisViolation, S as AnalyzeArchitectureConvergenceInput, T as AnalyzeChangeInput, U as AnalyzePolicyDeltaInput, V as AnalyzeProjectInput, W as AnalyzeResolvedProjectInput, X as ArchitectureActualChange, Y as ArchitectureChangeMap, Z as ArchitectureChangeMapContract, _ as ArchitectureChangeMapDependency, $ as ArchitectureChangeMapFile, a0 as ArchitectureChangeOperation, a1 as ArchitectureConvergenceClassification, a2 as ArchitectureConvergenceFinding, a3 as ArchitectureConvergenceResult, a4 as ArchitectureDependency, a5 as ArchitectureEngineEdge, a6 as ArchitectureEngineResult, a7 as ArchitectureEngineViolation, a8 as ArkDesignDeltaResult, a9 as ArkEnforcementHost, aa as ArkEnforcementState, ac as ChangePreflightResult, ae as CollectAnalysisConfigWarningsInput, af as DIAGNOSTIC_CATALOG, ag as DIAGNOSTIC_CATALOG_SCHEMA_VERSION, ah as DIAGNOSTIC_DOCS_RELATIVE_PATH, ai as DIAGNOSTIC_RULE_IDS, aj as DesignDeltaChange, ak as DesignDeltaEnforcementScope, al as DesignDeltaIdentity, am as DesignSmellEvidence, an as DesignSmellFinding, ao as DesignSmellId, ap as DiagnosticCatalogEntry, aq as DiagnosticCategory, ar as EnforcementBoundaryState, as as EnforcementEvidence, at as EnforcementEvidenceField, au as EnforcementVerification, av as EvaluateArchitectureGraphInput, aw as ForbiddenCapabilityUse, ay as POLICY_DELTA_SCHEMA_VERSION, az as PolicyDelta, aA as PolicyDeltaAcknowledgement, aB as PolicyDeltaAnalysis, aC as PolicyDeltaClassification, aD as PolicyDeltaFinding, aE as PreflightResolvedChangeInput, aF as PreparedChangeFile, aG as RESOLVED_CANDIDATE_FACTS_SCHEMA, aH as RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION, aI as ResolvedAmbientFact, aJ as ResolvedAnalysisFile, aK as ResolvedAnalysisIr, aL as ResolvedAnalysisResult, f as ResolvedArkRunCompositionRootHitFact, b as ResolvedArkRunDeclarationFact, c as ResolvedArkRunKernelCallFact, R as ResolvedArkRunKernelCallKind, d as ResolvedArkRunManagedNewFact, aM as ResolvedCandidateFacts, aN as ResolvedCandidateFactsInput, aO as ResolvedCapability, aP as ResolvedCapabilityFact, aQ as ResolvedChangePreflightResult, e as ResolvedDependencyFact, aR as ResolvedDependencyKind, aS as ResolvedDependencyState, aT as ResolvedFactsCompleteness, g as ResolvedFactsReason, aU as ResolvedFileFact, aV as ResolvedIntentReferenceFact, aW as ResolvedPublishFact, aX as ResolvedSafetyFact, aY as ResolvedSafetyKind, aZ as ResolvedSafetyReport, a_ as SemanticDependency, a$ as SemanticDependencyKind, b0 as analyzeArchitectureConvergence, b1 as analyzeChange, b2 as analyzePolicyDelta, b3 as analyzeProject, b4 as analyzeResolvedProject, b7 as catalogFixForRuleId, b8 as catalogWhyForRuleId, b9 as classifyArkPolicyDelta, ba as collectAnalysisConfigWarnings, bc as collectForbiddenCapabilityUses, bd as createAICodeGate, be as createAdapterResult, bf as createArchitectureProfile, bg as createArchitectureProfileFromArkConfig, bh as createElevenLayerArkConfig, bi as createResolvedCandidateFacts, bk as detectArchitectureCycles, bl as deterministicHash, bm as diagnosticDocsFragment, bn as diagnosticDocsPath, bo as elevenLayerProfile, bp as evaluateArchitectureGraph, bs as explainViolation, bu as extractSemanticDependencies, bv as getDiagnosticCatalogEntry, bw as isCataloguedOrArkRuleFamily, bx as isKnownDiagnosticCode, by as loadContract, bz as loadResolvedCandidateFacts, bA as policyDeltaAcknowledgementMatches, bB as preflightChange, bC as preflightResolvedChange, bD as resolvedFactsEvidenceRequirementsHash, bE as serializeDiagnosticCatalog, bF as stableSerialize, bG as toAdapterDiagnostic, bH as version } from '../diagnosticCatalog-BNxKdcN4.js';
2
2
  import { P as PolicyViolation, g as PolicySeverity, h as PolicyEnforcementMode, i as Policy, I as IntentName, j as IntentCreator, k as IntentRelationship, b as ArchitectureProfile, D as DomainEvent } from '../types-D5GT5ZT8.js';
3
3
  export { A as ArchitectureLayer, a as ArchitectureLayerConfig, c as ArchitectureRule, d as ArkCheckConfig, l as CorrelationId, C as CreateArchitectureProfileFromArkConfigOptions, e as CreateArchitectureProfileOptions, f as CreateElevenLayerArkConfigOptions, E as EventMetadata, m as IntentRelationshipKind } from '../types-D5GT5ZT8.js';
4
4
  import { I as IntentRegistry, D as DefineIntentOptions, a as DependencyGraph, G as GraphEdge, b as AuditStore, c as AuditRecord, d as AuditQuery, e as CreateAuditTrailOptions, f as AuditTrail, E as EventContractRegistry, g as EventContract, h as EventContractValidationResult, M as MetadataRegistry, R as ReadModelStore, i as CreateProjectionRegistryOptions, P as ProjectionRegistry, j as EventBufferStore, k as EventBufferRecord, l as EventBufferStatus, m as EventBusOptions, n as EventBus, o as CreateObservabilityReporterOptions, O as ObservabilityReporter, p as PolicyEngine, q as ArkManifest, W as WorkflowStore, S as SagaContext, r as WorkflowSnapshot, s as SagaDefinition, t as CreateWorkflowEngineOptions, u as SagaInstance, v as WorkflowEngine, w as DependencyInformationPackage, C as CreateArkKernelOptions, A as ArkKernel, x as ArkKernelConfig, y as CreateArkKernelFromConfigOptions, T as TraceRecordType, z as TraceRecord, B as OutboxStatus, F as OutboxRecord, H as ObservabilityDriftReport } from '../types-BSzRy2X1.js';