arkgate 4.8.1 → 4.8.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -0
- package/README.md +5 -3
- package/dist/{diagnosticCatalog-CSF4N3w8.d.ts → diagnosticCatalog-CPzH-MLN.d.ts} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/nestjs/index.cjs +1 -1
- package/dist/nestjs/index.js +1 -1
- package/dist/runtime/index.cjs +1 -1
- package/dist/runtime/index.d.ts +1 -1
- package/dist/runtime/index.js +1 -1
- package/docs/README.md +2 -2
- package/docs/agent-guide.md +10 -9
- package/docs/package-surface.md +3 -1
- package/package.json +1 -1
- package/server.json +2 -2
- package/templates/agent-skills/README.md +1 -1
- package/templates/agent-skills/ark-adopt/SKILL.md +41 -13
- package/templates/agent-skills/ark-architect/SKILL.md +4 -4
- package/templates/agent-skills/ark-autopilot/SKILL.md +22 -4
- package/templates/agent-skills/ark-contract/SKILL.md +7 -7
- package/templates/agent-skills/ark-coverage/SKILL.md +11 -5
- package/templates/agent-skills/ark-explain/SKILL.md +10 -4
- package/templates/agent-skills/ark-explore/SKILL.md +12 -4
- package/templates/agent-skills/ark-fix/SKILL.md +3 -3
- package/templates/agent-skills/ark-loop/SKILL.md +3 -3
- package/templates/agent-skills/ark-place/SKILL.md +12 -3
- package/templates/agent-skills/ark-runtime/SKILL.md +13 -11
- package/templates/agent-skills/ark-think/SKILL.md +13 -7
- package/templates/agent-skills/ark-upgrade/SKILL.md +12 -4
- package/templates/skills/ark-adopt.md +41 -13
- package/templates/skills/ark-architect.md +4 -4
- package/templates/skills/ark-autopilot.md +22 -4
- package/templates/skills/ark-contract.md +7 -7
- package/templates/skills/ark-coverage.md +11 -5
- package/templates/skills/ark-explain.md +10 -4
- package/templates/skills/ark-explore.md +12 -4
- package/templates/skills/ark-fix.md +3 -3
- package/templates/skills/ark-loop.md +3 -3
- package/templates/skills/ark-place.md +12 -3
- package/templates/skills/ark-runtime.md +13 -11
- package/templates/skills/ark-think.md +13 -7
- package/templates/skills/ark-upgrade.md +12 -4
package/dist/runtime/index.cjs
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
`)}function tl(e,t,n){let r=new Set(e.keys());if(go(n.include)&&(r=new Set([...r].filter(c=>{let l=e.get(c);return l!==void 0&&ua(l,n.include)}))),go(n.exclude))for(let c of[...r]){let l=e.get(c);l&&ua(l,n.exclude)&&r.delete(c)}let o=t.filter(c=>r.has(c.from)&&r.has(c.to));n.nodeIds.length>0&&(r=Xc(r,n.nodeIds,n.degreesOfSeparation,Qc(o)));let s=[...r].sort(hn).map(c=>e.get(c)).filter(c=>!!c),a=o.filter(c=>r.has(c.from)&&r.has(c.to)).sort((c,l)=>hn(c.from,l.from)||hn(c.kind,l.kind)||hn(c.to,l.to));return{nodes:s,edges:a}}function In(e={},t={}){let n=Yc(e),r=An(t),o=Jc(n.components,r.slice),s=tl(o.nodes,o.edges,r),a={schemaVersion:ar,kernelInstanceId:n.kernelInstanceId,slice:r.slice,query:r,nodes:s.nodes,edges:s.edges,mermaid:""};return a.mermaid=lr(a),a}var ar,ir,cr,ho,Ro,Ao,z,Bc,qc,zc,dr=St(()=>{"use strict";ft();ar="1.0",ir="process",cr=["process","technical"],ho=["component","interaction"],Ro=["raises","reactsTo","sends"],Ao=["uses"],z=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}},Bc=new Set(cr),qc=new Set(["slice","nodeIds","degreesOfSeparation","include","exclude"]),zc=new Set(["ids","labels","tags","groups","architectureKinds"]);i(hn,"compare");i(yo,"uniqueSorted");i(da,"emptyMatch");i(go,"matchHasCriteria");i(de,"nameList");i(ma,"globMatch");i(yn,"anyGlob");i(ya,"closedSlice");i(ga,"closedDegrees");i(pa,"closedMatch");i(An,"closeArkRunGraphQuery");i(kn,"arkRunGraphQueryFromSearchParams");i(Wc,"nodeFields");i(ua,"nodeMatches");i(Yc,"asPackage");i(Zc,"componentNode");i(or,"interactionNode");i(gn,"addNode");i(sr,"addEdge");i(Jc,"buildSlice");i(Qc,"adjacency");i(Xc,"neighborhood");i(Rn,"mermaidSafeId");i(fa,"mermaidLabel");i(el,"uniqueMermaidIds");i(lr,"formatArkRunGraphMermaid");i(tl,"filterGraph");i(In,"requestArkRunGraph")});function pr(e){if(e===void 0)return"local";if(typeof e=="string"&&nl.has(e))return e;throw new Ve("transport")}function ur(e){if(e===void 0)return!0;if(e===!0||e===!1)return e;throw new Ve("ephemeral")}function En(e){let t=pr(e.transport),n=ur(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 mt,je,nl,Ve,vn=St(()=>{"use strict";mt=["local","localBlocking","broker"],je=!0,nl=new Set(mt),Ve=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(pr,"closedArkRunTransportKind");i(ur,"closedArkRunEphemeral");i(En,"resolveArkRunSendPlan")});function Sn(e){return e==="production"}function ol(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 ha(e){if(e.startsWith("[::ffff:")&&e.endsWith("]"))return e.slice(8,-1);if(e.startsWith("::ffff:"))return e.slice(7)}function qe(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();if(t==="localhost"||t==="::1"||t==="[::1]")return!0;let n=ha(t);if(n)return qe(n);let r=ol(t);return r!==void 0&&r[0]===127}function Ra(e){if(e===void 0)return bn;if(typeof e!="string")throw new Q(String(e));let t=e.trim();if(rl.has(t.toLowerCase())||!qe(t))throw new Q(t);let n=t.toLowerCase();if(n==="localhost")return bn;if(n==="[::1]")return"::1";let r=ha(n);return r?Ra(r):n}function sl(e){if(e===void 0)return mr;if(typeof e!="number"||!Number.isInteger(e)||e<0||e>65535)throw new Q(`port:${String(e)}`);return e}function Rt(e={}){if(Sn(e.nodeEnv)||Sn(e.processNodeEnv))throw new Be;return{host:Ra(e.host),port:sl(e.port)}}function Se(e,t,n){return`http://${e.includes(":")?`[${e}]`:e}:${t}${n}`}function al(e){if(e!==void 0)try{return JSON.parse(JSON.stringify(e))}catch{return}}function il(e){return{kinds:[...mt],ephemeralDefault:e.ephemeralDefault===!1?!1:!0,brokerBound:e.brokerBound===!0,cloudSdksShipped:!1,fallback:gr}}function Cn(e={}){let t=Rt({host:e.host,port:e.port}),n=le({kernelInstanceId:e.kernelInstanceId,components:e.package&&typeof e.package=="object"&&!Array.isArray(e.package)&&Array.isArray(e.package.components)?e.package.components:[]});return{schemaVersion:fr,kernelInstanceId:typeof e.kernelInstanceId=="string"?e.kernelInstanceId:n.kernelInstanceId,bind:{host:t.host,port:t.port,loopback:!0},package:{...n,schemaVersion:"1.0"},transport:il(e),observability:al(e.observability)??{}}}function At(e){return`event: ${yr}
|
|
3
3
|
data: ${JSON.stringify(e)}
|
|
4
4
|
|
|
5
|
-
`}var fr,bn,mr,yt,gt,ht,yr,gr,Be,Q,rl,wn=St(()=>{"use strict";ft();vn();fr="1.0",bn="127.0.0.1",mr=0,yt="/snapshot",gt="/events",ht="/graph",yr="snapshot",gr="in-process-local",Be=class extends Error{static{i(this,"ArkRunInspectorProductionError")}constructor(){super("ArkRun inspector refuses to start when NODE_ENV=production."),this.name="ArkRunInspectorProductionError"}},Q=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"}},rl=new Set(["","*","0","0.0.0.0","::","::0","[::]","[::0]","::ffff:0.0.0.0","[::ffff:0.0.0.0]"]);i(Sn,"isArkRunInspectorProductionEnv");i(ol,"ipv4Octets");i(ha,"unwrapIpv4Mapped");i(qe,"isArkRunInspectorLoopbackHost");i(Ra,"closedHost");i(sl,"closedPort");i(Rt,"resolveArkRunInspectorBind");i(Se,"arkRunInspectorUrl");i(al,"jsonClone");i(il,"closedTransportFacts");i(Cn,"buildArkRunInspectorSnapshot");i(At,"formatArkRunInspectorSseEvent")});var Aa={};So(Aa,{listenArkRunInspector:()=>ul});function cl(){return{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}}function ll(){return{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-store",connection:"keep-alive","x-accel-buffering":"no"}}function dl(e){let t=e&&e.length>0?e:"/";return new URL(t,"http://127.0.0.1")}function hr(e,t,n){e.writeHead(t,cl()),e.end(JSON.stringify(n))}function pl(e,t){let n=e.address();if(n===null||typeof n=="string")throw new Q(t.host);if(!qe(n.address))throw new Q(n.address);return{host:t.host,port:n.port}}async function ul(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,c=i(()=>e.getInspectorSnapshot(a),"snapshot"),l=n.createServer((m,y)=>{let h=dl(m.url),d=h.pathname;if(m.method==="GET"&&(d==="/"||d===yt)){hr(y,200,c());return}if(m.method==="GET"&&d===ht){try{hr(y,200,e.requestGraph(kn({slice:h.searchParams.get("slice"),nodeIds:h.searchParams.get("nodeIds"),degreesOfSeparation:h.searchParams.get("degreesOfSeparation"),include:h.searchParams.get("include"),exclude:h.searchParams.get("exclude")})))}catch(p){if(p instanceof z){hr(y,400,{error:p.message,option:p.option});return}throw p}return}if(m.method==="GET"&&d===gt){y.writeHead(200,ll()),y.flushHeaders(),y.write(At(c())),r.add(y);let p=s>0?setInterval(()=>{y.write(At(c()))},s):void 0;p&&o.add(p);let u=i(()=>{r.delete(y),p&&(clearInterval(p),o.delete(p))},"drop");m.on("close",u),y.on("close",u);return}hr(y,404,{error:"not found"})});try{await new Promise((m,y)=>{let h=i(d=>y(d),"onError");l.once("error",h),l.listen({host:t.bind.host,port:t.bind.port},()=>{l.off("error",h);try{a=pl(l,t.bind),m()}catch(d){y(d instanceof Error?d:new Q(t.bind.host))}})})}catch(m){throw await new Promise(y=>{l.close(()=>y())}),m}return{host:a.host,port:a.port,url:Se(a.host,a.port,"/"),snapshotUrl:Se(a.host,a.port,yt),eventsUrl:Se(a.host,a.port,gt),graphUrl:Se(a.host,a.port,ht),close(){for(let m of o)clearInterval(m);o.clear();for(let m of r)m.end();return r.clear(),new Promise((m,y)=>{l.close(h=>{h?y(h):m()})})}}}var ka=St(()=>{"use strict";dr();wn();i(cl,"jsonHeaders");i(ll,"sseHeaders");i(dl,"requestUrl");i(hr,"writeJson");i(pl,"boundAddress");i(ul,"listenArkRunInspector")});var Rl={};So(Rl,{ANALYSIS_IR_SCHEMA_VERSION:()=>qn,ARK_ANALYSIS_RESULT_SCHEMA:()=>_o,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>_n,ARK_DESIGN_DELTA_SCHEMA_VERSION:()=>ia,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION:()=>aa,ARK_RUN_COMPONENT_LIFETIMES:()=>rr,ARK_RUN_EPHEMERAL_DEFAULT:()=>je,ARK_RUN_GRAPH_DEFAULT_SLICE:()=>ir,ARK_RUN_GRAPH_NODE_KINDS:()=>ho,ARK_RUN_GRAPH_PROCESS_EDGE_KINDS:()=>Ro,ARK_RUN_GRAPH_SCHEMA_VERSION:()=>ar,ARK_RUN_GRAPH_SLICES:()=>cr,ARK_RUN_GRAPH_TECHNICAL_EDGE_KINDS:()=>Ao,ARK_RUN_INFORMATION_PACKAGE_SCHEMA_VERSION:()=>mn,ARK_RUN_INSPECTOR_DEFAULT_HOST:()=>bn,ARK_RUN_INSPECTOR_DEFAULT_PORT:()=>mr,ARK_RUN_INSPECTOR_EVENTS_PATH:()=>gt,ARK_RUN_INSPECTOR_GRAPH_PATH:()=>ht,ARK_RUN_INSPECTOR_SCHEMA_VERSION:()=>fr,ARK_RUN_INSPECTOR_SNAPSHOT_PATH:()=>yt,ARK_RUN_INSPECTOR_SSE_EVENT:()=>yr,ARK_RUN_INSPECTOR_TRANSPORT_FALLBACK:()=>gr,ARK_RUN_TRANSPORT_KINDS:()=>mt,ArkRunInspectorBindError:()=>Q,ArkRunInspectorProductionError:()=>Be,DEFAULT_MAX_HISTORY_SIZE:()=>Rr,DIAGNOSTIC_CATALOG:()=>cn,DIAGNOSTIC_CATALOG_SCHEMA_VERSION:()=>Qs,DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>tr,DIAGNOSTIC_RULE_IDS:()=>Xs,EventContractRegistryImpl:()=>Xe,EventContractViolationError:()=>Te,InMemoryAuditStore:()=>et,InMemoryEventBuffer:()=>Ee,InMemoryOutboxStore:()=>_r,InMemoryReadModelStore:()=>dt,InMemoryWorkflowStore:()=>pt,IntentRegistry:()=>xe,InvalidArkRunGraphQueryError:()=>z,InvalidArkRunSendOptionError:()=>Ve,InvalidIntentNameError:()=>_e,LayerPolicyContextError:()=>Ne,MANIFEST_SCHEMA_VERSION:()=>pn,ObservedLayerFlowViolationError:()=>De,POLICY_DELTA_SCHEMA_VERSION:()=>Wn,PolicyEngine:()=>ke,PolicyViolationError:()=>pe,RESOLVED_CANDIDATE_FACTS_SCHEMA:()=>Bn,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION:()=>be,SourceMetadataOverrideError:()=>ue,UnknownEventSourceError:()=>Ie,UnregisteredIntentError:()=>Oe,analyzeArchitectureConvergence:()=>Ke,analyzeChange:()=>rn,analyzePolicyDelta:()=>eo,analyzeProject:()=>it,analyzeResolvedProject:()=>lt,architecturalPolicies:()=>Nn,arkRunGraphQueryFromSearchParams:()=>kn,arkRunInspectorUrl:()=>Se,buildArkRunInspectorSnapshot:()=>Cn,buildDependencyInformationPackage:()=>le,buildPublishPolicyContext:()=>_t,catalogFixForRuleId:()=>oa,catalogWhyForRuleId:()=>sa,checkAdapterGovernance:()=>Gn,checkContract:()=>Hr,classifyArkPolicyDelta:()=>Yn,closeArkRunGraphQuery:()=>An,closedArkRunEphemeral:()=>ur,closedArkRunTransportKind:()=>pr,collectAnalysisConfigWarnings:()=>an,collectForbiddenCapabilityUses:()=>Me,createAICodeGate:()=>Jr,createAdapter:()=>Mr,createAdapterResult:()=>Oo,createArchitectureProfile:()=>Vt,createArchitectureProfileFromArkConfig:()=>jt,createArkKernel:()=>kt,createArkKernelFromConfig:()=>Eo,createArkManifest:()=>un,createArkTestHarness:()=>Tr,createAuditTrail:()=>$t,createDependencyGraph:()=>Mt,createElevenLayerArkConfig:()=>Fr,createEventBus:()=>Or,createEventContractRegistry:()=>Lt,createIntentRegistry:()=>Ct,createLenientArkKernel:()=>kr,createLenientArkKernelFromConfig:()=>bo,createMetadataRegistry:()=>Bt,createObservabilityReporter:()=>Ft,createProjectionRegistry:()=>dn,createResolvedCandidateFacts:()=>jn,createSaga:()=>uo,createStrictArkKernel:()=>Ar,createStrictArkKernelFromConfig:()=>vo,createWorkflowEngine:()=>ut,defaultIntentRegistry:()=>br,defineArchitectureProfilePolicy:()=>Ot,defineIntent:()=>vr,defineLayerPolicy:()=>xt,definePolicy:()=>Pe,definePort:()=>$r,definePublishPolicy:()=>Sr,detectArchitectureCycles:()=>Qn,deterministicHash:()=>M,diagnosticDocsFragment:()=>io,diagnosticDocsPath:()=>na,elevenLayerProfile:()=>Fe,evaluateArchitectureGraph:()=>Ue,explainViolation:()=>to,extractSemanticDependencies:()=>$e,formatArkRunGraphMermaid:()=>lr,formatArkRunInspectorSseEvent:()=>At,getDiagnosticCatalogEntry:()=>ln,isArkRunInspectorLoopbackHost:()=>qe,isArkRunInspectorProductionEnv:()=>Sn,isCataloguedOrArkRuleFamily:()=>ta,isKnownDiagnosticCode:()=>ea,isLayerPolicy:()=>Pt,loadContract:()=>nn,loadResolvedCandidateFacts:()=>he,policyDeltaAcknowledgementMatches:()=>Zn,preflightChange:()=>oo,preflightResolvedChange:()=>so,requestArkRunGraph:()=>In,resolveArkRunInspectorBind:()=>Rt,resolveArkRunSendPlan:()=>En,resolvedFactsEvidenceRequirementsHash:()=>at,serializeDiagnosticCatalog:()=>ra,stableSerialize:()=>D,startArkRunInspector:()=>xn,syncRegistryToGraph:()=>Ht,toAdapterDiagnostic:()=>On,validateIntentName:()=>wt,version:()=>Pn});module.exports=Oa(Rl);var Pn="4.8.1";var _a=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,Na=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,Ta=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function Da(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),o=String(t?.toLayer??"");return _a.test(n)?"pure-shared":r==="PersistenceAdapters"&&(Na.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${o} ${n}`))?"kernel-emit":Ta.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&o==="PersistenceAdapters"?"use-case":"unknown"}i(Da,"classifyLayerImportKind");function La(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=Da(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(La,"layerImportNextAction");function Fa(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}i(Fa,"arkRunCallSiteName");function $a(e){let t=Fa(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($a,"arkRunNextAction");function ce(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return La(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"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";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 $a(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"Use release() to freeze \u03BE or proposeRelease() for a pattern change with blast radius, then preflight again. Never mechanical-safe.";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 only. Change \u03BE with proposeRelease + release. 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(ce,"deterministicNextAction");var _n="1.5",Ma="docs/diagnostics.md";function w(e){return typeof e=="string"&&e.length>0?e:void 0}i(w,"text");function wo(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}i(wo,"positiveInteger");function Po(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(Po,"adapterFindingTargetKey");function xo(e){let t=new Map;return e.map(n=>{let r=Po(n),o=(t.get(r)??0)+1;return t.set(r,o),o===1?r:`${r}#${o}`})}i(xo,"adapterFindingOccurrenceTargetKeys");function Ha(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(Ha,"adapterFindingRefFromTargetKey");function Ka(e){return`${Ma}#${e}`}i(Ka,"adapterDocsCodePath");function Ga(e,t,n){return ce({ruleId:e,target:w(t.target)??w(n.target)??void 0,fromLayer:w(t.fromLayer)??void 0,toLayer:w(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:w(t.edgeKind)??void 0,capability:w(t.capability)??w(n.capability)??void 0,arkruleId:w(t.arkruleId)??void 0,arkruleSource:w(t.arkruleSource)??void 0})}i(Ga,"nextActionForDiagnostic");function On(e,t="error",n){let r=w(e.ruleId)??w(e.code)??"ARK_UNKNOWN",o=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,s={...w(e.target)?{target:w(e.target)}:{},...w(e.fromLayer)?{fromLayer:w(e.fromLayer)}:{},...w(e.toLayer)?{toLayer:w(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}:{},...w(e.capability)?{capability:w(e.capability)}:{},...w(e.edgeKind)?{edgeKind:w(e.edgeKind)}:{},...w(e.arkruleId)?{arkruleId:w(e.arkruleId)}:{},...w(e.arkruleSource)?{arkruleSource:w(e.arkruleSource)}:{}},a=n??Po(e),c=Ha(a);return{ruleId:r,severity:o,message:w(e.message)??r,location:{file:w(e.file)??"<unknown>",line:wo(e.line,1),column:wo(e.column,1)},evidence:s,nextAction:w(e.nextAction)??Ga(r,s,e),findingRef:c,targetKey:a,docsCodePath:Ka(r)}}i(On,"toAdapterDiagnostic");function Oo(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(h=>({code:w(h.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:w(h.message)??`Analysis ${t}: required evidence is incomplete.`,...w(h.file)?{file:w(h.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],o={...w(e.policyHash)?{policyHash:w(e.policyHash)}:{},...w(e.resolverIdentity)?{resolverIdentity:w(e.resolverIdentity)}:{},...w(e.factsHash)?{factsHash:w(e.factsHash)}:{},...w(e.candidateTreeHash)?{candidateTreeHash:w(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let h of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!o[h])throw new Error(`${h} is required for resolved ${t} adapter evidence.`)}let s=e.violations??[],a=e.warnings??[],c=xo(s),l=xo(a),m=[...s.map((h,d)=>On(h,"error",c[d])),...a.map((h,d)=>On(h,"warning",l[d]))],y={schemaVersion:_n,completenessReasons:r,diagnostics:m};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...y,mode:n,valid:!1,completeness:t,...o};let h={policyHash:o.policyHash,resolverIdentity:o.resolverIdentity,factsHash:o.factsHash,candidateTreeHash:o.candidateTreeHash};return t==="complete"?{...y,mode:n,valid:e.valid,completeness:t,...h}:{...y,mode:n,valid:!1,completeness:t,...h}}return t==="complete"?{...y,mode:n,valid:e.valid,completeness:t,...o}:{...y,mode:n,valid:!1,completeness:t,...o}}i(Oo,"createAdapterResult");var _o={$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:_n},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}}}}}};var xe=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 No=new xe;function vr(e,t){return No.define(e,t)}i(vr,"defineIntent");function Ct(){return new xe}i(Ct,"createIntentRegistry");var br=No;var To=["Domain.","Application.","Adapter.","Workflow.","Job.","Presentation.","Reporting.","Metadata.","Security.","Audit.","Observability.","Kernel."];function wt(e){if(!e||typeof e!="string")return{valid:!1,reason:"Intent name must be a non-empty string"};if(!To.some(n=>e.startsWith(n)))return{valid:!1,reason:`Intent "${e}" must start with one of: ${To.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(wt,"validateIntentName");var pe=class extends Error{static{i(this,"PolicyViolationError")}violations;constructor(t){let n=t.map(r=>`- ${r.policyName}: ${r.message}`).join(`
|
|
5
|
+
`}var fr,bn,mr,yt,gt,ht,yr,gr,Be,Q,rl,wn=St(()=>{"use strict";ft();vn();fr="1.0",bn="127.0.0.1",mr=0,yt="/snapshot",gt="/events",ht="/graph",yr="snapshot",gr="in-process-local",Be=class extends Error{static{i(this,"ArkRunInspectorProductionError")}constructor(){super("ArkRun inspector refuses to start when NODE_ENV=production."),this.name="ArkRunInspectorProductionError"}},Q=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"}},rl=new Set(["","*","0","0.0.0.0","::","::0","[::]","[::0]","::ffff:0.0.0.0","[::ffff:0.0.0.0]"]);i(Sn,"isArkRunInspectorProductionEnv");i(ol,"ipv4Octets");i(ha,"unwrapIpv4Mapped");i(qe,"isArkRunInspectorLoopbackHost");i(Ra,"closedHost");i(sl,"closedPort");i(Rt,"resolveArkRunInspectorBind");i(Se,"arkRunInspectorUrl");i(al,"jsonClone");i(il,"closedTransportFacts");i(Cn,"buildArkRunInspectorSnapshot");i(At,"formatArkRunInspectorSseEvent")});var Aa={};So(Aa,{listenArkRunInspector:()=>ul});function cl(){return{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}}function ll(){return{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-store",connection:"keep-alive","x-accel-buffering":"no"}}function dl(e){let t=e&&e.length>0?e:"/";return new URL(t,"http://127.0.0.1")}function hr(e,t,n){e.writeHead(t,cl()),e.end(JSON.stringify(n))}function pl(e,t){let n=e.address();if(n===null||typeof n=="string")throw new Q(t.host);if(!qe(n.address))throw new Q(n.address);return{host:t.host,port:n.port}}async function ul(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,c=i(()=>e.getInspectorSnapshot(a),"snapshot"),l=n.createServer((m,y)=>{let h=dl(m.url),d=h.pathname;if(m.method==="GET"&&(d==="/"||d===yt)){hr(y,200,c());return}if(m.method==="GET"&&d===ht){try{hr(y,200,e.requestGraph(kn({slice:h.searchParams.get("slice"),nodeIds:h.searchParams.get("nodeIds"),degreesOfSeparation:h.searchParams.get("degreesOfSeparation"),include:h.searchParams.get("include"),exclude:h.searchParams.get("exclude")})))}catch(p){if(p instanceof z){hr(y,400,{error:p.message,option:p.option});return}throw p}return}if(m.method==="GET"&&d===gt){y.writeHead(200,ll()),y.flushHeaders(),y.write(At(c())),r.add(y);let p=s>0?setInterval(()=>{y.write(At(c()))},s):void 0;p&&o.add(p);let u=i(()=>{r.delete(y),p&&(clearInterval(p),o.delete(p))},"drop");m.on("close",u),y.on("close",u);return}hr(y,404,{error:"not found"})});try{await new Promise((m,y)=>{let h=i(d=>y(d),"onError");l.once("error",h),l.listen({host:t.bind.host,port:t.bind.port},()=>{l.off("error",h);try{a=pl(l,t.bind),m()}catch(d){y(d instanceof Error?d:new Q(t.bind.host))}})})}catch(m){throw await new Promise(y=>{l.close(()=>y())}),m}return{host:a.host,port:a.port,url:Se(a.host,a.port,"/"),snapshotUrl:Se(a.host,a.port,yt),eventsUrl:Se(a.host,a.port,gt),graphUrl:Se(a.host,a.port,ht),close(){for(let m of o)clearInterval(m);o.clear();for(let m of r)m.end();return r.clear(),new Promise((m,y)=>{l.close(h=>{h?y(h):m()})})}}}var ka=St(()=>{"use strict";dr();wn();i(cl,"jsonHeaders");i(ll,"sseHeaders");i(dl,"requestUrl");i(hr,"writeJson");i(pl,"boundAddress");i(ul,"listenArkRunInspector")});var Rl={};So(Rl,{ANALYSIS_IR_SCHEMA_VERSION:()=>qn,ARK_ANALYSIS_RESULT_SCHEMA:()=>_o,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>_n,ARK_DESIGN_DELTA_SCHEMA_VERSION:()=>ia,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION:()=>aa,ARK_RUN_COMPONENT_LIFETIMES:()=>rr,ARK_RUN_EPHEMERAL_DEFAULT:()=>je,ARK_RUN_GRAPH_DEFAULT_SLICE:()=>ir,ARK_RUN_GRAPH_NODE_KINDS:()=>ho,ARK_RUN_GRAPH_PROCESS_EDGE_KINDS:()=>Ro,ARK_RUN_GRAPH_SCHEMA_VERSION:()=>ar,ARK_RUN_GRAPH_SLICES:()=>cr,ARK_RUN_GRAPH_TECHNICAL_EDGE_KINDS:()=>Ao,ARK_RUN_INFORMATION_PACKAGE_SCHEMA_VERSION:()=>mn,ARK_RUN_INSPECTOR_DEFAULT_HOST:()=>bn,ARK_RUN_INSPECTOR_DEFAULT_PORT:()=>mr,ARK_RUN_INSPECTOR_EVENTS_PATH:()=>gt,ARK_RUN_INSPECTOR_GRAPH_PATH:()=>ht,ARK_RUN_INSPECTOR_SCHEMA_VERSION:()=>fr,ARK_RUN_INSPECTOR_SNAPSHOT_PATH:()=>yt,ARK_RUN_INSPECTOR_SSE_EVENT:()=>yr,ARK_RUN_INSPECTOR_TRANSPORT_FALLBACK:()=>gr,ARK_RUN_TRANSPORT_KINDS:()=>mt,ArkRunInspectorBindError:()=>Q,ArkRunInspectorProductionError:()=>Be,DEFAULT_MAX_HISTORY_SIZE:()=>Rr,DIAGNOSTIC_CATALOG:()=>cn,DIAGNOSTIC_CATALOG_SCHEMA_VERSION:()=>Qs,DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>tr,DIAGNOSTIC_RULE_IDS:()=>Xs,EventContractRegistryImpl:()=>Xe,EventContractViolationError:()=>Te,InMemoryAuditStore:()=>et,InMemoryEventBuffer:()=>Ee,InMemoryOutboxStore:()=>_r,InMemoryReadModelStore:()=>dt,InMemoryWorkflowStore:()=>pt,IntentRegistry:()=>xe,InvalidArkRunGraphQueryError:()=>z,InvalidArkRunSendOptionError:()=>Ve,InvalidIntentNameError:()=>_e,LayerPolicyContextError:()=>Ne,MANIFEST_SCHEMA_VERSION:()=>pn,ObservedLayerFlowViolationError:()=>De,POLICY_DELTA_SCHEMA_VERSION:()=>Wn,PolicyEngine:()=>ke,PolicyViolationError:()=>pe,RESOLVED_CANDIDATE_FACTS_SCHEMA:()=>Bn,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION:()=>be,SourceMetadataOverrideError:()=>ue,UnknownEventSourceError:()=>Ie,UnregisteredIntentError:()=>Oe,analyzeArchitectureConvergence:()=>Ke,analyzeChange:()=>rn,analyzePolicyDelta:()=>eo,analyzeProject:()=>it,analyzeResolvedProject:()=>lt,architecturalPolicies:()=>Nn,arkRunGraphQueryFromSearchParams:()=>kn,arkRunInspectorUrl:()=>Se,buildArkRunInspectorSnapshot:()=>Cn,buildDependencyInformationPackage:()=>le,buildPublishPolicyContext:()=>_t,catalogFixForRuleId:()=>oa,catalogWhyForRuleId:()=>sa,checkAdapterGovernance:()=>Gn,checkContract:()=>Hr,classifyArkPolicyDelta:()=>Yn,closeArkRunGraphQuery:()=>An,closedArkRunEphemeral:()=>ur,closedArkRunTransportKind:()=>pr,collectAnalysisConfigWarnings:()=>an,collectForbiddenCapabilityUses:()=>Me,createAICodeGate:()=>Jr,createAdapter:()=>Mr,createAdapterResult:()=>Oo,createArchitectureProfile:()=>Vt,createArchitectureProfileFromArkConfig:()=>jt,createArkKernel:()=>kt,createArkKernelFromConfig:()=>Eo,createArkManifest:()=>un,createArkTestHarness:()=>Tr,createAuditTrail:()=>$t,createDependencyGraph:()=>Mt,createElevenLayerArkConfig:()=>Fr,createEventBus:()=>Or,createEventContractRegistry:()=>Lt,createIntentRegistry:()=>Ct,createLenientArkKernel:()=>kr,createLenientArkKernelFromConfig:()=>bo,createMetadataRegistry:()=>Bt,createObservabilityReporter:()=>Ft,createProjectionRegistry:()=>dn,createResolvedCandidateFacts:()=>jn,createSaga:()=>uo,createStrictArkKernel:()=>Ar,createStrictArkKernelFromConfig:()=>vo,createWorkflowEngine:()=>ut,defaultIntentRegistry:()=>br,defineArchitectureProfilePolicy:()=>Ot,defineIntent:()=>vr,defineLayerPolicy:()=>xt,definePolicy:()=>Pe,definePort:()=>$r,definePublishPolicy:()=>Sr,detectArchitectureCycles:()=>Qn,deterministicHash:()=>M,diagnosticDocsFragment:()=>io,diagnosticDocsPath:()=>na,elevenLayerProfile:()=>Fe,evaluateArchitectureGraph:()=>Ue,explainViolation:()=>to,extractSemanticDependencies:()=>$e,formatArkRunGraphMermaid:()=>lr,formatArkRunInspectorSseEvent:()=>At,getDiagnosticCatalogEntry:()=>ln,isArkRunInspectorLoopbackHost:()=>qe,isArkRunInspectorProductionEnv:()=>Sn,isCataloguedOrArkRuleFamily:()=>ta,isKnownDiagnosticCode:()=>ea,isLayerPolicy:()=>Pt,loadContract:()=>nn,loadResolvedCandidateFacts:()=>he,policyDeltaAcknowledgementMatches:()=>Zn,preflightChange:()=>oo,preflightResolvedChange:()=>so,requestArkRunGraph:()=>In,resolveArkRunInspectorBind:()=>Rt,resolveArkRunSendPlan:()=>En,resolvedFactsEvidenceRequirementsHash:()=>at,serializeDiagnosticCatalog:()=>ra,stableSerialize:()=>D,startArkRunInspector:()=>xn,syncRegistryToGraph:()=>Ht,toAdapterDiagnostic:()=>On,validateIntentName:()=>wt,version:()=>Pn});module.exports=Oa(Rl);var Pn="4.8.2";var _a=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,Na=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,Ta=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function Da(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),o=String(t?.toLayer??"");return _a.test(n)?"pure-shared":r==="PersistenceAdapters"&&(Na.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${o} ${n}`))?"kernel-emit":Ta.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&o==="PersistenceAdapters"?"use-case":"unknown"}i(Da,"classifyLayerImportKind");function La(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=Da(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(La,"layerImportNextAction");function Fa(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}i(Fa,"arkRunCallSiteName");function $a(e){let t=Fa(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($a,"arkRunNextAction");function ce(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return La(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"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";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 $a(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"Use release() to freeze \u03BE or proposeRelease() for a pattern change with blast radius, then preflight again. Never mechanical-safe.";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 only. Change \u03BE with proposeRelease + release. 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(ce,"deterministicNextAction");var _n="1.5",Ma="docs/diagnostics.md";function w(e){return typeof e=="string"&&e.length>0?e:void 0}i(w,"text");function wo(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}i(wo,"positiveInteger");function Po(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(Po,"adapterFindingTargetKey");function xo(e){let t=new Map;return e.map(n=>{let r=Po(n),o=(t.get(r)??0)+1;return t.set(r,o),o===1?r:`${r}#${o}`})}i(xo,"adapterFindingOccurrenceTargetKeys");function Ha(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(Ha,"adapterFindingRefFromTargetKey");function Ka(e){return`${Ma}#${e}`}i(Ka,"adapterDocsCodePath");function Ga(e,t,n){return ce({ruleId:e,target:w(t.target)??w(n.target)??void 0,fromLayer:w(t.fromLayer)??void 0,toLayer:w(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:w(t.edgeKind)??void 0,capability:w(t.capability)??w(n.capability)??void 0,arkruleId:w(t.arkruleId)??void 0,arkruleSource:w(t.arkruleSource)??void 0})}i(Ga,"nextActionForDiagnostic");function On(e,t="error",n){let r=w(e.ruleId)??w(e.code)??"ARK_UNKNOWN",o=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,s={...w(e.target)?{target:w(e.target)}:{},...w(e.fromLayer)?{fromLayer:w(e.fromLayer)}:{},...w(e.toLayer)?{toLayer:w(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}:{},...w(e.capability)?{capability:w(e.capability)}:{},...w(e.edgeKind)?{edgeKind:w(e.edgeKind)}:{},...w(e.arkruleId)?{arkruleId:w(e.arkruleId)}:{},...w(e.arkruleSource)?{arkruleSource:w(e.arkruleSource)}:{}},a=n??Po(e),c=Ha(a);return{ruleId:r,severity:o,message:w(e.message)??r,location:{file:w(e.file)??"<unknown>",line:wo(e.line,1),column:wo(e.column,1)},evidence:s,nextAction:w(e.nextAction)??Ga(r,s,e),findingRef:c,targetKey:a,docsCodePath:Ka(r)}}i(On,"toAdapterDiagnostic");function Oo(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(h=>({code:w(h.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:w(h.message)??`Analysis ${t}: required evidence is incomplete.`,...w(h.file)?{file:w(h.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],o={...w(e.policyHash)?{policyHash:w(e.policyHash)}:{},...w(e.resolverIdentity)?{resolverIdentity:w(e.resolverIdentity)}:{},...w(e.factsHash)?{factsHash:w(e.factsHash)}:{},...w(e.candidateTreeHash)?{candidateTreeHash:w(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let h of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!o[h])throw new Error(`${h} is required for resolved ${t} adapter evidence.`)}let s=e.violations??[],a=e.warnings??[],c=xo(s),l=xo(a),m=[...s.map((h,d)=>On(h,"error",c[d])),...a.map((h,d)=>On(h,"warning",l[d]))],y={schemaVersion:_n,completenessReasons:r,diagnostics:m};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...y,mode:n,valid:!1,completeness:t,...o};let h={policyHash:o.policyHash,resolverIdentity:o.resolverIdentity,factsHash:o.factsHash,candidateTreeHash:o.candidateTreeHash};return t==="complete"?{...y,mode:n,valid:e.valid,completeness:t,...h}:{...y,mode:n,valid:!1,completeness:t,...h}}return t==="complete"?{...y,mode:n,valid:e.valid,completeness:t,...o}:{...y,mode:n,valid:!1,completeness:t,...o}}i(Oo,"createAdapterResult");var _o={$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:_n},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}}}}}};var xe=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 No=new xe;function vr(e,t){return No.define(e,t)}i(vr,"defineIntent");function Ct(){return new xe}i(Ct,"createIntentRegistry");var br=No;var To=["Domain.","Application.","Adapter.","Workflow.","Job.","Presentation.","Reporting.","Metadata.","Security.","Audit.","Observability.","Kernel."];function wt(e){if(!e||typeof e!="string")return{valid:!1,reason:"Intent name must be a non-empty string"};if(!To.some(n=>e.startsWith(n)))return{valid:!1,reason:`Intent "${e}" must start with one of: ${To.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(wt,"validateIntentName");var pe=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 ke=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 c of a)n.push({policyName:s.name,severity:s.severity,message:c.message,details:c.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 pe(n.hardViolations);return n}clear(){this.policies.length=0}};function Pe(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(Pe,"definePolicy");function Ua(e){let t=e.indexOf(".");return t>=0?e.slice(0,t):e}i(Ua,"defaultLayerOf");function Do(e,t){return t.resolveLayer?.(e)??Ua(e)}i(Do,"resolveLayer");function Va(e,t,n){return e===n.from&&t===n.to}i(Va,"matchesRule");function xt(e){let t=e.name??"Layer isolation",n=e.severity??"hard";return Pe({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 c=Do(a.from,e),l=Do(a.to,e);for(let m of e.rules)!m.allowed&&Va(c,l,m)&&s.push({policyName:t,severity:n,message:m.message??`Layer violation: ${a.from} (${c}) must not relate to ${a.to} (${l})`})}return s.length>0?s:!0},"check")})}i(xt,"defineLayerPolicy");function Pt(e){return e.tags?.includes("layer")??!1}i(Pt,"isLayerPolicy");var Nn={layerIsolation(){return Nn.cleanArchitectureMatrix()},cleanArchitectureMatrix(){return xt({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 Ot(e,t={}){return xt({name:t.name??`${e.name} layer policy`,severity:t.severity??"hard",rules:e.rules,resolveLayer:e.resolveLayer})}i(Ot,"defineArchitectureProfilePolicy");function _t(e){return t=>({event:t,relationships:e.intentRegistry?.getAllRelationships(),edges:e.dependencyGraph?.getEdges()})}i(_t,"buildPublishPolicyContext");function Sr(e){return Pe(e)}i(Sr,"definePublishPolicy");var Oe=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}},_e=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}},Ne=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"}},Te=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}},Ie=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}},ue=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}},De=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 Nt(e,t){if(!(!t.strictRegistry&&!t.validateIntentNaming)){if(t.validateIntentNaming){let n=wt(e);if(!n.valid)throw new _e(e,n.reason)}if(t.strictRegistry&&t.intentRegistry&&!t.intentRegistry.has(e))throw new Oe(e)}}i(Nt,"assertIntentAllowed");function Lo(e,t){if(t.requireKnownSource){if(!e.metadata.source||e.metadata.source==="unknown")throw new Ie(e.intent);if(t.intentRegistry&&!t.intentRegistry.has(e.metadata.source))throw new Ie(e.intent,e.metadata.source)}}i(Lo,"assertSourceAllowed");function Tt(e,t){if(!t.eventContracts)return;let n=t.eventContracts.validate(e);if(!n.ok&&(t.strictEventContracts||n.contract))throw new Te(e.intent,n.issues)}i(Tt,"assertContractAllowed");function Ze(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}i(Ze,"isPlainRecord");function Je(e){return Array.isArray(e)?e.map(Je):Ze(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Je(n)])):e}i(Je,"clonePatchValue");function Cr(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]=Je(s);continue}if(Ze(r[o])&&Ze(s)){r[o]=Cr(r[o],s,a);continue}if(Array.isArray(r[o])&&Array.isArray(s)){r[o]=wr(r[o],s,a);continue}throw new Error(`Interceptor patch cannot overwrite existing ${a}.`)}return r}i(Cr,"mergeRecordPatch");function wr(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]=Je(o);return}if(Ze(r[s])&&Ze(o)){r[s]=Cr(r[s],o,a);return}if(Array.isArray(r[s])&&Array.isArray(o)){r[s]=wr(r[s],o,a);return}throw new Error(`Interceptor patch cannot overwrite existing ${a}.`)}),r}i(wr,"mergeArrayPatch");function Fo(e,t){if(Array.isArray(t)){if(e===void 0)return Je(t);if(!Array.isArray(e))throw new Error("Array interceptor patch requires an array payload.");return wr(e,t)}if(e===void 0)return Je(t);if(!Ze(e))throw new Error("Object interceptor patch requires an object payload.");return Cr(e,t)}i(Fo,"applyPayloadPatch");async function $o(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(l=>{s.push(l)},"intercept")})),s.length===0)continue;let a=new Date().toISOString(),c={...r,metadata:{...r.metadata,interceptions:[...r.metadata.interceptions??[],{interceptorId:o.interceptorId,timestamp:a}]}};for(let l of s)c={...c,payload:Fo(c.payload,l),metadata:{...c.metadata}};Tt(c,{eventContracts:t.eventContracts,strictEventContracts:t.strictEventContracts}),r=c,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 ja(o,r,a,t)}}return r}i($o,"applyInterceptors");async function ja(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(ja,"recordInterceptorError");var Mo=new Map;function Ho(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(Ho,"escapeLiteral");function Tn(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(Tn,"normalizeGlobSeparators");function Ba(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(Ba,"bracesBalanced");function Le(e){let t=Mo.get(e);if(t)return t;let n=Tn(e),r=Ba(n),o="",s=0;for(let c=0;c<n.length;c+=1){let l=n[c];l==="\\"&&c+1<n.length?(o+=Ho(n[c+1]),c+=1):l==="*"?n[c+1]==="*"?n[c+2]==="/"?(o+="(?:.*/)?",c+=2):(o+=".*",c+=1):o+="[^/]*":l==="?"?o+="[^/]":l==="{"&&r?(o+="(?:",s+=1):l==="}"&&r&&s>0?(o+=")",s-=1):l===","&&r&&s>0?o+="|":o+=Ho(l)}let a=new RegExp(`^${o}$`);return Mo.set(e,a),a}i(Le,"globToRegExp");function qa(e){return Tn(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}i(qa,"concreteGlobSegments");function xr(e,t){let n=Tn(String(e)),r=qa(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 c=0,l=-1;for(let m of r){let y=-1;for(let h=c;h<a.length;h+=1)if(a[h]===m){y=h;break}if(y<0)return s;l=y,c=y+1}return(l+1)*1e6+r.length*1e4+o}i(xr,"patternSpecificity");function ne(e,t){let n=String(e).split(/[/\\]/).join("/"),r,o=-1;for(let s of t??[])if(!(s.exclude??[]).some(a=>Le(a).test(n))){for(let a of s.patterns??[])if(Le(a).test(n)){let c=xr(a,n);c>o&&(o=c,r=s.name)}}return r}i(ne,"layerForRelativePath");function Ko(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(Ko,"sliceIdForPath");function za(e){let t=new Set;for(let n of e??[]){let o=Tn(String(n)).split("/").filter(Boolean);for(let s=0;s<o.length;s+=1){let a=o[s];if((a==="**"||a==="*")&&s>0){let c=o[s-1];c&&!c.includes("*")&&!c.includes("{")&&!c.includes("}")&&t.add(c)}}}return[...t]}i(za,"inferSliceFoldersFromPatterns");function Wa(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 za(r?.patterns)}i(Wa,"resolveSliceFolders");function Ya(e){return!e.fromPath||!e.toPath||e.folderCount<=0||!e.fromSlice||!e.toSlice?!0:e.fromSlice!==e.toSlice}i(Ya,"peerIsolationMustDeny");function re(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,c=Wa(o,t,r?.layers),l=s&&a?Ko(s,c):void 0,m=s&&a?Ko(a,c):void 0;if(Ya({fromPath:s,toPath:a,folderCount:c.length,fromSlice:l,toSlice:m}))return o;continue}if(t!==n)return o}}i(re,"findDeniedEdgeRule");async function Go(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=re(r.rules,o,s);if(!a)return;let c=t.mode,l=a.message??`Observed layer violation: "${n}" (${o}) must not produce "${e.intent}" (${s}).`,m={source:n,intent:e.intent,fromLayer:o,toLayer:s,severity:c,message:l,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:m}),await t.recordAudit("layer.observedViolation",e,m),c==="hard")throw new De(n,e.intent,o,s,l)}i(Go,"assertObservedLayerFlowAllowed");async function Uo(e,t){let n=t.getPolicyContext(e),r;try{r=t.policyEngine.enforce(n)}catch(o){throw o instanceof pe&&(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(Uo,"enforcePublishPolicy");function Za(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(Za,"appendHistory");function Dt(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(Dt,"appendTrace");async function Dn(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){Dt(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(Dn,"recordAudit");async function Vo(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."};Dt(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 Dn(e,"event.rawPublish",t,n)}i(Vo,"recordRawPublishDiagnostic");async function jo(e,t,n,r){let o={event:t,publishedAt:new Date().toISOString(),subscribersNotified:n};return Za(e,o),await e.eventBuffer?.enqueue(t,r),Dt(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 Dn(e,"event.published",t,{subscribersNotified:n}),o}i(jo,"recordSuccessfulPublish");function Pr(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(Pr,"enrichMetadata");var Bo=0;function Ja(){return Bo+=1,`interceptor-${Date.now()}-${Bo}`}i(Ja,"nextInterceptorRegistrationId");var Qe=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 ke(t.policies)),(this.policyEngine?.getPolicies()??t.policies??[]).some(Pt)&&!t.intentRegistry&&!t.dependencyGraph&&!t.getPolicyContext)throw new Ne;t.getPolicyContext?this.getPolicyContext=t.getPolicyContext:t.intentRegistry||t.dependencyGraph?this.getPolicyContext=_t({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,c=o.runOnPublish!==!1,l,m=typeof t!="function";if(m){let d=t,p=r??n??{};l={...d,metadata:Pr(d.metadata,p,this.recording.instanceId)}}else{let d=t,p=n,u=r??{},f=d(p);l={...f,metadata:Pr(f.metadata,u,this.recording.instanceId)}}m&&this.strictRegistry&&await Vo(this.recording,l),Nt(l.intent,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),Lo(l,{requireKnownSource:this.requireKnownSource,intentRegistry:this.intentRegistry}),Tt(l,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),l=await $o(l,{interceptorsForIntent:i(d=>this.interceptorsByIntent.get(d)??[],"interceptorsForIntent"),eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts,appendTrace:i(d=>this.appendTrace(d),"appendTrace"),recordAudit:i((d,p,u)=>this.recordAudit(d,p,u),"recordAudit")}),Tt(l,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),await Go(l,{mode:this.enforceObservedLayerFlowMode,architectureProfile:this.architectureProfile,appendTrace:i(d=>this.appendTrace(d),"appendTrace"),recordAudit:i((d,p,u)=>this.recordAudit(d,p,u),"recordAudit")}),this.dependencyGraph?.registerEventFlow(l.metadata.source,l.intent);let y=[...this.subscriptionsByIntent.get(l.intent)??[]];this.policyEngine&&await Uo(l,{policyEngine:this.policyEngine,getPolicyContext:this.getPolicyContext,appendTrace:i(d=>this.appendTrace(d),"appendTrace"),recordAudit:i((d,p,u)=>this.recordAudit(d,p,u),"recordAudit"),onSoftViolation:this.onSoftViolation,safeHook:i((d,p,u)=>this.safeHook(d,p,u),"safeHook")}),await jo(this.recording,l,s?y.length:0,o.tx);let h=(async()=>{s&&await Promise.all(y.map(d=>this.invokeHandler(d,l))),c&&this.onPublish&&await this.safeHook(()=>this.onPublish(l),"onPublish",l)})();return a?await h:h.then(void 0,()=>{}),l}createPublisher(t){let n=typeof t=="string"?t:t.name;return Nt(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 ue(n,s.source);await this.publish(r,o,{...s,source:n},a)},"publish")}}subscribe(t,n){let r=typeof t=="string"?t:t.name;Nt(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 c=this.subscriptionsByIntent.get(r);if(!c)return;let l=c.indexOf(o);l>=0&&c.splice(l,1),c.length===0&&this.subscriptionsByIntent.delete(r)}}registerInterceptor(t,n,r){let o=typeof t=="string"?t:t.name;Nt(o,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let s={registrationId:Ja(),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){Dt(this.recording,t)}async recordAudit(t,n,r){await Dn(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 Or(e){return new Qe(e)}i(Or,"createEventBus");function Qa(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(Qa,"formatStandardSchemaPath");function Xa(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(Xa,"actualType");function ei(e,t){return e?`${e}.${t}`:t}i(ei,"formatPath");function qo(e,t,n,r,o){let s=Xa(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}zo(e,t.fields,r,o,n)}t.type==="array"&&t.items&&Array.isArray(e)&&e.forEach((a,c)=>{qo(a,t.items,`${n}[${c}]`,r,o)})}i(qo,"validateSchemaField");function zo(e,t,n,r,o){for(let[s,a]of Object.entries(t)){let c=ei(o,s),l=e[s];if(l===void 0){a.required&&r.push({intent:n.intent,version:n.version,field:c,message:"Required field is missing."});continue}qo(l,a,c,n,r)}}i(zo,"validateObjectSchema");var Xe=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(zo(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 c of a.issues)o.push({intent:t.intent,version:r.version,field:Qa(c.path),message:c.message})}return{ok:o.length===0,contract:r,issues:o}}clear(){this.contracts.clear()}key(t,n){return`${t}@${n}`}};function Lt(){return new Xe}i(Lt,"createEventContractRegistry");var Wo=0;function ti(){return Wo+=1,`outbox-${Date.now()}-${Wo}`}i(ti,"nextOutboxId");function Yo(e){return{...e,event:{...e.event,metadata:{...e.event.metadata}}}}i(Yo,"cloneRecord");var Ee=class{static{i(this,"InMemoryEventBuffer")}records=new Map;async enqueue(t){let n=new Date().toISOString(),r={id:ti(),event:t,status:"pending",attempts:0,createdAt:n,updatedAt:n};return this.records.set(r.id,r),Yo(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(Yo)}async clear(){this.records.clear()}},_r=Ee;function Nr(e){return`${e.from}->${e.to}`}i(Nr,"flowKey");function Zo(e){let t=new Set,n=[];for(let r of e){let o=Nr(r);t.has(o)||(t.add(o),n.push(r))}return n}i(Zo,"uniqueFlows");function Jo(e,t){let n=new Set(t.map(Nr));return e.filter(r=>!n.has(Nr(r)))}i(Jo,"difference");function Ft(e){let t=e.registry,n=e.eventBus,r=e.graph;return{report(){let o=t?t.getAllRelationships().filter(f=>f.kind==="produces").map(f=>({from:f.from,to:f.to})):[],s=o.length>0||!r?[]:r.getEdges().filter(f=>f.kind==="produces").map(f=>({from:f.from,to:f.to})),a=n?.getHistory().map(f=>({from:f.event.metadata.source,to:f.event.intent}))??[],c=a.length>0||!r?[]:r.getEdges().filter(f=>f.kind==="observed").map(f=>({from:f.from,to:f.to})),l=Zo([...o,...s]),m=Zo([...a,...c]),y=m.filter(f=>!f.from||f.from==="unknown"),h=t?Array.from(new Set(m.map(f=>f.from).filter(f=>f&&f!=="unknown"&&!t.has(f)))):[],d=t?Array.from(new Set(m.map(f=>f.to).filter(f=>!t.has(f)))):[],p=new Set(m.flatMap(f=>[f.from,f.to])),u=t?t.list().map(f=>f.name).filter(f=>!p.has(f)):[];return{generatedAt:new Date().toISOString(),declaredProductions:l,observedProductions:m,declaredButUnobserved:Jo(l,m),observedButUndeclared:Jo(m.filter(f=>f.from!=="unknown"),l),unknownSources:y,unregisteredObservedSources:h,unregisteredObservedIntents:d,registeredButNeverObserved:u}}}}i(Ft,"createObservabilityReporter");function Tr(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(Tr,"createArkTestHarness");var Qo=0;function ni(){return Qo+=1,`audit-${Date.now()}-${Qo}`}i(ni,"createAuditId");function ri(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(ri,"matchesQuery");var et=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=>ri(r,t));return t.limit===void 0?[...n]:n.slice(-t.limit)}clear(){this.records.length=0}},Ln=class{constructor(t){this.store=t}store;static{i(this,"AuditTrailImpl")}async record(t){let n={id:ni(),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 $t(e={}){return new Ln(e.store??new et(e.maxRecords))}i($t,"createAuditTrail");var Fn=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)}
|
package/dist/runtime/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { k as AICodeGate, l as AICodeGateContext, m as AICodeGateOptions, n as AICodeGateResult, o as AICodeGateViolation, p as AIGateExtension, q as ANALYSIS_IR_SCHEMA_VERSION, r as ARK_ANALYSIS_RESULT_SCHEMA, s as ARK_ANALYSIS_RESULT_SCHEMA_VERSION, t as ARK_DESIGN_DELTA_SCHEMA_VERSION, u as ARK_ENFORCEMENT_STATE_SCHEMA_VERSION, v as AdapterCompletenessReason, w as AdapterDiagnostic, x as AdapterResult, y as AdapterSeverity, z as AdapterViolationInput, B as AnalysisCapabilityUse, C as AnalysisCompilerOptions, D as AnalysisCompleteness, F as AnalysisContract, G as AnalysisEvidence, H as AnalysisFile, I as AnalysisFileChange, J as AnalysisFileInput, K as AnalysisImportEdge, L as AnalysisIr, M as AnalysisMode, N as AnalysisResult, O as AnalysisViolation, P as AnalyzeArchitectureConvergenceInput, Q as AnalyzeChangeInput, S as AnalyzePolicyDeltaInput, T as AnalyzeProjectInput, U as AnalyzeResolvedProjectInput, V as ArchitectureActualChange, W as ArchitectureChangeMap, X as ArchitectureChangeMapContract, Y as ArchitectureChangeMapDependency, Z as ArchitectureChangeMapFile, _ as ArchitectureChangeOperation, $ as ArchitectureConvergenceClassification, a0 as ArchitectureConvergenceFinding, a1 as ArchitectureConvergenceResult, a2 as ArchitectureDependency, a3 as ArchitectureEngineEdge, a4 as ArchitectureEngineResult, a5 as ArchitectureEngineViolation, a6 as ArkDesignDeltaResult, a7 as ArkEnforcementHost, a8 as ArkEnforcementState, aa as ChangePreflightResult, ac as CollectAnalysisConfigWarningsInput, ad as DIAGNOSTIC_CATALOG, ae as DIAGNOSTIC_CATALOG_SCHEMA_VERSION, af as DIAGNOSTIC_DOCS_RELATIVE_PATH, ag as DIAGNOSTIC_RULE_IDS, ah as DesignDeltaChange, ai as DesignDeltaEnforcementScope, aj as DesignDeltaIdentity, ak as DesignSmellEvidence, al as DesignSmellFinding, am as DesignSmellId, an as DiagnosticCatalogEntry, ao as DiagnosticCategory, ap as EnforcementBoundaryState, aq as EnforcementEvidence, ar as EnforcementEvidenceField, as as EnforcementVerification, at as EvaluateArchitectureGraphInput, au as ForbiddenCapabilityUse, aw as POLICY_DELTA_SCHEMA_VERSION, ax as PolicyDelta, ay as PolicyDeltaAcknowledgement, az as PolicyDeltaAnalysis, aA as PolicyDeltaClassification, aB as PolicyDeltaFinding, aC as PreflightResolvedChangeInput, aD as PreparedChangeFile, aE as RESOLVED_CANDIDATE_FACTS_SCHEMA, aF as RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION, aG as ResolvedAmbientFact, aH as ResolvedAnalysisFile, aI as ResolvedAnalysisIr, aJ as ResolvedAnalysisResult, e as ResolvedArkRunCompositionRootHitFact, a as ResolvedArkRunDeclarationFact, b as ResolvedArkRunKernelCallFact, R as ResolvedArkRunKernelCallKind, c as ResolvedArkRunManagedNewFact, aK as ResolvedCandidateFacts, aL as ResolvedCandidateFactsInput, aM as ResolvedCapability, aN as ResolvedCapabilityFact, aO as ResolvedChangePreflightResult, d as ResolvedDependencyFact, aP as ResolvedDependencyKind, aQ as ResolvedDependencyState, aR as ResolvedFactsCompleteness, f as ResolvedFactsReason, aS as ResolvedFileFact, aT as ResolvedIntentReferenceFact, aU as ResolvedPublishFact, aV as ResolvedSafetyFact, aW as ResolvedSafetyKind, aX as ResolvedSafetyReport, aY as SemanticDependency, aZ as SemanticDependencyKind, b2 as analyzeArchitectureConvergence, b3 as analyzeChange, b4 as analyzePolicyDelta, b5 as analyzeProject, b6 as analyzeResolvedProject, b9 as catalogFixForRuleId, ba as catalogWhyForRuleId, bb as classifyArkPolicyDelta, bc as collectAnalysisConfigWarnings, be as collectForbiddenCapabilityUses, bf as createAICodeGate, bg as createAdapterResult, bh as createArchitectureProfile, bi as createArchitectureProfileFromArkConfig, bj as createElevenLayerArkConfig, bk as createResolvedCandidateFacts, bm as detectArchitectureCycles, bn as deterministicHash, bo as diagnosticDocsFragment, bp as diagnosticDocsPath, bq as elevenLayerProfile, br as evaluateArchitectureGraph, bu as explainViolation, bw as extractSemanticDependencies, bx as getDiagnosticCatalogEntry, by as isCataloguedOrArkRuleFamily, bz as isKnownDiagnosticCode, bA as loadContract, bB as loadResolvedCandidateFacts, bC as policyDeltaAcknowledgementMatches, bD as preflightChange, bE as preflightResolvedChange, bF as resolvedFactsEvidenceRequirementsHash, bG as serializeDiagnosticCatalog, bH as stableSerialize, bI as toAdapterDiagnostic, bJ as version } from '../diagnosticCatalog-
|
|
1
|
+
export { k as AICodeGate, l as AICodeGateContext, m as AICodeGateOptions, n as AICodeGateResult, o as AICodeGateViolation, p as AIGateExtension, q as ANALYSIS_IR_SCHEMA_VERSION, r as ARK_ANALYSIS_RESULT_SCHEMA, s as ARK_ANALYSIS_RESULT_SCHEMA_VERSION, t as ARK_DESIGN_DELTA_SCHEMA_VERSION, u as ARK_ENFORCEMENT_STATE_SCHEMA_VERSION, v as AdapterCompletenessReason, w as AdapterDiagnostic, x as AdapterResult, y as AdapterSeverity, z as AdapterViolationInput, B as AnalysisCapabilityUse, C as AnalysisCompilerOptions, D as AnalysisCompleteness, F as AnalysisContract, G as AnalysisEvidence, H as AnalysisFile, I as AnalysisFileChange, J as AnalysisFileInput, K as AnalysisImportEdge, L as AnalysisIr, M as AnalysisMode, N as AnalysisResult, O as AnalysisViolation, P as AnalyzeArchitectureConvergenceInput, Q as AnalyzeChangeInput, S as AnalyzePolicyDeltaInput, T as AnalyzeProjectInput, U as AnalyzeResolvedProjectInput, V as ArchitectureActualChange, W as ArchitectureChangeMap, X as ArchitectureChangeMapContract, Y as ArchitectureChangeMapDependency, Z as ArchitectureChangeMapFile, _ as ArchitectureChangeOperation, $ as ArchitectureConvergenceClassification, a0 as ArchitectureConvergenceFinding, a1 as ArchitectureConvergenceResult, a2 as ArchitectureDependency, a3 as ArchitectureEngineEdge, a4 as ArchitectureEngineResult, a5 as ArchitectureEngineViolation, a6 as ArkDesignDeltaResult, a7 as ArkEnforcementHost, a8 as ArkEnforcementState, aa as ChangePreflightResult, ac as CollectAnalysisConfigWarningsInput, ad as DIAGNOSTIC_CATALOG, ae as DIAGNOSTIC_CATALOG_SCHEMA_VERSION, af as DIAGNOSTIC_DOCS_RELATIVE_PATH, ag as DIAGNOSTIC_RULE_IDS, ah as DesignDeltaChange, ai as DesignDeltaEnforcementScope, aj as DesignDeltaIdentity, ak as DesignSmellEvidence, al as DesignSmellFinding, am as DesignSmellId, an as DiagnosticCatalogEntry, ao as DiagnosticCategory, ap as EnforcementBoundaryState, aq as EnforcementEvidence, ar as EnforcementEvidenceField, as as EnforcementVerification, at as EvaluateArchitectureGraphInput, au as ForbiddenCapabilityUse, aw as POLICY_DELTA_SCHEMA_VERSION, ax as PolicyDelta, ay as PolicyDeltaAcknowledgement, az as PolicyDeltaAnalysis, aA as PolicyDeltaClassification, aB as PolicyDeltaFinding, aC as PreflightResolvedChangeInput, aD as PreparedChangeFile, aE as RESOLVED_CANDIDATE_FACTS_SCHEMA, aF as RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION, aG as ResolvedAmbientFact, aH as ResolvedAnalysisFile, aI as ResolvedAnalysisIr, aJ as ResolvedAnalysisResult, e as ResolvedArkRunCompositionRootHitFact, a as ResolvedArkRunDeclarationFact, b as ResolvedArkRunKernelCallFact, R as ResolvedArkRunKernelCallKind, c as ResolvedArkRunManagedNewFact, aK as ResolvedCandidateFacts, aL as ResolvedCandidateFactsInput, aM as ResolvedCapability, aN as ResolvedCapabilityFact, aO as ResolvedChangePreflightResult, d as ResolvedDependencyFact, aP as ResolvedDependencyKind, aQ as ResolvedDependencyState, aR as ResolvedFactsCompleteness, f as ResolvedFactsReason, aS as ResolvedFileFact, aT as ResolvedIntentReferenceFact, aU as ResolvedPublishFact, aV as ResolvedSafetyFact, aW as ResolvedSafetyKind, aX as ResolvedSafetyReport, aY as SemanticDependency, aZ as SemanticDependencyKind, b2 as analyzeArchitectureConvergence, b3 as analyzeChange, b4 as analyzePolicyDelta, b5 as analyzeProject, b6 as analyzeResolvedProject, b9 as catalogFixForRuleId, ba as catalogWhyForRuleId, bb as classifyArkPolicyDelta, bc as collectAnalysisConfigWarnings, be as collectForbiddenCapabilityUses, bf as createAICodeGate, bg as createAdapterResult, bh as createArchitectureProfile, bi as createArchitectureProfileFromArkConfig, bj as createElevenLayerArkConfig, bk as createResolvedCandidateFacts, bm as detectArchitectureCycles, bn as deterministicHash, bo as diagnosticDocsFragment, bp as diagnosticDocsPath, bq as elevenLayerProfile, br as evaluateArchitectureGraph, bu as explainViolation, bw as extractSemanticDependencies, bx as getDiagnosticCatalogEntry, by as isCataloguedOrArkRuleFamily, bz as isKnownDiagnosticCode, bA as loadContract, bB as loadResolvedCandidateFacts, bC as policyDeltaAcknowledgementMatches, bD as preflightChange, bE as preflightResolvedChange, bF as resolvedFactsEvidenceRequirementsHash, bG as serializeDiagnosticCatalog, bH as stableSerialize, bI as toAdapterDiagnostic, bJ as version } from '../diagnosticCatalog-CPzH-MLN.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-DCSlrRnV.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-DCSlrRnV.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, C as CreateArkKernelOptions, A as ArkKernel, w as ArkKernelConfig, x as CreateArkKernelFromConfigOptions, T as TraceRecordType, y as TraceRecord, z as OutboxStatus, B as OutboxRecord, F as ObservabilityDriftReport } from '../types-C9KApBzX.js';
|
package/dist/runtime/index.js
CHANGED
|
@@ -2,7 +2,7 @@ var eo=Object.defineProperty;var i=(e,t)=>eo(e,"name",{value:t,configurable:!0})
|
|
|
2
2
|
`)}function zc(e,t,n){let r=new Set(e.keys());if(Mr(n.include)&&(r=new Set([...r].filter(c=>{let l=e.get(c);return l!==void 0&&qs(l,n.include)}))),Mr(n.exclude))for(let c of[...r]){let l=e.get(c);l&&qs(l,n.exclude)&&r.delete(c)}let o=t.filter(c=>r.has(c.from)&&r.has(c.to));n.nodeIds.length>0&&(r=Bc(r,n.nodeIds,n.degreesOfSeparation,jc(o)));let s=[...r].sort(Ht).map(c=>e.get(c)).filter(c=>!!c),a=o.filter(c=>r.has(c.from)&&r.has(c.to)).sort((c,l)=>Ht(c.from,l.from)||Ht(c.kind,l.kind)||Ht(c.to,l.to));return{nodes:s,edges:a}}function Hn(e={},t={}){let n=Gc(e),r=$n(t),o=Vc(n.components,r.slice),s=zc(o.nodes,o.edges,r),a={schemaVersion:Hr,kernelInstanceId:n.kernelInstanceId,slice:r.slice,query:r,nodes:s.nodes,edges:s.edges,mermaid:""};return a.mermaid=Ur(a),a}var Hr,Kr,Gr,Ws,Ys,Zs,W,$c,Mc,Hc,Kn=lt(()=>{"use strict";tt();Hr="1.0",Kr="process",Gr=["process","technical"],Ws=["component","interaction"],Ys=["raises","reactsTo","sends"],Zs=["uses"],W=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}},$c=new Set(Gr),Mc=new Set(["slice","nodeIds","degreesOfSeparation","include","exclude"]),Hc=new Set(["ids","labels","tags","groups","architectureKinds"]);i(Ht,"compare");i($r,"uniqueSorted");i(js,"emptyMatch");i(Mr,"matchHasCriteria");i(le,"nameList");i(Js,"globMatch");i($t,"anyGlob");i(Qs,"closedSlice");i(Xs,"closedDegrees");i(Bs,"closedMatch");i($n,"closeArkRunGraphQuery");i(Mn,"arkRunGraphQueryFromSearchParams");i(Kc,"nodeFields");i(qs,"nodeMatches");i(Gc,"asPackage");i(Uc,"componentNode");i(Ln,"interactionNode");i(Mt,"addNode");i(Fn,"addEdge");i(Vc,"buildSlice");i(jc,"adjacency");i(Bc,"neighborhood");i(Kt,"mermaidSafeId");i(zs,"mermaidLabel");i(qc,"uniqueMermaidIds");i(Ur,"formatArkRunGraphMermaid");i(zc,"filterGraph");i(Hn,"requestArkRunGraph")});function Vr(e){if(e===void 0)return"local";if(typeof e=="string"&&Wc.has(e))return e;throw new nt("transport")}function jr(e){if(e===void 0)return!0;if(e===!0||e===!1)return e;throw new nt("ephemeral")}function Gn(e){let t=Vr(e.transport),n=jr(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 Gt,rt,Wc,nt,Ut=lt(()=>{"use strict";Gt=["local","localBlocking","broker"],rt=!0,Wc=new Set(Gt),nt=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(Vr,"closedArkRunTransportKind");i(jr,"closedArkRunEphemeral");i(Gn,"resolveArkRunSendPlan")});function Vn(e){return e==="production"}function Zc(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 ea(e){if(e.startsWith("[::ffff:")&&e.endsWith("]"))return e.slice(8,-1);if(e.startsWith("::ffff:"))return e.slice(7)}function st(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();if(t==="localhost"||t==="::1"||t==="[::1]")return!0;let n=ea(t);if(n)return st(n);let r=Zc(t);return r!==void 0&&r[0]===127}function ta(e){if(e===void 0)return Un;if(typeof e!="string")throw new te(String(e));let t=e.trim();if(Yc.has(t.toLowerCase())||!st(t))throw new te(t);let n=t.toLowerCase();if(n==="localhost")return Un;if(n==="[::1]")return"::1";let r=ea(n);return r?ta(r):n}function Jc(e){if(e===void 0)return qr;if(typeof e!="number"||!Number.isInteger(e)||e<0||e>65535)throw new te(`port:${String(e)}`);return e}function qt(e={}){if(Vn(e.nodeEnv)||Vn(e.processNodeEnv))throw new ot;return{host:ta(e.host),port:Jc(e.port)}}function Oe(e,t,n){return`http://${e.includes(":")?`[${e}]`:e}:${t}${n}`}function Qc(e){if(e!==void 0)try{return JSON.parse(JSON.stringify(e))}catch{return}}function Xc(e){return{kinds:[...Gt],ephemeralDefault:e.ephemeralDefault===!1?!1:!0,brokerBound:e.brokerBound===!0,cloudSdksShipped:!1,fallback:Wr}}function jn(e={}){let t=qt({host:e.host,port:e.port}),n=ye({kernelInstanceId:e.kernelInstanceId,components:e.package&&typeof e.package=="object"&&!Array.isArray(e.package)&&Array.isArray(e.package.components)?e.package.components:[]});return{schemaVersion:Br,kernelInstanceId:typeof e.kernelInstanceId=="string"?e.kernelInstanceId:n.kernelInstanceId,bind:{host:t.host,port:t.port,loopback:!0},package:{...n,schemaVersion:"1.0"},transport:Xc(e),observability:Qc(e.observability)??{}}}function zt(e){return`event: ${zr}
|
|
3
3
|
data: ${JSON.stringify(e)}
|
|
4
4
|
|
|
5
|
-
`}var Br,Un,qr,Vt,jt,Bt,zr,Wr,ot,te,Yc,Wt=lt(()=>{"use strict";tt();Ut();Br="1.0",Un="127.0.0.1",qr=0,Vt="/snapshot",jt="/events",Bt="/graph",zr="snapshot",Wr="in-process-local",ot=class extends Error{static{i(this,"ArkRunInspectorProductionError")}constructor(){super("ArkRun inspector refuses to start when NODE_ENV=production."),this.name="ArkRunInspectorProductionError"}},te=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"}},Yc=new Set(["","*","0","0.0.0.0","::","::0","[::]","[::0]","::ffff:0.0.0.0","[::ffff:0.0.0.0]"]);i(Vn,"isArkRunInspectorProductionEnv");i(Zc,"ipv4Octets");i(ea,"unwrapIpv4Mapped");i(st,"isArkRunInspectorLoopbackHost");i(ta,"closedHost");i(Jc,"closedPort");i(qt,"resolveArkRunInspectorBind");i(Oe,"arkRunInspectorUrl");i(Qc,"jsonClone");i(Xc,"closedTransportFacts");i(jn,"buildArkRunInspectorSnapshot");i(zt,"formatArkRunInspectorSseEvent")});var na={};da(na,{listenArkRunInspector:()=>ol});function el(){return{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}}function tl(){return{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-store",connection:"keep-alive","x-accel-buffering":"no"}}function nl(e){let t=e&&e.length>0?e:"/";return new URL(t,"http://127.0.0.1")}function Bn(e,t,n){e.writeHead(t,el()),e.end(JSON.stringify(n))}function rl(e,t){let n=e.address();if(n===null||typeof n=="string")throw new te(t.host);if(!st(n.address))throw new te(n.address);return{host:t.host,port:n.port}}async function ol(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,c=i(()=>e.getInspectorSnapshot(a),"snapshot"),l=n.createServer((m,y)=>{let h=nl(m.url),d=h.pathname;if(m.method==="GET"&&(d==="/"||d===Vt)){Bn(y,200,c());return}if(m.method==="GET"&&d===Bt){try{Bn(y,200,e.requestGraph(Mn({slice:h.searchParams.get("slice"),nodeIds:h.searchParams.get("nodeIds"),degreesOfSeparation:h.searchParams.get("degreesOfSeparation"),include:h.searchParams.get("include"),exclude:h.searchParams.get("exclude")})))}catch(p){if(p instanceof W){Bn(y,400,{error:p.message,option:p.option});return}throw p}return}if(m.method==="GET"&&d===jt){y.writeHead(200,tl()),y.flushHeaders(),y.write(zt(c())),r.add(y);let p=s>0?setInterval(()=>{y.write(zt(c()))},s):void 0;p&&o.add(p);let u=i(()=>{r.delete(y),p&&(clearInterval(p),o.delete(p))},"drop");m.on("close",u),y.on("close",u);return}Bn(y,404,{error:"not found"})});try{await new Promise((m,y)=>{let h=i(d=>y(d),"onError");l.once("error",h),l.listen({host:t.bind.host,port:t.bind.port},()=>{l.off("error",h);try{a=rl(l,t.bind),m()}catch(d){y(d instanceof Error?d:new te(t.bind.host))}})})}catch(m){throw await new Promise(y=>{l.close(()=>y())}),m}return{host:a.host,port:a.port,url:Oe(a.host,a.port,"/"),snapshotUrl:Oe(a.host,a.port,Vt),eventsUrl:Oe(a.host,a.port,jt),graphUrl:Oe(a.host,a.port,Bt),close(){for(let m of o)clearInterval(m);o.clear();for(let m of r)m.end();return r.clear(),new Promise((m,y)=>{l.close(h=>{h?y(h):m()})})}}}var ra=lt(()=>{"use strict";Kn();Wt();i(el,"jsonHeaders");i(tl,"sseHeaders");i(nl,"requestUrl");i(Bn,"writeJson");i(rl,"boundAddress");i(ol,"listenArkRunInspector")});var Yn="4.8.1";var pa=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,ua=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,fa=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function ma(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),o=String(t?.toLayer??"");return pa.test(n)?"pure-shared":r==="PersistenceAdapters"&&(ua.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${o} ${n}`))?"kernel-emit":fa.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&o==="PersistenceAdapters"?"use-case":"unknown"}i(ma,"classifyLayerImportKind");function ya(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=ma(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(ya,"layerImportNextAction");function ga(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}i(ga,"arkRunCallSiteName");function ha(e){let t=ga(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(ha,"arkRunNextAction");function ce(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return ya(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"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";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 ha(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"Use release() to freeze \u03BE or proposeRelease() for a pattern change with blast radius, then preflight again. Never mechanical-safe.";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 only. Change \u03BE with proposeRelease + release. 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(ce,"deterministicNextAction");var Jn="1.5",Ra="docs/diagnostics.md";function w(e){return typeof e=="string"&&e.length>0?e:void 0}i(w,"text");function to(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}i(to,"positiveInteger");function ro(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(ro,"adapterFindingTargetKey");function no(e){let t=new Map;return e.map(n=>{let r=ro(n),o=(t.get(r)??0)+1;return t.set(r,o),o===1?r:`${r}#${o}`})}i(no,"adapterFindingOccurrenceTargetKeys");function Aa(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(Aa,"adapterFindingRefFromTargetKey");function ka(e){return`${Ra}#${e}`}i(ka,"adapterDocsCodePath");function Ia(e,t,n){return ce({ruleId:e,target:w(t.target)??w(n.target)??void 0,fromLayer:w(t.fromLayer)??void 0,toLayer:w(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:w(t.edgeKind)??void 0,capability:w(t.capability)??w(n.capability)??void 0,arkruleId:w(t.arkruleId)??void 0,arkruleSource:w(t.arkruleSource)??void 0})}i(Ia,"nextActionForDiagnostic");function Zn(e,t="error",n){let r=w(e.ruleId)??w(e.code)??"ARK_UNKNOWN",o=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,s={...w(e.target)?{target:w(e.target)}:{},...w(e.fromLayer)?{fromLayer:w(e.fromLayer)}:{},...w(e.toLayer)?{toLayer:w(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}:{},...w(e.capability)?{capability:w(e.capability)}:{},...w(e.edgeKind)?{edgeKind:w(e.edgeKind)}:{},...w(e.arkruleId)?{arkruleId:w(e.arkruleId)}:{},...w(e.arkruleSource)?{arkruleSource:w(e.arkruleSource)}:{}},a=n??ro(e),c=Aa(a);return{ruleId:r,severity:o,message:w(e.message)??r,location:{file:w(e.file)??"<unknown>",line:to(e.line,1),column:to(e.column,1)},evidence:s,nextAction:w(e.nextAction)??Ia(r,s,e),findingRef:c,targetKey:a,docsCodePath:ka(r)}}i(Zn,"toAdapterDiagnostic");function Ea(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(h=>({code:w(h.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:w(h.message)??`Analysis ${t}: required evidence is incomplete.`,...w(h.file)?{file:w(h.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],o={...w(e.policyHash)?{policyHash:w(e.policyHash)}:{},...w(e.resolverIdentity)?{resolverIdentity:w(e.resolverIdentity)}:{},...w(e.factsHash)?{factsHash:w(e.factsHash)}:{},...w(e.candidateTreeHash)?{candidateTreeHash:w(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let h of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!o[h])throw new Error(`${h} is required for resolved ${t} adapter evidence.`)}let s=e.violations??[],a=e.warnings??[],c=no(s),l=no(a),m=[...s.map((h,d)=>Zn(h,"error",c[d])),...a.map((h,d)=>Zn(h,"warning",l[d]))],y={schemaVersion:Jn,completenessReasons:r,diagnostics:m};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...y,mode:n,valid:!1,completeness:t,...o};let h={policyHash:o.policyHash,resolverIdentity:o.resolverIdentity,factsHash:o.factsHash,candidateTreeHash:o.candidateTreeHash};return t==="complete"?{...y,mode:n,valid:e.valid,completeness:t,...h}:{...y,mode:n,valid:!1,completeness:t,...h}}return t==="complete"?{...y,mode:n,valid:e.valid,completeness:t,...o}:{...y,mode:n,valid:!1,completeness:t,...o}}i(Ea,"createAdapterResult");var va={$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:Jn},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}}}}}};var De=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 oo=new De;function so(e,t){return oo.define(e,t)}i(so,"defineIntent");function Zt(){return new De}i(Zt,"createIntentRegistry");var ao=oo;var io=["Domain.","Application.","Adapter.","Workflow.","Job.","Presentation.","Reporting.","Metadata.","Security.","Audit.","Observability.","Kernel."];function Jt(e){if(!e||typeof e!="string")return{valid:!1,reason:"Intent name must be a non-empty string"};if(!io.some(n=>e.startsWith(n)))return{valid:!1,reason:`Intent "${e}" must start with one of: ${io.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(Jt,"validateIntentName");var he=class extends Error{static{i(this,"PolicyViolationError")}violations;constructor(t){let n=t.map(r=>`- ${r.policyName}: ${r.message}`).join(`
|
|
5
|
+
`}var Br,Un,qr,Vt,jt,Bt,zr,Wr,ot,te,Yc,Wt=lt(()=>{"use strict";tt();Ut();Br="1.0",Un="127.0.0.1",qr=0,Vt="/snapshot",jt="/events",Bt="/graph",zr="snapshot",Wr="in-process-local",ot=class extends Error{static{i(this,"ArkRunInspectorProductionError")}constructor(){super("ArkRun inspector refuses to start when NODE_ENV=production."),this.name="ArkRunInspectorProductionError"}},te=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"}},Yc=new Set(["","*","0","0.0.0.0","::","::0","[::]","[::0]","::ffff:0.0.0.0","[::ffff:0.0.0.0]"]);i(Vn,"isArkRunInspectorProductionEnv");i(Zc,"ipv4Octets");i(ea,"unwrapIpv4Mapped");i(st,"isArkRunInspectorLoopbackHost");i(ta,"closedHost");i(Jc,"closedPort");i(qt,"resolveArkRunInspectorBind");i(Oe,"arkRunInspectorUrl");i(Qc,"jsonClone");i(Xc,"closedTransportFacts");i(jn,"buildArkRunInspectorSnapshot");i(zt,"formatArkRunInspectorSseEvent")});var na={};da(na,{listenArkRunInspector:()=>ol});function el(){return{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}}function tl(){return{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-store",connection:"keep-alive","x-accel-buffering":"no"}}function nl(e){let t=e&&e.length>0?e:"/";return new URL(t,"http://127.0.0.1")}function Bn(e,t,n){e.writeHead(t,el()),e.end(JSON.stringify(n))}function rl(e,t){let n=e.address();if(n===null||typeof n=="string")throw new te(t.host);if(!st(n.address))throw new te(n.address);return{host:t.host,port:n.port}}async function ol(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,c=i(()=>e.getInspectorSnapshot(a),"snapshot"),l=n.createServer((m,y)=>{let h=nl(m.url),d=h.pathname;if(m.method==="GET"&&(d==="/"||d===Vt)){Bn(y,200,c());return}if(m.method==="GET"&&d===Bt){try{Bn(y,200,e.requestGraph(Mn({slice:h.searchParams.get("slice"),nodeIds:h.searchParams.get("nodeIds"),degreesOfSeparation:h.searchParams.get("degreesOfSeparation"),include:h.searchParams.get("include"),exclude:h.searchParams.get("exclude")})))}catch(p){if(p instanceof W){Bn(y,400,{error:p.message,option:p.option});return}throw p}return}if(m.method==="GET"&&d===jt){y.writeHead(200,tl()),y.flushHeaders(),y.write(zt(c())),r.add(y);let p=s>0?setInterval(()=>{y.write(zt(c()))},s):void 0;p&&o.add(p);let u=i(()=>{r.delete(y),p&&(clearInterval(p),o.delete(p))},"drop");m.on("close",u),y.on("close",u);return}Bn(y,404,{error:"not found"})});try{await new Promise((m,y)=>{let h=i(d=>y(d),"onError");l.once("error",h),l.listen({host:t.bind.host,port:t.bind.port},()=>{l.off("error",h);try{a=rl(l,t.bind),m()}catch(d){y(d instanceof Error?d:new te(t.bind.host))}})})}catch(m){throw await new Promise(y=>{l.close(()=>y())}),m}return{host:a.host,port:a.port,url:Oe(a.host,a.port,"/"),snapshotUrl:Oe(a.host,a.port,Vt),eventsUrl:Oe(a.host,a.port,jt),graphUrl:Oe(a.host,a.port,Bt),close(){for(let m of o)clearInterval(m);o.clear();for(let m of r)m.end();return r.clear(),new Promise((m,y)=>{l.close(h=>{h?y(h):m()})})}}}var ra=lt(()=>{"use strict";Kn();Wt();i(el,"jsonHeaders");i(tl,"sseHeaders");i(nl,"requestUrl");i(Bn,"writeJson");i(rl,"boundAddress");i(ol,"listenArkRunInspector")});var Yn="4.8.2";var pa=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,ua=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,fa=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function ma(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),o=String(t?.toLayer??"");return pa.test(n)?"pure-shared":r==="PersistenceAdapters"&&(ua.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${o} ${n}`))?"kernel-emit":fa.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&o==="PersistenceAdapters"?"use-case":"unknown"}i(ma,"classifyLayerImportKind");function ya(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=ma(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(ya,"layerImportNextAction");function ga(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}i(ga,"arkRunCallSiteName");function ha(e){let t=ga(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(ha,"arkRunNextAction");function ce(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return ya(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"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";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 ha(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"Use release() to freeze \u03BE or proposeRelease() for a pattern change with blast radius, then preflight again. Never mechanical-safe.";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 only. Change \u03BE with proposeRelease + release. 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(ce,"deterministicNextAction");var Jn="1.5",Ra="docs/diagnostics.md";function w(e){return typeof e=="string"&&e.length>0?e:void 0}i(w,"text");function to(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}i(to,"positiveInteger");function ro(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(ro,"adapterFindingTargetKey");function no(e){let t=new Map;return e.map(n=>{let r=ro(n),o=(t.get(r)??0)+1;return t.set(r,o),o===1?r:`${r}#${o}`})}i(no,"adapterFindingOccurrenceTargetKeys");function Aa(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(Aa,"adapterFindingRefFromTargetKey");function ka(e){return`${Ra}#${e}`}i(ka,"adapterDocsCodePath");function Ia(e,t,n){return ce({ruleId:e,target:w(t.target)??w(n.target)??void 0,fromLayer:w(t.fromLayer)??void 0,toLayer:w(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:w(t.edgeKind)??void 0,capability:w(t.capability)??w(n.capability)??void 0,arkruleId:w(t.arkruleId)??void 0,arkruleSource:w(t.arkruleSource)??void 0})}i(Ia,"nextActionForDiagnostic");function Zn(e,t="error",n){let r=w(e.ruleId)??w(e.code)??"ARK_UNKNOWN",o=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,s={...w(e.target)?{target:w(e.target)}:{},...w(e.fromLayer)?{fromLayer:w(e.fromLayer)}:{},...w(e.toLayer)?{toLayer:w(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}:{},...w(e.capability)?{capability:w(e.capability)}:{},...w(e.edgeKind)?{edgeKind:w(e.edgeKind)}:{},...w(e.arkruleId)?{arkruleId:w(e.arkruleId)}:{},...w(e.arkruleSource)?{arkruleSource:w(e.arkruleSource)}:{}},a=n??ro(e),c=Aa(a);return{ruleId:r,severity:o,message:w(e.message)??r,location:{file:w(e.file)??"<unknown>",line:to(e.line,1),column:to(e.column,1)},evidence:s,nextAction:w(e.nextAction)??Ia(r,s,e),findingRef:c,targetKey:a,docsCodePath:ka(r)}}i(Zn,"toAdapterDiagnostic");function Ea(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(h=>({code:w(h.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:w(h.message)??`Analysis ${t}: required evidence is incomplete.`,...w(h.file)?{file:w(h.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],o={...w(e.policyHash)?{policyHash:w(e.policyHash)}:{},...w(e.resolverIdentity)?{resolverIdentity:w(e.resolverIdentity)}:{},...w(e.factsHash)?{factsHash:w(e.factsHash)}:{},...w(e.candidateTreeHash)?{candidateTreeHash:w(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let h of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!o[h])throw new Error(`${h} is required for resolved ${t} adapter evidence.`)}let s=e.violations??[],a=e.warnings??[],c=no(s),l=no(a),m=[...s.map((h,d)=>Zn(h,"error",c[d])),...a.map((h,d)=>Zn(h,"warning",l[d]))],y={schemaVersion:Jn,completenessReasons:r,diagnostics:m};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...y,mode:n,valid:!1,completeness:t,...o};let h={policyHash:o.policyHash,resolverIdentity:o.resolverIdentity,factsHash:o.factsHash,candidateTreeHash:o.candidateTreeHash};return t==="complete"?{...y,mode:n,valid:e.valid,completeness:t,...h}:{...y,mode:n,valid:!1,completeness:t,...h}}return t==="complete"?{...y,mode:n,valid:e.valid,completeness:t,...o}:{...y,mode:n,valid:!1,completeness:t,...o}}i(Ea,"createAdapterResult");var va={$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:Jn},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}}}}}};var De=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 oo=new De;function so(e,t){return oo.define(e,t)}i(so,"defineIntent");function Zt(){return new De}i(Zt,"createIntentRegistry");var ao=oo;var io=["Domain.","Application.","Adapter.","Workflow.","Job.","Presentation.","Reporting.","Metadata.","Security.","Audit.","Observability.","Kernel."];function Jt(e){if(!e||typeof e!="string")return{valid:!1,reason:"Intent name must be a non-empty string"};if(!io.some(n=>e.startsWith(n)))return{valid:!1,reason:`Intent "${e}" must start with one of: ${io.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(Jt,"validateIntentName");var he=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 ve=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 c of a)n.push({policyName:s.name,severity:s.severity,message:c.message,details:c.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 he(n.hardViolations);return n}clear(){this.policies.length=0}};function Le(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(Le,"definePolicy");function ba(e){let t=e.indexOf(".");return t>=0?e.slice(0,t):e}i(ba,"defaultLayerOf");function co(e,t){return t.resolveLayer?.(e)??ba(e)}i(co,"resolveLayer");function Sa(e,t,n){return e===n.from&&t===n.to}i(Sa,"matchesRule");function Qt(e){let t=e.name??"Layer isolation",n=e.severity??"hard";return Le({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 c=co(a.from,e),l=co(a.to,e);for(let m of e.rules)!m.allowed&&Sa(c,l,m)&&s.push({policyName:t,severity:n,message:m.message??`Layer violation: ${a.from} (${c}) must not relate to ${a.to} (${l})`})}return s.length>0?s:!0},"check")})}i(Qt,"defineLayerPolicy");function Xt(e){return e.tags?.includes("layer")??!1}i(Xt,"isLayerPolicy");var Qn={layerIsolation(){return Qn.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 en(e,t={}){return Qt({name:t.name??`${e.name} layer policy`,severity:t.severity??"hard",rules:e.rules,resolveLayer:e.resolveLayer})}i(en,"defineArchitectureProfilePolicy");function tn(e){return t=>({event:t,relationships:e.intentRegistry?.getAllRelationships(),edges:e.dependencyGraph?.getEdges()})}i(tn,"buildPublishPolicyContext");function lo(e){return Le(e)}i(lo,"definePublishPolicy");var Fe=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}},$e=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}},Me=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"}},He=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}},be=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}},Re=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}},Ke=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 dt(e,t){if(!(!t.strictRegistry&&!t.validateIntentNaming)){if(t.validateIntentNaming){let n=Jt(e);if(!n.valid)throw new $e(e,n.reason)}if(t.strictRegistry&&t.intentRegistry&&!t.intentRegistry.has(e))throw new Fe(e)}}i(dt,"assertIntentAllowed");function po(e,t){if(t.requireKnownSource){if(!e.metadata.source||e.metadata.source==="unknown")throw new be(e.intent);if(t.intentRegistry&&!t.intentRegistry.has(e.metadata.source))throw new be(e.intent,e.metadata.source)}}i(po,"assertSourceAllowed");function pt(e,t){if(!t.eventContracts)return;let n=t.eventContracts.validate(e);if(!n.ok&&(t.strictEventContracts||n.contract))throw new He(e.intent,n.issues)}i(pt,"assertContractAllowed");function Ge(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}i(Ge,"isPlainRecord");function Ue(e){return Array.isArray(e)?e.map(Ue):Ge(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Ue(n)])):e}i(Ue,"clonePatchValue");function Xn(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]=Ue(s);continue}if(Ge(r[o])&&Ge(s)){r[o]=Xn(r[o],s,a);continue}if(Array.isArray(r[o])&&Array.isArray(s)){r[o]=er(r[o],s,a);continue}throw new Error(`Interceptor patch cannot overwrite existing ${a}.`)}return r}i(Xn,"mergeRecordPatch");function er(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]=Ue(o);return}if(Ge(r[s])&&Ge(o)){r[s]=Xn(r[s],o,a);return}if(Array.isArray(r[s])&&Array.isArray(o)){r[s]=er(r[s],o,a);return}throw new Error(`Interceptor patch cannot overwrite existing ${a}.`)}),r}i(er,"mergeArrayPatch");function uo(e,t){if(Array.isArray(t)){if(e===void 0)return Ue(t);if(!Array.isArray(e))throw new Error("Array interceptor patch requires an array payload.");return er(e,t)}if(e===void 0)return Ue(t);if(!Ge(e))throw new Error("Object interceptor patch requires an object payload.");return Xn(e,t)}i(uo,"applyPayloadPatch");async function fo(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(l=>{s.push(l)},"intercept")})),s.length===0)continue;let a=new Date().toISOString(),c={...r,metadata:{...r.metadata,interceptions:[...r.metadata.interceptions??[],{interceptorId:o.interceptorId,timestamp:a}]}};for(let l of s)c={...c,payload:uo(c.payload,l),metadata:{...c.metadata}};pt(c,{eventContracts:t.eventContracts,strictEventContracts:t.strictEventContracts}),r=c,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 Ca(o,r,a,t)}}return r}i(fo,"applyInterceptors");async function Ca(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(Ca,"recordInterceptorError");var mo=new Map;function yo(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(yo,"escapeLiteral");function nn(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(nn,"normalizeGlobSeparators");function wa(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(wa,"bracesBalanced");function Se(e){let t=mo.get(e);if(t)return t;let n=nn(e),r=wa(n),o="",s=0;for(let c=0;c<n.length;c+=1){let l=n[c];l==="\\"&&c+1<n.length?(o+=yo(n[c+1]),c+=1):l==="*"?n[c+1]==="*"?n[c+2]==="/"?(o+="(?:.*/)?",c+=2):(o+=".*",c+=1):o+="[^/]*":l==="?"?o+="[^/]":l==="{"&&r?(o+="(?:",s+=1):l==="}"&&r&&s>0?(o+=")",s-=1):l===","&&r&&s>0?o+="|":o+=yo(l)}let a=new RegExp(`^${o}$`);return mo.set(e,a),a}i(Se,"globToRegExp");function xa(e){return nn(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}i(xa,"concreteGlobSegments");function tr(e,t){let n=nn(String(e)),r=xa(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 c=0,l=-1;for(let m of r){let y=-1;for(let h=c;h<a.length;h+=1)if(a[h]===m){y=h;break}if(y<0)return s;l=y,c=y+1}return(l+1)*1e6+r.length*1e4+o}i(tr,"patternSpecificity");function ne(e,t){let n=String(e).split(/[/\\]/).join("/"),r,o=-1;for(let s of t??[])if(!(s.exclude??[]).some(a=>Se(a).test(n))){for(let a of s.patterns??[])if(Se(a).test(n)){let c=tr(a,n);c>o&&(o=c,r=s.name)}}return r}i(ne,"layerForRelativePath");function go(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(go,"sliceIdForPath");function Pa(e){let t=new Set;for(let n of e??[]){let o=nn(String(n)).split("/").filter(Boolean);for(let s=0;s<o.length;s+=1){let a=o[s];if((a==="**"||a==="*")&&s>0){let c=o[s-1];c&&!c.includes("*")&&!c.includes("{")&&!c.includes("}")&&t.add(c)}}}return[...t]}i(Pa,"inferSliceFoldersFromPatterns");function Oa(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 Pa(r?.patterns)}i(Oa,"resolveSliceFolders");function _a(e){return!e.fromPath||!e.toPath||e.folderCount<=0||!e.fromSlice||!e.toSlice?!0:e.fromSlice!==e.toSlice}i(_a,"peerIsolationMustDeny");function re(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,c=Oa(o,t,r?.layers),l=s&&a?go(s,c):void 0,m=s&&a?go(a,c):void 0;if(_a({fromPath:s,toPath:a,folderCount:c.length,fromSlice:l,toSlice:m}))return o;continue}if(t!==n)return o}}i(re,"findDeniedEdgeRule");async function ho(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=re(r.rules,o,s);if(!a)return;let c=t.mode,l=a.message??`Observed layer violation: "${n}" (${o}) must not produce "${e.intent}" (${s}).`,m={source:n,intent:e.intent,fromLayer:o,toLayer:s,severity:c,message:l,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:m}),await t.recordAudit("layer.observedViolation",e,m),c==="hard")throw new Ke(n,e.intent,o,s,l)}i(ho,"assertObservedLayerFlowAllowed");async function Ro(e,t){let n=t.getPolicyContext(e),r;try{r=t.policyEngine.enforce(n)}catch(o){throw o instanceof he&&(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(Ro,"enforcePublishPolicy");function Na(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(Na,"appendHistory");function ut(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(ut,"appendTrace");async function rn(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){ut(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(rn,"recordAudit");async function Ao(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."};ut(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 rn(e,"event.rawPublish",t,n)}i(Ao,"recordRawPublishDiagnostic");async function ko(e,t,n,r){let o={event:t,publishedAt:new Date().toISOString(),subscribersNotified:n};return Na(e,o),await e.eventBuffer?.enqueue(t,r),ut(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 rn(e,"event.published",t,{subscribersNotified:n}),o}i(ko,"recordSuccessfulPublish");function nr(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(nr,"enrichMetadata");var Io=0;function Ta(){return Io+=1,`interceptor-${Date.now()}-${Io}`}i(Ta,"nextInterceptorRegistrationId");var Ve=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 ve(t.policies)),(this.policyEngine?.getPolicies()??t.policies??[]).some(Xt)&&!t.intentRegistry&&!t.dependencyGraph&&!t.getPolicyContext)throw new Me;t.getPolicyContext?this.getPolicyContext=t.getPolicyContext:t.intentRegistry||t.dependencyGraph?this.getPolicyContext=tn({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,c=o.runOnPublish!==!1,l,m=typeof t!="function";if(m){let d=t,p=r??n??{};l={...d,metadata:nr(d.metadata,p,this.recording.instanceId)}}else{let d=t,p=n,u=r??{},f=d(p);l={...f,metadata:nr(f.metadata,u,this.recording.instanceId)}}m&&this.strictRegistry&&await Ao(this.recording,l),dt(l.intent,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),po(l,{requireKnownSource:this.requireKnownSource,intentRegistry:this.intentRegistry}),pt(l,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),l=await fo(l,{interceptorsForIntent:i(d=>this.interceptorsByIntent.get(d)??[],"interceptorsForIntent"),eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts,appendTrace:i(d=>this.appendTrace(d),"appendTrace"),recordAudit:i((d,p,u)=>this.recordAudit(d,p,u),"recordAudit")}),pt(l,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),await ho(l,{mode:this.enforceObservedLayerFlowMode,architectureProfile:this.architectureProfile,appendTrace:i(d=>this.appendTrace(d),"appendTrace"),recordAudit:i((d,p,u)=>this.recordAudit(d,p,u),"recordAudit")}),this.dependencyGraph?.registerEventFlow(l.metadata.source,l.intent);let y=[...this.subscriptionsByIntent.get(l.intent)??[]];this.policyEngine&&await Ro(l,{policyEngine:this.policyEngine,getPolicyContext:this.getPolicyContext,appendTrace:i(d=>this.appendTrace(d),"appendTrace"),recordAudit:i((d,p,u)=>this.recordAudit(d,p,u),"recordAudit"),onSoftViolation:this.onSoftViolation,safeHook:i((d,p,u)=>this.safeHook(d,p,u),"safeHook")}),await ko(this.recording,l,s?y.length:0,o.tx);let h=(async()=>{s&&await Promise.all(y.map(d=>this.invokeHandler(d,l))),c&&this.onPublish&&await this.safeHook(()=>this.onPublish(l),"onPublish",l)})();return a?await h:h.then(void 0,()=>{}),l}createPublisher(t){let n=typeof t=="string"?t:t.name;return dt(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 Re(n,s.source);await this.publish(r,o,{...s,source:n},a)},"publish")}}subscribe(t,n){let r=typeof t=="string"?t:t.name;dt(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 c=this.subscriptionsByIntent.get(r);if(!c)return;let l=c.indexOf(o);l>=0&&c.splice(l,1),c.length===0&&this.subscriptionsByIntent.delete(r)}}registerInterceptor(t,n,r){let o=typeof t=="string"?t:t.name;dt(o,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let s={registrationId:Ta(),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){ut(this.recording,t)}async recordAudit(t,n,r){await rn(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 Ve(e)}i(Eo,"createEventBus");function Da(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(Da,"formatStandardSchemaPath");function La(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(La,"actualType");function Fa(e,t){return e?`${e}.${t}`:t}i(Fa,"formatPath");function vo(e,t,n,r,o){let s=La(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}bo(e,t.fields,r,o,n)}t.type==="array"&&t.items&&Array.isArray(e)&&e.forEach((a,c)=>{vo(a,t.items,`${n}[${c}]`,r,o)})}i(vo,"validateSchemaField");function bo(e,t,n,r,o){for(let[s,a]of Object.entries(t)){let c=Fa(o,s),l=e[s];if(l===void 0){a.required&&r.push({intent:n.intent,version:n.version,field:c,message:"Required field is missing."});continue}vo(l,a,c,n,r)}}i(bo,"validateObjectSchema");var ft=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(bo(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 c of a.issues)o.push({intent:t.intent,version:r.version,field:Da(c.path),message:c.message})}return{ok:o.length===0,contract:r,issues:o}}clear(){this.contracts.clear()}key(t,n){return`${t}@${n}`}};function on(){return new ft}i(on,"createEventContractRegistry");var So=0;function $a(){return So+=1,`outbox-${Date.now()}-${So}`}i($a,"nextOutboxId");function Co(e){return{...e,event:{...e.event,metadata:{...e.event.metadata}}}}i(Co,"cloneRecord");var Ce=class{static{i(this,"InMemoryEventBuffer")}records=new Map;async enqueue(t){let n=new Date().toISOString(),r={id:$a(),event:t,status:"pending",attempts:0,createdAt:n,updatedAt:n};return this.records.set(r.id,r),Co(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(Co)}async clear(){this.records.clear()}},wo=Ce;function rr(e){return`${e.from}->${e.to}`}i(rr,"flowKey");function xo(e){let t=new Set,n=[];for(let r of e){let o=rr(r);t.has(o)||(t.add(o),n.push(r))}return n}i(xo,"uniqueFlows");function Po(e,t){let n=new Set(t.map(rr));return e.filter(r=>!n.has(rr(r)))}i(Po,"difference");function sn(e){let t=e.registry,n=e.eventBus,r=e.graph;return{report(){let o=t?t.getAllRelationships().filter(f=>f.kind==="produces").map(f=>({from:f.from,to:f.to})):[],s=o.length>0||!r?[]:r.getEdges().filter(f=>f.kind==="produces").map(f=>({from:f.from,to:f.to})),a=n?.getHistory().map(f=>({from:f.event.metadata.source,to:f.event.intent}))??[],c=a.length>0||!r?[]:r.getEdges().filter(f=>f.kind==="observed").map(f=>({from:f.from,to:f.to})),l=xo([...o,...s]),m=xo([...a,...c]),y=m.filter(f=>!f.from||f.from==="unknown"),h=t?Array.from(new Set(m.map(f=>f.from).filter(f=>f&&f!=="unknown"&&!t.has(f)))):[],d=t?Array.from(new Set(m.map(f=>f.to).filter(f=>!t.has(f)))):[],p=new Set(m.flatMap(f=>[f.from,f.to])),u=t?t.list().map(f=>f.name).filter(f=>!p.has(f)):[];return{generatedAt:new Date().toISOString(),declaredProductions:l,observedProductions:m,declaredButUnobserved:Po(l,m),observedButUndeclared:Po(m.filter(f=>f.from!=="unknown"),l),unknownSources:y,unregisteredObservedSources:h,unregisteredObservedIntents:d,registeredButNeverObserved:u}}}}i(sn,"createObservabilityReporter");function Oo(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(Oo,"createArkTestHarness");var _o=0;function Ma(){return _o+=1,`audit-${Date.now()}-${_o}`}i(Ma,"createAuditId");function Ha(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(Ha,"matchesQuery");var mt=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=>Ha(r,t));return t.limit===void 0?[...n]:n.slice(-t.limit)}clear(){this.records.length=0}},an=class{constructor(t){this.store=t}store;static{i(this,"AuditTrailImpl")}async record(t){let n={id:Ma(),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 cn(e={}){return new an(e.store??new mt(e.maxRecords))}i(cn,"createAuditTrail");var ln=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)}
|
package/docs/README.md
CHANGED
|
@@ -62,8 +62,8 @@ These are **not** the day-to-day product path. They stay in the repo for evidenc
|
|
|
62
62
|
| Field adoption kit (scaffolding, not closed) | [field/](field/) |
|
|
63
63
|
| Runtime hardening (experimental) | [production-hardening.md](production-hardening.md) |
|
|
64
64
|
|
|
65
|
-
Current published: [releases/4.8.
|
|
66
|
-
Prior: [releases/4.
|
|
65
|
+
Current published: [releases/4.8.2.md](releases/4.8.2.md) (`arkgate@4.8.2` on npm `latest`; does not close `K01`).
|
|
66
|
+
Prior: [releases/4.8.1.md](releases/4.8.1.md) · [4.8.0](releases/4.8.0.md) · [4.7.6](releases/4.7.6.md) · [4.7.5](releases/4.7.5.md) · [4.7.4](releases/4.7.4.md) · [4.7.3](releases/4.7.3.md) · [4.7.2](releases/4.7.2.md) · [4.7.1](releases/4.7.1.md) · [4.7.0](releases/4.7.0.md) · [4.6.7](releases/4.6.7.md) · [4.6.6](releases/4.6.6.md) · [4.6.5](releases/4.6.5.md) · [4.6.4](releases/4.6.4.md) · [4.6.3](releases/4.6.3.md) · [4.6.2](releases/4.6.2.md) · [4.6.1](releases/4.6.1.md) · [4.6.0](releases/4.6.0.md).
|
|
67
67
|
Older notes: [releases/](releases/). Config: [configuration.md](configuration.md).
|
|
68
68
|
|
|
69
69
|
---
|
package/docs/agent-guide.md
CHANGED
|
@@ -692,8 +692,10 @@ It checks real on-disk contract, MCP, skill, and report artifacts; it does not m
|
|
|
692
692
|
|
|
693
693
|
## ArkRun kernel: contract discovery
|
|
694
694
|
|
|
695
|
-
The **ArkRun** kernel (
|
|
696
|
-
static gate adoption or presented as production-ready.
|
|
695
|
+
The **ArkRun** kernel (`arkgate/runtime`) is currently **experimental** and is not required for
|
|
696
|
+
static gate adoption or presented as production-ready. From **4.8.0** it lives in the same
|
|
697
|
+
`arkgate` tarball (ADR 0031). `@arkgate/runtime` is **deprecated leftover** — do not
|
|
698
|
+
`npm i @arkgate/runtime` for new work. If you are evaluating it, prefer
|
|
697
699
|
`createStrictArkKernel()`. Each call creates an isolated instance — there is no process-wide
|
|
698
700
|
singleton. It wires the registry, graph,
|
|
699
701
|
policies, event bus, audit trail, event contracts, outbox, observability,
|
|
@@ -702,7 +704,7 @@ projections, metadata, workflow engine, and 11-layer architecture profile:
|
|
|
702
704
|
```ts
|
|
703
705
|
import {
|
|
704
706
|
createStrictArkKernel,
|
|
705
|
-
} from '
|
|
707
|
+
} from 'arkgate/runtime';
|
|
706
708
|
|
|
707
709
|
const ark = createStrictArkKernel();
|
|
708
710
|
// ... define intents, event contracts, metadata, projections, and workflows through ark.*
|
|
@@ -712,11 +714,10 @@ const contract = ark.manifest().toJSON();
|
|
|
712
714
|
// contract.observability, projections
|
|
713
715
|
```
|
|
714
716
|
|
|
715
|
-
Use
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
Package surface policy: [package-surface.md](package-surface.md).
|
|
717
|
+
Use `arkgate/runtime` only when evaluating the experimental ArkRun kernel. One install:
|
|
718
|
+
`npm install arkgate`. The stable `arkgate` **root** export remains the gate (no kernel factory).
|
|
719
|
+
`@arkgate/runtime` is a deprecated leftover 0.x companion (`experimental` dist-tag) for existing
|
|
720
|
+
pins. Package surface policy: [package-surface.md](package-surface.md).
|
|
720
721
|
|
|
721
722
|
Agents should read `contract` and `ark.observability.report()` before generating or modifying code.
|
|
722
723
|
|
|
@@ -1216,7 +1217,7 @@ Decision rationale: [ADR 0017 — MCP verdicts require explicit project identity
|
|
|
1216
1217
|
## ArkRun kernel workflow (not the default path)
|
|
1217
1218
|
|
|
1218
1219
|
This section is for adopters who **opt into** the experimental **ArkRun** kernel
|
|
1219
|
-
(`@arkgate/runtime`). Construct it with `createStrictArkKernel` (per instance; no process-wide
|
|
1220
|
+
(`arkgate/runtime`; `@arkgate/runtime` is deprecated leftover). Construct it with `createStrictArkKernel` (per instance; no process-wide
|
|
1220
1221
|
singleton). It is **not** the Beautiful Path day-zero curriculum. Default remains: `ark start` →
|
|
1221
1222
|
doctor → compact router (and `/ark-autopilot` only after the skill pack).
|
|
1222
1223
|
|
package/docs/package-surface.md
CHANGED
|
@@ -218,7 +218,9 @@ production deployment would need to satisfy; it is not a readiness certification
|
|
|
218
218
|
## Release notes (maintainers)
|
|
219
219
|
|
|
220
220
|
Ship notes for a version live under [releases/](https://github.com/pedroknigge/arkgate/tree/main/docs/releases)
|
|
221
|
-
(current published: [4.8.
|
|
221
|
+
(current published: [4.8.2.md](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/4.8.2.md);
|
|
222
|
+
prior published: [4.8.1.md](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/4.8.1.md);
|
|
223
|
+
prior published: [4.8.0.md](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/4.8.0.md);
|
|
222
224
|
prior published: [4.7.6.md](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/4.7.6.md);
|
|
223
225
|
prior published: [4.7.5.md](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/4.7.5.md);
|
|
224
226
|
prior published: [4.7.3.md](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/4.7.3.md);
|
package/package.json
CHANGED
package/server.json
CHANGED
|
@@ -6,12 +6,12 @@
|
|
|
6
6
|
"url": "https://github.com/pedroknigge/arkgate",
|
|
7
7
|
"source": "github"
|
|
8
8
|
},
|
|
9
|
-
"version": "4.8.
|
|
9
|
+
"version": "4.8.2",
|
|
10
10
|
"packages": [
|
|
11
11
|
{
|
|
12
12
|
"registryType": "npm",
|
|
13
13
|
"identifier": "arkgate",
|
|
14
|
-
"version": "4.8.
|
|
14
|
+
"version": "4.8.2",
|
|
15
15
|
"runtimeHint": "npx",
|
|
16
16
|
"transport": {
|
|
17
17
|
"type": "stdio"
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
This directory is the **Agent Skills–compatible** packaging of the same **13**
|
|
8
8
|
`/ark-*` skills shipped as flat templates for Ark install. **No new skill names.**
|
|
9
9
|
|
|
10
|
-
Package version when last generated context: **arkgate@4.8.
|
|
10
|
+
Package version when last generated context: **arkgate@4.8.1**
|
|
11
11
|
Schema: agent-skills package contract `1.0`
|
|
12
12
|
|
|
13
13
|
## Skills (frozen catalog)
|