arkgate 3.8.0 → 3.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +37 -0
- package/README.md +4 -4
- package/bin/ark-layer-match.mjs +9 -4
- package/bin/lib/analysis-engine.mjs +6 -6
- package/dist/eslint/index.cjs +1 -1
- package/dist/eslint/index.d.ts +1 -1
- package/dist/eslint/index.js +1 -1
- package/dist/index.cjs +7 -7
- package/dist/index.d.ts +97 -69
- package/dist/index.js +6 -6
- package/docs/agent-guide.md +4 -4
- package/docs/configuration.md +3 -0
- package/docs/enthusiast/reference-commands.md +3 -3
- package/docs/package-surface.md +2 -2
- package/docs/typescript-support.md +11 -12
- package/package.json +1 -1
- package/server.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
"use strict";var qe=Object.defineProperty;var Kt=Object.getOwnPropertyDescriptor;var Yt=Object.getOwnPropertyNames;var Wt=Object.prototype.hasOwnProperty;var Jt=(e,t)=>{for(var n in t)qe(e,n,{get:t[n],enumerable:!0})},Zt=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Yt(t))!Wt.call(e,r)&&r!==n&&qe(e,r,{get:()=>t[r],enumerable:!(s=Kt(t,r))||s.enumerable});return e};var Xt=e=>Zt(qe({},"__esModule",{value:!0}),e);var Wn={};Jt(Wn,{ANALYSIS_IR_SCHEMA_VERSION:()=>De,ARK_ANALYSIS_RESULT_SCHEMA:()=>Ct,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>At,ARK_CONFIG_SCHEMA:()=>_e,ARK_CONFIG_SCHEMA_VERSION:()=>Lt,ARK_DESIGN_DELTA_SCHEMA_VERSION:()=>zt,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION:()=>qt,POLICY_DELTA_SCHEMA_VERSION:()=>He,RESOLVED_CANDIDATE_FACTS_SCHEMA:()=>dt,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION:()=>ct,analyzeArchitectureConvergence:()=>Z,analyzeChange:()=>Se,analyzePolicyDelta:()=>ft,analyzeProject:()=>ce,analyzeResolvedProject:()=>pe,classifyArkPolicyDelta:()=>Ve,collectAnalysisConfigWarnings:()=>xe,collectForbiddenCapabilityUses:()=>W,createAICodeGate:()=>st,createAdapterResult:()=>bt,createArchitectureProfile:()=>Ce,createArchitectureProfileFromArkConfig:()=>ot,createElevenLayerArkConfig:()=>lt,createResolvedCandidateFacts:()=>pt,detectArchitectureCycles:()=>Ge,deterministicHash:()=>k,elevenLayerProfile:()=>be,evaluateArchitectureGraph:()=>ee,explainViolation:()=>ut,extractSemanticDependencies:()=>Y,loadArkConfigContract:()=>Ae,loadContract:()=>ve,loadResolvedCandidateFacts:()=>q,parseArkConfigJson:()=>Ne,policyDeltaAcknowledgementMatches:()=>je,preflightChange:()=>yt,preflightResolvedChange:()=>mt,resolvedFactsEvidenceRequirementsHash:()=>Ie,stableSerialize:()=>v,toAdapterDiagnostic:()=>we,version:()=>gt});module.exports=Xt(Wn);var gt="3.8.0";var At="1.3";function I(e){return typeof e=="string"&&e.length>0?e:void 0}function ht(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function Qt(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 we(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:ht(e.line,1),column:ht(e.column,1)},evidence:r,nextAction:I(e.nextAction)??Qt(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=>we(c,"error")),...(e.warnings??[]).map(c=>we(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 Ct={$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 Ke=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),We=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Je=Object.freeze(Object.keys(We).sort()),ze=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"}),Ye=Object.freeze({process:Object.freeze(["process","node:process"])});function fe(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=ze[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let s=e.slice(0,n),r=ze[s];if(r)return r;let i=e.indexOf("/",n+1);return i<0?null:ze[e.slice(0,i)]??null}function H(e,t){for(let n of t)if(Ye[n]?.includes(e))return n;return null}function Pe(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let s=t.slice(0,n).join("."),r=We[s];if(r)return r}return null}function te(e){if(e?.pure===!0)return[...Ke].sort();let n=(e?.capabilities?.deny??[]).filter(s=>Ke.includes(s));return[...new Set(n)].sort()}function ue(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 Oe(e){let t=new Set,n=new Set,s=Object.keys(We);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 Ye[r]??[])t.add(`import-exact:${a}`)}for(let r of te(e)){if(t.add(`import:${r}`),r==="process")for(let i of Ye.process)t.add(`import-exact:${i}`);for(let i of s)Pe(i)===r&&t.add(`ambient:${i}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}var It=new Map;function Et(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function Ze(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 en(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=It.get(e);if(t)return t;let n=Ze(e),s=en(n),r="",i=0;for(let c=0;c<n.length;c+=1){let f=n[c];f==="\\"&&c+1<n.length?(r+=Et(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+=Et(f)}let a=new RegExp(`^${r}$`);return It.set(e,a),a}function Xe(e){let t=Ze(String(e)),s=t.split("*")[0].split("/").filter(Boolean).length,r=t.replace(/\*/g,"").length;return s*1e4+r}function V(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=Xe(a);c>r&&(r=c,s=i.name)}}return s}function Rt(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 tn(e){let t=new Set;for(let n of e??[]){let r=Ze(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 nn(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 tn(s?.patterns)}function T(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)continue;let c=nn(r,t,s?.layers);if(c.length===0)continue;let f=Rt(i,c),A=Rt(a,c);if(!f||!A)continue;if(f!==A)return r;continue}if(t!==n)return r}}function ne(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function xt(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function vt(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 kt(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 Qe(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function et(e,t,n,s){let r=s.parent&&e.isShorthandPropertyAssignment(s.parent)&&s.parent.name===s,i;try{i=r?t.getShorthandAssignmentValueSymbol(s.parent):Qe(t,s)}catch{i=void 0}return!!i?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}function Y(e,t){let n,s=[],r=(a,c,f,A=!1)=>s.push({specifier:f,kind:c,line:xt(t,a),typeOnly:A,unresolved:f===void 0,node:a}),i=a=>{if(e.isImportDeclaration(a))r(a,"import",ne(e,a.moduleSpecifier),vt(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)r(a,"export",ne(e,a.moduleSpecifier),vt(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))r(a,"require",ne(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"&&!et(e,n??(n=kt(e,t)),t,a.expression);(c||A)&&r(a,A?"require":"dynamic-import",ne(e,a.arguments[0]))}e.forEachChild(a,i)};return i(t),s}function rn(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=ne(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 sn(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 St(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 W(e,t,n){if(n.length===0)return[];let s=new Set(n),r=kt(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=rn(e,o);if(!l)return;let d=Qe(r,l.root),p=d?i.get(d):void 0;return p?[...p,...l.segments.slice(1)]:et(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 d=c(l.initializer),p=Qe(r,l.name);!d||!p||i.set(p,d)}let f=[],A=new Set,g=(o,l)=>{let d=xt(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?St(s,d):void 0;p&&g(p,o)}else e.isIdentifier(o)&&s.has(o.text)&&sn(e,o)&&!et(e,r,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?ne(e,p.propertyName)??p.propertyName.text:p.name.text,h=St(s,[...d,y]);h&&g(h,o.initializer)}}e.forEachChild(o,u)};return u(t),f}function tt(e,t,n){let s=[];for(let r of n?.dependencies??Y(e,t)){if(r.typeOnly||!r.specifier)continue;let i=fe(r.specifier);i&&s.push({capability:i,symbol:r.specifier,line:r.line,source:"import-based"})}for(let r of n?.ambientUses??W(e,t,Je)){let i=Pe(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 nt={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."},rt=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 it(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 J(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function ye(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&J(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:nt.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:nt.PUBLISH_MISSING_SOURCE}),t}function R(e,t,n){return{ruleId:e,code:e,message:t,...n}}function re(e,t){return e.slice(0,t).split(`
|
|
2
|
-
`).length}function an(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 on(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 ln(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 cn(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 pn(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}function dn(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}function ge(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function fn(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}function wt(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(s=>!e.isPropertyAssignment(s)&&!e.isShorthandPropertyAssignment(s)?!1:fn(e,s.name)===n)}function he(e,t,n){return wt(e,t,n)!==void 0}function me(e,t,n){let s=wt(e,t,n);return s&&e.isPropertyAssignment(s)?s.initializer:void 0}function un(e,t){let n=me(e,t,"metadata");return he(e,n,"source")}function Pt(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?Pt(e,t.name):!1:!1}function yn(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 mn(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],s=ge(e,n);return s!==void 0&&J(s)||he(e,n,"intent")||Pt(e,n)}function gn(e,t){if(!e.isCallExpression(t))return!1;let[n,s,r]=t.arguments;return un(e,n)||he(e,s,"source")||he(e,r,"source")}function hn(e,t){if(!e.isCallExpression(t))return;let[n,s,r]=t.arguments,i=me(e,n,"metadata");return ge(e,me(e,i,"source"))??ge(e,me(e,s,"source"))??ge(e,me(e,r,"source"))}function An(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(yn(e,u)){let o=u.arguments[0],l=ge(e,o);for(let p of ye({publishCall:!0,rawIntentName:l,objectHasIntent:he(e,o,"intent"),arkPublishCandidate:mn(e,u),hasSource:gn(e,u)}))f.push(R(p.ruleId,p.message,{line:A(u),filePath:a}));let d=hn(e,u);if(s&&c&&d&&J(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(r),f}function st(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?Y(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})):on(i),p=e.typescript?ln(e.typescript,i):an(i);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)||dn(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(R("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${m}`,{line:b.index===void 0?void 0:re(i,b.index),filePath:A,suggestion:"Remove infrastructure imports from domain/application layers."+h}))}else i.includes(m)&&c.push(R("FORBIDDEN_SUBSTRING",`Forbidden substring: ${m}`,{line:re(i,i.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,de=b?.layer;if(de&&g){let ke=T(e.architectureProfile?.rules,g,de,{fromPath:C?.relPath,toPath:b?.relPath,layers:e.architectureLayers});if(ke){if(m.typeOnly&&!ke.peerIsolation)continue;let Be=!!ke.peerIsolation;c.push(R("LAYER_IMPORT_VIOLATION",ke.message??(Be?`Layer "${g}" must not import across slices into "${de}".`:`Layer "${g}" must not import "${de}".`),{line:re(i,m.index),source:m.value,target:m.value,filePath:A,fromLayer:g,toLayer:de,suggestion:Be?"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:Be,...m.typeOnly?{typeOnly:!0}:{}}}));continue}continue}y||m.typeOnly||!cn(m.value)&&!pn(m.value)||c.push(R("FORBIDDEN_IMPORT",`Forbidden ${m.kind} target: "${m.value}".`,{line:re(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(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(r&&t.size>0)for(let m of p)J(m.value)&&!t.has(m.value)&&c.push(R("UNKNOWN_INTENT",`Unknown intent reference: "${m.value}"`,{line:re(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 p){if(!J(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:re(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(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(...W(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 tt(e.typescript,o))m.has(C.capability)&&(C.source==="ambient-global"&&ue(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(...An(e.typescript,i,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 Lt="1.0",$e="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",Ot=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],bn=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Cn(){let e=[];for(let t of Ot)for(let n of Ot)t===n||bn.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var Te=Cn();var j={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},_e={$schema:"https://json-schema.org/draft/2020-12/schema",$id:$e,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:$e,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:Te,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}}}}},se=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
|
|
3
|
-
${n.map(
|
|
4
|
-
`)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function $t(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function at(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function ie(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function In(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function Le(e,t,n,s,r){if(t.$ref){let i=In(t.$ref,s);if(!i){r.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}Le(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(!$t(e)){r.push({path:n,message:`must be an object; received ${ie(e)}`});return}let i=t.properties??{};for(let a of t.required??[])e[a]===void 0&&r.push({path:at(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in i||r.push({path:at(n,a),message:"unknown field"});for(let[a,c]of Object.entries(i))e[a]!==void 0&&Le(e[a],c,at(n,a),s,r);return}if(t.type==="array"){if(!Array.isArray(e)){r.push({path:n,message:`must be an array; received ${ie(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)=>Le(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 ${ie(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 ${ie(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){r.push({path:n,message:`must be an integer; received ${ie(e)}`});return}t.minimum!==void 0&&e<t.minimum&&r.push({path:n,message:`must be at least ${t.minimum}`})}}function En(e){return{...e,$schema:e.$schema===void 0?$e: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?Te.map(t=>({...t})):e.rules}}function Rn(e,t="ark.config.json"){if(!$t(e))throw new se(t,[{path:"$",message:`must be an object; received ${ie(e)}`}]);let n=e.schemaVersion===void 0?"unversioned":null;if(e.schemaVersion!==void 0&&e.schemaVersion!=="1.0")throw new se(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.0`}]);return{candidate:En(e),migratedFrom:n}}function Ae(e,t="ark.config.json"){let{candidate:n,migratedFrom:s}=Rn(e,t),r=[];if(Le(n,_e,"$",_e,r),r.length>0)throw new se(t,r);return{config:n,migratedFrom:s}}function Ne(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(s){throw new se(t,[{path:"$",message:`invalid JSON: ${s instanceof Error?s.message:String(s)}`}])}return Ae(n,t)}function _t(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:$e,schemaVersion:"1.0"};for(let[n,s]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=s);return t}function vn(e){return e.endsWith(".")?e:`${e}.`}function Sn(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 Ce(e){let t=e.layers.map(r=>({...r,prefixes:r.prefixes.map(vn)})),n=[...t].sort(Sn),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 ot(e,t={}){return Ce({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 xn=[{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}],be=Ce({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:xn,rules:Te.map(e=>({...e}))}),kn={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 lt(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,s=t==="."?"":`${t}/`;return _t({include:e.include??[t],layers:be.layers.map(r=>({name:r.name,patterns:(kn[r.name]??[r.name]).map(i=>`${s}${i}/**`),intentPrefixes:r.prefixes,optional:n})),rules:[...be.rules]})}var De="1.0",ct="1.0",Nt=["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 Ie(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 wn(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),r=e.capabilityUses.map(u=>({...u})).sort(B),i=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:r,ambientUses:i,publishCalls:a,intentReferences:c,safetyUses:f}}function Dt(e){let t=wn(e);return{...t,factsHash:k(v(t))}}function pt(e){return Dt(Mt(_(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),r=Object.keys(e).find(i=>!s.has(i));if(r)throw new Error(`${n}.${r} 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 ae(e,t,n){if(e[t]!==void 0)return x(e,t,n)}function D(e,t,n){let s=x(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 L(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}function Ft(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 oe(e,t,n){let s=Ft(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 r=e[t];if(typeof r!="string"||!n.includes(r))throw new Error(`${s}.${t} must be one of ${n.join(", ")}.`);return r}function Tt(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 Pn(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 Mt(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"],"$"),r=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"&&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=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:Ft(h,"parseDiagnosticCount",y),exportsOnlyTypes:L(h,"exportsOnlyTypes",y),typeOnlyExportNames:Tt(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=ae(h,"specifier",y),b=ae(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:oe(h,"line",y),resolution:C,...b?{target:D(h,"target",y)}:{},...h.namedBindings!==void 0?{namedBindings:Tt(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:oe(h,"line",y),symbol:x(h,"symbol",y),capability:U(h,"capability",Nt,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:oe(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=ae(h,"rawIntentName",y),b=ae(h,"sourceIntent",y);return{file:D(h,"file",y),line:oe(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:oe(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=ae(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:oe(h,"line",y),kind:b,...m?{symbol:m}:{}}});Pn(i,d=>d.path,"$.files");let o=new Set(i.map(d=>d.path));for(let d of i){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"&&i.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=ae(e,"projectPackageName","$");return{schemaVersion:n,completeness:s,completenessReasons:r,resolverIdentity:x(e,"resolverIdentity","$"),compilerIdentity:x(e,"compilerIdentity","$"),compilerOptionsHash:x(e,"compilerOptionsHash","$"),tsconfigHash:x(e,"tsconfigHash","$"),evidenceRequirementsHash:x(e,"evidenceRequirementsHash","$"),...l?{projectPackageName:l}:{},files:i,dependencies:a,capabilityUses:c,ambientUses:f,publishCalls:A,intentReferences:g,safetyUses:u}}function q(e){let t=_(e,"$"),n=x(t,"factsHash","$"),s=x(t,"candidateTreeHash","$"),r=Dt(Mt(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 E={type:"string",minLength:1},le={type:"integer",minimum:1},F={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},dt={$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:le,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:le,symbol:E,capability:{enum:Nt},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:F,line:le,symbol:E}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:F,line:le,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:le,intent:E}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:F,line:le,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 Ee(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 Z(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,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[...r.values()].sort((l,d)=>P(l).localeCompare(P(d)))){if(a.has(P(o))){t.push(Ee("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(Ee("contradictory",o,`${o.from} -> ${o.to} was planned, but the candidate contains the reverse edge.`))):t.push(Ee("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)))i.has(o)||r.has(o)||c.has(o)||!f.has(l.from)&&!f.has(l.to)||t.push({...Ee("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(([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({...Ee("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 He="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 X(e,t,n,s,r){let i=O(n),a=O(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&&S(e,{kind:"added",path:t,classification:r.added,message:r.addedMessage,before:i,after:a}),g.length>0&&S(e,{kind:"removed",path:t,classification:r.removed,message:r.removedMessage,before:i,after:a}))}function Fe(e,t,n,s,r,i,a){if(n===s)return;S(e,{kind:s?"enabled":"disabled",path:t,classification:s?r:r==="strengthening"?"weakening":"strengthening",message:s?i:a,before:n,after:s})}function Me(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 On(e,t,n){let s=Me(t,i=>i.name),r=Me(n,i=>i.name);(s.duplicates.length>0||r.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: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){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;X(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."}),X(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=Oe(a),g=Oe(c);X(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."}),X(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)}),Fe(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."),Fe(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 Ln(e,t,n){let s=a=>`${a.from}->${a.to}`,r=Me(t,s),i=Me(n,s);(r.duplicates.length>0||i.duplicates.length>0)&&S(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&&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 $n(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&&S(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"])Fe(e,`$.safety.${i}`,s[i]===!0,r[i]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}function _n(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 Ve(e,t){let n=[];X(n,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),X(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."}),X(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."}),Fe(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";S(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)&&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}),On(n,e.layers,t.layers),Ln(n,e.rules,t.rules),$n(n,e,t),n.sort((a,c)=>a.path.localeCompare(c.path)||a.id.localeCompare(c.id)),{schemaVersion:He,classification:_n(n),findings:n}}function je(e,t){if(!e||e.schemaVersion!==He||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=O(e.findingIds),s=O(t.findingIds);return n.length===s.length&&n.every((r,i)=>r===s[i])}function Q(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 Ht(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}function z(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}function Re(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 M(e,t,n){return e.startsWith(t,n)&&!Ht(e[n-1])&&!Ht(e[n+t.length])}function Tn(e,t){if(t=z(e,t+6),e[t]==="(")return Re(e,z(e,t+1));let n=!1;if(M(e,"type",t)){let r=z(e,t+4);e[r]!==","&&!M(e,"from",r)&&(n=!0)}let s=Vt(e,t,!0);return s&&n?{...s,typeOnly:!0}:s}function Nn(e,t){t=t+6;let n=z(e,t),s=!1;if(M(e,"type",n)){let i=z(e,n+4);(e[i]==="{"||e[i]==="*")&&(s=!0)}let r=Vt(e,t,!1);return r&&s?{...r,typeOnly:!0}:r}function Vt(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(M(e,"from",t))return Re(e,z(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return Re(e,t);if(t>0&&(M(e,"import",t)||M(e,"export",t)))return}}function Dn(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 Fn(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let s=z(e,t+7);if(e[s]!=="(")return;s=z(e,s+1);let r=Re(e,s);return r?{...r,requireCall:!0}:void 0}function Mn(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(
|
|
6
|
-
`).length;
|
|
7
|
-
`).length,c={kind:"import",file:e.path,line:a,excerpt:r.excerpt},f=Hn(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 Hn(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 Gt(e,t){let n=[];for(let s of e){if(!s.to||!s.fromLayer||!s.toLayer)continue;let r=T(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 Vn={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 ve(e,t){let n=typeof e=="string"?Ne(e,t):Ae(e,t);return{...n,policyHash:k(v(n.config))}}function ft(e){let t=ve(e.baseConfig,e.baseSource??"base ark.config.json"),n=ve(e.candidateConfig,e.candidateSource??"candidate ark.config.json"),s=Ve(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&&je(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=Q(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=[],r=[];for(let u of t){let o=jt(u,n);s.push(...o.edges),r.push(...o.capabilityUses)}let i=Gt(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(te(u))]));for(let u of r){let o=n.get(u.file)?.layer;if(!o)continue;let l=a.get(o),d=H(u.symbol,l?.forbiddenGlobals??[]);if(d){i.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)&&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"?[]:[{...Vn}],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:r,violations:i};return{mode:"lexical-compatibility",completeness:f,completenessReasons:A,valid:f==="complete"&&i.length===0,ir:g}}function Se(e){let t=new Map(e.files.map(n=>[Q(n.path),n]));for(let n of e.changes){let s=Q(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 ut(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 Ge(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 ee(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=T(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=Ge(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 xe(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 d=t.safety[l];d!==void 0&&(!Number.isInteger(d)||d<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(p=>typeof p!="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 d=Array.isArray(l.patterns)?l.patterns:[];if(d.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 p of d){let y;try{y=K(p)}catch(h){i.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&&i.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)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 d=-1,p=[];for(let y of a)for(let h of y.patterns??[]){if(!K(h).test(l))continue;let m=Xe(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&&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=>!V(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 jn(e,t){return t.some(n=>{try{return K(n).test(e)}catch{return!1}})}function Gn(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(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")&&!jn(p.file,i)).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:r}},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>r){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 (${r}).`})}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 Un(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,s)=>s.length-n.length)[0]}function Ut(e,t){let n=t.config.layers.filter(s=>(s.intentPrefixes??[]).length>0);return it(e,n.length>0?n:rt.map(s=>({name:s.layer,prefixes:s.prefixes})))}function Bn(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||!Un(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"&&ue(i.symbol,f))){if(i.source==="import-based"){let g=H(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}}te(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 ye({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=Ut(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=Ut(i.intent,e.contract);if(!c)continue;let f=T(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 qn(e){let{facts:t}=e,n=Ie(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((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=xe({config:e.contract.config,rules:e.contract.config.rules,files:a.map(d=>d.path)}),g=Gn(e,t),u=ee({config:e.contract.config,rules:e.contract.config.rules,files:a.filter(d=>d.layer).map(d=>d.path),contentViolations:Bn(e,t,c),edges:f,warnings:[...A,...g.warnings],safety:g.report}),o=r==="complete"&&u.violations.length===0,l=o&&u.warnings.every(d=>d.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(d=>d.name),edges:f,capabilityUses:t.capabilityUses,violations:u.violations,warnings:u.warnings}}}function pe(e){return qn({contract:e.contract,facts:q(e.facts)})}function Ue(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 Bt(e){return k(v(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}function yt(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 d=l.path.replace(/\\/g,"/"),p=Q(l.path);if(!p||p===".."||p.startsWith("../")||d.startsWith("/")||/^[A-Za-z]:\//.test(d)||d.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(p)){i.push({ruleId:"DUPLICATE_CHANGE_PATH",file:p,line:1,message:`The atomic change set contains more than one operation for ${p}.`});continue}r.add(p),"delete"in l&&l.delete&&!n.has(p)&&i.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&&i.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let a=Se({...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=ee({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=Q(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=[...i,...A.violations].map(l=>({...l,nextAction:Ue(l)})),o=e.changeMap?Z({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:Bt(t.ir.files),candidateTreeHash:Bt(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 zn(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 Kn(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 Yn(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 mt(e){let t=q(e.baseFacts),n=q(e.candidateFacts),s=pe({contract:e.contract,facts:t}),r=pe({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=Kn(t,n),f=new Map,A=[];for(let o of e.changes){let l=zn(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=i.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(Yn(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),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?Z({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:Ue(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 qt="1.1";var zt="1.0";0&&(module.exports={ANALYSIS_IR_SCHEMA_VERSION,ARK_ANALYSIS_RESULT_SCHEMA,ARK_ANALYSIS_RESULT_SCHEMA_VERSION,ARK_CONFIG_SCHEMA,ARK_CONFIG_SCHEMA_VERSION,ARK_DESIGN_DELTA_SCHEMA_VERSION,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION,POLICY_DELTA_SCHEMA_VERSION,RESOLVED_CANDIDATE_FACTS_SCHEMA,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,analyzeArchitectureConvergence,analyzeChange,analyzePolicyDelta,analyzeProject,analyzeResolvedProject,classifyArkPolicyDelta,collectAnalysisConfigWarnings,collectForbiddenCapabilityUses,createAICodeGate,createAdapterResult,createArchitectureProfile,createArchitectureProfileFromArkConfig,createElevenLayerArkConfig,createResolvedCandidateFacts,detectArchitectureCycles,deterministicHash,elevenLayerProfile,evaluateArchitectureGraph,explainViolation,extractSemanticDependencies,loadArkConfigContract,loadContract,loadResolvedCandidateFacts,parseArkConfigJson,policyDeltaAcknowledgementMatches,preflightChange,preflightResolvedChange,resolvedFactsEvidenceRequirementsHash,stableSerialize,toAdapterDiagnostic,version});
|
|
1
|
+
"use strict";var We=Object.defineProperty;var Wt=Object.getOwnPropertyDescriptor;var Jt=Object.getOwnPropertyNames;var Zt=Object.prototype.hasOwnProperty;var Xt=(e,t)=>{for(var n in t)We(e,n,{get:t[n],enumerable:!0})},Qt=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Jt(t))!Zt.call(e,r)&&r!==n&&We(e,r,{get:()=>t[r],enumerable:!(i=Wt(t,r))||i.enumerable});return e};var en=e=>Qt(We({},"__esModule",{value:!0}),e);var Xn={};Xt(Xn,{ANALYSIS_IR_SCHEMA_VERSION:()=>He,ARK_ANALYSIS_RESULT_SCHEMA:()=>It,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>bt,ARK_CONFIG_SCHEMA:()=>Te,ARK_CONFIG_SCHEMA_VERSION:()=>$t,ARK_DESIGN_DELTA_SCHEMA_VERSION:()=>Yt,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION:()=>Kt,POLICY_DELTA_SCHEMA_VERSION:()=>Ge,RESOLVED_CANDIDATE_FACTS_SCHEMA:()=>Me,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION:()=>B,analyzeArchitectureConvergence:()=>X,analyzeChange:()=>xe,analyzePolicyDelta:()=>ut,analyzeProject:()=>pe,analyzeResolvedProject:()=>fe,classifyArkPolicyDelta:()=>Ue,collectAnalysisConfigWarnings:()=>ke,collectForbiddenCapabilityUses:()=>J,createAICodeGate:()=>ct,createAdapterResult:()=>Ct,createArchitectureProfile:()=>Ee,createArchitectureProfileFromArkConfig:()=>pt,createElevenLayerArkConfig:()=>ft,createResolvedCandidateFacts:()=>Fe,detectArchitectureCycles:()=>ze,deterministicHash:()=>S,elevenLayerProfile:()=>Ie,evaluateArchitectureGraph:()=>te,explainViolation:()=>yt,extractSemanticDependencies:()=>W,loadArkConfigContract:()=>Ce,loadContract:()=>Se,loadResolvedCandidateFacts:()=>H,parseArkConfigJson:()=>Ne,policyDeltaAcknowledgementMatches:()=>Be,preflightChange:()=>mt,preflightResolvedChange:()=>gt,resolvedFactsEvidenceRequirementsHash:()=>ce,stableSerialize:()=>E,toAdapterDiagnostic:()=>Pe,version:()=>ht});module.exports=en(Xn);var ht="3.8.1";var bt="1.3";function I(e){return typeof e=="string"&&e.length>0?e:void 0}function At(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function tn(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 Pe(e,t="error"){let n=I(e.ruleId)??I(e.code)??"ARK_UNKNOWN",i=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:i,message:I(e.message)??n,location:{file:I(e.file)??"<unknown>",line:At(e.line,1),column:At(e.column,1)},evidence:r,nextAction:I(e.nextAction)??tn(n,r,e)}}function Ct(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 i=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 s=[...(e.violations??[]).map(c=>Pe(c,"error")),...(e.warnings??[]).map(c=>Pe(c,"warning"))],a={schemaVersion:"1.3",completenessReasons:i,diagnostics:s};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 It={$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 Ze=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),Qe=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),et=Object.freeze(Object.keys(Qe).sort()),Je=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"}),Xe=Object.freeze({process:Object.freeze(["process","node:process"])});function ye(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=Je[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let i=e.slice(0,n),r=Je[i];if(r)return r;let s=e.indexOf("/",n+1);return s<0?null:Je[e.slice(0,s)]??null}function j(e,t){for(let n of t)if(Xe[n]?.includes(e))return n;return null}function Oe(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let i=t.slice(0,n).join("."),r=Qe[i];if(r)return r}return null}function ne(e){if(e?.pure===!0)return[...Ze].sort();let n=(e?.capabilities?.deny??[]).filter(i=>Ze.includes(i));return[...new Set(n)].sort()}function me(e,t){if(t.length===0)return!1;let n=new Set(t),i=e.split(".");for(let r=i.length;r>=1;r-=1)if(n.has(i.slice(0,r).join(".")))return!0;return!1}function Le(e){let t=new Set,n=new Set,i=Object.keys(Qe);for(let r of e?.forbiddenGlobals??[]){let s=i.filter(a=>a===r||a.startsWith(`${r}.`));if(s.length===0)n.add(r);else for(let a of s)t.add(`ambient:${a}`);for(let a of Xe[r]??[])t.add(`import-exact:${a}`)}for(let r of ne(e)){if(t.add(`import:${r}`),r==="process")for(let s of Xe.process)t.add(`import-exact:${s}`);for(let s of i)Oe(s)===r&&t.add(`ambient:${s}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}var Et=new Map;function Rt(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function tt(e){let t="";for(let n=0;n<e.length;n+=1){let i=e[n];if(i==="\\"&&n+1<e.length){let r=e[n+1];if("*?{}[],".includes(r)||r==="\\"){t+="\\"+r,n+=1;continue}t+="/";continue}t+=i}return t}function nn(e){let t=0;for(let n=0;n<e.length;n+=1){let i=e[n];if(i==="\\"){n+=1;continue}if(i==="{")t+=1;else if(i==="}"&&(t-=1,t<0))return!1}return t===0}function Y(e){let t=Et.get(e);if(t)return t;let n=tt(e),i=nn(n),r="",s=0;for(let c=0;c<n.length;c+=1){let f=n[c];f==="\\"&&c+1<n.length?(r+=Rt(n[c+1]),c+=1):f==="*"?n[c+1]==="*"?n[c+2]==="/"?(r+="(?:.*/)?",c+=2):(r+=".*",c+=1):r+="[^/]*":f==="?"?r+="[^/]":f==="{"&&i?(r+="(?:",s+=1):f==="}"&&i&&s>0?(r+=")",s-=1):f===","&&i&&s>0?r+="|":r+=Rt(f)}let a=new RegExp(`^${r}$`);return Et.set(e,a),a}function nt(e){let t=tt(String(e)),i=t.split("*")[0].split("/").filter(Boolean).length,r=t.replace(/\*/g,"").length;return i*1e4+r}function G(e,t){let n=String(e).split(/[/\\]/).join("/"),i,r=-1;for(let s of t??[])if(!(s.exclude??[]).some(a=>Y(a).test(n))){for(let a of s.patterns??[])if(Y(a).test(n)){let c=nt(a);c>r&&(r=c,i=s.name)}}return i}function vt(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),i=new Set(t.map(r=>String(r).toLowerCase()));for(let r=0;r<n.length-1;r+=1)if(i.has(n[r].toLowerCase()))return`${n[r].toLowerCase()}/${n[r+1].toLowerCase()}`}function rn(e){let t=new Set;for(let n of e??[]){let r=tt(String(n)).split("/").filter(Boolean);for(let s=0;s<r.length;s+=1){let a=r[s];if((a==="**"||a==="*")&&s>0){let c=r[s-1];c&&!c.includes("*")&&!c.includes("{")&&!c.includes("}")&&t.add(c)}}}return[...t]}function sn(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(r=>typeof r=="string"&&r.length>0);let i=(n??[]).find(r=>r.name===t);return rn(i?.patterns)}function N(e,t,n,i){for(let r of e??[])if(!(r.from!==t||r.to!==n)&&r.allowed===!1){if(r.peerIsolation){let s=i?.fromPath,a=i?.toPath;if(!s||!a)return r;let c=sn(r,t,i?.layers);if(c.length===0)return r;let f=vt(s,c),A=vt(a,c);if(!f||!A||f!==A)return r;continue}if(t!==n)return r}}function re(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function kt(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function St(e,t){if(e.isImportDeclaration(t)){let i=t.importClause;if(!i)return!1;if(i.isTypeOnly)return!0;let r=i.namedBindings;return!!(r&&e.isNamedImports(r)&&r.elements.length>0&&r.elements.every(s=>s.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(i=>i.isTypeOnly))}function wt(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},i=e.createCompilerHost(n,!0);return i.getSourceFile=r=>r===t.fileName?t:void 0,i.fileExists=r=>r===t.fileName,i.readFile=r=>r===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,i).getTypeChecker()}function rt(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function it(e,t,n,i){let r=i.parent&&e.isShorthandPropertyAssignment(i.parent)&&i.parent.name===i,s;try{s=r?t.getShorthandAssignmentValueSymbol(i.parent):rt(t,i)}catch{s=void 0}return!!s?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}function W(e,t){let n,i=[],r=(a,c,f,A=!1)=>i.push({specifier:f,kind:c,line:kt(t,a),typeOnly:A,unresolved:f===void 0,node:a}),s=a=>{if(e.isImportDeclaration(a))r(a,"import",re(e,a.moduleSpecifier),St(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)r(a,"export",re(e,a.moduleSpecifier),St(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))r(a,"require",re(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"&&!it(e,n??(n=wt(e,t)),t,a.expression);(c||A)&&r(a,A?"require":"dynamic-import",re(e,a.arguments[0]))}e.forEachChild(a,s)};return s(t),i}function an(e,t){let n=[],i=t;for(;e.isPropertyAccessExpression(i)||e.isElementAccessExpression(i);){if(e.isPropertyAccessExpression(i))n.unshift(i.name.text);else{let r=re(e,i.argumentExpression);if(r===void 0)return;n.unshift(r)}i=i.expression}if(e.isIdentifier(i))return n.unshift(i.text),{root:i,segments:n}}function on(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 xt(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let i=n.length;i>=1;i-=1){let r=n.slice(0,i).join(".");if(e.has(r))return r}}function J(e,t,n){if(n.length===0)return[];let i=new Set(n),r=wt(e,t),s=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=an(e,o);if(!l)return;let p=rt(r,l.root),d=p?s.get(p):void 0;return d?[...d,...l.segments.slice(1)]:it(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=rt(r,l.name);!p||!d||s.set(d,p)}let f=[],A=new Set,g=(o,l)=>{let p=kt(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?xt(i,p):void 0;d&&g(d,o)}else e.isIdentifier(o)&&i.has(o.text)&&on(e,o)&&!it(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?re(e,d.propertyName)??d.propertyName.text:d.name.text,h=xt(i,[...p,y]);h&&g(h,o.initializer)}}e.forEachChild(o,u)};return u(t),f}function st(e,t,n){let i=[];for(let r of n?.dependencies??W(e,t)){if(r.typeOnly||!r.specifier)continue;let s=ye(r.specifier);s&&i.push({capability:s,symbol:r.specifier,line:r.line,source:"import-based"})}for(let r of n?.ambientUses??J(e,t,et)){let s=Oe(r.name);s&&i.push({capability:s,symbol:r.name,line:r.line,source:"ambient-global"})}return i.sort((r,s)=>r.line-s.line||r.capability.localeCompare(s.capability)||r.symbol.localeCompare(s.symbol))}var at={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."},ot=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 lt(e,t){return t.flatMap((i,r)=>(i.prefixes??i.intentPrefixes??[]).map(s=>({layer:i.name,layerIndex:r,prefix:s.endsWith(".")?s:`${s}.`}))).filter(({prefix:i})=>e.startsWith(i)).sort((i,r)=>r.prefix.length-i.prefix.length||i.layerIndex-r.layerIndex)[0]?.layer}function Z(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function ge(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&Z(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:at.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:at.PUBLISH_MISSING_SOURCE}),t}function v(e,t,n){return{ruleId:e,code:e,message:t,...n}}function ie(e,t){return e.slice(0,t).split(`
|
|
2
|
+
`).length}function ln(e){let t=[],n=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,i;for(;(i=n.exec(e))!==null;)t.push({value:i[1],index:i.index});return t}function cn(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 i of n){let r;for(;(r=i.re.exec(e))!==null;){let s=r.index+r[0].indexOf(r[1]),a=r[0],c=i.kind==="import"&&/\bimport\s+type\b/.test(a)||i.kind==="export"&&/\bexport\s+type\b/.test(a);t.push({value:r[1],index:s,kind:i.kind,typeOnly:c})}}return t.sort((i,r)=>i.index-r.index)}function dn(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),i=[],r=s=>{e.isStringLiteralLike(s)&&i.push({value:s.text,index:s.getStart(n)}),e.forEachChild(s,r)};return r(n),i}function pn(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 fn(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}function un(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}function Ae(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function yn(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}function Pt(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(i=>!e.isPropertyAssignment(i)&&!e.isShorthandPropertyAssignment(i)?!1:yn(e,i.name)===n)}function be(e,t,n){return Pt(e,t,n)!==void 0}function he(e,t,n){let i=Pt(e,t,n);return i&&e.isPropertyAssignment(i)?i.initializer:void 0}function mn(e,t){let n=he(e,t,"metadata");return be(e,n,"source")}function Ot(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?Ot(e,t.name):!1:!1}function gn(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 hn(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],i=Ae(e,n);return i!==void 0&&Z(i)||be(e,n,"intent")||Ot(e,n)}function An(e,t){if(!e.isCallExpression(t))return!1;let[n,i,r]=t.arguments;return mn(e,n)||be(e,i,"source")||be(e,r,"source")}function bn(e,t){if(!e.isCallExpression(t))return;let[n,i,r]=t.arguments,s=he(e,n,"metadata");return Ae(e,he(e,s,"source"))??Ae(e,he(e,i,"source"))??Ae(e,he(e,r,"source"))}function Cn(e,t,n,i){let r=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),s=n,a=s?.filePath,c=s?.layer,f=[],A=u=>r.getLineAndCharacterOfPosition(u.getStart(r)).line+1,g=u=>{if(gn(e,u)){let o=u.arguments[0],l=Ae(e,o);for(let d of ge({publishCall:!0,rawIntentName:l,objectHasIntent:be(e,o,"intent"),arkPublishCandidate:hn(e,u),hasSource:An(e,u)}))f.push(v(d.ruleId,d.message,{line:A(u),filePath:a}));let p=bn(e,u);if(i&&c&&p&&Z(p)){let d=i.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 ct(e={}){let t=new Set((e.intents||[]).map(s=>typeof s=="string"?s:s.name)),n=e.forbiddenPatterns||[],i=new Set(e.infrastructureLayers??[]),r=e.enforceIntentAllowlist??t.size>0;return{validate(s,a){let c=[],f=a,A=f?.filePath,g=f?.layer,u=e.typescript,o=u?u.createSourceFile(A??"generated.ts",s,u.ScriptTarget.Latest,!0):void 0,l=o?W(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})):cn(s),d=e.typescript?dn(e.typescript,s):ln(s);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&&(i.has(g)||un(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(s);m.lastIndex=0,b&&c.push(v("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${m}`,{line:b.index===void 0?void 0:ie(s,b.index),filePath:A,suggestion:"Remove infrastructure imports from domain/application layers."+h}))}else s.includes(m)&&c.push(v("FORBIDDEN_SUBSTRING",`Forbidden substring: ${m}`,{line:ie(s,s.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,ue=b?.layer;if(ue&&g){let we=N(e.architectureProfile?.rules,g,ue,{fromPath:C?.relPath,toPath:b?.relPath,layers:e.architectureLayers});if(we){if(m.typeOnly&&!we.peerIsolation)continue;let Ye=!!we.peerIsolation;c.push(v("LAYER_IMPORT_VIOLATION",we.message??(Ye?`Layer "${g}" must not import across slices into "${ue}".`:`Layer "${g}" must not import "${ue}".`),{line:ie(s,m.index),source:m.value,target:m.value,filePath:A,fromLayer:g,toLayer:ue,suggestion:Ye?"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:Ye,...m.typeOnly?{typeOnly:!0}:{}}}));continue}continue}y||m.typeOnly||!pn(m.value)&&!fn(m.value)||c.push(v("FORBIDDEN_IMPORT",`Forbidden ${m.kind} target: "${m.value}".`,{line:ie(s,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:s,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)Z(m.value)&&!t.has(m.value)&&c.push(v("UNKNOWN_INTENT",`Unknown intent reference: "${m.value}"`,{line:ie(s,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(!Z(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:ie(s,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(s,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(...J(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=j(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 st(e.typescript,o))m.has(C.capability)&&(C.source==="ambient-global"&&me(C.symbol,b)||C.source==="import-based"&&j(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(...Cn(e.typescript,s,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 $t="1.0",_e="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",Lt=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],In=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function En(){let e=[];for(let t of Lt)for(let n of Lt)t===n||In.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var De=En();var U={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Te={$schema:"https://json-schema.org/draft/2020-12/schema",$id:_e,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:_e,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:{...U,minItems:1,default:["src"]},exclude:{...U,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:De,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...U,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:{...U,minItems:1},exclude:U,intentPrefixes:U,description:{type:"string",minLength:1},forbiddenGlobals:U,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:{...U,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}}}}},ae=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
|
|
3
|
+
${n.map(i=>`- ${i.path}: ${i.message}`).join(`
|
|
4
|
+
`)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function _t(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function dt(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function se(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Rn(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function $e(e,t,n,i,r){if(t.$ref){let s=Rn(t.$ref,i);if(!s){r.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}$e(e,s,n,i,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(s=>Object.is(s,e))){r.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!_t(e)){r.push({path:n,message:`must be an object; received ${se(e)}`});return}let s=t.properties??{};for(let a of t.required??[])e[a]===void 0&&r.push({path:dt(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in s||r.push({path:dt(n,a),message:"unknown field"});for(let[a,c]of Object.entries(s))e[a]!==void 0&&$e(e[a],c,dt(n,a),i,r);return}if(t.type==="array"){if(!Array.isArray(e)){r.push({path:n,message:`must be an array; received ${se(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 s=e.map(a=>JSON.stringify(a));new Set(s).size!==s.length&&r.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((s,a)=>$e(s,t.items,`${n}[${a}]`,i,r));return}if(t.type==="string"){if(typeof e!="string"){r.push({path:n,message:`must be a string; received ${se(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 ${se(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){r.push({path:n,message:`must be an integer; received ${se(e)}`});return}t.minimum!==void 0&&e<t.minimum&&r.push({path:n,message:`must be at least ${t.minimum}`})}}function vn(e){return{...e,$schema:e.$schema===void 0?_e: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?De.map(t=>({...t})):e.rules}}function Sn(e,t="ark.config.json"){if(!_t(e))throw new ae(t,[{path:"$",message:`must be an object; received ${se(e)}`}]);let n=e.schemaVersion===void 0?"unversioned":null;if(e.schemaVersion!==void 0&&e.schemaVersion!=="1.0")throw new ae(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.0`}]);return{candidate:vn(e),migratedFrom:n}}function Ce(e,t="ark.config.json"){let{candidate:n,migratedFrom:i}=Sn(e,t),r=[];if($e(n,Te,"$",Te,r),r.length>0)throw new ae(t,r);return{config:n,migratedFrom:i}}function Ne(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(i){throw new ae(t,[{path:"$",message:`invalid JSON: ${i instanceof Error?i.message:String(i)}`}])}return Ce(n,t)}function Tt(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:_e,schemaVersion:"1.0"};for(let[n,i]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=i);return t}function xn(e){return e.endsWith(".")?e:`${e}.`}function kn(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 Ee(e){let t=e.layers.map(r=>({...r,prefixes:r.prefixes.map(xn)})),n=[...t].sort(kn),i=[...e.rules??[]];return{name:e.name,layers:t,rules:i,resolveLayer(r){return t.find(s=>s.match?.(r))?.name??n.find(s=>s.prefixes.some(a=>r.startsWith(a)))?.name}}}function pt(e,t={}){return Ee({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,i)=>({name:n.name,prefixes:n.intentPrefixes??[],description:n.description,order:i+1})),rules:e.rules??[]})}var wn=[{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}],Ie=Ee({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:wn,rules:De.map(e=>({...e}))}),Pn={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 ft(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,i=t==="."?"":`${t}/`;return Tt({include:e.include??[t],layers:Ie.layers.map(r=>({name:r.name,patterns:(Pn[r.name]??[r.name]).map(s=>`${i}${s}/**`),intentPrefixes:r.prefixes,optional:n})),rules:[...Ie.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 B="1.0",Dt=["network","filesystem","clock","randomness","environment","process","persistence"];function K(e,t){let n=E(e),i=E(t);return n<i?-1:n>i?1:0}function T(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}function ce(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(K),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 On(e){let t=e.completenessReasons.map(u=>({code:u.code,message:u.message,...u.file?{file:u.file}:{}})).sort(K),n=e.files.map(u=>({...u,typeOnlyExportNames:T(u.typeOnlyExportNames)})).sort((u,o)=>u.path<o.path?-1:u.path>o.path?1:0),i=e.dependencies.map(u=>({...u,...u.namedBindings?{namedBindings:T(u.namedBindings)}:{}})).sort(K),r=e.capabilityUses.map(u=>({...u})).sort(K),s=e.ambientUses.map(u=>({...u})).sort(K),a=e.publishCalls.map(u=>({...u})).sort(K),c=e.intentReferences.map(u=>({...u})).sort(K),f=e.safetyUses.map(u=>({...u})).sort(K),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:i,capabilityUses:r,ambientUses:s,publishCalls:a,intentReferences:c,safetyUses:f}}function Ft(e){let t=On(e);return{...t,factsHash:S(E(t))}}function Fe(e){return Ft(Ht(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 i=new Set(t),r=Object.keys(e).find(s=>!i.has(s));if(r)throw new Error(`${n}.${r} is not part of schema 1.0.`)}function k(e,t,n){let i=e[t];if(typeof i!="string"||i.length===0)throw new Error(`${n}.${t} must be a non-empty string.`);return i}function oe(e,t,n){if(e[t]!==void 0)return k(e,t,n)}function M(e,t,n){let i=k(e,t,n),r=i.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 s=[];for(let c of r.split("/"))if(!(!c||c==="."))if(c===".."){if(s.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);s.pop()}else s.push(c);let a=s.join("/");if(!a||a!==i)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 Mt(e,t,n){let i=e[t];if(!Number.isInteger(i)||Number(i)<0)throw new Error(`${n}.${t} must be a non-negative integer.`);return Number(i)}function le(e,t,n){let i=Mt(e,t,n);if(i===0)throw new Error(`${n}.${t} must be a positive integer.`);return i}function q(e,t,n){let i=e[t];if(!Array.isArray(i))throw new Error(`${n}.${t} must be an array.`);return i}function z(e,t,n,i){let r=e[t];if(typeof r!="string"||!n.includes(r))throw new Error(`${i}.${t} must be one of ${n.join(", ")}.`);return r}function Nt(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 Ln(e,t,n){let i=new Set;for(let r of e){let s=t(r);if(i.has(s))throw new Error(`${n} must not contain duplicate facts (${s}).`);i.add(s)}}function Ht(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=z(e,"schemaVersion",["1.0"],"$"),i=z(e,"completeness",["complete","partial","unavailable"],"$"),r=q(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(i==="complete"&&r.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(i!=="complete"&&r.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let s=q(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:z(h,"parseStatus",["parsed","invalid"],y),parseDiagnosticCount:Mt(h,"parseDiagnosticCount",y),exportsOnlyTypes:_(h,"exportsOnlyTypes",y),typeOnlyExportNames:Nt(h.typeOnlyExportNames,`${y}.typeOnlyExportNames`),hasTopLevelSideEffects:_(h,"hasTopLevelSideEffects",y)}}),a=q(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=oe(h,"specifier",y),b=oe(h,"target",y),C=z(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:z(h,"kind",["import","export","dynamic-import","require"],y),typeOnly:_(h,"typeOnly",y),line:le(h,"line",y),resolution:C,...b?{target:M(h,"target",y)}:{},...h.namedBindings!==void 0?{namedBindings:Nt(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=q(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:le(h,"line",y),symbol:k(h,"symbol",y),capability:z(h,"capability",Dt,y),source:z(h,"source",["ambient-global","import-based"],y)}}),f=q(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:le(h,"line",y),symbol:k(h,"symbol",y)}}),A=q(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=oe(h,"rawIntentName",y),b=oe(h,"sourceIntent",y);return{file:M(h,"file",y),line:le(h,"line",y),...m?{rawIntentName:m}:{},objectHasIntent:_(h,"objectHasIntent",y),arkPublishCandidate:_(h,"arkPublishCandidate",y),hasSource:_(h,"hasSource",y),...b?{sourceIntent:b}:{}}}),g=q(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:le(h,"line",y),intent:k(h,"intent",y)}}),u=q(e,"safetyUses","$").map((p,d)=>{let y=`$.safetyUses[${d}]`,h=D(p,y);F(h,["file","line","kind","symbol"],y);let m=oe(h,"symbol",y),b=z(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:le(h,"line",y),kind:b,...m?{symbol:m}:{}}});Ln(s,p=>p.path,"$.files");let o=new Set(s.map(p=>p.path));for(let p of s){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(i==="complete"&&s.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=oe(e,"projectPackageName","$");return{schemaVersion:n,completeness:i,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:s,dependencies:a,capabilityUses:c,ambientUses:f,publishCalls:A,intentReferences:g,safetyUses:u}}function H(e){let t=D(e,"$"),n=k(t,"factsHash","$"),i=k(t,"candidateTreeHash","$"),r=Ft(Ht(t,!0));if(r.factsHash!==n)throw new Error(`$.factsHash does not match the canonical payload (${r.factsHash}).`);if(i!==r.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${r.candidateTreeHash}).`);return r}var $n=["network","filesystem","clock","randomness","environment","process","persistence"],R={type:"string",minLength:1},de={type:"integer",minimum:1},V={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},Me={$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:V}}},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:V,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:V,specifier:R,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:de,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:V,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:V,line:de,symbol:R,capability:{enum:$n},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:V,line:de,symbol:R}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:V,line:de,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:V,line:de,intent:R}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:V,line:de,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 He="1.0";function P(e){return`${e.from}->${e.to}`}function Re(e,t,n,i="dependency"){return{id:`${e}:${i}:${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:i==="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 X(e){let t=[],n=new Map(e.changeMap.map.files.map(o=>[o.path,o])),i=new Map(e.changes.map(o=>[o.path,o])),r=new Map(e.changeMap.map.dependencies.map(o=>[P(o),o])),s=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=i.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[...i.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(Re("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(Re("contradictory",o,`${o.from} -> ${o.to} was planned, but the candidate contains the reverse edge.`))):t.push(Re("missing",o,`${o.from} -> ${o.to} is absent from the candidate architecture.`))}let f=new Set([...n.keys(),...i.keys()]);for(let[o,l]of[...a].sort(([p],[d])=>p.localeCompare(d)))s.has(o)||r.has(o)||c.has(o)||!f.has(l.from)&&!f.has(l.to)||t.push({...Re("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[...s].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({...Re("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 Ge="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 Q(e,t,n,i,r){let s=L(n),a=L(i),c=new Set(s),f=new Set(a),A=a.filter(u=>!c.has(u)),g=s.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:s,after:a}),g.length>0&&x(e,{kind:"removed",path:t,classification:r.removed,message:r.removedMessage,before:s,after:a}))}function Ve(e,t,n,i,r,s,a){if(n===i)return;x(e,{kind:i?"enabled":"disabled",path:t,classification:i?r:r==="strengthening"?"weakening":"strengthening",message:i?s:a,before:n,after:i})}function je(e,t){let n=new Map,i=new Set;for(let r of e){let s=t(r);n.has(s)?i.add(s):n.set(s,r)}return{values:n,duplicates:[...i].sort()}}function _n(e,t,n){let i=je(t,s=>s.name),r=je(n,s=>s.name);(i.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:i.duplicates,after:r.duplicates});for(let s of[...new Set([...i.values.keys(),...r.values.keys()])].sort()){let a=i.values.get(s),c=r.values.get(s),f=`$.layers[${s}]`;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;Q(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."}),Q(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=Le(a),g=Le(c);Q(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."}),Q(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)}),Ve(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."),Ve(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 Tn(e,t,n){let i=a=>`${a.from}->${a.to}`,r=je(t,i),s=je(n,i);(r.duplicates.length>0||s.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:s.duplicates});for(let a of[...new Set([...r.values.keys(),...s.values.keys()])].sort()){let c=r.values.get(a),f=s.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 Dn(e,t,n){let i=t.safety??{},r=n.safety??{};for(let s of["maxTsSuppressions","maxAnyCasts"]){let a=i[s]??0,c=r[s]??0;a!==c&&x(e,{kind:c>a?"threshold-raised":"threshold-lowered",path:`$.safety.${s}`,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 s of["allowInMemory","allowDisabledPeerIsolation"])Ve(e,`$.safety.${s}`,i[s]===!0,r[s]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}function Nn(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 Ue(e,t){let n=[];Q(n,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),Q(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."}),Q(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."}),Ve(n,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let i={off:0,soft:1,"framework-soft":1,strict:2},r=e.cyclePolicy??"strict",s=t.cyclePolicy??"strict";if(r!==s){let a=i[s]===i[r]?"judgment-required":i[s]>i[r]?"strengthening":"weakening";x(n,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:a,message:"The cycle enforcement level changed.",before:r,after:s})}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}),_n(n,e.layers,t.layers),Tn(n,e.rules,t.rules),Dn(n,e,t),n.sort((a,c)=>a.path.localeCompare(c.path)||a.id.localeCompare(c.id)),{schemaVersion:Ge,classification:Nn(n),findings:n}}function Be(e,t){if(!e||e.schemaVersion!==Ge||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),i=L(t.findingIds);return n.length===i.length&&n.every((r,s)=>r===i[s])}function ee(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 Vt(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}function qe(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 ve(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let i=t,r="";for(t+=1;t<e.length;t+=1){let s=e[t];if(s===n)return{value:r,offset:i,excerpt:e.slice(i,t+1)};s==="\\"&&t+1<e.length?(r+=e[t+1],t+=1):r+=s}}function $(e,t,n){return e.startsWith(t,n)&&!qe(e[n-1])&&!qe(e[n+t.length])}function jt(e,t){let n=O(e,t);if(e[n]!=="{")return!1;n+=1;let i=!1;for(;n<e.length;){if(n=O(e,n),e[n]==="}")return i;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)||!Vt(e[r]))return!1;for(n=r;n<e.length&&qe(e[n]);)n+=1;if(n=O(e,n),$(e,"as",n)){if(n=O(e,n+2),!Vt(e[n]))return!1;for(;n<e.length&&qe(e[n]);)n+=1}i=!0}return!1}function Fn(e,t){if(t=O(e,t+6),e[t]==="(")return ve(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 jt(e,t)&&(n=!0);let i=Gt(e,t,!0);return i&&n?{...i,typeOnly:!0}:i}function Mn(e,t){t=t+6;let n=O(e,t),i=!1;if($(e,"type",n)){let s=O(e,n+4);(e[s]==="{"||e[s]==="*")&&(i=!0)}else jt(e,n)&&(i=!0);let r=Gt(e,t,!1);return r&&i?{...r,typeOnly:!0}:r}function Gt(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if($(e,"from",t))return ve(e,O(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return ve(e,t);if(t>0&&($(e,"import",t)||$(e,"export",t)))return}}function Hn(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 Vn(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let i=O(e,t+7);if(e[i]!=="(")return;i=O(e,i+1);let r=ve(e,i);return r?{...r,requireCall:!0}:void 0}function jn(e){let t=[];for(let n=0;n<e.length;n+=1){let i=e[n];if(i==="/"&&e[n+1]==="/"){if(n=e.indexOf(`
|
|
5
|
+
`,n+2),n<0)break;continue}if(i==="/"&&e[n+1]==="*"){let s=e.indexOf("*/",n+2);if(s<0)break;n=s+1;continue}if(i==="`"){n=Hn(e,n);continue}if(i==="'"||i==='"'){let s=ve(e,n);s&&(n=s.offset+s.excerpt.length-1);continue}let r=i==="i"&&$(e,"import",n)?Fn(e,n):i==="e"&&$(e,"export",n)?Mn(e,n):i==="r"&&$(e,"require",n)?Vn(e,n):void 0;r&&(t.push(r),n=r.offset+r.excerpt.length-1)}return t}function Ut(e,t){let n=[],i=[];for(let r of jn(e.content)){let s=r.value;if(!s.startsWith(".")){if(r.typeOnly)continue;let A=ye(s);if(!A)continue;let g=e.content.slice(0,r.offset).split(`
|
|
6
|
+
`).length;i.push({file:e.path,symbol:s,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=Gn(e.path,s,t);n.push({from:e.path,specifier:s,to:f?.path??null,resolution:f?"resolved":"unresolved",fromLayer:e.layer,toLayer:f?.layer??null,evidence:c})}return{edges:n,capabilityUses:i}}function Gn(e,t,n){let i=e.split("/");i.pop();for(let s of t.split("/"))s==="."||s===""||(s===".."?i.pop():i.push(s));let r=i.join("/");for(let s of[r,`${r}.ts`,`${r}.tsx`,`${r}.mts`,`${r}.cts`,`${r}/index.ts`,`${r}/index.tsx`]){let a=n.get(s);if(a)return a}}function Bt(e,t){let n=[];for(let i of e){if(!i.to||!i.fromLayer||!i.toLayer)continue;let r=N(t.rules,i.fromLayer,i.toLayer,{fromPath:i.from,toPath:i.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:i,evidence:i.evidence})}return n}var Un={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 Se(e,t){let n=typeof e=="string"?Ne(e,t):Ce(e,t);return{...n,policyHash:S(E(n.config))}}function ut(e){let t=Se(e.baseConfig,e.baseSource??"base ark.config.json"),n=Se(e.candidateConfig,e.candidateSource??"candidate ark.config.json"),i=Ue(t.config,n.config),r=i.findings.filter(c=>c.classification==="weakening"||c.classification==="judgment-required").map(c=>c.id).sort(),s=r.length>0,a=s&&Be(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:r});return{schemaVersion:i.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:i.classification,findings:i.findings,blockingFindingIds:r,requiresAcknowledgement:s,acknowledged:a,valid:!s||a}}function pe(e){let t=e.files.map(u=>{let o=ee(u.path);return{path:o,content:u.content,contentHash:S(u.content),layer:G(o,e.contract.config.layers)??null}}).sort((u,o)=>u.path.localeCompare(o.path)),n=new Map(t.map(u=>[u.path,u])),i=[],r=[];for(let u of t){let o=Ut(u,n);i.push(...o.edges),r.push(...o.capabilityUses)}let s=Bt(i,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(ne(u))]));for(let u of r){let o=n.get(u.file)?.layer;if(!o)continue;let l=a.get(o),p=j(u.symbol,l?.forbiddenGlobals??[]);if(p){s.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)&&s.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"?[]:[{...Un}],g={schemaVersion:He,policyHash:e.contract.policyHash,compilerOptionsHash:S(E(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(u=>u.name),edges:i,capabilityUses:r,violations:s};return{mode:"lexical-compatibility",completeness:f,completenessReasons:A,valid:f==="complete"&&s.length===0,ir:g}}function xe(e){let t=new Map(e.files.map(n=>[ee(n.path),n]));for(let n of e.changes){let i=ee(n.path);"delete"in n&&n.delete?t.delete(i):"content"in n&&t.set(i,{path:i,content:n.content})}return pe({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}function yt(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 ze(e){let t=0,n=new Map,i=new Map,r=new Set,s=[],a=[],c=f=>{n.set(f,t),i.set(f,t),t+=1,s.push(f),r.add(f);for(let u of[...e.get(f)??[]].sort())e.has(u)&&(n.has(u)?r.has(u)&&i.set(f,Math.min(i.get(f)??0,n.get(u)??0)):(c(u),i.set(f,Math.min(i.get(f)??0,i.get(u)??0))));if(i.get(f)!==n.get(f))return;let A=[],g;do{if(g=s.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 te(e){let t=e.contentViolations.map(s=>({...s})),n=(e.warnings??[]).map(s=>({...s})),i=new Map(e.files.map(s=>[s,new Set]));for(let s of e.edges){if(s.to&&s.to!==s.from&&!s.typeOnly&&i.has(s.from)&&i.get(s.from)?.add(s.to),!s.to||!s.fromLayer||!s.toLayer)continue;let a=N(e.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:e.config.layers});if(!a)continue;let c=!!a.peerIsolation;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:s.from,line:s.line,fromLayer:s.fromLayer,toLayer:s.toLayer,target:s.to,...s.typeOnly?{typeOnly:!0}:{},...s.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...s.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...s.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!c&&s.portProofEligible?{portProofEligible:!0}:{},...s.kind?{edgeKind:s.kind}:{},...c?{peerIsolation:!0}:{},message:a.message??(c?`${s.fromLayer} must not ${s.kind} another slice of ${s.toLayer} (${s.from} \u2192 ${s.to}). Extract shared code or use events/ports across slices.`:`${s.fromLayer} must not ${s.kind} ${s.toLayer}.`)})}let r=String(e.config.cyclePolicy??"strict").toLowerCase();if(r!=="off"){let s=ze(i);r==="soft"||r==="framework-soft"?n.push(...s.map(a=>({...a,message:`${a.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...s)}return{violations:t,warnings:n,safety:e.safety}}function w(e,t,n={}){return{ruleId:e,message:t,...n}}function ke(e){let{config:t,rules:n,files:i,manifest:r}=e,s=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(l=>typeof l!="string"))&&s.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)))s.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)&&s.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&&s.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){s.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"))&&s.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){s.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=Y(d)}catch(h){s.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}!i.some(h=>y.test(h))&&!l.optional&&s.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)s.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)&&s.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)&&s.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 i){let p=-1,d=[];for(let y of a)for(let h of y.patterns??[]){if(!Y(h).test(l))continue;let m=nt(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&&s.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=i.filter(l=>!G(l,a));return o.length>0&&s.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)})),s}function Bn(e,t){return t.some(n=>{try{return Y(n).test(e)}catch{return!1}})}function qn(e,t){let n=e.contract.config.safety??{},i=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,r=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,s=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")&&!Bn(d.file,s)).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:i,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>i){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 (${i}).`})}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 zn(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,i)=>i.length-n.length)[0]}function qt(e,t){let n=t.config.layers.filter(i=>(i.intentPrefixes??[]).length>0);return lt(e,n.length>0?n:ot.map(i=>({name:i.layer,prefixes:i.prefixes})))}function Kn(e,t,n){let i=[],r=new Map(e.contract.config.layers.map(s=>[s.name,s]));for(let s of t.ambientUses){let a=n.get(s.file);!a||!zn(s.symbol,r.get(a)?.forbiddenGlobals??[])||i.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:a,target:s.symbol,message:`${a} must not use the ambient global "${s.symbol}".`})}for(let s of t.capabilityUses){let a=n.get(s.file);if(!a)continue;let c=r.get(a),f=c?.forbiddenGlobals??[],A=s.source==="import-based"?t.dependencies.find(g=>g.from===s.file&&g.line===s.line&&g.specifier===s.symbol&&!g.typeOnly)?.kind:void 0;if(!(s.source==="ambient-global"&&me(s.symbol,f))){if(s.source==="import-based"){let g=j(s.symbol,f);if(g){i.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:a,target:s.symbol,...A?{edgeKind:A}:{},message:`${a} must not use module "${s.symbol}" because it is the import form of forbidden global "${g}".`});continue}}ne(c).includes(s.capability)&&i.push({ruleId:"CAPABILITY_VIOLATION",file:s.file,line:s.line,fromLayer:a,target:s.symbol,capability:s.capability,...A?{edgeKind:A}:{},message:s.source==="import-based"?`${a} denies the ${s.capability} capability; found import of "${s.symbol}".`:`${a} denies the ${s.capability} capability; found ambient "${s.symbol}".`})}}for(let s of t.publishCalls){let a=n.get(s.file);if(!a)continue;for(let f of ge({publishCall:!0,rawIntentName:s.rawIntentName,objectHasIntent:s.objectHasIntent,arkPublishCandidate:s.arkPublishCandidate,hasSource:s.hasSource}))i.push({ruleId:f.ruleId,file:s.file,line:s.line,...f.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:a}:{},message:f.message});if(!s.sourceIntent)continue;let c=qt(s.sourceIntent,e.contract);!c||c===a||i.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:s.file,line:s.line,fromLayer:a,toLayer:c,target:s.sourceIntent,message:`Publish source "${s.sourceIntent}" resolves to ${c}, but the publishing file is classified as ${a}.`})}for(let s of t.intentReferences){let a=n.get(s.file);if(!a)continue;let c=qt(s.intent,e.contract);if(!c)continue;let f=N(e.contract.config.rules,a,c);f&&i.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:s.file,line:s.line,fromLayer:a,toLayer:c,target:s.intent,message:f.message??`${a} must not reference ${c} intent ${s.intent}.`})}return i}function Yn(e){let{facts:t}=e,n=ce(e.contract.config),i=t.evidenceRequirementsHash===n,r=i?t.completeness:"unavailable",s=i?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:G(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)??G(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=ke({config:e.contract.config,rules:e.contract.config.rules,files:a.map(p=>p.path)}),g=qn(e,t),u=te({config:e.contract.config,rules:e.contract.config.rules,files:a.filter(p=>p.layer).map(p=>p.path),contentViolations:Kn(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:s,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 fe(e){return Yn({contract:e.contract,facts:H(e.facts)})}function Ke(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 zt(e){return S(E(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}function mt(e){let t=pe(e),n=new Map(t.ir.files.map(l=>[l.path,l])),i=[],r=new Set,s=[];for(let l of e.changes){let p=l.path.replace(/\\/g,"/"),d=ee(l.path);if(!d||d===".."||d.startsWith("../")||p.startsWith("/")||/^[A-Za-z]:\//.test(p)||p.includes("\0")){s.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(r.has(d)){s.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)&&s.push({ruleId:"DELETE_TARGET_MISSING",file:d,line:1,message:`Cannot delete ${d} because it is not present in the supplied base tree.`}),i.push("delete"in l&&l.delete?{path:d,delete:!0}:{path:d,content:"content"in l?l.content:""})}e.changes.length===0&&s.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let a=xe({...e,changes:i}),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=te({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=i.map(l=>{let p=ee(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=[...s,...A.violations].map(l=>({...l,nextAction:Ke(l)})),o=e.changeMap?X({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:zt(t.ir.files),candidateTreeHash:zt(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 Wn(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 i=n.join("/");return i&&i===t?i: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(([,i,r])=>i!==r).map(([i,r,s])=>({ruleId:"FACTS_IDENTITY_MISMATCH",file:"<change-set>",line:1,field:i,before:r,candidate:s,message:`Base and candidate facts must use the same ${i}.`}))}function Zn(e,t,n,i){let r=n.get(t),s=i.get(t);return{path:t,operation:"delete"in e&&e.delete?"delete":r?"update":"create",...r?{beforeContentHash:r.contentHash}:{},...s?{candidateContentHash:s.contentHash}:{}}}function gt(e){let t=H(e.baseFacts),n=H(e.candidateFacts),i=fe({contract:e.contract,facts:t}),r=fe({contract:e.contract,facts:n}),s=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=Wn(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=s.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(Zn(o,l,s,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([...s.keys(),...a.keys()])){if(f.has(o))continue;let l=s.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?X({changeMap:e.changeMap,changes:A,baseDependencies:i.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:Ke(o)}));return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:i.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:i.completeness,candidateCompleteness:r.completeness,baseCompletenessReasons:i.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 Kt="1.1";var Yt="1.0";0&&(module.exports={ANALYSIS_IR_SCHEMA_VERSION,ARK_ANALYSIS_RESULT_SCHEMA,ARK_ANALYSIS_RESULT_SCHEMA_VERSION,ARK_CONFIG_SCHEMA,ARK_CONFIG_SCHEMA_VERSION,ARK_DESIGN_DELTA_SCHEMA_VERSION,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION,POLICY_DELTA_SCHEMA_VERSION,RESOLVED_CANDIDATE_FACTS_SCHEMA,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,analyzeArchitectureConvergence,analyzeChange,analyzePolicyDelta,analyzeProject,analyzeResolvedProject,classifyArkPolicyDelta,collectAnalysisConfigWarnings,collectForbiddenCapabilityUses,createAICodeGate,createAdapterResult,createArchitectureProfile,createArchitectureProfileFromArkConfig,createElevenLayerArkConfig,createResolvedCandidateFacts,detectArchitectureCycles,deterministicHash,elevenLayerProfile,evaluateArchitectureGraph,explainViolation,extractSemanticDependencies,loadArkConfigContract,loadContract,loadResolvedCandidateFacts,parseArkConfigJson,policyDeltaAcknowledgementMatches,preflightChange,preflightResolvedChange,resolvedFactsEvidenceRequirementsHash,stableSerialize,toAdapterDiagnostic,version});
|