arkgate 3.2.0 → 3.4.0
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 +77 -0
- package/README.md +4 -3
- package/bin/ark-check.mjs +1 -0
- package/bin/ark-mcp.mjs +10 -0
- package/bin/lib/adapter-contract.mjs +3 -0
- package/bin/lib/ambient-state.mjs +221 -0
- package/bin/lib/analysis-engine.mjs +6 -5
- package/bin/lib/architecture-scan.mjs +31 -0
- package/bin/lib/config-contract.mjs +25 -0
- package/bin/lib/doctor-advisories.mjs +20 -0
- package/bin/lib/doctor-plan.mjs +5 -5
- package/bin/lib/remediation.mjs +14 -0
- package/bin/lib/ts-resolve.mjs +2 -1
- package/bin/lib/violations.mjs +2 -0
- package/dist/configTypes-DAPvBqK6.d.cts +61 -0
- package/dist/configTypes-DAPvBqK6.d.ts +61 -0
- package/dist/eslint/index.cjs +3 -3
- package/dist/eslint/index.d.cts +3 -2
- package/dist/eslint/index.d.ts +3 -2
- package/dist/eslint/index.js +3 -3
- package/dist/index.cjs +6 -5
- package/dist/index.d.cts +344 -82
- package/dist/index.d.ts +344 -82
- package/dist/index.js +6 -5
- package/docs/agent-guide.md +18 -0
- package/docs/configuration.md +3 -0
- package/docs/package-surface.md +5 -1
- package/package.json +4 -3
- package/schemas/ark.config.schema.json +25 -0
- package/server.json +2 -2
- package/dist/configContract-BxSIwVRo.d.cts +0 -259
- package/dist/configContract-BxSIwVRo.d.ts +0 -259
package/dist/index.cjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
"use strict";var ge=Object.defineProperty;var nt=Object.getOwnPropertyDescriptor;var rt=Object.getOwnPropertyNames;var it=Object.prototype.hasOwnProperty;var at=(e,t)=>{for(var n in t)ge(e,n,{get:t[n],enumerable:!0})},ot=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of rt(t))!it.call(e,i)&&i!==n&&ge(e,i,{get:()=>t[i],enumerable:!(r=nt(t,i))||r.enumerable});return e};var st=e=>ot(ge({},"__esModule",{value:!0}),e);var zt={};at(zt,{ANALYSIS_IR_SCHEMA_VERSION:()=>ae,ARK_ANALYSIS_RESULT_SCHEMA:()=>_e,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>$e,ARK_CONFIG_SCHEMA:()=>ne,ARK_CONFIG_SCHEMA_VERSION:()=>Be,POLICY_DELTA_SCHEMA_VERSION:()=>qe,analyzeArchitectureConvergence:()=>Y,analyzeChange:()=>Le,analyzePolicyDelta:()=>Ze,analyzeProject:()=>fe,classifyArkPolicyDelta:()=>ce,collectAnalysisConfigWarnings:()=>tt,collectForbiddenCapabilityUses:()=>V,createAICodeGate:()=>xe,createAdapterResult:()=>ve,createArchitectureProfile:()=>z,createArchitectureProfileFromArkConfig:()=>Se,createElevenLayerArkConfig:()=>ke,detectArchitectureCycles:()=>we,deterministicHash:()=>P,elevenLayerProfile:()=>K,evaluateArchitectureGraph:()=>Pe,explainViolation:()=>Xe,extractSemanticDependencies:()=>H,loadArkConfigContract:()=>B,loadContract:()=>de,parseArkConfigJson:()=>ie,policyDeltaAcknowledgementMatches:()=>le,preflightChange:()=>et,stableSerialize:()=>L,toAdapterDiagnostic:()=>Q,version:()=>Re});module.exports=st(zt);var Re="3.2.0";var $e="1.1";function E(e){return typeof e=="string"&&e.length>0?e:void 0}function Oe(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function ct(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==="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 Q(e,t="error"){let n=E(e.ruleId)??E(e.code)??"ARK_UNKNOWN",r=e.severity==="warning"?"warning":t,i={...E(e.target)?{target:E(e.target)}:{},...E(e.fromLayer)?{fromLayer:E(e.fromLayer)}:{},...E(e.toLayer)?{toLayer:E(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{}};return{ruleId:n,severity:r,message:E(e.message)??n,location:{file:E(e.file)??"<unknown>",line:Oe(e.line,1),column:Oe(e.column,1)},evidence:i,nextAction:E(e.nextAction)??ct(n,i,e)}}function ve(e){return{schemaVersion:"1.1",valid:e.valid,diagnostics:[...(e.violations??[]).map(t=>Q(t,"error")),...(e.warnings??[]).map(t=>Q(t,"warning"))]}}var _e={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@2/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","valid","diagnostics"],properties:{schemaVersion:{const:"1.1"},valid:{type:"boolean"},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"}}},nextAction:{type:"string",minLength:1}}}}}};var Ne=new Map;function Me(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function ye(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let i=e[n+1];if("*?{}[],".includes(i)||i==="\\"){t+="\\"+i,n+=1;continue}t+="/";continue}t+=r}return t}function lt(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="{")t+=1;else if(r==="}"&&(t-=1,t<0))return!1}return t===0}function F(e){let t=Ne.get(e);if(t)return t;let n=ye(e),r=lt(n),i="",a=0;for(let c=0;c<n.length;c+=1){let d=n[c];d==="\\"&&c+1<n.length?(i+=Me(n[c+1]),c+=1):d==="*"?n[c+1]==="*"?n[c+2]==="/"?(i+="(?:.*/)?",c+=2):(i+=".*",c+=1):i+="[^/]*":d==="?"?i+="[^/]":d==="{"&&r?(i+="(?:",a+=1):d==="}"&&r&&a>0?(i+=")",a-=1):d===","&&r&&a>0?i+="|":i+=Me(d)}let s=new RegExp(`^${i}$`);return Ne.set(e,s),s}function he(e){let t=ye(String(e)),r=t.split("*")[0].split("/").filter(Boolean).length,i=t.replace(/\*/g,"").length;return r*1e4+i}function X(e,t){let n=String(e).split(/[/\\]/).join("/"),r,i=-1;for(let a of t??[])if(!(a.exclude??[]).some(s=>F(s).test(n))){for(let s of a.patterns??[])if(F(s).test(n)){let c=he(s);c>i&&(i=c,r=a.name)}}return r}function De(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),r=new Set(t.map(i=>String(i).toLowerCase()));for(let i=0;i<n.length-1;i+=1)if(r.has(n[i].toLowerCase()))return`${n[i]}/${n[i+1]}`}function dt(e){let t=new Set;for(let n of e??[]){let i=ye(String(n)).split("/").filter(Boolean);for(let a=0;a<i.length;a+=1){let s=i[a];if((s==="**"||s==="*")&&a>0){let c=i[a-1];c&&!c.includes("*")&&!c.includes("{")&&!c.includes("}")&&t.add(c)}}}return[...t]}function pt(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(i=>typeof i=="string"&&i.length>0);let r=(n??[]).find(i=>i.name===t);return dt(r?.patterns)}function v(e,t,n,r){for(let i of e??[])if(!(i.from!==t||i.to!==n)&&i.allowed===!1){if(i.peerIsolation){let a=r?.fromPath,s=r?.toPath;if(!a||!s)continue;let c=pt(i,t,r?.layers);if(c.length===0)continue;let d=De(a,c),u=De(s,c);if(!d||!u)continue;if(d!==u)return i;continue}if(t!==n)return i}}var me={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."};function O(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function Ae(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&O(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:me.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:me.PUBLISH_MISSING_SOURCE}),t}function _(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function He(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function Te(e,t){if(e.isImportDeclaration(t)){let n=t.importClause;if(!n)return!1;if(n.isTypeOnly)return!0;let r=n.namedBindings;return!!(r&&e.isNamedImports(r)&&r.elements.length>0&&r.elements.every(i=>i.isTypeOnly))}if(e.isExportDeclaration(t)){if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(r=>r.isTypeOnly))}return!1}function Ve(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=i=>i===t.fileName?t:void 0,r.fileExists=i=>i===t.fileName,r.readFile=i=>i===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}function Ce(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function be(e,t,n,r){let i=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,a;try{a=i?t.getShorthandAssignmentValueSymbol(r.parent):Ce(t,r)}catch{a=void 0}return!!a?.declarations?.some(s=>s.getSourceFile().fileName===n.fileName)}function H(e,t){let n,r=[],i=(s,c,d,u=!1)=>r.push({specifier:d,kind:c,line:He(t,s),typeOnly:u,unresolved:d===void 0,node:s}),a=s=>{if(e.isImportDeclaration(s))i(s,"import",_(e,s.moduleSpecifier),Te(e,s));else if(e.isExportDeclaration(s)&&s.moduleSpecifier)i(s,"export",_(e,s.moduleSpecifier),Te(e,s));else if(e.isImportEqualsDeclaration(s)&&e.isExternalModuleReference(s.moduleReference))i(s,"require",_(e,s.moduleReference.expression));else if(e.isCallExpression(s)){let c=s.expression.kind===e.SyntaxKind.ImportKeyword,u=e.isIdentifier(s.expression)&&s.expression.text==="require"&&!be(e,n??(n=Ve(e,t)),t,s.expression);(c||u)&&i(s,u?"require":"dynamic-import",_(e,s.arguments[0]))}e.forEachChild(s,a)};return a(t),r}function ft(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let i=_(e,r.argumentExpression);if(i===void 0)return;n.unshift(i)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}function ut(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 Fe(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let r=n.length;r>=1;r-=1){let i=n.slice(0,r).join(".");if(e.has(i))return i}}function V(e,t,n){if(n.length===0)return[];let r=new Set(n),i=Ve(e,t),a=new Map,s=new Set;for(let o of t.statements)if(e.isVariableStatement(o))for(let l of o.declarationList.declarations)e.isIdentifier(l.name)&&s.add(l.name.text);let c=o=>{let l=ft(e,o);if(!l)return;let f=Ce(i,l.root),y=f?a.get(f):void 0;return y?[...y,...l.segments.slice(1)]:be(e,i,t,l.root)||s.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 f=c(l.initializer),y=Ce(i,l.name);!f||!y||a.set(y,f)}let d=[],u=new Set,g=(o,l)=>{let f=He(t,l),y=`${o}:${l.getStart(t)}`;u.has(y)||(u.add(y),d.push({name:o,line:f,node:l}))},h=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 f=c(o),y=f?Fe(r,f):void 0;y&&g(y,o)}else e.isIdentifier(o)&&r.has(o.text)&&ut(e,o)&&!be(e,i,t,o)&&g(o.text,o);if(e.isVariableDeclaration(o)&&e.isObjectBindingPattern(o.name)&&o.initializer){let f=c(o.initializer);if(f)for(let y of o.name.elements){if(!e.isIdentifier(y.name))continue;let k=y.propertyName?_(e,y.propertyName)??y.propertyName.text:y.name.text,b=Fe(r,[...f,k]);b&&g(b,o.initializer)}}e.forEachChild(o,h)};return h(t),d}function A(e,t,n){return{ruleId:e,code:e,message:t,...n}}function N(e,t){return e.slice(0,t).split(`
|
|
2
|
-
`).length}function gt(e){let t=[],n=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,r;for(;(r=n.exec(e))!==null;)t.push({value:r[1],index:r.index});return t}function yt(e){let t=[],n=[{kind:"import",re:/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s*)?['"]([^'"]+)['"]/g},{kind:"export",re:/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s*['"]([^'"]+)['"]/g},{kind:"dynamic-import",re:/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g},{kind:"require",re:/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g}];for(let r of n){let i;for(;(i=r.re.exec(e))!==null;){let a=i.index+i[0].indexOf(i[1]),s=i[0],c=r.kind==="import"&&/\bimport\s+type\b/.test(s)||r.kind==="export"&&/\bexport\s+type\b/.test(s);t.push({value:i[1],index:a,kind:r.kind,typeOnly:c})}}return t.sort((r,i)=>r.index-i.index)}function ht(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],i=a=>{e.isStringLiteralLike(a)&&r.push({value:a.text,index:a.getStart(n)}),e.forEachChild(a,i)};return i(n),r}function mt(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 At(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}function Ct(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}function G(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function bt(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}function je(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:bt(e,r.name)===n)}function U(e,t,n){return je(e,t,n)!==void 0}function j(e,t,n){let r=je(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}function xt(e,t){let n=j(e,t,"metadata");return U(e,n,"source")}function Ge(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?Ge(e,t.name):!1:!1}function It(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 St(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=G(e,n);return r!==void 0&&O(r)||U(e,n,"intent")||Ge(e,n)}function kt(e,t){if(!e.isCallExpression(t))return!1;let[n,r,i]=t.arguments;return xt(e,n)||U(e,r,"source")||U(e,i,"source")}function Et(e,t){if(!e.isCallExpression(t))return;let[n,r,i]=t.arguments,a=j(e,n,"metadata");return G(e,j(e,a,"source"))??G(e,j(e,r,"source"))??G(e,j(e,i,"source"))}function Lt(e,t,n,r){let i=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),a=n,s=a?.filePath,c=a?.layer,d=[],u=h=>i.getLineAndCharacterOfPosition(h.getStart(i)).line+1,g=h=>{if(It(e,h)){let o=h.arguments[0],l=G(e,o);for(let y of Ae({publishCall:!0,rawIntentName:l,objectHasIntent:U(e,o,"intent"),arkPublishCandidate:St(e,h),hasSource:kt(e,h)}))d.push(A(y.ruleId,y.message,{line:u(h),filePath:s}));let f=Et(e,h);if(r&&c&&f&&O(f)){let y=r.resolveLayer(f);y&&y!==c&&d.push(A("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${f}" resolves to ${y}, but the target file is classified as ${c}.`,{line:u(h),filePath:s,target:f,fromLayer:c,toLayer:y}))}}e.forEachChild(h,g)};return g(i),d}function xe(e={}){let t=new Set((e.intents||[]).map(a=>typeof a=="string"?a:a.name)),n=e.forbiddenPatterns||[],r=new Set(e.infrastructureLayers??[]),i=e.enforceIntentAllowlist??t.size>0;return{validate(a,s){let c=[],d=s,u=d?.filePath,g=d?.layer,h=e.typescript,o=h?h.createSourceFile(u??"generated.ts",a,h.ScriptTarget.Latest,!0):void 0,l=o?H(e.typescript,o):void 0,f=l?l.filter(p=>p.specifier!==void 0).map(p=>({value:p.specifier,index:p.node.getStart(o),kind:p.kind,typeOnly:p.typeOnly})):yt(a),y=e.typescript?ht(e.typescript,a):gt(a);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(u))for(let p of l?.filter(({unresolved:m})=>m)??[]){let m=p.kind==="require";c.push(A(m?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${m?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:p.line,filePath:u}))}let k=g!==void 0&&(r.has(g)||Ct(g)),b=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 p of n)if(p instanceof RegExp){p.lastIndex=0;let m=p.exec(a);p.lastIndex=0,m&&c.push(A("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${p}`,{line:m.index===void 0?void 0:N(a,m.index),filePath:u,suggestion:"Remove infrastructure imports from domain/application layers."+b}))}else a.includes(p)&&c.push(A("FORBIDDEN_SUBSTRING",`Forbidden substring: ${p}`,{line:N(a,a.indexOf(p)),filePath:u}));for(let p of f){let m=e.resolveImportTarget?.(p.value,u)??(e.resolveImportLayer?{layer:e.resolveImportLayer(p.value,u)}:void 0),R=typeof u=="string"?e.resolveImportTarget?.(u)??(e.resolveImportLayer?{layer:g,relPath:void 0}:void 0):void 0,$=m?.layer;if($&&g){let Z=v(e.architectureProfile?.rules,g,$,{fromPath:R?.relPath,toPath:m?.relPath,layers:e.architectureLayers});if(Z){if(p.typeOnly&&!Z.peerIsolation)continue;let ue=!!Z.peerIsolation;c.push(A("LAYER_IMPORT_VIOLATION",Z.message??(ue?`Layer "${g}" must not import across slices into "${$}".`:`Layer "${g}" must not import "${$}".`),{line:N(a,p.index),source:p.value,target:p.value,filePath:u,fromLayer:g,toLayer:$,suggestion:ue?"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:p.kind,peerIsolation:ue,...p.typeOnly?{typeOnly:!0}:{}}}));continue}if($!==g)continue}k||p.typeOnly||!mt(p.value)&&!At(p.value)||c.push(A("FORBIDDEN_IMPORT",`Forbidden ${p.kind} target: "${p.value}".`,{line:N(a,p.index),source:p.value,target:p.value,filePath:u,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+b,details:{importKind:p.kind}}))}if(e.policies)for(let p of e.policies){let m=p.check({source:a,context:s});if(m!==!0)if(Array.isArray(m))for(let R of m)c.push(A("POLICY_VIOLATION",R.message,{filePath:u,suggestion:`Fix violation of policy "${p.name}".`}));else m===!1?c.push(A("POLICY_VIOLATION",`Policy ${p.name} failed on generated code`)):c.push(A("POLICY_VIOLATION",m.message))}if(i&&t.size>0)for(let p of y)O(p.value)&&!t.has(p.value)&&c.push(A("UNKNOWN_INTENT",`Unknown intent reference: "${p.value}"`,{line:N(a,p.index),filePath:u,target:p.value,suggestion:`Register intent "${p.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&g)for(let p of y){if(!O(p.value))continue;let m=e.architectureProfile.resolveLayer(p.value);if(!m)continue;let R=v(e.architectureProfile.rules,g,m);R&&c.push(A("LAYER_REFERENCE_VIOLATION",R.message??`Layer "${g}" must not reference "${m}" through "${p.value}".`,{line:N(a,p.index),filePath:u,target:p.value,fromLayer:g,toLayer:m,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:R}}))}if(e.extensions)for(let p of e.extensions)try{let m=p.analyze(a,s);c.push(...m)}catch(m){c.push(A("EXTENSION_ERROR",`Extension "${p.name}" failed: ${m instanceof Error?m.message:String(m)}`))}if(e.typescript&&o&&g&&e.forbiddenGlobals?.[g]?.length)try{c.push(...V(e.typescript,o,e.forbiddenGlobals[g]).map(p=>A("FORBIDDEN_GLOBAL",`${g} must not use the ambient global "${p.name}".`,{line:p.line,filePath:u,target:p.name,fromLayer:g,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})))}catch(p){c.push(A("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${p instanceof Error?p.message:String(p)}`))}if(e.typescript)try{c.push(...Lt(e.typescript,a,s,e.architectureProfile))}catch(p){c.push(A("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${p instanceof Error?p.message:String(p)}`))}return{valid:c.length===0,violations:c}}}}var Be="1.0",te="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",Ue=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],wt=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Pt(){let e=[];for(let t of Ue)for(let n of Ue)t===n||wt.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var re=Pt();var w={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},ne={$schema:"https://json-schema.org/draft/2020-12/schema",$id:te,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:te,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:{...w,minItems:1,default:["src"]},exclude:{...w,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:re,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...w,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:{...w,minItems:1},exclude:w,intentPrefixes:w,description:{type:"string",minLength:1},forbiddenGlobals:w,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:{...w,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}}}}},D=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
|
|
1
|
+
"use strict";var Se=Object.defineProperty;var yt=Object.getOwnPropertyDescriptor;var gt=Object.getOwnPropertyNames;var mt=Object.prototype.hasOwnProperty;var ht=(e,t)=>{for(var n in t)Se(e,n,{get:t[n],enumerable:!0})},At=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of gt(t))!mt.call(e,i)&&i!==n&&Se(e,i,{get:()=>t[i],enumerable:!(r=yt(t,i))||r.enumerable});return e};var bt=e=>At(Se({},"__esModule",{value:!0}),e);var an={};ht(an,{ANALYSIS_IR_SCHEMA_VERSION:()=>ge,ARK_ANALYSIS_RESULT_SCHEMA:()=>Ke,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>Ye,ARK_CONFIG_SCHEMA:()=>fe,ARK_CONFIG_SCHEMA_VERSION:()=>at,POLICY_DELTA_SCHEMA_VERSION:()=>Ae,analyzeArchitectureConvergence:()=>ee,analyzeChange:()=>re,analyzePolicyDelta:()=>Ve,analyzeProject:()=>U,classifyArkPolicyDelta:()=>be,collectAnalysisConfigWarnings:()=>Ue,collectForbiddenCapabilityUses:()=>N,createAICodeGate:()=>Te,createAdapterResult:()=>qe,createArchitectureProfile:()=>Q,createArchitectureProfileFromArkConfig:()=>Fe,createElevenLayerArkConfig:()=>je,detectArchitectureCycles:()=>Ie,deterministicHash:()=>P,elevenLayerProfile:()=>Z,evaluateArchitectureGraph:()=>ie,explainViolation:()=>Ge,extractSemanticDependencies:()=>_,loadArkConfigContract:()=>J,loadContract:()=>ne,parseArkConfigJson:()=>ye,policyDeltaAcknowledgementMatches:()=>Ce,preflightChange:()=>He,stableSerialize:()=>L,toAdapterDiagnostic:()=>oe,version:()=>Be});module.exports=bt(an);var Be="3.4.0";var Ye="1.1";function k(e){return typeof e=="string"&&e.length>0?e:void 0}function ze(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function Ct(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 ${k(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 oe(e,t="error"){let n=k(e.ruleId)??k(e.code)??"ARK_UNKNOWN",r=e.severity==="warning"?"warning":t,i={...k(e.target)?{target:k(e.target)}:{},...k(e.fromLayer)?{fromLayer:k(e.fromLayer)}:{},...k(e.toLayer)?{toLayer:k(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{}};return{ruleId:n,severity:r,message:k(e.message)??n,location:{file:k(e.file)??"<unknown>",line:ze(e.line,1),column:ze(e.column,1)},evidence:i,nextAction:k(e.nextAction)??Ct(n,i,e)}}function qe(e){return{schemaVersion:"1.1",valid:e.valid,diagnostics:[...(e.violations??[]).map(t=>oe(t,"error")),...(e.warnings??[]).map(t=>oe(t,"warning"))]}}var Ke={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@2/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","valid","diagnostics"],properties:{schemaVersion:{const:"1.1"},valid:{type:"boolean"},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"}}},nextAction:{type:"string",minLength:1}}}}}};var Ee=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"}),Le=Object.freeze(Object.keys(we).sort()),ke=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"});function B(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=ke[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),i=ke[r];if(i)return i;let a=e.indexOf("/",n+1);return a<0?null:ke[e.slice(0,a)]??null}function se(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),i=we[r];if(i)return i}return null}function ce(e){if(e?.pure===!0)return[...Ee].sort();let n=(e?.capabilities?.deny??[]).filter(r=>Ee.includes(r));return[...new Set(n)].sort()}function Pe(e,t){if(t.length===0)return!1;let n=new Set(t),r=e.split(".");for(let i=r.length;i>=1;i-=1)if(n.has(r.slice(0,i).join(".")))return!0;return!1}function le(e){let t=new Set,n=new Set,r=Object.keys(we);for(let i of e?.forbiddenGlobals??[]){let a=r.filter(s=>s===i||s.startsWith(`${i}.`));if(a.length===0)n.add(i);else for(let s of a)t.add(`ambient:${s}`)}for(let i of ce(e)){t.add(`import:${i}`);for(let a of r)se(a)===i&&t.add(`ambient:${a}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}var We=new Map;function Je(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function Oe(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let i=e[n+1];if("*?{}[],".includes(i)||i==="\\"){t+="\\"+i,n+=1;continue}t+="/";continue}t+=r}return t}function It(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="{")t+=1;else if(r==="}"&&(t-=1,t<0))return!1}return t===0}function z(e){let t=We.get(e);if(t)return t;let n=Oe(e),r=It(n),i="",a=0;for(let c=0;c<n.length;c+=1){let p=n[c];p==="\\"&&c+1<n.length?(i+=Je(n[c+1]),c+=1):p==="*"?n[c+1]==="*"?n[c+2]==="/"?(i+="(?:.*/)?",c+=2):(i+=".*",c+=1):i+="[^/]*":p==="?"?i+="[^/]":p==="{"&&r?(i+="(?:",a+=1):p==="}"&&r&&a>0?(i+=")",a-=1):p===","&&r&&a>0?i+="|":i+=Je(p)}let s=new RegExp(`^${i}$`);return We.set(e,s),s}function Re(e){let t=Oe(String(e)),r=t.split("*")[0].split("/").filter(Boolean).length,i=t.replace(/\*/g,"").length;return r*1e4+i}function Y(e,t){let n=String(e).split(/[/\\]/).join("/"),r,i=-1;for(let a of t??[])if(!(a.exclude??[]).some(s=>z(s).test(n))){for(let s of a.patterns??[])if(z(s).test(n)){let c=Re(s);c>i&&(i=c,r=a.name)}}return r}function Ze(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),r=new Set(t.map(i=>String(i).toLowerCase()));for(let i=0;i<n.length-1;i+=1)if(r.has(n[i].toLowerCase()))return`${n[i]}/${n[i+1]}`}function xt(e){let t=new Set;for(let n of e??[]){let i=Oe(String(n)).split("/").filter(Boolean);for(let a=0;a<i.length;a+=1){let s=i[a];if((s==="**"||s==="*")&&a>0){let c=i[a-1];c&&!c.includes("*")&&!c.includes("{")&&!c.includes("}")&&t.add(c)}}}return[...t]}function St(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(i=>typeof i=="string"&&i.length>0);let r=(n??[]).find(i=>i.name===t);return xt(r?.patterns)}function v(e,t,n,r){for(let i of e??[])if(!(i.from!==t||i.to!==n)&&i.allowed===!1){if(i.peerIsolation){let a=r?.fromPath,s=r?.toPath;if(!a||!s)continue;let c=St(i,t,r?.layers);if(c.length===0)continue;let p=Ze(a,c),y=Ze(s,c);if(!p||!y)continue;if(p!==y)return i;continue}if(t!==n)return i}}function j(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function et(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function Qe(e,t){if(e.isImportDeclaration(t)){let n=t.importClause;if(!n)return!1;if(n.isTypeOnly)return!0;let r=n.namedBindings;return!!(r&&e.isNamedImports(r)&&r.elements.length>0&&r.elements.every(i=>i.isTypeOnly))}if(e.isExportDeclaration(t)){if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(r=>r.isTypeOnly))}return!1}function tt(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=i=>i===t.fileName?t:void 0,r.fileExists=i=>i===t.fileName,r.readFile=i=>i===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}function $e(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function ve(e,t,n,r){let i=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,a;try{a=i?t.getShorthandAssignmentValueSymbol(r.parent):$e(t,r)}catch{a=void 0}return!!a?.declarations?.some(s=>s.getSourceFile().fileName===n.fileName)}function _(e,t){let n,r=[],i=(s,c,p,y=!1)=>r.push({specifier:p,kind:c,line:et(t,s),typeOnly:y,unresolved:p===void 0,node:s}),a=s=>{if(e.isImportDeclaration(s))i(s,"import",j(e,s.moduleSpecifier),Qe(e,s));else if(e.isExportDeclaration(s)&&s.moduleSpecifier)i(s,"export",j(e,s.moduleSpecifier),Qe(e,s));else if(e.isImportEqualsDeclaration(s)&&e.isExternalModuleReference(s.moduleReference))i(s,"require",j(e,s.moduleReference.expression));else if(e.isCallExpression(s)){let c=s.expression.kind===e.SyntaxKind.ImportKeyword,y=e.isIdentifier(s.expression)&&s.expression.text==="require"&&!ve(e,n??(n=tt(e,t)),t,s.expression);(c||y)&&i(s,y?"require":"dynamic-import",j(e,s.arguments[0]))}e.forEachChild(s,a)};return a(t),r}function kt(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let i=j(e,r.argumentExpression);if(i===void 0)return;n.unshift(i)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}function Et(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 Xe(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let r=n.length;r>=1;r-=1){let i=n.slice(0,r).join(".");if(e.has(i))return i}}function N(e,t,n){if(n.length===0)return[];let r=new Set(n),i=tt(e,t),a=new Map,s=new Set;for(let l of t.statements)if(e.isVariableStatement(l))for(let o of l.declarationList.declarations)e.isIdentifier(o.name)&&s.add(o.name.text);let c=l=>{let o=kt(e,l);if(!o)return;let g=$e(i,o.root),f=g?a.get(g):void 0;return f?[...f,...o.segments.slice(1)]:ve(e,i,t,o.root)||s.has(o.root.text)?void 0:o.segments};for(let l of t.statements)if(e.isVariableStatement(l))for(let o of l.declarationList.declarations){if(!o.initializer||!e.isIdentifier(o.name))continue;let g=c(o.initializer),f=$e(i,o.name);!g||!f||a.set(f,g)}let p=[],y=new Set,u=(l,o)=>{let g=et(t,o),f=`${l}:${o.getStart(t)}`;y.has(f)||(y.add(f),p.push({name:l,line:g,node:o}))},m=l=>{let o=l.parent&&(e.isPropertyAccessExpression(l.parent)||e.isElementAccessExpression(l.parent))&&l.parent.expression===l;if((e.isPropertyAccessExpression(l)||e.isElementAccessExpression(l))&&!o){let g=c(l),f=g?Xe(r,g):void 0;f&&u(f,l)}else e.isIdentifier(l)&&r.has(l.text)&&Et(e,l)&&!ve(e,i,t,l)&&u(l.text,l);if(e.isVariableDeclaration(l)&&e.isObjectBindingPattern(l.name)&&l.initializer){let g=c(l.initializer);if(g)for(let f of l.name.elements){if(!e.isIdentifier(f.name))continue;let I=f.propertyName?j(e,f.propertyName)??f.propertyName.text:f.name.text,x=Xe(r,[...g,I]);x&&u(x,l.initializer)}}e.forEachChild(l,m)};return m(t),p}function _e(e,t){let n=[];for(let r of _(e,t)){if(r.typeOnly||!r.specifier)continue;let i=B(r.specifier);i&&n.push({capability:i,symbol:r.specifier,line:r.line,source:"import-based"})}for(let r of N(e,t,Le)){let i=se(r.name);i&&n.push({capability:i,symbol:r.name,line:r.line,source:"ambient-global"})}return n.sort((r,i)=>r.line-i.line||r.capability.localeCompare(i.capability)||r.symbol.localeCompare(i.symbol))}var Ne={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."};function M(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function Me(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&M(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:Ne.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:Ne.PUBLISH_MISSING_SOURCE}),t}function b(e,t,n){return{ruleId:e,code:e,message:t,...n}}function V(e,t){return e.slice(0,t).split(`
|
|
2
|
+
`).length}function wt(e){let t=[],n=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,r;for(;(r=n.exec(e))!==null;)t.push({value:r[1],index:r.index});return t}function Lt(e){let t=[],n=[{kind:"import",re:/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s*)?['"]([^'"]+)['"]/g},{kind:"export",re:/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s*['"]([^'"]+)['"]/g},{kind:"dynamic-import",re:/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g},{kind:"require",re:/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g}];for(let r of n){let i;for(;(i=r.re.exec(e))!==null;){let a=i.index+i[0].indexOf(i[1]),s=i[0],c=r.kind==="import"&&/\bimport\s+type\b/.test(s)||r.kind==="export"&&/\bexport\s+type\b/.test(s);t.push({value:i[1],index:a,kind:r.kind,typeOnly:c})}}return t.sort((r,i)=>r.index-i.index)}function Pt(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],i=a=>{e.isStringLiteralLike(a)&&r.push({value:a.text,index:a.getStart(n)}),e.forEachChild(a,i)};return i(n),r}function Ot(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 Rt(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}function $t(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}function K(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function vt(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}function nt(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:vt(e,r.name)===n)}function W(e,t,n){return nt(e,t,n)!==void 0}function q(e,t,n){let r=nt(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}function _t(e,t){let n=q(e,t,"metadata");return W(e,n,"source")}function rt(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?rt(e,t.name):!1:!1}function Nt(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 Mt(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=K(e,n);return r!==void 0&&M(r)||W(e,n,"intent")||rt(e,n)}function Tt(e,t){if(!e.isCallExpression(t))return!1;let[n,r,i]=t.arguments;return _t(e,n)||W(e,r,"source")||W(e,i,"source")}function Dt(e,t){if(!e.isCallExpression(t))return;let[n,r,i]=t.arguments,a=q(e,n,"metadata");return K(e,q(e,a,"source"))??K(e,q(e,r,"source"))??K(e,q(e,i,"source"))}function Ft(e,t,n,r){let i=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),a=n,s=a?.filePath,c=a?.layer,p=[],y=m=>i.getLineAndCharacterOfPosition(m.getStart(i)).line+1,u=m=>{if(Nt(e,m)){let l=m.arguments[0],o=K(e,l);for(let f of Me({publishCall:!0,rawIntentName:o,objectHasIntent:W(e,l,"intent"),arkPublishCandidate:Mt(e,m),hasSource:Tt(e,m)}))p.push(b(f.ruleId,f.message,{line:y(m),filePath:s}));let g=Dt(e,m);if(r&&c&&g&&M(g)){let f=r.resolveLayer(g);f&&f!==c&&p.push(b("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${g}" resolves to ${f}, but the target file is classified as ${c}.`,{line:y(m),filePath:s,target:g,fromLayer:c,toLayer:f}))}}e.forEachChild(m,u)};return u(i),p}function Te(e={}){let t=new Set((e.intents||[]).map(a=>typeof a=="string"?a:a.name)),n=e.forbiddenPatterns||[],r=new Set(e.infrastructureLayers??[]),i=e.enforceIntentAllowlist??t.size>0;return{validate(a,s){let c=[],p=s,y=p?.filePath,u=p?.layer,m=e.typescript,l=m?m.createSourceFile(y??"generated.ts",a,m.ScriptTarget.Latest,!0):void 0,o=l?_(e.typescript,l):void 0,g=o?o.filter(d=>d.specifier!==void 0).map(d=>({value:d.specifier,index:d.node.getStart(l),kind:d.kind,typeOnly:d.typeOnly})):Lt(a),f=e.typescript?Pt(e.typescript,a):wt(a);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(y))for(let d of o?.filter(({unresolved:h})=>h)??[]){let h=d.kind==="require";c.push(b(h?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${h?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:d.line,filePath:y}))}let I=u!==void 0&&(r.has(u)||$t(u)),x=u!==void 0?` If "${u}" 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 d of n)if(d instanceof RegExp){d.lastIndex=0;let h=d.exec(a);d.lastIndex=0,h&&c.push(b("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${d}`,{line:h.index===void 0?void 0:V(a,h.index),filePath:y,suggestion:"Remove infrastructure imports from domain/application layers."+x}))}else a.includes(d)&&c.push(b("FORBIDDEN_SUBSTRING",`Forbidden substring: ${d}`,{line:V(a,a.indexOf(d)),filePath:y}));for(let d of g){let h=e.resolveImportTarget?.(d.value,y)??(e.resolveImportLayer?{layer:e.resolveImportLayer(d.value,y)}:void 0),A=typeof y=="string"?e.resolveImportTarget?.(y)??(e.resolveImportLayer?{layer:u,relPath:void 0}:void 0):void 0,F=h?.layer;if(F&&u){let ae=v(e.architectureProfile?.rules,u,F,{fromPath:A?.relPath,toPath:h?.relPath,layers:e.architectureLayers});if(ae){if(d.typeOnly&&!ae.peerIsolation)continue;let xe=!!ae.peerIsolation;c.push(b("LAYER_IMPORT_VIOLATION",ae.message??(xe?`Layer "${u}" must not import across slices into "${F}".`:`Layer "${u}" must not import "${F}".`),{line:V(a,d.index),source:d.value,target:d.value,filePath:y,fromLayer:u,toLayer:F,suggestion:xe?"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:d.kind,peerIsolation:xe,...d.typeOnly?{typeOnly:!0}:{}}}));continue}if(F!==u)continue}I||d.typeOnly||!Ot(d.value)&&!Rt(d.value)||c.push(b("FORBIDDEN_IMPORT",`Forbidden ${d.kind} target: "${d.value}".`,{line:V(a,d.index),source:d.value,target:d.value,filePath:y,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+x,details:{importKind:d.kind}}))}if(e.policies)for(let d of e.policies){let h=d.check({source:a,context:s});if(h!==!0)if(Array.isArray(h))for(let A of h)c.push(b("POLICY_VIOLATION",A.message,{filePath:y,suggestion:`Fix violation of policy "${d.name}".`}));else h===!1?c.push(b("POLICY_VIOLATION",`Policy ${d.name} failed on generated code`)):c.push(b("POLICY_VIOLATION",h.message))}if(i&&t.size>0)for(let d of f)M(d.value)&&!t.has(d.value)&&c.push(b("UNKNOWN_INTENT",`Unknown intent reference: "${d.value}"`,{line:V(a,d.index),filePath:y,target:d.value,suggestion:`Register intent "${d.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&u)for(let d of f){if(!M(d.value))continue;let h=e.architectureProfile.resolveLayer(d.value);if(!h)continue;let A=v(e.architectureProfile.rules,u,h);A&&c.push(b("LAYER_REFERENCE_VIOLATION",A.message??`Layer "${u}" must not reference "${h}" through "${d.value}".`,{line:V(a,d.index),filePath:y,target:d.value,fromLayer:u,toLayer:h,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:A}}))}if(e.extensions)for(let d of e.extensions)try{let h=d.analyze(a,s);c.push(...h)}catch(h){c.push(b("EXTENSION_ERROR",`Extension "${d.name}" failed: ${h instanceof Error?h.message:String(h)}`))}if(e.typescript&&l&&u&&e.forbiddenGlobals?.[u]?.length)try{c.push(...N(e.typescript,l,e.forbiddenGlobals[u]).map(d=>b("FORBIDDEN_GLOBAL",`${u} must not use the ambient global "${d.name}".`,{line:d.line,filePath:y,target:d.name,fromLayer:u,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})))}catch(d){c.push(b("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${d instanceof Error?d.message:String(d)}`))}if(e.typescript&&l&&u&&e.capabilityWalls?.[u]?.length)try{let d=new Set(e.capabilityWalls[u]),h=e.forbiddenGlobals?.[u]??[];for(let A of _e(e.typescript,l))d.has(A.capability)&&(A.source==="ambient-global"&&Pe(A.symbol,h)||c.push(b("CAPABILITY_VIOLATION",A.source==="import-based"?`${u} denies the ${A.capability} capability; found import of "${A.symbol}".`:`${u} denies the ${A.capability} capability; found ambient "${A.symbol}".`,{line:A.line,filePath:y,target:A.symbol,capability:A.capability,fromLayer:u,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(d){c.push(b("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${d instanceof Error?d.message:String(d)}`))}if(e.typescript)try{c.push(...Ft(e.typescript,a,s,e.architectureProfile))}catch(d){c.push(b("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${d instanceof Error?d.message:String(d)}`))}return{valid:c.length===0,violations:c}}}}var at="1.0",de="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",it=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],jt=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Vt(){let e=[];for(let t of it)for(let n of it)t===n||jt.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var ue=Vt();var R={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},fe={$schema:"https://json-schema.org/draft/2020-12/schema",$id:de,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:de,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:{...R,minItems:1,default:["src"]},exclude:{...R,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:ue,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...R,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:{...R,minItems:1},exclude:R,intentPrefixes:R,description:{type:"string",minLength:1},forbiddenGlobals:R,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:{...R,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}}}}},H=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
|
|
3
3
|
${n.map(r=>`- ${r.path}: ${r.message}`).join(`
|
|
4
|
-
`)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function Ke(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ie(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function M(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Rt(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function ee(e,t,n,r,i){if(t.$ref){let a=Rt(t.$ref,r);if(!a){i.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}ee(e,a,n,r,i);return}if(t.const!==void 0&&!Object.is(e,t.const)){i.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(a=>Object.is(a,e))){i.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!Ke(e)){i.push({path:n,message:`must be an object; received ${M(e)}`});return}let a=t.properties??{};for(let s of t.required??[])e[s]===void 0&&i.push({path:Ie(n,s),message:"is required"});if(t.additionalProperties===!1)for(let s of Object.keys(e))s in a||i.push({path:Ie(n,s),message:"unknown field"});for(let[s,c]of Object.entries(a))e[s]!==void 0&&ee(e[s],c,Ie(n,s),r,i);return}if(t.type==="array"){if(!Array.isArray(e)){i.push({path:n,message:`must be an array; received ${M(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&i.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let a=e.map(s=>JSON.stringify(s));new Set(a).size!==a.length&&i.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((a,s)=>ee(a,t.items,`${n}[${s}]`,r,i));return}if(t.type==="string"){if(typeof e!="string"){i.push({path:n,message:`must be a string; received ${M(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&i.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&i.push({path:n,message:`must be a boolean; received ${M(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){i.push({path:n,message:`must be an integer; received ${M(e)}`});return}t.minimum!==void 0&&e<t.minimum&&i.push({path:n,message:`must be at least ${t.minimum}`})}}function Ot(e){return{...e,$schema:e.$schema===void 0?te: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?re.map(t=>({...t})):e.rules}}function $t(e,t="ark.config.json"){if(!Ke(e))throw new D(t,[{path:"$",message:`must be an object; received ${M(e)}`}]);let n=e.schemaVersion===void 0?"unversioned":null;if(e.schemaVersion!==void 0&&e.schemaVersion!=="1.0")throw new D(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.0`}]);return{candidate:Ot(e),migratedFrom:n}}function B(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=$t(e,t),i=[];if(ee(n,ne,"$",ne,i),i.length>0)throw new D(t,i);return{config:n,migratedFrom:r}}function ie(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new D(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return B(n,t)}function ze(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:te,schemaVersion:"1.0"};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}function vt(e){return e.endsWith(".")?e:`${e}.`}function _t(e,t){let n=e.prefixes.length?Math.max(...e.prefixes.map(i=>i.length)):0;return(t.prefixes.length?Math.max(...t.prefixes.map(i=>i.length)):0)-n}function z(e){let t=e.layers.map(i=>({...i,prefixes:i.prefixes.map(vt)})),n=[...t].sort(_t),r=[...e.rules??[]];return{name:e.name,layers:t,rules:r,resolveLayer(i){return t.find(a=>a.match?.(i))?.name??n.find(a=>a.prefixes.some(s=>i.startsWith(s)))?.name}}}function Se(e,t={}){return z({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,r)=>({name:n.name,prefixes:n.intentPrefixes??[],description:n.description,order:r+1})),rules:e.rules??[]})}var Nt=[{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}],K=z({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:Nt,rules:re.map(e=>({...e}))}),Mt={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 ke(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return ze({include:e.include??[t],layers:K.layers.map(i=>({name:i.name,patterns:(Mt[i.name]??[i.name]).map(a=>`${r}${a}/**`),intentPrefixes:i.prefixes,optional:n})),rules:[...K.rules]})}var ae="1.0";function P(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 L(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(L).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${L(t[n])}`).join(",")}}`}var qe="1.0";function C(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 I(e){return[...new Set(e??[])].sort()}function T(e,t,n,r,i){let a=I(n),s=I(r),c=new Set(a),d=new Set(s),u=s.filter(h=>!c.has(h)),g=a.filter(h=>!d.has(h));u.length===0&&g.length===0||(u.length>0&&C(e,{kind:"added",path:t,classification:i.added,message:i.addedMessage,before:a,after:s}),g.length>0&&C(e,{kind:"removed",path:t,classification:i.removed,message:i.removedMessage,before:a,after:s}))}function oe(e,t,n,r,i,a,s){if(n===r)return;C(e,{kind:r?"enabled":"disabled",path:t,classification:r?i:i==="strengthening"?"weakening":"strengthening",message:r?a:s,before:n,after:r})}function se(e,t){let n=new Map,r=new Set;for(let i of e){let a=t(i);n.has(a)?r.add(a):n.set(a,i)}return{values:n,duplicates:[...r].sort()}}function Dt(e,t,n){let r=se(t,a=>a.name),i=se(n,a=>a.name);(r.duplicates.length>0||i.duplicates.length>0)&&C(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:r.duplicates,after:i.duplicates});for(let a of[...new Set([...r.values.keys(),...i.values.keys()])].sort()){let s=r.values.get(a),c=i.values.get(a),d=`$.layers[${a}]`;if(!s&&c){C(e,{kind:"layer-added",path:d,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:c});continue}if(s&&!c){C(e,{kind:"layer-removed",path:d,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:s});continue}!s||!c||(T(e,`${d}.patterns`,s.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."}),T(e,`${d}.exclude`,s.exclude,c.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."}),T(e,`${d}.forbiddenGlobals`,s.forbiddenGlobals,c.forbiddenGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),I(s.intentPrefixes).join("\0")!==I(c.intentPrefixes).join("\0")&&C(e,{kind:"intent-prefixes-changed",path:`${d}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:I(s.intentPrefixes),after:I(c.intentPrefixes)}),oe(e,`${d}.mayImportInfrastructure`,s.mayImportInfrastructure===!0,c.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),oe(e,`${d}.optional`,s.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 Tt(e,t,n){let r=s=>`${s.from}->${s.to}`,i=se(t,r),a=se(n,r);(i.duplicates.length>0||a.duplicates.length>0)&&C(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:i.duplicates,after:a.duplicates});for(let s of[...new Set([...i.values.keys(),...a.values.keys()])].sort()){let c=i.values.get(s),d=a.values.get(s),u=`$.rules[${s}]`;if(!c&&d){d.allowed===!1&&C(e,{kind:"deny-added",path:u,classification:"strengthening",message:"A denied dependency edge was added.",after:d});continue}if(c&&!d){c.allowed===!1&&C(e,{kind:"deny-removed",path:u,classification:"weakening",message:"A denied dependency edge was removed.",before:c});continue}if(!c||!d)continue;c.allowed!==d.allowed&&C(e,{kind:d.allowed?"deny-disabled":"deny-enabled",path:`${u}.allowed`,classification:d.allowed?"weakening":"strengthening",message:d.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:c.allowed,after:d.allowed});let g=c.peerIsolation===!0,h=d.peerIsolation===!0;if(g!==h){let o=c.from===c.to&&d.from===d.to;C(e,{kind:h?"peer-isolation-enabled":"peer-isolation-disabled",path:`${u}.peerIsolation`,classification:o?h?"strengthening":"weakening":"judgment-required",message:o?h?"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:h})}I(c.sliceFolders).join("\0")!==I(d.sliceFolders).join("\0")&&C(e,{kind:"slice-folders-changed",path:`${u}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:I(c.sliceFolders),after:I(d.sliceFolders)})}}function Ft(e,t,n){let r=t.safety??{},i=n.safety??{};for(let a of["maxTsSuppressions","maxAnyCasts"]){let s=r[a]??0,c=i[a]??0;s!==c&&C(e,{kind:c>s?"threshold-raised":"threshold-lowered",path:`$.safety.${a}`,classification:c>s?"weakening":"strengthening",message:c>s?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:s,after:c})}for(let a of["allowInMemory","allowDisabledPeerIsolation"])oe(e,`$.safety.${a}`,r[a]===!0,i[a]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}function Ht(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 ce(e,t){let n=[];T(n,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),T(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."}),T(n,"$.dynamicImportAllowlist",e.dynamicImportAllowlist,t.dynamicImportAllowlist,{added:"weakening",removed:"strengthening",addedMessage:"Additional files may use non-literal dynamic imports.",removedMessage:"Fewer files may use non-literal dynamic imports."}),oe(n,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let r={off:0,soft:1,"framework-soft":1,strict:2},i=e.cyclePolicy??"strict",a=t.cyclePolicy??"strict";if(i!==a){let s=r[a]===r[i]?"judgment-required":r[a]>r[i]?"strengthening":"weakening";C(n,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:s,message:"The cycle enforcement level changed.",before:i,after:a})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&C(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}),Dt(n,e.layers,t.layers),Tt(n,e.rules,t.rules),Ft(n,e,t),n.sort((s,c)=>s.path.localeCompare(c.path)||s.id.localeCompare(c.id)),{schemaVersion:"1.0",classification:Ht(n),findings:n}}function le(e,t){if(!e||e.schemaVersion!=="1.0"||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(i=>typeof i!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=I(e.findingIds),r=I(t.findingIds);return n.length===r.length&&n.every((i,a)=>i===r[a])}function S(e){return`${e.from}->${e.to}`}function q(e,t,n,r="dependency"){return{id:`${e}:${r}:${S(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${S(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${S(t)}, then preflight again.`}:e==="unplanned"?{nextAction:`Remove the unplanned dependency ${S(t)} from the candidate, then preflight again.`}:{}}}function Y(e){let t=[],n=new Map(e.changeMap.map.files.map(o=>[o.path,o])),r=new Map(e.changes.map(o=>[o.path,o])),i=new Map(e.changeMap.map.dependencies.map(o=>[S(o),o])),a=new Map(e.baseDependencies.map(o=>[S(o),o])),s=new Map(e.candidateDependencies.map(o=>[S(o),o]));for(let o of[...n.values()].sort((l,f)=>l.path.localeCompare(f.path))){let l=r.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[...r.values()].sort((l,f)=>l.path.localeCompare(f.path)))n.has(o.path)||t.push({id:`unplanned:file:${o.path}`,classification:"unplanned",subject:"file",path:o.path,actualOperation:o.operation,message:`${o.path} has an unplanned ${o.operation} operation.`,nextAction:`Remove ${o.path} from the change set, then preflight again.`});let c=new Set;for(let o of[...i.values()].sort((l,f)=>S(l).localeCompare(S(f)))){if(s.has(S(o))){t.push(q("satisfied",o,`${o.from} -> ${o.to} exists in the candidate architecture.`));continue}let l={from:o.to,to:o.from};s.has(S(l))?(c.add(S(l)),t.push(q("contradictory",o,`${o.from} -> ${o.to} was planned, but the candidate contains the reverse edge.`))):t.push(q("missing",o,`${o.from} -> ${o.to} is absent from the candidate architecture.`))}let d=new Set([...n.keys(),...r.keys()]);for(let[o,l]of[...s].sort(([f],[y])=>f.localeCompare(y)))a.has(o)||i.has(o)||c.has(o)||!d.has(l.from)&&!d.has(l.to)||t.push({...q("unplanned",l,`${l.from} -> ${l.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let u=new Set(e.changeMap.map.files.filter(o=>o.operation==="delete").map(o=>o.path));for(let[o,l]of[...a].sort(([f],[y])=>f.localeCompare(y)))s.has(o)||u.has(l.from)||u.has(l.to)||!d.has(l.from)&&!d.has(l.to)||t.push({...q("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 h={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:h.missing===0&&h.contradictory===0&&h.unplanned===0,behavioralCompletion:"not-evaluated",summary:h,findings:t}}function Ye(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"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 de(e,t){let n=typeof e=="string"?ie(e,t):B(e,t);return{...n,policyHash:P(L(n.config))}}function Ze(e){let t=de(e.baseConfig,e.baseSource??"base ark.config.json"),n=de(e.candidateConfig,e.candidateSource??"candidate ark.config.json"),r=ce(t.config,n.config),i=r.findings.filter(c=>c.classification==="weakening"||c.classification==="judgment-required").map(c=>c.id).sort(),a=i.length>0,s=a&&le(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:i});return{schemaVersion:r.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:r.classification,findings:r.findings,blockingFindingIds:i,requiresAcknowledgement:a,acknowledged:s,valid:!a||s}}function J(e){let t=[];for(let n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."&&t.length>0&&t.at(-1)!==".."?t.pop():t.push(n));return t.join("/")}function We(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}function Ee(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}function pe(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let r=t,i="";for(t+=1;t<e.length;t+=1){let a=e[t];if(a===n)return{value:i,offset:r,excerpt:e.slice(r,t+1)};a==="\\"&&t+1<e.length?(i+=e[t+1],t+=1):i+=a}}function W(e,t,n){return e.startsWith(t,n)&&!We(e[n-1])&&!We(e[n+t.length])}function Vt(e,t){return t=Ee(e,t+6),e[t]==="("?pe(e,Ee(e,t+1)):Qe(e,t,!0)}function jt(e,t){return Qe(e,t+6,!1)}function Qe(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(W(e,"from",t))return pe(e,Ee(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return pe(e,t);if(t>0&&(W(e,"import",t)||W(e,"export",t)))return}}function Gt(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="/"&&e[n+1]==="/"){if(n=e.indexOf(`
|
|
5
|
-
`,n+2),n<0)break;continue}if(r==="/"&&e[n+1]==="*"){let a=e.indexOf("*/",n+2);if(a<0)break;n=a+1;continue}if(r==="
|
|
6
|
-
`).length,s={kind:"import",file:e.path,line:a,excerpt:r.excerpt},c=Bt(e.path,i,t);n.push({from:e.path,specifier:i,to:c?.path??null,resolution:c?"resolved":"unresolved",fromLayer:e.layer,toLayer:c?.layer??null,evidence:s})}return n}function Bt(e,t,n){let r=e.split("/");r.pop();for(let a of t.split("/"))a==="."||a===""||(a===".."?r.pop():r.push(a));let i=r.join("/");for(let a of[i,`${i}.ts`,`${i}.tsx`,`${i}.mts`,`${i}.cts`,`${i}/index.ts`,`${i}/index.tsx`]){let s=n.get(a);if(s)return s}}function Kt(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let i=v(t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});i&&n.push({ruleId:`layer-dependency:${i.from}->${i.to}`,message:i.message??`${i.from} must not depend on ${i.to}.`,edge:r,evidence:r.evidence})}return n}function fe(e){let t=e.files.map(s=>{let c=J(s.path);return{path:c,content:s.content,contentHash:P(s.content),layer:X(c,e.contract.config.layers)??null}}).sort((s,c)=>s.path.localeCompare(c.path)),n=new Map(t.map(s=>[s.path,s])),r=t.flatMap(s=>Ut(s,n)),i=[],a=Kt(r,e.contract.config);return{ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:P(L(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(s=>s.name),edges:r,capabilityUses:i,violations:a}}}function Le(e){let t=new Map(e.files.map(n=>[J(n.path),n]));for(let n of e.changes){let r=J(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return fe({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}function Xe(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 we(e){let t=0,n=new Map,r=new Map,i=new Set,a=[],s=[],c=d=>{n.set(d,t),r.set(d,t),t+=1,a.push(d),i.add(d);for(let h of[...e.get(d)??[]].sort())e.has(h)&&(n.has(h)?i.has(h)&&r.set(d,Math.min(r.get(d)??0,n.get(h)??0)):(c(h),r.set(d,Math.min(r.get(d)??0,r.get(h)??0))));if(r.get(d)!==n.get(d))return;let u=[],g;do{if(g=a.pop(),g===void 0)break;i.delete(g),u.push(g)}while(g!==d);u.length>1&&s.push(u.sort())};for(let d of[...e.keys()].sort())n.has(d)||c(d);return s.sort((d,u)=>d[0].localeCompare(u[0])).map(d=>({ruleId:"CIRCULAR_DEPENDENCY",file:d[0],line:1,target:d.join(" \u2192 "),message:`Circular dependency among ${d.length} files: ${d.join(" \u2192 ")} \u2192 ${d[0]}.`,cycleKind:"value"}))}function Pe(e){let t=e.contentViolations.map(a=>({...a})),n=(e.warnings??[]).map(a=>({...a})),r=new Map(e.files.map(a=>[a,new Set]));for(let a of e.edges){if(a.to&&a.to!==a.from&&!a.typeOnly&&r.has(a.from)&&r.get(a.from)?.add(a.to),!a.to||!a.toLayer)continue;let s=v(e.rules,a.fromLayer,a.toLayer,{fromPath:a.from,toPath:a.to,layers:e.config.layers});if(!s)continue;let c=!!s.peerIsolation;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:a.from,line:a.line,fromLayer:a.fromLayer,toLayer:a.toLayer,target:a.to,...a.typeOnly?{typeOnly:!0}:{},...a.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...a.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...a.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!c&&a.portProofEligible?{portProofEligible:!0}:{},...a.kind?{edgeKind:a.kind}:{},...c?{peerIsolation:!0}:{},message:s.message??(c?`${a.fromLayer} must not ${a.kind} another slice of ${a.toLayer} (${a.from} \u2192 ${a.to}). Extract shared code or use events/ports across slices.`:`${a.fromLayer} must not ${a.kind} ${a.toLayer}.`)})}let i=String(e.config.cyclePolicy??"strict").toLowerCase();if(i!=="off"){let a=we(r);i==="soft"||i==="framework-soft"?n.push(...a.map(s=>({...s,message:`${s.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...a)}return{violations:t,warnings:n,safety:e.safety}}function Je(e){return P(L(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}function et(e){let t=fe(e),n=new Map(t.ir.files.map(o=>[o.path,o])),r=[],i=new Set,a=[];for(let o of e.changes){let l=o.path.replace(/\\/g,"/"),f=J(o.path);if(!f||f===".."||f.startsWith("../")||l.startsWith("/")||/^[A-Za-z]:\//.test(l)||l.includes("\0")){a.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(i.has(f)){a.push({ruleId:"DUPLICATE_CHANGE_PATH",file:f,line:1,message:`The atomic change set contains more than one operation for ${f}.`});continue}i.add(f),"delete"in o&&o.delete&&!n.has(f)&&a.push({ruleId:"DELETE_TARGET_MISSING",file:f,line:1,message:`Cannot delete ${f} because it is not present in the supplied base tree.`}),r.push("delete"in o&&o.delete?{path:f,delete:!0}:{path:f,content:"content"in o?o.content:""})}e.changes.length===0&&a.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let s=Le({...e,changes:r}),c=new Map(s.ir.files.map(o=>[o.path,o])),d=Pe({config:e.contract.config,rules:e.contract.config.rules,files:s.ir.files.map(o=>o.path),contentViolations:[],edges:s.ir.edges.filter(o=>!!o.fromLayer).map(o=>({from:o.from,fromLayer:o.fromLayer,...o.to?{to:o.to}:{},...o.toLayer?{toLayer:o.toLayer}:{},line:o.evidence.line,kind:"import"}))}),u=r.map(o=>{let l=J(o.path),f=n.get(l),y=c.get(l);return{path:l,operation:"delete"in o&&o.delete?"delete":f?"update":"create",...f?{beforeContentHash:f.contentHash}:{},...y?{candidateContentHash:y.contentHash}:{}}}).sort((o,l)=>o.path.localeCompare(l.path)),g=[...a,...d.violations].map(o=>({...o,nextAction:Ye(o)})),h=e.changeMap?Y({changeMap:e.changeMap,changes:u,baseDependencies:t.ir.edges.flatMap(o=>o.to?[{from:o.from,to:o.to}]:[]),candidateDependencies:s.ir.edges.flatMap(o=>o.to?[{from:o.from,to:o.to}]:[])}):void 0;return{schemaVersion:"1.0",valid:g.length===0&&(h?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:s.ir.compilerOptionsHash,baseTreeHash:Je(t.ir.files),candidateTreeHash:Je(s.ir.files),...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...h?{convergence:h}:{},changes:u,violations:g,warnings:d.warnings}}function x(e,t,n={}){return{ruleId:e,message:t,...n}}function tt(e){let{config:t,rules:n,files:r,manifest:i}=e,a=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(l=>typeof l!="string"))&&a.push(x("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)))a.push(x("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let l of["maxTsSuppressions","maxAnyCasts"]){let f=t.safety[l];f!==void 0&&(!Number.isInteger(f)||f<0)&&a.push(x("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${l} must be a non-negative integer.`))}let s=Array.isArray(t.layers)?t.layers:[],c=Array.isArray(i?.architecture?.layers)?i.architecture.layers:[],d=new Set([...s.map(l=>l.name).filter(Boolean),...c.map(l=>l.name).filter(l=>!!l)]);s.length===0&&a.push(x("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let u=new Set,g=new Set;for(let l of s){if(!l.name){a.push(x("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}u.has(l.name)&&g.add(l.name),u.add(l.name),l.forbiddenGlobals!==void 0&&(!Array.isArray(l.forbiddenGlobals)||l.forbiddenGlobals.some(y=>typeof y!="string"))&&a.push(x("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 f=Array.isArray(l.patterns)?l.patterns:[];if(f.length===0){a.push(x("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${l.name}" has no file patterns and will never classify files.`,{layer:l.name}));continue}for(let y of f){let k;try{k=F(y)}catch(b){a.push(x("CONFIG_INVALID_LAYER_PATTERN",`Layer "${l.name}" has an invalid pattern "${y}": ${b instanceof Error?b.message:String(b)}`,{layer:l.name,pattern:y}));continue}!r.some(b=>k.test(b))&&!l.optional&&a.push(x("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${l.name}" pattern "${y}" matched no included files.`,{layer:l.name,pattern:y,failsStrict:!1}))}}for(let l of g)a.push(x("CONFIG_DUPLICATE_LAYER",`Layer "${l}" is configured more than once.`,{layer:l}));if(d.size>0)for(let l of n??[])l.from&&!d.has(l.from)&&a.push(x("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${l.from}".`,{fromLayer:l.from,toLayer:l.to})),l.to&&!d.has(l.to)&&a.push(x("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${l.to}".`,{fromLayer:l.from,toLayer:l.to}));let h=new Set;if(s.length>1)for(let l of r){let f=-1,y=[];for(let k of s)for(let b of k.patterns??[]){if(!F(b).test(l))continue;let p=he(b);p>f?(f=p,y=[k.name]):p===f&&!y.includes(k.name)&&y.push(k.name)}y.length>1&&h.add([...y].sort().join(" + "))}h.size>0&&a.push(x("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...h].join(", ")}.`,{pairs:[...h]}));let o=r.filter(l=>!X(l,s));return o.length>0&&a.push(x("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)})),a}0&&(module.exports={ANALYSIS_IR_SCHEMA_VERSION,ARK_ANALYSIS_RESULT_SCHEMA,ARK_ANALYSIS_RESULT_SCHEMA_VERSION,ARK_CONFIG_SCHEMA,ARK_CONFIG_SCHEMA_VERSION,POLICY_DELTA_SCHEMA_VERSION,analyzeArchitectureConvergence,analyzeChange,analyzePolicyDelta,analyzeProject,classifyArkPolicyDelta,collectAnalysisConfigWarnings,collectForbiddenCapabilityUses,createAICodeGate,createAdapterResult,createArchitectureProfile,createArchitectureProfileFromArkConfig,createElevenLayerArkConfig,detectArchitectureCycles,deterministicHash,elevenLayerProfile,evaluateArchitectureGraph,explainViolation,extractSemanticDependencies,loadArkConfigContract,loadContract,parseArkConfigJson,policyDeltaAcknowledgementMatches,preflightChange,stableSerialize,toAdapterDiagnostic,version});
|
|
4
|
+
`)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function ot(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function De(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function G(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Gt(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function pe(e,t,n,r,i){if(t.$ref){let a=Gt(t.$ref,r);if(!a){i.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}pe(e,a,n,r,i);return}if(t.const!==void 0&&!Object.is(e,t.const)){i.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(a=>Object.is(a,e))){i.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!ot(e)){i.push({path:n,message:`must be an object; received ${G(e)}`});return}let a=t.properties??{};for(let s of t.required??[])e[s]===void 0&&i.push({path:De(n,s),message:"is required"});if(t.additionalProperties===!1)for(let s of Object.keys(e))s in a||i.push({path:De(n,s),message:"unknown field"});for(let[s,c]of Object.entries(a))e[s]!==void 0&&pe(e[s],c,De(n,s),r,i);return}if(t.type==="array"){if(!Array.isArray(e)){i.push({path:n,message:`must be an array; received ${G(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&i.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let a=e.map(s=>JSON.stringify(s));new Set(a).size!==a.length&&i.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((a,s)=>pe(a,t.items,`${n}[${s}]`,r,i));return}if(t.type==="string"){if(typeof e!="string"){i.push({path:n,message:`must be a string; received ${G(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&i.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&i.push({path:n,message:`must be a boolean; received ${G(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){i.push({path:n,message:`must be an integer; received ${G(e)}`});return}t.minimum!==void 0&&e<t.minimum&&i.push({path:n,message:`must be at least ${t.minimum}`})}}function Ht(e){return{...e,$schema:e.$schema===void 0?de: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?ue.map(t=>({...t})):e.rules}}function Ut(e,t="ark.config.json"){if(!ot(e))throw new H(t,[{path:"$",message:`must be an object; received ${G(e)}`}]);let n=e.schemaVersion===void 0?"unversioned":null;if(e.schemaVersion!==void 0&&e.schemaVersion!=="1.0")throw new H(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.0`}]);return{candidate:Ht(e),migratedFrom:n}}function J(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=Ut(e,t),i=[];if(pe(n,fe,"$",fe,i),i.length>0)throw new H(t,i);return{config:n,migratedFrom:r}}function ye(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new H(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return J(n,t)}function st(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:de,schemaVersion:"1.0"};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}function Bt(e){return e.endsWith(".")?e:`${e}.`}function zt(e,t){let n=e.prefixes.length?Math.max(...e.prefixes.map(i=>i.length)):0;return(t.prefixes.length?Math.max(...t.prefixes.map(i=>i.length)):0)-n}function Q(e){let t=e.layers.map(i=>({...i,prefixes:i.prefixes.map(Bt)})),n=[...t].sort(zt),r=[...e.rules??[]];return{name:e.name,layers:t,rules:r,resolveLayer(i){return t.find(a=>a.match?.(i))?.name??n.find(a=>a.prefixes.some(s=>i.startsWith(s)))?.name}}}function Fe(e,t={}){return Q({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,r)=>({name:n.name,prefixes:n.intentPrefixes??[],description:n.description,order:r+1})),rules:e.rules??[]})}var Yt=[{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}],Z=Q({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:Yt,rules:ue.map(e=>({...e}))}),qt={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 je(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return st({include:e.include??[t],layers:Z.layers.map(i=>({name:i.name,patterns:(qt[i.name]??[i.name]).map(a=>`${r}${a}/**`),intentPrefixes:i.prefixes,optional:n})),rules:[...Z.rules]})}var ge="1.0";function P(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 L(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(L).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${L(t[n])}`).join(",")}}`}function E(e){return`${e.from}->${e.to}`}function X(e,t,n,r="dependency"){return{id:`${e}:${r}:${E(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${E(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${E(t)}, then preflight again.`}:e==="unplanned"?{nextAction:`Remove the unplanned dependency ${E(t)} from the candidate, then preflight again.`}:{}}}function ee(e){let t=[],n=new Map(e.changeMap.map.files.map(l=>[l.path,l])),r=new Map(e.changes.map(l=>[l.path,l])),i=new Map(e.changeMap.map.dependencies.map(l=>[E(l),l])),a=new Map(e.baseDependencies.map(l=>[E(l),l])),s=new Map(e.candidateDependencies.map(l=>[E(l),l]));for(let l of[...n.values()].sort((o,g)=>o.path.localeCompare(g.path))){let o=r.get(l.path);o?o.operation!==l.operation?t.push({id:`contradictory:file:${l.path}`,classification:"contradictory",subject:"file",path:l.path,expectedOperation:l.operation,actualOperation:o.operation,message:`${l.path} was planned as ${l.operation} but the actual operation is ${o.operation}.`,nextAction:`Change ${l.path} to the planned ${l.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${l.path}`,classification:"satisfied",subject:"file",path:l.path,expectedOperation:l.operation,actualOperation:o.operation,message:`${l.path} matches the planned ${l.operation} operation.`}):t.push({id:`missing:file:${l.path}`,classification:"missing",subject:"file",path:l.path,expectedOperation:l.operation,message:`${l.path} was planned as ${l.operation} but is absent from the actual change.`,nextAction:`${l.operation[0].toUpperCase()}${l.operation.slice(1)} ${l.path} in the complete change set, then preflight again.`})}for(let l of[...r.values()].sort((o,g)=>o.path.localeCompare(g.path)))n.has(l.path)||t.push({id:`unplanned:file:${l.path}`,classification:"unplanned",subject:"file",path:l.path,actualOperation:l.operation,message:`${l.path} has an unplanned ${l.operation} operation.`,nextAction:`Remove ${l.path} from the change set, then preflight again.`});let c=new Set;for(let l of[...i.values()].sort((o,g)=>E(o).localeCompare(E(g)))){if(s.has(E(l))){t.push(X("satisfied",l,`${l.from} -> ${l.to} exists in the candidate architecture.`));continue}let o={from:l.to,to:l.from};s.has(E(o))?(c.add(E(o)),t.push(X("contradictory",l,`${l.from} -> ${l.to} was planned, but the candidate contains the reverse edge.`))):t.push(X("missing",l,`${l.from} -> ${l.to} is absent from the candidate architecture.`))}let p=new Set([...n.keys(),...r.keys()]);for(let[l,o]of[...s].sort(([g],[f])=>g.localeCompare(f)))a.has(l)||i.has(l)||c.has(l)||!p.has(o.from)&&!p.has(o.to)||t.push({...X("unplanned",o,`${o.from} -> ${o.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let y=new Set(e.changeMap.map.files.filter(l=>l.operation==="delete").map(l=>l.path));for(let[l,o]of[...a].sort(([g],[f])=>g.localeCompare(f)))s.has(l)||y.has(o.from)||y.has(o.to)||!p.has(o.from)&&!p.has(o.to)||t.push({...X("unplanned",o,`${o.from} -> ${o.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let u={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((l,o)=>u[l.classification]-u[o.classification]||(l.subject===o.subject?0:l.subject==="file"?-1:1)||l.id.localeCompare(o.id));let m={satisfied:t.filter(l=>l.classification==="satisfied").length,missing:t.filter(l=>l.classification==="missing").length,contradictory:t.filter(l=>l.classification==="contradictory").length,unplanned:t.filter(l=>l.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:m.missing===0&&m.contradictory===0&&m.unplanned===0,behavioralCompletion:"not-evaluated",summary:m,findings:t}}var Ae="1.0";function C(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 w(e){return[...new Set(e??[])].sort()}function T(e,t,n,r,i){let a=w(n),s=w(r),c=new Set(a),p=new Set(s),y=s.filter(m=>!c.has(m)),u=a.filter(m=>!p.has(m));y.length===0&&u.length===0||(y.length>0&&C(e,{kind:"added",path:t,classification:i.added,message:i.addedMessage,before:a,after:s}),u.length>0&&C(e,{kind:"removed",path:t,classification:i.removed,message:i.removedMessage,before:a,after:s}))}function me(e,t,n,r,i,a,s){if(n===r)return;C(e,{kind:r?"enabled":"disabled",path:t,classification:r?i:i==="strengthening"?"weakening":"strengthening",message:r?a:s,before:n,after:r})}function he(e,t){let n=new Map,r=new Set;for(let i of e){let a=t(i);n.has(a)?r.add(a):n.set(a,i)}return{values:n,duplicates:[...r].sort()}}function Kt(e,t,n){let r=he(t,a=>a.name),i=he(n,a=>a.name);(r.duplicates.length>0||i.duplicates.length>0)&&C(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:r.duplicates,after:i.duplicates});for(let a of[...new Set([...r.values.keys(),...i.values.keys()])].sort()){let s=r.values.get(a),c=i.values.get(a),p=`$.layers[${a}]`;if(!s&&c){C(e,{kind:"layer-added",path:p,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:c});continue}if(s&&!c){C(e,{kind:"layer-removed",path:p,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:s});continue}if(!s||!c)continue;T(e,`${p}.patterns`,s.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."}),T(e,`${p}.exclude`,s.exclude,c.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let y=le(s),u=le(c);T(e,`${p}.forbiddenGlobals`,y.rawGlobals,u.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),T(e,`${p}.capabilities`,y.atoms,u.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)."}),w(s.intentPrefixes).join("\0")!==w(c.intentPrefixes).join("\0")&&C(e,{kind:"intent-prefixes-changed",path:`${p}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:w(s.intentPrefixes),after:w(c.intentPrefixes)}),me(e,`${p}.mayImportInfrastructure`,s.mayImportInfrastructure===!0,c.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),me(e,`${p}.optional`,s.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 Wt(e,t,n){let r=s=>`${s.from}->${s.to}`,i=he(t,r),a=he(n,r);(i.duplicates.length>0||a.duplicates.length>0)&&C(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:i.duplicates,after:a.duplicates});for(let s of[...new Set([...i.values.keys(),...a.values.keys()])].sort()){let c=i.values.get(s),p=a.values.get(s),y=`$.rules[${s}]`;if(!c&&p){p.allowed===!1&&C(e,{kind:"deny-added",path:y,classification:"strengthening",message:"A denied dependency edge was added.",after:p});continue}if(c&&!p){c.allowed===!1&&C(e,{kind:"deny-removed",path:y,classification:"weakening",message:"A denied dependency edge was removed.",before:c});continue}if(!c||!p)continue;c.allowed!==p.allowed&&C(e,{kind:p.allowed?"deny-disabled":"deny-enabled",path:`${y}.allowed`,classification:p.allowed?"weakening":"strengthening",message:p.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:c.allowed,after:p.allowed});let u=c.peerIsolation===!0,m=p.peerIsolation===!0;if(u!==m){let l=c.from===c.to&&p.from===p.to;C(e,{kind:m?"peer-isolation-enabled":"peer-isolation-disabled",path:`${y}.peerIsolation`,classification:l?m?"strengthening":"weakening":"judgment-required",message:l?m?"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:u,after:m})}w(c.sliceFolders).join("\0")!==w(p.sliceFolders).join("\0")&&C(e,{kind:"slice-folders-changed",path:`${y}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:w(c.sliceFolders),after:w(p.sliceFolders)})}}function Jt(e,t,n){let r=t.safety??{},i=n.safety??{};for(let a of["maxTsSuppressions","maxAnyCasts"]){let s=r[a]??0,c=i[a]??0;s!==c&&C(e,{kind:c>s?"threshold-raised":"threshold-lowered",path:`$.safety.${a}`,classification:c>s?"weakening":"strengthening",message:c>s?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:s,after:c})}for(let a of["allowInMemory","allowDisabledPeerIsolation"])me(e,`$.safety.${a}`,r[a]===!0,i[a]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}function Zt(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 be(e,t){let n=[];T(n,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),T(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."}),T(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."}),me(n,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let r={off:0,soft:1,"framework-soft":1,strict:2},i=e.cyclePolicy??"strict",a=t.cyclePolicy??"strict";if(i!==a){let s=r[a]===r[i]?"judgment-required":r[a]>r[i]?"strengthening":"weakening";C(n,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:s,message:"The cycle enforcement level changed.",before:i,after:a})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&C(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}),Kt(n,e.layers,t.layers),Wt(n,e.rules,t.rules),Jt(n,e,t),n.sort((s,c)=>s.path.localeCompare(c.path)||s.id.localeCompare(c.id)),{schemaVersion:Ae,classification:Zt(n),findings:n}}function Ce(e,t){if(!e||e.schemaVersion!==Ae||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(i=>typeof i!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=w(e.findingIds),r=w(t.findingIds);return n.length===r.length&&n.every((i,a)=>i===r[a])}function D(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 ct(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}function $(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}function te(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let r=t,i="";for(t+=1;t<e.length;t+=1){let a=e[t];if(a===n)return{value:i,offset:r,excerpt:e.slice(r,t+1)};a==="\\"&&t+1<e.length?(i+=e[t+1],t+=1):i+=a}}function O(e,t,n){return e.startsWith(t,n)&&!ct(e[n-1])&&!ct(e[n+t.length])}function Qt(e,t){if(t=$(e,t+6),e[t]==="(")return te(e,$(e,t+1));let n=!1;if(O(e,"type",t)){let i=$(e,t+4);e[i]!==","&&!O(e,"from",i)&&(n=!0)}let r=lt(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}function Xt(e,t){t=t+6;let n=$(e,t),r=!1;if(O(e,"type",n)){let a=$(e,n+4);(e[a]==="{"||e[a]==="*")&&(r=!0)}let i=lt(e,t,!1);return i&&r?{...i,typeOnly:!0}:i}function lt(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(O(e,"from",t))return te(e,$(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return te(e,t);if(t>0&&(O(e,"import",t)||O(e,"export",t)))return}}function en(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 tn(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=$(e,t+7);if(e[r]!=="(")return;r=$(e,r+1);let i=te(e,r);return i?{...i,requireCall:!0}:void 0}function nn(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="/"&&e[n+1]==="/"){if(n=e.indexOf(`
|
|
5
|
+
`,n+2),n<0)break;continue}if(r==="/"&&e[n+1]==="*"){let a=e.indexOf("*/",n+2);if(a<0)break;n=a+1;continue}if(r==="`"){n=en(e,n);continue}if(r==="'"||r==='"'){let a=te(e,n);a&&(n=a.offset+a.excerpt.length-1);continue}let i=r==="i"&&O(e,"import",n)?Qt(e,n):r==="e"&&O(e,"export",n)?Xt(e,n):r==="r"&&O(e,"require",n)?tn(e,n):void 0;i&&t.push(i)}return t}function pt(e,t){let n=[],r=[];for(let i of nn(e.content)){let a=i.value;if(i.requireCall&&a.startsWith("."))continue;if(!a.startsWith(".")){if(i.typeOnly)continue;let y=B(a);if(!y)continue;let u=e.content.slice(0,i.offset).split(`
|
|
6
|
+
`).length;r.push({file:e.path,symbol:a,capability:y,evidence:{kind:"import",file:e.path,line:u,excerpt:i.excerpt}});continue}let s=e.content.slice(0,i.offset).split(`
|
|
7
|
+
`).length,c={kind:"import",file:e.path,line:s,excerpt:i.excerpt},p=rn(e.path,a,t);n.push({from:e.path,specifier:a,to:p?.path??null,resolution:p?"resolved":"unresolved",fromLayer:e.layer,toLayer:p?.layer??null,evidence:c})}return{edges:n,capabilityUses:r}}function rn(e,t,n){let r=e.split("/");r.pop();for(let a of t.split("/"))a==="."||a===""||(a===".."?r.pop():r.push(a));let i=r.join("/");for(let a of[i,`${i}.ts`,`${i}.tsx`,`${i}.mts`,`${i}.cts`,`${i}/index.ts`,`${i}/index.tsx`]){let s=n.get(a);if(s)return s}}function dt(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let i=v(t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});i&&n.push({ruleId:`layer-dependency:${i.from}->${i.to}`,message:i.message??`${i.from} must not depend on ${i.to}.`,edge:r,evidence:r.evidence})}return n}function ne(e,t){let n=typeof e=="string"?ye(e,t):J(e,t);return{...n,policyHash:P(L(n.config))}}function Ve(e){let t=ne(e.baseConfig,e.baseSource??"base ark.config.json"),n=ne(e.candidateConfig,e.candidateSource??"candidate ark.config.json"),r=be(t.config,n.config),i=r.findings.filter(c=>c.classification==="weakening"||c.classification==="judgment-required").map(c=>c.id).sort(),a=i.length>0,s=a&&Ce(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:i});return{schemaVersion:r.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:r.classification,findings:r.findings,blockingFindingIds:i,requiresAcknowledgement:a,acknowledged:s,valid:!a||s}}function U(e){let t=e.files.map(c=>{let p=D(c.path);return{path:p,content:c.content,contentHash:P(c.content),layer:Y(p,e.contract.config.layers)??null}}).sort((c,p)=>c.path.localeCompare(p.path)),n=new Map(t.map(c=>[c.path,c])),r=[],i=[];for(let c of t){let p=pt(c,n);r.push(...p.edges),i.push(...p.capabilityUses)}let a=dt(r,e.contract.config),s=new Map(e.contract.config.layers.map(c=>[c.name,new Set(ce(c))]));for(let c of i){let p=n.get(c.file)?.layer;!p||!s.get(p)?.has(c.capability)||a.push({ruleId:"CAPABILITY_VIOLATION",message:`${p} denies the ${c.capability} capability; found import of "${c.symbol}".`,capability:c.capability,symbol:c.symbol,evidence:c.evidence})}return{ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:P(L(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(c=>c.name),edges:r,capabilityUses:i,violations:a}}}function re(e){let t=new Map(e.files.map(n=>[D(n.path),n]));for(let n of e.changes){let r=D(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return U({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}function Ge(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 Ie(e){let t=0,n=new Map,r=new Map,i=new Set,a=[],s=[],c=p=>{n.set(p,t),r.set(p,t),t+=1,a.push(p),i.add(p);for(let m of[...e.get(p)??[]].sort())e.has(m)&&(n.has(m)?i.has(m)&&r.set(p,Math.min(r.get(p)??0,n.get(m)??0)):(c(m),r.set(p,Math.min(r.get(p)??0,r.get(m)??0))));if(r.get(p)!==n.get(p))return;let y=[],u;do{if(u=a.pop(),u===void 0)break;i.delete(u),y.push(u)}while(u!==p);y.length>1&&s.push(y.sort())};for(let p of[...e.keys()].sort())n.has(p)||c(p);return s.sort((p,y)=>p[0].localeCompare(y[0])).map(p=>({ruleId:"CIRCULAR_DEPENDENCY",file:p[0],line:1,target:p.join(" \u2192 "),message:`Circular dependency among ${p.length} files: ${p.join(" \u2192 ")} \u2192 ${p[0]}.`,cycleKind:"value"}))}function ie(e){let t=e.contentViolations.map(a=>({...a})),n=(e.warnings??[]).map(a=>({...a})),r=new Map(e.files.map(a=>[a,new Set]));for(let a of e.edges){if(a.to&&a.to!==a.from&&!a.typeOnly&&r.has(a.from)&&r.get(a.from)?.add(a.to),!a.to||!a.toLayer)continue;let s=v(e.rules,a.fromLayer,a.toLayer,{fromPath:a.from,toPath:a.to,layers:e.config.layers});if(!s)continue;let c=!!s.peerIsolation;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:a.from,line:a.line,fromLayer:a.fromLayer,toLayer:a.toLayer,target:a.to,...a.typeOnly?{typeOnly:!0}:{},...a.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...a.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...a.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!c&&a.portProofEligible?{portProofEligible:!0}:{},...a.kind?{edgeKind:a.kind}:{},...c?{peerIsolation:!0}:{},message:s.message??(c?`${a.fromLayer} must not ${a.kind} another slice of ${a.toLayer} (${a.from} \u2192 ${a.to}). Extract shared code or use events/ports across slices.`:`${a.fromLayer} must not ${a.kind} ${a.toLayer}.`)})}let i=String(e.config.cyclePolicy??"strict").toLowerCase();if(i!=="off"){let a=Ie(r);i==="soft"||i==="framework-soft"?n.push(...a.map(s=>({...s,message:`${s.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...a)}return{violations:t,warnings:n,safety:e.safety}}function ft(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 ut(e){return P(L(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}function He(e){let t=U(e),n=new Map(t.ir.files.map(o=>[o.path,o])),r=[],i=new Set,a=[];for(let o of e.changes){let g=o.path.replace(/\\/g,"/"),f=D(o.path);if(!f||f===".."||f.startsWith("../")||g.startsWith("/")||/^[A-Za-z]:\//.test(g)||g.includes("\0")){a.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(i.has(f)){a.push({ruleId:"DUPLICATE_CHANGE_PATH",file:f,line:1,message:`The atomic change set contains more than one operation for ${f}.`});continue}i.add(f),"delete"in o&&o.delete&&!n.has(f)&&a.push({ruleId:"DELETE_TARGET_MISSING",file:f,line:1,message:`Cannot delete ${f} because it is not present in the supplied base tree.`}),r.push("delete"in o&&o.delete?{path:f,delete:!0}:{path:f,content:"content"in o?o.content:""})}e.changes.length===0&&a.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let s=re({...e,changes:r}),c=new Map(s.ir.files.map(o=>[o.path,o])),p=s.ir.violations.filter(o=>o.ruleId==="CAPABILITY_VIOLATION").map(o=>({ruleId:o.ruleId,file:o.evidence.file,line:o.evidence.line,target:o.symbol,capability:o.capability,message:o.message})),y=ie({config:e.contract.config,rules:e.contract.config.rules,files:s.ir.files.map(o=>o.path),contentViolations:p,edges:s.ir.edges.filter(o=>!!o.fromLayer).map(o=>({from:o.from,fromLayer:o.fromLayer,...o.to?{to:o.to}:{},...o.toLayer?{toLayer:o.toLayer}:{},line:o.evidence.line,kind:"import"}))}),u=r.map(o=>{let g=D(o.path),f=n.get(g),I=c.get(g);return{path:g,operation:"delete"in o&&o.delete?"delete":f?"update":"create",...f?{beforeContentHash:f.contentHash}:{},...I?{candidateContentHash:I.contentHash}:{}}}).sort((o,g)=>o.path.localeCompare(g.path)),m=[...a,...y.violations].map(o=>({...o,nextAction:ft(o)})),l=e.changeMap?ee({changeMap:e.changeMap,changes:u,baseDependencies:t.ir.edges.flatMap(o=>o.to?[{from:o.from,to:o.to}]:[]),candidateDependencies:s.ir.edges.flatMap(o=>o.to?[{from:o.from,to:o.to}]:[])}):void 0;return{schemaVersion:"1.0",valid:m.length===0&&(l?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:s.ir.compilerOptionsHash,baseTreeHash:ut(t.ir.files),candidateTreeHash:ut(s.ir.files),...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...l?{convergence:l}:{},changes:u,violations:m,warnings:y.warnings}}function S(e,t,n={}){return{ruleId:e,message:t,...n}}function Ue(e){let{config:t,rules:n,files:r,manifest:i}=e,a=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(o=>typeof o!="string"))&&a.push(S("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)))a.push(S("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let o of["maxTsSuppressions","maxAnyCasts"]){let g=t.safety[o];g!==void 0&&(!Number.isInteger(g)||g<0)&&a.push(S("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${o} must be a non-negative integer.`))}let s=Array.isArray(t.layers)?t.layers:[],c=Array.isArray(i?.architecture?.layers)?i.architecture.layers:[],p=new Set([...s.map(o=>o.name).filter(Boolean),...c.map(o=>o.name).filter(o=>!!o)]);s.length===0&&a.push(S("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let y=new Set,u=new Set;for(let o of s){if(!o.name){a.push(S("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}y.has(o.name)&&u.add(o.name),y.add(o.name),o.forbiddenGlobals!==void 0&&(!Array.isArray(o.forbiddenGlobals)||o.forbiddenGlobals.some(f=>typeof f!="string"))&&a.push(S("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${o.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:o.name}));let g=Array.isArray(o.patterns)?o.patterns:[];if(g.length===0){a.push(S("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${o.name}" has no file patterns and will never classify files.`,{layer:o.name}));continue}for(let f of g){let I;try{I=z(f)}catch(x){a.push(S("CONFIG_INVALID_LAYER_PATTERN",`Layer "${o.name}" has an invalid pattern "${f}": ${x instanceof Error?x.message:String(x)}`,{layer:o.name,pattern:f}));continue}!r.some(x=>I.test(x))&&!o.optional&&a.push(S("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${o.name}" pattern "${f}" matched no included files.`,{layer:o.name,pattern:f,failsStrict:!1}))}}for(let o of u)a.push(S("CONFIG_DUPLICATE_LAYER",`Layer "${o}" is configured more than once.`,{layer:o}));if(p.size>0)for(let o of n??[])o.from&&!p.has(o.from)&&a.push(S("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${o.from}".`,{fromLayer:o.from,toLayer:o.to})),o.to&&!p.has(o.to)&&a.push(S("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${o.to}".`,{fromLayer:o.from,toLayer:o.to}));let m=new Set;if(s.length>1)for(let o of r){let g=-1,f=[];for(let I of s)for(let x of I.patterns??[]){if(!z(x).test(o))continue;let d=Re(x);d>g?(g=d,f=[I.name]):d===g&&!f.includes(I.name)&&f.push(I.name)}f.length>1&&m.add([...f].sort().join(" + "))}m.size>0&&a.push(S("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...m].join(", ")}.`,{pairs:[...m]}));let l=r.filter(o=>!Y(o,s));return l.length>0&&a.push(S("CONFIG_UNCLASSIFIED_FILES",`${l.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:l.length,samples:l.slice(0,5)})),a}0&&(module.exports={ANALYSIS_IR_SCHEMA_VERSION,ARK_ANALYSIS_RESULT_SCHEMA,ARK_ANALYSIS_RESULT_SCHEMA_VERSION,ARK_CONFIG_SCHEMA,ARK_CONFIG_SCHEMA_VERSION,POLICY_DELTA_SCHEMA_VERSION,analyzeArchitectureConvergence,analyzeChange,analyzePolicyDelta,analyzeProject,classifyArkPolicyDelta,collectAnalysisConfigWarnings,collectForbiddenCapabilityUses,createAICodeGate,createAdapterResult,createArchitectureProfile,createArchitectureProfileFromArkConfig,createElevenLayerArkConfig,detectArchitectureCycles,deterministicHash,elevenLayerProfile,evaluateArchitectureGraph,explainViolation,extractSemanticDependencies,loadArkConfigContract,loadContract,parseArkConfigJson,policyDeltaAcknowledgementMatches,preflightChange,stableSerialize,toAdapterDiagnostic,version});
|