arkgate 4.8.21 → 4.8.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/CHANGELOG.md +71 -0
  2. package/README.md +2 -2
  3. package/bin/ark-check-runtime.mjs +4 -2
  4. package/bin/ark-layer-match.mjs +606 -11
  5. package/bin/lib/analysis-engine.mjs +11 -11
  6. package/bin/lib/config-contract.mjs +492 -1
  7. package/bin/lib/diagnostic-catalog.mjs +32 -0
  8. package/bin/lib/doctor-advisories.mjs +60 -1
  9. package/bin/lib/doctor-plan.mjs +2 -2
  10. package/bin/lib/enforcement-honesty.mjs +22 -0
  11. package/bin/lib/flat-parent-pilot.mjs +252 -0
  12. package/bin/lib/html-report-advisories.mjs +2 -0
  13. package/bin/lib/html-report-depth.mjs +3 -1
  14. package/bin/lib/invariant-coverage.mjs +27 -3
  15. package/bin/lib/physical-cohesion.mjs +16 -18
  16. package/bin/lib/pilot-loop.mjs +21 -8
  17. package/bin/lib/team-parliament-io.mjs +4 -2
  18. package/dist/{configTypes-CTELo87-.d.ts → configTypes-Bbf_MFGe.d.ts} +36 -2
  19. package/dist/{diagnosticCatalog-B7BXlet6.d.ts → diagnosticCatalog-35mrwAHe.d.ts} +20 -5
  20. package/dist/eslint/index.cjs +4 -4
  21. package/dist/eslint/index.d.ts +51 -5
  22. package/dist/eslint/index.js +4 -4
  23. package/dist/index.cjs +36 -36
  24. package/dist/index.d.ts +104 -5
  25. package/dist/index.js +36 -36
  26. package/dist/nestjs/index.cjs +9 -9
  27. package/dist/nestjs/index.d.ts +3 -3
  28. package/dist/nestjs/index.js +9 -9
  29. package/dist/runtime/index.cjs +19 -19
  30. package/dist/runtime/index.d.ts +6 -6
  31. package/dist/runtime/index.js +19 -19
  32. package/dist/{types-yDNEQ603.d.ts → types-Bdj32QwA.d.ts} +1 -1
  33. package/dist/{types-fQ9-KrBj.d.ts → types-Ik_OakcI.d.ts} +1 -1
  34. package/docs/README.md +3 -1
  35. package/docs/agent-guide.md +9 -1
  36. package/docs/configuration.md +92 -1
  37. package/docs/diagnostics.md +32 -0
  38. package/docs/product-voice.md +1 -1
  39. package/package.json +2 -1
  40. package/schemas/ark.config.schema.json +124 -2
  41. package/server.json +2 -2
  42. package/templates/agent-skills/README.md +1 -1
@@ -1,32 +1,32 @@
1
- var Ho=Object.defineProperty;var i=(e,t)=>Ho(e,"name",{value:t,configurable:!0});var St=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var La=(e,t)=>{for(var n in t)Ho(e,n,{get:t[n],enumerable:!0})};function mo(e,t){return e<t?-1:e>t?1:0}function zd(e){return[...new Set(e)].sort(mo)}function Yt(e){if(!Array.isArray(e))return[];let t=[];for(let n of e)typeof n=="string"&&n.length>0&&t.push(n);return zd(t)}function qd(e){if(e===null)return null;if(typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return e}function Yd(e){return typeof e=="string"&&Wd.has(e)?e:"singleton"}function ca(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t={};for(let n of Object.keys(e).sort(mo)){if(n.length===0)continue;let r=qd(e[n]);r!==void 0&&(t[n]=r)}return Object.keys(t).length>0?t:void 0}function Xd(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=e,n={};typeof t.label=="string"&&t.label.length>0&&(n.label=t.label),typeof t.architectureKind=="string"&&t.architectureKind.length>0&&(n.architectureKind=t.architectureKind);let r=Yt(t.tags);r.length>0&&(n.tags=r),typeof t.group=="string"&&t.group.length>0&&(n.group=t.group);let o=ca(t.metadata);return o&&(n.metadata=o),Object.keys(n).length>0?n:void 0}function yo(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=e,n=typeof t.id=="string"?t.id.trim():"";if(!n)return;let r={id:n,lifetime:Yd(t.lifetime),uses:Yt(t.uses),reactsTo:Yt(t.reactsTo),raises:Yt(t.raises),sends:Yt(t.sends)},o=Xd(t.extendedInfo);return o&&(r.extendedInfo=o),r}function Jd(e){return ca(e)}function ho(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=e,n=typeof t.xiHash=="string"?t.xiHash.trim():"";if(!n)return;let r=t.event;if(r===null||typeof r!="object"||Array.isArray(r))return;let o=r,s=typeof o.kind=="string"?o.kind.trim():"";if(!s)return;let a=t.residual;if(a===null||typeof a!="object"||Array.isArray(a))return;let l=a,c=typeof l.kind=="string"&&Zd.has(l.kind)?l.kind:void 0;if(!c)return;let u={kind:s},f=Jd(o.payload);f&&(u.payload=f);let y={kind:c};return typeof l.reasonCode=="string"&&l.reasonCode.length>0&&(y.reasonCode=l.reasonCode),typeof l.eventId=="string"&&l.eventId.length>0&&(y.eventId=l.eventId),typeof l.target=="string"&&l.target.length>0&&(y.target=l.target),{xiHash:n,event:u,residual:y}}function Qd(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let r=ho(n);r&&t.push(r)}return t}function Ie(e){let t=typeof e.kernelInstanceId=="string"?e.kernelInstanceId:"",n=Array.isArray(e.components)?e.components:[],r=new Set,o=[];for(let a of n){let l=yo(a);!l||r.has(l.id)||(r.add(l.id),o.push(l))}o.sort((a,l)=>mo(a.id,l.id));let s=Qd(e.decisionTape);return{schemaVersion:"1.0",kernelInstanceId:t,components:o,...s.length>0?{decisionTape:s}:{}}}function da(e,t){let n=ho(t),r=e.decisionTape??[],o=n?[...r,n]:[...r];return{schemaVersion:e.schemaVersion,kernelInstanceId:e.kernelInstanceId,components:e.components,...o.length>0?{decisionTape:o}:{}}}var rr,go,la,Wd,Zd,ht=St(()=>{"use strict";rr="1.0",go=["singleton","transient"],la=["absorb","escalate_up","hold"],Wd=new Set(go);i(mo,"compare");i(zd,"uniqueSorted");i(Yt,"nameList");i(qd,"jsonPrimitive");i(Yd,"closedLifetime");i(ca,"sanitizeMetadata");i(Xd,"sanitizeArkRunExtendedInfo");i(yo,"sanitizeArkRunComponent");Zd=new Set(la);i(Jd,"sanitizeTapePayload");i(ho,"sanitizeDecisionTapeRecord");i(Qd,"sanitizeDecisionTape");i(Ie,"buildDependencyInformationPackage");i(da,"appendDecisionTape")});function Jt(e,t){return e<t?-1:e>t?1:0}function ko(e){return[...new Set(e)].sort(Jt)}function ga(){return{tokens:[],ids:[],labels:[],tags:[],groups:[],architectureKinds:[]}}function Io(e){return e.tokens.length+e.ids.length+e.labels.length+e.tags.length+e.groups.length+e.architectureKinds.length>0}function fe(e,t){if(e==null||e==="")return[];if(typeof e=="string")return ko(e.split(",").map(r=>r.trim()).filter(r=>r.length>0));if(!Array.isArray(e))throw new ne(t);let n=[];for(let r of e){if(typeof r!="string")throw new ne(t);let o=r.trim();o.length>0&&n.push(o)}return ko(n)}function Ia(e,t){if(t==="*")return e.length>0;if(!t.includes("*"))return e===t;let n="^";for(let r of t)r==="*"?n+=".*":/[.*+?^${}()|[\]\\]/.test(r)?n+=`\\${r}`:n+=r;return n+="$",new RegExp(n).test(e)}function Xt(e,t){return e?t.some(n=>Ia(e,n)):!1}function ba(e){if(e==null||e==="")return vo;if(typeof e=="string"&&eu.has(e))return e;throw new ne("slice")}function va(e){if(e==null||e==="")return null;if(typeof e=="string"&&/^(0|[1-9]\d*)$/.test(e))return Number(e);if(typeof e=="number"&&Number.isInteger(e)&&e>=0)return e;throw new ne("degreesOfSeparation")}function ma(e,t){if(e==null||e==="")return ga();if(typeof e=="string"||Array.isArray(e))return{...ga(),tokens:fe(e,t)};if(typeof e!="object")throw new ne(t);let n=e;for(let r of Object.keys(n))if(!nu.has(r))throw new ne(t);return{tokens:[],ids:fe(n.ids,t),labels:fe(n.labels,t),tags:fe(n.tags,t),groups:fe(n.groups,t),architectureKinds:fe(n.architectureKinds,t)}}function ir(e={}){if(e==null||e==="")return ir({});if(typeof e!="object"||Array.isArray(e))throw new ne("slice","ArkRun graph query must be an object.");let t=e;for(let n of Object.keys(t))if(!tu.has(n))throw new ne("slice",`ArkRun graph query key "${n}" is not closed.`);return{slice:ba(t.slice),nodeIds:fe(t.nodeIds,"nodeIds"),degreesOfSeparation:va(t.degreesOfSeparation),include:ma(t.include,"include"),exclude:ma(t.exclude,"exclude")}}function ar(e){let t={};e.slice&&(t.slice=ba(e.slice));let n=fe(e.nodeIds??void 0,"nodeIds");n.length>0&&(t.nodeIds=n);let r=va(e.degreesOfSeparation??void 0);r!==null&&(t.degreesOfSeparation=r);let o=fe(e.include??void 0,"include");o.length>0&&(t.include=o);let s=fe(e.exclude??void 0,"exclude");return s.length>0&&(t.exclude=s),t}function ru(e){let t=[e.id];return e.label&&t.push(e.label),e.group&&t.push(e.group),e.architectureKind&&t.push(e.architectureKind),e.tags&&t.push(...e.tags),t}function ya(e,t){if(!Io(t))return!0;let n=ru(e);return t.tokens.some(r=>n.some(o=>Ia(o,r)))||Xt(e.id,t.ids)||Xt(e.label,t.labels)||e.tags?.some(r=>Xt(r,t.tags))||Xt(e.group,t.groups)?!0:Xt(e.architectureKind,t.architectureKinds)}function ou(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;return Ie({kernelInstanceId:t.kernelInstanceId,components:t.components})}return Ie({})}function su(e){let t={id:e.id,kind:"component",lifetime:e.lifetime},n=e.extendedInfo;return n?.label&&(t.label=n.label),n?.group&&(t.group=n.group),n?.architectureKind&&(t.architectureKind=n.architectureKind),n?.tags&&n.tags.length>0&&(t.tags=[...n.tags]),t}function or(e){return{id:e,kind:"interaction"}}function Zt(e,t){let n=e.get(t.id);(!n||n.kind==="interaction"&&t.kind==="component")&&e.set(t.id,t)}function sr(e,t,n,r,o){let s=`${n}\0${o}\0${r}`;t.has(s)||(t.add(s),e.push({from:n,to:r,kind:o}))}function iu(e,t){let n=new Map,r=[],o=new Set;for(let s of e){if(Zt(n,su(s)),t==="technical"){for(let a of s.uses)Zt(n,n.get(a)??or(a)),sr(r,o,s.id,a,"uses");continue}for(let a of s.raises)Zt(n,n.get(a)??or(a)),sr(r,o,s.id,a,"raises");for(let a of s.reactsTo)Zt(n,n.get(a)??or(a)),sr(r,o,a,s.id,"reactsTo");for(let a of s.sends)Zt(n,n.get(a)??or(a)),sr(r,o,s.id,a,"sends")}return{nodes:n,edges:r}}function au(e){let t=new Map,n=i((r,o)=>{let s=t.get(r);s?s.push(o):t.set(r,[o])},"push");for(let r of e)n(r.from,r.to),n(r.to,r.from);return t}function lu(e,t,n,r){let o=t.filter(l=>e.has(l));if(o.length===0)return new Set;let s=new Set,a=o.map(l=>({id:l,depth:0}));for(;a.length>0;){let l=a.shift();if(!(!l||s.has(l.id))&&(s.add(l.id),!(n!==null&&l.depth>=n)))for(let c of r.get(l.id)??[])!s.has(c)&&e.has(c)&&a.push({id:c,depth:l.depth+1})}return s}function Qt(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return/^[A-Za-z_]/.test(t)?t:`n_${t}`}function ha(e){return e.replace(/\\/g,"\\\\").replace(/"/g,"#quot;").replace(/]/g,"#93;")}function cu(e){let t=new Set,n=new Map;for(let r of e){let o=Qt(r),s=o,a=2;for(;t.has(s);)s=`${o}_${a}`,a+=1;t.add(s),n.set(r,s)}return n}function So(e){let t=e.slice==="technical"?"TD":"LR",n=e.nodes.map(l=>l.id),r=cu(n),o=ko(e.nodes.map(l=>l.group).filter(l=>!!l)),s=[`flowchart ${t}`],a=i((l,c)=>{let u=r.get(l.id)??Qt(l.id),f=ha(l.label??l.id);s.push(`${c}${u}["${f}"]`)},"emitNode");for(let l of o){let c=Qt(`group_${l}`);s.push(` subgraph ${c}["${ha(l)}"]`);for(let u of e.nodes)u.group===l&&a(u," ");s.push(" end")}for(let l of e.nodes)l.group||a(l," ");for(let l of e.edges){let c=r.get(l.from)??Qt(l.from),u=r.get(l.to)??Qt(l.to);s.push(` ${c} -->|${l.kind}| ${u}`)}return s.join(`
2
- `)}function du(e,t,n){let r=new Set(e.keys());if(Io(n.include)&&(r=new Set([...r].filter(l=>{let c=e.get(l);return c!==void 0&&ya(c,n.include)}))),Io(n.exclude))for(let l of[...r]){let c=e.get(l);c&&ya(c,n.exclude)&&r.delete(l)}let o=t.filter(l=>r.has(l.from)&&r.has(l.to));n.nodeIds.length>0&&(r=lu(r,n.nodeIds,n.degreesOfSeparation,au(o)));let s=[...r].sort(Jt).map(l=>e.get(l)).filter(l=>!!l),a=o.filter(l=>r.has(l.from)&&r.has(l.to)).sort((l,c)=>Jt(l.from,c.from)||Jt(l.kind,c.kind)||Jt(l.to,c.to));return{nodes:s,edges:a}}function lr(e={},t={}){let n=ou(e),r=ir(t),o=iu(n.components,r.slice),s=du(o.nodes,o.edges,r),a={schemaVersion:bo,kernelInstanceId:n.kernelInstanceId,slice:r.slice,query:r,nodes:s.nodes,edges:s.edges,mermaid:""};return a.mermaid=So(a),a}var bo,vo,Eo,Ra,Aa,ka,ne,eu,tu,nu,cr=St(()=>{"use strict";ht();bo="1.0",vo="process",Eo=["process","technical"],Ra=["component","interaction"],Aa=["raises","reactsTo","sends"],ka=["uses"],ne=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}},eu=new Set(Eo),tu=new Set(["slice","nodeIds","degreesOfSeparation","include","exclude"]),nu=new Set(["ids","labels","tags","groups","architectureKinds"]);i(Jt,"compare");i(ko,"uniqueSorted");i(ga,"emptyMatch");i(Io,"matchHasCriteria");i(fe,"nameList");i(Ia,"globMatch");i(Xt,"anyGlob");i(ba,"closedSlice");i(va,"closedDegrees");i(ma,"closedMatch");i(ir,"closeArkRunGraphQuery");i(ar,"arkRunGraphQueryFromSearchParams");i(ru,"nodeFields");i(ya,"nodeMatches");i(ou,"asPackage");i(su,"componentNode");i(or,"interactionNode");i(Zt,"addNode");i(sr,"addEdge");i(iu,"buildSlice");i(au,"adjacency");i(lu,"neighborhood");i(Qt,"mermaidSafeId");i(ha,"mermaidLabel");i(cu,"uniqueMermaidIds");i(So,"formatArkRunGraphMermaid");i(du,"filterGraph");i(lr,"requestArkRunGraph")});function wo(e){if(e===void 0)return"local";if(typeof e=="string"&&uu.has(e))return e;throw new Rt("transport")}function Co(e){if(e===void 0)return!0;if(e===!0||e===!1)return e;throw new Rt("ephemeral")}function dr(e){let t=wo(e.transport),n=Co(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 en,At,uu,Rt,tn=St(()=>{"use strict";en=["local","localBlocking","broker"],At=!0,uu=new Set(en),Rt=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(wo,"closedArkRunTransportKind");i(Co,"closedArkRunEphemeral");i(dr,"resolveArkRunSendPlan")});function pr(e){return e==="production"}function fu(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 It(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 It(n);let r=fu(t);return r!==void 0&&r[0]===127}function Sa(e){if(e===void 0)return ur;if(typeof e!="string")throw new ce(String(e));let t=e.trim();if(pu.has(t.toLowerCase())||!It(t))throw new ce(t);let n=t.toLowerCase();if(n==="localhost")return ur;if(n==="[::1]")return"::1";let r=Ea(n);return r?Sa(r):n}function gu(e){if(e===void 0)return Oo;if(typeof e!="number"||!Number.isInteger(e)||e<0||e>65535)throw new ce(`port:${String(e)}`);return e}function ln(e={}){if(pr(e.nodeEnv)||pr(e.processNodeEnv))throw new kt;return{host:Sa(e.host),port:gu(e.port)}}function be(e,t,n){return`http://${e.includes(":")?`[${e}]`:e}:${t}${n}`}function mu(e){if(e!==void 0)try{return JSON.parse(JSON.stringify(e))}catch{return}}function yu(e){return{kinds:[...en],ephemeralDefault:e.ephemeralDefault===!1?!1:!0,brokerBound:e.brokerBound===!0,cloudSdksShipped:!1,fallback:_o}}function Te(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function hu(e){let t=Te(e);if(!t||typeof t.id!="string")return;let n=t.status;if(n!=="pending"&&n!=="failed")return;let r=Te(t.event),o=r&&typeof r.intent=="string"?r.intent:typeof t.intent=="string"?t.intent:void 0,s={id:t.id,status:n,attempts:typeof t.attempts=="number"&&Number.isFinite(t.attempts)?t.attempts:0};return o&&(s.intent=o),typeof t.error=="string"&&t.error.length>0&&(s.error=t.error),typeof t.updatedAt=="string"&&(s.updatedAt=t.updatedAt),s}function fr(e){if(typeof e!="number"||!Number.isFinite(e))return ie;let t=Math.trunc(e);return t<0?0:t>ie?ie:t}function Be(e,t){let n=typeof e=="string"&&e.trim().length>0?e.trim():e&&typeof e=="object"&&"constructor"in e?String(e.constructor?.name??t):t,r=/^InMemory/i.test(n)?"memory":"durable";return{role:t,id:n,kind:r}}function cn(e={}){let t=Te(e),n=Te(t?.durability)??t,r=Array.isArray(n?.stores)?n.stores:Array.isArray(t?.stores)?t.stores:[],o=[];for(let s of r){let a=Te(s);if(!a)continue;let l=a.role;if(l!=="outbox"&&l!=="audit"&&l!=="workflow")continue;let c=typeof a.id=="string"?a.id:typeof a.name=="string"?a.name:void 0;if(!c)continue;let u=a.kind==="memory"||a.kind==="durable"?a.kind:Be(c,l).kind;o.push({role:l,id:c,kind:u})}return{durability:{stores:o}}}function We(e=[],t={}){let n=fr(t.sampleLimit),r=Array.isArray(e)?e:[],o=[],s=[];for(let a of r){let l=hu(a);l&&(l.status==="pending"?o.push(l):s.push(l))}return{available:!0,pendingCount:o.length,failedCount:s.length,pending:o.slice(0,n),failed:s.slice(0,n),sampleLimit:n}}function Ve(){return{available:!1,pendingCount:0,failedCount:0,pending:[],failed:[],sampleLimit:ie}}function Ru(e){let t=Te(e);if(!t||typeof t.id!="string")return;let n=typeof t.workflowName=="string"?t.workflowName:typeof t.name=="string"?t.name:void 0;if(!n)return;let r={id:t.id,name:n,status:typeof t.status=="string"?t.status:"unknown"};return typeof t.currentStep=="string"&&(r.currentStep=t.currentStep),typeof t.error=="string"&&t.error.length>0&&(r.error=t.error),r}function Au(e){return e==="idle"||e==="waiting"}function ze(e=[],t={}){let n=fr(t.sampleLimit),r=Array.isArray(e)?e:[],o=[],s=0,a=0,l=0,c=0;for(let u of r){let f=Ru(u);f&&(o.push(f),f.status==="running"?s+=1:f.status==="compensating"?a+=1:f.status==="failed"?l+=1:Au(f.status)&&(c+=1))}return{available:!0,total:o.length,runningCount:s,compensatingCount:a,failedCount:l,pendingCount:c,workflows:o.slice(0,n),sampleLimit:n}}function je(){return{available:!1,total:0,runningCount:0,compensatingCount:0,failedCount:0,pendingCount:0,workflows:[],sampleLimit:ie}}function ku(e){if(e===void 0)return;let t=Te(e);if(!t||t.available===!1)return Ve();let n=fr(t.sampleLimit);if(Array.isArray(t.pending)||Array.isArray(t.failed)||Array.isArray(t.records)){let r=[...Array.isArray(t.pending)?t.pending:[],...Array.isArray(t.failed)?t.failed:[],...Array.isArray(t.records)?t.records:[]],o=We(r,{sampleLimit:n}),s=typeof t.pendingCount=="number"&&Number.isFinite(t.pendingCount)?Math.max(0,Math.trunc(t.pendingCount)):o.pendingCount,a=typeof t.failedCount=="number"&&Number.isFinite(t.failedCount)?Math.max(0,Math.trunc(t.failedCount)):o.failedCount;return{...o,pendingCount:s,failedCount:a,sampleLimit:n}}return Ve()}function Iu(e){if(e===void 0)return;let t=Te(e);if(!t||t.available===!1)return je();let n=fr(t.sampleLimit);if(Array.isArray(t.workflows)){let r=ze(t.workflows,{sampleLimit:n}),o=typeof t.total=="number"&&Number.isFinite(t.total)?Math.max(0,Math.trunc(t.total)):r.total,s=typeof t.runningCount=="number"&&Number.isFinite(t.runningCount)?Math.max(0,Math.trunc(t.runningCount)):r.runningCount,a=typeof t.compensatingCount=="number"&&Number.isFinite(t.compensatingCount)?Math.max(0,Math.trunc(t.compensatingCount)):r.compensatingCount,l=typeof t.failedCount=="number"&&Number.isFinite(t.failedCount)?Math.max(0,Math.trunc(t.failedCount)):r.failedCount,c=typeof t.pendingCount=="number"&&Number.isFinite(t.pendingCount)?Math.max(0,Math.trunc(t.pendingCount)):r.pendingCount;return{...r,total:o,runningCount:s,compensatingCount:a,failedCount:l,pendingCount:c,sampleLimit:n}}return je()}function gr(e={}){let t=ln({host:e.host,port:e.port}),n=Ie({kernelInstanceId:e.kernelInstanceId,components:e.package&&typeof e.package=="object"&&!Array.isArray(e.package)&&Array.isArray(e.package.components)?e.package.components:[]}),r=ku(e.outbox),o=Iu(e.workflows),s={schemaVersion:xo,kernelInstanceId:typeof e.kernelInstanceId=="string"?e.kernelInstanceId:n.kernelInstanceId,bind:{host:t.host,port:t.port,loopback:!0},package:{...n,schemaVersion:"1.0"},transport:yu(e),observability:mu(e.observability)??{},hardening:cn(e.hardening)};return r&&(s.outbox=r),o&&(s.workflows=o),s}function dn(e){return`event: ${Po}
1
+ var ss=Object.defineProperty;var a=(e,t)=>ss(e,"name",{value:t,configurable:!0});var Nt=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var ul=(e,t)=>{for(var n in t)ss(e,n,{get:t[n],enumerable:!0})};function Do(e,t){return e<t?-1:e>t?1:0}function hp(e){return[...new Set(e)].sort(Do)}function ln(e){if(!Array.isArray(e))return[];let t=[];for(let n of e)typeof n=="string"&&n.length>0&&t.push(n);return hp(t)}function Rp(e){if(e===null)return null;if(typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return e}function Ap(e){return typeof e=="string"&&yp.has(e)?e:"singleton"}function Ha(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t={};for(let n of Object.keys(e).sort(Do)){if(n.length===0)continue;let r=Rp(e[n]);r!==void 0&&(t[n]=r)}return Object.keys(t).length>0?t:void 0}function kp(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=e,n={};typeof t.label=="string"&&t.label.length>0&&(n.label=t.label),typeof t.architectureKind=="string"&&t.architectureKind.length>0&&(n.architectureKind=t.architectureKind);let r=ln(t.tags);r.length>0&&(n.tags=r),typeof t.group=="string"&&t.group.length>0&&(n.group=t.group);let o=Ha(t.metadata);return o&&(n.metadata=o),Object.keys(n).length>0?n:void 0}function Fo(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=e,n=typeof t.id=="string"?t.id.trim():"";if(!n)return;let r={id:n,lifetime:Ap(t.lifetime),uses:ln(t.uses),reactsTo:ln(t.reactsTo),raises:ln(t.raises),sends:ln(t.sends)},o=kp(t.extendedInfo);return o&&(r.extendedInfo=o),r}function bp(e){return Ha(e)}function $o(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=e,n=typeof t.xiHash=="string"?t.xiHash.trim():"";if(!n)return;let r=t.event;if(r===null||typeof r!="object"||Array.isArray(r))return;let o=r,s=typeof o.kind=="string"?o.kind.trim():"";if(!s)return;let i=t.residual;if(i===null||typeof i!="object"||Array.isArray(i))return;let l=i,c=typeof l.kind=="string"&&Ip.has(l.kind)?l.kind:void 0;if(!c)return;let u={kind:s},f=bp(o.payload);f&&(u.payload=f);let y={kind:c};return typeof l.reasonCode=="string"&&l.reasonCode.length>0&&(y.reasonCode=l.reasonCode),typeof l.eventId=="string"&&l.eventId.length>0&&(y.eventId=l.eventId),typeof l.target=="string"&&l.target.length>0&&(y.target=l.target),{xiHash:n,event:u,residual:y}}function Sp(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let r=$o(n);r&&t.push(r)}return t}function ve(e){let t=typeof e.kernelInstanceId=="string"?e.kernelInstanceId:"",n=Array.isArray(e.components)?e.components:[],r=new Set,o=[];for(let i of n){let l=Fo(i);!l||r.has(l.id)||(r.add(l.id),o.push(l))}o.sort((i,l)=>Do(i.id,l.id));let s=Sp(e.decisionTape);return{schemaVersion:"1.0",kernelInstanceId:t,components:o,...s.length>0?{decisionTape:s}:{}}}function Ka(e,t){let n=$o(t),r=e.decisionTape??[],o=n?[...r,n]:[...r];return{schemaVersion:e.schemaVersion,kernelInstanceId:e.kernelInstanceId,components:e.components,...o.length>0?{decisionTape:o}:{}}}var hr,Lo,Ma,yp,Ip,Et=Nt(()=>{"use strict";hr="1.0",Lo=["singleton","transient"],Ma=["absorb","escalate_up","hold"],yp=new Set(Lo);a(Do,"compare");a(hp,"uniqueSorted");a(ln,"nameList");a(Rp,"jsonPrimitive");a(Ap,"closedLifetime");a(Ha,"sanitizeMetadata");a(kp,"sanitizeArkRunExtendedInfo");a(Fo,"sanitizeArkRunComponent");Ip=new Set(Ma);a(bp,"sanitizeTapePayload");a($o,"sanitizeDecisionTapeRecord");a(Sp,"sanitizeDecisionTape");a(ve,"buildDependencyInformationPackage");a(Ka,"appendDecisionTape")});function un(e,t){return e<t?-1:e>t?1:0}function Ko(e){return[...new Set(e)].sort(un)}function ja(){return{tokens:[],ids:[],labels:[],tags:[],groups:[],architectureKinds:[]}}function Go(e){return e.tokens.length+e.ids.length+e.labels.length+e.tags.length+e.groups.length+e.architectureKinds.length>0}function Re(e,t){if(e==null||e==="")return[];if(typeof e=="string")return Ko(e.split(",").map(r=>r.trim()).filter(r=>r.length>0));if(!Array.isArray(e))throw new se(t);let n=[];for(let r of e){if(typeof r!="string")throw new se(t);let o=r.trim();o.length>0&&n.push(o)}return Ko(n)}function Za(e,t){if(t==="*")return e.length>0;if(!t.includes("*"))return e===t;let n="^";for(let r of t)r==="*"?n+=".*":/[.*+?^${}()|[\]\\]/.test(r)?n+=`\\${r}`:n+=r;return n+="$",new RegExp(n).test(e)}function cn(e,t){return e?t.some(n=>Za(e,n)):!1}function Ja(e){if(e==null||e==="")return Vo;if(typeof e=="string"&&vp.has(e))return e;throw new se("slice")}function Qa(e){if(e==null||e==="")return null;if(typeof e=="string"&&/^(0|[1-9]\d*)$/.test(e))return Number(e);if(typeof e=="number"&&Number.isInteger(e)&&e>=0)return e;throw new se("degreesOfSeparation")}function Ba(e,t){if(e==null||e==="")return ja();if(typeof e=="string"||Array.isArray(e))return{...ja(),tokens:Re(e,t)};if(typeof e!="object")throw new se(t);let n=e;for(let r of Object.keys(n))if(!wp.has(r))throw new se(t);return{tokens:[],ids:Re(n.ids,t),labels:Re(n.labels,t),tags:Re(n.tags,t),groups:Re(n.groups,t),architectureKinds:Re(n.architectureKinds,t)}}function kr(e={}){if(e==null||e==="")return kr({});if(typeof e!="object"||Array.isArray(e))throw new se("slice","ArkRun graph query must be an object.");let t=e;for(let n of Object.keys(t))if(!Ep.has(n))throw new se("slice",`ArkRun graph query key "${n}" is not closed.`);return{slice:Ja(t.slice),nodeIds:Re(t.nodeIds,"nodeIds"),degreesOfSeparation:Qa(t.degreesOfSeparation),include:Ba(t.include,"include"),exclude:Ba(t.exclude,"exclude")}}function Ir(e){let t={};e.slice&&(t.slice=Ja(e.slice));let n=Re(e.nodeIds??void 0,"nodeIds");n.length>0&&(t.nodeIds=n);let r=Qa(e.degreesOfSeparation??void 0);r!==null&&(t.degreesOfSeparation=r);let o=Re(e.include??void 0,"include");o.length>0&&(t.include=o);let s=Re(e.exclude??void 0,"exclude");return s.length>0&&(t.exclude=s),t}function Cp(e){let t=[e.id];return e.label&&t.push(e.label),e.group&&t.push(e.group),e.architectureKind&&t.push(e.architectureKind),e.tags&&t.push(...e.tags),t}function Wa(e,t){if(!Go(t))return!0;let n=Cp(e);return t.tokens.some(r=>n.some(o=>Za(o,r)))||cn(e.id,t.ids)||cn(e.label,t.labels)||e.tags?.some(r=>cn(r,t.tags))||cn(e.group,t.groups)?!0:cn(e.architectureKind,t.architectureKinds)}function xp(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;return ve({kernelInstanceId:t.kernelInstanceId,components:t.components})}return ve({})}function Op(e){let t={id:e.id,kind:"component",lifetime:e.lifetime},n=e.extendedInfo;return n?.label&&(t.label=n.label),n?.group&&(t.group=n.group),n?.architectureKind&&(t.architectureKind=n.architectureKind),n?.tags&&n.tags.length>0&&(t.tags=[...n.tags]),t}function Rr(e){return{id:e,kind:"interaction"}}function dn(e,t){let n=e.get(t.id);(!n||n.kind==="interaction"&&t.kind==="component")&&e.set(t.id,t)}function Ar(e,t,n,r,o){let s=`${n}\0${o}\0${r}`;t.has(s)||(t.add(s),e.push({from:n,to:r,kind:o}))}function Pp(e,t){let n=new Map,r=[],o=new Set;for(let s of e){if(dn(n,Op(s)),t==="technical"){for(let i of s.uses)dn(n,n.get(i)??Rr(i)),Ar(r,o,s.id,i,"uses");continue}for(let i of s.raises)dn(n,n.get(i)??Rr(i)),Ar(r,o,s.id,i,"raises");for(let i of s.reactsTo)dn(n,n.get(i)??Rr(i)),Ar(r,o,i,s.id,"reactsTo");for(let i of s.sends)dn(n,n.get(i)??Rr(i)),Ar(r,o,s.id,i,"sends")}return{nodes:n,edges:r}}function _p(e){let t=new Map,n=a((r,o)=>{let s=t.get(r);s?s.push(o):t.set(r,[o])},"push");for(let r of e)n(r.from,r.to),n(r.to,r.from);return t}function Tp(e,t,n,r){let o=t.filter(l=>e.has(l));if(o.length===0)return new Set;let s=new Set,i=o.map(l=>({id:l,depth:0}));for(;i.length>0;){let l=i.shift();if(!(!l||s.has(l.id))&&(s.add(l.id),!(n!==null&&l.depth>=n)))for(let c of r.get(l.id)??[])!s.has(c)&&e.has(c)&&i.push({id:c,depth:l.depth+1})}return s}function pn(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return/^[A-Za-z_]/.test(t)?t:`n_${t}`}function za(e){return e.replace(/\\/g,"\\\\").replace(/"/g,"#quot;").replace(/]/g,"#93;")}function Np(e){let t=new Set,n=new Map;for(let r of e){let o=pn(r),s=o,i=2;for(;t.has(s);)s=`${o}_${i}`,i+=1;t.add(s),n.set(r,s)}return n}function Bo(e){let t=e.slice==="technical"?"TD":"LR",n=e.nodes.map(l=>l.id),r=Np(n),o=Ko(e.nodes.map(l=>l.group).filter(l=>!!l)),s=[`flowchart ${t}`],i=a((l,c)=>{let u=r.get(l.id)??pn(l.id),f=za(l.label??l.id);s.push(`${c}${u}["${f}"]`)},"emitNode");for(let l of o){let c=pn(`group_${l}`);s.push(` subgraph ${c}["${za(l)}"]`);for(let u of e.nodes)u.group===l&&i(u," ");s.push(" end")}for(let l of e.nodes)l.group||i(l," ");for(let l of e.edges){let c=r.get(l.from)??pn(l.from),u=r.get(l.to)??pn(l.to);s.push(` ${c} -->|${l.kind}| ${u}`)}return s.join(`
2
+ `)}function Lp(e,t,n){let r=new Set(e.keys());if(Go(n.include)&&(r=new Set([...r].filter(l=>{let c=e.get(l);return c!==void 0&&Wa(c,n.include)}))),Go(n.exclude))for(let l of[...r]){let c=e.get(l);c&&Wa(c,n.exclude)&&r.delete(l)}let o=t.filter(l=>r.has(l.from)&&r.has(l.to));n.nodeIds.length>0&&(r=Tp(r,n.nodeIds,n.degreesOfSeparation,_p(o)));let s=[...r].sort(un).map(l=>e.get(l)).filter(l=>!!l),i=o.filter(l=>r.has(l.from)&&r.has(l.to)).sort((l,c)=>un(l.from,c.from)||un(l.kind,c.kind)||un(l.to,c.to));return{nodes:s,edges:i}}function br(e={},t={}){let n=xp(e),r=kr(t),o=Pp(n.components,r.slice),s=Lp(o.nodes,o.edges,r),i={schemaVersion:Uo,kernelInstanceId:n.kernelInstanceId,slice:r.slice,query:r,nodes:s.nodes,edges:s.edges,mermaid:""};return i.mermaid=Bo(i),i}var Uo,Vo,jo,qa,Ya,Xa,se,vp,Ep,wp,Sr=Nt(()=>{"use strict";Et();Uo="1.0",Vo="process",jo=["process","technical"],qa=["component","interaction"],Ya=["raises","reactsTo","sends"],Xa=["uses"],se=class extends Error{static{a(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}},vp=new Set(jo),Ep=new Set(["slice","nodeIds","degreesOfSeparation","include","exclude"]),wp=new Set(["ids","labels","tags","groups","architectureKinds"]);a(un,"compare");a(Ko,"uniqueSorted");a(ja,"emptyMatch");a(Go,"matchHasCriteria");a(Re,"nameList");a(Za,"globMatch");a(cn,"anyGlob");a(Ja,"closedSlice");a(Qa,"closedDegrees");a(Ba,"closedMatch");a(kr,"closeArkRunGraphQuery");a(Ir,"arkRunGraphQueryFromSearchParams");a(Cp,"nodeFields");a(Wa,"nodeMatches");a(xp,"asPackage");a(Op,"componentNode");a(Rr,"interactionNode");a(dn,"addNode");a(Ar,"addEdge");a(Pp,"buildSlice");a(_p,"adjacency");a(Tp,"neighborhood");a(pn,"mermaidSafeId");a(za,"mermaidLabel");a(Np,"uniqueMermaidIds");a(Bo,"formatArkRunGraphMermaid");a(Lp,"filterGraph");a(br,"requestArkRunGraph")});function Wo(e){if(e===void 0)return"local";if(typeof e=="string"&&Dp.has(e))return e;throw new wt("transport")}function zo(e){if(e===void 0)return!0;if(e===!0||e===!1)return e;throw new wt("ephemeral")}function vr(e){let t=Wo(e.transport),n=zo(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 fn,Ct,Dp,wt,gn=Nt(()=>{"use strict";fn=["local","localBlocking","broker"],Ct=!0,Dp=new Set(fn),wt=class extends Error{static{a(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}};a(Wo,"closedArkRunTransportKind");a(zo,"closedArkRunEphemeral");a(vr,"resolveArkRunSendPlan")});function wr(e){return e==="production"}function $p(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 el(e){if(e.startsWith("[::ffff:")&&e.endsWith("]"))return e.slice(8,-1);if(e.startsWith("::ffff:"))return e.slice(7)}function Ot(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();if(t==="localhost"||t==="::1"||t==="[::1]")return!0;let n=el(t);if(n)return Ot(n);let r=$p(t);return r!==void 0&&r[0]===127}function tl(e){if(e===void 0)return Er;if(typeof e!="string")throw new ue(String(e));let t=e.trim();if(Fp.has(t.toLowerCase())||!Ot(t))throw new ue(t);let n=t.toLowerCase();if(n==="localhost")return Er;if(n==="[::1]")return"::1";let r=el(n);return r?tl(r):n}function Mp(e){if(e===void 0)return Yo;if(typeof e!="number"||!Number.isInteger(e)||e<0||e>65535)throw new ue(`port:${String(e)}`);return e}function kn(e={}){if(wr(e.nodeEnv)||wr(e.processNodeEnv))throw new xt;return{host:tl(e.host),port:Mp(e.port)}}function Ee(e,t,n){return`http://${e.includes(":")?`[${e}]`:e}:${t}${n}`}function Hp(e){if(e!==void 0)try{return JSON.parse(JSON.stringify(e))}catch{return}}function Kp(e){return{kinds:[...fn],ephemeralDefault:e.ephemeralDefault===!1?!1:!0,brokerBound:e.brokerBound===!0,cloudSdksShipped:!1,fallback:Zo}}function De(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function Gp(e){let t=De(e);if(!t||typeof t.id!="string")return;let n=t.status;if(n!=="pending"&&n!=="failed")return;let r=De(t.event),o=r&&typeof r.intent=="string"?r.intent:typeof t.intent=="string"?t.intent:void 0,s={id:t.id,status:n,attempts:typeof t.attempts=="number"&&Number.isFinite(t.attempts)?t.attempts:0};return o&&(s.intent=o),typeof t.error=="string"&&t.error.length>0&&(s.error=t.error),typeof t.updatedAt=="string"&&(s.updatedAt=t.updatedAt),s}function Cr(e){if(typeof e!="number"||!Number.isFinite(e))return le;let t=Math.trunc(e);return t<0?0:t>le?le:t}function Ye(e,t){let n=typeof e=="string"&&e.trim().length>0?e.trim():e&&typeof e=="object"&&"constructor"in e?String(e.constructor?.name??t):t,r=/^InMemory/i.test(n)?"memory":"durable";return{role:t,id:n,kind:r}}function In(e={}){let t=De(e),n=De(t?.durability)??t,r=Array.isArray(n?.stores)?n.stores:Array.isArray(t?.stores)?t.stores:[],o=[];for(let s of r){let i=De(s);if(!i)continue;let l=i.role;if(l!=="outbox"&&l!=="audit"&&l!=="workflow")continue;let c=typeof i.id=="string"?i.id:typeof i.name=="string"?i.name:void 0;if(!c)continue;let u=i.kind==="memory"||i.kind==="durable"?i.kind:Ye(c,l).kind;o.push({role:l,id:c,kind:u})}return{durability:{stores:o}}}function Xe(e=[],t={}){let n=Cr(t.sampleLimit),r=Array.isArray(e)?e:[],o=[],s=[];for(let i of r){let l=Gp(i);l&&(l.status==="pending"?o.push(l):s.push(l))}return{available:!0,pendingCount:o.length,failedCount:s.length,pending:o.slice(0,n),failed:s.slice(0,n),sampleLimit:n}}function ze(){return{available:!1,pendingCount:0,failedCount:0,pending:[],failed:[],sampleLimit:le}}function Up(e){let t=De(e);if(!t||typeof t.id!="string")return;let n=typeof t.workflowName=="string"?t.workflowName:typeof t.name=="string"?t.name:void 0;if(!n)return;let r={id:t.id,name:n,status:typeof t.status=="string"?t.status:"unknown"};return typeof t.currentStep=="string"&&(r.currentStep=t.currentStep),typeof t.error=="string"&&t.error.length>0&&(r.error=t.error),r}function Vp(e){return e==="idle"||e==="waiting"}function Ze(e=[],t={}){let n=Cr(t.sampleLimit),r=Array.isArray(e)?e:[],o=[],s=0,i=0,l=0,c=0;for(let u of r){let f=Up(u);f&&(o.push(f),f.status==="running"?s+=1:f.status==="compensating"?i+=1:f.status==="failed"?l+=1:Vp(f.status)&&(c+=1))}return{available:!0,total:o.length,runningCount:s,compensatingCount:i,failedCount:l,pendingCount:c,workflows:o.slice(0,n),sampleLimit:n}}function qe(){return{available:!1,total:0,runningCount:0,compensatingCount:0,failedCount:0,pendingCount:0,workflows:[],sampleLimit:le}}function jp(e){if(e===void 0)return;let t=De(e);if(!t||t.available===!1)return ze();let n=Cr(t.sampleLimit);if(Array.isArray(t.pending)||Array.isArray(t.failed)||Array.isArray(t.records)){let r=[...Array.isArray(t.pending)?t.pending:[],...Array.isArray(t.failed)?t.failed:[],...Array.isArray(t.records)?t.records:[]],o=Xe(r,{sampleLimit:n}),s=typeof t.pendingCount=="number"&&Number.isFinite(t.pendingCount)?Math.max(0,Math.trunc(t.pendingCount)):o.pendingCount,i=typeof t.failedCount=="number"&&Number.isFinite(t.failedCount)?Math.max(0,Math.trunc(t.failedCount)):o.failedCount;return{...o,pendingCount:s,failedCount:i,sampleLimit:n}}return ze()}function Bp(e){if(e===void 0)return;let t=De(e);if(!t||t.available===!1)return qe();let n=Cr(t.sampleLimit);if(Array.isArray(t.workflows)){let r=Ze(t.workflows,{sampleLimit:n}),o=typeof t.total=="number"&&Number.isFinite(t.total)?Math.max(0,Math.trunc(t.total)):r.total,s=typeof t.runningCount=="number"&&Number.isFinite(t.runningCount)?Math.max(0,Math.trunc(t.runningCount)):r.runningCount,i=typeof t.compensatingCount=="number"&&Number.isFinite(t.compensatingCount)?Math.max(0,Math.trunc(t.compensatingCount)):r.compensatingCount,l=typeof t.failedCount=="number"&&Number.isFinite(t.failedCount)?Math.max(0,Math.trunc(t.failedCount)):r.failedCount,c=typeof t.pendingCount=="number"&&Number.isFinite(t.pendingCount)?Math.max(0,Math.trunc(t.pendingCount)):r.pendingCount;return{...r,total:o,runningCount:s,compensatingCount:i,failedCount:l,pendingCount:c,sampleLimit:n}}return qe()}function xr(e={}){let t=kn({host:e.host,port:e.port}),n=ve({kernelInstanceId:e.kernelInstanceId,components:e.package&&typeof e.package=="object"&&!Array.isArray(e.package)&&Array.isArray(e.package.components)?e.package.components:[]}),r=jp(e.outbox),o=Bp(e.workflows),s={schemaVersion:qo,kernelInstanceId:typeof e.kernelInstanceId=="string"?e.kernelInstanceId:n.kernelInstanceId,bind:{host:t.host,port:t.port,loopback:!0},package:{...n,schemaVersion:"1.0"},transport:Kp(e),observability:Hp(e.observability)??{},hardening:In(e.hardening)};return r&&(s.outbox=r),o&&(s.workflows=o),s}function bn(e){return`event: ${Xo}
3
3
  data: ${JSON.stringify(e)}
4
4
 
5
- `}var xo,ur,Oo,nn,rn,on,sn,an,Po,_o,ie,kt,ce,pu,un=St(()=>{"use strict";ht();tn();xo="1.0",ur="127.0.0.1",Oo=0,nn="/snapshot",rn="/events",on="/graph",sn="/outbox",an="/workflows",Po="snapshot",_o="in-process-local",ie=32,kt=class extends Error{static{i(this,"ArkRunInspectorProductionError")}constructor(){super("ArkRun inspector refuses to start when NODE_ENV=production."),this.name="ArkRunInspectorProductionError"}},ce=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"}},pu=new Set(["","*","0","0.0.0.0","::","::0","[::]","[::0]","::ffff:0.0.0.0","[::ffff:0.0.0.0]"]);i(pr,"isArkRunInspectorProductionEnv");i(fu,"ipv4Octets");i(Ea,"unwrapIpv4Mapped");i(It,"isArkRunInspectorLoopbackHost");i(Sa,"closedHost");i(gu,"closedPort");i(ln,"resolveArkRunInspectorBind");i(be,"arkRunInspectorUrl");i(mu,"jsonClone");i(yu,"closedTransportFacts");i(Te,"asRecord");i(hu,"closedOutboxSummary");i(fr,"closedSampleLimit");i(Be,"classifyArkRunInspectorStoreDurability");i(cn,"buildArkRunInspectorHardening");i(We,"buildArkRunInspectorOutboxMonitor");i(Ve,"unavailableArkRunInspectorOutboxMonitor");i(Ru,"closedWorkflowSummary");i(Au,"isPendingWorkflowStatus");i(ze,"buildArkRunInspectorWorkflowsMonitor");i(je,"unavailableArkRunInspectorWorkflowsMonitor");i(ku,"closedOutboxMonitor");i(Iu,"closedWorkflowsMonitor");i(gr,"buildArkRunInspectorSnapshot");i(dn,"formatArkRunInspectorSseEvent")});var wa={};La(wa,{listenArkRunInspector:()=>xu});function bu(){return{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}}function vu(){return{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-store",connection:"keep-alive","x-accel-buffering":"no"}}function Eu(e){let t=e&&e.length>0?e:"/";return new URL(t,"http://127.0.0.1")}function Ne(e,t,n){if(!(e.writableEnded||e.destroyed))try{e.writeHead(t,bu()),e.end(JSON.stringify(n))}catch{}}function Su(e,t){let n=e.address();if(n===null||typeof n=="string")throw new ce(t.host);if(!It(n.address))throw new ce(n.address);return{host:t.host,port:n.port}}async function wu(e){if(typeof e.listInspectorOutbox=="function")return e.listInspectorOutbox();let t=e.outbox??e.eventBuffer;if(!t||typeof t.list!="function")return Ve();let[n,r]=await Promise.all([t.list("pending"),t.list("failed")]);return We([...n??[],...r??[]],{sampleLimit:ie})}async function Cu(e){return typeof e.listInspectorWorkflows=="function"?e.listInspectorWorkflows():!e.workflowEngine||typeof e.workflowEngine.list!="function"?je():ze(await e.workflowEngine.list(),{sampleLimit:ie})}async function xu(e,t){let n=await import("http"),r=new Set,o=new Set,s=typeof t.sseIntervalMs=="number"&&Number.isFinite(t.sseIntervalMs)?Math.max(0,t.sseIntervalMs):1e3,a=t.bind,l=i(()=>e.getInspectorSnapshot(a),"snapshot"),c=n.createServer((u,f)=>{let y=Eu(u.url),p=y.pathname;if(u.method==="GET"&&(p==="/"||p===nn)){Ne(f,200,l());return}if(u.method==="GET"&&p===on){try{Ne(f,200,e.requestGraph(ar({slice:y.searchParams.get("slice"),nodeIds:y.searchParams.get("nodeIds"),degreesOfSeparation:y.searchParams.get("degreesOfSeparation"),include:y.searchParams.get("include"),exclude:y.searchParams.get("exclude")})))}catch(g){if(g instanceof ne){Ne(f,400,{error:g.message,option:g.option});return}throw g}return}if(u.method==="GET"&&p===sn){wu(e).then(g=>Ne(f,200,g)).catch(g=>{Ne(f,500,{error:g instanceof Error?g.message:"outbox monitor failed"})});return}if(u.method==="GET"&&p===an){Cu(e).then(g=>Ne(f,200,g)).catch(g=>{Ne(f,500,{error:g instanceof Error?g.message:"workflows monitor failed"})});return}if(u.method==="GET"&&p===rn){f.writeHead(200,vu()),f.flushHeaders(),f.write(dn(l())),r.add(f);let g=s>0?setInterval(()=>{f.write(dn(l()))},s):void 0;g&&o.add(g);let d=i(()=>{r.delete(f),g&&(clearInterval(g),o.delete(g))},"drop");u.on("close",d),f.on("close",d);return}Ne(f,404,{error:"not found"})});try{await new Promise((u,f)=>{let y=i(p=>f(p),"onError");c.once("error",y),c.listen({host:t.bind.host,port:t.bind.port},()=>{c.off("error",y);try{a=Su(c,t.bind),u()}catch(p){f(p instanceof Error?p:new ce(t.bind.host))}})})}catch(u){throw await new Promise(f=>{c.close(()=>f())}),u}return{host:a.host,port:a.port,url:be(a.host,a.port,"/"),snapshotUrl:be(a.host,a.port,nn),eventsUrl:be(a.host,a.port,rn),graphUrl:be(a.host,a.port,on),outboxUrl:be(a.host,a.port,sn),workflowsUrl:be(a.host,a.port,an),close(){for(let u of o)clearInterval(u);o.clear();for(let u of r)u.end();return r.clear(),new Promise((u,f)=>{c.close(y=>{y?f(y):u()})})}}}var Ca=St(()=>{"use strict";cr();un();i(bu,"jsonHeaders");i(vu,"sseHeaders");i(Eu,"requestUrl");i(Ne,"writeJson");i(Su,"boundAddress");i(wu,"resolveOutboxMonitor");i(Cu,"resolveWorkflowsMonitor");i(xu,"listenArkRunInspector")});var yr="4.8.21";var Fa=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,$a=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,Ma=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function Ha(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),o=String(t?.toLayer??"");return Fa.test(n)?"pure-shared":r==="PersistenceAdapters"&&($a.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${o} ${n}`))?"kernel-emit":Ma.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&o==="PersistenceAdapters"?"use-case":"unknown"}i(Ha,"classifyLayerImportKind");function Ka(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=Ha(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(Ka,"layerImportNextAction");function Ga(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}i(Ga,"arkRunCallSiteName");function Ua(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(Ua,"arkRunNextAction");function pe(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return Ka(e);case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, test at the public interface, then preflight again.`;case"CAPABILITY_VIOLATION":return`Define a ${String(e.capability??"capability")} port in ${e.fromLayer??"the walled layer"}, bind the implementation outside it, test at the public interface, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, test at the public interface, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"LITERAL_PATH_DRIFT":return typeof e.target=="string"&&e.target.length>0?`Rewrite the literal to ${e.target}, or run \`arkgate-check --path-drift --base-ref <ref> --write\` to apply every anchored replacement.`:"Rewrite the literal to the rename destination, or run `arkgate-check --path-drift --base-ref <ref> --write` to apply every anchored replacement.";case"LITERAL_PATH_UNRESOLVED":return"Read the candidate and decide: fix the path, or leave it. Advisory \u2014 with no rename to anchor it there is no destination to propose, so --write never touches it.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";case"INVARIANT_COVERAGE_OUTSIDE_ROOTS":return"Move the covering test under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json, then run Ark again.";case"INVARIANT_CATALOG_EMPTY":return typeof e.file=="string"&&e.file.length>0?`Add 1\u20132 short phrases to invariants[] in ${e.file}, then run ark-check --doctor. Starters show the shape.`:"Add 1\u20132 short phrases to invariants[] in arkrules/<Domain>.json, then run ark-check --doctor. Starters show the shape.";case"INVARIANT_TESTS_PATH_MISSING":return"Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present.";case"INVARIANT_COVERAGE_ROOTS_MISSING":return"Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. An enforced invariant fails closed until that path is present.";case"ARKRULE_STRUCTURE":case"ARKRULE_INVARIANT":case"INVARIANT_UNCOVERED":return`Fix the structure or invariant for ${typeof e.arkruleId=="string"&&e.arkruleId.length>0?e.arkruleId:"the ArkRule"} (declared in ${typeof e.arkruleSource=="string"&&e.arkruleSource.length>0?e.arkruleSource:"arkrules/<Layer>.json"}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`;case"ARKRUN_MISSING_ROOT":case"ARKRUN_KERNEL_IN_DOMAIN":case"ARKRUN_DIRECT_NEW":case"ARKRUN_UNDECLARED_EMIT":case"ARKRUN_UNDECLARED_HANDLE":case"ARKRUN_UNDECLARED_DEPEND":case"ARKRUN_TRANSPORT_BYPASS":return Ua(e);case"ARKORDER_MISSING_PLANE":return typeof e.target=="string"&&e.target.length>0?`Import createOrderPlane from arkgate/order and call it in plane root ${e.target} listed in arkOrder.planeRoots, then preflight again.`:"Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKORDER_KERNEL_IN_DOMAIN":return"Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe.";case"ARKORDER_GENERIC_UPDATE":return"Don't use a generic update. First freeze with release(). Later, propose the change, then apply it.";case"ARKORDER_TOO_MANY_PARAMS":return"Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe.";case"ARKORDER_INGEST_WRITES_XI":return"Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe.";case"ARKORDER_XI_FIELD_WRITE":return typeof e.target=="string"&&e.target.length>0?`Don't write ${e.target} from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.`:"Don't write a named product choice from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.";case"ARKORDER_UNVALVED_RELEASE":return"Change the choice with proposeRelease then apply. release() is only the first freeze. Never mechanical-safe.";default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(pe,"deterministicNextAction");var gn="1.5",hr="docs/diagnostics.md",Ko={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","mode","valid","completeness","completenessReasons","diagnostics"],allOf:[{if:{properties:{completeness:{enum:["partial","unavailable"]}},required:["completeness"]},then:{properties:{valid:{const:!1}}}},{if:{properties:{mode:{const:"resolved-candidate-facts"},completeness:{enum:["complete","partial"]}},required:["mode","completeness"]},then:{required:["policyHash","resolverIdentity","factsHash","candidateTreeHash"]}},{if:{properties:{completeness:{const:"complete"}},required:["completeness"]},then:{properties:{completenessReasons:{maxItems:0}}},else:{properties:{completenessReasons:{minItems:1}}}}],properties:{schemaVersion:{const:"1.5"},mode:{enum:["lexical-compatibility","resolved-candidate-facts"]},valid:{type:"boolean"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:{type:"string",minLength:1},message:{type:"string",minLength:1},file:{type:"string",minLength:1}}}},policyHash:{type:"string",minLength:1},resolverIdentity:{type:"string",minLength:1},factsHash:{type:"string",minLength:1},candidateTreeHash:{type:"string",minLength:1},diagnostics:{type:"array",items:{type:"object",additionalProperties:!1,required:["ruleId","severity","message","location","evidence"],properties:{ruleId:{type:"string",minLength:1},severity:{enum:["error","warning"]},message:{type:"string",minLength:1},location:{type:"object",additionalProperties:!1,required:["file","line","column"],properties:{file:{type:"string",minLength:1},line:{type:"integer",minimum:1},column:{type:"integer",minimum:1}}},evidence:{type:"object",additionalProperties:!1,properties:{target:{type:"string"},fromLayer:{type:"string"},toLayer:{type:"string"},typeOnly:{type:"boolean"},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"},peerIsolation:{type:"boolean"},capability:{type:"string",minLength:1},edgeKind:{type:"string",minLength:1},arkruleId:{type:"string",minLength:1},arkruleSource:{type:"string",minLength:1}}},nextAction:{type:"string",minLength:1},findingRef:{type:"string",minLength:1,pattern:"^fnv1a-[0-9a-f]{8}$"},targetKey:{type:"string",minLength:1},docsCodePath:{type:"string",minLength:1}}}}}};function mn(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(mn,"adapterFindingTargetKey");function yn(e){let t=new Map;return e.map(n=>{let r=mn(n),o=(t.get(r)??0)+1;return t.set(r,o),o===1?r:`${r}#${o}`})}i(yn,"adapterFindingOccurrenceTargetKeys");function Rr(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(Rr,"adapterFindingRefFromTargetKey");function Ar(e){return`${hr}#${e}`}i(Ar,"adapterDocsCodePath");function O(e){return typeof e=="string"&&e.length>0?e:void 0}i(O,"text");function Go(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}i(Go,"positiveInteger");function Va(e,t,n){return pe({ruleId:e,target:O(t.target)??O(n.target)??void 0,fromLayer:O(t.fromLayer)??void 0,toLayer:O(t.toLayer)??void 0,typeOnly:t.typeOnly===!0,targetTypeOnlyExports:t.targetTypeOnlyExports===!0,namedBindingsTypeOnly:t.namedBindingsTypeOnly===!0,portProofEligible:t.portProofEligible===!0,peerIsolation:t.peerIsolation===!0,sourcePureTypeModule:t.sourcePureTypeModule===!0,edgeKind:O(t.edgeKind)??void 0,capability:O(t.capability)??O(n.capability)??void 0,arkruleId:O(t.arkruleId)??void 0,arkruleSource:O(t.arkruleSource)??void 0})}i(Va,"nextActionForDiagnostic");function kr(e,t="error",n){let r=O(e.ruleId)??O(e.code)??"ARK_UNKNOWN",o=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,s={...O(e.target)?{target:O(e.target)}:{},...O(e.fromLayer)?{fromLayer:O(e.fromLayer)}:{},...O(e.toLayer)?{toLayer:O(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{},...typeof e.targetTypeOnlyExports=="boolean"?{targetTypeOnlyExports:e.targetTypeOnlyExports}:{},...typeof e.sourcePureTypeModule=="boolean"?{sourcePureTypeModule:e.sourcePureTypeModule}:{},...typeof e.namedBindingsTypeOnly=="boolean"?{namedBindingsTypeOnly:e.namedBindingsTypeOnly}:{},...typeof e.portProofEligible=="boolean"?{portProofEligible:e.portProofEligible}:{},...typeof e.peerIsolation=="boolean"?{peerIsolation:e.peerIsolation}:{},...O(e.capability)?{capability:O(e.capability)}:{},...O(e.edgeKind)?{edgeKind:O(e.edgeKind)}:{},...O(e.arkruleId)?{arkruleId:O(e.arkruleId)}:{},...O(e.arkruleSource)?{arkruleSource:O(e.arkruleSource)}:{}},a=n??mn(e),l=Rr(a);return{ruleId:r,severity:o,message:O(e.message)??r,location:{file:O(e.file)??"<unknown>",line:Go(e.line,1),column:Go(e.column,1)},evidence:s,nextAction:O(e.nextAction)??Va(r,s,e),findingRef:l,targetKey:a,docsCodePath:Ar(r)}}i(kr,"toAdapterDiagnostic");function ja(e){let t=e.completeness??"complete",n=e.mode??"lexical-compatibility";if(t==="complete"&&(e.completenessReasons?.length??0)>0)throw new Error("completenessReasons must be empty when completeness is complete.");let r=t==="complete"?[]:e.completenessReasons&&e.completenessReasons.length>0?e.completenessReasons.map(y=>({code:O(y.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:O(y.message)??`Analysis ${t}: required evidence is incomplete.`,...O(y.file)?{file:O(y.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],o={...O(e.policyHash)?{policyHash:O(e.policyHash)}:{},...O(e.resolverIdentity)?{resolverIdentity:O(e.resolverIdentity)}:{},...O(e.factsHash)?{factsHash:O(e.factsHash)}:{},...O(e.candidateTreeHash)?{candidateTreeHash:O(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let y of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!o[y])throw new Error(`${y} is required for resolved ${t} adapter evidence.`)}let s=e.violations??[],a=e.warnings??[],l=yn(s),c=yn(a),u=[...s.map((y,p)=>kr(y,"error",l[p])),...a.map((y,p)=>kr(y,"warning",c[p]))],f={schemaVersion:"1.5",completenessReasons:r,diagnostics:u};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...f,mode:n,valid:!1,completeness:t,...o};let y={policyHash:o.policyHash,resolverIdentity:o.resolverIdentity,factsHash:o.factsHash,candidateTreeHash:o.candidateTreeHash};return t==="complete"?{...f,mode:n,valid:e.valid,completeness:t,...y}:{...f,mode:n,valid:!1,completeness:t,...y}}return t==="complete"?{...f,mode:n,valid:e.valid,completeness:t,...o}:{...f,mode:n,valid:!1,completeness:t,...o}}i(ja,"createAdapterResult");var qe=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 Uo=new qe;function Vo(e,t){return Uo.define(e,t)}i(Vo,"defineIntent");function hn(){return new qe}i(hn,"createIntentRegistry");var jo=Uo;var Bo=["Domain.","Application.","Adapter.","Workflow.","Job.","Presentation.","Reporting.","Metadata.","Security.","Audit.","Observability.","Kernel."];function Rn(e){if(!e||typeof e!="string")return{valid:!1,reason:"Intent name must be a non-empty string"};if(!Bo.some(n=>e.startsWith(n)))return{valid:!1,reason:`Intent "${e}" must start with one of: ${Bo.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(Rn,"validateIntentName");var we=class extends Error{static{i(this,"PolicyViolationError")}violations;constructor(t){let n=t.map(r=>`- ${r.policyName}: ${r.message}`).join(`
5
+ `}var qo,Er,Yo,mn,yn,hn,Rn,An,Xo,Zo,le,xt,ue,Fp,Sn=Nt(()=>{"use strict";Et();gn();qo="1.0",Er="127.0.0.1",Yo=0,mn="/snapshot",yn="/events",hn="/graph",Rn="/outbox",An="/workflows",Xo="snapshot",Zo="in-process-local",le=32,xt=class extends Error{static{a(this,"ArkRunInspectorProductionError")}constructor(){super("ArkRun inspector refuses to start when NODE_ENV=production."),this.name="ArkRunInspectorProductionError"}},ue=class extends Error{static{a(this,"ArkRunInspectorBindError")}constructor(t){super(`ArkRun inspector binds loopback only (default 127.0.0.1). Public host "${t}" is rejected.`),this.name="ArkRunInspectorBindError"}},Fp=new Set(["","*","0","0.0.0.0","::","::0","[::]","[::0]","::ffff:0.0.0.0","[::ffff:0.0.0.0]"]);a(wr,"isArkRunInspectorProductionEnv");a($p,"ipv4Octets");a(el,"unwrapIpv4Mapped");a(Ot,"isArkRunInspectorLoopbackHost");a(tl,"closedHost");a(Mp,"closedPort");a(kn,"resolveArkRunInspectorBind");a(Ee,"arkRunInspectorUrl");a(Hp,"jsonClone");a(Kp,"closedTransportFacts");a(De,"asRecord");a(Gp,"closedOutboxSummary");a(Cr,"closedSampleLimit");a(Ye,"classifyArkRunInspectorStoreDurability");a(In,"buildArkRunInspectorHardening");a(Xe,"buildArkRunInspectorOutboxMonitor");a(ze,"unavailableArkRunInspectorOutboxMonitor");a(Up,"closedWorkflowSummary");a(Vp,"isPendingWorkflowStatus");a(Ze,"buildArkRunInspectorWorkflowsMonitor");a(qe,"unavailableArkRunInspectorWorkflowsMonitor");a(jp,"closedOutboxMonitor");a(Bp,"closedWorkflowsMonitor");a(xr,"buildArkRunInspectorSnapshot");a(bn,"formatArkRunInspectorSseEvent")});var nl={};ul(nl,{listenArkRunInspector:()=>Jp});function Wp(){return{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}}function zp(){return{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-store",connection:"keep-alive","x-accel-buffering":"no"}}function qp(e){let t=e&&e.length>0?e:"/";return new URL(t,"http://127.0.0.1")}function Fe(e,t,n){if(!(e.writableEnded||e.destroyed))try{e.writeHead(t,Wp()),e.end(JSON.stringify(n))}catch{}}function Yp(e,t){let n=e.address();if(n===null||typeof n=="string")throw new ue(t.host);if(!Ot(n.address))throw new ue(n.address);return{host:t.host,port:n.port}}async function Xp(e){if(typeof e.listInspectorOutbox=="function")return e.listInspectorOutbox();let t=e.outbox??e.eventBuffer;if(!t||typeof t.list!="function")return ze();let[n,r]=await Promise.all([t.list("pending"),t.list("failed")]);return Xe([...n??[],...r??[]],{sampleLimit:le})}async function Zp(e){return typeof e.listInspectorWorkflows=="function"?e.listInspectorWorkflows():!e.workflowEngine||typeof e.workflowEngine.list!="function"?qe():Ze(await e.workflowEngine.list(),{sampleLimit:le})}async function Jp(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,i=t.bind,l=a(()=>e.getInspectorSnapshot(i),"snapshot"),c=n.createServer((u,f)=>{let y=qp(u.url),p=y.pathname;if(u.method==="GET"&&(p==="/"||p===mn)){Fe(f,200,l());return}if(u.method==="GET"&&p===hn){try{Fe(f,200,e.requestGraph(Ir({slice:y.searchParams.get("slice"),nodeIds:y.searchParams.get("nodeIds"),degreesOfSeparation:y.searchParams.get("degreesOfSeparation"),include:y.searchParams.get("include"),exclude:y.searchParams.get("exclude")})))}catch(g){if(g instanceof se){Fe(f,400,{error:g.message,option:g.option});return}throw g}return}if(u.method==="GET"&&p===Rn){Xp(e).then(g=>Fe(f,200,g)).catch(g=>{Fe(f,500,{error:g instanceof Error?g.message:"outbox monitor failed"})});return}if(u.method==="GET"&&p===An){Zp(e).then(g=>Fe(f,200,g)).catch(g=>{Fe(f,500,{error:g instanceof Error?g.message:"workflows monitor failed"})});return}if(u.method==="GET"&&p===yn){f.writeHead(200,zp()),f.flushHeaders(),f.write(bn(l())),r.add(f);let g=s>0?setInterval(()=>{f.write(bn(l()))},s):void 0;g&&o.add(g);let d=a(()=>{r.delete(f),g&&(clearInterval(g),o.delete(g))},"drop");u.on("close",d),f.on("close",d);return}Fe(f,404,{error:"not found"})});try{await new Promise((u,f)=>{let y=a(p=>f(p),"onError");c.once("error",y),c.listen({host:t.bind.host,port:t.bind.port},()=>{c.off("error",y);try{i=Yp(c,t.bind),u()}catch(p){f(p instanceof Error?p:new ue(t.bind.host))}})})}catch(u){throw await new Promise(f=>{c.close(()=>f())}),u}return{host:i.host,port:i.port,url:Ee(i.host,i.port,"/"),snapshotUrl:Ee(i.host,i.port,mn),eventsUrl:Ee(i.host,i.port,yn),graphUrl:Ee(i.host,i.port,hn),outboxUrl:Ee(i.host,i.port,Rn),workflowsUrl:Ee(i.host,i.port,An),close(){for(let u of o)clearInterval(u);o.clear();for(let u of r)u.end();return r.clear(),new Promise((u,f)=>{c.close(y=>{y?f(y):u()})})}}}var rl=Nt(()=>{"use strict";Sr();Sn();a(Wp,"jsonHeaders");a(zp,"sseHeaders");a(qp,"requestUrl");a(Fe,"writeJson");a(Yp,"boundAddress");a(Xp,"resolveOutboxMonitor");a(Zp,"resolveWorkflowsMonitor");a(Jp,"listenArkRunInspector")});var Pr="4.8.23";var pl=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,fl=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,gl=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function ml(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),o=String(t?.toLayer??"");return pl.test(n)?"pure-shared":r==="PersistenceAdapters"&&(fl.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${o} ${n}`))?"kernel-emit":gl.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&o==="PersistenceAdapters"?"use-case":"unknown"}a(ml,"classifyLayerImportKind");function yl(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=ml(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."}a(yl,"layerImportNextAction");function hl(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}a(hl,"arkRunCallSiteName");function Rl(e){let t=hl(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.`}}a(Rl,"arkRunNextAction");function ye(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return yl(e);case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, test at the public interface, then preflight again.`;case"CAPABILITY_VIOLATION":return`Define a ${String(e.capability??"capability")} port in ${e.fromLayer??"the walled layer"}, bind the implementation outside it, test at the public interface, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, test at the public interface, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"LITERAL_PATH_DRIFT":return typeof e.target=="string"&&e.target.length>0?`Rewrite the literal to ${e.target}, or run \`arkgate-check --path-drift --base-ref <ref> --write\` to apply every anchored replacement.`:"Rewrite the literal to the rename destination, or run `arkgate-check --path-drift --base-ref <ref> --write` to apply every anchored replacement.";case"LITERAL_PATH_UNRESOLVED":return"Read the candidate and decide: fix the path, or leave it. Advisory \u2014 with no rename to anchor it there is no destination to propose, so --write never touches it.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";case"INVARIANT_COVERAGE_OUTSIDE_ROOTS":return"Move the covering test under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json, then run Ark again.";case"INVARIANT_CATALOG_EMPTY":return typeof e.file=="string"&&e.file.length>0?`Add 1\u20132 short phrases to invariants[] in ${e.file}, then run ark-check --doctor. Starters show the shape.`:"Add 1\u20132 short phrases to invariants[] in arkrules/<Domain>.json, then run ark-check --doctor. Starters show the shape.";case"INVARIANT_TESTS_PATH_MISSING":return"Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present.";case"INVARIANT_COVERAGE_ROOTS_MISSING":return"Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. An enforced invariant fails closed until that path is present.";case"ARKRULE_STRUCTURE":case"ARKRULE_INVARIANT":case"INVARIANT_UNCOVERED":return`Fix the structure or invariant for ${typeof e.arkruleId=="string"&&e.arkruleId.length>0?e.arkruleId:"the ArkRule"} (declared in ${typeof e.arkruleSource=="string"&&e.arkruleSource.length>0?e.arkruleSource:"arkrules/<Layer>.json"}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`;case"ARKRUN_MISSING_ROOT":case"ARKRUN_KERNEL_IN_DOMAIN":case"ARKRUN_DIRECT_NEW":case"ARKRUN_UNDECLARED_EMIT":case"ARKRUN_UNDECLARED_HANDLE":case"ARKRUN_UNDECLARED_DEPEND":case"ARKRUN_TRANSPORT_BYPASS":return Rl(e);case"ARKORDER_MISSING_PLANE":return typeof e.target=="string"&&e.target.length>0?`Import createOrderPlane from arkgate/order and call it in plane root ${e.target} listed in arkOrder.planeRoots, then preflight again.`:"Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKORDER_KERNEL_IN_DOMAIN":return"Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe.";case"ARKORDER_GENERIC_UPDATE":return"Don't use a generic update. First freeze with release(). Later, propose the change, then apply it.";case"ARKORDER_TOO_MANY_PARAMS":return"Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe.";case"ARKORDER_INGEST_WRITES_XI":return"Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe.";case"ARKORDER_XI_FIELD_WRITE":return typeof e.target=="string"&&e.target.length>0?`Don't write ${e.target} from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.`:"Don't write a named product choice from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.";case"ARKORDER_UNVALVED_RELEASE":return"Change the choice with proposeRelease then apply. release() is only the first freeze. Never mechanical-safe.";default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}a(ye,"deterministicNextAction");var wn="1.5",_r="docs/diagnostics.md",is={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","mode","valid","completeness","completenessReasons","diagnostics"],allOf:[{if:{properties:{completeness:{enum:["partial","unavailable"]}},required:["completeness"]},then:{properties:{valid:{const:!1}}}},{if:{properties:{mode:{const:"resolved-candidate-facts"},completeness:{enum:["complete","partial"]}},required:["mode","completeness"]},then:{required:["policyHash","resolverIdentity","factsHash","candidateTreeHash"]}},{if:{properties:{completeness:{const:"complete"}},required:["completeness"]},then:{properties:{completenessReasons:{maxItems:0}}},else:{properties:{completenessReasons:{minItems:1}}}}],properties:{schemaVersion:{const:"1.5"},mode:{enum:["lexical-compatibility","resolved-candidate-facts"]},valid:{type:"boolean"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:{type:"string",minLength:1},message:{type:"string",minLength:1},file:{type:"string",minLength:1}}}},policyHash:{type:"string",minLength:1},resolverIdentity:{type:"string",minLength:1},factsHash:{type:"string",minLength:1},candidateTreeHash:{type:"string",minLength:1},diagnostics:{type:"array",items:{type:"object",additionalProperties:!1,required:["ruleId","severity","message","location","evidence"],properties:{ruleId:{type:"string",minLength:1},severity:{enum:["error","warning"]},message:{type:"string",minLength:1},location:{type:"object",additionalProperties:!1,required:["file","line","column"],properties:{file:{type:"string",minLength:1},line:{type:"integer",minimum:1},column:{type:"integer",minimum:1}}},evidence:{type:"object",additionalProperties:!1,properties:{target:{type:"string"},fromLayer:{type:"string"},toLayer:{type:"string"},typeOnly:{type:"boolean"},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"},peerIsolation:{type:"boolean"},capability:{type:"string",minLength:1},edgeKind:{type:"string",minLength:1},arkruleId:{type:"string",minLength:1},arkruleSource:{type:"string",minLength:1}}},nextAction:{type:"string",minLength:1},findingRef:{type:"string",minLength:1,pattern:"^fnv1a-[0-9a-f]{8}$"},targetKey:{type:"string",minLength:1},docsCodePath:{type:"string",minLength:1}}}}}};function Cn(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("|")}a(Cn,"adapterFindingTargetKey");function xn(e){let t=new Map;return e.map(n=>{let r=Cn(n),o=(t.get(r)??0)+1;return t.set(r,o),o===1?r:`${r}#${o}`})}a(xn,"adapterFindingOccurrenceTargetKeys");function Tr(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")}`}a(Tr,"adapterFindingRefFromTargetKey");function Nr(e){return`${_r}#${e}`}a(Nr,"adapterDocsCodePath");function P(e){return typeof e=="string"&&e.length>0?e:void 0}a(P,"text");function as(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}a(as,"positiveInteger");function Al(e,t,n){return ye({ruleId:e,target:P(t.target)??P(n.target)??void 0,fromLayer:P(t.fromLayer)??void 0,toLayer:P(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:P(t.edgeKind)??void 0,capability:P(t.capability)??P(n.capability)??void 0,arkruleId:P(t.arkruleId)??void 0,arkruleSource:P(t.arkruleSource)??void 0})}a(Al,"nextActionForDiagnostic");function Lr(e,t="error",n){let r=P(e.ruleId)??P(e.code)??"ARK_UNKNOWN",o=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,s={...P(e.target)?{target:P(e.target)}:{},...P(e.fromLayer)?{fromLayer:P(e.fromLayer)}:{},...P(e.toLayer)?{toLayer:P(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}:{},...P(e.capability)?{capability:P(e.capability)}:{},...P(e.edgeKind)?{edgeKind:P(e.edgeKind)}:{},...P(e.arkruleId)?{arkruleId:P(e.arkruleId)}:{},...P(e.arkruleSource)?{arkruleSource:P(e.arkruleSource)}:{}},i=n??Cn(e),l=Tr(i);return{ruleId:r,severity:o,message:P(e.message)??r,location:{file:P(e.file)??"<unknown>",line:as(e.line,1),column:as(e.column,1)},evidence:s,nextAction:P(e.nextAction)??Al(r,s,e),findingRef:l,targetKey:i,docsCodePath:Nr(r)}}a(Lr,"toAdapterDiagnostic");function kl(e){let t=e.completeness??"complete",n=e.mode??"lexical-compatibility";if(t==="complete"&&(e.completenessReasons?.length??0)>0)throw new Error("completenessReasons must be empty when completeness is complete.");let r=t==="complete"?[]:e.completenessReasons&&e.completenessReasons.length>0?e.completenessReasons.map(y=>({code:P(y.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:P(y.message)??`Analysis ${t}: required evidence is incomplete.`,...P(y.file)?{file:P(y.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],o={...P(e.policyHash)?{policyHash:P(e.policyHash)}:{},...P(e.resolverIdentity)?{resolverIdentity:P(e.resolverIdentity)}:{},...P(e.factsHash)?{factsHash:P(e.factsHash)}:{},...P(e.candidateTreeHash)?{candidateTreeHash:P(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let y of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!o[y])throw new Error(`${y} is required for resolved ${t} adapter evidence.`)}let s=e.violations??[],i=e.warnings??[],l=xn(s),c=xn(i),u=[...s.map((y,p)=>Lr(y,"error",l[p])),...i.map((y,p)=>Lr(y,"warning",c[p]))],f={schemaVersion:"1.5",completenessReasons:r,diagnostics:u};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...f,mode:n,valid:!1,completeness:t,...o};let y={policyHash:o.policyHash,resolverIdentity:o.resolverIdentity,factsHash:o.factsHash,candidateTreeHash:o.candidateTreeHash};return t==="complete"?{...f,mode:n,valid:e.valid,completeness:t,...y}:{...f,mode:n,valid:!1,completeness:t,...y}}return t==="complete"?{...f,mode:n,valid:e.valid,completeness:t,...o}:{...f,mode:n,valid:!1,completeness:t,...o}}a(kl,"createAdapterResult");var Je=class{static{a(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=a(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 ls=new Je;function cs(e,t){return ls.define(e,t)}a(cs,"defineIntent");function On(){return new Je}a(On,"createIntentRegistry");var ds=ls;var us=["Domain.","Application.","Adapter.","Workflow.","Job.","Presentation.","Reporting.","Metadata.","Security.","Audit.","Observability.","Kernel."];function Pn(e){if(!e||typeof e!="string")return{valid:!1,reason:"Intent name must be a non-empty string"};if(!us.some(n=>e.startsWith(n)))return{valid:!1,reason:`Intent "${e}" must start with one of: ${us.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}}a(Pn,"validateIntentName");var xe=class extends Error{static{a(this,"PolicyViolationError")}violations;constructor(t){let n=t.map(r=>`- ${r.policyName}: ${r.message}`).join(`
6
6
  `);super(`Hard policy violation(s) detected:
7
- ${n}`),this.name="PolicyViolationError",this.violations=t}};var Le=class{static{i(this,"PolicyEngine")}policies=[];constructor(t=[]){for(let n of t)this.add(n)}add(t){if(this.policies.some(n=>n.name===t.name))throw new Error(`Policy "${t.name}" is already registered in this engine.`);this.policies.push(t)}getPolicies(){return[...this.policies]}evaluate(t){let n=[];for(let s of this.policies){let a=s.check(t);if(a!==!0){if(a===!1){n.push({policyName:s.name,severity:s.severity,message:`Policy "${s.name}" was violated.`});continue}if(Array.isArray(a))for(let l of a)n.push({policyName:s.name,severity:s.severity,message:l.message,details:l.details});else n.push({policyName:s.name,severity:s.severity,message:a.message,details:a.details})}}let r=n.filter(s=>s.severity==="hard"),o=n.filter(s=>s.severity==="soft");return{passed:n.length===0,violations:n,hardViolations:r,softViolations:o}}enforce(t){let n=this.evaluate(t);if(n.hardViolations.length>0)throw new we(n.hardViolations);return n}clear(){this.policies.length=0}};function Ye(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(Ye,"definePolicy");function Ba(e){let t=e.indexOf(".");return t>=0?e.slice(0,t):e}i(Ba,"defaultLayerOf");function Wo(e,t){return t.resolveLayer?.(e)??Ba(e)}i(Wo,"resolveLayer");function Wa(e,t,n){return e===n.from&&t===n.to}i(Wa,"matchesRule");function An(e){let t=e.name??"Layer isolation",n=e.severity??"hard";return Ye({name:t,severity:n,tags:["layer"],check:i(r=>{let o=[...(r.edges??[]).filter(a=>a.kind==="declared"||a.kind==="produces").map(a=>({from:a.from,to:a.to})),...(r.relationships??[]).filter(a=>a.kind==="dependsOn").map(a=>({from:a.from,to:a.to}))],s=[];for(let a of o){let l=Wo(a.from,e),c=Wo(a.to,e);for(let u of e.rules)!u.allowed&&Wa(l,c,u)&&s.push({policyName:t,severity:n,message:u.message??`Layer violation: ${a.from} (${l}) must not relate to ${a.to} (${c})`})}return s.length>0?s:!0},"check")})}i(An,"defineLayerPolicy");function kn(e){return e.tags?.includes("layer")??!1}i(kn,"isLayerPolicy");var Ir={layerIsolation(){return Ir.cleanArchitectureMatrix()},cleanArchitectureMatrix(){return An({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 In(e,t={}){return An({name:t.name??`${e.name} layer policy`,severity:t.severity??"hard",rules:e.rules,resolveLayer:e.resolveLayer})}i(In,"defineArchitectureProfilePolicy");function bn(e){return t=>({event:t,relationships:e.intentRegistry?.getAllRelationships(),edges:e.dependencyGraph?.getEdges()})}i(bn,"buildPublishPolicyContext");function zo(e){return Ye(e)}i(zo,"definePublishPolicy");var Xe=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}},Ze=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}},Je=class extends Error{static{i(this,"LayerPolicyContextError")}constructor(){super("Layer/architecture policies require intentRegistry, dependencyGraph, or a custom getPolicyContext. Without graph/registry context, layer policies cannot inspect relationships."),this.name="LayerPolicyContextError"}},Qe=class extends Error{static{i(this,"EventContractViolationError")}intentName;issues;constructor(t,n){super(`Event contract violation for "${t}". Register a matching event contract/version or fix the payload before publishing.`),this.name="EventContractViolationError",this.intentName=t,this.issues=n}},Fe=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}},Ce=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}},et=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 wt(e,t){if(!(!t.strictRegistry&&!t.validateIntentNaming)){if(t.validateIntentNaming){let n=Rn(e);if(!n.valid)throw new Ze(e,n.reason)}if(t.strictRegistry&&t.intentRegistry&&!t.intentRegistry.has(e))throw new Xe(e)}}i(wt,"assertIntentAllowed");function qo(e,t){if(t.requireKnownSource){if(!e.metadata.source||e.metadata.source==="unknown")throw new Fe(e.intent);if(t.intentRegistry&&!t.intentRegistry.has(e.metadata.source))throw new Fe(e.intent,e.metadata.source)}}i(qo,"assertSourceAllowed");function Ct(e,t){if(!t.eventContracts)return;let n=t.eventContracts.validate(e);if(!n.ok&&(t.strictEventContracts||n.contract))throw new Qe(e.intent,n.issues)}i(Ct,"assertContractAllowed");function tt(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}i(tt,"isPlainRecord");function nt(e){return Array.isArray(e)?e.map(nt):tt(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,nt(n)])):e}i(nt,"clonePatchValue");function br(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]=nt(s);continue}if(tt(r[o])&&tt(s)){r[o]=br(r[o],s,a);continue}if(Array.isArray(r[o])&&Array.isArray(s)){r[o]=vr(r[o],s,a);continue}throw new Error(`Interceptor patch cannot overwrite existing ${a}.`)}return r}i(br,"mergeRecordPatch");function vr(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]=nt(o);return}if(tt(r[s])&&tt(o)){r[s]=br(r[s],o,a);return}if(Array.isArray(r[s])&&Array.isArray(o)){r[s]=vr(r[s],o,a);return}throw new Error(`Interceptor patch cannot overwrite existing ${a}.`)}),r}i(vr,"mergeArrayPatch");function Yo(e,t){if(Array.isArray(t)){if(e===void 0)return nt(t);if(!Array.isArray(e))throw new Error("Array interceptor patch requires an array payload.");return vr(e,t)}if(e===void 0)return nt(t);if(!tt(e))throw new Error("Object interceptor patch requires an object payload.");return br(e,t)}i(Yo,"applyPayloadPatch");async function Xo(e,t){if(e.metadata.allowInterception===!1)return e;let n=[...t.interceptorsForIntent(e.intent)],r=e;for(let o of n){let s=[];try{if(await Promise.resolve(o.interceptor({event:r,intercept:i(c=>{s.push(c)},"intercept")})),s.length===0)continue;let a=new Date().toISOString(),l={...r,metadata:{...r.metadata,interceptions:[...r.metadata.interceptions??[],{interceptorId:o.interceptorId,timestamp:a}]}};for(let c of s)l={...l,payload:Yo(l.payload,c),metadata:{...l.metadata}};Ct(l,{eventContracts:t.eventContracts,strictEventContracts:t.strictEventContracts}),r=l,o.lastInterceptedAt=a,t.appendTrace({type:"event.intercepted",timestamp:a,intent:r.intent,correlationId:r.metadata.correlationId,traceId:r.metadata.traceId,spanId:r.metadata.spanId,details:{registrationId:o.registrationId,interceptorId:o.interceptorId,patchesApplied:s.length}}),await t.recordAudit("event.intercepted",r,{registrationId:o.registrationId,interceptorId:o.interceptorId,patchesApplied:s.length})}catch(a){await za(o,r,a,t)}}return r}i(Xo,"applyInterceptors");async function za(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(za,"recordInterceptorError");var Zo=new Map;function Jo(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(Jo,"escapeLiteral");function En(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(En,"normalizeGlobSeparators");function qa(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(qa,"bracesBalanced");function ye(e){let t=Zo.get(e);if(t)return t;let n=En(e),r=qa(n),o="",s=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(o+=Jo(n[l+1]),l+=1):c==="*"?n[l+1]==="*"?n[l+2]==="/"?(o+="(?:.*/)?",l+=2):(o+=".*",l+=1):o+="[^/]*":c==="?"?o+="[^/]":c==="{"&&r?(o+="(?:",s+=1):c==="}"&&r&&s>0?(o+=")",s-=1):c===","&&r&&s>0?o+="|":o+=Jo(c)}let a=new RegExp(`^${o}$`);return Zo.set(e,a),a}i(ye,"globToRegExp");function Ya(e){return En(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}i(Ya,"concreteGlobSegments");function Sr(e,t){let n=En(String(e)),r=Ya(n),o=n.replace(/\*/g,"").length,s=r.length*1e4+o;if(t==null||t==="")return s;let a=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return o;let l=0,c=-1;for(let u of r){let f=-1;for(let y=l;y<a.length;y+=1)if(a[y]===u){f=y;break}if(f<0)return s;c=f,l=f+1}return(c+1)*1e6+r.length*1e4+o}i(Sr,"patternSpecificity");function de(e,t){let n=String(e).split(/[/\\]/).join("/"),r,o=-1;for(let s of t??[])if(!(s.exclude??[]).some(a=>ye(a).test(n))){for(let a of s.patterns??[])if(ye(a).test(n)){let l=Sr(a,n);l>o&&(o=l,r=s.name)}}return r}i(de,"layerForRelativePath");function vn(e,t,n){if(!t?.length)return;let r=n==="stars"?"stars":"path",o=String(e).split(/[/\\]/).filter(Boolean);if(o.length===0)return;let s=new Set;for(let a of t)if(!(typeof a!="string"||a.length===0)){if(ts(a)){let l=Xa(o,a,r);if(l)return l;continue}!a.includes("/")&&!a.includes("\\")&&!a.includes("*")&&s.add(a.toLowerCase())}return el(o,s)}i(vn,"sliceIdForPath");function ts(e){let t=e.split(/[/\\]/).filter(n=>n.length>0);return t.length<2||t[0]==="*"||t[0]==="**"?!1:t.some(n=>n==="*")}i(ts,"isAnchoredSliceEntry");function Xa(e,t,n){let r=t.split(/[/\\]/).filter(s=>s.length>0).map(s=>s.toLowerCase()),o=ss(e,r[0]??"");for(let s of o){let a=Za(e,r,s,n);if(a)return a}}i(Xa,"anchoredSliceId");function Za(e,t,n,r="path"){let o=[],s=-1,a=n;for(let l=0;l<t.length;l+=1){let c=t[l];if(c==="*"){if(a>=e.length-1){for(let u=l;u<t.length;u+=1)if(t[u]!=="*")return;break}o.push(e[a].toLowerCase()),a+=1;continue}if(c==="**"||a>=e.length||e[a].toLowerCase()!==c)return;o.push(e[a].toLowerCase()),s=o.length-1,a+=1}if(o.length!==0)return r==="stars"?s<0?void 0:o.slice(s).join("/"):o.join("/")}i(Za,"bindAnchoredSlice");function ns(e){let t=[];for(let n of e??[]){if(!n||n.sliceIdentity!=="stars")continue;let r=new Map,o=new Map;for(let s of n.sliceFolders??[]){if(typeof s!="string"||s.length===0)continue;let a=Ja(s);if(!a)continue;let l=s.split(/[/\\]/).filter(f=>f.length>0).join("/").toLowerCase(),c=o.get(a)??new Set;if(c.has(l))continue;c.add(l),o.set(a,c);let u=r.get(a)??[];u.push(s),r.set(a,u)}for(let[s,a]of r)a.length<2||t.push({from:n.from,to:n.to,stem:s,paths:a,message:Qa(n.from,n.to,a,s)})}return t}i(ns,"sliceIdentityCollisions");function Ja(e){if(!ts(e))return;let t=e.split(/[/\\]/).filter(o=>o.length>0).map(o=>o.toLowerCase()),n=-1;for(let o=0;o<t.length;o+=1){let s=t[o]??"";if(s==="**")return;s!=="*"&&(n=o)}if(n<0)return;let r=t.slice(n);if(!r.some((o,s)=>s>0&&o!=="*"))return r.join("/")}i(Ja,"starsIdentityStem");function Qa(e,t,n,r){let o=n.length===2?`${n[0]} and ${n[1]}`:`${n.slice(0,-1).join(", ")}, and ${n[n.length-1]}`;return`${e} \u2192 ${t}: sliceIdentity "stars" gives one slice id to ${o}. They bind as ${r}.`}i(Qa,"formatSliceIdentityCollision");function el(e,t){if(t.size!==0){for(let n=0;n<e.length-1;n+=1)if(t.has(e[n].toLowerCase())&&!(n+1>=e.length-1))return`${e[n].toLowerCase()}/${e[n+1].toLowerCase()}`}}i(el,"bareSliceId");function tl(e){let t=new Set;for(let n of e??[]){let o=En(String(n)).split("/").filter(Boolean);for(let s=0;s<o.length;s+=1){let a=o[s];if((a==="**"||a==="*")&&s>0){let l=o[s-1];l&&!l.includes("*")&&!l.includes("{")&&!l.includes("}")&&t.add(l)}}}return[...t]}i(tl,"inferSliceFoldersFromPatterns");function rs(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 tl(r?.patterns)}i(rs,"resolveSliceFolders");function Qo(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}i(Qo,"normalizeSegments");function os(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}i(os,"trimTrailingSlashes");var nl=["src","app"];function ss(e,t){let n=(e[0]??"").toLowerCase(),r=t.toLowerCase();return nl.includes(n)&&r!==n?[0,1]:[0]}i(ss,"anchorOffsets");function rl(e){let t=os(e.replace(/^[./]+/,""));return t==="*"||t==="**"}i(rl,"isBlanketRoot");function Er(e,t){if(!e||!t?.length)return!1;let n=String(e).split(/[/\\]/).join("/"),r=n.toLowerCase(),o=Qo(n);for(let s of t){if(typeof s!="string"||s.length===0||rl(s))continue;if(s.includes("*")){let c=os(s.toLowerCase());if(ye(c).test(r)||ye(`${c}/**`).test(r))return!0;continue}let a=Qo(s);if(a.length===0)continue;let l=ss(o,a[0]??"");for(let c of l){if(c+a.length>o.length)continue;let u=!0;for(let f=0;f<a.length;f+=1)if(o[c+f]!==a[f]){u=!1;break}if(u)return!0}}return!1}i(Er,"pathUnderSharedRoot");function es(e,t){let n=String(e).split(/[/\\]/).filter(Boolean).join("/").toLowerCase();if(!n)return!1;let r=t.toLowerCase();return n===r?!0:!n.includes("/")&&r.endsWith(`/${n}`)}i(es,"sliceMatchesDeclaration");function ol(e,t,n){return!e?.length||!t||!n?!1:e.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&es(r.from,t)&&es(r.to,n))}i(ol,"crossSliceEdgeAllowed");function sl(e){if(!e.fromPath)return{denied:!0,reason:"missing-path"};if(e.folderCount<=0)return{denied:!0,reason:"no-slice-folders"};let t=!!e.fromSlice||e.fromShared===!0;if(!e.toPath)return t?e.fromSlice?{denied:!0,reason:"missing-path"}:{denied:!1}:{denied:!0,reason:"unclassifiable-path"};let n=!!e.toSlice||e.toShared===!0;return!t||!n?{denied:!0,reason:"unclassifiable-path"}:e.sharedImportsSlice==="deny"&&e.fromShared===!0&&e.toSlice&&!e.fromSlice?{denied:!0,reason:"shared-imports-slice"}:!e.fromSlice||!e.toSlice?{denied:!1}:e.fromSlice===e.toSlice?{denied:!1}:e.crossSliceAllowed?{denied:!1}:{denied:!0,reason:"cross-slice"}}i(sl,"peerIsolationDecision");function rt(e,t){switch(e){case"cross-slice":return`cross-slice edge ${t.fromSlice??"?"} \u2192 ${t.toSlice??"?"}. Extract the shared code, use events/ports across slices, or declare the edge in the rule's allowedCrossSlice.`;case"shared-imports-slice":return`shared root imports slice ${t.toSlice??"?"} (${t.fromPath??"?"} \u2192 ${t.toPath??"?"}). The wall is direct-only.`;case"unclassifiable-path":{let n=[t.fromSlice?void 0:t.fromPath,t.toSlice?void 0:t.toPath].filter(o=>!!o);return`unclassifiable path${n.length>0?` (${n.join(", ")})`:""} \u2014 ArkGate cannot place it in a slice, so it cannot prove this is not a cross-slice edge. Move it into a slice, or declare its root in the rule's sharedRoots.`}case"no-slice-folders":return"no slice folders \u2014 peerIsolation is on but no slice folder resolves from the rule or the layer patterns. Set sliceFolders on the rule.";default:return"no path evidence for this edge \u2014 peerIsolation needs the importer and importee paths."}}i(rt,"peerIsolationDenyExplanation");function ot(e,t,n,r){return $e(e,t,n,r)?.rule}i(ot,"findDeniedEdgeRule");function $e(e,t,n,r){for(let o of e??[])if(!(o.from!==t||o.to!==n)&&o.allowed===!1){if(o.peerIsolation){let s=r?.fromPath,a=r?.toPath,l=rs(o,t,r?.layers),c=s?vn(s,l,o.sliceIdentity):void 0,u=a?vn(a,l,o.sliceIdentity):void 0,f=sl({fromPath:s,toPath:a,folderCount:l.length,fromSlice:c,toSlice:u,fromShared:!c&&Er(s,o.sharedRoots),toShared:!u&&Er(a,o.sharedRoots),crossSliceAllowed:ol(o.allowedCrossSlice,c,u),sharedImportsSlice:o.sharedImportsSlice});if(f.denied)return{rule:o,peerIsolationReason:f.reason,fromSlice:c,toSlice:u};continue}if(t!==n)return{rule:o}}}i($e,"findDeniedEdgeDecision");function is(e,t,n,r){let o=r?.fromPath,s=r?.toPath;if(!(!o||!s))for(let a of e??[]){if(a.from!==t||a.to!==n||a.allowed!==!1||!a.peerIsolation||a.sharedImportsSlice==="deny")continue;let l=rs(a,t,r?.layers),c=vn(o,l,a.sliceIdentity),u=vn(s,l,a.sliceIdentity);if(!(c||!u)&&Er(o,a.sharedRoots))return{fromPath:o,toPath:s,toSlice:u}}}i(is,"findSharedImportsSliceBridge");async function as(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=ot(r.rules,o,s);if(!a)return;let l=t.mode,c=a.message??`Observed layer violation: "${n}" (${o}) must not produce "${e.intent}" (${s}).`,u={source:n,intent:e.intent,fromLayer:o,toLayer:s,severity:l,message:c,rule:a};if(t.appendTrace({type:"layer.observedViolation",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:u}),await t.recordAudit("layer.observedViolation",e,u),l==="hard")throw new et(n,e.intent,o,s,c)}i(as,"assertObservedLayerFlowAllowed");async function ls(e,t){let n=t.getPolicyContext(e),r;try{r=t.policyEngine.enforce(n)}catch(o){throw o instanceof we&&(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(ls,"enforcePublishPolicy");function il(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(il,"appendHistory");function xt(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(xt,"appendTrace");async function Sn(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){xt(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(Sn,"recordAudit");async function cs(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."};xt(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 Sn(e,"event.rawPublish",t,n)}i(cs,"recordRawPublishDiagnostic");async function ds(e,t,n,r){let o={event:t,publishedAt:new Date().toISOString(),subscribersNotified:n};return il(e,o),await e.eventBuffer?.enqueue(t,r),xt(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 Sn(e,"event.published",t,{subscribersNotified:n}),o}i(ds,"recordSuccessfulPublish");function wr(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(wr,"enrichMetadata");var us=0;function al(){return us+=1,`interceptor-${Date.now()}-${us}`}i(al,"nextInterceptorRegistrationId");var st=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 Le(t.policies)),(this.policyEngine?.getPolicies()??t.policies??[]).some(kn)&&!t.intentRegistry&&!t.dependencyGraph&&!t.getPolicyContext)throw new Je;t.getPolicyContext?this.getPolicyContext=t.getPolicyContext:t.intentRegistry||t.dependencyGraph?this.getPolicyContext=bn({intentRegistry:t.intentRegistry,dependencyGraph:t.dependencyGraph}):this.getPolicyContext=r=>({event:r})}async publish(t,n,r,o){await this.dispatch(t,n,r,o)}async dispatch(t,n,r,o={}){let s=o.notifySubscribers!==!1,a=o.awaitHandlers!==!1,l=o.runOnPublish!==!1,c,u=typeof t!="function";if(u){let p=t,g=r??n??{};c={...p,metadata:wr(p.metadata,g,this.recording.instanceId)}}else{let p=t,g=n,d=r??{},m=p(g);c={...m,metadata:wr(m.metadata,d,this.recording.instanceId)}}u&&this.strictRegistry&&await cs(this.recording,c),wt(c.intent,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),qo(c,{requireKnownSource:this.requireKnownSource,intentRegistry:this.intentRegistry}),Ct(c,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),c=await Xo(c,{interceptorsForIntent:i(p=>this.interceptorsByIntent.get(p)??[],"interceptorsForIntent"),eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts,appendTrace:i(p=>this.appendTrace(p),"appendTrace"),recordAudit:i((p,g,d)=>this.recordAudit(p,g,d),"recordAudit")}),Ct(c,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),await as(c,{mode:this.enforceObservedLayerFlowMode,architectureProfile:this.architectureProfile,appendTrace:i(p=>this.appendTrace(p),"appendTrace"),recordAudit:i((p,g,d)=>this.recordAudit(p,g,d),"recordAudit")}),this.dependencyGraph?.registerEventFlow(c.metadata.source,c.intent);let f=[...this.subscriptionsByIntent.get(c.intent)??[]];this.policyEngine&&await ls(c,{policyEngine:this.policyEngine,getPolicyContext:this.getPolicyContext,appendTrace:i(p=>this.appendTrace(p),"appendTrace"),recordAudit:i((p,g,d)=>this.recordAudit(p,g,d),"recordAudit"),onSoftViolation:this.onSoftViolation,safeHook:i((p,g,d)=>this.safeHook(p,g,d),"safeHook")}),await ds(this.recording,c,s?f.length:0,o.tx);let y=(async()=>{s&&await Promise.all(f.map(p=>this.invokeHandler(p,c))),l&&this.onPublish&&await this.safeHook(()=>this.onPublish(c),"onPublish",c)})();return a?await y:y.then(void 0,()=>{}),c}createPublisher(t){let n=typeof t=="string"?t:t.name;return wt(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 Ce(n,s.source);await this.publish(r,o,{...s,source:n},a)},"publish")}}subscribe(t,n){let r=typeof t=="string"?t:t.name;wt(r,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let o={intentName:r,handler:n};this.subscriptions.push(o);let s=this.subscriptionsByIntent.get(r)??[];return s.push(o),this.subscriptionsByIntent.set(r,s),()=>{let a=this.subscriptions.indexOf(o);a>=0&&this.subscriptions.splice(a,1);let l=this.subscriptionsByIntent.get(r);if(!l)return;let c=l.indexOf(o);c>=0&&l.splice(c,1),l.length===0&&this.subscriptionsByIntent.delete(r)}}registerInterceptor(t,n,r){let o=typeof t=="string"?t:t.name;wt(o,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let s={registrationId:al(),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){xt(this.recording,t)}async recordAudit(t,n,r){await Sn(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 ps(e){return new st(e)}i(ps,"createEventBus");function ll(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(ll,"formatStandardSchemaPath");function cl(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(cl,"actualType");function dl(e,t){return e?`${e}.${t}`:t}i(dl,"formatPath");function fs(e,t,n,r,o){let s=cl(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}gs(e,t.fields,r,o,n)}t.type==="array"&&t.items&&Array.isArray(e)&&e.forEach((a,l)=>{fs(a,t.items,`${n}[${l}]`,r,o)})}i(fs,"validateSchemaField");function gs(e,t,n,r,o){for(let[s,a]of Object.entries(t)){let l=dl(o,s),c=e[s];if(c===void 0){a.required&&r.push({intent:n.intent,version:n.version,field:l,message:"Required field is missing."});continue}fs(c,a,l,n,r)}}i(gs,"validateObjectSchema");var Ot=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(gs(s,r.schema,r,o),r.allowAdditionalFields===!1)for(let a of Object.keys(s))r.schema[a]||o.push({intent:t.intent,version:r.version,field:a,message:"Additional field is not allowed by event contract."})}if(r.standardSchema){let a=r.standardSchema["~standard"].validate(t.payload);if(a instanceof Promise)o.push({intent:t.intent,version:r.version,message:"Standard Schema validator returned a Promise; event contract validation is synchronous."});else if(a.issues)for(let l of a.issues)o.push({intent:t.intent,version:r.version,field:ll(l.path),message:l.message})}return{ok:o.length===0,contract:r,issues:o}}clear(){this.contracts.clear()}key(t,n){return`${t}@${n}`}};function wn(){return new Ot}i(wn,"createEventContractRegistry");var ms=0;function ul(){return ms+=1,`outbox-${Date.now()}-${ms}`}i(ul,"nextOutboxId");function ys(e){return{...e,event:{...e.event,metadata:{...e.event.metadata}}}}i(ys,"cloneRecord");var Me=class{static{i(this,"InMemoryEventBuffer")}records=new Map;async enqueue(t){let n=new Date().toISOString(),r={id:ul(),event:t,status:"pending",attempts:0,createdAt:n,updatedAt:n};return this.records.set(r.id,r),ys(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(ys)}async clear(){this.records.clear()}},hs=Me;function Cr(e){return`${e.from}->${e.to}`}i(Cr,"flowKey");function Rs(e){let t=new Set,n=[];for(let r of e){let o=Cr(r);t.has(o)||(t.add(o),n.push(r))}return n}i(Rs,"uniqueFlows");function As(e,t){let n=new Set(t.map(Cr));return e.filter(r=>!n.has(Cr(r)))}i(As,"difference");function Cn(e){let t=e.registry,n=e.eventBus,r=e.graph;return{report(){let o=t?t.getAllRelationships().filter(m=>m.kind==="produces").map(m=>({from:m.from,to:m.to})):[],s=o.length>0||!r?[]:r.getEdges().filter(m=>m.kind==="produces").map(m=>({from:m.from,to:m.to})),a=n?.getHistory().map(m=>({from:m.event.metadata.source,to:m.event.intent}))??[],l=a.length>0||!r?[]:r.getEdges().filter(m=>m.kind==="observed").map(m=>({from:m.from,to:m.to})),c=Rs([...o,...s]),u=Rs([...a,...l]),f=u.filter(m=>!m.from||m.from==="unknown"),y=t?Array.from(new Set(u.map(m=>m.from).filter(m=>m&&m!=="unknown"&&!t.has(m)))):[],p=t?Array.from(new Set(u.map(m=>m.to).filter(m=>!t.has(m)))):[],g=new Set(u.flatMap(m=>[m.from,m.to])),d=t?t.list().map(m=>m.name).filter(m=>!g.has(m)):[];return{generatedAt:new Date().toISOString(),declaredProductions:c,observedProductions:u,declaredButUnobserved:As(c,u),observedButUndeclared:As(u.filter(m=>m.from!=="unknown"),c),unknownSources:f,unregisteredObservedSources:y,unregisteredObservedIntents:p,registeredButNeverObserved:d}}}}i(Cn,"createObservabilityReporter");function ks(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(ks,"createArkTestHarness");var Is=0;function pl(){return Is+=1,`audit-${Date.now()}-${Is}`}i(pl,"createAuditId");function fl(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(fl,"matchesQuery");var Pt=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=>fl(r,t));return t.limit===void 0?[...n]:n.slice(-t.limit)}clear(){this.records.length=0}},xn=class{constructor(t){this.store=t}store;static{i(this,"AuditTrailImpl")}async record(t){let n={id:pl(),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 On(e={}){return new xn(e.store??new Pt(e.maxRecords))}i(On,"createAuditTrail");var Pn=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
7
+ ${n}`),this.name="PolicyViolationError",this.violations=t}};var $e=class{static{a(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 i=s.check(t);if(i!==!0){if(i===!1){n.push({policyName:s.name,severity:s.severity,message:`Policy "${s.name}" was violated.`});continue}if(Array.isArray(i))for(let l of i)n.push({policyName:s.name,severity:s.severity,message:l.message,details:l.details});else n.push({policyName:s.name,severity:s.severity,message:i.message,details:i.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 xe(n.hardViolations);return n}clear(){this.policies.length=0}};function Qe(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}}a(Qe,"definePolicy");function Il(e){let t=e.indexOf(".");return t>=0?e.slice(0,t):e}a(Il,"defaultLayerOf");function ps(e,t){return t.resolveLayer?.(e)??Il(e)}a(ps,"resolveLayer");function bl(e,t,n){return e===n.from&&t===n.to}a(bl,"matchesRule");function _n(e){let t=e.name??"Layer isolation",n=e.severity??"hard";return Qe({name:t,severity:n,tags:["layer"],check:a(r=>{let o=[...(r.edges??[]).filter(i=>i.kind==="declared"||i.kind==="produces").map(i=>({from:i.from,to:i.to})),...(r.relationships??[]).filter(i=>i.kind==="dependsOn").map(i=>({from:i.from,to:i.to}))],s=[];for(let i of o){let l=ps(i.from,e),c=ps(i.to,e);for(let u of e.rules)!u.allowed&&bl(l,c,u)&&s.push({policyName:t,severity:n,message:u.message??`Layer violation: ${i.from} (${l}) must not relate to ${i.to} (${c})`})}return s.length>0?s:!0},"check")})}a(_n,"defineLayerPolicy");function Tn(e){return e.tags?.includes("layer")??!1}a(Tn,"isLayerPolicy");var Dr={layerIsolation(){return Dr.cleanArchitectureMatrix()},cleanArchitectureMatrix(){return _n({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 Nn(e,t={}){return _n({name:t.name??`${e.name} layer policy`,severity:t.severity??"hard",rules:e.rules,resolveLayer:e.resolveLayer})}a(Nn,"defineArchitectureProfilePolicy");function Ln(e){return t=>({event:t,relationships:e.intentRegistry?.getAllRelationships(),edges:e.dependencyGraph?.getEdges()})}a(Ln,"buildPublishPolicyContext");function fs(e){return Qe(e)}a(fs,"definePublishPolicy");var et=class extends Error{static{a(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}},tt=class extends Error{static{a(this,"InvalidIntentNameError")}intentName;reason;constructor(t,n){super(`Invalid intent name "${t}": ${n}`),this.name="InvalidIntentNameError",this.intentName=t,this.reason=n}},nt=class extends Error{static{a(this,"LayerPolicyContextError")}constructor(){super("Layer/architecture policies require intentRegistry, dependencyGraph, or a custom getPolicyContext. Without graph/registry context, layer policies cannot inspect relationships."),this.name="LayerPolicyContextError"}},rt=class extends Error{static{a(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}},Me=class extends Error{static{a(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}},Oe=class extends Error{static{a(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}},ot=class extends Error{static{a(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 Lt(e,t){if(!(!t.strictRegistry&&!t.validateIntentNaming)){if(t.validateIntentNaming){let n=Pn(e);if(!n.valid)throw new tt(e,n.reason)}if(t.strictRegistry&&t.intentRegistry&&!t.intentRegistry.has(e))throw new et(e)}}a(Lt,"assertIntentAllowed");function gs(e,t){if(t.requireKnownSource){if(!e.metadata.source||e.metadata.source==="unknown")throw new Me(e.intent);if(t.intentRegistry&&!t.intentRegistry.has(e.metadata.source))throw new Me(e.intent,e.metadata.source)}}a(gs,"assertSourceAllowed");function Dt(e,t){if(!t.eventContracts)return;let n=t.eventContracts.validate(e);if(!n.ok&&(t.strictEventContracts||n.contract))throw new rt(e.intent,n.issues)}a(Dt,"assertContractAllowed");function st(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}a(st,"isPlainRecord");function it(e){return Array.isArray(e)?e.map(it):st(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,it(n)])):e}a(it,"clonePatchValue");function Fr(e,t,n="payload"){let r={...e};for(let[o,s]of Object.entries(t)){let i=`${n}.${o}`;if(!(o in r)||r[o]===void 0){r[o]=it(s);continue}if(st(r[o])&&st(s)){r[o]=Fr(r[o],s,i);continue}if(Array.isArray(r[o])&&Array.isArray(s)){r[o]=$r(r[o],s,i);continue}throw new Error(`Interceptor patch cannot overwrite existing ${i}.`)}return r}a(Fr,"mergeRecordPatch");function $r(e,t,n="payload"){let r=[...e];return t.forEach((o,s)=>{let i=`${n}[${s}]`;if(s>=r.length||r[s]===void 0){r[s]=it(o);return}if(st(r[s])&&st(o)){r[s]=Fr(r[s],o,i);return}if(Array.isArray(r[s])&&Array.isArray(o)){r[s]=$r(r[s],o,i);return}throw new Error(`Interceptor patch cannot overwrite existing ${i}.`)}),r}a($r,"mergeArrayPatch");function ms(e,t){if(Array.isArray(t)){if(e===void 0)return it(t);if(!Array.isArray(e))throw new Error("Array interceptor patch requires an array payload.");return $r(e,t)}if(e===void 0)return it(t);if(!st(e))throw new Error("Object interceptor patch requires an object payload.");return Fr(e,t)}a(ms,"applyPayloadPatch");async function ys(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:a(c=>{s.push(c)},"intercept")})),s.length===0)continue;let i=new Date().toISOString(),l={...r,metadata:{...r.metadata,interceptions:[...r.metadata.interceptions??[],{interceptorId:o.interceptorId,timestamp:i}]}};for(let c of s)l={...l,payload:ms(l.payload,c),metadata:{...l.metadata}};Dt(l,{eventContracts:t.eventContracts,strictEventContracts:t.strictEventContracts}),r=l,o.lastInterceptedAt=i,t.appendTrace({type:"event.intercepted",timestamp:i,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(i){await Sl(o,r,i,t)}}return r}a(ys,"applyInterceptors");async function Sl(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})}a(Sl,"recordInterceptorError");var hs="4.8.22",Rs=new Map;function As(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(As,"escapeLiteral");function $n(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}a($n,"normalizeGlobSeparators");function vl(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}a(vl,"bracesBalanced");function he(e){let t=Rs.get(e);if(t)return t;let n=$n(e),r=vl(n),o="",s=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(o+=As(n[l+1]),l+=1):c==="*"?n[l+1]==="*"?n[l+2]==="/"?(o+="(?:.*/)?",l+=2):(o+=".*",l+=1):o+="[^/]*":c==="?"?o+="[^/]":c==="{"&&r?(o+="(?:",s+=1):c==="}"&&r&&s>0?(o+=")",s-=1):c===","&&r&&s>0?o+="|":o+=As(c)}let i=new RegExp(`^${o}$`);return Rs.set(e,i),i}a(he,"globToRegExp");function El(e){return $n(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}a(El,"concreteGlobSegments");function Hr(e,t){let n=$n(String(e)),r=El(n),o=n.replace(/\*/g,"").length,s=r.length*1e4+o;if(t==null||t==="")return s;let i=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return o;let l=0,c=-1;for(let u of r){let f=-1;for(let y=l;y<i.length;y+=1)if(i[y]===u){f=y;break}if(f<0)return s;c=f,l=f+1}return(c+1)*1e6+r.length*1e4+o}a(Hr,"patternSpecificity");function fe(e,t){let n=String(e).split(/[/\\]/).join("/"),r,o=-1;for(let s of t??[])if(!(s.exclude??[]).some(i=>he(i).test(n))){for(let i of s.patterns??[])if(he(i).test(n)){let l=Hr(i,n);l>o&&(o=l,r=s.name)}}return r}a(fe,"layerForRelativePath");function Kr(e,t,n){if(!t?.length)return;let r=n==="stars"?"stars":"path",o=String(e).split(/[/\\]/).filter(Boolean);if(o.length===0)return;let s=new Set;for(let i of t)if(!(typeof i!="string"||i.length===0)){if(Ss(i)){let l=wl(o,i,r);if(l)return l;continue}!i.includes("/")&&!i.includes("\\")&&!i.includes("*")&&s.add(i.toLowerCase())}return Pl(o,s)}a(Kr,"sliceIdForPath");function Ss(e){let t=e.split(/[/\\]/).filter(n=>n.length>0);return t.length<2||t[0]==="*"||t[0]==="**"?!1:t.some(n=>n==="*")}a(Ss,"isAnchoredSliceEntry");function wl(e,t,n){let r=t.split(/[/\\]/).filter(s=>s.length>0).map(s=>s.toLowerCase()),o=Es(e,r[0]??"");for(let s of o){let i=Cl(e,r,s,n);if(i)return i}}a(wl,"anchoredSliceId");function Cl(e,t,n,r="path"){let o=[],s=-1,i=n;for(let l=0;l<t.length;l+=1){let c=t[l];if(c==="*"){if(i>=e.length-1){for(let u=l;u<t.length;u+=1)if(t[u]!=="*")return;break}o.push(e[i].toLowerCase()),i+=1;continue}if(c==="**"||i>=e.length||e[i].toLowerCase()!==c)return;o.push(e[i].toLowerCase()),s=o.length-1,i+=1}if(o.length!==0)return r==="stars"?s<0?void 0:o.slice(s).join("/"):o.join("/")}a(Cl,"bindAnchoredSlice");function vs(e){let t=[];for(let n of e??[]){if(!n||n.sliceIdentity!=="stars")continue;let r=new Map,o=new Map;for(let s of n.sliceFolders??[]){if(typeof s!="string"||s.length===0)continue;let i=xl(s);if(!i)continue;let l=s.split(/[/\\]/).filter(f=>f.length>0).join("/").toLowerCase(),c=o.get(i)??new Set;if(c.has(l))continue;c.add(l),o.set(i,c);let u=r.get(i)??[];u.push(s),r.set(i,u)}for(let[s,i]of r)i.length<2||t.push({from:n.from,to:n.to,stem:s,paths:i,message:Ol(n.from,n.to,i,s)})}return t}a(vs,"sliceIdentityCollisions");function xl(e){if(!Ss(e))return;let t=e.split(/[/\\]/).filter(o=>o.length>0).map(o=>o.toLowerCase()),n=-1;for(let o=0;o<t.length;o+=1){let s=t[o]??"";if(s==="**")return;s!=="*"&&(n=o)}if(n<0)return;let r=t.slice(n);if(!r.some((o,s)=>s>0&&o!=="*"))return r.join("/")}a(xl,"starsIdentityStem");function Ol(e,t,n,r){let o=n.length===2?`${n[0]} and ${n[1]}`:`${n.slice(0,-1).join(", ")}, and ${n[n.length-1]}`;return`${e} \u2192 ${t}: sliceIdentity "stars" gives one slice id to ${o}. They bind as ${r}.`}a(Ol,"formatSliceIdentityCollision");function Pl(e,t){if(t.size!==0){for(let n=0;n<e.length-1;n+=1)if(t.has(e[n].toLowerCase())&&!(n+1>=e.length-1))return`${e[n].toLowerCase()}/${e[n+1].toLowerCase()}`}}a(Pl,"bareSliceId");function _l(e){let t=new Set;for(let n of e??[]){let o=$n(String(n)).split("/").filter(Boolean);for(let s=0;s<o.length;s+=1){let i=o[s];if((i==="**"||i==="*")&&s>0){let l=o[s-1];l&&!l.includes("*")&&!l.includes("{")&&!l.includes("}")&&t.add(l)}}}return[...t]}a(_l,"inferSliceFoldersFromPatterns");function Gr(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 _l(r?.patterns)}a(Gr,"resolveSliceFolders");function ks(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}a(ks,"normalizeSegments");function Mt(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}a(Mt,"trimTrailingSlashes");var Tl=["src","app"];function Es(e,t){let n=(e[0]??"").toLowerCase(),r=t.toLowerCase();return Tl.includes(n)&&r!==n?[0,1]:[0]}a(Es,"anchorOffsets");function Nl(e){let t=Mt(e.replace(/^[./]+/,""));return t==="*"||t==="**"}a(Nl,"isBlanketRoot");function Ft(e,t){if(!e||!t?.length)return!1;let n=String(e).split(/[/\\]/).join("/"),r=n.toLowerCase(),o=ks(n);for(let s of t){if(typeof s!="string"||s.length===0||Nl(s))continue;if(s.includes("*")){let c=Mt(s.toLowerCase());if(he(c).test(r)||he(`${c}/**`).test(r))return!0;continue}let i=ks(s);if(i.length===0)continue;let l=Es(o,i[0]??"");for(let c of l){if(c+i.length>o.length)continue;let u=!0;for(let f=0;f<i.length;f+=1)if(o[c+f]!==i[f]){u=!1;break}if(u)return!0}}return!1}a(Ft,"pathUnderSharedRoot");function Is(e,t){let n=String(e).split(/[/\\]/).filter(Boolean).join("/").toLowerCase();if(!n)return!1;let r=t.toLowerCase();return n===r?!0:!n.includes("/")&&r.endsWith(`/${n}`)}a(Is,"sliceMatchesDeclaration");function Ll(e,t,n){return!e?.length||!t||!n?!1:e.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&Is(r.from,t)&&Is(r.to,n))}a(Ll,"crossSliceEdgeAllowed");function Dl(e){if(!e.fromPath)return{denied:!0,reason:"missing-path"};if(e.folderCount<=0)return{denied:!0,reason:"no-slice-folders"};let t=!!e.fromSlice||e.fromShared===!0;if(!e.toPath)return t?e.fromSlice?{denied:!0,reason:"missing-path"}:{denied:!1}:{denied:!0,reason:"unclassifiable-path"};let n=!!e.toSlice||e.toShared===!0;return!t||!n?{denied:!0,reason:"unclassifiable-path"}:e.sharedImportsSlice==="deny"&&e.fromShared===!0&&e.toSlice&&!e.fromSlice?{denied:!0,reason:"shared-imports-slice"}:!e.fromSlice||!e.toSlice?{denied:!1}:e.fromSlice===e.toSlice?{denied:!1}:e.crossSliceAllowed?{denied:!1}:{denied:!0,reason:"cross-slice"}}a(Dl,"peerIsolationDecision");function ws(e){return Mt(e.trim().replace(/\\/g,"/")).toLowerCase()}a(ws,"aliasGlobPattern");function Fl(e,t){let n=ws(e);if(!n||n==="*"||n==="**")return!1;let r=String(t).replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase(),o=Mr(r),s=he(n);return s.test(r)||o!==r&&s.test(o)}a(Fl,"aliasGlobMatches");function $l(e){let t=ws(e).split("/").filter(Boolean);return t.length<2||t.some(n=>n.includes("*")||n==="."||n==="..")?null:{universeId:t.slice(0,-1).join("/"),childId:t.join("/")}}a($l,"splitAliasTarget");function Ml(e,t){for(let n of t.childSlices?.sliceAliases??[])if(!(!n||typeof n.from!="string"||typeof n.to!="string")&&Fl(n.from,e))return $l(n.to);return null}a(Ml,"firstSliceAlias");function at(e,t,n){if(!e)return{};let r=n??t.sliceFolders,o=Kr(e,r?[...r]:void 0,t.sliceIdentity),s=Dn(e,o,t.childSlices);if(o||s.childId||s.mismatched)return s.childId?{universeId:o,childId:s.childId}:{universeId:o};let i=Ml(e,t);return i?{universeId:i.universeId,childId:i.childId}:{}}a(at,"resolveGovernedSlice");function Hl(e,t){switch(e){case"cross-slice":return`cross-slice edge ${t.fromSlice??"?"} \u2192 ${t.toSlice??"?"}. Extract the shared code, use events/ports across slices, or declare the edge in the rule's allowedCrossSlice.`;case"shared-imports-slice":return`shared root imports slice ${t.toSlice??"?"} (${t.fromPath??"?"} \u2192 ${t.toPath??"?"}). The wall is direct-only.`;case"unclassifiable-path":{let n=[t.fromSlice?void 0:t.fromPath,t.toSlice?void 0:t.toPath].filter(o=>!!o);return`unclassifiable path${n.length>0?` (${n.join(", ")})`:""} \u2014 ArkGate cannot place it in a slice, so it cannot prove this is not a cross-slice edge. Move it into a slice, or declare its root in the rule's sharedRoots.`}case"no-slice-folders":return"no slice folders \u2014 peerIsolation is on but no slice folder resolves from the rule or the layer patterns. Set sliceFolders on the rule.";default:return"no path evidence for this edge \u2014 peerIsolation needs the importer and importee paths."}}a(Hl,"peerIsolationDenyExplanation");function Kl(e,t){return`cross-parent slice ${e??"?"} \u2192 ${t??"?"}. The child wall cannot allow another universe.`}a(Kl,"crossParentExplanation");function Gl(e,t,n){return`cross-sibling slice ${e} \u2192 ${t} inside ${n}.`}a(Gl,"crossSiblingExplanation");function Ul(e){return`universe common imports child ${e}. parentMayImportChild is off.`}a(Ul,"parentImportsChildExplanation");function $t(e){if(!e)return;let t=e.split("/").filter(Boolean);return t.length>0?t[t.length-1]:void 0}a($t,"universePairLabel");function Vl(e){return String(e).split(/[/\\]/).filter(Boolean).slice(0,-1)}a(Vl,"directorySegments");function jl(e,t){if(!t?.length)return!1;let n=new Set;for(let r of t)typeof r=="string"&&r.length>0&&n.add(r.toLowerCase());return n.size===0?!1:Vl(e).some(r=>n.has(r.toLowerCase()))}a(jl,"pathHasCommonFolder");function Dn(e,t,n){if(!e||!n?.sliceFolders?.length)return{};if(jl(e,n.commonFolders))return{};let r=Kr(e,n.sliceFolders,n.sliceIdentity);if(!r||!t)return{};let o=r.toLowerCase(),s=t.toLowerCase();return o===s?{}:o.startsWith(`${s}/`)?{childId:r}:{mismatched:{childId:r,universeId:t}}}a(Dn,"resolveChildSliceId");function Bl(e){return Mt(e.trim().replace(/\\/g,"/")).toLowerCase()}a(Bl,"siblingEntryKey");function Mr(e){return e.replace(/^(?:src|app)\//,"")}a(Mr,"stripSrcOrApp");function Wl(e,t){let n=e.replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase(),r=Mr(t);if(!r)return!1;let o=Mr(n);return n===r||n.startsWith(`${r}/`)||o===r||o.startsWith(`${r}/`)}a(Wl,"pathUnderSubtree");function zl(e,t,n){if(!t||!n?.length)return!1;let r=t.toLowerCase();for(let o of n){if(typeof o!="string")continue;let s=Bl(o);if(!(!s||s.includes("*"))&&(r===s||e&&Wl(e,s)))return!0}return!1}a(zl,"importerInEnforcedSubtree");function ql(e,t,n){return e==null||e==="deny"?!1:e==="advisory"?!0:e.default==="deny"?!1:!zl(t,n,e.enforce)}a(ql,"siblingCrossingAdvisory");function Fn(e){if(typeof e!="string")return null;let t=Mt(e.trim().replace(/\\/g,"/")).toLowerCase();if(!t.includes("/"))return null;let n=t.split("/");for(let r of n)if(r.length===0||r==="."||r===".."||r.includes("*")&&r!=="*")return null;return n}a(Fn,"childSlicePatternSegments");function bs(e,t){let n=Fn(e),r=Fn(t);if(!n||!r||n.length!==r.length)return!1;for(let o=0;o<n.length;o+=1){let s=n[o];if(s!=="*"&&s!==r[o])return!1}return!0}a(bs,"childSlicePatternMatches");function Yl(e,t,n){if(!e?.length)return!1;for(let r of e)if(!(!r||typeof r.from!="string"||typeof r.to!="string")&&bs(r.from,t)&&bs(r.to,n))return!0;return!1}a(Yl,"childCrossSliceAllowed");function Xl(e,t){let n=Fn(e),r=Fn(t);if(!n||!r)return!1;let o=n.slice(0,-1),s=r.slice(0,-1);if(o.length!==s.length)return!0;for(let i=0;i<o.length;i+=1){let l=o[i],c=s[i];if(l==="*"||c==="*"||l!==c)return!0}return!1}a(Xl,"childAllowanceSpansUniverses");function Zl(e){let t=Dl({fromPath:e.fromPath,toPath:e.toPath,folderCount:e.folderCount,fromSlice:e.fromSlice,toSlice:e.toSlice,fromShared:e.fromShared,toShared:e.toShared,crossSliceAllowed:e.crossSliceAllowed,sharedImportsSlice:e.rule.sharedImportsSlice});if(t.denied){let i=!!e.rule.childSlices&&t.reason==="cross-slice";return{crossing:t.reason==="cross-slice"?"cross-parent":"fail-closed",decision:"deny",...i?{reasonId:"CROSS_PARENT_SLICE"}:{},explanation:i?Kl(e.fromSlice,e.toSlice):Hl(t.reason??"missing-path",{fromPath:e.fromPath,toPath:e.toPath,fromSlice:e.fromSlice,toSlice:e.toSlice}),peerIsolationReason:t.reason,fromUniverse:e.fromSlice,toUniverse:e.toSlice}}let n=e.rule.childSlices;if(!n||!e.fromSlice||!e.toSlice||e.fromSlice!==e.toSlice||!e.toPath)return{crossing:"none",decision:"allow",fromUniverse:e.fromSlice,toUniverse:e.toSlice};let r=e.fromChild??Dn(e.fromPath,e.fromSlice,n).childId,o=e.toChild??Dn(e.toPath,e.toSlice,n).childId,s={crossing:"none",decision:"allow",fromUniverse:e.fromSlice,toUniverse:e.toSlice};return r&&o&&r!==o?Yl(n.allowedCrossSlice,r,o)?s:{crossing:"cross-sibling",decision:ql(n.siblings,e.fromPath,r)?"advisory":"deny",reasonId:"CROSS_SIBLING_SLICE",explanation:Gl(r,o,e.fromSlice),fromUniverse:e.fromSlice,toUniverse:e.toSlice}:!r&&o&&n.parentMayImportChild!==!0?{crossing:"parent-imports-child",decision:"deny",explanation:Ul(o),fromUniverse:e.fromSlice,toUniverse:e.toSlice}:s}a(Zl,"evaluateNestedSliceWall");function lt(e){let t=e.verdict.explanation;if(e.surface==="intent"){let n=e.defaultMessage??`${e.fromLayer} must not reference ${e.toLayer} intent.`;return e.verdict.reasonId&&t?`${n} ${t}`:t&&e.verdict.peerIsolationReason!=="cross-slice"?`${n} ${t}`:e.ruleMessage?t?`${e.ruleMessage} (${t})`:e.ruleMessage:n}if(e.ruleMessage)return t?`${e.ruleMessage} (${t})`:e.ruleMessage;if(t){let n=e.kind??"import";return`${e.fromLayer} must not ${n} another slice of ${e.toLayer} (${e.fromPath} \u2192 ${e.toPath}): ${t}`}return`${e.fromLayer} must not ${e.kind??"import"} ${e.toLayer}.`}a(lt,"composeSliceDenialMessage");function He(e){if(!e||e.decision==="allow")return{};let t=$t(e.fromUniverse),n=$t(e.toUniverse);return{...e.reasonId?{reasonId:e.reasonId}:{},...e.reasonId&&t&&n?{universeFrom:t,universeTo:n}:{},...e.decision==="advisory"?{failsStrict:!1,severity:"warning"}:{}}}a(He,"sliceFindingExtras");function Cs(e,t){let n=[],r=!1,o=new Set,s=new Set;for(let i of e??[])if(i?.childSlices&&(r||(r=!0,n.push({ruleId:"CONFIG_CHILD_SLICES_VERSION",failsStrict:!1,message:`childSlices needs an arkgate newer than ${hs}. Version ${hs} and older reject the key because the rule schema sets additionalProperties: false.`})),!!i.peerIsolation)){for(let l of t){let c=Kr(l,i.sliceFolders,i.sliceIdentity),u=Dn(l,c,i.childSlices);if(!u.mismatched)continue;let f=`${i.from}\0${i.to}\0${u.mismatched.universeId}\0${u.mismatched.childId}`;o.has(f)||(o.add(f),n.push({ruleId:"CONFIG_CHILD_SLICE_EXTENDS",failsStrict:!1,fromLayer:i.from,toLayer:i.to,path:l,message:`${i.from} \u2192 ${i.to}: child id ${u.mismatched.childId} does not extend universe id ${u.mismatched.universeId} (${l}).`}))}for(let l of i.childSlices.allowedCrossSlice??[]){if(!l||typeof l.from!="string"||typeof l.to!="string"||!Xl(l.from,l.to))continue;let c=`${l.from.trim().toLowerCase()}\0${l.to.trim().toLowerCase()}`;s.has(c)||(s.add(c),n.push({ruleId:"CONFIG_CHILD_SLICE_CROSS_UNIVERSE",failsStrict:!1,fromLayer:i.from,toLayer:i.to,message:`childSlices.allowedCrossSlice ${l.from} \u2192 ${l.to} cannot cross the universe wall. The universe wall still denies that edge.`}))}}return n}a(Cs,"childSliceConfigFindings");function Mn(e,t,n,r){return Pe(e,t,n,r)?.rule}a(Mn,"findDeniedEdgeRule");function Pe(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,i=r?.toPath,l=Gr(o,t,r?.layers),c=at(s,o,l),u=at(i,o,l),f=c.universeId,y=u.universeId,p=Zl({rule:o,fromPath:s,toPath:i,folderCount:l.length,fromSlice:f,toSlice:y,fromChild:c.childId,toChild:u.childId,fromShared:!f&&Ft(s,o.sharedRoots),toShared:!y&&Ft(i,o.sharedRoots),crossSliceAllowed:Ll(o.allowedCrossSlice,f,y)});if(p.decision!=="allow")return{rule:o,peerIsolationReason:p.peerIsolationReason,fromSlice:f,toSlice:y,sliceVerdict:p};continue}if(t!==n)return{rule:o}}}a(Pe,"findDeniedEdgeDecision");function xs(e,t,n,r){let o=r?.fromPath,s=r?.toPath;if(!(!o||!s))for(let i of e??[]){if(i.from!==t||i.to!==n||i.allowed!==!1||!i.peerIsolation||i.sharedImportsSlice==="deny")continue;let l=Gr(i,t,r?.layers),c=at(o,i,l).universeId,u=at(s,i,l).universeId;if(!(c||!u)&&Ft(o,i.sharedRoots))return{fromPath:o,toPath:s,toSlice:u}}}a(xs,"findSharedImportsSliceBridge");function Os(e,t,n){return Gr(e,t,n)}a(Os,"peerSliceFolders");async function Ps(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 i=Mn(r.rules,o,s);if(!i)return;let l=t.mode,c=i.message??`Observed layer violation: "${n}" (${o}) must not produce "${e.intent}" (${s}).`,u={source:n,intent:e.intent,fromLayer:o,toLayer:s,severity:l,message:c,rule:i};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:u}),await t.recordAudit("layer.observedViolation",e,u),l==="hard")throw new ot(n,e.intent,o,s,c)}a(Ps,"assertObservedLayerFlowAllowed");async function _s(e,t){let n=t.getPolicyContext(e),r;try{r=t.policyEngine.enforce(n)}catch(o){throw o instanceof xe&&(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))}a(_s,"enforcePublishPolicy");function Jl(e,t){e.history.push(t),e.maxHistorySize!==void 0&&e.history.length>e.maxHistorySize&&e.history.splice(0,e.history.length-e.maxHistorySize)}a(Jl,"appendHistory");function Ht(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{}}a(Ht,"appendTrace");async function Hn(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){Ht(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)}})}}a(Hn,"recordAudit");async function Ts(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."};Ht(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 Hn(e,"event.rawPublish",t,n)}a(Ts,"recordRawPublishDiagnostic");async function Ns(e,t,n,r){let o={event:t,publishedAt:new Date().toISOString(),subscribersNotified:n};return Jl(e,o),await e.eventBuffer?.enqueue(t,r),Ht(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 Hn(e,"event.published",t,{subscribersNotified:n}),o}a(Ns,"recordSuccessfulPublish");function Ur(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}}a(Ur,"enrichMetadata");var Ls=0;function Ql(){return Ls+=1,`interceptor-${Date.now()}-${Ls}`}a(Ql,"nextInterceptorRegistrationId");var ct=class{static{a(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 $e(t.policies)),(this.policyEngine?.getPolicies()??t.policies??[]).some(Tn)&&!t.intentRegistry&&!t.dependencyGraph&&!t.getPolicyContext)throw new nt;t.getPolicyContext?this.getPolicyContext=t.getPolicyContext:t.intentRegistry||t.dependencyGraph?this.getPolicyContext=Ln({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,i=o.awaitHandlers!==!1,l=o.runOnPublish!==!1,c,u=typeof t!="function";if(u){let p=t,g=r??n??{};c={...p,metadata:Ur(p.metadata,g,this.recording.instanceId)}}else{let p=t,g=n,d=r??{},m=p(g);c={...m,metadata:Ur(m.metadata,d,this.recording.instanceId)}}u&&this.strictRegistry&&await Ts(this.recording,c),Lt(c.intent,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),gs(c,{requireKnownSource:this.requireKnownSource,intentRegistry:this.intentRegistry}),Dt(c,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),c=await ys(c,{interceptorsForIntent:a(p=>this.interceptorsByIntent.get(p)??[],"interceptorsForIntent"),eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts,appendTrace:a(p=>this.appendTrace(p),"appendTrace"),recordAudit:a((p,g,d)=>this.recordAudit(p,g,d),"recordAudit")}),Dt(c,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),await Ps(c,{mode:this.enforceObservedLayerFlowMode,architectureProfile:this.architectureProfile,appendTrace:a(p=>this.appendTrace(p),"appendTrace"),recordAudit:a((p,g,d)=>this.recordAudit(p,g,d),"recordAudit")}),this.dependencyGraph?.registerEventFlow(c.metadata.source,c.intent);let f=[...this.subscriptionsByIntent.get(c.intent)??[]];this.policyEngine&&await _s(c,{policyEngine:this.policyEngine,getPolicyContext:this.getPolicyContext,appendTrace:a(p=>this.appendTrace(p),"appendTrace"),recordAudit:a((p,g,d)=>this.recordAudit(p,g,d),"recordAudit"),onSoftViolation:this.onSoftViolation,safeHook:a((p,g,d)=>this.safeHook(p,g,d),"safeHook")}),await Ns(this.recording,c,s?f.length:0,o.tx);let y=(async()=>{s&&await Promise.all(f.map(p=>this.invokeHandler(p,c))),l&&this.onPublish&&await this.safeHook(()=>this.onPublish(c),"onPublish",c)})();return i?await y:y.then(void 0,()=>{}),c}createPublisher(t){let n=typeof t=="string"?t:t.name;return Lt(n,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),{source:n,publish:a(async(r,o,s={},i)=>{if(s.source&&s.source!==n)throw new Oe(n,s.source);await this.publish(r,o,{...s,source:n},i)},"publish")}}subscribe(t,n){let r=typeof t=="string"?t:t.name;Lt(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 i=this.subscriptions.indexOf(o);i>=0&&this.subscriptions.splice(i,1);let l=this.subscriptionsByIntent.get(r);if(!l)return;let c=l.indexOf(o);c>=0&&l.splice(c,1),l.length===0&&this.subscriptionsByIntent.delete(r)}}registerInterceptor(t,n,r){let o=typeof t=="string"?t:t.name;Lt(o,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let s={registrationId:Ql(),interceptorId:r??o,intentName:o,interceptor:n,createdAt:new Date().toISOString()};this.interceptors.push(s);let i=this.interceptorsByIntent.get(o)??[];return i.push(s),this.interceptorsByIntent.set(o,i),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){Ht(this.recording,t)}async recordAudit(t,n,r){await Hn(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 Ds(e){return new ct(e)}a(Ds,"createEventBus");function ec(e){if(!(!e||e.length===0))return e.map(t=>typeof t=="object"&&t!==null&&"key"in t?String(t.key):String(t)).join(".")}a(ec,"formatStandardSchemaPath");function tc(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"}a(tc,"actualType");function nc(e,t){return e?`${e}.${t}`:t}a(nc,"formatPath");function Fs(e,t,n,r,o){let s=tc(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(i=>Object.is(i,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}$s(e,t.fields,r,o,n)}t.type==="array"&&t.items&&Array.isArray(e)&&e.forEach((i,l)=>{Fs(i,t.items,`${n}[${l}]`,r,o)})}a(Fs,"validateSchemaField");function $s(e,t,n,r,o){for(let[s,i]of Object.entries(t)){let l=nc(o,s),c=e[s];if(c===void 0){i.required&&r.push({intent:n.intent,version:n.version,field:l,message:"Required field is missing."});continue}Fs(c,i,l,n,r)}}a($s,"validateObjectSchema");var Kt=class{static{a(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($s(s,r.schema,r,o),r.allowAdditionalFields===!1)for(let i of Object.keys(s))r.schema[i]||o.push({intent:t.intent,version:r.version,field:i,message:"Additional field is not allowed by event contract."})}if(r.standardSchema){let i=r.standardSchema["~standard"].validate(t.payload);if(i instanceof Promise)o.push({intent:t.intent,version:r.version,message:"Standard Schema validator returned a Promise; event contract validation is synchronous."});else if(i.issues)for(let l of i.issues)o.push({intent:t.intent,version:r.version,field:ec(l.path),message:l.message})}return{ok:o.length===0,contract:r,issues:o}}clear(){this.contracts.clear()}key(t,n){return`${t}@${n}`}};function Kn(){return new Kt}a(Kn,"createEventContractRegistry");var Ms=0;function rc(){return Ms+=1,`outbox-${Date.now()}-${Ms}`}a(rc,"nextOutboxId");function Hs(e){return{...e,event:{...e.event,metadata:{...e.event.metadata}}}}a(Hs,"cloneRecord");var Ke=class{static{a(this,"InMemoryEventBuffer")}records=new Map;async enqueue(t){let n=new Date().toISOString(),r={id:rc(),event:t,status:"pending",attempts:0,createdAt:n,updatedAt:n};return this.records.set(r.id,r),Hs(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(Hs)}async clear(){this.records.clear()}},Ks=Ke;function Vr(e){return`${e.from}->${e.to}`}a(Vr,"flowKey");function Gs(e){let t=new Set,n=[];for(let r of e){let o=Vr(r);t.has(o)||(t.add(o),n.push(r))}return n}a(Gs,"uniqueFlows");function Us(e,t){let n=new Set(t.map(Vr));return e.filter(r=>!n.has(Vr(r)))}a(Us,"difference");function Gn(e){let t=e.registry,n=e.eventBus,r=e.graph;return{report(){let o=t?t.getAllRelationships().filter(m=>m.kind==="produces").map(m=>({from:m.from,to:m.to})):[],s=o.length>0||!r?[]:r.getEdges().filter(m=>m.kind==="produces").map(m=>({from:m.from,to:m.to})),i=n?.getHistory().map(m=>({from:m.event.metadata.source,to:m.event.intent}))??[],l=i.length>0||!r?[]:r.getEdges().filter(m=>m.kind==="observed").map(m=>({from:m.from,to:m.to})),c=Gs([...o,...s]),u=Gs([...i,...l]),f=u.filter(m=>!m.from||m.from==="unknown"),y=t?Array.from(new Set(u.map(m=>m.from).filter(m=>m&&m!=="unknown"&&!t.has(m)))):[],p=t?Array.from(new Set(u.map(m=>m.to).filter(m=>!t.has(m)))):[],g=new Set(u.flatMap(m=>[m.from,m.to])),d=t?t.list().map(m=>m.name).filter(m=>!g.has(m)):[];return{generatedAt:new Date().toISOString(),declaredProductions:c,observedProductions:u,declaredButUnobserved:Us(c,u),observedButUndeclared:Us(u.filter(m=>m.from!=="unknown"),c),unknownSources:f,unregisteredObservedSources:y,unregisteredObservedIntents:p,registeredButNeverObserved:d}}}}a(Gn,"createObservabilityReporter");function Vs(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()}}}a(Vs,"createArkTestHarness");var js=0;function oc(){return js+=1,`audit-${Date.now()}-${js}`}a(oc,"createAuditId");function sc(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)}a(sc,"matchesQuery");var Gt=class{constructor(t){this.maxRecords=t}maxRecords;static{a(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=>sc(r,t));return t.limit===void 0?[...n]:n.slice(-t.limit)}clear(){this.records.length=0}},Un=class{constructor(t){this.store=t}store;static{a(this,"AuditTrailImpl")}async record(t){let n={id:oc(),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 Vn(e={}){return new Un(e.store??new Gt(e.maxRecords))}a(Vn,"createAuditTrail");var jn=class{static{a(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)}
9
9
  `}let n=new Set(this.edges.flatMap(r=>[r.from,r.to]));for(let r of this.nodes.keys())n.has(r)||(t+=` ${this.safeId(r)}
10
- `);return t.trim()}toLayerMermaid(t){let n=new Map;for(let s of this.nodes.keys()){let a=t.resolveLayer(s)??"Unclassified",l=n.get(a)??[];l.push(s),n.set(a,l)}let r=`flowchart TD
11
- `;for(let s of t.layers){let a=n.get(s.name)??[];if(a.length!==0){r+=` subgraph ${this.safeId(s.name)}[${s.name}]
12
- `;for(let l of a)r+=` ${this.safeId(l)}[${l}]
10
+ `);return t.trim()}toLayerMermaid(t){let n=new Map;for(let s of this.nodes.keys()){let i=t.resolveLayer(s)??"Unclassified",l=n.get(i)??[];l.push(s),n.set(i,l)}let r=`flowchart TD
11
+ `;for(let s of t.layers){let i=n.get(s.name)??[];if(i.length!==0){r+=` subgraph ${this.safeId(s.name)}[${s.name}]
12
+ `;for(let l of i)r+=` ${this.safeId(l)}[${l}]
13
13
  `;r+=` end
14
14
  `}}let o=n.get("Unclassified")??[];if(o.length>0){r+=` subgraph Unclassified[Unclassified]
15
15
  `;for(let s of o)r+=` ${this.safeId(s)}[${s}]
16
16
  `;r+=` end
17
- `}for(let s of this.edges){let a=s.kind?`|${s.kind}|`:"";r+=` ${this.safeId(s.from)} -->${a} ${this.safeId(s.to)}
18
- `}return r.trim()}detectViolations(t=[]){let n=[],r=this.findSimpleCycles();r.length>0&&n.push(`Cycle detected: ${r.map(o=>o.join("->")).join(", ")}`);for(let o of t)try{let s=o(this.edges);s&&s.length&&n.push(...s)}catch(s){n.push(`Rule error: ${s.message}`)}return n}ensureNode(t){this.nodes.has(t)||this.nodes.set(t,{id:t})}addEdge(t){this.edges.some(r=>r.from===t.from&&r.to===t.to&&r.kind===t.kind)||this.edges.push(t)}findSimpleCycles(){let t=new Map;for(let l of this.edges)t.has(l.from)||t.set(l.from,[]),t.get(l.from).push(l.to);let n=[],r=new Set,o=[],s=i(l=>{r.add(l),o.push(l);for(let c of t.get(l)||[])if(!r.has(c))s(c);else if(o.includes(c)){let u=o.indexOf(c),f=o.slice(u).concat(c);n.push(f)}o.pop()},"dfs");for(let l of t.keys())r.has(l)||s(l);let a=new Set(n.map(l=>l.join("->")));return Array.from(a).map(l=>l.split("->"))}safeId(t){return t.replace(/[^a-zA-Z0-9_]/g,"_")}};function _n(){return new Pn}i(_n,"createDependencyGraph");function Tn(e,t,n={}){let r=n.requireRegisteredTargets??!1;for(let o of e.getAllRelationships())r&&!e.has(o.to)||(o.kind==="dependsOn"?t.registerDependency(o.from,o.to,"declared"):t.registerDependency(o.from,o.to,"produces"))}i(Tn,"syncRegistryToGraph");var He={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},bs={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...He,default:[]},kernelRoots:{...He},managedLayers:{...He,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},vs={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...He,default:[]},managedLayers:{...He,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...He,default:[]},appliesTo:{...He,default:[]}}};function _t(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(_t,"isObject");function Es(e){let t=new Set;if(!Array.isArray(e.layers))return t;for(let n of e.layers)_t(n)&&typeof n.name=="string"&&n.name.length>0&&t.add(n.name);return t}i(Es,"declaredLayerNames");function Ss(e){if(!_t(e))return e;let t={mode:e.mode===void 0?"advisory":e.mode,compositionRoots:e.compositionRoots===void 0?[]:e.compositionRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,requireDeclarations:e.requireDeclarations===void 0?!0:e.requireDeclarations};return e.kernelRoots!==void 0&&(t.kernelRoots=e.kernelRoots),e.ignoreDirectNewForErrors!==void 0&&(t.ignoreDirectNewForErrors=e.ignoreDirectNewForErrors),{...e,...t}}i(Ss,"defaultedArkRun");function ws(e){if(!_t(e))return e;let t=typeof e.maxXiKeys=="number"&&e.maxXiKeys>0?e.maxXiKeys:7;return{...e,mode:e.mode===void 0?"advisory":e.mode,planeRoots:e.planeRoots===void 0?[]:e.planeRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,maxXiKeys:t,xiKeys:e.xiKeys===void 0?[]:e.xiKeys}}i(ws,"defaultedArkOrder");function Cs(e,t){let n=e.arkRun;if(n===void 0||!_t(n))return;let r=Es(e),o=n.managedLayers;if(Array.isArray(o)&&o.forEach((s,a)=>{typeof s=="string"&&s.length>0&&!r.has(s)&&t.push({path:`$.arkRun.managedLayers[${a}]`,message:`layer ${JSON.stringify(s)} is not declared in layers[]`})}),n.mode==="enforced"){let s=n.kernelRoots??n.compositionRoots;(!Array.isArray(s)||s.length===0)&&t.push({path:n.kernelRoots!==void 0?"$.arkRun.kernelRoots":"$.arkRun.compositionRoots",message:"ARKRUN_MISSING_ROOT: enforced mode requires at least one kernel root"}),(!Array.isArray(o)||o.length===0)&&t.push({path:"$.arkRun.managedLayers",message:"enforced mode requires at least one managed layer"})}}i(Cs,"validateArkRunExtra");function xs(e,t){let n=e.arkOrder;if(n===void 0||!_t(n))return;let r=Es(e),o=n.managedLayers;if(Array.isArray(o)&&o.forEach((s,a)=>{typeof s=="string"&&s.length>0&&!r.has(s)&&t.push({path:`$.arkOrder.managedLayers[${a}]`,message:`layer ${JSON.stringify(s)} is not declared in layers[]`})}),n.mode==="enforced"){let s=n.planeRoots;(!Array.isArray(s)||s.length===0)&&t.push({path:"$.arkOrder.planeRoots",message:"ARKORDER_MISSING_PLANE: enforced mode requires at least one plane root"}),(!Array.isArray(o)||o.length===0)&&t.push({path:"$.arkOrder.managedLayers",message:"enforced mode requires at least one managed layer"})}}i(xs,"validateArkOrderExtra");function Nn(e){if(typeof e!="string")return null;let t=e.trim().replace(/^@/,"").toLowerCase();return t.length>0?t:null}i(Nn,"normalizeStewardId");function Os(e){let t=Nn(e);return!t||xr(t)||t.includes(" ")||t.includes("@")?!1:/^(?!-)[a-z0-9-]{1,39}(?<!-)$/.test(t)}i(Os,"isGitHubHandle");function gl(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();return!t.includes("@")||t.includes(" ")||xr(t)?!1:/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}i(gl,"isGitHubEmail");function ml(e){if(typeof e!="string")return null;let t=e.trim().match(/^(?:\d+\+)?([^@]+)@users\.noreply\.github\.com$/i);return t&&Os(t[1])?Nn(t[1]):null}i(ml,"githubHandleFromEmail");function Ps(e){let t=ml(e);if(t)return t;let n=Nn(e);return!n||xr(n)?null:Os(n)||gl(n)?n:null}i(Ps,"canonicalStewardId");var yl=/bot\b|\[bot\]|dependabot|renovate|github-actions|imgbot|codecov/i;function xr(e){let t=Nn(e);return!t||yl.test(t)}i(xr,"isAutomationAuthor");var ae="1.3",hl=["public","auth","admin","internal"];function Rl(e){return e?.optional===!0||e?.reserved===!0||e?.allowEmpty===!0}i(Rl,"isFutureHouseLayer");function Al(e){let t=e&&typeof e=="object"?e.owners:void 0;if(!Array.isArray(t)||t.length===0)return;let n=t.filter(r=>typeof r=="string"&&r.length>0);return n.length>0?n:void 0}i(Al,"layerOwnersList");function Ns(e){return e?.requireLayerOwners!==!0||!Array.isArray(e.layers)?[]:e.layers.filter(t=>!Rl(t)&&!Al(t)).map(t=>t.name)}i(Ns,"layersMissingRequiredOwners");function Ds(e){return`Add a GitHub handle or email to ${e}'s owners in ark.config.json (/ark-adopt).`}i(Ds,"missingLayerOwnersNextAction");var Ln="https://unpkg.com/arkgate@4/schemas/ark.config.schema.json",_s=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],kl=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Il(){let e=[];for(let t of _s)for(let n of _s)t===n||kl.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}i(Il,"createDefaultRules");var Fn=Il(),Or=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"},{from:"1.1",to:"1.2"},{from:"1.2",to:"1.3"}],re={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Ts={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Ln,title:"ArkGate architecture contract",description:"Versioned contract consumed identically by ArkGate CLI, MCP, and ESLint surfaces.",type:"object",additionalProperties:!1,required:["$schema","schemaVersion","include","layers","rules"],properties:{$schema:{type:"string",minLength:1,default:Ln,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:ae,default:ae},name:{type:"string",minLength:1},include:{...re,minItems:1,default:["src"]},exclude:{...re,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:Fn,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...re,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},coverage:{$ref:"#/$defs/coverage"},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},arkRun:{$ref:"#/$defs/arkRun"},arkOrder:{$ref:"#/$defs/arkOrder"},stewards:{...re,default:[]},requireLayerOwners:{type:"boolean"}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...re,minItems:1},exclude:re,intentPrefixes:re,description:{type:"string",minLength:1},trustBoundary:{type:"string",enum:[...hl]},owners:{...re,minItems:1},forbiddenGlobals:re,capabilities:{type:"object",additionalProperties:!1,properties:{deny:{type:"array",uniqueItems:!0,items:{type:"string",enum:["network","filesystem","clock","randomness","environment","process","persistence"]}}}},pure:{type:"boolean"},mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"},reserved:{type:"boolean"},allowEmpty:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...re,minItems:1},sliceIdentity:{type:"string",enum:["path","stars"],description:"How a starred sliceFolders prefix is named. Absent and path keep today's ids (every literal and star binding). stars keeps the last literal plus the star bindings, so parallel trees share one feature id. Bare names are unchanged."},sharedRoots:{...re,minItems:1},allowedCrossSlice:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}},sharedImportsSlice:{type:"string",enum:["deny"]}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}},coverage:{type:"object",additionalProperties:!1,description:"Invariant coverage scan controls. testGlobs replaces the built-in test-name heuristic; maxFiles raises or lowers the evidence file budget and also bounds structural-hint preload for orchestration-only, thin-adapter, and writes-via-aggregate (default 400; there is no arkrules.hintBudget); coverageRoots declares where the project runs its tests, so a covering test found outside them is reported instead of silently certifying an invariant. When any invariant is enforced, missing coverageRoots fails closed.",properties:{testGlobs:{...re,minItems:1},maxFiles:{type:"integer",minimum:1,description:"Evidence file budget (default 400) and structural-hint preload cap for orchestration-only, thin-adapter, and writes-via-aggregate. Raise this when hinted/governed counts show truncated sensors. There is no separate arkrules.hintBudget."},coverageRoots:{...re,minItems:1}}},arkRun:bs,arkOrder:vs}},he=class extends Error{static{i(this,"ArkConfigValidationError")}issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
17
+ `}for(let s of this.edges){let i=s.kind?`|${s.kind}|`:"";r+=` ${this.safeId(s.from)} -->${i} ${this.safeId(s.to)}
18
+ `}return r.trim()}detectViolations(t=[]){let n=[],r=this.findSimpleCycles();r.length>0&&n.push(`Cycle detected: ${r.map(o=>o.join("->")).join(", ")}`);for(let o of t)try{let s=o(this.edges);s&&s.length&&n.push(...s)}catch(s){n.push(`Rule error: ${s.message}`)}return n}ensureNode(t){this.nodes.has(t)||this.nodes.set(t,{id:t})}addEdge(t){this.edges.some(r=>r.from===t.from&&r.to===t.to&&r.kind===t.kind)||this.edges.push(t)}findSimpleCycles(){let t=new Map;for(let l of this.edges)t.has(l.from)||t.set(l.from,[]),t.get(l.from).push(l.to);let n=[],r=new Set,o=[],s=a(l=>{r.add(l),o.push(l);for(let c of t.get(l)||[])if(!r.has(c))s(c);else if(o.includes(c)){let u=o.indexOf(c),f=o.slice(u).concat(c);n.push(f)}o.pop()},"dfs");for(let l of t.keys())r.has(l)||s(l);let i=new Set(n.map(l=>l.join("->")));return Array.from(i).map(l=>l.split("->"))}safeId(t){return t.replace(/[^a-zA-Z0-9_]/g,"_")}};function Bn(){return new jn}a(Bn,"createDependencyGraph");function Wn(e,t,n={}){let r=n.requireRegisteredTargets??!1;for(let o of e.getAllRelationships())r&&!e.has(o.to)||(o.kind==="dependsOn"?t.registerDependency(o.from,o.to,"declared"):t.registerDependency(o.from,o.to,"produces"))}a(Wn,"syncRegistryToGraph");var Ge={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Bs={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...Ge,default:[]},kernelRoots:{...Ge},managedLayers:{...Ge,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},Ws={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...Ge,default:[]},managedLayers:{...Ge,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...Ge,default:[]},appliesTo:{...Ge,default:[]}}};function Ut(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(Ut,"isObject");function zs(e){let t=new Set;if(!Array.isArray(e.layers))return t;for(let n of e.layers)Ut(n)&&typeof n.name=="string"&&n.name.length>0&&t.add(n.name);return t}a(zs,"declaredLayerNames");function qs(e){if(!Ut(e))return e;let t={mode:e.mode===void 0?"advisory":e.mode,compositionRoots:e.compositionRoots===void 0?[]:e.compositionRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,requireDeclarations:e.requireDeclarations===void 0?!0:e.requireDeclarations};return e.kernelRoots!==void 0&&(t.kernelRoots=e.kernelRoots),e.ignoreDirectNewForErrors!==void 0&&(t.ignoreDirectNewForErrors=e.ignoreDirectNewForErrors),{...e,...t}}a(qs,"defaultedArkRun");function Ys(e){if(!Ut(e))return e;let t=typeof e.maxXiKeys=="number"&&e.maxXiKeys>0?e.maxXiKeys:7;return{...e,mode:e.mode===void 0?"advisory":e.mode,planeRoots:e.planeRoots===void 0?[]:e.planeRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,maxXiKeys:t,xiKeys:e.xiKeys===void 0?[]:e.xiKeys}}a(Ys,"defaultedArkOrder");function Xs(e,t){let n=e.arkRun;if(n===void 0||!Ut(n))return;let r=zs(e),o=n.managedLayers;if(Array.isArray(o)&&o.forEach((s,i)=>{typeof s=="string"&&s.length>0&&!r.has(s)&&t.push({path:`$.arkRun.managedLayers[${i}]`,message:`layer ${JSON.stringify(s)} is not declared in layers[]`})}),n.mode==="enforced"){let s=n.kernelRoots??n.compositionRoots;(!Array.isArray(s)||s.length===0)&&t.push({path:n.kernelRoots!==void 0?"$.arkRun.kernelRoots":"$.arkRun.compositionRoots",message:"ARKRUN_MISSING_ROOT: enforced mode requires at least one kernel root"}),(!Array.isArray(o)||o.length===0)&&t.push({path:"$.arkRun.managedLayers",message:"enforced mode requires at least one managed layer"})}}a(Xs,"validateArkRunExtra");function Zs(e,t){let n=e.arkOrder;if(n===void 0||!Ut(n))return;let r=zs(e),o=n.managedLayers;if(Array.isArray(o)&&o.forEach((s,i)=>{typeof s=="string"&&s.length>0&&!r.has(s)&&t.push({path:`$.arkOrder.managedLayers[${i}]`,message:`layer ${JSON.stringify(s)} is not declared in layers[]`})}),n.mode==="enforced"){let s=n.planeRoots;(!Array.isArray(s)||s.length===0)&&t.push({path:"$.arkOrder.planeRoots",message:"ARKORDER_MISSING_PLANE: enforced mode requires at least one plane root"}),(!Array.isArray(o)||o.length===0)&&t.push({path:"$.arkOrder.managedLayers",message:"enforced mode requires at least one managed layer"})}}a(Zs,"validateArkOrderExtra");function zn(e){if(typeof e!="string")return null;let t=e.trim().replace(/^@/,"").toLowerCase();return t.length>0?t:null}a(zn,"normalizeStewardId");function Js(e){let t=zn(e);return!t||jr(t)||t.includes(" ")||t.includes("@")?!1:/^(?!-)[a-z0-9-]{1,39}(?<!-)$/.test(t)}a(Js,"isGitHubHandle");function ic(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();return!t.includes("@")||t.includes(" ")||jr(t)?!1:/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}a(ic,"isGitHubEmail");function ac(e){if(typeof e!="string")return null;let t=e.trim().match(/^(?:\d+\+)?([^@]+)@users\.noreply\.github\.com$/i);return t&&Js(t[1])?zn(t[1]):null}a(ac,"githubHandleFromEmail");function Qs(e){let t=ac(e);if(t)return t;let n=zn(e);return!n||jr(n)?null:Js(n)||ic(n)?n:null}a(Qs,"canonicalStewardId");var lc=/bot\b|\[bot\]|dependabot|renovate|github-actions|imgbot|codecov/i;function jr(e){let t=zn(e);return!t||lc.test(t)}a(jr,"isAutomationAuthor");var ce="1.3",cc=["public","auth","admin","internal"];function dc(e){return e?.optional===!0||e?.reserved===!0||e?.allowEmpty===!0}a(dc,"isFutureHouseLayer");function uc(e){let t=e&&typeof e=="object"?e.owners:void 0;if(!Array.isArray(t)||t.length===0)return;let n=t.filter(r=>typeof r=="string"&&r.length>0);return n.length>0?n:void 0}a(uc,"layerOwnersList");function ii(e){return e?.requireLayerOwners!==!0||!Array.isArray(e.layers)?[]:e.layers.filter(t=>!dc(t)&&!uc(t)).map(t=>t.name)}a(ii,"layersMissingRequiredOwners");function ai(e){return`Add a GitHub handle or email to ${e}'s owners in ark.config.json (/ark-adopt).`}a(ai,"missingLayerOwnersNextAction");var qn="https://unpkg.com/arkgate@4/schemas/ark.config.schema.json",ei=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],pc=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function fc(){let e=[];for(let t of ei)for(let n of ei)t===n||pc.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}a(fc,"createDefaultRules");var Yn=fc(),Br=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"},{from:"1.1",to:"1.2"},{from:"1.2",to:"1.3"}],ee={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},ti={$schema:"https://json-schema.org/draft/2020-12/schema",$id:qn,title:"ArkGate architecture contract",description:"Versioned contract consumed identically by ArkGate CLI, MCP, and ESLint surfaces.",type:"object",additionalProperties:!1,required:["$schema","schemaVersion","include","layers","rules"],properties:{$schema:{type:"string",minLength:1,default:qn,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:ce,default:ce},name:{type:"string",minLength:1},include:{...ee,minItems:1,default:["src"]},exclude:{...ee,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:Yn,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...ee,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},coverage:{$ref:"#/$defs/coverage"},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},arkRun:{$ref:"#/$defs/arkRun"},arkOrder:{$ref:"#/$defs/arkOrder"},stewards:{...ee,default:[]},requireLayerOwners:{type:"boolean"}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...ee,minItems:1},exclude:ee,intentPrefixes:ee,description:{type:"string",minLength:1},trustBoundary:{type:"string",enum:[...cc]},owners:{...ee,minItems:1},forbiddenGlobals:ee,capabilities:{type:"object",additionalProperties:!1,properties:{deny:{type:"array",uniqueItems:!0,items:{type:"string",enum:["network","filesystem","clock","randomness","environment","process","persistence"]}}}},pure:{type:"boolean"},mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"},reserved:{type:"boolean"},allowEmpty:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...ee,minItems:1},sliceIdentity:{type:"string",enum:["path","stars"],description:"How a starred sliceFolders prefix is named. Absent and path keep today's ids (every literal and star binding). stars keeps the last literal plus the star bindings, so parallel trees share one feature id. Bare names are unchanged."},sharedRoots:{...ee,minItems:1},allowedCrossSlice:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}},sharedImportsSlice:{type:"string",enum:["deny","deny-cross-parent"],description:"deny blocks every shared-root import of a slice. deny-cross-parent leaves that hop as a warning and, in ark-check and CI only, reports a slice that reaches another universe through a shared root. The write hook and ESLint see one edge and do not block it. arkgate 4.8.22 and older reject deny-cross-parent."},childSlices:{type:"object",additionalProperties:!1,required:["sliceFolders"],description:`Optional inner wall under this rule. Absent keeps today's universe wall. sliceFolders names children. commonFolders and flat files are universe common. siblings is "deny" (default), "advisory", or { default, enforce }. parentMayImportChild defaults to false. allowedCrossSlice may use a whole-segment *. It clears only a sibling crossing. Cross-parent has no advisory knob. arkgate 4.8.22 and older reject this key. A build that still rejects unknown childSlices fields rejects allowedCrossSlice at config load. A build that still types siblings as a string enum rejects the object at config load.`,properties:{sliceFolders:{...ee,minItems:1},sliceIdentity:{type:"string",enum:["path","stars"]},commonFolders:{...ee,minItems:1},siblings:{description:'"deny" or "advisory", or { default, enforce } so listed subtrees are errors while the default stays advisory. A string-enum build rejects the object at config load (must be one of deny, advisory).',oneOf:[{type:"string",enum:["deny","advisory"]},{type:"object",additionalProperties:!1,required:["default"],properties:{default:{type:"string",enum:["deny","advisory"]},enforce:{...ee}}}]},parentMayImportChild:{type:"boolean"},sliceAliases:{type:"array",minItems:1,description:"Maps a source path glob onto a child slice id (universe id plus one child segment) so files outside the slice trees take that universe and child for both walls. A bare name, a universe id alone, an unknown universe, and a wildcard in to are rejected. The glob may not overlap a slice folder, and two aliases may not match the same file. Doctor lists each alias as an owed move. A build that rejects unknown childSlices fields fails at config load (unknown field). arkgate 4.8.22 and older reject childSlices.",items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}},allowedCrossSlice:{type:"array",minItems:1,description:"Directed child-slice allowances. * matches one whole path segment (features/projects/*). ** and a partial segment are rejected. A bare name is rejected. This list clears only CROSS_SIBLING_SLICE. It cannot clear CROSS_PARENT_SLICE or CROSS_PARENT_VIA_SHARED. The universe allowedCrossSlice still treats * as a literal. A build that rejects unknown childSlices fields fails at config load (unknown field).",items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}}}}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}},coverage:{type:"object",additionalProperties:!1,description:"Invariant coverage scan controls. testGlobs replaces the built-in test-name heuristic; maxFiles raises or lowers the evidence file budget and also bounds structural-hint preload for orchestration-only, thin-adapter, and writes-via-aggregate (default 400; there is no arkrules.hintBudget); coverageRoots declares where the project runs its tests, so a covering test found outside them is reported instead of silently certifying an invariant. When any invariant is enforced, missing coverageRoots fails closed.",properties:{testGlobs:{...ee,minItems:1},maxFiles:{type:"integer",minimum:1,description:"Evidence file budget (default 400) and structural-hint preload cap for orchestration-only, thin-adapter, and writes-via-aggregate. Raise this when hinted/governed counts show truncated sensors. There is no separate arkrules.hintBudget."},coverageRoots:{...ee,minItems:1}}},arkRun:Bs,arkOrder:Ws}},ke=class extends Error{static{a(this,"ArkConfigValidationError")}issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
19
19
  ${n.map(r=>`- ${r.path}: ${r.message}`).join(`
20
- `)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function Ls(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(Ls,"isObject");function Dn(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}i(Dn,"propertyPath");function it(e){return e===null?"null":Array.isArray(e)?"array":typeof e}i(it,"valueType");function bl(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}i(bl,"resolveSchemaRef");function Tt(e,t,n,r,o){if(t.$ref){let s=bl(t.$ref,r);if(!s){o.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}Tt(e,s,n,r,o);return}if(t.const!==void 0&&!Object.is(e,t.const)){o.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(s=>Object.is(s,e))){o.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!Ls(e)){o.push({path:n,message:`must be an object; received ${it(e)}`});return}let s=t.properties??{};for(let a of t.required??[])e[a]===void 0&&o.push({path:Dn(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in s||o.push({path:Dn(n,a),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let a=t.additionalProperties;for(let l of Object.keys(e))l in s||Tt(e[l],a,Dn(n,l),r,o)}for(let[a,l]of Object.entries(s))e[a]!==void 0&&Tt(e[a],l,Dn(n,a),r,o);return}if(t.type==="array"){if(!Array.isArray(e)){o.push({path:n,message:`must be an array; received ${it(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&o.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let s=e.map(a=>JSON.stringify(a));new Set(s).size!==s.length&&o.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((s,a)=>Tt(s,t.items,`${n}[${a}]`,r,o));return}if(t.type==="string"){if(typeof e!="string"){o.push({path:n,message:`must be a string; received ${it(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&o.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&o.push({path:n,message:`must be a boolean; received ${it(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){o.push({path:n,message:`must be an integer; received ${it(e)}`});return}t.minimum!==void 0&&e<t.minimum&&o.push({path:n,message:`must be at least ${t.minimum}`})}}i(Tt,"validateNode");function vl(e,t){let n=e.layers;Array.isArray(n)&&n.forEach((r,o)=>{if(!r||typeof r!="object"||Array.isArray(r)||!("owners"in r))return;let s=r.owners;Array.isArray(s)&&s.forEach((a,l)=>{typeof a=="string"&&(Ps(a)||t.push({path:`$.layers[${o}].owners[${l}]`,message:"must be a GitHub handle or email (not a display name)"}))})})}i(vl,"validateLayerOwners");function El(e){let t={...e,$schema:e.$schema===void 0?Ln:e.$schema,schemaVersion:e.schemaVersion===void 0?ae:e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?Fn.map(n=>({...n})):e.rules};return e.arkRun!==void 0&&(t.arkRun=Ss(e.arkRun)),e.arkOrder!==void 0&&(t.arkOrder=ws(e.arkOrder)),t}i(El,"defaultedConfig");function Sl(e){return e===ae?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}i(Sl,"migratedFromOf");function wl(){let e=new Set([ae]);for(let t of Or)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}i(wl,"knownInputVersions");function Cl(e,t="ark.config.json"){if(!Ls(e))throw new he(t,[{path:"$",message:`must be an object; received ${it(e)}`}]);let n=wl(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new he(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected ${ae}`}]);if(r!=="unversioned"&&!n.has(r))throw new he(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${ae}`}]);let o=r,s={...e},a=0;for(;o!==ae&&a<Or.length+1;){a+=1;let l=Or.find(c=>c.from===o);if(!l)throw new he(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(o)}; expected ${ae}`}]);o=l.to,s.schemaVersion=o}if(o!==ae)throw new he(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${ae}`}]);return{candidate:El(s),migratedFrom:Sl(r)}}i(Cl,"migrateArkConfig");function Pr(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=Cl(e,t),o=[];if(Tt(n,Ts,"$",Ts,o),Cs(n,o),xs(n,o),vl(n,o),o.length>0)throw new he(t,o);return{config:n,migratedFrom:r}}i(Pr,"loadArkConfigContract");function Fs(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new he(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return Pr(n,t)}i(Fs,"parseArkConfigJson");function $s(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:Ln,schemaVersion:ae};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}i($s,"withArkConfigMetadata");function xl(e){return e.endsWith(".")?e:`${e}.`}i(xl,"normalizePrefix");function Ol(e,t){let n=e.prefixes.length?Math.max(...e.prefixes.map(o=>o.length)):0;return(t.prefixes.length?Math.max(...t.prefixes.map(o=>o.length)):0)-n}i(Ol,"byLongestPrefix");function $n(e){let t=e.layers.map(o=>({...o,prefixes:o.prefixes.map(xl)})),n=[...t].sort(Ol),r=[...e.rules??[]];return{name:e.name,layers:t,rules:r,resolveLayer(o){return t.find(s=>s.match?.(o))?.name??n.find(s=>s.prefixes.some(a=>o.startsWith(a)))?.name}}}i($n,"createArchitectureProfile");function Mn(e,t={}){return $n({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,r)=>({name:n.name,prefixes:n.intentPrefixes??[],description:n.description,trustBoundary:n.trustBoundary,owners:n.owners,order:r+1})),rules:e.rules??[]})}i(Mn,"createArchitectureProfileFromArkConfig");var Pl=[{name:"DomainModel",prefixes:["Domain"],description:"Rich domain model, business rules, and domain events.",order:1},{name:"ApplicationOrchestration",prefixes:["Application"],description:"Use cases and command orchestration.",order:2},{name:"PersistenceAdapters",prefixes:["Adapter.Persistence","Adapter.Repository"],description:"Database, repository, and storage adapters.",order:3},{name:"IntegrationAdapters",prefixes:["Adapter.Integration","Adapter.External"],description:"External systems, APIs, and integration adapters.",order:4},{name:"WorkflowSagaEngine",prefixes:["Workflow"],description:"Sagas, workflows, and long-running processes.",order:5},{name:"BackgroundJobsScheduling",prefixes:["Job"],description:"Background jobs, scheduled work, and async processors.",order:6},{name:"PresentationAdapters",prefixes:["Presentation","Adapter.Presentation","Adapter.Api"],description:"API, UI, controller, and presentation adapters.",order:7},{name:"ReportingReadModels",prefixes:["Reporting"],description:"Read models, projections, and reporting surfaces.",order:8},{name:"ExtensibilityMetadata",prefixes:["Metadata"],description:"Metadata, extensions, and schema contracts.",order:9},{name:"SecurityAuditObservability",prefixes:["Security","Audit","Observability"],description:"Security, audit, and observability concerns.",order:10},{name:"Kernel",prefixes:["Kernel"],description:"Ark-owned governance and kernel signals.",order:11}],at=$n({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:Pl,rules:Fn.map(e=>({...e}))}),_l={DomainModel:["domain"],ApplicationOrchestration:["application","app"],PersistenceAdapters:["adapters/persistence","adapters/repository","repositories","infra/persistence"],IntegrationAdapters:["adapters/integration","adapters/external","integrations"],WorkflowSagaEngine:["workflows","sagas"],BackgroundJobsScheduling:["jobs","schedules"],PresentationAdapters:["presentation","adapters/presentation","adapters/api"],ReportingReadModels:["reporting","read-models","projections"],ExtensibilityMetadata:["metadata","extensions"],SecurityAuditObservability:["security","audit","observability"],Kernel:["kernel"]};function Ms(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return $s({include:e.include??[t],layers:at.layers.map(o=>({name:o.name,patterns:(_l[o.name]??[o.name]).map(s=>`${r}${s}/**`),intentPrefixes:o.prefixes,optional:n})),rules:[...at.rules]})}i(Ms,"createElevenLayerArkConfig");var Hn=class{static{i(this,"MetadataRegistryImpl")}entities=new Map;entity(t,n,r={}){if(this.entities.has(t)&&!r.allowOverwrite)throw new Error(`Entity metadata "${t}" is already registered.`);let o={name:t,fields:{},...n};return this.entities.set(t,o),o}getEntity(t){return this.entities.get(t)}listEntities(){return Array.from(this.entities.values())}findEntitiesByIntent(t){return this.listEntities().filter(n=>n.emits?.includes(t)||n.consumes?.includes(t))}validate(){let t=[];for(let n of this.entities.values()){n.name.trim()||t.push({entity:n.name,message:"Entity name is required."});for(let[r,o]of Object.entries(n.fields))r.trim()||t.push({entity:n.name,field:r,message:"Field name is required."}),(!o.type||typeof o.type!="string")&&t.push({entity:n.name,field:r,message:"Field type must be a non-empty string."}),o.relation&&!this.entities.has(o.relation.entity)&&t.push({entity:n.name,field:r,message:`Related entity "${o.relation.entity}" is not registered.`})}return{ok:t.length===0,issues:t}}toJSON(){return this.listEntities()}};function Kn(){return new Hn}i(Kn,"createMetadataRegistry");function Hs(e,t={}){return{name:e,ownerLayer:t.ownerLayer,intent:t.intent,allowedAdapters:t.allowedAdapters?[...t.allowedAdapters]:void 0}}i(Hs,"definePort");function Ks(e,t,n,r={}){let o=Array.isArray(n)?{...r,requiredKeys:n}:{...n??{}},s=o.requiredKeys;if(s&&s.length>0){let c=s.filter(u=>!Us(t,u));if(c.length>0)throw new Error(`Adapter for port "${e.name}" is missing required members: ${c.join(", ")}`)}let a={name:o.name,layer:o.layer,intent:o.intent,port:e,impl:t},l=_r(a);if(!l.ok)throw new Error(l.issues.map(c=>c.message).join(`
21
- `));return a}i(Ks,"createAdapter");function Gs(e,t=[]){let n=t.filter(r=>!Us(e,r));return n.length===0?{ok:!0}:{ok:!1,missing:n}}i(Gs,"checkContract");function _r(e){let t=e.port.allowedAdapters??[];return t.length===0?{ok:!0,issues:[]}:[e.name,e.intent].filter(o=>typeof o=="string"&&o.length>0).some(o=>t.includes(o))?{ok:!0,issues:[]}:{ok:!1,issues:[{ruleId:"ADAPTER_NOT_ALLOWED_FOR_PORT",port:e.port.name,adapter:e.name??e.intent,message:`Adapter "${e.name??e.intent??"unknown"}" is not allowed for port "${e.port.name}".`}]}}i(_r,"checkAdapterGovernance");function Us(e,t){return e!=null&&(typeof e=="object"||typeof e=="function")&&t in e}i(Us,"hasMember");var Nr=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),Lr=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Fr=Object.freeze(Object.keys(Lr).sort()),Tr=Object.freeze({fs:"filesystem","node:fs":"filesystem","fs/promises":"filesystem","node:fs/promises":"filesystem","fs-extra":"filesystem","graceful-fs":"filesystem",memfs:"filesystem",chokidar:"filesystem",http:"network",https:"network",http2:"network",net:"network",tls:"network",dgram:"network",dns:"network","node:http":"network","node:https":"network","node:http2":"network","node:net":"network","node:tls":"network","node:dgram":"network","node:dns":"network",axios:"network",undici:"network","node-fetch":"network",got:"network",ky:"network",superagent:"network",ws:"network",process:"process","node:process":"process",child_process:"process","node:child_process":"process","@prisma/client":"persistence",prisma:"persistence",pg:"persistence",mysql:"persistence",mysql2:"persistence",mongodb:"persistence",mongoose:"persistence",sqlite3:"persistence","better-sqlite3":"persistence",redis:"persistence",ioredis:"persistence",typeorm:"persistence",knex:"persistence","drizzle-orm":"persistence",sequelize:"persistence",kysely:"persistence","@supabase/supabase-js":"persistence"}),Dr=Object.freeze({process:Object.freeze(["process","node:process"])});function Nt(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=Tr[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),o=Tr[r];if(o)return o;let s=e.indexOf("/",n+1);return s<0?null:Tr[e.slice(0,s)]??null}i(Nt,"capabilityForModuleSpecifier");function xe(e,t){for(let n of t)if(Dr[n]?.includes(e))return n;return null}i(xe,"forbiddenGlobalForModuleSpecifier");function Gn(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),o=Lr[r];if(o)return o}return null}i(Gn,"capabilityForAmbientName");function lt(e){if(e?.pure===!0)return[...Nr].sort();let n=(e?.capabilities?.deny??[]).filter(r=>Nr.includes(r));return[...new Set(n)].sort()}i(lt,"effectiveCapabilityDeny");function Dt(e,t){if(t.length===0)return!1;let n=new Set(t),r=e.split(".");for(let o=r.length;o>=1;o-=1)if(n.has(r.slice(0,o).join(".")))return!0;return!1}i(Dt,"ambientCoveredByForbiddenGlobals");function Un(e){let t=new Set,n=new Set,r=Object.keys(Lr);for(let o of e?.forbiddenGlobals??[]){let s=r.filter(a=>a===o||a.startsWith(`${o}.`));if(s.length===0)n.add(o);else for(let a of s)t.add(`ambient:${a}`);for(let a of Dr[o]??[])t.add(`import-exact:${a}`)}for(let o of lt(e)){if(t.add(`import:${o}`),o==="process")for(let s of Dr.process)t.add(`import-exact:${s}`);for(let s of r)Gn(s)===o&&t.add(`ambient:${s}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}i(Un,"loweredLayerCoverage");function ct(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(ct,"literalText");function Bs(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}i(Bs,"lineOf");function Vs(e,t){if(e.isImportDeclaration(t)){let r=t.importClause;if(!r)return!1;if(r.isTypeOnly)return!0;let o=r.namedBindings;return!!(o&&e.isNamedImports(o)&&o.elements.length>0&&o.elements.every(s=>s.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(r=>r.isTypeOnly))}i(Vs,"isTypeOnlyReference");function Ws(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=o=>o===t.fileName?t:void 0,r.fileExists=o=>o===t.fileName,r.readFile=o=>o===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}i(Ws,"singleFileChecker");function $r(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}i($r,"symbolAt");function Mr(e,t,n,r){let o=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,s;try{s=o?t.getShorthandAssignmentValueSymbol(r.parent):$r(t,r)}catch{s=void 0}return!!s?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}i(Mr,"localDeclaration");function dt(e,t){let n,r=[],o=i((a,l,c,u=!1)=>r.push({specifier:c,kind:l,line:Bs(t,a),typeOnly:u,unresolved:c===void 0,node:a}),"add"),s=i(a=>{if(e.isImportDeclaration(a))o(a,"import",ct(e,a.moduleSpecifier),Vs(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)o(a,"export",ct(e,a.moduleSpecifier),Vs(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))o(a,"require",ct(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let l=a.expression.kind===e.SyntaxKind.ImportKeyword,u=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!Mr(e,n??(n=Ws(e,t)),t,a.expression);(l||u)&&o(a,u?"require":"dynamic-import",ct(e,a.arguments[0]))}e.forEachChild(a,s)},"visit");return s(t),r}i(dt,"extractSemanticDependencies");function Tl(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let o=ct(e,r.argumentExpression);if(o===void 0)return;n.unshift(o)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}i(Tl,"staticAccessPath");function Nl(e,t){let n=t.parent;return e.isPropertyAccessExpression(n)||e.isElementAccessExpression(n)?!1:e.isExpressionNode(t)&&!e.isInTypeQuery(t)||e.isShorthandPropertyAssignment(n)&&n.name===t}i(Nl,"runtimeIdentifierReference");function js(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let r=n.length;r>=1;r-=1){let o=n.slice(0,r).join(".");if(e.has(o))return o}}i(js,"bestForbiddenMatch");function ut(e,t,n){if(n.length===0)return[];let r=new Set(n),o=Ws(e,t),s=new Map,a=new Set;for(let p of t.statements)if(e.isVariableStatement(p))for(let g of p.declarationList.declarations)e.isIdentifier(g.name)&&a.add(g.name.text);let l=i(p=>{let g=Tl(e,p);if(!g)return;let d=$r(o,g.root),m=d?s.get(d):void 0;return m?[...m,...g.segments.slice(1)]:Mr(e,o,t,g.root)||a.has(g.root.text)?void 0:g.segments},"resolvePath");for(let p of t.statements)if(e.isVariableStatement(p))for(let g of p.declarationList.declarations){if(!g.initializer||!e.isIdentifier(g.name))continue;let d=l(g.initializer),m=$r(o,g.name);!d||!m||s.set(m,d)}let c=[],u=new Set,f=i((p,g)=>{let d=Bs(t,g),m=`${p}:${g.getStart(t)}`;u.has(m)||(u.add(m),c.push({name:p,line:d,node:g}))},"flag"),y=i(p=>{let g=p.parent&&(e.isPropertyAccessExpression(p.parent)||e.isElementAccessExpression(p.parent))&&p.parent.expression===p;if((e.isPropertyAccessExpression(p)||e.isElementAccessExpression(p))&&!g){let d=l(p),m=d?js(r,d):void 0;m&&f(m,p)}else e.isIdentifier(p)&&r.has(p.text)&&Nl(e,p)&&!Mr(e,o,t,p)&&f(p.text,p);if(e.isVariableDeclaration(p)&&e.isObjectBindingPattern(p.name)&&p.initializer){let d=l(p.initializer);if(d)for(let m of p.name.elements){if(!e.isIdentifier(m.name))continue;let E=m.propertyName?ct(e,m.propertyName)??m.propertyName.text:m.name.text,S=js(r,[...d,E]);S&&f(S,p.initializer)}}e.forEachChild(p,y)},"visit");return y(t),c}i(ut,"collectForbiddenCapabilityUses");function Hr(e,t,n){let r=[];for(let o of n?.dependencies??dt(e,t)){if(o.typeOnly||!o.specifier)continue;let s=Nt(o.specifier);s&&r.push({capability:s,symbol:o.specifier,line:o.line,source:"import-based"})}for(let o of n?.ambientUses??ut(e,t,Fr)){let s=Gn(o.name);s&&r.push({capability:s,symbol:o.name,line:o.line,source:"ambient-global"})}return r.sort((o,s)=>o.line-s.line||o.capability.localeCompare(s.capability)||o.symbol.localeCompare(s.symbol))}i(Hr,"collectCapabilityUses");var Kr={RAW_EVENT_PUBLISH:"Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts and tooling.",PUBLISH_MISSING_SOURCE:"Strict Ark publish calls must include metadata.source."},Gr=Object.freeze([{layer:"DomainModel",prefixes:["Domain."]},{layer:"ApplicationOrchestration",prefixes:["Application."]},{layer:"PersistenceAdapters",prefixes:["Adapter.Persistence.","Adapter.Repository."]},{layer:"IntegrationAdapters",prefixes:["Adapter.Integration.","Adapter.External."]},{layer:"WorkflowSagaEngine",prefixes:["Workflow."]},{layer:"BackgroundJobsScheduling",prefixes:["Job."]},{layer:"PresentationAdapters",prefixes:["Presentation.","Adapter.Presentation.","Adapter.Api."]},{layer:"ReportingReadModels",prefixes:["Reporting."]},{layer:"ExtensibilityMetadata",prefixes:["Metadata."]},{layer:"SecurityAuditObservability",prefixes:["Security.","Audit.","Observability."]},{layer:"Kernel",prefixes:["Kernel."]}]);function Ur(e,t){return t.flatMap((r,o)=>(r.prefixes??r.intentPrefixes??[]).map(s=>({layer:r.name,layerIndex:o,prefix:s.endsWith(".")?s:`${s}.`}))).filter(({prefix:r})=>e.startsWith(r)).sort((r,o)=>o.prefix.length-r.prefix.length||r.layerIndex-o.layerIndex)[0]?.layer}i(Ur,"resolveIntentLayer");function Ke(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}i(Ke,"looksLikeArkIntent");function Lt(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&Ke(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:Kr.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:Kr.PUBLISH_MISSING_SOURCE}),t}i(Lt,"classifyPublishFacts");function j(e,t,n){return{ruleId:e,code:e,message:t,...n}}i(j,"violation");function pt(e,t){return e.slice(0,t).split(`
22
- `).length}i(pt,"lineOf");var Dl=new Set(["publish","subscribe","defineIntent","registerHandler"]);function Ll(e,t){return e.index+e[0].indexOf(t)}i(Ll,"captureIndex");function Fl(e){let t=[],n=new Set,r=i((l,c)=>{!l||n.has(c)||(n.add(c),t.push({value:l,index:c}))},"push"),o=i(l=>{l.lastIndex=0;let c;for(;(c=l.exec(e))!==null;){let u=c[1];u&&r(u,Ll(c,u))}},"pushFrom");o(/\b(?:publish|subscribe|defineIntent|registerHandler)\s{0,8}(?:<[^>]{0,120}>)?\s{0,8}\(\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),o(/\b(?:intent|onEvent)\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g);let s=/\breactsTo\s{0,8}:\s{0,8}\[([^\]]{0,2000})\]/g,a;for(;(a=s.exec(e))!==null;){let l=a[1]??"",c=a.index+a[0].indexOf(l),u=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,f;for(;(f=u.exec(l))!==null;){let y=f[1];y&&r(y,c+f.index+f[0].indexOf(y))}}return o(/\bmetadata\s{0,8}:\s{0,8}\{[^}]{0,400}\bsource\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),o(/\bpublish\s{0,8}(?:<[^>]{0,120}>)?\s{0,8}\([^;]{0,400}?\bsource\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),t.sort((l,c)=>l.index-c.index)}i(Fl,"extractQuotedStrings");function $l(e){let t=[],n=[{kind:"import",re:/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s*)?['"]([^'"]+)['"]/g},{kind:"export",re:/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s*['"]([^'"]+)['"]/g},{kind:"dynamic-import",re:/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g},{kind:"require",re:/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g}];for(let r of n){let o;for(;(o=r.re.exec(e))!==null;){let s=o.index+o[0].indexOf(o[1]),a=o[0],l=r.kind==="import"&&/\bimport\s+type\b/.test(a)||r.kind==="export"&&/\bexport\s+type\b/.test(a);t.push({value:o[1],index:s,kind:r.kind,typeOnly:l})}}return t.sort((r,o)=>r.index-o.index)}i($l,"extractModuleSpecifiers");function Ml(e,t){return!!(t&&(e.isParenthesizedExpression(t)||e.isAsExpression(t)||typeof e.isTypeAssertionExpression=="function"&&e.isTypeAssertionExpression(t)||typeof e.isSatisfiesExpression=="function"&&e.isSatisfiesExpression(t)))}i(Ml,"isSyntaxWrapper");function Vr(e,t){let n=t;for(;n?.parent&&Ml(e,n.parent);)n=n.parent;return n}i(Vr,"unwrapWrappers");function jr(e,t){if(!t||!e.isCallExpression(t))return;let n=t.expression;if(e.isIdentifier(n))return n.text;if(e.isPropertyAccessExpression(n))return n.name.text}i(jr,"callCalleeName");function Hl(e,t){let n=t.parent;if(!n||!e.isObjectLiteralExpression(n))return!1;let r=Vr(e,n),o=r.parent;if(!o)return!1;if(e.isCallExpression(o)&&jr(e,o)==="publish"){let s=o.arguments;return s[1]===r||s[2]===r}if(e.isPropertyAssignment(o)&&Br(e,o.name)==="metadata"){let s=o.parent;if(!s)return!1;let l=Vr(e,s).parent;return!!(l&&e.isCallExpression(l)&&jr(e,l)==="publish")}return!1}i(Hl,"isPublishMetadataSource");function zs(e,t){let n=Vr(e,t),r=n.parent;if(!r)return!1;if(e.isCallExpression(r)){let o=jr(e,r);if(o&&Dl.has(o)&&r.arguments.some(s=>s===n))return!0}if(e.isArrayLiteralExpression(r))return zs(e,r);if(e.isPropertyAssignment(r)){let o=Br(e,r.name);if(o==="intent"||o==="onEvent"||o==="reactsTo"||o==="source"&&Hl(e,r))return!0}return!1}i(zs,"isDeclaredIntentSite");function Kl(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],o=i(s=>{e.isStringLiteralLike(s)&&zs(e,s)&&r.push({value:s.text,index:s.getStart(n)}),e.forEachChild(s,o)},"visit");return o(n),r}i(Kl,"extractQuotedStringsAst");function Gl(e){let t=e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);return["adapter","adapters","infra","infrastructure","persistence","repository","repositories","integration","database","db"].some(n=>t.includes(n))}i(Gl,"hasInfrastructureToken");function Ul(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}i(Ul,"isKnownInfrastructurePackage");function Vl(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}i(Vl,"layerHasInfrastructureRole");function $t(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i($t,"tsStringLiteralText");function Br(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}i(Br,"tsPropertyName");function qs(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:Br(e,r.name)===n)}i(qs,"tsObjectProperty");function Mt(e,t,n){return qs(e,t,n)!==void 0}i(Mt,"tsObjectHasProperty");function Ft(e,t,n){let r=qs(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}i(Ft,"tsObjectPropertyValue");function jl(e,t){let n=Ft(e,t,"metadata");return Mt(e,n,"source")}i(jl,"tsObjectHasMetadataSource");function Ys(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?Ys(e,t.name):!1:!1}i(Ys,"tsLooksLikeIntentCreatorExpression");function Bl(e,t){if(!e.isCallExpression(t))return!1;let n=t.expression;return e.isPropertyAccessExpression(n)?n.name.text==="publish":e.isIdentifier(n)&&n.text==="publish"}i(Bl,"tsIsPublishCall");function Wl(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=$t(e,n);return r!==void 0&&Ke(r)||Mt(e,n,"intent")||Ys(e,n)}i(Wl,"tsIsArkPublishCandidate");function zl(e,t){if(!e.isCallExpression(t))return!1;let[n,r,o]=t.arguments;return jl(e,n)||Mt(e,r,"source")||Mt(e,o,"source")}i(zl,"tsPublishHasSource");function ql(e,t){if(!e.isCallExpression(t))return;let[n,r,o]=t.arguments,s=Ft(e,n,"metadata");return $t(e,Ft(e,s,"source"))??$t(e,Ft(e,r,"source"))??$t(e,Ft(e,o,"source"))}i(ql,"tsPublishSourceLiteral");function Yl(e,t,n,r){let o=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),s=n,a=s?.filePath,l=s?.layer,c=[],u=i(y=>o.getLineAndCharacterOfPosition(y.getStart(o)).line+1,"lineForNode"),f=i(y=>{if(Bl(e,y)){let p=y.arguments[0],g=$t(e,p);for(let m of Lt({publishCall:!0,rawIntentName:g,objectHasIntent:Mt(e,p,"intent"),arkPublishCandidate:Wl(e,y),hasSource:zl(e,y)}))c.push(j(m.ruleId,m.message,{line:u(y),filePath:a}));let d=ql(e,y);if(r&&l&&d&&Ke(d)){let m=r.resolveLayer(d);m&&m!==l&&c.push(j("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${d}" resolves to ${m}, but the target file is classified as ${l}.`,{line:u(y),filePath:a,target:d,fromLayer:l,toLayer:m}))}}e.forEachChild(y,f)},"visit");return f(o),c}i(Yl,"analyzePublishAst");function Xs(e={}){let t=new Set((e.intents||[]).map(s=>typeof s=="string"?s:s.name)),n=e.forbiddenPatterns||[],r=new Set(e.infrastructureLayers??[]),o=e.enforceIntentAllowlist??t.size>0;return{validate(s,a){let l=[],c=a,u=c?.filePath,f=c?.layer,y=e.typescript,p=y?y.createSourceFile(u??"generated.ts",s,y.ScriptTarget.Latest,!0):void 0,g=p?dt(e.typescript,p):void 0,d=g?g.filter(k=>k.specifier!==void 0).map(k=>({value:k.specifier,index:k.node.getStart(p),kind:k.kind,typeOnly:k.typeOnly})):$l(s),m=e.typescript?Kl(e.typescript,s):Fl(s);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(u))for(let k of g?.filter(({unresolved:v})=>v)??[]){let v=k.kind==="require";l.push(j(v?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${v?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:k.line,filePath:u}))}let E=f!==void 0&&(r.has(f)||Vl(f)),S=f!==void 0?` If "${f}" is an infrastructure layer, mark it in ark.config.json with "mayImportInfrastructure": true (or name it with an infra token like Adapters/Persistence/Repository).`:"";for(let k of n)if(k instanceof RegExp){k.lastIndex=0;let v=k.exec(s);k.lastIndex=0,v&&l.push(j("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${k}`,{line:v.index===void 0?void 0:pt(s,v.index),filePath:u,suggestion:"Remove infrastructure imports from domain/application layers."+S}))}else s.includes(k)&&l.push(j("FORBIDDEN_SUBSTRING",`Forbidden substring: ${k}`,{line:pt(s,s.indexOf(k)),filePath:u}));for(let k of d){let v=e.resolveImportTarget?.(k.value,u)??(e.resolveImportLayer?{layer:e.resolveImportLayer(k.value,u)}:void 0),C=typeof u=="string"?e.resolveImportTarget?.(u)??(e.resolveImportLayer?{layer:f,relPath:void 0}:void 0):void 0,N=v?.layer;if(N&&f){let b=ot(e.architectureProfile?.rules,f,N,{fromPath:C?.relPath,toPath:v?.relPath,layers:e.architectureLayers});if(b){if(k.typeOnly&&!b.peerIsolation)continue;let T=!!b.peerIsolation;l.push(j("LAYER_IMPORT_VIOLATION",b.message??(T?`Layer "${f}" must not import across slices into "${N}".`:`Layer "${f}" must not import "${N}".`),{line:pt(s,k.index),source:k.value,target:k.value,filePath:u,fromLayer:f,toLayer:N,suggestion:T?"Extract shared code to a shared layer, or coordinate slices via events/ports \u2014 do not import across feature/context slices.":"Depend on a port/interface owned by an inner layer instead, or move this code to a layer allowed to make this import.",details:{importKind:k.kind,peerIsolation:T,...k.typeOnly?{typeOnly:!0}:{}}}));continue}continue}E||k.typeOnly||!Gl(k.value)&&!Ul(k.value)||l.push(j("FORBIDDEN_IMPORT",`Forbidden ${k.kind} target: "${k.value}".`,{line:pt(s,k.index),source:k.value,target:k.value,filePath:u,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+S,details:{importKind:k.kind}}))}if(e.policies)for(let k of e.policies){let v=k.check({source:s,context:a});if(v!==!0)if(Array.isArray(v))for(let C of v)l.push(j("POLICY_VIOLATION",C.message,{filePath:u,suggestion:`Fix violation of policy "${k.name}".`}));else v===!1?l.push(j("POLICY_VIOLATION",`Policy ${k.name} failed on generated code`)):l.push(j("POLICY_VIOLATION",v.message))}if(o&&t.size>0)for(let k of m)Ke(k.value)&&!t.has(k.value)&&l.push(j("UNKNOWN_INTENT",`Unknown intent reference: "${k.value}"`,{line:pt(s,k.index),filePath:u,target:k.value,suggestion:`Register intent "${k.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&f)for(let k of m){if(!Ke(k.value))continue;let v=e.architectureProfile.resolveLayer(k.value);if(!v)continue;let C=$e(e.architectureProfile.rules,f,v,{fromPath:typeof u=="string"?u:void 0,layers:e.architectureLayers});if(C){let N=C.rule.peerIsolation?rt(C.peerIsolationReason??"cross-slice",{fromPath:typeof u=="string"?u:void 0,fromSlice:C.fromSlice,toSlice:C.toSlice}):void 0,b=`Layer "${f}" must not reference "${v}" through "${k.value}".`,T=N&&C.peerIsolationReason!=="cross-slice"?`${b} ${N}`:C.rule.message?N?`${C.rule.message} (${N})`:C.rule.message:b;l.push(j("LAYER_REFERENCE_VIOLATION",T,{line:pt(s,k.index),filePath:u,target:k.value,fromLayer:f,toLayer:v,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:C.rule,peerIsolationReason:C.peerIsolationReason}}))}}if(e.extensions)for(let k of e.extensions)try{let v=k.analyze(s,a);l.push(...v)}catch(v){l.push(j("EXTENSION_ERROR",`Extension "${k.name}" failed: ${v instanceof Error?v.message:String(v)}`))}if(e.typescript&&p&&f&&e.forbiddenGlobals?.[f]?.length)try{let k=e.forbiddenGlobals[f];l.push(...ut(e.typescript,p,k).map(v=>j("FORBIDDEN_GLOBAL",`${f} must not use the ambient global "${v.name}".`,{line:v.line,filePath:u,target:v.name,fromLayer:f,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let v of g??[]){if(v.typeOnly||!v.specifier)continue;let C=xe(v.specifier,k);C&&l.push(j("FORBIDDEN_GLOBAL",`${f} must not use module "${v.specifier}" because it is the import form of forbidden global "${C}".`,{line:v.line,filePath:u,source:v.specifier,target:v.specifier,fromLayer:f,details:{importKind:v.kind,forbiddenGlobal:C},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(k){l.push(j("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${k instanceof Error?k.message:String(k)}`))}if(e.typescript&&p&&f&&e.capabilityWalls?.[f]?.length)try{let k=new Set(e.capabilityWalls[f]),v=e.forbiddenGlobals?.[f]??[];for(let C of Hr(e.typescript,p))k.has(C.capability)&&(C.source==="ambient-global"&&Dt(C.symbol,v)||C.source==="import-based"&&xe(C.symbol,v)||l.push(j("CAPABILITY_VIOLATION",C.source==="import-based"?`${f} denies the ${C.capability} capability; found import of "${C.symbol}".`:`${f} denies the ${C.capability} capability; found ambient "${C.symbol}".`,{line:C.line,filePath:u,target:C.symbol,capability:C.capability,fromLayer:f,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(k){l.push(j("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${k instanceof Error?k.message:String(k)}`))}if(e.typescript)try{l.push(...Yl(e.typescript,s,a,e.architectureProfile))}catch(k){l.push(j("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${k instanceof Error?k.message:String(k)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:l.length===0,violations:l}}}}i(Xs,"createAICodeGate");function Y(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(Y,"deterministicHash");function M(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(M).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${M(t[n])}`).join(",")}}`}i(M,"stableSerialize");var Ge="1.2";var Zs=["network","filesystem","clock","randomness","environment","process","persistence"];function B(e,t){let n=M(e),r=M(t);return n<r?-1:n>r?1:0}i(B,"compareCanonical");function X(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}i(X,"sortedUnique");function Ht(e){let t={schemaVersion:"1.2",include:X(e.include??[]),exclude:X(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:X(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:X(n.patterns??[]),exclude:X(n.exclude??[]),forbiddenGlobals:X(n.forbiddenGlobals??[]),intentPrefixes:X(n.intentPrefixes??[]),capabilityDeny:X(n.capabilities?.deny??[]),pure:n.pure===!0})).sort(B),safety:{maxTsSuppressions:e.safety?.maxTsSuppressions??0,maxAnyCasts:e.safety?.maxAnyCasts??0,allowInMemory:e.safety?.allowInMemory===!0,allowDisabledPeerIsolation:e.safety?.allowDisabledPeerIsolation===!0},...e.arkRun?{arkRun:{mode:e.arkRun.mode,compositionRoots:X(e.arkRun.compositionRoots),managedLayers:X(e.arkRun.managedLayers),requireDeclarations:e.arkRun.requireDeclarations===!0}}:{}};return Y(M(t))}i(Ht,"resolvedFactsEvidenceRequirementsHash");function Xl(e){let t=e.completenessReasons.map(b=>({code:b.code,message:b.message,...b.file?{file:b.file}:{}})).sort(B),n=e.files.map(b=>({...b,typeOnlyExportNames:X(b.typeOnlyExportNames)})).sort((b,T)=>b.path<T.path?-1:b.path>T.path?1:0),r=e.dependencies.map(b=>({...b,...b.namedBindings?{namedBindings:X(b.namedBindings)}:{}})).sort(B),o=e.capabilityUses.map(b=>({...b})).sort(B),s=e.ambientUses.map(b=>({...b})).sort(B),a=e.publishCalls.map(b=>({...b})).sort(B),l=e.intentReferences.map(b=>({...b})).sort(B),c=e.safetyUses.map(b=>({...b})).sort(B),u=(e.classShapes??[]).map(b=>({...b,mutatingMethods:[...b.mutatingMethods??[]].map(T=>({...T}))})).sort(B),f=(e.arkRunKernelCalls??[]).map(b=>({...b})).sort(B),y=(e.arkRunManagedNews??[]).map(b=>({...b})).sort(B),p=(e.arkRunCompositionRootHits??[]).map(b=>({...b})).sort(B),g=(e.arkRunDeclarations??[]).map(b=>({...b,uses:X(b.uses),reactsTo:X(b.reactsTo),raises:X(b.raises),sends:X(b.sends)})).sort(B),d=(e.arkOrderPlaneCalls??[]).map(b=>({...b})).sort(B),m=(e.arkOrderGenericUpdates??[]).map(b=>({...b})).sort(B),E=(e.arkOrderRootHits??[]).map(b=>({...b})).sort(B),S=(e.arkOrderXiFieldWrites??[]).map(b=>({...b})).sort(B),k=(e.arkOrderIngestWritesXi??[]).map(b=>({...b})).sort(B),v=(e.arkOrderReleaseKeyCounts??[]).map(b=>({...b})).sort(B),C=e.files.map(({path:b,contentHash:T})=>({path:b,contentHash:T})).sort((b,T)=>b.path<T.path?-1:b.path>T.path?1:0),N=Y(M(C));return{schemaVersion:"1.2",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:N,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:r,capabilityUses:o,ambientUses:s,publishCalls:a,intentReferences:l,safetyUses:c,classShapes:u,arkRunKernelCalls:f,arkRunManagedNews:y,arkRunCompositionRootHits:p,arkRunDeclarations:g,arkOrderPlaneCalls:d,arkOrderGenericUpdates:m,arkOrderRootHits:E,arkOrderXiFieldWrites:S,arkOrderIngestWritesXi:k,arkOrderReleaseKeyCounts:v}}i(Xl,"canonicalResolvedFactsInput");function Js(e){let t=Xl(e);return{...t,factsHash:Y(M(t))}}i(Js,"createCanonicalResolvedCandidateFacts");function Wr(e){return Js(ei($(e,"$"),!1))}i(Wr,"createResolvedCandidateFacts");function $(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}i($,"asRecord");function H(e,t,n){let r=new Set(t),o=Object.keys(e).find(s=>!r.has(s));if(o)throw new Error(`${n}.${o} is not part of schema ${"1.2"}.`)}i(H,"assertOnlyKeys");function F(e,t,n){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`${n}.${t} must be a non-empty string.`);return r}i(F,"requiredText");function Re(e,t,n){if(e[t]!==void 0)return F(e,t,n)}i(Re,"optionalText");function K(e,t,n){let r=F(e,t,n),o=r.replace(/\\/g,"/");if(!o||o.startsWith("/")||/^[A-Za-z]:\//.test(o)||/[\u0000-\u001f\u007f]/.test(o))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let s=[];for(let l of o.split("/"))if(!(!l||l==="."))if(l===".."){if(s.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);s.pop()}else s.push(l);let a=s.join("/");if(!a||a!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return a}i(K,"requiredProjectPath");function G(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}i(G,"requiredBoolean");function Qs(e,t,n){let r=e[t];if(!Number.isInteger(r)||Number(r)<0)throw new Error(`${n}.${t} must be a non-negative integer.`);return Number(r)}i(Qs,"requiredInteger");function Q(e,t,n){let r=Qs(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}i(Q,"requiredPositiveInteger");function U(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}i(U,"requiredArray");function Ae(e,t,n,r){let o=e[t];if(typeof o!="string"||!n.includes(o))throw new Error(`${r}.${t} must be one of ${n.join(", ")}.`);return o}i(Ae,"enumValue");function ft(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!n))throw new Error(`${t} must be an array of non-empty strings.`);return[...e]}i(ft,"parseStringArray");function Zl(e,t,n){let r=new Set;for(let o of e){let s=t(o);if(r.has(s))throw new Error(`${n} must not contain duplicate facts (${s}).`);r.add(s)}}i(Zl,"assertUnique");function ei(e,t){H(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","classShapes","arkRunKernelCalls","arkRunManagedNews","arkRunCompositionRootHits","arkRunDeclarations","arkOrderPlaneCalls","arkOrderGenericUpdates","arkOrderRootHits","arkOrderXiFieldWrites","arkOrderIngestWritesXi","arkOrderReleaseKeyCounts",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=Ae(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=Ae(e,"completeness",["complete","partial","unavailable"],"$"),o=U(e,"completenessReasons","$").map((w,x)=>{let h=`$.completenessReasons[${x}]`,A=$(w,h);H(A,["code","message","file"],h);let L=A.file===void 0?void 0:K(A,"file",h);return{code:F(A,"code",h),message:F(A,"message",h),...L?{file:L}:{}}});if(r==="complete"&&o.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(r!=="complete"&&o.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let s=U(e,"files","$").map((w,x)=>{let h=`$.files[${x}]`,A=$(w,h);return H(A,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],h),{path:K(A,"path",h),contentHash:F(A,"contentHash",h),parseStatus:Ae(A,"parseStatus",["parsed","invalid"],h),parseDiagnosticCount:Qs(A,"parseDiagnosticCount",h),exportsOnlyTypes:G(A,"exportsOnlyTypes",h),typeOnlyExportNames:ft(A.typeOnlyExportNames,`${h}.typeOnlyExportNames`),hasTopLevelSideEffects:G(A,"hasTopLevelSideEffects",h)}}),a=U(e,"dependencies","$").map((w,x)=>{let h=`$.dependencies[${x}]`,A=$(w,h);H(A,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],h);let L=Re(A,"specifier",h),W=Re(A,"target",h),Se=Ae(A,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],h);if(Se==="resolved-project"&&!W)throw new Error(`${h}.target is required for resolved-project dependencies.`);if(Se!=="resolved-project"&&W)throw new Error(`${h}.target is only allowed for resolved-project dependencies.`);if(Se!=="dynamic"&&!L)throw new Error(`${h}.specifier is required unless resolution is dynamic.`);return{from:K(A,"from",h),...L?{specifier:L}:{},kind:Ae(A,"kind",["import","export","dynamic-import","require"],h),typeOnly:G(A,"typeOnly",h),line:Q(A,"line",h),resolution:Se,...W?{target:K(A,"target",h)}:{},...A.namedBindings!==void 0?{namedBindings:ft(A.namedBindings,`${h}.namedBindings`)}:{},...A.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:G(A,"targetTypeOnlyExports",h)}:{},...A.sourcePureTypeModule!==void 0?{sourcePureTypeModule:G(A,"sourcePureTypeModule",h)}:{},...A.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:G(A,"namedBindingsTypeOnly",h)}:{},...A.portProofEligible!==void 0?{portProofEligible:G(A,"portProofEligible",h)}:{}}}),l=U(e,"capabilityUses","$").map((w,x)=>{let h=`$.capabilityUses[${x}]`,A=$(w,h);return H(A,["file","line","symbol","capability","source"],h),{file:K(A,"file",h),line:Q(A,"line",h),symbol:F(A,"symbol",h),capability:Ae(A,"capability",Zs,h),source:Ae(A,"source",["ambient-global","import-based"],h)}}),c=U(e,"ambientUses","$").map((w,x)=>{let h=`$.ambientUses[${x}]`,A=$(w,h);return H(A,["file","line","symbol"],h),{file:K(A,"file",h),line:Q(A,"line",h),symbol:F(A,"symbol",h)}}),u=U(e,"publishCalls","$").map((w,x)=>{let h=`$.publishCalls[${x}]`,A=$(w,h);H(A,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],h);let L=Re(A,"rawIntentName",h),W=Re(A,"sourceIntent",h);return{file:K(A,"file",h),line:Q(A,"line",h),...L?{rawIntentName:L}:{},objectHasIntent:G(A,"objectHasIntent",h),arkPublishCandidate:G(A,"arkPublishCandidate",h),hasSource:G(A,"hasSource",h),...W?{sourceIntent:W}:{}}}),f=U(e,"intentReferences","$").map((w,x)=>{let h=`$.intentReferences[${x}]`,A=$(w,h);return H(A,["file","line","intent"],h),{file:K(A,"file",h),line:Q(A,"line",h),intent:F(A,"intent",h)}}),y=U(e,"safetyUses","$").map((w,x)=>{let h=`$.safetyUses[${x}]`,A=$(w,h);H(A,["file","line","kind","symbol"],h);let L=Re(A,"symbol",h),W=Ae(A,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],h);if(W==="in-memory-store"&&!L)throw new Error(`${h}.symbol is required for in-memory-store facts.`);if(W!=="in-memory-store"&&L)throw new Error(`${h}.symbol is only allowed for in-memory-store facts.`);return{file:K(A,"file",h),line:Q(A,"line",h),kind:W,...L?{symbol:L}:{}}});Zl(s,w=>w.path,"$.files");let p=new Set(s.map(w=>w.path));for(let w of s){if(w.parseStatus==="parsed"&&w.parseDiagnosticCount!==0)throw new Error(`$.files[${w.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(w.parseStatus==="invalid"&&w.parseDiagnosticCount===0)throw new Error(`$.files[${w.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&s.some(w=>w.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let w of a)if(!p.has(w.from))throw new Error(`$.dependencies references missing source file ${w.from}.`);let d=(e.arkRunKernelCalls===void 0?[]:U(e,"arkRunKernelCalls","$")).map((w,x)=>{let h=`$.arkRunKernelCalls[${x}]`,A=$(w,h);H(A,["file","line","kind","callee","viaImport","receiver","nameLiteral"],h);let L=Re(A,"receiver",h),W=Re(A,"nameLiteral",h);return{file:K(A,"file",h),line:Q(A,"line",h),kind:Ae(A,"kind",["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"],h),callee:F(A,"callee",h),viaImport:G(A,"viaImport",h),...L?{receiver:L}:{},...W?{nameLiteral:W}:{}}}),E=(e.arkRunManagedNews===void 0?[]:U(e,"arkRunManagedNews","$")).map((w,x)=>{let h=`$.arkRunManagedNews[${x}]`,A=$(w,h);H(A,["file","line","typeName","importedFrom"],h);let L=Re(A,"importedFrom",h);return{file:K(A,"file",h),line:Q(A,"line",h),typeName:F(A,"typeName",h),...L?{importedFrom:L}:{}}}),k=(e.arkRunCompositionRootHits===void 0?[]:U(e,"arkRunCompositionRootHits","$")).map((w,x)=>{let h=`$.arkRunCompositionRootHits[${x}]`,A=$(w,h);return H(A,["file","matchedRoot","hasKernelFactory"],h),{file:K(A,"file",h),matchedRoot:F(A,"matchedRoot",h),hasKernelFactory:G(A,"hasKernelFactory",h)}}),v=e.arkRunDeclarations===void 0?[]:U(e,"arkRunDeclarations","$"),N=(e.arkOrderPlaneCalls===void 0?[]:U(e,"arkOrderPlaneCalls","$")).map((w,x)=>{let h=`$.arkOrderPlaneCalls[${x}]`,A=$(w,h);return H(A,["file","line","callee"],h),{file:K(A,"file",h),line:Q(A,"line",h),callee:F(A,"callee",h)}}),T=(e.arkOrderGenericUpdates===void 0?[]:U(e,"arkOrderGenericUpdates","$")).map((w,x)=>{let h=`$.arkOrderGenericUpdates[${x}]`,A=$(w,h);return H(A,["file","line","method"],h),{file:K(A,"file",h),line:Q(A,"line",h),method:F(A,"method",h)}}),ge=(e.arkOrderRootHits===void 0?[]:U(e,"arkOrderRootHits","$")).map((w,x)=>{let h=`$.arkOrderRootHits[${x}]`,A=$(w,h);return H(A,["file","matchedRoot","hasPlaneFactory"],h),{file:K(A,"file",h),matchedRoot:F(A,"matchedRoot",h),hasPlaneFactory:G(A,"hasPlaneFactory",h)}}),D=(e.arkOrderXiFieldWrites===void 0?[]:U(e,"arkOrderXiFieldWrites","$")).map((w,x)=>{let h=`$.arkOrderXiFieldWrites[${x}]`,A=$(w,h);return H(A,["file","line","key"],h),{file:K(A,"file",h),line:Q(A,"line",h),key:F(A,"key",h)}}),q=(e.arkOrderIngestWritesXi===void 0?[]:U(e,"arkOrderIngestWritesXi","$")).map((w,x)=>{let h=`$.arkOrderIngestWritesXi[${x}]`,A=$(w,h);return H(A,["file","line"],h),{file:K(A,"file",h),line:Q(A,"line",h)}}),Ee=(e.arkOrderReleaseKeyCounts===void 0?[]:U(e,"arkOrderReleaseKeyCounts","$")).map((w,x)=>{let h=`$.arkOrderReleaseKeyCounts[${x}]`,A=$(w,h);return H(A,["file","line","keyCount"],h),{file:K(A,"file",h),line:Q(A,"line",h),keyCount:Q(A,"keyCount",h)}}),bt=v.map((w,x)=>{let h=`$.arkRunDeclarations[${x}]`,A=$(w,h);return H(A,["file","line","uses","reactsTo","raises","sends"],h),{file:K(A,"file",h),line:Q(A,"line",h),uses:ft(A.uses,`${h}.uses`),reactsTo:ft(A.reactsTo,`${h}.reactsTo`),raises:ft(A.raises,`${h}.raises`),sends:ft(A.sends,`${h}.sends`)}});for(let[w,x]of[["$.capabilityUses",l],["$.ambientUses",c],["$.publishCalls",u],["$.intentReferences",f],["$.safetyUses",y],["$.arkRunKernelCalls",d],["$.arkRunManagedNews",E],["$.arkRunCompositionRootHits",k],["$.arkRunDeclarations",bt],["$.arkOrderPlaneCalls",N],["$.arkOrderGenericUpdates",T],["$.arkOrderRootHits",ge],["$.arkOrderXiFieldWrites",D],["$.arkOrderIngestWritesXi",q],["$.arkOrderReleaseKeyCounts",Ee]])for(let h of x)if(!p.has(h.file))throw new Error(`${w} references missing file ${h.file}.`);let fn=Re(e,"projectPackageName","$"),Mo=(e.classShapes===void 0?[]:U(e,"classShapes","$")).map((w,x)=>{let h=`$.classShapes[${x}]`,A=$(w,h);H(A,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],h);let L=U(A,"mutatingMethods",h).map((W,Se)=>{let R=`${h}.mutatingMethods[${Se}]`,ee=$(W,R);return H(ee,["name","referencesGuardOrPublish"],R),{name:F(ee,"name",R),referencesGuardOrPublish:G(ee,"referencesGuardOrPublish",R)}});return{file:K(A,"file",h),className:F(A,"className",h),exported:G(A,"exported",h),hasPublicMutableFields:G(A,"hasPublicMutableFields",h),hasPublicSetters:G(A,"hasPublicSetters",h),hasPublicConstructor:G(A,"hasPublicConstructor",h),hasStaticFactory:G(A,"hasStaticFactory",h),mutatingMethods:L,...A.dataOnly===void 0?{}:{dataOnly:G(A,"dataOnly",h)}}});return{schemaVersion:n,completeness:r,completenessReasons:o,resolverIdentity:F(e,"resolverIdentity","$"),compilerIdentity:F(e,"compilerIdentity","$"),compilerOptionsHash:F(e,"compilerOptionsHash","$"),tsconfigHash:F(e,"tsconfigHash","$"),evidenceRequirementsHash:F(e,"evidenceRequirementsHash","$"),...fn?{projectPackageName:fn}:{},files:s,dependencies:a,capabilityUses:l,ambientUses:c,publishCalls:u,intentReferences:f,safetyUses:y,classShapes:Mo,arkRunKernelCalls:d,arkRunManagedNews:E,arkRunCompositionRootHits:k,arkRunDeclarations:bt,arkOrderPlaneCalls:N,arkOrderGenericUpdates:T,arkOrderRootHits:ge,arkOrderXiFieldWrites:D,arkOrderIngestWritesXi:q,arkOrderReleaseKeyCounts:Ee}}i(ei,"parseResolvedFactsInput");function Oe(e){let t=$(e,"$"),n=F(t,"factsHash","$"),r=F(t,"candidateTreeHash","$"),o=Js(ei(t,!0));if(o.factsHash!==n)throw new Error(`$.factsHash does not match the canonical payload (${o.factsHash}).`);if(r!==o.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${o.candidateTreeHash}).`);return o}i(Oe,"loadResolvedCandidateFacts");var Jl=["network","filesystem","clock","randomness","environment","process","persistence"],_={type:"string",minLength:1},te={type:"integer",minimum:1},V={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},zr={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.resolved-candidate-facts.schema.json",title:"ArkGate resolved candidate facts",type:"object",additionalProperties:!1,required:["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","candidateTreeHash","evidenceRequirementsHash","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","factsHash"],properties:{schemaVersion:{enum:["1.0","1.1","1.2"]},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:_,message:_,file:V}}},resolverIdentity:_,compilerIdentity:_,compilerOptionsHash:_,tsconfigHash:_,candidateTreeHash:_,evidenceRequirementsHash:_,projectPackageName:_,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:V,contentHash:_,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:_},hasTopLevelSideEffects:{type:"boolean"}},allOf:[{if:{properties:{parseStatus:{const:"parsed"}}},then:{properties:{parseDiagnosticCount:{const:0}}}},{if:{properties:{parseStatus:{const:"invalid"}}},then:{properties:{parseDiagnosticCount:{minimum:1}}}}]}},dependencies:{type:"array",items:{type:"object",additionalProperties:!1,required:["from","kind","typeOnly","line","resolution"],properties:{from:V,specifier:_,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:te,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:V,namedBindings:{type:"array",items:_},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"}},allOf:[{if:{properties:{resolution:{const:"resolved-project"}}},then:{required:["target"]},else:{not:{required:["target"]}}},{if:{properties:{resolution:{const:"dynamic"}}},else:{required:["specifier"]}}]}},capabilityUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol","capability","source"],properties:{file:V,line:te,symbol:_,capability:{enum:Jl},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:V,line:te,symbol:_}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:V,line:te,rawIntentName:_,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:_}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:V,line:te,intent:_}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:V,line:te,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:_},allOf:[{if:{properties:{kind:{const:"in-memory-store"}}},then:{required:["symbol"]},else:{not:{required:["symbol"]}}}]}},classShapes:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods"],properties:{file:V,className:_,exported:{type:"boolean"},hasPublicMutableFields:{type:"boolean"},hasPublicSetters:{type:"boolean"},hasPublicConstructor:{type:"boolean"},hasStaticFactory:{type:"boolean"},dataOnly:{type:"boolean"},mutatingMethods:{type:"array",items:{type:"object",additionalProperties:!1,required:["name","referencesGuardOrPublish"],properties:{name:_,referencesGuardOrPublish:{type:"boolean"}}}}}}},arkRunKernelCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind","callee","viaImport"],properties:{file:V,line:te,kind:{enum:["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"]},callee:_,viaImport:{type:"boolean"},receiver:_,nameLiteral:_}}},arkRunManagedNews:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","typeName"],properties:{file:V,line:te,typeName:_,importedFrom:_}}},arkRunCompositionRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasKernelFactory"],properties:{file:V,matchedRoot:_,hasKernelFactory:{type:"boolean"}}}},arkRunDeclarations:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","uses","reactsTo","raises","sends"],properties:{file:V,line:te,uses:{type:"array",items:_},reactsTo:{type:"array",items:_},raises:{type:"array",items:_},sends:{type:"array",items:_}}}},arkOrderPlaneCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","callee"],properties:{file:V,line:te,callee:_}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:V,line:te,method:_}}},arkOrderRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasPlaneFactory"],properties:{file:V,matchedRoot:_,hasPlaneFactory:{type:"boolean"}}}},arkOrderXiFieldWrites:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:V,line:te,key:_}}},arkOrderIngestWritesXi:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line"],properties:{file:V,line:te}}},arkOrderReleaseKeyCounts:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","keyCount"],properties:{file:V,line:te,keyCount:{type:"integer",minimum:1}}}},factsHash:_},allOf:[{if:{properties:{completeness:{const:"complete"}}},then:{properties:{completenessReasons:{maxItems:0},files:{items:{properties:{parseStatus:{const:"parsed"}}}}}}},{if:{properties:{completeness:{enum:["partial","unavailable"]}}},then:{properties:{completenessReasons:{minItems:1}}}}]};var qr="1.0";function oe(e){return`${e.from}->${e.to}`}i(oe,"dependencyKey");function Kt(e,t,n,r="dependency"){return{id:`${e}:${r}:${oe(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${oe(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${oe(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${oe(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${oe(t)} from the candidate, then preflight again.`}:{}}}i(Kt,"dependencyFinding");function gt(e){let t=[],n=new Map(e.changeMap.map.files.map(p=>[p.path,p])),r=new Map(e.changes.map(p=>[p.path,p])),o=new Map(e.changeMap.map.dependencies.map(p=>[oe(p),p])),s=new Map(e.baseDependencies.map(p=>[oe(p),p])),a=new Map(e.candidateDependencies.map(p=>[oe(p),p]));for(let p of[...n.values()].sort((g,d)=>g.path.localeCompare(d.path))){let g=r.get(p.path);g?g.operation!==p.operation?t.push({id:`contradictory:file:${p.path}`,classification:"contradictory",subject:"file",path:p.path,expectedOperation:p.operation,actualOperation:g.operation,message:`${p.path} was planned as ${p.operation} but the actual operation is ${g.operation}.`,nextAction:`Change ${p.path} to the planned ${p.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${p.path}`,classification:"satisfied",subject:"file",path:p.path,expectedOperation:p.operation,actualOperation:g.operation,message:`${p.path} matches the planned ${p.operation} operation.`}):t.push({id:`missing:file:${p.path}`,classification:"missing",subject:"file",path:p.path,expectedOperation:p.operation,message:`${p.path} was planned as ${p.operation} but is absent from the actual change.`,nextAction:`${p.operation[0].toUpperCase()}${p.operation.slice(1)} ${p.path} in the complete change set, then preflight again.`})}for(let p of[...r.values()].sort((g,d)=>g.path.localeCompare(d.path)))n.has(p.path)||t.push({id:`unplanned:file:${p.path}`,classification:"unplanned",subject:"file",path:p.path,actualOperation:p.operation,message:`${p.path} has an unplanned ${p.operation} operation.`,nextAction:`Remove ${p.path} from the change set, then preflight again.`});let l=new Set;for(let p of[...o.values()].sort((g,d)=>oe(g).localeCompare(oe(d)))){if(a.has(oe(p))){t.push(Kt("satisfied",p,`${p.from} -> ${p.to} exists in the candidate architecture.`));continue}let g={from:p.to,to:p.from};a.has(oe(g))?(l.add(oe(g)),t.push(Kt("contradictory",p,`${p.from} -> ${p.to} was planned, but the candidate contains the reverse edge.`))):t.push(Kt("missing",p,`${p.from} -> ${p.to} is absent from the candidate architecture.`))}let c=new Set([...n.keys(),...r.keys()]);for(let[p,g]of[...a].sort(([d],[m])=>d.localeCompare(m)))s.has(p)||o.has(p)||l.has(p)||!c.has(g.from)&&!c.has(g.to)||t.push({...Kt("unplanned",g,`${g.from} -> ${g.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let u=new Set(e.changeMap.map.files.filter(p=>p.operation==="delete").map(p=>p.path));for(let[p,g]of[...s].sort(([d],[m])=>d.localeCompare(m)))a.has(p)||u.has(g.from)||u.has(g.to)||!c.has(g.from)&&!c.has(g.to)||t.push({...Kt("unplanned",g,`${g.from} -> ${g.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let f={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((p,g)=>f[p.classification]-f[g.classification]||(p.subject===g.subject?0:p.subject==="file"?-1:1)||p.id.localeCompare(g.id));let y={satisfied:t.filter(p=>p.classification==="satisfied").length,missing:t.filter(p=>p.classification==="missing").length,contradictory:t.filter(p=>p.classification==="contradictory").length,unplanned:t.filter(p=>p.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:y.missing===0&&y.contradictory===0&&y.unplanned===0,behavioralCompletion:"not-evaluated",summary:y,findings:t}}i(gt,"analyzeArchitectureConvergence");var ti="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",Ql=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","writes-via-aggregate","no-anemic-model","invariant-coverage"];var ni={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Jg={$schema:"https://json-schema.org/draft/2020-12/schema",$id:ti,title:"ArkGate ArkRules (intra-layer contract)",description:"Per-layer structure sensors and invariant catalog consumed by the ArkGate Effective Contract.",type:"object",additionalProperties:!1,required:["schemaVersion","layer"],properties:{$schema:{type:"string",minLength:1,default:ti},schemaVersion:{type:"string",const:"1.0",default:"1.0"},layer:{type:"string",minLength:1},structure:{type:"array",default:[],items:{$ref:"#/$defs/structureEntry"}},invariants:{type:"array",default:[],items:{$ref:"#/$defs/invariantEntry"}}},$defs:{structureEntry:{type:"object",additionalProperties:!1,required:["id","sensor"],properties:{id:{type:"string",minLength:1},sensor:{type:"string",enum:[...Ql]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:ni,description:{type:"string",minLength:1}}},invariantEntry:{type:"object",additionalProperties:!1,required:["id","description"],properties:{id:{type:"string",minLength:1},description:{type:"string",minLength:1},aggregate:{type:"string",minLength:1},coverage:{type:"object",additionalProperties:!1,properties:{test:{type:"boolean"},symbol:{type:"string",minLength:1}}},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:ni}}}};function Gt(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}i(Gt,"emptyEffectiveArkRules");function Yr(e){return{...e,layers:e.layers.map(t=>{let{description:n,trustBoundary:r,owners:o,...s}=t;return s})}}i(Yr,"omitLayerDescriptions");function ri(e){let{stewards:t,...n}=Yr(e.config);return{config:n,arkRules:{schemaVersion:e.arkRules.schemaVersion,structure:e.arkRules.structure.map(r=>({id:r.id,sensor:r.sensor,mode:r.mode,appliesTo:r.appliesTo??null,description:r.description??null,provenance:r.provenance})),invariants:e.arkRules.invariants.map(r=>({id:r.id,description:r.description,aggregate:r.aggregate??null,coverage:r.coverage??null,mode:r.mode,appliesTo:r.appliesTo??null,provenance:r.provenance}))}}}i(ri,"effectiveContractPolicyPayload");var ec="INVARIANT_TESTS_PATH_MISSING",tc="This project is adopted and has domain invariants, but ark.config.json does not name a real tests path. Add coverage.testGlobs or coverage.coverageRoots pointing at the folder where those tests live, then re-run. Without that path, coverage is an empty checkbox.",nc="INVARIANT_COVERAGE_ROOTS_MISSING",rc="A domain invariant is enforced, but ark.config.json does not name coverage.coverageRoots \u2014 the folders where this project's test runner actually goes. Add coverage.coverageRoots pointing at that folder, then re-run. Without it, coverage can certify a test no runner runs.";function oi(e,t=!1){if(!e)return"";let n=e.discarded,r=[];if(n.budget>0&&!t&&r.push(`${n.budget} past the ${e.maxFiles}-file budget`),n.noInvariantMention>0&&r.push(`${n.noInvariantMention} naming no catalogued invariant`),n.oversize>0&&r.push(`${n.oversize} over the per-file byte cap`),n.unreadable>0&&r.push(`${n.unreadable} unreadable (files or directories)`),n.depthLimited>0&&r.push(`${n.depthLimited} directories past the walk depth limit`),n.outOfRoot>0&&r.push(`${n.outOfRoot} symlinked outside the project root`),r.length===0)return"";let o=t?"":` (loaded ${e.filesLoaded} files, kept ${e.testFilesRetained} tests)`;return` Scan discarded ${r.join(", ")}${o}.`}i(oi,"formatCoverageDiscards");function ai(e,t){let n=e.replace(/\\/g,"/").replace(/^\.\//,"");return t.some(r=>{let o=r.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"");return o===""||o==="."?!0:n===o||n.startsWith(`${o}/`)})}i(ai,"isUnderCoverageRoot");function li(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}i(li,"escapeRegExp");function Xr(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}i(Xr,"normalizePath");function ci(e,t){let n=[],r=0,o=e.length;for(;r<o;){let s=e[r],a=e[r+1];if(s==="/"&&a==="/"){for(;r<o&&e[r]!==`
23
- `;)n.push(" "),r+=1;continue}if(s==="/"&&a==="*"){for(n.push(" "," "),r+=2;r<o&&!(e[r]==="*"&&e[r+1]==="/");)n.push(e[r]===`
20
+ `)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function ge(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(ge,"isObject");function Ve(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}a(Ve,"propertyPath");function dt(e){return e===null?"null":Array.isArray(e)?"array":typeof e}a(dt,"valueType");function gc(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}a(gc,"resolveSchemaRef");function jt(e,t,n,r,o){if(t.$ref){let s=gc(t.$ref,r);if(!s){o.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}jt(e,s,n,r,o);return}if(t.const!==void 0&&!Object.is(e,t.const)){o.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(s=>Object.is(s,e))){o.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!ge(e)){o.push({path:n,message:`must be an object; received ${dt(e)}`});return}let s=t.properties??{};for(let i of t.required??[])e[i]===void 0&&o.push({path:Ve(n,i),message:"is required"});if(t.additionalProperties===!1)for(let i of Object.keys(e))i in s||o.push({path:Ve(n,i),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let i=t.additionalProperties;for(let l of Object.keys(e))l in s||jt(e[l],i,Ve(n,l),r,o)}for(let[i,l]of Object.entries(s))e[i]!==void 0&&jt(e[i],l,Ve(n,i),r,o);return}if(t.type==="array"){if(!Array.isArray(e)){o.push({path:n,message:`must be an array; received ${dt(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&o.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let s=e.map(i=>JSON.stringify(i));new Set(s).size!==s.length&&o.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((s,i)=>jt(s,t.items,`${n}[${i}]`,r,o));return}if(t.type==="string"){if(typeof e!="string"){o.push({path:n,message:`must be a string; received ${dt(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&o.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&o.push({path:n,message:`must be a boolean; received ${dt(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){o.push({path:n,message:`must be an integer; received ${dt(e)}`});return}t.minimum!==void 0&&e<t.minimum&&o.push({path:n,message:`must be at least ${t.minimum}`})}}a(jt,"validateNode");var mc=["deny","advisory"],ni='must be "deny", "advisory", or { "default": "deny" | "advisory", "enforce": ["<child id or subtree path>"] }';function yc(e,t){let n=e.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!ge(r))return;let s=r.childSlices;if(!ge(s)||s.siblings===void 0)return;let i=s.siblings,l=`$.rules[${o}].childSlices.siblings`;if(typeof i=="string"){mc.includes(i)||t.push({path:l,message:ni});return}if(!ge(i)){t.push({path:l,message:ni});return}for(let u of Object.keys(i))u!=="default"&&u!=="enforce"&&t.push({path:Ve(l,u),message:"unknown field"});if(i.default===void 0?t.push({path:`${l}.default`,message:"is required"}):i.default!=="deny"&&i.default!=="advisory"&&t.push({path:`${l}.default`,message:"must be deny or advisory"}),i.enforce===void 0)return;if(!Array.isArray(i.enforce)){t.push({path:`${l}.enforce`,message:"must be an array of child slice ids or subtree paths"});return}let c=new Set;i.enforce.forEach((u,f)=>{let y=`${l}.enforce[${f}]`;if(typeof u!="string"||u.trim().length===0){t.push({path:y,message:"must be a non-empty child slice id or subtree path"});return}let p=pt(u.trim().replace(/\\/g,"/"));if(p.split("/").some(g=>g.length===0||g==="."||g==="..")){t.push({path:y,message:"must be a child slice id or subtree path without . or .."});return}if(p.includes("*")){t.push({path:y,message:"must be a child slice id or subtree path. * is not a wildcard on siblings.enforce"});return}if(c.has(p)){t.push({path:y,message:"duplicate enforce entry"});return}c.add(p)})})}a(yc,"validateChildSliceSiblings");var hc="must be a slice id with a slash. A bare name is ambiguous across universes.",Rc="* matches one whole path segment. ** and a partial segment are not wildcards.";function Ac(e){let t=pt(e.trim().replace(/\\/g,"/"));if(t.length===0)return"must be a non-empty slice id";if(!t.includes("/"))return hc;let n=t.split("/");for(let r of n){if(r.length===0||r==="."||r==="..")return"must be a slice id without empty, . or .. segments";if(r.includes("*")&&r!=="*")return Rc}return null}a(Ac,"childCrossSlicePatternIssue");function ri(e){return pt(e.trim().replace(/\\/g,"/")).toLowerCase()}a(ri,"childCrossSlicePatternKey");function kc(e,t){let n=e.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!ge(r))return;let s=r.childSlices;if(!ge(s)||s.allowedCrossSlice===void 0)return;let i=s.allowedCrossSlice,l=`$.rules[${o}].childSlices.allowedCrossSlice`;if(!Array.isArray(i)){t.push({path:l,message:"must be an array of { from, to } child slice ids"});return}let c=new Set;i.forEach((u,f)=>{let y=`${l}[${f}]`;if(!ge(u)){t.push({path:y,message:"must be an object with from and to"});return}for(let g of Object.keys(u))g!=="from"&&g!=="to"&&t.push({path:Ve(y,g),message:"unknown field"});for(let g of["from","to"]){let d=u[g],m=`${y}.${g}`;if(typeof d!="string"||d.trim().length===0){t.push({path:m,message:"must be a non-empty slice id"});continue}let b=Ac(d);b&&t.push({path:m,message:b})}if(typeof u.from!="string"||typeof u.to!="string")return;let p=`${ri(u.from)}\0${ri(u.to)}`;if(!p.startsWith("\0")&&!p.endsWith("\0")){if(c.has(p)){t.push({path:y,message:"duplicate child slice allowance"});return}c.add(p)}})})}a(kc,"validateChildSliceAllowedCrossSlice");var ut="must be a child of an existing universe (the universe id this rule already names, plus one child segment). A bare name, a universe id alone, an unknown universe, and a wildcard are rejected.",Ic="overlaps a slice folder. An alias covers only files outside the slice trees.",bc="two slice aliases match the same file";function Sc(e){return pt(e.trim().replace(/\\/g,"/")).toLowerCase().split("/").filter(t=>t.length>0)}a(Sc,"aliasPathSegments");function li(e){let t=[];for(let n of e){if(n.includes("*"))break;t.push(n)}return t}a(li,"concreteGlobPrefix");function Vt(e,t){if(e.length>t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}a(Vt,"segmentsArePrefix");function vc(e){let t=e.split(/[/\\]/).filter(Boolean).map(r=>r.toLowerCase());if(t.length<2||t[0]==="*"||t[0]==="**"||!t.some(r=>r==="*"))return null;let n=[];for(let r of t){if(r==="*"||r==="**")break;if(r.includes("*"))return null;n.push(r)}return n.length>0?n:null}a(vc,"anchoredSlicePrefix");function Ec(e,t){let n=li(e),r=n.length<e.length,o=n[0]==="src"||n[0]==="app"?n.slice(1):n;return Vt(t,n)||Vt(t,o)?!0:r?Vt(n,t)&&n.length<t.length||Vt(n,["src",...t])&&n.length<t.length+1||Vt(n,["app",...t])&&n.length<t.length+1:!1}a(Ec,"globOverlapsAnchored");function wc(e,t){for(let r=0;r<e.length;r+=1){if(e[r]!==t&&e[r]!=="*")continue;let o=e.slice(r+1);if(o.length>=2||o.some(s=>s==="*"||s==="**"))return!0}let n=li(e);return n.length<e.length&&(n.length===0||n.length===1&&(n[0]==="src"||n[0]==="app"))}a(wc,"globOverlapsBare");function Cc(e,t){let n=t.split(/[/\\]/).filter(Boolean).map(o=>o.toLowerCase());if(n.length===1&&n[0]&&!n[0].includes("*"))return wc(e,n[0]);let r=vc(t);return r?Ec(e,r):!1}a(Cc,"globOverlapsSliceEntry");function xc(e){let t=pt(e.trim().replace(/\\/g,"/"));if(t.length===0)return"must be a non-empty path glob";if(t==="*"||t==="**")return"must not cover the whole tree";for(let n of t.split("/")){if(n.length===0||n==="."||n==="..")return"must be a path glob without empty, . or .. segments";if(!(n==="*"||n==="**")&&(n.includes("*")||n.includes("?")||n.includes("{")||n.includes("[")))return"* matches one whole path segment. ** is a whole segment. A partial segment is not a wildcard."}return null}a(xc,"aliasGlobIssue");function Oc(e,t){let n=[];if(!Array.isArray(e))return n;let r=t==="stars";for(let o of e){if(typeof o!="string"||o.length===0)continue;let s=o.split(/[/\\]/).filter(Boolean).map(i=>i.toLowerCase());if(s.length===1&&s[0]&&!s[0].includes("*")){n.push({literals:[s[0],null]});continue}if(!s.some(i=>i==="**"||i.includes("*")&&i!=="*")&&s.includes("*")){if(r){let i=-1;for(let l=0;l<s.length;l+=1)s[l]!=="*"&&(i=l);if(i<0)continue;n.push({literals:s.slice(i).map(l=>l==="*"?null:l)});continue}n.push({literals:s.map(i=>i==="*"?null:i)})}}return n}a(Oc,"universeShapes");function oi(e,t){return e.literals.length!==t.length?!1:e.literals.every((n,r)=>n===null||n===t[r])}a(oi,"shapeMatches");function Pc(e,t){let n=pt(e.trim().replace(/\\/g,"/"));if(n.length===0||n.split("/").some(o=>o.length===0||o==="."||o==="..")||n.includes("*")||!n.includes("/"))return ut;let r=n.split("/").map(o=>o.toLowerCase());return t.length===0||t.some(o=>oi(o,r))?ut:t.some(o=>oi(o,r.slice(0,-1)))?null:ut}a(Pc,"aliasTargetIssue");function si(e){let t=e[0];return(t==="src"||t==="app")&&e.length>1?[e,e.slice(1)]:[e]}a(si,"aliasGlobVariants");function _c(e,t){let n=si(e),r=si(t);for(let o of n)if(Ue(o,t,0,0,new Map))return!0;for(let o of r)if(Ue(e,o,0,0,new Map))return!0;return!1}a(_c,"aliasesCanMatchSameFile");function Ue(e,t,n,r,o){let s=`${n}:${r}`,i=o.get(s);if(i!==void 0)return i;let l=!1;if(n===e.length&&r===t.length)l=!0;else if(n<e.length&&e[n]==="**")l=Ue(e,t,n+1,r,o)||r<t.length&&Ue(e,t,n,r+1,o);else if(r<t.length&&t[r]==="**")l=Ue(e,t,n,r+1,o)||n<e.length&&Ue(e,t,n+1,r,o);else if(n<e.length&&r<t.length){let c=e[n],u=t[r];(c===u||c==="*"||u==="*")&&(l=Ue(e,t,n+1,r+1,o))}return o.set(s,l),l}a(Ue,"globsCanMatchSame");function Tc(e,t){let n=e.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!ge(r))return;let s=r.childSlices;if(!ge(s)||s.sliceAliases===void 0)return;let i=s.sliceAliases,l=`$.rules[${o}].childSlices.sliceAliases`;if(!Array.isArray(i)){t.push({path:l,message:"must be an array of { from, to } slice aliases"});return}let c=Oc(r.sliceFolders,r.sliceIdentity),u=[...Array.isArray(r.sliceFolders)?r.sliceFolders:[],...Array.isArray(s.sliceFolders)?s.sliceFolders:[]].filter(y=>typeof y=="string"&&y.length>0),f=[];i.forEach((y,p)=>{let g=`${l}[${p}]`;if(!ge(y)){t.push({path:g,message:"must be an object with from and to"});return}for(let b of Object.keys(y))b!=="from"&&b!=="to"&&t.push({path:Ve(g,b),message:"unknown field"});let d=y.from,m=y.to;if(typeof d!="string"||d.trim().length===0)t.push({path:`${g}.from`,message:"must be a non-empty path glob"});else{let b=xc(d);if(b)t.push({path:`${g}.from`,message:b});else{let v=Sc(d);u.some(k=>Cc(v,k))&&t.push({path:`${g}.from`,message:Ic});for(let k of f)if(_c(k,v)){t.push({path:g,message:bc});break}f.push(v)}}if(typeof m!="string"||m.trim().length===0)t.push({path:`${g}.to`,message:ut});else{let b=Pc(m,c);b&&t.push({path:`${g}.to`,message:b})}})})}a(Tc,"validateChildSliceAliases");function Nc(e,t){let n=e.layers;Array.isArray(n)&&n.forEach((r,o)=>{if(!r||typeof r!="object"||Array.isArray(r)||!("owners"in r))return;let s=r.owners;Array.isArray(s)&&s.forEach((i,l)=>{typeof i=="string"&&(Qs(i)||t.push({path:`$.layers[${o}].owners[${l}]`,message:"must be a GitHub handle or email (not a display name)"}))})})}a(Nc,"validateLayerOwners");function Lc(e){let t={...e,$schema:e.$schema===void 0?qn:e.$schema,schemaVersion:e.schemaVersion===void 0?ce:e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?Yn.map(n=>({...n})):e.rules};return e.arkRun!==void 0&&(t.arkRun=qs(e.arkRun)),e.arkOrder!==void 0&&(t.arkOrder=Ys(e.arkOrder)),t}a(Lc,"defaultedConfig");function Dc(e){return e===ce?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}a(Dc,"migratedFromOf");function Fc(){let e=new Set([ce]);for(let t of Br)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}a(Fc,"knownInputVersions");function $c(e,t="ark.config.json"){if(!ge(e))throw new ke(t,[{path:"$",message:`must be an object; received ${dt(e)}`}]);let n=Fc(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new ke(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected ${ce}`}]);if(r!=="unversioned"&&!n.has(r))throw new ke(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${ce}`}]);let o=r,s={...e},i=0;for(;o!==ce&&i<Br.length+1;){i+=1;let l=Br.find(c=>c.from===o);if(!l)throw new ke(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(o)}; expected ${ce}`}]);o=l.to,s.schemaVersion=o}if(o!==ce)throw new ke(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${ce}`}]);return{candidate:Lc(s),migratedFrom:Dc(r)}}a($c,"migrateArkConfig");function Wr(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=$c(e,t),o=[];if(jt(n,ti,"$",ti,o),Xs(n,o),Zs(n,o),Nc(n,o),yc(n,o),kc(n,o),Tc(n,o),o.length>0)throw new ke(t,o);return{config:n,migratedFrom:r}}a(Wr,"loadArkConfigContract");function ci(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new ke(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return Wr(n,t)}a(ci,"parseArkConfigJson");function di(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:qn,schemaVersion:ce};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}a(di,"withArkConfigMetadata");function pt(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}a(pt,"trimTrailingSlashes");function Mc(e){return e.endsWith(".")?e:`${e}.`}a(Mc,"normalizePrefix");function Hc(e,t){let n=e.prefixes.length?Math.max(...e.prefixes.map(o=>o.length)):0;return(t.prefixes.length?Math.max(...t.prefixes.map(o=>o.length)):0)-n}a(Hc,"byLongestPrefix");function Xn(e){let t=e.layers.map(o=>({...o,prefixes:o.prefixes.map(Mc)})),n=[...t].sort(Hc),r=[...e.rules??[]];return{name:e.name,layers:t,rules:r,resolveLayer(o){return t.find(s=>s.match?.(o))?.name??n.find(s=>s.prefixes.some(i=>o.startsWith(i)))?.name}}}a(Xn,"createArchitectureProfile");function Zn(e,t={}){return Xn({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,r)=>({name:n.name,prefixes:n.intentPrefixes??[],description:n.description,trustBoundary:n.trustBoundary,owners:n.owners,order:r+1})),rules:e.rules??[]})}a(Zn,"createArchitectureProfileFromArkConfig");var Kc=[{name:"DomainModel",prefixes:["Domain"],description:"Rich domain model, business rules, and domain events.",order:1},{name:"ApplicationOrchestration",prefixes:["Application"],description:"Use cases and command orchestration.",order:2},{name:"PersistenceAdapters",prefixes:["Adapter.Persistence","Adapter.Repository"],description:"Database, repository, and storage adapters.",order:3},{name:"IntegrationAdapters",prefixes:["Adapter.Integration","Adapter.External"],description:"External systems, APIs, and integration adapters.",order:4},{name:"WorkflowSagaEngine",prefixes:["Workflow"],description:"Sagas, workflows, and long-running processes.",order:5},{name:"BackgroundJobsScheduling",prefixes:["Job"],description:"Background jobs, scheduled work, and async processors.",order:6},{name:"PresentationAdapters",prefixes:["Presentation","Adapter.Presentation","Adapter.Api"],description:"API, UI, controller, and presentation adapters.",order:7},{name:"ReportingReadModels",prefixes:["Reporting"],description:"Read models, projections, and reporting surfaces.",order:8},{name:"ExtensibilityMetadata",prefixes:["Metadata"],description:"Metadata, extensions, and schema contracts.",order:9},{name:"SecurityAuditObservability",prefixes:["Security","Audit","Observability"],description:"Security, audit, and observability concerns.",order:10},{name:"Kernel",prefixes:["Kernel"],description:"Ark-owned governance and kernel signals.",order:11}],ft=Xn({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:Kc,rules:Yn.map(e=>({...e}))}),Gc={DomainModel:["domain"],ApplicationOrchestration:["application","app"],PersistenceAdapters:["adapters/persistence","adapters/repository","repositories","infra/persistence"],IntegrationAdapters:["adapters/integration","adapters/external","integrations"],WorkflowSagaEngine:["workflows","sagas"],BackgroundJobsScheduling:["jobs","schedules"],PresentationAdapters:["presentation","adapters/presentation","adapters/api"],ReportingReadModels:["reporting","read-models","projections"],ExtensibilityMetadata:["metadata","extensions"],SecurityAuditObservability:["security","audit","observability"],Kernel:["kernel"]};function ui(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return di({include:e.include??[t],layers:ft.layers.map(o=>({name:o.name,patterns:(Gc[o.name]??[o.name]).map(s=>`${r}${s}/**`),intentPrefixes:o.prefixes,optional:n})),rules:[...ft.rules]})}a(ui,"createElevenLayerArkConfig");var Jn=class{static{a(this,"MetadataRegistryImpl")}entities=new Map;entity(t,n,r={}){if(this.entities.has(t)&&!r.allowOverwrite)throw new Error(`Entity metadata "${t}" is already registered.`);let o={name:t,fields:{},...n};return this.entities.set(t,o),o}getEntity(t){return this.entities.get(t)}listEntities(){return Array.from(this.entities.values())}findEntitiesByIntent(t){return this.listEntities().filter(n=>n.emits?.includes(t)||n.consumes?.includes(t))}validate(){let t=[];for(let n of this.entities.values()){n.name.trim()||t.push({entity:n.name,message:"Entity name is required."});for(let[r,o]of Object.entries(n.fields))r.trim()||t.push({entity:n.name,field:r,message:"Field name is required."}),(!o.type||typeof o.type!="string")&&t.push({entity:n.name,field:r,message:"Field type must be a non-empty string."}),o.relation&&!this.entities.has(o.relation.entity)&&t.push({entity:n.name,field:r,message:`Related entity "${o.relation.entity}" is not registered.`})}return{ok:t.length===0,issues:t}}toJSON(){return this.listEntities()}};function Qn(){return new Jn}a(Qn,"createMetadataRegistry");function pi(e,t={}){return{name:e,ownerLayer:t.ownerLayer,intent:t.intent,allowedAdapters:t.allowedAdapters?[...t.allowedAdapters]:void 0}}a(pi,"definePort");function fi(e,t,n,r={}){let o=Array.isArray(n)?{...r,requiredKeys:n}:{...n??{}},s=o.requiredKeys;if(s&&s.length>0){let c=s.filter(u=>!mi(t,u));if(c.length>0)throw new Error(`Adapter for port "${e.name}" is missing required members: ${c.join(", ")}`)}let i={name:o.name,layer:o.layer,intent:o.intent,port:e,impl:t},l=zr(i);if(!l.ok)throw new Error(l.issues.map(c=>c.message).join(`
21
+ `));return i}a(fi,"createAdapter");function gi(e,t=[]){let n=t.filter(r=>!mi(e,r));return n.length===0?{ok:!0}:{ok:!1,missing:n}}a(gi,"checkContract");function zr(e){let t=e.port.allowedAdapters??[];return t.length===0?{ok:!0,issues:[]}:[e.name,e.intent].filter(o=>typeof o=="string"&&o.length>0).some(o=>t.includes(o))?{ok:!0,issues:[]}:{ok:!1,issues:[{ruleId:"ADAPTER_NOT_ALLOWED_FOR_PORT",port:e.port.name,adapter:e.name??e.intent,message:`Adapter "${e.name??e.intent??"unknown"}" is not allowed for port "${e.port.name}".`}]}}a(zr,"checkAdapterGovernance");function mi(e,t){return e!=null&&(typeof e=="object"||typeof e=="function")&&t in e}a(mi,"hasMember");var Yr=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),Zr=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Jr=Object.freeze(Object.keys(Zr).sort()),qr=Object.freeze({fs:"filesystem","node:fs":"filesystem","fs/promises":"filesystem","node:fs/promises":"filesystem","fs-extra":"filesystem","graceful-fs":"filesystem",memfs:"filesystem",chokidar:"filesystem",http:"network",https:"network",http2:"network",net:"network",tls:"network",dgram:"network",dns:"network","node:http":"network","node:https":"network","node:http2":"network","node:net":"network","node:tls":"network","node:dgram":"network","node:dns":"network",axios:"network",undici:"network","node-fetch":"network",got:"network",ky:"network",superagent:"network",ws:"network",process:"process","node:process":"process",child_process:"process","node:child_process":"process","@prisma/client":"persistence",prisma:"persistence",pg:"persistence",mysql:"persistence",mysql2:"persistence",mongodb:"persistence",mongoose:"persistence",sqlite3:"persistence","better-sqlite3":"persistence",redis:"persistence",ioredis:"persistence",typeorm:"persistence",knex:"persistence","drizzle-orm":"persistence",sequelize:"persistence",kysely:"persistence","@supabase/supabase-js":"persistence"}),Xr=Object.freeze({process:Object.freeze(["process","node:process"])});function Bt(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=qr[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),o=qr[r];if(o)return o;let s=e.indexOf("/",n+1);return s<0?null:qr[e.slice(0,s)]??null}a(Bt,"capabilityForModuleSpecifier");function _e(e,t){for(let n of t)if(Xr[n]?.includes(e))return n;return null}a(_e,"forbiddenGlobalForModuleSpecifier");function er(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),o=Zr[r];if(o)return o}return null}a(er,"capabilityForAmbientName");function gt(e){if(e?.pure===!0)return[...Yr].sort();let n=(e?.capabilities?.deny??[]).filter(r=>Yr.includes(r));return[...new Set(n)].sort()}a(gt,"effectiveCapabilityDeny");function Wt(e,t){if(t.length===0)return!1;let n=new Set(t),r=e.split(".");for(let o=r.length;o>=1;o-=1)if(n.has(r.slice(0,o).join(".")))return!0;return!1}a(Wt,"ambientCoveredByForbiddenGlobals");function tr(e){let t=new Set,n=new Set,r=Object.keys(Zr);for(let o of e?.forbiddenGlobals??[]){let s=r.filter(i=>i===o||i.startsWith(`${o}.`));if(s.length===0)n.add(o);else for(let i of s)t.add(`ambient:${i}`);for(let i of Xr[o]??[])t.add(`import-exact:${i}`)}for(let o of gt(e)){if(t.add(`import:${o}`),o==="process")for(let s of Xr.process)t.add(`import-exact:${s}`);for(let s of r)er(s)===o&&t.add(`ambient:${s}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}a(tr,"loweredLayerCoverage");function mt(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}a(mt,"literalText");function Ri(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}a(Ri,"lineOf");function yi(e,t){if(e.isImportDeclaration(t)){let r=t.importClause;if(!r)return!1;if(r.isTypeOnly)return!0;let o=r.namedBindings;return!!(o&&e.isNamedImports(o)&&o.elements.length>0&&o.elements.every(s=>s.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(r=>r.isTypeOnly))}a(yi,"isTypeOnlyReference");function Ai(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=o=>o===t.fileName?t:void 0,r.fileExists=o=>o===t.fileName,r.readFile=o=>o===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}a(Ai,"singleFileChecker");function Qr(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}a(Qr,"symbolAt");function eo(e,t,n,r){let o=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,s;try{s=o?t.getShorthandAssignmentValueSymbol(r.parent):Qr(t,r)}catch{s=void 0}return!!s?.declarations?.some(i=>i.getSourceFile().fileName===n.fileName)}a(eo,"localDeclaration");function yt(e,t){let n,r=[],o=a((i,l,c,u=!1)=>r.push({specifier:c,kind:l,line:Ri(t,i),typeOnly:u,unresolved:c===void 0,node:i}),"add"),s=a(i=>{if(e.isImportDeclaration(i))o(i,"import",mt(e,i.moduleSpecifier),yi(e,i));else if(e.isExportDeclaration(i)&&i.moduleSpecifier)o(i,"export",mt(e,i.moduleSpecifier),yi(e,i));else if(e.isImportEqualsDeclaration(i)&&e.isExternalModuleReference(i.moduleReference))o(i,"require",mt(e,i.moduleReference.expression),i.isTypeOnly===!0);else if(e.isCallExpression(i)){let l=i.expression.kind===e.SyntaxKind.ImportKeyword,u=e.isIdentifier(i.expression)&&i.expression.text==="require"&&!eo(e,n??(n=Ai(e,t)),t,i.expression);(l||u)&&o(i,u?"require":"dynamic-import",mt(e,i.arguments[0]))}e.forEachChild(i,s)},"visit");return s(t),r}a(yt,"extractSemanticDependencies");function Uc(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let o=mt(e,r.argumentExpression);if(o===void 0)return;n.unshift(o)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}a(Uc,"staticAccessPath");function Vc(e,t){let n=t.parent;return e.isPropertyAccessExpression(n)||e.isElementAccessExpression(n)?!1:e.isExpressionNode(t)&&!e.isInTypeQuery(t)||e.isShorthandPropertyAssignment(n)&&n.name===t}a(Vc,"runtimeIdentifierReference");function hi(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let r=n.length;r>=1;r-=1){let o=n.slice(0,r).join(".");if(e.has(o))return o}}a(hi,"bestForbiddenMatch");function ht(e,t,n){if(n.length===0)return[];let r=new Set(n),o=Ai(e,t),s=new Map,i=new Set;for(let p of t.statements)if(e.isVariableStatement(p))for(let g of p.declarationList.declarations)e.isIdentifier(g.name)&&i.add(g.name.text);let l=a(p=>{let g=Uc(e,p);if(!g)return;let d=Qr(o,g.root),m=d?s.get(d):void 0;return m?[...m,...g.segments.slice(1)]:eo(e,o,t,g.root)||i.has(g.root.text)?void 0:g.segments},"resolvePath");for(let p of t.statements)if(e.isVariableStatement(p))for(let g of p.declarationList.declarations){if(!g.initializer||!e.isIdentifier(g.name))continue;let d=l(g.initializer),m=Qr(o,g.name);!d||!m||s.set(m,d)}let c=[],u=new Set,f=a((p,g)=>{let d=Ri(t,g),m=`${p}:${g.getStart(t)}`;u.has(m)||(u.add(m),c.push({name:p,line:d,node:g}))},"flag"),y=a(p=>{let g=p.parent&&(e.isPropertyAccessExpression(p.parent)||e.isElementAccessExpression(p.parent))&&p.parent.expression===p;if((e.isPropertyAccessExpression(p)||e.isElementAccessExpression(p))&&!g){let d=l(p),m=d?hi(r,d):void 0;m&&f(m,p)}else e.isIdentifier(p)&&r.has(p.text)&&Vc(e,p)&&!eo(e,o,t,p)&&f(p.text,p);if(e.isVariableDeclaration(p)&&e.isObjectBindingPattern(p.name)&&p.initializer){let d=l(p.initializer);if(d)for(let m of p.name.elements){if(!e.isIdentifier(m.name))continue;let b=m.propertyName?mt(e,m.propertyName)??m.propertyName.text:m.name.text,v=hi(r,[...d,b]);v&&f(v,p.initializer)}}e.forEachChild(p,y)},"visit");return y(t),c}a(ht,"collectForbiddenCapabilityUses");function to(e,t,n){let r=[];for(let o of n?.dependencies??yt(e,t)){if(o.typeOnly||!o.specifier)continue;let s=Bt(o.specifier);s&&r.push({capability:s,symbol:o.specifier,line:o.line,source:"import-based"})}for(let o of n?.ambientUses??ht(e,t,Jr)){let s=er(o.name);s&&r.push({capability:s,symbol:o.name,line:o.line,source:"ambient-global"})}return r.sort((o,s)=>o.line-s.line||o.capability.localeCompare(s.capability)||o.symbol.localeCompare(s.symbol))}a(to,"collectCapabilityUses");var no={RAW_EVENT_PUBLISH:"Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts and tooling.",PUBLISH_MISSING_SOURCE:"Strict Ark publish calls must include metadata.source."},ro=Object.freeze([{layer:"DomainModel",prefixes:["Domain."]},{layer:"ApplicationOrchestration",prefixes:["Application."]},{layer:"PersistenceAdapters",prefixes:["Adapter.Persistence.","Adapter.Repository."]},{layer:"IntegrationAdapters",prefixes:["Adapter.Integration.","Adapter.External."]},{layer:"WorkflowSagaEngine",prefixes:["Workflow."]},{layer:"BackgroundJobsScheduling",prefixes:["Job."]},{layer:"PresentationAdapters",prefixes:["Presentation.","Adapter.Presentation.","Adapter.Api."]},{layer:"ReportingReadModels",prefixes:["Reporting."]},{layer:"ExtensibilityMetadata",prefixes:["Metadata."]},{layer:"SecurityAuditObservability",prefixes:["Security.","Audit.","Observability."]},{layer:"Kernel",prefixes:["Kernel."]}]);function oo(e,t){return t.flatMap((r,o)=>(r.prefixes??r.intentPrefixes??[]).map(s=>({layer:r.name,layerIndex:o,prefix:s.endsWith(".")?s:`${s}.`}))).filter(({prefix:r})=>e.startsWith(r)).sort((r,o)=>o.prefix.length-r.prefix.length||r.layerIndex-o.layerIndex)[0]?.layer}a(oo,"resolveIntentLayer");function je(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}a(je,"looksLikeArkIntent");function zt(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&je(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:no.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:no.PUBLISH_MISSING_SOURCE}),t}a(zt,"classifyPublishFacts");function B(e,t,n){return{ruleId:e,code:e,message:t,...n}}a(B,"violation");function Rt(e,t){return e.slice(0,t).split(`
22
+ `).length}a(Rt,"lineOf");var jc=new Set(["publish","subscribe","defineIntent","registerHandler"]);function Bc(e,t){return e.index+e[0].indexOf(t)}a(Bc,"captureIndex");function Wc(e){let t=[],n=new Set,r=a((l,c)=>{!l||n.has(c)||(n.add(c),t.push({value:l,index:c}))},"push"),o=a(l=>{l.lastIndex=0;let c;for(;(c=l.exec(e))!==null;){let u=c[1];u&&r(u,Bc(c,u))}},"pushFrom");o(/\b(?:publish|subscribe|defineIntent|registerHandler)\s{0,8}(?:<[^>]{0,120}>)?\s{0,8}\(\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),o(/\b(?:intent|onEvent)\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g);let s=/\breactsTo\s{0,8}:\s{0,8}\[([^\]]{0,2000})\]/g,i;for(;(i=s.exec(e))!==null;){let l=i[1]??"",c=i.index+i[0].indexOf(l),u=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,f;for(;(f=u.exec(l))!==null;){let y=f[1];y&&r(y,c+f.index+f[0].indexOf(y))}}return o(/\bmetadata\s{0,8}:\s{0,8}\{[^}]{0,400}\bsource\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),o(/\bpublish\s{0,8}(?:<[^>]{0,120}>)?\s{0,8}\([^;]{0,400}?\bsource\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),t.sort((l,c)=>l.index-c.index)}a(Wc,"extractQuotedStrings");function zc(e){let t=[],n=[{kind:"import",re:/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s*)?['"]([^'"]+)['"]/g},{kind:"export",re:/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s*['"]([^'"]+)['"]/g},{kind:"dynamic-import",re:/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g},{kind:"require",re:/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g}];for(let r of n){let o;for(;(o=r.re.exec(e))!==null;){let s=o.index+o[0].indexOf(o[1]),i=o[0],l=r.kind==="import"&&/\bimport\s+type\b/.test(i)||r.kind==="export"&&/\bexport\s+type\b/.test(i);t.push({value:o[1],index:s,kind:r.kind,typeOnly:l})}}return t.sort((r,o)=>r.index-o.index)}a(zc,"extractModuleSpecifiers");function qc(e,t){return!!(t&&(e.isParenthesizedExpression(t)||e.isAsExpression(t)||typeof e.isTypeAssertionExpression=="function"&&e.isTypeAssertionExpression(t)||typeof e.isSatisfiesExpression=="function"&&e.isSatisfiesExpression(t)))}a(qc,"isSyntaxWrapper");function so(e,t){let n=t;for(;n?.parent&&qc(e,n.parent);)n=n.parent;return n}a(so,"unwrapWrappers");function io(e,t){if(!t||!e.isCallExpression(t))return;let n=t.expression;if(e.isIdentifier(n))return n.text;if(e.isPropertyAccessExpression(n))return n.name.text}a(io,"callCalleeName");function Yc(e,t){let n=t.parent;if(!n||!e.isObjectLiteralExpression(n))return!1;let r=so(e,n),o=r.parent;if(!o)return!1;if(e.isCallExpression(o)&&io(e,o)==="publish"){let s=o.arguments;return s[1]===r||s[2]===r}if(e.isPropertyAssignment(o)&&ao(e,o.name)==="metadata"){let s=o.parent;if(!s)return!1;let l=so(e,s).parent;return!!(l&&e.isCallExpression(l)&&io(e,l)==="publish")}return!1}a(Yc,"isPublishMetadataSource");function ki(e,t){let n=so(e,t),r=n.parent;if(!r)return!1;if(e.isCallExpression(r)){let o=io(e,r);if(o&&jc.has(o)&&r.arguments.some(s=>s===n))return!0}if(e.isArrayLiteralExpression(r))return ki(e,r);if(e.isPropertyAssignment(r)){let o=ao(e,r.name);if(o==="intent"||o==="onEvent"||o==="reactsTo"||o==="source"&&Yc(e,r))return!0}return!1}a(ki,"isDeclaredIntentSite");function Xc(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],o=a(s=>{e.isStringLiteralLike(s)&&ki(e,s)&&r.push({value:s.text,index:s.getStart(n)}),e.forEachChild(s,o)},"visit");return o(n),r}a(Xc,"extractQuotedStringsAst");function Zc(e){let t=e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);return["adapter","adapters","infra","infrastructure","persistence","repository","repositories","integration","database","db"].some(n=>t.includes(n))}a(Zc,"hasInfrastructureToken");function Jc(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}a(Jc,"isKnownInfrastructurePackage");function Qc(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}a(Qc,"layerHasInfrastructureRole");function Yt(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}a(Yt,"tsStringLiteralText");function ao(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}a(ao,"tsPropertyName");function Ii(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:ao(e,r.name)===n)}a(Ii,"tsObjectProperty");function Xt(e,t,n){return Ii(e,t,n)!==void 0}a(Xt,"tsObjectHasProperty");function qt(e,t,n){let r=Ii(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}a(qt,"tsObjectPropertyValue");function ed(e,t){let n=qt(e,t,"metadata");return Xt(e,n,"source")}a(ed,"tsObjectHasMetadataSource");function bi(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?bi(e,t.name):!1:!1}a(bi,"tsLooksLikeIntentCreatorExpression");function td(e,t){if(!e.isCallExpression(t))return!1;let n=t.expression;return e.isPropertyAccessExpression(n)?n.name.text==="publish":e.isIdentifier(n)&&n.text==="publish"}a(td,"tsIsPublishCall");function nd(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=Yt(e,n);return r!==void 0&&je(r)||Xt(e,n,"intent")||bi(e,n)}a(nd,"tsIsArkPublishCandidate");function rd(e,t){if(!e.isCallExpression(t))return!1;let[n,r,o]=t.arguments;return ed(e,n)||Xt(e,r,"source")||Xt(e,o,"source")}a(rd,"tsPublishHasSource");function od(e,t){if(!e.isCallExpression(t))return;let[n,r,o]=t.arguments,s=qt(e,n,"metadata");return Yt(e,qt(e,s,"source"))??Yt(e,qt(e,r,"source"))??Yt(e,qt(e,o,"source"))}a(od,"tsPublishSourceLiteral");function sd(e,t,n,r){let o=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),s=n,i=s?.filePath,l=s?.layer,c=[],u=a(y=>o.getLineAndCharacterOfPosition(y.getStart(o)).line+1,"lineForNode"),f=a(y=>{if(td(e,y)){let p=y.arguments[0],g=Yt(e,p);for(let m of zt({publishCall:!0,rawIntentName:g,objectHasIntent:Xt(e,p,"intent"),arkPublishCandidate:nd(e,y),hasSource:rd(e,y)}))c.push(B(m.ruleId,m.message,{line:u(y),filePath:i}));let d=od(e,y);if(r&&l&&d&&je(d)){let m=r.resolveLayer(d);m&&m!==l&&c.push(B("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${d}" resolves to ${m}, but the target file is classified as ${l}.`,{line:u(y),filePath:i,target:d,fromLayer:l,toLayer:m}))}}e.forEachChild(y,f)},"visit");return f(o),c}a(sd,"analyzePublishAst");function Si(e={}){let t=new Set((e.intents||[]).map(s=>typeof s=="string"?s:s.name)),n=e.forbiddenPatterns||[],r=new Set(e.infrastructureLayers??[]),o=e.enforceIntentAllowlist??t.size>0;return{validate(s,i){let l=[],c=i,u=c?.filePath,f=c?.layer,y=e.typescript,p=y?y.createSourceFile(u??"generated.ts",s,y.ScriptTarget.Latest,!0):void 0,g=p?yt(e.typescript,p):void 0,d=g?g.filter(k=>k.specifier!==void 0).map(k=>({value:k.specifier,index:k.node.getStart(p),kind:k.kind,typeOnly:k.typeOnly})):zc(s),m=e.typescript?Xc(e.typescript,s):Wc(s);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(u))for(let k of g?.filter(({unresolved:E})=>E)??[]){let E=k.kind==="require";l.push(B(E?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${E?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:k.line,filePath:u}))}let b=f!==void 0&&(r.has(f)||Qc(f)),v=f!==void 0?` If "${f}" is an infrastructure layer, mark it in ark.config.json with "mayImportInfrastructure": true (or name it with an infra token like Adapters/Persistence/Repository).`:"";for(let k of n)if(k instanceof RegExp){k.lastIndex=0;let E=k.exec(s);k.lastIndex=0,E&&l.push(B("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${k}`,{line:E.index===void 0?void 0:Rt(s,E.index),filePath:u,suggestion:"Remove infrastructure imports from domain/application layers."+v}))}else s.includes(k)&&l.push(B("FORBIDDEN_SUBSTRING",`Forbidden substring: ${k}`,{line:Rt(s,s.indexOf(k)),filePath:u}));for(let k of d){let E=e.resolveImportTarget?.(k.value,u)??(e.resolveImportLayer?{layer:e.resolveImportLayer(k.value,u)}:void 0),O=typeof u=="string"?e.resolveImportTarget?.(u)??(e.resolveImportLayer?{layer:f,relPath:void 0}:void 0):void 0,L=E?.layer;if(L&&f){let S=Pe(e.architectureProfile?.rules,f,L,{fromPath:O?.relPath,toPath:E?.relPath,layers:e.architectureLayers});if(S){let N=S.rule;if(k.typeOnly&&!N.peerIsolation)continue;let z=!!N.peerIsolation,Q=He(S.sliceVerdict),pe=N.message??(z?`Layer "${f}" must not import across slices into "${L}".`:`Layer "${f}" must not import "${L}".`),T=Q.reasonId||z&&!S.peerIsolationReason?S.sliceVerdict?.explanation:void 0;l.push(B("LAYER_IMPORT_VIOLATION",T?`${pe} ${T}`:pe,{line:Rt(s,k.index),source:k.value,target:k.value,filePath:u,fromLayer:f,toLayer:L,...Q.reasonId?{reasonId:Q.reasonId}:{},...Q.failsStrict===!1?{failsStrict:!1}:{},suggestion:z?"Extract shared code to a shared layer, or coordinate slices via events/ports \u2014 do not import across feature/context slices.":"Depend on a port/interface owned by an inner layer instead, or move this code to a layer allowed to make this import.",details:{importKind:k.kind,peerIsolation:z,...k.typeOnly?{typeOnly:!0}:{},...Q.reasonId?{reasonId:Q.reasonId}:{}}}));continue}continue}b||k.typeOnly||!Zc(k.value)&&!Jc(k.value)||l.push(B("FORBIDDEN_IMPORT",`Forbidden ${k.kind} target: "${k.value}".`,{line:Rt(s,k.index),source:k.value,target:k.value,filePath:u,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+v,details:{importKind:k.kind}}))}if(e.policies)for(let k of e.policies){let E=k.check({source:s,context:i});if(E!==!0)if(Array.isArray(E))for(let O of E)l.push(B("POLICY_VIOLATION",O.message,{filePath:u,suggestion:`Fix violation of policy "${k.name}".`}));else E===!1?l.push(B("POLICY_VIOLATION",`Policy ${k.name} failed on generated code`)):l.push(B("POLICY_VIOLATION",E.message))}if(o&&t.size>0)for(let k of m)je(k.value)&&!t.has(k.value)&&l.push(B("UNKNOWN_INTENT",`Unknown intent reference: "${k.value}"`,{line:Rt(s,k.index),filePath:u,target:k.value,suggestion:`Register intent "${k.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&f)for(let k of m){if(!je(k.value))continue;let E=e.architectureProfile.resolveLayer(k.value);if(!E)continue;let O=Pe(e.architectureProfile.rules,f,E,{fromPath:typeof u=="string"?u:void 0,layers:e.architectureLayers});if(O){let L=O.sliceVerdict,S=`Layer "${f}" must not reference "${E}" through "${k.value}".`,N=L?lt({surface:"intent",verdict:L,fromLayer:f,toLayer:E,fromPath:typeof u=="string"?u:void 0,ruleMessage:O.rule.message,defaultMessage:S}):O.rule.message??S,z=He(L);l.push(B("LAYER_REFERENCE_VIOLATION",N,{line:Rt(s,k.index),filePath:u,target:k.value,fromLayer:f,toLayer:E,...z.reasonId?{reasonId:z.reasonId}:{},...z.failsStrict===!1?{failsStrict:!1}:{},suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:O.rule,peerIsolationReason:O.peerIsolationReason,...z.reasonId?{reasonId:z.reasonId}:{}}}))}}if(e.extensions)for(let k of e.extensions)try{let E=k.analyze(s,i);l.push(...E)}catch(E){l.push(B("EXTENSION_ERROR",`Extension "${k.name}" failed: ${E instanceof Error?E.message:String(E)}`))}if(e.typescript&&p&&f&&e.forbiddenGlobals?.[f]?.length)try{let k=e.forbiddenGlobals[f];l.push(...ht(e.typescript,p,k).map(E=>B("FORBIDDEN_GLOBAL",`${f} must not use the ambient global "${E.name}".`,{line:E.line,filePath:u,target:E.name,fromLayer:f,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let E of g??[]){if(E.typeOnly||!E.specifier)continue;let O=_e(E.specifier,k);O&&l.push(B("FORBIDDEN_GLOBAL",`${f} must not use module "${E.specifier}" because it is the import form of forbidden global "${O}".`,{line:E.line,filePath:u,source:E.specifier,target:E.specifier,fromLayer:f,details:{importKind:E.kind,forbiddenGlobal:O},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(k){l.push(B("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${k instanceof Error?k.message:String(k)}`))}if(e.typescript&&p&&f&&e.capabilityWalls?.[f]?.length)try{let k=new Set(e.capabilityWalls[f]),E=e.forbiddenGlobals?.[f]??[];for(let O of to(e.typescript,p))k.has(O.capability)&&(O.source==="ambient-global"&&Wt(O.symbol,E)||O.source==="import-based"&&_e(O.symbol,E)||l.push(B("CAPABILITY_VIOLATION",O.source==="import-based"?`${f} denies the ${O.capability} capability; found import of "${O.symbol}".`:`${f} denies the ${O.capability} capability; found ambient "${O.symbol}".`,{line:O.line,filePath:u,target:O.symbol,capability:O.capability,fromLayer:f,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(k){l.push(B("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${k instanceof Error?k.message:String(k)}`))}if(e.typescript)try{l.push(...sd(e.typescript,s,i,e.architectureProfile))}catch(k){l.push(B("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${k instanceof Error?k.message:String(k)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:!l.some(k=>k.failsStrict!==!1),violations:l}}}}a(Si,"createAICodeGate");function Z(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")}`}a(Z,"deterministicHash");function M(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(M).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${M(t[n])}`).join(",")}}`}a(M,"stableSerialize");var Be="1.2";var vi=["network","filesystem","clock","randomness","environment","process","persistence"];function W(e,t){let n=M(e),r=M(t);return n<r?-1:n>r?1:0}a(W,"compareCanonical");function te(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}a(te,"sortedUnique");function Zt(e){let t={schemaVersion:"1.2",include:te(e.include??[]),exclude:te(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:te(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:te(n.patterns??[]),exclude:te(n.exclude??[]),forbiddenGlobals:te(n.forbiddenGlobals??[]),intentPrefixes:te(n.intentPrefixes??[]),capabilityDeny:te(n.capabilities?.deny??[]),pure:n.pure===!0})).sort(W),safety:{maxTsSuppressions:e.safety?.maxTsSuppressions??0,maxAnyCasts:e.safety?.maxAnyCasts??0,allowInMemory:e.safety?.allowInMemory===!0,allowDisabledPeerIsolation:e.safety?.allowDisabledPeerIsolation===!0},...e.arkRun?{arkRun:{mode:e.arkRun.mode,compositionRoots:te(e.arkRun.compositionRoots),managedLayers:te(e.arkRun.managedLayers),requireDeclarations:e.arkRun.requireDeclarations===!0}}:{}};return Z(M(t))}a(Zt,"resolvedFactsEvidenceRequirementsHash");function id(e){let t=e.completenessReasons.map(S=>({code:S.code,message:S.message,...S.file?{file:S.file}:{}})).sort(W),n=e.files.map(S=>({...S,typeOnlyExportNames:te(S.typeOnlyExportNames)})).sort((S,N)=>S.path<N.path?-1:S.path>N.path?1:0),r=e.dependencies.map(S=>({...S,...S.namedBindings?{namedBindings:te(S.namedBindings)}:{}})).sort(W),o=e.capabilityUses.map(S=>({...S})).sort(W),s=e.ambientUses.map(S=>({...S})).sort(W),i=e.publishCalls.map(S=>({...S})).sort(W),l=e.intentReferences.map(S=>({...S})).sort(W),c=e.safetyUses.map(S=>({...S})).sort(W),u=(e.classShapes??[]).map(S=>({...S,mutatingMethods:[...S.mutatingMethods??[]].map(N=>({...N}))})).sort(W),f=(e.arkRunKernelCalls??[]).map(S=>({...S})).sort(W),y=(e.arkRunManagedNews??[]).map(S=>({...S})).sort(W),p=(e.arkRunCompositionRootHits??[]).map(S=>({...S})).sort(W),g=(e.arkRunDeclarations??[]).map(S=>({...S,uses:te(S.uses),reactsTo:te(S.reactsTo),raises:te(S.raises),sends:te(S.sends)})).sort(W),d=(e.arkOrderPlaneCalls??[]).map(S=>({...S})).sort(W),m=(e.arkOrderGenericUpdates??[]).map(S=>({...S})).sort(W),b=(e.arkOrderRootHits??[]).map(S=>({...S})).sort(W),v=(e.arkOrderXiFieldWrites??[]).map(S=>({...S})).sort(W),k=(e.arkOrderIngestWritesXi??[]).map(S=>({...S})).sort(W),E=(e.arkOrderReleaseKeyCounts??[]).map(S=>({...S})).sort(W),O=e.files.map(({path:S,contentHash:N})=>({path:S,contentHash:N})).sort((S,N)=>S.path<N.path?-1:S.path>N.path?1:0),L=Z(M(O));return{schemaVersion:"1.2",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:L,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:r,capabilityUses:o,ambientUses:s,publishCalls:i,intentReferences:l,safetyUses:c,classShapes:u,arkRunKernelCalls:f,arkRunManagedNews:y,arkRunCompositionRootHits:p,arkRunDeclarations:g,arkOrderPlaneCalls:d,arkOrderGenericUpdates:m,arkOrderRootHits:b,arkOrderXiFieldWrites:v,arkOrderIngestWritesXi:k,arkOrderReleaseKeyCounts:E}}a(id,"canonicalResolvedFactsInput");function Ei(e){let t=id(e);return{...t,factsHash:Z(M(t))}}a(Ei,"createCanonicalResolvedCandidateFacts");function lo(e){return Ei(Ci($(e,"$"),!1))}a(lo,"createResolvedCandidateFacts");function $(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}a($,"asRecord");function H(e,t,n){let r=new Set(t),o=Object.keys(e).find(s=>!r.has(s));if(o)throw new Error(`${n}.${o} is not part of schema ${"1.2"}.`)}a(H,"assertOnlyKeys");function F(e,t,n){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`${n}.${t} must be a non-empty string.`);return r}a(F,"requiredText");function Ie(e,t,n){if(e[t]!==void 0)return F(e,t,n)}a(Ie,"optionalText");function G(e,t,n){let r=F(e,t,n),o=r.replace(/\\/g,"/");if(!o||o.startsWith("/")||/^[A-Za-z]:\//.test(o)||/[\u0000-\u001f\u007f]/.test(o))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let s=[];for(let l of o.split("/"))if(!(!l||l==="."))if(l===".."){if(s.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);s.pop()}else s.push(l);let i=s.join("/");if(!i||i!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return i}a(G,"requiredProjectPath");function U(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}a(U,"requiredBoolean");function wi(e,t,n){let r=e[t];if(!Number.isInteger(r)||Number(r)<0)throw new Error(`${n}.${t} must be a non-negative integer.`);return Number(r)}a(wi,"requiredInteger");function ne(e,t,n){let r=wi(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}a(ne,"requiredPositiveInteger");function V(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}a(V,"requiredArray");function be(e,t,n,r){let o=e[t];if(typeof o!="string"||!n.includes(o))throw new Error(`${r}.${t} must be one of ${n.join(", ")}.`);return o}a(be,"enumValue");function At(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!n))throw new Error(`${t} must be an array of non-empty strings.`);return[...e]}a(At,"parseStringArray");function ad(e,t,n){let r=new Set;for(let o of e){let s=t(o);if(r.has(s))throw new Error(`${n} must not contain duplicate facts (${s}).`);r.add(s)}}a(ad,"assertUnique");function Ci(e,t){H(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","classShapes","arkRunKernelCalls","arkRunManagedNews","arkRunCompositionRootHits","arkRunDeclarations","arkOrderPlaneCalls","arkOrderGenericUpdates","arkOrderRootHits","arkOrderXiFieldWrites","arkOrderIngestWritesXi","arkOrderReleaseKeyCounts",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=be(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=be(e,"completeness",["complete","partial","unavailable"],"$"),o=V(e,"completenessReasons","$").map((w,x)=>{let h=`$.completenessReasons[${x}]`,A=$(w,h);H(A,["code","message","file"],h);let D=A.file===void 0?void 0:G(A,"file",h);return{code:F(A,"code",h),message:F(A,"message",h),...D?{file:D}:{}}});if(r==="complete"&&o.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(r!=="complete"&&o.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let s=V(e,"files","$").map((w,x)=>{let h=`$.files[${x}]`,A=$(w,h);return H(A,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],h),{path:G(A,"path",h),contentHash:F(A,"contentHash",h),parseStatus:be(A,"parseStatus",["parsed","invalid"],h),parseDiagnosticCount:wi(A,"parseDiagnosticCount",h),exportsOnlyTypes:U(A,"exportsOnlyTypes",h),typeOnlyExportNames:At(A.typeOnlyExportNames,`${h}.typeOnlyExportNames`),hasTopLevelSideEffects:U(A,"hasTopLevelSideEffects",h)}}),i=V(e,"dependencies","$").map((w,x)=>{let h=`$.dependencies[${x}]`,A=$(w,h);H(A,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],h);let D=Ie(A,"specifier",h),q=Ie(A,"target",h),Ce=be(A,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],h);if(Ce==="resolved-project"&&!q)throw new Error(`${h}.target is required for resolved-project dependencies.`);if(Ce!=="resolved-project"&&q)throw new Error(`${h}.target is only allowed for resolved-project dependencies.`);if(Ce!=="dynamic"&&!D)throw new Error(`${h}.specifier is required unless resolution is dynamic.`);return{from:G(A,"from",h),...D?{specifier:D}:{},kind:be(A,"kind",["import","export","dynamic-import","require"],h),typeOnly:U(A,"typeOnly",h),line:ne(A,"line",h),resolution:Ce,...q?{target:G(A,"target",h)}:{},...A.namedBindings!==void 0?{namedBindings:At(A.namedBindings,`${h}.namedBindings`)}:{},...A.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:U(A,"targetTypeOnlyExports",h)}:{},...A.sourcePureTypeModule!==void 0?{sourcePureTypeModule:U(A,"sourcePureTypeModule",h)}:{},...A.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:U(A,"namedBindingsTypeOnly",h)}:{},...A.portProofEligible!==void 0?{portProofEligible:U(A,"portProofEligible",h)}:{}}}),l=V(e,"capabilityUses","$").map((w,x)=>{let h=`$.capabilityUses[${x}]`,A=$(w,h);return H(A,["file","line","symbol","capability","source"],h),{file:G(A,"file",h),line:ne(A,"line",h),symbol:F(A,"symbol",h),capability:be(A,"capability",vi,h),source:be(A,"source",["ambient-global","import-based"],h)}}),c=V(e,"ambientUses","$").map((w,x)=>{let h=`$.ambientUses[${x}]`,A=$(w,h);return H(A,["file","line","symbol"],h),{file:G(A,"file",h),line:ne(A,"line",h),symbol:F(A,"symbol",h)}}),u=V(e,"publishCalls","$").map((w,x)=>{let h=`$.publishCalls[${x}]`,A=$(w,h);H(A,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],h);let D=Ie(A,"rawIntentName",h),q=Ie(A,"sourceIntent",h);return{file:G(A,"file",h),line:ne(A,"line",h),...D?{rawIntentName:D}:{},objectHasIntent:U(A,"objectHasIntent",h),arkPublishCandidate:U(A,"arkPublishCandidate",h),hasSource:U(A,"hasSource",h),...q?{sourceIntent:q}:{}}}),f=V(e,"intentReferences","$").map((w,x)=>{let h=`$.intentReferences[${x}]`,A=$(w,h);return H(A,["file","line","intent"],h),{file:G(A,"file",h),line:ne(A,"line",h),intent:F(A,"intent",h)}}),y=V(e,"safetyUses","$").map((w,x)=>{let h=`$.safetyUses[${x}]`,A=$(w,h);H(A,["file","line","kind","symbol"],h);let D=Ie(A,"symbol",h),q=be(A,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],h);if(q==="in-memory-store"&&!D)throw new Error(`${h}.symbol is required for in-memory-store facts.`);if(q!=="in-memory-store"&&D)throw new Error(`${h}.symbol is only allowed for in-memory-store facts.`);return{file:G(A,"file",h),line:ne(A,"line",h),kind:q,...D?{symbol:D}:{}}});ad(s,w=>w.path,"$.files");let p=new Set(s.map(w=>w.path));for(let w of s){if(w.parseStatus==="parsed"&&w.parseDiagnosticCount!==0)throw new Error(`$.files[${w.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(w.parseStatus==="invalid"&&w.parseDiagnosticCount===0)throw new Error(`$.files[${w.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&s.some(w=>w.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let w of i)if(!p.has(w.from))throw new Error(`$.dependencies references missing source file ${w.from}.`);let d=(e.arkRunKernelCalls===void 0?[]:V(e,"arkRunKernelCalls","$")).map((w,x)=>{let h=`$.arkRunKernelCalls[${x}]`,A=$(w,h);H(A,["file","line","kind","callee","viaImport","receiver","nameLiteral"],h);let D=Ie(A,"receiver",h),q=Ie(A,"nameLiteral",h);return{file:G(A,"file",h),line:ne(A,"line",h),kind:be(A,"kind",["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"],h),callee:F(A,"callee",h),viaImport:U(A,"viaImport",h),...D?{receiver:D}:{},...q?{nameLiteral:q}:{}}}),b=(e.arkRunManagedNews===void 0?[]:V(e,"arkRunManagedNews","$")).map((w,x)=>{let h=`$.arkRunManagedNews[${x}]`,A=$(w,h);H(A,["file","line","typeName","importedFrom"],h);let D=Ie(A,"importedFrom",h);return{file:G(A,"file",h),line:ne(A,"line",h),typeName:F(A,"typeName",h),...D?{importedFrom:D}:{}}}),k=(e.arkRunCompositionRootHits===void 0?[]:V(e,"arkRunCompositionRootHits","$")).map((w,x)=>{let h=`$.arkRunCompositionRootHits[${x}]`,A=$(w,h);return H(A,["file","matchedRoot","hasKernelFactory"],h),{file:G(A,"file",h),matchedRoot:F(A,"matchedRoot",h),hasKernelFactory:U(A,"hasKernelFactory",h)}}),E=e.arkRunDeclarations===void 0?[]:V(e,"arkRunDeclarations","$"),L=(e.arkOrderPlaneCalls===void 0?[]:V(e,"arkOrderPlaneCalls","$")).map((w,x)=>{let h=`$.arkOrderPlaneCalls[${x}]`,A=$(w,h);return H(A,["file","line","callee"],h),{file:G(A,"file",h),line:ne(A,"line",h),callee:F(A,"callee",h)}}),N=(e.arkOrderGenericUpdates===void 0?[]:V(e,"arkOrderGenericUpdates","$")).map((w,x)=>{let h=`$.arkOrderGenericUpdates[${x}]`,A=$(w,h);return H(A,["file","line","method"],h),{file:G(A,"file",h),line:ne(A,"line",h),method:F(A,"method",h)}}),Q=(e.arkOrderRootHits===void 0?[]:V(e,"arkOrderRootHits","$")).map((w,x)=>{let h=`$.arkOrderRootHits[${x}]`,A=$(w,h);return H(A,["file","matchedRoot","hasPlaneFactory"],h),{file:G(A,"file",h),matchedRoot:F(A,"matchedRoot",h),hasPlaneFactory:U(A,"hasPlaneFactory",h)}}),T=(e.arkOrderXiFieldWrites===void 0?[]:V(e,"arkOrderXiFieldWrites","$")).map((w,x)=>{let h=`$.arkOrderXiFieldWrites[${x}]`,A=$(w,h);return H(A,["file","line","key"],h),{file:G(A,"file",h),line:ne(A,"line",h),key:F(A,"key",h)}}),X=(e.arkOrderIngestWritesXi===void 0?[]:V(e,"arkOrderIngestWritesXi","$")).map((w,x)=>{let h=`$.arkOrderIngestWritesXi[${x}]`,A=$(w,h);return H(A,["file","line"],h),{file:G(A,"file",h),line:ne(A,"line",h)}}),we=(e.arkOrderReleaseKeyCounts===void 0?[]:V(e,"arkOrderReleaseKeyCounts","$")).map((w,x)=>{let h=`$.arkOrderReleaseKeyCounts[${x}]`,A=$(w,h);return H(A,["file","line","keyCount"],h),{file:G(A,"file",h),line:ne(A,"line",h),keyCount:ne(A,"keyCount",h)}}),Pt=E.map((w,x)=>{let h=`$.arkRunDeclarations[${x}]`,A=$(w,h);return H(A,["file","line","uses","reactsTo","raises","sends"],h),{file:G(A,"file",h),line:ne(A,"line",h),uses:At(A.uses,`${h}.uses`),reactsTo:At(A.reactsTo,`${h}.reactsTo`),raises:At(A.raises,`${h}.raises`),sends:At(A.sends,`${h}.sends`)}});for(let[w,x]of[["$.capabilityUses",l],["$.ambientUses",c],["$.publishCalls",u],["$.intentReferences",f],["$.safetyUses",y],["$.arkRunKernelCalls",d],["$.arkRunManagedNews",b],["$.arkRunCompositionRootHits",k],["$.arkRunDeclarations",Pt],["$.arkOrderPlaneCalls",L],["$.arkOrderGenericUpdates",N],["$.arkOrderRootHits",Q],["$.arkOrderXiFieldWrites",T],["$.arkOrderIngestWritesXi",X],["$.arkOrderReleaseKeyCounts",we]])for(let h of x)if(!p.has(h.file))throw new Error(`${w} references missing file ${h.file}.`);let En=Ie(e,"projectPackageName","$"),os=(e.classShapes===void 0?[]:V(e,"classShapes","$")).map((w,x)=>{let h=`$.classShapes[${x}]`,A=$(w,h);H(A,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],h);let D=V(A,"mutatingMethods",h).map((q,Ce)=>{let R=`${h}.mutatingMethods[${Ce}]`,re=$(q,R);return H(re,["name","referencesGuardOrPublish"],R),{name:F(re,"name",R),referencesGuardOrPublish:U(re,"referencesGuardOrPublish",R)}});return{file:G(A,"file",h),className:F(A,"className",h),exported:U(A,"exported",h),hasPublicMutableFields:U(A,"hasPublicMutableFields",h),hasPublicSetters:U(A,"hasPublicSetters",h),hasPublicConstructor:U(A,"hasPublicConstructor",h),hasStaticFactory:U(A,"hasStaticFactory",h),mutatingMethods:D,...A.dataOnly===void 0?{}:{dataOnly:U(A,"dataOnly",h)}}});return{schemaVersion:n,completeness:r,completenessReasons:o,resolverIdentity:F(e,"resolverIdentity","$"),compilerIdentity:F(e,"compilerIdentity","$"),compilerOptionsHash:F(e,"compilerOptionsHash","$"),tsconfigHash:F(e,"tsconfigHash","$"),evidenceRequirementsHash:F(e,"evidenceRequirementsHash","$"),...En?{projectPackageName:En}:{},files:s,dependencies:i,capabilityUses:l,ambientUses:c,publishCalls:u,intentReferences:f,safetyUses:y,classShapes:os,arkRunKernelCalls:d,arkRunManagedNews:b,arkRunCompositionRootHits:k,arkRunDeclarations:Pt,arkOrderPlaneCalls:L,arkOrderGenericUpdates:N,arkOrderRootHits:Q,arkOrderXiFieldWrites:T,arkOrderIngestWritesXi:X,arkOrderReleaseKeyCounts:we}}a(Ci,"parseResolvedFactsInput");function Te(e){let t=$(e,"$"),n=F(t,"factsHash","$"),r=F(t,"candidateTreeHash","$"),o=Ei(Ci(t,!0));if(o.factsHash!==n)throw new Error(`$.factsHash does not match the canonical payload (${o.factsHash}).`);if(r!==o.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${o.candidateTreeHash}).`);return o}a(Te,"loadResolvedCandidateFacts");var ld=["network","filesystem","clock","randomness","environment","process","persistence"],_={type:"string",minLength:1},oe={type:"integer",minimum:1},j={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},co={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.resolved-candidate-facts.schema.json",title:"ArkGate resolved candidate facts",type:"object",additionalProperties:!1,required:["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","candidateTreeHash","evidenceRequirementsHash","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","factsHash"],properties:{schemaVersion:{enum:["1.0","1.1","1.2"]},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:_,message:_,file:j}}},resolverIdentity:_,compilerIdentity:_,compilerOptionsHash:_,tsconfigHash:_,candidateTreeHash:_,evidenceRequirementsHash:_,projectPackageName:_,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:j,contentHash:_,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:_},hasTopLevelSideEffects:{type:"boolean"}},allOf:[{if:{properties:{parseStatus:{const:"parsed"}}},then:{properties:{parseDiagnosticCount:{const:0}}}},{if:{properties:{parseStatus:{const:"invalid"}}},then:{properties:{parseDiagnosticCount:{minimum:1}}}}]}},dependencies:{type:"array",items:{type:"object",additionalProperties:!1,required:["from","kind","typeOnly","line","resolution"],properties:{from:j,specifier:_,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:oe,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:j,namedBindings:{type:"array",items:_},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"}},allOf:[{if:{properties:{resolution:{const:"resolved-project"}}},then:{required:["target"]},else:{not:{required:["target"]}}},{if:{properties:{resolution:{const:"dynamic"}}},else:{required:["specifier"]}}]}},capabilityUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol","capability","source"],properties:{file:j,line:oe,symbol:_,capability:{enum:ld},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:j,line:oe,symbol:_}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:j,line:oe,rawIntentName:_,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:_}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:j,line:oe,intent:_}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:j,line:oe,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:_},allOf:[{if:{properties:{kind:{const:"in-memory-store"}}},then:{required:["symbol"]},else:{not:{required:["symbol"]}}}]}},classShapes:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods"],properties:{file:j,className:_,exported:{type:"boolean"},hasPublicMutableFields:{type:"boolean"},hasPublicSetters:{type:"boolean"},hasPublicConstructor:{type:"boolean"},hasStaticFactory:{type:"boolean"},dataOnly:{type:"boolean"},mutatingMethods:{type:"array",items:{type:"object",additionalProperties:!1,required:["name","referencesGuardOrPublish"],properties:{name:_,referencesGuardOrPublish:{type:"boolean"}}}}}}},arkRunKernelCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind","callee","viaImport"],properties:{file:j,line:oe,kind:{enum:["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"]},callee:_,viaImport:{type:"boolean"},receiver:_,nameLiteral:_}}},arkRunManagedNews:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","typeName"],properties:{file:j,line:oe,typeName:_,importedFrom:_}}},arkRunCompositionRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasKernelFactory"],properties:{file:j,matchedRoot:_,hasKernelFactory:{type:"boolean"}}}},arkRunDeclarations:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","uses","reactsTo","raises","sends"],properties:{file:j,line:oe,uses:{type:"array",items:_},reactsTo:{type:"array",items:_},raises:{type:"array",items:_},sends:{type:"array",items:_}}}},arkOrderPlaneCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","callee"],properties:{file:j,line:oe,callee:_}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:j,line:oe,method:_}}},arkOrderRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasPlaneFactory"],properties:{file:j,matchedRoot:_,hasPlaneFactory:{type:"boolean"}}}},arkOrderXiFieldWrites:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:j,line:oe,key:_}}},arkOrderIngestWritesXi:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line"],properties:{file:j,line:oe}}},arkOrderReleaseKeyCounts:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","keyCount"],properties:{file:j,line:oe,keyCount:{type:"integer",minimum:1}}}},factsHash:_},allOf:[{if:{properties:{completeness:{const:"complete"}}},then:{properties:{completenessReasons:{maxItems:0},files:{items:{properties:{parseStatus:{const:"parsed"}}}}}}},{if:{properties:{completeness:{enum:["partial","unavailable"]}}},then:{properties:{completenessReasons:{minItems:1}}}}]};var uo="1.0";function ie(e){return`${e.from}->${e.to}`}a(ie,"dependencyKey");function Jt(e,t,n,r="dependency"){return{id:`${e}:${r}:${ie(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${ie(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${ie(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${ie(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${ie(t)} from the candidate, then preflight again.`}:{}}}a(Jt,"dependencyFinding");function kt(e){let t=[],n=new Map(e.changeMap.map.files.map(p=>[p.path,p])),r=new Map(e.changes.map(p=>[p.path,p])),o=new Map(e.changeMap.map.dependencies.map(p=>[ie(p),p])),s=new Map(e.baseDependencies.map(p=>[ie(p),p])),i=new Map(e.candidateDependencies.map(p=>[ie(p),p]));for(let p of[...n.values()].sort((g,d)=>g.path.localeCompare(d.path))){let g=r.get(p.path);g?g.operation!==p.operation?t.push({id:`contradictory:file:${p.path}`,classification:"contradictory",subject:"file",path:p.path,expectedOperation:p.operation,actualOperation:g.operation,message:`${p.path} was planned as ${p.operation} but the actual operation is ${g.operation}.`,nextAction:`Change ${p.path} to the planned ${p.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${p.path}`,classification:"satisfied",subject:"file",path:p.path,expectedOperation:p.operation,actualOperation:g.operation,message:`${p.path} matches the planned ${p.operation} operation.`}):t.push({id:`missing:file:${p.path}`,classification:"missing",subject:"file",path:p.path,expectedOperation:p.operation,message:`${p.path} was planned as ${p.operation} but is absent from the actual change.`,nextAction:`${p.operation[0].toUpperCase()}${p.operation.slice(1)} ${p.path} in the complete change set, then preflight again.`})}for(let p of[...r.values()].sort((g,d)=>g.path.localeCompare(d.path)))n.has(p.path)||t.push({id:`unplanned:file:${p.path}`,classification:"unplanned",subject:"file",path:p.path,actualOperation:p.operation,message:`${p.path} has an unplanned ${p.operation} operation.`,nextAction:`Remove ${p.path} from the change set, then preflight again.`});let l=new Set;for(let p of[...o.values()].sort((g,d)=>ie(g).localeCompare(ie(d)))){if(i.has(ie(p))){t.push(Jt("satisfied",p,`${p.from} -> ${p.to} exists in the candidate architecture.`));continue}let g={from:p.to,to:p.from};i.has(ie(g))?(l.add(ie(g)),t.push(Jt("contradictory",p,`${p.from} -> ${p.to} was planned, but the candidate contains the reverse edge.`))):t.push(Jt("missing",p,`${p.from} -> ${p.to} is absent from the candidate architecture.`))}let c=new Set([...n.keys(),...r.keys()]);for(let[p,g]of[...i].sort(([d],[m])=>d.localeCompare(m)))s.has(p)||o.has(p)||l.has(p)||!c.has(g.from)&&!c.has(g.to)||t.push({...Jt("unplanned",g,`${g.from} -> ${g.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let u=new Set(e.changeMap.map.files.filter(p=>p.operation==="delete").map(p=>p.path));for(let[p,g]of[...s].sort(([d],[m])=>d.localeCompare(m)))i.has(p)||u.has(g.from)||u.has(g.to)||!c.has(g.from)&&!c.has(g.to)||t.push({...Jt("unplanned",g,`${g.from} -> ${g.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let f={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((p,g)=>f[p.classification]-f[g.classification]||(p.subject===g.subject?0:p.subject==="file"?-1:1)||p.id.localeCompare(g.id));let y={satisfied:t.filter(p=>p.classification==="satisfied").length,missing:t.filter(p=>p.classification==="missing").length,contradictory:t.filter(p=>p.classification==="contradictory").length,unplanned:t.filter(p=>p.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:y.missing===0&&y.contradictory===0&&y.unplanned===0,behavioralCompletion:"not-evaluated",summary:y,findings:t}}a(kt,"analyzeArchitectureConvergence");var xi="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",cd=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","writes-via-aggregate","no-anemic-model","invariant-coverage"];var Oi={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},by={$schema:"https://json-schema.org/draft/2020-12/schema",$id:xi,title:"ArkGate ArkRules (intra-layer contract)",description:"Per-layer structure sensors and invariant catalog consumed by the ArkGate Effective Contract.",type:"object",additionalProperties:!1,required:["schemaVersion","layer"],properties:{$schema:{type:"string",minLength:1,default:xi},schemaVersion:{type:"string",const:"1.0",default:"1.0"},layer:{type:"string",minLength:1},structure:{type:"array",default:[],items:{$ref:"#/$defs/structureEntry"}},invariants:{type:"array",default:[],items:{$ref:"#/$defs/invariantEntry"}}},$defs:{structureEntry:{type:"object",additionalProperties:!1,required:["id","sensor"],properties:{id:{type:"string",minLength:1},sensor:{type:"string",enum:[...cd]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:Oi,description:{type:"string",minLength:1}}},invariantEntry:{type:"object",additionalProperties:!1,required:["id","description"],properties:{id:{type:"string",minLength:1},description:{type:"string",minLength:1},aggregate:{type:"string",minLength:1},coverage:{type:"object",additionalProperties:!1,properties:{test:{type:"boolean"},symbol:{type:"string",minLength:1}}},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:Oi}}}};function Qt(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}a(Qt,"emptyEffectiveArkRules");function po(e){return{...e,layers:e.layers.map(t=>{let{description:n,trustBoundary:r,owners:o,...s}=t;return s})}}a(po,"omitLayerDescriptions");function Pi(e){let{stewards:t,...n}=po(e.config);return{config:n,arkRules:{schemaVersion:e.arkRules.schemaVersion,structure:e.arkRules.structure.map(r=>({id:r.id,sensor:r.sensor,mode:r.mode,appliesTo:r.appliesTo??null,description:r.description??null,provenance:r.provenance})),invariants:e.arkRules.invariants.map(r=>({id:r.id,description:r.description,aggregate:r.aggregate??null,coverage:r.coverage??null,mode:r.mode,appliesTo:r.appliesTo??null,provenance:r.provenance}))}}}a(Pi,"effectiveContractPolicyPayload");var dd="INVARIANT_TESTS_PATH_MISSING",ud="This project is adopted and has domain invariants, but ark.config.json does not name a real tests path. Add coverage.testGlobs or coverage.coverageRoots pointing at the folder where those tests live, then re-run. Without that path, coverage is an empty checkbox.",pd="INVARIANT_COVERAGE_ROOTS_MISSING",fd="A domain invariant is enforced, but ark.config.json does not name coverage.coverageRoots \u2014 the folders where this project's test runner actually goes. Add coverage.coverageRoots pointing at that folder, then re-run. Without it, coverage can certify a test no runner runs.";function _i(e,t=!1){if(!e)return"";let n=e.discarded,r=[];if(n.budget>0&&!t&&r.push(`${n.budget} past the ${e.maxFiles}-file budget`),n.noInvariantMention>0&&r.push(`${n.noInvariantMention} naming no catalogued invariant`),n.oversize>0&&r.push(`${n.oversize} over the per-file byte cap`),n.unreadable>0&&r.push(`${n.unreadable} unreadable (files or directories)`),n.depthLimited>0&&r.push(`${n.depthLimited} directories past the walk depth limit`),n.outOfRoot>0&&r.push(`${n.outOfRoot} symlinked outside the project root`),r.length===0)return"";let o=t?"":` (loaded ${e.filesLoaded} files, kept ${e.testFilesRetained} tests)`;return` Scan discarded ${r.join(", ")}${o}.`}a(_i,"formatCoverageDiscards");function Li(e,t){let n=e.replace(/\\/g,"/").replace(/^\.\//,"");return t.some(r=>{let o=r.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"");return o===""||o==="."?!0:n===o||n.startsWith(`${o}/`)})}a(Li,"isUnderCoverageRoot");function go(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}a(go,"escapeRegExp");function It(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}a(It,"normalizePath");function mo(e,t){let n=[],r=0,o=e.length;for(;r<o;){let s=e[r],i=e[r+1];if(s==="/"&&i==="/"){for(;r<o&&e[r]!==`
23
+ `;)n.push(" "),r+=1;continue}if(s==="/"&&i==="*"){for(n.push(" "," "),r+=2;r<o&&!(e[r]==="*"&&e[r+1]==="/");)n.push(e[r]===`
24
24
  `?`
25
25
  `:" "),r+=1;r<o&&(n.push(" "," "),r+=2);continue}if(s==='"'||s==="'"||s==="`"){let l=s;for(n.push(t?" ":s),r+=1;r<o;){let c=e[r];if(c==="\\"){let u=e[r+1];t?n.push(" ",u===void 0?"":" "):(n.push("\\"),u!==void 0&&n.push(u)),r+=u===void 0?1:2;continue}if(c===l){n.push(t?" ":c),r+=1;break}n.push(t&&c!==`
26
- `?" ":c),r+=1}continue}n.push(s),r+=1}return n.join("")}i(ci,"maskNonCode");function oc(e,t){if(!t)return;let n=li(t),s=new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*(['"\`])([^'"\`]*${n}[^'"\`]*)\\1`,"i").exec(ci(e,!1))?.[2];return s===void 0?void 0:s}i(oc,"matchTestTitle");function sc(e,t){if(!t)return;let n=li(t),r=ci(e,!0),o=[{shape:"function",source:`(?:^|[\\s;{}])(?:export\\s+(?:default\\s+)?)?(?:declare\\s+)?(?:async\\s+)?function\\s*\\*?\\s*${n}\\s*[(<]`},{shape:"class",source:`(?:^|[\\s;{}])(?:export\\s+(?:default\\s+)?)?(?:abstract\\s+)?class\\s+${n}\\b`},{shape:"const",source:`(?:^|[\\s;{}])export\\s+(?:const|let|var)\\s+${n}\\s*=`},{shape:"type",source:`(?:^|[\\s;{}])(?:export\\s+)?(?:declare\\s+)?type\\s+${n}\\b`},{shape:"interface",source:`(?:^|[\\s;{}])(?:export\\s+)?(?:declare\\s+)?interface\\s+${n}\\b`},{shape:"enum",source:`(?:^|[\\s;{}])(?:export\\s+)?(?:declare\\s+)?(?:const\\s+)?enum\\s+${n}\\b`},{shape:"method",source:`(?:^|[\\n;{}])\\s*(?:(?:public|private|protected|static|async|readonly|override|abstract|get|set|declare)\\s+)*${n}\\s*(?:<[^>\\n]*>)?\\s*\\([^;{}]*\\)\\s*(?::\\s*[^;{]+)?\\s*\\{`}];for(let s of o)if(new RegExp(s.source).test(r))return s.shape}i(sc,"declarationShape");function ic(e,t){let n=e.lastIndexOf(`
26
+ `?" ":c),r+=1}continue}n.push(s),r+=1}return n.join("")}a(mo,"maskNonCode");function gd(e,t){if(!t)return;let n=go(t),s=new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*(['"\`])((?:(?!\\1)[^\\\\]|\\\\.)*?${n}(?:(?!\\1)[^\\\\]|\\\\.)*?)\\1`,"i").exec(mo(e,!1))?.[2];return s===void 0?void 0:s}a(gd,"matchTestTitle");function md(e,t){if(!t)return;let n=go(t),r=mo(e,!0),o=[{shape:"function",source:`(?:^|[\\s;{}])(?:export\\s+(?:default\\s+)?)?(?:declare\\s+)?(?:async\\s+)?function\\s*\\*?\\s*${n}\\s*[(<]`},{shape:"class",source:`(?:^|[\\s;{}])(?:export\\s+(?:default\\s+)?)?(?:abstract\\s+)?class\\s+${n}\\b`},{shape:"const",source:`(?:^|[\\s;{}])export\\s+(?:const|let|var)\\s+${n}(?:\\s*:(?:[^=]|=>)+?)?\\s*=(?!>)`},{shape:"type",source:`(?:^|[\\s;{}])(?:export\\s+)?(?:declare\\s+)?type\\s+${n}\\b`},{shape:"interface",source:`(?:^|[\\s;{}])(?:export\\s+)?(?:declare\\s+)?interface\\s+${n}\\b`},{shape:"enum",source:`(?:^|[\\s;{}])(?:export\\s+)?(?:declare\\s+)?(?:const\\s+)?enum\\s+${n}\\b`},{shape:"method",source:`(?:^|[\\n;{}])\\s*(?:(?:public|private|protected|static|async|readonly|override|abstract|get|set|declare)\\s+)*${n}\\s*(?:<[^>\\n]*>)?\\s*\\([^;{}]*\\)\\s*(?::\\s*[^;{]+)?\\s*\\{`}];for(let s of o)if(new RegExp(s.source).test(r))return s.shape}a(md,"declarationShape");function yd(e,t){let n=e.lastIndexOf(`
27
27
  `,t-1)+1,r=e.indexOf(`
28
- `,t);return e.slice(n,r===-1?e.length:r)}i(ic,"lineAt");function ac(e){let t=e.trim();return/^import\b/.test(t)||/^export\s+/.test(t)&&/\bfrom\b/.test(t)?!0:/\brequire\s*\(/.test(t)}i(ac,"isImportLine");function si(e,t,n){if(!t||!e.includes(t))return;let r=new Set,o=0,s=e.length,a=i((l,c)=>{if(e.startsWith(t,l)){if(c==="comment"){r.add("comment");return}if(c==="string"){r.add("string");return}if(ac(ic(e,l))){r.add("import");return}n&&r.add("test-body")}},"note");for(;o<s;){let l=e[o],c=e[o+1];if(l==="/"&&c==="/"){for(;o<s&&e[o]!==`
29
- `;)a(o,"comment"),o+=1;continue}if(l==="/"&&c==="*"){for(a(o,"comment"),a(o+1,"comment"),o+=2;o<s&&!(e[o]==="*"&&e[o+1]==="/");)a(o,"comment"),o+=1;o<s&&(a(o,"comment"),a(o+1,"comment"),o+=2);continue}if(l==='"'||l==="'"||l==="`"){let u=l;for(a(o,"string"),o+=1;o<s;){let f=e[o];if(f==="\\"){a(o,"string"),e[o+1]!==void 0&&a(o+1,"string"),o+=e[o+1]===void 0?1:2;continue}if(f===u){a(o,"string"),o+=1;break}a(o,"string"),o+=1}continue}a(o,"code"),o+=1}if(r.has("comment"))return"comment";if(r.has("string"))return"string";if(r.has("test-body"))return"test-body";if(r.has("import"))return"import"}i(si,"mentionContext");function di(e){if(!e)return;let t=e.split("."),n=t[t.length-1]??"";return n?{className:t.length>1?t[0]??null:null,name:n}:void 0}i(di,"symbolNeedle");function lc(e){return di(e.coverage?.symbol)?.name??e.id}i(lc,"declaredLabel");function ii(e){return Object.keys(e).sort((t,n)=>t<n?-1:t>n?1:0)}i(ii,"sortedContentFiles");function cc(e,t,n=!0){let r=t.testFiles??[],o=new Set(r.map(g=>Xr(g))),s=(t.coverageRoots??[]).filter(g=>typeof g=="string"&&g.length>0),a=e.coverage?.test!==!1&&n,l=di(e.coverage?.symbol??void 0),c,u;if(a){for(let g of r){let d=t.fileContents[g];if(!d)continue;let m=oc(d,e.id);if(m!==void 0){if(s.length===0||ai(g,s)){c={file:g,title:m};break}u??={file:g,title:m}}}c??=u}let f;if(l)for(let g of ii(t.fileContents)){if(o.has(Xr(g)))continue;let d=t.fileContents[g];if(!d||l.className&&!d.includes(l.className))continue;let m=sc(d,l.name);if(m){f={file:g,shape:m};break}}let y;if(!c&&!f){if(a)for(let g of r){let d=t.fileContents[g];if(!d)continue;let m=si(d,e.id,!0);if(m){y={file:g,context:m};break}}if(!y&&l)for(let g of ii(t.fileContents)){if(o.has(Xr(g)))continue;let d=t.fileContents[g];if(!d)continue;let m=si(d,l.name,!1);if(m){y={file:g,context:m};break}}}return{best:c?{kind:"test-title",file:c.file,title:c.title}:f?{kind:"declaration",file:f.file,shape:f.shape}:y?{kind:"mention-only",file:y.file,context:y.context}:{kind:"none"},...c?{testTitle:c}:{},...f?{declaration:f}:{}}}i(cc,"rankCoverage");function dc(e){switch(e.kind){case"test-title":case"declaration":return!0;case"mention-only":case"none":return!1}}i(dc,"countsAsCoverage");function uc(e){switch(e){case"test-body":return"a test body";case"comment":return"a comment";case"string":return"a string";case"import":return"an import"}}i(uc,"mentionWhere");function pc(e,t){switch(t.kind){case"test-title":return`found \`${t.title}\` in a describe/it title in ${t.file}`;case"declaration":return`found \`${t.shape} ${lc(e)}\` in ${t.file}`;case"mention-only":return`${e.id} appears only in ${uc(t.context)} in ${t.file}; put it in a describe/it title`;case"none":return"no scanned test names it in a describe/it title and no declared symbol was found"}}i(pc,"describeCoverage");function ui(e){let t=e.arkRules.invariants??[];if(t.length===0)return{coverage:[],violations:[],partial:!1};let n=e.testFiles??[],r=e.testGlobsMissing===!0||n.length===0,o=e.coverageBudgetExhausted===!0,s=e.coverageStats,a=oi(s),l=oi(s,!0),c=s?`coverage file budget exhausted: ${s.filesLoaded} files loaded at the ${s.maxFiles}-file cap, ${s.testFilesRetained} tests retained, ${s.discarded.budget} files discarded at the cap; raise "coverage.maxFiles" in ark.config.json (the cap bounds files RETAINED as evidence${typeof s.filesRead=="number"?`; ${s.filesRead} were read`:""})`:"coverage file budget exhausted",u=(e.coverageRoots??[]).filter(d=>typeof d=="string"&&d.length>0),f=u.length>0,y=u.join(", "),p=[],g=[];for(let d of t){let m=d.coverage?.test!==!1,E=d.coverage?.symbol,S=!r&&m,k=cc(d,{fileContents:e.fileContents,testFiles:n,coverageRoots:u},S),v=k.best,C=[];S&&k.testTitle&&C.push("test-title"),k.declaration&&C.push("symbol");let N=dc(v),b,T;S&&k.testTitle&&(b=k.testTitle.file,f&&(T=!ai(b,u)));let De=k.declaration?.file,ge=k.declaration?.shape,D=(d.coverage?.test===!0||!!E||d.coverage===void 0)&&N||d.coverage?.test===!1&&!E?!0:N,z=r&&m&&!N;if(p.push({invariantId:d.id,layer:d.provenance.layer,sourceFile:d.provenance.sourceFile,mode:d.mode,covered:D&&!z,evidence:C,partial:z,description:d.description,...b!==void 0?{testEvidenceFile:b}:{},...De!==void 0?{symbolEvidenceFile:De}:{},...ge!==void 0?{shape:ge}:{},...T!==void 0?{outsideDeclaredRoots:T}:{},coverageRootsDeclared:f}),T===!0&&b!==void 0&&g.push({ruleId:"INVARIANT_COVERAGE_OUTSIDE_ROOTS",message:`Invariant ${d.id} is covered only by ${b}, which is outside the declared coverage roots (${y}). ArkGate matches declared text and never executes tests, so it cannot tell whether that file is run: move the test under a declared root, or add its root to "coverage.coverageRoots" in ark.config.json.`,file:b,line:1,arkruleId:d.id,arkruleSource:d.provenance.sourceFile,fromLayer:d.provenance.layer,severity:"warning",failsStrict:!1}),!D||z){let q=d.mode==="enforced"&&!z,me=r||n.length===0?"never-had-tests":"tests-disappeared";g.push({ruleId:"INVARIANT_UNCOVERED",message:(z?o?`Invariant ${d.id} coverage cannot be proven (${c}); reporting partial, not covered.`:`Invariant ${d.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered (never-had-tests).`:`Invariant ${d.id}: ${pc(d,v)} (${me==="tests-disappeared"?"tests-disappeared \u2014 a suite exists":"never-had-tests \u2014 the scan found no tests at all"}). ArkGate matches declared text; it never executes tests.`)+(z&&o?l:a),file:d.provenance.sourceFile,line:1,arkruleId:d.id,arkruleSource:d.provenance.sourceFile,fromLayer:d.provenance.layer,severity:q?"error":"warning",failsStrict:q,kind:me})}}return{coverage:p,violations:g,partial:p.some(d=>d.partial)}}i(ui,"evaluateInvariantCoverage");function pi(e){return e?e.partial?{ok:!1,reason:"Coverage is partial (missing test globs); cannot promote until evidence is complete."}:e.covered?e.outsideDeclaredRoots===!0?{ok:!1,reason:`Invariant ${e.invariantId} is covered only by ${e.testEvidenceFile??"a test"}, outside the declared coverage roots; ArkGate cannot tell whether that test runs, so it will not promote on it.`}:e.coverageRootsDeclared===!1?{ok:!1,reason:`Declare coverage.coverageRoots in ark.config.json before promoting ${e.invariantId} to enforced. Without that, ArkGate cannot tell whether a covering test is one the runner executes.`}:{ok:!0,reason:`Invariant ${e.invariantId} has coverage evidence.`}:{ok:!1,reason:`Invariant ${e.invariantId} is uncovered; add a test title or symbol before promoting to enforced.`}:{ok:!1,reason:"No coverage evidence supplied for this invariant; evaluate coverage before promoting to enforced."}}i(pi,"canPromoteInvariant");function Zr(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!="string")continue;let r=n.trim();r.length>0&&t.push(r)}return t}i(Zr,"nonEmptyPathStrings");function fc(e){return!e||typeof e!="object"?[]:[...Zr(e.testGlobs),...Zr(e.coverageRoots)]}i(fc,"configuredInvariantTestsPaths");function gc(e){return fc(e).length>0}i(gc,"hasConfiguredInvariantTestsPath");function Jr(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.coverage?.test!==!1)}i(Jr,"catalogDemandsInvariantTestsPath");function fi(e){let t=e.hasDomainInvariants===!0||e.hasDomainInvariants!==!1&&Jr(e.invariants);return e.adopted!==!0||!t?[]:gc(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:ec,message:tc,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]}i(fi,"collectMissingInvariantTestsPathFindings");function mc(e){return!e||typeof e!="object"?[]:Zr(e.coverageRoots)}i(mc,"configuredCoverageRoots");function yc(e){return mc(e).length>0}i(yc,"hasConfiguredCoverageRoots");function Qr(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.mode==="enforced")}i(Qr,"catalogHasEnforcedInvariant");function gi(e){return e.hasEnforcedInvariant===!0||e.hasEnforcedInvariant!==!1&&Qr(e.invariants)?yc(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:nc,message:rc,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]:[]}i(gi,"collectMissingCoverageRootsFindings");var no="1.0",hc="add a short note under docs/adr/ (or docs/decisions/) and put that file path in --policy-ack as adrPath.";function P(e,t){let n=t.classification==="weakening"||t.classification==="judgment-required"?`Restore the previous protection at ${t.path}, or ${hc}`:void 0,r=t.nextAction??n;e.push({id:`${t.classification}:${t.path}:${t.kind}`,path:t.path,classification:t.classification,message:t.message,...r?{nextAction:r}:{},...t.before===void 0?{}:{before:t.before},...t.after===void 0?{}:{after:t.after}})}i(P,"addFinding");function Z(e){return[...new Set(e??[])].sort()}i(Z,"sortedUnique");function ue(e,t,n,r,o){let s=Z(n),a=Z(r),l=new Set(s),c=new Set(a),u=a.filter(y=>!l.has(y)),f=s.filter(y=>!c.has(y));u.length===0&&f.length===0||(u.length>0&&P(e,{kind:"added",path:t,classification:o.added,message:o.addedMessage,before:s,after:a}),f.length>0&&P(e,{kind:"removed",path:t,classification:o.removed,message:o.removedMessage,before:s,after:a}))}i(ue,"compareStringSets");function Ut(e,t,n,r,o,s,a){if(n===r)return;P(e,{kind:r?"enabled":"disabled",path:t,classification:r?o:o==="strengthening"?"weakening":"strengthening",message:r?s:a,before:n,after:r})}i(Ut,"compareBoolean");function Vn(e,t){let n=new Map,r=new Set;for(let o of e){let s=t(o);n.has(s)?r.add(s):n.set(s,o)}return{values:n,duplicates:[...r].sort()}}i(Vn,"keyed");function Rc(e,t,n){let r=Vn(t,s=>s.name),o=Vn(n,s=>s.name);(r.duplicates.length>0||o.duplicates.length>0)&&P(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:r.duplicates,after:o.duplicates});for(let s of[...new Set([...r.values.keys(),...o.values.keys()])].sort()){let a=r.values.get(s),l=o.values.get(s),c=`$.layers[${s}]`;if(!a&&l){P(e,{kind:"layer-added",path:c,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",nextAction:"Write a short note under docs/adr/ (or docs/decisions/) for this new layer and put that file path in --policy-ack as adrPath.",after:l});continue}if(a&&!l){P(e,{kind:"layer-removed",path:c,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:a});continue}if(!a||!l)continue;ue(e,`${c}.patterns`,a.patterns,l.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),ue(e,`${c}.exclude`,a.exclude,l.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let u=Un(a),f=Un(l);ue(e,`${c}.forbiddenGlobals`,u.rawGlobals,f.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),ue(e,`${c}.capabilities`,u.atoms,f.atoms,{added:"strengthening",removed:"weakening",addedMessage:"Additional ambient/import protection is enforced in this layer (coverage atoms).",removedMessage:"An ambient/import protection was lost from this layer (coverage atoms)."}),Z(a.intentPrefixes).join("\0")!==Z(l.intentPrefixes).join("\0")&&P(e,{kind:"intent-prefixes-changed",path:`${c}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:Z(a.intentPrefixes),after:Z(l.intentPrefixes)}),Ut(e,`${c}.mayImportInfrastructure`,a.mayImportInfrastructure===!0,l.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),Ut(e,`${c}.optional`,a.optional===!0,l.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active.")}}i(Rc,"compareLayers");function Ac(e,t,n){let r=i(a=>`${a.from}->${a.to}`,"keyOf"),o=Vn(t,r),s=Vn(n,r);(o.duplicates.length>0||s.duplicates.length>0)&&P(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:o.duplicates,after:s.duplicates});for(let a of[...new Set([...o.values.keys(),...s.values.keys()])].sort()){let l=o.values.get(a),c=s.values.get(a),u=`$.rules[${a}]`;if(!l&&c){c.allowed===!1?P(e,{kind:"deny-added",path:u,classification:"strengthening",message:"A denied dependency edge was added.",after:c}):P(e,{kind:"allow-added",path:u,classification:"judgment-required",message:"A new import edge was added; confirm this house should import that one.",nextAction:"Write a short note under docs/adr/ (or docs/decisions/) for this new import edge and put that file path in --policy-ack as adrPath.",after:c});continue}if(l&&!c){l.allowed===!1&&P(e,{kind:"deny-removed",path:u,classification:"weakening",message:"A denied dependency edge was removed.",before:l});continue}if(!l||!c)continue;l.allowed!==c.allowed&&P(e,{kind:c.allowed?"deny-disabled":"deny-enabled",path:`${u}.allowed`,classification:c.allowed?"weakening":"strengthening",message:c.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:l.allowed,after:c.allowed});let f=l.peerIsolation===!0,y=c.peerIsolation===!0;if(f!==y){let d=l.from===l.to&&c.from===c.to;P(e,{kind:y?"peer-isolation-enabled":"peer-isolation-disabled",path:`${u}.peerIsolation`,classification:d?y?"strengthening":"weakening":"judgment-required",message:d?y?"Cross-slice dependencies inside this layer are now denied.":"Cross-slice dependencies inside this layer are no longer denied.":"Changing peer isolation on a cross-layer edge changes the denial scope.",before:f,after:y})}Z(l.sliceFolders).join("\0")!==Z(c.sliceFolders).join("\0")&&P(e,{kind:"slice-folders-changed",path:`${u}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:Z(l.sliceFolders),after:Z(c.sliceFolders)});let p=l.sliceIdentity??"path",g=c.sliceIdentity??"path";if(p!==g&&P(e,{kind:"slice-identity-changed",path:`${u}.sliceIdentity`,classification:"judgment-required",message:"Slice identity changed and can reclassify existing slice ids. Baselines and allowedCrossSlice use those ids.",before:p,after:g}),!(!f&&!y)&&(yi(e,`${u}.sharedRoots`,"shared-roots",Z(l.sharedRoots),Z(c.sharedRoots),"Roots declared shared are exempt from the peerIsolation unclassifiable denial.","Roots are no longer declared shared and fall back to the peerIsolation denial."),yi(e,`${u}.allowedCrossSlice`,"cross-slice-allowance",Z((l.allowedCrossSlice??[]).map(mi)),Z((c.allowedCrossSlice??[]).map(mi)),"Directed cross-slice edges are now allowed by declaration.","Directed cross-slice edges are no longer declared and deny again."),(l.sharedImportsSlice??null)!==(c.sharedImportsSlice??null))){let d=c.sharedImportsSlice==="deny";P(e,{kind:"shared-imports-slice",path:`${u}.sharedImportsSlice`,classification:d?"strengthening":"weakening",message:d?"A shared root may no longer import a slice.":"A shared root may import a slice again.",before:l.sharedImportsSlice??null,after:c.sharedImportsSlice??null})}}}i(Ac,"compareRules");function mi(e){return JSON.stringify([e.from,e.to])}i(mi,"crossSliceKey");function yi(e,t,n,r,o,s,a){if(JSON.stringify(r)===JSON.stringify(o))return;let l=o.filter(f=>!r.includes(f)),c=r.filter(f=>!o.includes(f)),u=l.length>0&&c.length>0;P(e,{kind:u?`${n}-changed`:l.length>0?`${n}-added`:`${n}-removed`,path:t,classification:u?"judgment-required":l.length>0?"weakening":"strengthening",message:u?`${s} Entries were added and removed in the same change.`:l.length>0?s:a,before:r,after:o})}i(yi,"compareDeclaredExceptions");function kc(e,t,n){let r=t.safety??{},o=n.safety??{};for(let s of["maxTsSuppressions","maxAnyCasts"]){let a=r[s]??0,l=o[s]??0;a!==l&&P(e,{kind:l>a?"threshold-raised":"threshold-lowered",path:`$.safety.${s}`,classification:l>a?"weakening":"strengthening",message:l>a?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:a,after:l})}for(let s of["allowInMemory","allowDisabledPeerIsolation"])Ut(e,`$.safety.${s}`,r[s]===!0,o[s]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}i(kc,"compareSafety");function eo(e){return e.mode==="enforced"?"enforced":"advisory"}i(eo,"arkRunMode");function to(e){return e.mode==="enforced"?"enforced":"advisory"}i(to,"arkOrderMode");function Ic(e,t,n){let r=t.arkOrder,o=n.arkOrder,s="$.arkOrder";if(!r&&!o)return;if(!r&&o){P(e,{kind:"arkorder-added",path:s,classification:"strengthening",message:`ArkOrder extra was added (${to(o)}).`,after:o});return}if(r&&!o){P(e,{kind:"arkorder-removed",path:s,classification:"weakening",message:"ArkOrder extra was removed.",before:r});return}if(!r||!o)return;let a=to(r),l=to(o);if(a!==l){let c=a==="advisory"&&l==="enforced";P(e,{kind:c?"arkorder-promoted":"arkorder-demoted",path:`${s}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkOrder extra was promoted to enforced.":"ArkOrder extra was demoted to advisory.",before:a,after:l})}ue(e,`${s}.planeRoots`,r.planeRoots,o.planeRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkOrder plane roots are governed.",removedMessage:"ArkOrder plane roots were removed and may skip the plane."}),ue(e,`${s}.managedLayers`,r.managedLayers,o.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkOrder.",removedMessage:"Layers were removed from ArkOrder management."})}i(Ic,"compareArkOrder");function bc(e,t,n){let r=t.arkRun,o=n.arkRun,s="$.arkRun";if(!r&&!o)return;if(!r&&o){P(e,{kind:"arkrun-added",path:s,classification:"strengthening",message:`ArkRun extra was added (${eo(o)}).`,after:o});return}if(r&&!o){P(e,{kind:"arkrun-removed",path:s,classification:"weakening",message:"ArkRun extra was removed.",before:r});return}if(!r||!o)return;let a=eo(r),l=eo(o);if(a!==l){let c=a==="advisory"&&l==="enforced";P(e,{kind:c?"arkrun-promoted":"arkrun-demoted",path:`${s}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkRun extra was promoted to enforced.":"ArkRun extra was demoted to advisory.",before:a,after:l})}ue(e,`${s}.compositionRoots`,r.compositionRoots,o.compositionRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkRun composition roots are governed.",removedMessage:"ArkRun composition roots were removed and may skip the kernel."}),ue(e,`${s}.managedLayers`,r.managedLayers,o.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkRun.",removedMessage:"Layers were removed from ArkRun management."}),Ut(e,`${s}.requireDeclarations`,r.requireDeclarations!==!1,o.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}i(bc,"compareArkRun");function vc(e){return e.some(t=>t.classification==="weakening")?"weakening":e.some(t=>t.classification==="judgment-required")?"judgment-required":e.some(t=>t.classification==="strengthening")?"strengthening":"neutral"}i(vc,"overallClassification");function hi(e,t){return`${e}::${t}`}i(hi,"ruleKey");function Ri(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(hi(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(hi(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}i(Ri,"indexEffectiveRules");function Ec(e,t,n,r,o,s){let a=new Map((s??[]).map(p=>[p.invariantId,p])),l=t.arkRules??{},c=n.arkRules??{},u=[...new Set([...Object.keys(l),...Object.keys(c)])].sort();for(let p of u){let g=l[p],d=c[p],m=`$.arkRules[${p}]`;if(g===void 0&&d!==void 0){P(e,{kind:"arkrules-ref-added",path:m,classification:"strengthening",message:`ArkRules reference for layer ${p} was added.`,after:d});continue}if(g!==void 0&&d===void 0){P(e,{kind:"arkrules-ref-removed",path:m,classification:"weakening",message:`ArkRules reference for layer ${p} was removed.`,before:g});continue}g!==d&&P(e,{kind:"arkrules-ref-path-changed",path:m,classification:"judgment-required",message:`ArkRules file path for layer ${p} changed; verify the effective rules still match intent.`,before:g,after:d})}let f=Ri(r),y=Ri(o);for(let p of[...new Set([...f.structure.keys(),...y.structure.keys()])].sort()){let g=f.structure.get(p),d=y.structure.get(p),m=`$.arkRules.structure[${p}]`;if(!g&&d){P(e,{kind:"arkrule-structure-added",path:m,classification:"strengthening",message:`Structure ArkRule ${d.id} was added (${d.mode}).`,after:d});continue}if(g&&!d){P(e,{kind:"arkrule-structure-removed",path:m,classification:"weakening",message:`Structure ArkRule ${g.id} was removed.`,before:g});continue}if(!(!g||!d)){if(g.mode!==d.mode){let E=g.mode==="advisory"&&d.mode==="enforced";P(e,{kind:E?"arkrule-promoted":"arkrule-demoted",path:`${m}.mode`,classification:E?"strengthening":"weakening",message:E?`Structure ArkRule ${d.id} was promoted to enforced.`:`Structure ArkRule ${d.id} was demoted to advisory.`,before:g.mode,after:d.mode})}g.sensor!==d.sensor&&P(e,{kind:"arkrule-sensor-changed",path:`${m}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${d.id} changed sensor identity.`,before:g.sensor,after:d.sensor})}}for(let p of[...new Set([...f.invariants.keys(),...y.invariants.keys()])].sort()){let g=f.invariants.get(p),d=y.invariants.get(p),m=`$.arkRules.invariants[${p}]`;if(!g&&d){P(e,{kind:"arkrule-invariant-added",path:m,classification:"strengthening",message:`Invariant ${d.id} was added (${d.mode}).`,after:d});continue}if(g&&!d){P(e,{kind:"arkrule-invariant-removed",path:m,classification:"weakening",message:`Invariant ${g.id} was removed.`,before:g});continue}if(!(!g||!d)&&g.mode!==d.mode)if(g.mode==="advisory"&&d.mode==="enforced"){let S=a?.get(d.id),k=pi(S);k.ok?P(e,{kind:"arkrule-invariant-promoted",path:`${m}.mode`,classification:"strengthening",message:`Invariant ${d.id} was promoted to enforced (coverage evidence present).`,before:g.mode,after:d.mode}):P(e,{kind:"arkrule-invariant-promote-refused",path:`${m}.mode`,classification:"judgment-required",message:`Invariant ${d.id} cannot be promoted to enforced: ${k.reason}`,before:g.mode,after:d.mode})}else P(e,{kind:"arkrule-invariant-demoted",path:`${m}.mode`,classification:"weakening",message:`Invariant ${d.id} was demoted to advisory.`,before:g.mode,after:d.mode})}}i(Ec,"compareArkRules");function ro(e,t,n){let r=[];ue(r,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),ue(r,"$.exclude",e.exclude,t.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional project paths are excluded from governance.",removedMessage:"Fewer project paths are excluded from governance."}),ue(r,"$.dynamicImportAllowlist",e.dynamicImportAllowlist,t.dynamicImportAllowlist,{added:"weakening",removed:"strengthening",addedMessage:"Additional files may use non-literal dynamic imports.",removedMessage:"Fewer files may use non-literal dynamic imports."}),Ut(r,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let o={off:0,soft:1,"framework-soft":1,strict:2},s=e.cyclePolicy??"strict",a=t.cyclePolicy??"strict";if(s!==a){let l=o[a]===o[s]?"judgment-required":o[a]>o[s]?"strengthening":"weakening";P(r,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:l,message:"The cycle enforcement level changed.",before:s,after:a})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&P(r,{kind:"framework-overlay-changed",path:"$.frameworkOverlay",classification:"judgment-required",message:"The framework overlay changed and may alter effective layer matching.",before:e.frameworkOverlay??null,after:t.frameworkOverlay??null}),Rc(r,e.layers,t.layers),Ac(r,e.rules,t.rules),kc(r,e,t),Ec(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),bc(r,e,t),Ic(r,e,t),r.sort((l,c)=>l.path.localeCompare(c.path)||l.id.localeCompare(c.id)),{schemaVersion:no,classification:vc(r),findings:r}}i(ro,"classifyArkPolicyDelta");function oo(e,t){if(!e||e.schemaVersion!==no||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(o=>typeof o!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=Z(e.findingIds),r=Z(t.findingIds);return n.length===r.length&&n.every((o,s)=>o===r[s])}i(oo,"policyDeltaAcknowledgementMatches");function Ue(e){let t=[];for(let n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."&&t.length>0&&t.at(-1)!==".."?t.pop():t.push(n));return t.join("/")}i(Ue,"normalizePath");function Ai(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}i(Ai,"isIdentifierStart");function jn(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}i(jn,"isIdentifierCharacter");function se(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}i(se,"skipWhitespace");function Vt(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let r=t,o="";for(t+=1;t<e.length;t+=1){let s=e[t];if(s===n)return{value:o,offset:r,excerpt:e.slice(r,t+1)};s==="\\"&&t+1<e.length?(o+=e[t+1],t+=1):o+=s}}i(Vt,"readString");function le(e,t,n){return e.startsWith(t,n)&&!jn(e[n-1])&&!jn(e[n+t.length])}i(le,"isWordAt");function ki(e,t){let n=se(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=se(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!le(e,"type",n))return!1;let o=se(e,n+4);if(o>=e.length||e[o]===","||e[o]==="}"||le(e,"as",o)||!Ai(e[o]))return!1;for(n=o;n<e.length&&jn(e[n]);)n+=1;if(n=se(e,n),le(e,"as",n)){if(n=se(e,n+2),!Ai(e[n]))return!1;for(;n<e.length&&jn(e[n]);)n+=1}r=!0}return!1}i(ki,"bracedNamedBindingsAreTypeOnly");function Sc(e,t){if(t=se(e,t+6),e[t]==="(")return Vt(e,se(e,t+1));let n=!1;if(le(e,"type",t)){let o=se(e,t+4);e[o]!==","&&!le(e,"from",o)&&(n=!0)}else ki(e,t)&&(n=!0);let r=Ii(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}i(Sc,"specifierAfterImport");function wc(e,t){t=t+6;let n=se(e,t),r=!1;if(le(e,"type",n)){let s=se(e,n+4);(e[s]==="{"||e[s]==="*")&&(r=!0)}else ki(e,n)&&(r=!0);let o=Ii(e,t,!1);return o&&r?{...o,typeOnly:!0}:o}i(wc,"specifierAfterExport");function Ii(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(le(e,"from",t))return Vt(e,se(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return Vt(e,t);if(t>0&&(le(e,"import",t)||le(e,"export",t)))return}}i(Ii,"specifierInStaticStatement");function Cc(e,t){for(t+=1;t<e.length;t+=1){let n=e[t];if(n==="\\")t+=1;else if(n==="`")return t}return e.length}i(Cc,"skipTemplateLiteral");function xc(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=se(e,t+7);if(e[r]!=="(")return;r=se(e,r+1);let o=Vt(e,r);return o?{...o,requireCall:!0}:void 0}i(xc,"specifierAfterRequire");function Oc(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="/"&&e[n+1]==="/"){if(n=e.indexOf(`
30
- `,n+2),n<0)break;continue}if(r==="/"&&e[n+1]==="*"){let s=e.indexOf("*/",n+2);if(s<0)break;n=s+1;continue}if(r==="`"){n=Cc(e,n);continue}if(r==="'"||r==='"'){let s=Vt(e,n);s&&(n=s.offset+s.excerpt.length-1);continue}let o=r==="i"&&le(e,"import",n)?Sc(e,n):r==="e"&&le(e,"export",n)?wc(e,n):r==="r"&&le(e,"require",n)?xc(e,n):void 0;o&&(t.push(o),n=o.offset+o.excerpt.length-1)}return t}i(Oc,"moduleSpecifiers");function bi(e,t){let n=[],r=[];for(let o of Oc(e.content)){let s=o.value;if(!s.startsWith(".")){if(o.typeOnly)continue;let u=Nt(s);if(!u)continue;let f=e.content.slice(0,o.offset).split(`
31
- `).length;r.push({file:e.path,symbol:s,capability:u,evidence:{kind:"import",file:e.path,line:f,excerpt:o.excerpt}});continue}let a=e.content.slice(0,o.offset).split(`
32
- `).length,l={kind:"import",file:e.path,line:a,excerpt:o.excerpt},c=Pc(e.path,s,t);n.push({from:e.path,specifier:s,to:c?.path??null,resolution:c?"resolved":"unresolved",fromLayer:e.layer,toLayer:c?.layer??null,evidence:l})}return{edges:n,capabilityUses:r}}i(bi,"moduleFactsFor");function Pc(e,t,n){let r=e.split("/");r.pop();for(let s of t.split("/"))s==="."||s===""||(s===".."?r.pop():r.push(s));let o=r.join("/");for(let s of[o,`${o}.ts`,`${o}.tsx`,`${o}.mts`,`${o}.cts`,`${o}/index.ts`,`${o}/index.tsx`]){let a=n.get(s);if(a)return a}}i(Pc,"resolveSpecifier");function vi(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let o=ot(t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});o&&n.push({ruleId:`layer-dependency:${o.from}->${o.to}`,message:o.message??`${o.from} must not depend on ${o.to}.`,edge:r,evidence:r.evidence})}return n}i(vi,"violationsFor");var _c={code:"LEXICAL_EVIDENCE_INCOMPLETE",message:"Lexical compatibility mode cannot prove parse status, TypeScript/package/symlink resolution, or symbol-aware source-policy and safety evidence. Use the resolved candidate facts APIs for an authoritative verdict."};function Tc(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}i(Tc,"hasActiveArkRules");function Nc(e,t){return Tc(e,t)?Y(M(ri({config:e,arkRules:t,warnings:[]}))):Y(M(Yr(e)))}i(Nc,"policyHashFor");function Bn(e,t,n){let r=typeof e=="string"?Fs(e,t):Pr(e,t),o=n?.arkRules??Gt();return{...r,arkRules:o,policyHash:Nc(r.config,o)}}i(Bn,"loadContract");function Ei(e){let t=Bn(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=Bn(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=ro(t.config,n.config,{baseArkRules:t.arkRules,candidateArkRules:n.arkRules,candidateInvariantCoverage:e.candidateInvariantCoverage}),o=r.findings.filter(l=>l.classification==="weakening"||l.classification==="judgment-required").map(l=>l.id).sort(),s=o.length>0,a=s&&oo(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:o});return{schemaVersion:r.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:r.classification,findings:r.findings,blockingFindingIds:o,requiresAcknowledgement:s,acknowledged:a,valid:!s||a}}i(Ei,"analyzePolicyDelta");function jt(e){let t=e.files.map(y=>{let p=Ue(y.path);return{path:p,content:y.content,contentHash:Y(y.content),layer:de(p,e.contract.config.layers)??null}}).sort((y,p)=>y.path.localeCompare(p.path)),n=new Map(t.map(y=>[y.path,y])),r=[],o=[];for(let y of t){let p=bi(y,n);r.push(...p.edges),o.push(...p.capabilityUses)}let s=vi(r,e.contract.config),a=new Map(e.contract.config.layers.map(y=>[y.name,y])),l=new Map(e.contract.config.layers.map(y=>[y.name,new Set(lt(y))]));for(let y of o){let p=n.get(y.file)?.layer;if(!p)continue;let g=a.get(p),d=xe(y.symbol,g?.forbiddenGlobals??[]);if(d){s.push({ruleId:"FORBIDDEN_GLOBAL",message:`${p} must not use module "${y.symbol}" because it is the import form of forbidden global "${d}".`,symbol:y.symbol,evidence:y.evidence});continue}l.get(p)?.has(y.capability)&&s.push({ruleId:"CAPABILITY_VIOLATION",message:`${p} denies the ${y.capability} capability; found import of "${y.symbol}".`,capability:y.capability,symbol:y.symbol,evidence:y.evidence})}let c=t.length===0?"complete":"partial",u=c==="complete"?[]:[{..._c}],f={schemaVersion:qr,policyHash:e.contract.policyHash,compilerOptionsHash:Y(M(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(y=>y.name),edges:r,capabilityUses:o,violations:s};return{mode:"lexical-compatibility",completeness:c,completenessReasons:u,valid:c==="complete"&&s.length===0,ir:f}}i(jt,"analyzeProject");function Wn(e){let t=new Map(e.files.map(n=>[Ue(n.path),n]));for(let n of e.changes){let r=Ue(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return jt({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}i(Wn,"analyzeChange");function Si(e){let t=`${e.evidence.file}:${e.evidence.line}`;if(!e.edge)return`${e.ruleId} at ${t}: ${e.message}`;let n=e.edge.to??e.edge.specifier;return`${e.ruleId} at ${t}: ${e.edge.from} imports ${n}. ${e.message}`}i(Si,"explainViolation");function so(e){let t=0,n=new Map,r=new Map,o=new Set,s=[],a=[],l=i(c=>{n.set(c,t),r.set(c,t),t+=1,s.push(c),o.add(c);for(let y of[...e.get(c)??[]].sort())e.has(y)&&(n.has(y)?o.has(y)&&r.set(c,Math.min(r.get(c)??0,n.get(y)??0)):(l(y),r.set(c,Math.min(r.get(c)??0,r.get(y)??0))));if(r.get(c)!==n.get(c))return;let u=[],f;do{if(f=s.pop(),f===void 0)break;o.delete(f),u.push(f)}while(f!==c);u.length>1&&a.push(u.sort())},"connect");for(let c of[...e.keys()].sort())n.has(c)||l(c);return a.sort((c,u)=>c[0]<u[0]?-1:c[0]>u[0]?1:0).map(c=>({ruleId:"CIRCULAR_DEPENDENCY",file:c[0],line:1,target:c.join(" \u2192 "),message:`Circular dependency among ${c.length} files: ${c.join(" \u2192 ")} \u2192 ${c[0]}.`,cycleKind:"value"}))}i(so,"detectArchitectureCycles");function mt(e){let t=e.contentViolations.map(s=>({...s})),n=(e.warnings??[]).map(s=>({...s})),r=new Map(e.files.map(s=>[s,new Set]));for(let s of e.edges){if(s.to&&s.to!==s.from&&!s.typeOnly&&r.has(s.from)&&r.get(s.from)?.add(s.to),!s.to||!s.fromLayer||!s.toLayer)continue;let a=$e(e.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:e.config.layers});if(!a){let p=is(e.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:e.config.layers});p&&n.push({ruleId:"SHARED_IMPORTS_SLICE",file:p.fromPath,line:s.line,fromLayer:s.fromLayer,toLayer:s.toLayer,target:p.toPath,toSlice:p.toSlice,failsStrict:!1,severity:"warning",message:`shared root ${p.fromPath} \u2192 slice ${p.toSlice} (${p.toPath}). The wall is direct-only.`});continue}let l=a.rule,c=!!l.peerIsolation,u=!c&&!!(s.typeOnly||s.namedBindingsTypeOnly),f=c?rt(a.peerIsolationReason??"cross-slice",{fromPath:s.from,toPath:s.to,fromSlice:a.fromSlice,toSlice:a.toSlice}):void 0,y=l.message?f?`${l.message} (${f})`:l.message:f?`${s.fromLayer} must not ${s.kind} another slice of ${s.toLayer} (${s.from} \u2192 ${s.to}): ${f}`:`${s.fromLayer} must not ${s.kind} ${s.toLayer}.`;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:s.from,line:s.line,fromLayer:s.fromLayer,toLayer:s.toLayer,target:s.to,...s.typeOnly?{typeOnly:!0}:{},...s.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...s.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...s.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!c&&s.portProofEligible?{portProofEligible:!0}:{},...s.kind?{edgeKind:s.kind}:{},...c?{peerIsolation:!0}:{},message:u?`${y} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:y,...u?{failsStrict:!1,severity:"warning"}:{}})}let o=String(e.config.cyclePolicy??"strict").toLowerCase();if(o!=="off"){let s=so(r);o==="soft"||o==="framework-soft"?n.push(...s.map(a=>({...a,message:`${a.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...s)}return{violations:t,warnings:n,safety:e.safety}}i(mt,"evaluateArchitectureGraph");function wi(e){if(typeof e.target=="string"&&e.target.length>0)return e.target;let t=String(e.sensor||e.code||"").trim();if(!t&&typeof e.message=="string"){let r=e.message.match(/\(sensor ([a-z0-9-]+)\)/i);r?.[1]&&(t=r[1])}let n=String(e.symbol||"").trim();return t?n?`${t}:${n}`:t:n}i(wi,"structureFreezeTarget");var Dc=["no-anemic-model"],_i=["ensureInvariants","assertInvariants","validate","publish","emit","raise","record"],Tm=new RegExp(`\\b(${_i.join("|")})\\b`),Ti="(?:_?pendingEvents|domainEvents|uncommittedEvents|recordedEvents)",Nm=new RegExp(`\\bthis\\.${Ti}\\.push\\s*\\(`),Dm=new RegExp(`^this\\.${Ti}\\s*=\\s*\\[\\s*\\]`);var Lc="truncatedUntil";function Fc(){return`${_i.join(", ")}, or events-array .push(`}i(Fc,"expectedDomainInvariantWordsPhrase");function io(e){let t=Object.getOwnPropertyDescriptor(e,Lc)?.value;return typeof t=="number"?t:void 0}i(io,"shapeTruncatedUntil");function $c(e){let t=io(e);return t==null?"":` shape analysed until character ${t}`}i($c,"shapeTruncationSuffix");function Ci(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(Ci,"escapeGlobLiteral");function Mc(e){let t="";for(let r=0;r<e.length;r+=1){let o=e[r];if(o==="\\"&&r+1<e.length){let s=e[r+1];if("*?{}[],".includes(s)||s==="\\"){t+="\\"+s,r+=1;continue}t+="/";continue}t+=o}let n="";for(let r=0;r<t.length;r+=1){let o=t[r];o==="\\"&&r+1<t.length?(n+=Ci(t[r+1]),r+=1):o==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":o==="?"?n+="[^/]":n+=Ci(o)}return new RegExp(`^${n}$`)}i(Mc,"globToRegExp");function yt(e,t){return!t||t.length===0?!0:t.some(n=>Mc(n).test(e))}i(yt,"matchesAppliesTo");function Ni(e){return Dc.includes(e)}i(Ni,"isTier2");function Di(e){return e.mode==="enforced"&&!Ni(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}i(Di,"severityFor");function Pe(e,t,n,r=1){let{severity:o,failsStrict:s}=Di(e);return{ruleId:"ARKRULE_STRUCTURE",code:e.sensor,message:n,file:t,line:r,fromLayer:e.provenance.layer,arkruleId:e.id,arkruleSource:e.provenance.sourceFile,severity:o,sensor:e.sensor,failsStrict:s}}i(Pe,"baseViolation");function zn(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}i(zn,"isInRuleLayer");function qn(e,t,n){return t.filter(r=>!(!r.exported||!yt(r.file,e.appliesTo)||!zn(r.file,e,n)))}i(qn,"shapesForRule");function Hc(e,t,n){let r=[];for(let o of qn(e,t,n))(o.hasPublicSetters||o.hasPublicMutableFields)&&r.push(Pe(e,o.file,`Exported class ${o.className} exposes public mutable state (sensor aggregate-private-state).`));return r}i(Hc,"evaluateAggregatePrivateState");function Kc(e,t,n){let r=[];for(let o of qn(e,t,n))if(o.hasPublicConstructor&&!o.hasStaticFactory){if(!(o.hasPublicMutableFields||o.hasPublicSetters||(o.mutatingMethods?.length??0)>0))continue;r.push(Pe(e,o.file,`Exported class ${o.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}return r}i(Kc,"evaluateAlwaysValidFactory");function Gc(e,t,n){let r=[],o=Fc();for(let s of qn(e,t,n)){let a=$c(s);io(s)!=null&&r.push(Pe(e,s.file,`Exported class ${s.className} shape analysed until character ${io(s)}; later methods may be invisible (sensor domain-event-on-mutation).`));for(let l of s.mutatingMethods)l.referencesGuardOrPublish||r.push(Pe(e,s.file,`Mutating method ${s.className}.${l.name} does not reference ${o} (sensor domain-event-on-mutation).${a}`))}return r}i(Gc,"evaluateDomainEventOnMutation");function Uc(e,t){let n=[];for(let r of t.files)yt(r,e.appliesTo)&&zn(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(Pe(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}i(Uc,"evaluateOrchestrationOnly");function Vc(e,t){let n=[];for(let r of t.files)yt(r,e.appliesTo)&&zn(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(Pe(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}i(Vc,"evaluateThinAdapter");function jc(e,t){let n=[];for(let r of t.files)yt(r,e.appliesTo)&&zn(r,e,t.layerForFile)&&t.fileHints?.[r]?.persistenceWrite&&n.push(Pe(e,r,"File imports a persistence driver and issues a write; route the write through a Domain aggregate and a persistence adapter (sensor writes-via-aggregate)."));return n}i(jc,"evaluateWritesViaAggregate");function Bc(e,t,n){let r=[];for(let o of qn(e,t,n))if(o.dataOnly===!0){let s=Pe(e,o.file,`Exported type ${o.className} looks data-only / anemic (sensor no-anemic-model; advisory only).`);r.push({...s,severity:"warning",failsStrict:!1})}return r}i(Bc,"evaluateNoAnemicModel");function Li(e){if(!e.arkRules.structure.length)return[];let t=[];for(let n of e.arkRules.structure)switch(n.sensor){case"aggregate-private-state":t.push(...Hc(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...Kc(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...Gc(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...Uc(n,e));break;case"thin-adapter":t.push(...Vc(n,e));break;case"writes-via-aggregate":t.push(...jc(n,e));break;case"no-anemic-model":t.push(...Bc(n,e.classShapes,e.layerForFile));break;case"invariant-coverage":break;default:break}return t.sort((n,r)=>n.file.localeCompare(r.file)||n.arkruleId.localeCompare(r.arkruleId)||n.message.localeCompare(r.message))}i(Li,"evaluateArkRuleSensors");function Fi(e,t){let n=[],r=t.map(o=>o.replace(/\\/g,"/"));for(let o of e.structure){if(!o.appliesTo||o.appliesTo.length===0||r.some(c=>yt(c,o.appliesTo)))continue;let{severity:a,failsStrict:l}=Di(o);n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule structure "${o.id}" appliesTo matched zero governed files (patterns: ${o.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:o.provenance.sourceFile,line:1,fromLayer:o.provenance.layer,arkruleId:o.id,arkruleSource:o.provenance.sourceFile,severity:a,sensor:o.sensor,failsStrict:l})}for(let o of e.invariants??[]){if(!o.appliesTo||o.appliesTo.length===0||r.some(l=>yt(l,o.appliesTo)))continue;let a=o.mode==="enforced";n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule invariant "${o.id}" appliesTo matched zero governed files (patterns: ${o.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:o.provenance.sourceFile,line:1,fromLayer:o.provenance.layer,arkruleId:o.id,arkruleSource:o.provenance.sourceFile,severity:a?"error":"warning",sensor:"invariant-coverage",failsStrict:a})}return n.sort((o,s)=>o.file.localeCompare(s.file)||o.arkruleId.localeCompare(s.arkruleId)||o.message.localeCompare(s.message))}i(Fi,"collectEmptyAppliesToFindings");var xi=64;function Wc(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===46;)t-=1;return t===e.length?e:e.slice(0,t)}i(Wc,"stripTrailingDots");function zc(e){let t=e.trim(),n=t.length>xi?t.slice(0,xi):t;return Wc(n)}i(zc,"normalizeIntentPrefix");function qc(e){let t=e.toLowerCase();return t.includes("domain")||t.includes("entity")||t.includes("aggregate")||t.includes("model")}i(qc,"layerNameLooksDomain");function Yc(e){return e.some(t=>{let n=zc(t);return n==="Domain"||n.startsWith("Domain.")})}i(Yc,"ownsDomainIntent");function Xc(e,t=[]){return qc(e)||Yc(t)}i(Xc,"isDomainRoleLayerName");function $i(e){if(e.arkRulesActive!==!0)return[];let t=(e.layers??[]).filter(c=>Xc(c.name,c.intentPrefixes??[])).map(c=>c.name);if(t.length===0)return[];let n=new Set(t);if(!(e.files??[]).some(c=>{let u=typeof c.layer=="string"?c.layer:"";return u.length>0&&n.has(u)}))return[];if((e.arkRules.invariants??[]).filter(c=>n.has(c.provenance.layer)).length>0)return[];let s=t.find(c=>e.arkRules.byLayer?.[c])??t[0],a=e.arkRules.byLayer?.[s]?.sourceFile??`arkrules/${s}.json`,l=(e.arkRules.structure??[]).some(c=>c.mode==="enforced"&&n.has(c.provenance.layer)&&!Ni(c.sensor));return[{ruleId:"INVARIANT_CATALOG_EMPTY",code:"invariant-catalog-empty",message:`ArkRules is on and ${s} has code, but invariants[] is empty \u2014 there are no phrases the code must preserve. Add 1\u20132 short phrases in ${a}.`,file:a,line:1,fromLayer:s,arkruleId:"invariant-catalog",arkruleSource:a,severity:l?"error":"warning",sensor:"invariant-coverage",failsStrict:l}]}i($i,"collectEmptyInvariantCatalogFindings");var Oi=/\bfrom\s+['"](?:@?prisma\/client|@supabase\/|drizzle-orm(?:\/[^'"]+)?|postgres(?:\/[^'"]+)?|typeorm|knex|mongodb|pg|mysql2|mongoose|better-sqlite3|ioredis|redis|kysely|sequelize)['"]|require\(\s*['"](?:@?prisma\/client|pg|postgres(?:\/[^'"]+)?|drizzle-orm(?:\/[^'"]+)?|knex|typeorm|mongoose)/,Pi=/\bfrom\s+['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)(?:\.[cm]?[jt]sx?)?['"]|require\(\s*['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)/,Zc=/\b(?:db|tx|client|prisma(?:Client)?|drizzle)\b(?:\s*\.\s*[A-Za-z_]\w*)*\s*\.\s*(?:insert(?:One|Many)?|update(?:One|Many)?|upsert|delete(?:One|Many)?|createMany|create|replaceOne|findOneAnd(?:Update|Delete|Replace))\s*\(|\bINSERT\s+INTO\b|\bUPDATE\s+[A-Za-z_][\w.]*\s+SET\b|\bDELETE\s+FROM\b/i;function Jc(e){return e==="PersistenceAdapters"}i(Jc,"isPersistenceDriverLayer");function Qc(e,t){if(Oi.test(e)||Pi.test(e))return!0;if(!t)return!1;for(let n of t){if(Jc(n.layer))return!0;let r=n.specifier;if(!r)continue;let o=`from '${r}'`;if(Oi.test(o)||Pi.test(o))return!0}return!1}i(Qc,"sourceImportsPersistenceDriver");var ed=/\b(?:@Controller|@Get|@Post|@Put|@Delete|Router\(\)|createRouter|express\.Router|fastify\.(?:get|post)|export\s+(?:async\s+)?function\s+(?:GET|POST|PUT|DELETE|PATCH)\b|export\s+const\s+(?:GET|POST|PUT|DELETE|PATCH)\s*=)/,td=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,nd=/\b(?:export\s+)?(?:async\s+)?function\s+(?:can|calculate|compute|should|ensure|validate|is|has)[A-Z]\w*|\b(?:export\s+)?const\s+(?:can|calculate|compute|should|ensure|validate|is|has)[A-Z]\w*\s*=/,rd=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function od(e,t,n){if(!t)return null;let r=Qc(t,n),o=r&&Zc.test(t);if(t.length<40)return o?{persistenceWrite:!0}:null;let s=t.match(new RegExp(nd.source,"g"))??[],a=t.match(new RegExp(rd.source,"g"))??[],l=(t.match(/\bif\s*\(/g)??[]).length,c=(t.match(/\bswitch\s*\(/g)??[]).length,u=s.length>=2||s.length>=1&&a.length>=2||a.length>=3&&l+c>=6,f=ed.test(t)||td.test(t),y=s.length>=1||a.length>=2,p=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),g=r&&y||f&&y||r&&p&&(l>=4||s.length>=1)||f&&r;return!u&&!g&&!o?null:{...u?{orchestrationHeavy:!0}:{},...g?{adapterThick:!0}:{},...o?{persistenceWrite:!0}:{}}}i(od,"deriveArkRuleFileHints");function Mi(e,t){let n={};for(let[r,o]of Object.entries(e)){let s=r.replace(/\\/g,"/"),a=od(r,o,t?.[s]);a&&(n[s]=a)}return n}i(Mi,"buildArkRuleFileHints");function sd(e){if(!e)return{};let t=typeof e.governedPercent=="number"?e.governedPercent:null,n=typeof e.populatedLayerCount=="number"?e.populatedLayerCount:null;return n==null&&typeof e.classifiedFiles=="number"&&(n=e.classifiedFiles>0?1:0),{governedPercent:t,populatedLayerCount:n}}i(sd,"normalizeExtraMergeTeethClassification");function Yn(e){let t=sd(e),n=typeof t.governedPercent=="number"?t.governedPercent:null,r=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null;return n==null&&r==null?!0:(n??0)>=50&&(r??0)>=1}i(Yn,"extraMergeTeethAllowed");function Hi(e){let t=e.length,n=0,r=new Set;for(let o of e){let s=typeof o.layer=="string"&&o.layer.length>0?o.layer:null;s&&(n+=1,r.add(s))}return{governedPercent:t>0?Math.round(n/t*100):0,populatedLayerCount:r.size}}i(Hi,"classifyResolvedLayerCoverage");var id=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"];var Hm=new Set(id);function Ki(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")}i(Ki,"isArkRunKernelModuleSpecifier");var ad=["events","node:events","eventemitter2","eventemitter3","emittery","kafkajs","kafka-node","amqplib","amqp","bull","bullmq","mqtt","nats","@aws-sdk/client-sqs","@aws-sdk/client-sns","@aws-sdk/client-eventbridge","@google-cloud/pubsub","@azure/service-bus"],ao=new Set(ad);function Gi(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(ao.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(ao.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:ao.has(e.slice(0,r))}i(Gi,"isArkRunTransportBypassSpecifier");var ld=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],Ym=new Set(ld);var Ui={"arkrun-missing-root":"ARKRUN_MISSING_ROOT","arkrun-kernel-in-domain":"ARKRUN_KERNEL_IN_DOMAIN","arkrun-direct-new":"ARKRUN_DIRECT_NEW","arkrun-undeclared-emit":"ARKRUN_UNDECLARED_EMIT","arkrun-undeclared-handle":"ARKRUN_UNDECLARED_HANDLE","arkrun-undeclared-depend":"ARKRUN_UNDECLARED_DEPEND","arkrun-transport-bypass":"ARKRUN_TRANSPORT_BYPASS"},cd="ARKRUN_INTERACTION_NAME_INCOMPLETE";function Bi(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)||/^(?:entit(?:y|ies)|aggregates?)(?:$|(?=[A-Z_\-\s]))/i.test(n)?!0:t.some(r=>{let o=r.trim().replace(/\.+$/,"");return o==="Domain"||o.startsWith("Domain.")})}i(Bi,"isDomainRoleLayer");function dd(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}i(dd,"compareFindings");function ke(e,t,n,r,o,s,a){let l=e.mode==="enforced"&&a;return{ruleId:Ui[t],sensor:t,message:o,file:n,line:r,...s?.fromLayer?{fromLayer:s.fromLayer}:{},...s?.target?{target:s.target}:{},severity:l?"error":"warning",failsStrict:l,nextAction:pe({ruleId:Ui[t],fromLayer:s?.fromLayer,target:s?.target})}}i(ke,"finding");function ud(e,t){let n=[],r=[],o=[],s=[];for(let a of e)a.file===t&&(n.push(...a.uses),r.push(...a.reactsTo),o.push(...a.raises),s.push(...a.sends));return{uses:new Set(n),reactsTo:new Set(r),raises:new Set(o),sends:new Set(s)}}i(ud,"bagForFile");function Vi(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}i(Vi,"emitKinds");function ji(e){return e==="subscribe"||e==="register-handler"}i(ji,"handleKinds");function pd(e){return e==="resolve"||e==="resolve-singleton"}i(pd,"dependKinds");function fd(e,t,n){let r=[],o=e.kernelRoots??e.compositionRoots;if(o.length===0)return r.push(ke(e,"arkrun-missing-root","ark.config.json",1,"ArkRun kernelRoots is empty; no createArkKernel factory site is declared.",void 0,n)),r;let s=new Map;for(let a of t){let l=s.get(a.matchedRoot)??[];l.push(a),s.set(a.matchedRoot,l)}for(let a of o){let l=[...s.get(a)??[]].sort((u,f)=>u.file.localeCompare(f.file));if(l.length===0){r.push(ke(e,"arkrun-missing-root","ark.config.json",1,`ArkRun kernel root ${JSON.stringify(a)} matched no governed files and has no createArkKernel factory.`,{target:a},n));continue}if(l.some(u=>u.hasKernelFactory))continue;let c=l[0];r.push(ke(e,"arkrun-missing-root",c.file,1,`ArkRun kernel root ${JSON.stringify(a)} has no createArkKernel / createStrictArkKernel factory.`,{target:a},n))}return r}i(fd,"evaluateMissingRoot");function gd(e,t,n,r,o){let s=new Map(t.map(l=>[l.name,l.intentPrefixes??[]])),a=[];for(let l of n){let c=l.specifier;if(!c||!Ki(c))continue;let u=r(l.from);u&&Bi(u,s.get(u)??[])&&a.push(ke(e,"arkrun-kernel-in-domain",l.from,l.line,`${u} must not import kernel module ${JSON.stringify(c)}.`,{fromLayer:u,target:c},o))}return a}i(gd,"evaluateKernelInDomain");function md(e,t,n,r,o,s){let a=new Set(e.managedLayers);if(a.size===0)return[];let l=new Map(t.map(f=>[f.name,f.intentPrefixes??[]])),c=new Set(r.filter(f=>f.hasKernelFactory).map(f=>f.file)),u=[];for(let f of n){if(c.has(f.file))continue;let y=f.typeName;if(e.ignoreDirectNewForErrors!==!1&&(y.endsWith("Error")||y==="Error")||y.endsWith("DTO")||y.endsWith("VO"))continue;let p=o(f.file);!p||!a.has(p)||Bi(p,l.get(p)??[])||u.push(ke(e,"arkrun-direct-new",f.file,f.line,`${p} must not construct ${f.typeName} with new outside an ArkRun composition-root factory.`,{fromLayer:p,target:f.typeName},s))}return u}i(md,"evaluateDirectNew");function yd(e,t,n,r,o){let s=[],a=[];if(e.requireDeclarations!==!0)return{findings:s,completenessReasons:a};let l=new Set(e.managedLayers);if(l.size===0)return{findings:s,completenessReasons:a};for(let c of t){if(!Vi(c.kind)&&!ji(c.kind)&&!pd(c.kind))continue;let u=r(c.file);if(!u||!l.has(u))continue;if(!c.nameLiteral){e.mode==="enforced"&&a.push({code:cd,file:c.file,message:`ArkRun ${c.kind} call in ${c.file} has no string-literal name; enforced extra cannot prove the declaration.`});continue}let f=ud(n,c.file);if(Vi(c.kind)){if(f.raises.has(c.nameLiteral)||f.sends.has(c.nameLiteral))continue;s.push(ke(e,"arkrun-undeclared-emit",c.file,c.line,`Emit ${JSON.stringify(c.nameLiteral)} is not declared in raises or sends.`,{fromLayer:u,target:c.nameLiteral},o));continue}if(ji(c.kind)){if(f.reactsTo.has(c.nameLiteral))continue;s.push(ke(e,"arkrun-undeclared-handle",c.file,c.line,`Handle ${JSON.stringify(c.nameLiteral)} is not declared in reactsTo.`,{fromLayer:u,target:c.nameLiteral},o));continue}f.uses.has(c.nameLiteral)||s.push(ke(e,"arkrun-undeclared-depend",c.file,c.line,`Depend ${JSON.stringify(c.nameLiteral)} is not declared in uses.`,{fromLayer:u,target:c.nameLiteral},o))}return{findings:s,completenessReasons:a}}i(yd,"evaluateUndeclared");function hd(e,t,n,r){let o=new Set(e.managedLayers);if(o.size===0)return[];let s=[];for(let a of t){if(a.typeOnly)continue;let l=a.specifier;if(!l||!Gi(l))continue;let c=n(a.from);!c||!o.has(c)||s.push(ke(e,"arkrun-transport-bypass",a.from,a.line,`${c} must not import broker/queue/emitter ${JSON.stringify(l)}; use the ArkRun kernel transport.`,{fromLayer:c,target:l},r))}return s}i(hd,"evaluateTransportBypass");function Wi(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=Yn(e.classification),r=yd(t,e.kernelCalls,e.declarations,e.layerForFile,n),o=[...fd(t,e.compositionRootHits,n),...gd(t,e.layers,e.dependencies,e.layerForFile,n),...md(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...hd(t,e.dependencies,e.layerForFile,n)].sort(dd),s=[...r.completenessReasons].sort((a,l)=>{let c=`${a.code}\0${a.file??""}\0${a.message}`,u=`${l.code}\0${l.file??""}\0${l.message}`;return c<u?-1:c>u?1:0});return{findings:o,completenessReasons:s}}i(Wi,"evaluateArkRunSensors");function zi(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}i(zi,"isArkOrderModuleSpecifier");var qi=new Map;function Yi(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(Yi,"escapeAppliesToLiteral");function Rd(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(Rd,"normalizeAppliesToGlob");function Ad(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(Ad,"appliesToBracesBalanced");function kd(e){let t=qi.get(e);if(t)return t;let n=Rd(e),r=Ad(n),o="",s=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(o+=Yi(n[l+1]),l+=1):c==="*"?n[l+1]==="*"?n[l+2]==="/"?(o+="(?:.*/)?",l+=2):(o+=".*",l+=1):o+="[^/]*":c==="?"?o+="[^/]":c==="{"&&r?(o+="(?:",s+=1):c==="}"&&r&&s>0?(o+=")",s-=1):c===","&&r&&s>0?o+="|":o+=Yi(c)}let a=new RegExp(`^${o}$`);return qi.set(e,a),a}i(kd,"globToRegExp");var Xi={"arkorder-missing-plane":"ARKORDER_MISSING_PLANE","arkorder-kernel-in-domain":"ARKORDER_KERNEL_IN_DOMAIN","arkorder-generic-update":"ARKORDER_GENERIC_UPDATE","arkorder-too-many-params":"ARKORDER_TOO_MANY_PARAMS","arkorder-ingest-writes-xi":"ARKORDER_INGEST_WRITES_XI","arkorder-xi-field-write":"ARKORDER_XI_FIELD_WRITE","arkorder-information-budget":"ARKORDER_INFORMATION_BUDGET","arkorder-xi-ttl":"ARKORDER_XI_TTL"};function Id(e,t){return!t||t.length===0?!0:t.some(n=>kd(n).test(e))}i(Id,"matchesArkOrderAppliesTo");function bd(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)?!0:t.some(r=>{let o=r.trim().replace(/\.+$/,"");return o==="Domain"||o.startsWith("Domain.")})}i(bd,"isDomainRoleLayer");function _e(e,t,n,r,o,s,a){let l=e.mode==="enforced"&&a;return{ruleId:Xi[t],sensor:t,message:o,file:n,line:r,...s?.fromLayer?{fromLayer:s.fromLayer}:{},...s?.target?{target:s.target}:{},severity:l?"error":"warning",failsStrict:l,nextAction:pe({ruleId:Xi[t],fromLayer:s?.fromLayer,target:s?.target})}}i(_e,"finding");function Zi(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let n=Yn(e.classification),r=[],o=t.planeRoots;if(t.mode==="enforced"&&o.length===0)r.push(_e(t,"arkorder-missing-plane","ark.config.json",1,"ArkOrder planeRoots is empty; no createOrderPlane site is declared.",void 0,n));else{let c=new Map;for(let u of e.planeRootHits){let f=c.get(u.matchedRoot)??[];f.push(u),c.set(u.matchedRoot,f)}for(let u of o){let f=c.get(u)??[];if(f.length===0){r.push(_e(t,"arkorder-missing-plane","ark.config.json",1,`ArkOrder plane root ${JSON.stringify(u)} matched no governed files and has no createOrderPlane factory.`,{target:u},n));continue}f.some(y=>y.hasPlaneFactory)||r.push(_e(t,"arkorder-missing-plane",f[0].file,1,`ArkOrder plane root ${JSON.stringify(u)} has no createOrderPlane factory.`,{target:u},n))}}let s=new Map(e.layers.map(c=>[c.name,c.intentPrefixes??[]]));for(let c of e.dependencies){let u=c.specifier;if(!u||!zi(u))continue;let f=e.layerForFile(c.from);f&&bd(f,s.get(f)??[])&&r.push(_e(t,"arkorder-kernel-in-domain",c.from,c.line,"Domain-role layer imports arkgate/order; Domain stays plane-free.",{fromLayer:f,target:u},n))}for(let c of e.genericUpdates)r.push(_e(t,"arkorder-generic-update",c.file,c.line,`Generic ${c.method}() on the order plane rewrites \u03BE; Haken forbids it.`,{target:c.method},n));let a=t.xiKeys??[];for(let c of e.releaseKeyCounts??[])c.keyCount<=t.maxXiKeys||r.push(_e(t,"arkorder-too-many-params",c.file,c.line,`release() freezes ${c.keyCount} keys; maxXiKeys is ${t.maxXiKeys} (few slow modes).`,{target:String(c.keyCount)},n));for(let c of e.ingestWritesXi??[])r.push(_e(t,"arkorder-ingest-writes-xi",c.file,c.line,"ingest() result is assigned into a Release or \u03BE store; ingest may absorb or escalate, never mint a pattern.",void 0,n));let l=new Set(t.managedLayers);for(let c of a.length===0?[]:e.xiFieldWrites??[]){let u=e.layerForFile(c.file);!u||!l.has(u)||Id(c.file,t.appliesTo)&&r.push(_e(t,"arkorder-xi-field-write",c.file,c.line,`This file writes ${JSON.stringify(c.key)} the same way it would write a seat count. Take the event in, or change that choice through the valve (propose, then apply).`,{fromLayer:u,target:c.key},n))}return r.sort((c,u)=>c.file.localeCompare(u.file)||c.ruleId.localeCompare(u.ruleId)||c.line-u.line),{findings:r,completenessReasons:[]}}i(Zi,"evaluateArkOrderSensors");function J(e,t,n={}){return{ruleId:e,message:t,...n}}i(J,"configWarning");function Xn(e){let{config:t,rules:n,files:r,manifest:o}=e,s=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(d=>typeof d!="string"))&&s.push(J("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","dynamicImportAllowlist must be an array of file globs.")),t.safety!==void 0&&(t.safety===null||typeof t.safety!="object"||Array.isArray(t.safety)))s.push(J("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let d of["maxTsSuppressions","maxAnyCasts"]){let m=t.safety[d];m!==void 0&&(!Number.isInteger(m)||m<0)&&s.push(J("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${d} must be a non-negative integer.`))}let a=Array.isArray(t.layers)?t.layers:[],l=Array.isArray(o?.architecture?.layers)?o.architecture.layers:[],c=new Set([...a.map(d=>d.name).filter(Boolean),...l.map(d=>d.name).filter(d=>!!d)]);a.length===0&&s.push(J("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let u=new Set,f=new Set;for(let d of a){if(!d.name){s.push(J("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}u.has(d.name)&&f.add(d.name),u.add(d.name),d.forbiddenGlobals!==void 0&&(!Array.isArray(d.forbiddenGlobals)||d.forbiddenGlobals.some(E=>typeof E!="string"))&&s.push(J("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${d.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:d.name}));let m=Array.isArray(d.patterns)?d.patterns:[];if(m.length===0){s.push(J("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${d.name}" has no file patterns and will never classify files.`,{layer:d.name}));continue}for(let E of m){let S;try{S=ye(E)}catch(v){s.push(J("CONFIG_INVALID_LAYER_PATTERN",`Layer "${d.name}" has an invalid pattern "${E}": ${v instanceof Error?v.message:String(v)}`,{layer:d.name,pattern:E}));continue}let k=d.optional===!0||d.reserved===!0||d.allowEmpty===!0;!r.some(v=>S.test(v))&&!k&&s.push(J("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${d.name}" pattern "${E}" matched no included files (possible typo). Mark the layer reserved/allowEmpty if this house is reserved for later.`,{layer:d.name,pattern:E,failsStrict:!1,reserved:!1}))}}for(let d of f)s.push(J("CONFIG_DUPLICATE_LAYER",`Layer "${d}" is configured more than once.`,{layer:d}));if(c.size>0)for(let d of n??[])d.from&&!c.has(d.from)&&s.push(J("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${d.from}".`,{fromLayer:d.from,toLayer:d.to})),d.to&&!c.has(d.to)&&s.push(J("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${d.to}".`,{fromLayer:d.from,toLayer:d.to}));let y=new Set;if(a.length>1)for(let d of r){let m=-1,E=[];for(let S of a)for(let k of S.patterns??[]){if(!ye(k).test(d))continue;let v=Sr(k,d);v>m?(m=v,E=[S.name]):v===m&&!E.includes(S.name)&&E.push(S.name)}E.length>1&&y.add([...E].sort().join(" + "))}y.size>0&&s.push(J("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...y].join(", ")}.`,{pairs:[...y]}));let p=r.filter(d=>!de(d,a));p.length>0&&s.push(J("CONFIG_UNCLASSIFIED_FILES",`${p.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:p.length,samples:p.slice(0,5)}));for(let d of ns(n))s.push(J("CONFIG_SLICE_IDENTITY_COLLISION",d.message,{paths:[...d.paths],fromLayer:d.from,toLayer:d.to,failsStrict:!1}));let g=Ns(t);if(g.length>0){let d=g[0]??"this layer";s.push(J("CONFIG_LAYER_MISSING_OWNER",`${d} has no owner. Add a GitHub handle or email to layers[].owners so this house has a name on the door.`,{layers:g,nextAction:Ds(d)}))}return s}i(Xn,"collectAnalysisConfigWarnings");function Ji(e,t){let n=e.ruleId==="ARKRULE_STRUCTURE",r=e.ruleId==="ARKRULE_SCOPE_EMPTY",o=e.ruleId==="INVARIANT_CATALOG_EMPTY";return{ruleId:e.ruleId,file:e.file,line:e.line,message:e.message,fromLayer:e.fromLayer,arkruleId:e.arkruleId,arkruleSource:e.arkruleSource,...n?{sensor:e.sensor,code:e.code,target:wi({sensor:e.sensor,code:e.code})}:{},...r||o?{freezable:!1}:{},nextAction:t}}i(Ji,"toArkRuleEngineViolation");function vd(e){let t=e.arkRules;return!!(t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0)}i(vd,"arkRulesMapIsOn");function Qi(e,t){return e.ruleId==="INVARIANT_CATALOG_EMPTY"?t?`Add 1\u20132 short phrases to invariants[] in ${e.arkruleSource} so Domain has policies the code must preserve (advisory \u2014 does not fail the merge until a domain structure rule is enforced).`:`Add 1\u20132 short phrases to invariants[] in ${e.arkruleSource} so Domain has policies the code must preserve. Empty catalog fails --strict-merge because a domain structure rule is already enforced.`:e.ruleId==="ARKRULE_SCOPE_EMPTY"?t?`Review appliesTo for ${e.arkruleId} in ${e.arkruleSource} (zero-match scope; advisory). Empty scope is not freezable; promote only after the folder exists.`:`Fix appliesTo globs for ${e.arkruleId} in ${e.arkruleSource} so they match governed files, or remove the rule. ARKRULE_SCOPE_EMPTY is a config diagnostic and is not freezable (even with --force). Land the rule as advisory until the folder exists, then promote.`:t?`Review ArkRule ${e.arkruleId} in ${e.arkruleSource} (advisory).`:`Fix the structure or invariant for ${e.arkruleId} (declared in ${e.arkruleSource}), then preflight again.`}i(Qi,"arkRuleFindingNextAction");function Ed(e,t){return t.some(n=>{try{return ye(n).test(e)}catch{return!1}})}i(Ed,"matchesAny");function Sd(e,t){let n=e.contract.config.safety??{},r=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,o=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,s=e.contract.config.dynamicImportAllowlist??[],a=t.safetyUses.filter(m=>m.kind==="ts-suppression").map(({file:m,line:E})=>({file:m,line:E})),l=t.safetyUses.filter(m=>m.kind==="any-cast").map(({file:m,line:E})=>({file:m,line:E})),c=t.safetyUses.filter(m=>(m.kind==="dynamic-import"||m.kind==="dynamic-require")&&!Ed(m.file,s)).map(m=>({file:m.file,line:m.line,kind:m.kind==="dynamic-require"?"require":"import"})),u=n.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(m=>m.kind==="in-memory-store").map(m=>({file:m.file,line:m.line,store:m.symbol??"in-memory store"})),f=n.allowDisabledPeerIsolation===!0?[]:(e.contract.config.rules??[]).filter(m=>m.peerIsolation===!1||m.allowed===!1&&!!m.from&&m.from===m.to&&m.peerIsolation!==!0).map(m=>({from:m.from,to:m.to})),y={tsSuppressions:a,anyCasts:l,nonLiteralDynamicImports:c,inMemoryProductionStores:u,disabledPeerIsolationRules:f,thresholds:{maxTsSuppressions:r,maxAnyCasts:o}},p=[],g=c.filter(m=>m.kind==="import");if(g.length>0){let m=g[0];p.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:m.file,line:m.line,message:`${g.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let d=c.filter(m=>m.kind==="require");if(d.length>0){let m=d[0];p.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:m.file,line:m.line,message:`${d.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(a.length>r){let m=a[0];p.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:m.file,line:m.line,message:`${a.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${r}).`})}if(l.length>o){let m=l[0];p.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:m.file,line:m.line,message:`${l.length} explicit any cast(s) exceed safety.maxAnyCasts (${o}).`})}if(u.length>0){let m=u[0];p.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:m.file,line:m.line,message:`${u.length} ArkGate InMemory store risk(s) appear in governed production source. Provide durable stores or set safety.allowInMemory only for an explicitly ephemeral service.`})}return f.length>0&&p.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${f.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:y,warnings:p}}i(Sd,"evaluateSafety");function wd(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}i(wd,"ambientForbiddenGlobal");function ea(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return Ur(e,n.length>0?n:Gr.map(r=>({name:r.layer,prefixes:r.prefixes})))}i(ea,"intentLayer");function Cd(e,t,n){let r=[],o=new Map(e.contract.config.layers.map(s=>[s.name,s]));for(let s of t.ambientUses){let a=n.get(s.file);!a||!wd(s.symbol,o.get(a)?.forbiddenGlobals??[])||r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:a,target:s.symbol,message:`${a} must not use the ambient global "${s.symbol}".`})}for(let s of t.capabilityUses){let a=n.get(s.file);if(!a)continue;let l=o.get(a),c=l?.forbiddenGlobals??[],u=s.source==="import-based"?t.dependencies.find(f=>f.from===s.file&&f.line===s.line&&f.specifier===s.symbol&&!f.typeOnly)?.kind:void 0;if(!(s.source==="ambient-global"&&Dt(s.symbol,c))){if(s.source==="import-based"){let f=xe(s.symbol,c);if(f){r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:a,target:s.symbol,...u?{edgeKind:u}:{},message:`${a} must not use module "${s.symbol}" because it is the import form of forbidden global "${f}".`});continue}}lt(l).includes(s.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:s.file,line:s.line,fromLayer:a,target:s.symbol,capability:s.capability,...u?{edgeKind:u}:{},message:s.source==="import-based"?`${a} denies the ${s.capability} capability; found import of "${s.symbol}".`:`${a} denies the ${s.capability} capability; found ambient "${s.symbol}".`})}}for(let s of t.publishCalls){let a=n.get(s.file);if(!a)continue;for(let c of Lt({publishCall:!0,rawIntentName:s.rawIntentName,objectHasIntent:s.objectHasIntent,arkPublishCandidate:s.arkPublishCandidate,hasSource:s.hasSource}))r.push({ruleId:c.ruleId,file:s.file,line:s.line,...c.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:a}:{},message:c.message});if(!s.sourceIntent)continue;let l=ea(s.sourceIntent,e.contract);!l||l===a||r.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:s.file,line:s.line,fromLayer:a,toLayer:l,target:s.sourceIntent,message:`Publish source "${s.sourceIntent}" resolves to ${l}, but the publishing file is classified as ${a}.`})}for(let s of t.intentReferences){let a=n.get(s.file);if(!a)continue;let l=ea(s.intent,e.contract);if(!l)continue;let c=$e(e.contract.config.rules,a,l,{fromPath:s.file,layers:e.contract.config.layers});if(!c)continue;let u=c.rule.peerIsolation?rt(c.peerIsolationReason??"cross-slice",{fromPath:s.file,fromSlice:c.fromSlice,toSlice:c.toSlice}):void 0,f=`${a} must not reference ${l} intent ${s.intent}.`,y=u&&c.peerIsolationReason!=="cross-slice"?`${f} ${u}`:c.rule.message?u?`${c.rule.message} (${u})`:c.rule.message:f;r.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:s.file,line:s.line,fromLayer:a,toLayer:l,target:s.intent,...c.rule.peerIsolation?{peerIsolation:!0}:{},message:y})}return r}i(Cd,"contentViolations");function xd(e){let{facts:t}=e,n=Ht(e.contract.config),r=t.evidenceRequirementsHash===n,o=r?t.completeness:"unavailable",s=r?t.completenessReasons:[...t.completenessReasons,{code:"EVIDENCE_REQUIREMENTS_MISMATCH",message:"Resolved facts were collected for different policy-controlled evidence requirements."}].sort((R,ee)=>{let vt=`${R.code}\0${R.file??""}\0${R.message}`,Et=`${ee.code}\0${ee.file??""}\0${ee.message}`;return vt<Et?-1:vt>Et?1:0}),a=t.files.map(R=>({...R,layer:de(R.path,e.contract.config.layers)??null})),l=new Map(a.map(R=>[R.path,R.layer])),c=t.dependencies.map(R=>{let ee=R.target?l.get(R.target)??de(R.target,e.contract.config.layers):void 0;return{from:R.from,fromLayer:l.get(R.from)??null,...R.resolution==="resolved-project"&&R.target?{to:R.target,...ee?{toLayer:ee}:{}}:{},line:R.line,kind:R.kind,typeOnly:R.typeOnly,...R.targetTypeOnlyExports?{targetTypeOnlyExports:R.targetTypeOnlyExports}:{},...R.sourcePureTypeModule?{sourcePureTypeModule:R.sourcePureTypeModule}:{},...R.namedBindingsTypeOnly?{namedBindingsTypeOnly:R.namedBindingsTypeOnly}:{},...R.portProofEligible?{portProofEligible:R.portProofEligible}:{}}}),u=Xn({config:e.contract.config,rules:e.contract.config.rules,files:a.map(R=>R.path)}),f=Sd(e,t),y=e.contract.arkRules??Gt(),p=a.map(R=>R.path),d={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?Mi(e.coverageInputs.fileContents):{},...e.fileHints??{}},m=i(R=>l.get(R)??de(R,e.contract.config.layers),"resolveLayer"),E=[...Li({arkRules:y,classShapes:e.contract.classShapes??t.classShapes??[],files:p,layerForFile:m,fileHints:d}),...Fi(y,p),...$i({arkRulesActive:vd(e.contract.config),arkRules:y,layers:e.contract.config.layers??[],files:p.map(R=>({path:R,layer:m(R)}))})],S=(y.invariants?.length??0)>0,k=gi({hasEnforcedInvariant:Qr(y.invariants),coverage:e.contract.config.coverage,...e.coverageRootsPresent===!1?{declaredPathPresent:!1}:{}}),v=k.length>0?[]:fi({adopted:e.adopted===!0,hasDomainInvariants:Jr(y.invariants),coverage:e.contract.config.coverage,...e.invariantTestsPathPresent===!1?{declaredPathPresent:!1}:{}}),C=[...k.map(R=>({ruleId:R.ruleId,file:R.file,line:R.line,message:R.message,nextAction:"Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. An enforced invariant fails closed until that path is present.",failsStrict:!0,freezable:!1})),...v.map(R=>({ruleId:R.ruleId,file:R.file,line:R.line,message:R.message,nextAction:"Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present.",failsStrict:!0,freezable:!1}))],N=E.filter(R=>R.failsStrict).map(R=>Ji(R,Qi(R,!1))),b=E.filter(R=>!R.failsStrict).map(R=>({...Ji(R,Qi(R,!0)),failsStrict:!1})),T=S?ui({arkRules:y,fileContents:e.coverageInputs?.fileContents??{},testFiles:e.coverageInputs?.testFiles??[],testGlobsMissing:e.coverageInputs?.testGlobsMissing===!0||e.coverageInputs===void 0||(e.coverageInputs.testFiles?.length??0)===0,coverageBudgetExhausted:e.coverageInputs?.coverageBudgetExhausted===!0,...e.coverageInputs?.stats?{coverageStats:e.coverageInputs.stats}:{},...e.coverageInputs?.coverageRoots?{coverageRoots:e.coverageInputs.coverageRoots}:{}}):{coverage:[],violations:[],partial:!1},De=T.violations.filter(R=>R.failsStrict).map(R=>({ruleId:R.ruleId,file:R.file,line:R.line,message:R.message,fromLayer:R.fromLayer,arkruleId:R.arkruleId,arkruleSource:R.arkruleSource,nextAction:`Add a test title or declared symbol covering ${R.arkruleId} (declared in ${R.arkruleSource}), then preflight again.`})),ge=T.violations.filter(R=>!R.failsStrict).map(R=>({ruleId:R.ruleId,file:R.file,line:R.line,message:R.message,fromLayer:R.fromLayer,arkruleId:R.arkruleId,arkruleSource:R.arkruleSource,failsStrict:!1,nextAction:R.ruleId==="INVARIANT_COVERAGE_OUTSIDE_ROOTS"?`Move ${R.file} under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json.`:`Cover invariant ${R.arkruleId} in ${R.arkruleSource} (advisory / partial).`})),ve=Hi(a),D=Wi({arkRun:e.contract.config.arkRun,layers:e.contract.config.layers,kernelCalls:t.arkRunKernelCalls,managedNews:t.arkRunManagedNews,compositionRootHits:t.arkRunCompositionRootHits,declarations:t.arkRunDeclarations,dependencies:t.dependencies,layerForFile:i(R=>l.get(R)??de(R,e.contract.config.layers),"layerForFile"),classification:ve}),z=e.contract.config.arkRun?.mode,q=D.findings.filter(()=>z==="enforced").map(R=>({ruleId:R.ruleId,file:R.file,line:R.line,message:R.message,fromLayer:R.fromLayer,target:R.target,nextAction:R.nextAction,sensor:R.sensor,failsStrict:R.failsStrict,...R.severity?{severity:R.severity}:{}})),me=D.findings.filter(()=>z!=="enforced").map(R=>({ruleId:R.ruleId,file:R.file,line:R.line,message:R.message,fromLayer:R.fromLayer,target:R.target,nextAction:R.nextAction,sensor:R.sensor,failsStrict:!1})),Ee=Zi({arkOrder:e.contract.config.arkOrder,layers:e.contract.config.layers,planeCalls:t.arkOrderPlaneCalls,genericUpdates:t.arkOrderGenericUpdates,planeRootHits:t.arkOrderRootHits,xiFieldWrites:t.arkOrderXiFieldWrites,ingestWritesXi:t.arkOrderIngestWritesXi,releaseKeyCounts:t.arkOrderReleaseKeyCounts,dependencies:t.dependencies,layerForFile:i(R=>l.get(R)??de(R,e.contract.config.layers),"layerForFile"),classification:ve}),bt=e.contract.config.arkOrder?.mode,fn=Ee.findings.filter(()=>bt==="enforced").map(R=>({ruleId:R.ruleId,file:R.file,line:R.line,message:R.message,fromLayer:R.fromLayer,target:R.target,nextAction:R.nextAction,sensor:R.sensor,failsStrict:R.failsStrict,...R.severity?{severity:R.severity}:{}})),$o=Ee.findings.filter(()=>bt!=="enforced").map(R=>({ruleId:R.ruleId,file:R.file,line:R.line,message:R.message,fromLayer:R.fromLayer,target:R.target,nextAction:R.nextAction,sensor:R.sensor,failsStrict:!1})),w=[...T.partial&&T.coverage.some(R=>R.mode==="enforced"&&R.partial)?[{code:"INVARIANT_COVERAGE_PARTIAL",message:"Enforced ArkRules invariant coverage cannot be fully proven (missing test globs or empty test set); reporting partial, never covered."}]:[],...D.completenessReasons,...Ee.completenessReasons],x=mt({config:e.contract.config,rules:e.contract.config.rules,files:a.filter(R=>R.layer).map(R=>R.path),contentViolations:[...Cd(e,t,l),...N,...C,...De,...q,...fn],edges:c,warnings:[...u,...f.warnings,...b,...ge,...me,...$o],safety:f.report}),h=o==="complete"&&w.length>0?"partial":o,A=h==="complete"?s:[...s,...w].sort((R,ee)=>{let vt=`${R.code}\0${R.file??""}\0${R.message}`,Et=`${ee.code}\0${ee.file??""}\0${ee.message}`;return vt<Et?-1:vt>Et?1:0}),L=x.violations.filter(R=>R.failsStrict!==!1),W=h==="complete"&&L.length===0,Se=W&&x.warnings.every(R=>R.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:h,completenessReasons:A,valid:W,strictValid:Se,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:f.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:a,layers:e.contract.config.layers.map(R=>R.name),edges:c,capabilityUses:t.capabilityUses,violations:x.violations,warnings:x.warnings}}}i(xd,"analyzeCanonicalResolvedProject");function Bt(e){return xd({contract:e.contract,facts:Oe(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints,adopted:e.adopted,invariantTestsPathPresent:e.invariantTestsPathPresent,coverageRootsPresent:e.coverageRootsPresent})}i(Bt,"analyzeResolvedProject");function ta(e){return Y(M(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}i(ta,"analysisTreeHash");function na(e){let t=jt(e),n=new Map(t.ir.files.map(d=>[d.path,d])),r=[],o=new Set,s=[];for(let d of e.changes){let m=d.path.replace(/\\/g,"/"),E=Ue(d.path);if(!E||E===".."||E.startsWith("../")||m.startsWith("/")||/^[A-Za-z]:\//.test(m)||m.includes("\0")){s.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(o.has(E)){s.push({ruleId:"DUPLICATE_CHANGE_PATH",file:E,line:1,message:`The atomic change set contains more than one operation for ${E}.`});continue}o.add(E),"delete"in d&&d.delete&&!n.has(E)&&s.push({ruleId:"DELETE_TARGET_MISSING",file:E,line:1,message:`Cannot delete ${E} because it is not present in the supplied base tree.`}),r.push("delete"in d&&d.delete?{path:E,delete:!0}:{path:E,content:"content"in d?d.content:""})}e.changes.length===0&&s.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let a=Wn({...e,changes:r}),l=new Map(a.ir.files.map(d=>[d.path,d])),c=a.ir.violations.filter(d=>d.ruleId==="CAPABILITY_VIOLATION"||d.ruleId==="FORBIDDEN_GLOBAL").map(d=>{let m=l.get(d.evidence.file)?.layer;return{ruleId:d.ruleId,file:d.evidence.file,line:d.evidence.line,target:d.symbol,...d.capability?{capability:d.capability}:{},...m?{fromLayer:m}:{},edgeKind:"import",message:d.message}}),u=mt({config:e.contract.config,rules:e.contract.config.rules,files:a.ir.files.map(d=>d.path),contentViolations:c,edges:a.ir.edges.filter(d=>!!d.fromLayer).map(d=>({from:d.from,fromLayer:d.fromLayer,...d.to?{to:d.to}:{},...d.toLayer?{toLayer:d.toLayer}:{},line:d.evidence.line,kind:"import",...d.typeOnly?{typeOnly:!0}:{},...d.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),f=r.map(d=>{let m=Ue(d.path),E=n.get(m),S=l.get(m);return{path:m,operation:"delete"in d&&d.delete?"delete":E?"update":"create",...E?{beforeContentHash:E.contentHash}:{},...S?{candidateContentHash:S.contentHash}:{}}}).sort((d,m)=>d.path.localeCompare(m.path)),y=[...s,...u.violations].map(d=>({...d,nextAction:pe(d)})),p=y.filter(d=>d.failsStrict!==!1),g=e.changeMap?gt({changeMap:e.changeMap,changes:f,baseDependencies:t.ir.edges.flatMap(d=>d.to?[{from:d.from,to:d.to}]:[]),candidateDependencies:a.ir.edges.flatMap(d=>d.to?[{from:d.from,to:d.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&a.valid&&p.length===0&&(g?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:a.ir.compilerOptionsHash,baseTreeHash:ta(t.ir.files),candidateTreeHash:ta(a.ir.files),baseCompleteness:t.completeness,candidateCompleteness:a.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:a.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...g?{convergence:g}:{},changes:f,violations:y,warnings:u.warnings}}i(na,"preflightChange");function Od(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let o of t.split("/"))if(!(!o||o==="."))if(o===".."){if(n.length===0)return;n.pop()}else n.push(o);let r=n.join("/");return r&&r===t?r:void 0}i(Od,"canonicalChangePath");function Pd(e,t){return[["resolverIdentity",e.resolverIdentity,t.resolverIdentity],["compilerIdentity",e.compilerIdentity,t.compilerIdentity],["evidenceRequirementsHash",e.evidenceRequirementsHash,t.evidenceRequirementsHash],["projectPackageName",e.projectPackageName??"",t.projectPackageName??""]].filter(([,r,o])=>r!==o).map(([r,o,s])=>({ruleId:"FACTS_IDENTITY_MISMATCH",file:"<change-set>",line:1,field:r,before:o,candidate:s,message:`Base and candidate facts must use the same ${r}.`}))}i(Pd,"identityViolations");function _d(e,t,n,r){let o=n.get(t),s=r.get(t);return{path:t,operation:"delete"in e&&e.delete?"delete":o?"update":"create",...o?{beforeContentHash:o.contentHash}:{},...s?{candidateContentHash:s.contentHash}:{}}}i(_d,"preparedChange");function ra(e){let t=Oe(e.baseFacts),n=Oe(e.candidateFacts),r=Bt({contract:e.contract,facts:t}),o=Bt({contract:e.contract,facts:n}),s=new Map(t.files.map(g=>[g.path,g])),a=new Map(n.files.map(g=>[g.path,g])),l=Pd(t,n),c=new Map,u=[];for(let g of e.changes){let d=Od(g.path);if(!d){l.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(c.has(d)){l.push({ruleId:"DUPLICATE_CHANGE_PATH",file:d,line:1,message:`The atomic change set contains more than one operation for ${d}.`});continue}c.set(d,g);let m=s.get(d),E=a.get(d);if("delete"in g&&g.delete)m||l.push({ruleId:"DELETE_TARGET_MISSING",file:d,line:1,message:`Cannot delete ${d} because it is not present in the supplied base facts.`}),E&&l.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:d,line:1,message:`Candidate facts still contain deleted file ${d}.`});else{let S="content"in g?g.content:"",k=Y(S);E?E.contentHash!==k&&l.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:d,line:1,expectedContentHash:k,candidateContentHash:E.contentHash,message:`Candidate facts for ${d} do not match the declared content.`}):l.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:d,line:1,message:`Candidate facts do not contain changed file ${d}.`})}u.push(_d(g,d,s,a))}e.changes.length===0&&l.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});for(let g of new Set([...s.keys(),...a.keys()])){if(c.has(g))continue;let d=s.get(g),m=a.get(g);d&&m&&M(d)===M(m)||l.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:g,line:1,message:`Candidate facts change ${g}, but the atomic change set does not declare it.`})}let f=e.changeMap?gt({changeMap:e.changeMap,changes:u,baseDependencies:r.ir.edges.flatMap(g=>g.to?[{from:g.from,to:g.to}]:[]),candidateDependencies:o.ir.edges.flatMap(g=>g.to?[{from:g.from,to:g.to}]:[])}):void 0,y=[...l,...o.ir.violations].map(g=>({...g,nextAction:pe(g)})),p=y.filter(g=>g.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&o.strictValid&&p.length===0&&(f?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,resolverIdentity:n.resolverIdentity,compilerIdentity:n.compilerIdentity,compilerOptionsHash:n.compilerOptionsHash,tsconfigHash:n.tsconfigHash,baseCompilerOptionsHash:t.compilerOptionsHash,candidateCompilerOptionsHash:n.compilerOptionsHash,baseTsconfigHash:t.tsconfigHash,candidateTsconfigHash:n.tsconfigHash,evidenceRequirementsHash:n.evidenceRequirementsHash,baseFactsHash:t.factsHash,candidateFactsHash:n.factsHash,baseTreeHash:t.candidateTreeHash,candidateTreeHash:n.candidateTreeHash,baseCompleteness:r.completeness,candidateCompleteness:o.completeness,baseCompletenessReasons:r.completenessReasons,candidateCompletenessReasons:o.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...f?{convergence:f}:{},changes:u.sort((g,d)=>g.path<d.path?-1:g.path>d.path?1:0),violations:y,warnings:o.ir.warnings}}i(ra,"preflightResolvedChange");var lo="docs/diagnostics.md",Td="1.0";function I(e,t,n,r,o,s){return{ruleId:e,title:n,why:r,fix:o,docsAnchor:e,category:t,...s?.oftenAdvisory?{oftenAdvisory:!0}:{}}}i(I,"entry");var Zn=Object.freeze([I("LAYER_IMPORT_VIOLATION","layer","This import is not allowed","This file imported a folder it may not reach. The write doesn\u2019t land. The same check fails the pull request.","Branch by import kind: constants/types/pure \u2192 adopt into DomainModel or SharedKernel (do not invent a port); kernel/events/bootstrap from Persistence \u2192 inject a port or move the map to SharedTypes (Persistence must not emit); define a port only when the target is a real use-case. Type-only edges use `import type`. Then preflight again. Do not weaken the layer rule without a hash-bound policy acknowledgement."),I("LAYER_INTENT_REFERENCE_VIOLATION","layer","Intent referenced across a blocked layer edge","A string intent (or intent-like reference) names a layer that the file\u2019s layer may not reach under the contract rules \u2014 the same plane as import edges, for event/intent coupling.","Reference that intent from a layer allowed to know about it (usually an adapter or application layer), or relocate the reference \u2014 then preflight again."),I("LAYER_REFERENCE_VIOLATION","layer","Layer reference blocked (snippet / AI gate)","Snippet analysis found an intent or string reference that would couple layers in a direction the architecture profile forbids.","Move the reference to an allowed layer or introduce a port/event boundary, then re-run the snippet gate."),I("CIRCULAR_DEPENDENCY","layer","Dependency cycle","Two or more modules import each other in a loop. Cycles make ownership unclear and break stable layer direction.","Extract the shared dependency into a third module, invert one edge behind a port, or merge units that are truly one \u2014 then preflight again."),I("FORBIDDEN_GLOBAL","capability","Forbidden ambient global or dual import","The file\u2019s layer lists this ambient (or its exact import dual, e.g. process / node:process) in forbiddenGlobals. Pure layers must not reach wall-clock, network, process, or similar effects directly.","Inject the capability through a small port (Clock, HttpPort, Config, \u2026), bind the implementation outside the walled layer, then preflight again."),I("CAPABILITY_VIOLATION","capability","Denied effect capability","The layer denies an effect capability (network, filesystem, clock, randomness, environment, process, persistence) and the candidate uses that effect via ambient or import evidence.","Define a capability port in the walled layer, bind the implementation in an adapter layer, then preflight again. Never mechanical-safe \u2014 port shape is a design decision."),I("RAW_EVENT_PUBLISH","publish","Raw event publish","Publish went through a raw string or object instead of a registered intent creator, bypassing Ark intent contracts and tooling.","Publish through a registered intent creator, then run Ark again."),I("PUBLISH_MISSING_SOURCE","publish","Publish missing metadata.source","A strict Ark publish call omitted metadata.source, so the publishing layer cannot be verified.","Add metadata.source to the publish call, then run Ark again."),I("PUBLISH_SOURCE_LAYER_MISMATCH","publish","Publish source layer mismatch","metadata.source resolves to a different layer than the file performing the publish.","Use a source intent owned by the same layer as this file, or move the publish call to the owning layer."),I("UNKNOWN_INTENT","publish","Unknown intent reference","Snippet analysis saw an intent string that is not registered in the intent registry / profile under check.","Register the intent or use a known intent name from the project registry, then re-run the gate."),I("DYNAMIC_IMPORT_NOT_ALLOWLISTED","safety","Non-literal dynamic import","A dynamic import(expr) cannot be resolved statically and the file is not on dynamicImportAllowlist. Unresolved dynamics can hide layer edges.","Rewrite to a static import when possible, or add only reviewed files to dynamicImportAllowlist after human sign-off."),I("DYNAMIC_REQUIRE_NOT_ALLOWLISTED","safety","Non-literal require","A require(expr) cannot be resolved statically and is not allowlisted \u2014 same hide-the-edge risk as dynamic import.","Prefer static import, or allowlist only reviewed files after sign-off."),I("TS_SUPPRESSION_THRESHOLD_EXCEEDED","safety","@ts-ignore / @ts-nocheck threshold","Count of TypeScript suppressions in governed production source exceeds safety.maxTsSuppressions.","Remove suppressions by fixing types, or raise the threshold only with an explicit production exception in ark.config.json."),I("ANY_CAST_THRESHOLD_EXCEEDED","safety","Explicit any cast threshold","Count of explicit any casts exceeds safety.maxAnyCasts.","Replace any with precise types, or raise the threshold only with a documented exception."),I("IN_MEMORY_STORE_IN_PRODUCTION_SOURCE","safety","In-memory store in production source","Governed production source references an Ark InMemory* store without safety.allowInMemory \u2014 durable systems should not ship ephemeral stores by accident.","Provide a durable store implementation, or set safety.allowInMemory only for an explicitly ephemeral service."),I("PEER_ISOLATION_DISABLED","safety","peerIsolation disabled on a rule","A same-layer or peer rule disables peerIsolation (or omits it where required), which allows cross-slice coupling the contract otherwise blocks.","Restore peerIsolation: true, or set safety.allowDisabledPeerIsolation only with a documented production exception."),I("ARKRULE_STRUCTURE","arkrules","ArkRule structure sensor failed","An opt-in ArkRules structure sensor (private state, factory shape, event publish, persistence write outside an aggregate, \u2026) failed on a governed file for a declared arkruleId.","Restore the declared structure for the ArkRule (see arkruleSource), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement."),I("ARKRULE_INVARIANT","arkrules","ArkRule invariant failed","Reserved / remediation-recognized code for invariant-plane failures bound to an ArkRule id (coverage path also emits INVARIANT_UNCOVERED).","Fix the invariant for the ArkRule declared in arkrules/<Layer>.json, then preflight again. Do not demote without acknowledgement."),I("ARKRULE_SCOPE_EMPTY","arkrules","ArkRule appliesTo matched zero files","An ArkRule\u2019s appliesTo globs matched no governed files \u2014 the rule cannot observe what it claims to protect.","Fix appliesTo globs so they match governed files, or remove the rule. Enforced empty scope fails; advisory empty scope warns.",{oftenAdvisory:!0}),I("ARKRULE_HINT_BUDGET_EXHAUSTED","arkrules","Structural-hint budget exhausted","orchestration-only, thin-adapter, and writes-via-aggregate only evaluate files the hint loader preloaded. When eligible governed files exceed that budget (coverage.maxFiles, default 400 \u2014 there is no arkrules.hintBudget), those sensors never saw the rest of their scope. Enforced + unreviewed is not green. The finding names exact hinted/governed counts and per-sensor reviewed N/M of scope.","Raise coverage.maxFiles in ark.config.json (this cap also bounds structural-hint preload; --doctor names the coupling) so hinted/governed counts match, then re-run with --strict-config. An enforced hint sensor that cannot see its scope fails strict."),I("INVARIANT_CATALOG_EMPTY","arkrules","Domain invariant catalog is empty","ArkRules is on and a Domain-role layer has code, but invariants[] has no phrases the code must preserve. Empty looks like \u201Cdone\u201D until someone fills the catalog.","Add 1\u20132 short phrases to invariants[] in arkrules/<Domain>.json (or the mapped file). Starters show the shape. Advisory unless a domain structure rule is already enforced \u2014 then --strict-merge can refuse. Do not freeze this finding.",{oftenAdvisory:!0}),I("INVARIANT_UNCOVERED","arkrules","Invariant without coverage evidence","An ArkRules invariant is under contract but no covering test title or declared symbol evidence was found (or coverage is partial). Kind is never-had-tests (adopt residual) vs tests-disappeared (suite exists).","Add a test title or declared symbol covering the arkruleId, then preflight again. Treat never-had-tests as adopt residual; treat tests-disappeared as a regression. Missing test globs report partial \u2014 never fake green. When the message reports an exhausted file budget, raise coverage.maxFiles (or narrow coverage.testGlobs) in ark.config.json."),I("INVARIANT_COVERAGE_OUTSIDE_ROOTS","arkrules","Covering test outside the declared coverage roots","The only test naming this invariant sits outside coverage.coverageRoots \u2014 the places the project declares its runner executes. ArkGate matches declared text and never executes tests, so it cannot tell whether that file is ever run: coverage there is a test that exists, not a test that runs.","Move the test under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json. Advisory: it never fails strict, but promotion to enforced refuses on it.",{oftenAdvisory:!0}),I("INVARIANT_TESTS_PATH_MISSING","arkrules","Domain-invariant tests path missing under adopted","The project is adopted (required CI or explicit advisory) and has domain invariants that want test evidence, but ark.config.json does not name where those tests live. Green coverage without a real tests path is an empty checkbox.","Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present. Not freezable."),I("INVARIANT_COVERAGE_ROOTS_MISSING","arkrules","Coverage roots missing while an invariant is enforced","A catalogued domain invariant is enforced, but ark.config.json does not name coverage.coverageRoots \u2014 the folders where the project says its test runner actually goes. Without that declaration, INVARIANT_COVERAGE_OUTSIDE_ROOTS cannot fire and coverage can certify a test no runner runs.","Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. testGlobs alone is not enough. Fail-closed until that path is present. Not freezable."),I("ARKRUN_MISSING_ROOT","arkrun","No kernel factory in composition roots","The ArkRun extra is on but no createArkKernel / createStrictArkKernel / createArkKernelFromConfig / createStrictArkKernelFromConfig factory was found in arkRun.compositionRoots, so agents can skip the kernel while the write gate stays green.","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."),I("ARKRUN_KERNEL_IN_DOMAIN","arkrun","Domain-role layer imports the kernel","A Domain-role layer imports arkgate/runtime, @arkgate/runtime, or kernel types. Domain stays kernel-free; composition roots and adapters own the factory.","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."),I("ARKRUN_DIRECT_NEW","arkrun","Managed type constructed with new","A managed non-Domain file constructs an admitted type with new outside an ArkRun composition-root factory, skipping kernel resolve/registration.","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."),I("ARKRUN_UNDECLARED_EMIT","arkrun","Emit name not in raises/sends","A publisher / publish / raise / send call-site literal is not listed in the file\u2019s raises or sends declaration.","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."),I("ARKRUN_UNDECLARED_HANDLE","arkrun","Handle name not in reactsTo","A subscribe / registerHandler call-site literal is not listed in the file\u2019s reactsTo declaration.","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."),I("ARKRUN_UNDECLARED_DEPEND","arkrun","Depend name not in uses","A resolve / resolveSingleton call-site literal is not listed in the file\u2019s uses declaration.","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."),I("ARKRUN_TRANSPORT_BYPASS","arkrun","Homemade broker or emitter import","A managed layer imports a closed broker/queue/emitter specifier (EventEmitter, queue clients, \u2026) instead of the ArkRun kernel transport.","Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe \u2014 homemade buses stay judgment."),I("ARKORDER_MISSING_PLANE","arkorder","No createOrderPlane in plane roots","The ArkOrder extra is on but no createOrderPlane factory was found in arkOrder.planeRoots, so agents can skip the pattern plane while the write gate stays green.","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."),I("ARKORDER_KERNEL_IN_DOMAIN","arkorder","Domain-role layer imports the order plane","A Domain-role layer imports arkgate/order. Domain stays plane-free; planeRoots own the factory.","Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe."),I("ARKORDER_GENERIC_UPDATE","arkorder","Generic update of a big product choice","A call to update/patch/set rewrites a named product choice (like billing plan) as if it were a seat count.","Don't use a generic update. First freeze with release(). Later, propose the change, then apply it."),I("ARKORDER_TOO_MANY_PARAMS","arkorder","Too many slow keys","\u03BE has more keys than arkOrder.maxXiKeys. Haken requires a few slow modes, not a dump of microstate.","Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe."),I("ARKORDER_INGEST_WRITES_XI","arkorder","ingest assigned into \u03BE","An ingest() result is written into a Release or \u03BE store. ingest may absorb, escalate_up, or hold; it never mints a pattern.","Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe."),I("ARKORDER_XI_FIELD_WRITE","arkorder","Big product choice written like a seat count","A use-case writes a named product choice (like billing plan) through a database update. Invoices and seats can flow. That choice cannot.","Keep invoices and seats as events. Change the choice through the valve (proposeRelease then apply), not a generic update."),I("ARKORDER_INFORMATION_BUDGET","arkorder","Projection observes a forbidden kind","h(\u03BE) allowedKinds includes a kind listed in informationBudget.cannotObserve. A scale may not look at what it was told not to see.","Cut that kind from the projector or from cannotObserve, then preflight again. Never mechanical-safe."),I("ARKORDER_XI_TTL","arkorder","Slow key carries a freshness field","\u03BE named ttl/freshUntil/maxAge. Freshness belongs on \u03C3. A slow parameter that expires per transaction is not slow.","Move freshness onto \u03C3 (freshUntil) and keep \u03BE stable, then preflight again. Never mechanical-safe."),I("ARKORDER_STALE_SIGMA","arkorder","\u03C3 is stale","ingest ran after \u03C3.freshUntil (or sigmaMaxAgeMs). \u03BE does not TTL.","Call refreshSigma and ingest again, or proposeRelease then apply(ProposeResult) if the pattern changed. Never mechanical-safe."),I("ARKORDER_UNVALVED_RELEASE","arkorder","Second freeze without the valve","release() already froze the big choice. A later release() with a different value does not land. First freeze is release(); later change is proposeRelease then apply.","Change the choice with proposeRelease then apply. release() is only the first freeze. Never mechanical-safe."),I("INVALID_CHANGE_PATH","preflight","Unsafe change path","A change set entry is not a safe, non-empty project-relative path (absolute, escape, empty, or NUL).","Use canonical project-relative paths only in the atomic change set, then preflight again."),I("DUPLICATE_CHANGE_PATH","preflight","Duplicate path in change set","The atomic change set lists more than one operation for the same path.","Collapse to one create/update/delete per path, then preflight again."),I("DELETE_TARGET_MISSING","preflight","Delete target missing","A delete operation targets a path that is not present in the supplied base tree.","Remove the delete, or include the file in the base tree facts, then preflight again."),I("CHANGE_SET_EMPTY","preflight","Empty change set","Atomic preflight was invoked with no create, update, or delete operations.","Provide at least one change operation, then preflight again."),I("FACTS_IDENTITY_MISMATCH","preflight","Base/candidate facts identity mismatch","Base and candidate resolved facts disagree on resolver, compiler, evidence requirements, or package identity \u2014 verdicts would not be comparable.","Regenerate both fact snapshots with the same resolver/compiler/evidence requirements, then preflight again."),I("CANDIDATE_DELETE_NOT_APPLIED","preflight","Candidate still contains deleted path","Facts claim a delete, but the candidate tree still includes the path.","Ensure the candidate facts apply the delete (path absent), then preflight again."),I("CANDIDATE_CHANGE_MISSING","preflight","Declared change missing from candidate","The change set declares a create/update whose path is missing from candidate facts.","Include the new content in the candidate facts (or drop the operation), then preflight again."),I("CANDIDATE_CONTENT_HASH_MISMATCH","preflight","Candidate content hash mismatch","The candidate file content hash does not match the hash expected for the declared change.","Rebuild candidate facts from the exact proposed content, then preflight again."),I("UNDECLARED_CANDIDATE_CHANGE","preflight","Undeclared candidate change","Candidate facts differ from base for a path that was not listed in the explicit change set.","Declare every path that changes in the atomic change set, then preflight again."),I("ATOMIC_PREFLIGHT_UNAVAILABLE","preflight","Atomic preflight unavailable","The host/MCP path could not run the atomic preflight engine (missing facts, incomplete setup, or unsupported mode).","Use resolved-candidate facts / ark_prepare_change with a complete batch, or fall back to ark-check on disk. Do not treat missing preflight as green."),I("DESIGN_SMELL_REGRESSION","preflight","Design smell regression on base-relative ratchet","Compared to the base ref, the candidate introduces a created-path domain-logic-in-ui file under --strict-merge, or introduces or worsens a blocking design-smell class under --fail-on-new-smells.","Move the new UI business rule out of the created file (or revert a --fail-on-new-smells regression), then re-run with the same base ref."),I("ANALYSIS_PARSE_INCOMPLETE","analysis","Parse incomplete","Governed source could not be fully parsed; evidence includes the TypeScript diagnostic (line + message). Incremental mid-edit parse is normal for agents. Contract exclude paths skip the write hook.","Finish the source or fix the reported syntax error, then re-run `npx arkgate-check`. The write hook does not deny solely on mid-edit parse. Partial never means pass."),I("LEXICAL_EVIDENCE_INCOMPLETE","analysis","Lexical evidence incomplete","This check only saw one file, so it cannot fully prove how the import resolves. The result is provisional \u2014 `ark-check` on the project is the authority.","Run `npx arkgate-check --root . --config ark.config.json` to confirm. Do not call ark_prepare_change from a hook deny."),I("ANALYSIS_COVERS_NO_FILES","analysis","Analysis covered no files","No file matched the contract include and layer patterns under the analyzed root, so the run had nothing to check. Every rule is vacuously satisfied on an empty set: a green here would read exactly like a green over a governed tree while certifying nothing. Usual causes are a --root that is not the tree the contract describes (including a contract found outside the requested root, whose directory is then adopted as the project root), include / exclude patterns that match nothing, or layer patterns written for a different layout.","Point --root at the tree the contract describes, or keep the contract inside that tree, or fix the include / exclude / layer patterns so they match real files \u2014 then re-run `npx arkgate-check --root . --config ark.config.json`. This is a refusal about ArkGate\u2019s own inputs, not a finding about your code; no baseline or policy acknowledgement can suppress it."),I("ANALYSIS_HOST_UNAVAILABLE","analysis","Analysis host unavailable","No usable TypeScript / analysis host was available for this invocation.","Install a supported TypeScript version visible to the project, then re-run. Unavailable analysis is fail-closed."),I("ADAPTER_NOT_ALLOWED_FOR_PORT","adapter","Adapter not allowed for port","Runtime/port wiring selected an adapter implementation that the architecture profile does not allow for that port.","Bind an allowed adapter for the port, or adjust the profile with an explicit policy decision \u2014 then re-run."),I("FORBIDDEN_PATTERN","snippet-policy","Forbidden regex pattern","Snippet content matched a project or profile forbiddenPatterns rule.","Remove or rewrite the matching code so the pattern no longer matches, then re-run the snippet gate."),I("FORBIDDEN_SUBSTRING","snippet-policy","Forbidden substring","Snippet content contained a forbidden substring from the AI gate options/profile.","Remove the forbidden substring, then re-run the snippet gate."),I("FORBIDDEN_IMPORT","snippet-policy","Forbidden import target","Snippet imported or required a module listed as forbidden for the active profile.","Import an allowed module or inject the dependency behind a port, then re-run."),I("POLICY_VIOLATION","snippet-policy","Policy engine violation","A registered Policy failed on the snippet or generated code under evaluation.","Adjust the code to satisfy the named policy, or change the policy only through an explicit contract decision."),I("EXTENSION_ERROR","snippet-policy","AI gate extension error","A registered AICodeGate extension threw while analyzing the snippet.","Fix or remove the failing extension; do not ignore extension failures as pass."),I("AST_ANALYZER_ERROR","snippet-policy","AST analyzer error","Built-in AST/symbol analysis failed (host error or unexpected analyzer exception).","Ensure TypeScript host and snippet are valid; re-run. If the analyzer crashes on valid input, file a bug with a minimal fixture."),I("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","config","Invalid dynamicImportAllowlist","dynamicImportAllowlist is present but not an array of file globs.","Set dynamicImportAllowlist to an array of project-relative globs (or omit it).",{oftenAdvisory:!0}),I("CONFIG_INVALID_SAFETY","config","Invalid safety object","The safety field is present but not an object.","Use a safety object with optional maxTsSuppressions, maxAnyCasts, allowInMemory, allowDisabledPeerIsolation.",{oftenAdvisory:!0}),I("CONFIG_INVALID_SAFETY_THRESHOLD","config","Invalid safety threshold","A safety threshold (maxTsSuppressions / maxAnyCasts) is not a non-negative integer.","Set each threshold to a non-negative integer.",{oftenAdvisory:!0}),I("CONFIG_NO_LAYERS","config","No layers configured","ark.config.json has no file layers, so import-boundary enforcement cannot classify files.","Declare at least one layer with name + patterns (or run ark start / a preset).",{oftenAdvisory:!0}),I("CONFIG_LAYER_WITHOUT_NAME","config","Layer missing name","A configured layer entry has no name.","Give every layer a unique non-empty name.",{oftenAdvisory:!0}),I("CONFIG_INVALID_FORBIDDEN_GLOBALS","config","Invalid forbiddenGlobals","A layer\u2019s forbiddenGlobals is not an array of strings; the entry is ignored.",'Use an array of strings (e.g. ["fetch", "Date.now"]).',{oftenAdvisory:!0}),I("CONFIG_LAYER_WITHOUT_PATTERNS","config","Layer without patterns","A named layer has no file patterns and will never classify files.","Add patterns globs that match the layer\u2019s source tree.",{oftenAdvisory:!0}),I("CONFIG_INVALID_LAYER_PATTERN","config","Invalid layer pattern","A layer pattern is not a valid glob / failed to compile.","Fix the pattern syntax for that layer.",{oftenAdvisory:!0}),I("CONFIG_LAYER_PATTERN_NO_MATCHES","config","Layer pattern matched no files","A layer pattern matched zero included files (often a typo or include mismatch). Reserved/allowEmpty houses do not emit this.","Adjust the pattern or include roots, or mark the layer reserved/allowEmpty if the glob is a future house.",{oftenAdvisory:!0}),I("CONFIG_DUPLICATE_LAYER","config","Duplicate layer name","The same layer name appears more than once in configuration.","Rename or merge duplicate layer entries.",{oftenAdvisory:!0}),I("CONFIG_RULE_UNKNOWN_FROM_LAYER","config","Rule unknown from layer","A dependency rule references a source layer name that is not declared.","Fix the rule\u2019s from field to a declared layer name.",{oftenAdvisory:!0}),I("CONFIG_RULE_UNKNOWN_TO_LAYER","config","Rule unknown to layer","A dependency rule references a target layer name that is not declared.","Fix the rule\u2019s to field to a declared layer name.",{oftenAdvisory:!0}),I("CONFIG_AMBIGUOUS_LAYERS","config","Ambiguous layer classification","Some files match multiple layers at equal specificity; classification falls back to declaration order.","Disambiguate overlapping patterns so each file has one clear layer owner.",{oftenAdvisory:!0}),I("CONFIG_UNCLASSIFIED_FILES","config","Unclassified included files","Included source files match no layer pattern; import rules will not enforce on them.","Extend layer patterns or narrow include so every governed file is classified.",{oftenAdvisory:!0}),I("CONFIG_LAYER_MISSING_OWNER","config","Layer missing owner","requireLayerOwners is on and this layer has no owners. Writes to that house fail closed, like a folder with no name on the door.","Add a GitHub handle or email to that layer\u2019s owners in ark.config.json (/ark-adopt), then re-run. Reserved/allowEmpty houses may stay unnamed. Turn the flag off only if you no longer want owners required."),I("CONFIG_SLICE_IDENTITY_COLLISION","config","Starred slice prefixes share one id","sliceIdentity is stars and two different sliceFolders prefixes bind as the same slice id. Parallel trees of one feature do that on purpose; unrelated trees that share the last folder name merge by accident.","Keep stars when those prefixes are one feature. Otherwise use path, or rename the last literal so the prefixes do not bind as the same id. Doctor names both paths.",{oftenAdvisory:!0}),I("LITERAL_PATH_DRIFT","drift","Literal path moved by a rename","A repo path written inside a string, a comment or a docstring no longer resolves, and the rename set says where it went. Nothing in the gate sees this class: `tsc` resolves imports, not strings, and ESLint does not either, so the rename compiles green and the reference lies afterwards. It appears in four forms \u2014 the tsconfig alias, a relative literal, a path written without the include-root prefix, and prose \u2014 and a hand sweep reliably covers one of them.","Apply the suggested replacement, or re-run `npx arkgate-check --path-drift --base-ref <ref> --write` to apply every writable anchored replacement at once. The rewrite is mechanical and one-directional: the destination comes from the rename, it must itself resolve and be path-shaped, and the token is rewritten in the form the author wrote it in. A destination that leaves the alias root of the literal is reported with the target only and must be rewritten by hand."),I("LITERAL_PATH_UNRESOLVED","drift","Literal path does not resolve","A literal that looks like a repo path does not resolve under this root, and no rename explains where it went. Unlike LITERAL_PATH_DRIFT this is a candidate, not a verdict: with nothing to anchor it, ArkGate cannot tell a dead reference from an illustrative path in a comment, an example in documentation, or a path belonging to another tree.","Read the candidate and decide: fix the path, or leave it. Advisory only \u2014 it never fails a run and is never rewritten by --write, because there is no destination to propose. Run `--path-drift --all` to list the sweep.",{oftenAdvisory:!0}),I("ARK_UNKNOWN","meta","Unknown diagnostic","A diagnostic lacked a stable ruleId/code; adapters may emit this fallback so agents never see an empty id.","Resolve the underlying finding without weakening ark.config.json, then run Ark again. Prefer fixing the producer to emit a catalogued ruleId.")]),co=new Map(Zn.map(e=>[e.ruleId,e])),Nd=Object.freeze(Zn.map(e=>e.ruleId));function Dd(e){return typeof e=="string"&&e.length>0&&co.has(e)}i(Dd,"isKnownDiagnosticCode");function Ld(e){return typeof e!="string"||e.length===0?!1:co.has(e)?!0:e.startsWith("ARKRULE_")}i(Ld,"isCataloguedOrArkRuleFamily");function Jn(e){if(!(typeof e!="string"||e.length===0))return co.get(e)}i(Jn,"getDiagnosticCatalogEntry");function oa(e){return`#${Jn(e)?.docsAnchor??e}`}i(oa,"diagnosticDocsFragment");function Fd(e){return`${lo}${oa(e)}`}i(Fd,"diagnosticDocsPath");function $d(){return{schemaVersion:"1.0",docsPath:lo,codes:Zn}}i($d,"serializeDiagnosticCatalog");function Md(e){return Jn(e)?.fix}i(Md,"catalogFixForRuleId");function Hd(e){return Jn(e)?.why}i(Hd,"catalogWhyForRuleId");var Kd="1.1";var Gd="1.0";var Wt=class{static{i(this,"InMemoryReadModelStore")}states=new Map;load(t){return this.states.get(t)}save(t,n){this.states.set(t,n)}clear(t){t?this.states.delete(t):this.states.clear()}};function Ud(e){return typeof e.initialState=="function"?e.initialState():e.initialState}i(Ud,"initialState");var Qn=class{static{i(this,"ProjectionRegistryImpl")}definitions=new Map;checkpoints=new Map;store;auditTrail;constructor(t={}){this.store=t.store??new Wt,this.auditTrail=t.auditTrail}register(t){if(this.definitions.has(t.name))throw new Error(`Projection "${t.name}" is already registered.`);this.definitions.set(t.name,t),this.checkpoints.set(t.name,{projection:t.name,appliedCount:0})}list(){return Array.from(this.definitions.values())}async apply(t){let n=[];for(let r of this.definitions.values()){if(!r.sourceIntents.includes(t.intent))continue;let o=await this.store.load(r.name)??Ud(r),s=await r.project(t,o);await this.store.save(r.name,s);let a=this.checkpoints.get(r.name);this.checkpoints.set(r.name,{projection:r.name,appliedCount:(a?.appliedCount??0)+1,lastIntent:t.intent,lastCorrelationId:t.metadata.correlationId,updatedAt:new Date().toISOString()}),await this.auditTrail?.record({type:"projection.applied",source:"Kernel.ProjectionRegistry",intent:t.intent,correlationId:t.metadata.correlationId,causationId:t.metadata.causationId,subject:r.name,details:{projection:r.name}}),n.push(r.name)}return n}async getState(t){return this.store.load(t)}getCheckpoint(t){return this.checkpoints.get(t)}getCheckpoints(){return Array.from(this.checkpoints.values())}async clear(){await this.store.clear();for(let t of this.definitions.values())this.checkpoints.set(t.name,{projection:t.name,appliedCount:0})}};function er(e){return new Qn(e)}i(er,"createProjectionRegistry");var tr="1.0";function Vd(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}i(Vd,"policyId");var uo=class{constructor(t){this.data=t}data;static{i(this,"ArkManifestImpl")}toJSON(){return{...this.data}}};function nr(e={}){let t=e.registry,n=e.policyEngine,r=e.metadata,o=e.graph,s=e.profile,a=e.projections,l=e.eventContracts,c=e.observability,u=t?t.list().map(S=>({name:S.name,dependencies:t.getDependencies(S.name),productions:t.getProductions(S.name)})):[],f=t?t.getAllRelationships():[],y=n?n.getPolicies().map(S=>({id:Vd(S.name),name:S.name,severity:S.severity,tags:S.tags?[...S.tags]:void 0,owner:S.owner,version:S.version,rationale:S.rationale,enforcementMode:S.enforcementMode,deprecated:S.deprecated,replacedBy:S.replacedBy,description:S.tags?.includes("layer")?"Enforces clean-architecture layer dependency rules on declared relationships.":void 0})):[],p=r?r.toJSON():[],g=o?o.toJSON():{nodes:[],edges:[]},d=p.filter(S=>(S.emits?.length??0)>0||(S.consumes?.length??0)>0).map(S=>({entity:S.name,emits:S.emits,consumes:S.consumes})),m=a?a.list().map(S=>({name:S.name,sourceIntents:S.sourceIntents,checkpoint:a.getCheckpoint(S.name)})):[],E={schemaVersion:"1.0",version:yr,exportedAt:new Date().toISOString(),intents:u,relationships:f,policies:y,entities:p,graph:g,architecture:s?{profile:s.name,layers:s.layers,rules:s.rules}:void 0,projections:m,eventContracts:l?.list()??[],observability:c?.report(),links:{entityIntents:d}};return new uo(E)}i(nr,"createArkManifest");var sa=0;function ia(e){return sa+=1,`${e}-${Date.now()}-${sa}`}i(ia,"createWorkflowId");function po(e){return e instanceof Error?e.message:String(e)}i(po,"errorMessage");function jd(e){return new Promise(t=>{setTimeout(t,e)})}i(jd,"sleep");async function Bd(e,t,n){let r=new AbortController;if(t===void 0)return e(r.signal);let o,s=new Promise((a,l)=>{o=setTimeout(()=>{let c=new Error(`Workflow step "${n}" timed out after ${t}ms.`);r.abort(c),l(c)},t)});try{return await Promise.race([e(r.signal),s])}finally{o&&clearTimeout(o)}}i(Bd,"withTimeout");var zt=class{static{i(this,"InMemoryWorkflowStore")}snapshots=new Map;save(t,n){let r=this.snapshots.get(t.id);if(r&&r.version!==t.version)throw new Error(`Optimistic concurrency conflict for workflow ${t.id}`);let o=(t.version??0)+1;this.snapshots.set(t.id,{...t,version:o,context:{...t.context}}),t.version=o}get(t,n){let r=this.snapshots.get(t);return r?{...r,context:{...r.context}}:void 0}list(t){return Array.from(this.snapshots.values()).filter(n=>!t||n.workflowName===t).map(n=>({...n,context:{...n.context}}))}claim(t,n,r){let o=Date.now();for(let s of this.snapshots.values()){if(r&&s.workflowName!==r||s.status!=="running"&&s.status!=="compensating")continue;let a=s.expiresAt?new Date(s.expiresAt).getTime()<o:!0;if(!s.ownerId||a){s.ownerId=t,s.expiresAt=new Date(o+n).toISOString();let l=(s.version??0)+1;return s.version=l,this.snapshots.set(s.id,{...s,context:{...s.context}}),{...s,context:{...s.context}}}}}clear(){this.snapshots.clear()}},fo=class{constructor(t,n={}){this.bus=t;this.options=n;this.store=n.store??new zt}bus;options;static{i(this,"WorkflowEngineImpl")}definitions=new Map;store;register(t){if(this.definitions.has(t.name))throw new Error(`Workflow "${t.name}" is already registered.`);let n=new Set;for(let r of t.steps){if(n.has(r.name))throw new Error(`Workflow "${t.name}" has duplicate step name "${r.name}".`);n.add(r.name)}if(this.definitions.set(t.name,t),t.startOn){let r=t.startOn;this.bus.subscribe(r.intent,async o=>{await this.start(t.name,r.mapEventToPayload(o))})}}async start(t,n,r={}){let o=this.definitions.get(t);if(!o)throw new Error(`Workflow "${t}" is not registered.`);let s=new Date().toISOString(),a={id:r.id??ia(t),version:0,workflowName:t,status:"running",context:{...n},completedSteps:[],attempts:{},startedAt:s,updatedAt:s};return await this.store.save(a,r.tx),await this.audit("workflow.started",a,{workflowName:t}),this.executeSnapshot(a,o,r.tx)}async resume(t,n={}){let r=await this.get(t,n.tx);if(!r)return;if(r.status!=="running"&&r.status!=="compensating")return r;let o=this.definitions.get(r.workflowName);if(!o)throw new Error(`Workflow "${r.workflowName}" is not registered.`);return this.executeSnapshot(r,o,n.tx)}async executeSnapshot(t,n,r){try{let o=n.steps.filter(s=>!t.completedSteps.includes(s.name));for(let s of o)await this.runStep(t,s,r);return t.status="completed",t.currentStep=void 0,t.completedAt=new Date().toISOString(),t.updatedAt=t.completedAt,await this.store.save(t,r),await this.audit("workflow.completed",t,{workflowName:t.workflowName}),{...t,context:{...t.context}}}catch(o){throw await this.compensate(t,n.steps,o,r),t.status="failed",t.currentStep=void 0,t.error=po(o),t.updatedAt=new Date().toISOString(),await this.store.save(t,r),await this.audit("workflow.failed",t,{workflowName:t.workflowName,error:t.error,failedStep:t.failedStep}),o}}async get(t,n){return this.store.get(t,n)}async list(t){return this.store.list(t)}async runStep(t,n,r){let o=n.retry??this.options.defaultRetry??{attempts:1},s=Math.max(1,o.attempts);t.currentStep=n.name,t.updatedAt=new Date().toISOString(),await this.store.save(t,r);for(let a=1;a<=s;a+=1){t.attempts[n.name]=a,await this.store.save(t,r);let l;try{l=await Bd(c=>Promise.resolve(n.execute(t.context,this.bus,c)),n.timeoutMs,n.name)}catch(c){if(a<s){o.delayMs&&await jd(o.delayMs);continue}throw t.failedStep=n.name,t.updatedAt=new Date().toISOString(),await this.store.save(t,r),await this.audit("workflow.step.failed",t,{step:n.name,attempt:a,error:po(c)}),c}l&&Object.assign(t.context,l),t.completedSteps.push(n.name),t.currentStep=void 0,t.updatedAt=new Date().toISOString(),await this.store.save(t,r),await this.audit("workflow.step.completed",t,{step:n.name,attempt:a});return}throw new Error(`Workflow step "${n.name}" did not complete.`)}async compensate(t,n,r,o){t.status="compensating",t.updatedAt=new Date().toISOString(),await this.store.save(t,o);let s=n.filter(a=>t.completedSteps.includes(a.name));for(let a=s.length-1;a>=0;a-=1){let l=s[a];if(l.compensate)try{await Promise.resolve(l.compensate(t.context,this.bus,r)),await this.audit("workflow.compensation.completed",t,{step:l.name})}catch(c){await this.audit("workflow.step.failed",t,{step:l.name,compensation:!0,error:po(c)})}}}async audit(t,n,r){await this.options.auditTrail?.record({type:t,source:"Kernel.WorkflowEngine",subject:n.id,details:r})}};function qt(e,t){return new fo(e,t)}i(qt,"createWorkflowEngine");function aa(e,t,n={}){let r=qt(t,n),o={name:e.name,steps:e.steps};r.register(o);let s=n.id??ia(e.name),a="idle",l=[];return{id:s,definition:e,get status(){return a},get completedSteps(){return[...l]},async run(c){a="running",l=[];try{let u=await r.start(e.name,c,{id:s});a=u.status==="waiting"?"idle":u.status,l=[...u.completedSteps]}catch(u){let f=await r.get(s);throw a=f?.status==="waiting"?"idle":f?.status??"failed",l=f?.completedSteps??[],u}}}}i(aa,"createSaga");ht();function ua(e){return Object.keys(e).sort()}i(ua,"sortedKeys");function Ro(e,t,n,r){if(e===t)return;if(e===null||t===null||typeof e!=typeof t){r.push({path:n,left:e,right:t});return}if(typeof e!="object"||typeof t!="object"){e!==t&&r.push({path:n,left:e,right:t});return}if(Array.isArray(e)||Array.isArray(t)){let l=Array.isArray(e)?e:[],c=Array.isArray(t)?t:[],u=Math.max(l.length,c.length);for(let f=0;f<u;f+=1)Ro(l[f],c[f],`${n}[${f}]`,r);return}let o=e,s=t,a=new Set([...ua(o),...ua(s)]);for(let l of[...a].sort())Ro(o[l],s[l],n?`${n}.${l}`:l,r)}i(Ro,"walk");function pa(e){return{schemaVersion:e.schemaVersion,kernelInstanceId:e.kernelInstanceId,components:e.components.map(t=>({id:t.id,lifetime:t.lifetime,uses:[...t.uses],reactsTo:[...t.reactsTo],raises:[...t.raises],sends:[...t.sends],...t.extendedInfo?{extendedInfo:{...t.extendedInfo}}:{}})),...e.decisionTape?{decisionTape:e.decisionTape.map(t=>({xiHash:t.xiHash,event:{kind:t.event.kind,...t.event.payload?{payload:{...t.event.payload}}:{}},residual:{...t.residual}}))}:{}}}i(pa,"shadowInformationPackage");function Ao(e,t){let n=[];return Ro(e,t,"",n),{equal:n.length===0,diffs:n}}i(Ao,"compareInformationPackages");function fa(e){let t=[];for(let n=1;n<e.length;n+=1)t.push(Ao(e[n-1],e[n]));return t}i(fa,"replayInformationPackages");cr();tn();un();un();async function mr(e,t={}){let n=ln({host:t.host,port:t.port,nodeEnv:t.nodeEnv,processNodeEnv:process.env.NODE_ENV}),{listenArkRunInspector:r}=await Promise.resolve().then(()=>(Ca(),wa));return r(e,{bind:n,sseIntervalMs:t.sseIntervalMs})}i(mr,"startArkRunInspector");cr();un();ht();tn();ht();var Ou=new Set(["singleton","transient"]);function xa(e){let t={id:e.id,lifetime:e.lifetime,uses:[...e.uses],reactsTo:[...e.reactsTo],raises:[...e.raises],sends:[...e.sends]};if(e.extendedInfo){let n=e.extendedInfo;t.extendedInfo={...n.label?{label:n.label}:{},...n.architectureKind?{architectureKind:n.architectureKind}:{},...n.tags?{tags:[...n.tags]}:{},...n.group?{group:n.group}:{},...n.metadata?{metadata:{...n.metadata}}:{}}}return t}i(xa,"cloneComponent");function Pu(e){if(e===void 0)return"singleton";if(typeof e=="string"&&Ou.has(e))return e;throw new Error('ArkRun component lifetime must be "singleton" or "transient".')}i(Pu,"closedLifetime");function Oa(){let e=new Map,t=new Map,n=new Set;function r(a){let l=e.get(a);if(!l)throw new Error(`ArkRun component "${a}" is not registered.`);return l}i(r,"mustRecord");function o(a,l){if(!l.factory)throw new Error(`ArkRun component "${a}" has no factory; declarations-only registrations cannot be resolved.`);if(n.has(a))throw new Error(`ArkRun component "${a}" has a circular resolve.`);n.add(a);try{return l.factory()}finally{n.delete(a)}}i(o,"instantiate");function s(a,l){if(t.has(a))return t.get(a);let c=o(a,l);return t.set(a,c),c}return i(s,"singleton"),{register(a){let l=typeof a?.id=="string"?a.id.trim():"";if(!l)throw new Error("ArkRun component id must be a non-empty string.");if(e.has(l))throw new Error(`ArkRun component "${l}" is already registered.`);let c=Pu(a.lifetime),u=yo({id:l,lifetime:c,uses:a.uses,reactsTo:a.reactsTo,raises:a.raises,sends:a.sends,extendedInfo:a.extendedInfo});if(!u)throw new Error("ArkRun component id must be a non-empty string.");let f=typeof a.factory=="function"?a.factory:void 0;return e.set(l,{component:u,factory:f}),xa(u)},resolve(a){let l=r(a);return l.component.lifetime==="transient"?o(a,l):s(a,l)},resolveSingleton(a){let l=r(a);if(l.component.lifetime==="transient")throw new Error(`ArkRun component "${a}" is transient; resolveSingleton requires lifetime "singleton".`);return s(a,l)},snapshotComponents(){return[...e.values()].map(a=>xa(a.component))}}}i(Oa,"createComponentRegistry");tn();function _u(e){let t={...e.metadata??{}};if(e.source===void 0)return t;if(t.source&&t.source!==e.source)throw new Ce(e.source,t.source);return t.source=e.source,t}i(_u,"stampMetadata");function Tu(){}i(Tu,"ignoreDetachedFailure");async function To(e,t,n,r={}){let o=dr({transport:r.transport,ephemeral:r.ephemeral??e.defaultEphemeral,brokerBound:typeof e.broker?.send=="function"}),s=_u(r),a=await e.eventBus.dispatch(t,n,s,{notifySubscribers:o.notifySubscribers,awaitHandlers:o.awaitHandlers});if(o.deliveredVia==="broker"&&e.broker){let l=Promise.resolve(e.broker.send(a));o.awaitHandoff?await l:l.then(void 0,Tu)}return o}i(To,"sendOnArkRunTransport");var No=1e3,Pa=0;function Nu(){return Pa+=1,`ark-kernel-${Date.now()}-${Pa}`}i(Nu,"nextKernelInstanceId");function _a(e,t){let n=e.constructor?.name;return typeof n=="string"&&n.length>0?n:t}i(_a,"portConstructorId");function pn(e={}){let t=e.strict??!0,n=e.instanceId??Nu(),r=e.profile??at,o=e.maxHistorySize??No,s=hn(),a=_n(),l=e.metadata??Kn(),c=e.auditTrail===void 0,u=e.auditTrail??On({maxRecords:o}),f=e.eventContracts??wn(),y=e.eventBuffer===void 0&&e.outbox===void 0,p=e.eventBuffer??e.outbox??new Me,g=e.projections??er({auditTrail:u}),d=new Le([In(r),...e.policies??[]]),m=i(()=>{Tn(s,a,{requireRegisteredTargets:!0})},"syncGraph"),E=e.ephemeral??!0,S=e.broker,k=new st({intentRegistry:s,dependencyGraph:a,policyEngine:d,strictRegistry:!0,validateIntentNaming:!0,auditTrail:u,eventContracts:f,strictEventContracts:e.strictEventContracts??t,requireKnownSource:e.requireKnownSource??!0,architectureProfile:r,enforceObservedLayerFlow:e.enforceObservedLayerFlow??(t?"hard":"off"),eventBuffer:p,instanceId:n,maxHistorySize:o,onPublish:e.autoApplyProjections===!1?void 0:async D=>{await g.apply(D)}}),v=qt(k,{auditTrail:u}),C=Cn({registry:s,eventBus:k,graph:a}),N=Oa(),b=typeof S?.send=="function",T=y?"InMemoryEventBuffer":_a(p,"EventBufferStore"),De=c?"InMemoryAuditStore":_a(u,"AuditTrail"),ge=cn({stores:[Be(T,"outbox"),Be(De,"audit"),Be("InMemoryWorkflowStore","workflow")]}),ve={instanceId:n,profile:r,registry:s,graph:a,metadata:l,auditTrail:u,eventContracts:f,eventBuffer:p,outbox:p,projections:g,policyEngine:d,eventBus:k,workflowEngine:v,observability:C,publisher(D){let z=k.createPublisher(D);return{source:z.source,publish:z.publish,send(q,me,Ee={}){return To({eventBus:k,broker:S,defaultEphemeral:E},q,me,{...Ee,source:z.source})}}},send(D,z,q={}){return To({eventBus:k,broker:S,defaultEphemeral:E},D,z,q)},register(D){return N.register(D)},resolve(D){return N.resolve(D)},resolveSingleton(D){return N.resolveSingleton(D)},getDependencyInformationPackage(){return Ie({kernelInstanceId:n,components:N.snapshotComponents()})},requestGraph(D){return lr({kernelInstanceId:n,components:N.snapshotComponents()},D)},getInspectorSnapshot(D){return gr({kernelInstanceId:n,host:D?.host,port:D?.port,package:{kernelInstanceId:n,components:N.snapshotComponents()},observability:C.report(),ephemeralDefault:E,brokerBound:b,hardening:ge})},startInspector(D){return mr({getInspectorSnapshot:i(q=>ve.getInspectorSnapshot(q),"getInspectorSnapshot"),requestGraph:i(q=>ve.requestGraph(q),"requestGraph"),async listInspectorOutbox(){let[q,me]=await Promise.all([p.list("pending"),p.list("failed")]);return We([...q,...me],{sampleLimit:ie})},async listInspectorWorkflows(){return ze(await v.list(),{sampleLimit:ie})}},D)},syncGraph:m,manifest(){return m(),nr({registry:s,policyEngine:d,metadata:l,graph:a,profile:r,projections:g,eventContracts:f,observability:C})}};return ve}i(pn,"createArkKernel");function Do(e={}){return pn({...e,strict:!0,strictEventContracts:e.strictEventContracts??!0,requireKnownSource:e.requireKnownSource??!0,enforceObservedLayerFlow:e.enforceObservedLayerFlow??"hard"})}i(Do,"createStrictArkKernel");function Lo(e,t={}){let{profileName:n,...r}=t;return{...r,profile:Mn(e,{name:n})}}i(Lo,"createOptionsFromConfig");function Ta(e,t={}){return pn(Lo(e,t))}i(Ta,"createArkKernelFromConfig");function Na(e,t={}){return Do(Lo(e,t))}i(Na,"createStrictArkKernelFromConfig");function Da(e,t={}){return Fo(Lo(e,t))}i(Da,"createLenientArkKernelFromConfig");function Fo(e={}){return pn({...e,strict:!1,strictEventContracts:e.strictEventContracts??!1,enforceObservedLayerFlow:e.enforceObservedLayerFlow??"off"})}i(Fo,"createLenientArkKernel");export{qr as ANALYSIS_IR_SCHEMA_VERSION,Ko as ARK_ANALYSIS_RESULT_SCHEMA,gn as ARK_ANALYSIS_RESULT_SCHEMA_VERSION,Gd as ARK_DESIGN_DELTA_SCHEMA_VERSION,Kd as ARK_ENFORCEMENT_STATE_SCHEMA_VERSION,go as ARK_RUN_COMPONENT_LIFETIMES,At as ARK_RUN_EPHEMERAL_DEFAULT,vo as ARK_RUN_GRAPH_DEFAULT_SLICE,Ra as ARK_RUN_GRAPH_NODE_KINDS,Aa as ARK_RUN_GRAPH_PROCESS_EDGE_KINDS,bo as ARK_RUN_GRAPH_SCHEMA_VERSION,Eo as ARK_RUN_GRAPH_SLICES,ka as ARK_RUN_GRAPH_TECHNICAL_EDGE_KINDS,rr as ARK_RUN_INFORMATION_PACKAGE_SCHEMA_VERSION,ur as ARK_RUN_INSPECTOR_DEFAULT_HOST,Oo as ARK_RUN_INSPECTOR_DEFAULT_PORT,rn as ARK_RUN_INSPECTOR_EVENTS_PATH,on as ARK_RUN_INSPECTOR_GRAPH_PATH,ie as ARK_RUN_INSPECTOR_MONITOR_SAMPLE_LIMIT,sn as ARK_RUN_INSPECTOR_OUTBOX_PATH,xo as ARK_RUN_INSPECTOR_SCHEMA_VERSION,nn as ARK_RUN_INSPECTOR_SNAPSHOT_PATH,Po as ARK_RUN_INSPECTOR_SSE_EVENT,_o as ARK_RUN_INSPECTOR_TRANSPORT_FALLBACK,an as ARK_RUN_INSPECTOR_WORKFLOWS_PATH,en as ARK_RUN_TRANSPORT_KINDS,ce as ArkRunInspectorBindError,kt as ArkRunInspectorProductionError,No as DEFAULT_MAX_HISTORY_SIZE,Zn as DIAGNOSTIC_CATALOG,Td as DIAGNOSTIC_CATALOG_SCHEMA_VERSION,lo as DIAGNOSTIC_DOCS_RELATIVE_PATH,Nd as DIAGNOSTIC_RULE_IDS,Ot as EventContractRegistryImpl,Qe as EventContractViolationError,Pt as InMemoryAuditStore,Me as InMemoryEventBuffer,hs as InMemoryOutboxStore,Wt as InMemoryReadModelStore,zt as InMemoryWorkflowStore,qe as IntentRegistry,ne as InvalidArkRunGraphQueryError,Rt as InvalidArkRunSendOptionError,Ze as InvalidIntentNameError,Je as LayerPolicyContextError,tr as MANIFEST_SCHEMA_VERSION,et as ObservedLayerFlowViolationError,no as POLICY_DELTA_SCHEMA_VERSION,Le as PolicyEngine,we as PolicyViolationError,zr as RESOLVED_CANDIDATE_FACTS_SCHEMA,Ge as RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,Ce as SourceMetadataOverrideError,Fe as UnknownEventSourceError,Xe as UnregisteredIntentError,gt as analyzeArchitectureConvergence,Wn as analyzeChange,Ei as analyzePolicyDelta,jt as analyzeProject,Bt as analyzeResolvedProject,da as appendDecisionTape,Ir as architecturalPolicies,ar as arkRunGraphQueryFromSearchParams,be as arkRunInspectorUrl,cn as buildArkRunInspectorHardening,We as buildArkRunInspectorOutboxMonitor,gr as buildArkRunInspectorSnapshot,ze as buildArkRunInspectorWorkflowsMonitor,Ie as buildDependencyInformationPackage,bn as buildPublishPolicyContext,Md as catalogFixForRuleId,Hd as catalogWhyForRuleId,_r as checkAdapterGovernance,Gs as checkContract,ro as classifyArkPolicyDelta,Be as classifyArkRunInspectorStoreDurability,ir as closeArkRunGraphQuery,Co as closedArkRunEphemeral,wo as closedArkRunTransportKind,Xn as collectAnalysisConfigWarnings,ut as collectForbiddenCapabilityUses,Ao as compareInformationPackages,Xs as createAICodeGate,Ks as createAdapter,ja as createAdapterResult,$n as createArchitectureProfile,Mn as createArchitectureProfileFromArkConfig,pn as createArkKernel,Ta as createArkKernelFromConfig,nr as createArkManifest,ks as createArkTestHarness,On as createAuditTrail,_n as createDependencyGraph,Ms as createElevenLayerArkConfig,ps as createEventBus,wn as createEventContractRegistry,hn as createIntentRegistry,Fo as createLenientArkKernel,Da as createLenientArkKernelFromConfig,Kn as createMetadataRegistry,Cn as createObservabilityReporter,er as createProjectionRegistry,Wr as createResolvedCandidateFacts,aa as createSaga,Do as createStrictArkKernel,Na as createStrictArkKernelFromConfig,qt as createWorkflowEngine,jo as defaultIntentRegistry,In as defineArchitectureProfilePolicy,Vo as defineIntent,An as defineLayerPolicy,Ye as definePolicy,Hs as definePort,zo as definePublishPolicy,so as detectArchitectureCycles,Y as deterministicHash,oa as diagnosticDocsFragment,Fd as diagnosticDocsPath,at as elevenLayerProfile,mt as evaluateArchitectureGraph,Si as explainViolation,dt as extractSemanticDependencies,So as formatArkRunGraphMermaid,dn as formatArkRunInspectorSseEvent,Jn as getDiagnosticCatalogEntry,It as isArkRunInspectorLoopbackHost,pr as isArkRunInspectorProductionEnv,Ld as isCataloguedOrArkRuleFamily,Dd as isKnownDiagnosticCode,kn as isLayerPolicy,Bn as loadContract,Oe as loadResolvedCandidateFacts,oo as policyDeltaAcknowledgementMatches,na as preflightChange,ra as preflightResolvedChange,fa as replayInformationPackages,lr as requestArkRunGraph,ln as resolveArkRunInspectorBind,dr as resolveArkRunSendPlan,Ht as resolvedFactsEvidenceRequirementsHash,$d as serializeDiagnosticCatalog,pa as shadowInformationPackage,M as stableSerialize,mr as startArkRunInspector,Tn as syncRegistryToGraph,kr as toAdapterDiagnostic,Ve as unavailableArkRunInspectorOutboxMonitor,je as unavailableArkRunInspectorWorkflowsMonitor,Rn as validateIntentName,yr as version};
28
+ `,t);return e.slice(n,r===-1?e.length:r)}a(yd,"lineAt");function hd(e){let t=e.trim();return/^import\b/.test(t)||/^export\s+/.test(t)&&/\bfrom\b/.test(t)?!0:/\brequire\s*\(/.test(t)}a(hd,"isImportLine");function Ti(e,t,n){if(!t||!e.includes(t))return;let r=new Set,o=0,s=e.length,i=a((l,c)=>{if(e.startsWith(t,l)){if(c==="comment"){r.add("comment");return}if(c==="string"){r.add("string");return}if(hd(yd(e,l))){r.add("import");return}n&&r.add("test-body")}},"note");for(;o<s;){let l=e[o],c=e[o+1];if(l==="/"&&c==="/"){for(;o<s&&e[o]!==`
29
+ `;)i(o,"comment"),o+=1;continue}if(l==="/"&&c==="*"){for(i(o,"comment"),i(o+1,"comment"),o+=2;o<s&&!(e[o]==="*"&&e[o+1]==="/");)i(o,"comment"),o+=1;o<s&&(i(o,"comment"),i(o+1,"comment"),o+=2);continue}if(l==='"'||l==="'"||l==="`"){let u=l;for(i(o,"string"),o+=1;o<s;){let f=e[o];if(f==="\\"){i(o,"string"),e[o+1]!==void 0&&i(o+1,"string"),o+=e[o+1]===void 0?1:2;continue}if(f===u){i(o,"string"),o+=1;break}i(o,"string"),o+=1}continue}i(o,"code"),o+=1}if(r.has("comment"))return"comment";if(r.has("string"))return"string";if(r.has("test-body"))return"test-body";if(r.has("import"))return"import"}a(Ti,"mentionContext");function Di(e){if(!e)return;let t=e.split("."),n=t[t.length-1]??"";return n?{className:t.length>1?t[0]??null:null,name:n}:void 0}a(Di,"symbolNeedle");function Rd(e){return Di(e.coverage?.symbol)?.name??e.id}a(Rd,"declaredLabel");function Ni(e){return Object.keys(e).sort((t,n)=>t<n?-1:t>n?1:0)}a(Ni,"sortedContentFiles");function Ad(e,t,n=!0){let r=t.testFiles??[],o=new Set(r.map(g=>It(g))),s=(t.coverageRoots??[]).filter(g=>typeof g=="string"&&g.length>0),i=e.coverage?.test!==!1&&n,l=Di(e.coverage?.symbol??void 0),c,u;if(i){for(let g of r){let d=t.fileContents[g];if(!d)continue;let m=gd(d,e.id);if(m!==void 0){if(s.length===0||Li(g,s)){c={file:g,title:m};break}u??={file:g,title:m}}}c??=u}let f;if(l)for(let g of Ni(t.fileContents)){if(o.has(It(g)))continue;let d=t.fileContents[g];if(!d||l.className&&!d.includes(l.className))continue;let m=md(d,l.name);if(m){f={file:g,shape:m};break}}let y;if(!c&&!f){if(i)for(let g of r){let d=t.fileContents[g];if(!d)continue;let m=Ti(d,e.id,!0);if(m){y={file:g,context:m};break}}if(!y&&l)for(let g of Ni(t.fileContents)){if(o.has(It(g)))continue;let d=t.fileContents[g];if(!d)continue;let m=Ti(d,l.name,!1);if(m){y={file:g,context:m};break}}}let p=c?{kind:"test-title",file:c.file,title:c.title}:f?{kind:"declaration",file:f.file,shape:f.shape}:y?{kind:"mention-only",file:y.file,context:y.context}:{kind:"none"};return p.kind==="mention-only"&&p.context==="comment"&&l&&kd(t.fileContents,o,l.name,p.file)&&(p={kind:"declaration-miss",symbol:l.name}),{best:p,...c?{testTitle:c}:{},...f?{declaration:f}:{}}}a(Ad,"rankCoverage");function kd(e,t,n,r){let o=new RegExp(`(?:^|[^A-Za-z0-9_$])${go(n)}(?=$|[^A-Za-z0-9_$])`),s=It(r);for(let i of Object.keys(e)){if(t.has(It(i))||It(i)===s)continue;let l=e[i];if(l&&o.test(mo(l,!0)))return!0}return!1}a(kd,"symbolInCodeElsewhere");function Id(e){switch(e.kind){case"test-title":case"declaration":return!0;case"mention-only":case"declaration-miss":case"none":return!1}}a(Id,"countsAsCoverage");function bd(e){switch(e){case"test-body":return"a test body";case"comment":return"a comment";case"string":return"a string";case"import":return"an import"}}a(bd,"mentionWhere");function Sd(e,t){switch(t.kind){case"test-title":return`found \`${t.title}\` in a describe/it title in ${t.file}`;case"declaration":return`found \`${t.shape} ${Rd(e)}\` in ${t.file}`;case"mention-only":return`${e.id} appears only in ${bd(t.context)} in ${t.file}; put it in a describe/it title`;case"declaration-miss":return`no declaration matched \`${t.symbol}\``;case"none":return"no scanned test names it in a describe/it title and no declared symbol was found"}}a(Sd,"describeCoverage");function Fi(e){let t=e.arkRules.invariants??[];if(t.length===0)return{coverage:[],violations:[],partial:!1};let n=e.testFiles??[],r=e.testGlobsMissing===!0||n.length===0,o=e.coverageBudgetExhausted===!0,s=e.coverageStats,i=_i(s),l=_i(s,!0),c=s?`coverage file budget exhausted: ${s.filesLoaded} files loaded at the ${s.maxFiles}-file cap, ${s.testFilesRetained} tests retained, ${s.discarded.budget} files discarded at the cap; raise "coverage.maxFiles" in ark.config.json (the cap bounds files RETAINED as evidence${typeof s.filesRead=="number"?`; ${s.filesRead} were read`:""})`:"coverage file budget exhausted",u=(e.coverageRoots??[]).filter(d=>typeof d=="string"&&d.length>0),f=u.length>0,y=u.join(", "),p=[],g=[];for(let d of t){let m=d.coverage?.test!==!1,b=d.coverage?.symbol,v=!r&&m,k=Ad(d,{fileContents:e.fileContents,testFiles:n,coverageRoots:u},v),E=k.best,O=[];v&&k.testTitle&&O.push("test-title"),k.declaration&&O.push("symbol");let L=Id(E),S,N;v&&k.testTitle&&(S=k.testTitle.file,f&&(N=!Li(S,u)));let z=k.declaration?.file,Q=k.declaration?.shape,T=(d.coverage?.test===!0||!!b||d.coverage===void 0)&&L||d.coverage?.test===!1&&!b?!0:L,Y=r&&m&&!L;if(p.push({invariantId:d.id,layer:d.provenance.layer,sourceFile:d.provenance.sourceFile,mode:d.mode,covered:T&&!Y,evidence:O,partial:Y,description:d.description,...S!==void 0?{testEvidenceFile:S}:{},...z!==void 0?{symbolEvidenceFile:z}:{},...Q!==void 0?{shape:Q}:{},...N!==void 0?{outsideDeclaredRoots:N}:{},coverageRootsDeclared:f}),N===!0&&S!==void 0&&g.push({ruleId:"INVARIANT_COVERAGE_OUTSIDE_ROOTS",message:`Invariant ${d.id} is covered only by ${S}, which is outside the declared coverage roots (${y}). ArkGate matches declared text and never executes tests, so it cannot tell whether that file is run: move the test under a declared root, or add its root to "coverage.coverageRoots" in ark.config.json.`,file:S,line:1,arkruleId:d.id,arkruleSource:d.provenance.sourceFile,fromLayer:d.provenance.layer,severity:"warning",failsStrict:!1}),!T||Y){let X=d.mode==="enforced"&&!Y,Ae=r||n.length===0?"never-had-tests":"tests-disappeared";g.push({ruleId:"INVARIANT_UNCOVERED",message:(Y?o?`Invariant ${d.id} coverage cannot be proven (${c}); reporting partial, not covered.`:`Invariant ${d.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered (never-had-tests).`:`Invariant ${d.id}: ${Sd(d,E)} (${Ae==="tests-disappeared"?"tests-disappeared \u2014 a suite exists":"never-had-tests \u2014 the scan found no tests at all"}). ArkGate matches declared text; it never executes tests.`)+(Y&&o?l:i),file:d.provenance.sourceFile,line:1,arkruleId:d.id,arkruleSource:d.provenance.sourceFile,fromLayer:d.provenance.layer,severity:X?"error":"warning",failsStrict:X,kind:Ae})}}return{coverage:p,violations:g,partial:p.some(d=>d.partial)}}a(Fi,"evaluateInvariantCoverage");function $i(e){return e?e.partial?{ok:!1,reason:"Coverage is partial (missing test globs); cannot promote until evidence is complete."}:e.covered?e.outsideDeclaredRoots===!0?{ok:!1,reason:`Invariant ${e.invariantId} is covered only by ${e.testEvidenceFile??"a test"}, outside the declared coverage roots; ArkGate cannot tell whether that test runs, so it will not promote on it.`}:e.coverageRootsDeclared===!1?{ok:!1,reason:`Declare coverage.coverageRoots in ark.config.json before promoting ${e.invariantId} to enforced. Without that, ArkGate cannot tell whether a covering test is one the runner executes.`}:{ok:!0,reason:`Invariant ${e.invariantId} has coverage evidence.`}:{ok:!1,reason:`Invariant ${e.invariantId} is uncovered; add a test title or symbol before promoting to enforced.`}:{ok:!1,reason:"No coverage evidence supplied for this invariant; evaluate coverage before promoting to enforced."}}a($i,"canPromoteInvariant");function fo(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!="string")continue;let r=n.trim();r.length>0&&t.push(r)}return t}a(fo,"nonEmptyPathStrings");function vd(e){return!e||typeof e!="object"?[]:[...fo(e.testGlobs),...fo(e.coverageRoots)]}a(vd,"configuredInvariantTestsPaths");function Ed(e){return vd(e).length>0}a(Ed,"hasConfiguredInvariantTestsPath");function yo(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.coverage?.test!==!1)}a(yo,"catalogDemandsInvariantTestsPath");function Mi(e){let t=e.hasDomainInvariants===!0||e.hasDomainInvariants!==!1&&yo(e.invariants);return e.adopted!==!0||!t?[]:Ed(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:dd,message:ud,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]}a(Mi,"collectMissingInvariantTestsPathFindings");function wd(e){return!e||typeof e!="object"?[]:fo(e.coverageRoots)}a(wd,"configuredCoverageRoots");function Cd(e){return wd(e).length>0}a(Cd,"hasConfiguredCoverageRoots");function ho(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.mode==="enforced")}a(ho,"catalogHasEnforcedInvariant");function Hi(e){return e.hasEnforcedInvariant===!0||e.hasEnforcedInvariant!==!1&&ho(e.invariants)?Cd(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:pd,message:fd,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]:[]}a(Hi,"collectMissingCoverageRootsFindings");var bo="1.0",xd="add a short note under docs/adr/ (or docs/decisions/) and put that file path in --policy-ack as adrPath.";function C(e,t){let n=t.classification==="weakening"||t.classification==="judgment-required"?`Restore the previous protection at ${t.path}, or ${xd}`:void 0,r=t.nextAction??n;e.push({id:`${t.classification}:${t.path}:${t.kind}`,path:t.path,classification:t.classification,message:t.message,...r?{nextAction:r}:{},...t.before===void 0?{}:{before:t.before},...t.after===void 0?{}:{after:t.after}})}a(C,"addFinding");function K(e){return[...new Set(e??[])].sort()}a(K,"sortedUnique");function me(e,t,n,r,o){let s=K(n),i=K(r),l=new Set(s),c=new Set(i),u=i.filter(y=>!l.has(y)),f=s.filter(y=>!c.has(y));u.length===0&&f.length===0||(u.length>0&&C(e,{kind:"added",path:t,classification:o.added,message:o.addedMessage,before:s,after:i}),f.length>0&&C(e,{kind:"removed",path:t,classification:o.removed,message:o.removedMessage,before:s,after:i}))}a(me,"compareStringSets");function en(e,t,n,r,o,s,i){if(n===r)return;C(e,{kind:r?"enabled":"disabled",path:t,classification:r?o:o==="strengthening"?"weakening":"strengthening",message:r?s:i,before:n,after:r})}a(en,"compareBoolean");function nr(e,t){let n=new Map,r=new Set;for(let o of e){let s=t(o);n.has(s)?r.add(s):n.set(s,o)}return{values:n,duplicates:[...r].sort()}}a(nr,"keyed");function Od(e,t,n){let r=nr(t,s=>s.name),o=nr(n,s=>s.name);(r.duplicates.length>0||o.duplicates.length>0)&&C(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:r.duplicates,after:o.duplicates});for(let s of[...new Set([...r.values.keys(),...o.values.keys()])].sort()){let i=r.values.get(s),l=o.values.get(s),c=`$.layers[${s}]`;if(!i&&l){C(e,{kind:"layer-added",path:c,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",nextAction:"Write a short note under docs/adr/ (or docs/decisions/) for this new layer and put that file path in --policy-ack as adrPath.",after:l});continue}if(i&&!l){C(e,{kind:"layer-removed",path:c,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:i});continue}if(!i||!l)continue;me(e,`${c}.patterns`,i.patterns,l.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),me(e,`${c}.exclude`,i.exclude,l.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let u=tr(i),f=tr(l);me(e,`${c}.forbiddenGlobals`,u.rawGlobals,f.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),me(e,`${c}.capabilities`,u.atoms,f.atoms,{added:"strengthening",removed:"weakening",addedMessage:"Additional ambient/import protection is enforced in this layer (coverage atoms).",removedMessage:"An ambient/import protection was lost from this layer (coverage atoms)."}),K(i.intentPrefixes).join("\0")!==K(l.intentPrefixes).join("\0")&&C(e,{kind:"intent-prefixes-changed",path:`${c}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:K(i.intentPrefixes),after:K(l.intentPrefixes)}),en(e,`${c}.mayImportInfrastructure`,i.mayImportInfrastructure===!0,l.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),en(e,`${c}.optional`,i.optional===!0,l.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active.")}}a(Od,"compareLayers");function Pd(e,t,n){let r=a(i=>`${i.from}->${i.to}`,"keyOf"),o=nr(t,r),s=nr(n,r);(o.duplicates.length>0||s.duplicates.length>0)&&C(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:o.duplicates,after:s.duplicates});for(let i of[...new Set([...o.values.keys(),...s.values.keys()])].sort()){let l=o.values.get(i),c=s.values.get(i),u=`$.rules[${i}]`;if(!l&&c){c.allowed===!1?C(e,{kind:"deny-added",path:u,classification:"strengthening",message:"A denied dependency edge was added.",after:c}):C(e,{kind:"allow-added",path:u,classification:"judgment-required",message:"A new import edge was added; confirm this house should import that one.",nextAction:"Write a short note under docs/adr/ (or docs/decisions/) for this new import edge and put that file path in --policy-ack as adrPath.",after:c});continue}if(l&&!c){l.allowed===!1&&C(e,{kind:"deny-removed",path:u,classification:"weakening",message:"A denied dependency edge was removed.",before:l});continue}if(!l||!c)continue;l.allowed!==c.allowed&&C(e,{kind:c.allowed?"deny-disabled":"deny-enabled",path:`${u}.allowed`,classification:c.allowed?"weakening":"strengthening",message:c.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:l.allowed,after:c.allowed});let f=l.peerIsolation===!0,y=c.peerIsolation===!0;if(f!==y){let d=l.from===l.to&&c.from===c.to;C(e,{kind:y?"peer-isolation-enabled":"peer-isolation-disabled",path:`${u}.peerIsolation`,classification:d?y?"strengthening":"weakening":"judgment-required",message:d?y?"Cross-slice dependencies inside this layer are now denied.":"Cross-slice dependencies inside this layer are no longer denied.":"Changing peer isolation on a cross-layer edge changes the denial scope.",before:f,after:y})}K(l.sliceFolders).join("\0")!==K(c.sliceFolders).join("\0")&&C(e,{kind:"slice-folders-changed",path:`${u}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:K(l.sliceFolders),after:K(c.sliceFolders)});let p=l.sliceIdentity??"path",g=c.sliceIdentity??"path";if(p!==g&&C(e,{kind:"slice-identity-changed",path:`${u}.sliceIdentity`,classification:"judgment-required",message:"Slice identity changed and can reclassify existing slice ids. Baselines and allowedCrossSlice use those ids.",before:p,after:g}),!(!f&&!y)){if(Io(e,`${u}.sharedRoots`,"shared-roots",K(l.sharedRoots),K(c.sharedRoots),"Roots declared shared are exempt from the peerIsolation unclassifiable denial.","Roots are no longer declared shared and fall back to the peerIsolation denial."),Io(e,`${u}.allowedCrossSlice`,"cross-slice-allowance",K((l.allowedCrossSlice??[]).map(ko)),K((c.allowedCrossSlice??[]).map(ko)),"Directed cross-slice edges are now allowed by declaration.","Directed cross-slice edges are no longer declared and deny again."),(l.sharedImportsSlice??null)!==(c.sharedImportsSlice??null)){let d=l.sharedImportsSlice??null,m=c.sharedImportsSlice??null,b=zi(m)>zi(d);C(e,{kind:"shared-imports-slice",path:`${u}.sharedImportsSlice`,classification:b?"strengthening":"weakening",message:Vd(d,m),before:d,after:m})}Td(e,u,l,c)}}}a(Pd,"compareRules");function Ki(e){let t=e.childSlices;return t?JSON.stringify([K(t.sliceFolders??[]),t.sliceIdentity??"path",K(t.commonFolders??[])]):""}a(Ki,"childSliceFoldersKey");function _d(e){return K((e??[]).map(t=>rr(t.trim().replace(/\\/g,"/")).toLowerCase()))}a(_d,"enforceKeys");function Gi(e){if(!e.childSlices)return null;let t=e.childSlices.siblings;return t==null||t==="deny"?{mode:"deny",enforce:[]}:t==="advisory"?{mode:"advisory",enforce:[]}:t.default==="deny"?{mode:"deny",enforce:[]}:{mode:"advisory",enforce:_d(t.enforce)}}a(Gi,"childSliceSiblingPolicy");function Td(e,t,n,r){let o=Gi(n),s=Gi(r);if(o===null&&s===null)return;if(o===null&&s!==null){C(e,{kind:"child-slices-added",path:`${t}.childSlices`,classification:s.mode==="advisory"?"judgment-required":"strengthening",message:s.mode==="advisory"?"A child slice wall was added with advisory sibling crossings.":"A child slice wall was added. Sibling crossings inside a universe are now denied.",after:r.childSlices});return}if(o!==null&&s===null){C(e,{kind:"child-slices-removed",path:`${t}.childSlices`,classification:"weakening",message:"The child slice wall was removed. Sibling crossings inside a universe are allowed again.",before:n.childSlices});return}if(Ki(n)!==Ki(r)){C(e,{kind:"child-slices-changed",path:`${t}.childSlices`,classification:"judgment-required",message:"Child slice folders changed and can reclassify edges inside a universe.",before:n.childSlices,after:r.childSlices});return}if(o===null||s===null)return;if(o.mode!==s.mode){let c=s.mode==="advisory";C(e,{kind:"child-slices-siblings",path:`${t}.childSlices.siblings`,classification:c?"weakening":"strengthening",message:c?s.enforce.length>0?"Sibling crossings outside the enforce list are now advisory.":"Sibling crossings inside a universe are now advisory.":"Sibling crossings inside a universe are now denied.",before:o.mode,after:s.mode})}else o.mode==="advisory"&&Nd(e,`${t}.childSlices.siblings.enforce`,o.enforce,s.enforce);let i=n.childSlices?.parentMayImportChild===!0,l=r.childSlices?.parentMayImportChild===!0;i!==l&&C(e,{kind:"child-slices-parent-import",path:`${t}.childSlices.parentMayImportChild`,classification:l?"weakening":"strengthening",message:l?"Universe common may now import a child slice.":"Universe common may no longer import a child slice.",before:i,after:l}),$d(e,t,n,r),Fd(e,t,n,r)}a(Td,"compareChildSlices");function Nd(e,t,n,r){if(JSON.stringify(n)===JSON.stringify(r))return;let o=r.filter(l=>!n.includes(l)),s=n.filter(l=>!r.includes(l)),i=o.length>0&&s.length>0;C(e,{kind:i?"child-slices-siblings-enforce-changed":"child-slices-siblings-enforce",path:t,classification:i?"judgment-required":o.length>0?"strengthening":"weakening",message:i?"Enforced sibling subtrees were added and removed in the same change.":o.length>0?"Sibling crossings from these subtrees are now errors.":"Sibling crossings from these subtrees are advisory again.",before:n,after:r})}a(Nd,"compareSiblingEnforceList");function ko(e){return JSON.stringify([e.from,e.to])}a(ko,"crossSliceKey");function Ui(e){return K((e.childSlices?.allowedCrossSlice??[]).map(ko))}a(Ui,"childCrossSliceKeys");function bt(e){return rr(e.trim().replace(/\\/g,"/")).toLowerCase().split("/").filter(t=>t.length>0)}a(bt,"allowanceSegments");function Vi(e,t){let n=bt(e),r=bt(t);if(n.length===0||n.length!==r.length)return!1;let o=!1;for(let s=0;s<n.length;s+=1)if(n[s]!==r[s]){if(n[s]==="*"&&r[s]!=="*"){o=!0;continue}return!1}return o}a(Vi,"patternWidens");function Ld(e,t){let n=JSON.parse(e),r=JSON.parse(t),o=bt(n[0]).join("/")===bt(r[0]).join("/"),s=bt(n[1]).join("/")===bt(r[1]).join("/"),i=Vi(n[0],r[0]),l=Vi(n[1],r[1]);return!(o||i)||!(s||l)?!1:i||l}a(Ld,"allowanceWidens");function Dd(e){return JSON.stringify([rr(e.from.trim().replace(/\\/g,"/")).toLowerCase(),rr(e.to.trim().replace(/\\/g,"/")).toLowerCase()])}a(Dd,"aliasEntryKey");function ji(e){return K((e.childSlices?.sliceAliases??[]).map(Dd))}a(ji,"sliceAliasKeys");function Fd(e,t,n,r){let o=ji(n),s=ji(r);if(JSON.stringify(o)===JSON.stringify(s))return;let i=s.filter(u=>!o.includes(u)),l=o.filter(u=>!s.includes(u)),c=i.length>0&&l.length>0;C(e,{kind:c?"slice-aliases-changed":i.length>0?"slice-aliases-added":"slice-aliases-removed",path:`${t}.childSlices.sliceAliases`,classification:c?"judgment-required":i.length>0?"strengthening":"weakening",message:c?"Slice aliases were added and removed in the same change.":i.length>0?"Unclassified files are now under the slice walls.":"Aliased files leave the slice walls.",before:o,after:s})}a(Fd,"compareSliceAliases");function $d(e,t,n,r){let o=Ui(n),s=Ui(r);if(JSON.stringify(o)===JSON.stringify(s))return;let i=s.filter(c=>!o.includes(c)),l=o.filter(c=>!s.includes(c));if(i.length>0&&l.length>0&&l.filter(u=>!i.some(f=>Ld(f,u))).length===0){C(e,{kind:"child-slices-cross-slice-allowance-added",path:`${t}.childSlices.allowedCrossSlice`,classification:"weakening",message:"A wildcard widened a declared sibling allowance.",before:o,after:s});return}Io(e,`${t}.childSlices.allowedCrossSlice`,"child-slices-cross-slice-allowance",o,s,"Sibling crossings inside a universe are now allowed by declaration.","Declared sibling crossings inside a universe deny again.")}a($d,"compareChildCrossSliceAllowances");function Io(e,t,n,r,o,s,i){if(JSON.stringify(r)===JSON.stringify(o))return;let l=o.filter(f=>!r.includes(f)),c=r.filter(f=>!o.includes(f)),u=l.length>0&&c.length>0;C(e,{kind:u?`${n}-changed`:l.length>0?`${n}-added`:`${n}-removed`,path:t,classification:u?"judgment-required":l.length>0?"weakening":"strengthening",message:u?`${s} Entries were added and removed in the same change.`:l.length>0?s:i,before:r,after:o})}a(Io,"compareDeclaredExceptions");function Md(e,t,n){let r=t.safety??{},o=n.safety??{};for(let s of["maxTsSuppressions","maxAnyCasts"]){let i=r[s]??0,l=o[s]??0;i!==l&&C(e,{kind:l>i?"threshold-raised":"threshold-lowered",path:`$.safety.${s}`,classification:l>i?"weakening":"strengthening",message:l>i?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:i,after:l})}for(let s of["allowInMemory","allowDisabledPeerIsolation"])en(e,`$.safety.${s}`,r[s]===!0,o[s]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}a(Md,"compareSafety");function Ro(e){return e.mode==="enforced"?"enforced":"advisory"}a(Ro,"arkRunMode");function Ao(e){return e.mode==="enforced"?"enforced":"advisory"}a(Ao,"arkOrderMode");function Hd(e,t,n){let r=t.arkOrder,o=n.arkOrder,s="$.arkOrder";if(!r&&!o)return;if(!r&&o){C(e,{kind:"arkorder-added",path:s,classification:"strengthening",message:`ArkOrder extra was added (${Ao(o)}).`,after:o});return}if(r&&!o){C(e,{kind:"arkorder-removed",path:s,classification:"weakening",message:"ArkOrder extra was removed.",before:r});return}if(!r||!o)return;let i=Ao(r),l=Ao(o);if(i!==l){let c=i==="advisory"&&l==="enforced";C(e,{kind:c?"arkorder-promoted":"arkorder-demoted",path:`${s}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkOrder extra was promoted to enforced.":"ArkOrder extra was demoted to advisory.",before:i,after:l})}me(e,`${s}.planeRoots`,r.planeRoots,o.planeRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkOrder plane roots are governed.",removedMessage:"ArkOrder plane roots were removed and may skip the plane."}),me(e,`${s}.managedLayers`,r.managedLayers,o.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkOrder.",removedMessage:"Layers were removed from ArkOrder management."})}a(Hd,"compareArkOrder");function Kd(e,t,n){let r=t.arkRun,o=n.arkRun,s="$.arkRun";if(!r&&!o)return;if(!r&&o){C(e,{kind:"arkrun-added",path:s,classification:"strengthening",message:`ArkRun extra was added (${Ro(o)}).`,after:o});return}if(r&&!o){C(e,{kind:"arkrun-removed",path:s,classification:"weakening",message:"ArkRun extra was removed.",before:r});return}if(!r||!o)return;let i=Ro(r),l=Ro(o);if(i!==l){let c=i==="advisory"&&l==="enforced";C(e,{kind:c?"arkrun-promoted":"arkrun-demoted",path:`${s}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkRun extra was promoted to enforced.":"ArkRun extra was demoted to advisory.",before:i,after:l})}me(e,`${s}.compositionRoots`,r.compositionRoots,o.compositionRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkRun composition roots are governed.",removedMessage:"ArkRun composition roots were removed and may skip the kernel."}),me(e,`${s}.managedLayers`,r.managedLayers,o.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkRun.",removedMessage:"Layers were removed from ArkRun management."}),en(e,`${s}.requireDeclarations`,r.requireDeclarations!==!1,o.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}a(Kd,"compareArkRun");function Gd(e){return e.some(t=>t.classification==="weakening")?"weakening":e.some(t=>t.classification==="judgment-required")?"judgment-required":e.some(t=>t.classification==="strengthening")?"strengthening":"neutral"}a(Gd,"overallClassification");function Bi(e,t){return`${e}::${t}`}a(Bi,"ruleKey");function Wi(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(Bi(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(Bi(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}a(Wi,"indexEffectiveRules");function Ud(e,t,n,r,o,s){let i=new Map((s??[]).map(p=>[p.invariantId,p])),l=t.arkRules??{},c=n.arkRules??{},u=[...new Set([...Object.keys(l),...Object.keys(c)])].sort();for(let p of u){let g=l[p],d=c[p],m=`$.arkRules[${p}]`;if(g===void 0&&d!==void 0){C(e,{kind:"arkrules-ref-added",path:m,classification:"strengthening",message:`ArkRules reference for layer ${p} was added.`,after:d});continue}if(g!==void 0&&d===void 0){C(e,{kind:"arkrules-ref-removed",path:m,classification:"weakening",message:`ArkRules reference for layer ${p} was removed.`,before:g});continue}g!==d&&C(e,{kind:"arkrules-ref-path-changed",path:m,classification:"judgment-required",message:`ArkRules file path for layer ${p} changed; verify the effective rules still match intent.`,before:g,after:d})}let f=Wi(r),y=Wi(o);for(let p of[...new Set([...f.structure.keys(),...y.structure.keys()])].sort()){let g=f.structure.get(p),d=y.structure.get(p),m=`$.arkRules.structure[${p}]`;if(!g&&d){C(e,{kind:"arkrule-structure-added",path:m,classification:"strengthening",message:`Structure ArkRule ${d.id} was added (${d.mode}).`,after:d});continue}if(g&&!d){C(e,{kind:"arkrule-structure-removed",path:m,classification:"weakening",message:`Structure ArkRule ${g.id} was removed.`,before:g});continue}if(!(!g||!d)){if(g.mode!==d.mode){let b=g.mode==="advisory"&&d.mode==="enforced";C(e,{kind:b?"arkrule-promoted":"arkrule-demoted",path:`${m}.mode`,classification:b?"strengthening":"weakening",message:b?`Structure ArkRule ${d.id} was promoted to enforced.`:`Structure ArkRule ${d.id} was demoted to advisory.`,before:g.mode,after:d.mode})}g.sensor!==d.sensor&&C(e,{kind:"arkrule-sensor-changed",path:`${m}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${d.id} changed sensor identity.`,before:g.sensor,after:d.sensor})}}for(let p of[...new Set([...f.invariants.keys(),...y.invariants.keys()])].sort()){let g=f.invariants.get(p),d=y.invariants.get(p),m=`$.arkRules.invariants[${p}]`;if(!g&&d){C(e,{kind:"arkrule-invariant-added",path:m,classification:"strengthening",message:`Invariant ${d.id} was added (${d.mode}).`,after:d});continue}if(g&&!d){C(e,{kind:"arkrule-invariant-removed",path:m,classification:"weakening",message:`Invariant ${g.id} was removed.`,before:g});continue}if(!(!g||!d)&&g.mode!==d.mode)if(g.mode==="advisory"&&d.mode==="enforced"){let v=i?.get(d.id),k=$i(v);k.ok?C(e,{kind:"arkrule-invariant-promoted",path:`${m}.mode`,classification:"strengthening",message:`Invariant ${d.id} was promoted to enforced (coverage evidence present).`,before:g.mode,after:d.mode}):C(e,{kind:"arkrule-invariant-promote-refused",path:`${m}.mode`,classification:"judgment-required",message:`Invariant ${d.id} cannot be promoted to enforced: ${k.reason}`,before:g.mode,after:d.mode})}else C(e,{kind:"arkrule-invariant-demoted",path:`${m}.mode`,classification:"weakening",message:`Invariant ${d.id} was demoted to advisory.`,before:g.mode,after:d.mode})}}a(Ud,"compareArkRules");function So(e,t,n){let r=[];me(r,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),me(r,"$.exclude",e.exclude,t.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional project paths are excluded from governance.",removedMessage:"Fewer project paths are excluded from governance."}),me(r,"$.dynamicImportAllowlist",e.dynamicImportAllowlist,t.dynamicImportAllowlist,{added:"weakening",removed:"strengthening",addedMessage:"Additional files may use non-literal dynamic imports.",removedMessage:"Fewer files may use non-literal dynamic imports."}),en(r,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let o={off:0,soft:1,"framework-soft":1,strict:2},s=e.cyclePolicy??"strict",i=t.cyclePolicy??"strict";if(s!==i){let l=o[i]===o[s]?"judgment-required":o[i]>o[s]?"strengthening":"weakening";C(r,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:l,message:"The cycle enforcement level changed.",before:s,after:i})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&C(r,{kind:"framework-overlay-changed",path:"$.frameworkOverlay",classification:"judgment-required",message:"The framework overlay changed and may alter effective layer matching.",before:e.frameworkOverlay??null,after:t.frameworkOverlay??null}),Od(r,e.layers,t.layers),Pd(r,e.rules,t.rules),Md(r,e,t),Ud(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),Kd(r,e,t),Hd(r,e,t),r.sort((l,c)=>l.path.localeCompare(c.path)||l.id.localeCompare(c.id)),{schemaVersion:bo,classification:Gd(r),findings:r}}a(So,"classifyArkPolicyDelta");function vo(e,t){if(!e||e.schemaVersion!==bo||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(o=>typeof o!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=K(e.findingIds),r=K(t.findingIds);return n.length===r.length&&n.every((o,s)=>o===r[s])}a(vo,"policyDeltaAcknowledgementMatches");function rr(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}a(rr,"trimTrailingSlashes");function zi(e){return e==="deny"?2:e==="deny-cross-parent"?1:0}a(zi,"sharedImportsSliceRank");function Vd(e,t){return t==="deny"?"A shared root may no longer import a slice.":e==="deny"&&t==="deny-cross-parent"?"A shared root may import a slice again, except when that hop carries another universe.":e==="deny"?"A shared root may import a slice again.":t==="deny-cross-parent"?"A slice may no longer reach another universe through a shared root. ark-check and CI report that path. The write hook and ESLint see one edge at a time and do not block it.":"A slice may reach another universe through a shared root again."}a(Vd,"sharedImportsSliceMessage");function We(e){let t=[];for(let n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."&&t.length>0&&t.at(-1)!==".."?t.pop():t.push(n));return t.join("/")}a(We,"normalizePath");function qi(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}a(qi,"isIdentifierStart");function or(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}a(or,"isIdentifierCharacter");function ae(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}a(ae,"skipWhitespace");function tn(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let r=t,o="";for(t+=1;t<e.length;t+=1){let s=e[t];if(s===n)return{value:o,offset:r,excerpt:e.slice(r,t+1)};s==="\\"&&t+1<e.length?(o+=e[t+1],t+=1):o+=s}}a(tn,"readString");function de(e,t,n){return e.startsWith(t,n)&&!or(e[n-1])&&!or(e[n+t.length])}a(de,"isWordAt");function Yi(e,t){let n=ae(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=ae(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!de(e,"type",n))return!1;let o=ae(e,n+4);if(o>=e.length||e[o]===","||e[o]==="}"||de(e,"as",o)||!qi(e[o]))return!1;for(n=o;n<e.length&&or(e[n]);)n+=1;if(n=ae(e,n),de(e,"as",n)){if(n=ae(e,n+2),!qi(e[n]))return!1;for(;n<e.length&&or(e[n]);)n+=1}r=!0}return!1}a(Yi,"bracedNamedBindingsAreTypeOnly");function jd(e,t){if(t=ae(e,t+6),e[t]==="(")return tn(e,ae(e,t+1));let n=!1;if(de(e,"type",t)){let o=ae(e,t+4);e[o]!==","&&!de(e,"from",o)&&(n=!0)}else Yi(e,t)&&(n=!0);let r=Xi(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}a(jd,"specifierAfterImport");function Bd(e,t){t=t+6;let n=ae(e,t),r=!1;if(de(e,"type",n)){let s=ae(e,n+4);(e[s]==="{"||e[s]==="*")&&(r=!0)}else Yi(e,n)&&(r=!0);let o=Xi(e,t,!1);return o&&r?{...o,typeOnly:!0}:o}a(Bd,"specifierAfterExport");function Xi(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(de(e,"from",t))return tn(e,ae(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return tn(e,t);if(t>0&&(de(e,"import",t)||de(e,"export",t)))return}}a(Xi,"specifierInStaticStatement");function Wd(e,t){for(t+=1;t<e.length;t+=1){let n=e[t];if(n==="\\")t+=1;else if(n==="`")return t}return e.length}a(Wd,"skipTemplateLiteral");function zd(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=ae(e,t+7);if(e[r]!=="(")return;r=ae(e,r+1);let o=tn(e,r);return o?{...o,requireCall:!0}:void 0}a(zd,"specifierAfterRequire");function qd(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="/"&&e[n+1]==="/"){if(n=e.indexOf(`
30
+ `,n+2),n<0)break;continue}if(r==="/"&&e[n+1]==="*"){let s=e.indexOf("*/",n+2);if(s<0)break;n=s+1;continue}if(r==="`"){n=Wd(e,n);continue}if(r==="'"||r==='"'){let s=tn(e,n);s&&(n=s.offset+s.excerpt.length-1);continue}let o=r==="i"&&de(e,"import",n)?jd(e,n):r==="e"&&de(e,"export",n)?Bd(e,n):r==="r"&&de(e,"require",n)?zd(e,n):void 0;o&&(t.push(o),n=o.offset+o.excerpt.length-1)}return t}a(qd,"moduleSpecifiers");function Zi(e,t){let n=[],r=[];for(let o of qd(e.content)){let s=o.value;if(!s.startsWith(".")){if(o.typeOnly)continue;let u=Bt(s);if(!u)continue;let f=e.content.slice(0,o.offset).split(`
31
+ `).length;r.push({file:e.path,symbol:s,capability:u,evidence:{kind:"import",file:e.path,line:f,excerpt:o.excerpt}});continue}let i=e.content.slice(0,o.offset).split(`
32
+ `).length,l={kind:"import",file:e.path,line:i,excerpt:o.excerpt},c=Yd(e.path,s,t);n.push({from:e.path,specifier:s,to:c?.path??null,resolution:c?"resolved":"unresolved",fromLayer:e.layer,toLayer:c?.layer??null,evidence:l})}return{edges:n,capabilityUses:r}}a(Zi,"moduleFactsFor");function Yd(e,t,n){let r=e.split("/");r.pop();for(let s of t.split("/"))s==="."||s===""||(s===".."?r.pop():r.push(s));let o=r.join("/");for(let s of[o,`${o}.ts`,`${o}.tsx`,`${o}.mts`,`${o}.cts`,`${o}/index.ts`,`${o}/index.tsx`]){let i=n.get(s);if(i)return i}}a(Yd,"resolveSpecifier");function Ji(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let o=Mn(t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});o&&n.push({ruleId:`layer-dependency:${o.from}->${o.to}`,message:o.message??`${o.from} must not depend on ${o.to}.`,edge:r,evidence:r.evidence})}return n}a(Ji,"violationsFor");var Xd={code:"LEXICAL_EVIDENCE_INCOMPLETE",message:"Lexical compatibility mode cannot prove parse status, TypeScript/package/symlink resolution, or symbol-aware source-policy and safety evidence. Use the resolved candidate facts APIs for an authoritative verdict."};function Zd(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}a(Zd,"hasActiveArkRules");function Jd(e,t){return Zd(e,t)?Z(M(Pi({config:e,arkRules:t,warnings:[]}))):Z(M(po(e)))}a(Jd,"policyHashFor");function sr(e,t,n){let r=typeof e=="string"?ci(e,t):Wr(e,t),o=n?.arkRules??Qt();return{...r,arkRules:o,policyHash:Jd(r.config,o)}}a(sr,"loadContract");function Qi(e){let t=sr(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=sr(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=So(t.config,n.config,{baseArkRules:t.arkRules,candidateArkRules:n.arkRules,candidateInvariantCoverage:e.candidateInvariantCoverage}),o=r.findings.filter(l=>l.classification==="weakening"||l.classification==="judgment-required").map(l=>l.id).sort(),s=o.length>0,i=s&&vo(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:o});return{schemaVersion:r.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:r.classification,findings:r.findings,blockingFindingIds:o,requiresAcknowledgement:s,acknowledged:i,valid:!s||i}}a(Qi,"analyzePolicyDelta");function nn(e){let t=e.files.map(y=>{let p=We(y.path);return{path:p,content:y.content,contentHash:Z(y.content),layer:fe(p,e.contract.config.layers)??null}}).sort((y,p)=>y.path.localeCompare(p.path)),n=new Map(t.map(y=>[y.path,y])),r=[],o=[];for(let y of t){let p=Zi(y,n);r.push(...p.edges),o.push(...p.capabilityUses)}let s=Ji(r,e.contract.config),i=new Map(e.contract.config.layers.map(y=>[y.name,y])),l=new Map(e.contract.config.layers.map(y=>[y.name,new Set(gt(y))]));for(let y of o){let p=n.get(y.file)?.layer;if(!p)continue;let g=i.get(p),d=_e(y.symbol,g?.forbiddenGlobals??[]);if(d){s.push({ruleId:"FORBIDDEN_GLOBAL",message:`${p} must not use module "${y.symbol}" because it is the import form of forbidden global "${d}".`,symbol:y.symbol,evidence:y.evidence});continue}l.get(p)?.has(y.capability)&&s.push({ruleId:"CAPABILITY_VIOLATION",message:`${p} denies the ${y.capability} capability; found import of "${y.symbol}".`,capability:y.capability,symbol:y.symbol,evidence:y.evidence})}let c=t.length===0?"complete":"partial",u=c==="complete"?[]:[{...Xd}],f={schemaVersion:uo,policyHash:e.contract.policyHash,compilerOptionsHash:Z(M(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(y=>y.name),edges:r,capabilityUses:o,violations:s};return{mode:"lexical-compatibility",completeness:c,completenessReasons:u,valid:c==="complete"&&s.length===0,ir:f}}a(nn,"analyzeProject");function ir(e){let t=new Map(e.files.map(n=>[We(n.path),n]));for(let n of e.changes){let r=We(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return nn({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}a(ir,"analyzeChange");function ea(e){let t=`${e.evidence.file}:${e.evidence.line}`;if(!e.edge)return`${e.ruleId} at ${t}: ${e.message}`;let n=e.edge.to??e.edge.specifier;return`${e.ruleId} at ${t}: ${e.edge.from} imports ${n}. ${e.message}`}a(ea,"explainViolation");function wo(e){let t=0,n=new Map,r=new Map,o=new Set,s=[],i=[],l=a(c=>{n.set(c,t),r.set(c,t),t+=1,s.push(c),o.add(c);for(let y of[...e.get(c)??[]].sort())e.has(y)&&(n.has(y)?o.has(y)&&r.set(c,Math.min(r.get(c)??0,n.get(y)??0)):(l(y),r.set(c,Math.min(r.get(c)??0,r.get(y)??0))));if(r.get(c)!==n.get(c))return;let u=[],f;do{if(f=s.pop(),f===void 0)break;o.delete(f),u.push(f)}while(f!==c);u.length>1&&i.push(u.sort())},"connect");for(let c of[...e.keys()].sort())n.has(c)||l(c);return i.sort((c,u)=>c[0]<u[0]?-1:c[0]>u[0]?1:0).map(c=>({ruleId:"CIRCULAR_DEPENDENCY",file:c[0],line:1,target:c.join(" \u2192 "),message:`Circular dependency among ${c.length} files: ${c.join(" \u2192 ")} \u2192 ${c[0]}.`,cycleKind:"value"}))}a(wo,"detectArchitectureCycles");function St(e){let t=e.contentViolations.map(s=>({...s})),n=(e.warnings??[]).map(s=>({...s})),r=new Map(e.files.map(s=>[s,new Set]));for(let s of e.edges){if(s.to&&s.to!==s.from&&!s.typeOnly&&r.has(s.from)&&r.get(s.from)?.add(s.to),!s.to||!s.fromLayer||!s.toLayer)continue;let i=Pe(e.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:e.config.layers});if(!i){let p=xs(e.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:e.config.layers});p&&n.push({ruleId:"SHARED_IMPORTS_SLICE",file:p.fromPath,line:s.line,fromLayer:s.fromLayer,toLayer:s.toLayer,target:p.toPath,toSlice:p.toSlice,failsStrict:!1,severity:"warning",message:`shared root ${p.fromPath} \u2192 slice ${p.toSlice} (${p.toPath}). The wall is direct-only.`});continue}let l=i.rule,c=!!l.peerIsolation,u=!c&&!!(s.typeOnly||s.namedBindingsTypeOnly),f=i.sliceVerdict,y=f?lt({surface:"import",verdict:f,fromLayer:s.fromLayer,toLayer:s.toLayer,kind:s.kind,fromPath:s.from,toPath:s.to,ruleMessage:l.message}):l.message??`${s.fromLayer} must not ${s.kind} ${s.toLayer}.`;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:s.from,line:s.line,fromLayer:s.fromLayer,toLayer:s.toLayer,target:s.to,...s.typeOnly?{typeOnly:!0}:{},...s.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...s.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...s.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!c&&s.portProofEligible?{portProofEligible:!0}:{},...s.kind?{edgeKind:s.kind}:{},...c?{peerIsolation:!0}:{},...He(f),message:u?`${y} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:y,...u?{failsStrict:!1,severity:"warning"}:{}})}t.push(...tu(e));let o=String(e.config.cyclePolicy??"strict").toLowerCase();if(o!=="off"){let s=wo(r);o==="soft"||o==="framework-soft"?n.push(...s.map(i=>({...i,message:`${i.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...s)}return{violations:t,warnings:n,safety:e.safety}}a(St,"evaluateArchitectureGraph");var Qd="CROSS_PARENT_VIA_SHARED",eu="ark-check and CI report this path. The write hook and ESLint see one edge at a time and do not block it.";function ta(e,t,n){for(let r of e??[])if(!(r.from!==t||r.to!==n)&&!(r.allowed!==!1||!r.peerIsolation)&&r.sharedImportsSlice==="deny-cross-parent")return r}a(ta,"denyingCrossParentRule");function Eo(e,t,n,r){let o=at(n,e,Os(e,t,r)).universeId;return o?{kind:"slice",id:o}:Ft(n,e.sharedRoots)?{kind:"shared"}:{kind:"other"}}a(Eo,"placeFile");function tu(e){let t=e.rules??[];if(!t.some(s=>s.sharedImportsSlice==="deny-cross-parent"))return[];let n=new Map;for(let s of e.edges){let i=nu(s);if(!i)continue;let l=n.get(i.from);l?l.push(i):n.set(i.from,[i])}for(let s of n.values())s.sort((i,l)=>i.to<l.to?-1:i.to>l.to?1:i.line-l.line);let r=new Map,o=[...n.values()].flat();o.sort((s,i)=>s.from<i.from?-1:s.from>i.from?1:s.to<i.to?-1:s.to>i.to?1:0);for(let s of o){let i=ta(t,s.fromLayer,s.toLayer);if(!i)continue;let l=Eo(i,s.fromLayer,s.from,e.config.layers),c=Eo(i,s.fromLayer,s.to,e.config.layers);if(l.kind!=="slice"||c.kind!=="shared")continue;let u=[{file:s.to,path:[s.from,s.to]}],f=new Set([s.to]);for(;u.length>0;){let y=u.shift();if(!y)break;for(let p of n.get(y.file)??[]){let g=ta(t,p.fromLayer,p.toLayer);if(!g)continue;let d=Eo(g,p.fromLayer,p.to,e.config.layers);if(d.kind==="shared"){if(f.has(p.to))continue;f.add(p.to),u.push({file:p.to,path:[...y.path,p.to]});continue}if(d.kind!=="slice"||d.id.toLowerCase()===l.id.toLowerCase())continue;let m=[...y.path,p.to],b=`${s.from}\0${p.to}`,v={file:s.from,target:p.to,line:s.line,fromLayer:s.fromLayer,toLayer:p.toLayer,fromSlice:l.id,toSlice:d.id,path:m},k=r.get(b);(!k||m.length<k.path.length||m.length===k.path.length&&m.join("\0")<k.path.join("\0"))&&r.set(b,v)}}}return[...r.values()].sort((s,i)=>s.file<i.file?-1:s.file>i.file?1:s.target<i.target?-1:s.target>i.target?1:0).map(s=>{let i=$t(s.fromSlice),l=$t(s.toSlice);return{ruleId:"LAYER_IMPORT_VIOLATION",reasonId:Qd,file:s.file,line:s.line,fromLayer:s.fromLayer,toLayer:s.toLayer,target:s.target,peerIsolation:!0,...i&&l?{universeFrom:i,universeTo:l}:{},message:`${s.fromLayer} reaches ${s.toLayer} in another universe through a shared root (${s.path.join(" \u2192 ")}): cross-parent via shared ${s.fromSlice} \u2192 ${s.toSlice}. ${eu}`}})}a(tu,"crossParentViaSharedViolations");function nu(e){if(!(!e.to||e.to===e.from||!e.fromLayer||!e.toLayer))return{from:e.from,to:e.to,line:e.line,fromLayer:e.fromLayer,toLayer:e.toLayer}}a(nu,"valueHop");function na(e){if(typeof e.target=="string"&&e.target.length>0)return e.target;let t=String(e.sensor||e.code||"").trim();if(!t&&typeof e.message=="string"){let r=e.message.match(/\(sensor ([a-z0-9-]+)\)/i);r?.[1]&&(t=r[1])}let n=String(e.symbol||"").trim();return t?n?`${t}:${n}`:t:n}a(na,"structureFreezeTarget");var ru=["no-anemic-model"],aa=["ensureInvariants","assertInvariants","validate","publish","emit","raise","record"],nh=new RegExp(`\\b(${aa.join("|")})\\b`),la="(?:_?pendingEvents|domainEvents|uncommittedEvents|recordedEvents)",rh=new RegExp(`\\bthis\\.${la}\\.push\\s*\\(`),oh=new RegExp(`^this\\.${la}\\s*=\\s*\\[\\s*\\]`);var ou="truncatedUntil";function su(){return`${aa.join(", ")}, or events-array .push(`}a(su,"expectedDomainInvariantWordsPhrase");function Co(e){let t=Object.getOwnPropertyDescriptor(e,ou)?.value;return typeof t=="number"?t:void 0}a(Co,"shapeTruncatedUntil");function iu(e){let t=Co(e);return t==null?"":` shape analysed until character ${t}`}a(iu,"shapeTruncationSuffix");function ra(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(ra,"escapeGlobLiteral");function au(e){let t="";for(let r=0;r<e.length;r+=1){let o=e[r];if(o==="\\"&&r+1<e.length){let s=e[r+1];if("*?{}[],".includes(s)||s==="\\"){t+="\\"+s,r+=1;continue}t+="/";continue}t+=o}let n="";for(let r=0;r<t.length;r+=1){let o=t[r];o==="\\"&&r+1<t.length?(n+=ra(t[r+1]),r+=1):o==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":o==="?"?n+="[^/]":n+=ra(o)}return new RegExp(`^${n}$`)}a(au,"globToRegExp");function vt(e,t){return!t||t.length===0?!0:t.some(n=>au(n).test(e))}a(vt,"matchesAppliesTo");function ca(e){return ru.includes(e)}a(ca,"isTier2");function da(e){return e.mode==="enforced"&&!ca(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}a(da,"severityFor");function Ne(e,t,n,r=1){let{severity:o,failsStrict:s}=da(e);return{ruleId:"ARKRULE_STRUCTURE",code:e.sensor,message:n,file:t,line:r,fromLayer:e.provenance.layer,arkruleId:e.id,arkruleSource:e.provenance.sourceFile,severity:o,sensor:e.sensor,failsStrict:s}}a(Ne,"baseViolation");function ar(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}a(ar,"isInRuleLayer");function lr(e,t,n){return t.filter(r=>!(!r.exported||!vt(r.file,e.appliesTo)||!ar(r.file,e,n)))}a(lr,"shapesForRule");function lu(e,t,n){let r=[];for(let o of lr(e,t,n))(o.hasPublicSetters||o.hasPublicMutableFields)&&r.push(Ne(e,o.file,`Exported class ${o.className} exposes public mutable state (sensor aggregate-private-state).`));return r}a(lu,"evaluateAggregatePrivateState");function cu(e,t,n){let r=[];for(let o of lr(e,t,n))if(o.hasPublicConstructor&&!o.hasStaticFactory){if(!(o.hasPublicMutableFields||o.hasPublicSetters||(o.mutatingMethods?.length??0)>0))continue;r.push(Ne(e,o.file,`Exported class ${o.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}return r}a(cu,"evaluateAlwaysValidFactory");function du(e,t,n){let r=[],o=su();for(let s of lr(e,t,n)){let i=iu(s);Co(s)!=null&&r.push(Ne(e,s.file,`Exported class ${s.className} shape analysed until character ${Co(s)}; later methods may be invisible (sensor domain-event-on-mutation).`));for(let l of s.mutatingMethods)l.referencesGuardOrPublish||r.push(Ne(e,s.file,`Mutating method ${s.className}.${l.name} does not reference ${o} (sensor domain-event-on-mutation).${i}`))}return r}a(du,"evaluateDomainEventOnMutation");function uu(e,t){let n=[];for(let r of t.files)vt(r,e.appliesTo)&&ar(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(Ne(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}a(uu,"evaluateOrchestrationOnly");function pu(e,t){let n=[];for(let r of t.files)vt(r,e.appliesTo)&&ar(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(Ne(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}a(pu,"evaluateThinAdapter");function fu(e,t){let n=[];for(let r of t.files)vt(r,e.appliesTo)&&ar(r,e,t.layerForFile)&&t.fileHints?.[r]?.persistenceWrite&&n.push(Ne(e,r,"File imports a persistence driver and issues a write; route the write through a Domain aggregate and a persistence adapter (sensor writes-via-aggregate)."));return n}a(fu,"evaluateWritesViaAggregate");function gu(e,t,n){let r=[];for(let o of lr(e,t,n))if(o.dataOnly===!0){let s=Ne(e,o.file,`Exported type ${o.className} looks data-only / anemic (sensor no-anemic-model; advisory only).`);r.push({...s,severity:"warning",failsStrict:!1})}return r}a(gu,"evaluateNoAnemicModel");function ua(e){if(!e.arkRules.structure.length)return[];let t=[];for(let n of e.arkRules.structure)switch(n.sensor){case"aggregate-private-state":t.push(...lu(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...cu(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...du(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...uu(n,e));break;case"thin-adapter":t.push(...pu(n,e));break;case"writes-via-aggregate":t.push(...fu(n,e));break;case"no-anemic-model":t.push(...gu(n,e.classShapes,e.layerForFile));break;case"invariant-coverage":break;default:break}return t.sort((n,r)=>n.file.localeCompare(r.file)||n.arkruleId.localeCompare(r.arkruleId)||n.message.localeCompare(r.message))}a(ua,"evaluateArkRuleSensors");function pa(e,t){let n=[],r=t.map(o=>o.replace(/\\/g,"/"));for(let o of e.structure){if(!o.appliesTo||o.appliesTo.length===0||r.some(c=>vt(c,o.appliesTo)))continue;let{severity:i,failsStrict:l}=da(o);n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule structure "${o.id}" appliesTo matched zero governed files (patterns: ${o.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:o.provenance.sourceFile,line:1,fromLayer:o.provenance.layer,arkruleId:o.id,arkruleSource:o.provenance.sourceFile,severity:i,sensor:o.sensor,failsStrict:l})}for(let o of e.invariants??[]){if(!o.appliesTo||o.appliesTo.length===0||r.some(l=>vt(l,o.appliesTo)))continue;let i=o.mode==="enforced";n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule invariant "${o.id}" appliesTo matched zero governed files (patterns: ${o.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:o.provenance.sourceFile,line:1,fromLayer:o.provenance.layer,arkruleId:o.id,arkruleSource:o.provenance.sourceFile,severity:i?"error":"warning",sensor:"invariant-coverage",failsStrict:i})}return n.sort((o,s)=>o.file.localeCompare(s.file)||o.arkruleId.localeCompare(s.arkruleId)||o.message.localeCompare(s.message))}a(pa,"collectEmptyAppliesToFindings");var oa=64;function mu(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===46;)t-=1;return t===e.length?e:e.slice(0,t)}a(mu,"stripTrailingDots");function yu(e){let t=e.trim(),n=t.length>oa?t.slice(0,oa):t;return mu(n)}a(yu,"normalizeIntentPrefix");function hu(e){let t=e.toLowerCase();return t.includes("domain")||t.includes("entity")||t.includes("aggregate")||t.includes("model")}a(hu,"layerNameLooksDomain");function Ru(e){return e.some(t=>{let n=yu(t);return n==="Domain"||n.startsWith("Domain.")})}a(Ru,"ownsDomainIntent");function Au(e,t=[]){return hu(e)||Ru(t)}a(Au,"isDomainRoleLayerName");function fa(e){if(e.arkRulesActive!==!0)return[];let t=(e.layers??[]).filter(c=>Au(c.name,c.intentPrefixes??[])).map(c=>c.name);if(t.length===0)return[];let n=new Set(t);if(!(e.files??[]).some(c=>{let u=typeof c.layer=="string"?c.layer:"";return u.length>0&&n.has(u)}))return[];if((e.arkRules.invariants??[]).filter(c=>n.has(c.provenance.layer)).length>0)return[];let s=t.find(c=>e.arkRules.byLayer?.[c])??t[0],i=e.arkRules.byLayer?.[s]?.sourceFile??`arkrules/${s}.json`,l=(e.arkRules.structure??[]).some(c=>c.mode==="enforced"&&n.has(c.provenance.layer)&&!ca(c.sensor));return[{ruleId:"INVARIANT_CATALOG_EMPTY",code:"invariant-catalog-empty",message:`ArkRules is on and ${s} has code, but invariants[] is empty \u2014 there are no phrases the code must preserve. Add 1\u20132 short phrases in ${i}.`,file:i,line:1,fromLayer:s,arkruleId:"invariant-catalog",arkruleSource:i,severity:l?"error":"warning",sensor:"invariant-coverage",failsStrict:l}]}a(fa,"collectEmptyInvariantCatalogFindings");var sa=/\bfrom\s+['"](?:@?prisma\/client|@supabase\/|drizzle-orm(?:\/[^'"]+)?|postgres(?:\/[^'"]+)?|typeorm|knex|mongodb|pg|mysql2|mongoose|better-sqlite3|ioredis|redis|kysely|sequelize)['"]|require\(\s*['"](?:@?prisma\/client|pg|postgres(?:\/[^'"]+)?|drizzle-orm(?:\/[^'"]+)?|knex|typeorm|mongoose)/,ia=/\bfrom\s+['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)(?:\.[cm]?[jt]sx?)?['"]|require\(\s*['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)/,ku=/\b(?:db|tx|client|prisma(?:Client)?|drizzle)\b(?:\s*\.\s*[A-Za-z_]\w*)*\s*\.\s*(?:insert(?:One|Many)?|update(?:One|Many)?|upsert|delete(?:One|Many)?|createMany|create|replaceOne|findOneAnd(?:Update|Delete|Replace))\s*\(|\bINSERT\s+INTO\b|\bUPDATE\s+[A-Za-z_][\w.]*\s+SET\b|\bDELETE\s+FROM\b/i;function Iu(e){return e==="PersistenceAdapters"}a(Iu,"isPersistenceDriverLayer");function bu(e,t){if(sa.test(e)||ia.test(e))return!0;if(!t)return!1;for(let n of t){if(Iu(n.layer))return!0;let r=n.specifier;if(!r)continue;let o=`from '${r}'`;if(sa.test(o)||ia.test(o))return!0}return!1}a(bu,"sourceImportsPersistenceDriver");var Su=/\b(?:@Controller|@Get|@Post|@Put|@Delete|Router\(\)|createRouter|express\.Router|fastify\.(?:get|post)|export\s+(?:async\s+)?function\s+(?:GET|POST|PUT|DELETE|PATCH)\b|export\s+const\s+(?:GET|POST|PUT|DELETE|PATCH)\s*=)/,vu=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,Eu=/\b(?:export\s+)?(?:async\s+)?function\s+(?:can|calculate|compute|should|ensure|validate|is|has)[A-Z]\w*|\b(?:export\s+)?const\s+(?:can|calculate|compute|should|ensure|validate|is|has)[A-Z]\w*\s*=/,wu=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function Cu(e,t,n){if(!t)return null;let r=bu(t,n),o=r&&ku.test(t);if(t.length<40)return o?{persistenceWrite:!0}:null;let s=t.match(new RegExp(Eu.source,"g"))??[],i=t.match(new RegExp(wu.source,"g"))??[],l=(t.match(/\bif\s*\(/g)??[]).length,c=(t.match(/\bswitch\s*\(/g)??[]).length,u=s.length>=2||s.length>=1&&i.length>=2||i.length>=3&&l+c>=6,f=Su.test(t)||vu.test(t),y=s.length>=1||i.length>=2,p=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),g=r&&y||f&&y||r&&p&&(l>=4||s.length>=1)||f&&r;return!u&&!g&&!o?null:{...u?{orchestrationHeavy:!0}:{},...g?{adapterThick:!0}:{},...o?{persistenceWrite:!0}:{}}}a(Cu,"deriveArkRuleFileHints");function ga(e,t){let n={};for(let[r,o]of Object.entries(e)){let s=r.replace(/\\/g,"/"),i=Cu(r,o,t?.[s]);i&&(n[s]=i)}return n}a(ga,"buildArkRuleFileHints");function xu(e){if(!e)return{};let t=typeof e.governedPercent=="number"?e.governedPercent:null,n=typeof e.populatedLayerCount=="number"?e.populatedLayerCount:null;return n==null&&typeof e.classifiedFiles=="number"&&(n=e.classifiedFiles>0?1:0),{governedPercent:t,populatedLayerCount:n}}a(xu,"normalizeExtraMergeTeethClassification");function cr(e){let t=xu(e),n=typeof t.governedPercent=="number"?t.governedPercent:null,r=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null;return n==null&&r==null?!0:(n??0)>=50&&(r??0)>=1}a(cr,"extraMergeTeethAllowed");function ma(e){let t=e.length,n=0,r=new Set;for(let o of e){let s=typeof o.layer=="string"&&o.layer.length>0?o.layer:null;s&&(n+=1,r.add(s))}return{governedPercent:t>0?Math.round(n/t*100):0,populatedLayerCount:r.size}}a(ma,"classifyResolvedLayerCoverage");var Ou=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"];var ch=new Set(Ou);function ya(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")}a(ya,"isArkRunKernelModuleSpecifier");var Pu=["events","node:events","eventemitter2","eventemitter3","emittery","kafkajs","kafka-node","amqplib","amqp","bull","bullmq","mqtt","nats","@aws-sdk/client-sqs","@aws-sdk/client-sns","@aws-sdk/client-eventbridge","@google-cloud/pubsub","@azure/service-bus"],xo=new Set(Pu);function ha(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(xo.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(xo.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:xo.has(e.slice(0,r))}a(ha,"isArkRunTransportBypassSpecifier");var _u=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],Ah=new Set(_u);var Ra={"arkrun-missing-root":"ARKRUN_MISSING_ROOT","arkrun-kernel-in-domain":"ARKRUN_KERNEL_IN_DOMAIN","arkrun-direct-new":"ARKRUN_DIRECT_NEW","arkrun-undeclared-emit":"ARKRUN_UNDECLARED_EMIT","arkrun-undeclared-handle":"ARKRUN_UNDECLARED_HANDLE","arkrun-undeclared-depend":"ARKRUN_UNDECLARED_DEPEND","arkrun-transport-bypass":"ARKRUN_TRANSPORT_BYPASS"},Tu="ARKRUN_INTERACTION_NAME_INCOMPLETE";function Ia(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)||/^(?:entit(?:y|ies)|aggregates?)(?:$|(?=[A-Z_\-\s]))/i.test(n)?!0:t.some(r=>{let o=r.trim().replace(/\.+$/,"");return o==="Domain"||o.startsWith("Domain.")})}a(Ia,"isDomainRoleLayer");function Nu(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}a(Nu,"compareFindings");function Se(e,t,n,r,o,s,i){let l=e.mode==="enforced"&&i;return{ruleId:Ra[t],sensor:t,message:o,file:n,line:r,...s?.fromLayer?{fromLayer:s.fromLayer}:{},...s?.target?{target:s.target}:{},severity:l?"error":"warning",failsStrict:l,nextAction:ye({ruleId:Ra[t],fromLayer:s?.fromLayer,target:s?.target})}}a(Se,"finding");function Lu(e,t){let n=[],r=[],o=[],s=[];for(let i of e)i.file===t&&(n.push(...i.uses),r.push(...i.reactsTo),o.push(...i.raises),s.push(...i.sends));return{uses:new Set(n),reactsTo:new Set(r),raises:new Set(o),sends:new Set(s)}}a(Lu,"bagForFile");function Aa(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}a(Aa,"emitKinds");function ka(e){return e==="subscribe"||e==="register-handler"}a(ka,"handleKinds");function Du(e){return e==="resolve"||e==="resolve-singleton"}a(Du,"dependKinds");function Fu(e,t,n){let r=[],o=e.kernelRoots??e.compositionRoots;if(o.length===0)return r.push(Se(e,"arkrun-missing-root","ark.config.json",1,"ArkRun kernelRoots is empty; no createArkKernel factory site is declared.",void 0,n)),r;let s=new Map;for(let i of t){let l=s.get(i.matchedRoot)??[];l.push(i),s.set(i.matchedRoot,l)}for(let i of o){let l=[...s.get(i)??[]].sort((u,f)=>u.file.localeCompare(f.file));if(l.length===0){r.push(Se(e,"arkrun-missing-root","ark.config.json",1,`ArkRun kernel root ${JSON.stringify(i)} matched no governed files and has no createArkKernel factory.`,{target:i},n));continue}if(l.some(u=>u.hasKernelFactory))continue;let c=l[0];r.push(Se(e,"arkrun-missing-root",c.file,1,`ArkRun kernel root ${JSON.stringify(i)} has no createArkKernel / createStrictArkKernel factory.`,{target:i},n))}return r}a(Fu,"evaluateMissingRoot");function $u(e,t,n,r,o){let s=new Map(t.map(l=>[l.name,l.intentPrefixes??[]])),i=[];for(let l of n){let c=l.specifier;if(!c||!ya(c))continue;let u=r(l.from);u&&Ia(u,s.get(u)??[])&&i.push(Se(e,"arkrun-kernel-in-domain",l.from,l.line,`${u} must not import kernel module ${JSON.stringify(c)}.`,{fromLayer:u,target:c},o))}return i}a($u,"evaluateKernelInDomain");function Mu(e,t,n,r,o,s){let i=new Set(e.managedLayers);if(i.size===0)return[];let l=new Map(t.map(f=>[f.name,f.intentPrefixes??[]])),c=new Set(r.filter(f=>f.hasKernelFactory).map(f=>f.file)),u=[];for(let f of n){if(c.has(f.file))continue;let y=f.typeName;if(e.ignoreDirectNewForErrors!==!1&&(y.endsWith("Error")||y==="Error")||y.endsWith("DTO")||y.endsWith("VO"))continue;let p=o(f.file);!p||!i.has(p)||Ia(p,l.get(p)??[])||u.push(Se(e,"arkrun-direct-new",f.file,f.line,`${p} must not construct ${f.typeName} with new outside an ArkRun composition-root factory.`,{fromLayer:p,target:f.typeName},s))}return u}a(Mu,"evaluateDirectNew");function Hu(e,t,n,r,o){let s=[],i=[];if(e.requireDeclarations!==!0)return{findings:s,completenessReasons:i};let l=new Set(e.managedLayers);if(l.size===0)return{findings:s,completenessReasons:i};for(let c of t){if(!Aa(c.kind)&&!ka(c.kind)&&!Du(c.kind))continue;let u=r(c.file);if(!u||!l.has(u))continue;if(!c.nameLiteral){e.mode==="enforced"&&i.push({code:Tu,file:c.file,message:`ArkRun ${c.kind} call in ${c.file} has no string-literal name; enforced extra cannot prove the declaration.`});continue}let f=Lu(n,c.file);if(Aa(c.kind)){if(f.raises.has(c.nameLiteral)||f.sends.has(c.nameLiteral))continue;s.push(Se(e,"arkrun-undeclared-emit",c.file,c.line,`Emit ${JSON.stringify(c.nameLiteral)} is not declared in raises or sends.`,{fromLayer:u,target:c.nameLiteral},o));continue}if(ka(c.kind)){if(f.reactsTo.has(c.nameLiteral))continue;s.push(Se(e,"arkrun-undeclared-handle",c.file,c.line,`Handle ${JSON.stringify(c.nameLiteral)} is not declared in reactsTo.`,{fromLayer:u,target:c.nameLiteral},o));continue}f.uses.has(c.nameLiteral)||s.push(Se(e,"arkrun-undeclared-depend",c.file,c.line,`Depend ${JSON.stringify(c.nameLiteral)} is not declared in uses.`,{fromLayer:u,target:c.nameLiteral},o))}return{findings:s,completenessReasons:i}}a(Hu,"evaluateUndeclared");function Ku(e,t,n,r){let o=new Set(e.managedLayers);if(o.size===0)return[];let s=[];for(let i of t){if(i.typeOnly)continue;let l=i.specifier;if(!l||!ha(l))continue;let c=n(i.from);!c||!o.has(c)||s.push(Se(e,"arkrun-transport-bypass",i.from,i.line,`${c} must not import broker/queue/emitter ${JSON.stringify(l)}; use the ArkRun kernel transport.`,{fromLayer:c,target:l},r))}return s}a(Ku,"evaluateTransportBypass");function ba(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=cr(e.classification),r=Hu(t,e.kernelCalls,e.declarations,e.layerForFile,n),o=[...Fu(t,e.compositionRootHits,n),...$u(t,e.layers,e.dependencies,e.layerForFile,n),...Mu(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...Ku(t,e.dependencies,e.layerForFile,n)].sort(Nu),s=[...r.completenessReasons].sort((i,l)=>{let c=`${i.code}\0${i.file??""}\0${i.message}`,u=`${l.code}\0${l.file??""}\0${l.message}`;return c<u?-1:c>u?1:0});return{findings:o,completenessReasons:s}}a(ba,"evaluateArkRunSensors");function Sa(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}a(Sa,"isArkOrderModuleSpecifier");var va=new Map;function Ea(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(Ea,"escapeAppliesToLiteral");function Gu(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}a(Gu,"normalizeAppliesToGlob");function Uu(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}a(Uu,"appliesToBracesBalanced");function Vu(e){let t=va.get(e);if(t)return t;let n=Gu(e),r=Uu(n),o="",s=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(o+=Ea(n[l+1]),l+=1):c==="*"?n[l+1]==="*"?n[l+2]==="/"?(o+="(?:.*/)?",l+=2):(o+=".*",l+=1):o+="[^/]*":c==="?"?o+="[^/]":c==="{"&&r?(o+="(?:",s+=1):c==="}"&&r&&s>0?(o+=")",s-=1):c===","&&r&&s>0?o+="|":o+=Ea(c)}let i=new RegExp(`^${o}$`);return va.set(e,i),i}a(Vu,"globToRegExp");var wa={"arkorder-missing-plane":"ARKORDER_MISSING_PLANE","arkorder-kernel-in-domain":"ARKORDER_KERNEL_IN_DOMAIN","arkorder-generic-update":"ARKORDER_GENERIC_UPDATE","arkorder-too-many-params":"ARKORDER_TOO_MANY_PARAMS","arkorder-ingest-writes-xi":"ARKORDER_INGEST_WRITES_XI","arkorder-xi-field-write":"ARKORDER_XI_FIELD_WRITE","arkorder-information-budget":"ARKORDER_INFORMATION_BUDGET","arkorder-xi-ttl":"ARKORDER_XI_TTL"};function ju(e,t){return!t||t.length===0?!0:t.some(n=>Vu(n).test(e))}a(ju,"matchesArkOrderAppliesTo");function Bu(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)?!0:t.some(r=>{let o=r.trim().replace(/\.+$/,"");return o==="Domain"||o.startsWith("Domain.")})}a(Bu,"isDomainRoleLayer");function Le(e,t,n,r,o,s,i){let l=e.mode==="enforced"&&i;return{ruleId:wa[t],sensor:t,message:o,file:n,line:r,...s?.fromLayer?{fromLayer:s.fromLayer}:{},...s?.target?{target:s.target}:{},severity:l?"error":"warning",failsStrict:l,nextAction:ye({ruleId:wa[t],fromLayer:s?.fromLayer,target:s?.target})}}a(Le,"finding");function Ca(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let n=cr(e.classification),r=[],o=t.planeRoots;if(t.mode==="enforced"&&o.length===0)r.push(Le(t,"arkorder-missing-plane","ark.config.json",1,"ArkOrder planeRoots is empty; no createOrderPlane site is declared.",void 0,n));else{let c=new Map;for(let u of e.planeRootHits){let f=c.get(u.matchedRoot)??[];f.push(u),c.set(u.matchedRoot,f)}for(let u of o){let f=c.get(u)??[];if(f.length===0){r.push(Le(t,"arkorder-missing-plane","ark.config.json",1,`ArkOrder plane root ${JSON.stringify(u)} matched no governed files and has no createOrderPlane factory.`,{target:u},n));continue}f.some(y=>y.hasPlaneFactory)||r.push(Le(t,"arkorder-missing-plane",f[0].file,1,`ArkOrder plane root ${JSON.stringify(u)} has no createOrderPlane factory.`,{target:u},n))}}let s=new Map(e.layers.map(c=>[c.name,c.intentPrefixes??[]]));for(let c of e.dependencies){let u=c.specifier;if(!u||!Sa(u))continue;let f=e.layerForFile(c.from);f&&Bu(f,s.get(f)??[])&&r.push(Le(t,"arkorder-kernel-in-domain",c.from,c.line,"Domain-role layer imports arkgate/order; Domain stays plane-free.",{fromLayer:f,target:u},n))}for(let c of e.genericUpdates)r.push(Le(t,"arkorder-generic-update",c.file,c.line,`Generic ${c.method}() on the order plane rewrites \u03BE; Haken forbids it.`,{target:c.method},n));let i=t.xiKeys??[];for(let c of e.releaseKeyCounts??[])c.keyCount<=t.maxXiKeys||r.push(Le(t,"arkorder-too-many-params",c.file,c.line,`release() freezes ${c.keyCount} keys; maxXiKeys is ${t.maxXiKeys} (few slow modes).`,{target:String(c.keyCount)},n));for(let c of e.ingestWritesXi??[])r.push(Le(t,"arkorder-ingest-writes-xi",c.file,c.line,"ingest() result is assigned into a Release or \u03BE store; ingest may absorb or escalate, never mint a pattern.",void 0,n));let l=new Set(t.managedLayers);for(let c of i.length===0?[]:e.xiFieldWrites??[]){let u=e.layerForFile(c.file);!u||!l.has(u)||ju(c.file,t.appliesTo)&&r.push(Le(t,"arkorder-xi-field-write",c.file,c.line,`This file writes ${JSON.stringify(c.key)} the same way it would write a seat count. Take the event in, or change that choice through the valve (propose, then apply).`,{fromLayer:u,target:c.key},n))}return r.sort((c,u)=>c.file.localeCompare(u.file)||c.ruleId.localeCompare(u.ruleId)||c.line-u.line),{findings:r,completenessReasons:[]}}a(Ca,"evaluateArkOrderSensors");function J(e,t,n={}){return{ruleId:e,message:t,...n}}a(J,"configWarning");function dr(e){let{config:t,rules:n,files:r,manifest:o}=e,s=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(d=>typeof d!="string"))&&s.push(J("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","dynamicImportAllowlist must be an array of file globs.")),t.safety!==void 0&&(t.safety===null||typeof t.safety!="object"||Array.isArray(t.safety)))s.push(J("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let d of["maxTsSuppressions","maxAnyCasts"]){let m=t.safety[d];m!==void 0&&(!Number.isInteger(m)||m<0)&&s.push(J("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${d} must be a non-negative integer.`))}let i=Array.isArray(t.layers)?t.layers:[],l=Array.isArray(o?.architecture?.layers)?o.architecture.layers:[],c=new Set([...i.map(d=>d.name).filter(Boolean),...l.map(d=>d.name).filter(d=>!!d)]);i.length===0&&s.push(J("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let u=new Set,f=new Set;for(let d of i){if(!d.name){s.push(J("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}u.has(d.name)&&f.add(d.name),u.add(d.name),d.forbiddenGlobals!==void 0&&(!Array.isArray(d.forbiddenGlobals)||d.forbiddenGlobals.some(b=>typeof b!="string"))&&s.push(J("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${d.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:d.name}));let m=Array.isArray(d.patterns)?d.patterns:[];if(m.length===0){s.push(J("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${d.name}" has no file patterns and will never classify files.`,{layer:d.name}));continue}for(let b of m){let v;try{v=he(b)}catch(E){s.push(J("CONFIG_INVALID_LAYER_PATTERN",`Layer "${d.name}" has an invalid pattern "${b}": ${E instanceof Error?E.message:String(E)}`,{layer:d.name,pattern:b}));continue}let k=d.optional===!0||d.reserved===!0||d.allowEmpty===!0;!r.some(E=>v.test(E))&&!k&&s.push(J("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${d.name}" pattern "${b}" matched no included files (possible typo). Mark the layer reserved/allowEmpty if this house is reserved for later.`,{layer:d.name,pattern:b,failsStrict:!1,reserved:!1}))}}for(let d of f)s.push(J("CONFIG_DUPLICATE_LAYER",`Layer "${d}" is configured more than once.`,{layer:d}));if(c.size>0)for(let d of n??[])d.from&&!c.has(d.from)&&s.push(J("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${d.from}".`,{fromLayer:d.from,toLayer:d.to})),d.to&&!c.has(d.to)&&s.push(J("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${d.to}".`,{fromLayer:d.from,toLayer:d.to}));let y=new Set;if(i.length>1)for(let d of r){let m=-1,b=[];for(let v of i)for(let k of v.patterns??[]){if(!he(k).test(d))continue;let E=Hr(k,d);E>m?(m=E,b=[v.name]):E===m&&!b.includes(v.name)&&b.push(v.name)}b.length>1&&y.add([...b].sort().join(" + "))}y.size>0&&s.push(J("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...y].join(", ")}.`,{pairs:[...y]}));let p=r.filter(d=>!fe(d,i));p.length>0&&s.push(J("CONFIG_UNCLASSIFIED_FILES",`${p.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:p.length,samples:p.slice(0,5)}));for(let d of vs(n))s.push(J("CONFIG_SLICE_IDENTITY_COLLISION",d.message,{paths:[...d.paths],fromLayer:d.from,toLayer:d.to,failsStrict:!1}));for(let d of Cs(n,r))s.push(J(d.ruleId,d.message,{failsStrict:!1,...d.path?{file:d.path}:{},...d.fromLayer?{fromLayer:d.fromLayer}:{},...d.toLayer?{toLayer:d.toLayer}:{}}));let g=ii(t);if(g.length>0){let d=g[0]??"this layer";s.push(J("CONFIG_LAYER_MISSING_OWNER",`${d} has no owner. Add a GitHub handle or email to layers[].owners so this house has a name on the door.`,{layers:g,nextAction:ai(d)}))}return s}a(dr,"collectAnalysisConfigWarnings");function xa(e,t){let n=e.ruleId==="ARKRULE_STRUCTURE",r=e.ruleId==="ARKRULE_SCOPE_EMPTY",o=e.ruleId==="INVARIANT_CATALOG_EMPTY";return{ruleId:e.ruleId,file:e.file,line:e.line,message:e.message,fromLayer:e.fromLayer,arkruleId:e.arkruleId,arkruleSource:e.arkruleSource,...n?{sensor:e.sensor,code:e.code,target:na({sensor:e.sensor,code:e.code})}:{},...r||o?{freezable:!1}:{},nextAction:t}}a(xa,"toArkRuleEngineViolation");function Wu(e){let t=e.arkRules;return!!(t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0)}a(Wu,"arkRulesMapIsOn");function Oa(e,t){return e.ruleId==="INVARIANT_CATALOG_EMPTY"?t?`Add 1\u20132 short phrases to invariants[] in ${e.arkruleSource} so Domain has policies the code must preserve (advisory \u2014 does not fail the merge until a domain structure rule is enforced).`:`Add 1\u20132 short phrases to invariants[] in ${e.arkruleSource} so Domain has policies the code must preserve. Empty catalog fails --strict-merge because a domain structure rule is already enforced.`:e.ruleId==="ARKRULE_SCOPE_EMPTY"?t?`Review appliesTo for ${e.arkruleId} in ${e.arkruleSource} (zero-match scope; advisory). Empty scope is not freezable; promote only after the folder exists.`:`Fix appliesTo globs for ${e.arkruleId} in ${e.arkruleSource} so they match governed files, or remove the rule. ARKRULE_SCOPE_EMPTY is a config diagnostic and is not freezable (even with --force). Land the rule as advisory until the folder exists, then promote.`:t?`Review ArkRule ${e.arkruleId} in ${e.arkruleSource} (advisory).`:`Fix the structure or invariant for ${e.arkruleId} (declared in ${e.arkruleSource}), then preflight again.`}a(Oa,"arkRuleFindingNextAction");function zu(e,t){return t.some(n=>{try{return he(n).test(e)}catch{return!1}})}a(zu,"matchesAny");function qu(e,t){let n=e.contract.config.safety??{},r=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,o=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,s=e.contract.config.dynamicImportAllowlist??[],i=t.safetyUses.filter(m=>m.kind==="ts-suppression").map(({file:m,line:b})=>({file:m,line:b})),l=t.safetyUses.filter(m=>m.kind==="any-cast").map(({file:m,line:b})=>({file:m,line:b})),c=t.safetyUses.filter(m=>(m.kind==="dynamic-import"||m.kind==="dynamic-require")&&!zu(m.file,s)).map(m=>({file:m.file,line:m.line,kind:m.kind==="dynamic-require"?"require":"import"})),u=n.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(m=>m.kind==="in-memory-store").map(m=>({file:m.file,line:m.line,store:m.symbol??"in-memory store"})),f=n.allowDisabledPeerIsolation===!0?[]:(e.contract.config.rules??[]).filter(m=>m.peerIsolation===!1||m.allowed===!1&&!!m.from&&m.from===m.to&&m.peerIsolation!==!0).map(m=>({from:m.from,to:m.to})),y={tsSuppressions:i,anyCasts:l,nonLiteralDynamicImports:c,inMemoryProductionStores:u,disabledPeerIsolationRules:f,thresholds:{maxTsSuppressions:r,maxAnyCasts:o}},p=[],g=c.filter(m=>m.kind==="import");if(g.length>0){let m=g[0];p.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:m.file,line:m.line,message:`${g.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let d=c.filter(m=>m.kind==="require");if(d.length>0){let m=d[0];p.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:m.file,line:m.line,message:`${d.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(i.length>r){let m=i[0];p.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:m.file,line:m.line,message:`${i.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${r}).`})}if(l.length>o){let m=l[0];p.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:m.file,line:m.line,message:`${l.length} explicit any cast(s) exceed safety.maxAnyCasts (${o}).`})}if(u.length>0){let m=u[0];p.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:m.file,line:m.line,message:`${u.length} ArkGate InMemory store risk(s) appear in governed production source. Provide durable stores or set safety.allowInMemory only for an explicitly ephemeral service.`})}return f.length>0&&p.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${f.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:y,warnings:p}}a(qu,"evaluateSafety");function Yu(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}a(Yu,"ambientForbiddenGlobal");function Pa(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return oo(e,n.length>0?n:ro.map(r=>({name:r.layer,prefixes:r.prefixes})))}a(Pa,"intentLayer");function Xu(e,t,n){let r=[],o=new Map(e.contract.config.layers.map(s=>[s.name,s]));for(let s of t.ambientUses){let i=n.get(s.file);!i||!Yu(s.symbol,o.get(i)?.forbiddenGlobals??[])||r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:i,target:s.symbol,message:`${i} must not use the ambient global "${s.symbol}".`})}for(let s of t.capabilityUses){let i=n.get(s.file);if(!i)continue;let l=o.get(i),c=l?.forbiddenGlobals??[],u=s.source==="import-based"?t.dependencies.find(f=>f.from===s.file&&f.line===s.line&&f.specifier===s.symbol&&!f.typeOnly)?.kind:void 0;if(!(s.source==="ambient-global"&&Wt(s.symbol,c))){if(s.source==="import-based"){let f=_e(s.symbol,c);if(f){r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:i,target:s.symbol,...u?{edgeKind:u}:{},message:`${i} must not use module "${s.symbol}" because it is the import form of forbidden global "${f}".`});continue}}gt(l).includes(s.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:s.file,line:s.line,fromLayer:i,target:s.symbol,capability:s.capability,...u?{edgeKind:u}:{},message:s.source==="import-based"?`${i} denies the ${s.capability} capability; found import of "${s.symbol}".`:`${i} denies the ${s.capability} capability; found ambient "${s.symbol}".`})}}for(let s of t.publishCalls){let i=n.get(s.file);if(!i)continue;for(let c of zt({publishCall:!0,rawIntentName:s.rawIntentName,objectHasIntent:s.objectHasIntent,arkPublishCandidate:s.arkPublishCandidate,hasSource:s.hasSource}))r.push({ruleId:c.ruleId,file:s.file,line:s.line,...c.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:i}:{},message:c.message});if(!s.sourceIntent)continue;let l=Pa(s.sourceIntent,e.contract);!l||l===i||r.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:s.file,line:s.line,fromLayer:i,toLayer:l,target:s.sourceIntent,message:`Publish source "${s.sourceIntent}" resolves to ${l}, but the publishing file is classified as ${i}.`})}for(let s of t.intentReferences){let i=n.get(s.file);if(!i)continue;let l=Pa(s.intent,e.contract);if(!l)continue;let c=Pe(e.contract.config.rules,i,l,{fromPath:s.file,layers:e.contract.config.layers});if(!c)continue;let u=c.sliceVerdict,f=`${i} must not reference ${l} intent ${s.intent}.`,y=u?lt({surface:"intent",verdict:u,fromLayer:i,toLayer:l,fromPath:s.file,ruleMessage:c.rule.message,defaultMessage:f}):c.rule.message??f;r.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:s.file,line:s.line,fromLayer:i,toLayer:l,target:s.intent,...c.rule.peerIsolation?{peerIsolation:!0}:{},...He(u),message:y})}return r}a(Xu,"contentViolations");function Zu(e){let{facts:t}=e,n=Zt(e.contract.config),r=t.evidenceRequirementsHash===n,o=r?t.completeness:"unavailable",s=r?t.completenessReasons:[...t.completenessReasons,{code:"EVIDENCE_REQUIREMENTS_MISMATCH",message:"Resolved facts were collected for different policy-controlled evidence requirements."}].sort((R,re)=>{let _t=`${R.code}\0${R.file??""}\0${R.message}`,Tt=`${re.code}\0${re.file??""}\0${re.message}`;return _t<Tt?-1:_t>Tt?1:0}),i=t.files.map(R=>({...R,layer:fe(R.path,e.contract.config.layers)??null})),l=new Map(i.map(R=>[R.path,R.layer])),c=t.dependencies.map(R=>{let re=R.target?l.get(R.target)??fe(R.target,e.contract.config.layers):void 0;return{from:R.from,fromLayer:l.get(R.from)??null,...R.resolution==="resolved-project"&&R.target?{to:R.target,...re?{toLayer:re}:{}}:{},line:R.line,kind:R.kind,typeOnly:R.typeOnly,...R.targetTypeOnlyExports?{targetTypeOnlyExports:R.targetTypeOnlyExports}:{},...R.sourcePureTypeModule?{sourcePureTypeModule:R.sourcePureTypeModule}:{},...R.namedBindingsTypeOnly?{namedBindingsTypeOnly:R.namedBindingsTypeOnly}:{},...R.portProofEligible?{portProofEligible:R.portProofEligible}:{}}}),u=dr({config:e.contract.config,rules:e.contract.config.rules,files:i.map(R=>R.path)}),f=qu(e,t),y=e.contract.arkRules??Qt(),p=i.map(R=>R.path),d={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?ga(e.coverageInputs.fileContents):{},...e.fileHints??{}},m=a(R=>l.get(R)??fe(R,e.contract.config.layers),"resolveLayer"),b=[...ua({arkRules:y,classShapes:e.contract.classShapes??t.classShapes??[],files:p,layerForFile:m,fileHints:d}),...pa(y,p),...fa({arkRulesActive:Wu(e.contract.config),arkRules:y,layers:e.contract.config.layers??[],files:p.map(R=>({path:R,layer:m(R)}))})],v=(y.invariants?.length??0)>0,k=Hi({hasEnforcedInvariant:ho(y.invariants),coverage:e.contract.config.coverage,...e.coverageRootsPresent===!1?{declaredPathPresent:!1}:{}}),E=k.length>0?[]:Mi({adopted:e.adopted===!0,hasDomainInvariants:yo(y.invariants),coverage:e.contract.config.coverage,...e.invariantTestsPathPresent===!1?{declaredPathPresent:!1}:{}}),O=[...k.map(R=>({ruleId:R.ruleId,file:R.file,line:R.line,message:R.message,nextAction:"Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. An enforced invariant fails closed until that path is present.",failsStrict:!0,freezable:!1})),...E.map(R=>({ruleId:R.ruleId,file:R.file,line:R.line,message:R.message,nextAction:"Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present.",failsStrict:!0,freezable:!1}))],L=b.filter(R=>R.failsStrict).map(R=>xa(R,Oa(R,!1))),S=b.filter(R=>!R.failsStrict).map(R=>({...xa(R,Oa(R,!0)),failsStrict:!1})),N=v?Fi({arkRules:y,fileContents:e.coverageInputs?.fileContents??{},testFiles:e.coverageInputs?.testFiles??[],testGlobsMissing:e.coverageInputs?.testGlobsMissing===!0||e.coverageInputs===void 0||(e.coverageInputs.testFiles?.length??0)===0,coverageBudgetExhausted:e.coverageInputs?.coverageBudgetExhausted===!0,...e.coverageInputs?.stats?{coverageStats:e.coverageInputs.stats}:{},...e.coverageInputs?.coverageRoots?{coverageRoots:e.coverageInputs.coverageRoots}:{}}):{coverage:[],violations:[],partial:!1},z=N.violations.filter(R=>R.failsStrict).map(R=>({ruleId:R.ruleId,file:R.file,line:R.line,message:R.message,fromLayer:R.fromLayer,arkruleId:R.arkruleId,arkruleSource:R.arkruleSource,nextAction:`Add a test title or declared symbol covering ${R.arkruleId} (declared in ${R.arkruleSource}), then preflight again.`})),Q=N.violations.filter(R=>!R.failsStrict).map(R=>({ruleId:R.ruleId,file:R.file,line:R.line,message:R.message,fromLayer:R.fromLayer,arkruleId:R.arkruleId,arkruleSource:R.arkruleSource,failsStrict:!1,nextAction:R.ruleId==="INVARIANT_COVERAGE_OUTSIDE_ROOTS"?`Move ${R.file} under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json.`:`Cover invariant ${R.arkruleId} in ${R.arkruleSource} (advisory / partial).`})),pe=ma(i),T=ba({arkRun:e.contract.config.arkRun,layers:e.contract.config.layers,kernelCalls:t.arkRunKernelCalls,managedNews:t.arkRunManagedNews,compositionRootHits:t.arkRunCompositionRootHits,declarations:t.arkRunDeclarations,dependencies:t.dependencies,layerForFile:a(R=>l.get(R)??fe(R,e.contract.config.layers),"layerForFile"),classification:pe}),Y=e.contract.config.arkRun?.mode,X=T.findings.filter(()=>Y==="enforced").map(R=>({ruleId:R.ruleId,file:R.file,line:R.line,message:R.message,fromLayer:R.fromLayer,target:R.target,nextAction:R.nextAction,sensor:R.sensor,failsStrict:R.failsStrict,...R.severity?{severity:R.severity}:{}})),Ae=T.findings.filter(()=>Y!=="enforced").map(R=>({ruleId:R.ruleId,file:R.file,line:R.line,message:R.message,fromLayer:R.fromLayer,target:R.target,nextAction:R.nextAction,sensor:R.sensor,failsStrict:!1})),we=Ca({arkOrder:e.contract.config.arkOrder,layers:e.contract.config.layers,planeCalls:t.arkOrderPlaneCalls,genericUpdates:t.arkOrderGenericUpdates,planeRootHits:t.arkOrderRootHits,xiFieldWrites:t.arkOrderXiFieldWrites,ingestWritesXi:t.arkOrderIngestWritesXi,releaseKeyCounts:t.arkOrderReleaseKeyCounts,dependencies:t.dependencies,layerForFile:a(R=>l.get(R)??fe(R,e.contract.config.layers),"layerForFile"),classification:pe}),Pt=e.contract.config.arkOrder?.mode,En=we.findings.filter(()=>Pt==="enforced").map(R=>({ruleId:R.ruleId,file:R.file,line:R.line,message:R.message,fromLayer:R.fromLayer,target:R.target,nextAction:R.nextAction,sensor:R.sensor,failsStrict:R.failsStrict,...R.severity?{severity:R.severity}:{}})),rs=we.findings.filter(()=>Pt!=="enforced").map(R=>({ruleId:R.ruleId,file:R.file,line:R.line,message:R.message,fromLayer:R.fromLayer,target:R.target,nextAction:R.nextAction,sensor:R.sensor,failsStrict:!1})),w=[...N.partial&&N.coverage.some(R=>R.mode==="enforced"&&R.partial)?[{code:"INVARIANT_COVERAGE_PARTIAL",message:"Enforced ArkRules invariant coverage cannot be fully proven (missing test globs or empty test set); reporting partial, never covered."}]:[],...T.completenessReasons,...we.completenessReasons],x=St({config:e.contract.config,rules:e.contract.config.rules,files:i.filter(R=>R.layer).map(R=>R.path),contentViolations:[...Xu(e,t,l),...L,...O,...z,...X,...En],edges:c,warnings:[...u,...f.warnings,...S,...Q,...Ae,...rs],safety:f.report}),h=o==="complete"&&w.length>0?"partial":o,A=h==="complete"?s:[...s,...w].sort((R,re)=>{let _t=`${R.code}\0${R.file??""}\0${R.message}`,Tt=`${re.code}\0${re.file??""}\0${re.message}`;return _t<Tt?-1:_t>Tt?1:0}),D=x.violations.filter(R=>R.failsStrict!==!1),q=h==="complete"&&D.length===0,Ce=q&&x.warnings.every(R=>R.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:h,completenessReasons:A,valid:q,strictValid:Ce,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:f.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:i,layers:e.contract.config.layers.map(R=>R.name),edges:c,capabilityUses:t.capabilityUses,violations:x.violations,warnings:x.warnings}}}a(Zu,"analyzeCanonicalResolvedProject");function rn(e){return Zu({contract:e.contract,facts:Te(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints,adopted:e.adopted,invariantTestsPathPresent:e.invariantTestsPathPresent,coverageRootsPresent:e.coverageRootsPresent})}a(rn,"analyzeResolvedProject");function _a(e){return Z(M(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}a(_a,"analysisTreeHash");function Ta(e){let t=nn(e),n=new Map(t.ir.files.map(d=>[d.path,d])),r=[],o=new Set,s=[];for(let d of e.changes){let m=d.path.replace(/\\/g,"/"),b=We(d.path);if(!b||b===".."||b.startsWith("../")||m.startsWith("/")||/^[A-Za-z]:\//.test(m)||m.includes("\0")){s.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(o.has(b)){s.push({ruleId:"DUPLICATE_CHANGE_PATH",file:b,line:1,message:`The atomic change set contains more than one operation for ${b}.`});continue}o.add(b),"delete"in d&&d.delete&&!n.has(b)&&s.push({ruleId:"DELETE_TARGET_MISSING",file:b,line:1,message:`Cannot delete ${b} because it is not present in the supplied base tree.`}),r.push("delete"in d&&d.delete?{path:b,delete:!0}:{path:b,content:"content"in d?d.content:""})}e.changes.length===0&&s.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let i=ir({...e,changes:r}),l=new Map(i.ir.files.map(d=>[d.path,d])),c=i.ir.violations.filter(d=>d.ruleId==="CAPABILITY_VIOLATION"||d.ruleId==="FORBIDDEN_GLOBAL").map(d=>{let m=l.get(d.evidence.file)?.layer;return{ruleId:d.ruleId,file:d.evidence.file,line:d.evidence.line,target:d.symbol,...d.capability?{capability:d.capability}:{},...m?{fromLayer:m}:{},edgeKind:"import",message:d.message}}),u=St({config:e.contract.config,rules:e.contract.config.rules,files:i.ir.files.map(d=>d.path),contentViolations:c,edges:i.ir.edges.filter(d=>!!d.fromLayer).map(d=>({from:d.from,fromLayer:d.fromLayer,...d.to?{to:d.to}:{},...d.toLayer?{toLayer:d.toLayer}:{},line:d.evidence.line,kind:"import",...d.typeOnly?{typeOnly:!0}:{},...d.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),f=r.map(d=>{let m=We(d.path),b=n.get(m),v=l.get(m);return{path:m,operation:"delete"in d&&d.delete?"delete":b?"update":"create",...b?{beforeContentHash:b.contentHash}:{},...v?{candidateContentHash:v.contentHash}:{}}}).sort((d,m)=>d.path.localeCompare(m.path)),y=[...s,...u.violations].map(d=>({...d,nextAction:ye(d)})),p=y.filter(d=>d.failsStrict!==!1),g=e.changeMap?kt({changeMap:e.changeMap,changes:f,baseDependencies:t.ir.edges.flatMap(d=>d.to?[{from:d.from,to:d.to}]:[]),candidateDependencies:i.ir.edges.flatMap(d=>d.to?[{from:d.from,to:d.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&i.valid&&p.length===0&&(g?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:i.ir.compilerOptionsHash,baseTreeHash:_a(t.ir.files),candidateTreeHash:_a(i.ir.files),baseCompleteness:t.completeness,candidateCompleteness:i.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:i.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...g?{convergence:g}:{},changes:f,violations:y,warnings:u.warnings}}a(Ta,"preflightChange");function Ju(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let o of t.split("/"))if(!(!o||o==="."))if(o===".."){if(n.length===0)return;n.pop()}else n.push(o);let r=n.join("/");return r&&r===t?r:void 0}a(Ju,"canonicalChangePath");function Qu(e,t){return[["resolverIdentity",e.resolverIdentity,t.resolverIdentity],["compilerIdentity",e.compilerIdentity,t.compilerIdentity],["evidenceRequirementsHash",e.evidenceRequirementsHash,t.evidenceRequirementsHash],["projectPackageName",e.projectPackageName??"",t.projectPackageName??""]].filter(([,r,o])=>r!==o).map(([r,o,s])=>({ruleId:"FACTS_IDENTITY_MISMATCH",file:"<change-set>",line:1,field:r,before:o,candidate:s,message:`Base and candidate facts must use the same ${r}.`}))}a(Qu,"identityViolations");function ep(e,t,n,r){let o=n.get(t),s=r.get(t);return{path:t,operation:"delete"in e&&e.delete?"delete":o?"update":"create",...o?{beforeContentHash:o.contentHash}:{},...s?{candidateContentHash:s.contentHash}:{}}}a(ep,"preparedChange");function Na(e){let t=Te(e.baseFacts),n=Te(e.candidateFacts),r=rn({contract:e.contract,facts:t}),o=rn({contract:e.contract,facts:n}),s=new Map(t.files.map(g=>[g.path,g])),i=new Map(n.files.map(g=>[g.path,g])),l=Qu(t,n),c=new Map,u=[];for(let g of e.changes){let d=Ju(g.path);if(!d){l.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(c.has(d)){l.push({ruleId:"DUPLICATE_CHANGE_PATH",file:d,line:1,message:`The atomic change set contains more than one operation for ${d}.`});continue}c.set(d,g);let m=s.get(d),b=i.get(d);if("delete"in g&&g.delete)m||l.push({ruleId:"DELETE_TARGET_MISSING",file:d,line:1,message:`Cannot delete ${d} because it is not present in the supplied base facts.`}),b&&l.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:d,line:1,message:`Candidate facts still contain deleted file ${d}.`});else{let v="content"in g?g.content:"",k=Z(v);b?b.contentHash!==k&&l.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:d,line:1,expectedContentHash:k,candidateContentHash:b.contentHash,message:`Candidate facts for ${d} do not match the declared content.`}):l.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:d,line:1,message:`Candidate facts do not contain changed file ${d}.`})}u.push(ep(g,d,s,i))}e.changes.length===0&&l.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});for(let g of new Set([...s.keys(),...i.keys()])){if(c.has(g))continue;let d=s.get(g),m=i.get(g);d&&m&&M(d)===M(m)||l.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:g,line:1,message:`Candidate facts change ${g}, but the atomic change set does not declare it.`})}let f=e.changeMap?kt({changeMap:e.changeMap,changes:u,baseDependencies:r.ir.edges.flatMap(g=>g.to?[{from:g.from,to:g.to}]:[]),candidateDependencies:o.ir.edges.flatMap(g=>g.to?[{from:g.from,to:g.to}]:[])}):void 0,y=[...l,...o.ir.violations].map(g=>({...g,nextAction:ye(g)})),p=y.filter(g=>g.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&o.strictValid&&p.length===0&&(f?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,resolverIdentity:n.resolverIdentity,compilerIdentity:n.compilerIdentity,compilerOptionsHash:n.compilerOptionsHash,tsconfigHash:n.tsconfigHash,baseCompilerOptionsHash:t.compilerOptionsHash,candidateCompilerOptionsHash:n.compilerOptionsHash,baseTsconfigHash:t.tsconfigHash,candidateTsconfigHash:n.tsconfigHash,evidenceRequirementsHash:n.evidenceRequirementsHash,baseFactsHash:t.factsHash,candidateFactsHash:n.factsHash,baseTreeHash:t.candidateTreeHash,candidateTreeHash:n.candidateTreeHash,baseCompleteness:r.completeness,candidateCompleteness:o.completeness,baseCompletenessReasons:r.completenessReasons,candidateCompletenessReasons:o.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...f?{convergence:f}:{},changes:u.sort((g,d)=>g.path<d.path?-1:g.path>d.path?1:0),violations:y,warnings:o.ir.warnings}}a(Na,"preflightResolvedChange");var Oo="docs/diagnostics.md",tp="1.0";function I(e,t,n,r,o,s){return{ruleId:e,title:n,why:r,fix:o,docsAnchor:e,category:t,...s?.oftenAdvisory?{oftenAdvisory:!0}:{}}}a(I,"entry");var ur=Object.freeze([I("LAYER_IMPORT_VIOLATION","layer","This import is not allowed","This file imported a folder it may not reach. The write doesn\u2019t land. The same check fails the pull request.","Branch by import kind: constants/types/pure \u2192 adopt into DomainModel or SharedKernel (do not invent a port); kernel/events/bootstrap from Persistence \u2192 inject a port or move the map to SharedTypes (Persistence must not emit); define a port only when the target is a real use-case. Type-only edges use `import type`. Then preflight again. Do not weaken the layer rule without a hash-bound policy acknowledgement."),I("LAYER_INTENT_REFERENCE_VIOLATION","layer","Intent referenced across a blocked layer edge","A string intent (or intent-like reference) names a layer that the file\u2019s layer may not reach under the contract rules \u2014 the same plane as import edges, for event/intent coupling.","Reference that intent from a layer allowed to know about it (usually an adapter or application layer), or relocate the reference \u2014 then preflight again."),I("LAYER_REFERENCE_VIOLATION","layer","Layer reference blocked (snippet / AI gate)","Snippet analysis found an intent or string reference that would couple layers in a direction the architecture profile forbids.","Move the reference to an allowed layer or introduce a port/event boundary, then re-run the snippet gate."),I("CIRCULAR_DEPENDENCY","layer","Dependency cycle","Two or more modules import each other in a loop. Cycles make ownership unclear and break stable layer direction.","Extract the shared dependency into a third module, invert one edge behind a port, or merge units that are truly one \u2014 then preflight again."),I("FORBIDDEN_GLOBAL","capability","Forbidden ambient global or dual import","The file\u2019s layer lists this ambient (or its exact import dual, e.g. process / node:process) in forbiddenGlobals. Pure layers must not reach wall-clock, network, process, or similar effects directly.","Inject the capability through a small port (Clock, HttpPort, Config, \u2026), bind the implementation outside the walled layer, then preflight again."),I("CAPABILITY_VIOLATION","capability","Denied effect capability","The layer denies an effect capability (network, filesystem, clock, randomness, environment, process, persistence) and the candidate uses that effect via ambient or import evidence.","Define a capability port in the walled layer, bind the implementation in an adapter layer, then preflight again. Never mechanical-safe \u2014 port shape is a design decision."),I("RAW_EVENT_PUBLISH","publish","Raw event publish","Publish went through a raw string or object instead of a registered intent creator, bypassing Ark intent contracts and tooling.","Publish through a registered intent creator, then run Ark again."),I("PUBLISH_MISSING_SOURCE","publish","Publish missing metadata.source","A strict Ark publish call omitted metadata.source, so the publishing layer cannot be verified.","Add metadata.source to the publish call, then run Ark again."),I("PUBLISH_SOURCE_LAYER_MISMATCH","publish","Publish source layer mismatch","metadata.source resolves to a different layer than the file performing the publish.","Use a source intent owned by the same layer as this file, or move the publish call to the owning layer."),I("UNKNOWN_INTENT","publish","Unknown intent reference","Snippet analysis saw an intent string that is not registered in the intent registry / profile under check.","Register the intent or use a known intent name from the project registry, then re-run the gate."),I("DYNAMIC_IMPORT_NOT_ALLOWLISTED","safety","Non-literal dynamic import","A dynamic import(expr) cannot be resolved statically and the file is not on dynamicImportAllowlist. Unresolved dynamics can hide layer edges.","Rewrite to a static import when possible, or add only reviewed files to dynamicImportAllowlist after human sign-off."),I("DYNAMIC_REQUIRE_NOT_ALLOWLISTED","safety","Non-literal require","A require(expr) cannot be resolved statically and is not allowlisted \u2014 same hide-the-edge risk as dynamic import.","Prefer static import, or allowlist only reviewed files after sign-off."),I("TS_SUPPRESSION_THRESHOLD_EXCEEDED","safety","@ts-ignore / @ts-nocheck threshold","Count of TypeScript suppressions in governed production source exceeds safety.maxTsSuppressions.","Remove suppressions by fixing types, or raise the threshold only with an explicit production exception in ark.config.json."),I("ANY_CAST_THRESHOLD_EXCEEDED","safety","Explicit any cast threshold","Count of explicit any casts exceeds safety.maxAnyCasts.","Replace any with precise types, or raise the threshold only with a documented exception."),I("IN_MEMORY_STORE_IN_PRODUCTION_SOURCE","safety","In-memory store in production source","Governed production source references an Ark InMemory* store without safety.allowInMemory \u2014 durable systems should not ship ephemeral stores by accident.","Provide a durable store implementation, or set safety.allowInMemory only for an explicitly ephemeral service."),I("PEER_ISOLATION_DISABLED","safety","peerIsolation disabled on a rule","A same-layer or peer rule disables peerIsolation (or omits it where required), which allows cross-slice coupling the contract otherwise blocks.","Restore peerIsolation: true, or set safety.allowDisabledPeerIsolation only with a documented production exception."),I("ARKRULE_STRUCTURE","arkrules","ArkRule structure sensor failed","An opt-in ArkRules structure sensor (private state, factory shape, event publish, persistence write outside an aggregate, \u2026) failed on a governed file for a declared arkruleId.","Restore the declared structure for the ArkRule (see arkruleSource), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement."),I("ARKRULE_INVARIANT","arkrules","ArkRule invariant failed","Reserved / remediation-recognized code for invariant-plane failures bound to an ArkRule id (coverage path also emits INVARIANT_UNCOVERED).","Fix the invariant for the ArkRule declared in arkrules/<Layer>.json, then preflight again. Do not demote without acknowledgement."),I("ARKRULE_SCOPE_EMPTY","arkrules","ArkRule appliesTo matched zero files","An ArkRule\u2019s appliesTo globs matched no governed files \u2014 the rule cannot observe what it claims to protect.","Fix appliesTo globs so they match governed files, or remove the rule. Enforced empty scope fails; advisory empty scope warns.",{oftenAdvisory:!0}),I("ARKRULE_HINT_BUDGET_EXHAUSTED","arkrules","Structural-hint budget exhausted","orchestration-only, thin-adapter, and writes-via-aggregate only evaluate files the hint loader preloaded. When eligible governed files exceed that budget (coverage.maxFiles, default 400 \u2014 there is no arkrules.hintBudget), those sensors never saw the rest of their scope. Enforced + unreviewed is not green. The finding names exact hinted/governed counts and per-sensor reviewed N/M of scope.","Raise coverage.maxFiles in ark.config.json (this cap also bounds structural-hint preload; --doctor names the coupling) so hinted/governed counts match, then re-run with --strict-config. An enforced hint sensor that cannot see its scope fails strict."),I("INVARIANT_CATALOG_EMPTY","arkrules","Domain invariant catalog is empty","ArkRules is on and a Domain-role layer has code, but invariants[] has no phrases the code must preserve. Empty looks like \u201Cdone\u201D until someone fills the catalog.","Add 1\u20132 short phrases to invariants[] in arkrules/<Domain>.json (or the mapped file). Starters show the shape. Advisory unless a domain structure rule is already enforced \u2014 then --strict-merge can refuse. Do not freeze this finding.",{oftenAdvisory:!0}),I("INVARIANT_UNCOVERED","arkrules","Invariant without coverage evidence","An ArkRules invariant is under contract but no covering test title or declared symbol evidence was found (or coverage is partial). Kind is never-had-tests (adopt residual) vs tests-disappeared (suite exists).","Add a test title or declared symbol covering the arkruleId, then preflight again. Treat never-had-tests as adopt residual; treat tests-disappeared as a regression. Missing test globs report partial \u2014 never fake green. When the message reports an exhausted file budget, raise coverage.maxFiles (or narrow coverage.testGlobs) in ark.config.json."),I("INVARIANT_COVERAGE_OUTSIDE_ROOTS","arkrules","Covering test outside the declared coverage roots","The only test naming this invariant sits outside coverage.coverageRoots \u2014 the places the project declares its runner executes. ArkGate matches declared text and never executes tests, so it cannot tell whether that file is ever run: coverage there is a test that exists, not a test that runs.","Move the test under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json. Advisory: it never fails strict, but promotion to enforced refuses on it.",{oftenAdvisory:!0}),I("INVARIANT_TESTS_PATH_MISSING","arkrules","Domain-invariant tests path missing under adopted","The project is adopted (required CI or explicit advisory) and has domain invariants that want test evidence, but ark.config.json does not name where those tests live. Green coverage without a real tests path is an empty checkbox.","Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present. Not freezable."),I("INVARIANT_COVERAGE_ROOTS_MISSING","arkrules","Coverage roots missing while an invariant is enforced","A catalogued domain invariant is enforced, but ark.config.json does not name coverage.coverageRoots \u2014 the folders where the project says its test runner actually goes. Without that declaration, INVARIANT_COVERAGE_OUTSIDE_ROOTS cannot fire and coverage can certify a test no runner runs.","Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. testGlobs alone is not enough. Fail-closed until that path is present. Not freezable."),I("ARKRUN_MISSING_ROOT","arkrun","No kernel factory in composition roots","The ArkRun extra is on but no createArkKernel / createStrictArkKernel / createArkKernelFromConfig / createStrictArkKernelFromConfig factory was found in arkRun.compositionRoots, so agents can skip the kernel while the write gate stays green.","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."),I("ARKRUN_KERNEL_IN_DOMAIN","arkrun","Domain-role layer imports the kernel","A Domain-role layer imports arkgate/runtime, @arkgate/runtime, or kernel types. Domain stays kernel-free; composition roots and adapters own the factory.","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."),I("ARKRUN_DIRECT_NEW","arkrun","Managed type constructed with new","A managed non-Domain file constructs an admitted type with new outside an ArkRun composition-root factory, skipping kernel resolve/registration.","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."),I("ARKRUN_UNDECLARED_EMIT","arkrun","Emit name not in raises/sends","A publisher / publish / raise / send call-site literal is not listed in the file\u2019s raises or sends declaration.","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."),I("ARKRUN_UNDECLARED_HANDLE","arkrun","Handle name not in reactsTo","A subscribe / registerHandler call-site literal is not listed in the file\u2019s reactsTo declaration.","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."),I("ARKRUN_UNDECLARED_DEPEND","arkrun","Depend name not in uses","A resolve / resolveSingleton call-site literal is not listed in the file\u2019s uses declaration.","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."),I("ARKRUN_TRANSPORT_BYPASS","arkrun","Homemade broker or emitter import","A managed layer imports a closed broker/queue/emitter specifier (EventEmitter, queue clients, \u2026) instead of the ArkRun kernel transport.","Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe \u2014 homemade buses stay judgment."),I("ARKORDER_MISSING_PLANE","arkorder","No createOrderPlane in plane roots","The ArkOrder extra is on but no createOrderPlane factory was found in arkOrder.planeRoots, so agents can skip the pattern plane while the write gate stays green.","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."),I("ARKORDER_KERNEL_IN_DOMAIN","arkorder","Domain-role layer imports the order plane","A Domain-role layer imports arkgate/order. Domain stays plane-free; planeRoots own the factory.","Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe."),I("ARKORDER_GENERIC_UPDATE","arkorder","Generic update of a big product choice","A call to update/patch/set rewrites a named product choice (like billing plan) as if it were a seat count.","Don't use a generic update. First freeze with release(). Later, propose the change, then apply it."),I("ARKORDER_TOO_MANY_PARAMS","arkorder","Too many slow keys","\u03BE has more keys than arkOrder.maxXiKeys. Haken requires a few slow modes, not a dump of microstate.","Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe."),I("ARKORDER_INGEST_WRITES_XI","arkorder","ingest assigned into \u03BE","An ingest() result is written into a Release or \u03BE store. ingest may absorb, escalate_up, or hold; it never mints a pattern.","Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe."),I("ARKORDER_XI_FIELD_WRITE","arkorder","Big product choice written like a seat count","A use-case writes a named product choice (like billing plan) through a database update. Invoices and seats can flow. That choice cannot.","Keep invoices and seats as events. Change the choice through the valve (proposeRelease then apply), not a generic update."),I("ARKORDER_INFORMATION_BUDGET","arkorder","Projection observes a forbidden kind","h(\u03BE) allowedKinds includes a kind listed in informationBudget.cannotObserve. A scale may not look at what it was told not to see.","Cut that kind from the projector or from cannotObserve, then preflight again. Never mechanical-safe."),I("ARKORDER_XI_TTL","arkorder","Slow key carries a freshness field","\u03BE named ttl/freshUntil/maxAge. Freshness belongs on \u03C3. A slow parameter that expires per transaction is not slow.","Move freshness onto \u03C3 (freshUntil) and keep \u03BE stable, then preflight again. Never mechanical-safe."),I("ARKORDER_STALE_SIGMA","arkorder","\u03C3 is stale","ingest ran after \u03C3.freshUntil (or sigmaMaxAgeMs). \u03BE does not TTL.","Call refreshSigma and ingest again, or proposeRelease then apply(ProposeResult) if the pattern changed. Never mechanical-safe."),I("ARKORDER_UNVALVED_RELEASE","arkorder","Second freeze without the valve","release() already froze the big choice. A later release() with a different value does not land. First freeze is release(); later change is proposeRelease then apply.","Change the choice with proposeRelease then apply. release() is only the first freeze. Never mechanical-safe."),I("INVALID_CHANGE_PATH","preflight","Unsafe change path","A change set entry is not a safe, non-empty project-relative path (absolute, escape, empty, or NUL).","Use canonical project-relative paths only in the atomic change set, then preflight again."),I("DUPLICATE_CHANGE_PATH","preflight","Duplicate path in change set","The atomic change set lists more than one operation for the same path.","Collapse to one create/update/delete per path, then preflight again."),I("DELETE_TARGET_MISSING","preflight","Delete target missing","A delete operation targets a path that is not present in the supplied base tree.","Remove the delete, or include the file in the base tree facts, then preflight again."),I("CHANGE_SET_EMPTY","preflight","Empty change set","Atomic preflight was invoked with no create, update, or delete operations.","Provide at least one change operation, then preflight again."),I("FACTS_IDENTITY_MISMATCH","preflight","Base/candidate facts identity mismatch","Base and candidate resolved facts disagree on resolver, compiler, evidence requirements, or package identity \u2014 verdicts would not be comparable.","Regenerate both fact snapshots with the same resolver/compiler/evidence requirements, then preflight again."),I("CANDIDATE_DELETE_NOT_APPLIED","preflight","Candidate still contains deleted path","Facts claim a delete, but the candidate tree still includes the path.","Ensure the candidate facts apply the delete (path absent), then preflight again."),I("CANDIDATE_CHANGE_MISSING","preflight","Declared change missing from candidate","The change set declares a create/update whose path is missing from candidate facts.","Include the new content in the candidate facts (or drop the operation), then preflight again."),I("CANDIDATE_CONTENT_HASH_MISMATCH","preflight","Candidate content hash mismatch","The candidate file content hash does not match the hash expected for the declared change.","Rebuild candidate facts from the exact proposed content, then preflight again."),I("UNDECLARED_CANDIDATE_CHANGE","preflight","Undeclared candidate change","Candidate facts differ from base for a path that was not listed in the explicit change set.","Declare every path that changes in the atomic change set, then preflight again."),I("ATOMIC_PREFLIGHT_UNAVAILABLE","preflight","Atomic preflight unavailable","The host/MCP path could not run the atomic preflight engine (missing facts, incomplete setup, or unsupported mode).","Use resolved-candidate facts / ark_prepare_change with a complete batch, or fall back to ark-check on disk. Do not treat missing preflight as green."),I("DESIGN_SMELL_REGRESSION","preflight","Design smell regression on base-relative ratchet","Compared to the base ref, the candidate introduces a created-path domain-logic-in-ui file under --strict-merge, or introduces or worsens a blocking design-smell class under --fail-on-new-smells.","Move the new UI business rule out of the created file (or revert a --fail-on-new-smells regression), then re-run with the same base ref."),I("ANALYSIS_PARSE_INCOMPLETE","analysis","Parse incomplete","Governed source could not be fully parsed; evidence includes the TypeScript diagnostic (line + message). Incremental mid-edit parse is normal for agents. Contract exclude paths skip the write hook.","Finish the source or fix the reported syntax error, then re-run `npx arkgate-check`. The write hook does not deny solely on mid-edit parse. Partial never means pass."),I("LEXICAL_EVIDENCE_INCOMPLETE","analysis","Lexical evidence incomplete","This check only saw one file, so it cannot fully prove how the import resolves. The result is provisional \u2014 `ark-check` on the project is the authority.","Run `npx arkgate-check --root . --config ark.config.json` to confirm. Do not call ark_prepare_change from a hook deny."),I("ANALYSIS_COVERS_NO_FILES","analysis","Analysis covered no files","No file matched the contract include and layer patterns under the analyzed root, so the run had nothing to check. Every rule is vacuously satisfied on an empty set: a green here would read exactly like a green over a governed tree while certifying nothing. Usual causes are a --root that is not the tree the contract describes (including a contract found outside the requested root, whose directory is then adopted as the project root), include / exclude patterns that match nothing, or layer patterns written for a different layout.","Point --root at the tree the contract describes, or keep the contract inside that tree, or fix the include / exclude / layer patterns so they match real files \u2014 then re-run `npx arkgate-check --root . --config ark.config.json`. This is a refusal about ArkGate\u2019s own inputs, not a finding about your code; no baseline or policy acknowledgement can suppress it."),I("ANALYSIS_HOST_UNAVAILABLE","analysis","Analysis host unavailable","No usable TypeScript / analysis host was available for this invocation.","Install a supported TypeScript version visible to the project, then re-run. Unavailable analysis is fail-closed."),I("ADAPTER_NOT_ALLOWED_FOR_PORT","adapter","Adapter not allowed for port","Runtime/port wiring selected an adapter implementation that the architecture profile does not allow for that port.","Bind an allowed adapter for the port, or adjust the profile with an explicit policy decision \u2014 then re-run."),I("FORBIDDEN_PATTERN","snippet-policy","Forbidden regex pattern","Snippet content matched a project or profile forbiddenPatterns rule.","Remove or rewrite the matching code so the pattern no longer matches, then re-run the snippet gate."),I("FORBIDDEN_SUBSTRING","snippet-policy","Forbidden substring","Snippet content contained a forbidden substring from the AI gate options/profile.","Remove the forbidden substring, then re-run the snippet gate."),I("FORBIDDEN_IMPORT","snippet-policy","Forbidden import target","Snippet imported or required a module listed as forbidden for the active profile.","Import an allowed module or inject the dependency behind a port, then re-run."),I("POLICY_VIOLATION","snippet-policy","Policy engine violation","A registered Policy failed on the snippet or generated code under evaluation.","Adjust the code to satisfy the named policy, or change the policy only through an explicit contract decision."),I("EXTENSION_ERROR","snippet-policy","AI gate extension error","A registered AICodeGate extension threw while analyzing the snippet.","Fix or remove the failing extension; do not ignore extension failures as pass."),I("AST_ANALYZER_ERROR","snippet-policy","AST analyzer error","Built-in AST/symbol analysis failed (host error or unexpected analyzer exception).","Ensure TypeScript host and snippet are valid; re-run. If the analyzer crashes on valid input, file a bug with a minimal fixture."),I("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","config","Invalid dynamicImportAllowlist","dynamicImportAllowlist is present but not an array of file globs.","Set dynamicImportAllowlist to an array of project-relative globs (or omit it).",{oftenAdvisory:!0}),I("CONFIG_INVALID_SAFETY","config","Invalid safety object","The safety field is present but not an object.","Use a safety object with optional maxTsSuppressions, maxAnyCasts, allowInMemory, allowDisabledPeerIsolation.",{oftenAdvisory:!0}),I("CONFIG_INVALID_SAFETY_THRESHOLD","config","Invalid safety threshold","A safety threshold (maxTsSuppressions / maxAnyCasts) is not a non-negative integer.","Set each threshold to a non-negative integer.",{oftenAdvisory:!0}),I("CONFIG_NO_LAYERS","config","No layers configured","ark.config.json has no file layers, so import-boundary enforcement cannot classify files.","Declare at least one layer with name + patterns (or run ark start / a preset).",{oftenAdvisory:!0}),I("CONFIG_LAYER_WITHOUT_NAME","config","Layer missing name","A configured layer entry has no name.","Give every layer a unique non-empty name.",{oftenAdvisory:!0}),I("CONFIG_INVALID_FORBIDDEN_GLOBALS","config","Invalid forbiddenGlobals","A layer\u2019s forbiddenGlobals is not an array of strings; the entry is ignored.",'Use an array of strings (e.g. ["fetch", "Date.now"]).',{oftenAdvisory:!0}),I("CONFIG_LAYER_WITHOUT_PATTERNS","config","Layer without patterns","A named layer has no file patterns and will never classify files.","Add patterns globs that match the layer\u2019s source tree.",{oftenAdvisory:!0}),I("CONFIG_INVALID_LAYER_PATTERN","config","Invalid layer pattern","A layer pattern is not a valid glob / failed to compile.","Fix the pattern syntax for that layer.",{oftenAdvisory:!0}),I("CONFIG_LAYER_PATTERN_NO_MATCHES","config","Layer pattern matched no files","A layer pattern matched zero included files (often a typo or include mismatch). Reserved/allowEmpty houses do not emit this.","Adjust the pattern or include roots, or mark the layer reserved/allowEmpty if the glob is a future house.",{oftenAdvisory:!0}),I("CONFIG_DUPLICATE_LAYER","config","Duplicate layer name","The same layer name appears more than once in configuration.","Rename or merge duplicate layer entries.",{oftenAdvisory:!0}),I("CONFIG_RULE_UNKNOWN_FROM_LAYER","config","Rule unknown from layer","A dependency rule references a source layer name that is not declared.","Fix the rule\u2019s from field to a declared layer name.",{oftenAdvisory:!0}),I("CONFIG_RULE_UNKNOWN_TO_LAYER","config","Rule unknown to layer","A dependency rule references a target layer name that is not declared.","Fix the rule\u2019s to field to a declared layer name.",{oftenAdvisory:!0}),I("CONFIG_AMBIGUOUS_LAYERS","config","Ambiguous layer classification","Some files match multiple layers at equal specificity; classification falls back to declaration order.","Disambiguate overlapping patterns so each file has one clear layer owner.",{oftenAdvisory:!0}),I("CONFIG_UNCLASSIFIED_FILES","config","Unclassified included files","Included source files match no layer pattern; import rules will not enforce on them.","Extend layer patterns or narrow include so every governed file is classified.",{oftenAdvisory:!0}),I("CONFIG_LAYER_MISSING_OWNER","config","Layer missing owner","requireLayerOwners is on and this layer has no owners. Writes to that house fail closed, like a folder with no name on the door.","Add a GitHub handle or email to that layer\u2019s owners in ark.config.json (/ark-adopt), then re-run. Reserved/allowEmpty houses may stay unnamed. Turn the flag off only if you no longer want owners required."),I("CONFIG_SLICE_IDENTITY_COLLISION","config","Starred slice prefixes share one id","sliceIdentity is stars and two different sliceFolders prefixes bind as the same slice id. Parallel trees of one feature do that on purpose; unrelated trees that share the last folder name merge by accident.","Keep stars when those prefixes are one feature. Otherwise use path, or rename the last literal so the prefixes do not bind as the same id. Doctor names both paths.",{oftenAdvisory:!0}),I("CONFIG_CHILD_SLICES_VERSION","config","childSlices needs a newer arkgate","The rule schema sets additionalProperties to false. arkgate 4.8.22 and older reject a config that contains childSlices instead of ignoring the key.","Pin arkgate newer than 4.8.22 before shipping a config that sets childSlices. This warning does not fail the check.",{oftenAdvisory:!0}),I("CONFIG_CHILD_SLICE_EXTENDS","config","Child slice id does not extend its universe","A path resolved a child id that is not the universe id plus a further segment. The child wall does not treat that id as a child, so the edge is universe common until the folders line up.","Point childSlices.sliceFolders at children under the same universe id the outer sliceFolders already names. Doctor names the path.",{oftenAdvisory:!0}),I("CONFIG_CHILD_SLICE_CROSS_UNIVERSE","config","Child slice allowance cannot cross the universe wall","childSlices.allowedCrossSlice names a pattern that can match two universes. That list clears only a sibling crossing inside one universe. The universe wall still denies the edge.","Narrow the pattern so both sides share one universe prefix (features/projects/* to features/projects/d2d-item), or remove the entry. This warning does not fail the check.",{oftenAdvisory:!0}),I("LITERAL_PATH_DRIFT","drift","Literal path moved by a rename","A repo path written inside a string, a comment or a docstring no longer resolves, and the rename set says where it went. Nothing in the gate sees this class: `tsc` resolves imports, not strings, and ESLint does not either, so the rename compiles green and the reference lies afterwards. It appears in four forms \u2014 the tsconfig alias, a relative literal, a path written without the include-root prefix, and prose \u2014 and a hand sweep reliably covers one of them.","Apply the suggested replacement, or re-run `npx arkgate-check --path-drift --base-ref <ref> --write` to apply every writable anchored replacement at once. The rewrite is mechanical and one-directional: the destination comes from the rename, it must itself resolve and be path-shaped, and the token is rewritten in the form the author wrote it in. A destination that leaves the alias root of the literal is reported with the target only and must be rewritten by hand."),I("LITERAL_PATH_UNRESOLVED","drift","Literal path does not resolve","A literal that looks like a repo path does not resolve under this root, and no rename explains where it went. Unlike LITERAL_PATH_DRIFT this is a candidate, not a verdict: with nothing to anchor it, ArkGate cannot tell a dead reference from an illustrative path in a comment, an example in documentation, or a path belonging to another tree.","Read the candidate and decide: fix the path, or leave it. Advisory only \u2014 it never fails a run and is never rewritten by --write, because there is no destination to propose. Run `--path-drift --all` to list the sweep.",{oftenAdvisory:!0}),I("ARK_UNKNOWN","meta","Unknown diagnostic","A diagnostic lacked a stable ruleId/code; adapters may emit this fallback so agents never see an empty id.","Resolve the underlying finding without weakening ark.config.json, then run Ark again. Prefer fixing the producer to emit a catalogued ruleId.")]),Po=new Map(ur.map(e=>[e.ruleId,e])),np=Object.freeze(ur.map(e=>e.ruleId));function rp(e){return typeof e=="string"&&e.length>0&&Po.has(e)}a(rp,"isKnownDiagnosticCode");function op(e){return typeof e!="string"||e.length===0?!1:Po.has(e)?!0:e.startsWith("ARKRULE_")}a(op,"isCataloguedOrArkRuleFamily");function pr(e){if(!(typeof e!="string"||e.length===0))return Po.get(e)}a(pr,"getDiagnosticCatalogEntry");function La(e){return`#${pr(e)?.docsAnchor??e}`}a(La,"diagnosticDocsFragment");function sp(e){return`${Oo}${La(e)}`}a(sp,"diagnosticDocsPath");function ip(){return{schemaVersion:"1.0",docsPath:Oo,codes:ur}}a(ip,"serializeDiagnosticCatalog");function ap(e){return pr(e)?.fix}a(ap,"catalogFixForRuleId");function lp(e){return pr(e)?.why}a(lp,"catalogWhyForRuleId");var cp=Object.freeze([Object.freeze({reasonId:"CROSS_PARENT_SLICE",ruleId:"LAYER_IMPORT_VIOLATION",title:"Cross-universe slice",why:"This import crosses two universe slices. The child wall cannot allow another universe.",fix:"Keep the import inside one universe, or move the shared code into a folder both universes may use."}),Object.freeze({reasonId:"CROSS_SIBLING_SLICE",ruleId:"LAYER_IMPORT_VIOLATION",title:"Cross-sibling slice",why:"This import crosses two feature slices inside one universe.",fix:"Import universe-common code, or move the shared piece into the feature that owns it. An enforce list makes those importer subtrees errors. Other sibling crossings stay warnings, and a new one past the baseline still fails."}),Object.freeze({reasonId:"CROSS_PARENT_VIA_SHARED",ruleId:"LAYER_IMPORT_VIOLATION",title:"Cross-universe through a shared root",why:"A slice reaches another universe only through a shared root. ark-check and CI report this path. The write hook and ESLint see one edge at a time and do not block it.",fix:"Stop the shared root from importing the other universe, or move that import into the universe that owns it. A shared hop that stays inside one universe is allowed."})]),OR=new Map(cp.map(e=>[e.reasonId,e]));var dp="1.1";var up="1.0";var on=class{static{a(this,"InMemoryReadModelStore")}states=new Map;load(t){return this.states.get(t)}save(t,n){this.states.set(t,n)}clear(t){t?this.states.delete(t):this.states.clear()}};function pp(e){return typeof e.initialState=="function"?e.initialState():e.initialState}a(pp,"initialState");var fr=class{static{a(this,"ProjectionRegistryImpl")}definitions=new Map;checkpoints=new Map;store;auditTrail;constructor(t={}){this.store=t.store??new on,this.auditTrail=t.auditTrail}register(t){if(this.definitions.has(t.name))throw new Error(`Projection "${t.name}" is already registered.`);this.definitions.set(t.name,t),this.checkpoints.set(t.name,{projection:t.name,appliedCount:0})}list(){return Array.from(this.definitions.values())}async apply(t){let n=[];for(let r of this.definitions.values()){if(!r.sourceIntents.includes(t.intent))continue;let o=await this.store.load(r.name)??pp(r),s=await r.project(t,o);await this.store.save(r.name,s);let i=this.checkpoints.get(r.name);this.checkpoints.set(r.name,{projection:r.name,appliedCount:(i?.appliedCount??0)+1,lastIntent:t.intent,lastCorrelationId:t.metadata.correlationId,updatedAt:new Date().toISOString()}),await this.auditTrail?.record({type:"projection.applied",source:"Kernel.ProjectionRegistry",intent:t.intent,correlationId:t.metadata.correlationId,causationId:t.metadata.causationId,subject:r.name,details:{projection:r.name}}),n.push(r.name)}return n}async getState(t){return this.store.load(t)}getCheckpoint(t){return this.checkpoints.get(t)}getCheckpoints(){return Array.from(this.checkpoints.values())}async clear(){await this.store.clear();for(let t of this.definitions.values())this.checkpoints.set(t.name,{projection:t.name,appliedCount:0})}};function gr(e){return new fr(e)}a(gr,"createProjectionRegistry");var mr="1.0";function fp(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}a(fp,"policyId");var _o=class{constructor(t){this.data=t}data;static{a(this,"ArkManifestImpl")}toJSON(){return{...this.data}}};function yr(e={}){let t=e.registry,n=e.policyEngine,r=e.metadata,o=e.graph,s=e.profile,i=e.projections,l=e.eventContracts,c=e.observability,u=t?t.list().map(v=>({name:v.name,dependencies:t.getDependencies(v.name),productions:t.getProductions(v.name)})):[],f=t?t.getAllRelationships():[],y=n?n.getPolicies().map(v=>({id:fp(v.name),name:v.name,severity:v.severity,tags:v.tags?[...v.tags]:void 0,owner:v.owner,version:v.version,rationale:v.rationale,enforcementMode:v.enforcementMode,deprecated:v.deprecated,replacedBy:v.replacedBy,description:v.tags?.includes("layer")?"Enforces clean-architecture layer dependency rules on declared relationships.":void 0})):[],p=r?r.toJSON():[],g=o?o.toJSON():{nodes:[],edges:[]},d=p.filter(v=>(v.emits?.length??0)>0||(v.consumes?.length??0)>0).map(v=>({entity:v.name,emits:v.emits,consumes:v.consumes})),m=i?i.list().map(v=>({name:v.name,sourceIntents:v.sourceIntents,checkpoint:i.getCheckpoint(v.name)})):[],b={schemaVersion:"1.0",version:Pr,exportedAt:new Date().toISOString(),intents:u,relationships:f,policies:y,entities:p,graph:g,architecture:s?{profile:s.name,layers:s.layers,rules:s.rules}:void 0,projections:m,eventContracts:l?.list()??[],observability:c?.report(),links:{entityIntents:d}};return new _o(b)}a(yr,"createArkManifest");var Da=0;function Fa(e){return Da+=1,`${e}-${Date.now()}-${Da}`}a(Fa,"createWorkflowId");function To(e){return e instanceof Error?e.message:String(e)}a(To,"errorMessage");function gp(e){return new Promise(t=>{setTimeout(t,e)})}a(gp,"sleep");async function mp(e,t,n){let r=new AbortController;if(t===void 0)return e(r.signal);let o,s=new Promise((i,l)=>{o=setTimeout(()=>{let c=new Error(`Workflow step "${n}" timed out after ${t}ms.`);r.abort(c),l(c)},t)});try{return await Promise.race([e(r.signal),s])}finally{o&&clearTimeout(o)}}a(mp,"withTimeout");var sn=class{static{a(this,"InMemoryWorkflowStore")}snapshots=new Map;save(t,n){let r=this.snapshots.get(t.id);if(r&&r.version!==t.version)throw new Error(`Optimistic concurrency conflict for workflow ${t.id}`);let o=(t.version??0)+1;this.snapshots.set(t.id,{...t,version:o,context:{...t.context}}),t.version=o}get(t,n){let r=this.snapshots.get(t);return r?{...r,context:{...r.context}}:void 0}list(t){return Array.from(this.snapshots.values()).filter(n=>!t||n.workflowName===t).map(n=>({...n,context:{...n.context}}))}claim(t,n,r){let o=Date.now();for(let s of this.snapshots.values()){if(r&&s.workflowName!==r||s.status!=="running"&&s.status!=="compensating")continue;let i=s.expiresAt?new Date(s.expiresAt).getTime()<o:!0;if(!s.ownerId||i){s.ownerId=t,s.expiresAt=new Date(o+n).toISOString();let l=(s.version??0)+1;return s.version=l,this.snapshots.set(s.id,{...s,context:{...s.context}}),{...s,context:{...s.context}}}}}clear(){this.snapshots.clear()}},No=class{constructor(t,n={}){this.bus=t;this.options=n;this.store=n.store??new sn}bus;options;static{a(this,"WorkflowEngineImpl")}definitions=new Map;store;register(t){if(this.definitions.has(t.name))throw new Error(`Workflow "${t.name}" is already registered.`);let n=new Set;for(let r of t.steps){if(n.has(r.name))throw new Error(`Workflow "${t.name}" has duplicate step name "${r.name}".`);n.add(r.name)}if(this.definitions.set(t.name,t),t.startOn){let r=t.startOn;this.bus.subscribe(r.intent,async o=>{await this.start(t.name,r.mapEventToPayload(o))})}}async start(t,n,r={}){let o=this.definitions.get(t);if(!o)throw new Error(`Workflow "${t}" is not registered.`);let s=new Date().toISOString(),i={id:r.id??Fa(t),version:0,workflowName:t,status:"running",context:{...n},completedSteps:[],attempts:{},startedAt:s,updatedAt:s};return await this.store.save(i,r.tx),await this.audit("workflow.started",i,{workflowName:t}),this.executeSnapshot(i,o,r.tx)}async resume(t,n={}){let r=await this.get(t,n.tx);if(!r)return;if(r.status!=="running"&&r.status!=="compensating")return r;let o=this.definitions.get(r.workflowName);if(!o)throw new Error(`Workflow "${r.workflowName}" is not registered.`);return this.executeSnapshot(r,o,n.tx)}async executeSnapshot(t,n,r){try{let o=n.steps.filter(s=>!t.completedSteps.includes(s.name));for(let s of o)await this.runStep(t,s,r);return t.status="completed",t.currentStep=void 0,t.completedAt=new Date().toISOString(),t.updatedAt=t.completedAt,await this.store.save(t,r),await this.audit("workflow.completed",t,{workflowName:t.workflowName}),{...t,context:{...t.context}}}catch(o){throw await this.compensate(t,n.steps,o,r),t.status="failed",t.currentStep=void 0,t.error=To(o),t.updatedAt=new Date().toISOString(),await this.store.save(t,r),await this.audit("workflow.failed",t,{workflowName:t.workflowName,error:t.error,failedStep:t.failedStep}),o}}async get(t,n){return this.store.get(t,n)}async list(t){return this.store.list(t)}async runStep(t,n,r){let o=n.retry??this.options.defaultRetry??{attempts:1},s=Math.max(1,o.attempts);t.currentStep=n.name,t.updatedAt=new Date().toISOString(),await this.store.save(t,r);for(let i=1;i<=s;i+=1){t.attempts[n.name]=i,await this.store.save(t,r);let l;try{l=await mp(c=>Promise.resolve(n.execute(t.context,this.bus,c)),n.timeoutMs,n.name)}catch(c){if(i<s){o.delayMs&&await gp(o.delayMs);continue}throw t.failedStep=n.name,t.updatedAt=new Date().toISOString(),await this.store.save(t,r),await this.audit("workflow.step.failed",t,{step:n.name,attempt:i,error:To(c)}),c}l&&Object.assign(t.context,l),t.completedSteps.push(n.name),t.currentStep=void 0,t.updatedAt=new Date().toISOString(),await this.store.save(t,r),await this.audit("workflow.step.completed",t,{step:n.name,attempt:i});return}throw new Error(`Workflow step "${n.name}" did not complete.`)}async compensate(t,n,r,o){t.status="compensating",t.updatedAt=new Date().toISOString(),await this.store.save(t,o);let s=n.filter(i=>t.completedSteps.includes(i.name));for(let i=s.length-1;i>=0;i-=1){let l=s[i];if(l.compensate)try{await Promise.resolve(l.compensate(t.context,this.bus,r)),await this.audit("workflow.compensation.completed",t,{step:l.name})}catch(c){await this.audit("workflow.step.failed",t,{step:l.name,compensation:!0,error:To(c)})}}}async audit(t,n,r){await this.options.auditTrail?.record({type:t,source:"Kernel.WorkflowEngine",subject:n.id,details:r})}};function an(e,t){return new No(e,t)}a(an,"createWorkflowEngine");function $a(e,t,n={}){let r=an(t,n),o={name:e.name,steps:e.steps};r.register(o);let s=n.id??Fa(e.name),i="idle",l=[];return{id:s,definition:e,get status(){return i},get completedSteps(){return[...l]},async run(c){i="running",l=[];try{let u=await r.start(e.name,c,{id:s});i=u.status==="waiting"?"idle":u.status,l=[...u.completedSteps]}catch(u){let f=await r.get(s);throw i=f?.status==="waiting"?"idle":f?.status??"failed",l=f?.completedSteps??[],u}}}}a($a,"createSaga");Et();function Ga(e){return Object.keys(e).sort()}a(Ga,"sortedKeys");function Mo(e,t,n,r){if(e===t)return;if(e===null||t===null||typeof e!=typeof t){r.push({path:n,left:e,right:t});return}if(typeof e!="object"||typeof t!="object"){e!==t&&r.push({path:n,left:e,right:t});return}if(Array.isArray(e)||Array.isArray(t)){let l=Array.isArray(e)?e:[],c=Array.isArray(t)?t:[],u=Math.max(l.length,c.length);for(let f=0;f<u;f+=1)Mo(l[f],c[f],`${n}[${f}]`,r);return}let o=e,s=t,i=new Set([...Ga(o),...Ga(s)]);for(let l of[...i].sort())Mo(o[l],s[l],n?`${n}.${l}`:l,r)}a(Mo,"walk");function Ua(e){return{schemaVersion:e.schemaVersion,kernelInstanceId:e.kernelInstanceId,components:e.components.map(t=>({id:t.id,lifetime:t.lifetime,uses:[...t.uses],reactsTo:[...t.reactsTo],raises:[...t.raises],sends:[...t.sends],...t.extendedInfo?{extendedInfo:{...t.extendedInfo}}:{}})),...e.decisionTape?{decisionTape:e.decisionTape.map(t=>({xiHash:t.xiHash,event:{kind:t.event.kind,...t.event.payload?{payload:{...t.event.payload}}:{}},residual:{...t.residual}}))}:{}}}a(Ua,"shadowInformationPackage");function Ho(e,t){let n=[];return Mo(e,t,"",n),{equal:n.length===0,diffs:n}}a(Ho,"compareInformationPackages");function Va(e){let t=[];for(let n=1;n<e.length;n+=1)t.push(Ho(e[n-1],e[n]));return t}a(Va,"replayInformationPackages");Sr();gn();Sn();Sn();async function Or(e,t={}){let n=kn({host:t.host,port:t.port,nodeEnv:t.nodeEnv,processNodeEnv:process.env.NODE_ENV}),{listenArkRunInspector:r}=await Promise.resolve().then(()=>(rl(),nl));return r(e,{bind:n,sseIntervalMs:t.sseIntervalMs})}a(Or,"startArkRunInspector");Sr();Sn();Et();gn();Et();var Qp=new Set(["singleton","transient"]);function ol(e){let t={id:e.id,lifetime:e.lifetime,uses:[...e.uses],reactsTo:[...e.reactsTo],raises:[...e.raises],sends:[...e.sends]};if(e.extendedInfo){let n=e.extendedInfo;t.extendedInfo={...n.label?{label:n.label}:{},...n.architectureKind?{architectureKind:n.architectureKind}:{},...n.tags?{tags:[...n.tags]}:{},...n.group?{group:n.group}:{},...n.metadata?{metadata:{...n.metadata}}:{}}}return t}a(ol,"cloneComponent");function ef(e){if(e===void 0)return"singleton";if(typeof e=="string"&&Qp.has(e))return e;throw new Error('ArkRun component lifetime must be "singleton" or "transient".')}a(ef,"closedLifetime");function sl(){let e=new Map,t=new Map,n=new Set;function r(i){let l=e.get(i);if(!l)throw new Error(`ArkRun component "${i}" is not registered.`);return l}a(r,"mustRecord");function o(i,l){if(!l.factory)throw new Error(`ArkRun component "${i}" has no factory; declarations-only registrations cannot be resolved.`);if(n.has(i))throw new Error(`ArkRun component "${i}" has a circular resolve.`);n.add(i);try{return l.factory()}finally{n.delete(i)}}a(o,"instantiate");function s(i,l){if(t.has(i))return t.get(i);let c=o(i,l);return t.set(i,c),c}return a(s,"singleton"),{register(i){let l=typeof i?.id=="string"?i.id.trim():"";if(!l)throw new Error("ArkRun component id must be a non-empty string.");if(e.has(l))throw new Error(`ArkRun component "${l}" is already registered.`);let c=ef(i.lifetime),u=Fo({id:l,lifetime:c,uses:i.uses,reactsTo:i.reactsTo,raises:i.raises,sends:i.sends,extendedInfo:i.extendedInfo});if(!u)throw new Error("ArkRun component id must be a non-empty string.");let f=typeof i.factory=="function"?i.factory:void 0;return e.set(l,{component:u,factory:f}),ol(u)},resolve(i){let l=r(i);return l.component.lifetime==="transient"?o(i,l):s(i,l)},resolveSingleton(i){let l=r(i);if(l.component.lifetime==="transient")throw new Error(`ArkRun component "${i}" is transient; resolveSingleton requires lifetime "singleton".`);return s(i,l)},snapshotComponents(){return[...e.values()].map(i=>ol(i.component))}}}a(sl,"createComponentRegistry");gn();function tf(e){let t={...e.metadata??{}};if(e.source===void 0)return t;if(t.source&&t.source!==e.source)throw new Oe(e.source,t.source);return t.source=e.source,t}a(tf,"stampMetadata");function nf(){}a(nf,"ignoreDetachedFailure");async function Jo(e,t,n,r={}){let o=vr({transport:r.transport,ephemeral:r.ephemeral??e.defaultEphemeral,brokerBound:typeof e.broker?.send=="function"}),s=tf(r),i=await e.eventBus.dispatch(t,n,s,{notifySubscribers:o.notifySubscribers,awaitHandlers:o.awaitHandlers});if(o.deliveredVia==="broker"&&e.broker){let l=Promise.resolve(e.broker.send(i));o.awaitHandoff?await l:l.then(void 0,nf)}return o}a(Jo,"sendOnArkRunTransport");var Qo=1e3,il=0;function rf(){return il+=1,`ark-kernel-${Date.now()}-${il}`}a(rf,"nextKernelInstanceId");function al(e,t){let n=e.constructor?.name;return typeof n=="string"&&n.length>0?n:t}a(al,"portConstructorId");function vn(e={}){let t=e.strict??!0,n=e.instanceId??rf(),r=e.profile??ft,o=e.maxHistorySize??Qo,s=On(),i=Bn(),l=e.metadata??Qn(),c=e.auditTrail===void 0,u=e.auditTrail??Vn({maxRecords:o}),f=e.eventContracts??Kn(),y=e.eventBuffer===void 0&&e.outbox===void 0,p=e.eventBuffer??e.outbox??new Ke,g=e.projections??gr({auditTrail:u}),d=new $e([Nn(r),...e.policies??[]]),m=a(()=>{Wn(s,i,{requireRegisteredTargets:!0})},"syncGraph"),b=e.ephemeral??!0,v=e.broker,k=new ct({intentRegistry:s,dependencyGraph:i,policyEngine:d,strictRegistry:!0,validateIntentNaming:!0,auditTrail:u,eventContracts:f,strictEventContracts:e.strictEventContracts??t,requireKnownSource:e.requireKnownSource??!0,architectureProfile:r,enforceObservedLayerFlow:e.enforceObservedLayerFlow??(t?"hard":"off"),eventBuffer:p,instanceId:n,maxHistorySize:o,onPublish:e.autoApplyProjections===!1?void 0:async T=>{await g.apply(T)}}),E=an(k,{auditTrail:u}),O=Gn({registry:s,eventBus:k,graph:i}),L=sl(),S=typeof v?.send=="function",N=y?"InMemoryEventBuffer":al(p,"EventBufferStore"),z=c?"InMemoryAuditStore":al(u,"AuditTrail"),Q=In({stores:[Ye(N,"outbox"),Ye(z,"audit"),Ye("InMemoryWorkflowStore","workflow")]}),pe={instanceId:n,profile:r,registry:s,graph:i,metadata:l,auditTrail:u,eventContracts:f,eventBuffer:p,outbox:p,projections:g,policyEngine:d,eventBus:k,workflowEngine:E,observability:O,publisher(T){let Y=k.createPublisher(T);return{source:Y.source,publish:Y.publish,send(X,Ae,we={}){return Jo({eventBus:k,broker:v,defaultEphemeral:b},X,Ae,{...we,source:Y.source})}}},send(T,Y,X={}){return Jo({eventBus:k,broker:v,defaultEphemeral:b},T,Y,X)},register(T){return L.register(T)},resolve(T){return L.resolve(T)},resolveSingleton(T){return L.resolveSingleton(T)},getDependencyInformationPackage(){return ve({kernelInstanceId:n,components:L.snapshotComponents()})},requestGraph(T){return br({kernelInstanceId:n,components:L.snapshotComponents()},T)},getInspectorSnapshot(T){return xr({kernelInstanceId:n,host:T?.host,port:T?.port,package:{kernelInstanceId:n,components:L.snapshotComponents()},observability:O.report(),ephemeralDefault:b,brokerBound:S,hardening:Q})},startInspector(T){return Or({getInspectorSnapshot:a(X=>pe.getInspectorSnapshot(X),"getInspectorSnapshot"),requestGraph:a(X=>pe.requestGraph(X),"requestGraph"),async listInspectorOutbox(){let[X,Ae]=await Promise.all([p.list("pending"),p.list("failed")]);return Xe([...X,...Ae],{sampleLimit:le})},async listInspectorWorkflows(){return Ze(await E.list(),{sampleLimit:le})}},T)},syncGraph:m,manifest(){return m(),yr({registry:s,policyEngine:d,metadata:l,graph:i,profile:r,projections:g,eventContracts:f,observability:O})}};return pe}a(vn,"createArkKernel");function es(e={}){return vn({...e,strict:!0,strictEventContracts:e.strictEventContracts??!0,requireKnownSource:e.requireKnownSource??!0,enforceObservedLayerFlow:e.enforceObservedLayerFlow??"hard"})}a(es,"createStrictArkKernel");function ts(e,t={}){let{profileName:n,...r}=t;return{...r,profile:Zn(e,{name:n})}}a(ts,"createOptionsFromConfig");function ll(e,t={}){return vn(ts(e,t))}a(ll,"createArkKernelFromConfig");function cl(e,t={}){return es(ts(e,t))}a(cl,"createStrictArkKernelFromConfig");function dl(e,t={}){return ns(ts(e,t))}a(dl,"createLenientArkKernelFromConfig");function ns(e={}){return vn({...e,strict:!1,strictEventContracts:e.strictEventContracts??!1,enforceObservedLayerFlow:e.enforceObservedLayerFlow??"off"})}a(ns,"createLenientArkKernel");export{uo as ANALYSIS_IR_SCHEMA_VERSION,is as ARK_ANALYSIS_RESULT_SCHEMA,wn as ARK_ANALYSIS_RESULT_SCHEMA_VERSION,up as ARK_DESIGN_DELTA_SCHEMA_VERSION,dp as ARK_ENFORCEMENT_STATE_SCHEMA_VERSION,Lo as ARK_RUN_COMPONENT_LIFETIMES,Ct as ARK_RUN_EPHEMERAL_DEFAULT,Vo as ARK_RUN_GRAPH_DEFAULT_SLICE,qa as ARK_RUN_GRAPH_NODE_KINDS,Ya as ARK_RUN_GRAPH_PROCESS_EDGE_KINDS,Uo as ARK_RUN_GRAPH_SCHEMA_VERSION,jo as ARK_RUN_GRAPH_SLICES,Xa as ARK_RUN_GRAPH_TECHNICAL_EDGE_KINDS,hr as ARK_RUN_INFORMATION_PACKAGE_SCHEMA_VERSION,Er as ARK_RUN_INSPECTOR_DEFAULT_HOST,Yo as ARK_RUN_INSPECTOR_DEFAULT_PORT,yn as ARK_RUN_INSPECTOR_EVENTS_PATH,hn as ARK_RUN_INSPECTOR_GRAPH_PATH,le as ARK_RUN_INSPECTOR_MONITOR_SAMPLE_LIMIT,Rn as ARK_RUN_INSPECTOR_OUTBOX_PATH,qo as ARK_RUN_INSPECTOR_SCHEMA_VERSION,mn as ARK_RUN_INSPECTOR_SNAPSHOT_PATH,Xo as ARK_RUN_INSPECTOR_SSE_EVENT,Zo as ARK_RUN_INSPECTOR_TRANSPORT_FALLBACK,An as ARK_RUN_INSPECTOR_WORKFLOWS_PATH,fn as ARK_RUN_TRANSPORT_KINDS,ue as ArkRunInspectorBindError,xt as ArkRunInspectorProductionError,Qo as DEFAULT_MAX_HISTORY_SIZE,ur as DIAGNOSTIC_CATALOG,tp as DIAGNOSTIC_CATALOG_SCHEMA_VERSION,Oo as DIAGNOSTIC_DOCS_RELATIVE_PATH,np as DIAGNOSTIC_RULE_IDS,Kt as EventContractRegistryImpl,rt as EventContractViolationError,Gt as InMemoryAuditStore,Ke as InMemoryEventBuffer,Ks as InMemoryOutboxStore,on as InMemoryReadModelStore,sn as InMemoryWorkflowStore,Je as IntentRegistry,se as InvalidArkRunGraphQueryError,wt as InvalidArkRunSendOptionError,tt as InvalidIntentNameError,nt as LayerPolicyContextError,mr as MANIFEST_SCHEMA_VERSION,ot as ObservedLayerFlowViolationError,bo as POLICY_DELTA_SCHEMA_VERSION,$e as PolicyEngine,xe as PolicyViolationError,co as RESOLVED_CANDIDATE_FACTS_SCHEMA,Be as RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,Oe as SourceMetadataOverrideError,Me as UnknownEventSourceError,et as UnregisteredIntentError,kt as analyzeArchitectureConvergence,ir as analyzeChange,Qi as analyzePolicyDelta,nn as analyzeProject,rn as analyzeResolvedProject,Ka as appendDecisionTape,Dr as architecturalPolicies,Ir as arkRunGraphQueryFromSearchParams,Ee as arkRunInspectorUrl,In as buildArkRunInspectorHardening,Xe as buildArkRunInspectorOutboxMonitor,xr as buildArkRunInspectorSnapshot,Ze as buildArkRunInspectorWorkflowsMonitor,ve as buildDependencyInformationPackage,Ln as buildPublishPolicyContext,ap as catalogFixForRuleId,lp as catalogWhyForRuleId,zr as checkAdapterGovernance,gi as checkContract,So as classifyArkPolicyDelta,Ye as classifyArkRunInspectorStoreDurability,kr as closeArkRunGraphQuery,zo as closedArkRunEphemeral,Wo as closedArkRunTransportKind,dr as collectAnalysisConfigWarnings,ht as collectForbiddenCapabilityUses,Ho as compareInformationPackages,Si as createAICodeGate,fi as createAdapter,kl as createAdapterResult,Xn as createArchitectureProfile,Zn as createArchitectureProfileFromArkConfig,vn as createArkKernel,ll as createArkKernelFromConfig,yr as createArkManifest,Vs as createArkTestHarness,Vn as createAuditTrail,Bn as createDependencyGraph,ui as createElevenLayerArkConfig,Ds as createEventBus,Kn as createEventContractRegistry,On as createIntentRegistry,ns as createLenientArkKernel,dl as createLenientArkKernelFromConfig,Qn as createMetadataRegistry,Gn as createObservabilityReporter,gr as createProjectionRegistry,lo as createResolvedCandidateFacts,$a as createSaga,es as createStrictArkKernel,cl as createStrictArkKernelFromConfig,an as createWorkflowEngine,ds as defaultIntentRegistry,Nn as defineArchitectureProfilePolicy,cs as defineIntent,_n as defineLayerPolicy,Qe as definePolicy,pi as definePort,fs as definePublishPolicy,wo as detectArchitectureCycles,Z as deterministicHash,La as diagnosticDocsFragment,sp as diagnosticDocsPath,ft as elevenLayerProfile,St as evaluateArchitectureGraph,ea as explainViolation,yt as extractSemanticDependencies,Bo as formatArkRunGraphMermaid,bn as formatArkRunInspectorSseEvent,pr as getDiagnosticCatalogEntry,Ot as isArkRunInspectorLoopbackHost,wr as isArkRunInspectorProductionEnv,op as isCataloguedOrArkRuleFamily,rp as isKnownDiagnosticCode,Tn as isLayerPolicy,sr as loadContract,Te as loadResolvedCandidateFacts,vo as policyDeltaAcknowledgementMatches,Ta as preflightChange,Na as preflightResolvedChange,Va as replayInformationPackages,br as requestArkRunGraph,kn as resolveArkRunInspectorBind,vr as resolveArkRunSendPlan,Zt as resolvedFactsEvidenceRequirementsHash,ip as serializeDiagnosticCatalog,Ua as shadowInformationPackage,M as stableSerialize,Or as startArkRunInspector,Wn as syncRegistryToGraph,Lr as toAdapterDiagnostic,ze as unavailableArkRunInspectorOutboxMonitor,qe as unavailableArkRunInspectorWorkflowsMonitor,Pn as validateIntentName,Pr as version};