arkgate 3.3.0 → 3.5.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 +75 -0
- package/README.md +4 -3
- package/bin/ark-check.mjs +3 -1
- 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 -6
- package/bin/lib/architecture-scan.mjs +31 -0
- package/bin/lib/config-contract.mjs +25 -0
- package/bin/lib/contract-smells.mjs +154 -18
- package/bin/lib/doctor-advisories.mjs +20 -0
- package/bin/lib/doctor-plan.mjs +5 -5
- package/bin/lib/html-report-advisories.mjs +149 -0
- package/bin/lib/html-report.mjs +6 -0
- 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-CVWWhBoe.d.cts → configTypes-DAPvBqK6.d.cts} +7 -0
- package/dist/{configTypes-CVWWhBoe.d.ts → configTypes-DAPvBqK6.d.ts} +7 -0
- package/dist/eslint/index.cjs +2 -2
- package/dist/eslint/index.d.cts +3 -2
- package/dist/eslint/index.d.ts +3 -2
- package/dist/eslint/index.js +2 -2
- package/dist/index.cjs +7 -7
- package/dist/index.d.cts +32 -2
- package/dist/index.d.ts +32 -2
- package/dist/index.js +6 -6
- package/docs/agent-guide.md +21 -5
- package/docs/configuration.md +3 -0
- package/docs/package-surface.md +7 -3
- package/package.json +3 -2
- package/schemas/ark.config.schema.json +25 -0
- package/server.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
"use strict";var Ce=Object.defineProperty;var st=Object.getOwnPropertyDescriptor;var ct=Object.getOwnPropertyNames;var lt=Object.prototype.hasOwnProperty;var pt=(e,t)=>{for(var n in t)Ce(e,n,{get:t[n],enumerable:!0})},dt=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of ct(t))!lt.call(e,r)&&r!==n&&Ce(e,r,{get:()=>t[r],enumerable:!(i=st(t,r))||i.enumerable});return e};var ft=e=>dt(Ce({},"__esModule",{value:!0}),e);var Qt={};pt(Qt,{ANALYSIS_IR_SCHEMA_VERSION:()=>pe,ARK_ANALYSIS_RESULT_SCHEMA:()=>je,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>De,ARK_CONFIG_SCHEMA:()=>se,ARK_CONFIG_SCHEMA_VERSION:()=>Je,POLICY_DELTA_SCHEMA_VERSION:()=>et,analyzeArchitectureConvergence:()=>X,analyzeChange:()=>te,analyzePolicyDelta:()=>$e,analyzeProject:()=>U,classifyArkPolicyDelta:()=>ye,collectAnalysisConfigWarnings:()=>Ne,collectForbiddenCapabilityUses:()=>D,createAICodeGate:()=>we,createAdapterResult:()=>Fe,createArchitectureProfile:()=>Z,createArchitectureProfileFromArkConfig:()=>Pe,createElevenLayerArkConfig:()=>Re,detectArchitectureCycles:()=>he,deterministicHash:()=>L,elevenLayerProfile:()=>J,evaluateArchitectureGraph:()=>ne,explainViolation:()=>ve,extractSemanticDependencies:()=>T,loadArkConfigContract:()=>W,loadContract:()=>ee,parseArkConfigJson:()=>le,policyDeltaAcknowledgementMatches:()=>ge,preflightChange:()=>_e,stableSerialize:()=>w,toAdapterDiagnostic:()=>ie,version:()=>Me});module.exports=ft(Qt);var Me="3.3.0";var De="1.1";function E(e){return typeof e=="string"&&e.length>0?e:void 0}function Te(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function ut(e,t,n){return e==="LAYER_IMPORT_VIOLATION"?t.typeOnly||n.targetTypeOnlyExports===!0||n.namedBindingsTypeOnly===!0?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":n.peerIsolation===!0?"Extract the shared dependency to a shared layer, then preflight again.":`Define a port in ${t.fromLayer??"the source layer"}, inject the ${t.toLayer??"outer-layer"} implementation, then preflight again.`:e==="FORBIDDEN_GLOBAL"?`Inject ${t.target??"the capability"} through a port, then preflight again.`:e==="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 ie(e,t="error"){let n=E(e.ruleId)??E(e.code)??"ARK_UNKNOWN",i=e.severity==="warning"?"warning":t,r={...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:i,message:E(e.message)??n,location:{file:E(e.file)??"<unknown>",line:Te(e.line,1),column:Te(e.column,1)},evidence:r,nextAction:E(e.nextAction)??ut(n,r,e)}}function Fe(e){return{schemaVersion:"1.1",valid:e.valid,diagnostics:[...(e.violations??[]).map(t=>ie(t,"error")),...(e.warnings??[]).map(t=>ie(t,"warning"))]}}var je={$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 Ve=new Map;function He(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function be(e){let t="";for(let n=0;n<e.length;n+=1){let i=e[n];if(i==="\\"&&n+1<e.length){let r=e[n+1];if("*?{}[],".includes(r)||r==="\\"){t+="\\"+r,n+=1;continue}t+="/";continue}t+=i}return t}function yt(e){let t=0;for(let n=0;n<e.length;n+=1){let i=e[n];if(i==="\\"){n+=1;continue}if(i==="{")t+=1;else if(i==="}"&&(t-=1,t<0))return!1}return t===0}function z(e){let t=Ve.get(e);if(t)return t;let n=be(e),i=yt(n),r="",a=0;for(let c=0;c<n.length;c+=1){let p=n[c];p==="\\"&&c+1<n.length?(r+=He(n[c+1]),c+=1):p==="*"?n[c+1]==="*"?n[c+2]==="/"?(r+="(?:.*/)?",c+=2):(r+=".*",c+=1):r+="[^/]*":p==="?"?r+="[^/]":p==="{"&&i?(r+="(?:",a+=1):p==="}"&&i&&a>0?(r+=")",a-=1):p===","&&i&&a>0?r+="|":r+=He(p)}let s=new RegExp(`^${r}$`);return Ve.set(e,s),s}function Ie(e){let t=be(String(e)),i=t.split("*")[0].split("/").filter(Boolean).length,r=t.replace(/\*/g,"").length;return i*1e4+r}function B(e,t){let n=String(e).split(/[/\\]/).join("/"),i,r=-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=Ie(s);c>r&&(r=c,i=a.name)}}return i}function Ge(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),i=new Set(t.map(r=>String(r).toLowerCase()));for(let r=0;r<n.length-1;r+=1)if(i.has(n[r].toLowerCase()))return`${n[r]}/${n[r+1]}`}function gt(e){let t=new Set;for(let n of e??[]){let r=be(String(n)).split("/").filter(Boolean);for(let a=0;a<r.length;a+=1){let s=r[a];if((s==="**"||s==="*")&&a>0){let c=r[a-1];c&&!c.includes("*")&&!c.includes("{")&&!c.includes("}")&&t.add(c)}}}return[...t]}function mt(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(r=>typeof r=="string"&&r.length>0);let i=(n??[]).find(r=>r.name===t);return gt(i?.patterns)}function $(e,t,n,i){for(let r of e??[])if(!(r.from!==t||r.to!==n)&&r.allowed===!1){if(r.peerIsolation){let a=i?.fromPath,s=i?.toPath;if(!a||!s)continue;let c=mt(r,t,i?.layers);if(c.length===0)continue;let p=Ge(a,c),u=Ge(s,c);if(!p||!u)continue;if(p!==u)return r;continue}if(t!==n)return r}}var xe={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 v(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function Se(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&v(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:xe.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:xe.PUBLISH_MISSING_SOURCE}),t}function M(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function Be(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function Ue(e,t){if(e.isImportDeclaration(t)){let n=t.importClause;if(!n)return!1;if(n.isTypeOnly)return!0;let i=n.namedBindings;return!!(i&&e.isNamedImports(i)&&i.elements.length>0&&i.elements.every(r=>r.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(i=>i.isTypeOnly))}return!1}function Ke(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},i=e.createCompilerHost(n,!0);return i.getSourceFile=r=>r===t.fileName?t:void 0,i.fileExists=r=>r===t.fileName,i.readFile=r=>r===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,i).getTypeChecker()}function ke(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function Ee(e,t,n,i){let r=i.parent&&e.isShorthandPropertyAssignment(i.parent)&&i.parent.name===i,a;try{a=r?t.getShorthandAssignmentValueSymbol(i.parent):ke(t,i)}catch{a=void 0}return!!a?.declarations?.some(s=>s.getSourceFile().fileName===n.fileName)}function T(e,t){let n,i=[],r=(s,c,p,u=!1)=>i.push({specifier:p,kind:c,line:Be(t,s),typeOnly:u,unresolved:p===void 0,node:s}),a=s=>{if(e.isImportDeclaration(s))r(s,"import",M(e,s.moduleSpecifier),Ue(e,s));else if(e.isExportDeclaration(s)&&s.moduleSpecifier)r(s,"export",M(e,s.moduleSpecifier),Ue(e,s));else if(e.isImportEqualsDeclaration(s)&&e.isExternalModuleReference(s.moduleReference))r(s,"require",M(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"&&!Ee(e,n??(n=Ke(e,t)),t,s.expression);(c||u)&&r(s,u?"require":"dynamic-import",M(e,s.arguments[0]))}e.forEachChild(s,a)};return a(t),i}function ht(e,t){let n=[],i=t;for(;e.isPropertyAccessExpression(i)||e.isElementAccessExpression(i);){if(e.isPropertyAccessExpression(i))n.unshift(i.name.text);else{let r=M(e,i.argumentExpression);if(r===void 0)return;n.unshift(r)}i=i.expression}if(e.isIdentifier(i))return n.unshift(i.text),{root:i,segments:n}}function At(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 ze(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let i=n.length;i>=1;i-=1){let r=n.slice(0,i).join(".");if(e.has(r))return r}}function D(e,t,n){if(n.length===0)return[];let i=new Set(n),r=Ke(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=ht(e,o);if(!l)return;let f=ke(r,l.root),g=f?a.get(f):void 0;return g?[...g,...l.segments.slice(1)]:Ee(e,r,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),g=ke(r,l.name);!f||!g||a.set(g,f)}let p=[],u=new Set,y=(o,l)=>{let f=Be(t,l),g=`${o}:${l.getStart(t)}`;u.has(g)||(u.add(g),p.push({name:o,line:f,node:l}))},m=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),g=f?ze(i,f):void 0;g&&y(g,o)}else e.isIdentifier(o)&&i.has(o.text)&&At(e,o)&&!Ee(e,r,t,o)&&y(o.text,o);if(e.isVariableDeclaration(o)&&e.isObjectBindingPattern(o.name)&&o.initializer){let f=c(o.initializer);if(f)for(let g of o.name.elements){if(!e.isIdentifier(g.name))continue;let k=g.propertyName?M(e,g.propertyName)??g.propertyName.text:g.name.text,b=ze(i,[...f,k]);b&&y(b,o.initializer)}}e.forEachChild(o,m)};return m(t),p}function A(e,t,n){return{ruleId:e,code:e,message:t,...n}}function F(e,t){return e.slice(0,t).split(`
|
|
2
|
-
`).length}function Ct(e){let t=[],n=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,i;for(;(i=n.exec(e))!==null;)t.push({value:i[1],index:i.index});return t}function bt(e){let t=[],n=[{kind:"import",re:/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s*)?['"]([^'"]+)['"]/g},{kind:"export",re:/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s*['"]([^'"]+)['"]/g},{kind:"dynamic-import",re:/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g},{kind:"require",re:/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g}];for(let i of n){let r;for(;(r=i.re.exec(e))!==null;){let a=r.index+r[0].indexOf(r[1]),s=r[0],c=i.kind==="import"&&/\bimport\s+type\b/.test(s)||i.kind==="export"&&/\bexport\s+type\b/.test(s);t.push({value:r[1],index:a,kind:i.kind,typeOnly:c})}}return t.sort((i,r)=>i.index-r.index)}function It(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),i=[],r=a=>{e.isStringLiteralLike(a)&&i.push({value:a.text,index:a.getStart(n)}),e.forEachChild(a,r)};return r(n),i}function xt(e){let t=e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);return["adapter","adapters","infra","infrastructure","persistence","repository","repositories","integration","database","db"].some(n=>t.includes(n))}function St(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}function kt(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}function Y(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function Et(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}function Ye(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(i=>!e.isPropertyAssignment(i)&&!e.isShorthandPropertyAssignment(i)?!1:Et(e,i.name)===n)}function q(e,t,n){return Ye(e,t,n)!==void 0}function K(e,t,n){let i=Ye(e,t,n);return i&&e.isPropertyAssignment(i)?i.initializer:void 0}function wt(e,t){let n=K(e,t,"metadata");return q(e,n,"source")}function qe(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?qe(e,t.name):!1:!1}function Lt(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 Pt(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],i=Y(e,n);return i!==void 0&&v(i)||q(e,n,"intent")||qe(e,n)}function Rt(e,t){if(!e.isCallExpression(t))return!1;let[n,i,r]=t.arguments;return wt(e,n)||q(e,i,"source")||q(e,r,"source")}function Ot(e,t){if(!e.isCallExpression(t))return;let[n,i,r]=t.arguments,a=K(e,n,"metadata");return Y(e,K(e,a,"source"))??Y(e,K(e,i,"source"))??Y(e,K(e,r,"source"))}function $t(e,t,n,i){let r=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),a=n,s=a?.filePath,c=a?.layer,p=[],u=m=>r.getLineAndCharacterOfPosition(m.getStart(r)).line+1,y=m=>{if(Lt(e,m)){let o=m.arguments[0],l=Y(e,o);for(let g of Se({publishCall:!0,rawIntentName:l,objectHasIntent:q(e,o,"intent"),arkPublishCandidate:Pt(e,m),hasSource:Rt(e,m)}))p.push(A(g.ruleId,g.message,{line:u(m),filePath:s}));let f=Ot(e,m);if(i&&c&&f&&v(f)){let g=i.resolveLayer(f);g&&g!==c&&p.push(A("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${f}" resolves to ${g}, but the target file is classified as ${c}.`,{line:u(m),filePath:s,target:f,fromLayer:c,toLayer:g}))}}e.forEachChild(m,y)};return y(r),p}function we(e={}){let t=new Set((e.intents||[]).map(a=>typeof a=="string"?a:a.name)),n=e.forbiddenPatterns||[],i=new Set(e.infrastructureLayers??[]),r=e.enforceIntentAllowlist??t.size>0;return{validate(a,s){let c=[],p=s,u=p?.filePath,y=p?.layer,m=e.typescript,o=m?m.createSourceFile(u??"generated.ts",a,m.ScriptTarget.Latest,!0):void 0,l=o?T(e.typescript,o):void 0,f=l?l.filter(d=>d.specifier!==void 0).map(d=>({value:d.specifier,index:d.node.getStart(o),kind:d.kind,typeOnly:d.typeOnly})):bt(a),g=e.typescript?It(e.typescript,a):Ct(a);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(u))for(let d of l?.filter(({unresolved:h})=>h)??[]){let h=d.kind==="require";c.push(A(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:u}))}let k=y!==void 0&&(i.has(y)||kt(y)),b=y!==void 0?` If "${y}" 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(A("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${d}`,{line:h.index===void 0?void 0:F(a,h.index),filePath:u,suggestion:"Remove infrastructure imports from domain/application layers."+b}))}else a.includes(d)&&c.push(A("FORBIDDEN_SUBSTRING",`Forbidden substring: ${d}`,{line:F(a,a.indexOf(d)),filePath:u}));for(let d of f){let h=e.resolveImportTarget?.(d.value,u)??(e.resolveImportLayer?{layer:e.resolveImportLayer(d.value,u)}:void 0),O=typeof u=="string"?e.resolveImportTarget?.(u)??(e.resolveImportLayer?{layer:y,relPath:void 0}:void 0):void 0,N=h?.layer;if(N&&y){let re=$(e.architectureProfile?.rules,y,N,{fromPath:O?.relPath,toPath:h?.relPath,layers:e.architectureLayers});if(re){if(d.typeOnly&&!re.peerIsolation)continue;let Ae=!!re.peerIsolation;c.push(A("LAYER_IMPORT_VIOLATION",re.message??(Ae?`Layer "${y}" must not import across slices into "${N}".`:`Layer "${y}" must not import "${N}".`),{line:F(a,d.index),source:d.value,target:d.value,filePath:u,fromLayer:y,toLayer:N,suggestion:Ae?"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:Ae,...d.typeOnly?{typeOnly:!0}:{}}}));continue}if(N!==y)continue}k||d.typeOnly||!xt(d.value)&&!St(d.value)||c.push(A("FORBIDDEN_IMPORT",`Forbidden ${d.kind} target: "${d.value}".`,{line:F(a,d.index),source:d.value,target:d.value,filePath:u,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+b,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 O of h)c.push(A("POLICY_VIOLATION",O.message,{filePath:u,suggestion:`Fix violation of policy "${d.name}".`}));else h===!1?c.push(A("POLICY_VIOLATION",`Policy ${d.name} failed on generated code`)):c.push(A("POLICY_VIOLATION",h.message))}if(r&&t.size>0)for(let d of g)v(d.value)&&!t.has(d.value)&&c.push(A("UNKNOWN_INTENT",`Unknown intent reference: "${d.value}"`,{line:F(a,d.index),filePath:u,target:d.value,suggestion:`Register intent "${d.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&y)for(let d of g){if(!v(d.value))continue;let h=e.architectureProfile.resolveLayer(d.value);if(!h)continue;let O=$(e.architectureProfile.rules,y,h);O&&c.push(A("LAYER_REFERENCE_VIOLATION",O.message??`Layer "${y}" must not reference "${h}" through "${d.value}".`,{line:F(a,d.index),filePath:u,target:d.value,fromLayer:y,toLayer:h,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:O}}))}if(e.extensions)for(let d of e.extensions)try{let h=d.analyze(a,s);c.push(...h)}catch(h){c.push(A("EXTENSION_ERROR",`Extension "${d.name}" failed: ${h instanceof Error?h.message:String(h)}`))}if(e.typescript&&o&&y&&e.forbiddenGlobals?.[y]?.length)try{c.push(...D(e.typescript,o,e.forbiddenGlobals[y]).map(d=>A("FORBIDDEN_GLOBAL",`${y} must not use the ambient global "${d.name}".`,{line:d.line,filePath:u,target:d.name,fromLayer:y,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(A("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${d instanceof Error?d.message:String(d)}`))}if(e.typescript)try{c.push(...$t(e.typescript,a,s,e.architectureProfile))}catch(d){c.push(A("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${d instanceof Error?d.message:String(d)}`))}return{valid:c.length===0,violations:c}}}}var Je="1.0",oe="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",We=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],vt=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function _t(){let e=[];for(let t of We)for(let n of We)t===n||vt.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var ce=_t();var P={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},se={$schema:"https://json-schema.org/draft/2020-12/schema",$id:oe,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:oe,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:{...P,minItems:1,default:["src"]},exclude:{...P,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:ce,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...P,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:{...P,minItems:1},exclude:P,intentPrefixes:P,description:{type:"string",minLength:1},forbiddenGlobals:P,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:{...P,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}}}}},V=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
|
|
3
|
-
${n.map(
|
|
4
|
-
`)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function Ze(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Le(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function j(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Nt(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function ae(e,t,n,i,r){if(t.$ref){let a=Nt(t.$ref,i);if(!a){r.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}ae(e,a,n,i,r);return}if(t.const!==void 0&&!Object.is(e,t.const)){r.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(a=>Object.is(a,e))){r.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!Ze(e)){r.push({path:n,message:`must be an object; received ${j(e)}`});return}let a=t.properties??{};for(let s of t.required??[])e[s]===void 0&&r.push({path:Le(n,s),message:"is required"});if(t.additionalProperties===!1)for(let s of Object.keys(e))s in a||r.push({path:Le(n,s),message:"unknown field"});for(let[s,c]of Object.entries(a))e[s]!==void 0&&ae(e[s],c,Le(n,s),i,r);return}if(t.type==="array"){if(!Array.isArray(e)){r.push({path:n,message:`must be an array; received ${j(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&r.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let a=e.map(s=>JSON.stringify(s));new Set(a).size!==a.length&&r.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((a,s)=>ae(a,t.items,`${n}[${s}]`,i,r));return}if(t.type==="string"){if(typeof e!="string"){r.push({path:n,message:`must be a string; received ${j(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&r.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&r.push({path:n,message:`must be a boolean; received ${j(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){r.push({path:n,message:`must be an integer; received ${j(e)}`});return}t.minimum!==void 0&&e<t.minimum&&r.push({path:n,message:`must be at least ${t.minimum}`})}}function Mt(e){return{...e,$schema:e.$schema===void 0?oe: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?ce.map(t=>({...t})):e.rules}}function Tt(e,t="ark.config.json"){if(!Ze(e))throw new V(t,[{path:"$",message:`must be an object; received ${j(e)}`}]);let n=e.schemaVersion===void 0?"unversioned":null;if(e.schemaVersion!==void 0&&e.schemaVersion!=="1.0")throw new V(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.0`}]);return{candidate:Mt(e),migratedFrom:n}}function W(e,t="ark.config.json"){let{candidate:n,migratedFrom:i}=Tt(e,t),r=[];if(ae(n,se,"$",se,r),r.length>0)throw new V(t,r);return{config:n,migratedFrom:i}}function le(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(i){throw new V(t,[{path:"$",message:`invalid JSON: ${i instanceof Error?i.message:String(i)}`}])}return W(n,t)}function Qe(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:oe,schemaVersion:"1.0"};for(let[n,i]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=i);return t}function Dt(e){return e.endsWith(".")?e:`${e}.`}function Ft(e,t){let n=e.prefixes.length?Math.max(...e.prefixes.map(r=>r.length)):0;return(t.prefixes.length?Math.max(...t.prefixes.map(r=>r.length)):0)-n}function Z(e){let t=e.layers.map(r=>({...r,prefixes:r.prefixes.map(Dt)})),n=[...t].sort(Ft),i=[...e.rules??[]];return{name:e.name,layers:t,rules:i,resolveLayer(r){return t.find(a=>a.match?.(r))?.name??n.find(a=>a.prefixes.some(s=>r.startsWith(s)))?.name}}}function Pe(e,t={}){return Z({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,i)=>({name:n.name,prefixes:n.intentPrefixes??[],description:n.description,order:i+1})),rules:e.rules??[]})}var jt=[{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}],J=Z({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:jt,rules:ce.map(e=>({...e}))}),Vt={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 Re(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,i=t==="."?"":`${t}/`;return Qe({include:e.include??[t],layers:J.layers.map(r=>({name:r.name,patterns:(Vt[r.name]??[r.name]).map(a=>`${i}${a}/**`),intentPrefixes:r.prefixes,optional:n})),rules:[...J.rules]})}var pe="1.0";function L(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 w(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(w).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${w(t[n])}`).join(",")}}`}function x(e){return`${e.from}->${e.to}`}function Q(e,t,n,i="dependency"){return{id:`${e}:${i}:${x(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${x(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${x(t)}, then preflight again.`}:e==="unplanned"?{nextAction:`Remove the unplanned dependency ${x(t)} from the candidate, then preflight again.`}:{}}}function X(e){let t=[],n=new Map(e.changeMap.map.files.map(o=>[o.path,o])),i=new Map(e.changes.map(o=>[o.path,o])),r=new Map(e.changeMap.map.dependencies.map(o=>[x(o),o])),a=new Map(e.baseDependencies.map(o=>[x(o),o])),s=new Map(e.candidateDependencies.map(o=>[x(o),o]));for(let o of[...n.values()].sort((l,f)=>l.path.localeCompare(f.path))){let l=i.get(o.path);l?l.operation!==o.operation?t.push({id:`contradictory:file:${o.path}`,classification:"contradictory",subject:"file",path:o.path,expectedOperation:o.operation,actualOperation:l.operation,message:`${o.path} was planned as ${o.operation} but the actual operation is ${l.operation}.`,nextAction:`Change ${o.path} to the planned ${o.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${o.path}`,classification:"satisfied",subject:"file",path:o.path,expectedOperation:o.operation,actualOperation:l.operation,message:`${o.path} matches the planned ${o.operation} operation.`}):t.push({id:`missing:file:${o.path}`,classification:"missing",subject:"file",path:o.path,expectedOperation:o.operation,message:`${o.path} was planned as ${o.operation} but is absent from the actual change.`,nextAction:`${o.operation[0].toUpperCase()}${o.operation.slice(1)} ${o.path} in the complete change set, then preflight again.`})}for(let o of[...i.values()].sort((l,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[...r.values()].sort((l,f)=>x(l).localeCompare(x(f)))){if(s.has(x(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(x(l))?(c.add(x(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 p=new Set([...n.keys(),...i.keys()]);for(let[o,l]of[...s].sort(([f],[g])=>f.localeCompare(g)))a.has(o)||r.has(o)||c.has(o)||!p.has(l.from)&&!p.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],[g])=>f.localeCompare(g)))s.has(o)||u.has(l.from)||u.has(l.to)||!p.has(l.from)&&!p.has(l.to)||t.push({...Q("unplanned",l,`${l.from} -> ${l.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let y={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((o,l)=>y[o.classification]-y[l.classification]||(o.subject===l.subject?0:o.subject==="file"?-1:1)||o.id.localeCompare(l.id));let m={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:m.missing===0&&m.contradictory===0&&m.unplanned===0,behavioralCompletion:"not-evaluated",summary:m,findings:t}}var Ht=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),Gt=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Xe=Object.freeze(Object.keys(Gt).sort()),Oe=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 de(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=Oe[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let i=e.slice(0,n),r=Oe[i];if(r)return r;let a=e.indexOf("/",n+1);return a<0?null:Oe[e.slice(0,a)]??null}var et="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 S(e){return[...new Set(e??[])].sort()}function H(e,t,n,i,r){let a=S(n),s=S(i),c=new Set(a),p=new Set(s),u=s.filter(m=>!c.has(m)),y=a.filter(m=>!p.has(m));u.length===0&&y.length===0||(u.length>0&&C(e,{kind:"added",path:t,classification:r.added,message:r.addedMessage,before:a,after:s}),y.length>0&&C(e,{kind:"removed",path:t,classification:r.removed,message:r.removedMessage,before:a,after:s}))}function fe(e,t,n,i,r,a,s){if(n===i)return;C(e,{kind:i?"enabled":"disabled",path:t,classification:i?r:r==="strengthening"?"weakening":"strengthening",message:i?a:s,before:n,after:i})}function ue(e,t){let n=new Map,i=new Set;for(let r of e){let a=t(r);n.has(a)?i.add(a):n.set(a,r)}return{values:n,duplicates:[...i].sort()}}function zt(e,t,n){let i=ue(t,a=>a.name),r=ue(n,a=>a.name);(i.duplicates.length>0||r.duplicates.length>0)&&C(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:i.duplicates,after:r.duplicates});for(let a of[...new Set([...i.values.keys(),...r.values.keys()])].sort()){let s=i.values.get(a),c=r.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}!s||!c||(H(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."}),H(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."}),H(e,`${p}.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."}),S(s.intentPrefixes).join("\0")!==S(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:S(s.intentPrefixes),after:S(c.intentPrefixes)}),fe(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."),fe(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 Bt(e,t,n){let i=s=>`${s.from}->${s.to}`,r=ue(t,i),a=ue(n,i);(r.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:r.duplicates,after:a.duplicates});for(let s of[...new Set([...r.values.keys(),...a.values.keys()])].sort()){let c=r.values.get(s),p=a.values.get(s),u=`$.rules[${s}]`;if(!c&&p){p.allowed===!1&&C(e,{kind:"deny-added",path:u,classification:"strengthening",message:"A denied dependency edge was added.",after:p});continue}if(c&&!p){c.allowed===!1&&C(e,{kind:"deny-removed",path:u,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:`${u}.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 y=c.peerIsolation===!0,m=p.peerIsolation===!0;if(y!==m){let o=c.from===c.to&&p.from===p.to;C(e,{kind:m?"peer-isolation-enabled":"peer-isolation-disabled",path:`${u}.peerIsolation`,classification:o?m?"strengthening":"weakening":"judgment-required",message:o?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:y,after:m})}S(c.sliceFolders).join("\0")!==S(p.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:S(c.sliceFolders),after:S(p.sliceFolders)})}}function Kt(e,t,n){let i=t.safety??{},r=n.safety??{};for(let a of["maxTsSuppressions","maxAnyCasts"]){let s=i[a]??0,c=r[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"])fe(e,`$.safety.${a}`,i[a]===!0,r[a]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}function Yt(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 ye(e,t){let n=[];H(n,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),H(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."}),H(n,"$.dynamicImportAllowlist",e.dynamicImportAllowlist,t.dynamicImportAllowlist,{added:"weakening",removed:"strengthening",addedMessage:"Additional files may use non-literal dynamic imports.",removedMessage:"Fewer files may use non-literal dynamic imports."}),fe(n,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let i={off:0,soft:1,"framework-soft":1,strict:2},r=e.cyclePolicy??"strict",a=t.cyclePolicy??"strict";if(r!==a){let s=i[a]===i[r]?"judgment-required":i[a]>i[r]?"strengthening":"weakening";C(n,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:s,message:"The cycle enforcement level changed.",before:r,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}),zt(n,e.layers,t.layers),Bt(n,e.rules,t.rules),Kt(n,e,t),n.sort((s,c)=>s.path.localeCompare(c.path)||s.id.localeCompare(c.id)),{schemaVersion:"1.0",classification:Yt(n),findings:n}}function ge(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(r=>typeof r!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=S(e.findingIds),i=S(t.findingIds);return n.length===i.length&&n.every((r,a)=>r===i[a])}function _(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 tt(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}function G(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}function me(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let i=t,r="";for(t+=1;t<e.length;t+=1){let a=e[t];if(a===n)return{value:r,offset:i,excerpt:e.slice(i,t+1)};a==="\\"&&t+1<e.length?(r+=e[t+1],t+=1):r+=a}}function R(e,t,n){return e.startsWith(t,n)&&!tt(e[n-1])&&!tt(e[n+t.length])}function qt(e,t){if(t=G(e,t+6),e[t]==="(")return me(e,G(e,t+1));let n=!1;if(R(e,"type",t)){let r=G(e,t+4);e[r]!==","&&!R(e,"from",r)&&(n=!0)}let i=nt(e,t,!0);return i&&n?{...i,typeOnly:!0}:i}function Wt(e,t){t=t+6;let n=G(e,t),i=!1;if(R(e,"type",n)){let a=G(e,n+4);(e[a]==="{"||e[a]==="*")&&(i=!0)}let r=nt(e,t,!1);return r&&i?{...r,typeOnly:!0}:r}function nt(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(R(e,"from",t))return me(e,G(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return me(e,t);if(t>0&&(R(e,"import",t)||R(e,"export",t)))return}}function Jt(e){let t=[];for(let n=0;n<e.length;n+=1){let i=e[n];if(i==="/"&&e[n+1]==="/"){if(n=e.indexOf(`
|
|
5
|
-
`,n+2),n<0)break;continue}if(
|
|
6
|
-
`).length;
|
|
7
|
-
`).length,c={kind:"import",file:e.path,line:s,excerpt:r.excerpt},p=Zt(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:i}}function Zt(e,t,n){let i=e.split("/");i.pop();for(let a of t.split("/"))a==="."||a===""||(a===".."?i.pop():i.push(a));let r=i.join("/");for(let a of[r,`${r}.ts`,`${r}.tsx`,`${r}.mts`,`${r}.cts`,`${r}/index.ts`,`${r}/index.tsx`]){let s=n.get(a);if(s)return s}}function it(e,t){let n=[];for(let i of e){if(!i.to||!i.fromLayer||!i.toLayer)continue;let r=$(t.rules,i.fromLayer,i.toLayer,{fromPath:i.from,toPath:i.to,layers:t.layers});r&&n.push({ruleId:`layer-dependency:${r.from}->${r.to}`,message:r.message??`${r.from} must not depend on ${r.to}.`,edge:i,evidence:i.evidence})}return n}function ee(e,t){let n=typeof e=="string"?le(e,t):W(e,t);return{...n,policyHash:L(w(n.config))}}function $e(e){let t=ee(e.baseConfig,e.baseSource??"base ark.config.json"),n=ee(e.candidateConfig,e.candidateSource??"candidate ark.config.json"),i=ye(t.config,n.config),r=i.findings.filter(c=>c.classification==="weakening"||c.classification==="judgment-required").map(c=>c.id).sort(),a=r.length>0,s=a&&ge(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:r});return{schemaVersion:i.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:i.classification,findings:i.findings,blockingFindingIds:r,requiresAcknowledgement:a,acknowledged:s,valid:!a||s}}function U(e){let t=e.files.map(s=>{let c=_(s.path);return{path:c,content:s.content,contentHash:L(s.content),layer:B(c,e.contract.config.layers)??null}}).sort((s,c)=>s.path.localeCompare(c.path)),n=new Map(t.map(s=>[s.path,s])),i=[],r=[];for(let s of t){let c=rt(s,n);i.push(...c.edges),r.push(...c.capabilityUses)}let a=it(i,e.contract.config);return{ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:L(w(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(s=>s.name),edges:i,capabilityUses:r,violations:a}}}function te(e){let t=new Map(e.files.map(n=>[_(n.path),n]));for(let n of e.changes){let i=_(n.path);"delete"in n&&n.delete?t.delete(i):"content"in n&&t.set(i,{path:i,content:n.content})}return U({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}function ve(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 he(e){let t=0,n=new Map,i=new Map,r=new Set,a=[],s=[],c=p=>{n.set(p,t),i.set(p,t),t+=1,a.push(p),r.add(p);for(let m of[...e.get(p)??[]].sort())e.has(m)&&(n.has(m)?r.has(m)&&i.set(p,Math.min(i.get(p)??0,n.get(m)??0)):(c(m),i.set(p,Math.min(i.get(p)??0,i.get(m)??0))));if(i.get(p)!==n.get(p))return;let u=[],y;do{if(y=a.pop(),y===void 0)break;r.delete(y),u.push(y)}while(y!==p);u.length>1&&s.push(u.sort())};for(let p of[...e.keys()].sort())n.has(p)||c(p);return s.sort((p,u)=>p[0].localeCompare(u[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 ne(e){let t=e.contentViolations.map(a=>({...a})),n=(e.warnings??[]).map(a=>({...a})),i=new Map(e.files.map(a=>[a,new Set]));for(let a of e.edges){if(a.to&&a.to!==a.from&&!a.typeOnly&&i.has(a.from)&&i.get(a.from)?.add(a.to),!a.to||!a.toLayer)continue;let s=$(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 r=String(e.config.cyclePolicy??"strict").toLowerCase();if(r!=="off"){let a=he(i);r==="soft"||r==="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 at(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 ot(e){return L(w(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}function _e(e){let t=U(e),n=new Map(t.ir.files.map(o=>[o.path,o])),i=[],r=new Set,a=[];for(let o of e.changes){let l=o.path.replace(/\\/g,"/"),f=_(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(r.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}r.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.`}),i.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=te({...e,changes:i}),c=new Map(s.ir.files.map(o=>[o.path,o])),p=ne({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=i.map(o=>{let l=_(o.path),f=n.get(l),g=c.get(l);return{path:l,operation:"delete"in o&&o.delete?"delete":f?"update":"create",...f?{beforeContentHash:f.contentHash}:{},...g?{candidateContentHash:g.contentHash}:{}}}).sort((o,l)=>o.path.localeCompare(l.path)),y=[...a,...p.violations].map(o=>({...o,nextAction:at(o)})),m=e.changeMap?X({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:y.length===0&&(m?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:s.ir.compilerOptionsHash,baseTreeHash:ot(t.ir.files),candidateTreeHash:ot(s.ir.files),...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...m?{convergence:m}:{},changes:u,violations:y,warnings:p.warnings}}function I(e,t,n={}){return{ruleId:e,message:t,...n}}function Ne(e){let{config:t,rules:n,files:i,manifest:r}=e,a=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(l=>typeof l!="string"))&&a.push(I("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(I("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(I("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${l} must be a non-negative integer.`))}let s=Array.isArray(t.layers)?t.layers:[],c=Array.isArray(r?.architecture?.layers)?r.architecture.layers:[],p=new Set([...s.map(l=>l.name).filter(Boolean),...c.map(l=>l.name).filter(l=>!!l)]);s.length===0&&a.push(I("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let u=new Set,y=new Set;for(let l of s){if(!l.name){a.push(I("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}u.has(l.name)&&y.add(l.name),u.add(l.name),l.forbiddenGlobals!==void 0&&(!Array.isArray(l.forbiddenGlobals)||l.forbiddenGlobals.some(g=>typeof g!="string"))&&a.push(I("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(I("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${l.name}" has no file patterns and will never classify files.`,{layer:l.name}));continue}for(let g of f){let k;try{k=z(g)}catch(b){a.push(I("CONFIG_INVALID_LAYER_PATTERN",`Layer "${l.name}" has an invalid pattern "${g}": ${b instanceof Error?b.message:String(b)}`,{layer:l.name,pattern:g}));continue}!i.some(b=>k.test(b))&&!l.optional&&a.push(I("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${l.name}" pattern "${g}" matched no included files.`,{layer:l.name,pattern:g,failsStrict:!1}))}}for(let l of y)a.push(I("CONFIG_DUPLICATE_LAYER",`Layer "${l}" is configured more than once.`,{layer:l}));if(p.size>0)for(let l of n??[])l.from&&!p.has(l.from)&&a.push(I("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${l.from}".`,{fromLayer:l.from,toLayer:l.to})),l.to&&!p.has(l.to)&&a.push(I("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${l.to}".`,{fromLayer:l.from,toLayer:l.to}));let m=new Set;if(s.length>1)for(let l of i){let f=-1,g=[];for(let k of s)for(let b of k.patterns??[]){if(!z(b).test(l))continue;let d=Ie(b);d>f?(f=d,g=[k.name]):d===f&&!g.includes(k.name)&&g.push(k.name)}g.length>1&&m.add([...g].sort().join(" + "))}m.size>0&&a.push(I("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 o=i.filter(l=>!B(l,s));return o.length>0&&a.push(I("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});
|
|
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.5.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
|
+
${n.map(r=>`- ${r.path}: ${r.message}`).join(`
|
|
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});
|
package/dist/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as ArkConfigRule, b as ArkConfigSchemaVersion, c as ArkConfigLoadResult, d as ArkConfigLayer, A as ArkConfig } from './configTypes-
|
|
1
|
+
import { a as ArkConfigRule, b as ArkConfigSchemaVersion, c as ArkConfigLoadResult, d as ArkConfigLayer, A as ArkConfig } from './configTypes-DAPvBqK6.cjs';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Canonical, pure contract for ark.config.json.
|
|
@@ -145,6 +145,23 @@ declare const ARK_CONFIG_SCHEMA: {
|
|
|
145
145
|
};
|
|
146
146
|
readonly uniqueItems: true;
|
|
147
147
|
};
|
|
148
|
+
readonly capabilities: {
|
|
149
|
+
readonly type: "object";
|
|
150
|
+
readonly additionalProperties: false;
|
|
151
|
+
readonly properties: {
|
|
152
|
+
readonly deny: {
|
|
153
|
+
readonly type: "array";
|
|
154
|
+
readonly uniqueItems: true;
|
|
155
|
+
readonly items: {
|
|
156
|
+
readonly type: "string";
|
|
157
|
+
readonly enum: readonly ["network", "filesystem", "clock", "randomness", "environment", "process", "persistence"];
|
|
158
|
+
};
|
|
159
|
+
};
|
|
160
|
+
};
|
|
161
|
+
};
|
|
162
|
+
readonly pure: {
|
|
163
|
+
readonly type: "boolean";
|
|
164
|
+
};
|
|
148
165
|
readonly mayImportInfrastructure: {
|
|
149
166
|
readonly type: "boolean";
|
|
150
167
|
};
|
|
@@ -217,7 +234,7 @@ declare function loadArkConfigContract(input: unknown, source?: string): ArkConf
|
|
|
217
234
|
declare function parseArkConfigJson(json: string, source?: string): ArkConfigLoadResult;
|
|
218
235
|
|
|
219
236
|
/** ArkGate library version — single source of truth. */
|
|
220
|
-
declare const version = "3.
|
|
237
|
+
declare const version = "3.5.0";
|
|
221
238
|
|
|
222
239
|
/** Versioned public result contract shared by every ArkGate enforcement adapter. */
|
|
223
240
|
declare const ARK_ANALYSIS_RESULT_SCHEMA_VERSION: "1.1";
|
|
@@ -238,6 +255,8 @@ type AdapterViolationInput = {
|
|
|
238
255
|
peerIsolation?: unknown;
|
|
239
256
|
severity?: unknown;
|
|
240
257
|
nextAction?: unknown;
|
|
258
|
+
/** U04: the denied capability id on CAPABILITY_VIOLATION. */
|
|
259
|
+
capability?: unknown;
|
|
241
260
|
};
|
|
242
261
|
type AdapterDiagnostic = {
|
|
243
262
|
ruleId: string;
|
|
@@ -601,6 +620,13 @@ interface AICodeGateOptions<Context = AICodeGateContext> {
|
|
|
601
620
|
* to a listed layer — mirrors ark-check's FORBIDDEN_GLOBAL rule.
|
|
602
621
|
*/
|
|
603
622
|
forbiddenGlobals?: Record<string, string[]>;
|
|
623
|
+
/**
|
|
624
|
+
* Layer → effective capability deny set (U04 walls; ADR 0009). Enforced like
|
|
625
|
+
* forbiddenGlobals when the target file's layer is known. An ambient use
|
|
626
|
+
* already covered by the layer's forbiddenGlobals reports only
|
|
627
|
+
* FORBIDDEN_GLOBAL (D7 — one violation, one voice).
|
|
628
|
+
*/
|
|
629
|
+
capabilityWalls?: Record<string, string[]>;
|
|
604
630
|
/**
|
|
605
631
|
* Layer names whose role is infrastructure and may therefore import infrastructure
|
|
606
632
|
* (a persistence adapter importing the DB is correct, not a violation). The built-in
|
|
@@ -764,6 +790,10 @@ type AnalysisViolation = {
|
|
|
764
790
|
ruleId: string;
|
|
765
791
|
message: string;
|
|
766
792
|
edge?: AnalysisImportEdge;
|
|
793
|
+
/** U04 (additive): present on CAPABILITY_VIOLATION — the denied capability id. */
|
|
794
|
+
capability?: string;
|
|
795
|
+
/** U04 (additive): the matched module specifier or ambient path. */
|
|
796
|
+
symbol?: string;
|
|
767
797
|
evidence: AnalysisEvidence;
|
|
768
798
|
};
|
|
769
799
|
type AnalysisIr = {
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as ArkConfigRule, b as ArkConfigSchemaVersion, c as ArkConfigLoadResult, d as ArkConfigLayer, A as ArkConfig } from './configTypes-
|
|
1
|
+
import { a as ArkConfigRule, b as ArkConfigSchemaVersion, c as ArkConfigLoadResult, d as ArkConfigLayer, A as ArkConfig } from './configTypes-DAPvBqK6.js';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Canonical, pure contract for ark.config.json.
|
|
@@ -145,6 +145,23 @@ declare const ARK_CONFIG_SCHEMA: {
|
|
|
145
145
|
};
|
|
146
146
|
readonly uniqueItems: true;
|
|
147
147
|
};
|
|
148
|
+
readonly capabilities: {
|
|
149
|
+
readonly type: "object";
|
|
150
|
+
readonly additionalProperties: false;
|
|
151
|
+
readonly properties: {
|
|
152
|
+
readonly deny: {
|
|
153
|
+
readonly type: "array";
|
|
154
|
+
readonly uniqueItems: true;
|
|
155
|
+
readonly items: {
|
|
156
|
+
readonly type: "string";
|
|
157
|
+
readonly enum: readonly ["network", "filesystem", "clock", "randomness", "environment", "process", "persistence"];
|
|
158
|
+
};
|
|
159
|
+
};
|
|
160
|
+
};
|
|
161
|
+
};
|
|
162
|
+
readonly pure: {
|
|
163
|
+
readonly type: "boolean";
|
|
164
|
+
};
|
|
148
165
|
readonly mayImportInfrastructure: {
|
|
149
166
|
readonly type: "boolean";
|
|
150
167
|
};
|
|
@@ -217,7 +234,7 @@ declare function loadArkConfigContract(input: unknown, source?: string): ArkConf
|
|
|
217
234
|
declare function parseArkConfigJson(json: string, source?: string): ArkConfigLoadResult;
|
|
218
235
|
|
|
219
236
|
/** ArkGate library version — single source of truth. */
|
|
220
|
-
declare const version = "3.
|
|
237
|
+
declare const version = "3.5.0";
|
|
221
238
|
|
|
222
239
|
/** Versioned public result contract shared by every ArkGate enforcement adapter. */
|
|
223
240
|
declare const ARK_ANALYSIS_RESULT_SCHEMA_VERSION: "1.1";
|
|
@@ -238,6 +255,8 @@ type AdapterViolationInput = {
|
|
|
238
255
|
peerIsolation?: unknown;
|
|
239
256
|
severity?: unknown;
|
|
240
257
|
nextAction?: unknown;
|
|
258
|
+
/** U04: the denied capability id on CAPABILITY_VIOLATION. */
|
|
259
|
+
capability?: unknown;
|
|
241
260
|
};
|
|
242
261
|
type AdapterDiagnostic = {
|
|
243
262
|
ruleId: string;
|
|
@@ -601,6 +620,13 @@ interface AICodeGateOptions<Context = AICodeGateContext> {
|
|
|
601
620
|
* to a listed layer — mirrors ark-check's FORBIDDEN_GLOBAL rule.
|
|
602
621
|
*/
|
|
603
622
|
forbiddenGlobals?: Record<string, string[]>;
|
|
623
|
+
/**
|
|
624
|
+
* Layer → effective capability deny set (U04 walls; ADR 0009). Enforced like
|
|
625
|
+
* forbiddenGlobals when the target file's layer is known. An ambient use
|
|
626
|
+
* already covered by the layer's forbiddenGlobals reports only
|
|
627
|
+
* FORBIDDEN_GLOBAL (D7 — one violation, one voice).
|
|
628
|
+
*/
|
|
629
|
+
capabilityWalls?: Record<string, string[]>;
|
|
604
630
|
/**
|
|
605
631
|
* Layer names whose role is infrastructure and may therefore import infrastructure
|
|
606
632
|
* (a persistence adapter importing the DB is correct, not a violation). The built-in
|
|
@@ -764,6 +790,10 @@ type AnalysisViolation = {
|
|
|
764
790
|
ruleId: string;
|
|
765
791
|
message: string;
|
|
766
792
|
edge?: AnalysisImportEdge;
|
|
793
|
+
/** U04 (additive): present on CAPABILITY_VIOLATION — the denied capability id. */
|
|
794
|
+
capability?: string;
|
|
795
|
+
/** U04 (additive): the matched module specifier or ambient path. */
|
|
796
|
+
symbol?: string;
|
|
767
797
|
evidence: AnalysisEvidence;
|
|
768
798
|
};
|
|
769
799
|
type AnalysisIr = {
|