arkgate 4.8.16 → 4.8.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +81 -0
- package/README.md +10 -7
- package/bin/ark-check-runtime.mjs +5 -1
- package/bin/ark-mcp-runtime.mjs +14 -7
- package/bin/ark-shared.mjs +10 -4
- package/bin/ark.mjs +6 -0
- package/bin/lib/adr-path.mjs +116 -0
- package/bin/lib/adr-presence.mjs +3 -2
- package/bin/lib/agent-gates.mjs +2 -0
- package/bin/lib/analysis-engine.mjs +6 -6
- package/bin/lib/doctor-human.mjs +2 -2
- package/bin/lib/doctor-next-actions.mjs +117 -17
- package/bin/lib/first-run-help.mjs +6 -2
- package/bin/lib/html-report.mjs +1 -1
- package/bin/lib/policy-delta-io.mjs +19 -10
- package/bin/lib/presets.mjs +15 -21
- package/bin/lib/skill-install.mjs +42 -4
- package/bin/lib/start-preview.mjs +75 -3
- package/dist/{diagnosticCatalog-KWvGLI1U.d.ts → diagnosticCatalog-BNxKdcN4.d.ts} +7 -1
- package/dist/index.cjs +9 -9
- package/dist/index.d.ts +2 -2
- package/dist/index.js +11 -11
- package/dist/nestjs/index.cjs +1 -1
- package/dist/nestjs/index.js +1 -1
- package/dist/runtime/index.cjs +6 -6
- package/dist/runtime/index.d.ts +1 -1
- package/dist/runtime/index.js +6 -6
- package/docs/README.md +2 -2
- package/docs/agent-guide.md +9 -2
- package/docs/ai-gates.md +4 -0
- package/docs/configuration.md +6 -3
- package/docs/enthusiast/how-to-agent-gates.md +3 -1
- package/docs/enthusiast/how-to-pick-shape.md +1 -1
- package/docs/package-surface.md +1 -1
- package/docs/use.md +9 -4
- package/package.json +1 -1
- package/server.json +2 -2
- package/templates/agent-skills/README.md +1 -1
- package/templates/agent-skills/ark-adopt/SKILL.md +8 -5
- package/templates/agent-skills/ark-explain/SKILL.md +3 -0
- package/templates/agent-skills/ark-explore/SKILL.md +3 -1
- package/templates/agent-skills/ark-upgrade/SKILL.md +1 -0
- package/templates/skills/ark-adopt.md +8 -5
- package/templates/skills/ark-explain.md +3 -0
- package/templates/skills/ark-explore.md +3 -1
- package/templates/skills/ark-upgrade.md +1 -0
package/dist/runtime/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var Fo=Object.defineProperty;var i=(e,t)=>Fo(e,"name",{value:t,configurable:!0});var St=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var va=(e,t)=>{for(var n in t)Fo(e,n,{get:t[n],enumerable:!0})};function po(e,t){return e<t?-1:e>t?1:0}function
|
|
2
|
-
`)}function
|
|
1
|
+
var Fo=Object.defineProperty;var i=(e,t)=>Fo(e,"name",{value:t,configurable:!0});var St=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var va=(e,t)=>{for(var n in t)Fo(e,n,{get:t[n],enumerable:!0})};function po(e,t){return e<t?-1:e>t?1:0}function Sd(e){return[...new Set(e)].sort(po)}function Yt(e){if(!Array.isArray(e))return[];let t=[];for(let n of e)typeof n=="string"&&n.length>0&&t.push(n);return Sd(t)}function wd(e){if(e===null)return null;if(typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return e}function Cd(e){return typeof e=="string"&&Ed.has(e)?e:"singleton"}function Zi(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t={};for(let n of Object.keys(e).sort(po)){if(n.length===0)continue;let r=wd(e[n]);r!==void 0&&(t[n]=r)}return Object.keys(t).length>0?t:void 0}function xd(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=e,n={};typeof t.label=="string"&&t.label.length>0&&(n.label=t.label),typeof t.architectureKind=="string"&&t.architectureKind.length>0&&(n.architectureKind=t.architectureKind);let r=Yt(t.tags);r.length>0&&(n.tags=r),typeof t.group=="string"&&t.group.length>0&&(n.group=t.group);let o=Zi(t.metadata);return o&&(n.metadata=o),Object.keys(n).length>0?n:void 0}function fo(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=e,n=typeof t.id=="string"?t.id.trim():"";if(!n)return;let r={id:n,lifetime:Cd(t.lifetime),uses:Yt(t.uses),reactsTo:Yt(t.reactsTo),raises:Yt(t.raises),sends:Yt(t.sends)},o=xd(t.extendedInfo);return o&&(r.extendedInfo=o),r}function Pd(e){return Zi(e)}function go(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=e,n=typeof t.xiHash=="string"?t.xiHash.trim():"";if(!n)return;let r=t.event;if(r===null||typeof r!="object"||Array.isArray(r))return;let o=r,s=typeof o.kind=="string"?o.kind.trim():"";if(!s)return;let a=t.residual;if(a===null||typeof a!="object"||Array.isArray(a))return;let l=a,c=typeof l.kind=="string"&&Od.has(l.kind)?l.kind:void 0;if(!c)return;let p={kind:s},f=Pd(o.payload);f&&(p.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:p,residual:y}}function _d(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let r=go(n);r&&t.push(r)}return t}function Ie(e){let t=typeof e.kernelInstanceId=="string"?e.kernelInstanceId:"",n=Array.isArray(e.components)?e.components:[],r=new Set,o=[];for(let a of n){let l=fo(a);!l||r.has(l.id)||(r.add(l.id),o.push(l))}o.sort((a,l)=>po(a.id,l.id));let s=_d(e.decisionTape);return{schemaVersion:"1.0",kernelInstanceId:t,components:o,...s.length>0?{decisionTape:s}:{}}}function Ji(e,t){let n=go(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 nr,uo,Xi,Ed,Od,ht=St(()=>{"use strict";nr="1.0",uo=["singleton","transient"],Xi=["absorb","escalate_up","hold"],Ed=new Set(uo);i(po,"compare");i(Sd,"uniqueSorted");i(Yt,"nameList");i(wd,"jsonPrimitive");i(Cd,"closedLifetime");i(Zi,"sanitizeMetadata");i(xd,"sanitizeArkRunExtendedInfo");i(fo,"sanitizeArkRunComponent");Od=new Set(Xi);i(Pd,"sanitizeTapePayload");i(go,"sanitizeDecisionTapeRecord");i(_d,"sanitizeDecisionTape");i(Ie,"buildDependencyInformationPackage");i(Ji,"appendDecisionTape")});function Jt(e,t){return e<t?-1:e>t?1:0}function ho(e){return[...new Set(e)].sort(Jt)}function na(){return{tokens:[],ids:[],labels:[],tags:[],groups:[],architectureKinds:[]}}function Ro(e){return e.tokens.length+e.ids.length+e.labels.length+e.tags.length+e.groups.length+e.architectureKinds.length>0}function ge(e,t){if(e==null||e==="")return[];if(typeof e=="string")return ho(e.split(",").map(r=>r.trim()).filter(r=>r.length>0));if(!Array.isArray(e))throw new te(t);let n=[];for(let r of e){if(typeof r!="string")throw new te(t);let o=r.trim();o.length>0&&n.push(o)}return ho(n)}function ca(e,t){if(t==="*")return e.length>0;if(!t.includes("*"))return e===t;let n="^";for(let r of t)r==="*"?n+=".*":/[.*+?^${}()|[\]\\]/.test(r)?n+=`\\${r}`:n+=r;return n+="$",new RegExp(n).test(e)}function Xt(e,t){return e?t.some(n=>ca(e,n)):!1}function da(e){if(e==null||e==="")return ko;if(typeof e=="string"&&Td.has(e))return e;throw new te("slice")}function ua(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 te("degreesOfSeparation")}function ra(e,t){if(e==null||e==="")return na();if(typeof e=="string"||Array.isArray(e))return{...na(),tokens:ge(e,t)};if(typeof e!="object")throw new te(t);let n=e;for(let r of Object.keys(n))if(!Dd.has(r))throw new te(t);return{tokens:[],ids:ge(n.ids,t),labels:ge(n.labels,t),tags:ge(n.tags,t),groups:ge(n.groups,t),architectureKinds:ge(n.architectureKinds,t)}}function sr(e={}){if(e==null||e==="")return sr({});if(typeof e!="object"||Array.isArray(e))throw new te("slice","ArkRun graph query must be an object.");let t=e;for(let n of Object.keys(t))if(!Nd.has(n))throw new te("slice",`ArkRun graph query key "${n}" is not closed.`);return{slice:da(t.slice),nodeIds:ge(t.nodeIds,"nodeIds"),degreesOfSeparation:ua(t.degreesOfSeparation),include:ra(t.include,"include"),exclude:ra(t.exclude,"exclude")}}function ir(e){let t={};e.slice&&(t.slice=da(e.slice));let n=ge(e.nodeIds??void 0,"nodeIds");n.length>0&&(t.nodeIds=n);let r=ua(e.degreesOfSeparation??void 0);r!==null&&(t.degreesOfSeparation=r);let o=ge(e.include??void 0,"include");o.length>0&&(t.include=o);let s=ge(e.exclude??void 0,"exclude");return s.length>0&&(t.exclude=s),t}function Ld(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 oa(e,t){if(!Ro(t))return!0;let n=Ld(e);return t.tokens.some(r=>n.some(o=>ca(o,r)))||Xt(e.id,t.ids)||Xt(e.label,t.labels)||e.tags?.some(r=>Xt(r,t.tags))||Xt(e.group,t.groups)?!0:Xt(e.architectureKind,t.architectureKinds)}function Fd(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;return Ie({kernelInstanceId:t.kernelInstanceId,components:t.components})}return Ie({})}function Md(e){let t={id:e.id,kind:"component",lifetime:e.lifetime},n=e.extendedInfo;return n?.label&&(t.label=n.label),n?.group&&(t.group=n.group),n?.architectureKind&&(t.architectureKind=n.architectureKind),n?.tags&&n.tags.length>0&&(t.tags=[...n.tags]),t}function rr(e){return{id:e,kind:"interaction"}}function Zt(e,t){let n=e.get(t.id);(!n||n.kind==="interaction"&&t.kind==="component")&&e.set(t.id,t)}function or(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 $d(e,t){let n=new Map,r=[],o=new Set;for(let s of e){if(Zt(n,Md(s)),t==="technical"){for(let a of s.uses)Zt(n,n.get(a)??rr(a)),or(r,o,s.id,a,"uses");continue}for(let a of s.raises)Zt(n,n.get(a)??rr(a)),or(r,o,s.id,a,"raises");for(let a of s.reactsTo)Zt(n,n.get(a)??rr(a)),or(r,o,a,s.id,"reactsTo");for(let a of s.sends)Zt(n,n.get(a)??rr(a)),or(r,o,s.id,a,"sends")}return{nodes:n,edges:r}}function Kd(e){let t=new Map,n=i((r,o)=>{let s=t.get(r);s?s.push(o):t.set(r,[o])},"push");for(let r of e)n(r.from,r.to),n(r.to,r.from);return t}function Hd(e,t,n,r){let o=t.filter(l=>e.has(l));if(o.length===0)return new Set;let s=new Set,a=o.map(l=>({id:l,depth:0}));for(;a.length>0;){let l=a.shift();if(!(!l||s.has(l.id))&&(s.add(l.id),!(n!==null&&l.depth>=n)))for(let c of r.get(l.id)??[])!s.has(c)&&e.has(c)&&a.push({id:c,depth:l.depth+1})}return s}function Qt(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return/^[A-Za-z_]/.test(t)?t:`n_${t}`}function sa(e){return e.replace(/\\/g,"\\\\").replace(/"/g,"#quot;").replace(/]/g,"#93;")}function Gd(e){let t=new Set,n=new Map;for(let r of e){let o=Qt(r),s=o,a=2;for(;t.has(s);)s=`${o}_${a}`,a+=1;t.add(s),n.set(r,s)}return n}function bo(e){let t=e.slice==="technical"?"TD":"LR",n=e.nodes.map(l=>l.id),r=Gd(n),o=ho(e.nodes.map(l=>l.group).filter(l=>!!l)),s=[`flowchart ${t}`],a=i((l,c)=>{let p=r.get(l.id)??Qt(l.id),f=sa(l.label??l.id);s.push(`${c}${p}["${f}"]`)},"emitNode");for(let l of o){let c=Qt(`group_${l}`);s.push(` subgraph ${c}["${sa(l)}"]`);for(let p of e.nodes)p.group===l&&a(p," ");s.push(" end")}for(let l of e.nodes)l.group||a(l," ");for(let l of e.edges){let c=r.get(l.from)??Qt(l.from),p=r.get(l.to)??Qt(l.to);s.push(` ${c} -->|${l.kind}| ${p}`)}return s.join(`
|
|
2
|
+
`)}function Ud(e,t,n){let r=new Set(e.keys());if(Ro(n.include)&&(r=new Set([...r].filter(l=>{let c=e.get(l);return c!==void 0&&oa(c,n.include)}))),Ro(n.exclude))for(let l of[...r]){let c=e.get(l);c&&oa(c,n.exclude)&&r.delete(l)}let o=t.filter(l=>r.has(l.from)&&r.has(l.to));n.nodeIds.length>0&&(r=Hd(r,n.nodeIds,n.degreesOfSeparation,Kd(o)));let s=[...r].sort(Jt).map(l=>e.get(l)).filter(l=>!!l),a=o.filter(l=>r.has(l.from)&&r.has(l.to)).sort((l,c)=>Jt(l.from,c.from)||Jt(l.kind,c.kind)||Jt(l.to,c.to));return{nodes:s,edges:a}}function ar(e={},t={}){let n=Fd(e),r=sr(t),o=$d(n.components,r.slice),s=Ud(o.nodes,o.edges,r),a={schemaVersion:Ao,kernelInstanceId:n.kernelInstanceId,slice:r.slice,query:r,nodes:s.nodes,edges:s.edges,mermaid:""};return a.mermaid=bo(a),a}var Ao,ko,Io,ia,aa,la,te,Td,Nd,Dd,lr=St(()=>{"use strict";ht();Ao="1.0",ko="process",Io=["process","technical"],ia=["component","interaction"],aa=["raises","reactsTo","sends"],la=["uses"],te=class extends Error{static{i(this,"InvalidArkRunGraphQueryError")}option;constructor(t,n){super(n??(t==="slice"?'ArkRun graph slice must be "process" or "technical".':t==="degreesOfSeparation"?"ArkRun graph degreesOfSeparation must be a non-negative integer.":`ArkRun graph ${t} is not a closed query.`)),this.name="InvalidArkRunGraphQueryError",this.option=t}},Td=new Set(Io),Nd=new Set(["slice","nodeIds","degreesOfSeparation","include","exclude"]),Dd=new Set(["ids","labels","tags","groups","architectureKinds"]);i(Jt,"compare");i(ho,"uniqueSorted");i(na,"emptyMatch");i(Ro,"matchHasCriteria");i(ge,"nameList");i(ca,"globMatch");i(Xt,"anyGlob");i(da,"closedSlice");i(ua,"closedDegrees");i(ra,"closedMatch");i(sr,"closeArkRunGraphQuery");i(ir,"arkRunGraphQueryFromSearchParams");i(Ld,"nodeFields");i(oa,"nodeMatches");i(Fd,"asPackage");i(Md,"componentNode");i(rr,"interactionNode");i(Zt,"addNode");i(or,"addEdge");i($d,"buildSlice");i(Kd,"adjacency");i(Hd,"neighborhood");i(Qt,"mermaidSafeId");i(sa,"mermaidLabel");i(Gd,"uniqueMermaidIds");i(bo,"formatArkRunGraphMermaid");i(Ud,"filterGraph");i(ar,"requestArkRunGraph")});function vo(e){if(e===void 0)return"local";if(typeof e=="string"&&Vd.has(e))return e;throw new Rt("transport")}function Eo(e){if(e===void 0)return!0;if(e===!0||e===!1)return e;throw new Rt("ephemeral")}function cr(e){let t=vo(e.transport),n=Eo(e.ephemeral),r=t==="broker"&&e.brokerBound!==!0,o=t==="broker"&&!r?"broker":"local",s=t==="localBlocking";return{transport:t,ephemeral:n,deliveredVia:o,fallbackToLocal:r,notifySubscribers:o==="local",awaitHandlers:s,awaitHandoff:n||s}}var en,At,Vd,Rt,tn=St(()=>{"use strict";en=["local","localBlocking","broker"],At=!0,Vd=new Set(en),Rt=class extends Error{static{i(this,"InvalidArkRunSendOptionError")}option;constructor(t){super(t==="transport"?'ArkRun transport must be "local", "localBlocking", or "broker".':"ArkRun ephemeral must be a boolean."),this.name="InvalidArkRunSendOptionError",this.option=t}};i(vo,"closedArkRunTransportKind");i(Eo,"closedArkRunEphemeral");i(cr,"resolveArkRunSendPlan")});function ur(e){return e==="production"}function Bd(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 pa(e){if(e.startsWith("[::ffff:")&&e.endsWith("]"))return e.slice(8,-1);if(e.startsWith("::ffff:"))return e.slice(7)}function It(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();if(t==="localhost"||t==="::1"||t==="[::1]")return!0;let n=pa(t);if(n)return It(n);let r=Bd(t);return r!==void 0&&r[0]===127}function fa(e){if(e===void 0)return dr;if(typeof e!="string")throw new ce(String(e));let t=e.trim();if(jd.has(t.toLowerCase())||!It(t))throw new ce(t);let n=t.toLowerCase();if(n==="localhost")return dr;if(n==="[::1]")return"::1";let r=pa(n);return r?fa(r):n}function Wd(e){if(e===void 0)return wo;if(typeof e!="number"||!Number.isInteger(e)||e<0||e>65535)throw new ce(`port:${String(e)}`);return e}function ln(e={}){if(ur(e.nodeEnv)||ur(e.processNodeEnv))throw new kt;return{host:fa(e.host),port:Wd(e.port)}}function be(e,t,n){return`http://${e.includes(":")?`[${e}]`:e}:${t}${n}`}function zd(e){if(e!==void 0)try{return JSON.parse(JSON.stringify(e))}catch{return}}function qd(e){return{kinds:[...en],ephemeralDefault:e.ephemeralDefault===!1?!1:!0,brokerBound:e.brokerBound===!0,cloudSdksShipped:!1,fallback:xo}}function _e(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function Yd(e){let t=_e(e);if(!t||typeof t.id!="string")return;let n=t.status;if(n!=="pending"&&n!=="failed")return;let r=_e(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 pr(e){if(typeof e!="number"||!Number.isFinite(e))return se;let t=Math.trunc(e);return t<0?0:t>se?se:t}function je(e,t){let n=typeof e=="string"&&e.trim().length>0?e.trim():e&&typeof e=="object"&&"constructor"in e?String(e.constructor?.name??t):t,r=/^InMemory/i.test(n)?"memory":"durable";return{role:t,id:n,kind:r}}function cn(e={}){let t=_e(e),n=_e(t?.durability)??t,r=Array.isArray(n?.stores)?n.stores:Array.isArray(t?.stores)?t.stores:[],o=[];for(let s of r){let a=_e(s);if(!a)continue;let l=a.role;if(l!=="outbox"&&l!=="audit"&&l!=="workflow")continue;let c=typeof a.id=="string"?a.id:typeof a.name=="string"?a.name:void 0;if(!c)continue;let p=a.kind==="memory"||a.kind==="durable"?a.kind:je(c,l).kind;o.push({role:l,id:c,kind:p})}return{durability:{stores:o}}}function Be(e=[],t={}){let n=pr(t.sampleLimit),r=Array.isArray(e)?e:[],o=[],s=[];for(let a of r){let l=Yd(a);l&&(l.status==="pending"?o.push(l):s.push(l))}return{available:!0,pendingCount:o.length,failedCount:s.length,pending:o.slice(0,n),failed:s.slice(0,n),sampleLimit:n}}function Ue(){return{available:!1,pendingCount:0,failedCount:0,pending:[],failed:[],sampleLimit:se}}function Xd(e){let t=_e(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 Zd(e){return e==="idle"||e==="waiting"}function We(e=[],t={}){let n=pr(t.sampleLimit),r=Array.isArray(e)?e:[],o=[],s=0,a=0,l=0,c=0;for(let p of r){let f=Xd(p);f&&(o.push(f),f.status==="running"?s+=1:f.status==="compensating"?a+=1:f.status==="failed"?l+=1:Zd(f.status)&&(c+=1))}return{available:!0,total:o.length,runningCount:s,compensatingCount:a,failedCount:l,pendingCount:c,workflows:o.slice(0,n),sampleLimit:n}}function Ve(){return{available:!1,total:0,runningCount:0,compensatingCount:0,failedCount:0,pendingCount:0,workflows:[],sampleLimit:se}}function Jd(e){if(e===void 0)return;let t=_e(e);if(!t||t.available===!1)return Ue();let n=pr(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=Be(r,{sampleLimit:n}),s=typeof t.pendingCount=="number"&&Number.isFinite(t.pendingCount)?Math.max(0,Math.trunc(t.pendingCount)):o.pendingCount,a=typeof t.failedCount=="number"&&Number.isFinite(t.failedCount)?Math.max(0,Math.trunc(t.failedCount)):o.failedCount;return{...o,pendingCount:s,failedCount:a,sampleLimit:n}}return Ue()}function Qd(e){if(e===void 0)return;let t=_e(e);if(!t||t.available===!1)return Ve();let n=pr(t.sampleLimit);if(Array.isArray(t.workflows)){let r=We(t.workflows,{sampleLimit:n}),o=typeof t.total=="number"&&Number.isFinite(t.total)?Math.max(0,Math.trunc(t.total)):r.total,s=typeof t.runningCount=="number"&&Number.isFinite(t.runningCount)?Math.max(0,Math.trunc(t.runningCount)):r.runningCount,a=typeof t.compensatingCount=="number"&&Number.isFinite(t.compensatingCount)?Math.max(0,Math.trunc(t.compensatingCount)):r.compensatingCount,l=typeof t.failedCount=="number"&&Number.isFinite(t.failedCount)?Math.max(0,Math.trunc(t.failedCount)):r.failedCount,c=typeof t.pendingCount=="number"&&Number.isFinite(t.pendingCount)?Math.max(0,Math.trunc(t.pendingCount)):r.pendingCount;return{...r,total:o,runningCount:s,compensatingCount:a,failedCount:l,pendingCount:c,sampleLimit:n}}return Ve()}function fr(e={}){let t=ln({host:e.host,port:e.port}),n=Ie({kernelInstanceId:e.kernelInstanceId,components:e.package&&typeof e.package=="object"&&!Array.isArray(e.package)&&Array.isArray(e.package.components)?e.package.components:[]}),r=Jd(e.outbox),o=Qd(e.workflows),s={schemaVersion:So,kernelInstanceId:typeof e.kernelInstanceId=="string"?e.kernelInstanceId:n.kernelInstanceId,bind:{host:t.host,port:t.port,loopback:!0},package:{...n,schemaVersion:"1.0"},transport:qd(e),observability:zd(e.observability)??{},hardening:cn(e.hardening)};return r&&(s.outbox=r),o&&(s.workflows=o),s}function dn(e){return`event: ${Co}
|
|
3
3
|
data: ${JSON.stringify(e)}
|
|
4
4
|
|
|
5
|
-
`}var So,dr,wo,nn,rn,on,sn,an,Co,xo,se,kt,ce,Vd,un=St(()=>{"use strict";ht();tn();So="1.0",dr="127.0.0.1",wo=0,nn="/snapshot",rn="/events",on="/graph",sn="/outbox",an="/workflows",Co="snapshot",xo="in-process-local",se=32,kt=class extends Error{static{i(this,"ArkRunInspectorProductionError")}constructor(){super("ArkRun inspector refuses to start when NODE_ENV=production."),this.name="ArkRunInspectorProductionError"}},ce=class extends Error{static{i(this,"ArkRunInspectorBindError")}constructor(t){super(`ArkRun inspector binds loopback only (default 127.0.0.1). Public host "${t}" is rejected.`),this.name="ArkRunInspectorBindError"}},Vd=new Set(["","*","0","0.0.0.0","::","::0","[::]","[::0]","::ffff:0.0.0.0","[::ffff:0.0.0.0]"]);i(ur,"isArkRunInspectorProductionEnv");i(jd,"ipv4Octets");i(pa,"unwrapIpv4Mapped");i(It,"isArkRunInspectorLoopbackHost");i(fa,"closedHost");i(Bd,"closedPort");i(ln,"resolveArkRunInspectorBind");i(be,"arkRunInspectorUrl");i(Wd,"jsonClone");i(zd,"closedTransportFacts");i(_e,"asRecord");i(qd,"closedOutboxSummary");i(pr,"closedSampleLimit");i(je,"classifyArkRunInspectorStoreDurability");i(cn,"buildArkRunInspectorHardening");i(Be,"buildArkRunInspectorOutboxMonitor");i(Ue,"unavailableArkRunInspectorOutboxMonitor");i(Yd,"closedWorkflowSummary");i(Xd,"isPendingWorkflowStatus");i(We,"buildArkRunInspectorWorkflowsMonitor");i(Ve,"unavailableArkRunInspectorWorkflowsMonitor");i(Zd,"closedOutboxMonitor");i(Jd,"closedWorkflowsMonitor");i(fr,"buildArkRunInspectorSnapshot");i(dn,"formatArkRunInspectorSseEvent")});var ga={};va(ga,{listenArkRunInspector:()=>su});function Qd(){return{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}}function eu(){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 Te(e,t,n){if(!(e.writableEnded||e.destroyed))try{e.writeHead(t,Qd()),e.end(JSON.stringify(n))}catch{}}function nu(e,t){let n=e.address();if(n===null||typeof n=="string")throw new ce(t.host);if(!It(n.address))throw new ce(n.address);return{host:t.host,port:n.port}}async function ru(e){if(typeof e.listInspectorOutbox=="function")return e.listInspectorOutbox();let t=e.outbox??e.eventBuffer;if(!t||typeof t.list!="function")return Ue();let[n,r]=await Promise.all([t.list("pending"),t.list("failed")]);return Be([...n??[],...r??[]],{sampleLimit:se})}async function ou(e){return typeof e.listInspectorWorkflows=="function"?e.listInspectorWorkflows():!e.workflowEngine||typeof e.workflowEngine.list!="function"?Ve():We(await e.workflowEngine.list(),{sampleLimit:se})}async function su(e,t){let n=await import("http"),r=new Set,o=new Set,s=typeof t.sseIntervalMs=="number"&&Number.isFinite(t.sseIntervalMs)?Math.max(0,t.sseIntervalMs):1e3,a=t.bind,l=i(()=>e.getInspectorSnapshot(a),"snapshot"),c=n.createServer((p,f)=>{let y=tu(p.url),u=y.pathname;if(p.method==="GET"&&(u==="/"||u===nn)){Te(f,200,l());return}if(p.method==="GET"&&u===on){try{Te(f,200,e.requestGraph(ir({slice:y.searchParams.get("slice"),nodeIds:y.searchParams.get("nodeIds"),degreesOfSeparation:y.searchParams.get("degreesOfSeparation"),include:y.searchParams.get("include"),exclude:y.searchParams.get("exclude")})))}catch(g){if(g instanceof te){Te(f,400,{error:g.message,option:g.option});return}throw g}return}if(p.method==="GET"&&u===sn){ru(e).then(g=>Te(f,200,g)).catch(g=>{Te(f,500,{error:g instanceof Error?g.message:"outbox monitor failed"})});return}if(p.method==="GET"&&u===an){ou(e).then(g=>Te(f,200,g)).catch(g=>{Te(f,500,{error:g instanceof Error?g.message:"workflows monitor failed"})});return}if(p.method==="GET"&&u===rn){f.writeHead(200,eu()),f.flushHeaders(),f.write(dn(l())),r.add(f);let g=s>0?setInterval(()=>{f.write(dn(l()))},s):void 0;g&&o.add(g);let d=i(()=>{r.delete(f),g&&(clearInterval(g),o.delete(g))},"drop");p.on("close",d),f.on("close",d);return}Te(f,404,{error:"not found"})});try{await new Promise((p,f)=>{let y=i(u=>f(u),"onError");c.once("error",y),c.listen({host:t.bind.host,port:t.bind.port},()=>{c.off("error",y);try{a=nu(c,t.bind),p()}catch(u){f(u instanceof Error?u:new ce(t.bind.host))}})})}catch(p){throw await new Promise(f=>{c.close(()=>f())}),p}return{host:a.host,port:a.port,url:be(a.host,a.port,"/"),snapshotUrl:be(a.host,a.port,nn),eventsUrl:be(a.host,a.port,rn),graphUrl:be(a.host,a.port,on),outboxUrl:be(a.host,a.port,sn),workflowsUrl:be(a.host,a.port,an),close(){for(let p of o)clearInterval(p);o.clear();for(let p of r)p.end();return r.clear(),new Promise((p,f)=>{c.close(y=>{y?f(y):p()})})}}}var ma=St(()=>{"use strict";lr();un();i(Qd,"jsonHeaders");i(eu,"sseHeaders");i(tu,"requestUrl");i(Te,"writeJson");i(nu,"boundAddress");i(ru,"resolveOutboxMonitor");i(ou,"resolveWorkflowsMonitor");i(su,"listenArkRunInspector")});var mr="4.8.16";var Ea=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,Sa=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,wa=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function Ca(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),o=String(t?.toLayer??"");return Ea.test(n)?"pure-shared":r==="PersistenceAdapters"&&(Sa.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${o} ${n}`))?"kernel-emit":wa.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&o==="PersistenceAdapters"?"use-case":"unknown"}i(Ca,"classifyLayerImportKind");function xa(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=Ca(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(xa,"layerImportNextAction");function Oa(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}i(Oa,"arkRunCallSiteName");function Pa(e){let t=Oa(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(Pa,"arkRunNextAction");function fe(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return xa(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 Pa(e);case"ARKORDER_MISSING_PLANE":return typeof e.target=="string"&&e.target.length>0?`Import createOrderPlane from arkgate/order and call it in plane root ${e.target} listed in arkOrder.planeRoots, then preflight again.`:"Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKORDER_KERNEL_IN_DOMAIN":return"Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe.";case"ARKORDER_GENERIC_UPDATE":return"Don't use a generic update. First freeze with release(). Later, propose the change, then apply it.";case"ARKORDER_TOO_MANY_PARAMS":return"Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe.";case"ARKORDER_INGEST_WRITES_XI":return"Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe.";case"ARKORDER_XI_FIELD_WRITE":return typeof e.target=="string"&&e.target.length>0?`Don't write ${e.target} from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.`:"Don't write a named product choice from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.";case"ARKORDER_UNVALVED_RELEASE":return"Change the choice with proposeRelease then apply. release() is only the first freeze. Never mechanical-safe.";default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(fe,"deterministicNextAction");var gn="1.5",yr="docs/diagnostics.md",Mo={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","mode","valid","completeness","completenessReasons","diagnostics"],allOf:[{if:{properties:{completeness:{enum:["partial","unavailable"]}},required:["completeness"]},then:{properties:{valid:{const:!1}}}},{if:{properties:{mode:{const:"resolved-candidate-facts"},completeness:{enum:["complete","partial"]}},required:["mode","completeness"]},then:{required:["policyHash","resolverIdentity","factsHash","candidateTreeHash"]}},{if:{properties:{completeness:{const:"complete"}},required:["completeness"]},then:{properties:{completenessReasons:{maxItems:0}}},else:{properties:{completenessReasons:{minItems:1}}}}],properties:{schemaVersion:{const:"1.5"},mode:{enum:["lexical-compatibility","resolved-candidate-facts"]},valid:{type:"boolean"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:{type:"string",minLength:1},message:{type:"string",minLength:1},file:{type:"string",minLength:1}}}},policyHash:{type:"string",minLength:1},resolverIdentity:{type:"string",minLength:1},factsHash:{type:"string",minLength:1},candidateTreeHash:{type:"string",minLength:1},diagnostics:{type:"array",items:{type:"object",additionalProperties:!1,required:["ruleId","severity","message","location","evidence"],properties:{ruleId:{type:"string",minLength:1},severity:{enum:["error","warning"]},message:{type:"string",minLength:1},location:{type:"object",additionalProperties:!1,required:["file","line","column"],properties:{file:{type:"string",minLength:1},line:{type:"integer",minimum:1},column:{type:"integer",minimum:1}}},evidence:{type:"object",additionalProperties:!1,properties:{target:{type:"string"},fromLayer:{type:"string"},toLayer:{type:"string"},typeOnly:{type:"boolean"},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"},peerIsolation:{type:"boolean"},capability:{type:"string",minLength:1},edgeKind:{type:"string",minLength:1},arkruleId:{type:"string",minLength:1},arkruleSource:{type:"string",minLength:1}}},nextAction:{type:"string",minLength:1},findingRef:{type:"string",minLength:1,pattern:"^fnv1a-[0-9a-f]{8}$"},targetKey:{type:"string",minLength:1},docsCodePath:{type:"string",minLength:1}}}}}};function mn(e){let t=typeof e.ruleId=="string"?e.ruleId:typeof e.code=="string"?e.code:void 0,n=typeof e.file=="string"?e.file:void 0,r=typeof e.fromLayer=="string"?e.fromLayer:void 0,o=typeof e.toLayer=="string"?e.toLayer:void 0,s=typeof e.target=="string"?e.target:void 0;return[t,n,r??"",o??"",s??""].join("|")}i(mn,"adapterFindingTargetKey");function yn(e){let t=new Map;return e.map(n=>{let r=mn(n),o=(t.get(r)??0)+1;return t.set(r,o),o===1?r:`${r}#${o}`})}i(yn,"adapterFindingOccurrenceTargetKeys");function hr(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(hr,"adapterFindingRefFromTargetKey");function Rr(e){return`${yr}#${e}`}i(Rr,"adapterDocsCodePath");function O(e){return typeof e=="string"&&e.length>0?e:void 0}i(O,"text");function $o(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}i($o,"positiveInteger");function _a(e,t,n){return fe({ruleId:e,target:O(t.target)??O(n.target)??void 0,fromLayer:O(t.fromLayer)??void 0,toLayer:O(t.toLayer)??void 0,typeOnly:t.typeOnly===!0,targetTypeOnlyExports:t.targetTypeOnlyExports===!0,namedBindingsTypeOnly:t.namedBindingsTypeOnly===!0,portProofEligible:t.portProofEligible===!0,peerIsolation:t.peerIsolation===!0,sourcePureTypeModule:t.sourcePureTypeModule===!0,edgeKind:O(t.edgeKind)??void 0,capability:O(t.capability)??O(n.capability)??void 0,arkruleId:O(t.arkruleId)??void 0,arkruleSource:O(t.arkruleSource)??void 0})}i(_a,"nextActionForDiagnostic");function Ar(e,t="error",n){let r=O(e.ruleId)??O(e.code)??"ARK_UNKNOWN",o=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,s={...O(e.target)?{target:O(e.target)}:{},...O(e.fromLayer)?{fromLayer:O(e.fromLayer)}:{},...O(e.toLayer)?{toLayer:O(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{},...typeof e.targetTypeOnlyExports=="boolean"?{targetTypeOnlyExports:e.targetTypeOnlyExports}:{},...typeof e.sourcePureTypeModule=="boolean"?{sourcePureTypeModule:e.sourcePureTypeModule}:{},...typeof e.namedBindingsTypeOnly=="boolean"?{namedBindingsTypeOnly:e.namedBindingsTypeOnly}:{},...typeof e.portProofEligible=="boolean"?{portProofEligible:e.portProofEligible}:{},...typeof e.peerIsolation=="boolean"?{peerIsolation:e.peerIsolation}:{},...O(e.capability)?{capability:O(e.capability)}:{},...O(e.edgeKind)?{edgeKind:O(e.edgeKind)}:{},...O(e.arkruleId)?{arkruleId:O(e.arkruleId)}:{},...O(e.arkruleSource)?{arkruleSource:O(e.arkruleSource)}:{}},a=n??mn(e),l=hr(a);return{ruleId:r,severity:o,message:O(e.message)??r,location:{file:O(e.file)??"<unknown>",line:$o(e.line,1),column:$o(e.column,1)},evidence:s,nextAction:O(e.nextAction)??_a(r,s,e),findingRef:l,targetKey:a,docsCodePath:Rr(r)}}i(Ar,"toAdapterDiagnostic");function Ta(e){let t=e.completeness??"complete",n=e.mode??"lexical-compatibility";if(t==="complete"&&(e.completenessReasons?.length??0)>0)throw new Error("completenessReasons must be empty when completeness is complete.");let r=t==="complete"?[]:e.completenessReasons&&e.completenessReasons.length>0?e.completenessReasons.map(y=>({code:O(y.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:O(y.message)??`Analysis ${t}: required evidence is incomplete.`,...O(y.file)?{file:O(y.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],o={...O(e.policyHash)?{policyHash:O(e.policyHash)}:{},...O(e.resolverIdentity)?{resolverIdentity:O(e.resolverIdentity)}:{},...O(e.factsHash)?{factsHash:O(e.factsHash)}:{},...O(e.candidateTreeHash)?{candidateTreeHash:O(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let y of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!o[y])throw new Error(`${y} is required for resolved ${t} adapter evidence.`)}let s=e.violations??[],a=e.warnings??[],l=yn(s),c=yn(a),p=[...s.map((y,u)=>Ar(y,"error",l[u])),...a.map((y,u)=>Ar(y,"warning",c[u]))],f={schemaVersion:"1.5",completenessReasons:r,diagnostics:p};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...f,mode:n,valid:!1,completeness:t,...o};let y={policyHash:o.policyHash,resolverIdentity:o.resolverIdentity,factsHash:o.factsHash,candidateTreeHash:o.candidateTreeHash};return t==="complete"?{...f,mode:n,valid:e.valid,completeness:t,...y}:{...f,mode:n,valid:!1,completeness:t,...y}}return t==="complete"?{...f,mode:n,valid:e.valid,completeness:t,...o}:{...f,mode:n,valid:!1,completeness:t,...o}}i(Ta,"createAdapterResult");var qe=class{static{i(this,"IntentRegistry")}intents=new Map;dependencies=new Map;productions=new Map;define(t,n){if(this.intents.has(t))throw new Error(`Intent "${t}" is already registered. Intent names must be unique within a registry.`);let r=i(s=>({intent:t,payload:s,metadata:{occurredAt:new Date().toISOString(),source:"unknown"}}),"fn");Object.defineProperty(r,"name",{value:t,enumerable:!0,configurable:!1,writable:!1});let o=r;if(this.intents.set(t,o),n?.dependsOn)for(let s of n.dependsOn)this.declareDependency(t,s);if(n?.produces)for(let s of n.produces)this.declareProduction(t,s);return o}declareDependency(t,n){this.dependencies.has(t)||this.dependencies.set(t,new Set),this.dependencies.get(t).add(n)}declareProduction(t,n){this.productions.has(t)||this.productions.set(t,new Set),this.productions.get(t).add(n)}get(t){return this.intents.get(t)}list(){return Array.from(this.intents.values())}getDependencies(t){let n=this.dependencies.get(t);return n?Array.from(n):[]}getProductions(t){let n=this.productions.get(t);return n?Array.from(n):[]}getAllRelationships(){let t=[];for(let[n,r]of this.dependencies.entries())for(let o of r)t.push({from:n,to:o,kind:"dependsOn"});for(let[n,r]of this.productions.entries())for(let o of r)t.push({from:n,to:o,kind:"produces"});return t}has(t){return this.intents.has(t)}clear(){this.intents.clear(),this.dependencies.clear(),this.productions.clear()}};var Ko=new qe;function Ho(e,t){return Ko.define(e,t)}i(Ho,"defineIntent");function hn(){return new qe}i(hn,"createIntentRegistry");var Go=Ko;var Uo=["Domain.","Application.","Adapter.","Workflow.","Job.","Presentation.","Reporting.","Metadata.","Security.","Audit.","Observability.","Kernel."];function Rn(e){if(!e||typeof e!="string")return{valid:!1,reason:"Intent name must be a non-empty string"};if(!Uo.some(n=>e.startsWith(n)))return{valid:!1,reason:`Intent "${e}" must start with one of: ${Uo.join(", ")}`};let t=e.slice(e.indexOf(".")+1);return!t||!/^[A-Za-z][A-Za-z0-9_.]*$/.test(t)?{valid:!1,reason:`Intent "${e}" has an invalid segment after the layer prefix`}:{valid:!0}}i(Rn,"validateIntentName");var Se=class extends Error{static{i(this,"PolicyViolationError")}violations;constructor(t){let n=t.map(r=>`- ${r.policyName}: ${r.message}`).join(`
|
|
5
|
+
`}var So,dr,wo,nn,rn,on,sn,an,Co,xo,se,kt,ce,jd,un=St(()=>{"use strict";ht();tn();So="1.0",dr="127.0.0.1",wo=0,nn="/snapshot",rn="/events",on="/graph",sn="/outbox",an="/workflows",Co="snapshot",xo="in-process-local",se=32,kt=class extends Error{static{i(this,"ArkRunInspectorProductionError")}constructor(){super("ArkRun inspector refuses to start when NODE_ENV=production."),this.name="ArkRunInspectorProductionError"}},ce=class extends Error{static{i(this,"ArkRunInspectorBindError")}constructor(t){super(`ArkRun inspector binds loopback only (default 127.0.0.1). Public host "${t}" is rejected.`),this.name="ArkRunInspectorBindError"}},jd=new Set(["","*","0","0.0.0.0","::","::0","[::]","[::0]","::ffff:0.0.0.0","[::ffff:0.0.0.0]"]);i(ur,"isArkRunInspectorProductionEnv");i(Bd,"ipv4Octets");i(pa,"unwrapIpv4Mapped");i(It,"isArkRunInspectorLoopbackHost");i(fa,"closedHost");i(Wd,"closedPort");i(ln,"resolveArkRunInspectorBind");i(be,"arkRunInspectorUrl");i(zd,"jsonClone");i(qd,"closedTransportFacts");i(_e,"asRecord");i(Yd,"closedOutboxSummary");i(pr,"closedSampleLimit");i(je,"classifyArkRunInspectorStoreDurability");i(cn,"buildArkRunInspectorHardening");i(Be,"buildArkRunInspectorOutboxMonitor");i(Ue,"unavailableArkRunInspectorOutboxMonitor");i(Xd,"closedWorkflowSummary");i(Zd,"isPendingWorkflowStatus");i(We,"buildArkRunInspectorWorkflowsMonitor");i(Ve,"unavailableArkRunInspectorWorkflowsMonitor");i(Jd,"closedOutboxMonitor");i(Qd,"closedWorkflowsMonitor");i(fr,"buildArkRunInspectorSnapshot");i(dn,"formatArkRunInspectorSseEvent")});var ga={};va(ga,{listenArkRunInspector:()=>iu});function eu(){return{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}}function tu(){return{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-store",connection:"keep-alive","x-accel-buffering":"no"}}function nu(e){let t=e&&e.length>0?e:"/";return new URL(t,"http://127.0.0.1")}function Te(e,t,n){if(!(e.writableEnded||e.destroyed))try{e.writeHead(t,eu()),e.end(JSON.stringify(n))}catch{}}function ru(e,t){let n=e.address();if(n===null||typeof n=="string")throw new ce(t.host);if(!It(n.address))throw new ce(n.address);return{host:t.host,port:n.port}}async function ou(e){if(typeof e.listInspectorOutbox=="function")return e.listInspectorOutbox();let t=e.outbox??e.eventBuffer;if(!t||typeof t.list!="function")return Ue();let[n,r]=await Promise.all([t.list("pending"),t.list("failed")]);return Be([...n??[],...r??[]],{sampleLimit:se})}async function su(e){return typeof e.listInspectorWorkflows=="function"?e.listInspectorWorkflows():!e.workflowEngine||typeof e.workflowEngine.list!="function"?Ve():We(await e.workflowEngine.list(),{sampleLimit:se})}async function iu(e,t){let n=await import("http"),r=new Set,o=new Set,s=typeof t.sseIntervalMs=="number"&&Number.isFinite(t.sseIntervalMs)?Math.max(0,t.sseIntervalMs):1e3,a=t.bind,l=i(()=>e.getInspectorSnapshot(a),"snapshot"),c=n.createServer((p,f)=>{let y=nu(p.url),u=y.pathname;if(p.method==="GET"&&(u==="/"||u===nn)){Te(f,200,l());return}if(p.method==="GET"&&u===on){try{Te(f,200,e.requestGraph(ir({slice:y.searchParams.get("slice"),nodeIds:y.searchParams.get("nodeIds"),degreesOfSeparation:y.searchParams.get("degreesOfSeparation"),include:y.searchParams.get("include"),exclude:y.searchParams.get("exclude")})))}catch(g){if(g instanceof te){Te(f,400,{error:g.message,option:g.option});return}throw g}return}if(p.method==="GET"&&u===sn){ou(e).then(g=>Te(f,200,g)).catch(g=>{Te(f,500,{error:g instanceof Error?g.message:"outbox monitor failed"})});return}if(p.method==="GET"&&u===an){su(e).then(g=>Te(f,200,g)).catch(g=>{Te(f,500,{error:g instanceof Error?g.message:"workflows monitor failed"})});return}if(p.method==="GET"&&u===rn){f.writeHead(200,tu()),f.flushHeaders(),f.write(dn(l())),r.add(f);let g=s>0?setInterval(()=>{f.write(dn(l()))},s):void 0;g&&o.add(g);let d=i(()=>{r.delete(f),g&&(clearInterval(g),o.delete(g))},"drop");p.on("close",d),f.on("close",d);return}Te(f,404,{error:"not found"})});try{await new Promise((p,f)=>{let y=i(u=>f(u),"onError");c.once("error",y),c.listen({host:t.bind.host,port:t.bind.port},()=>{c.off("error",y);try{a=ru(c,t.bind),p()}catch(u){f(u instanceof Error?u:new ce(t.bind.host))}})})}catch(p){throw await new Promise(f=>{c.close(()=>f())}),p}return{host:a.host,port:a.port,url:be(a.host,a.port,"/"),snapshotUrl:be(a.host,a.port,nn),eventsUrl:be(a.host,a.port,rn),graphUrl:be(a.host,a.port,on),outboxUrl:be(a.host,a.port,sn),workflowsUrl:be(a.host,a.port,an),close(){for(let p of o)clearInterval(p);o.clear();for(let p of r)p.end();return r.clear(),new Promise((p,f)=>{c.close(y=>{y?f(y):p()})})}}}var ma=St(()=>{"use strict";lr();un();i(eu,"jsonHeaders");i(tu,"sseHeaders");i(nu,"requestUrl");i(Te,"writeJson");i(ru,"boundAddress");i(ou,"resolveOutboxMonitor");i(su,"resolveWorkflowsMonitor");i(iu,"listenArkRunInspector")});var mr="4.8.18";var Ea=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,Sa=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,wa=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function Ca(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),o=String(t?.toLayer??"");return Ea.test(n)?"pure-shared":r==="PersistenceAdapters"&&(Sa.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${o} ${n}`))?"kernel-emit":wa.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&o==="PersistenceAdapters"?"use-case":"unknown"}i(Ca,"classifyLayerImportKind");function xa(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=Ca(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(xa,"layerImportNextAction");function Oa(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}i(Oa,"arkRunCallSiteName");function Pa(e){let t=Oa(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(Pa,"arkRunNextAction");function fe(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return xa(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 Pa(e);case"ARKORDER_MISSING_PLANE":return typeof e.target=="string"&&e.target.length>0?`Import createOrderPlane from arkgate/order and call it in plane root ${e.target} listed in arkOrder.planeRoots, then preflight again.`:"Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKORDER_KERNEL_IN_DOMAIN":return"Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe.";case"ARKORDER_GENERIC_UPDATE":return"Don't use a generic update. First freeze with release(). Later, propose the change, then apply it.";case"ARKORDER_TOO_MANY_PARAMS":return"Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe.";case"ARKORDER_INGEST_WRITES_XI":return"Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe.";case"ARKORDER_XI_FIELD_WRITE":return typeof e.target=="string"&&e.target.length>0?`Don't write ${e.target} from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.`:"Don't write a named product choice from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.";case"ARKORDER_UNVALVED_RELEASE":return"Change the choice with proposeRelease then apply. release() is only the first freeze. Never mechanical-safe.";default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(fe,"deterministicNextAction");var gn="1.5",yr="docs/diagnostics.md",Mo={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","mode","valid","completeness","completenessReasons","diagnostics"],allOf:[{if:{properties:{completeness:{enum:["partial","unavailable"]}},required:["completeness"]},then:{properties:{valid:{const:!1}}}},{if:{properties:{mode:{const:"resolved-candidate-facts"},completeness:{enum:["complete","partial"]}},required:["mode","completeness"]},then:{required:["policyHash","resolverIdentity","factsHash","candidateTreeHash"]}},{if:{properties:{completeness:{const:"complete"}},required:["completeness"]},then:{properties:{completenessReasons:{maxItems:0}}},else:{properties:{completenessReasons:{minItems:1}}}}],properties:{schemaVersion:{const:"1.5"},mode:{enum:["lexical-compatibility","resolved-candidate-facts"]},valid:{type:"boolean"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:{type:"string",minLength:1},message:{type:"string",minLength:1},file:{type:"string",minLength:1}}}},policyHash:{type:"string",minLength:1},resolverIdentity:{type:"string",minLength:1},factsHash:{type:"string",minLength:1},candidateTreeHash:{type:"string",minLength:1},diagnostics:{type:"array",items:{type:"object",additionalProperties:!1,required:["ruleId","severity","message","location","evidence"],properties:{ruleId:{type:"string",minLength:1},severity:{enum:["error","warning"]},message:{type:"string",minLength:1},location:{type:"object",additionalProperties:!1,required:["file","line","column"],properties:{file:{type:"string",minLength:1},line:{type:"integer",minimum:1},column:{type:"integer",minimum:1}}},evidence:{type:"object",additionalProperties:!1,properties:{target:{type:"string"},fromLayer:{type:"string"},toLayer:{type:"string"},typeOnly:{type:"boolean"},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"},peerIsolation:{type:"boolean"},capability:{type:"string",minLength:1},edgeKind:{type:"string",minLength:1},arkruleId:{type:"string",minLength:1},arkruleSource:{type:"string",minLength:1}}},nextAction:{type:"string",minLength:1},findingRef:{type:"string",minLength:1,pattern:"^fnv1a-[0-9a-f]{8}$"},targetKey:{type:"string",minLength:1},docsCodePath:{type:"string",minLength:1}}}}}};function mn(e){let t=typeof e.ruleId=="string"?e.ruleId:typeof e.code=="string"?e.code:void 0,n=typeof e.file=="string"?e.file:void 0,r=typeof e.fromLayer=="string"?e.fromLayer:void 0,o=typeof e.toLayer=="string"?e.toLayer:void 0,s=typeof e.target=="string"?e.target:void 0;return[t,n,r??"",o??"",s??""].join("|")}i(mn,"adapterFindingTargetKey");function yn(e){let t=new Map;return e.map(n=>{let r=mn(n),o=(t.get(r)??0)+1;return t.set(r,o),o===1?r:`${r}#${o}`})}i(yn,"adapterFindingOccurrenceTargetKeys");function hr(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(hr,"adapterFindingRefFromTargetKey");function Rr(e){return`${yr}#${e}`}i(Rr,"adapterDocsCodePath");function O(e){return typeof e=="string"&&e.length>0?e:void 0}i(O,"text");function $o(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}i($o,"positiveInteger");function _a(e,t,n){return fe({ruleId:e,target:O(t.target)??O(n.target)??void 0,fromLayer:O(t.fromLayer)??void 0,toLayer:O(t.toLayer)??void 0,typeOnly:t.typeOnly===!0,targetTypeOnlyExports:t.targetTypeOnlyExports===!0,namedBindingsTypeOnly:t.namedBindingsTypeOnly===!0,portProofEligible:t.portProofEligible===!0,peerIsolation:t.peerIsolation===!0,sourcePureTypeModule:t.sourcePureTypeModule===!0,edgeKind:O(t.edgeKind)??void 0,capability:O(t.capability)??O(n.capability)??void 0,arkruleId:O(t.arkruleId)??void 0,arkruleSource:O(t.arkruleSource)??void 0})}i(_a,"nextActionForDiagnostic");function Ar(e,t="error",n){let r=O(e.ruleId)??O(e.code)??"ARK_UNKNOWN",o=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,s={...O(e.target)?{target:O(e.target)}:{},...O(e.fromLayer)?{fromLayer:O(e.fromLayer)}:{},...O(e.toLayer)?{toLayer:O(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{},...typeof e.targetTypeOnlyExports=="boolean"?{targetTypeOnlyExports:e.targetTypeOnlyExports}:{},...typeof e.sourcePureTypeModule=="boolean"?{sourcePureTypeModule:e.sourcePureTypeModule}:{},...typeof e.namedBindingsTypeOnly=="boolean"?{namedBindingsTypeOnly:e.namedBindingsTypeOnly}:{},...typeof e.portProofEligible=="boolean"?{portProofEligible:e.portProofEligible}:{},...typeof e.peerIsolation=="boolean"?{peerIsolation:e.peerIsolation}:{},...O(e.capability)?{capability:O(e.capability)}:{},...O(e.edgeKind)?{edgeKind:O(e.edgeKind)}:{},...O(e.arkruleId)?{arkruleId:O(e.arkruleId)}:{},...O(e.arkruleSource)?{arkruleSource:O(e.arkruleSource)}:{}},a=n??mn(e),l=hr(a);return{ruleId:r,severity:o,message:O(e.message)??r,location:{file:O(e.file)??"<unknown>",line:$o(e.line,1),column:$o(e.column,1)},evidence:s,nextAction:O(e.nextAction)??_a(r,s,e),findingRef:l,targetKey:a,docsCodePath:Rr(r)}}i(Ar,"toAdapterDiagnostic");function Ta(e){let t=e.completeness??"complete",n=e.mode??"lexical-compatibility";if(t==="complete"&&(e.completenessReasons?.length??0)>0)throw new Error("completenessReasons must be empty when completeness is complete.");let r=t==="complete"?[]:e.completenessReasons&&e.completenessReasons.length>0?e.completenessReasons.map(y=>({code:O(y.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:O(y.message)??`Analysis ${t}: required evidence is incomplete.`,...O(y.file)?{file:O(y.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],o={...O(e.policyHash)?{policyHash:O(e.policyHash)}:{},...O(e.resolverIdentity)?{resolverIdentity:O(e.resolverIdentity)}:{},...O(e.factsHash)?{factsHash:O(e.factsHash)}:{},...O(e.candidateTreeHash)?{candidateTreeHash:O(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let y of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!o[y])throw new Error(`${y} is required for resolved ${t} adapter evidence.`)}let s=e.violations??[],a=e.warnings??[],l=yn(s),c=yn(a),p=[...s.map((y,u)=>Ar(y,"error",l[u])),...a.map((y,u)=>Ar(y,"warning",c[u]))],f={schemaVersion:"1.5",completenessReasons:r,diagnostics:p};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...f,mode:n,valid:!1,completeness:t,...o};let y={policyHash:o.policyHash,resolverIdentity:o.resolverIdentity,factsHash:o.factsHash,candidateTreeHash:o.candidateTreeHash};return t==="complete"?{...f,mode:n,valid:e.valid,completeness:t,...y}:{...f,mode:n,valid:!1,completeness:t,...y}}return t==="complete"?{...f,mode:n,valid:e.valid,completeness:t,...o}:{...f,mode:n,valid:!1,completeness:t,...o}}i(Ta,"createAdapterResult");var qe=class{static{i(this,"IntentRegistry")}intents=new Map;dependencies=new Map;productions=new Map;define(t,n){if(this.intents.has(t))throw new Error(`Intent "${t}" is already registered. Intent names must be unique within a registry.`);let r=i(s=>({intent:t,payload:s,metadata:{occurredAt:new Date().toISOString(),source:"unknown"}}),"fn");Object.defineProperty(r,"name",{value:t,enumerable:!0,configurable:!1,writable:!1});let o=r;if(this.intents.set(t,o),n?.dependsOn)for(let s of n.dependsOn)this.declareDependency(t,s);if(n?.produces)for(let s of n.produces)this.declareProduction(t,s);return o}declareDependency(t,n){this.dependencies.has(t)||this.dependencies.set(t,new Set),this.dependencies.get(t).add(n)}declareProduction(t,n){this.productions.has(t)||this.productions.set(t,new Set),this.productions.get(t).add(n)}get(t){return this.intents.get(t)}list(){return Array.from(this.intents.values())}getDependencies(t){let n=this.dependencies.get(t);return n?Array.from(n):[]}getProductions(t){let n=this.productions.get(t);return n?Array.from(n):[]}getAllRelationships(){let t=[];for(let[n,r]of this.dependencies.entries())for(let o of r)t.push({from:n,to:o,kind:"dependsOn"});for(let[n,r]of this.productions.entries())for(let o of r)t.push({from:n,to:o,kind:"produces"});return t}has(t){return this.intents.has(t)}clear(){this.intents.clear(),this.dependencies.clear(),this.productions.clear()}};var Ko=new qe;function Ho(e,t){return Ko.define(e,t)}i(Ho,"defineIntent");function hn(){return new qe}i(hn,"createIntentRegistry");var Go=Ko;var Uo=["Domain.","Application.","Adapter.","Workflow.","Job.","Presentation.","Reporting.","Metadata.","Security.","Audit.","Observability.","Kernel."];function Rn(e){if(!e||typeof e!="string")return{valid:!1,reason:"Intent name must be a non-empty string"};if(!Uo.some(n=>e.startsWith(n)))return{valid:!1,reason:`Intent "${e}" must start with one of: ${Uo.join(", ")}`};let t=e.slice(e.indexOf(".")+1);return!t||!/^[A-Za-z][A-Za-z0-9_.]*$/.test(t)?{valid:!1,reason:`Intent "${e}" has an invalid segment after the layer prefix`}:{valid:!0}}i(Rn,"validateIntentName");var Se=class extends Error{static{i(this,"PolicyViolationError")}violations;constructor(t){let n=t.map(r=>`- ${r.policyName}: ${r.message}`).join(`
|
|
6
6
|
`);super(`Hard policy violation(s) detected:
|
|
7
7
|
${n}`),this.name="PolicyViolationError",this.violations=t}};var De=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 Se(n.hardViolations);return n}clear(){this.policies.length=0}};function Ye(e){let t=e.severity??"soft";return{name:e.name,severity:t,tags:e.tags,owner:e.owner,version:e.version,rationale:e.rationale,enforcementMode:e.enforcementMode,deprecated:e.deprecated,replacedBy:e.replacedBy,check:e.check}}i(Ye,"definePolicy");function Na(e){let t=e.indexOf(".");return t>=0?e.slice(0,t):e}i(Na,"defaultLayerOf");function Vo(e,t){return t.resolveLayer?.(e)??Na(e)}i(Vo,"resolveLayer");function Da(e,t,n){return e===n.from&&t===n.to}i(Da,"matchesRule");function An(e){let t=e.name??"Layer isolation",n=e.severity??"hard";return Ye({name:t,severity:n,tags:["layer"],check:i(r=>{let o=[...(r.edges??[]).filter(a=>a.kind==="declared"||a.kind==="produces").map(a=>({from:a.from,to:a.to})),...(r.relationships??[]).filter(a=>a.kind==="dependsOn").map(a=>({from:a.from,to:a.to}))],s=[];for(let a of o){let l=Vo(a.from,e),c=Vo(a.to,e);for(let p of e.rules)!p.allowed&&Da(l,c,p)&&s.push({policyName:t,severity:n,message:p.message??`Layer violation: ${a.from} (${l}) must not relate to ${a.to} (${c})`})}return s.length>0?s:!0},"check")})}i(An,"defineLayerPolicy");function kn(e){return e.tags?.includes("layer")??!1}i(kn,"isLayerPolicy");var kr={layerIsolation(){return kr.cleanArchitectureMatrix()},cleanArchitectureMatrix(){return An({name:"Clean architecture matrix",severity:"hard",rules:[{from:"Domain",to:"Adapter",allowed:!1},{from:"Domain",to:"Application",allowed:!1},{from:"Adapter",to:"Application",allowed:!1},{from:"Adapter",to:"Domain",allowed:!1}]})}};function In(e,t={}){return An({name:t.name??`${e.name} layer policy`,severity:t.severity??"hard",rules:e.rules,resolveLayer:e.resolveLayer})}i(In,"defineArchitectureProfilePolicy");function bn(e){return t=>({event:t,relationships:e.intentRegistry?.getAllRelationships(),edges:e.dependencyGraph?.getEdges()})}i(bn,"buildPublishPolicyContext");function jo(e){return Ye(e)}i(jo,"definePublishPolicy");var Xe=class extends Error{static{i(this,"UnregisteredIntentError")}intentName;constructor(t){super(`Intent "${t}" is not registered. Register it with IntentRegistry.define() before publish/subscribe, including metadata.source producer intents in strict mode.`),this.name="UnregisteredIntentError",this.intentName=t}},Ze=class extends Error{static{i(this,"InvalidIntentNameError")}intentName;reason;constructor(t,n){super(`Invalid intent name "${t}": ${n}`),this.name="InvalidIntentNameError",this.intentName=t,this.reason=n}},Je=class extends Error{static{i(this,"LayerPolicyContextError")}constructor(){super("Layer/architecture policies require intentRegistry, dependencyGraph, or a custom getPolicyContext. Without graph/registry context, layer policies cannot inspect relationships."),this.name="LayerPolicyContextError"}},Qe=class extends Error{static{i(this,"EventContractViolationError")}intentName;issues;constructor(t,n){super(`Event contract violation for "${t}". Register a matching event contract/version or fix the payload before publishing.`),this.name="EventContractViolationError",this.intentName=t,this.issues=n}},Le=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}},we=class extends Error{static{i(this,"SourceMetadataOverrideError")}boundSource;attemptedSource;constructor(t,n){super(`Source-bound publisher for "${t}" cannot publish with metadata.source "${n}". Create a publisher for the intended source instead.`),this.name="SourceMetadataOverrideError",this.boundSource=t,this.attemptedSource=n}},et=class extends Error{static{i(this,"ObservedLayerFlowViolationError")}source;intentName;fromLayer;toLayer;constructor(t,n,r,o,s){super(s??`Observed layer violation: "${t}" (${r}) must not produce "${n}" (${o}). Route this through an allowed layer or adjust the architecture profile rule.`),this.name="ObservedLayerFlowViolationError",this.source=t,this.intentName=n,this.fromLayer=r,this.toLayer=o}};function wt(e,t){if(!(!t.strictRegistry&&!t.validateIntentNaming)){if(t.validateIntentNaming){let n=Rn(e);if(!n.valid)throw new Ze(e,n.reason)}if(t.strictRegistry&&t.intentRegistry&&!t.intentRegistry.has(e))throw new Xe(e)}}i(wt,"assertIntentAllowed");function Bo(e,t){if(t.requireKnownSource){if(!e.metadata.source||e.metadata.source==="unknown")throw new Le(e.intent);if(t.intentRegistry&&!t.intentRegistry.has(e.metadata.source))throw new Le(e.intent,e.metadata.source)}}i(Bo,"assertSourceAllowed");function Ct(e,t){if(!t.eventContracts)return;let n=t.eventContracts.validate(e);if(!n.ok&&(t.strictEventContracts||n.contract))throw new Qe(e.intent,n.issues)}i(Ct,"assertContractAllowed");function tt(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}i(tt,"isPlainRecord");function nt(e){return Array.isArray(e)?e.map(nt):tt(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,nt(n)])):e}i(nt,"clonePatchValue");function Ir(e,t,n="payload"){let r={...e};for(let[o,s]of Object.entries(t)){let a=`${n}.${o}`;if(!(o in r)||r[o]===void 0){r[o]=nt(s);continue}if(tt(r[o])&&tt(s)){r[o]=Ir(r[o],s,a);continue}if(Array.isArray(r[o])&&Array.isArray(s)){r[o]=br(r[o],s,a);continue}throw new Error(`Interceptor patch cannot overwrite existing ${a}.`)}return r}i(Ir,"mergeRecordPatch");function br(e,t,n="payload"){let r=[...e];return t.forEach((o,s)=>{let a=`${n}[${s}]`;if(s>=r.length||r[s]===void 0){r[s]=nt(o);return}if(tt(r[s])&&tt(o)){r[s]=Ir(r[s],o,a);return}if(Array.isArray(r[s])&&Array.isArray(o)){r[s]=br(r[s],o,a);return}throw new Error(`Interceptor patch cannot overwrite existing ${a}.`)}),r}i(br,"mergeArrayPatch");function Wo(e,t){if(Array.isArray(t)){if(e===void 0)return nt(t);if(!Array.isArray(e))throw new Error("Array interceptor patch requires an array payload.");return br(e,t)}if(e===void 0)return nt(t);if(!tt(e))throw new Error("Object interceptor patch requires an object payload.");return Ir(e,t)}i(Wo,"applyPayloadPatch");async function zo(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:Wo(l.payload,c),metadata:{...l.metadata}};Ct(l,{eventContracts:t.eventContracts,strictEventContracts:t.strictEventContracts}),r=l,o.lastInterceptedAt=a,t.appendTrace({type:"event.intercepted",timestamp:a,intent:r.intent,correlationId:r.metadata.correlationId,traceId:r.metadata.traceId,spanId:r.metadata.spanId,details:{registrationId:o.registrationId,interceptorId:o.interceptorId,patchesApplied:s.length}}),await t.recordAudit("event.intercepted",r,{registrationId:o.registrationId,interceptorId:o.interceptorId,patchesApplied:s.length})}catch(a){await La(o,r,a,t)}}return r}i(zo,"applyInterceptors");async function La(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(La,"recordInterceptorError");var qo=new Map;function Yo(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(Yo,"escapeLiteral");function vn(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(vn,"normalizeGlobSeparators");function Fa(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(Fa,"bracesBalanced");function ye(e){let t=qo.get(e);if(t)return t;let n=vn(e),r=Fa(n),o="",s=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(o+=Yo(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+=Yo(c)}let a=new RegExp(`^${o}$`);return qo.set(e,a),a}i(ye,"globToRegExp");function Ma(e){return vn(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}i(Ma,"concreteGlobSegments");function vr(e,t){let n=vn(String(e)),r=Ma(n),o=n.replace(/\*/g,"").length,s=r.length*1e4+o;if(t==null||t==="")return s;let a=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return o;let l=0,c=-1;for(let p of r){let f=-1;for(let y=l;y<a.length;y+=1)if(a[y]===p){f=y;break}if(f<0)return s;c=f,l=f+1}return(c+1)*1e6+r.length*1e4+o}i(vr,"patternSpecificity");function de(e,t){let n=String(e).split(/[/\\]/).join("/"),r,o=-1;for(let s of t??[])if(!(s.exclude??[]).some(a=>ye(a).test(n))){for(let a of s.patterns??[])if(ye(a).test(n)){let l=vr(a,n);l>o&&(o=l,r=s.name)}}return r}i(de,"layerForRelativePath");function Xo(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),r=new Set(t.map(o=>String(o).toLowerCase()));for(let o=0;o<n.length-1;o+=1)if(r.has(n[o].toLowerCase()))return`${n[o].toLowerCase()}/${n[o+1].toLowerCase()}`}i(Xo,"sliceIdForPath");function $a(e){let t=new Set;for(let n of e??[]){let o=vn(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($a,"inferSliceFoldersFromPatterns");function Ka(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 $a(r?.patterns)}i(Ka,"resolveSliceFolders");function Zo(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}i(Zo,"normalizeSegments");function es(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}i(es,"trimTrailingSlashes");var Ha=["src","app"];function Ga(e){let t=es(e.replace(/^[./]+/,""));return t==="*"||t==="**"}i(Ga,"isBlanketRoot");function Jo(e,t){if(!e||!t?.length)return!1;let n=String(e).split(/[/\\]/).join("/"),r=n.toLowerCase(),o=Zo(n);for(let s of t){if(typeof s!="string"||s.length===0||Ga(s))continue;if(s.includes("*")){let c=es(s.toLowerCase());if(ye(c).test(r)||ye(`${c}/**`).test(r))return!0;continue}let a=Zo(s);if(a.length===0)continue;let l=Ha.includes(o[0])&&a[0]!==o[0]?[0,1]:[0];for(let c of l){if(c+a.length>o.length)continue;let p=!0;for(let f=0;f<a.length;f+=1)if(o[c+f]!==a[f]){p=!1;break}if(p)return!0}}return!1}i(Jo,"pathUnderSharedRoot");function Qo(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(Qo,"sliceMatchesDeclaration");function Ua(e,t,n){return!e?.length||!t||!n?!1:e.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&Qo(r.from,t)&&Qo(r.to,n))}i(Ua,"crossSliceEdgeAllowed");function Va(e){if(!e.fromPath)return{denied:!0,reason:"missing-path"};if(e.folderCount<=0)return{denied:!0,reason:"no-slice-folders"};let t=!!e.fromSlice||e.fromShared===!0;if(!e.toPath)return t?e.fromSlice?{denied:!0,reason:"missing-path"}:{denied:!1}:{denied:!0,reason:"unclassifiable-path"};let n=!!e.toSlice||e.toShared===!0;return!t||!n?{denied:!0,reason:"unclassifiable-path"}:!e.fromSlice||!e.toSlice?{denied:!1}:e.fromSlice===e.toSlice?{denied:!1}:e.crossSliceAllowed?{denied:!1}:{denied:!0,reason:"cross-slice"}}i(Va,"peerIsolationDecision");function rt(e,t){switch(e){case"cross-slice":return`cross-slice edge ${t.fromSlice??"?"} \u2192 ${t.toSlice??"?"}. Extract the shared code, use events/ports across slices, or declare the edge in the rule's allowedCrossSlice.`;case"unclassifiable-path":{let n=[t.fromSlice?void 0:t.fromPath,t.toSlice?void 0:t.toPath].filter(o=>!!o);return`unclassifiable path${n.length>0?` (${n.join(", ")})`:""} \u2014 ArkGate cannot place it in a slice, so it cannot prove this is not a cross-slice edge. Move it into a slice, or declare its root in the rule's sharedRoots.`}case"no-slice-folders":return"no slice folders \u2014 peerIsolation is on but no slice folder resolves from the rule or the layer patterns. Set sliceFolders on the rule.";default:return"no path evidence for this edge \u2014 peerIsolation needs the importer and importee paths."}}i(rt,"peerIsolationDenyExplanation");function ot(e,t,n,r){return Fe(e,t,n,r)?.rule}i(ot,"findDeniedEdgeRule");function Fe(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=Ka(o,t,r?.layers),c=s?Xo(s,l):void 0,p=a?Xo(a,l):void 0,f=Va({fromPath:s,toPath:a,folderCount:l.length,fromSlice:c,toSlice:p,fromShared:!c&&Jo(s,o.sharedRoots),toShared:!p&&Jo(a,o.sharedRoots),crossSliceAllowed:Ua(o.allowedCrossSlice,c,p)});if(f.denied)return{rule:o,peerIsolationReason:f.reason,fromSlice:c,toSlice:p};continue}if(t!==n)return{rule:o}}}i(Fe,"findDeniedEdgeDecision");async function ts(e,t){if(t.mode==="off"||!t.architectureProfile)return;let n=e.metadata.source;if(!n||n==="unknown")return;let r=t.architectureProfile,o=r.resolveLayer(n),s=r.resolveLayer(e.intent);if(!o||!s)return;let a=ot(r.rules,o,s);if(!a)return;let l=t.mode,c=a.message??`Observed layer violation: "${n}" (${o}) must not produce "${e.intent}" (${s}).`,p={source:n,intent:e.intent,fromLayer:o,toLayer:s,severity:l,message:c,rule:a};if(t.appendTrace({type:"layer.observedViolation",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:p}),await t.recordAudit("layer.observedViolation",e,p),l==="hard")throw new et(n,e.intent,o,s,c)}i(ts,"assertObservedLayerFlowAllowed");async function ns(e,t){let n=t.getPolicyContext(e),r;try{r=t.policyEngine.enforce(n)}catch(o){throw o instanceof Se&&(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(ns,"enforcePublishPolicy");function ja(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(ja,"appendHistory");function xt(e,t){e.trace.push(t),e.maxHistorySize!==void 0&&e.trace.length>e.maxHistorySize&&e.trace.splice(0,e.trace.length-e.maxHistorySize);for(let n of e.traceSinks)try{n(t)}catch{}}i(xt,"appendTrace");async function En(e,t,n,r){if(e.auditTrail)try{await e.auditTrail.record({type:t,source:n.metadata.source,intent:n.intent,correlationId:n.metadata.correlationId,causationId:n.metadata.causationId,subject:n.intent,details:r})}catch(o){xt(e,{type:"hook.error",timestamp:new Date().toISOString(),intent:n.intent,correlationId:n.metadata.correlationId,traceId:n.metadata.traceId,spanId:n.metadata.spanId,details:{hook:"auditTrail",error:o instanceof Error?o.message:String(o)}})}}i(En,"recordAudit");async function rs(e,t){let n={intent:t.intent,source:t.metadata.source,suggestion:"Publish through a registered intent creator so strict registry, contracts, and agent tooling share one source of truth."};xt(e,{type:"event.rawPublish",timestamp:new Date().toISOString(),intent:t.intent,correlationId:t.metadata.correlationId,traceId:t.metadata.traceId,spanId:t.metadata.spanId,details:n}),await En(e,"event.rawPublish",t,n)}i(rs,"recordRawPublishDiagnostic");async function os(e,t,n,r){let o={event:t,publishedAt:new Date().toISOString(),subscribersNotified:n};return ja(e,o),await e.eventBuffer?.enqueue(t,r),xt(e,{type:"event.published",timestamp:o.publishedAt,intent:t.intent,correlationId:t.metadata.correlationId,traceId:t.metadata.traceId,spanId:t.metadata.spanId,details:{subscribersNotified:n}}),await En(e,"event.published",t,{subscribersNotified:n}),o}i(os,"recordSuccessfulPublish");function Er(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(Er,"enrichMetadata");var ss=0;function Ba(){return ss+=1,`interceptor-${Date.now()}-${ss}`}i(Ba,"nextInterceptorRegistrationId");var st=class{static{i(this,"EventBusImpl")}subscriptions=[];subscriptionsByIntent=new Map;interceptors=[];interceptorsByIntent=new Map;recording;onPublish;onSoftViolation;onHandlerError;eventContracts;strictEventContracts;requireKnownSource;architectureProfile;enforceObservedLayerFlowMode;rethrowHandlerErrors;policyEngine;getPolicyContext;intentRegistry;dependencyGraph;strictRegistry;validateIntentNaming;constructor(t={}){if(this.onPublish=t.onPublish,this.onSoftViolation=t.onSoftViolation,this.onHandlerError=t.onHandlerError,this.eventContracts=t.eventContracts,this.strictEventContracts=t.strictEventContracts??!1,this.requireKnownSource=t.requireKnownSource??!1,this.architectureProfile=t.architectureProfile,this.enforceObservedLayerFlowMode=t.enforceObservedLayerFlow??"off",this.rethrowHandlerErrors=t.rethrowHandlerErrors??!1,this.intentRegistry=t.intentRegistry,this.dependencyGraph=t.dependencyGraph,this.strictRegistry=t.strictRegistry??t.intentRegistry!==void 0,this.validateIntentNaming=t.validateIntentNaming??this.strictRegistry,this.recording={history:[],trace:[],maxHistorySize:t.maxHistorySize,traceSinks:[...t.traceSinks??[]],auditTrail:t.auditTrail,eventBuffer:t.eventBuffer??t.outbox,instanceId:t.instanceId},t.policyEngine?this.policyEngine=t.policyEngine:t.policies&&t.policies.length>0&&(this.policyEngine=new De(t.policies)),(this.policyEngine?.getPolicies()??t.policies??[]).some(kn)&&!t.intentRegistry&&!t.dependencyGraph&&!t.getPolicyContext)throw new Je;t.getPolicyContext?this.getPolicyContext=t.getPolicyContext:t.intentRegistry||t.dependencyGraph?this.getPolicyContext=bn({intentRegistry:t.intentRegistry,dependencyGraph:t.dependencyGraph}):this.getPolicyContext=r=>({event:r})}async publish(t,n,r,o){await this.dispatch(t,n,r,o)}async dispatch(t,n,r,o={}){let s=o.notifySubscribers!==!1,a=o.awaitHandlers!==!1,l=o.runOnPublish!==!1,c,p=typeof t!="function";if(p){let u=t,g=r??n??{};c={...u,metadata:Er(u.metadata,g,this.recording.instanceId)}}else{let u=t,g=n,d=r??{},m=u(g);c={...m,metadata:Er(m.metadata,d,this.recording.instanceId)}}p&&this.strictRegistry&&await rs(this.recording,c),wt(c.intent,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),Bo(c,{requireKnownSource:this.requireKnownSource,intentRegistry:this.intentRegistry}),Ct(c,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),c=await zo(c,{interceptorsForIntent:i(u=>this.interceptorsByIntent.get(u)??[],"interceptorsForIntent"),eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts,appendTrace:i(u=>this.appendTrace(u),"appendTrace"),recordAudit:i((u,g,d)=>this.recordAudit(u,g,d),"recordAudit")}),Ct(c,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),await ts(c,{mode:this.enforceObservedLayerFlowMode,architectureProfile:this.architectureProfile,appendTrace:i(u=>this.appendTrace(u),"appendTrace"),recordAudit:i((u,g,d)=>this.recordAudit(u,g,d),"recordAudit")}),this.dependencyGraph?.registerEventFlow(c.metadata.source,c.intent);let f=[...this.subscriptionsByIntent.get(c.intent)??[]];this.policyEngine&&await ns(c,{policyEngine:this.policyEngine,getPolicyContext:this.getPolicyContext,appendTrace:i(u=>this.appendTrace(u),"appendTrace"),recordAudit:i((u,g,d)=>this.recordAudit(u,g,d),"recordAudit"),onSoftViolation:this.onSoftViolation,safeHook:i((u,g,d)=>this.safeHook(u,g,d),"safeHook")}),await os(this.recording,c,s?f.length:0,o.tx);let y=(async()=>{s&&await Promise.all(f.map(u=>this.invokeHandler(u,c))),l&&this.onPublish&&await this.safeHook(()=>this.onPublish(c),"onPublish",c)})();return a?await y:y.then(void 0,()=>{}),c}createPublisher(t){let n=typeof t=="string"?t:t.name;return wt(n,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),{source:n,publish:i(async(r,o,s={},a)=>{if(s.source&&s.source!==n)throw new we(n,s.source);await this.publish(r,o,{...s,source:n},a)},"publish")}}subscribe(t,n){let r=typeof t=="string"?t:t.name;wt(r,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let o={intentName:r,handler:n};this.subscriptions.push(o);let s=this.subscriptionsByIntent.get(r)??[];return s.push(o),this.subscriptionsByIntent.set(r,s),()=>{let a=this.subscriptions.indexOf(o);a>=0&&this.subscriptions.splice(a,1);let l=this.subscriptionsByIntent.get(r);if(!l)return;let c=l.indexOf(o);c>=0&&l.splice(c,1),l.length===0&&this.subscriptionsByIntent.delete(r)}}registerInterceptor(t,n,r){let o=typeof t=="string"?t:t.name;wt(o,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let s={registrationId:Ba(),interceptorId:r??o,intentName:o,interceptor:n,createdAt:new Date().toISOString()};this.interceptors.push(s);let a=this.interceptorsByIntent.get(o)??[];return a.push(s),this.interceptorsByIntent.set(o,a),s.registrationId}unregisterInterceptor(t){let n=this.interceptors.find(s=>s.registrationId===t);if(!n)return!1;let r=this.interceptors.indexOf(n);r>=0&&this.interceptors.splice(r,1);let o=this.interceptorsByIntent.get(n.intentName);if(o){let s=o.indexOf(n);s>=0&&o.splice(s,1),o.length===0&&this.interceptorsByIntent.delete(n.intentName)}return!0}listInterceptors(t){return this.interceptors.filter(n=>!t||n.intentName===t).map(n=>({registrationId:n.registrationId,interceptorId:n.interceptorId,intent:n.intentName,createdAt:n.createdAt,lastInterceptedAt:n.lastInterceptedAt}))}getHistory(){return[...this.recording.history]}clearHistory(){this.recording.history.length=0}getTrace(){return[...this.recording.trace]}clearTrace(){this.recording.trace.length=0}appendTrace(t){xt(this.recording,t)}async recordAudit(t,n,r){await En(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 is(e){return new st(e)}i(is,"createEventBus");function Wa(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(Wa,"formatStandardSchemaPath");function za(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(za,"actualType");function qa(e,t){return e?`${e}.${t}`:t}i(qa,"formatPath");function as(e,t,n,r,o){let s=za(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}ls(e,t.fields,r,o,n)}t.type==="array"&&t.items&&Array.isArray(e)&&e.forEach((a,l)=>{as(a,t.items,`${n}[${l}]`,r,o)})}i(as,"validateSchemaField");function ls(e,t,n,r,o){for(let[s,a]of Object.entries(t)){let l=qa(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}as(c,a,l,n,r)}}i(ls,"validateObjectSchema");var Ot=class{static{i(this,"EventContractRegistryImpl")}contracts=new Map;register(t){let n=this.key(t.intent,t.version);if(this.contracts.has(n))throw new Error(`Event contract "${n}" is already registered.`);this.contracts.set(n,{allowAdditionalFields:!0,...t})}get(t,n){return n?this.contracts.get(this.key(t,n)):this.list(t).at(-1)}list(t){return Array.from(this.contracts.values()).filter(n=>!t||n.intent===t)}validate(t){let n=t.metadata.eventVersion,r=this.get(t.intent,n),o=[];if(!r)return{ok:!1,issues:[{intent:t.intent,version:n,message:n?`No event contract registered for version "${n}".`:"No event contract registered for intent."}]};r.deprecated&&o.push({intent:t.intent,version:r.version,message:typeof r.deprecated=="string"?r.deprecated:"Event contract is deprecated."});let s=t.payload!=null&&typeof t.payload=="object"?t.payload:void 0;if(r.schema){if(!s)o.push({intent:t.intent,version:r.version,message:"Payload must be an object for schema validation."});else if(ls(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:Wa(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 Sn(){return new Ot}i(Sn,"createEventContractRegistry");var cs=0;function Ya(){return cs+=1,`outbox-${Date.now()}-${cs}`}i(Ya,"nextOutboxId");function ds(e){return{...e,event:{...e.event,metadata:{...e.event.metadata}}}}i(ds,"cloneRecord");var Me=class{static{i(this,"InMemoryEventBuffer")}records=new Map;async enqueue(t){let n=new Date().toISOString(),r={id:Ya(),event:t,status:"pending",attempts:0,createdAt:n,updatedAt:n};return this.records.set(r.id,r),ds(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(ds)}async clear(){this.records.clear()}},us=Me;function Sr(e){return`${e.from}->${e.to}`}i(Sr,"flowKey");function ps(e){let t=new Set,n=[];for(let r of e){let o=Sr(r);t.has(o)||(t.add(o),n.push(r))}return n}i(ps,"uniqueFlows");function fs(e,t){let n=new Set(t.map(Sr));return e.filter(r=>!n.has(Sr(r)))}i(fs,"difference");function wn(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=ps([...o,...s]),p=ps([...a,...l]),f=p.filter(m=>!m.from||m.from==="unknown"),y=t?Array.from(new Set(p.map(m=>m.from).filter(m=>m&&m!=="unknown"&&!t.has(m)))):[],u=t?Array.from(new Set(p.map(m=>m.to).filter(m=>!t.has(m)))):[],g=new Set(p.flatMap(m=>[m.from,m.to])),d=t?t.list().map(m=>m.name).filter(m=>!g.has(m)):[];return{generatedAt:new Date().toISOString(),declaredProductions:c,observedProductions:p,declaredButUnobserved:fs(c,p),observedButUndeclared:fs(p.filter(m=>m.from!=="unknown"),c),unknownSources:f,unregisteredObservedSources:y,unregisteredObservedIntents:u,registeredButNeverObserved:d}}}}i(wn,"createObservabilityReporter");function gs(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(gs,"createArkTestHarness");var ms=0;function Xa(){return ms+=1,`audit-${Date.now()}-${ms}`}i(Xa,"createAuditId");function Za(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(Za,"matchesQuery");var Pt=class{constructor(t){this.maxRecords=t}maxRecords;static{i(this,"InMemoryAuditStore")}records=[];append(t){this.records.push(t),this.maxRecords!==void 0&&this.records.length>this.maxRecords&&this.records.splice(0,this.records.length-this.maxRecords)}query(t={}){let n=this.records.filter(r=>Za(r,t));return t.limit===void 0?[...n]:n.slice(-t.limit)}clear(){this.records.length=0}},Cn=class{constructor(t){this.store=t}store;static{i(this,"AuditTrailImpl")}async record(t){let n={id:Xa(),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 xn(e={}){return new Cn(e.store??new Pt(e.maxRecords))}i(xn,"createAuditTrail");var On=class{static{i(this,"DependencyGraphImpl")}nodes=new Map;edges=[];registerDependency(t,n,r="declared"){this.ensureNode(t),this.ensureNode(n),this.addEdge({from:t,to:n,kind:r})}registerEventFlow(t,n){this.ensureNode(t),this.ensureNode(n),this.addEdge({from:t,to:n,kind:"observed"})}getNodes(){return Array.from(this.nodes.values())}getEdges(){return[...this.edges]}toJSON(){return{nodes:this.getNodes(),edges:this.getEdges()}}toMermaid(){let t=`flowchart TD
|
|
8
8
|
`;for(let r of this.edges){let o=r.kind?`|${r.kind}|`:"";t+=` ${this.safeId(r.from)} -->${o} ${this.safeId(r.to)}
|
|
@@ -19,7 +19,7 @@ ${n}`),this.name="PolicyViolationError",this.violations=t}};var De=class{static{
|
|
|
19
19
|
${n.map(r=>`- ${r.path}: ${r.message}`).join(`
|
|
20
20
|
`)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function Os(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(Os,"isObject");function Nn(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}i(Nn,"propertyPath");function it(e){return e===null?"null":Array.isArray(e)?"array":typeof e}i(it,"valueType");function il(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}i(il,"resolveSchemaRef");function Tt(e,t,n,r,o){if(t.$ref){let s=il(t.$ref,r);if(!s){o.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}Tt(e,s,n,r,o);return}if(t.const!==void 0&&!Object.is(e,t.const)){o.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(s=>Object.is(s,e))){o.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!Os(e)){o.push({path:n,message:`must be an object; received ${it(e)}`});return}let s=t.properties??{};for(let a of t.required??[])e[a]===void 0&&o.push({path:Nn(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in s||o.push({path:Nn(n,a),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let a=t.additionalProperties;for(let l of Object.keys(e))l in s||Tt(e[l],a,Nn(n,l),r,o)}for(let[a,l]of Object.entries(s))e[a]!==void 0&&Tt(e[a],l,Nn(n,a),r,o);return}if(t.type==="array"){if(!Array.isArray(e)){o.push({path:n,message:`must be an array; received ${it(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&o.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let s=e.map(a=>JSON.stringify(a));new Set(s).size!==s.length&&o.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((s,a)=>Tt(s,t.items,`${n}[${a}]`,r,o));return}if(t.type==="string"){if(typeof e!="string"){o.push({path:n,message:`must be a string; received ${it(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&o.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&o.push({path:n,message:`must be a boolean; received ${it(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){o.push({path:n,message:`must be an integer; received ${it(e)}`});return}t.minimum!==void 0&&e<t.minimum&&o.push({path:n,message:`must be at least ${t.minimum}`})}}i(Tt,"validateNode");function al(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"&&(Es(a)||t.push({path:`$.layers[${o}].owners[${l}]`,message:"must be a GitHub handle or email (not a display name)"}))})})}i(al,"validateLayerOwners");function ll(e){let t={...e,$schema:e.$schema===void 0?Dn:e.$schema,schemaVersion:e.schemaVersion===void 0?ae:e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?Ln.map(n=>({...n})):e.rules};return e.arkRun!==void 0&&(t.arkRun=As(e.arkRun)),e.arkOrder!==void 0&&(t.arkOrder=ks(e.arkOrder)),t}i(ll,"defaultedConfig");function cl(e){return e===ae?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}i(cl,"migratedFromOf");function dl(){let e=new Set([ae]);for(let t of Cr)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}i(dl,"knownInputVersions");function ul(e,t="ark.config.json"){if(!Os(e))throw new he(t,[{path:"$",message:`must be an object; received ${it(e)}`}]);let n=dl(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new he(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected ${ae}`}]);if(r!=="unversioned"&&!n.has(r))throw new he(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${ae}`}]);let o=r,s={...e},a=0;for(;o!==ae&&a<Cr.length+1;){a+=1;let l=Cr.find(c=>c.from===o);if(!l)throw new he(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(o)}; expected ${ae}`}]);o=l.to,s.schemaVersion=o}if(o!==ae)throw new he(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${ae}`}]);return{candidate:ll(s),migratedFrom:cl(r)}}i(ul,"migrateArkConfig");function xr(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=ul(e,t),o=[];if(Tt(n,ws,"$",ws,o),Is(n,o),bs(n,o),al(n,o),o.length>0)throw new he(t,o);return{config:n,migratedFrom:r}}i(xr,"loadArkConfigContract");function Ps(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new he(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return xr(n,t)}i(Ps,"parseArkConfigJson");function _s(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:Dn,schemaVersion:ae};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}i(_s,"withArkConfigMetadata");function pl(e){return e.endsWith(".")?e:`${e}.`}i(pl,"normalizePrefix");function fl(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(fl,"byLongestPrefix");function Fn(e){let t=e.layers.map(o=>({...o,prefixes:o.prefixes.map(pl)})),n=[...t].sort(fl),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(Fn,"createArchitectureProfile");function Mn(e,t={}){return Fn({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,r)=>({name:n.name,prefixes:n.intentPrefixes??[],description:n.description,trustBoundary:n.trustBoundary,owners:n.owners,order:r+1})),rules:e.rules??[]})}i(Mn,"createArchitectureProfileFromArkConfig");var gl=[{name:"DomainModel",prefixes:["Domain"],description:"Rich domain model, business rules, and domain events.",order:1},{name:"ApplicationOrchestration",prefixes:["Application"],description:"Use cases and command orchestration.",order:2},{name:"PersistenceAdapters",prefixes:["Adapter.Persistence","Adapter.Repository"],description:"Database, repository, and storage adapters.",order:3},{name:"IntegrationAdapters",prefixes:["Adapter.Integration","Adapter.External"],description:"External systems, APIs, and integration adapters.",order:4},{name:"WorkflowSagaEngine",prefixes:["Workflow"],description:"Sagas, workflows, and long-running processes.",order:5},{name:"BackgroundJobsScheduling",prefixes:["Job"],description:"Background jobs, scheduled work, and async processors.",order:6},{name:"PresentationAdapters",prefixes:["Presentation","Adapter.Presentation","Adapter.Api"],description:"API, UI, controller, and presentation adapters.",order:7},{name:"ReportingReadModels",prefixes:["Reporting"],description:"Read models, projections, and reporting surfaces.",order:8},{name:"ExtensibilityMetadata",prefixes:["Metadata"],description:"Metadata, extensions, and schema contracts.",order:9},{name:"SecurityAuditObservability",prefixes:["Security","Audit","Observability"],description:"Security, audit, and observability concerns.",order:10},{name:"Kernel",prefixes:["Kernel"],description:"Ark-owned governance and kernel signals.",order:11}],at=Fn({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:gl,rules:Ln.map(e=>({...e}))}),ml={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 Ts(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return _s({include:e.include??[t],layers:at.layers.map(o=>({name:o.name,patterns:(ml[o.name]??[o.name]).map(s=>`${r}${s}/**`),intentPrefixes:o.prefixes,optional:n})),rules:[...at.rules]})}i(Ts,"createElevenLayerArkConfig");var $n=class{static{i(this,"MetadataRegistryImpl")}entities=new Map;entity(t,n,r={}){if(this.entities.has(t)&&!r.allowOverwrite)throw new Error(`Entity metadata "${t}" is already registered.`);let o={name:t,fields:{},...n};return this.entities.set(t,o),o}getEntity(t){return this.entities.get(t)}listEntities(){return Array.from(this.entities.values())}findEntitiesByIntent(t){return this.listEntities().filter(n=>n.emits?.includes(t)||n.consumes?.includes(t))}validate(){let t=[];for(let n of this.entities.values()){n.name.trim()||t.push({entity:n.name,message:"Entity name is required."});for(let[r,o]of Object.entries(n.fields))r.trim()||t.push({entity:n.name,field:r,message:"Field name is required."}),(!o.type||typeof o.type!="string")&&t.push({entity:n.name,field:r,message:"Field type must be a non-empty string."}),o.relation&&!this.entities.has(o.relation.entity)&&t.push({entity:n.name,field:r,message:`Related entity "${o.relation.entity}" is not registered.`})}return{ok:t.length===0,issues:t}}toJSON(){return this.listEntities()}};function Kn(){return new $n}i(Kn,"createMetadataRegistry");function Ns(e,t={}){return{name:e,ownerLayer:t.ownerLayer,intent:t.intent,allowedAdapters:t.allowedAdapters?[...t.allowedAdapters]:void 0}}i(Ns,"definePort");function Ds(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(p=>!Fs(t,p));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=Or(a);if(!l.ok)throw new Error(l.issues.map(c=>c.message).join(`
|
|
21
21
|
`));return a}i(Ds,"createAdapter");function Ls(e,t=[]){let n=t.filter(r=>!Fs(e,r));return n.length===0?{ok:!0}:{ok:!1,missing:n}}i(Ls,"checkContract");function Or(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(Or,"checkAdapterGovernance");function Fs(e,t){return e!=null&&(typeof e=="object"||typeof e=="function")&&t in e}i(Fs,"hasMember");var _r=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),Nr=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Dr=Object.freeze(Object.keys(Nr).sort()),Pr=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"}),Tr=Object.freeze({process:Object.freeze(["process","node:process"])});function Nt(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=Pr[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),o=Pr[r];if(o)return o;let s=e.indexOf("/",n+1);return s<0?null:Pr[e.slice(0,s)]??null}i(Nt,"capabilityForModuleSpecifier");function Ce(e,t){for(let n of t)if(Tr[n]?.includes(e))return n;return null}i(Ce,"forbiddenGlobalForModuleSpecifier");function Hn(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),o=Nr[r];if(o)return o}return null}i(Hn,"capabilityForAmbientName");function lt(e){if(e?.pure===!0)return[..._r].sort();let n=(e?.capabilities?.deny??[]).filter(r=>_r.includes(r));return[...new Set(n)].sort()}i(lt,"effectiveCapabilityDeny");function Dt(e,t){if(t.length===0)return!1;let n=new Set(t),r=e.split(".");for(let o=r.length;o>=1;o-=1)if(n.has(r.slice(0,o).join(".")))return!0;return!1}i(Dt,"ambientCoveredByForbiddenGlobals");function Gn(e){let t=new Set,n=new Set,r=Object.keys(Nr);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 Tr[o]??[])t.add(`import-exact:${a}`)}for(let o of lt(e)){if(t.add(`import:${o}`),o==="process")for(let s of Tr.process)t.add(`import-exact:${s}`);for(let s of r)Hn(s)===o&&t.add(`ambient:${s}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}i(Gn,"loweredLayerCoverage");function ct(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(ct,"literalText");function Ks(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}i(Ks,"lineOf");function Ms(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(Ms,"isTypeOnlyReference");function Hs(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(Hs,"singleFileChecker");function Lr(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}i(Lr,"symbolAt");function Fr(e,t,n,r){let o=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,s;try{s=o?t.getShorthandAssignmentValueSymbol(r.parent):Lr(t,r)}catch{s=void 0}return!!s?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}i(Fr,"localDeclaration");function dt(e,t){let n,r=[],o=i((a,l,c,p=!1)=>r.push({specifier:c,kind:l,line:Ks(t,a),typeOnly:p,unresolved:c===void 0,node:a}),"add"),s=i(a=>{if(e.isImportDeclaration(a))o(a,"import",ct(e,a.moduleSpecifier),Ms(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)o(a,"export",ct(e,a.moduleSpecifier),Ms(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))o(a,"require",ct(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let l=a.expression.kind===e.SyntaxKind.ImportKeyword,p=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!Fr(e,n??(n=Hs(e,t)),t,a.expression);(l||p)&&o(a,p?"require":"dynamic-import",ct(e,a.arguments[0]))}e.forEachChild(a,s)},"visit");return s(t),r}i(dt,"extractSemanticDependencies");function yl(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let o=ct(e,r.argumentExpression);if(o===void 0)return;n.unshift(o)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}i(yl,"staticAccessPath");function hl(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(hl,"runtimeIdentifierReference");function $s(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($s,"bestForbiddenMatch");function ut(e,t,n){if(n.length===0)return[];let r=new Set(n),o=Hs(e,t),s=new Map,a=new Set;for(let u of t.statements)if(e.isVariableStatement(u))for(let g of u.declarationList.declarations)e.isIdentifier(g.name)&&a.add(g.name.text);let l=i(u=>{let g=yl(e,u);if(!g)return;let d=Lr(o,g.root),m=d?s.get(d):void 0;return m?[...m,...g.segments.slice(1)]:Fr(e,o,t,g.root)||a.has(g.root.text)?void 0:g.segments},"resolvePath");for(let u of t.statements)if(e.isVariableStatement(u))for(let g of u.declarationList.declarations){if(!g.initializer||!e.isIdentifier(g.name))continue;let d=l(g.initializer),m=Lr(o,g.name);!d||!m||s.set(m,d)}let c=[],p=new Set,f=i((u,g)=>{let d=Ks(t,g),m=`${u}:${g.getStart(t)}`;p.has(m)||(p.add(m),c.push({name:u,line:d,node:g}))},"flag"),y=i(u=>{let g=u.parent&&(e.isPropertyAccessExpression(u.parent)||e.isElementAccessExpression(u.parent))&&u.parent.expression===u;if((e.isPropertyAccessExpression(u)||e.isElementAccessExpression(u))&&!g){let d=l(u),m=d?$s(r,d):void 0;m&&f(m,u)}else e.isIdentifier(u)&&r.has(u.text)&&hl(e,u)&&!Fr(e,o,t,u)&&f(u.text,u);if(e.isVariableDeclaration(u)&&e.isObjectBindingPattern(u.name)&&u.initializer){let d=l(u.initializer);if(d)for(let m of u.name.elements){if(!e.isIdentifier(m.name))continue;let E=m.propertyName?ct(e,m.propertyName)??m.propertyName.text:m.name.text,S=$s(r,[...d,E]);S&&f(S,u.initializer)}}e.forEachChild(u,y)},"visit");return y(t),c}i(ut,"collectForbiddenCapabilityUses");function Mr(e,t,n){let r=[];for(let o of n?.dependencies??dt(e,t)){if(o.typeOnly||!o.specifier)continue;let s=Nt(o.specifier);s&&r.push({capability:s,symbol:o.specifier,line:o.line,source:"import-based"})}for(let o of n?.ambientUses??ut(e,t,Dr)){let s=Hn(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(Mr,"collectCapabilityUses");var $r={RAW_EVENT_PUBLISH:"Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts and tooling.",PUBLISH_MISSING_SOURCE:"Strict Ark publish calls must include metadata.source."},Kr=Object.freeze([{layer:"DomainModel",prefixes:["Domain."]},{layer:"ApplicationOrchestration",prefixes:["Application."]},{layer:"PersistenceAdapters",prefixes:["Adapter.Persistence.","Adapter.Repository."]},{layer:"IntegrationAdapters",prefixes:["Adapter.Integration.","Adapter.External."]},{layer:"WorkflowSagaEngine",prefixes:["Workflow."]},{layer:"BackgroundJobsScheduling",prefixes:["Job."]},{layer:"PresentationAdapters",prefixes:["Presentation.","Adapter.Presentation.","Adapter.Api."]},{layer:"ReportingReadModels",prefixes:["Reporting."]},{layer:"ExtensibilityMetadata",prefixes:["Metadata."]},{layer:"SecurityAuditObservability",prefixes:["Security.","Audit.","Observability."]},{layer:"Kernel",prefixes:["Kernel."]}]);function Hr(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(Hr,"resolveIntentLayer");function Ke(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}i(Ke,"looksLikeArkIntent");function Lt(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&Ke(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:$r.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:$r.PUBLISH_MISSING_SOURCE}),t}i(Lt,"classifyPublishFacts");function j(e,t,n){return{ruleId:e,code:e,message:t,...n}}i(j,"violation");function pt(e,t){return e.slice(0,t).split(`
|
|
22
|
-
`).length}i(pt,"lineOf");var Rl=new Set(["publish","subscribe","defineIntent","registerHandler"]);function Al(e,t){return e.index+e[0].indexOf(t)}i(Al,"captureIndex");function kl(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 p=c[1];p&&r(p,Al(c,p))}},"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),p=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,f;for(;(f=p.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(kl,"extractQuotedStrings");function Il(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(Il,"extractModuleSpecifiers");function bl(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(bl,"isSyntaxWrapper");function Gr(e,t){let n=t;for(;n?.parent&&bl(e,n.parent);)n=n.parent;return n}i(Gr,"unwrapWrappers");function Ur(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(Ur,"callCalleeName");function vl(e,t){let n=t.parent;if(!n||!e.isObjectLiteralExpression(n))return!1;let r=Gr(e,n),o=r.parent;if(!o)return!1;if(e.isCallExpression(o)&&Ur(e,o)==="publish"){let s=o.arguments;return s[1]===r||s[2]===r}if(e.isPropertyAssignment(o)&&Vr(e,o.name)==="metadata"){let s=o.parent;if(!s)return!1;let l=Gr(e,s).parent;return!!(l&&e.isCallExpression(l)&&Ur(e,l)==="publish")}return!1}i(vl,"isPublishMetadataSource");function Gs(e,t){let n=Gr(e,t),r=n.parent;if(!r)return!1;if(e.isCallExpression(r)){let o=Ur(e,r);if(o&&Rl.has(o)&&r.arguments.some(s=>s===n))return!0}if(e.isArrayLiteralExpression(r))return Gs(e,r);if(e.isPropertyAssignment(r)){let o=Vr(e,r.name);if(o==="intent"||o==="onEvent"||o==="reactsTo"||o==="source"&&vl(e,r))return!0}return!1}i(Gs,"isDeclaredIntentSite");function El(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],o=i(s=>{e.isStringLiteralLike(s)&&Gs(e,s)&&r.push({value:s.text,index:s.getStart(n)}),e.forEachChild(s,o)},"visit");return o(n),r}i(El,"extractQuotedStringsAst");function Sl(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(Sl,"hasInfrastructureToken");function wl(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}i(wl,"isKnownInfrastructurePackage");function Cl(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}i(Cl,"layerHasInfrastructureRole");function Mt(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(Mt,"tsStringLiteralText");function Vr(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}i(Vr,"tsPropertyName");function Us(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:Vr(e,r.name)===n)}i(Us,"tsObjectProperty");function $t(e,t,n){return Us(e,t,n)!==void 0}i($t,"tsObjectHasProperty");function Ft(e,t,n){let r=Us(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}i(Ft,"tsObjectPropertyValue");function xl(e,t){let n=Ft(e,t,"metadata");return $t(e,n,"source")}i(xl,"tsObjectHasMetadataSource");function Vs(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?Vs(e,t.name):!1:!1}i(Vs,"tsLooksLikeIntentCreatorExpression");function Ol(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(Ol,"tsIsPublishCall");function Pl(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=Mt(e,n);return r!==void 0&&Ke(r)||$t(e,n,"intent")||Vs(e,n)}i(Pl,"tsIsArkPublishCandidate");function _l(e,t){if(!e.isCallExpression(t))return!1;let[n,r,o]=t.arguments;return xl(e,n)||$t(e,r,"source")||$t(e,o,"source")}i(_l,"tsPublishHasSource");function Tl(e,t){if(!e.isCallExpression(t))return;let[n,r,o]=t.arguments,s=Ft(e,n,"metadata");return Mt(e,Ft(e,s,"source"))??Mt(e,Ft(e,r,"source"))??Mt(e,Ft(e,o,"source"))}i(Tl,"tsPublishSourceLiteral");function Nl(e,t,n,r){let o=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),s=n,a=s?.filePath,l=s?.layer,c=[],p=i(y=>o.getLineAndCharacterOfPosition(y.getStart(o)).line+1,"lineForNode"),f=i(y=>{if(Ol(e,y)){let u=y.arguments[0],g=Mt(e,u);for(let m of Lt({publishCall:!0,rawIntentName:g,objectHasIntent:$t(e,u,"intent"),arkPublishCandidate:Pl(e,y),hasSource:_l(e,y)}))c.push(j(m.ruleId,m.message,{line:p(y),filePath:a}));let d=Tl(e,y);if(r&&l&&d&&Ke(d)){let m=r.resolveLayer(d);m&&m!==l&&c.push(j("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${d}" resolves to ${m}, but the target file is classified as ${l}.`,{line:p(y),filePath:a,target:d,fromLayer:l,toLayer:m}))}}e.forEachChild(y,f)},"visit");return f(o),c}i(Nl,"analyzePublishAst");function js(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,p=c?.filePath,f=c?.layer,y=e.typescript,u=y?y.createSourceFile(p??"generated.ts",s,y.ScriptTarget.Latest,!0):void 0,g=u?dt(e.typescript,u):void 0,d=g?g.filter(k=>k.specifier!==void 0).map(k=>({value:k.specifier,index:k.node.getStart(u),kind:k.kind,typeOnly:k.typeOnly})):Il(s),m=e.typescript?El(e.typescript,s):kl(s);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(p))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:p}))}let E=f!==void 0&&(r.has(f)||Cl(f)),S=f!==void 0?` If "${f}" is an infrastructure layer, mark it in ark.config.json with "mayImportInfrastructure": true (or name it with an infra token like Adapters/Persistence/Repository).`:"";for(let k of n)if(k instanceof RegExp){k.lastIndex=0;let v=k.exec(s);k.lastIndex=0,v&&l.push(j("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${k}`,{line:v.index===void 0?void 0:pt(s,v.index),filePath:p,suggestion:"Remove infrastructure imports from domain/application layers."+S}))}else s.includes(k)&&l.push(j("FORBIDDEN_SUBSTRING",`Forbidden substring: ${k}`,{line:pt(s,s.indexOf(k)),filePath:p}));for(let k of d){let v=e.resolveImportTarget?.(k.value,p)??(e.resolveImportLayer?{layer:e.resolveImportLayer(k.value,p)}:void 0),x=typeof p=="string"?e.resolveImportTarget?.(p)??(e.resolveImportLayer?{layer:f,relPath:void 0}:void 0):void 0,N=v?.layer;if(N&&f){let b=ot(e.architectureProfile?.rules,f,N,{fromPath:x?.relPath,toPath:v?.relPath,layers:e.architectureLayers});if(b){if(k.typeOnly&&!b.peerIsolation)continue;let T=!!b.peerIsolation;l.push(j("LAYER_IMPORT_VIOLATION",b.message??(T?`Layer "${f}" must not import across slices into "${N}".`:`Layer "${f}" must not import "${N}".`),{line:pt(s,k.index),source:k.value,target:k.value,filePath:p,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||!Sl(k.value)&&!wl(k.value)||l.push(j("FORBIDDEN_IMPORT",`Forbidden ${k.kind} target: "${k.value}".`,{line:pt(s,k.index),source:k.value,target:k.value,filePath:p,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 x of v)l.push(j("POLICY_VIOLATION",x.message,{filePath:p,suggestion:`Fix violation of policy "${k.name}".`}));else v===!1?l.push(j("POLICY_VIOLATION",`Policy ${k.name} failed on generated code`)):l.push(j("POLICY_VIOLATION",v.message))}if(o&&t.size>0)for(let k of m)Ke(k.value)&&!t.has(k.value)&&l.push(j("UNKNOWN_INTENT",`Unknown intent reference: "${k.value}"`,{line:pt(s,k.index),filePath:p,target:k.value,suggestion:`Register intent "${k.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&f)for(let k of m){if(!Ke(k.value))continue;let v=e.architectureProfile.resolveLayer(k.value);if(!v)continue;let x=Fe(e.architectureProfile.rules,f,v,{fromPath:typeof p=="string"?p:void 0,layers:e.architectureLayers});if(x){let N=x.rule.peerIsolation?rt(x.peerIsolationReason??"cross-slice",{fromPath:typeof p=="string"?p:void 0,fromSlice:x.fromSlice,toSlice:x.toSlice}):void 0,b=`Layer "${f}" must not reference "${v}" through "${k.value}".`,T=N&&x.peerIsolationReason!=="cross-slice"?`${b} ${N}`:x.rule.message?N?`${x.rule.message} (${N})`:x.rule.message:b;l.push(j("LAYER_REFERENCE_VIOLATION",T,{line:pt(s,k.index),filePath:p,target:k.value,fromLayer:f,toLayer:v,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:x.rule,peerIsolationReason:x.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&&u&&f&&e.forbiddenGlobals?.[f]?.length)try{let k=e.forbiddenGlobals[f];l.push(...ut(e.typescript,u,k).map(v=>j("FORBIDDEN_GLOBAL",`${f} must not use the ambient global "${v.name}".`,{line:v.line,filePath:p,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 x=Ce(v.specifier,k);x&&l.push(j("FORBIDDEN_GLOBAL",`${f} must not use module "${v.specifier}" because it is the import form of forbidden global "${x}".`,{line:v.line,filePath:p,source:v.specifier,target:v.specifier,fromLayer:f,details:{importKind:v.kind,forbiddenGlobal:x},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&&u&&f&&e.capabilityWalls?.[f]?.length)try{let k=new Set(e.capabilityWalls[f]),v=e.forbiddenGlobals?.[f]??[];for(let x of Mr(e.typescript,u))k.has(x.capability)&&(x.source==="ambient-global"&&Dt(x.symbol,v)||x.source==="import-based"&&Ce(x.symbol,v)||l.push(j("CAPABILITY_VIOLATION",x.source==="import-based"?`${f} denies the ${x.capability} capability; found import of "${x.symbol}".`:`${f} denies the ${x.capability} capability; found ambient "${x.symbol}".`,{line:x.line,filePath:p,target:x.symbol,capability:x.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(...Nl(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(js,"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 He="1.2";var Bs=["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 q(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}i(q,"sortedUnique");function Kt(e){let t={schemaVersion:"1.2",include:q(e.include??[]),exclude:q(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:q(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:q(n.patterns??[]),exclude:q(n.exclude??[]),forbiddenGlobals:q(n.forbiddenGlobals??[]),intentPrefixes:q(n.intentPrefixes??[]),capabilityDeny:q(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:q(e.arkRun.compositionRoots),managedLayers:q(e.arkRun.managedLayers),requireDeclarations:e.arkRun.requireDeclarations===!0}}:{}};return z($(t))}i(Kt,"resolvedFactsEvidenceRequirementsHash");function Dl(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:q(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:q(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),p=(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),u=(e.arkRunCompositionRootHits??[]).map(b=>({...b})).sort(B),g=(e.arkRunDeclarations??[]).map(b=>({...b,uses:q(b.uses),reactsTo:q(b.reactsTo),raises:q(b.raises),sends:q(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),x=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($(x));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:p,arkRunKernelCalls:f,arkRunManagedNews:y,arkRunCompositionRootHits:u,arkRunDeclarations:g,arkOrderPlaneCalls:d,arkOrderGenericUpdates:m,arkOrderRootHits:E,arkOrderXiFieldWrites:S,arkOrderIngestWritesXi:k,arkOrderReleaseKeyCounts:v}}i(Dl,"canonicalResolvedFactsInput");function Ws(e){let t=Dl(e);return{...t,factsHash:z($(t))}}i(Ws,"createCanonicalResolvedCandidateFacts");function jr(e){return Ws(qs(M(e,"$"),!1))}i(jr,"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 K(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(K,"assertOnlyKeys");function F(e,t,n){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`${n}.${t} must be a non-empty string.`);return r}i(F,"requiredText");function Re(e,t,n){if(e[t]!==void 0)return F(e,t,n)}i(Re,"optionalText");function H(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(H,"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 zs(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(zs,"requiredInteger");function X(e,t,n){let r=zs(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}i(X,"requiredPositiveInteger");function U(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}i(U,"requiredArray");function Ae(e,t,n,r){let o=e[t];if(typeof o!="string"||!n.includes(o))throw new Error(`${r}.${t} must be one of ${n.join(", ")}.`);return o}i(Ae,"enumValue");function ft(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!n))throw new Error(`${t} must be an array of non-empty strings.`);return[...e]}i(ft,"parseStringArray");function Ll(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(Ll,"assertUnique");function qs(e,t){K(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","classShapes","arkRunKernelCalls","arkRunManagedNews","arkRunCompositionRootHits","arkRunDeclarations","arkOrderPlaneCalls","arkOrderGenericUpdates","arkOrderRootHits","arkOrderXiFieldWrites","arkOrderIngestWritesXi","arkOrderReleaseKeyCounts",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=Ae(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=Ae(e,"completeness",["complete","partial","unavailable"],"$"),o=U(e,"completenessReasons","$").map((w,C)=>{let h=`$.completenessReasons[${C}]`,A=M(w,h);K(A,["code","message","file"],h);let L=A.file===void 0?void 0:H(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,C)=>{let h=`$.files[${C}]`,A=M(w,h);return K(A,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],h),{path:H(A,"path",h),contentHash:F(A,"contentHash",h),parseStatus:Ae(A,"parseStatus",["parsed","invalid"],h),parseDiagnosticCount:zs(A,"parseDiagnosticCount",h),exportsOnlyTypes:G(A,"exportsOnlyTypes",h),typeOnlyExportNames:ft(A.typeOnlyExportNames,`${h}.typeOnlyExportNames`),hasTopLevelSideEffects:G(A,"hasTopLevelSideEffects",h)}}),a=U(e,"dependencies","$").map((w,C)=>{let h=`$.dependencies[${C}]`,A=M(w,h);K(A,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],h);let L=Re(A,"specifier",h),W=Re(A,"target",h),Ee=Ae(A,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],h);if(Ee==="resolved-project"&&!W)throw new Error(`${h}.target is required for resolved-project dependencies.`);if(Ee!=="resolved-project"&&W)throw new Error(`${h}.target is only allowed for resolved-project dependencies.`);if(Ee!=="dynamic"&&!L)throw new Error(`${h}.specifier is required unless resolution is dynamic.`);return{from:H(A,"from",h),...L?{specifier:L}:{},kind:Ae(A,"kind",["import","export","dynamic-import","require"],h),typeOnly:G(A,"typeOnly",h),line:X(A,"line",h),resolution:Ee,...W?{target:H(A,"target",h)}:{},...A.namedBindings!==void 0?{namedBindings:ft(A.namedBindings,`${h}.namedBindings`)}:{},...A.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:G(A,"targetTypeOnlyExports",h)}:{},...A.sourcePureTypeModule!==void 0?{sourcePureTypeModule:G(A,"sourcePureTypeModule",h)}:{},...A.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:G(A,"namedBindingsTypeOnly",h)}:{},...A.portProofEligible!==void 0?{portProofEligible:G(A,"portProofEligible",h)}:{}}}),l=U(e,"capabilityUses","$").map((w,C)=>{let h=`$.capabilityUses[${C}]`,A=M(w,h);return K(A,["file","line","symbol","capability","source"],h),{file:H(A,"file",h),line:X(A,"line",h),symbol:F(A,"symbol",h),capability:Ae(A,"capability",Bs,h),source:Ae(A,"source",["ambient-global","import-based"],h)}}),c=U(e,"ambientUses","$").map((w,C)=>{let h=`$.ambientUses[${C}]`,A=M(w,h);return K(A,["file","line","symbol"],h),{file:H(A,"file",h),line:X(A,"line",h),symbol:F(A,"symbol",h)}}),p=U(e,"publishCalls","$").map((w,C)=>{let h=`$.publishCalls[${C}]`,A=M(w,h);K(A,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],h);let L=Re(A,"rawIntentName",h),W=Re(A,"sourceIntent",h);return{file:H(A,"file",h),line:X(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,C)=>{let h=`$.intentReferences[${C}]`,A=M(w,h);return K(A,["file","line","intent"],h),{file:H(A,"file",h),line:X(A,"line",h),intent:F(A,"intent",h)}}),y=U(e,"safetyUses","$").map((w,C)=>{let h=`$.safetyUses[${C}]`,A=M(w,h);K(A,["file","line","kind","symbol"],h);let L=Re(A,"symbol",h),W=Ae(A,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],h);if(W==="in-memory-store"&&!L)throw new Error(`${h}.symbol is required for in-memory-store facts.`);if(W!=="in-memory-store"&&L)throw new Error(`${h}.symbol is only allowed for in-memory-store facts.`);return{file:H(A,"file",h),line:X(A,"line",h),kind:W,...L?{symbol:L}:{}}});Ll(s,w=>w.path,"$.files");let u=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(!u.has(w.from))throw new Error(`$.dependencies references missing source file ${w.from}.`);let d=(e.arkRunKernelCalls===void 0?[]:U(e,"arkRunKernelCalls","$")).map((w,C)=>{let h=`$.arkRunKernelCalls[${C}]`,A=M(w,h);K(A,["file","line","kind","callee","viaImport","receiver","nameLiteral"],h);let L=Re(A,"receiver",h),W=Re(A,"nameLiteral",h);return{file:H(A,"file",h),line:X(A,"line",h),kind:Ae(A,"kind",["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"],h),callee:F(A,"callee",h),viaImport:G(A,"viaImport",h),...L?{receiver:L}:{},...W?{nameLiteral:W}:{}}}),E=(e.arkRunManagedNews===void 0?[]:U(e,"arkRunManagedNews","$")).map((w,C)=>{let h=`$.arkRunManagedNews[${C}]`,A=M(w,h);K(A,["file","line","typeName","importedFrom"],h);let L=Re(A,"importedFrom",h);return{file:H(A,"file",h),line:X(A,"line",h),typeName:F(A,"typeName",h),...L?{importedFrom:L}:{}}}),k=(e.arkRunCompositionRootHits===void 0?[]:U(e,"arkRunCompositionRootHits","$")).map((w,C)=>{let h=`$.arkRunCompositionRootHits[${C}]`,A=M(w,h);return K(A,["file","matchedRoot","hasKernelFactory"],h),{file:H(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,C)=>{let h=`$.arkOrderPlaneCalls[${C}]`,A=M(w,h);return K(A,["file","line","callee"],h),{file:H(A,"file",h),line:X(A,"line",h),callee:F(A,"callee",h)}}),T=(e.arkOrderGenericUpdates===void 0?[]:U(e,"arkOrderGenericUpdates","$")).map((w,C)=>{let h=`$.arkOrderGenericUpdates[${C}]`,A=M(w,h);return K(A,["file","line","method"],h),{file:H(A,"file",h),line:X(A,"line",h),method:F(A,"method",h)}}),me=(e.arkOrderRootHits===void 0?[]:U(e,"arkOrderRootHits","$")).map((w,C)=>{let h=`$.arkOrderRootHits[${C}]`,A=M(w,h);return K(A,["file","matchedRoot","hasPlaneFactory"],h),{file:H(A,"file",h),matchedRoot:F(A,"matchedRoot",h),hasPlaneFactory:G(A,"hasPlaneFactory",h)}}),D=(e.arkOrderXiFieldWrites===void 0?[]:U(e,"arkOrderXiFieldWrites","$")).map((w,C)=>{let h=`$.arkOrderXiFieldWrites[${C}]`,A=M(w,h);return K(A,["file","line","key"],h),{file:H(A,"file",h),line:X(A,"line",h),key:F(A,"key",h)}}),J=(e.arkOrderIngestWritesXi===void 0?[]:U(e,"arkOrderIngestWritesXi","$")).map((w,C)=>{let h=`$.arkOrderIngestWritesXi[${C}]`,A=M(w,h);return K(A,["file","line"],h),{file:H(A,"file",h),line:X(A,"line",h)}}),ve=(e.arkOrderReleaseKeyCounts===void 0?[]:U(e,"arkOrderReleaseKeyCounts","$")).map((w,C)=>{let h=`$.arkOrderReleaseKeyCounts[${C}]`,A=M(w,h);return K(A,["file","line","keyCount"],h),{file:H(A,"file",h),line:X(A,"line",h),keyCount:X(A,"keyCount",h)}}),bt=v.map((w,C)=>{let h=`$.arkRunDeclarations[${C}]`,A=M(w,h);return K(A,["file","line","uses","reactsTo","raises","sends"],h),{file:H(A,"file",h),line:X(A,"line",h),uses:ft(A.uses,`${h}.uses`),reactsTo:ft(A.reactsTo,`${h}.reactsTo`),raises:ft(A.raises,`${h}.raises`),sends:ft(A.sends,`${h}.sends`)}});for(let[w,C]of[["$.capabilityUses",l],["$.ambientUses",c],["$.publishCalls",p],["$.intentReferences",f],["$.safetyUses",y],["$.arkRunKernelCalls",d],["$.arkRunManagedNews",E],["$.arkRunCompositionRootHits",k],["$.arkRunDeclarations",bt],["$.arkOrderPlaneCalls",N],["$.arkOrderGenericUpdates",T],["$.arkOrderRootHits",me],["$.arkOrderXiFieldWrites",D],["$.arkOrderIngestWritesXi",J],["$.arkOrderReleaseKeyCounts",ve]])for(let h of C)if(!u.has(h.file))throw new Error(`${w} references missing file ${h.file}.`);let fn=Re(e,"projectPackageName","$"),Lo=(e.classShapes===void 0?[]:U(e,"classShapes","$")).map((w,C)=>{let h=`$.classShapes[${C}]`,A=M(w,h);K(A,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],h);let L=U(A,"mutatingMethods",h).map((W,Ee)=>{let R=`${h}.mutatingMethods[${Ee}]`,Q=M(W,R);return K(Q,["name","referencesGuardOrPublish"],R),{name:F(Q,"name",R),referencesGuardOrPublish:G(Q,"referencesGuardOrPublish",R)}});return{file:H(A,"file",h),className:F(A,"className",h),exported:G(A,"exported",h),hasPublicMutableFields:G(A,"hasPublicMutableFields",h),hasPublicSetters:G(A,"hasPublicSetters",h),hasPublicConstructor:G(A,"hasPublicConstructor",h),hasStaticFactory:G(A,"hasStaticFactory",h),mutatingMethods:L,...A.dataOnly===void 0?{}:{dataOnly:G(A,"dataOnly",h)}}});return{schemaVersion:n,completeness:r,completenessReasons:o,resolverIdentity:F(e,"resolverIdentity","$"),compilerIdentity:F(e,"compilerIdentity","$"),compilerOptionsHash:F(e,"compilerOptionsHash","$"),tsconfigHash:F(e,"tsconfigHash","$"),evidenceRequirementsHash:F(e,"evidenceRequirementsHash","$"),...fn?{projectPackageName:fn}:{},files:s,dependencies:a,capabilityUses:l,ambientUses:c,publishCalls:p,intentReferences:f,safetyUses:y,classShapes:Lo,arkRunKernelCalls:d,arkRunManagedNews:E,arkRunCompositionRootHits:k,arkRunDeclarations:bt,arkOrderPlaneCalls:N,arkOrderGenericUpdates:T,arkOrderRootHits:me,arkOrderXiFieldWrites:D,arkOrderIngestWritesXi:J,arkOrderReleaseKeyCounts:ve}}i(qs,"parseResolvedFactsInput");function xe(e){let t=M(e,"$"),n=F(t,"factsHash","$"),r=F(t,"candidateTreeHash","$"),o=Ws(qs(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(xe,"loadResolvedCandidateFacts");var Fl=["network","filesystem","clock","randomness","environment","process","persistence"],P={type:"string",minLength:1},ee={type:"integer",minimum:1},V={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},Br={$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:P,message:P,file:V}}},resolverIdentity:P,compilerIdentity:P,compilerOptionsHash:P,tsconfigHash:P,candidateTreeHash:P,evidenceRequirementsHash:P,projectPackageName:P,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:V,contentHash:P,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:P},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:P,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:ee,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:V,namedBindings:{type:"array",items:P},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:ee,symbol:P,capability:{enum:Fl},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:V,line:ee,symbol:P}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:V,line:ee,rawIntentName:P,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:P}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:V,line:ee,intent:P}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:V,line:ee,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:P},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:P,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:P,referencesGuardOrPublish:{type:"boolean"}}}}}}},arkRunKernelCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind","callee","viaImport"],properties:{file:V,line:ee,kind:{enum:["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"]},callee:P,viaImport:{type:"boolean"},receiver:P,nameLiteral:P}}},arkRunManagedNews:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","typeName"],properties:{file:V,line:ee,typeName:P,importedFrom:P}}},arkRunCompositionRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasKernelFactory"],properties:{file:V,matchedRoot:P,hasKernelFactory:{type:"boolean"}}}},arkRunDeclarations:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","uses","reactsTo","raises","sends"],properties:{file:V,line:ee,uses:{type:"array",items:P},reactsTo:{type:"array",items:P},raises:{type:"array",items:P},sends:{type:"array",items:P}}}},arkOrderPlaneCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","callee"],properties:{file:V,line:ee,callee:P}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:V,line:ee,method:P}}},arkOrderRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasPlaneFactory"],properties:{file:V,matchedRoot:P,hasPlaneFactory:{type:"boolean"}}}},arkOrderXiFieldWrites:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:V,line:ee,key:P}}},arkOrderIngestWritesXi:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line"],properties:{file:V,line:ee}}},arkOrderReleaseKeyCounts:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","keyCount"],properties:{file:V,line:ee,keyCount:{type:"integer",minimum:1}}}},factsHash:P},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 re(e){return`${e.from}->${e.to}`}i(re,"dependencyKey");function Ht(e,t,n,r="dependency"){return{id:`${e}:${r}:${re(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${re(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${re(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${re(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${re(t)} from the candidate, then preflight again.`}:{}}}i(Ht,"dependencyFinding");function gt(e){let t=[],n=new Map(e.changeMap.map.files.map(u=>[u.path,u])),r=new Map(e.changes.map(u=>[u.path,u])),o=new Map(e.changeMap.map.dependencies.map(u=>[re(u),u])),s=new Map(e.baseDependencies.map(u=>[re(u),u])),a=new Map(e.candidateDependencies.map(u=>[re(u),u]));for(let u of[...n.values()].sort((g,d)=>g.path.localeCompare(d.path))){let g=r.get(u.path);g?g.operation!==u.operation?t.push({id:`contradictory:file:${u.path}`,classification:"contradictory",subject:"file",path:u.path,expectedOperation:u.operation,actualOperation:g.operation,message:`${u.path} was planned as ${u.operation} but the actual operation is ${g.operation}.`,nextAction:`Change ${u.path} to the planned ${u.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${u.path}`,classification:"satisfied",subject:"file",path:u.path,expectedOperation:u.operation,actualOperation:g.operation,message:`${u.path} matches the planned ${u.operation} operation.`}):t.push({id:`missing:file:${u.path}`,classification:"missing",subject:"file",path:u.path,expectedOperation:u.operation,message:`${u.path} was planned as ${u.operation} but is absent from the actual change.`,nextAction:`${u.operation[0].toUpperCase()}${u.operation.slice(1)} ${u.path} in the complete change set, then preflight again.`})}for(let u of[...r.values()].sort((g,d)=>g.path.localeCompare(d.path)))n.has(u.path)||t.push({id:`unplanned:file:${u.path}`,classification:"unplanned",subject:"file",path:u.path,actualOperation:u.operation,message:`${u.path} has an unplanned ${u.operation} operation.`,nextAction:`Remove ${u.path} from the change set, then preflight again.`});let l=new Set;for(let u of[...o.values()].sort((g,d)=>re(g).localeCompare(re(d)))){if(a.has(re(u))){t.push(Ht("satisfied",u,`${u.from} -> ${u.to} exists in the candidate architecture.`));continue}let g={from:u.to,to:u.from};a.has(re(g))?(l.add(re(g)),t.push(Ht("contradictory",u,`${u.from} -> ${u.to} was planned, but the candidate contains the reverse edge.`))):t.push(Ht("missing",u,`${u.from} -> ${u.to} is absent from the candidate architecture.`))}let c=new Set([...n.keys(),...r.keys()]);for(let[u,g]of[...a].sort(([d],[m])=>d.localeCompare(m)))s.has(u)||o.has(u)||l.has(u)||!c.has(g.from)&&!c.has(g.to)||t.push({...Ht("unplanned",g,`${g.from} -> ${g.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let p=new Set(e.changeMap.map.files.filter(u=>u.operation==="delete").map(u=>u.path));for(let[u,g]of[...s].sort(([d],[m])=>d.localeCompare(m)))a.has(u)||p.has(g.from)||p.has(g.to)||!c.has(g.from)&&!c.has(g.to)||t.push({...Ht("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((u,g)=>f[u.classification]-f[g.classification]||(u.subject===g.subject?0:u.subject==="file"?-1:1)||u.id.localeCompare(g.id));let y={satisfied:t.filter(u=>u.classification==="satisfied").length,missing:t.filter(u=>u.classification==="missing").length,contradictory:t.filter(u=>u.classification==="contradictory").length,unplanned:t.filter(u=>u.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:y.missing===0&&y.contradictory===0&&y.unplanned===0,behavioralCompletion:"not-evaluated",summary:y,findings:t}}i(gt,"analyzeArchitectureConvergence");var Ys="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",Ml=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","writes-via-aggregate","no-anemic-model","invariant-coverage"];var Xs={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Og={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Ys,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:Ys},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:[...Ml]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:Xs,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:Xs}}}};function Gt(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}i(Gt,"emptyEffectiveArkRules");function zr(e){return{...e,layers:e.layers.map(t=>{let{description:n,trustBoundary:r,owners:o,...s}=t;return s})}}i(zr,"omitLayerDescriptions");function Zs(e){let{stewards:t,...n}=zr(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(Zs,"effectiveContractPolicyPayload");var $l="INVARIANT_TESTS_PATH_MISSING",Kl="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.",Hl="INVARIANT_COVERAGE_ROOTS_MISSING",Gl="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 Js(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(Js,"formatCoverageDiscards");function Ul(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(Ul,"isUnderCoverageRoot");function Vl(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*['"\`][^'"\`]*${n}[^'"\`]*['"\`]`,"i").test(e)||e.includes(t)}i(Vl,"titleMatchesInvariant");function jl(e,t){if(!t)return!1;let n=t.split("."),r=n[n.length-1],o=n.length>1?n[0]:null;for(let s of Object.values(e))if(!(o&&!s.includes(o))&&(new RegExp(`(?:function\\s+|\\b)${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[(<]`).test(s)||s.includes(t)))return!0;return!1}i(jl,"symbolPresent");function Qs(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=Js(s),l=Js(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",p=(e.coverageRoots??[]).filter(d=>typeof d=="string"&&d.length>0),f=p.length>0,y=p.join(", "),u=[],g=[];for(let d of t){let m=[],E=d.coverage?.test!==!1,S=d.coverage?.symbol,k,v;if(!r&&E){let T;for(let ie of n){let me=e.fileContents[ie];if(!(!me||!Vl(me,d.id))){if(!f||Ul(ie,p)){k=ie,v=f?!1:void 0;break}T??=ie}}k===void 0&&T!==void 0&&(k=T,v=!0),k!==void 0&&m.push("test-title")}S&&jl(e.fileContents,S)&&m.push("symbol");let N=(d.coverage?.test===!0||!!S||d.coverage===void 0)&&m.length>0||d.coverage?.test===!1&&!S?!0:m.length>0,b=r&&E&&m.length===0;if(u.push({invariantId:d.id,layer:d.provenance.layer,sourceFile:d.provenance.sourceFile,mode:d.mode,covered:N&&!b,evidence:m,partial:b,description:d.description,...k!==void 0?{testEvidenceFile:k}:{},...v!==void 0?{outsideDeclaredRoots:v}:{},coverageRootsDeclared:f}),v===!0&&k!==void 0&&g.push({ruleId:"INVARIANT_COVERAGE_OUTSIDE_ROOTS",message:`Invariant ${d.id} is covered only by ${k}, 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:k,line:1,arkruleId:d.id,arkruleSource:d.provenance.sourceFile,fromLayer:d.provenance.layer,severity:"warning",failsStrict:!1}),!N||b){let T=d.mode==="enforced"&&!b,ie=r||n.length===0?"never-had-tests":"tests-disappeared";g.push({ruleId:"INVARIANT_UNCOVERED",message:(b?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).`:ie==="tests-disappeared"?`Invariant ${d.id}: no scanned test names it in a describe/it title and no declared symbol was found (tests-disappeared \u2014 a suite exists). ArkGate matches declared text; it never executes tests.`:`Invariant ${d.id}: no scanned test names it in a describe/it title and no declared symbol was found (never-had-tests \u2014 the scan found no tests at all). ArkGate matches declared text; it never executes tests.`)+(b&&o?l:a),file:d.provenance.sourceFile,line:1,arkruleId:d.id,arkruleSource:d.provenance.sourceFile,fromLayer:d.provenance.layer,severity:T?"error":"warning",failsStrict:T,kind:ie})}}return{coverage:u,violations:g,partial:u.some(d=>d.partial)}}i(Qs,"evaluateInvariantCoverage");function ei(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(ei,"canPromoteInvariant");function qr(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(qr,"nonEmptyPathStrings");function Bl(e){return!e||typeof e!="object"?[]:[...qr(e.testGlobs),...qr(e.coverageRoots)]}i(Bl,"configuredInvariantTestsPaths");function Wl(e){return Bl(e).length>0}i(Wl,"hasConfiguredInvariantTestsPath");function Yr(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.coverage?.test!==!1)}i(Yr,"catalogDemandsInvariantTestsPath");function ti(e){let t=e.hasDomainInvariants===!0||e.hasDomainInvariants!==!1&&Yr(e.invariants);return e.adopted!==!0||!t?[]:Wl(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:$l,message:Kl,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]}i(ti,"collectMissingInvariantTestsPathFindings");function zl(e){return!e||typeof e!="object"?[]:qr(e.coverageRoots)}i(zl,"configuredCoverageRoots");function ql(e){return zl(e).length>0}i(ql,"hasConfiguredCoverageRoots");function Xr(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.mode==="enforced")}i(Xr,"catalogHasEnforcedInvariant");function ni(e){return e.hasEnforcedInvariant===!0||e.hasEnforcedInvariant!==!1&&Xr(e.invariants)?ql(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:Hl,message:Gl,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]:[]}i(ni,"collectMissingCoverageRootsFindings");var Qr="1.0";function _(e,t){e.push({id:`${t.classification}:${t.path}:${t.kind}`,path:t.path,classification:t.classification,message:t.message,...t.classification==="weakening"||t.classification==="judgment-required"?{nextAction:`Restore the previous protection at ${t.path}, then run ArkGate again.`}:{},...t.before===void 0?{}:{before:t.before},...t.after===void 0?{}:{after:t.after}})}i(_,"addFinding");function Y(e){return[...new Set(e??[])].sort()}i(Y,"sortedUnique");function ue(e,t,n,r,o){let s=Y(n),a=Y(r),l=new Set(s),c=new Set(a),p=a.filter(y=>!l.has(y)),f=s.filter(y=>!c.has(y));p.length===0&&f.length===0||(p.length>0&&_(e,{kind:"added",path:t,classification:o.added,message:o.addedMessage,before:s,after:a}),f.length>0&&_(e,{kind:"removed",path:t,classification:o.removed,message:o.removedMessage,before:s,after:a}))}i(ue,"compareStringSets");function Ut(e,t,n,r,o,s,a){if(n===r)return;_(e,{kind:r?"enabled":"disabled",path:t,classification:r?o:o==="strengthening"?"weakening":"strengthening",message:r?s:a,before:n,after:r})}i(Ut,"compareBoolean");function Un(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(Un,"keyed");function Yl(e,t,n){let r=Un(t,s=>s.name),o=Un(n,s=>s.name);(r.duplicates.length>0||o.duplicates.length>0)&&_(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){_(e,{kind:"layer-added",path:c,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:l});continue}if(a&&!l){_(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 p=Gn(a),f=Gn(l);ue(e,`${c}.forbiddenGlobals`,p.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`,p.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)."}),Y(a.intentPrefixes).join("\0")!==Y(l.intentPrefixes).join("\0")&&_(e,{kind:"intent-prefixes-changed",path:`${c}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:Y(a.intentPrefixes),after:Y(l.intentPrefixes)}),Ut(e,`${c}.mayImportInfrastructure`,a.mayImportInfrastructure===!0,l.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),Ut(e,`${c}.optional`,a.optional===!0,l.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active.")}}i(Yl,"compareLayers");function Xl(e,t,n){let r=i(a=>`${a.from}->${a.to}`,"keyOf"),o=Un(t,r),s=Un(n,r);(o.duplicates.length>0||s.duplicates.length>0)&&_(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),p=`$.rules[${a}]`;if(!l&&c){c.allowed===!1&&_(e,{kind:"deny-added",path:p,classification:"strengthening",message:"A denied dependency edge was added.",after:c});continue}if(l&&!c){l.allowed===!1&&_(e,{kind:"deny-removed",path:p,classification:"weakening",message:"A denied dependency edge was removed.",before:l});continue}if(!l||!c)continue;l.allowed!==c.allowed&&_(e,{kind:c.allowed?"deny-disabled":"deny-enabled",path:`${p}.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 u=l.from===l.to&&c.from===c.to;_(e,{kind:y?"peer-isolation-enabled":"peer-isolation-disabled",path:`${p}.peerIsolation`,classification:u?y?"strengthening":"weakening":"judgment-required",message:u?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})}Y(l.sliceFolders).join("\0")!==Y(c.sliceFolders).join("\0")&&_(e,{kind:"slice-folders-changed",path:`${p}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:Y(l.sliceFolders),after:Y(c.sliceFolders)}),!(!f&&!y)&&(oi(e,`${p}.sharedRoots`,"shared-roots",Y(l.sharedRoots),Y(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."),oi(e,`${p}.allowedCrossSlice`,"cross-slice-allowance",Y((l.allowedCrossSlice??[]).map(ri)),Y((c.allowedCrossSlice??[]).map(ri)),"Directed cross-slice edges are now allowed by declaration.","Directed cross-slice edges are no longer declared and deny again."))}}i(Xl,"compareRules");function ri(e){return JSON.stringify([e.from,e.to])}i(ri,"crossSliceKey");function oi(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)),p=l.length>0&&c.length>0;_(e,{kind:p?`${n}-changed`:l.length>0?`${n}-added`:`${n}-removed`,path:t,classification:p?"judgment-required":l.length>0?"weakening":"strengthening",message:p?`${s} Entries were added and removed in the same change.`:l.length>0?s:a,before:r,after:o})}i(oi,"compareDeclaredExceptions");function Zl(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&&_(e,{kind:l>a?"threshold-raised":"threshold-lowered",path:`$.safety.${s}`,classification:l>a?"weakening":"strengthening",message:l>a?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:a,after:l})}for(let s of["allowInMemory","allowDisabledPeerIsolation"])Ut(e,`$.safety.${s}`,r[s]===!0,o[s]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}i(Zl,"compareSafety");function Zr(e){return e.mode==="enforced"?"enforced":"advisory"}i(Zr,"arkRunMode");function Jr(e){return e.mode==="enforced"?"enforced":"advisory"}i(Jr,"arkOrderMode");function Jl(e,t,n){let r=t.arkOrder,o=n.arkOrder,s="$.arkOrder";if(!r&&!o)return;if(!r&&o){_(e,{kind:"arkorder-added",path:s,classification:"strengthening",message:`ArkOrder extra was added (${Jr(o)}).`,after:o});return}if(r&&!o){_(e,{kind:"arkorder-removed",path:s,classification:"weakening",message:"ArkOrder extra was removed.",before:r});return}if(!r||!o)return;let a=Jr(r),l=Jr(o);if(a!==l){let c=a==="advisory"&&l==="enforced";_(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(Jl,"compareArkOrder");function Ql(e,t,n){let r=t.arkRun,o=n.arkRun,s="$.arkRun";if(!r&&!o)return;if(!r&&o){_(e,{kind:"arkrun-added",path:s,classification:"strengthening",message:`ArkRun extra was added (${Zr(o)}).`,after:o});return}if(r&&!o){_(e,{kind:"arkrun-removed",path:s,classification:"weakening",message:"ArkRun extra was removed.",before:r});return}if(!r||!o)return;let a=Zr(r),l=Zr(o);if(a!==l){let c=a==="advisory"&&l==="enforced";_(e,{kind:c?"arkrun-promoted":"arkrun-demoted",path:`${s}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkRun extra was promoted to enforced.":"ArkRun extra was demoted to advisory.",before:a,after:l})}ue(e,`${s}.compositionRoots`,r.compositionRoots,o.compositionRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkRun composition roots are governed.",removedMessage:"ArkRun composition roots were removed and may skip the kernel."}),ue(e,`${s}.managedLayers`,r.managedLayers,o.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkRun.",removedMessage:"Layers were removed from ArkRun management."}),Ut(e,`${s}.requireDeclarations`,r.requireDeclarations!==!1,o.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}i(Ql,"compareArkRun");function ec(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(ec,"overallClassification");function si(e,t){return`${e}::${t}`}i(si,"ruleKey");function ii(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(si(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(si(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}i(ii,"indexEffectiveRules");function tc(e,t,n,r,o,s){let a=new Map((s??[]).map(u=>[u.invariantId,u])),l=t.arkRules??{},c=n.arkRules??{},p=[...new Set([...Object.keys(l),...Object.keys(c)])].sort();for(let u of p){let g=l[u],d=c[u],m=`$.arkRules[${u}]`;if(g===void 0&&d!==void 0){_(e,{kind:"arkrules-ref-added",path:m,classification:"strengthening",message:`ArkRules reference for layer ${u} was added.`,after:d});continue}if(g!==void 0&&d===void 0){_(e,{kind:"arkrules-ref-removed",path:m,classification:"weakening",message:`ArkRules reference for layer ${u} was removed.`,before:g});continue}g!==d&&_(e,{kind:"arkrules-ref-path-changed",path:m,classification:"judgment-required",message:`ArkRules file path for layer ${u} changed; verify the effective rules still match intent.`,before:g,after:d})}let f=ii(r),y=ii(o);for(let u of[...new Set([...f.structure.keys(),...y.structure.keys()])].sort()){let g=f.structure.get(u),d=y.structure.get(u),m=`$.arkRules.structure[${u}]`;if(!g&&d){_(e,{kind:"arkrule-structure-added",path:m,classification:"strengthening",message:`Structure ArkRule ${d.id} was added (${d.mode}).`,after:d});continue}if(g&&!d){_(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";_(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&&_(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 u of[...new Set([...f.invariants.keys(),...y.invariants.keys()])].sort()){let g=f.invariants.get(u),d=y.invariants.get(u),m=`$.arkRules.invariants[${u}]`;if(!g&&d){_(e,{kind:"arkrule-invariant-added",path:m,classification:"strengthening",message:`Invariant ${d.id} was added (${d.mode}).`,after:d});continue}if(g&&!d){_(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=ei(S);k.ok?_(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}):_(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 _(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(tc,"compareArkRules");function eo(e,t,n){let r=[];ue(r,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),ue(r,"$.exclude",e.exclude,t.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional project paths are excluded from governance.",removedMessage:"Fewer project paths are excluded from governance."}),ue(r,"$.dynamicImportAllowlist",e.dynamicImportAllowlist,t.dynamicImportAllowlist,{added:"weakening",removed:"strengthening",addedMessage:"Additional files may use non-literal dynamic imports.",removedMessage:"Fewer files may use non-literal dynamic imports."}),Ut(r,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let o={off:0,soft:1,"framework-soft":1,strict:2},s=e.cyclePolicy??"strict",a=t.cyclePolicy??"strict";if(s!==a){let l=o[a]===o[s]?"judgment-required":o[a]>o[s]?"strengthening":"weakening";_(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)&&_(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}),Yl(r,e.layers,t.layers),Xl(r,e.rules,t.rules),Zl(r,e,t),tc(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),Ql(r,e,t),Jl(r,e,t),r.sort((l,c)=>l.path.localeCompare(c.path)||l.id.localeCompare(c.id)),{schemaVersion:Qr,classification:ec(r),findings:r}}i(eo,"classifyArkPolicyDelta");function to(e,t){if(!e||e.schemaVersion!==Qr||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=Y(e.findingIds),r=Y(t.findingIds);return n.length===r.length&&n.every((o,s)=>o===r[s])}i(to,"policyDeltaAcknowledgementMatches");function Ge(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(Ge,"normalizePath");function ai(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}i(ai,"isIdentifierStart");function Vn(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}i(Vn,"isIdentifierCharacter");function oe(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}i(oe,"skipWhitespace");function Vt(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let r=t,o="";for(t+=1;t<e.length;t+=1){let s=e[t];if(s===n)return{value:o,offset:r,excerpt:e.slice(r,t+1)};s==="\\"&&t+1<e.length?(o+=e[t+1],t+=1):o+=s}}i(Vt,"readString");function le(e,t,n){return e.startsWith(t,n)&&!Vn(e[n-1])&&!Vn(e[n+t.length])}i(le,"isWordAt");function li(e,t){let n=oe(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=oe(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!le(e,"type",n))return!1;let o=oe(e,n+4);if(o>=e.length||e[o]===","||e[o]==="}"||le(e,"as",o)||!ai(e[o]))return!1;for(n=o;n<e.length&&Vn(e[n]);)n+=1;if(n=oe(e,n),le(e,"as",n)){if(n=oe(e,n+2),!ai(e[n]))return!1;for(;n<e.length&&Vn(e[n]);)n+=1}r=!0}return!1}i(li,"bracedNamedBindingsAreTypeOnly");function nc(e,t){if(t=oe(e,t+6),e[t]==="(")return Vt(e,oe(e,t+1));let n=!1;if(le(e,"type",t)){let o=oe(e,t+4);e[o]!==","&&!le(e,"from",o)&&(n=!0)}else li(e,t)&&(n=!0);let r=ci(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}i(nc,"specifierAfterImport");function rc(e,t){t=t+6;let n=oe(e,t),r=!1;if(le(e,"type",n)){let s=oe(e,n+4);(e[s]==="{"||e[s]==="*")&&(r=!0)}else li(e,n)&&(r=!0);let o=ci(e,t,!1);return o&&r?{...o,typeOnly:!0}:o}i(rc,"specifierAfterExport");function ci(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(le(e,"from",t))return Vt(e,oe(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return Vt(e,t);if(t>0&&(le(e,"import",t)||le(e,"export",t)))return}}i(ci,"specifierInStaticStatement");function oc(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(oc,"skipTemplateLiteral");function sc(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=oe(e,t+7);if(e[r]!=="(")return;r=oe(e,r+1);let o=Vt(e,r);return o?{...o,requireCall:!0}:void 0}i(sc,"specifierAfterRequire");function ic(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(`
|
|
23
|
-
`,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=
|
|
22
|
+
`).length}i(pt,"lineOf");var Rl=new Set(["publish","subscribe","defineIntent","registerHandler"]);function Al(e,t){return e.index+e[0].indexOf(t)}i(Al,"captureIndex");function kl(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 p=c[1];p&&r(p,Al(c,p))}},"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),p=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,f;for(;(f=p.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(kl,"extractQuotedStrings");function Il(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(Il,"extractModuleSpecifiers");function bl(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(bl,"isSyntaxWrapper");function Gr(e,t){let n=t;for(;n?.parent&&bl(e,n.parent);)n=n.parent;return n}i(Gr,"unwrapWrappers");function Ur(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(Ur,"callCalleeName");function vl(e,t){let n=t.parent;if(!n||!e.isObjectLiteralExpression(n))return!1;let r=Gr(e,n),o=r.parent;if(!o)return!1;if(e.isCallExpression(o)&&Ur(e,o)==="publish"){let s=o.arguments;return s[1]===r||s[2]===r}if(e.isPropertyAssignment(o)&&Vr(e,o.name)==="metadata"){let s=o.parent;if(!s)return!1;let l=Gr(e,s).parent;return!!(l&&e.isCallExpression(l)&&Ur(e,l)==="publish")}return!1}i(vl,"isPublishMetadataSource");function Gs(e,t){let n=Gr(e,t),r=n.parent;if(!r)return!1;if(e.isCallExpression(r)){let o=Ur(e,r);if(o&&Rl.has(o)&&r.arguments.some(s=>s===n))return!0}if(e.isArrayLiteralExpression(r))return Gs(e,r);if(e.isPropertyAssignment(r)){let o=Vr(e,r.name);if(o==="intent"||o==="onEvent"||o==="reactsTo"||o==="source"&&vl(e,r))return!0}return!1}i(Gs,"isDeclaredIntentSite");function El(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],o=i(s=>{e.isStringLiteralLike(s)&&Gs(e,s)&&r.push({value:s.text,index:s.getStart(n)}),e.forEachChild(s,o)},"visit");return o(n),r}i(El,"extractQuotedStringsAst");function Sl(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(Sl,"hasInfrastructureToken");function wl(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}i(wl,"isKnownInfrastructurePackage");function Cl(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}i(Cl,"layerHasInfrastructureRole");function Mt(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(Mt,"tsStringLiteralText");function Vr(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}i(Vr,"tsPropertyName");function Us(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:Vr(e,r.name)===n)}i(Us,"tsObjectProperty");function $t(e,t,n){return Us(e,t,n)!==void 0}i($t,"tsObjectHasProperty");function Ft(e,t,n){let r=Us(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}i(Ft,"tsObjectPropertyValue");function xl(e,t){let n=Ft(e,t,"metadata");return $t(e,n,"source")}i(xl,"tsObjectHasMetadataSource");function Vs(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?Vs(e,t.name):!1:!1}i(Vs,"tsLooksLikeIntentCreatorExpression");function Ol(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(Ol,"tsIsPublishCall");function Pl(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=Mt(e,n);return r!==void 0&&Ke(r)||$t(e,n,"intent")||Vs(e,n)}i(Pl,"tsIsArkPublishCandidate");function _l(e,t){if(!e.isCallExpression(t))return!1;let[n,r,o]=t.arguments;return xl(e,n)||$t(e,r,"source")||$t(e,o,"source")}i(_l,"tsPublishHasSource");function Tl(e,t){if(!e.isCallExpression(t))return;let[n,r,o]=t.arguments,s=Ft(e,n,"metadata");return Mt(e,Ft(e,s,"source"))??Mt(e,Ft(e,r,"source"))??Mt(e,Ft(e,o,"source"))}i(Tl,"tsPublishSourceLiteral");function Nl(e,t,n,r){let o=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),s=n,a=s?.filePath,l=s?.layer,c=[],p=i(y=>o.getLineAndCharacterOfPosition(y.getStart(o)).line+1,"lineForNode"),f=i(y=>{if(Ol(e,y)){let u=y.arguments[0],g=Mt(e,u);for(let m of Lt({publishCall:!0,rawIntentName:g,objectHasIntent:$t(e,u,"intent"),arkPublishCandidate:Pl(e,y),hasSource:_l(e,y)}))c.push(j(m.ruleId,m.message,{line:p(y),filePath:a}));let d=Tl(e,y);if(r&&l&&d&&Ke(d)){let m=r.resolveLayer(d);m&&m!==l&&c.push(j("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${d}" resolves to ${m}, but the target file is classified as ${l}.`,{line:p(y),filePath:a,target:d,fromLayer:l,toLayer:m}))}}e.forEachChild(y,f)},"visit");return f(o),c}i(Nl,"analyzePublishAst");function js(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,p=c?.filePath,f=c?.layer,y=e.typescript,u=y?y.createSourceFile(p??"generated.ts",s,y.ScriptTarget.Latest,!0):void 0,g=u?dt(e.typescript,u):void 0,d=g?g.filter(k=>k.specifier!==void 0).map(k=>({value:k.specifier,index:k.node.getStart(u),kind:k.kind,typeOnly:k.typeOnly})):Il(s),m=e.typescript?El(e.typescript,s):kl(s);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(p))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:p}))}let E=f!==void 0&&(r.has(f)||Cl(f)),S=f!==void 0?` If "${f}" is an infrastructure layer, mark it in ark.config.json with "mayImportInfrastructure": true (or name it with an infra token like Adapters/Persistence/Repository).`:"";for(let k of n)if(k instanceof RegExp){k.lastIndex=0;let v=k.exec(s);k.lastIndex=0,v&&l.push(j("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${k}`,{line:v.index===void 0?void 0:pt(s,v.index),filePath:p,suggestion:"Remove infrastructure imports from domain/application layers."+S}))}else s.includes(k)&&l.push(j("FORBIDDEN_SUBSTRING",`Forbidden substring: ${k}`,{line:pt(s,s.indexOf(k)),filePath:p}));for(let k of d){let v=e.resolveImportTarget?.(k.value,p)??(e.resolveImportLayer?{layer:e.resolveImportLayer(k.value,p)}:void 0),x=typeof p=="string"?e.resolveImportTarget?.(p)??(e.resolveImportLayer?{layer:f,relPath:void 0}:void 0):void 0,N=v?.layer;if(N&&f){let b=ot(e.architectureProfile?.rules,f,N,{fromPath:x?.relPath,toPath:v?.relPath,layers:e.architectureLayers});if(b){if(k.typeOnly&&!b.peerIsolation)continue;let T=!!b.peerIsolation;l.push(j("LAYER_IMPORT_VIOLATION",b.message??(T?`Layer "${f}" must not import across slices into "${N}".`:`Layer "${f}" must not import "${N}".`),{line:pt(s,k.index),source:k.value,target:k.value,filePath:p,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||!Sl(k.value)&&!wl(k.value)||l.push(j("FORBIDDEN_IMPORT",`Forbidden ${k.kind} target: "${k.value}".`,{line:pt(s,k.index),source:k.value,target:k.value,filePath:p,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 x of v)l.push(j("POLICY_VIOLATION",x.message,{filePath:p,suggestion:`Fix violation of policy "${k.name}".`}));else v===!1?l.push(j("POLICY_VIOLATION",`Policy ${k.name} failed on generated code`)):l.push(j("POLICY_VIOLATION",v.message))}if(o&&t.size>0)for(let k of m)Ke(k.value)&&!t.has(k.value)&&l.push(j("UNKNOWN_INTENT",`Unknown intent reference: "${k.value}"`,{line:pt(s,k.index),filePath:p,target:k.value,suggestion:`Register intent "${k.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&f)for(let k of m){if(!Ke(k.value))continue;let v=e.architectureProfile.resolveLayer(k.value);if(!v)continue;let x=Fe(e.architectureProfile.rules,f,v,{fromPath:typeof p=="string"?p:void 0,layers:e.architectureLayers});if(x){let N=x.rule.peerIsolation?rt(x.peerIsolationReason??"cross-slice",{fromPath:typeof p=="string"?p:void 0,fromSlice:x.fromSlice,toSlice:x.toSlice}):void 0,b=`Layer "${f}" must not reference "${v}" through "${k.value}".`,T=N&&x.peerIsolationReason!=="cross-slice"?`${b} ${N}`:x.rule.message?N?`${x.rule.message} (${N})`:x.rule.message:b;l.push(j("LAYER_REFERENCE_VIOLATION",T,{line:pt(s,k.index),filePath:p,target:k.value,fromLayer:f,toLayer:v,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:x.rule,peerIsolationReason:x.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&&u&&f&&e.forbiddenGlobals?.[f]?.length)try{let k=e.forbiddenGlobals[f];l.push(...ut(e.typescript,u,k).map(v=>j("FORBIDDEN_GLOBAL",`${f} must not use the ambient global "${v.name}".`,{line:v.line,filePath:p,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 x=Ce(v.specifier,k);x&&l.push(j("FORBIDDEN_GLOBAL",`${f} must not use module "${v.specifier}" because it is the import form of forbidden global "${x}".`,{line:v.line,filePath:p,source:v.specifier,target:v.specifier,fromLayer:f,details:{importKind:v.kind,forbiddenGlobal:x},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&&u&&f&&e.capabilityWalls?.[f]?.length)try{let k=new Set(e.capabilityWalls[f]),v=e.forbiddenGlobals?.[f]??[];for(let x of Mr(e.typescript,u))k.has(x.capability)&&(x.source==="ambient-global"&&Dt(x.symbol,v)||x.source==="import-based"&&Ce(x.symbol,v)||l.push(j("CAPABILITY_VIOLATION",x.source==="import-based"?`${f} denies the ${x.capability} capability; found import of "${x.symbol}".`:`${f} denies the ${x.capability} capability; found ambient "${x.symbol}".`,{line:x.line,filePath:p,target:x.symbol,capability:x.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(...Nl(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(js,"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 He="1.2";var Bs=["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 q(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}i(q,"sortedUnique");function Kt(e){let t={schemaVersion:"1.2",include:q(e.include??[]),exclude:q(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:q(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:q(n.patterns??[]),exclude:q(n.exclude??[]),forbiddenGlobals:q(n.forbiddenGlobals??[]),intentPrefixes:q(n.intentPrefixes??[]),capabilityDeny:q(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:q(e.arkRun.compositionRoots),managedLayers:q(e.arkRun.managedLayers),requireDeclarations:e.arkRun.requireDeclarations===!0}}:{}};return z($(t))}i(Kt,"resolvedFactsEvidenceRequirementsHash");function Dl(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:q(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:q(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),p=(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),u=(e.arkRunCompositionRootHits??[]).map(b=>({...b})).sort(B),g=(e.arkRunDeclarations??[]).map(b=>({...b,uses:q(b.uses),reactsTo:q(b.reactsTo),raises:q(b.raises),sends:q(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),x=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($(x));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:p,arkRunKernelCalls:f,arkRunManagedNews:y,arkRunCompositionRootHits:u,arkRunDeclarations:g,arkOrderPlaneCalls:d,arkOrderGenericUpdates:m,arkOrderRootHits:E,arkOrderXiFieldWrites:S,arkOrderIngestWritesXi:k,arkOrderReleaseKeyCounts:v}}i(Dl,"canonicalResolvedFactsInput");function Ws(e){let t=Dl(e);return{...t,factsHash:z($(t))}}i(Ws,"createCanonicalResolvedCandidateFacts");function jr(e){return Ws(qs(M(e,"$"),!1))}i(jr,"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 K(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(K,"assertOnlyKeys");function F(e,t,n){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`${n}.${t} must be a non-empty string.`);return r}i(F,"requiredText");function Re(e,t,n){if(e[t]!==void 0)return F(e,t,n)}i(Re,"optionalText");function H(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(H,"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 zs(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(zs,"requiredInteger");function X(e,t,n){let r=zs(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}i(X,"requiredPositiveInteger");function U(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}i(U,"requiredArray");function Ae(e,t,n,r){let o=e[t];if(typeof o!="string"||!n.includes(o))throw new Error(`${r}.${t} must be one of ${n.join(", ")}.`);return o}i(Ae,"enumValue");function ft(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!n))throw new Error(`${t} must be an array of non-empty strings.`);return[...e]}i(ft,"parseStringArray");function Ll(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(Ll,"assertUnique");function qs(e,t){K(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","classShapes","arkRunKernelCalls","arkRunManagedNews","arkRunCompositionRootHits","arkRunDeclarations","arkOrderPlaneCalls","arkOrderGenericUpdates","arkOrderRootHits","arkOrderXiFieldWrites","arkOrderIngestWritesXi","arkOrderReleaseKeyCounts",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=Ae(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=Ae(e,"completeness",["complete","partial","unavailable"],"$"),o=U(e,"completenessReasons","$").map((w,C)=>{let h=`$.completenessReasons[${C}]`,A=M(w,h);K(A,["code","message","file"],h);let L=A.file===void 0?void 0:H(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,C)=>{let h=`$.files[${C}]`,A=M(w,h);return K(A,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],h),{path:H(A,"path",h),contentHash:F(A,"contentHash",h),parseStatus:Ae(A,"parseStatus",["parsed","invalid"],h),parseDiagnosticCount:zs(A,"parseDiagnosticCount",h),exportsOnlyTypes:G(A,"exportsOnlyTypes",h),typeOnlyExportNames:ft(A.typeOnlyExportNames,`${h}.typeOnlyExportNames`),hasTopLevelSideEffects:G(A,"hasTopLevelSideEffects",h)}}),a=U(e,"dependencies","$").map((w,C)=>{let h=`$.dependencies[${C}]`,A=M(w,h);K(A,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],h);let L=Re(A,"specifier",h),W=Re(A,"target",h),Ee=Ae(A,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],h);if(Ee==="resolved-project"&&!W)throw new Error(`${h}.target is required for resolved-project dependencies.`);if(Ee!=="resolved-project"&&W)throw new Error(`${h}.target is only allowed for resolved-project dependencies.`);if(Ee!=="dynamic"&&!L)throw new Error(`${h}.specifier is required unless resolution is dynamic.`);return{from:H(A,"from",h),...L?{specifier:L}:{},kind:Ae(A,"kind",["import","export","dynamic-import","require"],h),typeOnly:G(A,"typeOnly",h),line:X(A,"line",h),resolution:Ee,...W?{target:H(A,"target",h)}:{},...A.namedBindings!==void 0?{namedBindings:ft(A.namedBindings,`${h}.namedBindings`)}:{},...A.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:G(A,"targetTypeOnlyExports",h)}:{},...A.sourcePureTypeModule!==void 0?{sourcePureTypeModule:G(A,"sourcePureTypeModule",h)}:{},...A.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:G(A,"namedBindingsTypeOnly",h)}:{},...A.portProofEligible!==void 0?{portProofEligible:G(A,"portProofEligible",h)}:{}}}),l=U(e,"capabilityUses","$").map((w,C)=>{let h=`$.capabilityUses[${C}]`,A=M(w,h);return K(A,["file","line","symbol","capability","source"],h),{file:H(A,"file",h),line:X(A,"line",h),symbol:F(A,"symbol",h),capability:Ae(A,"capability",Bs,h),source:Ae(A,"source",["ambient-global","import-based"],h)}}),c=U(e,"ambientUses","$").map((w,C)=>{let h=`$.ambientUses[${C}]`,A=M(w,h);return K(A,["file","line","symbol"],h),{file:H(A,"file",h),line:X(A,"line",h),symbol:F(A,"symbol",h)}}),p=U(e,"publishCalls","$").map((w,C)=>{let h=`$.publishCalls[${C}]`,A=M(w,h);K(A,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],h);let L=Re(A,"rawIntentName",h),W=Re(A,"sourceIntent",h);return{file:H(A,"file",h),line:X(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,C)=>{let h=`$.intentReferences[${C}]`,A=M(w,h);return K(A,["file","line","intent"],h),{file:H(A,"file",h),line:X(A,"line",h),intent:F(A,"intent",h)}}),y=U(e,"safetyUses","$").map((w,C)=>{let h=`$.safetyUses[${C}]`,A=M(w,h);K(A,["file","line","kind","symbol"],h);let L=Re(A,"symbol",h),W=Ae(A,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],h);if(W==="in-memory-store"&&!L)throw new Error(`${h}.symbol is required for in-memory-store facts.`);if(W!=="in-memory-store"&&L)throw new Error(`${h}.symbol is only allowed for in-memory-store facts.`);return{file:H(A,"file",h),line:X(A,"line",h),kind:W,...L?{symbol:L}:{}}});Ll(s,w=>w.path,"$.files");let u=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(!u.has(w.from))throw new Error(`$.dependencies references missing source file ${w.from}.`);let d=(e.arkRunKernelCalls===void 0?[]:U(e,"arkRunKernelCalls","$")).map((w,C)=>{let h=`$.arkRunKernelCalls[${C}]`,A=M(w,h);K(A,["file","line","kind","callee","viaImport","receiver","nameLiteral"],h);let L=Re(A,"receiver",h),W=Re(A,"nameLiteral",h);return{file:H(A,"file",h),line:X(A,"line",h),kind:Ae(A,"kind",["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"],h),callee:F(A,"callee",h),viaImport:G(A,"viaImport",h),...L?{receiver:L}:{},...W?{nameLiteral:W}:{}}}),E=(e.arkRunManagedNews===void 0?[]:U(e,"arkRunManagedNews","$")).map((w,C)=>{let h=`$.arkRunManagedNews[${C}]`,A=M(w,h);K(A,["file","line","typeName","importedFrom"],h);let L=Re(A,"importedFrom",h);return{file:H(A,"file",h),line:X(A,"line",h),typeName:F(A,"typeName",h),...L?{importedFrom:L}:{}}}),k=(e.arkRunCompositionRootHits===void 0?[]:U(e,"arkRunCompositionRootHits","$")).map((w,C)=>{let h=`$.arkRunCompositionRootHits[${C}]`,A=M(w,h);return K(A,["file","matchedRoot","hasKernelFactory"],h),{file:H(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,C)=>{let h=`$.arkOrderPlaneCalls[${C}]`,A=M(w,h);return K(A,["file","line","callee"],h),{file:H(A,"file",h),line:X(A,"line",h),callee:F(A,"callee",h)}}),T=(e.arkOrderGenericUpdates===void 0?[]:U(e,"arkOrderGenericUpdates","$")).map((w,C)=>{let h=`$.arkOrderGenericUpdates[${C}]`,A=M(w,h);return K(A,["file","line","method"],h),{file:H(A,"file",h),line:X(A,"line",h),method:F(A,"method",h)}}),me=(e.arkOrderRootHits===void 0?[]:U(e,"arkOrderRootHits","$")).map((w,C)=>{let h=`$.arkOrderRootHits[${C}]`,A=M(w,h);return K(A,["file","matchedRoot","hasPlaneFactory"],h),{file:H(A,"file",h),matchedRoot:F(A,"matchedRoot",h),hasPlaneFactory:G(A,"hasPlaneFactory",h)}}),D=(e.arkOrderXiFieldWrites===void 0?[]:U(e,"arkOrderXiFieldWrites","$")).map((w,C)=>{let h=`$.arkOrderXiFieldWrites[${C}]`,A=M(w,h);return K(A,["file","line","key"],h),{file:H(A,"file",h),line:X(A,"line",h),key:F(A,"key",h)}}),J=(e.arkOrderIngestWritesXi===void 0?[]:U(e,"arkOrderIngestWritesXi","$")).map((w,C)=>{let h=`$.arkOrderIngestWritesXi[${C}]`,A=M(w,h);return K(A,["file","line"],h),{file:H(A,"file",h),line:X(A,"line",h)}}),ve=(e.arkOrderReleaseKeyCounts===void 0?[]:U(e,"arkOrderReleaseKeyCounts","$")).map((w,C)=>{let h=`$.arkOrderReleaseKeyCounts[${C}]`,A=M(w,h);return K(A,["file","line","keyCount"],h),{file:H(A,"file",h),line:X(A,"line",h),keyCount:X(A,"keyCount",h)}}),bt=v.map((w,C)=>{let h=`$.arkRunDeclarations[${C}]`,A=M(w,h);return K(A,["file","line","uses","reactsTo","raises","sends"],h),{file:H(A,"file",h),line:X(A,"line",h),uses:ft(A.uses,`${h}.uses`),reactsTo:ft(A.reactsTo,`${h}.reactsTo`),raises:ft(A.raises,`${h}.raises`),sends:ft(A.sends,`${h}.sends`)}});for(let[w,C]of[["$.capabilityUses",l],["$.ambientUses",c],["$.publishCalls",p],["$.intentReferences",f],["$.safetyUses",y],["$.arkRunKernelCalls",d],["$.arkRunManagedNews",E],["$.arkRunCompositionRootHits",k],["$.arkRunDeclarations",bt],["$.arkOrderPlaneCalls",N],["$.arkOrderGenericUpdates",T],["$.arkOrderRootHits",me],["$.arkOrderXiFieldWrites",D],["$.arkOrderIngestWritesXi",J],["$.arkOrderReleaseKeyCounts",ve]])for(let h of C)if(!u.has(h.file))throw new Error(`${w} references missing file ${h.file}.`);let fn=Re(e,"projectPackageName","$"),Lo=(e.classShapes===void 0?[]:U(e,"classShapes","$")).map((w,C)=>{let h=`$.classShapes[${C}]`,A=M(w,h);K(A,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],h);let L=U(A,"mutatingMethods",h).map((W,Ee)=>{let R=`${h}.mutatingMethods[${Ee}]`,Q=M(W,R);return K(Q,["name","referencesGuardOrPublish"],R),{name:F(Q,"name",R),referencesGuardOrPublish:G(Q,"referencesGuardOrPublish",R)}});return{file:H(A,"file",h),className:F(A,"className",h),exported:G(A,"exported",h),hasPublicMutableFields:G(A,"hasPublicMutableFields",h),hasPublicSetters:G(A,"hasPublicSetters",h),hasPublicConstructor:G(A,"hasPublicConstructor",h),hasStaticFactory:G(A,"hasStaticFactory",h),mutatingMethods:L,...A.dataOnly===void 0?{}:{dataOnly:G(A,"dataOnly",h)}}});return{schemaVersion:n,completeness:r,completenessReasons:o,resolverIdentity:F(e,"resolverIdentity","$"),compilerIdentity:F(e,"compilerIdentity","$"),compilerOptionsHash:F(e,"compilerOptionsHash","$"),tsconfigHash:F(e,"tsconfigHash","$"),evidenceRequirementsHash:F(e,"evidenceRequirementsHash","$"),...fn?{projectPackageName:fn}:{},files:s,dependencies:a,capabilityUses:l,ambientUses:c,publishCalls:p,intentReferences:f,safetyUses:y,classShapes:Lo,arkRunKernelCalls:d,arkRunManagedNews:E,arkRunCompositionRootHits:k,arkRunDeclarations:bt,arkOrderPlaneCalls:N,arkOrderGenericUpdates:T,arkOrderRootHits:me,arkOrderXiFieldWrites:D,arkOrderIngestWritesXi:J,arkOrderReleaseKeyCounts:ve}}i(qs,"parseResolvedFactsInput");function xe(e){let t=M(e,"$"),n=F(t,"factsHash","$"),r=F(t,"candidateTreeHash","$"),o=Ws(qs(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(xe,"loadResolvedCandidateFacts");var Fl=["network","filesystem","clock","randomness","environment","process","persistence"],P={type:"string",minLength:1},ee={type:"integer",minimum:1},V={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},Br={$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:P,message:P,file:V}}},resolverIdentity:P,compilerIdentity:P,compilerOptionsHash:P,tsconfigHash:P,candidateTreeHash:P,evidenceRequirementsHash:P,projectPackageName:P,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:V,contentHash:P,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:P},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:P,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:ee,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:V,namedBindings:{type:"array",items:P},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:ee,symbol:P,capability:{enum:Fl},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:V,line:ee,symbol:P}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:V,line:ee,rawIntentName:P,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:P}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:V,line:ee,intent:P}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:V,line:ee,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:P},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:P,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:P,referencesGuardOrPublish:{type:"boolean"}}}}}}},arkRunKernelCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind","callee","viaImport"],properties:{file:V,line:ee,kind:{enum:["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"]},callee:P,viaImport:{type:"boolean"},receiver:P,nameLiteral:P}}},arkRunManagedNews:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","typeName"],properties:{file:V,line:ee,typeName:P,importedFrom:P}}},arkRunCompositionRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasKernelFactory"],properties:{file:V,matchedRoot:P,hasKernelFactory:{type:"boolean"}}}},arkRunDeclarations:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","uses","reactsTo","raises","sends"],properties:{file:V,line:ee,uses:{type:"array",items:P},reactsTo:{type:"array",items:P},raises:{type:"array",items:P},sends:{type:"array",items:P}}}},arkOrderPlaneCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","callee"],properties:{file:V,line:ee,callee:P}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:V,line:ee,method:P}}},arkOrderRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasPlaneFactory"],properties:{file:V,matchedRoot:P,hasPlaneFactory:{type:"boolean"}}}},arkOrderXiFieldWrites:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:V,line:ee,key:P}}},arkOrderIngestWritesXi:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line"],properties:{file:V,line:ee}}},arkOrderReleaseKeyCounts:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","keyCount"],properties:{file:V,line:ee,keyCount:{type:"integer",minimum:1}}}},factsHash:P},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 re(e){return`${e.from}->${e.to}`}i(re,"dependencyKey");function Ht(e,t,n,r="dependency"){return{id:`${e}:${r}:${re(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${re(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${re(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${re(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${re(t)} from the candidate, then preflight again.`}:{}}}i(Ht,"dependencyFinding");function gt(e){let t=[],n=new Map(e.changeMap.map.files.map(u=>[u.path,u])),r=new Map(e.changes.map(u=>[u.path,u])),o=new Map(e.changeMap.map.dependencies.map(u=>[re(u),u])),s=new Map(e.baseDependencies.map(u=>[re(u),u])),a=new Map(e.candidateDependencies.map(u=>[re(u),u]));for(let u of[...n.values()].sort((g,d)=>g.path.localeCompare(d.path))){let g=r.get(u.path);g?g.operation!==u.operation?t.push({id:`contradictory:file:${u.path}`,classification:"contradictory",subject:"file",path:u.path,expectedOperation:u.operation,actualOperation:g.operation,message:`${u.path} was planned as ${u.operation} but the actual operation is ${g.operation}.`,nextAction:`Change ${u.path} to the planned ${u.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${u.path}`,classification:"satisfied",subject:"file",path:u.path,expectedOperation:u.operation,actualOperation:g.operation,message:`${u.path} matches the planned ${u.operation} operation.`}):t.push({id:`missing:file:${u.path}`,classification:"missing",subject:"file",path:u.path,expectedOperation:u.operation,message:`${u.path} was planned as ${u.operation} but is absent from the actual change.`,nextAction:`${u.operation[0].toUpperCase()}${u.operation.slice(1)} ${u.path} in the complete change set, then preflight again.`})}for(let u of[...r.values()].sort((g,d)=>g.path.localeCompare(d.path)))n.has(u.path)||t.push({id:`unplanned:file:${u.path}`,classification:"unplanned",subject:"file",path:u.path,actualOperation:u.operation,message:`${u.path} has an unplanned ${u.operation} operation.`,nextAction:`Remove ${u.path} from the change set, then preflight again.`});let l=new Set;for(let u of[...o.values()].sort((g,d)=>re(g).localeCompare(re(d)))){if(a.has(re(u))){t.push(Ht("satisfied",u,`${u.from} -> ${u.to} exists in the candidate architecture.`));continue}let g={from:u.to,to:u.from};a.has(re(g))?(l.add(re(g)),t.push(Ht("contradictory",u,`${u.from} -> ${u.to} was planned, but the candidate contains the reverse edge.`))):t.push(Ht("missing",u,`${u.from} -> ${u.to} is absent from the candidate architecture.`))}let c=new Set([...n.keys(),...r.keys()]);for(let[u,g]of[...a].sort(([d],[m])=>d.localeCompare(m)))s.has(u)||o.has(u)||l.has(u)||!c.has(g.from)&&!c.has(g.to)||t.push({...Ht("unplanned",g,`${g.from} -> ${g.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let p=new Set(e.changeMap.map.files.filter(u=>u.operation==="delete").map(u=>u.path));for(let[u,g]of[...s].sort(([d],[m])=>d.localeCompare(m)))a.has(u)||p.has(g.from)||p.has(g.to)||!c.has(g.from)&&!c.has(g.to)||t.push({...Ht("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((u,g)=>f[u.classification]-f[g.classification]||(u.subject===g.subject?0:u.subject==="file"?-1:1)||u.id.localeCompare(g.id));let y={satisfied:t.filter(u=>u.classification==="satisfied").length,missing:t.filter(u=>u.classification==="missing").length,contradictory:t.filter(u=>u.classification==="contradictory").length,unplanned:t.filter(u=>u.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:y.missing===0&&y.contradictory===0&&y.unplanned===0,behavioralCompletion:"not-evaluated",summary:y,findings:t}}i(gt,"analyzeArchitectureConvergence");var Ys="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",Ml=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","writes-via-aggregate","no-anemic-model","invariant-coverage"];var Xs={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Pg={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Ys,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:Ys},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:[...Ml]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:Xs,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:Xs}}}};function Gt(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}i(Gt,"emptyEffectiveArkRules");function zr(e){return{...e,layers:e.layers.map(t=>{let{description:n,trustBoundary:r,owners:o,...s}=t;return s})}}i(zr,"omitLayerDescriptions");function Zs(e){let{stewards:t,...n}=zr(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(Zs,"effectiveContractPolicyPayload");var $l="INVARIANT_TESTS_PATH_MISSING",Kl="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.",Hl="INVARIANT_COVERAGE_ROOTS_MISSING",Gl="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 Js(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(Js,"formatCoverageDiscards");function Ul(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(Ul,"isUnderCoverageRoot");function Vl(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*['"\`][^'"\`]*${n}[^'"\`]*['"\`]`,"i").test(e)||e.includes(t)}i(Vl,"titleMatchesInvariant");function jl(e,t){if(!t)return!1;let n=t.split("."),r=n[n.length-1],o=n.length>1?n[0]:null;for(let s of Object.values(e))if(!(o&&!s.includes(o))&&(new RegExp(`(?:function\\s+|\\b)${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[(<]`).test(s)||s.includes(t)))return!0;return!1}i(jl,"symbolPresent");function Qs(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=Js(s),l=Js(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",p=(e.coverageRoots??[]).filter(d=>typeof d=="string"&&d.length>0),f=p.length>0,y=p.join(", "),u=[],g=[];for(let d of t){let m=[],E=d.coverage?.test!==!1,S=d.coverage?.symbol,k,v;if(!r&&E){let T;for(let ie of n){let me=e.fileContents[ie];if(!(!me||!Vl(me,d.id))){if(!f||Ul(ie,p)){k=ie,v=f?!1:void 0;break}T??=ie}}k===void 0&&T!==void 0&&(k=T,v=!0),k!==void 0&&m.push("test-title")}S&&jl(e.fileContents,S)&&m.push("symbol");let N=(d.coverage?.test===!0||!!S||d.coverage===void 0)&&m.length>0||d.coverage?.test===!1&&!S?!0:m.length>0,b=r&&E&&m.length===0;if(u.push({invariantId:d.id,layer:d.provenance.layer,sourceFile:d.provenance.sourceFile,mode:d.mode,covered:N&&!b,evidence:m,partial:b,description:d.description,...k!==void 0?{testEvidenceFile:k}:{},...v!==void 0?{outsideDeclaredRoots:v}:{},coverageRootsDeclared:f}),v===!0&&k!==void 0&&g.push({ruleId:"INVARIANT_COVERAGE_OUTSIDE_ROOTS",message:`Invariant ${d.id} is covered only by ${k}, 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:k,line:1,arkruleId:d.id,arkruleSource:d.provenance.sourceFile,fromLayer:d.provenance.layer,severity:"warning",failsStrict:!1}),!N||b){let T=d.mode==="enforced"&&!b,ie=r||n.length===0?"never-had-tests":"tests-disappeared";g.push({ruleId:"INVARIANT_UNCOVERED",message:(b?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).`:ie==="tests-disappeared"?`Invariant ${d.id}: no scanned test names it in a describe/it title and no declared symbol was found (tests-disappeared \u2014 a suite exists). ArkGate matches declared text; it never executes tests.`:`Invariant ${d.id}: no scanned test names it in a describe/it title and no declared symbol was found (never-had-tests \u2014 the scan found no tests at all). ArkGate matches declared text; it never executes tests.`)+(b&&o?l:a),file:d.provenance.sourceFile,line:1,arkruleId:d.id,arkruleSource:d.provenance.sourceFile,fromLayer:d.provenance.layer,severity:T?"error":"warning",failsStrict:T,kind:ie})}}return{coverage:u,violations:g,partial:u.some(d=>d.partial)}}i(Qs,"evaluateInvariantCoverage");function ei(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(ei,"canPromoteInvariant");function qr(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(qr,"nonEmptyPathStrings");function Bl(e){return!e||typeof e!="object"?[]:[...qr(e.testGlobs),...qr(e.coverageRoots)]}i(Bl,"configuredInvariantTestsPaths");function Wl(e){return Bl(e).length>0}i(Wl,"hasConfiguredInvariantTestsPath");function Yr(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.coverage?.test!==!1)}i(Yr,"catalogDemandsInvariantTestsPath");function ti(e){let t=e.hasDomainInvariants===!0||e.hasDomainInvariants!==!1&&Yr(e.invariants);return e.adopted!==!0||!t?[]:Wl(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:$l,message:Kl,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]}i(ti,"collectMissingInvariantTestsPathFindings");function zl(e){return!e||typeof e!="object"?[]:qr(e.coverageRoots)}i(zl,"configuredCoverageRoots");function ql(e){return zl(e).length>0}i(ql,"hasConfiguredCoverageRoots");function Xr(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.mode==="enforced")}i(Xr,"catalogHasEnforcedInvariant");function ni(e){return e.hasEnforcedInvariant===!0||e.hasEnforcedInvariant!==!1&&Xr(e.invariants)?ql(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:Hl,message:Gl,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]:[]}i(ni,"collectMissingCoverageRootsFindings");var Qr="1.0",Yl="add a short note under docs/adr/ (or docs/decisions/) and put that file path in --policy-ack as adrPath.";function _(e,t){let n=t.classification==="weakening"||t.classification==="judgment-required"?`Restore the previous protection at ${t.path}, or ${Yl}`: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(_,"addFinding");function Y(e){return[...new Set(e??[])].sort()}i(Y,"sortedUnique");function ue(e,t,n,r,o){let s=Y(n),a=Y(r),l=new Set(s),c=new Set(a),p=a.filter(y=>!l.has(y)),f=s.filter(y=>!c.has(y));p.length===0&&f.length===0||(p.length>0&&_(e,{kind:"added",path:t,classification:o.added,message:o.addedMessage,before:s,after:a}),f.length>0&&_(e,{kind:"removed",path:t,classification:o.removed,message:o.removedMessage,before:s,after:a}))}i(ue,"compareStringSets");function Ut(e,t,n,r,o,s,a){if(n===r)return;_(e,{kind:r?"enabled":"disabled",path:t,classification:r?o:o==="strengthening"?"weakening":"strengthening",message:r?s:a,before:n,after:r})}i(Ut,"compareBoolean");function Un(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(Un,"keyed");function Xl(e,t,n){let r=Un(t,s=>s.name),o=Un(n,s=>s.name);(r.duplicates.length>0||o.duplicates.length>0)&&_(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){_(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){_(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 p=Gn(a),f=Gn(l);ue(e,`${c}.forbiddenGlobals`,p.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`,p.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)."}),Y(a.intentPrefixes).join("\0")!==Y(l.intentPrefixes).join("\0")&&_(e,{kind:"intent-prefixes-changed",path:`${c}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:Y(a.intentPrefixes),after:Y(l.intentPrefixes)}),Ut(e,`${c}.mayImportInfrastructure`,a.mayImportInfrastructure===!0,l.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),Ut(e,`${c}.optional`,a.optional===!0,l.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active.")}}i(Xl,"compareLayers");function Zl(e,t,n){let r=i(a=>`${a.from}->${a.to}`,"keyOf"),o=Un(t,r),s=Un(n,r);(o.duplicates.length>0||s.duplicates.length>0)&&_(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),p=`$.rules[${a}]`;if(!l&&c){c.allowed===!1?_(e,{kind:"deny-added",path:p,classification:"strengthening",message:"A denied dependency edge was added.",after:c}):_(e,{kind:"allow-added",path:p,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&&_(e,{kind:"deny-removed",path:p,classification:"weakening",message:"A denied dependency edge was removed.",before:l});continue}if(!l||!c)continue;l.allowed!==c.allowed&&_(e,{kind:c.allowed?"deny-disabled":"deny-enabled",path:`${p}.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 u=l.from===l.to&&c.from===c.to;_(e,{kind:y?"peer-isolation-enabled":"peer-isolation-disabled",path:`${p}.peerIsolation`,classification:u?y?"strengthening":"weakening":"judgment-required",message:u?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})}Y(l.sliceFolders).join("\0")!==Y(c.sliceFolders).join("\0")&&_(e,{kind:"slice-folders-changed",path:`${p}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:Y(l.sliceFolders),after:Y(c.sliceFolders)}),!(!f&&!y)&&(oi(e,`${p}.sharedRoots`,"shared-roots",Y(l.sharedRoots),Y(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."),oi(e,`${p}.allowedCrossSlice`,"cross-slice-allowance",Y((l.allowedCrossSlice??[]).map(ri)),Y((c.allowedCrossSlice??[]).map(ri)),"Directed cross-slice edges are now allowed by declaration.","Directed cross-slice edges are no longer declared and deny again."))}}i(Zl,"compareRules");function ri(e){return JSON.stringify([e.from,e.to])}i(ri,"crossSliceKey");function oi(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)),p=l.length>0&&c.length>0;_(e,{kind:p?`${n}-changed`:l.length>0?`${n}-added`:`${n}-removed`,path:t,classification:p?"judgment-required":l.length>0?"weakening":"strengthening",message:p?`${s} Entries were added and removed in the same change.`:l.length>0?s:a,before:r,after:o})}i(oi,"compareDeclaredExceptions");function Jl(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&&_(e,{kind:l>a?"threshold-raised":"threshold-lowered",path:`$.safety.${s}`,classification:l>a?"weakening":"strengthening",message:l>a?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:a,after:l})}for(let s of["allowInMemory","allowDisabledPeerIsolation"])Ut(e,`$.safety.${s}`,r[s]===!0,o[s]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}i(Jl,"compareSafety");function Zr(e){return e.mode==="enforced"?"enforced":"advisory"}i(Zr,"arkRunMode");function Jr(e){return e.mode==="enforced"?"enforced":"advisory"}i(Jr,"arkOrderMode");function Ql(e,t,n){let r=t.arkOrder,o=n.arkOrder,s="$.arkOrder";if(!r&&!o)return;if(!r&&o){_(e,{kind:"arkorder-added",path:s,classification:"strengthening",message:`ArkOrder extra was added (${Jr(o)}).`,after:o});return}if(r&&!o){_(e,{kind:"arkorder-removed",path:s,classification:"weakening",message:"ArkOrder extra was removed.",before:r});return}if(!r||!o)return;let a=Jr(r),l=Jr(o);if(a!==l){let c=a==="advisory"&&l==="enforced";_(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(Ql,"compareArkOrder");function ec(e,t,n){let r=t.arkRun,o=n.arkRun,s="$.arkRun";if(!r&&!o)return;if(!r&&o){_(e,{kind:"arkrun-added",path:s,classification:"strengthening",message:`ArkRun extra was added (${Zr(o)}).`,after:o});return}if(r&&!o){_(e,{kind:"arkrun-removed",path:s,classification:"weakening",message:"ArkRun extra was removed.",before:r});return}if(!r||!o)return;let a=Zr(r),l=Zr(o);if(a!==l){let c=a==="advisory"&&l==="enforced";_(e,{kind:c?"arkrun-promoted":"arkrun-demoted",path:`${s}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkRun extra was promoted to enforced.":"ArkRun extra was demoted to advisory.",before:a,after:l})}ue(e,`${s}.compositionRoots`,r.compositionRoots,o.compositionRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkRun composition roots are governed.",removedMessage:"ArkRun composition roots were removed and may skip the kernel."}),ue(e,`${s}.managedLayers`,r.managedLayers,o.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkRun.",removedMessage:"Layers were removed from ArkRun management."}),Ut(e,`${s}.requireDeclarations`,r.requireDeclarations!==!1,o.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}i(ec,"compareArkRun");function tc(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(tc,"overallClassification");function si(e,t){return`${e}::${t}`}i(si,"ruleKey");function ii(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(si(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(si(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}i(ii,"indexEffectiveRules");function nc(e,t,n,r,o,s){let a=new Map((s??[]).map(u=>[u.invariantId,u])),l=t.arkRules??{},c=n.arkRules??{},p=[...new Set([...Object.keys(l),...Object.keys(c)])].sort();for(let u of p){let g=l[u],d=c[u],m=`$.arkRules[${u}]`;if(g===void 0&&d!==void 0){_(e,{kind:"arkrules-ref-added",path:m,classification:"strengthening",message:`ArkRules reference for layer ${u} was added.`,after:d});continue}if(g!==void 0&&d===void 0){_(e,{kind:"arkrules-ref-removed",path:m,classification:"weakening",message:`ArkRules reference for layer ${u} was removed.`,before:g});continue}g!==d&&_(e,{kind:"arkrules-ref-path-changed",path:m,classification:"judgment-required",message:`ArkRules file path for layer ${u} changed; verify the effective rules still match intent.`,before:g,after:d})}let f=ii(r),y=ii(o);for(let u of[...new Set([...f.structure.keys(),...y.structure.keys()])].sort()){let g=f.structure.get(u),d=y.structure.get(u),m=`$.arkRules.structure[${u}]`;if(!g&&d){_(e,{kind:"arkrule-structure-added",path:m,classification:"strengthening",message:`Structure ArkRule ${d.id} was added (${d.mode}).`,after:d});continue}if(g&&!d){_(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";_(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&&_(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 u of[...new Set([...f.invariants.keys(),...y.invariants.keys()])].sort()){let g=f.invariants.get(u),d=y.invariants.get(u),m=`$.arkRules.invariants[${u}]`;if(!g&&d){_(e,{kind:"arkrule-invariant-added",path:m,classification:"strengthening",message:`Invariant ${d.id} was added (${d.mode}).`,after:d});continue}if(g&&!d){_(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=ei(S);k.ok?_(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}):_(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 _(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(nc,"compareArkRules");function eo(e,t,n){let r=[];ue(r,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),ue(r,"$.exclude",e.exclude,t.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional project paths are excluded from governance.",removedMessage:"Fewer project paths are excluded from governance."}),ue(r,"$.dynamicImportAllowlist",e.dynamicImportAllowlist,t.dynamicImportAllowlist,{added:"weakening",removed:"strengthening",addedMessage:"Additional files may use non-literal dynamic imports.",removedMessage:"Fewer files may use non-literal dynamic imports."}),Ut(r,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let o={off:0,soft:1,"framework-soft":1,strict:2},s=e.cyclePolicy??"strict",a=t.cyclePolicy??"strict";if(s!==a){let l=o[a]===o[s]?"judgment-required":o[a]>o[s]?"strengthening":"weakening";_(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)&&_(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}),Xl(r,e.layers,t.layers),Zl(r,e.rules,t.rules),Jl(r,e,t),nc(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),ec(r,e,t),Ql(r,e,t),r.sort((l,c)=>l.path.localeCompare(c.path)||l.id.localeCompare(c.id)),{schemaVersion:Qr,classification:tc(r),findings:r}}i(eo,"classifyArkPolicyDelta");function to(e,t){if(!e||e.schemaVersion!==Qr||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=Y(e.findingIds),r=Y(t.findingIds);return n.length===r.length&&n.every((o,s)=>o===r[s])}i(to,"policyDeltaAcknowledgementMatches");function Ge(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(Ge,"normalizePath");function ai(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}i(ai,"isIdentifierStart");function Vn(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}i(Vn,"isIdentifierCharacter");function oe(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}i(oe,"skipWhitespace");function Vt(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let r=t,o="";for(t+=1;t<e.length;t+=1){let s=e[t];if(s===n)return{value:o,offset:r,excerpt:e.slice(r,t+1)};s==="\\"&&t+1<e.length?(o+=e[t+1],t+=1):o+=s}}i(Vt,"readString");function le(e,t,n){return e.startsWith(t,n)&&!Vn(e[n-1])&&!Vn(e[n+t.length])}i(le,"isWordAt");function li(e,t){let n=oe(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=oe(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!le(e,"type",n))return!1;let o=oe(e,n+4);if(o>=e.length||e[o]===","||e[o]==="}"||le(e,"as",o)||!ai(e[o]))return!1;for(n=o;n<e.length&&Vn(e[n]);)n+=1;if(n=oe(e,n),le(e,"as",n)){if(n=oe(e,n+2),!ai(e[n]))return!1;for(;n<e.length&&Vn(e[n]);)n+=1}r=!0}return!1}i(li,"bracedNamedBindingsAreTypeOnly");function rc(e,t){if(t=oe(e,t+6),e[t]==="(")return Vt(e,oe(e,t+1));let n=!1;if(le(e,"type",t)){let o=oe(e,t+4);e[o]!==","&&!le(e,"from",o)&&(n=!0)}else li(e,t)&&(n=!0);let r=ci(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}i(rc,"specifierAfterImport");function oc(e,t){t=t+6;let n=oe(e,t),r=!1;if(le(e,"type",n)){let s=oe(e,n+4);(e[s]==="{"||e[s]==="*")&&(r=!0)}else li(e,n)&&(r=!0);let o=ci(e,t,!1);return o&&r?{...o,typeOnly:!0}:o}i(oc,"specifierAfterExport");function ci(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(le(e,"from",t))return Vt(e,oe(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return Vt(e,t);if(t>0&&(le(e,"import",t)||le(e,"export",t)))return}}i(ci,"specifierInStaticStatement");function sc(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(sc,"skipTemplateLiteral");function ic(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=oe(e,t+7);if(e[r]!=="(")return;r=oe(e,r+1);let o=Vt(e,r);return o?{...o,requireCall:!0}:void 0}i(ic,"specifierAfterRequire");function ac(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(`
|
|
23
|
+
`,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=sc(e,n);continue}if(r==="'"||r==='"'){let s=Vt(e,n);s&&(n=s.offset+s.excerpt.length-1);continue}let o=r==="i"&&le(e,"import",n)?rc(e,n):r==="e"&&le(e,"export",n)?oc(e,n):r==="r"&&le(e,"require",n)?ic(e,n):void 0;o&&(t.push(o),n=o.offset+o.excerpt.length-1)}return t}i(ac,"moduleSpecifiers");function di(e,t){let n=[],r=[];for(let o of ac(e.content)){let s=o.value;if(!s.startsWith(".")){if(o.typeOnly)continue;let p=Nt(s);if(!p)continue;let f=e.content.slice(0,o.offset).split(`
|
|
24
24
|
`).length;r.push({file:e.path,symbol:s,capability:p,evidence:{kind:"import",file:e.path,line:f,excerpt:o.excerpt}});continue}let a=e.content.slice(0,o.offset).split(`
|
|
25
|
-
`).length,l={kind:"import",file:e.path,line:a,excerpt:o.excerpt},c=ac(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(di,"moduleFactsFor");function ac(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(ac,"resolveSpecifier");function ui(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let o=ot(t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});o&&n.push({ruleId:`layer-dependency:${o.from}->${o.to}`,message:o.message??`${o.from} must not depend on ${o.to}.`,edge:r,evidence:r.evidence})}return n}i(ui,"violationsFor");var lc={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 cc(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}i(cc,"hasActiveArkRules");function dc(e,t){return cc(e,t)?z($(Zs({config:e,arkRules:t,warnings:[]}))):z($(zr(e)))}i(dc,"policyHashFor");function jn(e,t,n){let r=typeof e=="string"?Ps(e,t):xr(e,t),o=n?.arkRules??Gt();return{...r,arkRules:o,policyHash:dc(r.config,o)}}i(jn,"loadContract");function pi(e){let t=jn(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=jn(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=eo(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&&to(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(pi,"analyzePolicyDelta");function jt(e){let t=e.files.map(y=>{let u=Ge(y.path);return{path:u,content:y.content,contentHash:z(y.content),layer:de(u,e.contract.config.layers)??null}}).sort((y,u)=>y.path.localeCompare(u.path)),n=new Map(t.map(y=>[y.path,y])),r=[],o=[];for(let y of t){let u=di(y,n);r.push(...u.edges),o.push(...u.capabilityUses)}let s=ui(r,e.contract.config),a=new Map(e.contract.config.layers.map(y=>[y.name,y])),l=new Map(e.contract.config.layers.map(y=>[y.name,new Set(lt(y))]));for(let y of o){let u=n.get(y.file)?.layer;if(!u)continue;let g=a.get(u),d=Ce(y.symbol,g?.forbiddenGlobals??[]);if(d){s.push({ruleId:"FORBIDDEN_GLOBAL",message:`${u} 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(u)?.has(y.capability)&&s.push({ruleId:"CAPABILITY_VIOLATION",message:`${u} 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",p=c==="complete"?[]:[{...lc}],f={schemaVersion:Wr,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:p,valid:c==="complete"&&s.length===0,ir:f}}i(jt,"analyzeProject");function Bn(e){let t=new Map(e.files.map(n=>[Ge(n.path),n]));for(let n of e.changes){let r=Ge(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return jt({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}i(Bn,"analyzeChange");function fi(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(fi,"explainViolation");function no(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 p=[],f;do{if(f=s.pop(),f===void 0)break;o.delete(f),p.push(f)}while(f!==c);p.length>1&&a.push(p.sort())},"connect");for(let c of[...e.keys()].sort())n.has(c)||l(c);return a.sort((c,p)=>c[0]<p[0]?-1:c[0]>p[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(no,"detectArchitectureCycles");function mt(e){let t=e.contentViolations.map(s=>({...s})),n=(e.warnings??[]).map(s=>({...s})),r=new Map(e.files.map(s=>[s,new Set]));for(let s of e.edges){if(s.to&&s.to!==s.from&&!s.typeOnly&&r.has(s.from)&&r.get(s.from)?.add(s.to),!s.to||!s.fromLayer||!s.toLayer)continue;let a=Fe(e.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:e.config.layers});if(!a)continue;let l=a.rule,c=!!l.peerIsolation,p=!c&&!!(s.typeOnly||s.namedBindingsTypeOnly),f=c?rt(a.peerIsolationReason??"cross-slice",{fromPath:s.from,toPath:s.to,fromSlice:a.fromSlice,toSlice:a.toSlice}):void 0,y=l.message?f?`${l.message} (${f})`:l.message:f?`${s.fromLayer} must not ${s.kind} another slice of ${s.toLayer} (${s.from} \u2192 ${s.to}): ${f}`:`${s.fromLayer} must not ${s.kind} ${s.toLayer}.`;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:s.from,line:s.line,fromLayer:s.fromLayer,toLayer:s.toLayer,target:s.to,...s.typeOnly?{typeOnly:!0}:{},...s.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...s.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...s.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!c&&s.portProofEligible?{portProofEligible:!0}:{},...s.kind?{edgeKind:s.kind}:{},...c?{peerIsolation:!0}:{},message:p?`${y} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:y,...p?{failsStrict:!1,severity:"warning"}:{}})}let o=String(e.config.cyclePolicy??"strict").toLowerCase();if(o!=="off"){let s=no(r);o==="soft"||o==="framework-soft"?n.push(...s.map(a=>({...a,message:`${a.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...s)}return{violations:t,warnings:n,safety:e.safety}}i(mt,"evaluateArchitectureGraph");function gi(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(gi,"structureFreezeTarget");var uc=["no-anemic-model"],Ai=["ensureInvariants","assertInvariants","validate","publish","emit","raise","record"],cm=new RegExp(`\\b(${Ai.join("|")})\\b`),ki="(?:_?pendingEvents|domainEvents|uncommittedEvents|recordedEvents)",dm=new RegExp(`\\bthis\\.${ki}\\.push\\s*\\(`),um=new RegExp(`^this\\.${ki}\\s*=\\s*\\[\\s*\\]`);var pc="truncatedUntil";function fc(){return`${Ai.join(", ")}, or events-array .push(`}i(fc,"expectedDomainInvariantWordsPhrase");function ro(e){let t=Object.getOwnPropertyDescriptor(e,pc)?.value;return typeof t=="number"?t:void 0}i(ro,"shapeTruncatedUntil");function gc(e){let t=ro(e);return t==null?"":` shape analysed until character ${t}`}i(gc,"shapeTruncationSuffix");function mi(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(mi,"escapeGlobLiteral");function mc(e){let t="";for(let r=0;r<e.length;r+=1){let o=e[r];if(o==="\\"&&r+1<e.length){let s=e[r+1];if("*?{}[],".includes(s)||s==="\\"){t+="\\"+s,r+=1;continue}t+="/";continue}t+=o}let n="";for(let r=0;r<t.length;r+=1){let o=t[r];o==="\\"&&r+1<t.length?(n+=mi(t[r+1]),r+=1):o==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":o==="?"?n+="[^/]":n+=mi(o)}return new RegExp(`^${n}$`)}i(mc,"globToRegExp");function yt(e,t){return!t||t.length===0?!0:t.some(n=>mc(n).test(e))}i(yt,"matchesAppliesTo");function Ii(e){return uc.includes(e)}i(Ii,"isTier2");function bi(e){return e.mode==="enforced"&&!Ii(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}i(bi,"severityFor");function Oe(e,t,n,r=1){let{severity:o,failsStrict:s}=bi(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(Oe,"baseViolation");function Wn(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}i(Wn,"isInRuleLayer");function zn(e,t,n){return t.filter(r=>!(!r.exported||!yt(r.file,e.appliesTo)||!Wn(r.file,e,n)))}i(zn,"shapesForRule");function yc(e,t,n){let r=[];for(let o of zn(e,t,n))(o.hasPublicSetters||o.hasPublicMutableFields)&&r.push(Oe(e,o.file,`Exported class ${o.className} exposes public mutable state (sensor aggregate-private-state).`));return r}i(yc,"evaluateAggregatePrivateState");function hc(e,t,n){let r=[];for(let o of zn(e,t,n))if(o.hasPublicConstructor&&!o.hasStaticFactory){if(!(o.hasPublicMutableFields||o.hasPublicSetters||(o.mutatingMethods?.length??0)>0))continue;r.push(Oe(e,o.file,`Exported class ${o.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}return r}i(hc,"evaluateAlwaysValidFactory");function Rc(e,t,n){let r=[],o=fc();for(let s of zn(e,t,n)){let a=gc(s);ro(s)!=null&&r.push(Oe(e,s.file,`Exported class ${s.className} shape analysed until character ${ro(s)}; later methods may be invisible (sensor domain-event-on-mutation).`));for(let l of s.mutatingMethods)l.referencesGuardOrPublish||r.push(Oe(e,s.file,`Mutating method ${s.className}.${l.name} does not reference ${o} (sensor domain-event-on-mutation).${a}`))}return r}i(Rc,"evaluateDomainEventOnMutation");function Ac(e,t){let n=[];for(let r of t.files)yt(r,e.appliesTo)&&Wn(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(Oe(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}i(Ac,"evaluateOrchestrationOnly");function kc(e,t){let n=[];for(let r of t.files)yt(r,e.appliesTo)&&Wn(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(Oe(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}i(kc,"evaluateThinAdapter");function Ic(e,t){let n=[];for(let r of t.files)yt(r,e.appliesTo)&&Wn(r,e,t.layerForFile)&&t.fileHints?.[r]?.persistenceWrite&&n.push(Oe(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(Ic,"evaluateWritesViaAggregate");function bc(e,t,n){let r=[];for(let o of zn(e,t,n))if(o.dataOnly===!0){let s=Oe(e,o.file,`Exported type ${o.className} looks data-only / anemic (sensor no-anemic-model; advisory only).`);r.push({...s,severity:"warning",failsStrict:!1})}return r}i(bc,"evaluateNoAnemicModel");function vi(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(...yc(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...hc(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...Rc(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...Ac(n,e));break;case"thin-adapter":t.push(...kc(n,e));break;case"writes-via-aggregate":t.push(...Ic(n,e));break;case"no-anemic-model":t.push(...bc(n,e.classShapes,e.layerForFile));break;case"invariant-coverage":break;default:break}return t.sort((n,r)=>n.file.localeCompare(r.file)||n.arkruleId.localeCompare(r.arkruleId)||n.message.localeCompare(r.message))}i(vi,"evaluateArkRuleSensors");function Ei(e,t){let n=[],r=t.map(o=>o.replace(/\\/g,"/"));for(let o of e.structure){if(!o.appliesTo||o.appliesTo.length===0||r.some(c=>yt(c,o.appliesTo)))continue;let{severity:a,failsStrict:l}=bi(o);n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule structure "${o.id}" appliesTo matched zero governed files (patterns: ${o.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:o.provenance.sourceFile,line:1,fromLayer:o.provenance.layer,arkruleId:o.id,arkruleSource:o.provenance.sourceFile,severity:a,sensor:o.sensor,failsStrict:l})}for(let o of e.invariants??[]){if(!o.appliesTo||o.appliesTo.length===0||r.some(l=>yt(l,o.appliesTo)))continue;let a=o.mode==="enforced";n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule invariant "${o.id}" appliesTo matched zero governed files (patterns: ${o.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:o.provenance.sourceFile,line:1,fromLayer:o.provenance.layer,arkruleId:o.id,arkruleSource:o.provenance.sourceFile,severity:a?"error":"warning",sensor:"invariant-coverage",failsStrict:a})}return n.sort((o,s)=>o.file.localeCompare(s.file)||o.arkruleId.localeCompare(s.arkruleId)||o.message.localeCompare(s.message))}i(Ei,"collectEmptyAppliesToFindings");var yi=64;function vc(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(vc,"stripTrailingDots");function Ec(e){let t=e.trim(),n=t.length>yi?t.slice(0,yi):t;return vc(n)}i(Ec,"normalizeIntentPrefix");function Sc(e){let t=e.toLowerCase();return t.includes("domain")||t.includes("entity")||t.includes("aggregate")||t.includes("model")}i(Sc,"layerNameLooksDomain");function wc(e){return e.some(t=>{let n=Ec(t);return n==="Domain"||n.startsWith("Domain.")})}i(wc,"ownsDomainIntent");function Cc(e,t=[]){return Sc(e)||wc(t)}i(Cc,"isDomainRoleLayerName");function Si(e){if(e.arkRulesActive!==!0)return[];let t=(e.layers??[]).filter(c=>Cc(c.name,c.intentPrefixes??[])).map(c=>c.name);if(t.length===0)return[];let n=new Set(t);if(!(e.files??[]).some(c=>{let p=typeof c.layer=="string"?c.layer:"";return p.length>0&&n.has(p)}))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)&&!Ii(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(Si,"collectEmptyInvariantCatalogFindings");var hi=/\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)/,Ri=/\bfrom\s+['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)(?:\.[cm]?[jt]sx?)?['"]|require\(\s*['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)/,xc=/\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 Oc(e){return e==="PersistenceAdapters"}i(Oc,"isPersistenceDriverLayer");function Pc(e,t){if(hi.test(e)||Ri.test(e))return!0;if(!t)return!1;for(let n of t){if(Oc(n.layer))return!0;let r=n.specifier;if(!r)continue;let o=`from '${r}'`;if(hi.test(o)||Ri.test(o))return!0}return!1}i(Pc,"sourceImportsPersistenceDriver");var _c=/\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*=)/,Tc=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,Nc=/\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*=/,Dc=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function Lc(e,t,n){if(!t)return null;let r=Pc(t,n),o=r&&xc.test(t);if(t.length<40)return o?{persistenceWrite:!0}:null;let s=t.match(new RegExp(Nc.source,"g"))??[],a=t.match(new RegExp(Dc.source,"g"))??[],l=(t.match(/\bif\s*\(/g)??[]).length,c=(t.match(/\bswitch\s*\(/g)??[]).length,p=s.length>=2||s.length>=1&&a.length>=2||a.length>=3&&l+c>=6,f=_c.test(t)||Tc.test(t),y=s.length>=1||a.length>=2,u=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),g=r&&y||f&&y||r&&u&&(l>=4||s.length>=1)||f&&r;return!p&&!g&&!o?null:{...p?{orchestrationHeavy:!0}:{},...g?{adapterThick:!0}:{},...o?{persistenceWrite:!0}:{}}}i(Lc,"deriveArkRuleFileHints");function wi(e,t){let n={};for(let[r,o]of Object.entries(e)){let s=r.replace(/\\/g,"/"),a=Lc(r,o,t?.[s]);a&&(n[s]=a)}return n}i(wi,"buildArkRuleFileHints");function Fc(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(Fc,"normalizeExtraMergeTeethClassification");function qn(e){let t=Fc(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(qn,"extraMergeTeethAllowed");function Ci(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(Ci,"classifyResolvedLayerCoverage");var Mc=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"];var ym=new Set(Mc);function xi(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")}i(xi,"isArkRunKernelModuleSpecifier");var $c=["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"],oo=new Set($c);function Oi(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(oo.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(oo.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:oo.has(e.slice(0,r))}i(Oi,"isArkRunTransportBypassSpecifier");var Kc=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],wm=new Set(Kc);var Pi={"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"},Hc="ARKRUN_INTERACTION_NAME_INCOMPLETE";function Ni(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(Ni,"isDomainRoleLayer");function Gc(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}i(Gc,"compareFindings");function ke(e,t,n,r,o,s,a){let l=e.mode==="enforced"&&a;return{ruleId:Pi[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:fe({ruleId:Pi[t],fromLayer:s?.fromLayer,target:s?.target})}}i(ke,"finding");function Uc(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(Uc,"bagForFile");function _i(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}i(_i,"emitKinds");function Ti(e){return e==="subscribe"||e==="register-handler"}i(Ti,"handleKinds");function Vc(e){return e==="resolve"||e==="resolve-singleton"}i(Vc,"dependKinds");function jc(e,t,n){let r=[],o=e.kernelRoots??e.compositionRoots;if(o.length===0)return r.push(ke(e,"arkrun-missing-root","ark.config.json",1,"ArkRun kernelRoots is empty; no createArkKernel factory site is declared.",void 0,n)),r;let s=new Map;for(let a of t){let l=s.get(a.matchedRoot)??[];l.push(a),s.set(a.matchedRoot,l)}for(let a of o){let l=[...s.get(a)??[]].sort((p,f)=>p.file.localeCompare(f.file));if(l.length===0){r.push(ke(e,"arkrun-missing-root","ark.config.json",1,`ArkRun kernel root ${JSON.stringify(a)} matched no governed files and has no createArkKernel factory.`,{target:a},n));continue}if(l.some(p=>p.hasKernelFactory))continue;let c=l[0];r.push(ke(e,"arkrun-missing-root",c.file,1,`ArkRun kernel root ${JSON.stringify(a)} has no createArkKernel / createStrictArkKernel factory.`,{target:a},n))}return r}i(jc,"evaluateMissingRoot");function Bc(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||!xi(c))continue;let p=r(l.from);p&&Ni(p,s.get(p)??[])&&a.push(ke(e,"arkrun-kernel-in-domain",l.from,l.line,`${p} must not import kernel module ${JSON.stringify(c)}.`,{fromLayer:p,target:c},o))}return a}i(Bc,"evaluateKernelInDomain");function Wc(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)),p=[];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 u=o(f.file);!u||!a.has(u)||Ni(u,l.get(u)??[])||p.push(ke(e,"arkrun-direct-new",f.file,f.line,`${u} must not construct ${f.typeName} with new outside an ArkRun composition-root factory.`,{fromLayer:u,target:f.typeName},s))}return p}i(Wc,"evaluateDirectNew");function zc(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(!_i(c.kind)&&!Ti(c.kind)&&!Vc(c.kind))continue;let p=r(c.file);if(!p||!l.has(p))continue;if(!c.nameLiteral){e.mode==="enforced"&&a.push({code:Hc,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=Uc(n,c.file);if(_i(c.kind)){if(f.raises.has(c.nameLiteral)||f.sends.has(c.nameLiteral))continue;s.push(ke(e,"arkrun-undeclared-emit",c.file,c.line,`Emit ${JSON.stringify(c.nameLiteral)} is not declared in raises or sends.`,{fromLayer:p,target:c.nameLiteral},o));continue}if(Ti(c.kind)){if(f.reactsTo.has(c.nameLiteral))continue;s.push(ke(e,"arkrun-undeclared-handle",c.file,c.line,`Handle ${JSON.stringify(c.nameLiteral)} is not declared in reactsTo.`,{fromLayer:p,target:c.nameLiteral},o));continue}f.uses.has(c.nameLiteral)||s.push(ke(e,"arkrun-undeclared-depend",c.file,c.line,`Depend ${JSON.stringify(c.nameLiteral)} is not declared in uses.`,{fromLayer:p,target:c.nameLiteral},o))}return{findings:s,completenessReasons:a}}i(zc,"evaluateUndeclared");function qc(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||!Oi(l))continue;let c=n(a.from);!c||!o.has(c)||s.push(ke(e,"arkrun-transport-bypass",a.from,a.line,`${c} must not import broker/queue/emitter ${JSON.stringify(l)}; use the ArkRun kernel transport.`,{fromLayer:c,target:l},r))}return s}i(qc,"evaluateTransportBypass");function Di(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=qn(e.classification),r=zc(t,e.kernelCalls,e.declarations,e.layerForFile,n),o=[...jc(t,e.compositionRootHits,n),...Bc(t,e.layers,e.dependencies,e.layerForFile,n),...Wc(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...qc(t,e.dependencies,e.layerForFile,n)].sort(Gc),s=[...r.completenessReasons].sort((a,l)=>{let c=`${a.code}\0${a.file??""}\0${a.message}`,p=`${l.code}\0${l.file??""}\0${l.message}`;return c<p?-1:c>p?1:0});return{findings:o,completenessReasons:s}}i(Di,"evaluateArkRunSensors");function Li(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}i(Li,"isArkOrderModuleSpecifier");var Fi=new Map;function Mi(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(Mi,"escapeAppliesToLiteral");function Yc(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(Yc,"normalizeAppliesToGlob");function Xc(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(Xc,"appliesToBracesBalanced");function Zc(e){let t=Fi.get(e);if(t)return t;let n=Yc(e),r=Xc(n),o="",s=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(o+=Mi(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+=Mi(c)}let a=new RegExp(`^${o}$`);return Fi.set(e,a),a}i(Zc,"globToRegExp");var $i={"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 Jc(e,t){return!t||t.length===0?!0:t.some(n=>Zc(n).test(e))}i(Jc,"matchesArkOrderAppliesTo");function Qc(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(Qc,"isDomainRoleLayer");function Pe(e,t,n,r,o,s,a){let l=e.mode==="enforced"&&a;return{ruleId:$i[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:fe({ruleId:$i[t],fromLayer:s?.fromLayer,target:s?.target})}}i(Pe,"finding");function Ki(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let n=qn(e.classification),r=[],o=t.planeRoots;if(t.mode==="enforced"&&o.length===0)r.push(Pe(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 p of e.planeRootHits){let f=c.get(p.matchedRoot)??[];f.push(p),c.set(p.matchedRoot,f)}for(let p of o){let f=c.get(p)??[];if(f.length===0){r.push(Pe(t,"arkorder-missing-plane","ark.config.json",1,`ArkOrder plane root ${JSON.stringify(p)} matched no governed files and has no createOrderPlane factory.`,{target:p},n));continue}f.some(y=>y.hasPlaneFactory)||r.push(Pe(t,"arkorder-missing-plane",f[0].file,1,`ArkOrder plane root ${JSON.stringify(p)} has no createOrderPlane factory.`,{target:p},n))}}let s=new Map(e.layers.map(c=>[c.name,c.intentPrefixes??[]]));for(let c of e.dependencies){let p=c.specifier;if(!p||!Li(p))continue;let f=e.layerForFile(c.from);f&&Qc(f,s.get(f)??[])&&r.push(Pe(t,"arkorder-kernel-in-domain",c.from,c.line,"Domain-role layer imports arkgate/order; Domain stays plane-free.",{fromLayer:f,target:p},n))}for(let c of e.genericUpdates)r.push(Pe(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(Pe(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(Pe(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 p=e.layerForFile(c.file);!p||!l.has(p)||Jc(c.file,t.appliesTo)&&r.push(Pe(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:p,target:c.key},n))}return r.sort((c,p)=>c.file.localeCompare(p.file)||c.ruleId.localeCompare(p.ruleId)||c.line-p.line),{findings:r,completenessReasons:[]}}i(Ki,"evaluateArkOrderSensors");function Z(e,t,n={}){return{ruleId:e,message:t,...n}}i(Z,"configWarning");function Yn(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(Z("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(Z("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(Z("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(Z("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let p=new Set,f=new Set;for(let d of a){if(!d.name){s.push(Z("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}p.has(d.name)&&f.add(d.name),p.add(d.name),d.forbiddenGlobals!==void 0&&(!Array.isArray(d.forbiddenGlobals)||d.forbiddenGlobals.some(E=>typeof E!="string"))&&s.push(Z("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(Z("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${d.name}" has no file patterns and will never classify files.`,{layer:d.name}));continue}for(let E of m){let S;try{S=ye(E)}catch(v){s.push(Z("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(Z("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(Z("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(Z("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(Z("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${d.to}".`,{fromLayer:d.from,toLayer:d.to}));let y=new Set;if(a.length>1)for(let d of r){let m=-1,E=[];for(let S of a)for(let k of S.patterns??[]){if(!ye(k).test(d))continue;let v=vr(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(Z("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 u=r.filter(d=>!de(d,a));u.length>0&&s.push(Z("CONFIG_UNCLASSIFIED_FILES",`${u.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:u.length,samples:u.slice(0,5)}));let g=Cs(t);if(g.length>0){let d=g[0]??"this layer";s.push(Z("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:xs(d)}))}return s}i(Yn,"collectAnalysisConfigWarnings");function Hi(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:gi({sensor:e.sensor,code:e.code})}:{},...r||o?{freezable:!1}:{},nextAction:t}}i(Hi,"toArkRuleEngineViolation");function ed(e){let t=e.arkRules;return!!(t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0)}i(ed,"arkRulesMapIsOn");function Gi(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(Gi,"arkRuleFindingNextAction");function td(e,t){return t.some(n=>{try{return ye(n).test(e)}catch{return!1}})}i(td,"matchesAny");function nd(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")&&!td(m.file,s)).map(m=>({file:m.file,line:m.line,kind:m.kind==="dynamic-require"?"require":"import"})),p=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:p,disabledPeerIsolationRules:f,thresholds:{maxTsSuppressions:r,maxAnyCasts:o}},u=[],g=c.filter(m=>m.kind==="import");if(g.length>0){let m=g[0];u.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];u.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];u.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];u.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:m.file,line:m.line,message:`${l.length} explicit any cast(s) exceed safety.maxAnyCasts (${o}).`})}if(p.length>0){let m=p[0];u.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:m.file,line:m.line,message:`${p.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&&u.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:u}}i(nd,"evaluateSafety");function rd(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}i(rd,"ambientForbiddenGlobal");function Ui(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return Hr(e,n.length>0?n:Kr.map(r=>({name:r.layer,prefixes:r.prefixes})))}i(Ui,"intentLayer");function od(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||!rd(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??[],p=s.source==="import-based"?t.dependencies.find(f=>f.from===s.file&&f.line===s.line&&f.specifier===s.symbol&&!f.typeOnly)?.kind:void 0;if(!(s.source==="ambient-global"&&Dt(s.symbol,c))){if(s.source==="import-based"){let f=Ce(s.symbol,c);if(f){r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:a,target:s.symbol,...p?{edgeKind:p}:{},message:`${a} must not use module "${s.symbol}" because it is the import form of forbidden global "${f}".`});continue}}lt(l).includes(s.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:s.file,line:s.line,fromLayer:a,target:s.symbol,capability:s.capability,...p?{edgeKind:p}:{},message:s.source==="import-based"?`${a} denies the ${s.capability} capability; found import of "${s.symbol}".`:`${a} denies the ${s.capability} capability; found ambient "${s.symbol}".`})}}for(let s of t.publishCalls){let a=n.get(s.file);if(!a)continue;for(let c of Lt({publishCall:!0,rawIntentName:s.rawIntentName,objectHasIntent:s.objectHasIntent,arkPublishCandidate:s.arkPublishCandidate,hasSource:s.hasSource}))r.push({ruleId:c.ruleId,file:s.file,line:s.line,...c.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:a}:{},message:c.message});if(!s.sourceIntent)continue;let l=Ui(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=Ui(s.intent,e.contract);if(!l)continue;let c=Fe(e.contract.config.rules,a,l,{fromPath:s.file,layers:e.contract.config.layers});if(!c)continue;let p=c.rule.peerIsolation?rt(c.peerIsolationReason??"cross-slice",{fromPath:s.file,fromSlice:c.fromSlice,toSlice:c.toSlice}):void 0,f=`${a} must not reference ${l} intent ${s.intent}.`,y=p&&c.peerIsolationReason!=="cross-slice"?`${f} ${p}`:c.rule.message?p?`${c.rule.message} (${p})`: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(od,"contentViolations");function sd(e){let{facts:t}=e,n=Kt(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,Q)=>{let vt=`${R.code}\0${R.file??""}\0${R.message}`,Et=`${Q.code}\0${Q.file??""}\0${Q.message}`;return vt<Et?-1:vt>Et?1:0}),a=t.files.map(R=>({...R,layer:de(R.path,e.contract.config.layers)??null})),l=new Map(a.map(R=>[R.path,R.layer])),c=t.dependencies.map(R=>{let Q=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,...Q?{toLayer:Q}:{}}:{},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}:{}}}),p=Yn({config:e.contract.config,rules:e.contract.config.rules,files:a.map(R=>R.path)}),f=nd(e,t),y=e.contract.arkRules??Gt(),u=a.map(R=>R.path),d={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?wi(e.coverageInputs.fileContents):{},...e.fileHints??{}},m=i(R=>l.get(R)??de(R,e.contract.config.layers),"resolveLayer"),E=[...vi({arkRules:y,classShapes:e.contract.classShapes??t.classShapes??[],files:u,layerForFile:m,fileHints:d}),...Ei(y,u),...Si({arkRulesActive:ed(e.contract.config),arkRules:y,layers:e.contract.config.layers??[],files:u.map(R=>({path:R,layer:m(R)}))})],S=(y.invariants?.length??0)>0,k=ni({hasEnforcedInvariant:Xr(y.invariants),coverage:e.contract.config.coverage,...e.coverageRootsPresent===!1?{declaredPathPresent:!1}:{}}),v=k.length>0?[]:ti({adopted:e.adopted===!0,hasDomainInvariants:Yr(y.invariants),coverage:e.contract.config.coverage,...e.invariantTestsPathPresent===!1?{declaredPathPresent:!1}:{}}),x=[...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=>Hi(R,Gi(R,!1))),b=E.filter(R=>!R.failsStrict).map(R=>({...Hi(R,Gi(R,!0)),failsStrict:!1})),T=S?Qs({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},ie=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.`})),me=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).`})),Ne=Ci(a),D=Di({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:Ne}),pe=e.contract.config.arkRun?.mode,J=D.findings.filter(()=>pe==="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}:{}})),ze=D.findings.filter(()=>pe!=="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})),ve=Ki({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:Ne}),bt=e.contract.config.arkOrder?.mode,fn=ve.findings.filter(()=>bt==="enforced").map(R=>({ruleId:R.ruleId,file:R.file,line:R.line,message:R.message,fromLayer:R.fromLayer,target:R.target,nextAction:R.nextAction,sensor:R.sensor,failsStrict:R.failsStrict,...R.severity?{severity:R.severity}:{}})),Do=ve.findings.filter(()=>bt!=="enforced").map(R=>({ruleId:R.ruleId,file:R.file,line:R.line,message:R.message,fromLayer:R.fromLayer,target:R.target,nextAction:R.nextAction,sensor:R.sensor,failsStrict:!1})),w=[...T.partial&&T.coverage.some(R=>R.mode==="enforced"&&R.partial)?[{code:"INVARIANT_COVERAGE_PARTIAL",message:"Enforced ArkRules invariant coverage cannot be fully proven (missing test globs or empty test set); reporting partial, never covered."}]:[],...D.completenessReasons,...ve.completenessReasons],C=mt({config:e.contract.config,rules:e.contract.config.rules,files:a.filter(R=>R.layer).map(R=>R.path),contentViolations:[...od(e,t,l),...N,...x,...ie,...J,...fn],edges:c,warnings:[...p,...f.warnings,...b,...me,...ze,...Do],safety:f.report}),h=o==="complete"&&w.length>0?"partial":o,A=h==="complete"?s:[...s,...w].sort((R,Q)=>{let vt=`${R.code}\0${R.file??""}\0${R.message}`,Et=`${Q.code}\0${Q.file??""}\0${Q.message}`;return vt<Et?-1:vt>Et?1:0}),L=C.violations.filter(R=>R.failsStrict!==!1),W=h==="complete"&&L.length===0,Ee=W&&C.warnings.every(R=>R.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:h,completenessReasons:A,valid:W,strictValid:Ee,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:C.violations,warnings:C.warnings}}}i(sd,"analyzeCanonicalResolvedProject");function Bt(e){return sd({contract:e.contract,facts:xe(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints,adopted:e.adopted,invariantTestsPathPresent:e.invariantTestsPathPresent,coverageRootsPresent:e.coverageRootsPresent})}i(Bt,"analyzeResolvedProject");function Vi(e){return z($(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}i(Vi,"analysisTreeHash");function ji(e){let t=jt(e),n=new Map(t.ir.files.map(d=>[d.path,d])),r=[],o=new Set,s=[];for(let d of e.changes){let m=d.path.replace(/\\/g,"/"),E=Ge(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=Bn({...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}}),p=mt({config:e.contract.config,rules:e.contract.config.rules,files:a.ir.files.map(d=>d.path),contentViolations:c,edges:a.ir.edges.filter(d=>!!d.fromLayer).map(d=>({from:d.from,fromLayer:d.fromLayer,...d.to?{to:d.to}:{},...d.toLayer?{toLayer:d.toLayer}:{},line:d.evidence.line,kind:"import",...d.typeOnly?{typeOnly:!0}:{},...d.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),f=r.map(d=>{let m=Ge(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,...p.violations].map(d=>({...d,nextAction:fe(d)})),u=y.filter(d=>d.failsStrict!==!1),g=e.changeMap?gt({changeMap:e.changeMap,changes:f,baseDependencies:t.ir.edges.flatMap(d=>d.to?[{from:d.from,to:d.to}]:[]),candidateDependencies:a.ir.edges.flatMap(d=>d.to?[{from:d.from,to:d.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&a.valid&&u.length===0&&(g?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:a.ir.compilerOptionsHash,baseTreeHash:Vi(t.ir.files),candidateTreeHash:Vi(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:p.warnings}}i(ji,"preflightChange");function id(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(id,"canonicalChangePath");function ad(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(ad,"identityViolations");function ld(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(ld,"preparedChange");function Bi(e){let t=xe(e.baseFacts),n=xe(e.candidateFacts),r=Bt({contract:e.contract,facts:t}),o=Bt({contract:e.contract,facts:n}),s=new Map(t.files.map(g=>[g.path,g])),a=new Map(n.files.map(g=>[g.path,g])),l=ad(t,n),c=new Map,p=[];for(let g of e.changes){let d=id(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}.`})}p.push(ld(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?gt({changeMap:e.changeMap,changes:p,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:fe(g)})),u=y.filter(g=>g.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&o.strictValid&&u.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:p.sort((g,d)=>g.path<d.path?-1:g.path>d.path?1:0),violations:y,warnings:o.ir.warnings}}i(Bi,"preflightResolvedChange");var so="docs/diagnostics.md",cd="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 Xn=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("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.")]),io=new Map(Xn.map(e=>[e.ruleId,e])),dd=Object.freeze(Xn.map(e=>e.ruleId));function ud(e){return typeof e=="string"&&e.length>0&&io.has(e)}i(ud,"isKnownDiagnosticCode");function pd(e){return typeof e!="string"||e.length===0?!1:io.has(e)?!0:e.startsWith("ARKRULE_")}i(pd,"isCataloguedOrArkRuleFamily");function Zn(e){if(!(typeof e!="string"||e.length===0))return io.get(e)}i(Zn,"getDiagnosticCatalogEntry");function Wi(e){return`#${Zn(e)?.docsAnchor??e}`}i(Wi,"diagnosticDocsFragment");function fd(e){return`${so}${Wi(e)}`}i(fd,"diagnosticDocsPath");function gd(){return{schemaVersion:"1.0",docsPath:so,codes:Xn}}i(gd,"serializeDiagnosticCatalog");function md(e){return Zn(e)?.fix}i(md,"catalogFixForRuleId");function yd(e){return Zn(e)?.why}i(yd,"catalogWhyForRuleId");var hd="1.1";var Rd="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 Ad(e){return typeof e.initialState=="function"?e.initialState():e.initialState}i(Ad,"initialState");var Jn=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)??Ad(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 Qn(e){return new Jn(e)}i(Qn,"createProjectionRegistry");var er="1.0";function kd(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}i(kd,"policyId");var ao=class{constructor(t){this.data=t}data;static{i(this,"ArkManifestImpl")}toJSON(){return{...this.data}}};function tr(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,p=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:kd(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})):[],u=r?r.toJSON():[],g=o?o.toJSON():{nodes:[],edges:[]},d=u.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:mr,exportedAt:new Date().toISOString(),intents:p,relationships:f,policies:y,entities:u,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 ao(E)}i(tr,"createArkManifest");var zi=0;function qi(e){return zi+=1,`${e}-${Date.now()}-${zi}`}i(qi,"createWorkflowId");function lo(e){return e instanceof Error?e.message:String(e)}i(lo,"errorMessage");function Id(e){return new Promise(t=>{setTimeout(t,e)})}i(Id,"sleep");async function bd(e,t,n){let r=new AbortController;if(t===void 0)return e(r.signal);let o,s=new Promise((a,l)=>{o=setTimeout(()=>{let c=new Error(`Workflow step "${n}" timed out after ${t}ms.`);r.abort(c),l(c)},t)});try{return await Promise.race([e(r.signal),s])}finally{o&&clearTimeout(o)}}i(bd,"withTimeout");var zt=class{static{i(this,"InMemoryWorkflowStore")}snapshots=new Map;save(t,n){let r=this.snapshots.get(t.id);if(r&&r.version!==t.version)throw new Error(`Optimistic concurrency conflict for workflow ${t.id}`);let o=(t.version??0)+1;this.snapshots.set(t.id,{...t,version:o,context:{...t.context}}),t.version=o}get(t,n){let r=this.snapshots.get(t);return r?{...r,context:{...r.context}}:void 0}list(t){return Array.from(this.snapshots.values()).filter(n=>!t||n.workflowName===t).map(n=>({...n,context:{...n.context}}))}claim(t,n,r){let o=Date.now();for(let s of this.snapshots.values()){if(r&&s.workflowName!==r||s.status!=="running"&&s.status!=="compensating")continue;let a=s.expiresAt?new Date(s.expiresAt).getTime()<o:!0;if(!s.ownerId||a){s.ownerId=t,s.expiresAt=new Date(o+n).toISOString();let l=(s.version??0)+1;return s.version=l,this.snapshots.set(s.id,{...s,context:{...s.context}}),{...s,context:{...s.context}}}}}clear(){this.snapshots.clear()}},co=class{constructor(t,n={}){this.bus=t;this.options=n;this.store=n.store??new zt}bus;options;static{i(this,"WorkflowEngineImpl")}definitions=new Map;store;register(t){if(this.definitions.has(t.name))throw new Error(`Workflow "${t.name}" is already registered.`);let n=new Set;for(let r of t.steps){if(n.has(r.name))throw new Error(`Workflow "${t.name}" has duplicate step name "${r.name}".`);n.add(r.name)}if(this.definitions.set(t.name,t),t.startOn){let r=t.startOn;this.bus.subscribe(r.intent,async o=>{await this.start(t.name,r.mapEventToPayload(o))})}}async start(t,n,r={}){let o=this.definitions.get(t);if(!o)throw new Error(`Workflow "${t}" is not registered.`);let s=new Date().toISOString(),a={id:r.id??qi(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=lo(o),t.updatedAt=new Date().toISOString(),await this.store.save(t,r),await this.audit("workflow.failed",t,{workflowName:t.workflowName,error:t.error,failedStep:t.failedStep}),o}}async get(t,n){return this.store.get(t,n)}async list(t){return this.store.list(t)}async runStep(t,n,r){let o=n.retry??this.options.defaultRetry??{attempts:1},s=Math.max(1,o.attempts);t.currentStep=n.name,t.updatedAt=new Date().toISOString(),await this.store.save(t,r);for(let a=1;a<=s;a+=1){t.attempts[n.name]=a,await this.store.save(t,r);let l;try{l=await bd(c=>Promise.resolve(n.execute(t.context,this.bus,c)),n.timeoutMs,n.name)}catch(c){if(a<s){o.delayMs&&await Id(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:lo(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:lo(c)})}}}async audit(t,n,r){await this.options.auditTrail?.record({type:t,source:"Kernel.WorkflowEngine",subject:n.id,details:r})}};function qt(e,t){return new co(e,t)}i(qt,"createWorkflowEngine");function Yi(e,t,n={}){let r=qt(t,n),o={name:e.name,steps:e.steps};r.register(o);let s=n.id??qi(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 p=await r.start(e.name,c,{id:s});a=p.status==="waiting"?"idle":p.status,l=[...p.completedSteps]}catch(p){let f=await r.get(s);throw a=f?.status==="waiting"?"idle":f?.status??"failed",l=f?.completedSteps??[],p}}}}i(Yi,"createSaga");ht();function Qi(e){return Object.keys(e).sort()}i(Qi,"sortedKeys");function mo(e,t,n,r){if(e===t)return;if(e===null||t===null||typeof e!=typeof t){r.push({path:n,left:e,right:t});return}if(typeof e!="object"||typeof t!="object"){e!==t&&r.push({path:n,left:e,right:t});return}if(Array.isArray(e)||Array.isArray(t)){let l=Array.isArray(e)?e:[],c=Array.isArray(t)?t:[],p=Math.max(l.length,c.length);for(let f=0;f<p;f+=1)mo(l[f],c[f],`${n}[${f}]`,r);return}let o=e,s=t,a=new Set([...Qi(o),...Qi(s)]);for(let l of[...a].sort())mo(o[l],s[l],n?`${n}.${l}`:l,r)}i(mo,"walk");function ea(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(ea,"shadowInformationPackage");function yo(e,t){let n=[];return mo(e,t,"",n),{equal:n.length===0,diffs:n}}i(yo,"compareInformationPackages");function ta(e){let t=[];for(let n=1;n<e.length;n+=1)t.push(yo(e[n-1],e[n]));return t}i(ta,"replayInformationPackages");lr();tn();un();un();async function gr(e,t={}){let n=ln({host:t.host,port:t.port,nodeEnv:t.nodeEnv,processNodeEnv:process.env.NODE_ENV}),{listenArkRunInspector:r}=await Promise.resolve().then(()=>(ma(),ga));return r(e,{bind:n,sseIntervalMs:t.sseIntervalMs})}i(gr,"startArkRunInspector");lr();un();ht();tn();ht();var iu=new Set(["singleton","transient"]);function ya(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(ya,"cloneComponent");function au(e){if(e===void 0)return"singleton";if(typeof e=="string"&&iu.has(e))return e;throw new Error('ArkRun component lifetime must be "singleton" or "transient".')}i(au,"closedLifetime");function ha(){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=au(a.lifetime),p=fo({id:l,lifetime:c,uses:a.uses,reactsTo:a.reactsTo,raises:a.raises,sends:a.sends,extendedInfo:a.extendedInfo});if(!p)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:p,factory:f}),ya(p)},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=>ya(a.component))}}}i(ha,"createComponentRegistry");tn();function lu(e){let t={...e.metadata??{}};if(e.source===void 0)return t;if(t.source&&t.source!==e.source)throw new we(e.source,t.source);return t.source=e.source,t}i(lu,"stampMetadata");function cu(){}i(cu,"ignoreDetachedFailure");async function Oo(e,t,n,r={}){let o=cr({transport:r.transport,ephemeral:r.ephemeral??e.defaultEphemeral,brokerBound:typeof e.broker?.send=="function"}),s=lu(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,cu)}return o}i(Oo,"sendOnArkRunTransport");var Po=1e3,Ra=0;function du(){return Ra+=1,`ark-kernel-${Date.now()}-${Ra}`}i(du,"nextKernelInstanceId");function Aa(e,t){let n=e.constructor?.name;return typeof n=="string"&&n.length>0?n:t}i(Aa,"portConstructorId");function pn(e={}){let t=e.strict??!0,n=e.instanceId??du(),r=e.profile??at,o=e.maxHistorySize??Po,s=hn(),a=Pn(),l=e.metadata??Kn(),c=e.auditTrail===void 0,p=e.auditTrail??xn({maxRecords:o}),f=e.eventContracts??Sn(),y=e.eventBuffer===void 0&&e.outbox===void 0,u=e.eventBuffer??e.outbox??new Me,g=e.projections??Qn({auditTrail:p}),d=new De([In(r),...e.policies??[]]),m=i(()=>{_n(s,a,{requireRegisteredTargets:!0})},"syncGraph"),E=e.ephemeral??!0,S=e.broker,k=new st({intentRegistry:s,dependencyGraph:a,policyEngine:d,strictRegistry:!0,validateIntentNaming:!0,auditTrail:p,eventContracts:f,strictEventContracts:e.strictEventContracts??t,requireKnownSource:e.requireKnownSource??!0,architectureProfile:r,enforceObservedLayerFlow:e.enforceObservedLayerFlow??(t?"hard":"off"),eventBuffer:u,instanceId:n,maxHistorySize:o,onPublish:e.autoApplyProjections===!1?void 0:async D=>{await g.apply(D)}}),v=qt(k,{auditTrail:p}),x=wn({registry:s,eventBus:k,graph:a}),N=ha(),b=typeof S?.send=="function",T=y?"InMemoryEventBuffer":Aa(u,"EventBufferStore"),ie=c?"InMemoryAuditStore":Aa(p,"AuditTrail"),me=cn({stores:[je(T,"outbox"),je(ie,"audit"),je("InMemoryWorkflowStore","workflow")]}),Ne={instanceId:n,profile:r,registry:s,graph:a,metadata:l,auditTrail:p,eventContracts:f,eventBuffer:u,outbox:u,projections:g,policyEngine:d,eventBus:k,workflowEngine:v,observability:x,publisher(D){let pe=k.createPublisher(D);return{source:pe.source,publish:pe.publish,send(J,ze,ve={}){return Oo({eventBus:k,broker:S,defaultEphemeral:E},J,ze,{...ve,source:pe.source})}}},send(D,pe,J={}){return Oo({eventBus:k,broker:S,defaultEphemeral:E},D,pe,J)},register(D){return N.register(D)},resolve(D){return N.resolve(D)},resolveSingleton(D){return N.resolveSingleton(D)},getDependencyInformationPackage(){return Ie({kernelInstanceId:n,components:N.snapshotComponents()})},requestGraph(D){return ar({kernelInstanceId:n,components:N.snapshotComponents()},D)},getInspectorSnapshot(D){return fr({kernelInstanceId:n,host:D?.host,port:D?.port,package:{kernelInstanceId:n,components:N.snapshotComponents()},observability:x.report(),ephemeralDefault:E,brokerBound:b,hardening:me})},startInspector(D){return gr({getInspectorSnapshot:i(J=>Ne.getInspectorSnapshot(J),"getInspectorSnapshot"),requestGraph:i(J=>Ne.requestGraph(J),"requestGraph"),async listInspectorOutbox(){let[J,ze]=await Promise.all([u.list("pending"),u.list("failed")]);return Be([...J,...ze],{sampleLimit:se})},async listInspectorWorkflows(){return We(await v.list(),{sampleLimit:se})}},D)},syncGraph:m,manifest(){return m(),tr({registry:s,policyEngine:d,metadata:l,graph:a,profile:r,projections:g,eventContracts:f,observability:x})}};return Ne}i(pn,"createArkKernel");function _o(e={}){return pn({...e,strict:!0,strictEventContracts:e.strictEventContracts??!0,requireKnownSource:e.requireKnownSource??!0,enforceObservedLayerFlow:e.enforceObservedLayerFlow??"hard"})}i(_o,"createStrictArkKernel");function To(e,t={}){let{profileName:n,...r}=t;return{...r,profile:Mn(e,{name:n})}}i(To,"createOptionsFromConfig");function ka(e,t={}){return pn(To(e,t))}i(ka,"createArkKernelFromConfig");function Ia(e,t={}){return _o(To(e,t))}i(Ia,"createStrictArkKernelFromConfig");function ba(e,t={}){return No(To(e,t))}i(ba,"createLenientArkKernelFromConfig");function No(e={}){return pn({...e,strict:!1,strictEventContracts:e.strictEventContracts??!1,enforceObservedLayerFlow:e.enforceObservedLayerFlow??"off"})}i(No,"createLenientArkKernel");export{Wr as ANALYSIS_IR_SCHEMA_VERSION,Mo as ARK_ANALYSIS_RESULT_SCHEMA,gn as ARK_ANALYSIS_RESULT_SCHEMA_VERSION,Rd as ARK_DESIGN_DELTA_SCHEMA_VERSION,hd as ARK_ENFORCEMENT_STATE_SCHEMA_VERSION,uo as ARK_RUN_COMPONENT_LIFETIMES,At as ARK_RUN_EPHEMERAL_DEFAULT,ko as ARK_RUN_GRAPH_DEFAULT_SLICE,ia as ARK_RUN_GRAPH_NODE_KINDS,aa as ARK_RUN_GRAPH_PROCESS_EDGE_KINDS,Ao as ARK_RUN_GRAPH_SCHEMA_VERSION,Io as ARK_RUN_GRAPH_SLICES,la as ARK_RUN_GRAPH_TECHNICAL_EDGE_KINDS,nr as ARK_RUN_INFORMATION_PACKAGE_SCHEMA_VERSION,dr as ARK_RUN_INSPECTOR_DEFAULT_HOST,wo as ARK_RUN_INSPECTOR_DEFAULT_PORT,rn as ARK_RUN_INSPECTOR_EVENTS_PATH,on as ARK_RUN_INSPECTOR_GRAPH_PATH,se as ARK_RUN_INSPECTOR_MONITOR_SAMPLE_LIMIT,sn as ARK_RUN_INSPECTOR_OUTBOX_PATH,So as ARK_RUN_INSPECTOR_SCHEMA_VERSION,nn as ARK_RUN_INSPECTOR_SNAPSHOT_PATH,Co as ARK_RUN_INSPECTOR_SSE_EVENT,xo as ARK_RUN_INSPECTOR_TRANSPORT_FALLBACK,an as ARK_RUN_INSPECTOR_WORKFLOWS_PATH,en as ARK_RUN_TRANSPORT_KINDS,ce as ArkRunInspectorBindError,kt as ArkRunInspectorProductionError,Po as DEFAULT_MAX_HISTORY_SIZE,Xn as DIAGNOSTIC_CATALOG,cd as DIAGNOSTIC_CATALOG_SCHEMA_VERSION,so as DIAGNOSTIC_DOCS_RELATIVE_PATH,dd as DIAGNOSTIC_RULE_IDS,Ot as EventContractRegistryImpl,Qe as EventContractViolationError,Pt as InMemoryAuditStore,Me as InMemoryEventBuffer,us as InMemoryOutboxStore,Wt as InMemoryReadModelStore,zt as InMemoryWorkflowStore,qe as IntentRegistry,te as InvalidArkRunGraphQueryError,Rt as InvalidArkRunSendOptionError,Ze as InvalidIntentNameError,Je as LayerPolicyContextError,er as MANIFEST_SCHEMA_VERSION,et as ObservedLayerFlowViolationError,Qr as POLICY_DELTA_SCHEMA_VERSION,De as PolicyEngine,Se as PolicyViolationError,Br as RESOLVED_CANDIDATE_FACTS_SCHEMA,He as RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,we as SourceMetadataOverrideError,Le as UnknownEventSourceError,Xe as UnregisteredIntentError,gt as analyzeArchitectureConvergence,Bn as analyzeChange,pi as analyzePolicyDelta,jt as analyzeProject,Bt as analyzeResolvedProject,Ji as appendDecisionTape,kr as architecturalPolicies,ir as arkRunGraphQueryFromSearchParams,be as arkRunInspectorUrl,cn as buildArkRunInspectorHardening,Be as buildArkRunInspectorOutboxMonitor,fr as buildArkRunInspectorSnapshot,We as buildArkRunInspectorWorkflowsMonitor,Ie as buildDependencyInformationPackage,bn as buildPublishPolicyContext,md as catalogFixForRuleId,yd as catalogWhyForRuleId,Or as checkAdapterGovernance,Ls as checkContract,eo as classifyArkPolicyDelta,je as classifyArkRunInspectorStoreDurability,sr as closeArkRunGraphQuery,Eo as closedArkRunEphemeral,vo as closedArkRunTransportKind,Yn as collectAnalysisConfigWarnings,ut as collectForbiddenCapabilityUses,yo as compareInformationPackages,js as createAICodeGate,Ds as createAdapter,Ta as createAdapterResult,Fn as createArchitectureProfile,Mn as createArchitectureProfileFromArkConfig,pn as createArkKernel,ka as createArkKernelFromConfig,tr as createArkManifest,gs as createArkTestHarness,xn as createAuditTrail,Pn as createDependencyGraph,Ts as createElevenLayerArkConfig,is as createEventBus,Sn as createEventContractRegistry,hn as createIntentRegistry,No as createLenientArkKernel,ba as createLenientArkKernelFromConfig,Kn as createMetadataRegistry,wn as createObservabilityReporter,Qn as createProjectionRegistry,jr as createResolvedCandidateFacts,Yi as createSaga,_o as createStrictArkKernel,Ia as createStrictArkKernelFromConfig,qt as createWorkflowEngine,Go as defaultIntentRegistry,In as defineArchitectureProfilePolicy,Ho as defineIntent,An as defineLayerPolicy,Ye as definePolicy,Ns as definePort,jo as definePublishPolicy,no as detectArchitectureCycles,z as deterministicHash,Wi as diagnosticDocsFragment,fd as diagnosticDocsPath,at as elevenLayerProfile,mt as evaluateArchitectureGraph,fi as explainViolation,dt as extractSemanticDependencies,bo as formatArkRunGraphMermaid,dn as formatArkRunInspectorSseEvent,Zn as getDiagnosticCatalogEntry,It as isArkRunInspectorLoopbackHost,ur as isArkRunInspectorProductionEnv,pd as isCataloguedOrArkRuleFamily,ud as isKnownDiagnosticCode,kn as isLayerPolicy,jn as loadContract,xe as loadResolvedCandidateFacts,to as policyDeltaAcknowledgementMatches,ji as preflightChange,Bi as preflightResolvedChange,ta as replayInformationPackages,ar as requestArkRunGraph,ln as resolveArkRunInspectorBind,cr as resolveArkRunSendPlan,Kt as resolvedFactsEvidenceRequirementsHash,gd as serializeDiagnosticCatalog,ea as shadowInformationPackage,$ as stableSerialize,gr as startArkRunInspector,_n as syncRegistryToGraph,Ar as toAdapterDiagnostic,Ue as unavailableArkRunInspectorOutboxMonitor,Ve as unavailableArkRunInspectorWorkflowsMonitor,Rn as validateIntentName,mr as version};
|
|
25
|
+
`).length,l={kind:"import",file:e.path,line:a,excerpt:o.excerpt},c=lc(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(di,"moduleFactsFor");function lc(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(lc,"resolveSpecifier");function ui(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let o=ot(t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});o&&n.push({ruleId:`layer-dependency:${o.from}->${o.to}`,message:o.message??`${o.from} must not depend on ${o.to}.`,edge:r,evidence:r.evidence})}return n}i(ui,"violationsFor");var cc={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 dc(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}i(dc,"hasActiveArkRules");function uc(e,t){return dc(e,t)?z($(Zs({config:e,arkRules:t,warnings:[]}))):z($(zr(e)))}i(uc,"policyHashFor");function jn(e,t,n){let r=typeof e=="string"?Ps(e,t):xr(e,t),o=n?.arkRules??Gt();return{...r,arkRules:o,policyHash:uc(r.config,o)}}i(jn,"loadContract");function pi(e){let t=jn(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=jn(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=eo(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&&to(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(pi,"analyzePolicyDelta");function jt(e){let t=e.files.map(y=>{let u=Ge(y.path);return{path:u,content:y.content,contentHash:z(y.content),layer:de(u,e.contract.config.layers)??null}}).sort((y,u)=>y.path.localeCompare(u.path)),n=new Map(t.map(y=>[y.path,y])),r=[],o=[];for(let y of t){let u=di(y,n);r.push(...u.edges),o.push(...u.capabilityUses)}let s=ui(r,e.contract.config),a=new Map(e.contract.config.layers.map(y=>[y.name,y])),l=new Map(e.contract.config.layers.map(y=>[y.name,new Set(lt(y))]));for(let y of o){let u=n.get(y.file)?.layer;if(!u)continue;let g=a.get(u),d=Ce(y.symbol,g?.forbiddenGlobals??[]);if(d){s.push({ruleId:"FORBIDDEN_GLOBAL",message:`${u} 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(u)?.has(y.capability)&&s.push({ruleId:"CAPABILITY_VIOLATION",message:`${u} 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",p=c==="complete"?[]:[{...cc}],f={schemaVersion:Wr,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:p,valid:c==="complete"&&s.length===0,ir:f}}i(jt,"analyzeProject");function Bn(e){let t=new Map(e.files.map(n=>[Ge(n.path),n]));for(let n of e.changes){let r=Ge(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return jt({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}i(Bn,"analyzeChange");function fi(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(fi,"explainViolation");function no(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 p=[],f;do{if(f=s.pop(),f===void 0)break;o.delete(f),p.push(f)}while(f!==c);p.length>1&&a.push(p.sort())},"connect");for(let c of[...e.keys()].sort())n.has(c)||l(c);return a.sort((c,p)=>c[0]<p[0]?-1:c[0]>p[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(no,"detectArchitectureCycles");function mt(e){let t=e.contentViolations.map(s=>({...s})),n=(e.warnings??[]).map(s=>({...s})),r=new Map(e.files.map(s=>[s,new Set]));for(let s of e.edges){if(s.to&&s.to!==s.from&&!s.typeOnly&&r.has(s.from)&&r.get(s.from)?.add(s.to),!s.to||!s.fromLayer||!s.toLayer)continue;let a=Fe(e.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:e.config.layers});if(!a)continue;let l=a.rule,c=!!l.peerIsolation,p=!c&&!!(s.typeOnly||s.namedBindingsTypeOnly),f=c?rt(a.peerIsolationReason??"cross-slice",{fromPath:s.from,toPath:s.to,fromSlice:a.fromSlice,toSlice:a.toSlice}):void 0,y=l.message?f?`${l.message} (${f})`:l.message:f?`${s.fromLayer} must not ${s.kind} another slice of ${s.toLayer} (${s.from} \u2192 ${s.to}): ${f}`:`${s.fromLayer} must not ${s.kind} ${s.toLayer}.`;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:s.from,line:s.line,fromLayer:s.fromLayer,toLayer:s.toLayer,target:s.to,...s.typeOnly?{typeOnly:!0}:{},...s.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...s.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...s.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!c&&s.portProofEligible?{portProofEligible:!0}:{},...s.kind?{edgeKind:s.kind}:{},...c?{peerIsolation:!0}:{},message:p?`${y} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:y,...p?{failsStrict:!1,severity:"warning"}:{}})}let o=String(e.config.cyclePolicy??"strict").toLowerCase();if(o!=="off"){let s=no(r);o==="soft"||o==="framework-soft"?n.push(...s.map(a=>({...a,message:`${a.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...s)}return{violations:t,warnings:n,safety:e.safety}}i(mt,"evaluateArchitectureGraph");function gi(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(gi,"structureFreezeTarget");var pc=["no-anemic-model"],Ai=["ensureInvariants","assertInvariants","validate","publish","emit","raise","record"],dm=new RegExp(`\\b(${Ai.join("|")})\\b`),ki="(?:_?pendingEvents|domainEvents|uncommittedEvents|recordedEvents)",um=new RegExp(`\\bthis\\.${ki}\\.push\\s*\\(`),pm=new RegExp(`^this\\.${ki}\\s*=\\s*\\[\\s*\\]`);var fc="truncatedUntil";function gc(){return`${Ai.join(", ")}, or events-array .push(`}i(gc,"expectedDomainInvariantWordsPhrase");function ro(e){let t=Object.getOwnPropertyDescriptor(e,fc)?.value;return typeof t=="number"?t:void 0}i(ro,"shapeTruncatedUntil");function mc(e){let t=ro(e);return t==null?"":` shape analysed until character ${t}`}i(mc,"shapeTruncationSuffix");function mi(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(mi,"escapeGlobLiteral");function yc(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+=mi(t[r+1]),r+=1):o==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":o==="?"?n+="[^/]":n+=mi(o)}return new RegExp(`^${n}$`)}i(yc,"globToRegExp");function yt(e,t){return!t||t.length===0?!0:t.some(n=>yc(n).test(e))}i(yt,"matchesAppliesTo");function Ii(e){return pc.includes(e)}i(Ii,"isTier2");function bi(e){return e.mode==="enforced"&&!Ii(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}i(bi,"severityFor");function Oe(e,t,n,r=1){let{severity:o,failsStrict:s}=bi(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(Oe,"baseViolation");function Wn(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}i(Wn,"isInRuleLayer");function zn(e,t,n){return t.filter(r=>!(!r.exported||!yt(r.file,e.appliesTo)||!Wn(r.file,e,n)))}i(zn,"shapesForRule");function hc(e,t,n){let r=[];for(let o of zn(e,t,n))(o.hasPublicSetters||o.hasPublicMutableFields)&&r.push(Oe(e,o.file,`Exported class ${o.className} exposes public mutable state (sensor aggregate-private-state).`));return r}i(hc,"evaluateAggregatePrivateState");function Rc(e,t,n){let r=[];for(let o of zn(e,t,n))if(o.hasPublicConstructor&&!o.hasStaticFactory){if(!(o.hasPublicMutableFields||o.hasPublicSetters||(o.mutatingMethods?.length??0)>0))continue;r.push(Oe(e,o.file,`Exported class ${o.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}return r}i(Rc,"evaluateAlwaysValidFactory");function Ac(e,t,n){let r=[],o=gc();for(let s of zn(e,t,n)){let a=mc(s);ro(s)!=null&&r.push(Oe(e,s.file,`Exported class ${s.className} shape analysed until character ${ro(s)}; later methods may be invisible (sensor domain-event-on-mutation).`));for(let l of s.mutatingMethods)l.referencesGuardOrPublish||r.push(Oe(e,s.file,`Mutating method ${s.className}.${l.name} does not reference ${o} (sensor domain-event-on-mutation).${a}`))}return r}i(Ac,"evaluateDomainEventOnMutation");function kc(e,t){let n=[];for(let r of t.files)yt(r,e.appliesTo)&&Wn(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(Oe(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}i(kc,"evaluateOrchestrationOnly");function Ic(e,t){let n=[];for(let r of t.files)yt(r,e.appliesTo)&&Wn(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(Oe(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}i(Ic,"evaluateThinAdapter");function bc(e,t){let n=[];for(let r of t.files)yt(r,e.appliesTo)&&Wn(r,e,t.layerForFile)&&t.fileHints?.[r]?.persistenceWrite&&n.push(Oe(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(bc,"evaluateWritesViaAggregate");function vc(e,t,n){let r=[];for(let o of zn(e,t,n))if(o.dataOnly===!0){let s=Oe(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(vc,"evaluateNoAnemicModel");function vi(e){if(!e.arkRules.structure.length)return[];let t=[];for(let n of e.arkRules.structure)switch(n.sensor){case"aggregate-private-state":t.push(...hc(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...Rc(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...Ac(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...kc(n,e));break;case"thin-adapter":t.push(...Ic(n,e));break;case"writes-via-aggregate":t.push(...bc(n,e));break;case"no-anemic-model":t.push(...vc(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(vi,"evaluateArkRuleSensors");function Ei(e,t){let n=[],r=t.map(o=>o.replace(/\\/g,"/"));for(let o of e.structure){if(!o.appliesTo||o.appliesTo.length===0||r.some(c=>yt(c,o.appliesTo)))continue;let{severity:a,failsStrict:l}=bi(o);n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule structure "${o.id}" appliesTo matched zero governed files (patterns: ${o.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:o.provenance.sourceFile,line:1,fromLayer:o.provenance.layer,arkruleId:o.id,arkruleSource:o.provenance.sourceFile,severity:a,sensor:o.sensor,failsStrict:l})}for(let o of e.invariants??[]){if(!o.appliesTo||o.appliesTo.length===0||r.some(l=>yt(l,o.appliesTo)))continue;let a=o.mode==="enforced";n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule invariant "${o.id}" appliesTo matched zero governed files (patterns: ${o.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:o.provenance.sourceFile,line:1,fromLayer:o.provenance.layer,arkruleId:o.id,arkruleSource:o.provenance.sourceFile,severity:a?"error":"warning",sensor:"invariant-coverage",failsStrict:a})}return n.sort((o,s)=>o.file.localeCompare(s.file)||o.arkruleId.localeCompare(s.arkruleId)||o.message.localeCompare(s.message))}i(Ei,"collectEmptyAppliesToFindings");var yi=64;function Ec(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(Ec,"stripTrailingDots");function Sc(e){let t=e.trim(),n=t.length>yi?t.slice(0,yi):t;return Ec(n)}i(Sc,"normalizeIntentPrefix");function wc(e){let t=e.toLowerCase();return t.includes("domain")||t.includes("entity")||t.includes("aggregate")||t.includes("model")}i(wc,"layerNameLooksDomain");function Cc(e){return e.some(t=>{let n=Sc(t);return n==="Domain"||n.startsWith("Domain.")})}i(Cc,"ownsDomainIntent");function xc(e,t=[]){return wc(e)||Cc(t)}i(xc,"isDomainRoleLayerName");function Si(e){if(e.arkRulesActive!==!0)return[];let t=(e.layers??[]).filter(c=>xc(c.name,c.intentPrefixes??[])).map(c=>c.name);if(t.length===0)return[];let n=new Set(t);if(!(e.files??[]).some(c=>{let p=typeof c.layer=="string"?c.layer:"";return p.length>0&&n.has(p)}))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)&&!Ii(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(Si,"collectEmptyInvariantCatalogFindings");var hi=/\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)/,Ri=/\bfrom\s+['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)(?:\.[cm]?[jt]sx?)?['"]|require\(\s*['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)/,Oc=/\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 Pc(e){return e==="PersistenceAdapters"}i(Pc,"isPersistenceDriverLayer");function _c(e,t){if(hi.test(e)||Ri.test(e))return!0;if(!t)return!1;for(let n of t){if(Pc(n.layer))return!0;let r=n.specifier;if(!r)continue;let o=`from '${r}'`;if(hi.test(o)||Ri.test(o))return!0}return!1}i(_c,"sourceImportsPersistenceDriver");var Tc=/\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*=)/,Nc=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,Dc=/\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*=/,Lc=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function Fc(e,t,n){if(!t)return null;let r=_c(t,n),o=r&&Oc.test(t);if(t.length<40)return o?{persistenceWrite:!0}:null;let s=t.match(new RegExp(Dc.source,"g"))??[],a=t.match(new RegExp(Lc.source,"g"))??[],l=(t.match(/\bif\s*\(/g)??[]).length,c=(t.match(/\bswitch\s*\(/g)??[]).length,p=s.length>=2||s.length>=1&&a.length>=2||a.length>=3&&l+c>=6,f=Tc.test(t)||Nc.test(t),y=s.length>=1||a.length>=2,u=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),g=r&&y||f&&y||r&&u&&(l>=4||s.length>=1)||f&&r;return!p&&!g&&!o?null:{...p?{orchestrationHeavy:!0}:{},...g?{adapterThick:!0}:{},...o?{persistenceWrite:!0}:{}}}i(Fc,"deriveArkRuleFileHints");function wi(e,t){let n={};for(let[r,o]of Object.entries(e)){let s=r.replace(/\\/g,"/"),a=Fc(r,o,t?.[s]);a&&(n[s]=a)}return n}i(wi,"buildArkRuleFileHints");function Mc(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(Mc,"normalizeExtraMergeTeethClassification");function qn(e){let t=Mc(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(qn,"extraMergeTeethAllowed");function Ci(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(Ci,"classifyResolvedLayerCoverage");var $c=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"];var hm=new Set($c);function xi(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")}i(xi,"isArkRunKernelModuleSpecifier");var Kc=["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"],oo=new Set(Kc);function Oi(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(oo.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(oo.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:oo.has(e.slice(0,r))}i(Oi,"isArkRunTransportBypassSpecifier");var Hc=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],Cm=new Set(Hc);var Pi={"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"},Gc="ARKRUN_INTERACTION_NAME_INCOMPLETE";function Ni(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(Ni,"isDomainRoleLayer");function Uc(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}i(Uc,"compareFindings");function ke(e,t,n,r,o,s,a){let l=e.mode==="enforced"&&a;return{ruleId:Pi[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:fe({ruleId:Pi[t],fromLayer:s?.fromLayer,target:s?.target})}}i(ke,"finding");function Vc(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(Vc,"bagForFile");function _i(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}i(_i,"emitKinds");function Ti(e){return e==="subscribe"||e==="register-handler"}i(Ti,"handleKinds");function jc(e){return e==="resolve"||e==="resolve-singleton"}i(jc,"dependKinds");function Bc(e,t,n){let r=[],o=e.kernelRoots??e.compositionRoots;if(o.length===0)return r.push(ke(e,"arkrun-missing-root","ark.config.json",1,"ArkRun kernelRoots is empty; no createArkKernel factory site is declared.",void 0,n)),r;let s=new Map;for(let a of t){let l=s.get(a.matchedRoot)??[];l.push(a),s.set(a.matchedRoot,l)}for(let a of o){let l=[...s.get(a)??[]].sort((p,f)=>p.file.localeCompare(f.file));if(l.length===0){r.push(ke(e,"arkrun-missing-root","ark.config.json",1,`ArkRun kernel root ${JSON.stringify(a)} matched no governed files and has no createArkKernel factory.`,{target:a},n));continue}if(l.some(p=>p.hasKernelFactory))continue;let c=l[0];r.push(ke(e,"arkrun-missing-root",c.file,1,`ArkRun kernel root ${JSON.stringify(a)} has no createArkKernel / createStrictArkKernel factory.`,{target:a},n))}return r}i(Bc,"evaluateMissingRoot");function Wc(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||!xi(c))continue;let p=r(l.from);p&&Ni(p,s.get(p)??[])&&a.push(ke(e,"arkrun-kernel-in-domain",l.from,l.line,`${p} must not import kernel module ${JSON.stringify(c)}.`,{fromLayer:p,target:c},o))}return a}i(Wc,"evaluateKernelInDomain");function zc(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)),p=[];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 u=o(f.file);!u||!a.has(u)||Ni(u,l.get(u)??[])||p.push(ke(e,"arkrun-direct-new",f.file,f.line,`${u} must not construct ${f.typeName} with new outside an ArkRun composition-root factory.`,{fromLayer:u,target:f.typeName},s))}return p}i(zc,"evaluateDirectNew");function qc(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(!_i(c.kind)&&!Ti(c.kind)&&!jc(c.kind))continue;let p=r(c.file);if(!p||!l.has(p))continue;if(!c.nameLiteral){e.mode==="enforced"&&a.push({code:Gc,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=Vc(n,c.file);if(_i(c.kind)){if(f.raises.has(c.nameLiteral)||f.sends.has(c.nameLiteral))continue;s.push(ke(e,"arkrun-undeclared-emit",c.file,c.line,`Emit ${JSON.stringify(c.nameLiteral)} is not declared in raises or sends.`,{fromLayer:p,target:c.nameLiteral},o));continue}if(Ti(c.kind)){if(f.reactsTo.has(c.nameLiteral))continue;s.push(ke(e,"arkrun-undeclared-handle",c.file,c.line,`Handle ${JSON.stringify(c.nameLiteral)} is not declared in reactsTo.`,{fromLayer:p,target:c.nameLiteral},o));continue}f.uses.has(c.nameLiteral)||s.push(ke(e,"arkrun-undeclared-depend",c.file,c.line,`Depend ${JSON.stringify(c.nameLiteral)} is not declared in uses.`,{fromLayer:p,target:c.nameLiteral},o))}return{findings:s,completenessReasons:a}}i(qc,"evaluateUndeclared");function Yc(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||!Oi(l))continue;let c=n(a.from);!c||!o.has(c)||s.push(ke(e,"arkrun-transport-bypass",a.from,a.line,`${c} must not import broker/queue/emitter ${JSON.stringify(l)}; use the ArkRun kernel transport.`,{fromLayer:c,target:l},r))}return s}i(Yc,"evaluateTransportBypass");function Di(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=qn(e.classification),r=qc(t,e.kernelCalls,e.declarations,e.layerForFile,n),o=[...Bc(t,e.compositionRootHits,n),...Wc(t,e.layers,e.dependencies,e.layerForFile,n),...zc(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...Yc(t,e.dependencies,e.layerForFile,n)].sort(Uc),s=[...r.completenessReasons].sort((a,l)=>{let c=`${a.code}\0${a.file??""}\0${a.message}`,p=`${l.code}\0${l.file??""}\0${l.message}`;return c<p?-1:c>p?1:0});return{findings:o,completenessReasons:s}}i(Di,"evaluateArkRunSensors");function Li(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}i(Li,"isArkOrderModuleSpecifier");var Fi=new Map;function Mi(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(Mi,"escapeAppliesToLiteral");function Xc(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(Xc,"normalizeAppliesToGlob");function Zc(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(Zc,"appliesToBracesBalanced");function Jc(e){let t=Fi.get(e);if(t)return t;let n=Xc(e),r=Zc(n),o="",s=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(o+=Mi(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+=Mi(c)}let a=new RegExp(`^${o}$`);return Fi.set(e,a),a}i(Jc,"globToRegExp");var $i={"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 Qc(e,t){return!t||t.length===0?!0:t.some(n=>Jc(n).test(e))}i(Qc,"matchesArkOrderAppliesTo");function ed(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(ed,"isDomainRoleLayer");function Pe(e,t,n,r,o,s,a){let l=e.mode==="enforced"&&a;return{ruleId:$i[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:fe({ruleId:$i[t],fromLayer:s?.fromLayer,target:s?.target})}}i(Pe,"finding");function Ki(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let n=qn(e.classification),r=[],o=t.planeRoots;if(t.mode==="enforced"&&o.length===0)r.push(Pe(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 p of e.planeRootHits){let f=c.get(p.matchedRoot)??[];f.push(p),c.set(p.matchedRoot,f)}for(let p of o){let f=c.get(p)??[];if(f.length===0){r.push(Pe(t,"arkorder-missing-plane","ark.config.json",1,`ArkOrder plane root ${JSON.stringify(p)} matched no governed files and has no createOrderPlane factory.`,{target:p},n));continue}f.some(y=>y.hasPlaneFactory)||r.push(Pe(t,"arkorder-missing-plane",f[0].file,1,`ArkOrder plane root ${JSON.stringify(p)} has no createOrderPlane factory.`,{target:p},n))}}let s=new Map(e.layers.map(c=>[c.name,c.intentPrefixes??[]]));for(let c of e.dependencies){let p=c.specifier;if(!p||!Li(p))continue;let f=e.layerForFile(c.from);f&&ed(f,s.get(f)??[])&&r.push(Pe(t,"arkorder-kernel-in-domain",c.from,c.line,"Domain-role layer imports arkgate/order; Domain stays plane-free.",{fromLayer:f,target:p},n))}for(let c of e.genericUpdates)r.push(Pe(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(Pe(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(Pe(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 p=e.layerForFile(c.file);!p||!l.has(p)||Qc(c.file,t.appliesTo)&&r.push(Pe(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:p,target:c.key},n))}return r.sort((c,p)=>c.file.localeCompare(p.file)||c.ruleId.localeCompare(p.ruleId)||c.line-p.line),{findings:r,completenessReasons:[]}}i(Ki,"evaluateArkOrderSensors");function Z(e,t,n={}){return{ruleId:e,message:t,...n}}i(Z,"configWarning");function Yn(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(Z("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(Z("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(Z("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(Z("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let p=new Set,f=new Set;for(let d of a){if(!d.name){s.push(Z("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}p.has(d.name)&&f.add(d.name),p.add(d.name),d.forbiddenGlobals!==void 0&&(!Array.isArray(d.forbiddenGlobals)||d.forbiddenGlobals.some(E=>typeof E!="string"))&&s.push(Z("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(Z("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${d.name}" has no file patterns and will never classify files.`,{layer:d.name}));continue}for(let E of m){let S;try{S=ye(E)}catch(v){s.push(Z("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(Z("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(Z("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(Z("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(Z("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${d.to}".`,{fromLayer:d.from,toLayer:d.to}));let y=new Set;if(a.length>1)for(let d of r){let m=-1,E=[];for(let S of a)for(let k of S.patterns??[]){if(!ye(k).test(d))continue;let v=vr(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(Z("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 u=r.filter(d=>!de(d,a));u.length>0&&s.push(Z("CONFIG_UNCLASSIFIED_FILES",`${u.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:u.length,samples:u.slice(0,5)}));let g=Cs(t);if(g.length>0){let d=g[0]??"this layer";s.push(Z("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:xs(d)}))}return s}i(Yn,"collectAnalysisConfigWarnings");function Hi(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:gi({sensor:e.sensor,code:e.code})}:{},...r||o?{freezable:!1}:{},nextAction:t}}i(Hi,"toArkRuleEngineViolation");function td(e){let t=e.arkRules;return!!(t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0)}i(td,"arkRulesMapIsOn");function Gi(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(Gi,"arkRuleFindingNextAction");function nd(e,t){return t.some(n=>{try{return ye(n).test(e)}catch{return!1}})}i(nd,"matchesAny");function rd(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")&&!nd(m.file,s)).map(m=>({file:m.file,line:m.line,kind:m.kind==="dynamic-require"?"require":"import"})),p=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:p,disabledPeerIsolationRules:f,thresholds:{maxTsSuppressions:r,maxAnyCasts:o}},u=[],g=c.filter(m=>m.kind==="import");if(g.length>0){let m=g[0];u.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];u.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];u.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];u.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:m.file,line:m.line,message:`${l.length} explicit any cast(s) exceed safety.maxAnyCasts (${o}).`})}if(p.length>0){let m=p[0];u.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:m.file,line:m.line,message:`${p.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&&u.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:u}}i(rd,"evaluateSafety");function od(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}i(od,"ambientForbiddenGlobal");function Ui(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return Hr(e,n.length>0?n:Kr.map(r=>({name:r.layer,prefixes:r.prefixes})))}i(Ui,"intentLayer");function sd(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||!od(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??[],p=s.source==="import-based"?t.dependencies.find(f=>f.from===s.file&&f.line===s.line&&f.specifier===s.symbol&&!f.typeOnly)?.kind:void 0;if(!(s.source==="ambient-global"&&Dt(s.symbol,c))){if(s.source==="import-based"){let f=Ce(s.symbol,c);if(f){r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:a,target:s.symbol,...p?{edgeKind:p}:{},message:`${a} must not use module "${s.symbol}" because it is the import form of forbidden global "${f}".`});continue}}lt(l).includes(s.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:s.file,line:s.line,fromLayer:a,target:s.symbol,capability:s.capability,...p?{edgeKind:p}:{},message:s.source==="import-based"?`${a} denies the ${s.capability} capability; found import of "${s.symbol}".`:`${a} denies the ${s.capability} capability; found ambient "${s.symbol}".`})}}for(let s of t.publishCalls){let a=n.get(s.file);if(!a)continue;for(let c of Lt({publishCall:!0,rawIntentName:s.rawIntentName,objectHasIntent:s.objectHasIntent,arkPublishCandidate:s.arkPublishCandidate,hasSource:s.hasSource}))r.push({ruleId:c.ruleId,file:s.file,line:s.line,...c.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:a}:{},message:c.message});if(!s.sourceIntent)continue;let l=Ui(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=Ui(s.intent,e.contract);if(!l)continue;let c=Fe(e.contract.config.rules,a,l,{fromPath:s.file,layers:e.contract.config.layers});if(!c)continue;let p=c.rule.peerIsolation?rt(c.peerIsolationReason??"cross-slice",{fromPath:s.file,fromSlice:c.fromSlice,toSlice:c.toSlice}):void 0,f=`${a} must not reference ${l} intent ${s.intent}.`,y=p&&c.peerIsolationReason!=="cross-slice"?`${f} ${p}`:c.rule.message?p?`${c.rule.message} (${p})`: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(sd,"contentViolations");function id(e){let{facts:t}=e,n=Kt(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,Q)=>{let vt=`${R.code}\0${R.file??""}\0${R.message}`,Et=`${Q.code}\0${Q.file??""}\0${Q.message}`;return vt<Et?-1:vt>Et?1:0}),a=t.files.map(R=>({...R,layer:de(R.path,e.contract.config.layers)??null})),l=new Map(a.map(R=>[R.path,R.layer])),c=t.dependencies.map(R=>{let Q=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,...Q?{toLayer:Q}:{}}:{},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}:{}}}),p=Yn({config:e.contract.config,rules:e.contract.config.rules,files:a.map(R=>R.path)}),f=rd(e,t),y=e.contract.arkRules??Gt(),u=a.map(R=>R.path),d={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?wi(e.coverageInputs.fileContents):{},...e.fileHints??{}},m=i(R=>l.get(R)??de(R,e.contract.config.layers),"resolveLayer"),E=[...vi({arkRules:y,classShapes:e.contract.classShapes??t.classShapes??[],files:u,layerForFile:m,fileHints:d}),...Ei(y,u),...Si({arkRulesActive:td(e.contract.config),arkRules:y,layers:e.contract.config.layers??[],files:u.map(R=>({path:R,layer:m(R)}))})],S=(y.invariants?.length??0)>0,k=ni({hasEnforcedInvariant:Xr(y.invariants),coverage:e.contract.config.coverage,...e.coverageRootsPresent===!1?{declaredPathPresent:!1}:{}}),v=k.length>0?[]:ti({adopted:e.adopted===!0,hasDomainInvariants:Yr(y.invariants),coverage:e.contract.config.coverage,...e.invariantTestsPathPresent===!1?{declaredPathPresent:!1}:{}}),x=[...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=>Hi(R,Gi(R,!1))),b=E.filter(R=>!R.failsStrict).map(R=>({...Hi(R,Gi(R,!0)),failsStrict:!1})),T=S?Qs({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},ie=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.`})),me=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).`})),Ne=Ci(a),D=Di({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:Ne}),pe=e.contract.config.arkRun?.mode,J=D.findings.filter(()=>pe==="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}:{}})),ze=D.findings.filter(()=>pe!=="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})),ve=Ki({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:Ne}),bt=e.contract.config.arkOrder?.mode,fn=ve.findings.filter(()=>bt==="enforced").map(R=>({ruleId:R.ruleId,file:R.file,line:R.line,message:R.message,fromLayer:R.fromLayer,target:R.target,nextAction:R.nextAction,sensor:R.sensor,failsStrict:R.failsStrict,...R.severity?{severity:R.severity}:{}})),Do=ve.findings.filter(()=>bt!=="enforced").map(R=>({ruleId:R.ruleId,file:R.file,line:R.line,message:R.message,fromLayer:R.fromLayer,target:R.target,nextAction:R.nextAction,sensor:R.sensor,failsStrict:!1})),w=[...T.partial&&T.coverage.some(R=>R.mode==="enforced"&&R.partial)?[{code:"INVARIANT_COVERAGE_PARTIAL",message:"Enforced ArkRules invariant coverage cannot be fully proven (missing test globs or empty test set); reporting partial, never covered."}]:[],...D.completenessReasons,...ve.completenessReasons],C=mt({config:e.contract.config,rules:e.contract.config.rules,files:a.filter(R=>R.layer).map(R=>R.path),contentViolations:[...sd(e,t,l),...N,...x,...ie,...J,...fn],edges:c,warnings:[...p,...f.warnings,...b,...me,...ze,...Do],safety:f.report}),h=o==="complete"&&w.length>0?"partial":o,A=h==="complete"?s:[...s,...w].sort((R,Q)=>{let vt=`${R.code}\0${R.file??""}\0${R.message}`,Et=`${Q.code}\0${Q.file??""}\0${Q.message}`;return vt<Et?-1:vt>Et?1:0}),L=C.violations.filter(R=>R.failsStrict!==!1),W=h==="complete"&&L.length===0,Ee=W&&C.warnings.every(R=>R.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:h,completenessReasons:A,valid:W,strictValid:Ee,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:C.violations,warnings:C.warnings}}}i(id,"analyzeCanonicalResolvedProject");function Bt(e){return id({contract:e.contract,facts:xe(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints,adopted:e.adopted,invariantTestsPathPresent:e.invariantTestsPathPresent,coverageRootsPresent:e.coverageRootsPresent})}i(Bt,"analyzeResolvedProject");function Vi(e){return z($(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}i(Vi,"analysisTreeHash");function ji(e){let t=jt(e),n=new Map(t.ir.files.map(d=>[d.path,d])),r=[],o=new Set,s=[];for(let d of e.changes){let m=d.path.replace(/\\/g,"/"),E=Ge(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=Bn({...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}}),p=mt({config:e.contract.config,rules:e.contract.config.rules,files:a.ir.files.map(d=>d.path),contentViolations:c,edges:a.ir.edges.filter(d=>!!d.fromLayer).map(d=>({from:d.from,fromLayer:d.fromLayer,...d.to?{to:d.to}:{},...d.toLayer?{toLayer:d.toLayer}:{},line:d.evidence.line,kind:"import",...d.typeOnly?{typeOnly:!0}:{},...d.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),f=r.map(d=>{let m=Ge(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,...p.violations].map(d=>({...d,nextAction:fe(d)})),u=y.filter(d=>d.failsStrict!==!1),g=e.changeMap?gt({changeMap:e.changeMap,changes:f,baseDependencies:t.ir.edges.flatMap(d=>d.to?[{from:d.from,to:d.to}]:[]),candidateDependencies:a.ir.edges.flatMap(d=>d.to?[{from:d.from,to:d.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&a.valid&&u.length===0&&(g?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:a.ir.compilerOptionsHash,baseTreeHash:Vi(t.ir.files),candidateTreeHash:Vi(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:p.warnings}}i(ji,"preflightChange");function ad(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(ad,"canonicalChangePath");function ld(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(ld,"identityViolations");function cd(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(cd,"preparedChange");function Bi(e){let t=xe(e.baseFacts),n=xe(e.candidateFacts),r=Bt({contract:e.contract,facts:t}),o=Bt({contract:e.contract,facts:n}),s=new Map(t.files.map(g=>[g.path,g])),a=new Map(n.files.map(g=>[g.path,g])),l=ld(t,n),c=new Map,p=[];for(let g of e.changes){let d=ad(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}.`})}p.push(cd(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?gt({changeMap:e.changeMap,changes:p,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:fe(g)})),u=y.filter(g=>g.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&o.strictValid&&u.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:p.sort((g,d)=>g.path<d.path?-1:g.path>d.path?1:0),violations:y,warnings:o.ir.warnings}}i(Bi,"preflightResolvedChange");var so="docs/diagnostics.md",dd="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 Xn=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("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.")]),io=new Map(Xn.map(e=>[e.ruleId,e])),ud=Object.freeze(Xn.map(e=>e.ruleId));function pd(e){return typeof e=="string"&&e.length>0&&io.has(e)}i(pd,"isKnownDiagnosticCode");function fd(e){return typeof e!="string"||e.length===0?!1:io.has(e)?!0:e.startsWith("ARKRULE_")}i(fd,"isCataloguedOrArkRuleFamily");function Zn(e){if(!(typeof e!="string"||e.length===0))return io.get(e)}i(Zn,"getDiagnosticCatalogEntry");function Wi(e){return`#${Zn(e)?.docsAnchor??e}`}i(Wi,"diagnosticDocsFragment");function gd(e){return`${so}${Wi(e)}`}i(gd,"diagnosticDocsPath");function md(){return{schemaVersion:"1.0",docsPath:so,codes:Xn}}i(md,"serializeDiagnosticCatalog");function yd(e){return Zn(e)?.fix}i(yd,"catalogFixForRuleId");function hd(e){return Zn(e)?.why}i(hd,"catalogWhyForRuleId");var Rd="1.1";var Ad="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 kd(e){return typeof e.initialState=="function"?e.initialState():e.initialState}i(kd,"initialState");var Jn=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)??kd(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 Qn(e){return new Jn(e)}i(Qn,"createProjectionRegistry");var er="1.0";function Id(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}i(Id,"policyId");var ao=class{constructor(t){this.data=t}data;static{i(this,"ArkManifestImpl")}toJSON(){return{...this.data}}};function tr(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,p=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:Id(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})):[],u=r?r.toJSON():[],g=o?o.toJSON():{nodes:[],edges:[]},d=u.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:mr,exportedAt:new Date().toISOString(),intents:p,relationships:f,policies:y,entities:u,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 ao(E)}i(tr,"createArkManifest");var zi=0;function qi(e){return zi+=1,`${e}-${Date.now()}-${zi}`}i(qi,"createWorkflowId");function lo(e){return e instanceof Error?e.message:String(e)}i(lo,"errorMessage");function bd(e){return new Promise(t=>{setTimeout(t,e)})}i(bd,"sleep");async function vd(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(vd,"withTimeout");var zt=class{static{i(this,"InMemoryWorkflowStore")}snapshots=new Map;save(t,n){let r=this.snapshots.get(t.id);if(r&&r.version!==t.version)throw new Error(`Optimistic concurrency conflict for workflow ${t.id}`);let o=(t.version??0)+1;this.snapshots.set(t.id,{...t,version:o,context:{...t.context}}),t.version=o}get(t,n){let r=this.snapshots.get(t);return r?{...r,context:{...r.context}}:void 0}list(t){return Array.from(this.snapshots.values()).filter(n=>!t||n.workflowName===t).map(n=>({...n,context:{...n.context}}))}claim(t,n,r){let o=Date.now();for(let s of this.snapshots.values()){if(r&&s.workflowName!==r||s.status!=="running"&&s.status!=="compensating")continue;let a=s.expiresAt?new Date(s.expiresAt).getTime()<o:!0;if(!s.ownerId||a){s.ownerId=t,s.expiresAt=new Date(o+n).toISOString();let l=(s.version??0)+1;return s.version=l,this.snapshots.set(s.id,{...s,context:{...s.context}}),{...s,context:{...s.context}}}}}clear(){this.snapshots.clear()}},co=class{constructor(t,n={}){this.bus=t;this.options=n;this.store=n.store??new zt}bus;options;static{i(this,"WorkflowEngineImpl")}definitions=new Map;store;register(t){if(this.definitions.has(t.name))throw new Error(`Workflow "${t.name}" is already registered.`);let n=new Set;for(let r of t.steps){if(n.has(r.name))throw new Error(`Workflow "${t.name}" has duplicate step name "${r.name}".`);n.add(r.name)}if(this.definitions.set(t.name,t),t.startOn){let r=t.startOn;this.bus.subscribe(r.intent,async o=>{await this.start(t.name,r.mapEventToPayload(o))})}}async start(t,n,r={}){let o=this.definitions.get(t);if(!o)throw new Error(`Workflow "${t}" is not registered.`);let s=new Date().toISOString(),a={id:r.id??qi(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=lo(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 vd(c=>Promise.resolve(n.execute(t.context,this.bus,c)),n.timeoutMs,n.name)}catch(c){if(a<s){o.delayMs&&await bd(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:lo(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:lo(c)})}}}async audit(t,n,r){await this.options.auditTrail?.record({type:t,source:"Kernel.WorkflowEngine",subject:n.id,details:r})}};function qt(e,t){return new co(e,t)}i(qt,"createWorkflowEngine");function Yi(e,t,n={}){let r=qt(t,n),o={name:e.name,steps:e.steps};r.register(o);let s=n.id??qi(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 p=await r.start(e.name,c,{id:s});a=p.status==="waiting"?"idle":p.status,l=[...p.completedSteps]}catch(p){let f=await r.get(s);throw a=f?.status==="waiting"?"idle":f?.status??"failed",l=f?.completedSteps??[],p}}}}i(Yi,"createSaga");ht();function Qi(e){return Object.keys(e).sort()}i(Qi,"sortedKeys");function mo(e,t,n,r){if(e===t)return;if(e===null||t===null||typeof e!=typeof t){r.push({path:n,left:e,right:t});return}if(typeof e!="object"||typeof t!="object"){e!==t&&r.push({path:n,left:e,right:t});return}if(Array.isArray(e)||Array.isArray(t)){let l=Array.isArray(e)?e:[],c=Array.isArray(t)?t:[],p=Math.max(l.length,c.length);for(let f=0;f<p;f+=1)mo(l[f],c[f],`${n}[${f}]`,r);return}let o=e,s=t,a=new Set([...Qi(o),...Qi(s)]);for(let l of[...a].sort())mo(o[l],s[l],n?`${n}.${l}`:l,r)}i(mo,"walk");function ea(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(ea,"shadowInformationPackage");function yo(e,t){let n=[];return mo(e,t,"",n),{equal:n.length===0,diffs:n}}i(yo,"compareInformationPackages");function ta(e){let t=[];for(let n=1;n<e.length;n+=1)t.push(yo(e[n-1],e[n]));return t}i(ta,"replayInformationPackages");lr();tn();un();un();async function gr(e,t={}){let n=ln({host:t.host,port:t.port,nodeEnv:t.nodeEnv,processNodeEnv:process.env.NODE_ENV}),{listenArkRunInspector:r}=await Promise.resolve().then(()=>(ma(),ga));return r(e,{bind:n,sseIntervalMs:t.sseIntervalMs})}i(gr,"startArkRunInspector");lr();un();ht();tn();ht();var au=new Set(["singleton","transient"]);function ya(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(ya,"cloneComponent");function lu(e){if(e===void 0)return"singleton";if(typeof e=="string"&&au.has(e))return e;throw new Error('ArkRun component lifetime must be "singleton" or "transient".')}i(lu,"closedLifetime");function ha(){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=lu(a.lifetime),p=fo({id:l,lifetime:c,uses:a.uses,reactsTo:a.reactsTo,raises:a.raises,sends:a.sends,extendedInfo:a.extendedInfo});if(!p)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:p,factory:f}),ya(p)},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=>ya(a.component))}}}i(ha,"createComponentRegistry");tn();function cu(e){let t={...e.metadata??{}};if(e.source===void 0)return t;if(t.source&&t.source!==e.source)throw new we(e.source,t.source);return t.source=e.source,t}i(cu,"stampMetadata");function du(){}i(du,"ignoreDetachedFailure");async function Oo(e,t,n,r={}){let o=cr({transport:r.transport,ephemeral:r.ephemeral??e.defaultEphemeral,brokerBound:typeof e.broker?.send=="function"}),s=cu(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,du)}return o}i(Oo,"sendOnArkRunTransport");var Po=1e3,Ra=0;function uu(){return Ra+=1,`ark-kernel-${Date.now()}-${Ra}`}i(uu,"nextKernelInstanceId");function Aa(e,t){let n=e.constructor?.name;return typeof n=="string"&&n.length>0?n:t}i(Aa,"portConstructorId");function pn(e={}){let t=e.strict??!0,n=e.instanceId??uu(),r=e.profile??at,o=e.maxHistorySize??Po,s=hn(),a=Pn(),l=e.metadata??Kn(),c=e.auditTrail===void 0,p=e.auditTrail??xn({maxRecords:o}),f=e.eventContracts??Sn(),y=e.eventBuffer===void 0&&e.outbox===void 0,u=e.eventBuffer??e.outbox??new Me,g=e.projections??Qn({auditTrail:p}),d=new De([In(r),...e.policies??[]]),m=i(()=>{_n(s,a,{requireRegisteredTargets:!0})},"syncGraph"),E=e.ephemeral??!0,S=e.broker,k=new st({intentRegistry:s,dependencyGraph:a,policyEngine:d,strictRegistry:!0,validateIntentNaming:!0,auditTrail:p,eventContracts:f,strictEventContracts:e.strictEventContracts??t,requireKnownSource:e.requireKnownSource??!0,architectureProfile:r,enforceObservedLayerFlow:e.enforceObservedLayerFlow??(t?"hard":"off"),eventBuffer:u,instanceId:n,maxHistorySize:o,onPublish:e.autoApplyProjections===!1?void 0:async D=>{await g.apply(D)}}),v=qt(k,{auditTrail:p}),x=wn({registry:s,eventBus:k,graph:a}),N=ha(),b=typeof S?.send=="function",T=y?"InMemoryEventBuffer":Aa(u,"EventBufferStore"),ie=c?"InMemoryAuditStore":Aa(p,"AuditTrail"),me=cn({stores:[je(T,"outbox"),je(ie,"audit"),je("InMemoryWorkflowStore","workflow")]}),Ne={instanceId:n,profile:r,registry:s,graph:a,metadata:l,auditTrail:p,eventContracts:f,eventBuffer:u,outbox:u,projections:g,policyEngine:d,eventBus:k,workflowEngine:v,observability:x,publisher(D){let pe=k.createPublisher(D);return{source:pe.source,publish:pe.publish,send(J,ze,ve={}){return Oo({eventBus:k,broker:S,defaultEphemeral:E},J,ze,{...ve,source:pe.source})}}},send(D,pe,J={}){return Oo({eventBus:k,broker:S,defaultEphemeral:E},D,pe,J)},register(D){return N.register(D)},resolve(D){return N.resolve(D)},resolveSingleton(D){return N.resolveSingleton(D)},getDependencyInformationPackage(){return Ie({kernelInstanceId:n,components:N.snapshotComponents()})},requestGraph(D){return ar({kernelInstanceId:n,components:N.snapshotComponents()},D)},getInspectorSnapshot(D){return fr({kernelInstanceId:n,host:D?.host,port:D?.port,package:{kernelInstanceId:n,components:N.snapshotComponents()},observability:x.report(),ephemeralDefault:E,brokerBound:b,hardening:me})},startInspector(D){return gr({getInspectorSnapshot:i(J=>Ne.getInspectorSnapshot(J),"getInspectorSnapshot"),requestGraph:i(J=>Ne.requestGraph(J),"requestGraph"),async listInspectorOutbox(){let[J,ze]=await Promise.all([u.list("pending"),u.list("failed")]);return Be([...J,...ze],{sampleLimit:se})},async listInspectorWorkflows(){return We(await v.list(),{sampleLimit:se})}},D)},syncGraph:m,manifest(){return m(),tr({registry:s,policyEngine:d,metadata:l,graph:a,profile:r,projections:g,eventContracts:f,observability:x})}};return Ne}i(pn,"createArkKernel");function _o(e={}){return pn({...e,strict:!0,strictEventContracts:e.strictEventContracts??!0,requireKnownSource:e.requireKnownSource??!0,enforceObservedLayerFlow:e.enforceObservedLayerFlow??"hard"})}i(_o,"createStrictArkKernel");function To(e,t={}){let{profileName:n,...r}=t;return{...r,profile:Mn(e,{name:n})}}i(To,"createOptionsFromConfig");function ka(e,t={}){return pn(To(e,t))}i(ka,"createArkKernelFromConfig");function Ia(e,t={}){return _o(To(e,t))}i(Ia,"createStrictArkKernelFromConfig");function ba(e,t={}){return No(To(e,t))}i(ba,"createLenientArkKernelFromConfig");function No(e={}){return pn({...e,strict:!1,strictEventContracts:e.strictEventContracts??!1,enforceObservedLayerFlow:e.enforceObservedLayerFlow??"off"})}i(No,"createLenientArkKernel");export{Wr as ANALYSIS_IR_SCHEMA_VERSION,Mo as ARK_ANALYSIS_RESULT_SCHEMA,gn as ARK_ANALYSIS_RESULT_SCHEMA_VERSION,Ad as ARK_DESIGN_DELTA_SCHEMA_VERSION,Rd as ARK_ENFORCEMENT_STATE_SCHEMA_VERSION,uo as ARK_RUN_COMPONENT_LIFETIMES,At as ARK_RUN_EPHEMERAL_DEFAULT,ko as ARK_RUN_GRAPH_DEFAULT_SLICE,ia as ARK_RUN_GRAPH_NODE_KINDS,aa as ARK_RUN_GRAPH_PROCESS_EDGE_KINDS,Ao as ARK_RUN_GRAPH_SCHEMA_VERSION,Io as ARK_RUN_GRAPH_SLICES,la as ARK_RUN_GRAPH_TECHNICAL_EDGE_KINDS,nr as ARK_RUN_INFORMATION_PACKAGE_SCHEMA_VERSION,dr as ARK_RUN_INSPECTOR_DEFAULT_HOST,wo as ARK_RUN_INSPECTOR_DEFAULT_PORT,rn as ARK_RUN_INSPECTOR_EVENTS_PATH,on as ARK_RUN_INSPECTOR_GRAPH_PATH,se as ARK_RUN_INSPECTOR_MONITOR_SAMPLE_LIMIT,sn as ARK_RUN_INSPECTOR_OUTBOX_PATH,So as ARK_RUN_INSPECTOR_SCHEMA_VERSION,nn as ARK_RUN_INSPECTOR_SNAPSHOT_PATH,Co as ARK_RUN_INSPECTOR_SSE_EVENT,xo as ARK_RUN_INSPECTOR_TRANSPORT_FALLBACK,an as ARK_RUN_INSPECTOR_WORKFLOWS_PATH,en as ARK_RUN_TRANSPORT_KINDS,ce as ArkRunInspectorBindError,kt as ArkRunInspectorProductionError,Po as DEFAULT_MAX_HISTORY_SIZE,Xn as DIAGNOSTIC_CATALOG,dd as DIAGNOSTIC_CATALOG_SCHEMA_VERSION,so as DIAGNOSTIC_DOCS_RELATIVE_PATH,ud as DIAGNOSTIC_RULE_IDS,Ot as EventContractRegistryImpl,Qe as EventContractViolationError,Pt as InMemoryAuditStore,Me as InMemoryEventBuffer,us as InMemoryOutboxStore,Wt as InMemoryReadModelStore,zt as InMemoryWorkflowStore,qe as IntentRegistry,te as InvalidArkRunGraphQueryError,Rt as InvalidArkRunSendOptionError,Ze as InvalidIntentNameError,Je as LayerPolicyContextError,er as MANIFEST_SCHEMA_VERSION,et as ObservedLayerFlowViolationError,Qr as POLICY_DELTA_SCHEMA_VERSION,De as PolicyEngine,Se as PolicyViolationError,Br as RESOLVED_CANDIDATE_FACTS_SCHEMA,He as RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,we as SourceMetadataOverrideError,Le as UnknownEventSourceError,Xe as UnregisteredIntentError,gt as analyzeArchitectureConvergence,Bn as analyzeChange,pi as analyzePolicyDelta,jt as analyzeProject,Bt as analyzeResolvedProject,Ji as appendDecisionTape,kr as architecturalPolicies,ir as arkRunGraphQueryFromSearchParams,be as arkRunInspectorUrl,cn as buildArkRunInspectorHardening,Be as buildArkRunInspectorOutboxMonitor,fr as buildArkRunInspectorSnapshot,We as buildArkRunInspectorWorkflowsMonitor,Ie as buildDependencyInformationPackage,bn as buildPublishPolicyContext,yd as catalogFixForRuleId,hd as catalogWhyForRuleId,Or as checkAdapterGovernance,Ls as checkContract,eo as classifyArkPolicyDelta,je as classifyArkRunInspectorStoreDurability,sr as closeArkRunGraphQuery,Eo as closedArkRunEphemeral,vo as closedArkRunTransportKind,Yn as collectAnalysisConfigWarnings,ut as collectForbiddenCapabilityUses,yo as compareInformationPackages,js as createAICodeGate,Ds as createAdapter,Ta as createAdapterResult,Fn as createArchitectureProfile,Mn as createArchitectureProfileFromArkConfig,pn as createArkKernel,ka as createArkKernelFromConfig,tr as createArkManifest,gs as createArkTestHarness,xn as createAuditTrail,Pn as createDependencyGraph,Ts as createElevenLayerArkConfig,is as createEventBus,Sn as createEventContractRegistry,hn as createIntentRegistry,No as createLenientArkKernel,ba as createLenientArkKernelFromConfig,Kn as createMetadataRegistry,wn as createObservabilityReporter,Qn as createProjectionRegistry,jr as createResolvedCandidateFacts,Yi as createSaga,_o as createStrictArkKernel,Ia as createStrictArkKernelFromConfig,qt as createWorkflowEngine,Go as defaultIntentRegistry,In as defineArchitectureProfilePolicy,Ho as defineIntent,An as defineLayerPolicy,Ye as definePolicy,Ns as definePort,jo as definePublishPolicy,no as detectArchitectureCycles,z as deterministicHash,Wi as diagnosticDocsFragment,gd as diagnosticDocsPath,at as elevenLayerProfile,mt as evaluateArchitectureGraph,fi as explainViolation,dt as extractSemanticDependencies,bo as formatArkRunGraphMermaid,dn as formatArkRunInspectorSseEvent,Zn as getDiagnosticCatalogEntry,It as isArkRunInspectorLoopbackHost,ur as isArkRunInspectorProductionEnv,fd as isCataloguedOrArkRuleFamily,pd as isKnownDiagnosticCode,kn as isLayerPolicy,jn as loadContract,xe as loadResolvedCandidateFacts,to as policyDeltaAcknowledgementMatches,ji as preflightChange,Bi as preflightResolvedChange,ta as replayInformationPackages,ar as requestArkRunGraph,ln as resolveArkRunInspectorBind,cr as resolveArkRunSendPlan,Kt as resolvedFactsEvidenceRequirementsHash,md as serializeDiagnosticCatalog,ea as shadowInformationPackage,$ as stableSerialize,gr as startArkRunInspector,_n as syncRegistryToGraph,Ar as toAdapterDiagnostic,Ue as unavailableArkRunInspectorOutboxMonitor,Ve as unavailableArkRunInspectorWorkflowsMonitor,Rn as validateIntentName,mr as version};
|