arkgate 3.7.0 → 3.8.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 +76 -1145
- package/README.md +59 -19
- package/bin/ark-check-runtime.mjs +1598 -0
- package/bin/ark-check.mjs +32 -1565
- package/bin/ark-mcp-runtime.mjs +1976 -0
- package/bin/ark-mcp.mjs +84 -1495
- package/bin/ark-shared.mjs +34 -38
- package/bin/ark.mjs +33 -66
- package/bin/lib/adapter-contract.mjs +161 -9
- package/bin/lib/agent-gates.mjs +1 -0
- package/bin/lib/analysis-completeness.mjs +28 -0
- package/bin/lib/analysis-engine.mjs +8 -8
- package/bin/lib/analysis-policy.mjs +27 -0
- package/bin/lib/architecture-scan.mjs +70 -357
- package/bin/lib/auto-patch.mjs +76 -8
- package/bin/lib/ci-and-commands.mjs +1 -1
- package/bin/lib/codex-home.mjs +43 -16
- package/bin/lib/design-delta.mjs +4 -0
- package/bin/lib/doctor-advisories.mjs +4 -3
- package/bin/lib/doctor-plan.mjs +40 -41
- package/bin/lib/enforcement-state.mjs +2 -0
- package/bin/lib/github-enforcement.mjs +443 -0
- package/bin/lib/hook-templates.mjs +12 -148
- package/bin/lib/html-report-advisories.mjs +1 -1
- package/bin/lib/html-report-depth.mjs +9 -0
- package/bin/lib/html-report.mjs +5 -5
- package/bin/lib/install-migrate.mjs +83 -79
- package/bin/lib/managed-upgrade.mjs +622 -0
- package/bin/lib/mcp-adoption.mjs +3 -1
- package/bin/lib/parse-health.mjs +6 -5
- package/bin/lib/port-proof.mjs +2 -2
- package/bin/lib/prepare-change.mjs +68 -38
- package/bin/lib/prepare-write.mjs +7 -1
- package/bin/lib/resident-doctor-client.mjs +55 -0
- package/bin/lib/resident-hook.mjs +247 -0
- package/bin/lib/resolved-candidate-facts.mjs +1160 -0
- package/bin/lib/scan-files.mjs +19 -6
- package/bin/lib/snippet-analysis.mjs +119 -0
- package/bin/lib/source-policy.mjs +24 -0
- package/bin/lib/typescript-host.mjs +15 -18
- package/bin/lib/unavailable-analysis.mjs +76 -0
- package/bin/lib/upgrade-command.mjs +115 -0
- package/bin/lib/weakest-link.mjs +21 -179
- package/bin/lib/write-path-capabilities.mjs +167 -16
- package/bin/lib/write-path-detect.mjs +3 -2
- package/dist/eslint/index.cjs +3 -3
- package/dist/eslint/index.d.ts +3 -0
- package/dist/eslint/index.js +3 -3
- package/dist/index.cjs +7 -7
- package/dist/index.d.ts +1073 -141
- package/dist/index.js +7 -7
- package/docs/agent-guide.md +103 -59
- package/docs/ai-gates.md +97 -16
- package/docs/demos/01-write-gate-self-correction.md +2 -2
- package/docs/enthusiast/README.md +10 -10
- package/docs/enthusiast/how-to-gallery-starter.md +2 -2
- package/docs/enthusiast/reference-commands.md +18 -1
- package/docs/enthusiast/tutorial-first-project.md +2 -2
- package/docs/package-surface.md +98 -12
- package/docs/typescript-support.md +109 -37
- package/package.json +32 -4
- package/schemas/ark.analysis-result.schema.json +159 -2
- package/schemas/ark.design-delta.schema.json +1 -0
- package/schemas/ark.enforcement-state.schema.json +84 -0
- package/schemas/ark.resolved-candidate-facts.schema.json +1 -0
- package/server.json +2 -2
- package/templates/skills/ark-explore.md +5 -5
- package/templates/skills/ark-fix.md +1 -1
- package/templates/skills/ark-runtime.md +15 -8
- package/templates/skills/ark-upgrade.md +122 -182
- package/bin/lib/ai-velocity.mjs +0 -293
- package/bin/lib/graph-cycles.mjs +0 -6
- package/bin/lib/safety-diagnostics.mjs +0 -284
- package/bin/lib/ts-resolve.mjs +0 -228
- package/dist/configTypes-DAPvBqK6.d.cts +0 -61
- package/dist/eslint/index.d.cts +0 -146
- package/dist/index.d.cts +0 -986
package/dist/index.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
"use strict";var ke=Object.defineProperty;var mt=Object.getOwnPropertyDescriptor;var ht=Object.getOwnPropertyNames;var At=Object.prototype.hasOwnProperty;var bt=(e,t)=>{for(var n in t)ke(e,n,{get:t[n],enumerable:!0})},Ct=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of ht(t))!At.call(e,r)&&r!==n&&ke(e,r,{get:()=>t[r],enumerable:!(i=mt(t,r))||i.enumerable});return e};var It=e=>Ct(ke({},"__esModule",{value:!0}),e);var sn={};bt(sn,{ANALYSIS_IR_SCHEMA_VERSION:()=>me,ARK_ANALYSIS_RESULT_SCHEMA:()=>Je,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>qe,ARK_CONFIG_SCHEMA:()=>ue,ARK_CONFIG_SCHEMA_VERSION:()=>st,POLICY_DELTA_SCHEMA_VERSION:()=>be,analyzeArchitectureConvergence:()=>te,analyzeChange:()=>ie,analyzePolicyDelta:()=>He,analyzeProject:()=>B,classifyArkPolicyDelta:()=>Ce,collectAnalysisConfigWarnings:()=>ze,collectForbiddenCapabilityUses:()=>N,createAICodeGate:()=>Fe,createAdapterResult:()=>We,createArchitectureProfile:()=>X,createArchitectureProfileFromArkConfig:()=>Ge,createElevenLayerArkConfig:()=>Ve,detectArchitectureCycles:()=>xe,deterministicHash:()=>P,elevenLayerProfile:()=>Q,evaluateArchitectureGraph:()=>ae,explainViolation:()=>Ue,extractSemanticDependencies:()=>_,loadArkConfigContract:()=>Z,loadContract:()=>re,parseArkConfigJson:()=>ge,policyDeltaAcknowledgementMatches:()=>Ie,preflightChange:()=>Be,stableSerialize:()=>w,toAdapterDiagnostic:()=>se,version:()=>Ke});module.exports=It(sn);var Ke="3.7.0";var qe="1.1";function E(e){return typeof e=="string"&&e.length>0?e:void 0}function Ye(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function xt(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 ${E(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 se(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:Ye(e.line,1),column:Ye(e.column,1)},evidence:r,nextAction:E(e.nextAction)??xt(n,r,e)}}function We(e){return{schemaVersion:"1.1",valid:e.valid,diagnostics:[...(e.violations??[]).map(t=>se(t,"error")),...(e.warnings??[]).map(t=>se(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 Le=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),Pe=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Oe=Object.freeze(Object.keys(Pe).sort()),Ee=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"}),we=Object.freeze({process:Object.freeze(["process","node:process"])});function z(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=Ee[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let i=e.slice(0,n),r=Ee[i];if(r)return r;let a=e.indexOf("/",n+1);return a<0?null:Ee[e.slice(0,a)]??null}function j(e,t){for(let n of t)if(we[n]?.includes(e))return n;return null}function ce(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let i=t.slice(0,n).join("."),r=Pe[i];if(r)return r}return null}function le(e){if(e?.pure===!0)return[...Le].sort();let n=(e?.capabilities?.deny??[]).filter(i=>Le.includes(i));return[...new Set(n)].sort()}function Re(e,t){if(t.length===0)return!1;let n=new Set(t),i=e.split(".");for(let r=i.length;r>=1;r-=1)if(n.has(i.slice(0,r).join(".")))return!0;return!1}function pe(e){let t=new Set,n=new Set,i=Object.keys(Pe);for(let r of e?.forbiddenGlobals??[]){let a=i.filter(s=>s===r||s.startsWith(`${r}.`));if(a.length===0)n.add(r);else for(let s of a)t.add(`ambient:${s}`);for(let s of we[r]??[])t.add(`import-exact:${s}`)}for(let r of le(e)){if(t.add(`import:${r}`),r==="process")for(let a of we.process)t.add(`import-exact:${a}`);for(let a of i)ce(a)===r&&t.add(`ambient:${a}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}var Ze=new Map;function Qe(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function $e(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 St(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 K(e){let t=Ze.get(e);if(t)return t;let n=$e(e),i=St(n),r="",a=0;for(let l=0;l<n.length;l+=1){let p=n[l];p==="\\"&&l+1<n.length?(r+=Qe(n[l+1]),l+=1):p==="*"?n[l+1]==="*"?n[l+2]==="/"?(r+="(?:.*/)?",l+=2):(r+=".*",l+=1):r+="[^/]*":p==="?"?r+="[^/]":p==="{"&&i?(r+="(?:",a+=1):p==="}"&&i&&a>0?(r+=")",a-=1):p===","&&i&&a>0?r+="|":r+=Qe(p)}let s=new RegExp(`^${r}$`);return Ze.set(e,s),s}function ve(e){let t=$e(String(e)),i=t.split("*")[0].split("/").filter(Boolean).length,r=t.replace(/\*/g,"").length;return i*1e4+r}function Y(e,t){let n=String(e).split(/[/\\]/).join("/"),i,r=-1;for(let a of t??[])if(!(a.exclude??[]).some(s=>K(s).test(n))){for(let s of a.patterns??[])if(K(s).test(n)){let l=ve(s);l>r&&(r=l,i=a.name)}}return i}function Xe(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),i=new Set(t.map(r=>String(r).toLowerCase()));for(let r=0;r<n.length-1;r+=1)if(i.has(n[r].toLowerCase()))return`${n[r].toLowerCase()}/${n[r+1].toLowerCase()}`}function kt(e){let t=new Set;for(let n of e??[]){let r=$e(String(n)).split("/").filter(Boolean);for(let a=0;a<r.length;a+=1){let s=r[a];if((s==="**"||s==="*")&&a>0){let l=r[a-1];l&&!l.includes("*")&&!l.includes("{")&&!l.includes("}")&&t.add(l)}}}return[...t]}function Et(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 kt(i?.patterns)}function v(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 l=Et(r,t,i?.layers);if(l.length===0)continue;let p=Xe(a,l),f=Xe(s,l);if(!p||!f)continue;if(p!==f)return r;continue}if(t!==n)return r}}function G(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function nt(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function et(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 rt(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 _e(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function Ne(e,t,n,i){let r=i.parent&&e.isShorthandPropertyAssignment(i.parent)&&i.parent.name===i,a;try{a=r?t.getShorthandAssignmentValueSymbol(i.parent):_e(t,i)}catch{a=void 0}return!!a?.declarations?.some(s=>s.getSourceFile().fileName===n.fileName)}function _(e,t){let n,i=[],r=(s,l,p,f=!1)=>i.push({specifier:p,kind:l,line:nt(t,s),typeOnly:f,unresolved:p===void 0,node:s}),a=s=>{if(e.isImportDeclaration(s))r(s,"import",G(e,s.moduleSpecifier),et(e,s));else if(e.isExportDeclaration(s)&&s.moduleSpecifier)r(s,"export",G(e,s.moduleSpecifier),et(e,s));else if(e.isImportEqualsDeclaration(s)&&e.isExternalModuleReference(s.moduleReference))r(s,"require",G(e,s.moduleReference.expression),s.isTypeOnly===!0);else if(e.isCallExpression(s)){let l=s.expression.kind===e.SyntaxKind.ImportKeyword,f=e.isIdentifier(s.expression)&&s.expression.text==="require"&&!Ne(e,n??(n=rt(e,t)),t,s.expression);(l||f)&&r(s,f?"require":"dynamic-import",G(e,s.arguments[0]))}e.forEachChild(s,a)};return a(t),i}function Lt(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=G(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 wt(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 tt(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 N(e,t,n){if(n.length===0)return[];let i=new Set(n),r=rt(e,t),a=new Map,s=new Set;for(let c of t.statements)if(e.isVariableStatement(c))for(let o of c.declarationList.declarations)e.isIdentifier(o.name)&&s.add(o.name.text);let l=c=>{let o=Lt(e,c);if(!o)return;let g=_e(r,o.root),y=g?a.get(g):void 0;return y?[...y,...o.segments.slice(1)]:Ne(e,r,t,o.root)||s.has(o.root.text)?void 0:o.segments};for(let c of t.statements)if(e.isVariableStatement(c))for(let o of c.declarationList.declarations){if(!o.initializer||!e.isIdentifier(o.name))continue;let g=l(o.initializer),y=_e(r,o.name);!g||!y||a.set(y,g)}let p=[],f=new Set,u=(c,o)=>{let g=nt(t,o),y=`${c}:${o.getStart(t)}`;f.has(y)||(f.add(y),p.push({name:c,line:g,node:o}))},m=c=>{let o=c.parent&&(e.isPropertyAccessExpression(c.parent)||e.isElementAccessExpression(c.parent))&&c.parent.expression===c;if((e.isPropertyAccessExpression(c)||e.isElementAccessExpression(c))&&!o){let g=l(c),y=g?tt(i,g):void 0;y&&u(y,c)}else e.isIdentifier(c)&&i.has(c.text)&&wt(e,c)&&!Ne(e,r,t,c)&&u(c.text,c);if(e.isVariableDeclaration(c)&&e.isObjectBindingPattern(c.name)&&c.initializer){let g=l(c.initializer);if(g)for(let y of c.name.elements){if(!e.isIdentifier(y.name))continue;let I=y.propertyName?G(e,y.propertyName)??y.propertyName.text:y.name.text,x=tt(i,[...g,I]);x&&u(x,c.initializer)}}e.forEachChild(c,m)};return m(t),p}function Me(e,t){let n=[];for(let i of _(e,t)){if(i.typeOnly||!i.specifier)continue;let r=z(i.specifier);r&&n.push({capability:r,symbol:i.specifier,line:i.line,source:"import-based"})}for(let i of N(e,t,Oe)){let r=ce(i.name);r&&n.push({capability:r,symbol:i.name,line:i.line,source:"ambient-global"})}return n.sort((i,r)=>i.line-r.line||i.capability.localeCompare(r.capability)||i.symbol.localeCompare(r.symbol))}var Te={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 De(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&M(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:Te.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:Te.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 Pt(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 Ot(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],l=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:l})}}return t.sort((i,r)=>i.index-r.index)}function Rt(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 $t(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 vt(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 W(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function Nt(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}function it(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(i=>!e.isPropertyAssignment(i)&&!e.isShorthandPropertyAssignment(i)?!1:Nt(e,i.name)===n)}function J(e,t,n){return it(e,t,n)!==void 0}function q(e,t,n){let i=it(e,t,n);return i&&e.isPropertyAssignment(i)?i.initializer:void 0}function Mt(e,t){let n=q(e,t,"metadata");return J(e,n,"source")}function at(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?at(e,t.name):!1:!1}function Tt(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 Dt(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],i=W(e,n);return i!==void 0&&M(i)||J(e,n,"intent")||at(e,n)}function Ft(e,t){if(!e.isCallExpression(t))return!1;let[n,i,r]=t.arguments;return Mt(e,n)||J(e,i,"source")||J(e,r,"source")}function jt(e,t){if(!e.isCallExpression(t))return;let[n,i,r]=t.arguments,a=q(e,n,"metadata");return W(e,q(e,a,"source"))??W(e,q(e,i,"source"))??W(e,q(e,r,"source"))}function Gt(e,t,n,i){let r=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),a=n,s=a?.filePath,l=a?.layer,p=[],f=m=>r.getLineAndCharacterOfPosition(m.getStart(r)).line+1,u=m=>{if(Tt(e,m)){let c=m.arguments[0],o=W(e,c);for(let y of De({publishCall:!0,rawIntentName:o,objectHasIntent:J(e,c,"intent"),arkPublishCandidate:Dt(e,m),hasSource:Ft(e,m)}))p.push(b(y.ruleId,y.message,{line:f(m),filePath:s}));let g=jt(e,m);if(i&&l&&g&&M(g)){let y=i.resolveLayer(g);y&&y!==l&&p.push(b("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${g}" resolves to ${y}, but the target file is classified as ${l}.`,{line:f(m),filePath:s,target:g,fromLayer:l,toLayer:y}))}}e.forEachChild(m,u)};return u(r),p}function Fe(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 l=[],p=s,f=p?.filePath,u=p?.layer,m=e.typescript,c=m?m.createSourceFile(f??"generated.ts",a,m.ScriptTarget.Latest,!0):void 0,o=c?_(e.typescript,c):void 0,g=o?o.filter(d=>d.specifier!==void 0).map(d=>({value:d.specifier,index:d.node.getStart(c),kind:d.kind,typeOnly:d.typeOnly})):Ot(a),y=e.typescript?Rt(e.typescript,a):Pt(a);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(f))for(let d of o?.filter(({unresolved:h})=>h)??[]){let h=d.kind==="require";l.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:f}))}let I=u!==void 0&&(i.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&&l.push(b("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${d}`,{line:h.index===void 0?void 0:V(a,h.index),filePath:f,suggestion:"Remove infrastructure imports from domain/application layers."+x}))}else a.includes(d)&&l.push(b("FORBIDDEN_SUBSTRING",`Forbidden substring: ${d}`,{line:V(a,a.indexOf(d)),filePath:f}));for(let d of g){let h=e.resolveImportTarget?.(d.value,f)??(e.resolveImportLayer?{layer:e.resolveImportLayer(d.value,f)}:void 0),A=typeof f=="string"?e.resolveImportTarget?.(f)??(e.resolveImportLayer?{layer:u,relPath:void 0}:void 0):void 0,F=h?.layer;if(F&&u){let oe=v(e.architectureProfile?.rules,u,F,{fromPath:A?.relPath,toPath:h?.relPath,layers:e.architectureLayers});if(oe){if(d.typeOnly&&!oe.peerIsolation)continue;let Se=!!oe.peerIsolation;l.push(b("LAYER_IMPORT_VIOLATION",oe.message??(Se?`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:f,fromLayer:u,toLayer:F,suggestion:Se?"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:Se,...d.typeOnly?{typeOnly:!0}:{}}}));continue}if(F!==u)continue}I||d.typeOnly||!$t(d.value)&&!vt(d.value)||l.push(b("FORBIDDEN_IMPORT",`Forbidden ${d.kind} target: "${d.value}".`,{line:V(a,d.index),source:d.value,target:d.value,filePath:f,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)l.push(b("POLICY_VIOLATION",A.message,{filePath:f,suggestion:`Fix violation of policy "${d.name}".`}));else h===!1?l.push(b("POLICY_VIOLATION",`Policy ${d.name} failed on generated code`)):l.push(b("POLICY_VIOLATION",h.message))}if(r&&t.size>0)for(let d of y)M(d.value)&&!t.has(d.value)&&l.push(b("UNKNOWN_INTENT",`Unknown intent reference: "${d.value}"`,{line:V(a,d.index),filePath:f,target:d.value,suggestion:`Register intent "${d.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&u)for(let d of y){if(!M(d.value))continue;let h=e.architectureProfile.resolveLayer(d.value);if(!h)continue;let A=v(e.architectureProfile.rules,u,h);A&&l.push(b("LAYER_REFERENCE_VIOLATION",A.message??`Layer "${u}" must not reference "${h}" through "${d.value}".`,{line:V(a,d.index),filePath:f,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);l.push(...h)}catch(h){l.push(b("EXTENSION_ERROR",`Extension "${d.name}" failed: ${h instanceof Error?h.message:String(h)}`))}if(e.typescript&&c&&u&&e.forbiddenGlobals?.[u]?.length)try{let d=e.forbiddenGlobals[u];l.push(...N(e.typescript,c,d).map(h=>b("FORBIDDEN_GLOBAL",`${u} must not use the ambient global "${h.name}".`,{line:h.line,filePath:f,target:h.name,fromLayer:u,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let h of o??[]){if(h.typeOnly||!h.specifier)continue;let A=j(h.specifier,d);A&&l.push(b("FORBIDDEN_GLOBAL",`${u} must not use module "${h.specifier}" because it is the import form of forbidden global "${A}".`,{line:h.line,filePath:f,source:h.specifier,target:h.specifier,fromLayer:u,details:{importKind:h.kind,forbiddenGlobal:A},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(d){l.push(b("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${d instanceof Error?d.message:String(d)}`))}if(e.typescript&&c&&u&&e.capabilityWalls?.[u]?.length)try{let d=new Set(e.capabilityWalls[u]),h=e.forbiddenGlobals?.[u]??[];for(let A of Me(e.typescript,c))d.has(A.capability)&&(A.source==="ambient-global"&&Re(A.symbol,h)||A.source==="import-based"&&j(A.symbol,h)||l.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:f,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){l.push(b("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${d instanceof Error?d.message:String(d)}`))}if(e.typescript)try{l.push(...Gt(e.typescript,a,s,e.architectureProfile))}catch(d){l.push(b("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${d instanceof Error?d.message:String(d)}`))}return{valid:l.length===0,violations:l}}}}var st="1.0",fe="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",ot=["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 Ht(){let e=[];for(let t of ot)for(let n of ot)t===n||Vt.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var ye=Ht();var R={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},ue={$schema:"https://json-schema.org/draft/2020-12/schema",$id:fe,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:fe,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:ye,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}}}}},U=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 ct(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function je(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function H(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Ut(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function de(e,t,n,i,r){if(t.$ref){let a=Ut(t.$ref,i);if(!a){r.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}de(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(!ct(e)){r.push({path:n,message:`must be an object; received ${H(e)}`});return}let a=t.properties??{};for(let s of t.required??[])e[s]===void 0&&r.push({path:je(n,s),message:"is required"});if(t.additionalProperties===!1)for(let s of Object.keys(e))s in a||r.push({path:je(n,s),message:"unknown field"});for(let[s,l]of Object.entries(a))e[s]!==void 0&&de(e[s],l,je(n,s),i,r);return}if(t.type==="array"){if(!Array.isArray(e)){r.push({path:n,message:`must be an array; received ${H(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)=>de(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 ${H(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 ${H(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){r.push({path:n,message:`must be an integer; received ${H(e)}`});return}t.minimum!==void 0&&e<t.minimum&&r.push({path:n,message:`must be at least ${t.minimum}`})}}function Bt(e){return{...e,$schema:e.$schema===void 0?fe: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?ye.map(t=>({...t})):e.rules}}function zt(e,t="ark.config.json"){if(!ct(e))throw new U(t,[{path:"$",message:`must be an object; received ${H(e)}`}]);let n=e.schemaVersion===void 0?"unversioned":null;if(e.schemaVersion!==void 0&&e.schemaVersion!=="1.0")throw new U(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.0`}]);return{candidate:Bt(e),migratedFrom:n}}function Z(e,t="ark.config.json"){let{candidate:n,migratedFrom:i}=zt(e,t),r=[];if(de(n,ue,"$",ue,r),r.length>0)throw new U(t,r);return{config:n,migratedFrom:i}}function ge(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(i){throw new U(t,[{path:"$",message:`invalid JSON: ${i instanceof Error?i.message:String(i)}`}])}return Z(n,t)}function lt(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:fe,schemaVersion:"1.0"};for(let[n,i]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=i);return t}function Kt(e){return e.endsWith(".")?e:`${e}.`}function Yt(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 X(e){let t=e.layers.map(r=>({...r,prefixes:r.prefixes.map(Kt)})),n=[...t].sort(Yt),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 Ge(e,t={}){return X({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 qt=[{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}],Q=X({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:qt,rules:ye.map(e=>({...e}))}),Wt={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 Ve(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,i=t==="."?"":`${t}/`;return lt({include:e.include??[t],layers:Q.layers.map(r=>({name:r.name,patterns:(Wt[r.name]??[r.name]).map(a=>`${i}${a}/**`),intentPrefixes:r.prefixes,optional:n})),rules:[...Q.rules]})}var me="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 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 k(e){return`${e.from}->${e.to}`}function ee(e,t,n,i="dependency"){return{id:`${e}:${i}:${k(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${k(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${k(t)}, then preflight again.`}:e==="unplanned"?{nextAction:i==="dependency-removed"?`Restore the removed dependency ${k(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${k(t)} from the candidate, then preflight again.`}:{}}}function te(e){let t=[],n=new Map(e.changeMap.map.files.map(c=>[c.path,c])),i=new Map(e.changes.map(c=>[c.path,c])),r=new Map(e.changeMap.map.dependencies.map(c=>[k(c),c])),a=new Map(e.baseDependencies.map(c=>[k(c),c])),s=new Map(e.candidateDependencies.map(c=>[k(c),c]));for(let c of[...n.values()].sort((o,g)=>o.path.localeCompare(g.path))){let o=i.get(c.path);o?o.operation!==c.operation?t.push({id:`contradictory:file:${c.path}`,classification:"contradictory",subject:"file",path:c.path,expectedOperation:c.operation,actualOperation:o.operation,message:`${c.path} was planned as ${c.operation} but the actual operation is ${o.operation}.`,nextAction:`Change ${c.path} to the planned ${c.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${c.path}`,classification:"satisfied",subject:"file",path:c.path,expectedOperation:c.operation,actualOperation:o.operation,message:`${c.path} matches the planned ${c.operation} operation.`}):t.push({id:`missing:file:${c.path}`,classification:"missing",subject:"file",path:c.path,expectedOperation:c.operation,message:`${c.path} was planned as ${c.operation} but is absent from the actual change.`,nextAction:`${c.operation[0].toUpperCase()}${c.operation.slice(1)} ${c.path} in the complete change set, then preflight again.`})}for(let c of[...i.values()].sort((o,g)=>o.path.localeCompare(g.path)))n.has(c.path)||t.push({id:`unplanned:file:${c.path}`,classification:"unplanned",subject:"file",path:c.path,actualOperation:c.operation,message:`${c.path} has an unplanned ${c.operation} operation.`,nextAction:`Remove ${c.path} from the change set, then preflight again.`});let l=new Set;for(let c of[...r.values()].sort((o,g)=>k(o).localeCompare(k(g)))){if(s.has(k(c))){t.push(ee("satisfied",c,`${c.from} -> ${c.to} exists in the candidate architecture.`));continue}let o={from:c.to,to:c.from};s.has(k(o))?(l.add(k(o)),t.push(ee("contradictory",c,`${c.from} -> ${c.to} was planned, but the candidate contains the reverse edge.`))):t.push(ee("missing",c,`${c.from} -> ${c.to} is absent from the candidate architecture.`))}let p=new Set([...n.keys(),...i.keys()]);for(let[c,o]of[...s].sort(([g],[y])=>g.localeCompare(y)))a.has(c)||r.has(c)||l.has(c)||!p.has(o.from)&&!p.has(o.to)||t.push({...ee("unplanned",o,`${o.from} -> ${o.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let f=new Set(e.changeMap.map.files.filter(c=>c.operation==="delete").map(c=>c.path));for(let[c,o]of[...a].sort(([g],[y])=>g.localeCompare(y)))s.has(c)||f.has(o.from)||f.has(o.to)||!p.has(o.from)&&!p.has(o.to)||t.push({...ee("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((c,o)=>u[c.classification]-u[o.classification]||(c.subject===o.subject?0:c.subject==="file"?-1:1)||c.id.localeCompare(o.id));let m={satisfied:t.filter(c=>c.classification==="satisfied").length,missing:t.filter(c=>c.classification==="missing").length,contradictory:t.filter(c=>c.classification==="contradictory").length,unplanned:t.filter(c=>c.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 be="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 L(e){return[...new Set(e??[])].sort()}function T(e,t,n,i,r){let a=L(n),s=L(i),l=new Set(a),p=new Set(s),f=s.filter(m=>!l.has(m)),u=a.filter(m=>!p.has(m));f.length===0&&u.length===0||(f.length>0&&C(e,{kind:"added",path:t,classification:r.added,message:r.addedMessage,before:a,after:s}),u.length>0&&C(e,{kind:"removed",path:t,classification:r.removed,message:r.removedMessage,before:a,after:s}))}function he(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 Ae(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 Jt(e,t,n){let i=Ae(t,a=>a.name),r=Ae(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),l=r.values.get(a),p=`$.layers[${a}]`;if(!s&&l){C(e,{kind:"layer-added",path:p,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:l});continue}if(s&&!l){C(e,{kind:"layer-removed",path:p,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:s});continue}if(!s||!l)continue;T(e,`${p}.patterns`,s.patterns,l.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),T(e,`${p}.exclude`,s.exclude,l.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let f=pe(s),u=pe(l);T(e,`${p}.forbiddenGlobals`,f.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`,f.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)."}),L(s.intentPrefixes).join("\0")!==L(l.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:L(s.intentPrefixes),after:L(l.intentPrefixes)}),he(e,`${p}.mayImportInfrastructure`,s.mayImportInfrastructure===!0,l.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),he(e,`${p}.optional`,s.optional===!0,l.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active.")}}function Zt(e,t,n){let i=s=>`${s.from}->${s.to}`,r=Ae(t,i),a=Ae(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 l=r.values.get(s),p=a.values.get(s),f=`$.rules[${s}]`;if(!l&&p){p.allowed===!1&&C(e,{kind:"deny-added",path:f,classification:"strengthening",message:"A denied dependency edge was added.",after:p});continue}if(l&&!p){l.allowed===!1&&C(e,{kind:"deny-removed",path:f,classification:"weakening",message:"A denied dependency edge was removed.",before:l});continue}if(!l||!p)continue;l.allowed!==p.allowed&&C(e,{kind:p.allowed?"deny-disabled":"deny-enabled",path:`${f}.allowed`,classification:p.allowed?"weakening":"strengthening",message:p.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:l.allowed,after:p.allowed});let u=l.peerIsolation===!0,m=p.peerIsolation===!0;if(u!==m){let c=l.from===l.to&&p.from===p.to;C(e,{kind:m?"peer-isolation-enabled":"peer-isolation-disabled",path:`${f}.peerIsolation`,classification:c?m?"strengthening":"weakening":"judgment-required",message:c?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})}L(l.sliceFolders).join("\0")!==L(p.sliceFolders).join("\0")&&C(e,{kind:"slice-folders-changed",path:`${f}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:L(l.sliceFolders),after:L(p.sliceFolders)})}}function Qt(e,t,n){let i=t.safety??{},r=n.safety??{};for(let a of["maxTsSuppressions","maxAnyCasts"]){let s=i[a]??0,l=r[a]??0;s!==l&&C(e,{kind:l>s?"threshold-raised":"threshold-lowered",path:`$.safety.${a}`,classification:l>s?"weakening":"strengthening",message:l>s?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:s,after:l})}for(let a of["allowInMemory","allowDisabledPeerIsolation"])he(e,`$.safety.${a}`,i[a]===!0,r[a]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}function Xt(e){return e.some(t=>t.classification==="weakening")?"weakening":e.some(t=>t.classification==="judgment-required")?"judgment-required":e.some(t=>t.classification==="strengthening")?"strengthening":"neutral"}function Ce(e,t){let n=[];T(n,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),T(n,"$.exclude",e.exclude,t.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional project paths are excluded from governance.",removedMessage:"Fewer project paths are excluded from governance."}),T(n,"$.dynamicImportAllowlist",e.dynamicImportAllowlist,t.dynamicImportAllowlist,{added:"weakening",removed:"strengthening",addedMessage:"Additional files may use non-literal dynamic imports.",removedMessage:"Fewer files may use non-literal dynamic imports."}),he(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}),Jt(n,e.layers,t.layers),Zt(n,e.rules,t.rules),Qt(n,e,t),n.sort((s,l)=>s.path.localeCompare(l.path)||s.id.localeCompare(l.id)),{schemaVersion:be,classification:Xt(n),findings:n}}function Ie(e,t){if(!e||e.schemaVersion!==be||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(r=>typeof r!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=L(e.findingIds),i=L(t.findingIds);return n.length===i.length&&n.every((r,a)=>r===i[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 pt(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 ne(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 O(e,t,n){return e.startsWith(t,n)&&!pt(e[n-1])&&!pt(e[n+t.length])}function en(e,t){if(t=$(e,t+6),e[t]==="(")return ne(e,$(e,t+1));let n=!1;if(O(e,"type",t)){let r=$(e,t+4);e[r]!==","&&!O(e,"from",r)&&(n=!0)}let i=dt(e,t,!0);return i&&n?{...i,typeOnly:!0}:i}function tn(e,t){t=t+6;let n=$(e,t),i=!1;if(O(e,"type",n)){let a=$(e,n+4);(e[a]==="{"||e[a]==="*")&&(i=!0)}let r=dt(e,t,!1);return r&&i?{...r,typeOnly:!0}:r}function dt(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(O(e,"from",t))return ne(e,$(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return ne(e,t);if(t>0&&(O(e,"import",t)||O(e,"export",t)))return}}function nn(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 rn(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let i=$(e,t+7);if(e[i]!=="(")return;i=$(e,i+1);let r=ne(e,i);return r?{...r,requireCall:!0}:void 0}function an(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,l={kind:"import",file:e.path,line:s,excerpt:r.excerpt},p=on(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:l})}return{edges:n,capabilityUses:i}}function on(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 ut(e,t){let n=[];for(let i of e){if(!i.to||!i.fromLayer||!i.toLayer)continue;let r=v(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 re(e,t){let n=typeof e=="string"?ge(e,t):Z(e,t);return{...n,policyHash:P(w(n.config))}}function He(e){let t=re(e.baseConfig,e.baseSource??"base ark.config.json"),n=re(e.candidateConfig,e.candidateSource??"candidate ark.config.json"),i=Ce(t.config,n.config),r=i.findings.filter(l=>l.classification==="weakening"||l.classification==="judgment-required").map(l=>l.id).sort(),a=r.length>0,s=a&&Ie(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 B(e){let t=e.files.map(p=>{let f=D(p.path);return{path:f,content:p.content,contentHash:P(p.content),layer:Y(f,e.contract.config.layers)??null}}).sort((p,f)=>p.path.localeCompare(f.path)),n=new Map(t.map(p=>[p.path,p])),i=[],r=[];for(let p of t){let f=ft(p,n);i.push(...f.edges),r.push(...f.capabilityUses)}let a=ut(i,e.contract.config),s=new Map(e.contract.config.layers.map(p=>[p.name,p])),l=new Map(e.contract.config.layers.map(p=>[p.name,new Set(le(p))]));for(let p of r){let f=n.get(p.file)?.layer;if(!f)continue;let u=s.get(f),m=j(p.symbol,u?.forbiddenGlobals??[]);if(m){a.push({ruleId:"FORBIDDEN_GLOBAL",message:`${f} must not use module "${p.symbol}" because it is the import form of forbidden global "${m}".`,symbol:p.symbol,evidence:p.evidence});continue}l.get(f)?.has(p.capability)&&a.push({ruleId:"CAPABILITY_VIOLATION",message:`${f} denies the ${p.capability} capability; found import of "${p.symbol}".`,capability:p.capability,symbol:p.symbol,evidence:p.evidence})}return{ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:P(w(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(p=>p.name),edges:i,capabilityUses:r,violations:a}}}function ie(e){let t=new Map(e.files.map(n=>[D(n.path),n]));for(let n of e.changes){let i=D(n.path);"delete"in n&&n.delete?t.delete(i):"content"in n&&t.set(i,{path:i,content:n.content})}return B({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}function Ue(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 xe(e){let t=0,n=new Map,i=new Map,r=new Set,a=[],s=[],l=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)):(l(m),i.set(p,Math.min(i.get(p)??0,i.get(m)??0))));if(i.get(p)!==n.get(p))return;let f=[],u;do{if(u=a.pop(),u===void 0)break;r.delete(u),f.push(u)}while(u!==p);f.length>1&&s.push(f.sort())};for(let p of[...e.keys()].sort())n.has(p)||l(p);return s.sort((p,f)=>p[0].localeCompare(f[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 ae(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=v(e.rules,a.fromLayer,a.toLayer,{fromPath:a.from,toPath:a.to,layers:e.config.layers});if(!s)continue;let l=!!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}:{},...!l&&a.portProofEligible?{portProofEligible:!0}:{},...a.kind?{edgeKind:a.kind}:{},...l?{peerIsolation:!0}:{},message:s.message??(l?`${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=xe(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 yt(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 gt(e){return P(w(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}function Be(e){let t=B(e),n=new Map(t.ir.files.map(o=>[o.path,o])),i=[],r=new Set,a=[];for(let o of e.changes){let g=o.path.replace(/\\/g,"/"),y=D(o.path);if(!y||y===".."||y.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(r.has(y)){a.push({ruleId:"DUPLICATE_CHANGE_PATH",file:y,line:1,message:`The atomic change set contains more than one operation for ${y}.`});continue}r.add(y),"delete"in o&&o.delete&&!n.has(y)&&a.push({ruleId:"DELETE_TARGET_MISSING",file:y,line:1,message:`Cannot delete ${y} because it is not present in the supplied base tree.`}),i.push("delete"in o&&o.delete?{path:y,delete:!0}:{path:y,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=ie({...e,changes:i}),l=new Map(s.ir.files.map(o=>[o.path,o])),p=s.ir.violations.filter(o=>o.ruleId==="CAPABILITY_VIOLATION"||o.ruleId==="FORBIDDEN_GLOBAL").map(o=>{let g=l.get(o.evidence.file)?.layer;return{ruleId:o.ruleId,file:o.evidence.file,line:o.evidence.line,target:o.symbol,...o.capability?{capability:o.capability}:{},...g?{fromLayer:g}:{},edgeKind:"import",message:o.message}}),f=ae({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=i.map(o=>{let g=D(o.path),y=n.get(g),I=l.get(g);return{path:g,operation:"delete"in o&&o.delete?"delete":y?"update":"create",...y?{beforeContentHash:y.contentHash}:{},...I?{candidateContentHash:I.contentHash}:{}}}).sort((o,g)=>o.path.localeCompare(g.path)),m=[...a,...f.violations].map(o=>({...o,nextAction:yt(o)})),c=e.changeMap?te({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&&(c?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:s.ir.compilerOptionsHash,baseTreeHash:gt(t.ir.files),candidateTreeHash:gt(s.ir.files),...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...c?{convergence:c}:{},changes:u,violations:m,warnings:f.warnings}}function S(e,t,n={}){return{ruleId:e,message:t,...n}}function ze(e){let{config:t,rules:n,files:i,manifest:r}=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:[],l=Array.isArray(r?.architecture?.layers)?r.architecture.layers:[],p=new Set([...s.map(o=>o.name).filter(Boolean),...l.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 f=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}f.has(o.name)&&u.add(o.name),f.add(o.name),o.forbiddenGlobals!==void 0&&(!Array.isArray(o.forbiddenGlobals)||o.forbiddenGlobals.some(y=>typeof y!="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 y of g){let I;try{I=K(y)}catch(x){a.push(S("CONFIG_INVALID_LAYER_PATTERN",`Layer "${o.name}" has an invalid pattern "${y}": ${x instanceof Error?x.message:String(x)}`,{layer:o.name,pattern:y}));continue}!i.some(x=>I.test(x))&&!o.optional&&a.push(S("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${o.name}" pattern "${y}" matched no included files.`,{layer:o.name,pattern:y,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 i){let g=-1,y=[];for(let I of s)for(let x of I.patterns??[]){if(!K(x).test(o))continue;let d=ve(x);d>g?(g=d,y=[I.name]):d===g&&!y.includes(I.name)&&y.push(I.name)}y.length>1&&m.add([...y].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 c=i.filter(o=>!Y(o,s));return c.length>0&&a.push(S("CONFIG_UNCLASSIFIED_FILES",`${c.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:c.length,samples:c.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 qe=Object.defineProperty;var Kt=Object.getOwnPropertyDescriptor;var Yt=Object.getOwnPropertyNames;var Wt=Object.prototype.hasOwnProperty;var Jt=(e,t)=>{for(var n in t)qe(e,n,{get:t[n],enumerable:!0})},Zt=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Yt(t))!Wt.call(e,r)&&r!==n&&qe(e,r,{get:()=>t[r],enumerable:!(s=Kt(t,r))||s.enumerable});return e};var Xt=e=>Zt(qe({},"__esModule",{value:!0}),e);var Wn={};Jt(Wn,{ANALYSIS_IR_SCHEMA_VERSION:()=>De,ARK_ANALYSIS_RESULT_SCHEMA:()=>Ct,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>At,ARK_CONFIG_SCHEMA:()=>_e,ARK_CONFIG_SCHEMA_VERSION:()=>Lt,ARK_DESIGN_DELTA_SCHEMA_VERSION:()=>zt,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION:()=>qt,POLICY_DELTA_SCHEMA_VERSION:()=>He,RESOLVED_CANDIDATE_FACTS_SCHEMA:()=>dt,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION:()=>ct,analyzeArchitectureConvergence:()=>Z,analyzeChange:()=>Se,analyzePolicyDelta:()=>ft,analyzeProject:()=>ce,analyzeResolvedProject:()=>pe,classifyArkPolicyDelta:()=>Ve,collectAnalysisConfigWarnings:()=>xe,collectForbiddenCapabilityUses:()=>W,createAICodeGate:()=>st,createAdapterResult:()=>bt,createArchitectureProfile:()=>Ce,createArchitectureProfileFromArkConfig:()=>ot,createElevenLayerArkConfig:()=>lt,createResolvedCandidateFacts:()=>pt,detectArchitectureCycles:()=>Ge,deterministicHash:()=>k,elevenLayerProfile:()=>be,evaluateArchitectureGraph:()=>ee,explainViolation:()=>ut,extractSemanticDependencies:()=>Y,loadArkConfigContract:()=>Ae,loadContract:()=>ve,loadResolvedCandidateFacts:()=>q,parseArkConfigJson:()=>Ne,policyDeltaAcknowledgementMatches:()=>je,preflightChange:()=>yt,preflightResolvedChange:()=>mt,resolvedFactsEvidenceRequirementsHash:()=>Ie,stableSerialize:()=>v,toAdapterDiagnostic:()=>we,version:()=>gt});module.exports=Xt(Wn);var gt="3.8.0";var At="1.3";function I(e){return typeof e=="string"&&e.length>0?e:void 0}function ht(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function Qt(e,t,n){return e==="LAYER_IMPORT_VIOLATION"?t.typeOnly||n.targetTypeOnlyExports===!0||n.namedBindingsTypeOnly===!0?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":n.peerIsolation===!0?"Extract the shared dependency to a shared layer, then preflight again.":`Define a port in ${t.fromLayer??"the source layer"}, inject the ${t.toLayer??"outer-layer"} implementation, then preflight again.`:e==="FORBIDDEN_GLOBAL"?`Inject ${t.target??"the capability"} through a port, then preflight again.`:e==="CAPABILITY_VIOLATION"?`Define a ${I(n.capability)??"capability"} port in ${t.fromLayer??"the walled layer"}, bind the implementation outside it, then preflight again.`:e==="CIRCULAR_DEPENDENCY"?"Extract the shared dependency into a third module, then preflight again.":e==="RAW_EVENT_PUBLISH"?"Publish through a registered intent creator, then run Ark again.":e==="PUBLISH_MISSING_SOURCE"?"Add metadata.source to the publish call, then run Ark again.":`Resolve ${e} without weakening ark.config.json, then run Ark again.`}function we(e,t="error"){let n=I(e.ruleId)??I(e.code)??"ARK_UNKNOWN",s=e.severity==="warning"?"warning":t,r={...I(e.target)?{target:I(e.target)}:{},...I(e.fromLayer)?{fromLayer:I(e.fromLayer)}:{},...I(e.toLayer)?{toLayer:I(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{},...typeof e.targetTypeOnlyExports=="boolean"?{targetTypeOnlyExports:e.targetTypeOnlyExports}:{},...typeof e.sourcePureTypeModule=="boolean"?{sourcePureTypeModule:e.sourcePureTypeModule}:{},...typeof e.namedBindingsTypeOnly=="boolean"?{namedBindingsTypeOnly:e.namedBindingsTypeOnly}:{},...typeof e.portProofEligible=="boolean"?{portProofEligible:e.portProofEligible}:{},...typeof e.peerIsolation=="boolean"?{peerIsolation:e.peerIsolation}:{},...I(e.capability)?{capability:I(e.capability)}:{},...I(e.edgeKind)?{edgeKind:I(e.edgeKind)}:{}};return{ruleId:n,severity:s,message:I(e.message)??n,location:{file:I(e.file)??"<unknown>",line:ht(e.line,1),column:ht(e.column,1)},evidence:r,nextAction:I(e.nextAction)??Qt(n,r,e)}}function bt(e){let t=e.completeness??"complete",n=e.mode??"lexical-compatibility";if(t==="complete"&&(e.completenessReasons?.length??0)>0)throw new Error("completenessReasons must be empty when completeness is complete.");let s=t==="complete"?[]:e.completenessReasons&&e.completenessReasons.length>0?e.completenessReasons.map(c=>({code:I(c.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:I(c.message)??`Analysis ${t}: required evidence is incomplete.`,...I(c.file)?{file:I(c.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],r={...I(e.policyHash)?{policyHash:I(e.policyHash)}:{},...I(e.resolverIdentity)?{resolverIdentity:I(e.resolverIdentity)}:{},...I(e.factsHash)?{factsHash:I(e.factsHash)}:{},...I(e.candidateTreeHash)?{candidateTreeHash:I(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let c of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!r[c])throw new Error(`${c} is required for resolved ${t} adapter evidence.`)}let i=[...(e.violations??[]).map(c=>we(c,"error")),...(e.warnings??[]).map(c=>we(c,"warning"))],a={schemaVersion:"1.3",completenessReasons:s,diagnostics:i};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...a,mode:n,valid:!1,completeness:t,...r};let c={policyHash:r.policyHash,resolverIdentity:r.resolverIdentity,factsHash:r.factsHash,candidateTreeHash:r.candidateTreeHash};return t==="complete"?{...a,mode:n,valid:e.valid,completeness:t,...c}:{...a,mode:n,valid:!1,completeness:t,...c}}return t==="complete"?{...a,mode:n,valid:e.valid,completeness:t,...r}:{...a,mode:n,valid:!1,completeness:t,...r}}var Ct={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","mode","valid","completeness","completenessReasons","diagnostics"],allOf:[{if:{properties:{completeness:{enum:["partial","unavailable"]}},required:["completeness"]},then:{properties:{valid:{const:!1}}}},{if:{properties:{mode:{const:"resolved-candidate-facts"},completeness:{enum:["complete","partial"]}},required:["mode","completeness"]},then:{required:["policyHash","resolverIdentity","factsHash","candidateTreeHash"]}},{if:{properties:{completeness:{const:"complete"}},required:["completeness"]},then:{properties:{completenessReasons:{maxItems:0}}},else:{properties:{completenessReasons:{minItems:1}}}}],properties:{schemaVersion:{const:"1.3"},mode:{enum:["lexical-compatibility","resolved-candidate-facts"]},valid:{type:"boolean"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:{type:"string",minLength:1},message:{type:"string",minLength:1},file:{type:"string",minLength:1}}}},policyHash:{type:"string",minLength:1},resolverIdentity:{type:"string",minLength:1},factsHash:{type:"string",minLength:1},candidateTreeHash:{type:"string",minLength:1},diagnostics:{type:"array",items:{type:"object",additionalProperties:!1,required:["ruleId","severity","message","location","evidence"],properties:{ruleId:{type:"string",minLength:1},severity:{enum:["error","warning"]},message:{type:"string",minLength:1},location:{type:"object",additionalProperties:!1,required:["file","line","column"],properties:{file:{type:"string",minLength:1},line:{type:"integer",minimum:1},column:{type:"integer",minimum:1}}},evidence:{type:"object",additionalProperties:!1,properties:{target:{type:"string"},fromLayer:{type:"string"},toLayer:{type:"string"},typeOnly:{type:"boolean"},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"},peerIsolation:{type:"boolean"},capability:{type:"string",minLength:1},edgeKind:{type:"string",minLength:1}}},nextAction:{type:"string",minLength:1}}}}}};var Ke=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),We=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Je=Object.freeze(Object.keys(We).sort()),ze=Object.freeze({fs:"filesystem","node:fs":"filesystem","fs/promises":"filesystem","node:fs/promises":"filesystem","fs-extra":"filesystem","graceful-fs":"filesystem",memfs:"filesystem",chokidar:"filesystem",http:"network",https:"network",http2:"network",net:"network",tls:"network",dgram:"network",dns:"network","node:http":"network","node:https":"network","node:http2":"network","node:net":"network","node:tls":"network","node:dgram":"network","node:dns":"network",axios:"network",undici:"network","node-fetch":"network",got:"network",ky:"network",superagent:"network",ws:"network",process:"process","node:process":"process",child_process:"process","node:child_process":"process","@prisma/client":"persistence",prisma:"persistence",pg:"persistence",mysql:"persistence",mysql2:"persistence",mongodb:"persistence",mongoose:"persistence",sqlite3:"persistence","better-sqlite3":"persistence",redis:"persistence",ioredis:"persistence",typeorm:"persistence",knex:"persistence","drizzle-orm":"persistence",sequelize:"persistence",kysely:"persistence","@supabase/supabase-js":"persistence"}),Ye=Object.freeze({process:Object.freeze(["process","node:process"])});function fe(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=ze[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let s=e.slice(0,n),r=ze[s];if(r)return r;let i=e.indexOf("/",n+1);return i<0?null:ze[e.slice(0,i)]??null}function H(e,t){for(let n of t)if(Ye[n]?.includes(e))return n;return null}function Pe(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let s=t.slice(0,n).join("."),r=We[s];if(r)return r}return null}function te(e){if(e?.pure===!0)return[...Ke].sort();let n=(e?.capabilities?.deny??[]).filter(s=>Ke.includes(s));return[...new Set(n)].sort()}function ue(e,t){if(t.length===0)return!1;let n=new Set(t),s=e.split(".");for(let r=s.length;r>=1;r-=1)if(n.has(s.slice(0,r).join(".")))return!0;return!1}function Oe(e){let t=new Set,n=new Set,s=Object.keys(We);for(let r of e?.forbiddenGlobals??[]){let i=s.filter(a=>a===r||a.startsWith(`${r}.`));if(i.length===0)n.add(r);else for(let a of i)t.add(`ambient:${a}`);for(let a of Ye[r]??[])t.add(`import-exact:${a}`)}for(let r of te(e)){if(t.add(`import:${r}`),r==="process")for(let i of Ye.process)t.add(`import-exact:${i}`);for(let i of s)Pe(i)===r&&t.add(`ambient:${i}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}var It=new Map;function Et(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function Ze(e){let t="";for(let n=0;n<e.length;n+=1){let s=e[n];if(s==="\\"&&n+1<e.length){let r=e[n+1];if("*?{}[],".includes(r)||r==="\\"){t+="\\"+r,n+=1;continue}t+="/";continue}t+=s}return t}function en(e){let t=0;for(let n=0;n<e.length;n+=1){let s=e[n];if(s==="\\"){n+=1;continue}if(s==="{")t+=1;else if(s==="}"&&(t-=1,t<0))return!1}return t===0}function K(e){let t=It.get(e);if(t)return t;let n=Ze(e),s=en(n),r="",i=0;for(let c=0;c<n.length;c+=1){let f=n[c];f==="\\"&&c+1<n.length?(r+=Et(n[c+1]),c+=1):f==="*"?n[c+1]==="*"?n[c+2]==="/"?(r+="(?:.*/)?",c+=2):(r+=".*",c+=1):r+="[^/]*":f==="?"?r+="[^/]":f==="{"&&s?(r+="(?:",i+=1):f==="}"&&s&&i>0?(r+=")",i-=1):f===","&&s&&i>0?r+="|":r+=Et(f)}let a=new RegExp(`^${r}$`);return It.set(e,a),a}function Xe(e){let t=Ze(String(e)),s=t.split("*")[0].split("/").filter(Boolean).length,r=t.replace(/\*/g,"").length;return s*1e4+r}function V(e,t){let n=String(e).split(/[/\\]/).join("/"),s,r=-1;for(let i of t??[])if(!(i.exclude??[]).some(a=>K(a).test(n))){for(let a of i.patterns??[])if(K(a).test(n)){let c=Xe(a);c>r&&(r=c,s=i.name)}}return s}function Rt(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),s=new Set(t.map(r=>String(r).toLowerCase()));for(let r=0;r<n.length-1;r+=1)if(s.has(n[r].toLowerCase()))return`${n[r].toLowerCase()}/${n[r+1].toLowerCase()}`}function tn(e){let t=new Set;for(let n of e??[]){let r=Ze(String(n)).split("/").filter(Boolean);for(let i=0;i<r.length;i+=1){let a=r[i];if((a==="**"||a==="*")&&i>0){let c=r[i-1];c&&!c.includes("*")&&!c.includes("{")&&!c.includes("}")&&t.add(c)}}}return[...t]}function nn(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(r=>typeof r=="string"&&r.length>0);let s=(n??[]).find(r=>r.name===t);return tn(s?.patterns)}function T(e,t,n,s){for(let r of e??[])if(!(r.from!==t||r.to!==n)&&r.allowed===!1){if(r.peerIsolation){let i=s?.fromPath,a=s?.toPath;if(!i||!a)continue;let c=nn(r,t,s?.layers);if(c.length===0)continue;let f=Rt(i,c),A=Rt(a,c);if(!f||!A)continue;if(f!==A)return r;continue}if(t!==n)return r}}function ne(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function xt(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function vt(e,t){if(e.isImportDeclaration(t)){let s=t.importClause;if(!s)return!1;if(s.isTypeOnly)return!0;let r=s.namedBindings;return!!(r&&e.isNamedImports(r)&&r.elements.length>0&&r.elements.every(i=>i.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(s=>s.isTypeOnly))}function kt(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},s=e.createCompilerHost(n,!0);return s.getSourceFile=r=>r===t.fileName?t:void 0,s.fileExists=r=>r===t.fileName,s.readFile=r=>r===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,s).getTypeChecker()}function Qe(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function et(e,t,n,s){let r=s.parent&&e.isShorthandPropertyAssignment(s.parent)&&s.parent.name===s,i;try{i=r?t.getShorthandAssignmentValueSymbol(s.parent):Qe(t,s)}catch{i=void 0}return!!i?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}function Y(e,t){let n,s=[],r=(a,c,f,A=!1)=>s.push({specifier:f,kind:c,line:xt(t,a),typeOnly:A,unresolved:f===void 0,node:a}),i=a=>{if(e.isImportDeclaration(a))r(a,"import",ne(e,a.moduleSpecifier),vt(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)r(a,"export",ne(e,a.moduleSpecifier),vt(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))r(a,"require",ne(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let c=a.expression.kind===e.SyntaxKind.ImportKeyword,A=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!et(e,n??(n=kt(e,t)),t,a.expression);(c||A)&&r(a,A?"require":"dynamic-import",ne(e,a.arguments[0]))}e.forEachChild(a,i)};return i(t),s}function rn(e,t){let n=[],s=t;for(;e.isPropertyAccessExpression(s)||e.isElementAccessExpression(s);){if(e.isPropertyAccessExpression(s))n.unshift(s.name.text);else{let r=ne(e,s.argumentExpression);if(r===void 0)return;n.unshift(r)}s=s.expression}if(e.isIdentifier(s))return n.unshift(s.text),{root:s,segments:n}}function sn(e,t){let n=t.parent;return e.isPropertyAccessExpression(n)||e.isElementAccessExpression(n)?!1:e.isExpressionNode(t)&&!e.isInTypeQuery(t)||e.isShorthandPropertyAssignment(n)&&n.name===t}function St(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let s=n.length;s>=1;s-=1){let r=n.slice(0,s).join(".");if(e.has(r))return r}}function W(e,t,n){if(n.length===0)return[];let s=new Set(n),r=kt(e,t),i=new Map,a=new Set;for(let o of t.statements)if(e.isVariableStatement(o))for(let l of o.declarationList.declarations)e.isIdentifier(l.name)&&a.add(l.name.text);let c=o=>{let l=rn(e,o);if(!l)return;let d=Qe(r,l.root),p=d?i.get(d):void 0;return p?[...p,...l.segments.slice(1)]:et(e,r,t,l.root)||a.has(l.root.text)?void 0:l.segments};for(let o of t.statements)if(e.isVariableStatement(o))for(let l of o.declarationList.declarations){if(!l.initializer||!e.isIdentifier(l.name))continue;let d=c(l.initializer),p=Qe(r,l.name);!d||!p||i.set(p,d)}let f=[],A=new Set,g=(o,l)=>{let d=xt(t,l),p=`${o}:${l.getStart(t)}`;A.has(p)||(A.add(p),f.push({name:o,line:d,node:l}))},u=o=>{let l=o.parent&&(e.isPropertyAccessExpression(o.parent)||e.isElementAccessExpression(o.parent))&&o.parent.expression===o;if((e.isPropertyAccessExpression(o)||e.isElementAccessExpression(o))&&!l){let d=c(o),p=d?St(s,d):void 0;p&&g(p,o)}else e.isIdentifier(o)&&s.has(o.text)&&sn(e,o)&&!et(e,r,t,o)&&g(o.text,o);if(e.isVariableDeclaration(o)&&e.isObjectBindingPattern(o.name)&&o.initializer){let d=c(o.initializer);if(d)for(let p of o.name.elements){if(!e.isIdentifier(p.name))continue;let y=p.propertyName?ne(e,p.propertyName)??p.propertyName.text:p.name.text,h=St(s,[...d,y]);h&&g(h,o.initializer)}}e.forEachChild(o,u)};return u(t),f}function tt(e,t,n){let s=[];for(let r of n?.dependencies??Y(e,t)){if(r.typeOnly||!r.specifier)continue;let i=fe(r.specifier);i&&s.push({capability:i,symbol:r.specifier,line:r.line,source:"import-based"})}for(let r of n?.ambientUses??W(e,t,Je)){let i=Pe(r.name);i&&s.push({capability:i,symbol:r.name,line:r.line,source:"ambient-global"})}return s.sort((r,i)=>r.line-i.line||r.capability.localeCompare(i.capability)||r.symbol.localeCompare(i.symbol))}var nt={RAW_EVENT_PUBLISH:"Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts and tooling.",PUBLISH_MISSING_SOURCE:"Strict Ark publish calls must include metadata.source."},rt=Object.freeze([{layer:"DomainModel",prefixes:["Domain."]},{layer:"ApplicationOrchestration",prefixes:["Application."]},{layer:"PersistenceAdapters",prefixes:["Adapter.Persistence.","Adapter.Repository."]},{layer:"IntegrationAdapters",prefixes:["Adapter.Integration.","Adapter.External."]},{layer:"WorkflowSagaEngine",prefixes:["Workflow."]},{layer:"BackgroundJobsScheduling",prefixes:["Job."]},{layer:"PresentationAdapters",prefixes:["Presentation.","Adapter.Presentation.","Adapter.Api."]},{layer:"ReportingReadModels",prefixes:["Reporting."]},{layer:"ExtensibilityMetadata",prefixes:["Metadata."]},{layer:"SecurityAuditObservability",prefixes:["Security.","Audit.","Observability."]},{layer:"Kernel",prefixes:["Kernel."]}]);function it(e,t){return t.flatMap((s,r)=>(s.prefixes??s.intentPrefixes??[]).map(i=>({layer:s.name,layerIndex:r,prefix:i.endsWith(".")?i:`${i}.`}))).filter(({prefix:s})=>e.startsWith(s)).sort((s,r)=>r.prefix.length-s.prefix.length||s.layerIndex-r.layerIndex)[0]?.layer}function J(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function ye(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&J(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:nt.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:nt.PUBLISH_MISSING_SOURCE}),t}function R(e,t,n){return{ruleId:e,code:e,message:t,...n}}function re(e,t){return e.slice(0,t).split(`
|
|
2
|
+
`).length}function an(e){let t=[],n=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,s;for(;(s=n.exec(e))!==null;)t.push({value:s[1],index:s.index});return t}function on(e){let t=[],n=[{kind:"import",re:/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s*)?['"]([^'"]+)['"]/g},{kind:"export",re:/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s*['"]([^'"]+)['"]/g},{kind:"dynamic-import",re:/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g},{kind:"require",re:/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g}];for(let s of n){let r;for(;(r=s.re.exec(e))!==null;){let i=r.index+r[0].indexOf(r[1]),a=r[0],c=s.kind==="import"&&/\bimport\s+type\b/.test(a)||s.kind==="export"&&/\bexport\s+type\b/.test(a);t.push({value:r[1],index:i,kind:s.kind,typeOnly:c})}}return t.sort((s,r)=>s.index-r.index)}function ln(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),s=[],r=i=>{e.isStringLiteralLike(i)&&s.push({value:i.text,index:i.getStart(n)}),e.forEachChild(i,r)};return r(n),s}function cn(e){let t=e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);return["adapter","adapters","infra","infrastructure","persistence","repository","repositories","integration","database","db"].some(n=>t.includes(n))}function pn(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}function dn(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}function ge(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function fn(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}function wt(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(s=>!e.isPropertyAssignment(s)&&!e.isShorthandPropertyAssignment(s)?!1:fn(e,s.name)===n)}function he(e,t,n){return wt(e,t,n)!==void 0}function me(e,t,n){let s=wt(e,t,n);return s&&e.isPropertyAssignment(s)?s.initializer:void 0}function un(e,t){let n=me(e,t,"metadata");return he(e,n,"source")}function Pt(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?Pt(e,t.name):!1:!1}function yn(e,t){if(!e.isCallExpression(t))return!1;let n=t.expression;return e.isPropertyAccessExpression(n)?n.name.text==="publish":e.isIdentifier(n)&&n.text==="publish"}function mn(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],s=ge(e,n);return s!==void 0&&J(s)||he(e,n,"intent")||Pt(e,n)}function gn(e,t){if(!e.isCallExpression(t))return!1;let[n,s,r]=t.arguments;return un(e,n)||he(e,s,"source")||he(e,r,"source")}function hn(e,t){if(!e.isCallExpression(t))return;let[n,s,r]=t.arguments,i=me(e,n,"metadata");return ge(e,me(e,i,"source"))??ge(e,me(e,s,"source"))??ge(e,me(e,r,"source"))}function An(e,t,n,s){let r=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),i=n,a=i?.filePath,c=i?.layer,f=[],A=u=>r.getLineAndCharacterOfPosition(u.getStart(r)).line+1,g=u=>{if(yn(e,u)){let o=u.arguments[0],l=ge(e,o);for(let p of ye({publishCall:!0,rawIntentName:l,objectHasIntent:he(e,o,"intent"),arkPublishCandidate:mn(e,u),hasSource:gn(e,u)}))f.push(R(p.ruleId,p.message,{line:A(u),filePath:a}));let d=hn(e,u);if(s&&c&&d&&J(d)){let p=s.resolveLayer(d);p&&p!==c&&f.push(R("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${d}" resolves to ${p}, but the target file is classified as ${c}.`,{line:A(u),filePath:a,target:d,fromLayer:c,toLayer:p}))}}e.forEachChild(u,g)};return g(r),f}function st(e={}){let t=new Set((e.intents||[]).map(i=>typeof i=="string"?i:i.name)),n=e.forbiddenPatterns||[],s=new Set(e.infrastructureLayers??[]),r=e.enforceIntentAllowlist??t.size>0;return{validate(i,a){let c=[],f=a,A=f?.filePath,g=f?.layer,u=e.typescript,o=u?u.createSourceFile(A??"generated.ts",i,u.ScriptTarget.Latest,!0):void 0,l=o?Y(e.typescript,o):void 0,d=l?l.filter(m=>m.specifier!==void 0).map(m=>({value:m.specifier,index:m.node.getStart(o),kind:m.kind,typeOnly:m.typeOnly})):on(i),p=e.typescript?ln(e.typescript,i):an(i);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(A))for(let m of l?.filter(({unresolved:b})=>b)??[]){let b=m.kind==="require";c.push(R(b?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${b?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:m.line,filePath:A}))}let y=g!==void 0&&(s.has(g)||dn(g)),h=g!==void 0?` If "${g}" is an infrastructure layer, mark it in ark.config.json with "mayImportInfrastructure": true (or name it with an infra token like Adapters/Persistence/Repository).`:"";for(let m of n)if(m instanceof RegExp){m.lastIndex=0;let b=m.exec(i);m.lastIndex=0,b&&c.push(R("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${m}`,{line:b.index===void 0?void 0:re(i,b.index),filePath:A,suggestion:"Remove infrastructure imports from domain/application layers."+h}))}else i.includes(m)&&c.push(R("FORBIDDEN_SUBSTRING",`Forbidden substring: ${m}`,{line:re(i,i.indexOf(m)),filePath:A}));for(let m of d){let b=e.resolveImportTarget?.(m.value,A)??(e.resolveImportLayer?{layer:e.resolveImportLayer(m.value,A)}:void 0),C=typeof A=="string"?e.resolveImportTarget?.(A)??(e.resolveImportLayer?{layer:g,relPath:void 0}:void 0):void 0,de=b?.layer;if(de&&g){let ke=T(e.architectureProfile?.rules,g,de,{fromPath:C?.relPath,toPath:b?.relPath,layers:e.architectureLayers});if(ke){if(m.typeOnly&&!ke.peerIsolation)continue;let Be=!!ke.peerIsolation;c.push(R("LAYER_IMPORT_VIOLATION",ke.message??(Be?`Layer "${g}" must not import across slices into "${de}".`:`Layer "${g}" must not import "${de}".`),{line:re(i,m.index),source:m.value,target:m.value,filePath:A,fromLayer:g,toLayer:de,suggestion:Be?"Extract shared code to a shared layer, or coordinate slices via events/ports \u2014 do not import across feature/context slices.":"Depend on a port/interface owned by an inner layer instead, or move this code to a layer allowed to make this import.",details:{importKind:m.kind,peerIsolation:Be,...m.typeOnly?{typeOnly:!0}:{}}}));continue}continue}y||m.typeOnly||!cn(m.value)&&!pn(m.value)||c.push(R("FORBIDDEN_IMPORT",`Forbidden ${m.kind} target: "${m.value}".`,{line:re(i,m.index),source:m.value,target:m.value,filePath:A,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+h,details:{importKind:m.kind}}))}if(e.policies)for(let m of e.policies){let b=m.check({source:i,context:a});if(b!==!0)if(Array.isArray(b))for(let C of b)c.push(R("POLICY_VIOLATION",C.message,{filePath:A,suggestion:`Fix violation of policy "${m.name}".`}));else b===!1?c.push(R("POLICY_VIOLATION",`Policy ${m.name} failed on generated code`)):c.push(R("POLICY_VIOLATION",b.message))}if(r&&t.size>0)for(let m of p)J(m.value)&&!t.has(m.value)&&c.push(R("UNKNOWN_INTENT",`Unknown intent reference: "${m.value}"`,{line:re(i,m.index),filePath:A,target:m.value,suggestion:`Register intent "${m.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&g)for(let m of p){if(!J(m.value))continue;let b=e.architectureProfile.resolveLayer(m.value);if(!b)continue;let C=T(e.architectureProfile.rules,g,b);C&&c.push(R("LAYER_REFERENCE_VIOLATION",C.message??`Layer "${g}" must not reference "${b}" through "${m.value}".`,{line:re(i,m.index),filePath:A,target:m.value,fromLayer:g,toLayer:b,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:C}}))}if(e.extensions)for(let m of e.extensions)try{let b=m.analyze(i,a);c.push(...b)}catch(b){c.push(R("EXTENSION_ERROR",`Extension "${m.name}" failed: ${b instanceof Error?b.message:String(b)}`))}if(e.typescript&&o&&g&&e.forbiddenGlobals?.[g]?.length)try{let m=e.forbiddenGlobals[g];c.push(...W(e.typescript,o,m).map(b=>R("FORBIDDEN_GLOBAL",`${g} must not use the ambient global "${b.name}".`,{line:b.line,filePath:A,target:b.name,fromLayer:g,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let b of l??[]){if(b.typeOnly||!b.specifier)continue;let C=H(b.specifier,m);C&&c.push(R("FORBIDDEN_GLOBAL",`${g} must not use module "${b.specifier}" because it is the import form of forbidden global "${C}".`,{line:b.line,filePath:A,source:b.specifier,target:b.specifier,fromLayer:g,details:{importKind:b.kind,forbiddenGlobal:C},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(m){c.push(R("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${m instanceof Error?m.message:String(m)}`))}if(e.typescript&&o&&g&&e.capabilityWalls?.[g]?.length)try{let m=new Set(e.capabilityWalls[g]),b=e.forbiddenGlobals?.[g]??[];for(let C of tt(e.typescript,o))m.has(C.capability)&&(C.source==="ambient-global"&&ue(C.symbol,b)||C.source==="import-based"&&H(C.symbol,b)||c.push(R("CAPABILITY_VIOLATION",C.source==="import-based"?`${g} denies the ${C.capability} capability; found import of "${C.symbol}".`:`${g} denies the ${C.capability} capability; found ambient "${C.symbol}".`,{line:C.line,filePath:A,target:C.symbol,capability:C.capability,fromLayer:g,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(m){c.push(R("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${m instanceof Error?m.message:String(m)}`))}if(e.typescript)try{c.push(...An(e.typescript,i,a,e.architectureProfile))}catch(m){c.push(R("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${m instanceof Error?m.message:String(m)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:c.length===0,violations:c}}}}var Lt="1.0",$e="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",Ot=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],bn=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Cn(){let e=[];for(let t of Ot)for(let n of Ot)t===n||bn.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var Te=Cn();var j={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},_e={$schema:"https://json-schema.org/draft/2020-12/schema",$id:$e,title:"ArkGate architecture contract",description:"Versioned contract consumed identically by ArkGate CLI, MCP, and ESLint surfaces.",type:"object",additionalProperties:!1,required:["$schema","schemaVersion","include","layers","rules"],properties:{$schema:{type:"string",minLength:1,default:$e,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:"1.0",default:"1.0"},name:{type:"string",minLength:1},include:{...j,minItems:1,default:["src"]},exclude:{...j,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:Te,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...j,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...j,minItems:1},exclude:j,intentPrefixes:j,description:{type:"string",minLength:1},forbiddenGlobals:j,capabilities:{type:"object",additionalProperties:!1,properties:{deny:{type:"array",uniqueItems:!0,items:{type:"string",enum:["network","filesystem","clock","randomness","environment","process","persistence"]}}}},pure:{type:"boolean"},mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...j,minItems:1}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}}}},se=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
|
|
3
|
+
${n.map(s=>`- ${s.path}: ${s.message}`).join(`
|
|
4
|
+
`)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function $t(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function at(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function ie(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function In(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function Le(e,t,n,s,r){if(t.$ref){let i=In(t.$ref,s);if(!i){r.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}Le(e,i,n,s,r);return}if(t.const!==void 0&&!Object.is(e,t.const)){r.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(i=>Object.is(i,e))){r.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!$t(e)){r.push({path:n,message:`must be an object; received ${ie(e)}`});return}let i=t.properties??{};for(let a of t.required??[])e[a]===void 0&&r.push({path:at(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in i||r.push({path:at(n,a),message:"unknown field"});for(let[a,c]of Object.entries(i))e[a]!==void 0&&Le(e[a],c,at(n,a),s,r);return}if(t.type==="array"){if(!Array.isArray(e)){r.push({path:n,message:`must be an array; received ${ie(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&r.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let i=e.map(a=>JSON.stringify(a));new Set(i).size!==i.length&&r.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((i,a)=>Le(i,t.items,`${n}[${a}]`,s,r));return}if(t.type==="string"){if(typeof e!="string"){r.push({path:n,message:`must be a string; received ${ie(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&r.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&r.push({path:n,message:`must be a boolean; received ${ie(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){r.push({path:n,message:`must be an integer; received ${ie(e)}`});return}t.minimum!==void 0&&e<t.minimum&&r.push({path:n,message:`must be at least ${t.minimum}`})}}function En(e){return{...e,$schema:e.$schema===void 0?$e:e.$schema,schemaVersion:e.schemaVersion===void 0?"1.0":e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?Te.map(t=>({...t})):e.rules}}function Rn(e,t="ark.config.json"){if(!$t(e))throw new se(t,[{path:"$",message:`must be an object; received ${ie(e)}`}]);let n=e.schemaVersion===void 0?"unversioned":null;if(e.schemaVersion!==void 0&&e.schemaVersion!=="1.0")throw new se(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.0`}]);return{candidate:En(e),migratedFrom:n}}function Ae(e,t="ark.config.json"){let{candidate:n,migratedFrom:s}=Rn(e,t),r=[];if(Le(n,_e,"$",_e,r),r.length>0)throw new se(t,r);return{config:n,migratedFrom:s}}function Ne(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(s){throw new se(t,[{path:"$",message:`invalid JSON: ${s instanceof Error?s.message:String(s)}`}])}return Ae(n,t)}function _t(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:$e,schemaVersion:"1.0"};for(let[n,s]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=s);return t}function vn(e){return e.endsWith(".")?e:`${e}.`}function Sn(e,t){let n=e.prefixes.length?Math.max(...e.prefixes.map(r=>r.length)):0;return(t.prefixes.length?Math.max(...t.prefixes.map(r=>r.length)):0)-n}function Ce(e){let t=e.layers.map(r=>({...r,prefixes:r.prefixes.map(vn)})),n=[...t].sort(Sn),s=[...e.rules??[]];return{name:e.name,layers:t,rules:s,resolveLayer(r){return t.find(i=>i.match?.(r))?.name??n.find(i=>i.prefixes.some(a=>r.startsWith(a)))?.name}}}function ot(e,t={}){return Ce({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,s)=>({name:n.name,prefixes:n.intentPrefixes??[],description:n.description,order:s+1})),rules:e.rules??[]})}var xn=[{name:"DomainModel",prefixes:["Domain"],description:"Rich domain model, business rules, and domain events.",order:1},{name:"ApplicationOrchestration",prefixes:["Application"],description:"Use cases and command orchestration.",order:2},{name:"PersistenceAdapters",prefixes:["Adapter.Persistence","Adapter.Repository"],description:"Database, repository, and storage adapters.",order:3},{name:"IntegrationAdapters",prefixes:["Adapter.Integration","Adapter.External"],description:"External systems, APIs, and integration adapters.",order:4},{name:"WorkflowSagaEngine",prefixes:["Workflow"],description:"Sagas, workflows, and long-running processes.",order:5},{name:"BackgroundJobsScheduling",prefixes:["Job"],description:"Background jobs, scheduled work, and async processors.",order:6},{name:"PresentationAdapters",prefixes:["Presentation","Adapter.Presentation","Adapter.Api"],description:"API, UI, controller, and presentation adapters.",order:7},{name:"ReportingReadModels",prefixes:["Reporting"],description:"Read models, projections, and reporting surfaces.",order:8},{name:"ExtensibilityMetadata",prefixes:["Metadata"],description:"Metadata, extensions, and schema contracts.",order:9},{name:"SecurityAuditObservability",prefixes:["Security","Audit","Observability"],description:"Security, audit, and observability concerns.",order:10},{name:"Kernel",prefixes:["Kernel"],description:"Ark-owned governance and kernel signals.",order:11}],be=Ce({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:xn,rules:Te.map(e=>({...e}))}),kn={DomainModel:["domain"],ApplicationOrchestration:["application","app"],PersistenceAdapters:["adapters/persistence","adapters/repository","repositories","infra/persistence"],IntegrationAdapters:["adapters/integration","adapters/external","integrations"],WorkflowSagaEngine:["workflows","sagas"],BackgroundJobsScheduling:["jobs","schedules"],PresentationAdapters:["presentation","adapters/presentation","adapters/api"],ReportingReadModels:["reporting","read-models","projections"],ExtensibilityMetadata:["metadata","extensions"],SecurityAuditObservability:["security","audit","observability"],Kernel:["kernel"]};function lt(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,s=t==="."?"":`${t}/`;return _t({include:e.include??[t],layers:be.layers.map(r=>({name:r.name,patterns:(kn[r.name]??[r.name]).map(i=>`${s}${i}/**`),intentPrefixes:r.prefixes,optional:n})),rules:[...be.rules]})}var De="1.0",ct="1.0",Nt=["network","filesystem","clock","randomness","environment","process","persistence"];function k(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}function v(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(v).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${v(t[n])}`).join(",")}}`}function B(e,t){let n=v(e),s=v(t);return n<s?-1:n>s?1:0}function $(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}function Ie(e){let t={schemaVersion:"1.0",include:$(e.include??[]),exclude:$(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:$(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:$(n.patterns??[]),exclude:$(n.exclude??[]),forbiddenGlobals:$(n.forbiddenGlobals??[]),intentPrefixes:$(n.intentPrefixes??[]),capabilityDeny:$(n.capabilities?.deny??[]),pure:n.pure===!0})).sort(B),safety:{maxTsSuppressions:e.safety?.maxTsSuppressions??0,maxAnyCasts:e.safety?.maxAnyCasts??0,allowInMemory:e.safety?.allowInMemory===!0,allowDisabledPeerIsolation:e.safety?.allowDisabledPeerIsolation===!0}};return k(v(t))}function wn(e){let t=e.completenessReasons.map(u=>({code:u.code,message:u.message,...u.file?{file:u.file}:{}})).sort(B),n=e.files.map(u=>({...u,typeOnlyExportNames:$(u.typeOnlyExportNames)})).sort((u,o)=>u.path<o.path?-1:u.path>o.path?1:0),s=e.dependencies.map(u=>({...u,...u.namedBindings?{namedBindings:$(u.namedBindings)}:{}})).sort(B),r=e.capabilityUses.map(u=>({...u})).sort(B),i=e.ambientUses.map(u=>({...u})).sort(B),a=e.publishCalls.map(u=>({...u})).sort(B),c=e.intentReferences.map(u=>({...u})).sort(B),f=e.safetyUses.map(u=>({...u})).sort(B),A=e.files.map(({path:u,contentHash:o})=>({path:u,contentHash:o})).sort((u,o)=>u.path<o.path?-1:u.path>o.path?1:0),g=k(v(A));return{schemaVersion:"1.0",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:g,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:s,capabilityUses:r,ambientUses:i,publishCalls:a,intentReferences:c,safetyUses:f}}function Dt(e){let t=wn(e);return{...t,factsHash:k(v(t))}}function pt(e){return Dt(Mt(_(e,"$"),!1))}function _(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}function N(e,t,n){let s=new Set(t),r=Object.keys(e).find(i=>!s.has(i));if(r)throw new Error(`${n}.${r} is not part of schema 1.0.`)}function x(e,t,n){let s=e[t];if(typeof s!="string"||s.length===0)throw new Error(`${n}.${t} must be a non-empty string.`);return s}function ae(e,t,n){if(e[t]!==void 0)return x(e,t,n)}function D(e,t,n){let s=x(e,t,n),r=s.replace(/\\/g,"/");if(!r||r.startsWith("/")||/^[A-Za-z]:\//.test(r)||/[\u0000-\u001f\u007f]/.test(r))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let i=[];for(let c of r.split("/"))if(!(!c||c==="."))if(c===".."){if(i.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);i.pop()}else i.push(c);let a=i.join("/");if(!a||a!==s)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return a}function L(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}function Ft(e,t,n){let s=e[t];if(!Number.isInteger(s)||Number(s)<0)throw new Error(`${n}.${t} must be a non-negative integer.`);return Number(s)}function oe(e,t,n){let s=Ft(e,t,n);if(s===0)throw new Error(`${n}.${t} must be a positive integer.`);return s}function G(e,t,n){let s=e[t];if(!Array.isArray(s))throw new Error(`${n}.${t} must be an array.`);return s}function U(e,t,n,s){let r=e[t];if(typeof r!="string"||!n.includes(r))throw new Error(`${s}.${t} must be one of ${n.join(", ")}.`);return r}function Tt(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!n))throw new Error(`${t} must be an array of non-empty strings.`);return[...e]}function Pn(e,t,n){let s=new Set;for(let r of e){let i=t(r);if(s.has(i))throw new Error(`${n} must not contain duplicate facts (${i}).`);s.add(i)}}function Mt(e,t){N(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=U(e,"schemaVersion",["1.0"],"$"),s=U(e,"completeness",["complete","partial","unavailable"],"$"),r=G(e,"completenessReasons","$").map((d,p)=>{let y=`$.completenessReasons[${p}]`,h=_(d,y);N(h,["code","message","file"],y);let m=h.file===void 0?void 0:D(h,"file",y);return{code:x(h,"code",y),message:x(h,"message",y),...m?{file:m}:{}}});if(s==="complete"&&r.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(s!=="complete"&&r.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let i=G(e,"files","$").map((d,p)=>{let y=`$.files[${p}]`,h=_(d,y);return N(h,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],y),{path:D(h,"path",y),contentHash:x(h,"contentHash",y),parseStatus:U(h,"parseStatus",["parsed","invalid"],y),parseDiagnosticCount:Ft(h,"parseDiagnosticCount",y),exportsOnlyTypes:L(h,"exportsOnlyTypes",y),typeOnlyExportNames:Tt(h.typeOnlyExportNames,`${y}.typeOnlyExportNames`),hasTopLevelSideEffects:L(h,"hasTopLevelSideEffects",y)}}),a=G(e,"dependencies","$").map((d,p)=>{let y=`$.dependencies[${p}]`,h=_(d,y);N(h,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],y);let m=ae(h,"specifier",y),b=ae(h,"target",y),C=U(h,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],y);if(C==="resolved-project"&&!b)throw new Error(`${y}.target is required for resolved-project dependencies.`);if(C!=="resolved-project"&&b)throw new Error(`${y}.target is only allowed for resolved-project dependencies.`);if(C!=="dynamic"&&!m)throw new Error(`${y}.specifier is required unless resolution is dynamic.`);return{from:D(h,"from",y),...m?{specifier:m}:{},kind:U(h,"kind",["import","export","dynamic-import","require"],y),typeOnly:L(h,"typeOnly",y),line:oe(h,"line",y),resolution:C,...b?{target:D(h,"target",y)}:{},...h.namedBindings!==void 0?{namedBindings:Tt(h.namedBindings,`${y}.namedBindings`)}:{},...h.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:L(h,"targetTypeOnlyExports",y)}:{},...h.sourcePureTypeModule!==void 0?{sourcePureTypeModule:L(h,"sourcePureTypeModule",y)}:{},...h.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:L(h,"namedBindingsTypeOnly",y)}:{},...h.portProofEligible!==void 0?{portProofEligible:L(h,"portProofEligible",y)}:{}}}),c=G(e,"capabilityUses","$").map((d,p)=>{let y=`$.capabilityUses[${p}]`,h=_(d,y);return N(h,["file","line","symbol","capability","source"],y),{file:D(h,"file",y),line:oe(h,"line",y),symbol:x(h,"symbol",y),capability:U(h,"capability",Nt,y),source:U(h,"source",["ambient-global","import-based"],y)}}),f=G(e,"ambientUses","$").map((d,p)=>{let y=`$.ambientUses[${p}]`,h=_(d,y);return N(h,["file","line","symbol"],y),{file:D(h,"file",y),line:oe(h,"line",y),symbol:x(h,"symbol",y)}}),A=G(e,"publishCalls","$").map((d,p)=>{let y=`$.publishCalls[${p}]`,h=_(d,y);N(h,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],y);let m=ae(h,"rawIntentName",y),b=ae(h,"sourceIntent",y);return{file:D(h,"file",y),line:oe(h,"line",y),...m?{rawIntentName:m}:{},objectHasIntent:L(h,"objectHasIntent",y),arkPublishCandidate:L(h,"arkPublishCandidate",y),hasSource:L(h,"hasSource",y),...b?{sourceIntent:b}:{}}}),g=G(e,"intentReferences","$").map((d,p)=>{let y=`$.intentReferences[${p}]`,h=_(d,y);return N(h,["file","line","intent"],y),{file:D(h,"file",y),line:oe(h,"line",y),intent:x(h,"intent",y)}}),u=G(e,"safetyUses","$").map((d,p)=>{let y=`$.safetyUses[${p}]`,h=_(d,y);N(h,["file","line","kind","symbol"],y);let m=ae(h,"symbol",y),b=U(h,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],y);if(b==="in-memory-store"&&!m)throw new Error(`${y}.symbol is required for in-memory-store facts.`);if(b!=="in-memory-store"&&m)throw new Error(`${y}.symbol is only allowed for in-memory-store facts.`);return{file:D(h,"file",y),line:oe(h,"line",y),kind:b,...m?{symbol:m}:{}}});Pn(i,d=>d.path,"$.files");let o=new Set(i.map(d=>d.path));for(let d of i){if(d.parseStatus==="parsed"&&d.parseDiagnosticCount!==0)throw new Error(`$.files[${d.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(d.parseStatus==="invalid"&&d.parseDiagnosticCount===0)throw new Error(`$.files[${d.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(s==="complete"&&i.some(d=>d.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let d of a)if(!o.has(d.from))throw new Error(`$.dependencies references missing source file ${d.from}.`);for(let[d,p]of[["$.capabilityUses",c],["$.ambientUses",f],["$.publishCalls",A],["$.intentReferences",g],["$.safetyUses",u]])for(let y of p)if(!o.has(y.file))throw new Error(`${d} references missing file ${y.file}.`);let l=ae(e,"projectPackageName","$");return{schemaVersion:n,completeness:s,completenessReasons:r,resolverIdentity:x(e,"resolverIdentity","$"),compilerIdentity:x(e,"compilerIdentity","$"),compilerOptionsHash:x(e,"compilerOptionsHash","$"),tsconfigHash:x(e,"tsconfigHash","$"),evidenceRequirementsHash:x(e,"evidenceRequirementsHash","$"),...l?{projectPackageName:l}:{},files:i,dependencies:a,capabilityUses:c,ambientUses:f,publishCalls:A,intentReferences:g,safetyUses:u}}function q(e){let t=_(e,"$"),n=x(t,"factsHash","$"),s=x(t,"candidateTreeHash","$"),r=Dt(Mt(t,!0));if(r.factsHash!==n)throw new Error(`$.factsHash does not match the canonical payload (${r.factsHash}).`);if(s!==r.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${r.candidateTreeHash}).`);return r}var E={type:"string",minLength:1},le={type:"integer",minimum:1},F={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},dt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.resolved-candidate-facts.schema.json",title:"ArkGate resolved candidate facts",type:"object",additionalProperties:!1,required:["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","candidateTreeHash","evidenceRequirementsHash","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","factsHash"],properties:{schemaVersion:{const:"1.0"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:E,message:E,file:F}}},resolverIdentity:E,compilerIdentity:E,compilerOptionsHash:E,tsconfigHash:E,candidateTreeHash:E,evidenceRequirementsHash:E,projectPackageName:E,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:F,contentHash:E,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:E},hasTopLevelSideEffects:{type:"boolean"}},allOf:[{if:{properties:{parseStatus:{const:"parsed"}}},then:{properties:{parseDiagnosticCount:{const:0}}}},{if:{properties:{parseStatus:{const:"invalid"}}},then:{properties:{parseDiagnosticCount:{minimum:1}}}}]}},dependencies:{type:"array",items:{type:"object",additionalProperties:!1,required:["from","kind","typeOnly","line","resolution"],properties:{from:F,specifier:E,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:le,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:F,namedBindings:{type:"array",items:E},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"}},allOf:[{if:{properties:{resolution:{const:"resolved-project"}}},then:{required:["target"]},else:{not:{required:["target"]}}},{if:{properties:{resolution:{const:"dynamic"}}},else:{required:["specifier"]}}]}},capabilityUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol","capability","source"],properties:{file:F,line:le,symbol:E,capability:{enum:Nt},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:F,line:le,symbol:E}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:F,line:le,rawIntentName:E,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:E}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:F,line:le,intent:E}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:F,line:le,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:E},allOf:[{if:{properties:{kind:{const:"in-memory-store"}}},then:{required:["symbol"]},else:{not:{required:["symbol"]}}}]}},factsHash:E},allOf:[{if:{properties:{completeness:{const:"complete"}}},then:{properties:{completenessReasons:{maxItems:0},files:{items:{properties:{parseStatus:{const:"parsed"}}}}}}},{if:{properties:{completeness:{enum:["partial","unavailable"]}}},then:{properties:{completenessReasons:{minItems:1}}}}]};function P(e){return`${e.from}->${e.to}`}function Ee(e,t,n,s="dependency"){return{id:`${e}:${s}:${P(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${P(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${P(t)}, then preflight again.`}:e==="unplanned"?{nextAction:s==="dependency-removed"?`Restore the removed dependency ${P(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${P(t)} from the candidate, then preflight again.`}:{}}}function Z(e){let t=[],n=new Map(e.changeMap.map.files.map(o=>[o.path,o])),s=new Map(e.changes.map(o=>[o.path,o])),r=new Map(e.changeMap.map.dependencies.map(o=>[P(o),o])),i=new Map(e.baseDependencies.map(o=>[P(o),o])),a=new Map(e.candidateDependencies.map(o=>[P(o),o]));for(let o of[...n.values()].sort((l,d)=>l.path.localeCompare(d.path))){let l=s.get(o.path);l?l.operation!==o.operation?t.push({id:`contradictory:file:${o.path}`,classification:"contradictory",subject:"file",path:o.path,expectedOperation:o.operation,actualOperation:l.operation,message:`${o.path} was planned as ${o.operation} but the actual operation is ${l.operation}.`,nextAction:`Change ${o.path} to the planned ${o.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${o.path}`,classification:"satisfied",subject:"file",path:o.path,expectedOperation:o.operation,actualOperation:l.operation,message:`${o.path} matches the planned ${o.operation} operation.`}):t.push({id:`missing:file:${o.path}`,classification:"missing",subject:"file",path:o.path,expectedOperation:o.operation,message:`${o.path} was planned as ${o.operation} but is absent from the actual change.`,nextAction:`${o.operation[0].toUpperCase()}${o.operation.slice(1)} ${o.path} in the complete change set, then preflight again.`})}for(let o of[...s.values()].sort((l,d)=>l.path.localeCompare(d.path)))n.has(o.path)||t.push({id:`unplanned:file:${o.path}`,classification:"unplanned",subject:"file",path:o.path,actualOperation:o.operation,message:`${o.path} has an unplanned ${o.operation} operation.`,nextAction:`Remove ${o.path} from the change set, then preflight again.`});let c=new Set;for(let o of[...r.values()].sort((l,d)=>P(l).localeCompare(P(d)))){if(a.has(P(o))){t.push(Ee("satisfied",o,`${o.from} -> ${o.to} exists in the candidate architecture.`));continue}let l={from:o.to,to:o.from};a.has(P(l))?(c.add(P(l)),t.push(Ee("contradictory",o,`${o.from} -> ${o.to} was planned, but the candidate contains the reverse edge.`))):t.push(Ee("missing",o,`${o.from} -> ${o.to} is absent from the candidate architecture.`))}let f=new Set([...n.keys(),...s.keys()]);for(let[o,l]of[...a].sort(([d],[p])=>d.localeCompare(p)))i.has(o)||r.has(o)||c.has(o)||!f.has(l.from)&&!f.has(l.to)||t.push({...Ee("unplanned",l,`${l.from} -> ${l.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let A=new Set(e.changeMap.map.files.filter(o=>o.operation==="delete").map(o=>o.path));for(let[o,l]of[...i].sort(([d],[p])=>d.localeCompare(p)))a.has(o)||A.has(l.from)||A.has(l.to)||!f.has(l.from)&&!f.has(l.to)||t.push({...Ee("unplanned",l,`${l.from} -> ${l.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let g={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((o,l)=>g[o.classification]-g[l.classification]||(o.subject===l.subject?0:o.subject==="file"?-1:1)||o.id.localeCompare(l.id));let u={satisfied:t.filter(o=>o.classification==="satisfied").length,missing:t.filter(o=>o.classification==="missing").length,contradictory:t.filter(o=>o.classification==="contradictory").length,unplanned:t.filter(o=>o.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:u.missing===0&&u.contradictory===0&&u.unplanned===0,behavioralCompletion:"not-evaluated",summary:u,findings:t}}var He="1.0";function S(e,t){e.push({id:`${t.classification}:${t.path}:${t.kind}`,path:t.path,classification:t.classification,message:t.message,...t.classification==="weakening"||t.classification==="judgment-required"?{nextAction:`Restore the previous protection at ${t.path}, then run ArkGate again.`}:{},...t.before===void 0?{}:{before:t.before},...t.after===void 0?{}:{after:t.after}})}function O(e){return[...new Set(e??[])].sort()}function X(e,t,n,s,r){let i=O(n),a=O(s),c=new Set(i),f=new Set(a),A=a.filter(u=>!c.has(u)),g=i.filter(u=>!f.has(u));A.length===0&&g.length===0||(A.length>0&&S(e,{kind:"added",path:t,classification:r.added,message:r.addedMessage,before:i,after:a}),g.length>0&&S(e,{kind:"removed",path:t,classification:r.removed,message:r.removedMessage,before:i,after:a}))}function Fe(e,t,n,s,r,i,a){if(n===s)return;S(e,{kind:s?"enabled":"disabled",path:t,classification:s?r:r==="strengthening"?"weakening":"strengthening",message:s?i:a,before:n,after:s})}function Me(e,t){let n=new Map,s=new Set;for(let r of e){let i=t(r);n.has(i)?s.add(i):n.set(i,r)}return{values:n,duplicates:[...s].sort()}}function On(e,t,n){let s=Me(t,i=>i.name),r=Me(n,i=>i.name);(s.duplicates.length>0||r.duplicates.length>0)&&S(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:s.duplicates,after:r.duplicates});for(let i of[...new Set([...s.values.keys(),...r.values.keys()])].sort()){let a=s.values.get(i),c=r.values.get(i),f=`$.layers[${i}]`;if(!a&&c){S(e,{kind:"layer-added",path:f,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:c});continue}if(a&&!c){S(e,{kind:"layer-removed",path:f,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:a});continue}if(!a||!c)continue;X(e,`${f}.patterns`,a.patterns,c.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),X(e,`${f}.exclude`,a.exclude,c.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let A=Oe(a),g=Oe(c);X(e,`${f}.forbiddenGlobals`,A.rawGlobals,g.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),X(e,`${f}.capabilities`,A.atoms,g.atoms,{added:"strengthening",removed:"weakening",addedMessage:"Additional ambient/import protection is enforced in this layer (coverage atoms).",removedMessage:"An ambient/import protection was lost from this layer (coverage atoms)."}),O(a.intentPrefixes).join("\0")!==O(c.intentPrefixes).join("\0")&&S(e,{kind:"intent-prefixes-changed",path:`${f}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:O(a.intentPrefixes),after:O(c.intentPrefixes)}),Fe(e,`${f}.mayImportInfrastructure`,a.mayImportInfrastructure===!0,c.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),Fe(e,`${f}.optional`,a.optional===!0,c.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active.")}}function Ln(e,t,n){let s=a=>`${a.from}->${a.to}`,r=Me(t,s),i=Me(n,s);(r.duplicates.length>0||i.duplicates.length>0)&&S(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:r.duplicates,after:i.duplicates});for(let a of[...new Set([...r.values.keys(),...i.values.keys()])].sort()){let c=r.values.get(a),f=i.values.get(a),A=`$.rules[${a}]`;if(!c&&f){f.allowed===!1&&S(e,{kind:"deny-added",path:A,classification:"strengthening",message:"A denied dependency edge was added.",after:f});continue}if(c&&!f){c.allowed===!1&&S(e,{kind:"deny-removed",path:A,classification:"weakening",message:"A denied dependency edge was removed.",before:c});continue}if(!c||!f)continue;c.allowed!==f.allowed&&S(e,{kind:f.allowed?"deny-disabled":"deny-enabled",path:`${A}.allowed`,classification:f.allowed?"weakening":"strengthening",message:f.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:c.allowed,after:f.allowed});let g=c.peerIsolation===!0,u=f.peerIsolation===!0;if(g!==u){let o=c.from===c.to&&f.from===f.to;S(e,{kind:u?"peer-isolation-enabled":"peer-isolation-disabled",path:`${A}.peerIsolation`,classification:o?u?"strengthening":"weakening":"judgment-required",message:o?u?"Cross-slice dependencies inside this layer are now denied.":"Cross-slice dependencies inside this layer are no longer denied.":"Changing peer isolation on a cross-layer edge changes the denial scope.",before:g,after:u})}O(c.sliceFolders).join("\0")!==O(f.sliceFolders).join("\0")&&S(e,{kind:"slice-folders-changed",path:`${A}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:O(c.sliceFolders),after:O(f.sliceFolders)})}}function $n(e,t,n){let s=t.safety??{},r=n.safety??{};for(let i of["maxTsSuppressions","maxAnyCasts"]){let a=s[i]??0,c=r[i]??0;a!==c&&S(e,{kind:c>a?"threshold-raised":"threshold-lowered",path:`$.safety.${i}`,classification:c>a?"weakening":"strengthening",message:c>a?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:a,after:c})}for(let i of["allowInMemory","allowDisabledPeerIsolation"])Fe(e,`$.safety.${i}`,s[i]===!0,r[i]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}function _n(e){return e.some(t=>t.classification==="weakening")?"weakening":e.some(t=>t.classification==="judgment-required")?"judgment-required":e.some(t=>t.classification==="strengthening")?"strengthening":"neutral"}function Ve(e,t){let n=[];X(n,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),X(n,"$.exclude",e.exclude,t.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional project paths are excluded from governance.",removedMessage:"Fewer project paths are excluded from governance."}),X(n,"$.dynamicImportAllowlist",e.dynamicImportAllowlist,t.dynamicImportAllowlist,{added:"weakening",removed:"strengthening",addedMessage:"Additional files may use non-literal dynamic imports.",removedMessage:"Fewer files may use non-literal dynamic imports."}),Fe(n,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let s={off:0,soft:1,"framework-soft":1,strict:2},r=e.cyclePolicy??"strict",i=t.cyclePolicy??"strict";if(r!==i){let a=s[i]===s[r]?"judgment-required":s[i]>s[r]?"strengthening":"weakening";S(n,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:a,message:"The cycle enforcement level changed.",before:r,after:i})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&S(n,{kind:"framework-overlay-changed",path:"$.frameworkOverlay",classification:"judgment-required",message:"The framework overlay changed and may alter effective layer matching.",before:e.frameworkOverlay??null,after:t.frameworkOverlay??null}),On(n,e.layers,t.layers),Ln(n,e.rules,t.rules),$n(n,e,t),n.sort((a,c)=>a.path.localeCompare(c.path)||a.id.localeCompare(c.id)),{schemaVersion:He,classification:_n(n),findings:n}}function je(e,t){if(!e||e.schemaVersion!==He||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(r=>typeof r!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=O(e.findingIds),s=O(t.findingIds);return n.length===s.length&&n.every((r,i)=>r===s[i])}function Q(e){let t=[];for(let n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."&&t.length>0&&t.at(-1)!==".."?t.pop():t.push(n));return t.join("/")}function Ht(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}function z(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}function Re(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let s=t,r="";for(t+=1;t<e.length;t+=1){let i=e[t];if(i===n)return{value:r,offset:s,excerpt:e.slice(s,t+1)};i==="\\"&&t+1<e.length?(r+=e[t+1],t+=1):r+=i}}function M(e,t,n){return e.startsWith(t,n)&&!Ht(e[n-1])&&!Ht(e[n+t.length])}function Tn(e,t){if(t=z(e,t+6),e[t]==="(")return Re(e,z(e,t+1));let n=!1;if(M(e,"type",t)){let r=z(e,t+4);e[r]!==","&&!M(e,"from",r)&&(n=!0)}let s=Vt(e,t,!0);return s&&n?{...s,typeOnly:!0}:s}function Nn(e,t){t=t+6;let n=z(e,t),s=!1;if(M(e,"type",n)){let i=z(e,n+4);(e[i]==="{"||e[i]==="*")&&(s=!0)}let r=Vt(e,t,!1);return r&&s?{...r,typeOnly:!0}:r}function Vt(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(M(e,"from",t))return Re(e,z(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return Re(e,t);if(t>0&&(M(e,"import",t)||M(e,"export",t)))return}}function Dn(e,t){for(t+=1;t<e.length;t+=1){let n=e[t];if(n==="\\")t+=1;else if(n==="`")return t}return e.length}function Fn(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let s=z(e,t+7);if(e[s]!=="(")return;s=z(e,s+1);let r=Re(e,s);return r?{...r,requireCall:!0}:void 0}function Mn(e){let t=[];for(let n=0;n<e.length;n+=1){let s=e[n];if(s==="/"&&e[n+1]==="/"){if(n=e.indexOf(`
|
|
5
|
+
`,n+2),n<0)break;continue}if(s==="/"&&e[n+1]==="*"){let i=e.indexOf("*/",n+2);if(i<0)break;n=i+1;continue}if(s==="`"){n=Dn(e,n);continue}if(s==="'"||s==='"'){let i=Re(e,n);i&&(n=i.offset+i.excerpt.length-1);continue}let r=s==="i"&&M(e,"import",n)?Tn(e,n):s==="e"&&M(e,"export",n)?Nn(e,n):s==="r"&&M(e,"require",n)?Fn(e,n):void 0;r&&(t.push(r),n=r.offset+r.excerpt.length-1)}return t}function jt(e,t){let n=[],s=[];for(let r of Mn(e.content)){let i=r.value;if(r.requireCall&&i.startsWith("."))continue;if(!i.startsWith(".")){if(r.typeOnly)continue;let A=fe(i);if(!A)continue;let g=e.content.slice(0,r.offset).split(`
|
|
6
|
+
`).length;s.push({file:e.path,symbol:i,capability:A,evidence:{kind:"import",file:e.path,line:g,excerpt:r.excerpt}});continue}let a=e.content.slice(0,r.offset).split(`
|
|
7
|
+
`).length,c={kind:"import",file:e.path,line:a,excerpt:r.excerpt},f=Hn(e.path,i,t);n.push({from:e.path,specifier:i,to:f?.path??null,resolution:f?"resolved":"unresolved",fromLayer:e.layer,toLayer:f?.layer??null,evidence:c})}return{edges:n,capabilityUses:s}}function Hn(e,t,n){let s=e.split("/");s.pop();for(let i of t.split("/"))i==="."||i===""||(i===".."?s.pop():s.push(i));let r=s.join("/");for(let i of[r,`${r}.ts`,`${r}.tsx`,`${r}.mts`,`${r}.cts`,`${r}/index.ts`,`${r}/index.tsx`]){let a=n.get(i);if(a)return a}}function Gt(e,t){let n=[];for(let s of e){if(!s.to||!s.fromLayer||!s.toLayer)continue;let r=T(t.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:t.layers});r&&n.push({ruleId:`layer-dependency:${r.from}->${r.to}`,message:r.message??`${r.from} must not depend on ${r.to}.`,edge:s,evidence:s.evidence})}return n}var Vn={code:"LEXICAL_EVIDENCE_INCOMPLETE",message:"Lexical compatibility mode cannot prove parse status, TypeScript/package/symlink resolution, or symbol-aware source-policy and safety evidence. Use the resolved candidate facts APIs for an authoritative verdict."};function ve(e,t){let n=typeof e=="string"?Ne(e,t):Ae(e,t);return{...n,policyHash:k(v(n.config))}}function ft(e){let t=ve(e.baseConfig,e.baseSource??"base ark.config.json"),n=ve(e.candidateConfig,e.candidateSource??"candidate ark.config.json"),s=Ve(t.config,n.config),r=s.findings.filter(c=>c.classification==="weakening"||c.classification==="judgment-required").map(c=>c.id).sort(),i=r.length>0,a=i&&je(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:r});return{schemaVersion:s.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:s.classification,findings:s.findings,blockingFindingIds:r,requiresAcknowledgement:i,acknowledged:a,valid:!i||a}}function ce(e){let t=e.files.map(u=>{let o=Q(u.path);return{path:o,content:u.content,contentHash:k(u.content),layer:V(o,e.contract.config.layers)??null}}).sort((u,o)=>u.path.localeCompare(o.path)),n=new Map(t.map(u=>[u.path,u])),s=[],r=[];for(let u of t){let o=jt(u,n);s.push(...o.edges),r.push(...o.capabilityUses)}let i=Gt(s,e.contract.config),a=new Map(e.contract.config.layers.map(u=>[u.name,u])),c=new Map(e.contract.config.layers.map(u=>[u.name,new Set(te(u))]));for(let u of r){let o=n.get(u.file)?.layer;if(!o)continue;let l=a.get(o),d=H(u.symbol,l?.forbiddenGlobals??[]);if(d){i.push({ruleId:"FORBIDDEN_GLOBAL",message:`${o} must not use module "${u.symbol}" because it is the import form of forbidden global "${d}".`,symbol:u.symbol,evidence:u.evidence});continue}c.get(o)?.has(u.capability)&&i.push({ruleId:"CAPABILITY_VIOLATION",message:`${o} denies the ${u.capability} capability; found import of "${u.symbol}".`,capability:u.capability,symbol:u.symbol,evidence:u.evidence})}let f=t.length===0?"complete":"partial",A=f==="complete"?[]:[{...Vn}],g={schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:k(v(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(u=>u.name),edges:s,capabilityUses:r,violations:i};return{mode:"lexical-compatibility",completeness:f,completenessReasons:A,valid:f==="complete"&&i.length===0,ir:g}}function Se(e){let t=new Map(e.files.map(n=>[Q(n.path),n]));for(let n of e.changes){let s=Q(n.path);"delete"in n&&n.delete?t.delete(s):"content"in n&&t.set(s,{path:s,content:n.content})}return ce({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}function ut(e){let t=`${e.evidence.file}:${e.evidence.line}`;if(!e.edge)return`${e.ruleId} at ${t}: ${e.message}`;let n=e.edge.to??e.edge.specifier;return`${e.ruleId} at ${t}: ${e.edge.from} imports ${n}. ${e.message}`}function Ge(e){let t=0,n=new Map,s=new Map,r=new Set,i=[],a=[],c=f=>{n.set(f,t),s.set(f,t),t+=1,i.push(f),r.add(f);for(let u of[...e.get(f)??[]].sort())e.has(u)&&(n.has(u)?r.has(u)&&s.set(f,Math.min(s.get(f)??0,n.get(u)??0)):(c(u),s.set(f,Math.min(s.get(f)??0,s.get(u)??0))));if(s.get(f)!==n.get(f))return;let A=[],g;do{if(g=i.pop(),g===void 0)break;r.delete(g),A.push(g)}while(g!==f);A.length>1&&a.push(A.sort())};for(let f of[...e.keys()].sort())n.has(f)||c(f);return a.sort((f,A)=>f[0]<A[0]?-1:f[0]>A[0]?1:0).map(f=>({ruleId:"CIRCULAR_DEPENDENCY",file:f[0],line:1,target:f.join(" \u2192 "),message:`Circular dependency among ${f.length} files: ${f.join(" \u2192 ")} \u2192 ${f[0]}.`,cycleKind:"value"}))}function ee(e){let t=e.contentViolations.map(i=>({...i})),n=(e.warnings??[]).map(i=>({...i})),s=new Map(e.files.map(i=>[i,new Set]));for(let i of e.edges){if(i.to&&i.to!==i.from&&!i.typeOnly&&s.has(i.from)&&s.get(i.from)?.add(i.to),!i.to||!i.fromLayer||!i.toLayer)continue;let a=T(e.rules,i.fromLayer,i.toLayer,{fromPath:i.from,toPath:i.to,layers:e.config.layers});if(!a)continue;let c=!!a.peerIsolation;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:i.from,line:i.line,fromLayer:i.fromLayer,toLayer:i.toLayer,target:i.to,...i.typeOnly?{typeOnly:!0}:{},...i.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...i.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...i.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!c&&i.portProofEligible?{portProofEligible:!0}:{},...i.kind?{edgeKind:i.kind}:{},...c?{peerIsolation:!0}:{},message:a.message??(c?`${i.fromLayer} must not ${i.kind} another slice of ${i.toLayer} (${i.from} \u2192 ${i.to}). Extract shared code or use events/ports across slices.`:`${i.fromLayer} must not ${i.kind} ${i.toLayer}.`)})}let r=String(e.config.cyclePolicy??"strict").toLowerCase();if(r!=="off"){let i=Ge(s);r==="soft"||r==="framework-soft"?n.push(...i.map(a=>({...a,message:`${a.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...i)}return{violations:t,warnings:n,safety:e.safety}}function w(e,t,n={}){return{ruleId:e,message:t,...n}}function xe(e){let{config:t,rules:n,files:s,manifest:r}=e,i=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(l=>typeof l!="string"))&&i.push(w("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","dynamicImportAllowlist must be an array of file globs.")),t.safety!==void 0&&(t.safety===null||typeof t.safety!="object"||Array.isArray(t.safety)))i.push(w("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let l of["maxTsSuppressions","maxAnyCasts"]){let d=t.safety[l];d!==void 0&&(!Number.isInteger(d)||d<0)&&i.push(w("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${l} must be a non-negative integer.`))}let a=Array.isArray(t.layers)?t.layers:[],c=Array.isArray(r?.architecture?.layers)?r.architecture.layers:[],f=new Set([...a.map(l=>l.name).filter(Boolean),...c.map(l=>l.name).filter(l=>!!l)]);a.length===0&&i.push(w("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let A=new Set,g=new Set;for(let l of a){if(!l.name){i.push(w("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}A.has(l.name)&&g.add(l.name),A.add(l.name),l.forbiddenGlobals!==void 0&&(!Array.isArray(l.forbiddenGlobals)||l.forbiddenGlobals.some(p=>typeof p!="string"))&&i.push(w("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${l.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:l.name}));let d=Array.isArray(l.patterns)?l.patterns:[];if(d.length===0){i.push(w("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${l.name}" has no file patterns and will never classify files.`,{layer:l.name}));continue}for(let p of d){let y;try{y=K(p)}catch(h){i.push(w("CONFIG_INVALID_LAYER_PATTERN",`Layer "${l.name}" has an invalid pattern "${p}": ${h instanceof Error?h.message:String(h)}`,{layer:l.name,pattern:p}));continue}!s.some(h=>y.test(h))&&!l.optional&&i.push(w("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${l.name}" pattern "${p}" matched no included files.`,{layer:l.name,pattern:p,failsStrict:!1}))}}for(let l of g)i.push(w("CONFIG_DUPLICATE_LAYER",`Layer "${l}" is configured more than once.`,{layer:l}));if(f.size>0)for(let l of n??[])l.from&&!f.has(l.from)&&i.push(w("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${l.from}".`,{fromLayer:l.from,toLayer:l.to})),l.to&&!f.has(l.to)&&i.push(w("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${l.to}".`,{fromLayer:l.from,toLayer:l.to}));let u=new Set;if(a.length>1)for(let l of s){let d=-1,p=[];for(let y of a)for(let h of y.patterns??[]){if(!K(h).test(l))continue;let m=Xe(h);m>d?(d=m,p=[y.name]):m===d&&!p.includes(y.name)&&p.push(y.name)}p.length>1&&u.add([...p].sort().join(" + "))}u.size>0&&i.push(w("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...u].join(", ")}.`,{pairs:[...u]}));let o=s.filter(l=>!V(l,a));return o.length>0&&i.push(w("CONFIG_UNCLASSIFIED_FILES",`${o.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:o.length,samples:o.slice(0,5)})),i}function jn(e,t){return t.some(n=>{try{return K(n).test(e)}catch{return!1}})}function Gn(e,t){let n=e.contract.config.safety??{},s=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,r=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,i=e.contract.config.dynamicImportAllowlist??[],a=t.safetyUses.filter(p=>p.kind==="ts-suppression").map(({file:p,line:y})=>({file:p,line:y})),c=t.safetyUses.filter(p=>p.kind==="any-cast").map(({file:p,line:y})=>({file:p,line:y})),f=t.safetyUses.filter(p=>(p.kind==="dynamic-import"||p.kind==="dynamic-require")&&!jn(p.file,i)).map(p=>({file:p.file,line:p.line,kind:p.kind==="dynamic-require"?"require":"import"})),A=n.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(p=>p.kind==="in-memory-store").map(p=>({file:p.file,line:p.line,store:p.symbol??"in-memory store"})),g=n.allowDisabledPeerIsolation===!0?[]:(e.contract.config.rules??[]).filter(p=>p.peerIsolation===!1||p.allowed===!1&&!!p.from&&p.from===p.to&&p.peerIsolation!==!0).map(p=>({from:p.from,to:p.to})),u={tsSuppressions:a,anyCasts:c,nonLiteralDynamicImports:f,inMemoryProductionStores:A,disabledPeerIsolationRules:g,thresholds:{maxTsSuppressions:s,maxAnyCasts:r}},o=[],l=f.filter(p=>p.kind==="import");if(l.length>0){let p=l[0];o.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:p.file,line:p.line,message:`${l.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let d=f.filter(p=>p.kind==="require");if(d.length>0){let p=d[0];o.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:p.file,line:p.line,message:`${d.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(a.length>s){let p=a[0];o.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:p.file,line:p.line,message:`${a.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${s}).`})}if(c.length>r){let p=c[0];o.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:p.file,line:p.line,message:`${c.length} explicit any cast(s) exceed safety.maxAnyCasts (${r}).`})}if(A.length>0){let p=A[0];o.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:p.file,line:p.line,message:`${A.length} ArkGate InMemory store risk(s) appear in governed production source. Provide durable stores or set safety.allowInMemory only for an explicitly ephemeral service.`})}return g.length>0&&o.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${g.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:u,warnings:o}}function Un(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,s)=>s.length-n.length)[0]}function Ut(e,t){let n=t.config.layers.filter(s=>(s.intentPrefixes??[]).length>0);return it(e,n.length>0?n:rt.map(s=>({name:s.layer,prefixes:s.prefixes})))}function Bn(e,t,n){let s=[],r=new Map(e.contract.config.layers.map(i=>[i.name,i]));for(let i of t.ambientUses){let a=n.get(i.file);!a||!Un(i.symbol,r.get(a)?.forbiddenGlobals??[])||s.push({ruleId:"FORBIDDEN_GLOBAL",file:i.file,line:i.line,fromLayer:a,target:i.symbol,message:`${a} must not use the ambient global "${i.symbol}".`})}for(let i of t.capabilityUses){let a=n.get(i.file);if(!a)continue;let c=r.get(a),f=c?.forbiddenGlobals??[],A=i.source==="import-based"?t.dependencies.find(g=>g.from===i.file&&g.line===i.line&&g.specifier===i.symbol&&!g.typeOnly)?.kind:void 0;if(!(i.source==="ambient-global"&&ue(i.symbol,f))){if(i.source==="import-based"){let g=H(i.symbol,f);if(g){s.push({ruleId:"FORBIDDEN_GLOBAL",file:i.file,line:i.line,fromLayer:a,target:i.symbol,...A?{edgeKind:A}:{},message:`${a} must not use module "${i.symbol}" because it is the import form of forbidden global "${g}".`});continue}}te(c).includes(i.capability)&&s.push({ruleId:"CAPABILITY_VIOLATION",file:i.file,line:i.line,fromLayer:a,target:i.symbol,capability:i.capability,...A?{edgeKind:A}:{},message:i.source==="import-based"?`${a} denies the ${i.capability} capability; found import of "${i.symbol}".`:`${a} denies the ${i.capability} capability; found ambient "${i.symbol}".`})}}for(let i of t.publishCalls){let a=n.get(i.file);if(!a)continue;for(let f of ye({publishCall:!0,rawIntentName:i.rawIntentName,objectHasIntent:i.objectHasIntent,arkPublishCandidate:i.arkPublishCandidate,hasSource:i.hasSource}))s.push({ruleId:f.ruleId,file:i.file,line:i.line,...f.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:a}:{},message:f.message});if(!i.sourceIntent)continue;let c=Ut(i.sourceIntent,e.contract);!c||c===a||s.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:i.file,line:i.line,fromLayer:a,toLayer:c,target:i.sourceIntent,message:`Publish source "${i.sourceIntent}" resolves to ${c}, but the publishing file is classified as ${a}.`})}for(let i of t.intentReferences){let a=n.get(i.file);if(!a)continue;let c=Ut(i.intent,e.contract);if(!c)continue;let f=T(e.contract.config.rules,a,c);f&&s.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:i.file,line:i.line,fromLayer:a,toLayer:c,target:i.intent,message:f.message??`${a} must not reference ${c} intent ${i.intent}.`})}return s}function qn(e){let{facts:t}=e,n=Ie(e.contract.config),s=t.evidenceRequirementsHash===n,r=s?t.completeness:"unavailable",i=s?t.completenessReasons:[...t.completenessReasons,{code:"EVIDENCE_REQUIREMENTS_MISMATCH",message:"Resolved facts were collected for different policy-controlled evidence requirements."}].sort((d,p)=>{let y=`${d.code}\0${d.file??""}\0${d.message}`,h=`${p.code}\0${p.file??""}\0${p.message}`;return y<h?-1:y>h?1:0}),a=t.files.map(d=>({...d,layer:V(d.path,e.contract.config.layers)??null})),c=new Map(a.map(d=>[d.path,d.layer])),f=t.dependencies.map(d=>{let p=d.target?c.get(d.target)??V(d.target,e.contract.config.layers):void 0;return{from:d.from,fromLayer:c.get(d.from)??null,...d.resolution==="resolved-project"&&d.target?{to:d.target,...p?{toLayer:p}:{}}:{},line:d.line,kind:d.kind,typeOnly:d.typeOnly,...d.targetTypeOnlyExports?{targetTypeOnlyExports:d.targetTypeOnlyExports}:{},...d.sourcePureTypeModule?{sourcePureTypeModule:d.sourcePureTypeModule}:{},...d.namedBindingsTypeOnly?{namedBindingsTypeOnly:d.namedBindingsTypeOnly}:{},...d.portProofEligible?{portProofEligible:d.portProofEligible}:{}}}),A=xe({config:e.contract.config,rules:e.contract.config.rules,files:a.map(d=>d.path)}),g=Gn(e,t),u=ee({config:e.contract.config,rules:e.contract.config.rules,files:a.filter(d=>d.layer).map(d=>d.path),contentViolations:Bn(e,t,c),edges:f,warnings:[...A,...g.warnings],safety:g.report}),o=r==="complete"&&u.violations.length===0,l=o&&u.warnings.every(d=>d.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:r,completenessReasons:i,valid:o,strictValid:l,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:g.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:a,layers:e.contract.config.layers.map(d=>d.name),edges:f,capabilityUses:t.capabilityUses,violations:u.violations,warnings:u.warnings}}}function pe(e){return qn({contract:e.contract,facts:q(e.facts)})}function Ue(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return e.typeOnly||e.targetTypeOnlyExports||e.namedBindingsTypeOnly?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":e.peerIsolation?"Extract the shared dependency to a shared layer, then preflight again.":`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, then preflight again.`;case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, then preflight again.`;case"CAPABILITY_VIOLATION":return`Define a ${String(e.capability??"capability")} port in ${e.fromLayer??"the walled layer"}, bind the implementation outside it, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";default:return`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}function Bt(e){return k(v(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}function yt(e){let t=ce(e),n=new Map(t.ir.files.map(l=>[l.path,l])),s=[],r=new Set,i=[];for(let l of e.changes){let d=l.path.replace(/\\/g,"/"),p=Q(l.path);if(!p||p===".."||p.startsWith("../")||d.startsWith("/")||/^[A-Za-z]:\//.test(d)||d.includes("\0")){i.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(r.has(p)){i.push({ruleId:"DUPLICATE_CHANGE_PATH",file:p,line:1,message:`The atomic change set contains more than one operation for ${p}.`});continue}r.add(p),"delete"in l&&l.delete&&!n.has(p)&&i.push({ruleId:"DELETE_TARGET_MISSING",file:p,line:1,message:`Cannot delete ${p} because it is not present in the supplied base tree.`}),s.push("delete"in l&&l.delete?{path:p,delete:!0}:{path:p,content:"content"in l?l.content:""})}e.changes.length===0&&i.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let a=Se({...e,changes:s}),c=new Map(a.ir.files.map(l=>[l.path,l])),f=a.ir.violations.filter(l=>l.ruleId==="CAPABILITY_VIOLATION"||l.ruleId==="FORBIDDEN_GLOBAL").map(l=>{let d=c.get(l.evidence.file)?.layer;return{ruleId:l.ruleId,file:l.evidence.file,line:l.evidence.line,target:l.symbol,...l.capability?{capability:l.capability}:{},...d?{fromLayer:d}:{},edgeKind:"import",message:l.message}}),A=ee({config:e.contract.config,rules:e.contract.config.rules,files:a.ir.files.map(l=>l.path),contentViolations:f,edges:a.ir.edges.filter(l=>!!l.fromLayer).map(l=>({from:l.from,fromLayer:l.fromLayer,...l.to?{to:l.to}:{},...l.toLayer?{toLayer:l.toLayer}:{},line:l.evidence.line,kind:"import"}))}),g=s.map(l=>{let d=Q(l.path),p=n.get(d),y=c.get(d);return{path:d,operation:"delete"in l&&l.delete?"delete":p?"update":"create",...p?{beforeContentHash:p.contentHash}:{},...y?{candidateContentHash:y.contentHash}:{}}}).sort((l,d)=>l.path.localeCompare(d.path)),u=[...i,...A.violations].map(l=>({...l,nextAction:Ue(l)})),o=e.changeMap?Z({changeMap:e.changeMap,changes:g,baseDependencies:t.ir.edges.flatMap(l=>l.to?[{from:l.from,to:l.to}]:[]),candidateDependencies:a.ir.edges.flatMap(l=>l.to?[{from:l.from,to:l.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&a.valid&&u.length===0&&(o?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:a.ir.compilerOptionsHash,baseTreeHash:Bt(t.ir.files),candidateTreeHash:Bt(a.ir.files),baseCompleteness:t.completeness,candidateCompleteness:a.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:a.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...o?{convergence:o}:{},changes:g,violations:u,warnings:A.warnings}}function zn(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let r of t.split("/"))if(!(!r||r==="."))if(r===".."){if(n.length===0)return;n.pop()}else n.push(r);let s=n.join("/");return s&&s===t?s:void 0}function Kn(e,t){return[["resolverIdentity",e.resolverIdentity,t.resolverIdentity],["compilerIdentity",e.compilerIdentity,t.compilerIdentity],["evidenceRequirementsHash",e.evidenceRequirementsHash,t.evidenceRequirementsHash],["projectPackageName",e.projectPackageName??"",t.projectPackageName??""]].filter(([,s,r])=>s!==r).map(([s,r,i])=>({ruleId:"FACTS_IDENTITY_MISMATCH",file:"<change-set>",line:1,field:s,before:r,candidate:i,message:`Base and candidate facts must use the same ${s}.`}))}function Yn(e,t,n,s){let r=n.get(t),i=s.get(t);return{path:t,operation:"delete"in e&&e.delete?"delete":r?"update":"create",...r?{beforeContentHash:r.contentHash}:{},...i?{candidateContentHash:i.contentHash}:{}}}function mt(e){let t=q(e.baseFacts),n=q(e.candidateFacts),s=pe({contract:e.contract,facts:t}),r=pe({contract:e.contract,facts:n}),i=new Map(t.files.map(o=>[o.path,o])),a=new Map(n.files.map(o=>[o.path,o])),c=Kn(t,n),f=new Map,A=[];for(let o of e.changes){let l=zn(o.path);if(!l){c.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(f.has(l)){c.push({ruleId:"DUPLICATE_CHANGE_PATH",file:l,line:1,message:`The atomic change set contains more than one operation for ${l}.`});continue}f.set(l,o);let d=i.get(l),p=a.get(l);if("delete"in o&&o.delete)d||c.push({ruleId:"DELETE_TARGET_MISSING",file:l,line:1,message:`Cannot delete ${l} because it is not present in the supplied base facts.`}),p&&c.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:l,line:1,message:`Candidate facts still contain deleted file ${l}.`});else{let y="content"in o?o.content:"",h=k(y);p?p.contentHash!==h&&c.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:l,line:1,expectedContentHash:h,candidateContentHash:p.contentHash,message:`Candidate facts for ${l} do not match the declared content.`}):c.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:l,line:1,message:`Candidate facts do not contain changed file ${l}.`})}A.push(Yn(o,l,i,a))}e.changes.length===0&&c.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});for(let o of new Set([...i.keys(),...a.keys()])){if(f.has(o))continue;let l=i.get(o),d=a.get(o);l&&d&&v(l)===v(d)||c.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:o,line:1,message:`Candidate facts change ${o}, but the atomic change set does not declare it.`})}let g=e.changeMap?Z({changeMap:e.changeMap,changes:A,baseDependencies:s.ir.edges.flatMap(o=>o.to?[{from:o.from,to:o.to}]:[]),candidateDependencies:r.ir.edges.flatMap(o=>o.to?[{from:o.from,to:o.to}]:[])}):void 0,u=[...c,...r.ir.violations].map(o=>({...o,nextAction:Ue(o)}));return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:s.completeness==="complete"&&r.strictValid&&u.length===0&&(g?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,resolverIdentity:n.resolverIdentity,compilerIdentity:n.compilerIdentity,compilerOptionsHash:n.compilerOptionsHash,tsconfigHash:n.tsconfigHash,baseCompilerOptionsHash:t.compilerOptionsHash,candidateCompilerOptionsHash:n.compilerOptionsHash,baseTsconfigHash:t.tsconfigHash,candidateTsconfigHash:n.tsconfigHash,evidenceRequirementsHash:n.evidenceRequirementsHash,baseFactsHash:t.factsHash,candidateFactsHash:n.factsHash,baseTreeHash:t.candidateTreeHash,candidateTreeHash:n.candidateTreeHash,baseCompleteness:s.completeness,candidateCompleteness:r.completeness,baseCompletenessReasons:s.completenessReasons,candidateCompletenessReasons:r.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...g?{convergence:g}:{},changes:A.sort((o,l)=>o.path<l.path?-1:o.path>l.path?1:0),violations:u,warnings:r.ir.warnings}}var qt="1.1";var zt="1.0";0&&(module.exports={ANALYSIS_IR_SCHEMA_VERSION,ARK_ANALYSIS_RESULT_SCHEMA,ARK_ANALYSIS_RESULT_SCHEMA_VERSION,ARK_CONFIG_SCHEMA,ARK_CONFIG_SCHEMA_VERSION,ARK_DESIGN_DELTA_SCHEMA_VERSION,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION,POLICY_DELTA_SCHEMA_VERSION,RESOLVED_CANDIDATE_FACTS_SCHEMA,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,analyzeArchitectureConvergence,analyzeChange,analyzePolicyDelta,analyzeProject,analyzeResolvedProject,classifyArkPolicyDelta,collectAnalysisConfigWarnings,collectForbiddenCapabilityUses,createAICodeGate,createAdapterResult,createArchitectureProfile,createArchitectureProfileFromArkConfig,createElevenLayerArkConfig,createResolvedCandidateFacts,detectArchitectureCycles,deterministicHash,elevenLayerProfile,evaluateArchitectureGraph,explainViolation,extractSemanticDependencies,loadArkConfigContract,loadContract,loadResolvedCandidateFacts,parseArkConfigJson,policyDeltaAcknowledgementMatches,preflightChange,preflightResolvedChange,resolvedFactsEvidenceRequirementsHash,stableSerialize,toAdapterDiagnostic,version});
|