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.
- package/CHANGELOG.md +71 -0
- package/README.md +2 -2
- package/bin/ark-check-runtime.mjs +4 -2
- package/bin/ark-layer-match.mjs +606 -11
- package/bin/lib/analysis-engine.mjs +11 -11
- package/bin/lib/config-contract.mjs +492 -1
- package/bin/lib/diagnostic-catalog.mjs +32 -0
- package/bin/lib/doctor-advisories.mjs +60 -1
- package/bin/lib/doctor-plan.mjs +2 -2
- package/bin/lib/enforcement-honesty.mjs +22 -0
- package/bin/lib/flat-parent-pilot.mjs +252 -0
- package/bin/lib/html-report-advisories.mjs +2 -0
- package/bin/lib/html-report-depth.mjs +3 -1
- package/bin/lib/invariant-coverage.mjs +27 -3
- package/bin/lib/physical-cohesion.mjs +16 -18
- package/bin/lib/pilot-loop.mjs +21 -8
- package/bin/lib/team-parliament-io.mjs +4 -2
- package/dist/{configTypes-CTELo87-.d.ts → configTypes-Bbf_MFGe.d.ts} +36 -2
- package/dist/{diagnosticCatalog-B7BXlet6.d.ts → diagnosticCatalog-35mrwAHe.d.ts} +20 -5
- package/dist/eslint/index.cjs +4 -4
- package/dist/eslint/index.d.ts +51 -5
- package/dist/eslint/index.js +4 -4
- package/dist/index.cjs +36 -36
- package/dist/index.d.ts +104 -5
- package/dist/index.js +36 -36
- package/dist/nestjs/index.cjs +9 -9
- package/dist/nestjs/index.d.ts +3 -3
- package/dist/nestjs/index.js +9 -9
- package/dist/runtime/index.cjs +19 -19
- package/dist/runtime/index.d.ts +6 -6
- package/dist/runtime/index.js +19 -19
- package/dist/{types-yDNEQ603.d.ts → types-Bdj32QwA.d.ts} +1 -1
- package/dist/{types-fQ9-KrBj.d.ts → types-Ik_OakcI.d.ts} +1 -1
- package/docs/README.md +3 -1
- package/docs/agent-guide.md +9 -1
- package/docs/configuration.md +92 -1
- package/docs/diagnostics.md +32 -0
- package/docs/product-voice.md +1 -1
- package/package.json +2 -1
- package/schemas/ark.config.schema.json +124 -2
- package/server.json +2 -2
- package/templates/agent-skills/README.md +1 -1
package/dist/runtime/index.cjs
CHANGED
|
@@ -1,32 +1,32 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`)}function
|
|
1
|
+
"use strict";var vl=Object.create;var Zt=Object.defineProperty;var El=Object.getOwnPropertyDescriptor;var wl=Object.getOwnPropertyNames;var Cl=Object.getPrototypeOf,xl=Object.prototype.hasOwnProperty;var a=(e,t)=>Zt(e,"name",{value:t,configurable:!0});var Jt=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Ns=(e,t)=>{for(var n in t)Zt(e,n,{get:t[n],enumerable:!0})},Ls=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of wl(t))!xl.call(e,o)&&o!==n&&Zt(e,o,{get:()=>t[o],enumerable:!(r=El(t,o))||r.enumerable});return e};var Ol=(e,t,n)=>(n=e!=null?vl(Cl(e)):{},Ls(t||!e||!e.__esModule?Zt(n,"default",{value:e,enumerable:!0}):n,e)),Pl=e=>Ls(Zt({},"__esModule",{value:!0}),e);function gs(e,t){return e<t?-1:e>t?1:0}function Ep(e){return[...new Set(e)].sort(gs)}function Un(e){if(!Array.isArray(e))return[];let t=[];for(let n of e)typeof n=="string"&&n.length>0&&t.push(n);return Ep(t)}function wp(e){if(e===null)return null;if(typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return e}function Cp(e){return typeof e=="string"&&vp.has(e)?e:"singleton"}function al(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t={};for(let n of Object.keys(e).sort(gs)){if(n.length===0)continue;let r=wp(e[n]);r!==void 0&&(t[n]=r)}return Object.keys(t).length>0?t:void 0}function xp(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=Un(t.tags);r.length>0&&(n.tags=r),typeof t.group=="string"&&t.group.length>0&&(n.group=t.group);let o=al(t.metadata);return o&&(n.metadata=o),Object.keys(n).length>0?n:void 0}function ms(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:Cp(t.lifetime),uses:Un(t.uses),reactsTo:Un(t.reactsTo),raises:Un(t.raises),sends:Un(t.sends)},o=xp(t.extendedInfo);return o&&(r.extendedInfo=o),r}function Pp(e){return al(e)}function ys(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"&&Op.has(l.kind)?l.kind:void 0;if(!c)return;let u={kind:s},f=Pp(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 _p(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let r=ys(n);r&&t.push(r)}return t}function Re(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=ms(i);!l||r.has(l.id)||(r.add(l.id),o.push(l))}o.sort((i,l)=>gs(i.id,l.id));let s=_p(e.decisionTape);return{schemaVersion:"1.0",kernelInstanceId:t,components:o,...s.length>0?{decisionTape:s}:{}}}function hs(e,t){let n=ys(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 Vn,Hr,il,vp,Op,$t=Jt(()=>{"use strict";Vn="1.0",Hr=["singleton","transient"],il=["absorb","escalate_up","hold"],vp=new Set(Hr);a(gs,"compare");a(Ep,"uniqueSorted");a(Un,"nameList");a(wp,"jsonPrimitive");a(Cp,"closedLifetime");a(al,"sanitizeMetadata");a(xp,"sanitizeArkRunExtendedInfo");a(ms,"sanitizeArkRunComponent");Op=new Set(il);a(Pp,"sanitizeTapePayload");a(ys,"sanitizeDecisionTapeRecord");a(_p,"sanitizeDecisionTape");a(Re,"buildDependencyInformationPackage");a(hs,"appendDecisionTape")});function Wn(e,t){return e<t?-1:e>t?1:0}function Is(e){return[...new Set(e)].sort(Wn)}function cl(){return{tokens:[],ids:[],labels:[],tags:[],groups:[],architectureKinds:[]}}function bs(e){return e.tokens.length+e.ids.length+e.labels.length+e.tags.length+e.groups.length+e.architectureKinds.length>0}function Ae(e,t){if(e==null||e==="")return[];if(typeof e=="string")return Is(e.split(",").map(r=>r.trim()).filter(r=>r.length>0));if(!Array.isArray(e))throw new re(t);let n=[];for(let r of e){if(typeof r!="string")throw new re(t);let o=r.trim();o.length>0&&n.push(o)}return Is(n)}function fl(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 jn(e,t){return e?t.some(n=>fl(e,n)):!1}function gl(e){if(e==null||e==="")return jr;if(typeof e=="string"&&Tp.has(e))return e;throw new re("slice")}function ml(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 re("degreesOfSeparation")}function dl(e,t){if(e==null||e==="")return cl();if(typeof e=="string"||Array.isArray(e))return{...cl(),tokens:Ae(e,t)};if(typeof e!="object")throw new re(t);let n=e;for(let r of Object.keys(n))if(!Lp.has(r))throw new re(t);return{tokens:[],ids:Ae(n.ids,t),labels:Ae(n.labels,t),tags:Ae(n.tags,t),groups:Ae(n.groups,t),architectureKinds:Ae(n.architectureKinds,t)}}function qn(e={}){if(e==null||e==="")return qn({});if(typeof e!="object"||Array.isArray(e))throw new re("slice","ArkRun graph query must be an object.");let t=e;for(let n of Object.keys(t))if(!Np.has(n))throw new re("slice",`ArkRun graph query key "${n}" is not closed.`);return{slice:gl(t.slice),nodeIds:Ae(t.nodeIds,"nodeIds"),degreesOfSeparation:ml(t.degreesOfSeparation),include:dl(t.include,"include"),exclude:dl(t.exclude,"exclude")}}function Yn(e){let t={};e.slice&&(t.slice=gl(e.slice));let n=Ae(e.nodeIds??void 0,"nodeIds");n.length>0&&(t.nodeIds=n);let r=ml(e.degreesOfSeparation??void 0);r!==null&&(t.degreesOfSeparation=r);let o=Ae(e.include??void 0,"include");o.length>0&&(t.include=o);let s=Ae(e.exclude??void 0,"exclude");return s.length>0&&(t.exclude=s),t}function Dp(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 ul(e,t){if(!bs(t))return!0;let n=Dp(e);return t.tokens.some(r=>n.some(o=>fl(o,r)))||jn(e.id,t.ids)||jn(e.label,t.labels)||e.tags?.some(r=>jn(r,t.tags))||jn(e.group,t.groups)?!0:jn(e.architectureKind,t.architectureKinds)}function Fp(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;return Re({kernelInstanceId:t.kernelInstanceId,components:t.components})}return Re({})}function $p(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 Gr(e){return{id:e,kind:"interaction"}}function Bn(e,t){let n=e.get(t.id);(!n||n.kind==="interaction"&&t.kind==="component")&&e.set(t.id,t)}function Ur(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 Mp(e,t){let n=new Map,r=[],o=new Set;for(let s of e){if(Bn(n,$p(s)),t==="technical"){for(let i of s.uses)Bn(n,n.get(i)??Gr(i)),Ur(r,o,s.id,i,"uses");continue}for(let i of s.raises)Bn(n,n.get(i)??Gr(i)),Ur(r,o,s.id,i,"raises");for(let i of s.reactsTo)Bn(n,n.get(i)??Gr(i)),Ur(r,o,i,s.id,"reactsTo");for(let i of s.sends)Bn(n,n.get(i)??Gr(i)),Ur(r,o,s.id,i,"sends")}return{nodes:n,edges:r}}function Hp(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 Kp(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 zn(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return/^[A-Za-z_]/.test(t)?t:`n_${t}`}function pl(e){return e.replace(/\\/g,"\\\\").replace(/"/g,"#quot;").replace(/]/g,"#93;")}function Gp(e){let t=new Set,n=new Map;for(let r of e){let o=zn(r),s=o,i=2;for(;t.has(s);)s=`${o}_${i}`,i+=1;t.add(s),n.set(r,s)}return n}function Wr(e){let t=e.slice==="technical"?"TD":"LR",n=e.nodes.map(l=>l.id),r=Gp(n),o=Is(e.nodes.map(l=>l.group).filter(l=>!!l)),s=[`flowchart ${t}`],i=a((l,c)=>{let u=r.get(l.id)??zn(l.id),f=pl(l.label??l.id);s.push(`${c}${u}["${f}"]`)},"emitNode");for(let l of o){let c=zn(`group_${l}`);s.push(` subgraph ${c}["${pl(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)??zn(l.from),u=r.get(l.to)??zn(l.to);s.push(` ${c} -->|${l.kind}| ${u}`)}return s.join(`
|
|
2
|
+
`)}function Up(e,t,n){let r=new Set(e.keys());if(bs(n.include)&&(r=new Set([...r].filter(l=>{let c=e.get(l);return c!==void 0&&ul(c,n.include)}))),bs(n.exclude))for(let l of[...r]){let c=e.get(l);c&&ul(c,n.exclude)&&r.delete(l)}let o=t.filter(l=>r.has(l.from)&&r.has(l.to));n.nodeIds.length>0&&(r=Kp(r,n.nodeIds,n.degreesOfSeparation,Hp(o)));let s=[...r].sort(Wn).map(l=>e.get(l)).filter(l=>!!l),i=o.filter(l=>r.has(l.from)&&r.has(l.to)).sort((l,c)=>Wn(l.from,c.from)||Wn(l.kind,c.kind)||Wn(l.to,c.to));return{nodes:s,edges:i}}function Xn(e={},t={}){let n=Fp(e),r=qn(t),o=Mp(n.components,r.slice),s=Up(o.nodes,o.edges,r),i={schemaVersion:Vr,kernelInstanceId:n.kernelInstanceId,slice:r.slice,query:r,nodes:s.nodes,edges:s.edges,mermaid:""};return i.mermaid=Wr(i),i}var Vr,jr,Br,Ss,vs,Es,re,Tp,Np,Lp,zr=Jt(()=>{"use strict";$t();Vr="1.0",jr="process",Br=["process","technical"],Ss=["component","interaction"],vs=["raises","reactsTo","sends"],Es=["uses"],re=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}},Tp=new Set(Br),Np=new Set(["slice","nodeIds","degreesOfSeparation","include","exclude"]),Lp=new Set(["ids","labels","tags","groups","architectureKinds"]);a(Wn,"compare");a(Is,"uniqueSorted");a(cl,"emptyMatch");a(bs,"matchHasCriteria");a(Ae,"nameList");a(fl,"globMatch");a(jn,"anyGlob");a(gl,"closedSlice");a(ml,"closedDegrees");a(dl,"closedMatch");a(qn,"closeArkRunGraphQuery");a(Yn,"arkRunGraphQueryFromSearchParams");a(Dp,"nodeFields");a(ul,"nodeMatches");a(Fp,"asPackage");a($p,"componentNode");a(Gr,"interactionNode");a(Bn,"addNode");a(Ur,"addEdge");a(Mp,"buildSlice");a(Hp,"adjacency");a(Kp,"neighborhood");a(zn,"mermaidSafeId");a(pl,"mermaidLabel");a(Gp,"uniqueMermaidIds");a(Wr,"formatArkRunGraphMermaid");a(Up,"filterGraph");a(Xn,"requestArkRunGraph")});function qr(e){if(e===void 0)return"local";if(typeof e=="string"&&Vp.has(e))return e;throw new dt("transport")}function Yr(e){if(e===void 0)return!0;if(e===!0||e===!1)return e;throw new dt("ephemeral")}function Zn(e){let t=qr(e.transport),n=Yr(e.ephemeral),r=t==="broker"&&e.brokerBound!==!0,o=t==="broker"&&!r?"broker":"local",s=t==="localBlocking";return{transport:t,ephemeral:n,deliveredVia:o,fallbackToLocal:r,notifySubscribers:o==="local",awaitHandlers:s,awaitHandoff:n||s}}var Mt,ut,Vp,dt,Jn=Jt(()=>{"use strict";Mt=["local","localBlocking","broker"],ut=!0,Vp=new Set(Mt),dt=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(qr,"closedArkRunTransportKind");a(Yr,"closedArkRunEphemeral");a(Zn,"resolveArkRunSendPlan")});function er(e){return e==="production"}function Bp(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 yl(e){if(e.startsWith("[::ffff:")&&e.endsWith("]"))return e.slice(8,-1);if(e.startsWith("::ffff:"))return e.slice(7)}function ft(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();if(t==="localhost"||t==="::1"||t==="[::1]")return!0;let n=yl(t);if(n)return ft(n);let r=Bp(t);return r!==void 0&&r[0]===127}function hl(e){if(e===void 0)return Qn;if(typeof e!="string")throw new ce(String(e));let t=e.trim();if(jp.has(t.toLowerCase())||!ft(t))throw new ce(t);let n=t.toLowerCase();if(n==="localhost")return Qn;if(n==="[::1]")return"::1";let r=yl(n);return r?hl(r):n}function Wp(e){if(e===void 0)return Zr;if(typeof e!="number"||!Number.isInteger(e)||e<0||e>65535)throw new ce(`port:${String(e)}`);return e}function jt(e={}){if(er(e.nodeEnv)||er(e.processNodeEnv))throw new pt;return{host:hl(e.host),port:Wp(e.port)}}function ke(e,t,n){return`http://${e.includes(":")?`[${e}]`:e}:${t}${n}`}function zp(e){if(e!==void 0)try{return JSON.parse(JSON.stringify(e))}catch{return}}function qp(e){return{kinds:[...Mt],ephemeralDefault:e.ephemeralDefault===!1?!1:!0,brokerBound:e.brokerBound===!0,cloudSdksShipped:!1,fallback:Qr}}function He(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function Yp(e){let t=He(e);if(!t||typeof t.id!="string")return;let n=t.status;if(n!=="pending"&&n!=="failed")return;let r=He(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 eo(e){if(typeof e!="number"||!Number.isFinite(e))return ie;let t=Math.trunc(e);return t<0?0:t>ie?ie:t}function Ue(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 Bt(e={}){let t=He(e),n=He(t?.durability)??t,r=Array.isArray(n?.stores)?n.stores:Array.isArray(t?.stores)?t.stores:[],o=[];for(let s of r){let i=He(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:Ue(c,l).kind;o.push({role:l,id:c,kind:u})}return{durability:{stores:o}}}function Ve(e=[],t={}){let n=eo(t.sampleLimit),r=Array.isArray(e)?e:[],o=[],s=[];for(let i of r){let l=Yp(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 Ke(){return{available:!1,pendingCount:0,failedCount:0,pending:[],failed:[],sampleLimit:ie}}function Xp(e){let t=He(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 Zp(e){return e==="idle"||e==="waiting"}function je(e=[],t={}){let n=eo(t.sampleLimit),r=Array.isArray(e)?e:[],o=[],s=0,i=0,l=0,c=0;for(let u of r){let f=Xp(u);f&&(o.push(f),f.status==="running"?s+=1:f.status==="compensating"?i+=1:f.status==="failed"?l+=1:Zp(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 Ge(){return{available:!1,total:0,runningCount:0,compensatingCount:0,failedCount:0,pendingCount:0,workflows:[],sampleLimit:ie}}function Jp(e){if(e===void 0)return;let t=He(e);if(!t||t.available===!1)return Ke();let n=eo(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=Ve(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 Ke()}function Qp(e){if(e===void 0)return;let t=He(e);if(!t||t.available===!1)return Ge();let n=eo(t.sampleLimit);if(Array.isArray(t.workflows)){let r=je(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 Ge()}function tr(e={}){let t=jt({host:e.host,port:e.port}),n=Re({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=Qp(e.workflows),s={schemaVersion:Xr,kernelInstanceId:typeof e.kernelInstanceId=="string"?e.kernelInstanceId:n.kernelInstanceId,bind:{host:t.host,port:t.port,loopback:!0},package:{...n,schemaVersion:"1.0"},transport:qp(e),observability:zp(e.observability)??{},hardening:Bt(e.hardening)};return r&&(s.outbox=r),o&&(s.workflows=o),s}function Wt(e){return`event: ${Jr}
|
|
3
3
|
data: ${JSON.stringify(e)}
|
|
4
4
|
|
|
5
|
-
`}var Fr,Gn,$r,_t,Tt,Nt,Dt,Lt,Mr,Hr,re,lt,ae,ku,jn=jt(()=>{"use strict";Ot();Kn();Fr="1.0",Gn="127.0.0.1",$r=0,_t="/snapshot",Tt="/events",Nt="/graph",Dt="/outbox",Lt="/workflows",Mr="snapshot",Hr="in-process-local",re=32,lt=class extends Error{static{i(this,"ArkRunInspectorProductionError")}constructor(){super("ArkRun inspector refuses to start when NODE_ENV=production."),this.name="ArkRunInspectorProductionError"}},ae=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"}},ku=new Set(["","*","0","0.0.0.0","::","::0","[::]","[::0]","::ffff:0.0.0.0","[::ffff:0.0.0.0]"]);i(Un,"isArkRunInspectorProductionEnv");i(Iu,"ipv4Octets");i(Ka,"unwrapIpv4Mapped");i(ct,"isArkRunInspectorLoopbackHost");i(Ga,"closedHost");i(bu,"closedPort");i(Ft,"resolveArkRunInspectorBind");i(me,"arkRunInspectorUrl");i(vu,"jsonClone");i(Eu,"closedTransportFacts");i(Fe,"asRecord");i(Su,"closedOutboxSummary");i(Kr,"closedSampleLimit");i(He,"classifyArkRunInspectorStoreDurability");i($t,"buildArkRunInspectorHardening");i(Ke,"buildArkRunInspectorOutboxMonitor");i($e,"unavailableArkRunInspectorOutboxMonitor");i(wu,"closedWorkflowSummary");i(Cu,"isPendingWorkflowStatus");i(Ge,"buildArkRunInspectorWorkflowsMonitor");i(Me,"unavailableArkRunInspectorWorkflowsMonitor");i(xu,"closedOutboxMonitor");i(Ou,"closedWorkflowsMonitor");i(Vn,"buildArkRunInspectorSnapshot");i(Mt,"formatArkRunInspectorSseEvent")});var Ua={};fs(Ua,{listenArkRunInspector:()=>Fu});function Pu(){return{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}}function _u(){return{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-store",connection:"keep-alive","x-accel-buffering":"no"}}function Tu(e){let t=e&&e.length>0?e:"/";return new URL(t,"http://127.0.0.1")}function Ue(e,t,n){if(!(e.writableEnded||e.destroyed))try{e.writeHead(t,Pu()),e.end(JSON.stringify(n))}catch{}}function Nu(e,t){let n=e.address();if(n===null||typeof n=="string")throw new ae(t.host);if(!ct(n.address))throw new ae(n.address);return{host:t.host,port:n.port}}async function Du(e){if(typeof e.listInspectorOutbox=="function")return e.listInspectorOutbox();let t=e.outbox??e.eventBuffer;if(!t||typeof t.list!="function")return $e();let[n,r]=await Promise.all([t.list("pending"),t.list("failed")]);return Ke([...n??[],...r??[]],{sampleLimit:re})}async function Lu(e){return typeof e.listInspectorWorkflows=="function"?e.listInspectorWorkflows():!e.workflowEngine||typeof e.workflowEngine.list!="function"?Me():Ge(await e.workflowEngine.list(),{sampleLimit:re})}async function Fu(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=Tu(u.url),p=y.pathname;if(u.method==="GET"&&(p==="/"||p===_t)){Ue(f,200,l());return}if(u.method==="GET"&&p===Nt){try{Ue(f,200,e.requestGraph($n({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 ee){Ue(f,400,{error:g.message,option:g.option});return}throw g}return}if(u.method==="GET"&&p===Dt){Du(e).then(g=>Ue(f,200,g)).catch(g=>{Ue(f,500,{error:g instanceof Error?g.message:"outbox monitor failed"})});return}if(u.method==="GET"&&p===Lt){Lu(e).then(g=>Ue(f,200,g)).catch(g=>{Ue(f,500,{error:g instanceof Error?g.message:"workflows monitor failed"})});return}if(u.method==="GET"&&p===Tt){f.writeHead(200,_u()),f.flushHeaders(),f.write(Mt(l())),r.add(f);let g=s>0?setInterval(()=>{f.write(Mt(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}Ue(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=Nu(c,t.bind),u()}catch(p){f(p instanceof Error?p:new ae(t.bind.host))}})})}catch(u){throw await new Promise(f=>{c.close(()=>f())}),u}return{host:a.host,port:a.port,url:me(a.host,a.port,"/"),snapshotUrl:me(a.host,a.port,_t),eventsUrl:me(a.host,a.port,Tt),graphUrl:me(a.host,a.port,Nt),outboxUrl:me(a.host,a.port,Dt),workflowsUrl:me(a.host,a.port,Lt),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 Va=jt(()=>{"use strict";Nr();jn();i(Pu,"jsonHeaders");i(_u,"sseHeaders");i(Tu,"requestUrl");i(Ue,"writeJson");i(Nu,"boundAddress");i(Du,"resolveOutboxMonitor");i(Lu,"resolveWorkflowsMonitor");i(Fu,"listenArkRunInspector")});var Uu={};fs(Uu,{ANALYSIS_IR_SCHEMA_VERSION:()=>fr,ARK_ANALYSIS_RESULT_SCHEMA:()=>Br,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>Bt,ARK_DESIGN_DELTA_SCHEMA_VERSION:()=>Ca,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION:()=>wa,ARK_RUN_COMPONENT_LIFETIMES:()=>Sr,ARK_RUN_EPHEMERAL_DEFAULT:()=>at,ARK_RUN_GRAPH_DEFAULT_SLICE:()=>Pr,ARK_RUN_GRAPH_NODE_KINDS:()=>rs,ARK_RUN_GRAPH_PROCESS_EDGE_KINDS:()=>os,ARK_RUN_GRAPH_SCHEMA_VERSION:()=>Or,ARK_RUN_GRAPH_SLICES:()=>_r,ARK_RUN_GRAPH_TECHNICAL_EDGE_KINDS:()=>ss,ARK_RUN_INFORMATION_PACKAGE_SCHEMA_VERSION:()=>_n,ARK_RUN_INSPECTOR_DEFAULT_HOST:()=>Gn,ARK_RUN_INSPECTOR_DEFAULT_PORT:()=>$r,ARK_RUN_INSPECTOR_EVENTS_PATH:()=>Tt,ARK_RUN_INSPECTOR_GRAPH_PATH:()=>Nt,ARK_RUN_INSPECTOR_MONITOR_SAMPLE_LIMIT:()=>re,ARK_RUN_INSPECTOR_OUTBOX_PATH:()=>Dt,ARK_RUN_INSPECTOR_SCHEMA_VERSION:()=>Fr,ARK_RUN_INSPECTOR_SNAPSHOT_PATH:()=>_t,ARK_RUN_INSPECTOR_SSE_EVENT:()=>Mr,ARK_RUN_INSPECTOR_TRANSPORT_FALLBACK:()=>Hr,ARK_RUN_INSPECTOR_WORKFLOWS_PATH:()=>Lt,ARK_RUN_TRANSPORT_KINDS:()=>Pt,ArkRunInspectorBindError:()=>ae,ArkRunInspectorProductionError:()=>lt,DEFAULT_MAX_HISTORY_SIZE:()=>Gr,DIAGNOSTIC_CATALOG:()=>Sn,DIAGNOSTIC_CATALOG_SCHEMA_VERSION:()=>Ra,DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>vr,DIAGNOSTIC_RULE_IDS:()=>Aa,EventContractRegistryImpl:()=>mt,EventContractViolationError:()=>Ye,InMemoryAuditStore:()=>yt,InMemoryEventBuffer:()=>_e,InMemoryOutboxStore:()=>ro,InMemoryReadModelStore:()=>wt,InMemoryWorkflowStore:()=>Ct,IntentRegistry:()=>je,InvalidArkRunGraphQueryError:()=>ee,InvalidArkRunSendOptionError:()=>it,InvalidIntentNameError:()=>ze,LayerPolicyContextError:()=>qe,MANIFEST_SCHEMA_VERSION:()=>xn,ObservedLayerFlowViolationError:()=>Xe,POLICY_DELTA_SCHEMA_VERSION:()=>mr,PolicyEngine:()=>Oe,PolicyViolationError:()=>Re,RESOLVED_CANDIDATE_FACTS_SCHEMA:()=>pr,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION:()=>Ne,SourceMetadataOverrideError:()=>Ae,UnknownEventSourceError:()=>Pe,UnregisteredIntentError:()=>We,analyzeArchitectureConvergence:()=>rt,analyzeChange:()=>vn,analyzePolicyDelta:()=>Fo,analyzeProject:()=>vt,analyzeResolvedProject:()=>St,appendDecisionTape:()=>Zo,architecturalPolicies:()=>Zn,arkRunGraphQueryFromSearchParams:()=>$n,arkRunInspectorUrl:()=>me,buildArkRunInspectorHardening:()=>$t,buildArkRunInspectorOutboxMonitor:()=>Ke,buildArkRunInspectorSnapshot:()=>Vn,buildArkRunInspectorWorkflowsMonitor:()=>Ge,buildDependencyInformationPackage:()=>fe,buildPublishPolicyContext:()=>Zt,catalogFixForRuleId:()=>Ea,catalogWhyForRuleId:()=>Sa,checkAdapterGovernance:()=>lr,checkContract:()=>fo,classifyArkPolicyDelta:()=>yr,classifyArkRunInspectorStoreDurability:()=>He,closeArkRunGraphQuery:()=>Fn,closedArkRunEphemeral:()=>Lr,closedArkRunTransportKind:()=>Dr,collectAnalysisConfigWarnings:()=>En,collectForbiddenCapabilityUses:()=>tt,compareInformationPackages:()=>wr,createAICodeGate:()=>xo,createAdapter:()=>po,createAdapterResult:()=>ys,createArchitectureProfile:()=>cn,createArchitectureProfileFromArkConfig:()=>dn,createArkKernel:()=>Ht,createArkKernelFromConfig:()=>ls,createArkManifest:()=>On,createArkTestHarness:()=>so,createAuditTrail:()=>rn,createDependencyGraph:()=>on,createElevenLayerArkConfig:()=>co,createEventBus:()=>no,createEventContractRegistry:()=>tn,createIntentRegistry:()=>Wt,createLenientArkKernel:()=>Vr,createLenientArkKernelFromConfig:()=>ds,createMetadataRegistry:()=>un,createObservabilityReporter:()=>nn,createProjectionRegistry:()=>Cn,createResolvedCandidateFacts:()=>ur,createSaga:()=>zo,createStrictArkKernel:()=>Ur,createStrictArkKernelFromConfig:()=>cs,createWorkflowEngine:()=>xt,defaultIntentRegistry:()=>Yr,defineArchitectureProfilePolicy:()=>Xt,defineIntent:()=>qr,defineLayerPolicy:()=>qt,definePolicy:()=>Be,definePort:()=>uo,definePublishPolicy:()=>Xr,detectArchitectureCycles:()=>Ar,deterministicHash:()=>z,diagnosticDocsFragment:()=>Vo,diagnosticDocsPath:()=>ba,elevenLayerProfile:()=>Qe,evaluateArchitectureGraph:()=>st,explainViolation:()=>$o,extractSemanticDependencies:()=>et,formatArkRunGraphMermaid:()=>Tr,formatArkRunInspectorSseEvent:()=>Mt,getDiagnosticCatalogEntry:()=>wn,isArkRunInspectorLoopbackHost:()=>ct,isArkRunInspectorProductionEnv:()=>Un,isCataloguedOrArkRuleFamily:()=>Ia,isKnownDiagnosticCode:()=>ka,isLayerPolicy:()=>Yt,loadContract:()=>bn,loadResolvedCandidateFacts:()=>Ee,policyDeltaAcknowledgementMatches:()=>hr,preflightChange:()=>Ko,preflightResolvedChange:()=>Go,replayInformationPackages:()=>es,requestArkRunGraph:()=>Mn,resolveArkRunInspectorBind:()=>Ft,resolveArkRunSendPlan:()=>Hn,resolvedFactsEvidenceRequirementsHash:()=>bt,serializeDiagnosticCatalog:()=>va,shadowInformationPackage:()=>Qo,stableSerialize:()=>$,startArkRunInspector:()=>Bn,syncRegistryToGraph:()=>sn,toAdapterDiagnostic:()=>Xn,unavailableArkRunInspectorOutboxMonitor:()=>$e,unavailableArkRunInspectorWorkflowsMonitor:()=>Me,validateIntentName:()=>zt,version:()=>zn});module.exports=el(Uu);var zn="4.8.21";var tl=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,nl=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,rl=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function ol(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),o=String(t?.toLayer??"");return tl.test(n)?"pure-shared":r==="PersistenceAdapters"&&(nl.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${o} ${n}`))?"kernel-emit":rl.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&o==="PersistenceAdapters"?"use-case":"unknown"}i(ol,"classifyLayerImportKind");function sl(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=ol(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(sl,"layerImportNextAction");function il(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}i(il,"arkRunCallSiteName");function al(e){let t=il(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(al,"arkRunNextAction");function pe(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return sl(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 al(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 Bt="1.5",jr="docs/diagnostics.md",Br={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","mode","valid","completeness","completenessReasons","diagnostics"],allOf:[{if:{properties:{completeness:{enum:["partial","unavailable"]}},required:["completeness"]},then:{properties:{valid:{const:!1}}}},{if:{properties:{mode:{const:"resolved-candidate-facts"},completeness:{enum:["complete","partial"]}},required:["mode","completeness"]},then:{required:["policyHash","resolverIdentity","factsHash","candidateTreeHash"]}},{if:{properties:{completeness:{const:"complete"}},required:["completeness"]},then:{properties:{completenessReasons:{maxItems:0}}},else:{properties:{completenessReasons:{minItems:1}}}}],properties:{schemaVersion:{const:"1.5"},mode:{enum:["lexical-compatibility","resolved-candidate-facts"]},valid:{type:"boolean"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:{type:"string",minLength:1},message:{type:"string",minLength:1},file:{type:"string",minLength:1}}}},policyHash:{type:"string",minLength:1},resolverIdentity:{type:"string",minLength:1},factsHash:{type:"string",minLength:1},candidateTreeHash:{type:"string",minLength:1},diagnostics:{type:"array",items:{type:"object",additionalProperties:!1,required:["ruleId","severity","message","location","evidence"],properties:{ruleId:{type:"string",minLength:1},severity:{enum:["error","warning"]},message:{type:"string",minLength:1},location:{type:"object",additionalProperties:!1,required:["file","line","column"],properties:{file:{type:"string",minLength:1},line:{type:"integer",minimum:1},column:{type:"integer",minimum:1}}},evidence:{type:"object",additionalProperties:!1,properties:{target:{type:"string"},fromLayer:{type:"string"},toLayer:{type:"string"},typeOnly:{type:"boolean"},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"},peerIsolation:{type:"boolean"},capability:{type:"string",minLength:1},edgeKind:{type:"string",minLength:1},arkruleId:{type:"string",minLength:1},arkruleSource:{type:"string",minLength:1}}},nextAction:{type:"string",minLength:1},findingRef:{type:"string",minLength:1,pattern:"^fnv1a-[0-9a-f]{8}$"},targetKey:{type:"string",minLength:1},docsCodePath:{type:"string",minLength:1}}}}}};function qn(e){let t=typeof e.ruleId=="string"?e.ruleId:typeof e.code=="string"?e.code:void 0,n=typeof e.file=="string"?e.file:void 0,r=typeof e.fromLayer=="string"?e.fromLayer:void 0,o=typeof e.toLayer=="string"?e.toLayer:void 0,s=typeof e.target=="string"?e.target:void 0;return[t,n,r??"",o??"",s??""].join("|")}i(qn,"adapterFindingTargetKey");function Yn(e){let t=new Map;return e.map(n=>{let r=qn(n),o=(t.get(r)??0)+1;return t.set(r,o),o===1?r:`${r}#${o}`})}i(Yn,"adapterFindingOccurrenceTargetKeys");function Wr(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(Wr,"adapterFindingRefFromTargetKey");function zr(e){return`${jr}#${e}`}i(zr,"adapterDocsCodePath");function O(e){return typeof e=="string"&&e.length>0?e:void 0}i(O,"text");function ms(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}i(ms,"positiveInteger");function ll(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(ll,"nextActionForDiagnostic");function Xn(e,t="error",n){let r=O(e.ruleId)??O(e.code)??"ARK_UNKNOWN",o=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,s={...O(e.target)?{target:O(e.target)}:{},...O(e.fromLayer)?{fromLayer:O(e.fromLayer)}:{},...O(e.toLayer)?{toLayer:O(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{},...typeof e.targetTypeOnlyExports=="boolean"?{targetTypeOnlyExports:e.targetTypeOnlyExports}:{},...typeof e.sourcePureTypeModule=="boolean"?{sourcePureTypeModule:e.sourcePureTypeModule}:{},...typeof e.namedBindingsTypeOnly=="boolean"?{namedBindingsTypeOnly:e.namedBindingsTypeOnly}:{},...typeof e.portProofEligible=="boolean"?{portProofEligible:e.portProofEligible}:{},...typeof e.peerIsolation=="boolean"?{peerIsolation:e.peerIsolation}:{},...O(e.capability)?{capability:O(e.capability)}:{},...O(e.edgeKind)?{edgeKind:O(e.edgeKind)}:{},...O(e.arkruleId)?{arkruleId:O(e.arkruleId)}:{},...O(e.arkruleSource)?{arkruleSource:O(e.arkruleSource)}:{}},a=n??qn(e),l=Wr(a);return{ruleId:r,severity:o,message:O(e.message)??r,location:{file:O(e.file)??"<unknown>",line:ms(e.line,1),column:ms(e.column,1)},evidence:s,nextAction:O(e.nextAction)??ll(r,s,e),findingRef:l,targetKey:a,docsCodePath:zr(r)}}i(Xn,"toAdapterDiagnostic");function ys(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)=>Xn(y,"error",l[p])),...a.map((y,p)=>Xn(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(ys,"createAdapterResult");var je=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 hs=new je;function qr(e,t){return hs.define(e,t)}i(qr,"defineIntent");function Wt(){return new je}i(Wt,"createIntentRegistry");var Yr=hs;var Rs=["Domain.","Application.","Adapter.","Workflow.","Job.","Presentation.","Reporting.","Metadata.","Security.","Audit.","Observability.","Kernel."];function zt(e){if(!e||typeof e!="string")return{valid:!1,reason:"Intent name must be a non-empty string"};if(!Rs.some(n=>e.startsWith(n)))return{valid:!1,reason:`Intent "${e}" must start with one of: ${Rs.join(", ")}`};let t=e.slice(e.indexOf(".")+1);return!t||!/^[A-Za-z][A-Za-z0-9_.]*$/.test(t)?{valid:!1,reason:`Intent "${e}" has an invalid segment after the layer prefix`}:{valid:!0}}i(zt,"validateIntentName");var Re=class extends Error{static{i(this,"PolicyViolationError")}violations;constructor(t){let n=t.map(r=>`- ${r.policyName}: ${r.message}`).join(`
|
|
5
|
+
`}var Xr,Qn,Zr,Ht,Kt,Gt,Ut,Vt,Jr,Qr,ie,pt,ce,jp,nr=Jt(()=>{"use strict";$t();Jn();Xr="1.0",Qn="127.0.0.1",Zr=0,Ht="/snapshot",Kt="/events",Gt="/graph",Ut="/outbox",Vt="/workflows",Jr="snapshot",Qr="in-process-local",ie=32,pt=class extends Error{static{a(this,"ArkRunInspectorProductionError")}constructor(){super("ArkRun inspector refuses to start when NODE_ENV=production."),this.name="ArkRunInspectorProductionError"}},ce=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"}},jp=new Set(["","*","0","0.0.0.0","::","::0","[::]","[::0]","::ffff:0.0.0.0","[::ffff:0.0.0.0]"]);a(er,"isArkRunInspectorProductionEnv");a(Bp,"ipv4Octets");a(yl,"unwrapIpv4Mapped");a(ft,"isArkRunInspectorLoopbackHost");a(hl,"closedHost");a(Wp,"closedPort");a(jt,"resolveArkRunInspectorBind");a(ke,"arkRunInspectorUrl");a(zp,"jsonClone");a(qp,"closedTransportFacts");a(He,"asRecord");a(Yp,"closedOutboxSummary");a(eo,"closedSampleLimit");a(Ue,"classifyArkRunInspectorStoreDurability");a(Bt,"buildArkRunInspectorHardening");a(Ve,"buildArkRunInspectorOutboxMonitor");a(Ke,"unavailableArkRunInspectorOutboxMonitor");a(Xp,"closedWorkflowSummary");a(Zp,"isPendingWorkflowStatus");a(je,"buildArkRunInspectorWorkflowsMonitor");a(Ge,"unavailableArkRunInspectorWorkflowsMonitor");a(Jp,"closedOutboxMonitor");a(Qp,"closedWorkflowsMonitor");a(tr,"buildArkRunInspectorSnapshot");a(Wt,"formatArkRunInspectorSseEvent")});var Rl={};Ns(Rl,{listenArkRunInspector:()=>af});function ef(){return{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}}function tf(){return{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-store",connection:"keep-alive","x-accel-buffering":"no"}}function nf(e){let t=e&&e.length>0?e:"/";return new URL(t,"http://127.0.0.1")}function Be(e,t,n){if(!(e.writableEnded||e.destroyed))try{e.writeHead(t,ef()),e.end(JSON.stringify(n))}catch{}}function rf(e,t){let n=e.address();if(n===null||typeof n=="string")throw new ce(t.host);if(!ft(n.address))throw new ce(n.address);return{host:t.host,port:n.port}}async function of(e){if(typeof e.listInspectorOutbox=="function")return e.listInspectorOutbox();let t=e.outbox??e.eventBuffer;if(!t||typeof t.list!="function")return Ke();let[n,r]=await Promise.all([t.list("pending"),t.list("failed")]);return Ve([...n??[],...r??[]],{sampleLimit:ie})}async function sf(e){return typeof e.listInspectorWorkflows=="function"?e.listInspectorWorkflows():!e.workflowEngine||typeof e.workflowEngine.list!="function"?Ge():je(await e.workflowEngine.list(),{sampleLimit:ie})}async function af(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=nf(u.url),p=y.pathname;if(u.method==="GET"&&(p==="/"||p===Ht)){Be(f,200,l());return}if(u.method==="GET"&&p===Gt){try{Be(f,200,e.requestGraph(Yn({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 re){Be(f,400,{error:g.message,option:g.option});return}throw g}return}if(u.method==="GET"&&p===Ut){of(e).then(g=>Be(f,200,g)).catch(g=>{Be(f,500,{error:g instanceof Error?g.message:"outbox monitor failed"})});return}if(u.method==="GET"&&p===Vt){sf(e).then(g=>Be(f,200,g)).catch(g=>{Be(f,500,{error:g instanceof Error?g.message:"workflows monitor failed"})});return}if(u.method==="GET"&&p===Kt){f.writeHead(200,tf()),f.flushHeaders(),f.write(Wt(l())),r.add(f);let g=s>0?setInterval(()=>{f.write(Wt(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}Be(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=rf(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:i.host,port:i.port,url:ke(i.host,i.port,"/"),snapshotUrl:ke(i.host,i.port,Ht),eventsUrl:ke(i.host,i.port,Kt),graphUrl:ke(i.host,i.port,Gt),outboxUrl:ke(i.host,i.port,Ut),workflowsUrl:ke(i.host,i.port,Vt),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 Al=Jt(()=>{"use strict";zr();nr();a(ef,"jsonHeaders");a(tf,"sseHeaders");a(nf,"requestUrl");a(Be,"writeJson");a(rf,"boundAddress");a(of,"resolveOutboxMonitor");a(sf,"resolveWorkflowsMonitor");a(af,"listenArkRunInspector")});var ff={};Ns(ff,{ANALYSIS_IR_SCHEMA_VERSION:()=>wr,ARK_ANALYSIS_RESULT_SCHEMA:()=>so,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>Qt,ARK_DESIGN_DELTA_SCHEMA_VERSION:()=>rl,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION:()=>nl,ARK_RUN_COMPONENT_LIFETIMES:()=>Hr,ARK_RUN_EPHEMERAL_DEFAULT:()=>ut,ARK_RUN_GRAPH_DEFAULT_SLICE:()=>jr,ARK_RUN_GRAPH_NODE_KINDS:()=>Ss,ARK_RUN_GRAPH_PROCESS_EDGE_KINDS:()=>vs,ARK_RUN_GRAPH_SCHEMA_VERSION:()=>Vr,ARK_RUN_GRAPH_SLICES:()=>Br,ARK_RUN_GRAPH_TECHNICAL_EDGE_KINDS:()=>Es,ARK_RUN_INFORMATION_PACKAGE_SCHEMA_VERSION:()=>Vn,ARK_RUN_INSPECTOR_DEFAULT_HOST:()=>Qn,ARK_RUN_INSPECTOR_DEFAULT_PORT:()=>Zr,ARK_RUN_INSPECTOR_EVENTS_PATH:()=>Kt,ARK_RUN_INSPECTOR_GRAPH_PATH:()=>Gt,ARK_RUN_INSPECTOR_MONITOR_SAMPLE_LIMIT:()=>ie,ARK_RUN_INSPECTOR_OUTBOX_PATH:()=>Ut,ARK_RUN_INSPECTOR_SCHEMA_VERSION:()=>Xr,ARK_RUN_INSPECTOR_SNAPSHOT_PATH:()=>Ht,ARK_RUN_INSPECTOR_SSE_EVENT:()=>Jr,ARK_RUN_INSPECTOR_TRANSPORT_FALLBACK:()=>Qr,ARK_RUN_INSPECTOR_WORKFLOWS_PATH:()=>Vt,ARK_RUN_TRANSPORT_KINDS:()=>Mt,ArkRunInspectorBindError:()=>ce,ArkRunInspectorProductionError:()=>pt,DEFAULT_MAX_HISTORY_SIZE:()=>to,DIAGNOSTIC_CATALOG:()=>$n,DIAGNOSTIC_CATALOG_SCHEMA_VERSION:()=>qa,DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>$r,DIAGNOSTIC_RULE_IDS:()=>Ya,EventContractRegistryImpl:()=>At,EventContractViolationError:()=>Ze,InMemoryAuditStore:()=>kt,InMemoryEventBuffer:()=>Le,InMemoryOutboxStore:()=>ko,InMemoryReadModelStore:()=>Lt,InMemoryWorkflowStore:()=>Dt,IntentRegistry:()=>We,InvalidArkRunGraphQueryError:()=>re,InvalidArkRunSendOptionError:()=>dt,InvalidIntentNameError:()=>Ye,LayerPolicyContextError:()=>Xe,MANIFEST_SCHEMA_VERSION:()=>Kn,ObservedLayerFlowViolationError:()=>Je,POLICY_DELTA_SCHEMA_VERSION:()=>Or,PolicyEngine:()=>_e,PolicyViolationError:()=>be,RESOLVED_CANDIDATE_FACTS_SCHEMA:()=>Er,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION:()=>Fe,SourceMetadataOverrideError:()=>Se,UnknownEventSourceError:()=>Te,UnregisteredIntentError:()=>qe,analyzeArchitectureConvergence:()=>at,analyzeChange:()=>Dn,analyzePolicyDelta:()=>ts,analyzeProject:()=>_t,analyzeResolvedProject:()=>Nt,appendDecisionTape:()=>hs,architecturalPolicies:()=>cr,arkRunGraphQueryFromSearchParams:()=>Yn,arkRunInspectorUrl:()=>ke,buildArkRunInspectorHardening:()=>Bt,buildArkRunInspectorOutboxMonitor:()=>Ve,buildArkRunInspectorSnapshot:()=>tr,buildArkRunInspectorWorkflowsMonitor:()=>je,buildDependencyInformationPackage:()=>Re,buildPublishPolicyContext:()=>sn,catalogFixForRuleId:()=>el,catalogWhyForRuleId:()=>tl,checkAdapterGovernance:()=>Ir,checkContract:()=>Oo,classifyArkPolicyDelta:()=>Pr,classifyArkRunInspectorStoreDurability:()=>Ue,closeArkRunGraphQuery:()=>qn,closedArkRunEphemeral:()=>Yr,closedArkRunTransportKind:()=>qr,collectAnalysisConfigWarnings:()=>Fn,collectForbiddenCapabilityUses:()=>st,compareInformationPackages:()=>Kr,createAICodeGate:()=>jo,createAdapter:()=>xo,createAdapterResult:()=>Fs,createArchitectureProfile:()=>In,createArchitectureProfileFromArkConfig:()=>bn,createArkKernel:()=>zt,createArkKernelFromConfig:()=>xs,createArkManifest:()=>Gn,createArkTestHarness:()=>bo,createAuditTrail:()=>mn,createDependencyGraph:()=>yn,createElevenLayerArkConfig:()=>wo,createEventBus:()=>Ao,createEventContractRegistry:()=>fn,createIntentRegistry:()=>en,createLenientArkKernel:()=>ro,createLenientArkKernelFromConfig:()=>Ps,createMetadataRegistry:()=>Sn,createObservabilityReporter:()=>gn,createProjectionRegistry:()=>Hn,createResolvedCandidateFacts:()=>vr,createSaga:()=>fs,createStrictArkKernel:()=>no,createStrictArkKernelFromConfig:()=>Os,createWorkflowEngine:()=>Ft,defaultIntentRegistry:()=>co,defineArchitectureProfilePolicy:()=>on,defineIntent:()=>lo,defineLayerPolicy:()=>nn,definePolicy:()=>ze,definePort:()=>Co,definePublishPolicy:()=>uo,detectArchitectureCycles:()=>Nr,deterministicHash:()=>Y,diagnosticDocsFragment:()=>cs,diagnosticDocsPath:()=>Ja,elevenLayerProfile:()=>rt,evaluateArchitectureGraph:()=>ct,explainViolation:()=>ns,extractSemanticDependencies:()=>ot,formatArkRunGraphMermaid:()=>Wr,formatArkRunInspectorSseEvent:()=>Wt,getDiagnosticCatalogEntry:()=>Mn,isArkRunInspectorLoopbackHost:()=>ft,isArkRunInspectorProductionEnv:()=>er,isCataloguedOrArkRuleFamily:()=>Za,isKnownDiagnosticCode:()=>Xa,isLayerPolicy:()=>rn,loadContract:()=>Ln,loadResolvedCandidateFacts:()=>Ce,policyDeltaAcknowledgementMatches:()=>_r,preflightChange:()=>is,preflightResolvedChange:()=>as,replayInformationPackages:()=>ks,requestArkRunGraph:()=>Xn,resolveArkRunInspectorBind:()=>jt,resolveArkRunSendPlan:()=>Zn,resolvedFactsEvidenceRequirementsHash:()=>xt,serializeDiagnosticCatalog:()=>Qa,shadowInformationPackage:()=>As,stableSerialize:()=>$,startArkRunInspector:()=>rr,syncRegistryToGraph:()=>hn,toAdapterDiagnostic:()=>lr,unavailableArkRunInspectorOutboxMonitor:()=>Ke,unavailableArkRunInspectorWorkflowsMonitor:()=>Ge,validateIntentName:()=>tn,version:()=>sr});module.exports=Pl(ff);var sr="4.8.23";var _l=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,Tl=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,Nl=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function Ll(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),o=String(t?.toLayer??"");return _l.test(n)?"pure-shared":r==="PersistenceAdapters"&&(Tl.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${o} ${n}`))?"kernel-emit":Nl.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&o==="PersistenceAdapters"?"use-case":"unknown"}a(Ll,"classifyLayerImportKind");function Dl(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=Ll(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(Dl,"layerImportNextAction");function Fl(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}a(Fl,"arkRunCallSiteName");function $l(e){let t=Fl(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($l,"arkRunNextAction");function ye(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return Dl(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 $l(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 Qt="1.5",oo="docs/diagnostics.md",so={$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 ir(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(ir,"adapterFindingTargetKey");function ar(e){let t=new Map;return e.map(n=>{let r=ir(n),o=(t.get(r)??0)+1;return t.set(r,o),o===1?r:`${r}#${o}`})}a(ar,"adapterFindingOccurrenceTargetKeys");function io(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(io,"adapterFindingRefFromTargetKey");function ao(e){return`${oo}#${e}`}a(ao,"adapterDocsCodePath");function P(e){return typeof e=="string"&&e.length>0?e:void 0}a(P,"text");function Ds(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}a(Ds,"positiveInteger");function Ml(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(Ml,"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??ir(e),l=io(i);return{ruleId:r,severity:o,message:P(e.message)??r,location:{file:P(e.file)??"<unknown>",line:Ds(e.line,1),column:Ds(e.column,1)},evidence:s,nextAction:P(e.nextAction)??Ml(r,s,e),findingRef:l,targetKey:i,docsCodePath:ao(r)}}a(lr,"toAdapterDiagnostic");function Fs(e){let t=e.completeness??"complete",n=e.mode??"lexical-compatibility";if(t==="complete"&&(e.completenessReasons?.length??0)>0)throw new Error("completenessReasons must be empty when completeness is complete.");let r=t==="complete"?[]:e.completenessReasons&&e.completenessReasons.length>0?e.completenessReasons.map(y=>({code: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=ar(s),c=ar(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(Fs,"createAdapterResult");var We=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 $s=new We;function lo(e,t){return $s.define(e,t)}a(lo,"defineIntent");function en(){return new We}a(en,"createIntentRegistry");var co=$s;var Ms=["Domain.","Application.","Adapter.","Workflow.","Job.","Presentation.","Reporting.","Metadata.","Security.","Audit.","Observability.","Kernel."];function tn(e){if(!e||typeof e!="string")return{valid:!1,reason:"Intent name must be a non-empty string"};if(!Ms.some(n=>e.startsWith(n)))return{valid:!1,reason:`Intent "${e}" must start with one of: ${Ms.join(", ")}`};let t=e.slice(e.indexOf(".")+1);return!t||!/^[A-Za-z][A-Za-z0-9_.]*$/.test(t)?{valid:!1,reason:`Intent "${e}" has an invalid segment after the layer prefix`}:{valid:!0}}a(tn,"validateIntentName");var be=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 Oe=class{static{i(this,"PolicyEngine")}policies=[];constructor(t=[]){for(let n of t)this.add(n)}add(t){if(this.policies.some(n=>n.name===t.name))throw new Error(`Policy "${t.name}" is already registered in this engine.`);this.policies.push(t)}getPolicies(){return[...this.policies]}evaluate(t){let n=[];for(let s of this.policies){let a=s.check(t);if(a!==!0){if(a===!1){n.push({policyName:s.name,severity:s.severity,message:`Policy "${s.name}" was violated.`});continue}if(Array.isArray(a))for(let l of a)n.push({policyName:s.name,severity:s.severity,message:l.message,details:l.details});else n.push({policyName:s.name,severity:s.severity,message:a.message,details:a.details})}}let r=n.filter(s=>s.severity==="hard"),o=n.filter(s=>s.severity==="soft");return{passed:n.length===0,violations:n,hardViolations:r,softViolations:o}}enforce(t){let n=this.evaluate(t);if(n.hardViolations.length>0)throw new Re(n.hardViolations);return n}clear(){this.policies.length=0}};function Be(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(Be,"definePolicy");function cl(e){let t=e.indexOf(".");return t>=0?e.slice(0,t):e}i(cl,"defaultLayerOf");function As(e,t){return t.resolveLayer?.(e)??cl(e)}i(As,"resolveLayer");function dl(e,t,n){return e===n.from&&t===n.to}i(dl,"matchesRule");function qt(e){let t=e.name??"Layer isolation",n=e.severity??"hard";return Be({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=As(a.from,e),c=As(a.to,e);for(let u of e.rules)!u.allowed&&dl(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(qt,"defineLayerPolicy");function Yt(e){return e.tags?.includes("layer")??!1}i(Yt,"isLayerPolicy");var Zn={layerIsolation(){return Zn.cleanArchitectureMatrix()},cleanArchitectureMatrix(){return qt({name:"Clean architecture matrix",severity:"hard",rules:[{from:"Domain",to:"Adapter",allowed:!1},{from:"Domain",to:"Application",allowed:!1},{from:"Adapter",to:"Application",allowed:!1},{from:"Adapter",to:"Domain",allowed:!1}]})}};function Xt(e,t={}){return qt({name:t.name??`${e.name} layer policy`,severity:t.severity??"hard",rules:e.rules,resolveLayer:e.resolveLayer})}i(Xt,"defineArchitectureProfilePolicy");function Zt(e){return t=>({event:t,relationships:e.intentRegistry?.getAllRelationships(),edges:e.dependencyGraph?.getEdges()})}i(Zt,"buildPublishPolicyContext");function Xr(e){return Be(e)}i(Xr,"definePublishPolicy");var We=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}},qe=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"}},Ye=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}},Pe=class extends Error{static{i(this,"UnknownEventSourceError")}intentName;source;constructor(t,n){super(n?`Event "${t}" metadata.source "${n}" is not registered. Register the producer intent or publish from a known source.`:`Event "${t}" must include metadata.source. Strict Ark uses source to enforce observed layer flow.`),this.name="UnknownEventSourceError",this.intentName=t,this.source=n}},Ae=class extends Error{static{i(this,"SourceMetadataOverrideError")}boundSource;attemptedSource;constructor(t,n){super(`Source-bound publisher for "${t}" cannot publish with metadata.source "${n}". Create a publisher for the intended source instead.`),this.name="SourceMetadataOverrideError",this.boundSource=t,this.attemptedSource=n}},Xe=class extends Error{static{i(this,"ObservedLayerFlowViolationError")}source;intentName;fromLayer;toLayer;constructor(t,n,r,o,s){super(s??`Observed layer violation: "${t}" (${r}) must not produce "${n}" (${o}). Route this through an allowed layer or adjust the architecture profile rule.`),this.name="ObservedLayerFlowViolationError",this.source=t,this.intentName=n,this.fromLayer=r,this.toLayer=o}};function Jt(e,t){if(!(!t.strictRegistry&&!t.validateIntentNaming)){if(t.validateIntentNaming){let n=zt(e);if(!n.valid)throw new ze(e,n.reason)}if(t.strictRegistry&&t.intentRegistry&&!t.intentRegistry.has(e))throw new We(e)}}i(Jt,"assertIntentAllowed");function ks(e,t){if(t.requireKnownSource){if(!e.metadata.source||e.metadata.source==="unknown")throw new Pe(e.intent);if(t.intentRegistry&&!t.intentRegistry.has(e.metadata.source))throw new Pe(e.intent,e.metadata.source)}}i(ks,"assertSourceAllowed");function Qt(e,t){if(!t.eventContracts)return;let n=t.eventContracts.validate(e);if(!n.ok&&(t.strictEventContracts||n.contract))throw new Ye(e.intent,n.issues)}i(Qt,"assertContractAllowed");function dt(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}i(dt,"isPlainRecord");function ut(e){return Array.isArray(e)?e.map(ut):dt(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,ut(n)])):e}i(ut,"clonePatchValue");function Zr(e,t,n="payload"){let r={...e};for(let[o,s]of Object.entries(t)){let a=`${n}.${o}`;if(!(o in r)||r[o]===void 0){r[o]=ut(s);continue}if(dt(r[o])&&dt(s)){r[o]=Zr(r[o],s,a);continue}if(Array.isArray(r[o])&&Array.isArray(s)){r[o]=Jr(r[o],s,a);continue}throw new Error(`Interceptor patch cannot overwrite existing ${a}.`)}return r}i(Zr,"mergeRecordPatch");function Jr(e,t,n="payload"){let r=[...e];return t.forEach((o,s)=>{let a=`${n}[${s}]`;if(s>=r.length||r[s]===void 0){r[s]=ut(o);return}if(dt(r[s])&&dt(o)){r[s]=Zr(r[s],o,a);return}if(Array.isArray(r[s])&&Array.isArray(o)){r[s]=Jr(r[s],o,a);return}throw new Error(`Interceptor patch cannot overwrite existing ${a}.`)}),r}i(Jr,"mergeArrayPatch");function Is(e,t){if(Array.isArray(t)){if(e===void 0)return ut(t);if(!Array.isArray(e))throw new Error("Array interceptor patch requires an array payload.");return Jr(e,t)}if(e===void 0)return ut(t);if(!dt(e))throw new Error("Object interceptor patch requires an object payload.");return Zr(e,t)}i(Is,"applyPayloadPatch");async function bs(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:Is(l.payload,c),metadata:{...l.metadata}};Qt(l,{eventContracts:t.eventContracts,strictEventContracts:t.strictEventContracts}),r=l,o.lastInterceptedAt=a,t.appendTrace({type:"event.intercepted",timestamp:a,intent:r.intent,correlationId:r.metadata.correlationId,traceId:r.metadata.traceId,spanId:r.metadata.spanId,details:{registrationId:o.registrationId,interceptorId:o.interceptorId,patchesApplied:s.length}}),await t.recordAudit("event.intercepted",r,{registrationId:o.registrationId,interceptorId:o.interceptorId,patchesApplied:s.length})}catch(a){await ul(o,r,a,t)}}return r}i(bs,"applyInterceptors");async function ul(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(ul,"recordInterceptorError");var vs=new Map;function Es(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(Es,"escapeLiteral");function Qn(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(Qn,"normalizeGlobSeparators");function pl(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(pl,"bracesBalanced");function ke(e){let t=vs.get(e);if(t)return t;let n=Qn(e),r=pl(n),o="",s=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(o+=Es(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+=Es(c)}let a=new RegExp(`^${o}$`);return vs.set(e,a),a}i(ke,"globToRegExp");function fl(e){return Qn(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}i(fl,"concreteGlobSegments");function eo(e,t){let n=Qn(String(e)),r=fl(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(eo,"patternSpecificity");function de(e,t){let n=String(e).split(/[/\\]/).join("/"),r,o=-1;for(let s of t??[])if(!(s.exclude??[]).some(a=>ke(a).test(n))){for(let a of s.patterns??[])if(ke(a).test(n)){let l=eo(a,n);l>o&&(o=l,r=s.name)}}return r}i(de,"layerForRelativePath");function Jn(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(Cs(a)){let l=gl(o,a,r);if(l)return l;continue}!a.includes("/")&&!a.includes("\\")&&!a.includes("*")&&s.add(a.toLowerCase())}return Rl(o,s)}i(Jn,"sliceIdForPath");function Cs(e){let t=e.split(/[/\\]/).filter(n=>n.length>0);return t.length<2||t[0]==="*"||t[0]==="**"?!1:t.some(n=>n==="*")}i(Cs,"isAnchoredSliceEntry");function gl(e,t,n){let r=t.split(/[/\\]/).filter(s=>s.length>0).map(s=>s.toLowerCase()),o=_s(e,r[0]??"");for(let s of o){let a=ml(e,r,s,n);if(a)return a}}i(gl,"anchoredSliceId");function ml(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(ml,"bindAnchoredSlice");function xs(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=yl(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:hl(n.from,n.to,a,s)})}return t}i(xs,"sliceIdentityCollisions");function yl(e){if(!Cs(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(yl,"starsIdentityStem");function hl(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(hl,"formatSliceIdentityCollision");function Rl(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(Rl,"bareSliceId");function Al(e){let t=new Set;for(let n of e??[]){let o=Qn(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(Al,"inferSliceFoldersFromPatterns");function Os(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 Al(r?.patterns)}i(Os,"resolveSliceFolders");function Ss(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}i(Ss,"normalizeSegments");function Ps(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}i(Ps,"trimTrailingSlashes");var kl=["src","app"];function _s(e,t){let n=(e[0]??"").toLowerCase(),r=t.toLowerCase();return kl.includes(n)&&r!==n?[0,1]:[0]}i(_s,"anchorOffsets");function Il(e){let t=Ps(e.replace(/^[./]+/,""));return t==="*"||t==="**"}i(Il,"isBlanketRoot");function Qr(e,t){if(!e||!t?.length)return!1;let n=String(e).split(/[/\\]/).join("/"),r=n.toLowerCase(),o=Ss(n);for(let s of t){if(typeof s!="string"||s.length===0||Il(s))continue;if(s.includes("*")){let c=Ps(s.toLowerCase());if(ke(c).test(r)||ke(`${c}/**`).test(r))return!0;continue}let a=Ss(s);if(a.length===0)continue;let l=_s(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(Qr,"pathUnderSharedRoot");function ws(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(ws,"sliceMatchesDeclaration");function bl(e,t,n){return!e?.length||!t||!n?!1:e.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&ws(r.from,t)&&ws(r.to,n))}i(bl,"crossSliceEdgeAllowed");function vl(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(vl,"peerIsolationDecision");function pt(e,t){switch(e){case"cross-slice":return`cross-slice edge ${t.fromSlice??"?"} \u2192 ${t.toSlice??"?"}. Extract the shared code, use events/ports across slices, or declare the edge in the rule's allowedCrossSlice.`;case"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(pt,"peerIsolationDenyExplanation");function ft(e,t,n,r){return Ze(e,t,n,r)?.rule}i(ft,"findDeniedEdgeRule");function Ze(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=Os(o,t,r?.layers),c=s?Jn(s,l,o.sliceIdentity):void 0,u=a?Jn(a,l,o.sliceIdentity):void 0,f=vl({fromPath:s,toPath:a,folderCount:l.length,fromSlice:c,toSlice:u,fromShared:!c&&Qr(s,o.sharedRoots),toShared:!u&&Qr(a,o.sharedRoots),crossSliceAllowed:bl(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(Ze,"findDeniedEdgeDecision");function Ts(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=Os(a,t,r?.layers),c=Jn(o,l,a.sliceIdentity),u=Jn(s,l,a.sliceIdentity);if(!(c||!u)&&Qr(o,a.sharedRoots))return{fromPath:o,toPath:s,toSlice:u}}}i(Ts,"findSharedImportsSliceBridge");async function Ns(e,t){if(t.mode==="off"||!t.architectureProfile)return;let n=e.metadata.source;if(!n||n==="unknown")return;let r=t.architectureProfile,o=r.resolveLayer(n),s=r.resolveLayer(e.intent);if(!o||!s)return;let a=ft(r.rules,o,s);if(!a)return;let l=t.mode,c=a.message??`Observed layer violation: "${n}" (${o}) must not produce "${e.intent}" (${s}).`,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 Xe(n,e.intent,o,s,c)}i(Ns,"assertObservedLayerFlowAllowed");async function Ds(e,t){let n=t.getPolicyContext(e),r;try{r=t.policyEngine.enforce(n)}catch(o){throw o instanceof Re&&(t.appendTrace({type:"policy.hardViolation",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:{violations:o.violations}}),await t.recordAudit("policy.hardViolation",e,{violations:o.violations})),o}r.softViolations.length>0&&(t.appendTrace({type:"policy.softViolation",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:{violations:r.softViolations}}),await t.recordAudit("policy.softViolation",e,{violations:r.softViolations}),t.onSoftViolation&&await t.safeHook(()=>t.onSoftViolation(r,e),"onSoftViolation",e))}i(Ds,"enforcePublishPolicy");function El(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(El,"appendHistory");function en(e,t){e.trace.push(t),e.maxHistorySize!==void 0&&e.trace.length>e.maxHistorySize&&e.trace.splice(0,e.trace.length-e.maxHistorySize);for(let n of e.traceSinks)try{n(t)}catch{}}i(en,"appendTrace");async function er(e,t,n,r){if(e.auditTrail)try{await e.auditTrail.record({type:t,source:n.metadata.source,intent:n.intent,correlationId:n.metadata.correlationId,causationId:n.metadata.causationId,subject:n.intent,details:r})}catch(o){en(e,{type:"hook.error",timestamp:new Date().toISOString(),intent:n.intent,correlationId:n.metadata.correlationId,traceId:n.metadata.traceId,spanId:n.metadata.spanId,details:{hook:"auditTrail",error:o instanceof Error?o.message:String(o)}})}}i(er,"recordAudit");async function Ls(e,t){let n={intent:t.intent,source:t.metadata.source,suggestion:"Publish through a registered intent creator so strict registry, contracts, and agent tooling share one source of truth."};en(e,{type:"event.rawPublish",timestamp:new Date().toISOString(),intent:t.intent,correlationId:t.metadata.correlationId,traceId:t.metadata.traceId,spanId:t.metadata.spanId,details:n}),await er(e,"event.rawPublish",t,n)}i(Ls,"recordRawPublishDiagnostic");async function Fs(e,t,n,r){let o={event:t,publishedAt:new Date().toISOString(),subscribersNotified:n};return El(e,o),await e.eventBuffer?.enqueue(t,r),en(e,{type:"event.published",timestamp:o.publishedAt,intent:t.intent,correlationId:t.metadata.correlationId,traceId:t.metadata.traceId,spanId:t.metadata.spanId,details:{subscribersNotified:n}}),await er(e,"event.published",t,{subscribersNotified:n}),o}i(Fs,"recordSuccessfulPublish");function to(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(to,"enrichMetadata");var $s=0;function Sl(){return $s+=1,`interceptor-${Date.now()}-${$s}`}i(Sl,"nextInterceptorRegistrationId");var gt=class{static{i(this,"EventBusImpl")}subscriptions=[];subscriptionsByIntent=new Map;interceptors=[];interceptorsByIntent=new Map;recording;onPublish;onSoftViolation;onHandlerError;eventContracts;strictEventContracts;requireKnownSource;architectureProfile;enforceObservedLayerFlowMode;rethrowHandlerErrors;policyEngine;getPolicyContext;intentRegistry;dependencyGraph;strictRegistry;validateIntentNaming;constructor(t={}){if(this.onPublish=t.onPublish,this.onSoftViolation=t.onSoftViolation,this.onHandlerError=t.onHandlerError,this.eventContracts=t.eventContracts,this.strictEventContracts=t.strictEventContracts??!1,this.requireKnownSource=t.requireKnownSource??!1,this.architectureProfile=t.architectureProfile,this.enforceObservedLayerFlowMode=t.enforceObservedLayerFlow??"off",this.rethrowHandlerErrors=t.rethrowHandlerErrors??!1,this.intentRegistry=t.intentRegistry,this.dependencyGraph=t.dependencyGraph,this.strictRegistry=t.strictRegistry??t.intentRegistry!==void 0,this.validateIntentNaming=t.validateIntentNaming??this.strictRegistry,this.recording={history:[],trace:[],maxHistorySize:t.maxHistorySize,traceSinks:[...t.traceSinks??[]],auditTrail:t.auditTrail,eventBuffer:t.eventBuffer??t.outbox,instanceId:t.instanceId},t.policyEngine?this.policyEngine=t.policyEngine:t.policies&&t.policies.length>0&&(this.policyEngine=new Oe(t.policies)),(this.policyEngine?.getPolicies()??t.policies??[]).some(Yt)&&!t.intentRegistry&&!t.dependencyGraph&&!t.getPolicyContext)throw new qe;t.getPolicyContext?this.getPolicyContext=t.getPolicyContext:t.intentRegistry||t.dependencyGraph?this.getPolicyContext=Zt({intentRegistry:t.intentRegistry,dependencyGraph:t.dependencyGraph}):this.getPolicyContext=r=>({event:r})}async publish(t,n,r,o){await this.dispatch(t,n,r,o)}async dispatch(t,n,r,o={}){let s=o.notifySubscribers!==!1,a=o.awaitHandlers!==!1,l=o.runOnPublish!==!1,c,u=typeof t!="function";if(u){let p=t,g=r??n??{};c={...p,metadata:to(p.metadata,g,this.recording.instanceId)}}else{let p=t,g=n,d=r??{},m=p(g);c={...m,metadata:to(m.metadata,d,this.recording.instanceId)}}u&&this.strictRegistry&&await Ls(this.recording,c),Jt(c.intent,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),ks(c,{requireKnownSource:this.requireKnownSource,intentRegistry:this.intentRegistry}),Qt(c,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),c=await bs(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")}),Qt(c,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),await Ns(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 Ds(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 Fs(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 Jt(n,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),{source:n,publish:i(async(r,o,s={},a)=>{if(s.source&&s.source!==n)throw new Ae(n,s.source);await this.publish(r,o,{...s,source:n},a)},"publish")}}subscribe(t,n){let r=typeof t=="string"?t:t.name;Jt(r,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let o={intentName:r,handler:n};this.subscriptions.push(o);let s=this.subscriptionsByIntent.get(r)??[];return s.push(o),this.subscriptionsByIntent.set(r,s),()=>{let a=this.subscriptions.indexOf(o);a>=0&&this.subscriptions.splice(a,1);let l=this.subscriptionsByIntent.get(r);if(!l)return;let c=l.indexOf(o);c>=0&&l.splice(c,1),l.length===0&&this.subscriptionsByIntent.delete(r)}}registerInterceptor(t,n,r){let o=typeof t=="string"?t:t.name;Jt(o,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let s={registrationId:Sl(),interceptorId:r??o,intentName:o,interceptor:n,createdAt:new Date().toISOString()};this.interceptors.push(s);let a=this.interceptorsByIntent.get(o)??[];return a.push(s),this.interceptorsByIntent.set(o,a),s.registrationId}unregisterInterceptor(t){let n=this.interceptors.find(s=>s.registrationId===t);if(!n)return!1;let r=this.interceptors.indexOf(n);r>=0&&this.interceptors.splice(r,1);let o=this.interceptorsByIntent.get(n.intentName);if(o){let s=o.indexOf(n);s>=0&&o.splice(s,1),o.length===0&&this.interceptorsByIntent.delete(n.intentName)}return!0}listInterceptors(t){return this.interceptors.filter(n=>!t||n.intentName===t).map(n=>({registrationId:n.registrationId,interceptorId:n.interceptorId,intent:n.intentName,createdAt:n.createdAt,lastInterceptedAt:n.lastInterceptedAt}))}getHistory(){return[...this.recording.history]}clearHistory(){this.recording.history.length=0}getTrace(){return[...this.recording.trace]}clearTrace(){this.recording.trace.length=0}appendTrace(t){en(this.recording,t)}async recordAudit(t,n,r){await er(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 no(e){return new gt(e)}i(no,"createEventBus");function wl(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(wl,"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 xl(e,t){return e?`${e}.${t}`:t}i(xl,"formatPath");function Ms(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}Hs(e,t.fields,r,o,n)}t.type==="array"&&t.items&&Array.isArray(e)&&e.forEach((a,l)=>{Ms(a,t.items,`${n}[${l}]`,r,o)})}i(Ms,"validateSchemaField");function Hs(e,t,n,r,o){for(let[s,a]of Object.entries(t)){let l=xl(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}Ms(c,a,l,n,r)}}i(Hs,"validateObjectSchema");var mt=class{static{i(this,"EventContractRegistryImpl")}contracts=new Map;register(t){let n=this.key(t.intent,t.version);if(this.contracts.has(n))throw new Error(`Event contract "${n}" is already registered.`);this.contracts.set(n,{allowAdditionalFields:!0,...t})}get(t,n){return n?this.contracts.get(this.key(t,n)):this.list(t).at(-1)}list(t){return Array.from(this.contracts.values()).filter(n=>!t||n.intent===t)}validate(t){let n=t.metadata.eventVersion,r=this.get(t.intent,n),o=[];if(!r)return{ok:!1,issues:[{intent:t.intent,version:n,message:n?`No event contract registered for version "${n}".`:"No event contract registered for intent."}]};r.deprecated&&o.push({intent:t.intent,version:r.version,message:typeof r.deprecated=="string"?r.deprecated:"Event contract is deprecated."});let s=t.payload!=null&&typeof t.payload=="object"?t.payload:void 0;if(r.schema){if(!s)o.push({intent:t.intent,version:r.version,message:"Payload must be an object for schema validation."});else if(Hs(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:wl(l.path),message:l.message})}return{ok:o.length===0,contract:r,issues:o}}clear(){this.contracts.clear()}key(t,n){return`${t}@${n}`}};function tn(){return new mt}i(tn,"createEventContractRegistry");var Ks=0;function Ol(){return Ks+=1,`outbox-${Date.now()}-${Ks}`}i(Ol,"nextOutboxId");function Gs(e){return{...e,event:{...e.event,metadata:{...e.event.metadata}}}}i(Gs,"cloneRecord");var _e=class{static{i(this,"InMemoryEventBuffer")}records=new Map;async enqueue(t){let n=new Date().toISOString(),r={id:Ol(),event:t,status:"pending",attempts:0,createdAt:n,updatedAt:n};return this.records.set(r.id,r),Gs(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(Gs)}async clear(){this.records.clear()}},ro=_e;function oo(e){return`${e.from}->${e.to}`}i(oo,"flowKey");function Us(e){let t=new Set,n=[];for(let r of e){let o=oo(r);t.has(o)||(t.add(o),n.push(r))}return n}i(Us,"uniqueFlows");function Vs(e,t){let n=new Set(t.map(oo));return e.filter(r=>!n.has(oo(r)))}i(Vs,"difference");function nn(e){let t=e.registry,n=e.eventBus,r=e.graph;return{report(){let o=t?t.getAllRelationships().filter(m=>m.kind==="produces").map(m=>({from:m.from,to:m.to})):[],s=o.length>0||!r?[]:r.getEdges().filter(m=>m.kind==="produces").map(m=>({from:m.from,to:m.to})),a=n?.getHistory().map(m=>({from:m.event.metadata.source,to:m.event.intent}))??[],l=a.length>0||!r?[]:r.getEdges().filter(m=>m.kind==="observed").map(m=>({from:m.from,to:m.to})),c=Us([...o,...s]),u=Us([...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:Vs(c,u),observedButUndeclared:Vs(u.filter(m=>m.from!=="unknown"),c),unknownSources:f,unregisteredObservedSources:y,unregisteredObservedIntents:p,registeredButNeverObserved:d}}}}i(nn,"createObservabilityReporter");function so(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(so,"createArkTestHarness");var js=0;function Pl(){return js+=1,`audit-${Date.now()}-${js}`}i(Pl,"createAuditId");function _l(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(_l,"matchesQuery");var yt=class{constructor(t){this.maxRecords=t}maxRecords;static{i(this,"InMemoryAuditStore")}records=[];append(t){this.records.push(t),this.maxRecords!==void 0&&this.records.length>this.maxRecords&&this.records.splice(0,this.records.length-this.maxRecords)}query(t={}){let n=this.records.filter(r=>_l(r,t));return t.limit===void 0?[...n]:n.slice(-t.limit)}clear(){this.records.length=0}},tr=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 rn(e={}){return new tr(e.store??new yt(e.maxRecords))}i(rn,"createAuditTrail");var nr=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 be(n.hardViolations);return n}clear(){this.policies.length=0}};function ze(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(ze,"definePolicy");function Hl(e){let t=e.indexOf(".");return t>=0?e.slice(0,t):e}a(Hl,"defaultLayerOf");function Hs(e,t){return t.resolveLayer?.(e)??Hl(e)}a(Hs,"resolveLayer");function Kl(e,t,n){return e===n.from&&t===n.to}a(Kl,"matchesRule");function nn(e){let t=e.name??"Layer isolation",n=e.severity??"hard";return ze({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=Hs(i.from,e),c=Hs(i.to,e);for(let u of e.rules)!u.allowed&&Kl(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(nn,"defineLayerPolicy");function rn(e){return e.tags?.includes("layer")??!1}a(rn,"isLayerPolicy");var cr={layerIsolation(){return cr.cleanArchitectureMatrix()},cleanArchitectureMatrix(){return nn({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 on(e,t={}){return nn({name:t.name??`${e.name} layer policy`,severity:t.severity??"hard",rules:e.rules,resolveLayer:e.resolveLayer})}a(on,"defineArchitectureProfilePolicy");function sn(e){return t=>({event:t,relationships:e.intentRegistry?.getAllRelationships(),edges:e.dependencyGraph?.getEdges()})}a(sn,"buildPublishPolicyContext");function uo(e){return ze(e)}a(uo,"definePublishPolicy");var qe=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}},Ye=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}},Xe=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"}},Ze=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}},Te=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}},Se=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}},Je=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 an(e,t){if(!(!t.strictRegistry&&!t.validateIntentNaming)){if(t.validateIntentNaming){let n=tn(e);if(!n.valid)throw new Ye(e,n.reason)}if(t.strictRegistry&&t.intentRegistry&&!t.intentRegistry.has(e))throw new qe(e)}}a(an,"assertIntentAllowed");function Ks(e,t){if(t.requireKnownSource){if(!e.metadata.source||e.metadata.source==="unknown")throw new Te(e.intent);if(t.intentRegistry&&!t.intentRegistry.has(e.metadata.source))throw new Te(e.intent,e.metadata.source)}}a(Ks,"assertSourceAllowed");function ln(e,t){if(!t.eventContracts)return;let n=t.eventContracts.validate(e);if(!n.ok&&(t.strictEventContracts||n.contract))throw new Ze(e.intent,n.issues)}a(ln,"assertContractAllowed");function gt(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}a(gt,"isPlainRecord");function mt(e){return Array.isArray(e)?e.map(mt):gt(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,mt(n)])):e}a(mt,"clonePatchValue");function po(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]=mt(s);continue}if(gt(r[o])&>(s)){r[o]=po(r[o],s,i);continue}if(Array.isArray(r[o])&&Array.isArray(s)){r[o]=fo(r[o],s,i);continue}throw new Error(`Interceptor patch cannot overwrite existing ${i}.`)}return r}a(po,"mergeRecordPatch");function fo(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]=mt(o);return}if(gt(r[s])&>(o)){r[s]=po(r[s],o,i);return}if(Array.isArray(r[s])&&Array.isArray(o)){r[s]=fo(r[s],o,i);return}throw new Error(`Interceptor patch cannot overwrite existing ${i}.`)}),r}a(fo,"mergeArrayPatch");function Gs(e,t){if(Array.isArray(t)){if(e===void 0)return mt(t);if(!Array.isArray(e))throw new Error("Array interceptor patch requires an array payload.");return fo(e,t)}if(e===void 0)return mt(t);if(!gt(e))throw new Error("Object interceptor patch requires an object payload.");return po(e,t)}a(Gs,"applyPayloadPatch");async function Us(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:Gs(l.payload,c),metadata:{...l.metadata}};ln(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 Gl(o,r,i,t)}}return r}a(Us,"applyInterceptors");async function Gl(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(Gl,"recordInterceptorError");var Vs="4.8.22",js=new Map;function Bs(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(Bs,"escapeLiteral");function pr(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(pr,"normalizeGlobSeparators");function Ul(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(Ul,"bracesBalanced");function he(e){let t=js.get(e);if(t)return t;let n=pr(e),r=Ul(n),o="",s=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(o+=Bs(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+=Bs(c)}let i=new RegExp(`^${o}$`);return js.set(e,i),i}a(he,"globToRegExp");function Vl(e){return pr(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}a(Vl,"concreteGlobSegments");function mo(e,t){let n=pr(String(e)),r=Vl(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(mo,"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=mo(i,n);l>o&&(o=l,r=s.name)}}return r}a(fe,"layerForRelativePath");function yo(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(Ys(i)){let l=jl(o,i,r);if(l)return l;continue}!i.includes("/")&&!i.includes("\\")&&!i.includes("*")&&s.add(i.toLowerCase())}return ql(o,s)}a(yo,"sliceIdForPath");function Ys(e){let t=e.split(/[/\\]/).filter(n=>n.length>0);return t.length<2||t[0]==="*"||t[0]==="**"?!1:t.some(n=>n==="*")}a(Ys,"isAnchoredSliceEntry");function jl(e,t,n){let r=t.split(/[/\\]/).filter(s=>s.length>0).map(s=>s.toLowerCase()),o=Zs(e,r[0]??"");for(let s of o){let i=Bl(e,r,s,n);if(i)return i}}a(jl,"anchoredSliceId");function Bl(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(Bl,"bindAnchoredSlice");function Xs(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=Wl(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:zl(n.from,n.to,i,s)})}return t}a(Xs,"sliceIdentityCollisions");function Wl(e){if(!Ys(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(Wl,"starsIdentityStem");function zl(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(zl,"formatSliceIdentityCollision");function ql(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(ql,"bareSliceId");function Yl(e){let t=new Set;for(let n of e??[]){let o=pr(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(Yl,"inferSliceFoldersFromPatterns");function ho(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 Yl(r?.patterns)}a(ho,"resolveSliceFolders");function Ws(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}a(Ws,"normalizeSegments");function un(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}a(un,"trimTrailingSlashes");var Xl=["src","app"];function Zs(e,t){let n=(e[0]??"").toLowerCase(),r=t.toLowerCase();return Xl.includes(n)&&r!==n?[0,1]:[0]}a(Zs,"anchorOffsets");function Zl(e){let t=un(e.replace(/^[./]+/,""));return t==="*"||t==="**"}a(Zl,"isBlanketRoot");function cn(e,t){if(!e||!t?.length)return!1;let n=String(e).split(/[/\\]/).join("/"),r=n.toLowerCase(),o=Ws(n);for(let s of t){if(typeof s!="string"||s.length===0||Zl(s))continue;if(s.includes("*")){let c=un(s.toLowerCase());if(he(c).test(r)||he(`${c}/**`).test(r))return!0;continue}let i=Ws(s);if(i.length===0)continue;let l=Zs(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(cn,"pathUnderSharedRoot");function zs(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(zs,"sliceMatchesDeclaration");function Jl(e,t,n){return!e?.length||!t||!n?!1:e.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&zs(r.from,t)&&zs(r.to,n))}a(Jl,"crossSliceEdgeAllowed");function Ql(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(Ql,"peerIsolationDecision");function Js(e){return un(e.trim().replace(/\\/g,"/")).toLowerCase()}a(Js,"aliasGlobPattern");function ec(e,t){let n=Js(e);if(!n||n==="*"||n==="**")return!1;let r=String(t).replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase(),o=go(r),s=he(n);return s.test(r)||o!==r&&s.test(o)}a(ec,"aliasGlobMatches");function tc(e){let t=Js(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(tc,"splitAliasTarget");function nc(e,t){for(let n of t.childSlices?.sliceAliases??[])if(!(!n||typeof n.from!="string"||typeof n.to!="string")&&ec(n.from,e))return tc(n.to);return null}a(nc,"firstSliceAlias");function yt(e,t,n){if(!e)return{};let r=n??t.sliceFolders,o=yo(e,r?[...r]:void 0,t.sliceIdentity),s=dr(e,o,t.childSlices);if(o||s.childId||s.mismatched)return s.childId?{universeId:o,childId:s.childId}:{universeId:o};let i=nc(e,t);return i?{universeId:i.universeId,childId:i.childId}:{}}a(yt,"resolveGovernedSlice");function rc(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(rc,"peerIsolationDenyExplanation");function oc(e,t){return`cross-parent slice ${e??"?"} \u2192 ${t??"?"}. The child wall cannot allow another universe.`}a(oc,"crossParentExplanation");function sc(e,t,n){return`cross-sibling slice ${e} \u2192 ${t} inside ${n}.`}a(sc,"crossSiblingExplanation");function ic(e){return`universe common imports child ${e}. parentMayImportChild is off.`}a(ic,"parentImportsChildExplanation");function dn(e){if(!e)return;let t=e.split("/").filter(Boolean);return t.length>0?t[t.length-1]:void 0}a(dn,"universePairLabel");function ac(e){return String(e).split(/[/\\]/).filter(Boolean).slice(0,-1)}a(ac,"directorySegments");function lc(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:ac(e).some(r=>n.has(r.toLowerCase()))}a(lc,"pathHasCommonFolder");function dr(e,t,n){if(!e||!n?.sliceFolders?.length)return{};if(lc(e,n.commonFolders))return{};let r=yo(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(dr,"resolveChildSliceId");function cc(e){return un(e.trim().replace(/\\/g,"/")).toLowerCase()}a(cc,"siblingEntryKey");function go(e){return e.replace(/^(?:src|app)\//,"")}a(go,"stripSrcOrApp");function dc(e,t){let n=e.replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase(),r=go(t);if(!r)return!1;let o=go(n);return n===r||n.startsWith(`${r}/`)||o===r||o.startsWith(`${r}/`)}a(dc,"pathUnderSubtree");function uc(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=cc(o);if(!(!s||s.includes("*"))&&(r===s||e&&dc(e,s)))return!0}return!1}a(uc,"importerInEnforcedSubtree");function pc(e,t,n){return e==null||e==="deny"?!1:e==="advisory"?!0:e.default==="deny"?!1:!uc(t,n,e.enforce)}a(pc,"siblingCrossingAdvisory");function ur(e){if(typeof e!="string")return null;let t=un(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(ur,"childSlicePatternSegments");function qs(e,t){let n=ur(e),r=ur(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(qs,"childSlicePatternMatches");function fc(e,t,n){if(!e?.length)return!1;for(let r of e)if(!(!r||typeof r.from!="string"||typeof r.to!="string")&&qs(r.from,t)&&qs(r.to,n))return!0;return!1}a(fc,"childCrossSliceAllowed");function gc(e,t){let n=ur(e),r=ur(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(gc,"childAllowanceSpansUniverses");function mc(e){let t=Ql({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?oc(e.fromSlice,e.toSlice):rc(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??dr(e.fromPath,e.fromSlice,n).childId,o=e.toChild??dr(e.toPath,e.toSlice,n).childId,s={crossing:"none",decision:"allow",fromUniverse:e.fromSlice,toUniverse:e.toSlice};return r&&o&&r!==o?fc(n.allowedCrossSlice,r,o)?s:{crossing:"cross-sibling",decision:pc(n.siblings,e.fromPath,r)?"advisory":"deny",reasonId:"CROSS_SIBLING_SLICE",explanation:sc(r,o,e.fromSlice),fromUniverse:e.fromSlice,toUniverse:e.toSlice}:!r&&o&&n.parentMayImportChild!==!0?{crossing:"parent-imports-child",decision:"deny",explanation:ic(o),fromUniverse:e.fromSlice,toUniverse:e.toSlice}:s}a(mc,"evaluateNestedSliceWall");function ht(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(ht,"composeSliceDenialMessage");function Qe(e){if(!e||e.decision==="allow")return{};let t=dn(e.fromUniverse),n=dn(e.toUniverse);return{...e.reasonId?{reasonId:e.reasonId}:{},...e.reasonId&&t&&n?{universeFrom:t,universeTo:n}:{},...e.decision==="advisory"?{failsStrict:!1,severity:"warning"}:{}}}a(Qe,"sliceFindingExtras");function Qs(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 ${Vs}. Version ${Vs} and older reject the key because the rule schema sets additionalProperties: false.`})),!!i.peerIsolation)){for(let l of t){let c=yo(l,i.sliceFolders,i.sliceIdentity),u=dr(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"||!gc(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(Qs,"childSliceConfigFindings");function fr(e,t,n,r){return Ne(e,t,n,r)?.rule}a(fr,"findDeniedEdgeRule");function Ne(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=ho(o,t,r?.layers),c=yt(s,o,l),u=yt(i,o,l),f=c.universeId,y=u.universeId,p=mc({rule:o,fromPath:s,toPath:i,folderCount:l.length,fromSlice:f,toSlice:y,fromChild:c.childId,toChild:u.childId,fromShared:!f&&cn(s,o.sharedRoots),toShared:!y&&cn(i,o.sharedRoots),crossSliceAllowed:Jl(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(Ne,"findDeniedEdgeDecision");function ei(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=ho(i,t,r?.layers),c=yt(o,i,l).universeId,u=yt(s,i,l).universeId;if(!(c||!u)&&cn(o,i.sharedRoots))return{fromPath:o,toPath:s,toSlice:u}}}a(ei,"findSharedImportsSliceBridge");function ti(e,t,n){return ho(e,t,n)}a(ti,"peerSliceFolders");async function ni(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=fr(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 Je(n,e.intent,o,s,c)}a(ni,"assertObservedLayerFlowAllowed");async function ri(e,t){let n=t.getPolicyContext(e),r;try{r=t.policyEngine.enforce(n)}catch(o){throw o instanceof be&&(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(ri,"enforcePublishPolicy");function yc(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(yc,"appendHistory");function pn(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(pn,"appendTrace");async function gr(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){pn(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(gr,"recordAudit");async function oi(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."};pn(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 gr(e,"event.rawPublish",t,n)}a(oi,"recordRawPublishDiagnostic");async function si(e,t,n,r){let o={event:t,publishedAt:new Date().toISOString(),subscribersNotified:n};return yc(e,o),await e.eventBuffer?.enqueue(t,r),pn(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 gr(e,"event.published",t,{subscribersNotified:n}),o}a(si,"recordSuccessfulPublish");function Ro(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(Ro,"enrichMetadata");var ii=0;function hc(){return ii+=1,`interceptor-${Date.now()}-${ii}`}a(hc,"nextInterceptorRegistrationId");var Rt=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(rn)&&!t.intentRegistry&&!t.dependencyGraph&&!t.getPolicyContext)throw new Xe;t.getPolicyContext?this.getPolicyContext=t.getPolicyContext:t.intentRegistry||t.dependencyGraph?this.getPolicyContext=sn({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:Ro(p.metadata,g,this.recording.instanceId)}}else{let p=t,g=n,d=r??{},m=p(g);c={...m,metadata:Ro(m.metadata,d,this.recording.instanceId)}}u&&this.strictRegistry&&await oi(this.recording,c),an(c.intent,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),Ks(c,{requireKnownSource:this.requireKnownSource,intentRegistry:this.intentRegistry}),ln(c,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),c=await Us(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")}),ln(c,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),await ni(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 ri(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 si(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 an(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 Se(n,s.source);await this.publish(r,o,{...s,source:n},i)},"publish")}}subscribe(t,n){let r=typeof t=="string"?t:t.name;an(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;an(o,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let s={registrationId:hc(),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){pn(this.recording,t)}async recordAudit(t,n,r){await gr(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 Ao(e){return new Rt(e)}a(Ao,"createEventBus");function Rc(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(Rc,"formatStandardSchemaPath");function Ac(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(Ac,"actualType");function kc(e,t){return e?`${e}.${t}`:t}a(kc,"formatPath");function ai(e,t,n,r,o){let s=Ac(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}li(e,t.fields,r,o,n)}t.type==="array"&&t.items&&Array.isArray(e)&&e.forEach((i,l)=>{ai(i,t.items,`${n}[${l}]`,r,o)})}a(ai,"validateSchemaField");function li(e,t,n,r,o){for(let[s,i]of Object.entries(t)){let l=kc(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}ai(c,i,l,n,r)}}a(li,"validateObjectSchema");var At=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(li(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:Rc(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 fn(){return new At}a(fn,"createEventContractRegistry");var ci=0;function Ic(){return ci+=1,`outbox-${Date.now()}-${ci}`}a(Ic,"nextOutboxId");function di(e){return{...e,event:{...e.event,metadata:{...e.event.metadata}}}}a(di,"cloneRecord");var Le=class{static{a(this,"InMemoryEventBuffer")}records=new Map;async enqueue(t){let n=new Date().toISOString(),r={id:Ic(),event:t,status:"pending",attempts:0,createdAt:n,updatedAt:n};return this.records.set(r.id,r),di(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(di)}async clear(){this.records.clear()}},ko=Le;function Io(e){return`${e.from}->${e.to}`}a(Io,"flowKey");function ui(e){let t=new Set,n=[];for(let r of e){let o=Io(r);t.has(o)||(t.add(o),n.push(r))}return n}a(ui,"uniqueFlows");function pi(e,t){let n=new Set(t.map(Io));return e.filter(r=>!n.has(Io(r)))}a(pi,"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=ui([...o,...s]),u=ui([...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:pi(c,u),observedButUndeclared:pi(u.filter(m=>m.from!=="unknown"),c),unknownSources:f,unregisteredObservedSources:y,unregisteredObservedIntents:p,registeredButNeverObserved:d}}}}a(gn,"createObservabilityReporter");function bo(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(bo,"createArkTestHarness");var fi=0;function bc(){return fi+=1,`audit-${Date.now()}-${fi}`}a(bc,"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 kt=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}},mr=class{constructor(t){this.store=t}store;static{a(this,"AuditTrailImpl")}async record(t){let n={id:bc(),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 mn(e={}){return new mr(e.store??new kt(e.maxRecords))}a(mn,"createAuditTrail");var yr=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
|
|
11
|
-
`;for(let s of t.layers){let
|
|
12
|
-
`;for(let l of
|
|
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
|
|
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 on(){return new nr}i(on,"createDependencyGraph");function sn(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(sn,"syncRegistryToGraph");var Je={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Bs={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...Je,default:[]},kernelRoots:{...Je},managedLayers:{...Je,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:{...Je,default:[]},managedLayers:{...Je,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...Je,default:[]},appliesTo:{...Je,default:[]}}};function an(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(an,"isObject");function zs(e){let t=new Set;if(!Array.isArray(e.layers))return t;for(let n of e.layers)an(n)&&typeof n.name=="string"&&n.name.length>0&&t.add(n.name);return t}i(zs,"declaredLayerNames");function qs(e){if(!an(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(qs,"defaultedArkRun");function Ys(e){if(!an(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(Ys,"defaultedArkOrder");function Xs(e,t){let n=e.arkRun;if(n===void 0||!an(n))return;let r=zs(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(Xs,"validateArkRunExtra");function Zs(e,t){let n=e.arkOrder;if(n===void 0||!an(n))return;let r=zs(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(Zs,"validateArkOrderExtra");function rr(e){if(typeof e!="string")return null;let t=e.trim().replace(/^@/,"").toLowerCase();return t.length>0?t:null}i(rr,"normalizeStewardId");function Js(e){let t=rr(e);return!t||io(t)||t.includes(" ")||t.includes("@")?!1:/^(?!-)[a-z0-9-]{1,39}(?<!-)$/.test(t)}i(Js,"isGitHubHandle");function Tl(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();return!t.includes("@")||t.includes(" ")||io(t)?!1:/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}i(Tl,"isGitHubEmail");function Nl(e){if(typeof e!="string")return null;let t=e.trim().match(/^(?:\d+\+)?([^@]+)@users\.noreply\.github\.com$/i);return t&&Js(t[1])?rr(t[1]):null}i(Nl,"githubHandleFromEmail");function Qs(e){let t=Nl(e);if(t)return t;let n=rr(e);return!n||io(n)?null:Js(n)||Tl(n)?n:null}i(Qs,"canonicalStewardId");var Dl=/bot\b|\[bot\]|dependabot|renovate|github-actions|imgbot|codecov/i;function io(e){let t=rr(e);return!t||Dl.test(t)}i(io,"isAutomationAuthor");var le="1.3",Ll=["public","auth","admin","internal"];function Fl(e){return e?.optional===!0||e?.reserved===!0||e?.allowEmpty===!0}i(Fl,"isFutureHouseLayer");function $l(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($l,"layerOwnersList");function ni(e){return e?.requireLayerOwners!==!0||!Array.isArray(e.layers)?[]:e.layers.filter(t=>!Fl(t)&&!$l(t)).map(t=>t.name)}i(ni,"layersMissingRequiredOwners");function ri(e){return`Add a GitHub handle or email to ${e}'s owners in ark.config.json (/ark-adopt).`}i(ri,"missingLayerOwnersNextAction");var sr="https://unpkg.com/arkgate@4/schemas/ark.config.schema.json",ei=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Ml=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Hl(){let e=[];for(let t of ei)for(let n of ei)t===n||Ml.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}i(Hl,"createDefaultRules");var ir=Hl(),ao=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"},{from:"1.1",to:"1.2"},{from:"1.2",to:"1.3"}],oe={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},ti={$schema:"https://json-schema.org/draft/2020-12/schema",$id:sr,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:sr,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:le,default:le},name:{type:"string",minLength:1},include:{...oe,minItems:1,default:["src"]},exclude:{...oe,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:ir,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...oe,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:{...oe,default:[]},requireLayerOwners:{type:"boolean"}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...oe,minItems:1},exclude:oe,intentPrefixes:oe,description:{type:"string",minLength:1},trustBoundary:{type:"string",enum:[...Ll]},owners:{...oe,minItems:1},forbiddenGlobals:oe,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:{...oe,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:{...oe,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:{...oe,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:{...oe,minItems:1}}},arkRun:Bs,arkOrder:Ws}},Ie=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 yn(){return new yr}a(yn,"createDependencyGraph");function hn(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(hn,"syncRegistryToGraph");var et={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},gi={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...et,default:[]},kernelRoots:{...et},managedLayers:{...et,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},mi={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...et,default:[]},managedLayers:{...et,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...et,default:[]},appliesTo:{...et,default:[]}}};function Rn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(Rn,"isObject");function yi(e){let t=new Set;if(!Array.isArray(e.layers))return t;for(let n of e.layers)Rn(n)&&typeof n.name=="string"&&n.name.length>0&&t.add(n.name);return t}a(yi,"declaredLayerNames");function hi(e){if(!Rn(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(hi,"defaultedArkRun");function Ri(e){if(!Rn(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(Ri,"defaultedArkOrder");function Ai(e,t){let n=e.arkRun;if(n===void 0||!Rn(n))return;let r=yi(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(Ai,"validateArkRunExtra");function ki(e,t){let n=e.arkOrder;if(n===void 0||!Rn(n))return;let r=yi(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(ki,"validateArkOrderExtra");function hr(e){if(typeof e!="string")return null;let t=e.trim().replace(/^@/,"").toLowerCase();return t.length>0?t:null}a(hr,"normalizeStewardId");function Ii(e){let t=hr(e);return!t||So(t)||t.includes(" ")||t.includes("@")?!1:/^(?!-)[a-z0-9-]{1,39}(?<!-)$/.test(t)}a(Ii,"isGitHubHandle");function vc(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();return!t.includes("@")||t.includes(" ")||So(t)?!1:/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}a(vc,"isGitHubEmail");function Ec(e){if(typeof e!="string")return null;let t=e.trim().match(/^(?:\d+\+)?([^@]+)@users\.noreply\.github\.com$/i);return t&&Ii(t[1])?hr(t[1]):null}a(Ec,"githubHandleFromEmail");function bi(e){let t=Ec(e);if(t)return t;let n=hr(e);return!n||So(n)?null:Ii(n)||vc(n)?n:null}a(bi,"canonicalStewardId");var wc=/bot\b|\[bot\]|dependabot|renovate|github-actions|imgbot|codecov/i;function So(e){let t=hr(e);return!t||wc.test(t)}a(So,"isAutomationAuthor");var de="1.3",Cc=["public","auth","admin","internal"];function xc(e){return e?.optional===!0||e?.reserved===!0||e?.allowEmpty===!0}a(xc,"isFutureHouseLayer");function Oc(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(Oc,"layerOwnersList");function Oi(e){return e?.requireLayerOwners!==!0||!Array.isArray(e.layers)?[]:e.layers.filter(t=>!xc(t)&&!Oc(t)).map(t=>t.name)}a(Oi,"layersMissingRequiredOwners");function Pi(e){return`Add a GitHub handle or email to ${e}'s owners in ark.config.json (/ark-adopt).`}a(Pi,"missingLayerOwnersNextAction");var Rr="https://unpkg.com/arkgate@4/schemas/ark.config.schema.json",Si=["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 _c(){let e=[];for(let t of Si)for(let n of Si)t===n||Pc.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}a(_c,"createDefaultRules");var Ar=_c(),vo=[{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},vi={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Rr,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:Rr,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:de,default:de},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:Ar,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:gi,arkOrder:mi}},ve=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 oi(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(oi,"isObject");function or(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}i(or,"propertyPath");function ht(e){return e===null?"null":Array.isArray(e)?"array":typeof e}i(ht,"valueType");function Kl(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}i(Kl,"resolveSchemaRef");function ln(e,t,n,r,o){if(t.$ref){let s=Kl(t.$ref,r);if(!s){o.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}ln(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(!oi(e)){o.push({path:n,message:`must be an object; received ${ht(e)}`});return}let s=t.properties??{};for(let a of t.required??[])e[a]===void 0&&o.push({path:or(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in s||o.push({path:or(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||ln(e[l],a,or(n,l),r,o)}for(let[a,l]of Object.entries(s))e[a]!==void 0&&ln(e[a],l,or(n,a),r,o);return}if(t.type==="array"){if(!Array.isArray(e)){o.push({path:n,message:`must be an array; received ${ht(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)=>ln(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 ${ht(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 ${ht(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){o.push({path:n,message:`must be an integer; received ${ht(e)}`});return}t.minimum!==void 0&&e<t.minimum&&o.push({path:n,message:`must be at least ${t.minimum}`})}}i(ln,"validateNode");function Gl(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"&&(Qs(a)||t.push({path:`$.layers[${o}].owners[${l}]`,message:"must be a GitHub handle or email (not a display name)"}))})})}i(Gl,"validateLayerOwners");function Ul(e){let t={...e,$schema:e.$schema===void 0?sr:e.$schema,schemaVersion:e.schemaVersion===void 0?le:e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?ir.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}i(Ul,"defaultedConfig");function Vl(e){return e===le?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}i(Vl,"migratedFromOf");function jl(){let e=new Set([le]);for(let t of ao)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}i(jl,"knownInputVersions");function Bl(e,t="ark.config.json"){if(!oi(e))throw new Ie(t,[{path:"$",message:`must be an object; received ${ht(e)}`}]);let n=jl(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new Ie(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected ${le}`}]);if(r!=="unversioned"&&!n.has(r))throw new Ie(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${le}`}]);let o=r,s={...e},a=0;for(;o!==le&&a<ao.length+1;){a+=1;let l=ao.find(c=>c.from===o);if(!l)throw new Ie(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(o)}; expected ${le}`}]);o=l.to,s.schemaVersion=o}if(o!==le)throw new Ie(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${le}`}]);return{candidate:Ul(s),migratedFrom:Vl(r)}}i(Bl,"migrateArkConfig");function lo(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=Bl(e,t),o=[];if(ln(n,ti,"$",ti,o),Xs(n,o),Zs(n,o),Gl(n,o),o.length>0)throw new Ie(t,o);return{config:n,migratedFrom:r}}i(lo,"loadArkConfigContract");function si(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new Ie(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return lo(n,t)}i(si,"parseArkConfigJson");function ii(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:sr,schemaVersion:le};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}i(ii,"withArkConfigMetadata");function Wl(e){return e.endsWith(".")?e:`${e}.`}i(Wl,"normalizePrefix");function zl(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(zl,"byLongestPrefix");function cn(e){let t=e.layers.map(o=>({...o,prefixes:o.prefixes.map(Wl)})),n=[...t].sort(zl),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(cn,"createArchitectureProfile");function dn(e,t={}){return cn({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(dn,"createArchitectureProfileFromArkConfig");var ql=[{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}],Qe=cn({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:ql,rules:ir.map(e=>({...e}))}),Yl={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 co(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return ii({include:e.include??[t],layers:Qe.layers.map(o=>({name:o.name,patterns:(Yl[o.name]??[o.name]).map(s=>`${r}${s}/**`),intentPrefixes:o.prefixes,optional:n})),rules:[...Qe.rules]})}i(co,"createElevenLayerArkConfig");var ar=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 un(){return new ar}i(un,"createMetadataRegistry");function uo(e,t={}){return{name:e,ownerLayer:t.ownerLayer,intent:t.intent,allowedAdapters:t.allowedAdapters?[...t.allowedAdapters]:void 0}}i(uo,"definePort");function po(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=>!ai(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=lr(a);if(!l.ok)throw new Error(l.issues.map(c=>c.message).join(`
|
|
21
|
-
`));return a}i(po,"createAdapter");function fo(e,t=[]){let n=t.filter(r=>!ai(e,r));return n.length===0?{ok:!0}:{ok:!1,missing:n}}i(fo,"checkContract");function lr(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(lr,"checkAdapterGovernance");function ai(e,t){return e!=null&&(typeof e=="object"||typeof e=="function")&&t in e}i(ai,"hasMember");var mo=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),ho=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Ro=Object.freeze(Object.keys(ho).sort()),go=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"}),yo=Object.freeze({process:Object.freeze(["process","node:process"])});function pn(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=go[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),o=go[r];if(o)return o;let s=e.indexOf("/",n+1);return s<0?null:go[e.slice(0,s)]??null}i(pn,"capabilityForModuleSpecifier");function Te(e,t){for(let n of t)if(yo[n]?.includes(e))return n;return null}i(Te,"forbiddenGlobalForModuleSpecifier");function cr(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),o=ho[r];if(o)return o}return null}i(cr,"capabilityForAmbientName");function Rt(e){if(e?.pure===!0)return[...mo].sort();let n=(e?.capabilities?.deny??[]).filter(r=>mo.includes(r));return[...new Set(n)].sort()}i(Rt,"effectiveCapabilityDeny");function fn(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(fn,"ambientCoveredByForbiddenGlobals");function dr(e){let t=new Set,n=new Set,r=Object.keys(ho);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 yo[o]??[])t.add(`import-exact:${a}`)}for(let o of Rt(e)){if(t.add(`import:${o}`),o==="process")for(let s of yo.process)t.add(`import-exact:${s}`);for(let s of r)cr(s)===o&&t.add(`ambient:${s}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}i(dr,"loweredLayerCoverage");function At(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(At,"literalText");function di(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}i(di,"lineOf");function li(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(li,"isTypeOnlyReference");function ui(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(ui,"singleFileChecker");function Ao(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}i(Ao,"symbolAt");function ko(e,t,n,r){let o=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,s;try{s=o?t.getShorthandAssignmentValueSymbol(r.parent):Ao(t,r)}catch{s=void 0}return!!s?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}i(ko,"localDeclaration");function et(e,t){let n,r=[],o=i((a,l,c,u=!1)=>r.push({specifier:c,kind:l,line:di(t,a),typeOnly:u,unresolved:c===void 0,node:a}),"add"),s=i(a=>{if(e.isImportDeclaration(a))o(a,"import",At(e,a.moduleSpecifier),li(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)o(a,"export",At(e,a.moduleSpecifier),li(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))o(a,"require",At(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"&&!ko(e,n??(n=ui(e,t)),t,a.expression);(l||u)&&o(a,u?"require":"dynamic-import",At(e,a.arguments[0]))}e.forEachChild(a,s)},"visit");return s(t),r}i(et,"extractSemanticDependencies");function Xl(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=At(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(Xl,"staticAccessPath");function Zl(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(Zl,"runtimeIdentifierReference");function ci(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(ci,"bestForbiddenMatch");function tt(e,t,n){if(n.length===0)return[];let r=new Set(n),o=ui(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=Xl(e,p);if(!g)return;let d=Ao(o,g.root),m=d?s.get(d):void 0;return m?[...m,...g.segments.slice(1)]:ko(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=Ao(o,g.name);!d||!m||s.set(m,d)}let c=[],u=new Set,f=i((p,g)=>{let d=di(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?ci(r,d):void 0;m&&f(m,p)}else e.isIdentifier(p)&&r.has(p.text)&&Zl(e,p)&&!ko(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?At(e,m.propertyName)??m.propertyName.text:m.name.text,S=ci(r,[...d,E]);S&&f(S,p.initializer)}}e.forEachChild(p,y)},"visit");return y(t),c}i(tt,"collectForbiddenCapabilityUses");function Io(e,t,n){let r=[];for(let o of n?.dependencies??et(e,t)){if(o.typeOnly||!o.specifier)continue;let s=pn(o.specifier);s&&r.push({capability:s,symbol:o.specifier,line:o.line,source:"import-based"})}for(let o of n?.ambientUses??tt(e,t,Ro)){let s=cr(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(Io,"collectCapabilityUses");var bo={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."},vo=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 Eo(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(Eo,"resolveIntentLayer");function nt(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}i(nt,"looksLikeArkIntent");function gn(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&nt(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:bo.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:bo.PUBLISH_MISSING_SOURCE}),t}i(gn,"classifyPublishFacts");function j(e,t,n){return{ruleId:e,code:e,message:t,...n}}i(j,"violation");function kt(e,t){return e.slice(0,t).split(`
|
|
22
|
-
`).length}i(kt,"lineOf");var Jl=new Set(["publish","subscribe","defineIntent","registerHandler"]);function Ql(e,t){return e.index+e[0].indexOf(t)}i(Ql,"captureIndex");function ec(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,Ql(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(ec,"extractQuotedStrings");function tc(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(tc,"extractModuleSpecifiers");function nc(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(nc,"isSyntaxWrapper");function So(e,t){let n=t;for(;n?.parent&&nc(e,n.parent);)n=n.parent;return n}i(So,"unwrapWrappers");function wo(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(wo,"callCalleeName");function rc(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)&&wo(e,o)==="publish"){let s=o.arguments;return s[1]===r||s[2]===r}if(e.isPropertyAssignment(o)&&Co(e,o.name)==="metadata"){let s=o.parent;if(!s)return!1;let l=So(e,s).parent;return!!(l&&e.isCallExpression(l)&&wo(e,l)==="publish")}return!1}i(rc,"isPublishMetadataSource");function pi(e,t){let n=So(e,t),r=n.parent;if(!r)return!1;if(e.isCallExpression(r)){let o=wo(e,r);if(o&&Jl.has(o)&&r.arguments.some(s=>s===n))return!0}if(e.isArrayLiteralExpression(r))return pi(e,r);if(e.isPropertyAssignment(r)){let o=Co(e,r.name);if(o==="intent"||o==="onEvent"||o==="reactsTo"||o==="source"&&rc(e,r))return!0}return!1}i(pi,"isDeclaredIntentSite");function oc(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],o=i(s=>{e.isStringLiteralLike(s)&&pi(e,s)&&r.push({value:s.text,index:s.getStart(n)}),e.forEachChild(s,o)},"visit");return o(n),r}i(oc,"extractQuotedStringsAst");function sc(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(sc,"hasInfrastructureToken");function ic(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}i(ic,"isKnownInfrastructurePackage");function ac(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}i(ac,"layerHasInfrastructureRole");function yn(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(yn,"tsStringLiteralText");function Co(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}i(Co,"tsPropertyName");function fi(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:Co(e,r.name)===n)}i(fi,"tsObjectProperty");function hn(e,t,n){return fi(e,t,n)!==void 0}i(hn,"tsObjectHasProperty");function mn(e,t,n){let r=fi(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}i(mn,"tsObjectPropertyValue");function lc(e,t){let n=mn(e,t,"metadata");return hn(e,n,"source")}i(lc,"tsObjectHasMetadataSource");function gi(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?gi(e,t.name):!1:!1}i(gi,"tsLooksLikeIntentCreatorExpression");function cc(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(cc,"tsIsPublishCall");function dc(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=yn(e,n);return r!==void 0&&nt(r)||hn(e,n,"intent")||gi(e,n)}i(dc,"tsIsArkPublishCandidate");function uc(e,t){if(!e.isCallExpression(t))return!1;let[n,r,o]=t.arguments;return lc(e,n)||hn(e,r,"source")||hn(e,o,"source")}i(uc,"tsPublishHasSource");function pc(e,t){if(!e.isCallExpression(t))return;let[n,r,o]=t.arguments,s=mn(e,n,"metadata");return yn(e,mn(e,s,"source"))??yn(e,mn(e,r,"source"))??yn(e,mn(e,o,"source"))}i(pc,"tsPublishSourceLiteral");function fc(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(cc(e,y)){let p=y.arguments[0],g=yn(e,p);for(let m of gn({publishCall:!0,rawIntentName:g,objectHasIntent:hn(e,p,"intent"),arkPublishCandidate:dc(e,y),hasSource:uc(e,y)}))c.push(j(m.ruleId,m.message,{line:u(y),filePath:a}));let d=pc(e,y);if(r&&l&&d&&nt(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(fc,"analyzePublishAst");function xo(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?et(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})):tc(s),m=e.typescript?oc(e.typescript,s):ec(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)||ac(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:kt(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:kt(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=ft(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:kt(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||!sc(k.value)&&!ic(k.value)||l.push(j("FORBIDDEN_IMPORT",`Forbidden ${k.kind} target: "${k.value}".`,{line:kt(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)nt(k.value)&&!t.has(k.value)&&l.push(j("UNKNOWN_INTENT",`Unknown intent reference: "${k.value}"`,{line:kt(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(!nt(k.value))continue;let v=e.architectureProfile.resolveLayer(k.value);if(!v)continue;let C=Ze(e.architectureProfile.rules,f,v,{fromPath:typeof u=="string"?u:void 0,layers:e.architectureLayers});if(C){let N=C.rule.peerIsolation?pt(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:kt(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(...tt(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=Te(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 Io(e.typescript,p))k.has(C.capability)&&(C.source==="ambient-global"&&fn(C.symbol,v)||C.source==="import-based"&&Te(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(...fc(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(xo,"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")}`}i(z,"deterministicHash");function $(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map($).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${$(t[n])}`).join(",")}}`}i($,"stableSerialize");var Ne="1.2";var mi=["network","filesystem","clock","randomness","environment","process","persistence"];function B(e,t){let n=$(e),r=$(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 bt(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 z($(t))}i(bt,"resolvedFactsEvidenceRequirementsHash");function gc(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=z($(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(gc,"canonicalResolvedFactsInput");function yi(e){let t=gc(e);return{...t,factsHash:z($(t))}}i(yi,"createCanonicalResolvedCandidateFacts");function ur(e){return yi(Ri(M(e,"$"),!1))}i(ur,"createResolvedCandidateFacts");function M(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}i(M,"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 be(e,t,n){if(e[t]!==void 0)return F(e,t,n)}i(be,"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 hi(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(hi,"requiredInteger");function Q(e,t,n){let r=hi(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 ve(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(ve,"enumValue");function It(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(It,"parseStringArray");function mc(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(mc,"assertUnique");function Ri(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=ve(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=ve(e,"completeness",["complete","partial","unavailable"],"$"),o=U(e,"completenessReasons","$").map((w,x)=>{let h=`$.completenessReasons[${x}]`,A=M(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=M(w,h);return H(A,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],h),{path:K(A,"path",h),contentHash:F(A,"contentHash",h),parseStatus:ve(A,"parseStatus",["parsed","invalid"],h),parseDiagnosticCount:hi(A,"parseDiagnosticCount",h),exportsOnlyTypes:G(A,"exportsOnlyTypes",h),typeOnlyExportNames:It(A.typeOnlyExportNames,`${h}.typeOnlyExportNames`),hasTopLevelSideEffects:G(A,"hasTopLevelSideEffects",h)}}),a=U(e,"dependencies","$").map((w,x)=>{let h=`$.dependencies[${x}]`,A=M(w,h);H(A,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],h);let L=be(A,"specifier",h),W=be(A,"target",h),xe=ve(A,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],h);if(xe==="resolved-project"&&!W)throw new Error(`${h}.target is required for resolved-project dependencies.`);if(xe!=="resolved-project"&&W)throw new Error(`${h}.target is only allowed for resolved-project dependencies.`);if(xe!=="dynamic"&&!L)throw new Error(`${h}.specifier is required unless resolution is dynamic.`);return{from:K(A,"from",h),...L?{specifier:L}:{},kind:ve(A,"kind",["import","export","dynamic-import","require"],h),typeOnly:G(A,"typeOnly",h),line:Q(A,"line",h),resolution:xe,...W?{target:K(A,"target",h)}:{},...A.namedBindings!==void 0?{namedBindings:It(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=M(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:ve(A,"capability",mi,h),source:ve(A,"source",["ambient-global","import-based"],h)}}),c=U(e,"ambientUses","$").map((w,x)=>{let h=`$.ambientUses[${x}]`,A=M(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=M(w,h);H(A,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],h);let L=be(A,"rawIntentName",h),W=be(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=M(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=M(w,h);H(A,["file","line","kind","symbol"],h);let L=be(A,"symbol",h),W=ve(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}:{}}});mc(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=M(w,h);H(A,["file","line","kind","callee","viaImport","receiver","nameLiteral"],h);let L=be(A,"receiver",h),W=be(A,"nameLiteral",h);return{file:K(A,"file",h),line:Q(A,"line",h),kind:ve(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=M(w,h);H(A,["file","line","typeName","importedFrom"],h);let L=be(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=M(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=M(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=M(w,h);return H(A,["file","line","method"],h),{file:K(A,"file",h),line:Q(A,"line",h),method:F(A,"method",h)}}),ye=(e.arkOrderRootHits===void 0?[]:U(e,"arkOrderRootHits","$")).map((w,x)=>{let h=`$.arkOrderRootHits[${x}]`,A=M(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=M(w,h);return H(A,["file","line","key"],h),{file:K(A,"file",h),line:Q(A,"line",h),key:F(A,"key",h)}}),Y=(e.arkOrderIngestWritesXi===void 0?[]:U(e,"arkOrderIngestWritesXi","$")).map((w,x)=>{let h=`$.arkOrderIngestWritesXi[${x}]`,A=M(w,h);return H(A,["file","line"],h),{file:K(A,"file",h),line:Q(A,"line",h)}}),Ce=(e.arkOrderReleaseKeyCounts===void 0?[]:U(e,"arkOrderReleaseKeyCounts","$")).map((w,x)=>{let h=`$.arkOrderReleaseKeyCounts[${x}]`,A=M(w,h);return H(A,["file","line","keyCount"],h),{file:K(A,"file",h),line:Q(A,"line",h),keyCount:Q(A,"keyCount",h)}}),Kt=v.map((w,x)=>{let h=`$.arkRunDeclarations[${x}]`,A=M(w,h);return H(A,["file","line","uses","reactsTo","raises","sends"],h),{file:K(A,"file",h),line:Q(A,"line",h),uses:It(A.uses,`${h}.uses`),reactsTo:It(A.reactsTo,`${h}.reactsTo`),raises:It(A.raises,`${h}.raises`),sends:It(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",Kt],["$.arkOrderPlaneCalls",N],["$.arkOrderGenericUpdates",T],["$.arkOrderRootHits",ye],["$.arkOrderXiFieldWrites",D],["$.arkOrderIngestWritesXi",Y],["$.arkOrderReleaseKeyCounts",Ce]])for(let h of x)if(!p.has(h.file))throw new Error(`${w} references missing file ${h.file}.`);let Wn=be(e,"projectPackageName","$"),ps=(e.classShapes===void 0?[]:U(e,"classShapes","$")).map((w,x)=>{let h=`$.classShapes[${x}]`,A=M(w,h);H(A,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],h);let L=U(A,"mutatingMethods",h).map((W,xe)=>{let R=`${h}.mutatingMethods[${xe}]`,te=M(W,R);return H(te,["name","referencesGuardOrPublish"],R),{name:F(te,"name",R),referencesGuardOrPublish:G(te,"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","$"),...Wn?{projectPackageName:Wn}:{},files:s,dependencies:a,capabilityUses:l,ambientUses:c,publishCalls:u,intentReferences:f,safetyUses:y,classShapes:ps,arkRunKernelCalls:d,arkRunManagedNews:E,arkRunCompositionRootHits:k,arkRunDeclarations:Kt,arkOrderPlaneCalls:N,arkOrderGenericUpdates:T,arkOrderRootHits:ye,arkOrderXiFieldWrites:D,arkOrderIngestWritesXi:Y,arkOrderReleaseKeyCounts:Ce}}i(Ri,"parseResolvedFactsInput");function Ee(e){let t=M(e,"$"),n=F(t,"factsHash","$"),r=F(t,"candidateTreeHash","$"),o=yi(Ri(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(Ee,"loadResolvedCandidateFacts");var yc=["network","filesystem","clock","randomness","environment","process","persistence"],_={type:"string",minLength:1},ne={type:"integer",minimum:1},V={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},pr={$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:ne,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:ne,symbol:_,capability:{enum:yc},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:V,line:ne,symbol:_}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:V,line:ne,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:ne,intent:_}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:V,line:ne,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:ne,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:ne,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:ne,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:ne,callee:_}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:V,line:ne,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:ne,key:_}}},arkOrderIngestWritesXi:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line"],properties:{file:V,line:ne}}},arkOrderReleaseKeyCounts:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","keyCount"],properties:{file:V,line:ne,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 fr="1.0";function se(e){return`${e.from}->${e.to}`}i(se,"dependencyKey");function Rn(e,t,n,r="dependency"){return{id:`${e}:${r}:${se(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${se(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${se(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${se(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${se(t)} from the candidate, then preflight again.`}:{}}}i(Rn,"dependencyFinding");function rt(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=>[se(p),p])),s=new Map(e.baseDependencies.map(p=>[se(p),p])),a=new Map(e.candidateDependencies.map(p=>[se(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)=>se(g).localeCompare(se(d)))){if(a.has(se(p))){t.push(Rn("satisfied",p,`${p.from} -> ${p.to} exists in the candidate architecture.`));continue}let g={from:p.to,to:p.from};a.has(se(g))?(l.add(se(g)),t.push(Rn("contradictory",p,`${p.from} -> ${p.to} was planned, but the candidate contains the reverse edge.`))):t.push(Rn("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({...Rn("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({...Rn("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(rt,"analyzeArchitectureConvergence");var Ai="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",hc=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","writes-via-aggregate","no-anemic-model","invariant-coverage"];var ki={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},am={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Ai,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:Ai},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:[...hc]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:ki,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:ki}}}};function An(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}i(An,"emptyEffectiveArkRules");function Oo(e){return{...e,layers:e.layers.map(t=>{let{description:n,trustBoundary:r,owners:o,...s}=t;return s})}}i(Oo,"omitLayerDescriptions");function Ii(e){let{stewards:t,...n}=Oo(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(Ii,"effectiveContractPolicyPayload");var Rc="INVARIANT_TESTS_PATH_MISSING",Ac="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.",kc="INVARIANT_COVERAGE_ROOTS_MISSING",Ic="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 bi(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(bi,"formatCoverageDiscards");function Si(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(Si,"isUnderCoverageRoot");function wi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}i(wi,"escapeRegExp");function Po(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}i(Po,"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==="/"&&
|
|
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 nt(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}a(nt,"propertyPath");function It(e){return e===null?"null":Array.isArray(e)?"array":typeof e}a(It,"valueType");function Tc(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}a(Tc,"resolveSchemaRef");function kn(e,t,n,r,o){if(t.$ref){let s=Tc(t.$ref,r);if(!s){o.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}kn(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 ${It(e)}`});return}let s=t.properties??{};for(let i of t.required??[])e[i]===void 0&&o.push({path:nt(n,i),message:"is required"});if(t.additionalProperties===!1)for(let i of Object.keys(e))i in s||o.push({path:nt(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||kn(e[l],i,nt(n,l),r,o)}for(let[i,l]of Object.entries(s))e[i]!==void 0&&kn(e[i],l,nt(n,i),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(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)=>kn(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 ${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}`})}}a(kn,"validateNode");var Nc=["deny","advisory"],Ei='must be "deny", "advisory", or { "default": "deny" | "advisory", "enforce": ["<child id or subtree path>"] }';function Lc(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"){Nc.includes(i)||t.push({path:l,message:Ei});return}if(!ge(i)){t.push({path:l,message:Ei});return}for(let u of Object.keys(i))u!=="default"&&u!=="enforce"&&t.push({path:nt(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=St(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(Lc,"validateChildSliceSiblings");var Dc="must be a slice id with a slash. A bare name is ambiguous across universes.",Fc="* matches one whole path segment. ** and a partial segment are not wildcards.";function $c(e){let t=St(e.trim().replace(/\\/g,"/"));if(t.length===0)return"must be a non-empty slice id";if(!t.includes("/"))return Dc;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 Fc}return null}a($c,"childCrossSlicePatternIssue");function wi(e){return St(e.trim().replace(/\\/g,"/")).toLowerCase()}a(wi,"childCrossSlicePatternKey");function Mc(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:nt(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=$c(d);b&&t.push({path:m,message:b})}if(typeof u.from!="string"||typeof u.to!="string")return;let p=`${wi(u.from)}\0${wi(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(Mc,"validateChildSliceAllowedCrossSlice");var bt="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.",Hc="overlaps a slice folder. An alias covers only files outside the slice trees.",Kc="two slice aliases match the same file";function Gc(e){return St(e.trim().replace(/\\/g,"/")).toLowerCase().split("/").filter(t=>t.length>0)}a(Gc,"aliasPathSegments");function _i(e){let t=[];for(let n of e){if(n.includes("*"))break;t.push(n)}return t}a(_i,"concreteGlobPrefix");function An(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(An,"segmentsArePrefix");function Uc(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(Uc,"anchoredSlicePrefix");function Vc(e,t){let n=_i(e),r=n.length<e.length,o=n[0]==="src"||n[0]==="app"?n.slice(1):n;return An(t,n)||An(t,o)?!0:r?An(n,t)&&n.length<t.length||An(n,["src",...t])&&n.length<t.length+1||An(n,["app",...t])&&n.length<t.length+1:!1}a(Vc,"globOverlapsAnchored");function jc(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=_i(e);return n.length<e.length&&(n.length===0||n.length===1&&(n[0]==="src"||n[0]==="app"))}a(jc,"globOverlapsBare");function Bc(e,t){let n=t.split(/[/\\]/).filter(Boolean).map(o=>o.toLowerCase());if(n.length===1&&n[0]&&!n[0].includes("*"))return jc(e,n[0]);let r=Uc(t);return r?Vc(e,r):!1}a(Bc,"globOverlapsSliceEntry");function Wc(e){let t=St(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(Wc,"aliasGlobIssue");function zc(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(zc,"universeShapes");function Ci(e,t){return e.literals.length!==t.length?!1:e.literals.every((n,r)=>n===null||n===t[r])}a(Ci,"shapeMatches");function qc(e,t){let n=St(e.trim().replace(/\\/g,"/"));if(n.length===0||n.split("/").some(o=>o.length===0||o==="."||o==="..")||n.includes("*")||!n.includes("/"))return bt;let r=n.split("/").map(o=>o.toLowerCase());return t.length===0||t.some(o=>Ci(o,r))?bt:t.some(o=>Ci(o,r.slice(0,-1)))?null:bt}a(qc,"aliasTargetIssue");function xi(e){let t=e[0];return(t==="src"||t==="app")&&e.length>1?[e,e.slice(1)]:[e]}a(xi,"aliasGlobVariants");function Yc(e,t){let n=xi(e),r=xi(t);for(let o of n)if(tt(o,t,0,0,new Map))return!0;for(let o of r)if(tt(e,o,0,0,new Map))return!0;return!1}a(Yc,"aliasesCanMatchSameFile");function tt(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=tt(e,t,n+1,r,o)||r<t.length&&tt(e,t,n,r+1,o);else if(r<t.length&&t[r]==="**")l=tt(e,t,n,r+1,o)||n<e.length&&tt(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=tt(e,t,n+1,r+1,o))}return o.set(s,l),l}a(tt,"globsCanMatchSame");function Xc(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=zc(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:nt(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=Wc(d);if(b)t.push({path:`${g}.from`,message:b});else{let v=Gc(d);u.some(k=>Bc(v,k))&&t.push({path:`${g}.from`,message:Hc});for(let k of f)if(Yc(k,v)){t.push({path:g,message:Kc});break}f.push(v)}}if(typeof m!="string"||m.trim().length===0)t.push({path:`${g}.to`,message:bt});else{let b=qc(m,c);b&&t.push({path:`${g}.to`,message:b})}})})}a(Xc,"validateChildSliceAliases");function Zc(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"&&(bi(i)||t.push({path:`$.layers[${o}].owners[${l}]`,message:"must be a GitHub handle or email (not a display name)"}))})})}a(Zc,"validateLayerOwners");function Jc(e){let t={...e,$schema:e.$schema===void 0?Rr:e.$schema,schemaVersion:e.schemaVersion===void 0?de:e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?Ar.map(n=>({...n})):e.rules};return e.arkRun!==void 0&&(t.arkRun=hi(e.arkRun)),e.arkOrder!==void 0&&(t.arkOrder=Ri(e.arkOrder)),t}a(Jc,"defaultedConfig");function Qc(e){return e===de?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}a(Qc,"migratedFromOf");function ed(){let e=new Set([de]);for(let t of vo)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}a(ed,"knownInputVersions");function td(e,t="ark.config.json"){if(!ge(e))throw new ve(t,[{path:"$",message:`must be an object; received ${It(e)}`}]);let n=ed(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new ve(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected ${de}`}]);if(r!=="unversioned"&&!n.has(r))throw new ve(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${de}`}]);let o=r,s={...e},i=0;for(;o!==de&&i<vo.length+1;){i+=1;let l=vo.find(c=>c.from===o);if(!l)throw new ve(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(o)}; expected ${de}`}]);o=l.to,s.schemaVersion=o}if(o!==de)throw new ve(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${de}`}]);return{candidate:Jc(s),migratedFrom:Qc(r)}}a(td,"migrateArkConfig");function Eo(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=td(e,t),o=[];if(kn(n,vi,"$",vi,o),Ai(n,o),ki(n,o),Zc(n,o),Lc(n,o),Mc(n,o),Xc(n,o),o.length>0)throw new ve(t,o);return{config:n,migratedFrom:r}}a(Eo,"loadArkConfigContract");function Ti(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new ve(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return Eo(n,t)}a(Ti,"parseArkConfigJson");function Ni(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:Rr,schemaVersion:de};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}a(Ni,"withArkConfigMetadata");function St(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}a(St,"trimTrailingSlashes");function nd(e){return e.endsWith(".")?e:`${e}.`}a(nd,"normalizePrefix");function rd(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(rd,"byLongestPrefix");function In(e){let t=e.layers.map(o=>({...o,prefixes:o.prefixes.map(nd)})),n=[...t].sort(rd),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(In,"createArchitectureProfile");function bn(e,t={}){return In({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(bn,"createArchitectureProfileFromArkConfig");var od=[{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}],rt=In({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:od,rules:Ar.map(e=>({...e}))}),sd={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 wo(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return Ni({include:e.include??[t],layers:rt.layers.map(o=>({name:o.name,patterns:(sd[o.name]??[o.name]).map(s=>`${r}${s}/**`),intentPrefixes:o.prefixes,optional:n})),rules:[...rt.rules]})}a(wo,"createElevenLayerArkConfig");var kr=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 Sn(){return new kr}a(Sn,"createMetadataRegistry");function Co(e,t={}){return{name:e,ownerLayer:t.ownerLayer,intent:t.intent,allowedAdapters:t.allowedAdapters?[...t.allowedAdapters]:void 0}}a(Co,"definePort");function xo(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=>!Li(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=Ir(i);if(!l.ok)throw new Error(l.issues.map(c=>c.message).join(`
|
|
21
|
+
`));return i}a(xo,"createAdapter");function Oo(e,t=[]){let n=t.filter(r=>!Li(e,r));return n.length===0?{ok:!0}:{ok:!1,missing:n}}a(Oo,"checkContract");function Ir(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(Ir,"checkAdapterGovernance");function Li(e,t){return e!=null&&(typeof e=="object"||typeof e=="function")&&t in e}a(Li,"hasMember");var _o=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),No=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Lo=Object.freeze(Object.keys(No).sort()),Po=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"}),To=Object.freeze({process:Object.freeze(["process","node:process"])});function vn(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=Po[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),o=Po[r];if(o)return o;let s=e.indexOf("/",n+1);return s<0?null:Po[e.slice(0,s)]??null}a(vn,"capabilityForModuleSpecifier");function De(e,t){for(let n of t)if(To[n]?.includes(e))return n;return null}a(De,"forbiddenGlobalForModuleSpecifier");function br(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),o=No[r];if(o)return o}return null}a(br,"capabilityForAmbientName");function vt(e){if(e?.pure===!0)return[..._o].sort();let n=(e?.capabilities?.deny??[]).filter(r=>_o.includes(r));return[...new Set(n)].sort()}a(vt,"effectiveCapabilityDeny");function En(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(En,"ambientCoveredByForbiddenGlobals");function Sr(e){let t=new Set,n=new Set,r=Object.keys(No);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 To[o]??[])t.add(`import-exact:${i}`)}for(let o of vt(e)){if(t.add(`import:${o}`),o==="process")for(let s of To.process)t.add(`import-exact:${s}`);for(let s of r)br(s)===o&&t.add(`ambient:${s}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}a(Sr,"loweredLayerCoverage");function Et(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}a(Et,"literalText");function $i(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}a($i,"lineOf");function Di(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(Di,"isTypeOnlyReference");function Mi(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(Mi,"singleFileChecker");function Do(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}a(Do,"symbolAt");function Fo(e,t,n,r){let o=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,s;try{s=o?t.getShorthandAssignmentValueSymbol(r.parent):Do(t,r)}catch{s=void 0}return!!s?.declarations?.some(i=>i.getSourceFile().fileName===n.fileName)}a(Fo,"localDeclaration");function ot(e,t){let n,r=[],o=a((i,l,c,u=!1)=>r.push({specifier:c,kind:l,line:$i(t,i),typeOnly:u,unresolved:c===void 0,node:i}),"add"),s=a(i=>{if(e.isImportDeclaration(i))o(i,"import",Et(e,i.moduleSpecifier),Di(e,i));else if(e.isExportDeclaration(i)&&i.moduleSpecifier)o(i,"export",Et(e,i.moduleSpecifier),Di(e,i));else if(e.isImportEqualsDeclaration(i)&&e.isExternalModuleReference(i.moduleReference))o(i,"require",Et(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"&&!Fo(e,n??(n=Mi(e,t)),t,i.expression);(l||u)&&o(i,u?"require":"dynamic-import",Et(e,i.arguments[0]))}e.forEachChild(i,s)},"visit");return s(t),r}a(ot,"extractSemanticDependencies");function id(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=Et(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(id,"staticAccessPath");function ad(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(ad,"runtimeIdentifierReference");function Fi(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(Fi,"bestForbiddenMatch");function st(e,t,n){if(n.length===0)return[];let r=new Set(n),o=Mi(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=id(e,p);if(!g)return;let d=Do(o,g.root),m=d?s.get(d):void 0;return m?[...m,...g.segments.slice(1)]:Fo(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=Do(o,g.name);!d||!m||s.set(m,d)}let c=[],u=new Set,f=a((p,g)=>{let d=$i(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?Fi(r,d):void 0;m&&f(m,p)}else e.isIdentifier(p)&&r.has(p.text)&&ad(e,p)&&!Fo(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?Et(e,m.propertyName)??m.propertyName.text:m.name.text,v=Fi(r,[...d,b]);v&&f(v,p.initializer)}}e.forEachChild(p,y)},"visit");return y(t),c}a(st,"collectForbiddenCapabilityUses");function $o(e,t,n){let r=[];for(let o of n?.dependencies??ot(e,t)){if(o.typeOnly||!o.specifier)continue;let s=vn(o.specifier);s&&r.push({capability:s,symbol:o.specifier,line:o.line,source:"import-based"})}for(let o of n?.ambientUses??st(e,t,Lo)){let s=br(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($o,"collectCapabilityUses");var Mo={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."},Ho=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 Ko(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(Ko,"resolveIntentLayer");function it(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}a(it,"looksLikeArkIntent");function wn(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&it(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:Mo.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:Mo.PUBLISH_MISSING_SOURCE}),t}a(wn,"classifyPublishFacts");function B(e,t,n){return{ruleId:e,code:e,message:t,...n}}a(B,"violation");function wt(e,t){return e.slice(0,t).split(`
|
|
22
|
+
`).length}a(wt,"lineOf");var ld=new Set(["publish","subscribe","defineIntent","registerHandler"]);function cd(e,t){return e.index+e[0].indexOf(t)}a(cd,"captureIndex");function dd(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,cd(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(dd,"extractQuotedStrings");function ud(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(ud,"extractModuleSpecifiers");function pd(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(pd,"isSyntaxWrapper");function Go(e,t){let n=t;for(;n?.parent&&pd(e,n.parent);)n=n.parent;return n}a(Go,"unwrapWrappers");function Uo(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(Uo,"callCalleeName");function fd(e,t){let n=t.parent;if(!n||!e.isObjectLiteralExpression(n))return!1;let r=Go(e,n),o=r.parent;if(!o)return!1;if(e.isCallExpression(o)&&Uo(e,o)==="publish"){let s=o.arguments;return s[1]===r||s[2]===r}if(e.isPropertyAssignment(o)&&Vo(e,o.name)==="metadata"){let s=o.parent;if(!s)return!1;let l=Go(e,s).parent;return!!(l&&e.isCallExpression(l)&&Uo(e,l)==="publish")}return!1}a(fd,"isPublishMetadataSource");function Hi(e,t){let n=Go(e,t),r=n.parent;if(!r)return!1;if(e.isCallExpression(r)){let o=Uo(e,r);if(o&&ld.has(o)&&r.arguments.some(s=>s===n))return!0}if(e.isArrayLiteralExpression(r))return Hi(e,r);if(e.isPropertyAssignment(r)){let o=Vo(e,r.name);if(o==="intent"||o==="onEvent"||o==="reactsTo"||o==="source"&&fd(e,r))return!0}return!1}a(Hi,"isDeclaredIntentSite");function gd(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],o=a(s=>{e.isStringLiteralLike(s)&&Hi(e,s)&&r.push({value:s.text,index:s.getStart(n)}),e.forEachChild(s,o)},"visit");return o(n),r}a(gd,"extractQuotedStringsAst");function md(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(md,"hasInfrastructureToken");function yd(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}a(yd,"isKnownInfrastructurePackage");function hd(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}a(hd,"layerHasInfrastructureRole");function xn(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}a(xn,"tsStringLiteralText");function Vo(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}a(Vo,"tsPropertyName");function Ki(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:Vo(e,r.name)===n)}a(Ki,"tsObjectProperty");function On(e,t,n){return Ki(e,t,n)!==void 0}a(On,"tsObjectHasProperty");function Cn(e,t,n){let r=Ki(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}a(Cn,"tsObjectPropertyValue");function Rd(e,t){let n=Cn(e,t,"metadata");return On(e,n,"source")}a(Rd,"tsObjectHasMetadataSource");function Gi(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?Gi(e,t.name):!1:!1}a(Gi,"tsLooksLikeIntentCreatorExpression");function Ad(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(Ad,"tsIsPublishCall");function kd(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=xn(e,n);return r!==void 0&&it(r)||On(e,n,"intent")||Gi(e,n)}a(kd,"tsIsArkPublishCandidate");function Id(e,t){if(!e.isCallExpression(t))return!1;let[n,r,o]=t.arguments;return Rd(e,n)||On(e,r,"source")||On(e,o,"source")}a(Id,"tsPublishHasSource");function bd(e,t){if(!e.isCallExpression(t))return;let[n,r,o]=t.arguments,s=Cn(e,n,"metadata");return xn(e,Cn(e,s,"source"))??xn(e,Cn(e,r,"source"))??xn(e,Cn(e,o,"source"))}a(bd,"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(Ad(e,y)){let p=y.arguments[0],g=xn(e,p);for(let m of wn({publishCall:!0,rawIntentName:g,objectHasIntent:On(e,p,"intent"),arkPublishCandidate:kd(e,y),hasSource:Id(e,y)}))c.push(B(m.ruleId,m.message,{line:u(y),filePath:i}));let d=bd(e,y);if(r&&l&&d&&it(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 jo(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?ot(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})):ud(s),m=e.typescript?gd(e.typescript,s):dd(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)||hd(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:wt(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:wt(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=Ne(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=Qe(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:wt(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||!md(k.value)&&!yd(k.value)||l.push(B("FORBIDDEN_IMPORT",`Forbidden ${k.kind} target: "${k.value}".`,{line:wt(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)it(k.value)&&!t.has(k.value)&&l.push(B("UNKNOWN_INTENT",`Unknown intent reference: "${k.value}"`,{line:wt(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(!it(k.value))continue;let E=e.architectureProfile.resolveLayer(k.value);if(!E)continue;let O=Ne(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?ht({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=Qe(L);l.push(B("LAYER_REFERENCE_VIOLATION",N,{line:wt(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(...st(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=De(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 $o(e.typescript,p))k.has(O.capability)&&(O.source==="ambient-global"&&En(O.symbol,E)||O.source==="import-based"&&De(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(jo,"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")}`}a(Y,"deterministicHash");function $(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map($).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${$(t[n])}`).join(",")}}`}a($,"stableSerialize");var Fe="1.2";var Ui=["network","filesystem","clock","randomness","environment","process","persistence"];function W(e,t){let n=$(e),r=$(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 xt(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 Y($(t))}a(xt,"resolvedFactsEvidenceRequirementsHash");function vd(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=Y($(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(vd,"canonicalResolvedFactsInput");function Vi(e){let t=vd(e);return{...t,factsHash:Y($(t))}}a(Vi,"createCanonicalResolvedCandidateFacts");function vr(e){return Vi(Bi(M(e,"$"),!1))}a(vr,"createResolvedCandidateFacts");function M(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}a(M,"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 Ee(e,t,n){if(e[t]!==void 0)return F(e,t,n)}a(Ee,"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 ji(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(ji,"requiredInteger");function ne(e,t,n){let r=ji(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 we(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(we,"enumValue");function Ct(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(Ct,"parseStringArray");function Ed(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(Ed,"assertUnique");function Bi(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=we(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=we(e,"completeness",["complete","partial","unavailable"],"$"),o=V(e,"completenessReasons","$").map((w,x)=>{let h=`$.completenessReasons[${x}]`,A=M(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=M(w,h);return H(A,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],h),{path:G(A,"path",h),contentHash:F(A,"contentHash",h),parseStatus:we(A,"parseStatus",["parsed","invalid"],h),parseDiagnosticCount:ji(A,"parseDiagnosticCount",h),exportsOnlyTypes:U(A,"exportsOnlyTypes",h),typeOnlyExportNames:Ct(A.typeOnlyExportNames,`${h}.typeOnlyExportNames`),hasTopLevelSideEffects:U(A,"hasTopLevelSideEffects",h)}}),i=V(e,"dependencies","$").map((w,x)=>{let h=`$.dependencies[${x}]`,A=M(w,h);H(A,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],h);let D=Ee(A,"specifier",h),q=Ee(A,"target",h),Pe=we(A,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],h);if(Pe==="resolved-project"&&!q)throw new Error(`${h}.target is required for resolved-project dependencies.`);if(Pe!=="resolved-project"&&q)throw new Error(`${h}.target is only allowed for resolved-project dependencies.`);if(Pe!=="dynamic"&&!D)throw new Error(`${h}.specifier is required unless resolution is dynamic.`);return{from:G(A,"from",h),...D?{specifier:D}:{},kind:we(A,"kind",["import","export","dynamic-import","require"],h),typeOnly:U(A,"typeOnly",h),line:ne(A,"line",h),resolution:Pe,...q?{target:G(A,"target",h)}:{},...A.namedBindings!==void 0?{namedBindings:Ct(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=M(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:we(A,"capability",Ui,h),source:we(A,"source",["ambient-global","import-based"],h)}}),c=V(e,"ambientUses","$").map((w,x)=>{let h=`$.ambientUses[${x}]`,A=M(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=M(w,h);H(A,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],h);let D=Ee(A,"rawIntentName",h),q=Ee(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=M(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=M(w,h);H(A,["file","line","kind","symbol"],h);let D=Ee(A,"symbol",h),q=we(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}:{}}});Ed(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=M(w,h);H(A,["file","line","kind","callee","viaImport","receiver","nameLiteral"],h);let D=Ee(A,"receiver",h),q=Ee(A,"nameLiteral",h);return{file:G(A,"file",h),line:ne(A,"line",h),kind:we(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=M(w,h);H(A,["file","line","typeName","importedFrom"],h);let D=Ee(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=M(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=M(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=M(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=M(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=M(w,h);return H(A,["file","line","key"],h),{file:G(A,"file",h),line:ne(A,"line",h),key:F(A,"key",h)}}),Z=(e.arkOrderIngestWritesXi===void 0?[]:V(e,"arkOrderIngestWritesXi","$")).map((w,x)=>{let h=`$.arkOrderIngestWritesXi[${x}]`,A=M(w,h);return H(A,["file","line"],h),{file:G(A,"file",h),line:ne(A,"line",h)}}),Oe=(e.arkOrderReleaseKeyCounts===void 0?[]:V(e,"arkOrderReleaseKeyCounts","$")).map((w,x)=>{let h=`$.arkOrderReleaseKeyCounts[${x}]`,A=M(w,h);return H(A,["file","line","keyCount"],h),{file:G(A,"file",h),line:ne(A,"line",h),keyCount:ne(A,"keyCount",h)}}),qt=E.map((w,x)=>{let h=`$.arkRunDeclarations[${x}]`,A=M(w,h);return H(A,["file","line","uses","reactsTo","raises","sends"],h),{file:G(A,"file",h),line:ne(A,"line",h),uses:Ct(A.uses,`${h}.uses`),reactsTo:Ct(A.reactsTo,`${h}.reactsTo`),raises:Ct(A.raises,`${h}.raises`),sends:Ct(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",qt],["$.arkOrderPlaneCalls",L],["$.arkOrderGenericUpdates",N],["$.arkOrderRootHits",Q],["$.arkOrderXiFieldWrites",T],["$.arkOrderIngestWritesXi",Z],["$.arkOrderReleaseKeyCounts",Oe]])for(let h of x)if(!p.has(h.file))throw new Error(`${w} references missing file ${h.file}.`);let or=Ee(e,"projectPackageName","$"),Ts=(e.classShapes===void 0?[]:V(e,"classShapes","$")).map((w,x)=>{let h=`$.classShapes[${x}]`,A=M(w,h);H(A,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],h);let D=V(A,"mutatingMethods",h).map((q,Pe)=>{let R=`${h}.mutatingMethods[${Pe}]`,oe=M(q,R);return H(oe,["name","referencesGuardOrPublish"],R),{name:F(oe,"name",R),referencesGuardOrPublish:U(oe,"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","$"),...or?{projectPackageName:or}:{},files:s,dependencies:i,capabilityUses:l,ambientUses:c,publishCalls:u,intentReferences:f,safetyUses:y,classShapes:Ts,arkRunKernelCalls:d,arkRunManagedNews:b,arkRunCompositionRootHits:k,arkRunDeclarations:qt,arkOrderPlaneCalls:L,arkOrderGenericUpdates:N,arkOrderRootHits:Q,arkOrderXiFieldWrites:T,arkOrderIngestWritesXi:Z,arkOrderReleaseKeyCounts:Oe}}a(Bi,"parseResolvedFactsInput");function Ce(e){let t=M(e,"$"),n=F(t,"factsHash","$"),r=F(t,"candidateTreeHash","$"),o=Vi(Bi(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(Ce,"loadResolvedCandidateFacts");var wd=["network","filesystem","clock","randomness","environment","process","persistence"],_={type:"string",minLength:1},se={type:"integer",minimum:1},j={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},Er={$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:se,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:se,symbol:_,capability:{enum:wd},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:j,line:se,symbol:_}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:j,line:se,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:se,intent:_}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:j,line:se,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:se,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:se,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:se,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:se,callee:_}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:j,line:se,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:se,key:_}}},arkOrderIngestWritesXi:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line"],properties:{file:j,line:se}}},arkOrderReleaseKeyCounts:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","keyCount"],properties:{file:j,line:se,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 wr="1.0";function ae(e){return`${e.from}->${e.to}`}a(ae,"dependencyKey");function Pn(e,t,n,r="dependency"){return{id:`${e}:${r}:${ae(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${ae(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${ae(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${ae(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${ae(t)} from the candidate, then preflight again.`}:{}}}a(Pn,"dependencyFinding");function at(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=>[ae(p),p])),s=new Map(e.baseDependencies.map(p=>[ae(p),p])),i=new Map(e.candidateDependencies.map(p=>[ae(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)=>ae(g).localeCompare(ae(d)))){if(i.has(ae(p))){t.push(Pn("satisfied",p,`${p.from} -> ${p.to} exists in the candidate architecture.`));continue}let g={from:p.to,to:p.from};i.has(ae(g))?(l.add(ae(g)),t.push(Pn("contradictory",p,`${p.from} -> ${p.to} was planned, but the candidate contains the reverse edge.`))):t.push(Pn("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({...Pn("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({...Pn("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(at,"analyzeArchitectureConvergence");var Wi="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 zi={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},_y={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Wi,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:Wi},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:zi,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:zi}}}};function _n(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}a(_n,"emptyEffectiveArkRules");function Bo(e){return{...e,layers:e.layers.map(t=>{let{description:n,trustBoundary:r,owners:o,...s}=t;return s})}}a(Bo,"omitLayerDescriptions");function qi(e){let{stewards:t,...n}=Bo(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(qi,"effectiveContractPolicyPayload");var xd="INVARIANT_TESTS_PATH_MISSING",Od="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",_d="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 Yi(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(Yi,"formatCoverageDiscards");function Ji(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(Ji,"isUnderCoverageRoot");function zo(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}a(zo,"escapeRegExp");function Ot(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}a(Ot,"normalizePath");function qo(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("")}
|
|
26
|
+
`?" ":c),r+=1}continue}n.push(s),r+=1}return n.join("")}a(qo,"maskNonCode");function Td(e,t){if(!t)return;let n=zo(t),s=new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*(['"\`])((?:(?!\\1)[^\\\\]|\\\\.)*?${n}(?:(?!\\1)[^\\\\]|\\\\.)*?)\\1`,"i").exec(qo(e,!1))?.[2];return s===void 0?void 0:s}a(Td,"matchTestTitle");function Nd(e,t){if(!t)return;let n=zo(t),r=qo(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(Nd,"declarationShape");function Ld(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)}
|
|
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(vi,"mentionContext");function xi(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(xi,"symbolNeedle");function wc(e){return xi(e.coverage?.symbol)?.name??e.id}i(wc,"declaredLabel");function Ei(e){return Object.keys(e).sort((t,n)=>t<n?-1:t>n?1:0)}i(Ei,"sortedContentFiles");function Cc(e,t,n=!0){let r=t.testFiles??[],o=new Set(r.map(g=>Po(g))),s=(t.coverageRoots??[]).filter(g=>typeof g=="string"&&g.length>0),a=e.coverage?.test!==!1&&n,l=xi(e.coverage?.symbol??void 0),c,u;if(a){for(let g of r){let d=t.fileContents[g];if(!d)continue;let m=bc(d,e.id);if(m!==void 0){if(s.length===0||Si(g,s)){c={file:g,title:m};break}u??={file:g,title:m}}}c??=u}let f;if(l)for(let g of Ei(t.fileContents)){if(o.has(Po(g)))continue;let d=t.fileContents[g];if(!d||l.className&&!d.includes(l.className))continue;let m=vc(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=vi(d,e.id,!0);if(m){y={file:g,context:m};break}}if(!y&&l)for(let g of Ei(t.fileContents)){if(o.has(Po(g)))continue;let d=t.fileContents[g];if(!d)continue;let m=vi(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 xc(e){switch(e.kind){case"test-title":case"declaration":return!0;case"mention-only":case"none":return!1}}i(xc,"countsAsCoverage");function Oc(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(Oc,"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} ${wc(e)}\` in ${t.file}`;case"mention-only":return`${e.id} appears only in ${Oc(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 Oi(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=bi(s),l=bi(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=xc(v),b,T;S&&k.testTitle&&(b=k.testTitle.file,f&&(T=!Si(b,u)));let Ve=k.declaration?.file,ye=k.declaration?.shape,D=(d.coverage?.test===!0||!!E||d.coverage===void 0)&&N||d.coverage?.test===!1&&!E?!0:N,q=r&&m&&!N;if(p.push({invariantId:d.id,layer:d.provenance.layer,sourceFile:d.provenance.sourceFile,mode:d.mode,covered:D&&!q,evidence:C,partial:q,description:d.description,...b!==void 0?{testEvidenceFile:b}:{},...Ve!==void 0?{symbolEvidenceFile:Ve}:{},...ye!==void 0?{shape:ye}:{},...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||q){let Y=d.mode==="enforced"&&!q,he=r||n.length===0?"never-had-tests":"tests-disappeared";g.push({ruleId:"INVARIANT_UNCOVERED",message:(q?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)} (${he==="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.`)+(q&&o?l:a),file:d.provenance.sourceFile,line:1,arkruleId:d.id,arkruleSource:d.provenance.sourceFile,fromLayer:d.provenance.layer,severity:Y?"error":"warning",failsStrict:Y,kind:he})}}return{coverage:p,violations:g,partial:p.some(d=>d.partial)}}i(Oi,"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 _o(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(_o,"nonEmptyPathStrings");function _c(e){return!e||typeof e!="object"?[]:[..._o(e.testGlobs),..._o(e.coverageRoots)]}i(_c,"configuredInvariantTestsPaths");function Tc(e){return _c(e).length>0}i(Tc,"hasConfiguredInvariantTestsPath");function To(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.coverage?.test!==!1)}i(To,"catalogDemandsInvariantTestsPath");function _i(e){let t=e.hasDomainInvariants===!0||e.hasDomainInvariants!==!1&&To(e.invariants);return e.adopted!==!0||!t?[]:Tc(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:Rc,message:Ac,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]}i(_i,"collectMissingInvariantTestsPathFindings");function Nc(e){return!e||typeof e!="object"?[]:_o(e.coverageRoots)}i(Nc,"configuredCoverageRoots");function Dc(e){return Nc(e).length>0}i(Dc,"hasConfiguredCoverageRoots");function No(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.mode==="enforced")}i(No,"catalogHasEnforcedInvariant");function Ti(e){return e.hasEnforcedInvariant===!0||e.hasEnforcedInvariant!==!1&&No(e.invariants)?Dc(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:kc,message:Ic,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]:[]}i(Ti,"collectMissingCoverageRootsFindings");var mr="1.0",Lc="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 ${Lc}`: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 kn(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(kn,"compareBoolean");function gr(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(gr,"keyed");function Fc(e,t,n){let r=gr(t,s=>s.name),o=gr(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=dr(a),f=dr(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)}),kn(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."),kn(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(Fc,"compareLayers");function $c(e,t,n){let r=i(a=>`${a.from}->${a.to}`,"keyOf"),o=gr(t,r),s=gr(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)&&(Di(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."),Di(e,`${u}.allowedCrossSlice`,"cross-slice-allowance",Z((l.allowedCrossSlice??[]).map(Ni)),Z((c.allowedCrossSlice??[]).map(Ni)),"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($c,"compareRules");function Ni(e){return JSON.stringify([e.from,e.to])}i(Ni,"crossSliceKey");function Di(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(Di,"compareDeclaredExceptions");function Mc(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"])kn(e,`$.safety.${s}`,r[s]===!0,o[s]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}i(Mc,"compareSafety");function Do(e){return e.mode==="enforced"?"enforced":"advisory"}i(Do,"arkRunMode");function Lo(e){return e.mode==="enforced"?"enforced":"advisory"}i(Lo,"arkOrderMode");function Hc(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 (${Lo(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=Lo(r),l=Lo(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(Hc,"compareArkOrder");function Kc(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 (${Do(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=Do(r),l=Do(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."}),kn(e,`${s}.requireDeclarations`,r.requireDeclarations!==!1,o.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}i(Kc,"compareArkRun");function Gc(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(Gc,"overallClassification");function Li(e,t){return`${e}::${t}`}i(Li,"ruleKey");function Fi(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(Li(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(Li(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}i(Fi,"indexEffectiveRules");function Uc(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=Fi(r),y=Fi(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(Uc,"compareArkRules");function yr(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."}),kn(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}),Fc(r,e.layers,t.layers),$c(r,e.rules,t.rules),Mc(r,e,t),Uc(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),Kc(r,e,t),Hc(r,e,t),r.sort((l,c)=>l.path.localeCompare(c.path)||l.id.localeCompare(c.id)),{schemaVersion:mr,classification:Gc(r),findings:r}}i(yr,"classifyArkPolicyDelta");function hr(e,t){if(!e||e.schemaVersion!==mr||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(hr,"policyDeltaAcknowledgementMatches");function ot(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(ot,"normalizePath");function $i(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}i($i,"isIdentifierStart");function Rr(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}i(Rr,"isIdentifierCharacter");function ie(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}i(ie,"skipWhitespace");function In(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(In,"readString");function ce(e,t,n){return e.startsWith(t,n)&&!Rr(e[n-1])&&!Rr(e[n+t.length])}i(ce,"isWordAt");function Mi(e,t){let n=ie(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=ie(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!ce(e,"type",n))return!1;let o=ie(e,n+4);if(o>=e.length||e[o]===","||e[o]==="}"||ce(e,"as",o)||!$i(e[o]))return!1;for(n=o;n<e.length&&Rr(e[n]);)n+=1;if(n=ie(e,n),ce(e,"as",n)){if(n=ie(e,n+2),!$i(e[n]))return!1;for(;n<e.length&&Rr(e[n]);)n+=1}r=!0}return!1}i(Mi,"bracedNamedBindingsAreTypeOnly");function Vc(e,t){if(t=ie(e,t+6),e[t]==="(")return In(e,ie(e,t+1));let n=!1;if(ce(e,"type",t)){let o=ie(e,t+4);e[o]!==","&&!ce(e,"from",o)&&(n=!0)}else Mi(e,t)&&(n=!0);let r=Hi(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}i(Vc,"specifierAfterImport");function jc(e,t){t=t+6;let n=ie(e,t),r=!1;if(ce(e,"type",n)){let s=ie(e,n+4);(e[s]==="{"||e[s]==="*")&&(r=!0)}else Mi(e,n)&&(r=!0);let o=Hi(e,t,!1);return o&&r?{...o,typeOnly:!0}:o}i(jc,"specifierAfterExport");function Hi(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(ce(e,"from",t))return In(e,ie(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return In(e,t);if(t>0&&(ce(e,"import",t)||ce(e,"export",t)))return}}i(Hi,"specifierInStaticStatement");function Bc(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(Bc,"skipTemplateLiteral");function Wc(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=ie(e,t+7);if(e[r]!=="(")return;r=ie(e,r+1);let o=In(e,r);return o?{...o,requireCall:!0}:void 0}i(Wc,"specifierAfterRequire");function zc(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=
|
|
31
|
-
`).length;r.push({file:e.path,symbol:s,capability:u,evidence:{kind:"import",file:e.path,line:f,excerpt:o.excerpt}});continue}let
|
|
32
|
-
`).length,l={kind:"import",file:e.path,line:a,excerpt:o.excerpt},c=qc(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(Ki,"moduleFactsFor");function qc(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(qc,"resolveSpecifier");function Gi(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let o=ft(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(Gi,"violationsFor");var Yc={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 Xc(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}i(Xc,"hasActiveArkRules");function Zc(e,t){return Xc(e,t)?z($(Ii({config:e,arkRules:t,warnings:[]}))):z($(Oo(e)))}i(Zc,"policyHashFor");function bn(e,t,n){let r=typeof e=="string"?si(e,t):lo(e,t),o=n?.arkRules??An();return{...r,arkRules:o,policyHash:Zc(r.config,o)}}i(bn,"loadContract");function Fo(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=yr(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&&hr(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(Fo,"analyzePolicyDelta");function vt(e){let t=e.files.map(y=>{let p=ot(y.path);return{path:p,content:y.content,contentHash:z(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=Ki(y,n);r.push(...p.edges),o.push(...p.capabilityUses)}let s=Gi(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(Rt(y))]));for(let y of o){let p=n.get(y.file)?.layer;if(!p)continue;let g=a.get(p),d=Te(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"?[]:[{...Yc}],f={schemaVersion:fr,policyHash:e.contract.policyHash,compilerOptionsHash:z($(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(vt,"analyzeProject");function vn(e){let t=new Map(e.files.map(n=>[ot(n.path),n]));for(let n of e.changes){let r=ot(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return vt({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}i(vn,"analyzeChange");function $o(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($o,"explainViolation");function Ar(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(Ar,"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 a=Ze(e.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:e.config.layers});if(!a){let p=Ts(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?pt(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=Ar(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(st,"evaluateArchitectureGraph");function Ui(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(Ui,"structureFreezeTarget");var Jc=["no-anemic-model"],zi=["ensureInvariants","assertInvariants","validate","publish","emit","raise","record"],Gm=new RegExp(`\\b(${zi.join("|")})\\b`),qi="(?:_?pendingEvents|domainEvents|uncommittedEvents|recordedEvents)",Um=new RegExp(`\\bthis\\.${qi}\\.push\\s*\\(`),Vm=new RegExp(`^this\\.${qi}\\s*=\\s*\\[\\s*\\]`);var Qc="truncatedUntil";function ed(){return`${zi.join(", ")}, or events-array .push(`}i(ed,"expectedDomainInvariantWordsPhrase");function Mo(e){let t=Object.getOwnPropertyDescriptor(e,Qc)?.value;return typeof t=="number"?t:void 0}i(Mo,"shapeTruncatedUntil");function td(e){let t=Mo(e);return t==null?"":` shape analysed until character ${t}`}i(td,"shapeTruncationSuffix");function Vi(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(Vi,"escapeGlobLiteral");function nd(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+=Vi(t[r+1]),r+=1):o==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":o==="?"?n+="[^/]":n+=Vi(o)}return new RegExp(`^${n}$`)}i(nd,"globToRegExp");function Et(e,t){return!t||t.length===0?!0:t.some(n=>nd(n).test(e))}i(Et,"matchesAppliesTo");function Yi(e){return Jc.includes(e)}i(Yi,"isTier2");function Xi(e){return e.mode==="enforced"&&!Yi(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}i(Xi,"severityFor");function De(e,t,n,r=1){let{severity:o,failsStrict:s}=Xi(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(De,"baseViolation");function kr(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}i(kr,"isInRuleLayer");function Ir(e,t,n){return t.filter(r=>!(!r.exported||!Et(r.file,e.appliesTo)||!kr(r.file,e,n)))}i(Ir,"shapesForRule");function rd(e,t,n){let r=[];for(let o of Ir(e,t,n))(o.hasPublicSetters||o.hasPublicMutableFields)&&r.push(De(e,o.file,`Exported class ${o.className} exposes public mutable state (sensor aggregate-private-state).`));return r}i(rd,"evaluateAggregatePrivateState");function od(e,t,n){let r=[];for(let o of Ir(e,t,n))if(o.hasPublicConstructor&&!o.hasStaticFactory){if(!(o.hasPublicMutableFields||o.hasPublicSetters||(o.mutatingMethods?.length??0)>0))continue;r.push(De(e,o.file,`Exported class ${o.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}return r}i(od,"evaluateAlwaysValidFactory");function sd(e,t,n){let r=[],o=ed();for(let s of Ir(e,t,n)){let a=td(s);Mo(s)!=null&&r.push(De(e,s.file,`Exported class ${s.className} shape analysed until character ${Mo(s)}; later methods may be invisible (sensor domain-event-on-mutation).`));for(let l of s.mutatingMethods)l.referencesGuardOrPublish||r.push(De(e,s.file,`Mutating method ${s.className}.${l.name} does not reference ${o} (sensor domain-event-on-mutation).${a}`))}return r}i(sd,"evaluateDomainEventOnMutation");function id(e,t){let n=[];for(let r of t.files)Et(r,e.appliesTo)&&kr(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(De(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}i(id,"evaluateOrchestrationOnly");function ad(e,t){let n=[];for(let r of t.files)Et(r,e.appliesTo)&&kr(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(De(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}i(ad,"evaluateThinAdapter");function ld(e,t){let n=[];for(let r of t.files)Et(r,e.appliesTo)&&kr(r,e,t.layerForFile)&&t.fileHints?.[r]?.persistenceWrite&&n.push(De(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(ld,"evaluateWritesViaAggregate");function cd(e,t,n){let r=[];for(let o of Ir(e,t,n))if(o.dataOnly===!0){let s=De(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(cd,"evaluateNoAnemicModel");function Zi(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(...rd(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...od(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...sd(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...id(n,e));break;case"thin-adapter":t.push(...ad(n,e));break;case"writes-via-aggregate":t.push(...ld(n,e));break;case"no-anemic-model":t.push(...cd(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(Zi,"evaluateArkRuleSensors");function Ji(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=>Et(c,o.appliesTo)))continue;let{severity:a,failsStrict:l}=Xi(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=>Et(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(Ji,"collectEmptyAppliesToFindings");var ji=64;function dd(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(dd,"stripTrailingDots");function ud(e){let t=e.trim(),n=t.length>ji?t.slice(0,ji):t;return dd(n)}i(ud,"normalizeIntentPrefix");function pd(e){let t=e.toLowerCase();return t.includes("domain")||t.includes("entity")||t.includes("aggregate")||t.includes("model")}i(pd,"layerNameLooksDomain");function fd(e){return e.some(t=>{let n=ud(t);return n==="Domain"||n.startsWith("Domain.")})}i(fd,"ownsDomainIntent");function gd(e,t=[]){return pd(e)||fd(t)}i(gd,"isDomainRoleLayerName");function Qi(e){if(e.arkRulesActive!==!0)return[];let t=(e.layers??[]).filter(c=>gd(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)&&!Yi(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(Qi,"collectEmptyInvariantCatalogFindings");var Bi=/\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)/,Wi=/\bfrom\s+['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)(?:\.[cm]?[jt]sx?)?['"]|require\(\s*['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)/,md=/\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 yd(e){return e==="PersistenceAdapters"}i(yd,"isPersistenceDriverLayer");function hd(e,t){if(Bi.test(e)||Wi.test(e))return!0;if(!t)return!1;for(let n of t){if(yd(n.layer))return!0;let r=n.specifier;if(!r)continue;let o=`from '${r}'`;if(Bi.test(o)||Wi.test(o))return!0}return!1}i(hd,"sourceImportsPersistenceDriver");var Rd=/\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*=)/,Ad=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,kd=/\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*=/,Id=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function bd(e,t,n){if(!t)return null;let r=hd(t,n),o=r&&md.test(t);if(t.length<40)return o?{persistenceWrite:!0}:null;let s=t.match(new RegExp(kd.source,"g"))??[],a=t.match(new RegExp(Id.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=Rd.test(t)||Ad.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(bd,"deriveArkRuleFileHints");function ea(e,t){let n={};for(let[r,o]of Object.entries(e)){let s=r.replace(/\\/g,"/"),a=bd(r,o,t?.[s]);a&&(n[s]=a)}return n}i(ea,"buildArkRuleFileHints");function vd(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(vd,"normalizeExtraMergeTeethClassification");function br(e){let t=vd(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(br,"extraMergeTeethAllowed");function ta(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(ta,"classifyResolvedLayerCoverage");var Ed=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"];var qm=new Set(Ed);function na(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")}i(na,"isArkRunKernelModuleSpecifier");var Sd=["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"],Ho=new Set(Sd);function ra(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(Ho.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(Ho.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:Ho.has(e.slice(0,r))}i(ra,"isArkRunTransportBypassSpecifier");var wd=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],oy=new Set(wd);var oa={"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 aa(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(aa,"isDomainRoleLayer");function xd(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}i(xd,"compareFindings");function Se(e,t,n,r,o,s,a){let l=e.mode==="enforced"&&a;return{ruleId:oa[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:oa[t],fromLayer:s?.fromLayer,target:s?.target})}}i(Se,"finding");function Od(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(Od,"bagForFile");function sa(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}i(sa,"emitKinds");function ia(e){return e==="subscribe"||e==="register-handler"}i(ia,"handleKinds");function Pd(e){return e==="resolve"||e==="resolve-singleton"}i(Pd,"dependKinds");function _d(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 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(Se(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(Se(e,"arkrun-missing-root",c.file,1,`ArkRun kernel root ${JSON.stringify(a)} has no createArkKernel / createStrictArkKernel factory.`,{target:a},n))}return r}i(_d,"evaluateMissingRoot");function Td(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||!na(c))continue;let u=r(l.from);u&&aa(u,s.get(u)??[])&&a.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 a}i(Td,"evaluateKernelInDomain");function Nd(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)||aa(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}i(Nd,"evaluateDirectNew");function Dd(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(!sa(c.kind)&&!ia(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=Od(n,c.file);if(sa(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(ia(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:a}}i(Dd,"evaluateUndeclared");function Ld(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||!ra(l))continue;let c=n(a.from);!c||!o.has(c)||s.push(Se(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(Ld,"evaluateTransportBypass");function la(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=br(e.classification),r=Dd(t,e.kernelCalls,e.declarations,e.layerForFile,n),o=[..._d(t,e.compositionRootHits,n),...Td(t,e.layers,e.dependencies,e.layerForFile,n),...Nd(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...Ld(t,e.dependencies,e.layerForFile,n)].sort(xd),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(la,"evaluateArkRunSensors");function ca(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}i(ca,"isArkOrderModuleSpecifier");var da=new Map;function ua(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(ua,"escapeAppliesToLiteral");function Fd(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(Fd,"normalizeAppliesToGlob");function $d(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($d,"appliesToBracesBalanced");function Md(e){let t=da.get(e);if(t)return t;let n=Fd(e),r=$d(n),o="",s=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(o+=ua(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+=ua(c)}let a=new RegExp(`^${o}$`);return da.set(e,a),a}i(Md,"globToRegExp");var pa={"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 Hd(e,t){return!t||t.length===0?!0:t.some(n=>Md(n).test(e))}i(Hd,"matchesArkOrderAppliesTo");function Kd(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(Kd,"isDomainRoleLayer");function Le(e,t,n,r,o,s,a){let l=e.mode==="enforced"&&a;return{ruleId:pa[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:pa[t],fromLayer:s?.fromLayer,target:s?.target})}}i(Le,"finding");function fa(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let n=br(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||!ca(u))continue;let f=e.layerForFile(c.from);f&&Kd(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 a=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 a.length===0?[]:e.xiFieldWrites??[]){let u=e.layerForFile(c.file);!u||!l.has(u)||Hd(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:[]}}i(fa,"evaluateArkOrderSensors");function J(e,t,n={}){return{ruleId:e,message:t,...n}}i(J,"configWarning");function En(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=ke(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(!ke(k).test(d))continue;let v=eo(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 xs(n))s.push(J("CONFIG_SLICE_IDENTITY_COLLISION",d.message,{paths:[...d.paths],fromLayer:d.from,toLayer:d.to,failsStrict:!1}));let g=ni(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:ri(d)}))}return s}i(En,"collectAnalysisConfigWarnings");function ga(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:Ui({sensor:e.sensor,code:e.code})}:{},...r||o?{freezable:!1}:{},nextAction:t}}i(ga,"toArkRuleEngineViolation");function Gd(e){let t=e.arkRules;return!!(t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0)}i(Gd,"arkRulesMapIsOn");function ma(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(ma,"arkRuleFindingNextAction");function Ud(e,t){return t.some(n=>{try{return ke(n).test(e)}catch{return!1}})}i(Ud,"matchesAny");function Vd(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")&&!Ud(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(Vd,"evaluateSafety");function jd(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}i(jd,"ambientForbiddenGlobal");function ya(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return Eo(e,n.length>0?n:vo.map(r=>({name:r.layer,prefixes:r.prefixes})))}i(ya,"intentLayer");function Bd(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||!jd(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"&&fn(s.symbol,c))){if(s.source==="import-based"){let f=Te(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}}Rt(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 gn({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=ya(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=ya(s.intent,e.contract);if(!l)continue;let c=Ze(e.contract.config.rules,a,l,{fromPath:s.file,layers:e.contract.config.layers});if(!c)continue;let u=c.rule.peerIsolation?pt(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(Bd,"contentViolations");function Wd(e){let{facts:t}=e,n=bt(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,te)=>{let Gt=`${R.code}\0${R.file??""}\0${R.message}`,Ut=`${te.code}\0${te.file??""}\0${te.message}`;return Gt<Ut?-1:Gt>Ut?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 te=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,...te?{toLayer:te}:{}}:{},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=En({config:e.contract.config,rules:e.contract.config.rules,files:a.map(R=>R.path)}),f=Vd(e,t),y=e.contract.arkRules??An(),p=a.map(R=>R.path),d={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?ea(e.coverageInputs.fileContents):{},...e.fileHints??{}},m=i(R=>l.get(R)??de(R,e.contract.config.layers),"resolveLayer"),E=[...Zi({arkRules:y,classShapes:e.contract.classShapes??t.classShapes??[],files:p,layerForFile:m,fileHints:d}),...Ji(y,p),...Qi({arkRulesActive:Gd(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=Ti({hasEnforcedInvariant:No(y.invariants),coverage:e.contract.config.coverage,...e.coverageRootsPresent===!1?{declaredPathPresent:!1}:{}}),v=k.length>0?[]:_i({adopted:e.adopted===!0,hasDomainInvariants:To(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=>ga(R,ma(R,!1))),b=E.filter(R=>!R.failsStrict).map(R=>({...ga(R,ma(R,!0)),failsStrict:!1})),T=S?Oi({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},Ve=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.`})),ye=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).`})),we=ta(a),D=la({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:we}),q=e.contract.config.arkRun?.mode,Y=D.findings.filter(()=>q==="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}:{}})),he=D.findings.filter(()=>q!=="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})),Ce=fa({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:we}),Kt=e.contract.config.arkOrder?.mode,Wn=Ce.findings.filter(()=>Kt==="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}:{}})),us=Ce.findings.filter(()=>Kt!=="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,...Ce.completenessReasons],x=st({config:e.contract.config,rules:e.contract.config.rules,files:a.filter(R=>R.layer).map(R=>R.path),contentViolations:[...Bd(e,t,l),...N,...C,...Ve,...Y,...Wn],edges:c,warnings:[...u,...f.warnings,...b,...ye,...he,...us],safety:f.report}),h=o==="complete"&&w.length>0?"partial":o,A=h==="complete"?s:[...s,...w].sort((R,te)=>{let Gt=`${R.code}\0${R.file??""}\0${R.message}`,Ut=`${te.code}\0${te.file??""}\0${te.message}`;return Gt<Ut?-1:Gt>Ut?1:0}),L=x.violations.filter(R=>R.failsStrict!==!1),W=h==="complete"&&L.length===0,xe=W&&x.warnings.every(R=>R.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:h,completenessReasons:A,valid:W,strictValid:xe,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(Wd,"analyzeCanonicalResolvedProject");function St(e){return Wd({contract:e.contract,facts:Ee(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints,adopted:e.adopted,invariantTestsPathPresent:e.invariantTestsPathPresent,coverageRootsPresent:e.coverageRootsPresent})}i(St,"analyzeResolvedProject");function ha(e){return z($(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}i(ha,"analysisTreeHash");function Ko(e){let t=vt(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=ot(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=vn({...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=st({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=ot(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?rt({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:ha(t.ir.files),candidateTreeHash:ha(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(Ko,"preflightChange");function zd(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(zd,"canonicalChangePath");function qd(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(qd,"identityViolations");function Yd(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(Yd,"preparedChange");function Go(e){let t=Ee(e.baseFacts),n=Ee(e.candidateFacts),r=St({contract:e.contract,facts:t}),o=St({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=qd(t,n),c=new Map,u=[];for(let g of e.changes){let d=zd(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=z(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(Yd(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&&$(d)===$(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?rt({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(Go,"preflightResolvedChange");var vr="docs/diagnostics.md",Ra="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 Sn=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.")]),Uo=new Map(Sn.map(e=>[e.ruleId,e])),Aa=Object.freeze(Sn.map(e=>e.ruleId));function ka(e){return typeof e=="string"&&e.length>0&&Uo.has(e)}i(ka,"isKnownDiagnosticCode");function Ia(e){return typeof e!="string"||e.length===0?!1:Uo.has(e)?!0:e.startsWith("ARKRULE_")}i(Ia,"isCataloguedOrArkRuleFamily");function wn(e){if(!(typeof e!="string"||e.length===0))return Uo.get(e)}i(wn,"getDiagnosticCatalogEntry");function Vo(e){return`#${wn(e)?.docsAnchor??e}`}i(Vo,"diagnosticDocsFragment");function ba(e){return`${vr}${Vo(e)}`}i(ba,"diagnosticDocsPath");function va(){return{schemaVersion:"1.0",docsPath:vr,codes:Sn}}i(va,"serializeDiagnosticCatalog");function Ea(e){return wn(e)?.fix}i(Ea,"catalogFixForRuleId");function Sa(e){return wn(e)?.why}i(Sa,"catalogWhyForRuleId");var wa="1.1";var Ca="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 Xd(e){return typeof e.initialState=="function"?e.initialState():e.initialState}i(Xd,"initialState");var Er=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)??Xd(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 Cn(e){return new Er(e)}i(Cn,"createProjectionRegistry");var xn="1.0";function Zd(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}i(Zd,"policyId");var jo=class{constructor(t){this.data=t}data;static{i(this,"ArkManifestImpl")}toJSON(){return{...this.data}}};function On(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:Zd(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:zn,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 jo(E)}i(On,"createArkManifest");var xa=0;function Oa(e){return xa+=1,`${e}-${Date.now()}-${xa}`}i(Oa,"createWorkflowId");function Bo(e){return e instanceof Error?e.message:String(e)}i(Bo,"errorMessage");function Jd(e){return new Promise(t=>{setTimeout(t,e)})}i(Jd,"sleep");async function Qd(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(Qd,"withTimeout");var Ct=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()}},Wo=class{constructor(t,n={}){this.bus=t;this.options=n;this.store=n.store??new Ct}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??Oa(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=Bo(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 Qd(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:Bo(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:Bo(c)})}}}async audit(t,n,r){await this.options.auditTrail?.record({type:t,source:"Kernel.WorkflowEngine",subject:n.id,details:r})}};function xt(e,t){return new Wo(e,t)}i(xt,"createWorkflowEngine");function zo(e,t,n={}){let r=xt(t,n),o={name:e.name,steps:e.steps};r.register(o);let s=n.id??Oa(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(zo,"createSaga");Ot();function Ta(e){return Object.keys(e).sort()}i(Ta,"sortedKeys");function Jo(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)Jo(l[f],c[f],`${n}[${f}]`,r);return}let o=e,s=t,a=new Set([...Ta(o),...Ta(s)]);for(let l of[...a].sort())Jo(o[l],s[l],n?`${n}.${l}`:l,r)}i(Jo,"walk");function Qo(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(Qo,"shadowInformationPackage");function wr(e,t){let n=[];return Jo(e,t,"",n),{equal:n.length===0,diffs:n}}i(wr,"compareInformationPackages");function es(e){let t=[];for(let n=1;n<e.length;n+=1)t.push(wr(e[n-1],e[n]));return t}i(es,"replayInformationPackages");Nr();Kn();jn();jn();async function Bn(e,t={}){let n=Ft({host:t.host,port:t.port,nodeEnv:t.nodeEnv,processNodeEnv:process.env.NODE_ENV}),{listenArkRunInspector:r}=await Promise.resolve().then(()=>(Va(),Ua));return r(e,{bind:n,sseIntervalMs:t.sseIntervalMs})}i(Bn,"startArkRunInspector");Nr();jn();Ot();Kn();Ot();var $u=new Set(["singleton","transient"]);function ja(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(ja,"cloneComponent");function Mu(e){if(e===void 0)return"singleton";if(typeof e=="string"&&$u.has(e))return e;throw new Error('ArkRun component lifetime must be "singleton" or "transient".')}i(Mu,"closedLifetime");function Ba(){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=Mu(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}),ja(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=>ja(a.component))}}}i(Ba,"createComponentRegistry");Kn();function Hu(e){let t={...e.metadata??{}};if(e.source===void 0)return t;if(t.source&&t.source!==e.source)throw new Ae(e.source,t.source);return t.source=e.source,t}i(Hu,"stampMetadata");function Ku(){}i(Ku,"ignoreDetachedFailure");async function is(e,t,n,r={}){let o=Hn({transport:r.transport,ephemeral:r.ephemeral??e.defaultEphemeral,brokerBound:typeof e.broker?.send=="function"}),s=Hu(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,Ku)}return o}i(is,"sendOnArkRunTransport");var Gr=1e3,Wa=0;function Gu(){return Wa+=1,`ark-kernel-${Date.now()}-${Wa}`}i(Gu,"nextKernelInstanceId");function za(e,t){let n=e.constructor?.name;return typeof n=="string"&&n.length>0?n:t}i(za,"portConstructorId");function Ht(e={}){let t=e.strict??!0,n=e.instanceId??Gu(),r=e.profile??Qe,o=e.maxHistorySize??Gr,s=Wt(),a=on(),l=e.metadata??un(),c=e.auditTrail===void 0,u=e.auditTrail??rn({maxRecords:o}),f=e.eventContracts??tn(),y=e.eventBuffer===void 0&&e.outbox===void 0,p=e.eventBuffer??e.outbox??new _e,g=e.projections??Cn({auditTrail:u}),d=new Oe([Xt(r),...e.policies??[]]),m=i(()=>{sn(s,a,{requireRegisteredTargets:!0})},"syncGraph"),E=e.ephemeral??!0,S=e.broker,k=new gt({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=xt(k,{auditTrail:u}),C=nn({registry:s,eventBus:k,graph:a}),N=Ba(),b=typeof S?.send=="function",T=y?"InMemoryEventBuffer":za(p,"EventBufferStore"),Ve=c?"InMemoryAuditStore":za(u,"AuditTrail"),ye=$t({stores:[He(T,"outbox"),He(Ve,"audit"),He("InMemoryWorkflowStore","workflow")]}),we={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 q=k.createPublisher(D);return{source:q.source,publish:q.publish,send(Y,he,Ce={}){return is({eventBus:k,broker:S,defaultEphemeral:E},Y,he,{...Ce,source:q.source})}}},send(D,q,Y={}){return is({eventBus:k,broker:S,defaultEphemeral:E},D,q,Y)},register(D){return N.register(D)},resolve(D){return N.resolve(D)},resolveSingleton(D){return N.resolveSingleton(D)},getDependencyInformationPackage(){return fe({kernelInstanceId:n,components:N.snapshotComponents()})},requestGraph(D){return Mn({kernelInstanceId:n,components:N.snapshotComponents()},D)},getInspectorSnapshot(D){return Vn({kernelInstanceId:n,host:D?.host,port:D?.port,package:{kernelInstanceId:n,components:N.snapshotComponents()},observability:C.report(),ephemeralDefault:E,brokerBound:b,hardening:ye})},startInspector(D){return Bn({getInspectorSnapshot:i(Y=>we.getInspectorSnapshot(Y),"getInspectorSnapshot"),requestGraph:i(Y=>we.requestGraph(Y),"requestGraph"),async listInspectorOutbox(){let[Y,he]=await Promise.all([p.list("pending"),p.list("failed")]);return Ke([...Y,...he],{sampleLimit:re})},async listInspectorWorkflows(){return Ge(await v.list(),{sampleLimit:re})}},D)},syncGraph:m,manifest(){return m(),On({registry:s,policyEngine:d,metadata:l,graph:a,profile:r,projections:g,eventContracts:f,observability:C})}};return we}i(Ht,"createArkKernel");function Ur(e={}){return Ht({...e,strict:!0,strictEventContracts:e.strictEventContracts??!0,requireKnownSource:e.requireKnownSource??!0,enforceObservedLayerFlow:e.enforceObservedLayerFlow??"hard"})}i(Ur,"createStrictArkKernel");function as(e,t={}){let{profileName:n,...r}=t;return{...r,profile:dn(e,{name:n})}}i(as,"createOptionsFromConfig");function ls(e,t={}){return Ht(as(e,t))}i(ls,"createArkKernelFromConfig");function cs(e,t={}){return Ur(as(e,t))}i(cs,"createStrictArkKernelFromConfig");function ds(e,t={}){return Vr(as(e,t))}i(ds,"createLenientArkKernelFromConfig");function Vr(e={}){return Ht({...e,strict:!1,strictEventContracts:e.strictEventContracts??!1,enforceObservedLayerFlow:e.enforceObservedLayerFlow??"off"})}i(Vr,"createLenientArkKernel");0&&(module.exports={ANALYSIS_IR_SCHEMA_VERSION,ARK_ANALYSIS_RESULT_SCHEMA,ARK_ANALYSIS_RESULT_SCHEMA_VERSION,ARK_DESIGN_DELTA_SCHEMA_VERSION,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION,ARK_RUN_COMPONENT_LIFETIMES,ARK_RUN_EPHEMERAL_DEFAULT,ARK_RUN_GRAPH_DEFAULT_SLICE,ARK_RUN_GRAPH_NODE_KINDS,ARK_RUN_GRAPH_PROCESS_EDGE_KINDS,ARK_RUN_GRAPH_SCHEMA_VERSION,ARK_RUN_GRAPH_SLICES,ARK_RUN_GRAPH_TECHNICAL_EDGE_KINDS,ARK_RUN_INFORMATION_PACKAGE_SCHEMA_VERSION,ARK_RUN_INSPECTOR_DEFAULT_HOST,ARK_RUN_INSPECTOR_DEFAULT_PORT,ARK_RUN_INSPECTOR_EVENTS_PATH,ARK_RUN_INSPECTOR_GRAPH_PATH,ARK_RUN_INSPECTOR_MONITOR_SAMPLE_LIMIT,ARK_RUN_INSPECTOR_OUTBOX_PATH,ARK_RUN_INSPECTOR_SCHEMA_VERSION,ARK_RUN_INSPECTOR_SNAPSHOT_PATH,ARK_RUN_INSPECTOR_SSE_EVENT,ARK_RUN_INSPECTOR_TRANSPORT_FALLBACK,ARK_RUN_INSPECTOR_WORKFLOWS_PATH,ARK_RUN_TRANSPORT_KINDS,ArkRunInspectorBindError,ArkRunInspectorProductionError,DEFAULT_MAX_HISTORY_SIZE,DIAGNOSTIC_CATALOG,DIAGNOSTIC_CATALOG_SCHEMA_VERSION,DIAGNOSTIC_DOCS_RELATIVE_PATH,DIAGNOSTIC_RULE_IDS,EventContractRegistryImpl,EventContractViolationError,InMemoryAuditStore,InMemoryEventBuffer,InMemoryOutboxStore,InMemoryReadModelStore,InMemoryWorkflowStore,IntentRegistry,InvalidArkRunGraphQueryError,InvalidArkRunSendOptionError,InvalidIntentNameError,LayerPolicyContextError,MANIFEST_SCHEMA_VERSION,ObservedLayerFlowViolationError,POLICY_DELTA_SCHEMA_VERSION,PolicyEngine,PolicyViolationError,RESOLVED_CANDIDATE_FACTS_SCHEMA,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,SourceMetadataOverrideError,UnknownEventSourceError,UnregisteredIntentError,analyzeArchitectureConvergence,analyzeChange,analyzePolicyDelta,analyzeProject,analyzeResolvedProject,appendDecisionTape,architecturalPolicies,arkRunGraphQueryFromSearchParams,arkRunInspectorUrl,buildArkRunInspectorHardening,buildArkRunInspectorOutboxMonitor,buildArkRunInspectorSnapshot,buildArkRunInspectorWorkflowsMonitor,buildDependencyInformationPackage,buildPublishPolicyContext,catalogFixForRuleId,catalogWhyForRuleId,checkAdapterGovernance,checkContract,classifyArkPolicyDelta,classifyArkRunInspectorStoreDurability,closeArkRunGraphQuery,closedArkRunEphemeral,closedArkRunTransportKind,collectAnalysisConfigWarnings,collectForbiddenCapabilityUses,compareInformationPackages,createAICodeGate,createAdapter,createAdapterResult,createArchitectureProfile,createArchitectureProfileFromArkConfig,createArkKernel,createArkKernelFromConfig,createArkManifest,createArkTestHarness,createAuditTrail,createDependencyGraph,createElevenLayerArkConfig,createEventBus,createEventContractRegistry,createIntentRegistry,createLenientArkKernel,createLenientArkKernelFromConfig,createMetadataRegistry,createObservabilityReporter,createProjectionRegistry,createResolvedCandidateFacts,createSaga,createStrictArkKernel,createStrictArkKernelFromConfig,createWorkflowEngine,defaultIntentRegistry,defineArchitectureProfilePolicy,defineIntent,defineLayerPolicy,definePolicy,definePort,definePublishPolicy,detectArchitectureCycles,deterministicHash,diagnosticDocsFragment,diagnosticDocsPath,elevenLayerProfile,evaluateArchitectureGraph,explainViolation,extractSemanticDependencies,formatArkRunGraphMermaid,formatArkRunInspectorSseEvent,getDiagnosticCatalogEntry,isArkRunInspectorLoopbackHost,isArkRunInspectorProductionEnv,isCataloguedOrArkRuleFamily,isKnownDiagnosticCode,isLayerPolicy,loadContract,loadResolvedCandidateFacts,policyDeltaAcknowledgementMatches,preflightChange,preflightResolvedChange,replayInformationPackages,requestArkRunGraph,resolveArkRunInspectorBind,resolveArkRunSendPlan,resolvedFactsEvidenceRequirementsHash,serializeDiagnosticCatalog,shadowInformationPackage,stableSerialize,startArkRunInspector,syncRegistryToGraph,toAdapterDiagnostic,unavailableArkRunInspectorOutboxMonitor,unavailableArkRunInspectorWorkflowsMonitor,validateIntentName,version});
|
|
28
|
+
`,t);return e.slice(n,r===-1?e.length:r)}a(Ld,"lineAt");function Dd(e){let t=e.trim();return/^import\b/.test(t)||/^export\s+/.test(t)&&/\bfrom\b/.test(t)?!0:/\brequire\s*\(/.test(t)}a(Dd,"isImportLine");function Xi(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(Dd(Ld(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(Xi,"mentionContext");function Qi(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(Qi,"symbolNeedle");function Fd(e){return Qi(e.coverage?.symbol)?.name??e.id}a(Fd,"declaredLabel");function Zi(e){return Object.keys(e).sort((t,n)=>t<n?-1:t>n?1:0)}a(Zi,"sortedContentFiles");function $d(e,t,n=!0){let r=t.testFiles??[],o=new Set(r.map(g=>Ot(g))),s=(t.coverageRoots??[]).filter(g=>typeof g=="string"&&g.length>0),i=e.coverage?.test!==!1&&n,l=Qi(e.coverage?.symbol??void 0),c,u;if(i){for(let g of r){let d=t.fileContents[g];if(!d)continue;let m=Td(d,e.id);if(m!==void 0){if(s.length===0||Ji(g,s)){c={file:g,title:m};break}u??={file:g,title:m}}}c??=u}let f;if(l)for(let g of Zi(t.fileContents)){if(o.has(Ot(g)))continue;let d=t.fileContents[g];if(!d||l.className&&!d.includes(l.className))continue;let m=Nd(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=Xi(d,e.id,!0);if(m){y={file:g,context:m};break}}if(!y&&l)for(let g of Zi(t.fileContents)){if(o.has(Ot(g)))continue;let d=t.fileContents[g];if(!d)continue;let m=Xi(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&&Md(t.fileContents,o,l.name,p.file)&&(p={kind:"declaration-miss",symbol:l.name}),{best:p,...c?{testTitle:c}:{},...f?{declaration:f}:{}}}a($d,"rankCoverage");function Md(e,t,n,r){let o=new RegExp(`(?:^|[^A-Za-z0-9_$])${zo(n)}(?=$|[^A-Za-z0-9_$])`),s=Ot(r);for(let i of Object.keys(e)){if(t.has(Ot(i))||Ot(i)===s)continue;let l=e[i];if(l&&o.test(qo(l,!0)))return!0}return!1}a(Md,"symbolInCodeElsewhere");function Hd(e){switch(e.kind){case"test-title":case"declaration":return!0;case"mention-only":case"declaration-miss":case"none":return!1}}a(Hd,"countsAsCoverage");function Kd(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(Kd,"mentionWhere");function Gd(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} ${Fd(e)}\` in ${t.file}`;case"mention-only":return`${e.id} appears only in ${Kd(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(Gd,"describeCoverage");function ea(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=Yi(s),l=Yi(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=$d(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=Hd(E),S,N;v&&k.testTitle&&(S=k.testTitle.file,f&&(N=!Ji(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,X=r&&m&&!L;if(p.push({invariantId:d.id,layer:d.provenance.layer,sourceFile:d.provenance.sourceFile,mode:d.mode,covered:T&&!X,evidence:O,partial:X,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||X){let Z=d.mode==="enforced"&&!X,Ie=r||n.length===0?"never-had-tests":"tests-disappeared";g.push({ruleId:"INVARIANT_UNCOVERED",message:(X?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}: ${Gd(d,E)} (${Ie==="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.`)+(X&&o?l:i),file:d.provenance.sourceFile,line:1,arkruleId:d.id,arkruleSource:d.provenance.sourceFile,fromLayer:d.provenance.layer,severity:Z?"error":"warning",failsStrict:Z,kind:Ie})}}return{coverage:p,violations:g,partial:p.some(d=>d.partial)}}a(ea,"evaluateInvariantCoverage");function ta(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(ta,"canPromoteInvariant");function Wo(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(Wo,"nonEmptyPathStrings");function Ud(e){return!e||typeof e!="object"?[]:[...Wo(e.testGlobs),...Wo(e.coverageRoots)]}a(Ud,"configuredInvariantTestsPaths");function Vd(e){return Ud(e).length>0}a(Vd,"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 na(e){let t=e.hasDomainInvariants===!0||e.hasDomainInvariants!==!1&&Yo(e.invariants);return e.adopted!==!0||!t?[]:Vd(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:xd,message:Od,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]}a(na,"collectMissingInvariantTestsPathFindings");function jd(e){return!e||typeof e!="object"?[]:Wo(e.coverageRoots)}a(jd,"configuredCoverageRoots");function Bd(e){return jd(e).length>0}a(Bd,"hasConfiguredCoverageRoots");function Xo(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.mode==="enforced")}a(Xo,"catalogHasEnforcedInvariant");function ra(e){return e.hasEnforcedInvariant===!0||e.hasEnforcedInvariant!==!1&&Xo(e.invariants)?Bd(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:Pd,message:_d,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]:[]}a(ra,"collectMissingCoverageRootsFindings");var Or="1.0",Wd="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 ${Wd}`: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 Tn(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(Tn,"compareBoolean");function Cr(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(Cr,"keyed");function zd(e,t,n){let r=Cr(t,s=>s.name),o=Cr(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=Sr(i),f=Sr(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)}),Tn(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."),Tn(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(zd,"compareLayers");function qd(e,t,n){let r=a(i=>`${i.from}->${i.to}`,"keyOf"),o=Cr(t,r),s=Cr(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(es(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."),es(e,`${u}.allowedCrossSlice`,"cross-slice-allowance",K((l.allowedCrossSlice??[]).map(Qo)),K((c.allowedCrossSlice??[]).map(Qo)),"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=ua(m)>ua(d);C(e,{kind:"shared-imports-slice",path:`${u}.sharedImportsSlice`,classification:b?"strengthening":"weakening",message:au(d,m),before:d,after:m})}Xd(e,u,l,c)}}}a(qd,"compareRules");function oa(e){let t=e.childSlices;return t?JSON.stringify([K(t.sliceFolders??[]),t.sliceIdentity??"path",K(t.commonFolders??[])]):""}a(oa,"childSliceFoldersKey");function Yd(e){return K((e??[]).map(t=>xr(t.trim().replace(/\\/g,"/")).toLowerCase()))}a(Yd,"enforceKeys");function sa(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:Yd(t.enforce)}}a(sa,"childSliceSiblingPolicy");function Xd(e,t,n,r){let o=sa(n),s=sa(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(oa(n)!==oa(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"&&Zd(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}),tu(e,t,n,r),eu(e,t,n,r)}a(Xd,"compareChildSlices");function Zd(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(Zd,"compareSiblingEnforceList");function Qo(e){return JSON.stringify([e.from,e.to])}a(Qo,"crossSliceKey");function ia(e){return K((e.childSlices?.allowedCrossSlice??[]).map(Qo))}a(ia,"childCrossSliceKeys");function Pt(e){return xr(e.trim().replace(/\\/g,"/")).toLowerCase().split("/").filter(t=>t.length>0)}a(Pt,"allowanceSegments");function aa(e,t){let n=Pt(e),r=Pt(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(aa,"patternWidens");function Jd(e,t){let n=JSON.parse(e),r=JSON.parse(t),o=Pt(n[0]).join("/")===Pt(r[0]).join("/"),s=Pt(n[1]).join("/")===Pt(r[1]).join("/"),i=aa(n[0],r[0]),l=aa(n[1],r[1]);return!(o||i)||!(s||l)?!1:i||l}a(Jd,"allowanceWidens");function Qd(e){return JSON.stringify([xr(e.from.trim().replace(/\\/g,"/")).toLowerCase(),xr(e.to.trim().replace(/\\/g,"/")).toLowerCase()])}a(Qd,"aliasEntryKey");function la(e){return K((e.childSlices?.sliceAliases??[]).map(Qd))}a(la,"sliceAliasKeys");function eu(e,t,n,r){let o=la(n),s=la(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(eu,"compareSliceAliases");function tu(e,t,n,r){let o=ia(n),s=ia(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=>Jd(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}es(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(tu,"compareChildCrossSliceAllowances");function es(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(es,"compareDeclaredExceptions");function nu(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"])Tn(e,`$.safety.${s}`,r[s]===!0,o[s]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}a(nu,"compareSafety");function Zo(e){return e.mode==="enforced"?"enforced":"advisory"}a(Zo,"arkRunMode");function Jo(e){return e.mode==="enforced"?"enforced":"advisory"}a(Jo,"arkOrderMode");function ru(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 (${Jo(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=Jo(r),l=Jo(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(ru,"compareArkOrder");function ou(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 (${Zo(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=Zo(r),l=Zo(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."}),Tn(e,`${s}.requireDeclarations`,r.requireDeclarations!==!1,o.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}a(ou,"compareArkRun");function su(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(su,"overallClassification");function ca(e,t){return`${e}::${t}`}a(ca,"ruleKey");function da(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(ca(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(ca(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}a(da,"indexEffectiveRules");function iu(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=da(r),y=da(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=ta(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(iu,"compareArkRules");function Pr(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."}),Tn(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}),zd(r,e.layers,t.layers),qd(r,e.rules,t.rules),nu(r,e,t),iu(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),ou(r,e,t),ru(r,e,t),r.sort((l,c)=>l.path.localeCompare(c.path)||l.id.localeCompare(c.id)),{schemaVersion:Or,classification:su(r),findings:r}}a(Pr,"classifyArkPolicyDelta");function _r(e,t){if(!e||e.schemaVersion!==Or||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(_r,"policyDeltaAcknowledgementMatches");function xr(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}a(xr,"trimTrailingSlashes");function ua(e){return e==="deny"?2:e==="deny-cross-parent"?1:0}a(ua,"sharedImportsSliceRank");function au(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(au,"sharedImportsSliceMessage");function lt(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(lt,"normalizePath");function pa(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}a(pa,"isIdentifierStart");function Tr(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}a(Tr,"isIdentifierCharacter");function le(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}a(le,"skipWhitespace");function Nn(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(Nn,"readString");function ue(e,t,n){return e.startsWith(t,n)&&!Tr(e[n-1])&&!Tr(e[n+t.length])}a(ue,"isWordAt");function fa(e,t){let n=le(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=le(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!ue(e,"type",n))return!1;let o=le(e,n+4);if(o>=e.length||e[o]===","||e[o]==="}"||ue(e,"as",o)||!pa(e[o]))return!1;for(n=o;n<e.length&&Tr(e[n]);)n+=1;if(n=le(e,n),ue(e,"as",n)){if(n=le(e,n+2),!pa(e[n]))return!1;for(;n<e.length&&Tr(e[n]);)n+=1}r=!0}return!1}a(fa,"bracedNamedBindingsAreTypeOnly");function lu(e,t){if(t=le(e,t+6),e[t]==="(")return Nn(e,le(e,t+1));let n=!1;if(ue(e,"type",t)){let o=le(e,t+4);e[o]!==","&&!ue(e,"from",o)&&(n=!0)}else fa(e,t)&&(n=!0);let r=ga(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}a(lu,"specifierAfterImport");function cu(e,t){t=t+6;let n=le(e,t),r=!1;if(ue(e,"type",n)){let s=le(e,n+4);(e[s]==="{"||e[s]==="*")&&(r=!0)}else fa(e,n)&&(r=!0);let o=ga(e,t,!1);return o&&r?{...o,typeOnly:!0}:o}a(cu,"specifierAfterExport");function ga(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(ue(e,"from",t))return Nn(e,le(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return Nn(e,t);if(t>0&&(ue(e,"import",t)||ue(e,"export",t)))return}}a(ga,"specifierInStaticStatement");function du(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(du,"skipTemplateLiteral");function uu(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=le(e,t+7);if(e[r]!=="(")return;r=le(e,r+1);let o=Nn(e,r);return o?{...o,requireCall:!0}:void 0}a(uu,"specifierAfterRequire");function pu(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=du(e,n);continue}if(r==="'"||r==='"'){let s=Nn(e,n);s&&(n=s.offset+s.excerpt.length-1);continue}let o=r==="i"&&ue(e,"import",n)?lu(e,n):r==="e"&&ue(e,"export",n)?cu(e,n):r==="r"&&ue(e,"require",n)?uu(e,n):void 0;o&&(t.push(o),n=o.offset+o.excerpt.length-1)}return t}a(pu,"moduleSpecifiers");function ma(e,t){let n=[],r=[];for(let o of pu(e.content)){let s=o.value;if(!s.startsWith(".")){if(o.typeOnly)continue;let u=vn(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=fu(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(ma,"moduleFactsFor");function fu(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(fu,"resolveSpecifier");function ya(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let o=fr(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(ya,"violationsFor");var gu={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 mu(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}a(mu,"hasActiveArkRules");function yu(e,t){return mu(e,t)?Y($(qi({config:e,arkRules:t,warnings:[]}))):Y($(Bo(e)))}a(yu,"policyHashFor");function Ln(e,t,n){let r=typeof e=="string"?Ti(e,t):Eo(e,t),o=n?.arkRules??_n();return{...r,arkRules:o,policyHash:yu(r.config,o)}}a(Ln,"loadContract");function ts(e){let t=Ln(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=Ln(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=Pr(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&&_r(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(ts,"analyzePolicyDelta");function _t(e){let t=e.files.map(y=>{let p=lt(y.path);return{path:p,content:y.content,contentHash:Y(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=ma(y,n);r.push(...p.edges),o.push(...p.capabilityUses)}let s=ya(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(vt(y))]));for(let y of o){let p=n.get(y.file)?.layer;if(!p)continue;let g=i.get(p),d=De(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"?[]:[{...gu}],f={schemaVersion:wr,policyHash:e.contract.policyHash,compilerOptionsHash:Y($(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(_t,"analyzeProject");function Dn(e){let t=new Map(e.files.map(n=>[lt(n.path),n]));for(let n of e.changes){let r=lt(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return _t({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}a(Dn,"analyzeChange");function ns(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(ns,"explainViolation");function Nr(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(Nr,"detectArchitectureCycles");function ct(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=Ne(e.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:e.config.layers});if(!i){let p=ei(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?ht({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}:{},...Qe(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(...Au(e));let o=String(e.config.cyclePolicy??"strict").toLowerCase();if(o!=="off"){let s=Nr(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(ct,"evaluateArchitectureGraph");var hu="CROSS_PARENT_VIA_SHARED",Ru="ark-check and CI report this path. The write hook and ESLint see one edge at a time and do not block it.";function ha(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(ha,"denyingCrossParentRule");function rs(e,t,n,r){let o=yt(n,e,ti(e,t,r)).universeId;return o?{kind:"slice",id:o}:cn(n,e.sharedRoots)?{kind:"shared"}:{kind:"other"}}a(rs,"placeFile");function Au(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=ku(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=ha(t,s.fromLayer,s.toLayer);if(!i)continue;let l=rs(i,s.fromLayer,s.from,e.config.layers),c=rs(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=ha(t,p.fromLayer,p.toLayer);if(!g)continue;let d=rs(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=dn(s.fromSlice),l=dn(s.toSlice);return{ruleId:"LAYER_IMPORT_VIOLATION",reasonId:hu,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}. ${Ru}`}})}a(Au,"crossParentViaSharedViolations");function ku(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(ku,"valueHop");function Ra(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(Ra,"structureFreezeTarget");var Iu=["no-anemic-model"],Sa=["ensureInvariants","assertInvariants","validate","publish","emit","raise","record"],uh=new RegExp(`\\b(${Sa.join("|")})\\b`),va="(?:_?pendingEvents|domainEvents|uncommittedEvents|recordedEvents)",ph=new RegExp(`\\bthis\\.${va}\\.push\\s*\\(`),fh=new RegExp(`^this\\.${va}\\s*=\\s*\\[\\s*\\]`);var bu="truncatedUntil";function Su(){return`${Sa.join(", ")}, or events-array .push(`}a(Su,"expectedDomainInvariantWordsPhrase");function os(e){let t=Object.getOwnPropertyDescriptor(e,bu)?.value;return typeof t=="number"?t:void 0}a(os,"shapeTruncatedUntil");function vu(e){let t=os(e);return t==null?"":` shape analysed until character ${t}`}a(vu,"shapeTruncationSuffix");function Aa(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(Aa,"escapeGlobLiteral");function Eu(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+=Aa(t[r+1]),r+=1):o==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":o==="?"?n+="[^/]":n+=Aa(o)}return new RegExp(`^${n}$`)}a(Eu,"globToRegExp");function Tt(e,t){return!t||t.length===0?!0:t.some(n=>Eu(n).test(e))}a(Tt,"matchesAppliesTo");function Ea(e){return Iu.includes(e)}a(Ea,"isTier2");function wa(e){return e.mode==="enforced"&&!Ea(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}a(wa,"severityFor");function $e(e,t,n,r=1){let{severity:o,failsStrict:s}=wa(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($e,"baseViolation");function Lr(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}a(Lr,"isInRuleLayer");function Dr(e,t,n){return t.filter(r=>!(!r.exported||!Tt(r.file,e.appliesTo)||!Lr(r.file,e,n)))}a(Dr,"shapesForRule");function wu(e,t,n){let r=[];for(let o of Dr(e,t,n))(o.hasPublicSetters||o.hasPublicMutableFields)&&r.push($e(e,o.file,`Exported class ${o.className} exposes public mutable state (sensor aggregate-private-state).`));return r}a(wu,"evaluateAggregatePrivateState");function Cu(e,t,n){let r=[];for(let o of Dr(e,t,n))if(o.hasPublicConstructor&&!o.hasStaticFactory){if(!(o.hasPublicMutableFields||o.hasPublicSetters||(o.mutatingMethods?.length??0)>0))continue;r.push($e(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 xu(e,t,n){let r=[],o=Su();for(let s of Dr(e,t,n)){let i=vu(s);os(s)!=null&&r.push($e(e,s.file,`Exported class ${s.className} shape analysed until character ${os(s)}; later methods may be invisible (sensor domain-event-on-mutation).`));for(let l of s.mutatingMethods)l.referencesGuardOrPublish||r.push($e(e,s.file,`Mutating method ${s.className}.${l.name} does not reference ${o} (sensor domain-event-on-mutation).${i}`))}return r}a(xu,"evaluateDomainEventOnMutation");function Ou(e,t){let n=[];for(let r of t.files)Tt(r,e.appliesTo)&&Lr(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push($e(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}a(Ou,"evaluateOrchestrationOnly");function Pu(e,t){let n=[];for(let r of t.files)Tt(r,e.appliesTo)&&Lr(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push($e(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}a(Pu,"evaluateThinAdapter");function _u(e,t){let n=[];for(let r of t.files)Tt(r,e.appliesTo)&&Lr(r,e,t.layerForFile)&&t.fileHints?.[r]?.persistenceWrite&&n.push($e(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(_u,"evaluateWritesViaAggregate");function Tu(e,t,n){let r=[];for(let o of Dr(e,t,n))if(o.dataOnly===!0){let s=$e(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(Tu,"evaluateNoAnemicModel");function Ca(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(...wu(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(...xu(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...Ou(n,e));break;case"thin-adapter":t.push(...Pu(n,e));break;case"writes-via-aggregate":t.push(..._u(n,e));break;case"no-anemic-model":t.push(...Tu(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(Ca,"evaluateArkRuleSensors");function xa(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=>Tt(c,o.appliesTo)))continue;let{severity:i,failsStrict:l}=wa(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=>Tt(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(xa,"collectEmptyAppliesToFindings");var ka=64;function Nu(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(Nu,"stripTrailingDots");function Lu(e){let t=e.trim(),n=t.length>ka?t.slice(0,ka):t;return Nu(n)}a(Lu,"normalizeIntentPrefix");function Du(e){let t=e.toLowerCase();return t.includes("domain")||t.includes("entity")||t.includes("aggregate")||t.includes("model")}a(Du,"layerNameLooksDomain");function Fu(e){return e.some(t=>{let n=Lu(t);return n==="Domain"||n.startsWith("Domain.")})}a(Fu,"ownsDomainIntent");function $u(e,t=[]){return Du(e)||Fu(t)}a($u,"isDomainRoleLayerName");function Oa(e){if(e.arkRulesActive!==!0)return[];let t=(e.layers??[]).filter(c=>$u(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)&&!Ea(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(Oa,"collectEmptyInvariantCatalogFindings");var Ia=/\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)/,ba=/\bfrom\s+['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)(?:\.[cm]?[jt]sx?)?['"]|require\(\s*['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)/,Mu=/\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 Hu(e){return e==="PersistenceAdapters"}a(Hu,"isPersistenceDriverLayer");function Ku(e,t){if(Ia.test(e)||ba.test(e))return!0;if(!t)return!1;for(let n of t){if(Hu(n.layer))return!0;let r=n.specifier;if(!r)continue;let o=`from '${r}'`;if(Ia.test(o)||ba.test(o))return!0}return!1}a(Ku,"sourceImportsPersistenceDriver");var Gu=/\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*=)/,Uu=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,Vu=/\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*=/,ju=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function Bu(e,t,n){if(!t)return null;let r=Ku(t,n),o=r&&Mu.test(t);if(t.length<40)return o?{persistenceWrite:!0}:null;let s=t.match(new RegExp(Vu.source,"g"))??[],i=t.match(new RegExp(ju.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=Gu.test(t)||Uu.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(Bu,"deriveArkRuleFileHints");function Pa(e,t){let n={};for(let[r,o]of Object.entries(e)){let s=r.replace(/\\/g,"/"),i=Bu(r,o,t?.[s]);i&&(n[s]=i)}return n}a(Pa,"buildArkRuleFileHints");function Wu(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(Wu,"normalizeExtraMergeTeethClassification");function Fr(e){let t=Wu(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(Fr,"extraMergeTeethAllowed");function _a(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(_a,"classifyResolvedLayerCoverage");var zu=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"];var Rh=new Set(zu);function Ta(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")}a(Ta,"isArkRunKernelModuleSpecifier");var qu=["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"],ss=new Set(qu);function Na(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(ss.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(ss.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:ss.has(e.slice(0,r))}a(Na,"isArkRunTransportBypassSpecifier");var Yu=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],xh=new Set(Yu);var La={"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"},Xu="ARKRUN_INTERACTION_NAME_INCOMPLETE";function $a(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($a,"isDomainRoleLayer");function Zu(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}a(Zu,"compareFindings");function xe(e,t,n,r,o,s,i){let l=e.mode==="enforced"&&i;return{ruleId:La[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:La[t],fromLayer:s?.fromLayer,target:s?.target})}}a(xe,"finding");function Ju(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(Ju,"bagForFile");function Da(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}a(Da,"emitKinds");function Fa(e){return e==="subscribe"||e==="register-handler"}a(Fa,"handleKinds");function Qu(e){return e==="resolve"||e==="resolve-singleton"}a(Qu,"dependKinds");function ep(e,t,n){let r=[],o=e.kernelRoots??e.compositionRoots;if(o.length===0)return r.push(xe(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(xe(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(xe(e,"arkrun-missing-root",c.file,1,`ArkRun kernel root ${JSON.stringify(i)} has no createArkKernel / createStrictArkKernel factory.`,{target:i},n))}return r}a(ep,"evaluateMissingRoot");function tp(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||!Ta(c))continue;let u=r(l.from);u&&$a(u,s.get(u)??[])&&i.push(xe(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(tp,"evaluateKernelInDomain");function np(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)||$a(p,l.get(p)??[])||u.push(xe(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(np,"evaluateDirectNew");function rp(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(!Da(c.kind)&&!Fa(c.kind)&&!Qu(c.kind))continue;let u=r(c.file);if(!u||!l.has(u))continue;if(!c.nameLiteral){e.mode==="enforced"&&i.push({code:Xu,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=Ju(n,c.file);if(Da(c.kind)){if(f.raises.has(c.nameLiteral)||f.sends.has(c.nameLiteral))continue;s.push(xe(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(Fa(c.kind)){if(f.reactsTo.has(c.nameLiteral))continue;s.push(xe(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(xe(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(rp,"evaluateUndeclared");function op(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||!Na(l))continue;let c=n(i.from);!c||!o.has(c)||s.push(xe(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(op,"evaluateTransportBypass");function Ma(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=Fr(e.classification),r=rp(t,e.kernelCalls,e.declarations,e.layerForFile,n),o=[...ep(t,e.compositionRootHits,n),...tp(t,e.layers,e.dependencies,e.layerForFile,n),...np(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...op(t,e.dependencies,e.layerForFile,n)].sort(Zu),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(Ma,"evaluateArkRunSensors");function Ha(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}a(Ha,"isArkOrderModuleSpecifier");var Ka=new Map;function Ga(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(Ga,"escapeAppliesToLiteral");function sp(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(sp,"normalizeAppliesToGlob");function ip(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(ip,"appliesToBracesBalanced");function ap(e){let t=Ka.get(e);if(t)return t;let n=sp(e),r=ip(n),o="",s=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(o+=Ga(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+=Ga(c)}let i=new RegExp(`^${o}$`);return Ka.set(e,i),i}a(ap,"globToRegExp");var Ua={"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 lp(e,t){return!t||t.length===0?!0:t.some(n=>ap(n).test(e))}a(lp,"matchesArkOrderAppliesTo");function cp(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(cp,"isDomainRoleLayer");function Me(e,t,n,r,o,s,i){let l=e.mode==="enforced"&&i;return{ruleId:Ua[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:Ua[t],fromLayer:s?.fromLayer,target:s?.target})}}a(Me,"finding");function Va(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let n=Fr(e.classification),r=[],o=t.planeRoots;if(t.mode==="enforced"&&o.length===0)r.push(Me(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(Me(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(Me(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||!Ha(u))continue;let f=e.layerForFile(c.from);f&&cp(f,s.get(f)??[])&&r.push(Me(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(Me(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(Me(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(Me(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)||lp(c.file,t.appliesTo)&&r.push(Me(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(Va,"evaluateArkOrderSensors");function J(e,t,n={}){return{ruleId:e,message:t,...n}}a(J,"configWarning");function Fn(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=mo(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 Xs(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 Qs(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=Oi(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:Pi(d)}))}return s}a(Fn,"collectAnalysisConfigWarnings");function ja(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:Ra({sensor:e.sensor,code:e.code})}:{},...r||o?{freezable:!1}:{},nextAction:t}}a(ja,"toArkRuleEngineViolation");function dp(e){let t=e.arkRules;return!!(t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0)}a(dp,"arkRulesMapIsOn");function Ba(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(Ba,"arkRuleFindingNextAction");function up(e,t){return t.some(n=>{try{return he(n).test(e)}catch{return!1}})}a(up,"matchesAny");function pp(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")&&!up(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(pp,"evaluateSafety");function fp(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}a(fp,"ambientForbiddenGlobal");function Wa(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return Ko(e,n.length>0?n:Ho.map(r=>({name:r.layer,prefixes:r.prefixes})))}a(Wa,"intentLayer");function gp(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||!fp(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"&&En(s.symbol,c))){if(s.source==="import-based"){let f=De(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}}vt(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 wn({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=Wa(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=Wa(s.intent,e.contract);if(!l)continue;let c=Ne(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?ht({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}:{},...Qe(u),message:y})}return r}a(gp,"contentViolations");function mp(e){let{facts:t}=e,n=xt(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,oe)=>{let Yt=`${R.code}\0${R.file??""}\0${R.message}`,Xt=`${oe.code}\0${oe.file??""}\0${oe.message}`;return Yt<Xt?-1:Yt>Xt?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 oe=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,...oe?{toLayer:oe}:{}}:{},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=Fn({config:e.contract.config,rules:e.contract.config.rules,files:i.map(R=>R.path)}),f=pp(e,t),y=e.contract.arkRules??_n(),p=i.map(R=>R.path),d={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?Pa(e.coverageInputs.fileContents):{},...e.fileHints??{}},m=a(R=>l.get(R)??fe(R,e.contract.config.layers),"resolveLayer"),b=[...Ca({arkRules:y,classShapes:e.contract.classShapes??t.classShapes??[],files:p,layerForFile:m,fileHints:d}),...xa(y,p),...Oa({arkRulesActive:dp(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=ra({hasEnforcedInvariant:Xo(y.invariants),coverage:e.contract.config.coverage,...e.coverageRootsPresent===!1?{declaredPathPresent:!1}:{}}),E=k.length>0?[]:na({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=>ja(R,Ba(R,!1))),S=b.filter(R=>!R.failsStrict).map(R=>({...ja(R,Ba(R,!0)),failsStrict:!1})),N=v?ea({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=_a(i),T=Ma({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}),X=e.contract.config.arkRun?.mode,Z=T.findings.filter(()=>X==="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}:{}})),Ie=T.findings.filter(()=>X!=="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})),Oe=Va({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}),qt=e.contract.config.arkOrder?.mode,or=Oe.findings.filter(()=>qt==="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}:{}})),_s=Oe.findings.filter(()=>qt!=="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,...Oe.completenessReasons],x=ct({config:e.contract.config,rules:e.contract.config.rules,files:i.filter(R=>R.layer).map(R=>R.path),contentViolations:[...gp(e,t,l),...L,...O,...z,...Z,...or],edges:c,warnings:[...u,...f.warnings,...S,...Q,...Ie,..._s],safety:f.report}),h=o==="complete"&&w.length>0?"partial":o,A=h==="complete"?s:[...s,...w].sort((R,oe)=>{let Yt=`${R.code}\0${R.file??""}\0${R.message}`,Xt=`${oe.code}\0${oe.file??""}\0${oe.message}`;return Yt<Xt?-1:Yt>Xt?1:0}),D=x.violations.filter(R=>R.failsStrict!==!1),q=h==="complete"&&D.length===0,Pe=q&&x.warnings.every(R=>R.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:h,completenessReasons:A,valid:q,strictValid:Pe,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(mp,"analyzeCanonicalResolvedProject");function Nt(e){return mp({contract:e.contract,facts:Ce(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints,adopted:e.adopted,invariantTestsPathPresent:e.invariantTestsPathPresent,coverageRootsPresent:e.coverageRootsPresent})}a(Nt,"analyzeResolvedProject");function za(e){return Y($(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}a(za,"analysisTreeHash");function is(e){let t=_t(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=lt(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=Dn({...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=ct({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=lt(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?at({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:za(t.ir.files),candidateTreeHash:za(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(is,"preflightChange");function yp(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(yp,"canonicalChangePath");function hp(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(hp,"identityViolations");function Rp(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(Rp,"preparedChange");function as(e){let t=Ce(e.baseFacts),n=Ce(e.candidateFacts),r=Nt({contract:e.contract,facts:t}),o=Nt({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=hp(t,n),c=new Map,u=[];for(let g of e.changes){let d=yp(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=Y(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(Rp(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&&$(d)===$(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?at({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(as,"preflightResolvedChange");var $r="docs/diagnostics.md",qa="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 $n=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.")]),ls=new Map($n.map(e=>[e.ruleId,e])),Ya=Object.freeze($n.map(e=>e.ruleId));function Xa(e){return typeof e=="string"&&e.length>0&&ls.has(e)}a(Xa,"isKnownDiagnosticCode");function Za(e){return typeof e!="string"||e.length===0?!1:ls.has(e)?!0:e.startsWith("ARKRULE_")}a(Za,"isCataloguedOrArkRuleFamily");function Mn(e){if(!(typeof e!="string"||e.length===0))return ls.get(e)}a(Mn,"getDiagnosticCatalogEntry");function cs(e){return`#${Mn(e)?.docsAnchor??e}`}a(cs,"diagnosticDocsFragment");function Ja(e){return`${$r}${cs(e)}`}a(Ja,"diagnosticDocsPath");function Qa(){return{schemaVersion:"1.0",docsPath:$r,codes:$n}}a(Qa,"serializeDiagnosticCatalog");function el(e){return Mn(e)?.fix}a(el,"catalogFixForRuleId");function tl(e){return Mn(e)?.why}a(tl,"catalogWhyForRuleId");var Ap=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."})]),MR=new Map(Ap.map(e=>[e.reasonId,e]));var nl="1.1";var rl="1.0";var Lt=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 kp(e){return typeof e.initialState=="function"?e.initialState():e.initialState}a(kp,"initialState");var Mr=class{static{a(this,"ProjectionRegistryImpl")}definitions=new Map;checkpoints=new Map;store;auditTrail;constructor(t={}){this.store=t.store??new Lt,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)??kp(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 Hn(e){return new Mr(e)}a(Hn,"createProjectionRegistry");var Kn="1.0";function Ip(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}a(Ip,"policyId");var ds=class{constructor(t){this.data=t}data;static{a(this,"ArkManifestImpl")}toJSON(){return{...this.data}}};function Gn(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:Ip(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:sr,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 ds(b)}a(Gn,"createArkManifest");var ol=0;function sl(e){return ol+=1,`${e}-${Date.now()}-${ol}`}a(sl,"createWorkflowId");function us(e){return e instanceof Error?e.message:String(e)}a(us,"errorMessage");function bp(e){return new Promise(t=>{setTimeout(t,e)})}a(bp,"sleep");async function Sp(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(Sp,"withTimeout");var Dt=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()}},ps=class{constructor(t,n={}){this.bus=t;this.options=n;this.store=n.store??new Dt}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??sl(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=us(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 Sp(c=>Promise.resolve(n.execute(t.context,this.bus,c)),n.timeoutMs,n.name)}catch(c){if(i<s){o.delayMs&&await bp(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:us(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:us(c)})}}}async audit(t,n,r){await this.options.auditTrail?.record({type:t,source:"Kernel.WorkflowEngine",subject:n.id,details:r})}};function Ft(e,t){return new ps(e,t)}a(Ft,"createWorkflowEngine");function fs(e,t,n={}){let r=Ft(t,n),o={name:e.name,steps:e.steps};r.register(o);let s=n.id??sl(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(fs,"createSaga");$t();function ll(e){return Object.keys(e).sort()}a(ll,"sortedKeys");function Rs(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)Rs(l[f],c[f],`${n}[${f}]`,r);return}let o=e,s=t,i=new Set([...ll(o),...ll(s)]);for(let l of[...i].sort())Rs(o[l],s[l],n?`${n}.${l}`:l,r)}a(Rs,"walk");function As(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(As,"shadowInformationPackage");function Kr(e,t){let n=[];return Rs(e,t,"",n),{equal:n.length===0,diffs:n}}a(Kr,"compareInformationPackages");function ks(e){let t=[];for(let n=1;n<e.length;n+=1)t.push(Kr(e[n-1],e[n]));return t}a(ks,"replayInformationPackages");zr();Jn();nr();nr();async function rr(e,t={}){let n=jt({host:t.host,port:t.port,nodeEnv:t.nodeEnv,processNodeEnv:process.env.NODE_ENV}),{listenArkRunInspector:r}=await Promise.resolve().then(()=>(Al(),Rl));return r(e,{bind:n,sseIntervalMs:t.sseIntervalMs})}a(rr,"startArkRunInspector");zr();nr();$t();Jn();$t();var lf=new Set(["singleton","transient"]);function kl(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(kl,"cloneComponent");function cf(e){if(e===void 0)return"singleton";if(typeof e=="string"&&lf.has(e))return e;throw new Error('ArkRun component lifetime must be "singleton" or "transient".')}a(cf,"closedLifetime");function Il(){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=cf(i.lifetime),u=ms({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}),kl(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=>kl(i.component))}}}a(Il,"createComponentRegistry");Jn();function df(e){let t={...e.metadata??{}};if(e.source===void 0)return t;if(t.source&&t.source!==e.source)throw new Se(e.source,t.source);return t.source=e.source,t}a(df,"stampMetadata");function uf(){}a(uf,"ignoreDetachedFailure");async function ws(e,t,n,r={}){let o=Zn({transport:r.transport,ephemeral:r.ephemeral??e.defaultEphemeral,brokerBound:typeof e.broker?.send=="function"}),s=df(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,uf)}return o}a(ws,"sendOnArkRunTransport");var to=1e3,bl=0;function pf(){return bl+=1,`ark-kernel-${Date.now()}-${bl}`}a(pf,"nextKernelInstanceId");function Sl(e,t){let n=e.constructor?.name;return typeof n=="string"&&n.length>0?n:t}a(Sl,"portConstructorId");function zt(e={}){let t=e.strict??!0,n=e.instanceId??pf(),r=e.profile??rt,o=e.maxHistorySize??to,s=en(),i=yn(),l=e.metadata??Sn(),c=e.auditTrail===void 0,u=e.auditTrail??mn({maxRecords:o}),f=e.eventContracts??fn(),y=e.eventBuffer===void 0&&e.outbox===void 0,p=e.eventBuffer??e.outbox??new Le,g=e.projections??Hn({auditTrail:u}),d=new _e([on(r),...e.policies??[]]),m=a(()=>{hn(s,i,{requireRegisteredTargets:!0})},"syncGraph"),b=e.ephemeral??!0,v=e.broker,k=new Rt({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=Ft(k,{auditTrail:u}),O=gn({registry:s,eventBus:k,graph:i}),L=Il(),S=typeof v?.send=="function",N=y?"InMemoryEventBuffer":Sl(p,"EventBufferStore"),z=c?"InMemoryAuditStore":Sl(u,"AuditTrail"),Q=Bt({stores:[Ue(N,"outbox"),Ue(z,"audit"),Ue("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 X=k.createPublisher(T);return{source:X.source,publish:X.publish,send(Z,Ie,Oe={}){return ws({eventBus:k,broker:v,defaultEphemeral:b},Z,Ie,{...Oe,source:X.source})}}},send(T,X,Z={}){return ws({eventBus:k,broker:v,defaultEphemeral:b},T,X,Z)},register(T){return L.register(T)},resolve(T){return L.resolve(T)},resolveSingleton(T){return L.resolveSingleton(T)},getDependencyInformationPackage(){return Re({kernelInstanceId:n,components:L.snapshotComponents()})},requestGraph(T){return Xn({kernelInstanceId:n,components:L.snapshotComponents()},T)},getInspectorSnapshot(T){return tr({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 rr({getInspectorSnapshot:a(Z=>pe.getInspectorSnapshot(Z),"getInspectorSnapshot"),requestGraph:a(Z=>pe.requestGraph(Z),"requestGraph"),async listInspectorOutbox(){let[Z,Ie]=await Promise.all([p.list("pending"),p.list("failed")]);return Ve([...Z,...Ie],{sampleLimit:ie})},async listInspectorWorkflows(){return je(await E.list(),{sampleLimit:ie})}},T)},syncGraph:m,manifest(){return m(),Gn({registry:s,policyEngine:d,metadata:l,graph:i,profile:r,projections:g,eventContracts:f,observability:O})}};return pe}a(zt,"createArkKernel");function no(e={}){return zt({...e,strict:!0,strictEventContracts:e.strictEventContracts??!0,requireKnownSource:e.requireKnownSource??!0,enforceObservedLayerFlow:e.enforceObservedLayerFlow??"hard"})}a(no,"createStrictArkKernel");function Cs(e,t={}){let{profileName:n,...r}=t;return{...r,profile:bn(e,{name:n})}}a(Cs,"createOptionsFromConfig");function xs(e,t={}){return zt(Cs(e,t))}a(xs,"createArkKernelFromConfig");function Os(e,t={}){return no(Cs(e,t))}a(Os,"createStrictArkKernelFromConfig");function Ps(e,t={}){return ro(Cs(e,t))}a(Ps,"createLenientArkKernelFromConfig");function ro(e={}){return zt({...e,strict:!1,strictEventContracts:e.strictEventContracts??!1,enforceObservedLayerFlow:e.enforceObservedLayerFlow??"off"})}a(ro,"createLenientArkKernel");0&&(module.exports={ANALYSIS_IR_SCHEMA_VERSION,ARK_ANALYSIS_RESULT_SCHEMA,ARK_ANALYSIS_RESULT_SCHEMA_VERSION,ARK_DESIGN_DELTA_SCHEMA_VERSION,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION,ARK_RUN_COMPONENT_LIFETIMES,ARK_RUN_EPHEMERAL_DEFAULT,ARK_RUN_GRAPH_DEFAULT_SLICE,ARK_RUN_GRAPH_NODE_KINDS,ARK_RUN_GRAPH_PROCESS_EDGE_KINDS,ARK_RUN_GRAPH_SCHEMA_VERSION,ARK_RUN_GRAPH_SLICES,ARK_RUN_GRAPH_TECHNICAL_EDGE_KINDS,ARK_RUN_INFORMATION_PACKAGE_SCHEMA_VERSION,ARK_RUN_INSPECTOR_DEFAULT_HOST,ARK_RUN_INSPECTOR_DEFAULT_PORT,ARK_RUN_INSPECTOR_EVENTS_PATH,ARK_RUN_INSPECTOR_GRAPH_PATH,ARK_RUN_INSPECTOR_MONITOR_SAMPLE_LIMIT,ARK_RUN_INSPECTOR_OUTBOX_PATH,ARK_RUN_INSPECTOR_SCHEMA_VERSION,ARK_RUN_INSPECTOR_SNAPSHOT_PATH,ARK_RUN_INSPECTOR_SSE_EVENT,ARK_RUN_INSPECTOR_TRANSPORT_FALLBACK,ARK_RUN_INSPECTOR_WORKFLOWS_PATH,ARK_RUN_TRANSPORT_KINDS,ArkRunInspectorBindError,ArkRunInspectorProductionError,DEFAULT_MAX_HISTORY_SIZE,DIAGNOSTIC_CATALOG,DIAGNOSTIC_CATALOG_SCHEMA_VERSION,DIAGNOSTIC_DOCS_RELATIVE_PATH,DIAGNOSTIC_RULE_IDS,EventContractRegistryImpl,EventContractViolationError,InMemoryAuditStore,InMemoryEventBuffer,InMemoryOutboxStore,InMemoryReadModelStore,InMemoryWorkflowStore,IntentRegistry,InvalidArkRunGraphQueryError,InvalidArkRunSendOptionError,InvalidIntentNameError,LayerPolicyContextError,MANIFEST_SCHEMA_VERSION,ObservedLayerFlowViolationError,POLICY_DELTA_SCHEMA_VERSION,PolicyEngine,PolicyViolationError,RESOLVED_CANDIDATE_FACTS_SCHEMA,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,SourceMetadataOverrideError,UnknownEventSourceError,UnregisteredIntentError,analyzeArchitectureConvergence,analyzeChange,analyzePolicyDelta,analyzeProject,analyzeResolvedProject,appendDecisionTape,architecturalPolicies,arkRunGraphQueryFromSearchParams,arkRunInspectorUrl,buildArkRunInspectorHardening,buildArkRunInspectorOutboxMonitor,buildArkRunInspectorSnapshot,buildArkRunInspectorWorkflowsMonitor,buildDependencyInformationPackage,buildPublishPolicyContext,catalogFixForRuleId,catalogWhyForRuleId,checkAdapterGovernance,checkContract,classifyArkPolicyDelta,classifyArkRunInspectorStoreDurability,closeArkRunGraphQuery,closedArkRunEphemeral,closedArkRunTransportKind,collectAnalysisConfigWarnings,collectForbiddenCapabilityUses,compareInformationPackages,createAICodeGate,createAdapter,createAdapterResult,createArchitectureProfile,createArchitectureProfileFromArkConfig,createArkKernel,createArkKernelFromConfig,createArkManifest,createArkTestHarness,createAuditTrail,createDependencyGraph,createElevenLayerArkConfig,createEventBus,createEventContractRegistry,createIntentRegistry,createLenientArkKernel,createLenientArkKernelFromConfig,createMetadataRegistry,createObservabilityReporter,createProjectionRegistry,createResolvedCandidateFacts,createSaga,createStrictArkKernel,createStrictArkKernelFromConfig,createWorkflowEngine,defaultIntentRegistry,defineArchitectureProfilePolicy,defineIntent,defineLayerPolicy,definePolicy,definePort,definePublishPolicy,detectArchitectureCycles,deterministicHash,diagnosticDocsFragment,diagnosticDocsPath,elevenLayerProfile,evaluateArchitectureGraph,explainViolation,extractSemanticDependencies,formatArkRunGraphMermaid,formatArkRunInspectorSseEvent,getDiagnosticCatalogEntry,isArkRunInspectorLoopbackHost,isArkRunInspectorProductionEnv,isCataloguedOrArkRuleFamily,isKnownDiagnosticCode,isLayerPolicy,loadContract,loadResolvedCandidateFacts,policyDeltaAcknowledgementMatches,preflightChange,preflightResolvedChange,replayInformationPackages,requestArkRunGraph,resolveArkRunInspectorBind,resolveArkRunSendPlan,resolvedFactsEvidenceRequirementsHash,serializeDiagnosticCatalog,shadowInformationPackage,stableSerialize,startArkRunInspector,syncRegistryToGraph,toAdapterDiagnostic,unavailableArkRunInspectorOutboxMonitor,unavailableArkRunInspectorWorkflowsMonitor,validateIntentName,version});
|