arkgate 3.8.0 → 3.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
- var Ht="3.8.0";var Vt="1.3";function I(e){return typeof e=="string"&&e.length>0?e:void 0}function st(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function jt(e,t,n){return e==="LAYER_IMPORT_VIOLATION"?t.typeOnly||n.targetTypeOnlyExports===!0||n.namedBindingsTypeOnly===!0?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":n.peerIsolation===!0?"Extract the shared dependency to a shared layer, then preflight again.":`Define a port in ${t.fromLayer??"the source layer"}, inject the ${t.toLayer??"outer-layer"} implementation, then preflight again.`:e==="FORBIDDEN_GLOBAL"?`Inject ${t.target??"the capability"} through a port, then preflight again.`:e==="CAPABILITY_VIOLATION"?`Define a ${I(n.capability)??"capability"} port in ${t.fromLayer??"the walled layer"}, bind the implementation outside it, then preflight again.`:e==="CIRCULAR_DEPENDENCY"?"Extract the shared dependency into a third module, then preflight again.":e==="RAW_EVENT_PUBLISH"?"Publish through a registered intent creator, then run Ark again.":e==="PUBLISH_MISSING_SOURCE"?"Add metadata.source to the publish call, then run Ark again.":`Resolve ${e} without weakening ark.config.json, then run Ark again.`}function Fe(e,t="error"){let n=I(e.ruleId)??I(e.code)??"ARK_UNKNOWN",s=e.severity==="warning"?"warning":t,i={...I(e.target)?{target:I(e.target)}:{},...I(e.fromLayer)?{fromLayer:I(e.fromLayer)}:{},...I(e.toLayer)?{toLayer:I(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}:{},...I(e.capability)?{capability:I(e.capability)}:{},...I(e.edgeKind)?{edgeKind:I(e.edgeKind)}:{}};return{ruleId:n,severity:s,message:I(e.message)??n,location:{file:I(e.file)??"<unknown>",line:st(e.line,1),column:st(e.column,1)},evidence:i,nextAction:I(e.nextAction)??jt(n,i,e)}}function Gt(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 s=t==="complete"?[]:e.completenessReasons&&e.completenessReasons.length>0?e.completenessReasons.map(c=>({code:I(c.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:I(c.message)??`Analysis ${t}: required evidence is incomplete.`,...I(c.file)?{file:I(c.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],i={...I(e.policyHash)?{policyHash:I(e.policyHash)}:{},...I(e.resolverIdentity)?{resolverIdentity:I(e.resolverIdentity)}:{},...I(e.factsHash)?{factsHash:I(e.factsHash)}:{},...I(e.candidateTreeHash)?{candidateTreeHash:I(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let c of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!i[c])throw new Error(`${c} is required for resolved ${t} adapter evidence.`)}let r=[...(e.violations??[]).map(c=>Fe(c,"error")),...(e.warnings??[]).map(c=>Fe(c,"warning"))],a={schemaVersion:"1.3",completenessReasons:s,diagnostics:r};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...a,mode:n,valid:!1,completeness:t,...i};let c={policyHash:i.policyHash,resolverIdentity:i.resolverIdentity,factsHash:i.factsHash,candidateTreeHash:i.candidateTreeHash};return t==="complete"?{...a,mode:n,valid:e.valid,completeness:t,...c}:{...a,mode:n,valid:!1,completeness:t,...c}}return t==="complete"?{...a,mode:n,valid:e.valid,completeness:t,...i}:{...a,mode:n,valid:!1,completeness:t,...i}}var Ut={$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.3"},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}}},nextAction:{type:"string",minLength:1}}}}}};var He=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),je=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Ge=Object.freeze(Object.keys(je).sort()),Me=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"}),Ve=Object.freeze({process:Object.freeze(["process","node:process"])});function pe(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=Me[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let s=e.slice(0,n),i=Me[s];if(i)return i;let r=e.indexOf("/",n+1);return r<0?null:Me[e.slice(0,r)]??null}function H(e,t){for(let n of t)if(Ve[n]?.includes(e))return n;return null}function Ie(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let s=t.slice(0,n).join("."),i=je[s];if(i)return i}return null}function Z(e){if(e?.pure===!0)return[...He].sort();let n=(e?.capabilities?.deny??[]).filter(s=>He.includes(s));return[...new Set(n)].sort()}function de(e,t){if(t.length===0)return!1;let n=new Set(t),s=e.split(".");for(let i=s.length;i>=1;i-=1)if(n.has(s.slice(0,i).join(".")))return!0;return!1}function Ee(e){let t=new Set,n=new Set,s=Object.keys(je);for(let i of e?.forbiddenGlobals??[]){let r=s.filter(a=>a===i||a.startsWith(`${i}.`));if(r.length===0)n.add(i);else for(let a of r)t.add(`ambient:${a}`);for(let a of Ve[i]??[])t.add(`import-exact:${a}`)}for(let i of Z(e)){if(t.add(`import:${i}`),i==="process")for(let r of Ve.process)t.add(`import-exact:${r}`);for(let r of s)Ie(r)===i&&t.add(`ambient:${r}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}var at=new Map;function ot(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function Ue(e){let t="";for(let n=0;n<e.length;n+=1){let s=e[n];if(s==="\\"&&n+1<e.length){let i=e[n+1];if("*?{}[],".includes(i)||i==="\\"){t+="\\"+i,n+=1;continue}t+="/";continue}t+=s}return t}function Bt(e){let t=0;for(let n=0;n<e.length;n+=1){let s=e[n];if(s==="\\"){n+=1;continue}if(s==="{")t+=1;else if(s==="}"&&(t-=1,t<0))return!1}return t===0}function z(e){let t=at.get(e);if(t)return t;let n=Ue(e),s=Bt(n),i="",r=0;for(let c=0;c<n.length;c+=1){let f=n[c];f==="\\"&&c+1<n.length?(i+=ot(n[c+1]),c+=1):f==="*"?n[c+1]==="*"?n[c+2]==="/"?(i+="(?:.*/)?",c+=2):(i+=".*",c+=1):i+="[^/]*":f==="?"?i+="[^/]":f==="{"&&s?(i+="(?:",r+=1):f==="}"&&s&&r>0?(i+=")",r-=1):f===","&&s&&r>0?i+="|":i+=ot(f)}let a=new RegExp(`^${i}$`);return at.set(e,a),a}function Be(e){let t=Ue(String(e)),s=t.split("*")[0].split("/").filter(Boolean).length,i=t.replace(/\*/g,"").length;return s*1e4+i}function V(e,t){let n=String(e).split(/[/\\]/).join("/"),s,i=-1;for(let r of t??[])if(!(r.exclude??[]).some(a=>z(a).test(n))){for(let a of r.patterns??[])if(z(a).test(n)){let c=Be(a);c>i&&(i=c,s=r.name)}}return s}function lt(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),s=new Set(t.map(i=>String(i).toLowerCase()));for(let i=0;i<n.length-1;i+=1)if(s.has(n[i].toLowerCase()))return`${n[i].toLowerCase()}/${n[i+1].toLowerCase()}`}function qt(e){let t=new Set;for(let n of e??[]){let i=Ue(String(n)).split("/").filter(Boolean);for(let r=0;r<i.length;r+=1){let a=i[r];if((a==="**"||a==="*")&&r>0){let c=i[r-1];c&&!c.includes("*")&&!c.includes("{")&&!c.includes("}")&&t.add(c)}}}return[...t]}function zt(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(i=>typeof i=="string"&&i.length>0);let s=(n??[]).find(i=>i.name===t);return qt(s?.patterns)}function T(e,t,n,s){for(let i of e??[])if(!(i.from!==t||i.to!==n)&&i.allowed===!1){if(i.peerIsolation){let r=s?.fromPath,a=s?.toPath;if(!r||!a)continue;let c=zt(i,t,s?.layers);if(c.length===0)continue;let f=lt(r,c),A=lt(a,c);if(!f||!A)continue;if(f!==A)return i;continue}if(t!==n)return i}}function X(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function dt(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function ct(e,t){if(e.isImportDeclaration(t)){let s=t.importClause;if(!s)return!1;if(s.isTypeOnly)return!0;let i=s.namedBindings;return!!(i&&e.isNamedImports(i)&&i.elements.length>0&&i.elements.every(r=>r.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(s=>s.isTypeOnly))}function ft(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},s=e.createCompilerHost(n,!0);return s.getSourceFile=i=>i===t.fileName?t:void 0,s.fileExists=i=>i===t.fileName,s.readFile=i=>i===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,s).getTypeChecker()}function qe(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function ze(e,t,n,s){let i=s.parent&&e.isShorthandPropertyAssignment(s.parent)&&s.parent.name===s,r;try{r=i?t.getShorthandAssignmentValueSymbol(s.parent):qe(t,s)}catch{r=void 0}return!!r?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}function Q(e,t){let n,s=[],i=(a,c,f,A=!1)=>s.push({specifier:f,kind:c,line:dt(t,a),typeOnly:A,unresolved:f===void 0,node:a}),r=a=>{if(e.isImportDeclaration(a))i(a,"import",X(e,a.moduleSpecifier),ct(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)i(a,"export",X(e,a.moduleSpecifier),ct(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))i(a,"require",X(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let c=a.expression.kind===e.SyntaxKind.ImportKeyword,A=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!ze(e,n??(n=ft(e,t)),t,a.expression);(c||A)&&i(a,A?"require":"dynamic-import",X(e,a.arguments[0]))}e.forEachChild(a,r)};return r(t),s}function Kt(e,t){let n=[],s=t;for(;e.isPropertyAccessExpression(s)||e.isElementAccessExpression(s);){if(e.isPropertyAccessExpression(s))n.unshift(s.name.text);else{let i=X(e,s.argumentExpression);if(i===void 0)return;n.unshift(i)}s=s.expression}if(e.isIdentifier(s))return n.unshift(s.text),{root:s,segments:n}}function Yt(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}function pt(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let s=n.length;s>=1;s-=1){let i=n.slice(0,s).join(".");if(e.has(i))return i}}function ee(e,t,n){if(n.length===0)return[];let s=new Set(n),i=ft(e,t),r=new Map,a=new Set;for(let o of t.statements)if(e.isVariableStatement(o))for(let l of o.declarationList.declarations)e.isIdentifier(l.name)&&a.add(l.name.text);let c=o=>{let l=Kt(e,o);if(!l)return;let d=qe(i,l.root),p=d?r.get(d):void 0;return p?[...p,...l.segments.slice(1)]:ze(e,i,t,l.root)||a.has(l.root.text)?void 0:l.segments};for(let o of t.statements)if(e.isVariableStatement(o))for(let l of o.declarationList.declarations){if(!l.initializer||!e.isIdentifier(l.name))continue;let d=c(l.initializer),p=qe(i,l.name);!d||!p||r.set(p,d)}let f=[],A=new Set,g=(o,l)=>{let d=dt(t,l),p=`${o}:${l.getStart(t)}`;A.has(p)||(A.add(p),f.push({name:o,line:d,node:l}))},u=o=>{let l=o.parent&&(e.isPropertyAccessExpression(o.parent)||e.isElementAccessExpression(o.parent))&&o.parent.expression===o;if((e.isPropertyAccessExpression(o)||e.isElementAccessExpression(o))&&!l){let d=c(o),p=d?pt(s,d):void 0;p&&g(p,o)}else e.isIdentifier(o)&&s.has(o.text)&&Yt(e,o)&&!ze(e,i,t,o)&&g(o.text,o);if(e.isVariableDeclaration(o)&&e.isObjectBindingPattern(o.name)&&o.initializer){let d=c(o.initializer);if(d)for(let p of o.name.elements){if(!e.isIdentifier(p.name))continue;let y=p.propertyName?X(e,p.propertyName)??p.propertyName.text:p.name.text,h=pt(s,[...d,y]);h&&g(h,o.initializer)}}e.forEachChild(o,u)};return u(t),f}function Ke(e,t,n){let s=[];for(let i of n?.dependencies??Q(e,t)){if(i.typeOnly||!i.specifier)continue;let r=pe(i.specifier);r&&s.push({capability:r,symbol:i.specifier,line:i.line,source:"import-based"})}for(let i of n?.ambientUses??ee(e,t,Ge)){let r=Ie(i.name);r&&s.push({capability:r,symbol:i.name,line:i.line,source:"ambient-global"})}return s.sort((i,r)=>i.line-r.line||i.capability.localeCompare(r.capability)||i.symbol.localeCompare(r.symbol))}var Ye={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."},We=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 Je(e,t){return t.flatMap((s,i)=>(s.prefixes??s.intentPrefixes??[]).map(r=>({layer:s.name,layerIndex:i,prefix:r.endsWith(".")?r:`${r}.`}))).filter(({prefix:s})=>e.startsWith(s)).sort((s,i)=>i.prefix.length-s.prefix.length||s.layerIndex-i.layerIndex)[0]?.layer}function K(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function fe(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&K(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:Ye.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:Ye.PUBLISH_MISSING_SOURCE}),t}function R(e,t,n){return{ruleId:e,code:e,message:t,...n}}function te(e,t){return e.slice(0,t).split(`
2
- `).length}function Wt(e){let t=[],n=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,s;for(;(s=n.exec(e))!==null;)t.push({value:s[1],index:s.index});return t}function Jt(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 s of n){let i;for(;(i=s.re.exec(e))!==null;){let r=i.index+i[0].indexOf(i[1]),a=i[0],c=s.kind==="import"&&/\bimport\s+type\b/.test(a)||s.kind==="export"&&/\bexport\s+type\b/.test(a);t.push({value:i[1],index:r,kind:s.kind,typeOnly:c})}}return t.sort((s,i)=>s.index-i.index)}function Zt(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),s=[],i=r=>{e.isStringLiteralLike(r)&&s.push({value:r.text,index:r.getStart(n)}),e.forEachChild(r,i)};return i(n),s}function Xt(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))}function Qt(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}function en(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}function ye(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function tn(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}function ut(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(s=>!e.isPropertyAssignment(s)&&!e.isShorthandPropertyAssignment(s)?!1:tn(e,s.name)===n)}function me(e,t,n){return ut(e,t,n)!==void 0}function ue(e,t,n){let s=ut(e,t,n);return s&&e.isPropertyAssignment(s)?s.initializer:void 0}function nn(e,t){let n=ue(e,t,"metadata");return me(e,n,"source")}function yt(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?yt(e,t.name):!1:!1}function rn(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"}function sn(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],s=ye(e,n);return s!==void 0&&K(s)||me(e,n,"intent")||yt(e,n)}function an(e,t){if(!e.isCallExpression(t))return!1;let[n,s,i]=t.arguments;return nn(e,n)||me(e,s,"source")||me(e,i,"source")}function on(e,t){if(!e.isCallExpression(t))return;let[n,s,i]=t.arguments,r=ue(e,n,"metadata");return ye(e,ue(e,r,"source"))??ye(e,ue(e,s,"source"))??ye(e,ue(e,i,"source"))}function ln(e,t,n,s){let i=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=n,a=r?.filePath,c=r?.layer,f=[],A=u=>i.getLineAndCharacterOfPosition(u.getStart(i)).line+1,g=u=>{if(rn(e,u)){let o=u.arguments[0],l=ye(e,o);for(let p of fe({publishCall:!0,rawIntentName:l,objectHasIntent:me(e,o,"intent"),arkPublishCandidate:sn(e,u),hasSource:an(e,u)}))f.push(R(p.ruleId,p.message,{line:A(u),filePath:a}));let d=on(e,u);if(s&&c&&d&&K(d)){let p=s.resolveLayer(d);p&&p!==c&&f.push(R("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${d}" resolves to ${p}, but the target file is classified as ${c}.`,{line:A(u),filePath:a,target:d,fromLayer:c,toLayer:p}))}}e.forEachChild(u,g)};return g(i),f}function mt(e={}){let t=new Set((e.intents||[]).map(r=>typeof r=="string"?r:r.name)),n=e.forbiddenPatterns||[],s=new Set(e.infrastructureLayers??[]),i=e.enforceIntentAllowlist??t.size>0;return{validate(r,a){let c=[],f=a,A=f?.filePath,g=f?.layer,u=e.typescript,o=u?u.createSourceFile(A??"generated.ts",r,u.ScriptTarget.Latest,!0):void 0,l=o?Q(e.typescript,o):void 0,d=l?l.filter(m=>m.specifier!==void 0).map(m=>({value:m.specifier,index:m.node.getStart(o),kind:m.kind,typeOnly:m.typeOnly})):Jt(r),p=e.typescript?Zt(e.typescript,r):Wt(r);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(A))for(let m of l?.filter(({unresolved:b})=>b)??[]){let b=m.kind==="require";c.push(R(b?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${b?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:m.line,filePath:A}))}let y=g!==void 0&&(s.has(g)||en(g)),h=g!==void 0?` If "${g}" 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 m of n)if(m instanceof RegExp){m.lastIndex=0;let b=m.exec(r);m.lastIndex=0,b&&c.push(R("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${m}`,{line:b.index===void 0?void 0:te(r,b.index),filePath:A,suggestion:"Remove infrastructure imports from domain/application layers."+h}))}else r.includes(m)&&c.push(R("FORBIDDEN_SUBSTRING",`Forbidden substring: ${m}`,{line:te(r,r.indexOf(m)),filePath:A}));for(let m of d){let b=e.resolveImportTarget?.(m.value,A)??(e.resolveImportLayer?{layer:e.resolveImportLayer(m.value,A)}:void 0),C=typeof A=="string"?e.resolveImportTarget?.(A)??(e.resolveImportLayer?{layer:g,relPath:void 0}:void 0):void 0,ce=b?.layer;if(ce&&g){let Ce=T(e.architectureProfile?.rules,g,ce,{fromPath:C?.relPath,toPath:b?.relPath,layers:e.architectureLayers});if(Ce){if(m.typeOnly&&!Ce.peerIsolation)continue;let De=!!Ce.peerIsolation;c.push(R("LAYER_IMPORT_VIOLATION",Ce.message??(De?`Layer "${g}" must not import across slices into "${ce}".`:`Layer "${g}" must not import "${ce}".`),{line:te(r,m.index),source:m.value,target:m.value,filePath:A,fromLayer:g,toLayer:ce,suggestion:De?"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:m.kind,peerIsolation:De,...m.typeOnly?{typeOnly:!0}:{}}}));continue}continue}y||m.typeOnly||!Xt(m.value)&&!Qt(m.value)||c.push(R("FORBIDDEN_IMPORT",`Forbidden ${m.kind} target: "${m.value}".`,{line:te(r,m.index),source:m.value,target:m.value,filePath:A,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+h,details:{importKind:m.kind}}))}if(e.policies)for(let m of e.policies){let b=m.check({source:r,context:a});if(b!==!0)if(Array.isArray(b))for(let C of b)c.push(R("POLICY_VIOLATION",C.message,{filePath:A,suggestion:`Fix violation of policy "${m.name}".`}));else b===!1?c.push(R("POLICY_VIOLATION",`Policy ${m.name} failed on generated code`)):c.push(R("POLICY_VIOLATION",b.message))}if(i&&t.size>0)for(let m of p)K(m.value)&&!t.has(m.value)&&c.push(R("UNKNOWN_INTENT",`Unknown intent reference: "${m.value}"`,{line:te(r,m.index),filePath:A,target:m.value,suggestion:`Register intent "${m.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&g)for(let m of p){if(!K(m.value))continue;let b=e.architectureProfile.resolveLayer(m.value);if(!b)continue;let C=T(e.architectureProfile.rules,g,b);C&&c.push(R("LAYER_REFERENCE_VIOLATION",C.message??`Layer "${g}" must not reference "${b}" through "${m.value}".`,{line:te(r,m.index),filePath:A,target:m.value,fromLayer:g,toLayer:b,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:C}}))}if(e.extensions)for(let m of e.extensions)try{let b=m.analyze(r,a);c.push(...b)}catch(b){c.push(R("EXTENSION_ERROR",`Extension "${m.name}" failed: ${b instanceof Error?b.message:String(b)}`))}if(e.typescript&&o&&g&&e.forbiddenGlobals?.[g]?.length)try{let m=e.forbiddenGlobals[g];c.push(...ee(e.typescript,o,m).map(b=>R("FORBIDDEN_GLOBAL",`${g} must not use the ambient global "${b.name}".`,{line:b.line,filePath:A,target:b.name,fromLayer:g,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let b of l??[]){if(b.typeOnly||!b.specifier)continue;let C=H(b.specifier,m);C&&c.push(R("FORBIDDEN_GLOBAL",`${g} must not use module "${b.specifier}" because it is the import form of forbidden global "${C}".`,{line:b.line,filePath:A,source:b.specifier,target:b.specifier,fromLayer:g,details:{importKind:b.kind,forbiddenGlobal:C},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(m){c.push(R("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${m instanceof Error?m.message:String(m)}`))}if(e.typescript&&o&&g&&e.capabilityWalls?.[g]?.length)try{let m=new Set(e.capabilityWalls[g]),b=e.forbiddenGlobals?.[g]??[];for(let C of Ke(e.typescript,o))m.has(C.capability)&&(C.source==="ambient-global"&&de(C.symbol,b)||C.source==="import-based"&&H(C.symbol,b)||c.push(R("CAPABILITY_VIOLATION",C.source==="import-based"?`${g} denies the ${C.capability} capability; found import of "${C.symbol}".`:`${g} denies the ${C.capability} capability; found ambient "${C.symbol}".`,{line:C.line,filePath:A,target:C.symbol,capability:C.capability,fromLayer:g,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(m){c.push(R("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${m instanceof Error?m.message:String(m)}`))}if(e.typescript)try{c.push(...ln(e.typescript,r,a,e.architectureProfile))}catch(m){c.push(R("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${m instanceof Error?m.message:String(m)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:c.length===0,violations:c}}}}var cn="1.0",ve="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",gt=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],pn=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function dn(){let e=[];for(let t of gt)for(let n of gt)t===n||pn.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var Se=dn();var j={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Xe={$schema:"https://json-schema.org/draft/2020-12/schema",$id:ve,title:"ArkGate architecture contract",description:"Versioned contract consumed identically by ArkGate CLI, MCP, and ESLint surfaces.",type:"object",additionalProperties:!1,required:["$schema","schemaVersion","include","layers","rules"],properties:{$schema:{type:"string",minLength:1,default:ve,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:"1.0",default:"1.0"},name:{type:"string",minLength:1},include:{...j,minItems:1,default:["src"]},exclude:{...j,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:Se,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...j,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...j,minItems:1},exclude:j,intentPrefixes:j,description:{type:"string",minLength:1},forbiddenGlobals:j,capabilities:{type:"object",additionalProperties:!1,properties:{deny:{type:"array",uniqueItems:!0,items:{type:"string",enum:["network","filesystem","clock","randomness","environment","process","persistence"]}}}},pure:{type:"boolean"},mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...j,minItems:1}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}}}},re=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
1
+ var jt="3.8.2";var Gt="1.3";function I(e){return typeof e=="string"&&e.length>0?e:void 0}function ct(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function Ut(e,t,n){return e==="LAYER_IMPORT_VIOLATION"?t.typeOnly||n.targetTypeOnlyExports===!0||n.namedBindingsTypeOnly===!0?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":n.peerIsolation===!0?"Extract the shared dependency to a shared layer, then preflight again.":`Define a port in ${t.fromLayer??"the source layer"}, inject the ${t.toLayer??"outer-layer"} implementation, then preflight again.`:e==="FORBIDDEN_GLOBAL"?`Inject ${t.target??"the capability"} through a port, then preflight again.`:e==="CAPABILITY_VIOLATION"?`Define a ${I(n.capability)??"capability"} port in ${t.fromLayer??"the walled layer"}, bind the implementation outside it, then preflight again.`:e==="CIRCULAR_DEPENDENCY"?"Extract the shared dependency into a third module, then preflight again.":e==="RAW_EVENT_PUBLISH"?"Publish through a registered intent creator, then run Ark again.":e==="PUBLISH_MISSING_SOURCE"?"Add metadata.source to the publish call, then run Ark again.":`Resolve ${e} without weakening ark.config.json, then run Ark again.`}function He(e,t="error"){let n=I(e.ruleId)??I(e.code)??"ARK_UNKNOWN",s=e.severity==="warning"?"warning":t,r={...I(e.target)?{target:I(e.target)}:{},...I(e.fromLayer)?{fromLayer:I(e.fromLayer)}:{},...I(e.toLayer)?{toLayer:I(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}:{},...I(e.capability)?{capability:I(e.capability)}:{},...I(e.edgeKind)?{edgeKind:I(e.edgeKind)}:{}};return{ruleId:n,severity:s,message:I(e.message)??n,location:{file:I(e.file)??"<unknown>",line:ct(e.line,1),column:ct(e.column,1)},evidence:r,nextAction:I(e.nextAction)??Ut(n,r,e)}}function Bt(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 s=t==="complete"?[]:e.completenessReasons&&e.completenessReasons.length>0?e.completenessReasons.map(c=>({code:I(c.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:I(c.message)??`Analysis ${t}: required evidence is incomplete.`,...I(c.file)?{file:I(c.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],r={...I(e.policyHash)?{policyHash:I(e.policyHash)}:{},...I(e.resolverIdentity)?{resolverIdentity:I(e.resolverIdentity)}:{},...I(e.factsHash)?{factsHash:I(e.factsHash)}:{},...I(e.candidateTreeHash)?{candidateTreeHash:I(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let c of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!r[c])throw new Error(`${c} is required for resolved ${t} adapter evidence.`)}let i=[...(e.violations??[]).map(c=>He(c,"error")),...(e.warnings??[]).map(c=>He(c,"warning"))],a={schemaVersion:"1.3",completenessReasons:s,diagnostics:i};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...a,mode:n,valid:!1,completeness:t,...r};let c={policyHash:r.policyHash,resolverIdentity:r.resolverIdentity,factsHash:r.factsHash,candidateTreeHash:r.candidateTreeHash};return t==="complete"?{...a,mode:n,valid:e.valid,completeness:t,...c}:{...a,mode:n,valid:!1,completeness:t,...c}}return t==="complete"?{...a,mode:n,valid:e.valid,completeness:t,...r}:{...a,mode:n,valid:!1,completeness:t,...r}}var qt={$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.3"},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}}},nextAction:{type:"string",minLength:1}}}}}};var je=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),Ue=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Be=Object.freeze(Object.keys(Ue).sort()),Ve=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"}),Ge=Object.freeze({process:Object.freeze(["process","node:process"])});function pe(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=Ve[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let s=e.slice(0,n),r=Ve[s];if(r)return r;let i=e.indexOf("/",n+1);return i<0?null:Ve[e.slice(0,i)]??null}function V(e,t){for(let n of t)if(Ge[n]?.includes(e))return n;return null}function Re(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let s=t.slice(0,n).join("."),r=Ue[s];if(r)return r}return null}function X(e){if(e?.pure===!0)return[...je].sort();let n=(e?.capabilities?.deny??[]).filter(s=>je.includes(s));return[...new Set(n)].sort()}function fe(e,t){if(t.length===0)return!1;let n=new Set(t),s=e.split(".");for(let r=s.length;r>=1;r-=1)if(n.has(s.slice(0,r).join(".")))return!0;return!1}function ve(e){let t=new Set,n=new Set,s=Object.keys(Ue);for(let r of e?.forbiddenGlobals??[]){let i=s.filter(a=>a===r||a.startsWith(`${r}.`));if(i.length===0)n.add(r);else for(let a of i)t.add(`ambient:${a}`);for(let a of Ge[r]??[])t.add(`import-exact:${a}`)}for(let r of X(e)){if(t.add(`import:${r}`),r==="process")for(let i of Ge.process)t.add(`import-exact:${i}`);for(let i of s)Re(i)===r&&t.add(`ambient:${i}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}var dt=new Map;function pt(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function qe(e){let t="";for(let n=0;n<e.length;n+=1){let s=e[n];if(s==="\\"&&n+1<e.length){let r=e[n+1];if("*?{}[],".includes(r)||r==="\\"){t+="\\"+r,n+=1;continue}t+="/";continue}t+=s}return t}function zt(e){let t=0;for(let n=0;n<e.length;n+=1){let s=e[n];if(s==="\\"){n+=1;continue}if(s==="{")t+=1;else if(s==="}"&&(t-=1,t<0))return!1}return t===0}function K(e){let t=dt.get(e);if(t)return t;let n=qe(e),s=zt(n),r="",i=0;for(let c=0;c<n.length;c+=1){let f=n[c];f==="\\"&&c+1<n.length?(r+=pt(n[c+1]),c+=1):f==="*"?n[c+1]==="*"?n[c+2]==="/"?(r+="(?:.*/)?",c+=2):(r+=".*",c+=1):r+="[^/]*":f==="?"?r+="[^/]":f==="{"&&s?(r+="(?:",i+=1):f==="}"&&s&&i>0?(r+=")",i-=1):f===","&&s&&i>0?r+="|":r+=pt(f)}let a=new RegExp(`^${r}$`);return dt.set(e,a),a}function ze(e){let t=qe(String(e)),s=t.split("*")[0].split("/").filter(Boolean).length,r=t.replace(/\*/g,"").length;return s*1e4+r}function j(e,t){let n=String(e).split(/[/\\]/).join("/"),s,r=-1;for(let i of t??[])if(!(i.exclude??[]).some(a=>K(a).test(n))){for(let a of i.patterns??[])if(K(a).test(n)){let c=ze(a);c>r&&(r=c,s=i.name)}}return s}function ft(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),s=new Set(t.map(r=>String(r).toLowerCase()));for(let r=0;r<n.length-1;r+=1)if(s.has(n[r].toLowerCase()))return`${n[r].toLowerCase()}/${n[r+1].toLowerCase()}`}function Kt(e){let t=new Set;for(let n of e??[]){let r=qe(String(n)).split("/").filter(Boolean);for(let i=0;i<r.length;i+=1){let a=r[i];if((a==="**"||a==="*")&&i>0){let c=r[i-1];c&&!c.includes("*")&&!c.includes("{")&&!c.includes("}")&&t.add(c)}}}return[...t]}function Yt(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(r=>typeof r=="string"&&r.length>0);let s=(n??[]).find(r=>r.name===t);return Kt(s?.patterns)}function N(e,t,n,s){for(let r of e??[])if(!(r.from!==t||r.to!==n)&&r.allowed===!1){if(r.peerIsolation){let i=s?.fromPath,a=s?.toPath;if(!i||!a)return r;let c=Yt(r,t,s?.layers);if(c.length===0)return r;let f=ft(i,c),A=ft(a,c);if(!f||!A||f!==A)return r;continue}if(t!==n)return r}}function Q(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function mt(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function ut(e,t){if(e.isImportDeclaration(t)){let s=t.importClause;if(!s)return!1;if(s.isTypeOnly)return!0;let r=s.namedBindings;return!!(r&&e.isNamedImports(r)&&r.elements.length>0&&r.elements.every(i=>i.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(s=>s.isTypeOnly))}function gt(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},s=e.createCompilerHost(n,!0);return s.getSourceFile=r=>r===t.fileName?t:void 0,s.fileExists=r=>r===t.fileName,s.readFile=r=>r===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,s).getTypeChecker()}function Ke(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function Ye(e,t,n,s){let r=s.parent&&e.isShorthandPropertyAssignment(s.parent)&&s.parent.name===s,i;try{i=r?t.getShorthandAssignmentValueSymbol(s.parent):Ke(t,s)}catch{i=void 0}return!!i?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}function ee(e,t){let n,s=[],r=(a,c,f,A=!1)=>s.push({specifier:f,kind:c,line:mt(t,a),typeOnly:A,unresolved:f===void 0,node:a}),i=a=>{if(e.isImportDeclaration(a))r(a,"import",Q(e,a.moduleSpecifier),ut(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)r(a,"export",Q(e,a.moduleSpecifier),ut(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))r(a,"require",Q(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let c=a.expression.kind===e.SyntaxKind.ImportKeyword,A=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!Ye(e,n??(n=gt(e,t)),t,a.expression);(c||A)&&r(a,A?"require":"dynamic-import",Q(e,a.arguments[0]))}e.forEachChild(a,i)};return i(t),s}function Wt(e,t){let n=[],s=t;for(;e.isPropertyAccessExpression(s)||e.isElementAccessExpression(s);){if(e.isPropertyAccessExpression(s))n.unshift(s.name.text);else{let r=Q(e,s.argumentExpression);if(r===void 0)return;n.unshift(r)}s=s.expression}if(e.isIdentifier(s))return n.unshift(s.text),{root:s,segments:n}}function Jt(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}function yt(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let s=n.length;s>=1;s-=1){let r=n.slice(0,s).join(".");if(e.has(r))return r}}function te(e,t,n){if(n.length===0)return[];let s=new Set(n),r=gt(e,t),i=new Map,a=new Set;for(let o of t.statements)if(e.isVariableStatement(o))for(let l of o.declarationList.declarations)e.isIdentifier(l.name)&&a.add(l.name.text);let c=o=>{let l=Wt(e,o);if(!l)return;let p=Ke(r,l.root),d=p?i.get(p):void 0;return d?[...d,...l.segments.slice(1)]:Ye(e,r,t,l.root)||a.has(l.root.text)?void 0:l.segments};for(let o of t.statements)if(e.isVariableStatement(o))for(let l of o.declarationList.declarations){if(!l.initializer||!e.isIdentifier(l.name))continue;let p=c(l.initializer),d=Ke(r,l.name);!p||!d||i.set(d,p)}let f=[],A=new Set,g=(o,l)=>{let p=mt(t,l),d=`${o}:${l.getStart(t)}`;A.has(d)||(A.add(d),f.push({name:o,line:p,node:l}))},u=o=>{let l=o.parent&&(e.isPropertyAccessExpression(o.parent)||e.isElementAccessExpression(o.parent))&&o.parent.expression===o;if((e.isPropertyAccessExpression(o)||e.isElementAccessExpression(o))&&!l){let p=c(o),d=p?yt(s,p):void 0;d&&g(d,o)}else e.isIdentifier(o)&&s.has(o.text)&&Jt(e,o)&&!Ye(e,r,t,o)&&g(o.text,o);if(e.isVariableDeclaration(o)&&e.isObjectBindingPattern(o.name)&&o.initializer){let p=c(o.initializer);if(p)for(let d of o.name.elements){if(!e.isIdentifier(d.name))continue;let y=d.propertyName?Q(e,d.propertyName)??d.propertyName.text:d.name.text,h=yt(s,[...p,y]);h&&g(h,o.initializer)}}e.forEachChild(o,u)};return u(t),f}function We(e,t,n){let s=[];for(let r of n?.dependencies??ee(e,t)){if(r.typeOnly||!r.specifier)continue;let i=pe(r.specifier);i&&s.push({capability:i,symbol:r.specifier,line:r.line,source:"import-based"})}for(let r of n?.ambientUses??te(e,t,Be)){let i=Re(r.name);i&&s.push({capability:i,symbol:r.name,line:r.line,source:"ambient-global"})}return s.sort((r,i)=>r.line-i.line||r.capability.localeCompare(i.capability)||r.symbol.localeCompare(i.symbol))}var Je={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."},Ze=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 Xe(e,t){return t.flatMap((s,r)=>(s.prefixes??s.intentPrefixes??[]).map(i=>({layer:s.name,layerIndex:r,prefix:i.endsWith(".")?i:`${i}.`}))).filter(({prefix:s})=>e.startsWith(s)).sort((s,r)=>r.prefix.length-s.prefix.length||s.layerIndex-r.layerIndex)[0]?.layer}function Y(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function ue(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&Y(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:Je.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:Je.PUBLISH_MISSING_SOURCE}),t}function v(e,t,n){return{ruleId:e,code:e,message:t,...n}}function ne(e,t){return e.slice(0,t).split(`
2
+ `).length}function Zt(e){let t=[],n=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,s;for(;(s=n.exec(e))!==null;)t.push({value:s[1],index:s.index});return t}function Xt(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 s of n){let r;for(;(r=s.re.exec(e))!==null;){let i=r.index+r[0].indexOf(r[1]),a=r[0],c=s.kind==="import"&&/\bimport\s+type\b/.test(a)||s.kind==="export"&&/\bexport\s+type\b/.test(a);t.push({value:r[1],index:i,kind:s.kind,typeOnly:c})}}return t.sort((s,r)=>s.index-r.index)}function Qt(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),s=[],r=i=>{e.isStringLiteralLike(i)&&s.push({value:i.text,index:i.getStart(n)}),e.forEachChild(i,r)};return r(n),s}function en(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))}function tn(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}function nn(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}function me(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function rn(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}function ht(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(s=>!e.isPropertyAssignment(s)&&!e.isShorthandPropertyAssignment(s)?!1:rn(e,s.name)===n)}function ge(e,t,n){return ht(e,t,n)!==void 0}function ye(e,t,n){let s=ht(e,t,n);return s&&e.isPropertyAssignment(s)?s.initializer:void 0}function sn(e,t){let n=ye(e,t,"metadata");return ge(e,n,"source")}function At(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?At(e,t.name):!1:!1}function an(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"}function on(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],s=me(e,n);return s!==void 0&&Y(s)||ge(e,n,"intent")||At(e,n)}function ln(e,t){if(!e.isCallExpression(t))return!1;let[n,s,r]=t.arguments;return sn(e,n)||ge(e,s,"source")||ge(e,r,"source")}function cn(e,t){if(!e.isCallExpression(t))return;let[n,s,r]=t.arguments,i=ye(e,n,"metadata");return me(e,ye(e,i,"source"))??me(e,ye(e,s,"source"))??me(e,ye(e,r,"source"))}function dn(e,t,n,s){let r=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),i=n,a=i?.filePath,c=i?.layer,f=[],A=u=>r.getLineAndCharacterOfPosition(u.getStart(r)).line+1,g=u=>{if(an(e,u)){let o=u.arguments[0],l=me(e,o);for(let d of ue({publishCall:!0,rawIntentName:l,objectHasIntent:ge(e,o,"intent"),arkPublishCandidate:on(e,u),hasSource:ln(e,u)}))f.push(v(d.ruleId,d.message,{line:A(u),filePath:a}));let p=cn(e,u);if(s&&c&&p&&Y(p)){let d=s.resolveLayer(p);d&&d!==c&&f.push(v("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${p}" resolves to ${d}, but the target file is classified as ${c}.`,{line:A(u),filePath:a,target:p,fromLayer:c,toLayer:d}))}}e.forEachChild(u,g)};return g(r),f}function bt(e={}){let t=new Set((e.intents||[]).map(i=>typeof i=="string"?i:i.name)),n=e.forbiddenPatterns||[],s=new Set(e.infrastructureLayers??[]),r=e.enforceIntentAllowlist??t.size>0;return{validate(i,a){let c=[],f=a,A=f?.filePath,g=f?.layer,u=e.typescript,o=u?u.createSourceFile(A??"generated.ts",i,u.ScriptTarget.Latest,!0):void 0,l=o?ee(e.typescript,o):void 0,p=l?l.filter(m=>m.specifier!==void 0).map(m=>({value:m.specifier,index:m.node.getStart(o),kind:m.kind,typeOnly:m.typeOnly})):Xt(i),d=e.typescript?Qt(e.typescript,i):Zt(i);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(A))for(let m of l?.filter(({unresolved:b})=>b)??[]){let b=m.kind==="require";c.push(v(b?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${b?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:m.line,filePath:A}))}let y=g!==void 0&&(s.has(g)||nn(g)),h=g!==void 0?` If "${g}" 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 m of n)if(m instanceof RegExp){m.lastIndex=0;let b=m.exec(i);m.lastIndex=0,b&&c.push(v("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${m}`,{line:b.index===void 0?void 0:ne(i,b.index),filePath:A,suggestion:"Remove infrastructure imports from domain/application layers."+h}))}else i.includes(m)&&c.push(v("FORBIDDEN_SUBSTRING",`Forbidden substring: ${m}`,{line:ne(i,i.indexOf(m)),filePath:A}));for(let m of p){let b=e.resolveImportTarget?.(m.value,A)??(e.resolveImportLayer?{layer:e.resolveImportLayer(m.value,A)}:void 0),C=typeof A=="string"?e.resolveImportTarget?.(A)??(e.resolveImportLayer?{layer:g,relPath:void 0}:void 0):void 0,de=b?.layer;if(de&&g){let Ee=N(e.architectureProfile?.rules,g,de,{fromPath:C?.relPath,toPath:b?.relPath,layers:e.architectureLayers});if(Ee){if(m.typeOnly&&!Ee.peerIsolation)continue;let Me=!!Ee.peerIsolation;c.push(v("LAYER_IMPORT_VIOLATION",Ee.message??(Me?`Layer "${g}" must not import across slices into "${de}".`:`Layer "${g}" must not import "${de}".`),{line:ne(i,m.index),source:m.value,target:m.value,filePath:A,fromLayer:g,toLayer:de,suggestion:Me?"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:m.kind,peerIsolation:Me,...m.typeOnly?{typeOnly:!0}:{}}}));continue}continue}y||m.typeOnly||!en(m.value)&&!tn(m.value)||c.push(v("FORBIDDEN_IMPORT",`Forbidden ${m.kind} target: "${m.value}".`,{line:ne(i,m.index),source:m.value,target:m.value,filePath:A,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+h,details:{importKind:m.kind}}))}if(e.policies)for(let m of e.policies){let b=m.check({source:i,context:a});if(b!==!0)if(Array.isArray(b))for(let C of b)c.push(v("POLICY_VIOLATION",C.message,{filePath:A,suggestion:`Fix violation of policy "${m.name}".`}));else b===!1?c.push(v("POLICY_VIOLATION",`Policy ${m.name} failed on generated code`)):c.push(v("POLICY_VIOLATION",b.message))}if(r&&t.size>0)for(let m of d)Y(m.value)&&!t.has(m.value)&&c.push(v("UNKNOWN_INTENT",`Unknown intent reference: "${m.value}"`,{line:ne(i,m.index),filePath:A,target:m.value,suggestion:`Register intent "${m.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&g)for(let m of d){if(!Y(m.value))continue;let b=e.architectureProfile.resolveLayer(m.value);if(!b)continue;let C=N(e.architectureProfile.rules,g,b);C&&c.push(v("LAYER_REFERENCE_VIOLATION",C.message??`Layer "${g}" must not reference "${b}" through "${m.value}".`,{line:ne(i,m.index),filePath:A,target:m.value,fromLayer:g,toLayer:b,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:C}}))}if(e.extensions)for(let m of e.extensions)try{let b=m.analyze(i,a);c.push(...b)}catch(b){c.push(v("EXTENSION_ERROR",`Extension "${m.name}" failed: ${b instanceof Error?b.message:String(b)}`))}if(e.typescript&&o&&g&&e.forbiddenGlobals?.[g]?.length)try{let m=e.forbiddenGlobals[g];c.push(...te(e.typescript,o,m).map(b=>v("FORBIDDEN_GLOBAL",`${g} must not use the ambient global "${b.name}".`,{line:b.line,filePath:A,target:b.name,fromLayer:g,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let b of l??[]){if(b.typeOnly||!b.specifier)continue;let C=V(b.specifier,m);C&&c.push(v("FORBIDDEN_GLOBAL",`${g} must not use module "${b.specifier}" because it is the import form of forbidden global "${C}".`,{line:b.line,filePath:A,source:b.specifier,target:b.specifier,fromLayer:g,details:{importKind:b.kind,forbiddenGlobal:C},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(m){c.push(v("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${m instanceof Error?m.message:String(m)}`))}if(e.typescript&&o&&g&&e.capabilityWalls?.[g]?.length)try{let m=new Set(e.capabilityWalls[g]),b=e.forbiddenGlobals?.[g]??[];for(let C of We(e.typescript,o))m.has(C.capability)&&(C.source==="ambient-global"&&fe(C.symbol,b)||C.source==="import-based"&&V(C.symbol,b)||c.push(v("CAPABILITY_VIOLATION",C.source==="import-based"?`${g} denies the ${C.capability} capability; found import of "${C.symbol}".`:`${g} denies the ${C.capability} capability; found ambient "${C.symbol}".`,{line:C.line,filePath:A,target:C.symbol,capability:C.capability,fromLayer:g,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(m){c.push(v("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${m instanceof Error?m.message:String(m)}`))}if(e.typescript)try{c.push(...dn(e.typescript,i,a,e.architectureProfile))}catch(m){c.push(v("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${m instanceof Error?m.message:String(m)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:c.length===0,violations:c}}}}var pn="1.0",xe="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",Ct=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],fn=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function un(){let e=[];for(let t of Ct)for(let n of Ct)t===n||fn.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var ke=un();var G={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},et={$schema:"https://json-schema.org/draft/2020-12/schema",$id:xe,title:"ArkGate architecture contract",description:"Versioned contract consumed identically by ArkGate CLI, MCP, and ESLint surfaces.",type:"object",additionalProperties:!1,required:["$schema","schemaVersion","include","layers","rules"],properties:{$schema:{type:"string",minLength:1,default:xe,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:"1.0",default:"1.0"},name:{type:"string",minLength:1},include:{...G,minItems:1,default:["src"]},exclude:{...G,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:ke,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...G,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...G,minItems:1},exclude:G,intentPrefixes:G,description:{type:"string",minLength:1},forbiddenGlobals:G,capabilities:{type:"object",additionalProperties:!1,properties:{deny:{type:"array",uniqueItems:!0,items:{type:"string",enum:["network","filesystem","clock","randomness","environment","process","persistence"]}}}},pure:{type:"boolean"},mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...G,minItems:1}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}}}},ie=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
3
3
  ${n.map(s=>`- ${s.path}: ${s.message}`).join(`
4
- `)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function ht(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ze(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function ne(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function fn(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function Re(e,t,n,s,i){if(t.$ref){let r=fn(t.$ref,s);if(!r){i.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}Re(e,r,n,s,i);return}if(t.const!==void 0&&!Object.is(e,t.const)){i.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(r=>Object.is(r,e))){i.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!ht(e)){i.push({path:n,message:`must be an object; received ${ne(e)}`});return}let r=t.properties??{};for(let a of t.required??[])e[a]===void 0&&i.push({path:Ze(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in r||i.push({path:Ze(n,a),message:"unknown field"});for(let[a,c]of Object.entries(r))e[a]!==void 0&&Re(e[a],c,Ze(n,a),s,i);return}if(t.type==="array"){if(!Array.isArray(e)){i.push({path:n,message:`must be an array; received ${ne(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&i.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let r=e.map(a=>JSON.stringify(a));new Set(r).size!==r.length&&i.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((r,a)=>Re(r,t.items,`${n}[${a}]`,s,i));return}if(t.type==="string"){if(typeof e!="string"){i.push({path:n,message:`must be a string; received ${ne(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&i.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&i.push({path:n,message:`must be a boolean; received ${ne(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){i.push({path:n,message:`must be an integer; received ${ne(e)}`});return}t.minimum!==void 0&&e<t.minimum&&i.push({path:n,message:`must be at least ${t.minimum}`})}}function un(e){return{...e,$schema:e.$schema===void 0?ve:e.$schema,schemaVersion:e.schemaVersion===void 0?"1.0":e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?Se.map(t=>({...t})):e.rules}}function yn(e,t="ark.config.json"){if(!ht(e))throw new re(t,[{path:"$",message:`must be an object; received ${ne(e)}`}]);let n=e.schemaVersion===void 0?"unversioned":null;if(e.schemaVersion!==void 0&&e.schemaVersion!=="1.0")throw new re(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.0`}]);return{candidate:un(e),migratedFrom:n}}function xe(e,t="ark.config.json"){let{candidate:n,migratedFrom:s}=yn(e,t),i=[];if(Re(n,Xe,"$",Xe,i),i.length>0)throw new re(t,i);return{config:n,migratedFrom:s}}function Qe(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(s){throw new re(t,[{path:"$",message:`invalid JSON: ${s instanceof Error?s.message:String(s)}`}])}return xe(n,t)}function At(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:ve,schemaVersion:"1.0"};for(let[n,s]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=s);return t}function mn(e){return e.endsWith(".")?e:`${e}.`}function gn(e,t){let n=e.prefixes.length?Math.max(...e.prefixes.map(i=>i.length)):0;return(t.prefixes.length?Math.max(...t.prefixes.map(i=>i.length)):0)-n}function we(e){let t=e.layers.map(i=>({...i,prefixes:i.prefixes.map(mn)})),n=[...t].sort(gn),s=[...e.rules??[]];return{name:e.name,layers:t,rules:s,resolveLayer(i){return t.find(r=>r.match?.(i))?.name??n.find(r=>r.prefixes.some(a=>i.startsWith(a)))?.name}}}function bt(e,t={}){return we({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,s)=>({name:n.name,prefixes:n.intentPrefixes??[],description:n.description,order:s+1})),rules:e.rules??[]})}var hn=[{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}],ke=we({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:hn,rules:Se.map(e=>({...e}))}),An={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 Ct(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,s=t==="."?"":`${t}/`;return At({include:e.include??[t],layers:ke.layers.map(i=>({name:i.name,patterns:(An[i.name]??[i.name]).map(r=>`${s}${r}/**`),intentPrefixes:i.prefixes,optional:n})),rules:[...ke.rules]})}var et="1.0",Et="1.0",Rt=["network","filesystem","clock","randomness","environment","process","persistence"];function k(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")}`}function v(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(v).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${v(t[n])}`).join(",")}}`}function B(e,t){let n=v(e),s=v(t);return n<s?-1:n>s?1:0}function $(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}function Pe(e){let t={schemaVersion:"1.0",include:$(e.include??[]),exclude:$(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:$(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:$(n.patterns??[]),exclude:$(n.exclude??[]),forbiddenGlobals:$(n.forbiddenGlobals??[]),intentPrefixes:$(n.intentPrefixes??[]),capabilityDeny:$(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}};return k(v(t))}function bn(e){let t=e.completenessReasons.map(u=>({code:u.code,message:u.message,...u.file?{file:u.file}:{}})).sort(B),n=e.files.map(u=>({...u,typeOnlyExportNames:$(u.typeOnlyExportNames)})).sort((u,o)=>u.path<o.path?-1:u.path>o.path?1:0),s=e.dependencies.map(u=>({...u,...u.namedBindings?{namedBindings:$(u.namedBindings)}:{}})).sort(B),i=e.capabilityUses.map(u=>({...u})).sort(B),r=e.ambientUses.map(u=>({...u})).sort(B),a=e.publishCalls.map(u=>({...u})).sort(B),c=e.intentReferences.map(u=>({...u})).sort(B),f=e.safetyUses.map(u=>({...u})).sort(B),A=e.files.map(({path:u,contentHash:o})=>({path:u,contentHash:o})).sort((u,o)=>u.path<o.path?-1:u.path>o.path?1:0),g=k(v(A));return{schemaVersion:"1.0",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:g,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:s,capabilityUses:i,ambientUses:r,publishCalls:a,intentReferences:c,safetyUses:f}}function vt(e){let t=bn(e);return{...t,factsHash:k(v(t))}}function St(e){return vt(kt(_(e,"$"),!1))}function _(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}function N(e,t,n){let s=new Set(t),i=Object.keys(e).find(r=>!s.has(r));if(i)throw new Error(`${n}.${i} is not part of schema 1.0.`)}function x(e,t,n){let s=e[t];if(typeof s!="string"||s.length===0)throw new Error(`${n}.${t} must be a non-empty string.`);return s}function ie(e,t,n){if(e[t]!==void 0)return x(e,t,n)}function D(e,t,n){let s=x(e,t,n),i=s.replace(/\\/g,"/");if(!i||i.startsWith("/")||/^[A-Za-z]:\//.test(i)||/[\u0000-\u001f\u007f]/.test(i))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let r=[];for(let c of i.split("/"))if(!(!c||c==="."))if(c===".."){if(r.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);r.pop()}else r.push(c);let a=r.join("/");if(!a||a!==s)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return a}function L(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}function xt(e,t,n){let s=e[t];if(!Number.isInteger(s)||Number(s)<0)throw new Error(`${n}.${t} must be a non-negative integer.`);return Number(s)}function se(e,t,n){let s=xt(e,t,n);if(s===0)throw new Error(`${n}.${t} must be a positive integer.`);return s}function G(e,t,n){let s=e[t];if(!Array.isArray(s))throw new Error(`${n}.${t} must be an array.`);return s}function U(e,t,n,s){let i=e[t];if(typeof i!="string"||!n.includes(i))throw new Error(`${s}.${t} must be one of ${n.join(", ")}.`);return i}function It(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!n))throw new Error(`${t} must be an array of non-empty strings.`);return[...e]}function Cn(e,t,n){let s=new Set;for(let i of e){let r=t(i);if(s.has(r))throw new Error(`${n} must not contain duplicate facts (${r}).`);s.add(r)}}function kt(e,t){N(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=U(e,"schemaVersion",["1.0"],"$"),s=U(e,"completeness",["complete","partial","unavailable"],"$"),i=G(e,"completenessReasons","$").map((d,p)=>{let y=`$.completenessReasons[${p}]`,h=_(d,y);N(h,["code","message","file"],y);let m=h.file===void 0?void 0:D(h,"file",y);return{code:x(h,"code",y),message:x(h,"message",y),...m?{file:m}:{}}});if(s==="complete"&&i.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(s!=="complete"&&i.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let r=G(e,"files","$").map((d,p)=>{let y=`$.files[${p}]`,h=_(d,y);return N(h,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],y),{path:D(h,"path",y),contentHash:x(h,"contentHash",y),parseStatus:U(h,"parseStatus",["parsed","invalid"],y),parseDiagnosticCount:xt(h,"parseDiagnosticCount",y),exportsOnlyTypes:L(h,"exportsOnlyTypes",y),typeOnlyExportNames:It(h.typeOnlyExportNames,`${y}.typeOnlyExportNames`),hasTopLevelSideEffects:L(h,"hasTopLevelSideEffects",y)}}),a=G(e,"dependencies","$").map((d,p)=>{let y=`$.dependencies[${p}]`,h=_(d,y);N(h,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],y);let m=ie(h,"specifier",y),b=ie(h,"target",y),C=U(h,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],y);if(C==="resolved-project"&&!b)throw new Error(`${y}.target is required for resolved-project dependencies.`);if(C!=="resolved-project"&&b)throw new Error(`${y}.target is only allowed for resolved-project dependencies.`);if(C!=="dynamic"&&!m)throw new Error(`${y}.specifier is required unless resolution is dynamic.`);return{from:D(h,"from",y),...m?{specifier:m}:{},kind:U(h,"kind",["import","export","dynamic-import","require"],y),typeOnly:L(h,"typeOnly",y),line:se(h,"line",y),resolution:C,...b?{target:D(h,"target",y)}:{},...h.namedBindings!==void 0?{namedBindings:It(h.namedBindings,`${y}.namedBindings`)}:{},...h.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:L(h,"targetTypeOnlyExports",y)}:{},...h.sourcePureTypeModule!==void 0?{sourcePureTypeModule:L(h,"sourcePureTypeModule",y)}:{},...h.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:L(h,"namedBindingsTypeOnly",y)}:{},...h.portProofEligible!==void 0?{portProofEligible:L(h,"portProofEligible",y)}:{}}}),c=G(e,"capabilityUses","$").map((d,p)=>{let y=`$.capabilityUses[${p}]`,h=_(d,y);return N(h,["file","line","symbol","capability","source"],y),{file:D(h,"file",y),line:se(h,"line",y),symbol:x(h,"symbol",y),capability:U(h,"capability",Rt,y),source:U(h,"source",["ambient-global","import-based"],y)}}),f=G(e,"ambientUses","$").map((d,p)=>{let y=`$.ambientUses[${p}]`,h=_(d,y);return N(h,["file","line","symbol"],y),{file:D(h,"file",y),line:se(h,"line",y),symbol:x(h,"symbol",y)}}),A=G(e,"publishCalls","$").map((d,p)=>{let y=`$.publishCalls[${p}]`,h=_(d,y);N(h,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],y);let m=ie(h,"rawIntentName",y),b=ie(h,"sourceIntent",y);return{file:D(h,"file",y),line:se(h,"line",y),...m?{rawIntentName:m}:{},objectHasIntent:L(h,"objectHasIntent",y),arkPublishCandidate:L(h,"arkPublishCandidate",y),hasSource:L(h,"hasSource",y),...b?{sourceIntent:b}:{}}}),g=G(e,"intentReferences","$").map((d,p)=>{let y=`$.intentReferences[${p}]`,h=_(d,y);return N(h,["file","line","intent"],y),{file:D(h,"file",y),line:se(h,"line",y),intent:x(h,"intent",y)}}),u=G(e,"safetyUses","$").map((d,p)=>{let y=`$.safetyUses[${p}]`,h=_(d,y);N(h,["file","line","kind","symbol"],y);let m=ie(h,"symbol",y),b=U(h,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],y);if(b==="in-memory-store"&&!m)throw new Error(`${y}.symbol is required for in-memory-store facts.`);if(b!=="in-memory-store"&&m)throw new Error(`${y}.symbol is only allowed for in-memory-store facts.`);return{file:D(h,"file",y),line:se(h,"line",y),kind:b,...m?{symbol:m}:{}}});Cn(r,d=>d.path,"$.files");let o=new Set(r.map(d=>d.path));for(let d of r){if(d.parseStatus==="parsed"&&d.parseDiagnosticCount!==0)throw new Error(`$.files[${d.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(d.parseStatus==="invalid"&&d.parseDiagnosticCount===0)throw new Error(`$.files[${d.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(s==="complete"&&r.some(d=>d.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let d of a)if(!o.has(d.from))throw new Error(`$.dependencies references missing source file ${d.from}.`);for(let[d,p]of[["$.capabilityUses",c],["$.ambientUses",f],["$.publishCalls",A],["$.intentReferences",g],["$.safetyUses",u]])for(let y of p)if(!o.has(y.file))throw new Error(`${d} references missing file ${y.file}.`);let l=ie(e,"projectPackageName","$");return{schemaVersion:n,completeness:s,completenessReasons:i,resolverIdentity:x(e,"resolverIdentity","$"),compilerIdentity:x(e,"compilerIdentity","$"),compilerOptionsHash:x(e,"compilerOptionsHash","$"),tsconfigHash:x(e,"tsconfigHash","$"),evidenceRequirementsHash:x(e,"evidenceRequirementsHash","$"),...l?{projectPackageName:l}:{},files:r,dependencies:a,capabilityUses:c,ambientUses:f,publishCalls:A,intentReferences:g,safetyUses:u}}function Y(e){let t=_(e,"$"),n=x(t,"factsHash","$"),s=x(t,"candidateTreeHash","$"),i=vt(kt(t,!0));if(i.factsHash!==n)throw new Error(`$.factsHash does not match the canonical payload (${i.factsHash}).`);if(s!==i.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${i.candidateTreeHash}).`);return i}var E={type:"string",minLength:1},ae={type:"integer",minimum:1},F={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},wt={$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:{const:"1.0"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:E,message:E,file:F}}},resolverIdentity:E,compilerIdentity:E,compilerOptionsHash:E,tsconfigHash:E,candidateTreeHash:E,evidenceRequirementsHash:E,projectPackageName:E,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:F,contentHash:E,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:E},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:F,specifier:E,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:ae,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:F,namedBindings:{type:"array",items:E},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:F,line:ae,symbol:E,capability:{enum:Rt},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:F,line:ae,symbol:E}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:F,line:ae,rawIntentName:E,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:E}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:F,line:ae,intent:E}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:F,line:ae,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:E},allOf:[{if:{properties:{kind:{const:"in-memory-store"}}},then:{required:["symbol"]},else:{not:{required:["symbol"]}}}]}},factsHash:E},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}}}}]};function P(e){return`${e.from}->${e.to}`}function ge(e,t,n,s="dependency"){return{id:`${e}:${s}:${P(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${P(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${P(t)}, then preflight again.`}:e==="unplanned"?{nextAction:s==="dependency-removed"?`Restore the removed dependency ${P(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${P(t)} from the candidate, then preflight again.`}:{}}}function oe(e){let t=[],n=new Map(e.changeMap.map.files.map(o=>[o.path,o])),s=new Map(e.changes.map(o=>[o.path,o])),i=new Map(e.changeMap.map.dependencies.map(o=>[P(o),o])),r=new Map(e.baseDependencies.map(o=>[P(o),o])),a=new Map(e.candidateDependencies.map(o=>[P(o),o]));for(let o of[...n.values()].sort((l,d)=>l.path.localeCompare(d.path))){let l=s.get(o.path);l?l.operation!==o.operation?t.push({id:`contradictory:file:${o.path}`,classification:"contradictory",subject:"file",path:o.path,expectedOperation:o.operation,actualOperation:l.operation,message:`${o.path} was planned as ${o.operation} but the actual operation is ${l.operation}.`,nextAction:`Change ${o.path} to the planned ${o.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${o.path}`,classification:"satisfied",subject:"file",path:o.path,expectedOperation:o.operation,actualOperation:l.operation,message:`${o.path} matches the planned ${o.operation} operation.`}):t.push({id:`missing:file:${o.path}`,classification:"missing",subject:"file",path:o.path,expectedOperation:o.operation,message:`${o.path} was planned as ${o.operation} but is absent from the actual change.`,nextAction:`${o.operation[0].toUpperCase()}${o.operation.slice(1)} ${o.path} in the complete change set, then preflight again.`})}for(let o of[...s.values()].sort((l,d)=>l.path.localeCompare(d.path)))n.has(o.path)||t.push({id:`unplanned:file:${o.path}`,classification:"unplanned",subject:"file",path:o.path,actualOperation:o.operation,message:`${o.path} has an unplanned ${o.operation} operation.`,nextAction:`Remove ${o.path} from the change set, then preflight again.`});let c=new Set;for(let o of[...i.values()].sort((l,d)=>P(l).localeCompare(P(d)))){if(a.has(P(o))){t.push(ge("satisfied",o,`${o.from} -> ${o.to} exists in the candidate architecture.`));continue}let l={from:o.to,to:o.from};a.has(P(l))?(c.add(P(l)),t.push(ge("contradictory",o,`${o.from} -> ${o.to} was planned, but the candidate contains the reverse edge.`))):t.push(ge("missing",o,`${o.from} -> ${o.to} is absent from the candidate architecture.`))}let f=new Set([...n.keys(),...s.keys()]);for(let[o,l]of[...a].sort(([d],[p])=>d.localeCompare(p)))r.has(o)||i.has(o)||c.has(o)||!f.has(l.from)&&!f.has(l.to)||t.push({...ge("unplanned",l,`${l.from} -> ${l.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let A=new Set(e.changeMap.map.files.filter(o=>o.operation==="delete").map(o=>o.path));for(let[o,l]of[...r].sort(([d],[p])=>d.localeCompare(p)))a.has(o)||A.has(l.from)||A.has(l.to)||!f.has(l.from)&&!f.has(l.to)||t.push({...ge("unplanned",l,`${l.from} -> ${l.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let g={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((o,l)=>g[o.classification]-g[l.classification]||(o.subject===l.subject?0:o.subject==="file"?-1:1)||o.id.localeCompare(l.id));let u={satisfied:t.filter(o=>o.classification==="satisfied").length,missing:t.filter(o=>o.classification==="missing").length,contradictory:t.filter(o=>o.classification==="contradictory").length,unplanned:t.filter(o=>o.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:u.missing===0&&u.contradictory===0&&u.unplanned===0,behavioralCompletion:"not-evaluated",summary:u,findings:t}}var tt="1.0";function S(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}})}function O(e){return[...new Set(e??[])].sort()}function W(e,t,n,s,i){let r=O(n),a=O(s),c=new Set(r),f=new Set(a),A=a.filter(u=>!c.has(u)),g=r.filter(u=>!f.has(u));A.length===0&&g.length===0||(A.length>0&&S(e,{kind:"added",path:t,classification:i.added,message:i.addedMessage,before:r,after:a}),g.length>0&&S(e,{kind:"removed",path:t,classification:i.removed,message:i.removedMessage,before:r,after:a}))}function Oe(e,t,n,s,i,r,a){if(n===s)return;S(e,{kind:s?"enabled":"disabled",path:t,classification:s?i:i==="strengthening"?"weakening":"strengthening",message:s?r:a,before:n,after:s})}function Le(e,t){let n=new Map,s=new Set;for(let i of e){let r=t(i);n.has(r)?s.add(r):n.set(r,i)}return{values:n,duplicates:[...s].sort()}}function In(e,t,n){let s=Le(t,r=>r.name),i=Le(n,r=>r.name);(s.duplicates.length>0||i.duplicates.length>0)&&S(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:s.duplicates,after:i.duplicates});for(let r of[...new Set([...s.values.keys(),...i.values.keys()])].sort()){let a=s.values.get(r),c=i.values.get(r),f=`$.layers[${r}]`;if(!a&&c){S(e,{kind:"layer-added",path:f,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:c});continue}if(a&&!c){S(e,{kind:"layer-removed",path:f,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:a});continue}if(!a||!c)continue;W(e,`${f}.patterns`,a.patterns,c.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),W(e,`${f}.exclude`,a.exclude,c.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let A=Ee(a),g=Ee(c);W(e,`${f}.forbiddenGlobals`,A.rawGlobals,g.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),W(e,`${f}.capabilities`,A.atoms,g.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)."}),O(a.intentPrefixes).join("\0")!==O(c.intentPrefixes).join("\0")&&S(e,{kind:"intent-prefixes-changed",path:`${f}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:O(a.intentPrefixes),after:O(c.intentPrefixes)}),Oe(e,`${f}.mayImportInfrastructure`,a.mayImportInfrastructure===!0,c.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),Oe(e,`${f}.optional`,a.optional===!0,c.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.")}}function En(e,t,n){let s=a=>`${a.from}->${a.to}`,i=Le(t,s),r=Le(n,s);(i.duplicates.length>0||r.duplicates.length>0)&&S(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:i.duplicates,after:r.duplicates});for(let a of[...new Set([...i.values.keys(),...r.values.keys()])].sort()){let c=i.values.get(a),f=r.values.get(a),A=`$.rules[${a}]`;if(!c&&f){f.allowed===!1&&S(e,{kind:"deny-added",path:A,classification:"strengthening",message:"A denied dependency edge was added.",after:f});continue}if(c&&!f){c.allowed===!1&&S(e,{kind:"deny-removed",path:A,classification:"weakening",message:"A denied dependency edge was removed.",before:c});continue}if(!c||!f)continue;c.allowed!==f.allowed&&S(e,{kind:f.allowed?"deny-disabled":"deny-enabled",path:`${A}.allowed`,classification:f.allowed?"weakening":"strengthening",message:f.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:c.allowed,after:f.allowed});let g=c.peerIsolation===!0,u=f.peerIsolation===!0;if(g!==u){let o=c.from===c.to&&f.from===f.to;S(e,{kind:u?"peer-isolation-enabled":"peer-isolation-disabled",path:`${A}.peerIsolation`,classification:o?u?"strengthening":"weakening":"judgment-required",message:o?u?"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:g,after:u})}O(c.sliceFolders).join("\0")!==O(f.sliceFolders).join("\0")&&S(e,{kind:"slice-folders-changed",path:`${A}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:O(c.sliceFolders),after:O(f.sliceFolders)})}}function Rn(e,t,n){let s=t.safety??{},i=n.safety??{};for(let r of["maxTsSuppressions","maxAnyCasts"]){let a=s[r]??0,c=i[r]??0;a!==c&&S(e,{kind:c>a?"threshold-raised":"threshold-lowered",path:`$.safety.${r}`,classification:c>a?"weakening":"strengthening",message:c>a?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:a,after:c})}for(let r of["allowInMemory","allowDisabledPeerIsolation"])Oe(e,`$.safety.${r}`,s[r]===!0,i[r]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}function vn(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"}function nt(e,t){let n=[];W(n,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),W(n,"$.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."}),W(n,"$.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."}),Oe(n,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let s={off:0,soft:1,"framework-soft":1,strict:2},i=e.cyclePolicy??"strict",r=t.cyclePolicy??"strict";if(i!==r){let a=s[r]===s[i]?"judgment-required":s[r]>s[i]?"strengthening":"weakening";S(n,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:a,message:"The cycle enforcement level changed.",before:i,after:r})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&S(n,{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}),In(n,e.layers,t.layers),En(n,e.rules,t.rules),Rn(n,e,t),n.sort((a,c)=>a.path.localeCompare(c.path)||a.id.localeCompare(c.id)),{schemaVersion:tt,classification:vn(n),findings:n}}function rt(e,t){if(!e||e.schemaVersion!==tt||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(i=>typeof i!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=O(e.findingIds),s=O(t.findingIds);return n.length===s.length&&n.every((i,r)=>i===s[r])}function J(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("/")}function Pt(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}function q(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}function he(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let s=t,i="";for(t+=1;t<e.length;t+=1){let r=e[t];if(r===n)return{value:i,offset:s,excerpt:e.slice(s,t+1)};r==="\\"&&t+1<e.length?(i+=e[t+1],t+=1):i+=r}}function M(e,t,n){return e.startsWith(t,n)&&!Pt(e[n-1])&&!Pt(e[n+t.length])}function Sn(e,t){if(t=q(e,t+6),e[t]==="(")return he(e,q(e,t+1));let n=!1;if(M(e,"type",t)){let i=q(e,t+4);e[i]!==","&&!M(e,"from",i)&&(n=!0)}let s=Ot(e,t,!0);return s&&n?{...s,typeOnly:!0}:s}function xn(e,t){t=t+6;let n=q(e,t),s=!1;if(M(e,"type",n)){let r=q(e,n+4);(e[r]==="{"||e[r]==="*")&&(s=!0)}let i=Ot(e,t,!1);return i&&s?{...i,typeOnly:!0}:i}function Ot(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(M(e,"from",t))return he(e,q(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return he(e,t);if(t>0&&(M(e,"import",t)||M(e,"export",t)))return}}function kn(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}function wn(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let s=q(e,t+7);if(e[s]!=="(")return;s=q(e,s+1);let i=he(e,s);return i?{...i,requireCall:!0}:void 0}function Pn(e){let t=[];for(let n=0;n<e.length;n+=1){let s=e[n];if(s==="/"&&e[n+1]==="/"){if(n=e.indexOf(`
5
- `,n+2),n<0)break;continue}if(s==="/"&&e[n+1]==="*"){let r=e.indexOf("*/",n+2);if(r<0)break;n=r+1;continue}if(s==="`"){n=kn(e,n);continue}if(s==="'"||s==='"'){let r=he(e,n);r&&(n=r.offset+r.excerpt.length-1);continue}let i=s==="i"&&M(e,"import",n)?Sn(e,n):s==="e"&&M(e,"export",n)?xn(e,n):s==="r"&&M(e,"require",n)?wn(e,n):void 0;i&&(t.push(i),n=i.offset+i.excerpt.length-1)}return t}function Lt(e,t){let n=[],s=[];for(let i of Pn(e.content)){let r=i.value;if(i.requireCall&&r.startsWith("."))continue;if(!r.startsWith(".")){if(i.typeOnly)continue;let A=pe(r);if(!A)continue;let g=e.content.slice(0,i.offset).split(`
6
- `).length;s.push({file:e.path,symbol:r,capability:A,evidence:{kind:"import",file:e.path,line:g,excerpt:i.excerpt}});continue}let a=e.content.slice(0,i.offset).split(`
7
- `).length,c={kind:"import",file:e.path,line:a,excerpt:i.excerpt},f=On(e.path,r,t);n.push({from:e.path,specifier:r,to:f?.path??null,resolution:f?"resolved":"unresolved",fromLayer:e.layer,toLayer:f?.layer??null,evidence:c})}return{edges:n,capabilityUses:s}}function On(e,t,n){let s=e.split("/");s.pop();for(let r of t.split("/"))r==="."||r===""||(r===".."?s.pop():s.push(r));let i=s.join("/");for(let r of[i,`${i}.ts`,`${i}.tsx`,`${i}.mts`,`${i}.cts`,`${i}/index.ts`,`${i}/index.tsx`]){let a=n.get(r);if(a)return a}}function $t(e,t){let n=[];for(let s of e){if(!s.to||!s.fromLayer||!s.toLayer)continue;let i=T(t.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:t.layers});i&&n.push({ruleId:`layer-dependency:${i.from}->${i.to}`,message:i.message??`${i.from} must not depend on ${i.to}.`,edge:s,evidence:s.evidence})}return n}var Ln={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 $e(e,t){let n=typeof e=="string"?Qe(e,t):xe(e,t);return{...n,policyHash:k(v(n.config))}}function _t(e){let t=$e(e.baseConfig,e.baseSource??"base ark.config.json"),n=$e(e.candidateConfig,e.candidateSource??"candidate ark.config.json"),s=nt(t.config,n.config),i=s.findings.filter(c=>c.classification==="weakening"||c.classification==="judgment-required").map(c=>c.id).sort(),r=i.length>0,a=r&&rt(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:i});return{schemaVersion:s.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:s.classification,findings:s.findings,blockingFindingIds:i,requiresAcknowledgement:r,acknowledged:a,valid:!r||a}}function Ae(e){let t=e.files.map(u=>{let o=J(u.path);return{path:o,content:u.content,contentHash:k(u.content),layer:V(o,e.contract.config.layers)??null}}).sort((u,o)=>u.path.localeCompare(o.path)),n=new Map(t.map(u=>[u.path,u])),s=[],i=[];for(let u of t){let o=Lt(u,n);s.push(...o.edges),i.push(...o.capabilityUses)}let r=$t(s,e.contract.config),a=new Map(e.contract.config.layers.map(u=>[u.name,u])),c=new Map(e.contract.config.layers.map(u=>[u.name,new Set(Z(u))]));for(let u of i){let o=n.get(u.file)?.layer;if(!o)continue;let l=a.get(o),d=H(u.symbol,l?.forbiddenGlobals??[]);if(d){r.push({ruleId:"FORBIDDEN_GLOBAL",message:`${o} must not use module "${u.symbol}" because it is the import form of forbidden global "${d}".`,symbol:u.symbol,evidence:u.evidence});continue}c.get(o)?.has(u.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",message:`${o} denies the ${u.capability} capability; found import of "${u.symbol}".`,capability:u.capability,symbol:u.symbol,evidence:u.evidence})}let f=t.length===0?"complete":"partial",A=f==="complete"?[]:[{...Ln}],g={schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:k(v(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(u=>u.name),edges:s,capabilityUses:i,violations:r};return{mode:"lexical-compatibility",completeness:f,completenessReasons:A,valid:f==="complete"&&r.length===0,ir:g}}function _e(e){let t=new Map(e.files.map(n=>[J(n.path),n]));for(let n of e.changes){let s=J(n.path);"delete"in n&&n.delete?t.delete(s):"content"in n&&t.set(s,{path:s,content:n.content})}return Ae({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}function Tt(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}`}function it(e){let t=0,n=new Map,s=new Map,i=new Set,r=[],a=[],c=f=>{n.set(f,t),s.set(f,t),t+=1,r.push(f),i.add(f);for(let u of[...e.get(f)??[]].sort())e.has(u)&&(n.has(u)?i.has(u)&&s.set(f,Math.min(s.get(f)??0,n.get(u)??0)):(c(u),s.set(f,Math.min(s.get(f)??0,s.get(u)??0))));if(s.get(f)!==n.get(f))return;let A=[],g;do{if(g=r.pop(),g===void 0)break;i.delete(g),A.push(g)}while(g!==f);A.length>1&&a.push(A.sort())};for(let f of[...e.keys()].sort())n.has(f)||c(f);return a.sort((f,A)=>f[0]<A[0]?-1:f[0]>A[0]?1:0).map(f=>({ruleId:"CIRCULAR_DEPENDENCY",file:f[0],line:1,target:f.join(" \u2192 "),message:`Circular dependency among ${f.length} files: ${f.join(" \u2192 ")} \u2192 ${f[0]}.`,cycleKind:"value"}))}function le(e){let t=e.contentViolations.map(r=>({...r})),n=(e.warnings??[]).map(r=>({...r})),s=new Map(e.files.map(r=>[r,new Set]));for(let r of e.edges){if(r.to&&r.to!==r.from&&!r.typeOnly&&s.has(r.from)&&s.get(r.from)?.add(r.to),!r.to||!r.fromLayer||!r.toLayer)continue;let a=T(e.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:e.config.layers});if(!a)continue;let c=!!a.peerIsolation;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:r.from,line:r.line,fromLayer:r.fromLayer,toLayer:r.toLayer,target:r.to,...r.typeOnly?{typeOnly:!0}:{},...r.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...r.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...r.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!c&&r.portProofEligible?{portProofEligible:!0}:{},...r.kind?{edgeKind:r.kind}:{},...c?{peerIsolation:!0}:{},message:a.message??(c?`${r.fromLayer} must not ${r.kind} another slice of ${r.toLayer} (${r.from} \u2192 ${r.to}). Extract shared code or use events/ports across slices.`:`${r.fromLayer} must not ${r.kind} ${r.toLayer}.`)})}let i=String(e.config.cyclePolicy??"strict").toLowerCase();if(i!=="off"){let r=it(s);i==="soft"||i==="framework-soft"?n.push(...r.map(a=>({...a,message:`${a.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...r)}return{violations:t,warnings:n,safety:e.safety}}function w(e,t,n={}){return{ruleId:e,message:t,...n}}function Te(e){let{config:t,rules:n,files:s,manifest:i}=e,r=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(l=>typeof l!="string"))&&r.push(w("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)))r.push(w("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let l of["maxTsSuppressions","maxAnyCasts"]){let d=t.safety[l];d!==void 0&&(!Number.isInteger(d)||d<0)&&r.push(w("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${l} must be a non-negative integer.`))}let a=Array.isArray(t.layers)?t.layers:[],c=Array.isArray(i?.architecture?.layers)?i.architecture.layers:[],f=new Set([...a.map(l=>l.name).filter(Boolean),...c.map(l=>l.name).filter(l=>!!l)]);a.length===0&&r.push(w("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let A=new Set,g=new Set;for(let l of a){if(!l.name){r.push(w("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}A.has(l.name)&&g.add(l.name),A.add(l.name),l.forbiddenGlobals!==void 0&&(!Array.isArray(l.forbiddenGlobals)||l.forbiddenGlobals.some(p=>typeof p!="string"))&&r.push(w("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${l.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:l.name}));let d=Array.isArray(l.patterns)?l.patterns:[];if(d.length===0){r.push(w("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${l.name}" has no file patterns and will never classify files.`,{layer:l.name}));continue}for(let p of d){let y;try{y=z(p)}catch(h){r.push(w("CONFIG_INVALID_LAYER_PATTERN",`Layer "${l.name}" has an invalid pattern "${p}": ${h instanceof Error?h.message:String(h)}`,{layer:l.name,pattern:p}));continue}!s.some(h=>y.test(h))&&!l.optional&&r.push(w("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${l.name}" pattern "${p}" matched no included files.`,{layer:l.name,pattern:p,failsStrict:!1}))}}for(let l of g)r.push(w("CONFIG_DUPLICATE_LAYER",`Layer "${l}" is configured more than once.`,{layer:l}));if(f.size>0)for(let l of n??[])l.from&&!f.has(l.from)&&r.push(w("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${l.from}".`,{fromLayer:l.from,toLayer:l.to})),l.to&&!f.has(l.to)&&r.push(w("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${l.to}".`,{fromLayer:l.from,toLayer:l.to}));let u=new Set;if(a.length>1)for(let l of s){let d=-1,p=[];for(let y of a)for(let h of y.patterns??[]){if(!z(h).test(l))continue;let m=Be(h);m>d?(d=m,p=[y.name]):m===d&&!p.includes(y.name)&&p.push(y.name)}p.length>1&&u.add([...p].sort().join(" + "))}u.size>0&&r.push(w("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...u].join(", ")}.`,{pairs:[...u]}));let o=s.filter(l=>!V(l,a));return o.length>0&&r.push(w("CONFIG_UNCLASSIFIED_FILES",`${o.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:o.length,samples:o.slice(0,5)})),r}function $n(e,t){return t.some(n=>{try{return z(n).test(e)}catch{return!1}})}function _n(e,t){let n=e.contract.config.safety??{},s=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,i=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,r=e.contract.config.dynamicImportAllowlist??[],a=t.safetyUses.filter(p=>p.kind==="ts-suppression").map(({file:p,line:y})=>({file:p,line:y})),c=t.safetyUses.filter(p=>p.kind==="any-cast").map(({file:p,line:y})=>({file:p,line:y})),f=t.safetyUses.filter(p=>(p.kind==="dynamic-import"||p.kind==="dynamic-require")&&!$n(p.file,r)).map(p=>({file:p.file,line:p.line,kind:p.kind==="dynamic-require"?"require":"import"})),A=n.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(p=>p.kind==="in-memory-store").map(p=>({file:p.file,line:p.line,store:p.symbol??"in-memory store"})),g=n.allowDisabledPeerIsolation===!0?[]:(e.contract.config.rules??[]).filter(p=>p.peerIsolation===!1||p.allowed===!1&&!!p.from&&p.from===p.to&&p.peerIsolation!==!0).map(p=>({from:p.from,to:p.to})),u={tsSuppressions:a,anyCasts:c,nonLiteralDynamicImports:f,inMemoryProductionStores:A,disabledPeerIsolationRules:g,thresholds:{maxTsSuppressions:s,maxAnyCasts:i}},o=[],l=f.filter(p=>p.kind==="import");if(l.length>0){let p=l[0];o.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:p.file,line:p.line,message:`${l.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let d=f.filter(p=>p.kind==="require");if(d.length>0){let p=d[0];o.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:p.file,line:p.line,message:`${d.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(a.length>s){let p=a[0];o.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:p.file,line:p.line,message:`${a.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${s}).`})}if(c.length>i){let p=c[0];o.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:p.file,line:p.line,message:`${c.length} explicit any cast(s) exceed safety.maxAnyCasts (${i}).`})}if(A.length>0){let p=A[0];o.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:p.file,line:p.line,message:`${A.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 g.length>0&&o.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${g.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:u,warnings:o}}function Tn(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,s)=>s.length-n.length)[0]}function Nt(e,t){let n=t.config.layers.filter(s=>(s.intentPrefixes??[]).length>0);return Je(e,n.length>0?n:We.map(s=>({name:s.layer,prefixes:s.prefixes})))}function Nn(e,t,n){let s=[],i=new Map(e.contract.config.layers.map(r=>[r.name,r]));for(let r of t.ambientUses){let a=n.get(r.file);!a||!Tn(r.symbol,i.get(a)?.forbiddenGlobals??[])||s.push({ruleId:"FORBIDDEN_GLOBAL",file:r.file,line:r.line,fromLayer:a,target:r.symbol,message:`${a} must not use the ambient global "${r.symbol}".`})}for(let r of t.capabilityUses){let a=n.get(r.file);if(!a)continue;let c=i.get(a),f=c?.forbiddenGlobals??[],A=r.source==="import-based"?t.dependencies.find(g=>g.from===r.file&&g.line===r.line&&g.specifier===r.symbol&&!g.typeOnly)?.kind:void 0;if(!(r.source==="ambient-global"&&de(r.symbol,f))){if(r.source==="import-based"){let g=H(r.symbol,f);if(g){s.push({ruleId:"FORBIDDEN_GLOBAL",file:r.file,line:r.line,fromLayer:a,target:r.symbol,...A?{edgeKind:A}:{},message:`${a} must not use module "${r.symbol}" because it is the import form of forbidden global "${g}".`});continue}}Z(c).includes(r.capability)&&s.push({ruleId:"CAPABILITY_VIOLATION",file:r.file,line:r.line,fromLayer:a,target:r.symbol,capability:r.capability,...A?{edgeKind:A}:{},message:r.source==="import-based"?`${a} denies the ${r.capability} capability; found import of "${r.symbol}".`:`${a} denies the ${r.capability} capability; found ambient "${r.symbol}".`})}}for(let r of t.publishCalls){let a=n.get(r.file);if(!a)continue;for(let f of fe({publishCall:!0,rawIntentName:r.rawIntentName,objectHasIntent:r.objectHasIntent,arkPublishCandidate:r.arkPublishCandidate,hasSource:r.hasSource}))s.push({ruleId:f.ruleId,file:r.file,line:r.line,...f.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:a}:{},message:f.message});if(!r.sourceIntent)continue;let c=Nt(r.sourceIntent,e.contract);!c||c===a||s.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:r.file,line:r.line,fromLayer:a,toLayer:c,target:r.sourceIntent,message:`Publish source "${r.sourceIntent}" resolves to ${c}, but the publishing file is classified as ${a}.`})}for(let r of t.intentReferences){let a=n.get(r.file);if(!a)continue;let c=Nt(r.intent,e.contract);if(!c)continue;let f=T(e.contract.config.rules,a,c);f&&s.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:r.file,line:r.line,fromLayer:a,toLayer:c,target:r.intent,message:f.message??`${a} must not reference ${c} intent ${r.intent}.`})}return s}function Dn(e){let{facts:t}=e,n=Pe(e.contract.config),s=t.evidenceRequirementsHash===n,i=s?t.completeness:"unavailable",r=s?t.completenessReasons:[...t.completenessReasons,{code:"EVIDENCE_REQUIREMENTS_MISMATCH",message:"Resolved facts were collected for different policy-controlled evidence requirements."}].sort((d,p)=>{let y=`${d.code}\0${d.file??""}\0${d.message}`,h=`${p.code}\0${p.file??""}\0${p.message}`;return y<h?-1:y>h?1:0}),a=t.files.map(d=>({...d,layer:V(d.path,e.contract.config.layers)??null})),c=new Map(a.map(d=>[d.path,d.layer])),f=t.dependencies.map(d=>{let p=d.target?c.get(d.target)??V(d.target,e.contract.config.layers):void 0;return{from:d.from,fromLayer:c.get(d.from)??null,...d.resolution==="resolved-project"&&d.target?{to:d.target,...p?{toLayer:p}:{}}:{},line:d.line,kind:d.kind,typeOnly:d.typeOnly,...d.targetTypeOnlyExports?{targetTypeOnlyExports:d.targetTypeOnlyExports}:{},...d.sourcePureTypeModule?{sourcePureTypeModule:d.sourcePureTypeModule}:{},...d.namedBindingsTypeOnly?{namedBindingsTypeOnly:d.namedBindingsTypeOnly}:{},...d.portProofEligible?{portProofEligible:d.portProofEligible}:{}}}),A=Te({config:e.contract.config,rules:e.contract.config.rules,files:a.map(d=>d.path)}),g=_n(e,t),u=le({config:e.contract.config,rules:e.contract.config.rules,files:a.filter(d=>d.layer).map(d=>d.path),contentViolations:Nn(e,t,c),edges:f,warnings:[...A,...g.warnings],safety:g.report}),o=i==="complete"&&u.violations.length===0,l=o&&u.warnings.every(d=>d.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:i,completenessReasons:r,valid:o,strictValid:l,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:g.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:a,layers:e.contract.config.layers.map(d=>d.name),edges:f,capabilityUses:t.capabilityUses,violations:u.violations,warnings:u.warnings}}}function be(e){return Dn({contract:e.contract,facts:Y(e.facts)})}function Ne(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return e.typeOnly||e.targetTypeOnlyExports||e.namedBindingsTypeOnly?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":e.peerIsolation?"Extract the shared dependency to a shared layer, then preflight again.":`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, then preflight again.`;case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, 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, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";default:return`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}function Dt(e){return k(v(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}function Ft(e){let t=Ae(e),n=new Map(t.ir.files.map(l=>[l.path,l])),s=[],i=new Set,r=[];for(let l of e.changes){let d=l.path.replace(/\\/g,"/"),p=J(l.path);if(!p||p===".."||p.startsWith("../")||d.startsWith("/")||/^[A-Za-z]:\//.test(d)||d.includes("\0")){r.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(i.has(p)){r.push({ruleId:"DUPLICATE_CHANGE_PATH",file:p,line:1,message:`The atomic change set contains more than one operation for ${p}.`});continue}i.add(p),"delete"in l&&l.delete&&!n.has(p)&&r.push({ruleId:"DELETE_TARGET_MISSING",file:p,line:1,message:`Cannot delete ${p} because it is not present in the supplied base tree.`}),s.push("delete"in l&&l.delete?{path:p,delete:!0}:{path:p,content:"content"in l?l.content:""})}e.changes.length===0&&r.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let a=_e({...e,changes:s}),c=new Map(a.ir.files.map(l=>[l.path,l])),f=a.ir.violations.filter(l=>l.ruleId==="CAPABILITY_VIOLATION"||l.ruleId==="FORBIDDEN_GLOBAL").map(l=>{let d=c.get(l.evidence.file)?.layer;return{ruleId:l.ruleId,file:l.evidence.file,line:l.evidence.line,target:l.symbol,...l.capability?{capability:l.capability}:{},...d?{fromLayer:d}:{},edgeKind:"import",message:l.message}}),A=le({config:e.contract.config,rules:e.contract.config.rules,files:a.ir.files.map(l=>l.path),contentViolations:f,edges:a.ir.edges.filter(l=>!!l.fromLayer).map(l=>({from:l.from,fromLayer:l.fromLayer,...l.to?{to:l.to}:{},...l.toLayer?{toLayer:l.toLayer}:{},line:l.evidence.line,kind:"import"}))}),g=s.map(l=>{let d=J(l.path),p=n.get(d),y=c.get(d);return{path:d,operation:"delete"in l&&l.delete?"delete":p?"update":"create",...p?{beforeContentHash:p.contentHash}:{},...y?{candidateContentHash:y.contentHash}:{}}}).sort((l,d)=>l.path.localeCompare(d.path)),u=[...r,...A.violations].map(l=>({...l,nextAction:Ne(l)})),o=e.changeMap?oe({changeMap:e.changeMap,changes:g,baseDependencies:t.ir.edges.flatMap(l=>l.to?[{from:l.from,to:l.to}]:[]),candidateDependencies:a.ir.edges.flatMap(l=>l.to?[{from:l.from,to:l.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&a.valid&&u.length===0&&(o?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:a.ir.compilerOptionsHash,baseTreeHash:Dt(t.ir.files),candidateTreeHash:Dt(a.ir.files),baseCompleteness:t.completeness,candidateCompleteness:a.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:a.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...o?{convergence:o}:{},changes:g,violations:u,warnings:A.warnings}}function Fn(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let i of t.split("/"))if(!(!i||i==="."))if(i===".."){if(n.length===0)return;n.pop()}else n.push(i);let s=n.join("/");return s&&s===t?s:void 0}function Mn(e,t){return[["resolverIdentity",e.resolverIdentity,t.resolverIdentity],["compilerIdentity",e.compilerIdentity,t.compilerIdentity],["evidenceRequirementsHash",e.evidenceRequirementsHash,t.evidenceRequirementsHash],["projectPackageName",e.projectPackageName??"",t.projectPackageName??""]].filter(([,s,i])=>s!==i).map(([s,i,r])=>({ruleId:"FACTS_IDENTITY_MISMATCH",file:"<change-set>",line:1,field:s,before:i,candidate:r,message:`Base and candidate facts must use the same ${s}.`}))}function Hn(e,t,n,s){let i=n.get(t),r=s.get(t);return{path:t,operation:"delete"in e&&e.delete?"delete":i?"update":"create",...i?{beforeContentHash:i.contentHash}:{},...r?{candidateContentHash:r.contentHash}:{}}}function Mt(e){let t=Y(e.baseFacts),n=Y(e.candidateFacts),s=be({contract:e.contract,facts:t}),i=be({contract:e.contract,facts:n}),r=new Map(t.files.map(o=>[o.path,o])),a=new Map(n.files.map(o=>[o.path,o])),c=Mn(t,n),f=new Map,A=[];for(let o of e.changes){let l=Fn(o.path);if(!l){c.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(f.has(l)){c.push({ruleId:"DUPLICATE_CHANGE_PATH",file:l,line:1,message:`The atomic change set contains more than one operation for ${l}.`});continue}f.set(l,o);let d=r.get(l),p=a.get(l);if("delete"in o&&o.delete)d||c.push({ruleId:"DELETE_TARGET_MISSING",file:l,line:1,message:`Cannot delete ${l} because it is not present in the supplied base facts.`}),p&&c.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:l,line:1,message:`Candidate facts still contain deleted file ${l}.`});else{let y="content"in o?o.content:"",h=k(y);p?p.contentHash!==h&&c.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:l,line:1,expectedContentHash:h,candidateContentHash:p.contentHash,message:`Candidate facts for ${l} do not match the declared content.`}):c.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:l,line:1,message:`Candidate facts do not contain changed file ${l}.`})}A.push(Hn(o,l,r,a))}e.changes.length===0&&c.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});for(let o of new Set([...r.keys(),...a.keys()])){if(f.has(o))continue;let l=r.get(o),d=a.get(o);l&&d&&v(l)===v(d)||c.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:o,line:1,message:`Candidate facts change ${o}, but the atomic change set does not declare it.`})}let g=e.changeMap?oe({changeMap:e.changeMap,changes:A,baseDependencies:s.ir.edges.flatMap(o=>o.to?[{from:o.from,to:o.to}]:[]),candidateDependencies:i.ir.edges.flatMap(o=>o.to?[{from:o.from,to:o.to}]:[])}):void 0,u=[...c,...i.ir.violations].map(o=>({...o,nextAction:Ne(o)}));return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:s.completeness==="complete"&&i.strictValid&&u.length===0&&(g?.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:s.completeness,candidateCompleteness:i.completeness,baseCompletenessReasons:s.completenessReasons,candidateCompletenessReasons:i.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...g?{convergence:g}:{},changes:A.sort((o,l)=>o.path<l.path?-1:o.path>l.path?1:0),violations:u,warnings:i.ir.warnings}}var Vn="1.1";var jn="1.0";export{et as ANALYSIS_IR_SCHEMA_VERSION,Ut as ARK_ANALYSIS_RESULT_SCHEMA,Vt as ARK_ANALYSIS_RESULT_SCHEMA_VERSION,Xe as ARK_CONFIG_SCHEMA,cn as ARK_CONFIG_SCHEMA_VERSION,jn as ARK_DESIGN_DELTA_SCHEMA_VERSION,Vn as ARK_ENFORCEMENT_STATE_SCHEMA_VERSION,tt as POLICY_DELTA_SCHEMA_VERSION,wt as RESOLVED_CANDIDATE_FACTS_SCHEMA,Et as RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,oe as analyzeArchitectureConvergence,_e as analyzeChange,_t as analyzePolicyDelta,Ae as analyzeProject,be as analyzeResolvedProject,nt as classifyArkPolicyDelta,Te as collectAnalysisConfigWarnings,ee as collectForbiddenCapabilityUses,mt as createAICodeGate,Gt as createAdapterResult,we as createArchitectureProfile,bt as createArchitectureProfileFromArkConfig,Ct as createElevenLayerArkConfig,St as createResolvedCandidateFacts,it as detectArchitectureCycles,k as deterministicHash,ke as elevenLayerProfile,le as evaluateArchitectureGraph,Tt as explainViolation,Q as extractSemanticDependencies,xe as loadArkConfigContract,$e as loadContract,Y as loadResolvedCandidateFacts,Qe as parseArkConfigJson,rt as policyDeltaAcknowledgementMatches,Ft as preflightChange,Mt as preflightResolvedChange,Pe as resolvedFactsEvidenceRequirementsHash,v as stableSerialize,Fe as toAdapterDiagnostic,Ht as version};
4
+ `)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function It(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Qe(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function re(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function yn(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function Se(e,t,n,s,r){if(t.$ref){let i=yn(t.$ref,s);if(!i){r.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}Se(e,i,n,s,r);return}if(t.const!==void 0&&!Object.is(e,t.const)){r.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(i=>Object.is(i,e))){r.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!It(e)){r.push({path:n,message:`must be an object; received ${re(e)}`});return}let i=t.properties??{};for(let a of t.required??[])e[a]===void 0&&r.push({path:Qe(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in i||r.push({path:Qe(n,a),message:"unknown field"});for(let[a,c]of Object.entries(i))e[a]!==void 0&&Se(e[a],c,Qe(n,a),s,r);return}if(t.type==="array"){if(!Array.isArray(e)){r.push({path:n,message:`must be an array; received ${re(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&r.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let i=e.map(a=>JSON.stringify(a));new Set(i).size!==i.length&&r.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((i,a)=>Se(i,t.items,`${n}[${a}]`,s,r));return}if(t.type==="string"){if(typeof e!="string"){r.push({path:n,message:`must be a string; received ${re(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&r.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&r.push({path:n,message:`must be a boolean; received ${re(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){r.push({path:n,message:`must be an integer; received ${re(e)}`});return}t.minimum!==void 0&&e<t.minimum&&r.push({path:n,message:`must be at least ${t.minimum}`})}}function mn(e){return{...e,$schema:e.$schema===void 0?xe:e.$schema,schemaVersion:e.schemaVersion===void 0?"1.0":e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?ke.map(t=>({...t})):e.rules}}function gn(e,t="ark.config.json"){if(!It(e))throw new ie(t,[{path:"$",message:`must be an object; received ${re(e)}`}]);let n=e.schemaVersion===void 0?"unversioned":null;if(e.schemaVersion!==void 0&&e.schemaVersion!=="1.0")throw new ie(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.0`}]);return{candidate:mn(e),migratedFrom:n}}function we(e,t="ark.config.json"){let{candidate:n,migratedFrom:s}=gn(e,t),r=[];if(Se(n,et,"$",et,r),r.length>0)throw new ie(t,r);return{config:n,migratedFrom:s}}function tt(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(s){throw new ie(t,[{path:"$",message:`invalid JSON: ${s instanceof Error?s.message:String(s)}`}])}return we(n,t)}function Et(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:xe,schemaVersion:"1.0"};for(let[n,s]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=s);return t}function hn(e){return e.endsWith(".")?e:`${e}.`}function An(e,t){let n=e.prefixes.length?Math.max(...e.prefixes.map(r=>r.length)):0;return(t.prefixes.length?Math.max(...t.prefixes.map(r=>r.length)):0)-n}function Oe(e){let t=e.layers.map(r=>({...r,prefixes:r.prefixes.map(hn)})),n=[...t].sort(An),s=[...e.rules??[]];return{name:e.name,layers:t,rules:s,resolveLayer(r){return t.find(i=>i.match?.(r))?.name??n.find(i=>i.prefixes.some(a=>r.startsWith(a)))?.name}}}function Rt(e,t={}){return Oe({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,s)=>({name:n.name,prefixes:n.intentPrefixes??[],description:n.description,order:s+1})),rules:e.rules??[]})}var bn=[{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}],Pe=Oe({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:bn,rules:ke.map(e=>({...e}))}),Cn={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 vt(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,s=t==="."?"":`${t}/`;return Et({include:e.include??[t],layers:Pe.layers.map(r=>({name:r.name,patterns:(Cn[r.name]??[r.name]).map(i=>`${s}${i}/**`),intentPrefixes:r.prefixes,optional:n})),rules:[...Pe.rules]})}function S(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")}`}function E(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(E).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${E(t[n])}`).join(",")}}`}var W="1.0",St=["network","filesystem","clock","randomness","environment","process","persistence"];function q(e,t){let n=E(e),s=E(t);return n<s?-1:n>s?1:0}function T(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}function he(e){let t={schemaVersion:"1.0",include:T(e.include??[]),exclude:T(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:T(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:T(n.patterns??[]),exclude:T(n.exclude??[]),forbiddenGlobals:T(n.forbiddenGlobals??[]),intentPrefixes:T(n.intentPrefixes??[]),capabilityDeny:T(n.capabilities?.deny??[]),pure:n.pure===!0})).sort(q),safety:{maxTsSuppressions:e.safety?.maxTsSuppressions??0,maxAnyCasts:e.safety?.maxAnyCasts??0,allowInMemory:e.safety?.allowInMemory===!0,allowDisabledPeerIsolation:e.safety?.allowDisabledPeerIsolation===!0}};return S(E(t))}function In(e){let t=e.completenessReasons.map(u=>({code:u.code,message:u.message,...u.file?{file:u.file}:{}})).sort(q),n=e.files.map(u=>({...u,typeOnlyExportNames:T(u.typeOnlyExportNames)})).sort((u,o)=>u.path<o.path?-1:u.path>o.path?1:0),s=e.dependencies.map(u=>({...u,...u.namedBindings?{namedBindings:T(u.namedBindings)}:{}})).sort(q),r=e.capabilityUses.map(u=>({...u})).sort(q),i=e.ambientUses.map(u=>({...u})).sort(q),a=e.publishCalls.map(u=>({...u})).sort(q),c=e.intentReferences.map(u=>({...u})).sort(q),f=e.safetyUses.map(u=>({...u})).sort(q),A=e.files.map(({path:u,contentHash:o})=>({path:u,contentHash:o})).sort((u,o)=>u.path<o.path?-1:u.path>o.path?1:0),g=S(E(A));return{schemaVersion:"1.0",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:g,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:s,capabilityUses:r,ambientUses:i,publishCalls:a,intentReferences:c,safetyUses:f}}function kt(e){let t=In(e);return{...t,factsHash:S(E(t))}}function nt(e){return kt(Pt(D(e,"$"),!1))}function D(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}function F(e,t,n){let s=new Set(t),r=Object.keys(e).find(i=>!s.has(i));if(r)throw new Error(`${n}.${r} is not part of schema 1.0.`)}function k(e,t,n){let s=e[t];if(typeof s!="string"||s.length===0)throw new Error(`${n}.${t} must be a non-empty string.`);return s}function se(e,t,n){if(e[t]!==void 0)return k(e,t,n)}function M(e,t,n){let s=k(e,t,n),r=s.replace(/\\/g,"/");if(!r||r.startsWith("/")||/^[A-Za-z]:\//.test(r)||/[\u0000-\u001f\u007f]/.test(r))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let i=[];for(let c of r.split("/"))if(!(!c||c==="."))if(c===".."){if(i.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);i.pop()}else i.push(c);let a=i.join("/");if(!a||a!==s)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return a}function _(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}function wt(e,t,n){let s=e[t];if(!Number.isInteger(s)||Number(s)<0)throw new Error(`${n}.${t} must be a non-negative integer.`);return Number(s)}function ae(e,t,n){let s=wt(e,t,n);if(s===0)throw new Error(`${n}.${t} must be a positive integer.`);return s}function U(e,t,n){let s=e[t];if(!Array.isArray(s))throw new Error(`${n}.${t} must be an array.`);return s}function B(e,t,n,s){let r=e[t];if(typeof r!="string"||!n.includes(r))throw new Error(`${s}.${t} must be one of ${n.join(", ")}.`);return r}function xt(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]}function En(e,t,n){let s=new Set;for(let r of e){let i=t(r);if(s.has(i))throw new Error(`${n} must not contain duplicate facts (${i}).`);s.add(i)}}function Pt(e,t){F(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=B(e,"schemaVersion",["1.0"],"$"),s=B(e,"completeness",["complete","partial","unavailable"],"$"),r=U(e,"completenessReasons","$").map((p,d)=>{let y=`$.completenessReasons[${d}]`,h=D(p,y);F(h,["code","message","file"],y);let m=h.file===void 0?void 0:M(h,"file",y);return{code:k(h,"code",y),message:k(h,"message",y),...m?{file:m}:{}}});if(s==="complete"&&r.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(s!=="complete"&&r.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let i=U(e,"files","$").map((p,d)=>{let y=`$.files[${d}]`,h=D(p,y);return F(h,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],y),{path:M(h,"path",y),contentHash:k(h,"contentHash",y),parseStatus:B(h,"parseStatus",["parsed","invalid"],y),parseDiagnosticCount:wt(h,"parseDiagnosticCount",y),exportsOnlyTypes:_(h,"exportsOnlyTypes",y),typeOnlyExportNames:xt(h.typeOnlyExportNames,`${y}.typeOnlyExportNames`),hasTopLevelSideEffects:_(h,"hasTopLevelSideEffects",y)}}),a=U(e,"dependencies","$").map((p,d)=>{let y=`$.dependencies[${d}]`,h=D(p,y);F(h,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],y);let m=se(h,"specifier",y),b=se(h,"target",y),C=B(h,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],y);if(C==="resolved-project"&&!b)throw new Error(`${y}.target is required for resolved-project dependencies.`);if(C!=="resolved-project"&&b)throw new Error(`${y}.target is only allowed for resolved-project dependencies.`);if(C!=="dynamic"&&!m)throw new Error(`${y}.specifier is required unless resolution is dynamic.`);return{from:M(h,"from",y),...m?{specifier:m}:{},kind:B(h,"kind",["import","export","dynamic-import","require"],y),typeOnly:_(h,"typeOnly",y),line:ae(h,"line",y),resolution:C,...b?{target:M(h,"target",y)}:{},...h.namedBindings!==void 0?{namedBindings:xt(h.namedBindings,`${y}.namedBindings`)}:{},...h.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:_(h,"targetTypeOnlyExports",y)}:{},...h.sourcePureTypeModule!==void 0?{sourcePureTypeModule:_(h,"sourcePureTypeModule",y)}:{},...h.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:_(h,"namedBindingsTypeOnly",y)}:{},...h.portProofEligible!==void 0?{portProofEligible:_(h,"portProofEligible",y)}:{}}}),c=U(e,"capabilityUses","$").map((p,d)=>{let y=`$.capabilityUses[${d}]`,h=D(p,y);return F(h,["file","line","symbol","capability","source"],y),{file:M(h,"file",y),line:ae(h,"line",y),symbol:k(h,"symbol",y),capability:B(h,"capability",St,y),source:B(h,"source",["ambient-global","import-based"],y)}}),f=U(e,"ambientUses","$").map((p,d)=>{let y=`$.ambientUses[${d}]`,h=D(p,y);return F(h,["file","line","symbol"],y),{file:M(h,"file",y),line:ae(h,"line",y),symbol:k(h,"symbol",y)}}),A=U(e,"publishCalls","$").map((p,d)=>{let y=`$.publishCalls[${d}]`,h=D(p,y);F(h,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],y);let m=se(h,"rawIntentName",y),b=se(h,"sourceIntent",y);return{file:M(h,"file",y),line:ae(h,"line",y),...m?{rawIntentName:m}:{},objectHasIntent:_(h,"objectHasIntent",y),arkPublishCandidate:_(h,"arkPublishCandidate",y),hasSource:_(h,"hasSource",y),...b?{sourceIntent:b}:{}}}),g=U(e,"intentReferences","$").map((p,d)=>{let y=`$.intentReferences[${d}]`,h=D(p,y);return F(h,["file","line","intent"],y),{file:M(h,"file",y),line:ae(h,"line",y),intent:k(h,"intent",y)}}),u=U(e,"safetyUses","$").map((p,d)=>{let y=`$.safetyUses[${d}]`,h=D(p,y);F(h,["file","line","kind","symbol"],y);let m=se(h,"symbol",y),b=B(h,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],y);if(b==="in-memory-store"&&!m)throw new Error(`${y}.symbol is required for in-memory-store facts.`);if(b!=="in-memory-store"&&m)throw new Error(`${y}.symbol is only allowed for in-memory-store facts.`);return{file:M(h,"file",y),line:ae(h,"line",y),kind:b,...m?{symbol:m}:{}}});En(i,p=>p.path,"$.files");let o=new Set(i.map(p=>p.path));for(let p of i){if(p.parseStatus==="parsed"&&p.parseDiagnosticCount!==0)throw new Error(`$.files[${p.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(p.parseStatus==="invalid"&&p.parseDiagnosticCount===0)throw new Error(`$.files[${p.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(s==="complete"&&i.some(p=>p.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let p of a)if(!o.has(p.from))throw new Error(`$.dependencies references missing source file ${p.from}.`);for(let[p,d]of[["$.capabilityUses",c],["$.ambientUses",f],["$.publishCalls",A],["$.intentReferences",g],["$.safetyUses",u]])for(let y of d)if(!o.has(y.file))throw new Error(`${p} references missing file ${y.file}.`);let l=se(e,"projectPackageName","$");return{schemaVersion:n,completeness:s,completenessReasons:r,resolverIdentity:k(e,"resolverIdentity","$"),compilerIdentity:k(e,"compilerIdentity","$"),compilerOptionsHash:k(e,"compilerOptionsHash","$"),tsconfigHash:k(e,"tsconfigHash","$"),evidenceRequirementsHash:k(e,"evidenceRequirementsHash","$"),...l?{projectPackageName:l}:{},files:i,dependencies:a,capabilityUses:c,ambientUses:f,publishCalls:A,intentReferences:g,safetyUses:u}}function z(e){let t=D(e,"$"),n=k(t,"factsHash","$"),s=k(t,"candidateTreeHash","$"),r=kt(Pt(t,!0));if(r.factsHash!==n)throw new Error(`$.factsHash does not match the canonical payload (${r.factsHash}).`);if(s!==r.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${r.candidateTreeHash}).`);return r}var Rn=["network","filesystem","clock","randomness","environment","process","persistence"],R={type:"string",minLength:1},oe={type:"integer",minimum:1},H={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},rt={$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:{const:"1.0"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:R,message:R,file:H}}},resolverIdentity:R,compilerIdentity:R,compilerOptionsHash:R,tsconfigHash:R,candidateTreeHash:R,evidenceRequirementsHash:R,projectPackageName:R,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:H,contentHash:R,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:R},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:H,specifier:R,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:oe,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:H,namedBindings:{type:"array",items:R},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:H,line:oe,symbol:R,capability:{enum:Rn},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:H,line:oe,symbol:R}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:H,line:oe,rawIntentName:R,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:R}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:H,line:oe,intent:R}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:H,line:oe,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:R},allOf:[{if:{properties:{kind:{const:"in-memory-store"}}},then:{required:["symbol"]},else:{not:{required:["symbol"]}}}]}},factsHash:R},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 it="1.0";function P(e){return`${e.from}->${e.to}`}function Ae(e,t,n,s="dependency"){return{id:`${e}:${s}:${P(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${P(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${P(t)}, then preflight again.`}:e==="unplanned"?{nextAction:s==="dependency-removed"?`Restore the removed dependency ${P(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${P(t)} from the candidate, then preflight again.`}:{}}}function le(e){let t=[],n=new Map(e.changeMap.map.files.map(o=>[o.path,o])),s=new Map(e.changes.map(o=>[o.path,o])),r=new Map(e.changeMap.map.dependencies.map(o=>[P(o),o])),i=new Map(e.baseDependencies.map(o=>[P(o),o])),a=new Map(e.candidateDependencies.map(o=>[P(o),o]));for(let o of[...n.values()].sort((l,p)=>l.path.localeCompare(p.path))){let l=s.get(o.path);l?l.operation!==o.operation?t.push({id:`contradictory:file:${o.path}`,classification:"contradictory",subject:"file",path:o.path,expectedOperation:o.operation,actualOperation:l.operation,message:`${o.path} was planned as ${o.operation} but the actual operation is ${l.operation}.`,nextAction:`Change ${o.path} to the planned ${o.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${o.path}`,classification:"satisfied",subject:"file",path:o.path,expectedOperation:o.operation,actualOperation:l.operation,message:`${o.path} matches the planned ${o.operation} operation.`}):t.push({id:`missing:file:${o.path}`,classification:"missing",subject:"file",path:o.path,expectedOperation:o.operation,message:`${o.path} was planned as ${o.operation} but is absent from the actual change.`,nextAction:`${o.operation[0].toUpperCase()}${o.operation.slice(1)} ${o.path} in the complete change set, then preflight again.`})}for(let o of[...s.values()].sort((l,p)=>l.path.localeCompare(p.path)))n.has(o.path)||t.push({id:`unplanned:file:${o.path}`,classification:"unplanned",subject:"file",path:o.path,actualOperation:o.operation,message:`${o.path} has an unplanned ${o.operation} operation.`,nextAction:`Remove ${o.path} from the change set, then preflight again.`});let c=new Set;for(let o of[...r.values()].sort((l,p)=>P(l).localeCompare(P(p)))){if(a.has(P(o))){t.push(Ae("satisfied",o,`${o.from} -> ${o.to} exists in the candidate architecture.`));continue}let l={from:o.to,to:o.from};a.has(P(l))?(c.add(P(l)),t.push(Ae("contradictory",o,`${o.from} -> ${o.to} was planned, but the candidate contains the reverse edge.`))):t.push(Ae("missing",o,`${o.from} -> ${o.to} is absent from the candidate architecture.`))}let f=new Set([...n.keys(),...s.keys()]);for(let[o,l]of[...a].sort(([p],[d])=>p.localeCompare(d)))i.has(o)||r.has(o)||c.has(o)||!f.has(l.from)&&!f.has(l.to)||t.push({...Ae("unplanned",l,`${l.from} -> ${l.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let A=new Set(e.changeMap.map.files.filter(o=>o.operation==="delete").map(o=>o.path));for(let[o,l]of[...i].sort(([p],[d])=>p.localeCompare(d)))a.has(o)||A.has(l.from)||A.has(l.to)||!f.has(l.from)&&!f.has(l.to)||t.push({...Ae("unplanned",l,`${l.from} -> ${l.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let g={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((o,l)=>g[o.classification]-g[l.classification]||(o.subject===l.subject?0:o.subject==="file"?-1:1)||o.id.localeCompare(l.id));let u={satisfied:t.filter(o=>o.classification==="satisfied").length,missing:t.filter(o=>o.classification==="missing").length,contradictory:t.filter(o=>o.classification==="contradictory").length,unplanned:t.filter(o=>o.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:u.missing===0&&u.contradictory===0&&u.unplanned===0,behavioralCompletion:"not-evaluated",summary:u,findings:t}}var st="1.0";function x(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}})}function L(e){return[...new Set(e??[])].sort()}function J(e,t,n,s,r){let i=L(n),a=L(s),c=new Set(i),f=new Set(a),A=a.filter(u=>!c.has(u)),g=i.filter(u=>!f.has(u));A.length===0&&g.length===0||(A.length>0&&x(e,{kind:"added",path:t,classification:r.added,message:r.addedMessage,before:i,after:a}),g.length>0&&x(e,{kind:"removed",path:t,classification:r.removed,message:r.removedMessage,before:i,after:a}))}function Le(e,t,n,s,r,i,a){if(n===s)return;x(e,{kind:s?"enabled":"disabled",path:t,classification:s?r:r==="strengthening"?"weakening":"strengthening",message:s?i:a,before:n,after:s})}function $e(e,t){let n=new Map,s=new Set;for(let r of e){let i=t(r);n.has(i)?s.add(i):n.set(i,r)}return{values:n,duplicates:[...s].sort()}}function vn(e,t,n){let s=$e(t,i=>i.name),r=$e(n,i=>i.name);(s.duplicates.length>0||r.duplicates.length>0)&&x(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:s.duplicates,after:r.duplicates});for(let i of[...new Set([...s.values.keys(),...r.values.keys()])].sort()){let a=s.values.get(i),c=r.values.get(i),f=`$.layers[${i}]`;if(!a&&c){x(e,{kind:"layer-added",path:f,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:c});continue}if(a&&!c){x(e,{kind:"layer-removed",path:f,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:a});continue}if(!a||!c)continue;J(e,`${f}.patterns`,a.patterns,c.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),J(e,`${f}.exclude`,a.exclude,c.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let A=ve(a),g=ve(c);J(e,`${f}.forbiddenGlobals`,A.rawGlobals,g.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),J(e,`${f}.capabilities`,A.atoms,g.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)."}),L(a.intentPrefixes).join("\0")!==L(c.intentPrefixes).join("\0")&&x(e,{kind:"intent-prefixes-changed",path:`${f}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:L(a.intentPrefixes),after:L(c.intentPrefixes)}),Le(e,`${f}.mayImportInfrastructure`,a.mayImportInfrastructure===!0,c.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),Le(e,`${f}.optional`,a.optional===!0,c.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.")}}function Sn(e,t,n){let s=a=>`${a.from}->${a.to}`,r=$e(t,s),i=$e(n,s);(r.duplicates.length>0||i.duplicates.length>0)&&x(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:r.duplicates,after:i.duplicates});for(let a of[...new Set([...r.values.keys(),...i.values.keys()])].sort()){let c=r.values.get(a),f=i.values.get(a),A=`$.rules[${a}]`;if(!c&&f){f.allowed===!1&&x(e,{kind:"deny-added",path:A,classification:"strengthening",message:"A denied dependency edge was added.",after:f});continue}if(c&&!f){c.allowed===!1&&x(e,{kind:"deny-removed",path:A,classification:"weakening",message:"A denied dependency edge was removed.",before:c});continue}if(!c||!f)continue;c.allowed!==f.allowed&&x(e,{kind:f.allowed?"deny-disabled":"deny-enabled",path:`${A}.allowed`,classification:f.allowed?"weakening":"strengthening",message:f.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:c.allowed,after:f.allowed});let g=c.peerIsolation===!0,u=f.peerIsolation===!0;if(g!==u){let o=c.from===c.to&&f.from===f.to;x(e,{kind:u?"peer-isolation-enabled":"peer-isolation-disabled",path:`${A}.peerIsolation`,classification:o?u?"strengthening":"weakening":"judgment-required",message:o?u?"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:g,after:u})}L(c.sliceFolders).join("\0")!==L(f.sliceFolders).join("\0")&&x(e,{kind:"slice-folders-changed",path:`${A}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:L(c.sliceFolders),after:L(f.sliceFolders)})}}function xn(e,t,n){let s=t.safety??{},r=n.safety??{};for(let i of["maxTsSuppressions","maxAnyCasts"]){let a=s[i]??0,c=r[i]??0;a!==c&&x(e,{kind:c>a?"threshold-raised":"threshold-lowered",path:`$.safety.${i}`,classification:c>a?"weakening":"strengthening",message:c>a?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:a,after:c})}for(let i of["allowInMemory","allowDisabledPeerIsolation"])Le(e,`$.safety.${i}`,s[i]===!0,r[i]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}function kn(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"}function at(e,t){let n=[];J(n,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),J(n,"$.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."}),J(n,"$.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."}),Le(n,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let s={off:0,soft:1,"framework-soft":1,strict:2},r=e.cyclePolicy??"strict",i=t.cyclePolicy??"strict";if(r!==i){let a=s[i]===s[r]?"judgment-required":s[i]>s[r]?"strengthening":"weakening";x(n,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:a,message:"The cycle enforcement level changed.",before:r,after:i})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&x(n,{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}),vn(n,e.layers,t.layers),Sn(n,e.rules,t.rules),xn(n,e,t),n.sort((a,c)=>a.path.localeCompare(c.path)||a.id.localeCompare(c.id)),{schemaVersion:st,classification:kn(n),findings:n}}function ot(e,t){if(!e||e.schemaVersion!==st||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(r=>typeof r!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=L(e.findingIds),s=L(t.findingIds);return n.length===s.length&&n.every((r,i)=>r===s[i])}function Z(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("/")}function Ot(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}function _e(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}function O(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}function be(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let s=t,r="";for(t+=1;t<e.length;t+=1){let i=e[t];if(i===n)return{value:r,offset:s,excerpt:e.slice(s,t+1)};i==="\\"&&t+1<e.length?(r+=e[t+1],t+=1):r+=i}}function $(e,t,n){return e.startsWith(t,n)&&!_e(e[n-1])&&!_e(e[n+t.length])}function Lt(e,t){let n=O(e,t);if(e[n]!=="{")return!1;n+=1;let s=!1;for(;n<e.length;){if(n=O(e,n),e[n]==="}")return s;if(e[n]===","){n+=1;continue}if(!$(e,"type",n))return!1;let r=O(e,n+4);if(r>=e.length||e[r]===","||e[r]==="}"||$(e,"as",r)||!Ot(e[r]))return!1;for(n=r;n<e.length&&_e(e[n]);)n+=1;if(n=O(e,n),$(e,"as",n)){if(n=O(e,n+2),!Ot(e[n]))return!1;for(;n<e.length&&_e(e[n]);)n+=1}s=!0}return!1}function wn(e,t){if(t=O(e,t+6),e[t]==="(")return be(e,O(e,t+1));let n=!1;if($(e,"type",t)){let r=O(e,t+4);e[r]!==","&&!$(e,"from",r)&&(n=!0)}else Lt(e,t)&&(n=!0);let s=$t(e,t,!0);return s&&n?{...s,typeOnly:!0}:s}function Pn(e,t){t=t+6;let n=O(e,t),s=!1;if($(e,"type",n)){let i=O(e,n+4);(e[i]==="{"||e[i]==="*")&&(s=!0)}else Lt(e,n)&&(s=!0);let r=$t(e,t,!1);return r&&s?{...r,typeOnly:!0}:r}function $t(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if($(e,"from",t))return be(e,O(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return be(e,t);if(t>0&&($(e,"import",t)||$(e,"export",t)))return}}function On(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}function Ln(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let s=O(e,t+7);if(e[s]!=="(")return;s=O(e,s+1);let r=be(e,s);return r?{...r,requireCall:!0}:void 0}function $n(e){let t=[];for(let n=0;n<e.length;n+=1){let s=e[n];if(s==="/"&&e[n+1]==="/"){if(n=e.indexOf(`
5
+ `,n+2),n<0)break;continue}if(s==="/"&&e[n+1]==="*"){let i=e.indexOf("*/",n+2);if(i<0)break;n=i+1;continue}if(s==="`"){n=On(e,n);continue}if(s==="'"||s==='"'){let i=be(e,n);i&&(n=i.offset+i.excerpt.length-1);continue}let r=s==="i"&&$(e,"import",n)?wn(e,n):s==="e"&&$(e,"export",n)?Pn(e,n):s==="r"&&$(e,"require",n)?Ln(e,n):void 0;r&&(t.push(r),n=r.offset+r.excerpt.length-1)}return t}function _t(e,t){let n=[],s=[];for(let r of $n(e.content)){let i=r.value;if(!i.startsWith(".")){if(r.typeOnly)continue;let A=pe(i);if(!A)continue;let g=e.content.slice(0,r.offset).split(`
6
+ `).length;s.push({file:e.path,symbol:i,capability:A,evidence:{kind:"import",file:e.path,line:g,excerpt:r.excerpt}});continue}let a=e.content.slice(0,r.offset).split(`
7
+ `).length,c={kind:"import",file:e.path,line:a,excerpt:r.excerpt},f=_n(e.path,i,t);n.push({from:e.path,specifier:i,to:f?.path??null,resolution:f?"resolved":"unresolved",fromLayer:e.layer,toLayer:f?.layer??null,evidence:c})}return{edges:n,capabilityUses:s}}function _n(e,t,n){let s=e.split("/");s.pop();for(let i of t.split("/"))i==="."||i===""||(i===".."?s.pop():s.push(i));let r=s.join("/");for(let i of[r,`${r}.ts`,`${r}.tsx`,`${r}.mts`,`${r}.cts`,`${r}/index.ts`,`${r}/index.tsx`]){let a=n.get(i);if(a)return a}}function Tt(e,t){let n=[];for(let s of e){if(!s.to||!s.fromLayer||!s.toLayer)continue;let r=N(t.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:t.layers});r&&n.push({ruleId:`layer-dependency:${r.from}->${r.to}`,message:r.message??`${r.from} must not depend on ${r.to}.`,edge:s,evidence:s.evidence})}return n}var Tn={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 Te(e,t){let n=typeof e=="string"?tt(e,t):we(e,t);return{...n,policyHash:S(E(n.config))}}function Dt(e){let t=Te(e.baseConfig,e.baseSource??"base ark.config.json"),n=Te(e.candidateConfig,e.candidateSource??"candidate ark.config.json"),s=at(t.config,n.config),r=s.findings.filter(c=>c.classification==="weakening"||c.classification==="judgment-required").map(c=>c.id).sort(),i=r.length>0,a=i&&ot(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:r});return{schemaVersion:s.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:s.classification,findings:s.findings,blockingFindingIds:r,requiresAcknowledgement:i,acknowledged:a,valid:!i||a}}function Ce(e){let t=e.files.map(u=>{let o=Z(u.path);return{path:o,content:u.content,contentHash:S(u.content),layer:j(o,e.contract.config.layers)??null}}).sort((u,o)=>u.path.localeCompare(o.path)),n=new Map(t.map(u=>[u.path,u])),s=[],r=[];for(let u of t){let o=_t(u,n);s.push(...o.edges),r.push(...o.capabilityUses)}let i=Tt(s,e.contract.config),a=new Map(e.contract.config.layers.map(u=>[u.name,u])),c=new Map(e.contract.config.layers.map(u=>[u.name,new Set(X(u))]));for(let u of r){let o=n.get(u.file)?.layer;if(!o)continue;let l=a.get(o),p=V(u.symbol,l?.forbiddenGlobals??[]);if(p){i.push({ruleId:"FORBIDDEN_GLOBAL",message:`${o} must not use module "${u.symbol}" because it is the import form of forbidden global "${p}".`,symbol:u.symbol,evidence:u.evidence});continue}c.get(o)?.has(u.capability)&&i.push({ruleId:"CAPABILITY_VIOLATION",message:`${o} denies the ${u.capability} capability; found import of "${u.symbol}".`,capability:u.capability,symbol:u.symbol,evidence:u.evidence})}let f=t.length===0?"complete":"partial",A=f==="complete"?[]:[{...Tn}],g={schemaVersion:it,policyHash:e.contract.policyHash,compilerOptionsHash:S(E(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(u=>u.name),edges:s,capabilityUses:r,violations:i};return{mode:"lexical-compatibility",completeness:f,completenessReasons:A,valid:f==="complete"&&i.length===0,ir:g}}function De(e){let t=new Map(e.files.map(n=>[Z(n.path),n]));for(let n of e.changes){let s=Z(n.path);"delete"in n&&n.delete?t.delete(s):"content"in n&&t.set(s,{path:s,content:n.content})}return Ce({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}function Nt(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}`}function lt(e){let t=0,n=new Map,s=new Map,r=new Set,i=[],a=[],c=f=>{n.set(f,t),s.set(f,t),t+=1,i.push(f),r.add(f);for(let u of[...e.get(f)??[]].sort())e.has(u)&&(n.has(u)?r.has(u)&&s.set(f,Math.min(s.get(f)??0,n.get(u)??0)):(c(u),s.set(f,Math.min(s.get(f)??0,s.get(u)??0))));if(s.get(f)!==n.get(f))return;let A=[],g;do{if(g=i.pop(),g===void 0)break;r.delete(g),A.push(g)}while(g!==f);A.length>1&&a.push(A.sort())};for(let f of[...e.keys()].sort())n.has(f)||c(f);return a.sort((f,A)=>f[0]<A[0]?-1:f[0]>A[0]?1:0).map(f=>({ruleId:"CIRCULAR_DEPENDENCY",file:f[0],line:1,target:f.join(" \u2192 "),message:`Circular dependency among ${f.length} files: ${f.join(" \u2192 ")} \u2192 ${f[0]}.`,cycleKind:"value"}))}function ce(e){let t=e.contentViolations.map(i=>({...i})),n=(e.warnings??[]).map(i=>({...i})),s=new Map(e.files.map(i=>[i,new Set]));for(let i of e.edges){if(i.to&&i.to!==i.from&&!i.typeOnly&&s.has(i.from)&&s.get(i.from)?.add(i.to),!i.to||!i.fromLayer||!i.toLayer)continue;let a=N(e.rules,i.fromLayer,i.toLayer,{fromPath:i.from,toPath:i.to,layers:e.config.layers});if(!a)continue;let c=!!a.peerIsolation;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:i.from,line:i.line,fromLayer:i.fromLayer,toLayer:i.toLayer,target:i.to,...i.typeOnly?{typeOnly:!0}:{},...i.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...i.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...i.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!c&&i.portProofEligible?{portProofEligible:!0}:{},...i.kind?{edgeKind:i.kind}:{},...c?{peerIsolation:!0}:{},message:a.message??(c?`${i.fromLayer} must not ${i.kind} another slice of ${i.toLayer} (${i.from} \u2192 ${i.to}). Extract shared code or use events/ports across slices.`:`${i.fromLayer} must not ${i.kind} ${i.toLayer}.`)})}let r=String(e.config.cyclePolicy??"strict").toLowerCase();if(r!=="off"){let i=lt(s);r==="soft"||r==="framework-soft"?n.push(...i.map(a=>({...a,message:`${a.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...i)}return{violations:t,warnings:n,safety:e.safety}}function w(e,t,n={}){return{ruleId:e,message:t,...n}}function Ne(e){let{config:t,rules:n,files:s,manifest:r}=e,i=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(l=>typeof l!="string"))&&i.push(w("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)))i.push(w("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let l of["maxTsSuppressions","maxAnyCasts"]){let p=t.safety[l];p!==void 0&&(!Number.isInteger(p)||p<0)&&i.push(w("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${l} must be a non-negative integer.`))}let a=Array.isArray(t.layers)?t.layers:[],c=Array.isArray(r?.architecture?.layers)?r.architecture.layers:[],f=new Set([...a.map(l=>l.name).filter(Boolean),...c.map(l=>l.name).filter(l=>!!l)]);a.length===0&&i.push(w("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let A=new Set,g=new Set;for(let l of a){if(!l.name){i.push(w("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}A.has(l.name)&&g.add(l.name),A.add(l.name),l.forbiddenGlobals!==void 0&&(!Array.isArray(l.forbiddenGlobals)||l.forbiddenGlobals.some(d=>typeof d!="string"))&&i.push(w("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${l.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:l.name}));let p=Array.isArray(l.patterns)?l.patterns:[];if(p.length===0){i.push(w("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${l.name}" has no file patterns and will never classify files.`,{layer:l.name}));continue}for(let d of p){let y;try{y=K(d)}catch(h){i.push(w("CONFIG_INVALID_LAYER_PATTERN",`Layer "${l.name}" has an invalid pattern "${d}": ${h instanceof Error?h.message:String(h)}`,{layer:l.name,pattern:d}));continue}!s.some(h=>y.test(h))&&!l.optional&&i.push(w("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${l.name}" pattern "${d}" matched no included files.`,{layer:l.name,pattern:d,failsStrict:!1}))}}for(let l of g)i.push(w("CONFIG_DUPLICATE_LAYER",`Layer "${l}" is configured more than once.`,{layer:l}));if(f.size>0)for(let l of n??[])l.from&&!f.has(l.from)&&i.push(w("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${l.from}".`,{fromLayer:l.from,toLayer:l.to})),l.to&&!f.has(l.to)&&i.push(w("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${l.to}".`,{fromLayer:l.from,toLayer:l.to}));let u=new Set;if(a.length>1)for(let l of s){let p=-1,d=[];for(let y of a)for(let h of y.patterns??[]){if(!K(h).test(l))continue;let m=ze(h);m>p?(p=m,d=[y.name]):m===p&&!d.includes(y.name)&&d.push(y.name)}d.length>1&&u.add([...d].sort().join(" + "))}u.size>0&&i.push(w("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...u].join(", ")}.`,{pairs:[...u]}));let o=s.filter(l=>!j(l,a));return o.length>0&&i.push(w("CONFIG_UNCLASSIFIED_FILES",`${o.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:o.length,samples:o.slice(0,5)})),i}function Dn(e,t){return t.some(n=>{try{return K(n).test(e)}catch{return!1}})}function Nn(e,t){let n=e.contract.config.safety??{},s=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,r=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,i=e.contract.config.dynamicImportAllowlist??[],a=t.safetyUses.filter(d=>d.kind==="ts-suppression").map(({file:d,line:y})=>({file:d,line:y})),c=t.safetyUses.filter(d=>d.kind==="any-cast").map(({file:d,line:y})=>({file:d,line:y})),f=t.safetyUses.filter(d=>(d.kind==="dynamic-import"||d.kind==="dynamic-require")&&!Dn(d.file,i)).map(d=>({file:d.file,line:d.line,kind:d.kind==="dynamic-require"?"require":"import"})),A=n.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(d=>d.kind==="in-memory-store").map(d=>({file:d.file,line:d.line,store:d.symbol??"in-memory store"})),g=n.allowDisabledPeerIsolation===!0?[]:(e.contract.config.rules??[]).filter(d=>d.peerIsolation===!1||d.allowed===!1&&!!d.from&&d.from===d.to&&d.peerIsolation!==!0).map(d=>({from:d.from,to:d.to})),u={tsSuppressions:a,anyCasts:c,nonLiteralDynamicImports:f,inMemoryProductionStores:A,disabledPeerIsolationRules:g,thresholds:{maxTsSuppressions:s,maxAnyCasts:r}},o=[],l=f.filter(d=>d.kind==="import");if(l.length>0){let d=l[0];o.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:d.file,line:d.line,message:`${l.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let p=f.filter(d=>d.kind==="require");if(p.length>0){let d=p[0];o.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:d.file,line:d.line,message:`${p.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(a.length>s){let d=a[0];o.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:d.file,line:d.line,message:`${a.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${s}).`})}if(c.length>r){let d=c[0];o.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:d.file,line:d.line,message:`${c.length} explicit any cast(s) exceed safety.maxAnyCasts (${r}).`})}if(A.length>0){let d=A[0];o.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:d.file,line:d.line,message:`${A.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 g.length>0&&o.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${g.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:u,warnings:o}}function Fn(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,s)=>s.length-n.length)[0]}function Ft(e,t){let n=t.config.layers.filter(s=>(s.intentPrefixes??[]).length>0);return Xe(e,n.length>0?n:Ze.map(s=>({name:s.layer,prefixes:s.prefixes})))}function Mn(e,t,n){let s=[],r=new Map(e.contract.config.layers.map(i=>[i.name,i]));for(let i of t.ambientUses){let a=n.get(i.file);!a||!Fn(i.symbol,r.get(a)?.forbiddenGlobals??[])||s.push({ruleId:"FORBIDDEN_GLOBAL",file:i.file,line:i.line,fromLayer:a,target:i.symbol,message:`${a} must not use the ambient global "${i.symbol}".`})}for(let i of t.capabilityUses){let a=n.get(i.file);if(!a)continue;let c=r.get(a),f=c?.forbiddenGlobals??[],A=i.source==="import-based"?t.dependencies.find(g=>g.from===i.file&&g.line===i.line&&g.specifier===i.symbol&&!g.typeOnly)?.kind:void 0;if(!(i.source==="ambient-global"&&fe(i.symbol,f))){if(i.source==="import-based"){let g=V(i.symbol,f);if(g){s.push({ruleId:"FORBIDDEN_GLOBAL",file:i.file,line:i.line,fromLayer:a,target:i.symbol,...A?{edgeKind:A}:{},message:`${a} must not use module "${i.symbol}" because it is the import form of forbidden global "${g}".`});continue}}X(c).includes(i.capability)&&s.push({ruleId:"CAPABILITY_VIOLATION",file:i.file,line:i.line,fromLayer:a,target:i.symbol,capability:i.capability,...A?{edgeKind:A}:{},message:i.source==="import-based"?`${a} denies the ${i.capability} capability; found import of "${i.symbol}".`:`${a} denies the ${i.capability} capability; found ambient "${i.symbol}".`})}}for(let i of t.publishCalls){let a=n.get(i.file);if(!a)continue;for(let f of ue({publishCall:!0,rawIntentName:i.rawIntentName,objectHasIntent:i.objectHasIntent,arkPublishCandidate:i.arkPublishCandidate,hasSource:i.hasSource}))s.push({ruleId:f.ruleId,file:i.file,line:i.line,...f.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:a}:{},message:f.message});if(!i.sourceIntent)continue;let c=Ft(i.sourceIntent,e.contract);!c||c===a||s.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:i.file,line:i.line,fromLayer:a,toLayer:c,target:i.sourceIntent,message:`Publish source "${i.sourceIntent}" resolves to ${c}, but the publishing file is classified as ${a}.`})}for(let i of t.intentReferences){let a=n.get(i.file);if(!a)continue;let c=Ft(i.intent,e.contract);if(!c)continue;let f=N(e.contract.config.rules,a,c);f&&s.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:i.file,line:i.line,fromLayer:a,toLayer:c,target:i.intent,message:f.message??`${a} must not reference ${c} intent ${i.intent}.`})}return s}function Hn(e){let{facts:t}=e,n=he(e.contract.config),s=t.evidenceRequirementsHash===n,r=s?t.completeness:"unavailable",i=s?t.completenessReasons:[...t.completenessReasons,{code:"EVIDENCE_REQUIREMENTS_MISMATCH",message:"Resolved facts were collected for different policy-controlled evidence requirements."}].sort((p,d)=>{let y=`${p.code}\0${p.file??""}\0${p.message}`,h=`${d.code}\0${d.file??""}\0${d.message}`;return y<h?-1:y>h?1:0}),a=t.files.map(p=>({...p,layer:j(p.path,e.contract.config.layers)??null})),c=new Map(a.map(p=>[p.path,p.layer])),f=t.dependencies.map(p=>{let d=p.target?c.get(p.target)??j(p.target,e.contract.config.layers):void 0;return{from:p.from,fromLayer:c.get(p.from)??null,...p.resolution==="resolved-project"&&p.target?{to:p.target,...d?{toLayer:d}:{}}:{},line:p.line,kind:p.kind,typeOnly:p.typeOnly,...p.targetTypeOnlyExports?{targetTypeOnlyExports:p.targetTypeOnlyExports}:{},...p.sourcePureTypeModule?{sourcePureTypeModule:p.sourcePureTypeModule}:{},...p.namedBindingsTypeOnly?{namedBindingsTypeOnly:p.namedBindingsTypeOnly}:{},...p.portProofEligible?{portProofEligible:p.portProofEligible}:{}}}),A=Ne({config:e.contract.config,rules:e.contract.config.rules,files:a.map(p=>p.path)}),g=Nn(e,t),u=ce({config:e.contract.config,rules:e.contract.config.rules,files:a.filter(p=>p.layer).map(p=>p.path),contentViolations:Mn(e,t,c),edges:f,warnings:[...A,...g.warnings],safety:g.report}),o=r==="complete"&&u.violations.length===0,l=o&&u.warnings.every(p=>p.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:r,completenessReasons:i,valid:o,strictValid:l,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:g.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:a,layers:e.contract.config.layers.map(p=>p.name),edges:f,capabilityUses:t.capabilityUses,violations:u.violations,warnings:u.warnings}}}function Ie(e){return Hn({contract:e.contract,facts:z(e.facts)})}function Fe(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return e.typeOnly||e.targetTypeOnlyExports||e.namedBindingsTypeOnly?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":e.peerIsolation?"Extract the shared dependency to a shared layer, then preflight again.":`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, then preflight again.`;case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, 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, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";default:return`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}function Mt(e){return S(E(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}function Ht(e){let t=Ce(e),n=new Map(t.ir.files.map(l=>[l.path,l])),s=[],r=new Set,i=[];for(let l of e.changes){let p=l.path.replace(/\\/g,"/"),d=Z(l.path);if(!d||d===".."||d.startsWith("../")||p.startsWith("/")||/^[A-Za-z]:\//.test(p)||p.includes("\0")){i.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(r.has(d)){i.push({ruleId:"DUPLICATE_CHANGE_PATH",file:d,line:1,message:`The atomic change set contains more than one operation for ${d}.`});continue}r.add(d),"delete"in l&&l.delete&&!n.has(d)&&i.push({ruleId:"DELETE_TARGET_MISSING",file:d,line:1,message:`Cannot delete ${d} because it is not present in the supplied base tree.`}),s.push("delete"in l&&l.delete?{path:d,delete:!0}:{path:d,content:"content"in l?l.content:""})}e.changes.length===0&&i.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let a=De({...e,changes:s}),c=new Map(a.ir.files.map(l=>[l.path,l])),f=a.ir.violations.filter(l=>l.ruleId==="CAPABILITY_VIOLATION"||l.ruleId==="FORBIDDEN_GLOBAL").map(l=>{let p=c.get(l.evidence.file)?.layer;return{ruleId:l.ruleId,file:l.evidence.file,line:l.evidence.line,target:l.symbol,...l.capability?{capability:l.capability}:{},...p?{fromLayer:p}:{},edgeKind:"import",message:l.message}}),A=ce({config:e.contract.config,rules:e.contract.config.rules,files:a.ir.files.map(l=>l.path),contentViolations:f,edges:a.ir.edges.filter(l=>!!l.fromLayer).map(l=>({from:l.from,fromLayer:l.fromLayer,...l.to?{to:l.to}:{},...l.toLayer?{toLayer:l.toLayer}:{},line:l.evidence.line,kind:"import"}))}),g=s.map(l=>{let p=Z(l.path),d=n.get(p),y=c.get(p);return{path:p,operation:"delete"in l&&l.delete?"delete":d?"update":"create",...d?{beforeContentHash:d.contentHash}:{},...y?{candidateContentHash:y.contentHash}:{}}}).sort((l,p)=>l.path.localeCompare(p.path)),u=[...i,...A.violations].map(l=>({...l,nextAction:Fe(l)})),o=e.changeMap?le({changeMap:e.changeMap,changes:g,baseDependencies:t.ir.edges.flatMap(l=>l.to?[{from:l.from,to:l.to}]:[]),candidateDependencies:a.ir.edges.flatMap(l=>l.to?[{from:l.from,to:l.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&a.valid&&u.length===0&&(o?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:a.ir.compilerOptionsHash,baseTreeHash:Mt(t.ir.files),candidateTreeHash:Mt(a.ir.files),baseCompleteness:t.completeness,candidateCompleteness:a.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:a.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...o?{convergence:o}:{},changes:g,violations:u,warnings:A.warnings}}function Vn(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let r of t.split("/"))if(!(!r||r==="."))if(r===".."){if(n.length===0)return;n.pop()}else n.push(r);let s=n.join("/");return s&&s===t?s:void 0}function jn(e,t){return[["resolverIdentity",e.resolverIdentity,t.resolverIdentity],["compilerIdentity",e.compilerIdentity,t.compilerIdentity],["evidenceRequirementsHash",e.evidenceRequirementsHash,t.evidenceRequirementsHash],["projectPackageName",e.projectPackageName??"",t.projectPackageName??""]].filter(([,s,r])=>s!==r).map(([s,r,i])=>({ruleId:"FACTS_IDENTITY_MISMATCH",file:"<change-set>",line:1,field:s,before:r,candidate:i,message:`Base and candidate facts must use the same ${s}.`}))}function Gn(e,t,n,s){let r=n.get(t),i=s.get(t);return{path:t,operation:"delete"in e&&e.delete?"delete":r?"update":"create",...r?{beforeContentHash:r.contentHash}:{},...i?{candidateContentHash:i.contentHash}:{}}}function Vt(e){let t=z(e.baseFacts),n=z(e.candidateFacts),s=Ie({contract:e.contract,facts:t}),r=Ie({contract:e.contract,facts:n}),i=new Map(t.files.map(o=>[o.path,o])),a=new Map(n.files.map(o=>[o.path,o])),c=jn(t,n),f=new Map,A=[];for(let o of e.changes){let l=Vn(o.path);if(!l){c.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(f.has(l)){c.push({ruleId:"DUPLICATE_CHANGE_PATH",file:l,line:1,message:`The atomic change set contains more than one operation for ${l}.`});continue}f.set(l,o);let p=i.get(l),d=a.get(l);if("delete"in o&&o.delete)p||c.push({ruleId:"DELETE_TARGET_MISSING",file:l,line:1,message:`Cannot delete ${l} because it is not present in the supplied base facts.`}),d&&c.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:l,line:1,message:`Candidate facts still contain deleted file ${l}.`});else{let y="content"in o?o.content:"",h=S(y);d?d.contentHash!==h&&c.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:l,line:1,expectedContentHash:h,candidateContentHash:d.contentHash,message:`Candidate facts for ${l} do not match the declared content.`}):c.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:l,line:1,message:`Candidate facts do not contain changed file ${l}.`})}A.push(Gn(o,l,i,a))}e.changes.length===0&&c.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});for(let o of new Set([...i.keys(),...a.keys()])){if(f.has(o))continue;let l=i.get(o),p=a.get(o);l&&p&&E(l)===E(p)||c.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:o,line:1,message:`Candidate facts change ${o}, but the atomic change set does not declare it.`})}let g=e.changeMap?le({changeMap:e.changeMap,changes:A,baseDependencies:s.ir.edges.flatMap(o=>o.to?[{from:o.from,to:o.to}]:[]),candidateDependencies:r.ir.edges.flatMap(o=>o.to?[{from:o.from,to:o.to}]:[])}):void 0,u=[...c,...r.ir.violations].map(o=>({...o,nextAction:Fe(o)}));return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:s.completeness==="complete"&&r.strictValid&&u.length===0&&(g?.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:s.completeness,candidateCompleteness:r.completeness,baseCompletenessReasons:s.completenessReasons,candidateCompletenessReasons:r.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...g?{convergence:g}:{},changes:A.sort((o,l)=>o.path<l.path?-1:o.path>l.path?1:0),violations:u,warnings:r.ir.warnings}}var Un="1.1";var Bn="1.0";export{it as ANALYSIS_IR_SCHEMA_VERSION,qt as ARK_ANALYSIS_RESULT_SCHEMA,Gt as ARK_ANALYSIS_RESULT_SCHEMA_VERSION,et as ARK_CONFIG_SCHEMA,pn as ARK_CONFIG_SCHEMA_VERSION,Bn as ARK_DESIGN_DELTA_SCHEMA_VERSION,Un as ARK_ENFORCEMENT_STATE_SCHEMA_VERSION,st as POLICY_DELTA_SCHEMA_VERSION,rt as RESOLVED_CANDIDATE_FACTS_SCHEMA,W as RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,le as analyzeArchitectureConvergence,De as analyzeChange,Dt as analyzePolicyDelta,Ce as analyzeProject,Ie as analyzeResolvedProject,at as classifyArkPolicyDelta,Ne as collectAnalysisConfigWarnings,te as collectForbiddenCapabilityUses,bt as createAICodeGate,Bt as createAdapterResult,Oe as createArchitectureProfile,Rt as createArchitectureProfileFromArkConfig,vt as createElevenLayerArkConfig,nt as createResolvedCandidateFacts,lt as detectArchitectureCycles,S as deterministicHash,Pe as elevenLayerProfile,ce as evaluateArchitectureGraph,Nt as explainViolation,ee as extractSemanticDependencies,we as loadArkConfigContract,Te as loadContract,z as loadResolvedCandidateFacts,tt as parseArkConfigJson,ot as policyDeltaAcknowledgementMatches,Ht as preflightChange,Vt as preflightResolvedChange,he as resolvedFactsEvidenceRequirementsHash,E as stableSerialize,He as toAdapterDiagnostic,jt as version};
@@ -8,7 +8,7 @@ hard-CI split is a deliberate trade-off, not a gap: local hooks and MCP coach at
8
8
  while a required merge status is the one boundary a repository can make every write path share.
9
9
 
10
10
  CLI names: prefer **`arkgate` / `arkgate-check` / `arkgate-mcp`**; aliases `ark` / `ark-check` /
11
- `ark-mcp` still work for one major. The current source candidate tests packed project TypeScript
11
+ `ark-mcp` still work for one major. **arkgate@3.8.0+** tests packed project TypeScript
12
12
  **5.9.3 / 6.0.3 / 7.0.2** and uses an exact, physically distinct TypeScript 6 analysis host when
13
13
  the project API is unusable. Published 3.7.0 predates that correction; see the distribution and
14
14
  completeness boundary in [typescript-support.md](typescript-support.md).
@@ -631,10 +631,10 @@ edges are not denied by that rule.
631
631
  ```
632
632
 
633
633
  - **Denied:** `src/features/auth/**` → `src/features/payments/**` (different slice id).
634
- - **Allowed:** same-slice imports; classic non-peerIsolation denies still apply across layers.
634
+ - **Allowed:** same-slice imports when both paths classify; classic non-peerIsolation denies still apply across layers.
635
635
  - **`sliceFolders`:** optional parent segments (default: inferred from layer globs).
636
- - **Fail-open:** missing paths or unclassifiable slicesdo not deny via peerIsolation.
637
- - Enforced by `ark-check`, `arkgate/eslint`, and `ark-mcp` when paths resolve.
636
+ - **Fail-closed:** missing paths, empty/unresolvable slice folders, or unclassifiable either side **deny** via peerIsolation (cannot prove same-slice).
637
+ - Enforced by `ark-check`, `arkgate/eslint`, and `ark-mcp` (path-aware edges and path-less intent refs share the same SoT).
638
638
  - Fixes are **judgment** (not mechanical-safe).
639
639
 
640
640
  Agents can generate a config from the project's actual directory layout instead of inventing layer mappings:
@@ -96,6 +96,9 @@ process module-capability family must be denied.
96
96
  Rule fields:
97
97
 
98
98
  - `from`, `to`, `allowed`, `message`, `peerIsolation`, `sliceFolders`
99
+ - `peerIsolation: true` + `allowed: false`: deny only when slice ids differ; same-slice allows
100
+ when both paths classify. Missing paths, empty slice folders, or unclassifiable slices
101
+ **fail closed** (deny — cannot prove same-slice).
99
102
 
100
103
  Safety fields:
101
104
 
@@ -1,9 +1,9 @@
1
1
  # Reference: commands and artifacts
2
2
 
3
3
  Product: **ArkGate** (`arkgate`). Prefer `arkgate` / `arkgate-check` / `arkgate-mcp`; aliases
4
- `ark` / `ark-check` / `ark-mcp` work for one major. The current source candidate supports packed
5
- project TypeScript 5.9/6.0/7.0 with a physically distinct TypeScript 6 analysis host; published
6
- 3.7.0 predates that correction: [typescript-support.md](../typescript-support.md).
4
+ `ark` / `ark-check` / `ark-mcp` work for one major. **arkgate@3.8.0+** supports packed project
5
+ TypeScript 5.9/6.0/7.0 with a physically distinct TypeScript 6 analysis host; published 3.7.0
6
+ predates that correction: [typescript-support.md](../typescript-support.md).
7
7
 
8
8
  ## Recommendation
9
9