arkgate 3.9.2 → 4.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +125 -0
- package/README.md +16 -4
- package/bin/ark-check-runtime.mjs +75 -3
- package/bin/ark-mcp-runtime.mjs +94 -0
- package/bin/lib/adapter-contract.mjs +14 -1
- package/bin/lib/analysis-engine.mjs +8 -8
- package/bin/lib/architecture-scan.mjs +35 -2
- package/bin/lib/arkrule-file-hints.mjs +71 -0
- package/bin/lib/arkrules-contract.mjs +382 -0
- package/bin/lib/arkrules-sensors.mjs +411 -0
- package/bin/lib/config-contract.mjs +85 -6
- package/bin/lib/doctor-advisories.mjs +14 -1
- package/bin/lib/doctor-plan.mjs +21 -0
- package/bin/lib/effective-contract-load.mjs +116 -0
- package/bin/lib/field-install.mjs +104 -0
- package/bin/lib/graph-blind.mjs +20 -1
- package/bin/lib/html-report-advisories.mjs +12 -5
- package/bin/lib/install-migrate.mjs +20 -2
- package/bin/lib/invariant-coverage-io.mjs +157 -0
- package/bin/lib/invariant-coverage.mjs +127 -0
- package/bin/lib/managed-upgrade.mjs +1 -1
- package/bin/lib/policy-delta-io.mjs +33 -0
- package/bin/lib/presets.mjs +241 -1
- package/bin/lib/remediation.mjs +28 -0
- package/bin/lib/resolved-candidate-facts.mjs +14 -1
- package/bin/lib/rules-inventory.mjs +144 -0
- package/bin/lib/rules-under-contract.mjs +320 -0
- package/bin/lib/start-preview.mjs +24 -7
- package/bin/lib/upgrade-command.mjs +373 -16
- package/dist/{configTypes-DAPvBqK6.d.ts → configTypes-CC0FEXoF.d.ts} +16 -3
- package/dist/eslint/index.cjs +2 -2
- package/dist/eslint/index.d.ts +1 -1
- package/dist/eslint/index.js +2 -2
- package/dist/index.cjs +14 -7
- package/dist/index.d.ts +615 -20
- package/dist/index.js +13 -6
- package/docs/README.md +5 -3
- package/docs/agent-guide.md +7 -3
- package/docs/ai-gates.md +6 -1
- package/docs/brownfield-adoption.md +22 -0
- package/docs/configuration.md +53 -4
- package/docs/develop.md +8 -2
- package/docs/enthusiast/README.md +11 -0
- package/docs/package-surface.md +13 -10
- package/docs/product-voice.md +11 -2
- package/docs/use.md +11 -0
- package/package.json +4 -17
- package/schemas/ark.analysis-result.schema.json +9 -1
- package/schemas/ark.arkrules.schema.json +141 -0
- package/schemas/ark.config.schema.json +10 -2
- package/schemas/ark.resolved-candidate-facts.schema.json +1 -1
- package/server.json +2 -2
- package/templates/arkrules/ApplicationOrchestration.json +14 -0
- package/templates/arkrules/DomainModel.json +32 -0
- package/templates/arkrules/PersistenceAdapters.json +14 -0
- package/templates/arkrules/PresentationAdapters.json +14 -0
- package/templates/skills/ark-adopt.md +28 -1
- package/templates/skills/ark-architect.md +23 -0
- package/templates/skills/ark-autopilot.md +27 -1
- package/templates/skills/ark-contract.md +27 -1
- package/templates/skills/ark-coverage.md +23 -0
- package/templates/skills/ark-explain.md +39 -3
- package/templates/skills/ark-explore.md +26 -1
- package/templates/skills/ark-fix.md +23 -0
- package/templates/skills/ark-loop.md +23 -0
- package/templates/skills/ark-place.md +26 -0
- package/templates/skills/ark-runtime.md +4 -0
- package/templates/skills/ark-think.md +24 -1
- package/templates/skills/ark-upgrade.md +80 -11
- package/compat/nestjs.cjs +0 -2
- package/compat/nestjs.d.ts +0 -2
- package/compat/nestjs.js +0 -1
- package/compat/runtime.cjs +0 -2
- package/compat/runtime.d.ts +0 -2
- package/compat/runtime.js +0 -1
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
// GENERATED from src/kernel/analysis.ts by scripts/generate-analysis-engine.mjs.
|
|
2
2
|
// Do not edit this file directly.
|
|
3
|
-
function E(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 C(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(C).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${C(t[n])}`).join(",")}}`}var K="1.0",Ke=["network","filesystem","clock","randomness","environment","process","persistence"];function j(e,t){let n=C(e),s=C(t);return n<s?-1:n>s?1:0}function T(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}function ce(e){let t={schemaVersion:"1.0",include:T(e.include??[]),exclude:T(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:T(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:T(n.patterns??[]),exclude:T(n.exclude??[]),forbiddenGlobals:T(n.forbiddenGlobals??[]),intentPrefixes:T(n.intentPrefixes??[]),capabilityDeny:T(n.capabilities?.deny??[]),pure:n.pure===!0})).sort(j),safety:{maxTsSuppressions:e.safety?.maxTsSuppressions??0,maxAnyCasts:e.safety?.maxAnyCasts??0,allowInMemory:e.safety?.allowInMemory===!0,allowDisabledPeerIsolation:e.safety?.allowDisabledPeerIsolation===!0}};return E(C(t))}function wt(e){let t=e.completenessReasons.map(m=>({code:m.code,message:m.message,...m.file?{file:m.file}:{}})).sort(j),n=e.files.map(m=>({...m,typeOnlyExportNames:T(m.typeOnlyExportNames)})).sort((m,a)=>m.path<a.path?-1:m.path>a.path?1:0),s=e.dependencies.map(m=>({...m,...m.namedBindings?{namedBindings:T(m.namedBindings)}:{}})).sort(j),i=e.capabilityUses.map(m=>({...m})).sort(j),r=e.ambientUses.map(m=>({...m})).sort(j),o=e.publishCalls.map(m=>({...m})).sort(j),p=e.intentReferences.map(m=>({...m})).sort(j),f=e.safetyUses.map(m=>({...m})).sort(j),g=e.files.map(({path:m,contentHash:a})=>({path:m,contentHash:a})).sort((m,a)=>m.path<a.path?-1:m.path>a.path?1:0),h=E(C(g));return{schemaVersion:"1.0",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:h,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:s,capabilityUses:i,ambientUses:r,publishCalls:o,intentReferences:p,safetyUses:f}}function We(e){let t=wt(e);return{...t,factsHash:E(C(t))}}function de(e){return We(Ze(L(e,"$"),!1))}function L(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}function _(e,t,n){let s=new Set(t),i=Object.keys(e).find(r=>!s.has(r));if(i)throw new Error(`${n}.${i} is not part of schema 1.0.`)}function S(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 Y(e,t,n){if(e[t]!==void 0)return S(e,t,n)}function F(e,t,n){let s=S(e,t,n),i=s.replace(/\\/g,"/");if(!i||i.startsWith("/")||/^[A-Za-z]:\//.test(i)||/[\u0000-\u001f\u007f]/.test(i))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let r=[];for(let p of i.split("/"))if(!(!p||p==="."))if(p===".."){if(r.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);r.pop()}else r.push(p);let o=r.join("/");if(!o||o!==s)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return o}function P(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}function Je(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 W(e,t,n){let s=Je(e,t,n);if(s===0)throw new Error(`${n}.${t} must be a positive integer.`);return s}function H(e,t,n){let s=e[t];if(!Array.isArray(s))throw new Error(`${n}.${t} must be an array.`);return s}function M(e,t,n,s){let i=e[t];if(typeof i!="string"||!n.includes(i))throw new Error(`${s}.${t} must be one of ${n.join(", ")}.`);return i}function Ye(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 xt(e,t,n){let s=new Set;for(let i of e){let r=t(i);if(s.has(r))throw new Error(`${n} must not contain duplicate facts (${r}).`);s.add(r)}}function Ze(e,t){_(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=M(e,"schemaVersion",["1.0"],"$"),s=M(e,"completeness",["complete","partial","unavailable"],"$"),i=H(e,"completenessReasons","$").map((c,d)=>{let u=`$.completenessReasons[${d}]`,y=L(c,u);_(y,["code","message","file"],u);let b=y.file===void 0?void 0:F(y,"file",u);return{code:S(y,"code",u),message:S(y,"message",u),...b?{file:b}:{}}});if(s==="complete"&&i.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(s!=="complete"&&i.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let r=H(e,"files","$").map((c,d)=>{let u=`$.files[${d}]`,y=L(c,u);return _(y,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],u),{path:F(y,"path",u),contentHash:S(y,"contentHash",u),parseStatus:M(y,"parseStatus",["parsed","invalid"],u),parseDiagnosticCount:Je(y,"parseDiagnosticCount",u),exportsOnlyTypes:P(y,"exportsOnlyTypes",u),typeOnlyExportNames:Ye(y.typeOnlyExportNames,`${u}.typeOnlyExportNames`),hasTopLevelSideEffects:P(y,"hasTopLevelSideEffects",u)}}),o=H(e,"dependencies","$").map((c,d)=>{let u=`$.dependencies[${d}]`,y=L(c,u);_(y,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],u);let b=Y(y,"specifier",u),A=Y(y,"target",u),R=M(y,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],u);if(R==="resolved-project"&&!A)throw new Error(`${u}.target is required for resolved-project dependencies.`);if(R!=="resolved-project"&&A)throw new Error(`${u}.target is only allowed for resolved-project dependencies.`);if(R!=="dynamic"&&!b)throw new Error(`${u}.specifier is required unless resolution is dynamic.`);return{from:F(y,"from",u),...b?{specifier:b}:{},kind:M(y,"kind",["import","export","dynamic-import","require"],u),typeOnly:P(y,"typeOnly",u),line:W(y,"line",u),resolution:R,...A?{target:F(y,"target",u)}:{},...y.namedBindings!==void 0?{namedBindings:Ye(y.namedBindings,`${u}.namedBindings`)}:{},...y.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:P(y,"targetTypeOnlyExports",u)}:{},...y.sourcePureTypeModule!==void 0?{sourcePureTypeModule:P(y,"sourcePureTypeModule",u)}:{},...y.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:P(y,"namedBindingsTypeOnly",u)}:{},...y.portProofEligible!==void 0?{portProofEligible:P(y,"portProofEligible",u)}:{}}}),p=H(e,"capabilityUses","$").map((c,d)=>{let u=`$.capabilityUses[${d}]`,y=L(c,u);return _(y,["file","line","symbol","capability","source"],u),{file:F(y,"file",u),line:W(y,"line",u),symbol:S(y,"symbol",u),capability:M(y,"capability",Ke,u),source:M(y,"source",["ambient-global","import-based"],u)}}),f=H(e,"ambientUses","$").map((c,d)=>{let u=`$.ambientUses[${d}]`,y=L(c,u);return _(y,["file","line","symbol"],u),{file:F(y,"file",u),line:W(y,"line",u),symbol:S(y,"symbol",u)}}),g=H(e,"publishCalls","$").map((c,d)=>{let u=`$.publishCalls[${d}]`,y=L(c,u);_(y,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],u);let b=Y(y,"rawIntentName",u),A=Y(y,"sourceIntent",u);return{file:F(y,"file",u),line:W(y,"line",u),...b?{rawIntentName:b}:{},objectHasIntent:P(y,"objectHasIntent",u),arkPublishCandidate:P(y,"arkPublishCandidate",u),hasSource:P(y,"hasSource",u),...A?{sourceIntent:A}:{}}}),h=H(e,"intentReferences","$").map((c,d)=>{let u=`$.intentReferences[${d}]`,y=L(c,u);return _(y,["file","line","intent"],u),{file:F(y,"file",u),line:W(y,"line",u),intent:S(y,"intent",u)}}),m=H(e,"safetyUses","$").map((c,d)=>{let u=`$.safetyUses[${d}]`,y=L(c,u);_(y,["file","line","kind","symbol"],u);let b=Y(y,"symbol",u),A=M(y,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],u);if(A==="in-memory-store"&&!b)throw new Error(`${u}.symbol is required for in-memory-store facts.`);if(A!=="in-memory-store"&&b)throw new Error(`${u}.symbol is only allowed for in-memory-store facts.`);return{file:F(y,"file",u),line:W(y,"line",u),kind:A,...b?{symbol:b}:{}}});xt(r,c=>c.path,"$.files");let a=new Set(r.map(c=>c.path));for(let c of r){if(c.parseStatus==="parsed"&&c.parseDiagnosticCount!==0)throw new Error(`$.files[${c.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(c.parseStatus==="invalid"&&c.parseDiagnosticCount===0)throw new Error(`$.files[${c.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(s==="complete"&&r.some(c=>c.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let c of o)if(!a.has(c.from))throw new Error(`$.dependencies references missing source file ${c.from}.`);for(let[c,d]of[["$.capabilityUses",p],["$.ambientUses",f],["$.publishCalls",g],["$.intentReferences",h],["$.safetyUses",m]])for(let u of d)if(!a.has(u.file))throw new Error(`${c} references missing file ${u.file}.`);let l=Y(e,"projectPackageName","$");return{schemaVersion:n,completeness:s,completenessReasons:i,resolverIdentity:S(e,"resolverIdentity","$"),compilerIdentity:S(e,"compilerIdentity","$"),compilerOptionsHash:S(e,"compilerOptionsHash","$"),tsconfigHash:S(e,"tsconfigHash","$"),evidenceRequirementsHash:S(e,"evidenceRequirementsHash","$"),...l?{projectPackageName:l}:{},files:r,dependencies:o,capabilityUses:p,ambientUses:f,publishCalls:g,intentReferences:h,safetyUses:m}}function U(e){let t=L(e,"$"),n=S(t,"factsHash","$"),s=S(t,"candidateTreeHash","$"),i=We(Ze(t,!0));if(i.factsHash!==n)throw new Error(`$.factsHash does not match the canonical payload (${i.factsHash}).`);if(s!==i.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${i.candidateTreeHash}).`);return i}var $t=["network","filesystem","clock","randomness","environment","process","persistence"],I={type:"string",minLength:1},J={type:"integer",minimum:1},N={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},Xe={$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:I,message:I,file:N}}},resolverIdentity:I,compilerIdentity:I,compilerOptionsHash:I,tsconfigHash:I,candidateTreeHash:I,evidenceRequirementsHash:I,projectPackageName:I,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:N,contentHash:I,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:I},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:N,specifier:I,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:J,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:N,namedBindings:{type:"array",items:I},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:N,line:J,symbol:I,capability:{enum:$t},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:N,line:J,symbol:I}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:N,line:J,rawIntentName:I,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:I}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:N,line:J,intent:I}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:N,line:J,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:I},allOf:[{if:{properties:{kind:{const:"in-memory-store"}}},then:{required:["symbol"]},else:{not:{required:["symbol"]}}}]}},factsHash:I},allOf:[{if:{properties:{completeness:{const:"complete"}}},then:{properties:{completenessReasons:{maxItems:0},files:{items:{properties:{parseStatus:{const:"parsed"}}}}}}},{if:{properties:{completeness:{enum:["partial","unavailable"]}}},then:{properties:{completenessReasons:{minItems:1}}}}]};var Qe="1.0";var Ee=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"}),Se=Object.freeze(Object.keys(pe).sort()),Re=Object.freeze({fs:"filesystem","node:fs":"filesystem","fs/promises":"filesystem","node:fs/promises":"filesystem","fs-extra":"filesystem","graceful-fs":"filesystem",memfs:"filesystem",chokidar:"filesystem",http:"network",https:"network",http2:"network",net:"network",tls:"network",dgram:"network",dns:"network","node:http":"network","node:https":"network","node:http2":"network","node:net":"network","node:tls":"network","node:dgram":"network","node:dns":"network",axios:"network",undici:"network","node-fetch":"network",got:"network",ky:"network",superagent:"network",ws:"network",process:"process","node:process":"process",child_process:"process","node:child_process":"process","@prisma/client":"persistence",prisma:"persistence",pg:"persistence",mysql:"persistence",mysql2:"persistence",mongodb:"persistence",mongoose:"persistence",sqlite3:"persistence","better-sqlite3":"persistence",redis:"persistence",ioredis:"persistence",typeorm:"persistence",knex:"persistence","drizzle-orm":"persistence",sequelize:"persistence",kysely:"persistence","@supabase/supabase-js":"persistence"}),ve=Object.freeze({process:Object.freeze(["process","node:process"])});function ne(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=Re[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let s=e.slice(0,n),i=Re[s];if(i)return i;let r=e.indexOf("/",n+1);return r<0?null:Re[e.slice(0,r)]??null}function se(e,t){for(let n of t)if(ve[n]?.includes(e))return n;return null}function ie(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let s=t.slice(0,n).join("."),i=pe[s];if(i)return i}return null}function Z(e){if(e?.pure===!0)return[...Ee].sort();let n=(e?.capabilities?.deny??[]).filter(s=>Ee.includes(s));return[...new Set(n)].sort()}function we(e,t){if(t.length===0)return!1;let n=new Set(t),s=e.split(".");for(let i=s.length;i>=1;i-=1)if(n.has(s.slice(0,i).join(".")))return!0;return!1}function fe(e){let t=new Set,n=new Set,s=Object.keys(pe);for(let i of e?.forbiddenGlobals??[]){let r=s.filter(o=>o===i||o.startsWith(`${i}.`));if(r.length===0)n.add(i);else for(let o of r)t.add(`ambient:${o}`);for(let o of ve[i]??[])t.add(`import-exact:${o}`)}for(let i of Z(e)){if(t.add(`import:${i}`),i==="process")for(let r of ve.process)t.add(`import-exact:${r}`);for(let r of s)ie(r)===i&&t.add(`ambient:${r}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}function kt(e){let t=new Set,n=ie(e);n&&t.add(n);for(let[s,i]of Object.entries(pe))(s===e||s.startsWith(`${e}.`))&&t.add(i);return[...t].sort()}var et=new Map;function tt(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function xe(e){let t="";for(let n=0;n<e.length;n+=1){let s=e[n];if(s==="\\"&&n+1<e.length){let i=e[n+1];if("*?{}[],".includes(i)||i==="\\"){t+="\\"+i,n+=1;continue}t+="/";continue}t+=s}return t}function Ot(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 G(e){let t=et.get(e);if(t)return t;let n=xe(e),s=Ot(n),i="",r=0;for(let p=0;p<n.length;p+=1){let f=n[p];f==="\\"&&p+1<n.length?(i+=tt(n[p+1]),p+=1):f==="*"?n[p+1]==="*"?n[p+2]==="/"?(i+="(?:.*/)?",p+=2):(i+=".*",p+=1):i+="[^/]*":f==="?"?i+="[^/]":f==="{"&&s?(i+="(?:",r+=1):f==="}"&&s&&r>0?(i+=")",r-=1):f===","&&s&&r>0?i+="|":i+=tt(f)}let o=new RegExp(`^${i}$`);return et.set(e,o),o}function $e(e){let t=xe(String(e)),s=t.split("*")[0].split("/").filter(Boolean).length,i=t.replace(/\*/g,"").length;return s*1e4+i}function D(e,t){let n=String(e).split(/[/\\]/).join("/"),s,i=-1;for(let r of t??[])if(!(r.exclude??[]).some(o=>G(o).test(n))){for(let o of r.patterns??[])if(G(o).test(n)){let p=$e(o);p>i&&(i=p,s=r.name)}}return s}function nt(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),s=new Set(t.map(i=>String(i).toLowerCase()));for(let i=0;i<n.length-1;i+=1)if(s.has(n[i].toLowerCase()))return`${n[i].toLowerCase()}/${n[i+1].toLowerCase()}`}function Pt(e){let t=new Set;for(let n of e??[]){let i=xe(String(n)).split("/").filter(Boolean);for(let r=0;r<i.length;r+=1){let o=i[r];if((o==="**"||o==="*")&&r>0){let p=i[r-1];p&&!p.includes("*")&&!p.includes("{")&&!p.includes("}")&&t.add(p)}}}return[...t]}function Tt(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(i=>typeof i=="string"&&i.length>0);let s=(n??[]).find(i=>i.name===t);return Pt(s?.patterns)}function X(e,t,n,s){for(let i of e??[])if(!(i.from!==t||i.to!==n)&&i.allowed===!1){if(i.peerIsolation){let r=s?.fromPath,o=s?.toPath;if(!r||!o)return i;let p=Tt(i,t,s?.layers);if(p.length===0)return i;let f=nt(r,p),g=nt(o,p);if(!f||!g||f!==g)return i;continue}if(t!==n)return i}}var ke={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."},Oe=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 Pe(e,t){return t.flatMap((s,i)=>(s.prefixes??s.intentPrefixes??[]).map(r=>({layer:s.name,layerIndex:i,prefix:r.endsWith(".")?r:`${r}.`}))).filter(({prefix:s})=>e.startsWith(s)).sort((s,i)=>i.prefix.length-s.prefix.length||s.layerIndex-i.layerIndex)[0]?.layer}function st(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function Te(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&st(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:ke.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:ke.PUBLISH_MISSING_SOURCE}),t}function w(e,t,n={}){return{ruleId:e,message:t,...n}}function Le(e){let{config:t,rules:n,files:s,manifest:i}=e,r=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(l=>typeof l!="string"))&&r.push(w("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","dynamicImportAllowlist must be an array of file globs.")),t.safety!==void 0&&(t.safety===null||typeof t.safety!="object"||Array.isArray(t.safety)))r.push(w("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let l of["maxTsSuppressions","maxAnyCasts"]){let c=t.safety[l];c!==void 0&&(!Number.isInteger(c)||c<0)&&r.push(w("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${l} must be a non-negative integer.`))}let o=Array.isArray(t.layers)?t.layers:[],p=Array.isArray(i?.architecture?.layers)?i.architecture.layers:[],f=new Set([...o.map(l=>l.name).filter(Boolean),...p.map(l=>l.name).filter(l=>!!l)]);o.length===0&&r.push(w("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let g=new Set,h=new Set;for(let l of o){if(!l.name){r.push(w("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}g.has(l.name)&&h.add(l.name),g.add(l.name),l.forbiddenGlobals!==void 0&&(!Array.isArray(l.forbiddenGlobals)||l.forbiddenGlobals.some(d=>typeof d!="string"))&&r.push(w("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${l.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:l.name}));let c=Array.isArray(l.patterns)?l.patterns:[];if(c.length===0){r.push(w("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${l.name}" has no file patterns and will never classify files.`,{layer:l.name}));continue}for(let d of c){let u;try{u=G(d)}catch(y){r.push(w("CONFIG_INVALID_LAYER_PATTERN",`Layer "${l.name}" has an invalid pattern "${d}": ${y instanceof Error?y.message:String(y)}`,{layer:l.name,pattern:d}));continue}!s.some(y=>u.test(y))&&!l.optional&&r.push(w("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${l.name}" pattern "${d}" matched no included files.`,{layer:l.name,pattern:d,failsStrict:!1}))}}for(let l of h)r.push(w("CONFIG_DUPLICATE_LAYER",`Layer "${l}" is configured more than once.`,{layer:l}));if(f.size>0)for(let l of n??[])l.from&&!f.has(l.from)&&r.push(w("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${l.from}".`,{fromLayer:l.from,toLayer:l.to})),l.to&&!f.has(l.to)&&r.push(w("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${l.to}".`,{fromLayer:l.from,toLayer:l.to}));let m=new Set;if(o.length>1)for(let l of s){let c=-1,d=[];for(let u of o)for(let y of u.patterns??[]){if(!G(y).test(l))continue;let b=$e(y);b>c?(c=b,d=[u.name]):b===c&&!d.includes(u.name)&&d.push(u.name)}d.length>1&&m.add([...d].sort().join(" + "))}m.size>0&&r.push(w("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...m].join(", ")}.`,{pairs:[...m]}));let a=s.filter(l=>!D(l,o));return a.length>0&&r.push(w("CONFIG_UNCLASSIFIED_FILES",`${a.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:a.length,samples:a.slice(0,5)})),r}function it(e){let t=0,n=new Map,s=new Map,i=new Set,r=[],o=[],p=f=>{n.set(f,t),s.set(f,t),t+=1,r.push(f),i.add(f);for(let m of[...e.get(f)??[]].sort())e.has(m)&&(n.has(m)?i.has(m)&&s.set(f,Math.min(s.get(f)??0,n.get(m)??0)):(p(m),s.set(f,Math.min(s.get(f)??0,s.get(m)??0))));if(s.get(f)!==n.get(f))return;let g=[],h;do{if(h=r.pop(),h===void 0)break;i.delete(h),g.push(h)}while(h!==f);g.length>1&&o.push(g.sort())};for(let f of[...e.keys()].sort())n.has(f)||p(f);return o.sort((f,g)=>f[0]<g[0]?-1:f[0]>g[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 re(e){let t=e.contentViolations.map(r=>({...r})),n=(e.warnings??[]).map(r=>({...r})),s=new Map(e.files.map(r=>[r,new Set]));for(let r of e.edges){if(r.to&&r.to!==r.from&&!r.typeOnly&&s.has(r.from)&&s.get(r.from)?.add(r.to),!r.to||!r.fromLayer||!r.toLayer)continue;let o=X(e.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:e.config.layers});if(!o)continue;let p=!!o.peerIsolation;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:r.from,line:r.line,fromLayer:r.fromLayer,toLayer:r.toLayer,target:r.to,...r.typeOnly?{typeOnly:!0}:{},...r.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...r.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...r.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!p&&r.portProofEligible?{portProofEligible:!0}:{},...r.kind?{edgeKind:r.kind}:{},...p?{peerIsolation:!0}:{},message:o.message??(p?`${r.fromLayer} must not ${r.kind} another slice of ${r.toLayer} (${r.from} \u2192 ${r.to}). Extract shared code or use events/ports across slices.`:`${r.fromLayer} must not ${r.kind} ${r.toLayer}.`)})}let i=String(e.config.cyclePolicy??"strict").toLowerCase();if(i!=="off"){let r=it(s);i==="soft"||i==="framework-soft"?n.push(...r.map(o=>({...o,message:`${o.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...r)}return{violations:t,warnings:n,safety:e.safety}}function Lt(e,t){return t.some(n=>{try{return G(n).test(e)}catch{return!1}})}function _t(e,t){let n=e.contract.config.safety??{},s=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,i=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,r=e.contract.config.dynamicImportAllowlist??[],o=t.safetyUses.filter(d=>d.kind==="ts-suppression").map(({file:d,line:u})=>({file:d,line:u})),p=t.safetyUses.filter(d=>d.kind==="any-cast").map(({file:d,line:u})=>({file:d,line:u})),f=t.safetyUses.filter(d=>(d.kind==="dynamic-import"||d.kind==="dynamic-require")&&!Lt(d.file,r)).map(d=>({file:d.file,line:d.line,kind:d.kind==="dynamic-require"?"require":"import"})),g=n.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(d=>d.kind==="in-memory-store").map(d=>({file:d.file,line:d.line,store:d.symbol??"in-memory store"})),h=n.allowDisabledPeerIsolation===!0?[]:(e.contract.config.rules??[]).filter(d=>d.peerIsolation===!1||d.allowed===!1&&!!d.from&&d.from===d.to&&d.peerIsolation!==!0).map(d=>({from:d.from,to:d.to})),m={tsSuppressions:o,anyCasts:p,nonLiteralDynamicImports:f,inMemoryProductionStores:g,disabledPeerIsolationRules:h,thresholds:{maxTsSuppressions:s,maxAnyCasts:i}},a=[],l=f.filter(d=>d.kind==="import");if(l.length>0){let d=l[0];a.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:d.file,line:d.line,message:`${l.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let c=f.filter(d=>d.kind==="require");if(c.length>0){let d=c[0];a.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:d.file,line:d.line,message:`${c.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(o.length>s){let d=o[0];a.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:d.file,line:d.line,message:`${o.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${s}).`})}if(p.length>i){let d=p[0];a.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:d.file,line:d.line,message:`${p.length} explicit any cast(s) exceed safety.maxAnyCasts (${i}).`})}if(g.length>0){let d=g[0];a.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:d.file,line:d.line,message:`${g.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 h.length>0&&a.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${h.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:m,warnings:a}}function Ft(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,s)=>s.length-n.length)[0]}function rt(e,t){let n=t.config.layers.filter(s=>(s.intentPrefixes??[]).length>0);return Pe(e,n.length>0?n:Oe.map(s=>({name:s.layer,prefixes:s.prefixes})))}function Nt(e,t,n){let s=[],i=new Map(e.contract.config.layers.map(r=>[r.name,r]));for(let r of t.ambientUses){let o=n.get(r.file);!o||!Ft(r.symbol,i.get(o)?.forbiddenGlobals??[])||s.push({ruleId:"FORBIDDEN_GLOBAL",file:r.file,line:r.line,fromLayer:o,target:r.symbol,message:`${o} must not use the ambient global "${r.symbol}".`})}for(let r of t.capabilityUses){let o=n.get(r.file);if(!o)continue;let p=i.get(o),f=p?.forbiddenGlobals??[],g=r.source==="import-based"?t.dependencies.find(h=>h.from===r.file&&h.line===r.line&&h.specifier===r.symbol&&!h.typeOnly)?.kind:void 0;if(!(r.source==="ambient-global"&&we(r.symbol,f))){if(r.source==="import-based"){let h=se(r.symbol,f);if(h){s.push({ruleId:"FORBIDDEN_GLOBAL",file:r.file,line:r.line,fromLayer:o,target:r.symbol,...g?{edgeKind:g}:{},message:`${o} must not use module "${r.symbol}" because it is the import form of forbidden global "${h}".`});continue}}Z(p).includes(r.capability)&&s.push({ruleId:"CAPABILITY_VIOLATION",file:r.file,line:r.line,fromLayer:o,target:r.symbol,capability:r.capability,...g?{edgeKind:g}:{},message:r.source==="import-based"?`${o} denies the ${r.capability} capability; found import of "${r.symbol}".`:`${o} denies the ${r.capability} capability; found ambient "${r.symbol}".`})}}for(let r of t.publishCalls){let o=n.get(r.file);if(!o)continue;for(let f of Te({publishCall:!0,rawIntentName:r.rawIntentName,objectHasIntent:r.objectHasIntent,arkPublishCandidate:r.arkPublishCandidate,hasSource:r.hasSource}))s.push({ruleId:f.ruleId,file:r.file,line:r.line,...f.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:o}:{},message:f.message});if(!r.sourceIntent)continue;let p=rt(r.sourceIntent,e.contract);!p||p===o||s.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:r.file,line:r.line,fromLayer:o,toLayer:p,target:r.sourceIntent,message:`Publish source "${r.sourceIntent}" resolves to ${p}, but the publishing file is classified as ${o}.`})}for(let r of t.intentReferences){let o=n.get(r.file);if(!o)continue;let p=rt(r.intent,e.contract);if(!p)continue;let f=X(e.contract.config.rules,o,p);f&&s.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:r.file,line:r.line,fromLayer:o,toLayer:p,target:r.intent,message:f.message??`${o} must not reference ${p} intent ${r.intent}.`})}return s}function _e(e){let{facts:t}=e,n=ce(e.contract.config),s=t.evidenceRequirementsHash===n,i=s?t.completeness:"unavailable",r=s?t.completenessReasons:[...t.completenessReasons,{code:"EVIDENCE_REQUIREMENTS_MISMATCH",message:"Resolved facts were collected for different policy-controlled evidence requirements."}].sort((c,d)=>{let u=`${c.code}\0${c.file??""}\0${c.message}`,y=`${d.code}\0${d.file??""}\0${d.message}`;return u<y?-1:u>y?1:0}),o=t.files.map(c=>({...c,layer:D(c.path,e.contract.config.layers)??null})),p=new Map(o.map(c=>[c.path,c.layer])),f=t.dependencies.map(c=>{let d=c.target?p.get(c.target)??D(c.target,e.contract.config.layers):void 0;return{from:c.from,fromLayer:p.get(c.from)??null,...c.resolution==="resolved-project"&&c.target?{to:c.target,...d?{toLayer:d}:{}}:{},line:c.line,kind:c.kind,typeOnly:c.typeOnly,...c.targetTypeOnlyExports?{targetTypeOnlyExports:c.targetTypeOnlyExports}:{},...c.sourcePureTypeModule?{sourcePureTypeModule:c.sourcePureTypeModule}:{},...c.namedBindingsTypeOnly?{namedBindingsTypeOnly:c.namedBindingsTypeOnly}:{},...c.portProofEligible?{portProofEligible:c.portProofEligible}:{}}}),g=Le({config:e.contract.config,rules:e.contract.config.rules,files:o.map(c=>c.path)}),h=_t(e,t),m=re({config:e.contract.config,rules:e.contract.config.rules,files:o.filter(c=>c.layer).map(c=>c.path),contentViolations:Nt(e,t,p),edges:f,warnings:[...g,...h.warnings],safety:h.report}),a=i==="complete"&&m.violations.length===0,l=a&&m.warnings.every(c=>c.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:i,completenessReasons:r,valid:a,strictValid:l,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:h.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:o,layers:e.contract.config.layers.map(c=>c.name),edges:f,capabilityUses:t.capabilityUses,violations:m.violations,warnings:m.warnings}}}function ue(e){return _e({contract:e.contract,facts:U(e.facts)})}var Fe="1.0";var me=class extends Error{issues;source;constructor(t,n){super(`Invalid architecture change map (${t}):
|
|
4
|
-
${n.map(
|
|
5
|
-
`)}`),this.name="ArchitectureChangeMapValidationError",this.source=t,this.issues=n}};function Ne(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function De(e,t,n,s){for(let i of Object.keys(e))t.includes(i)||s.push({path:`${n}.${i}`,message:"unknown field"})}function q(e,t,n,s){let i=e[t];if(typeof i=="string"&&i.length>0)return i;s.push({path:`${n}.${t}`,message:"must be a non-empty string"})}function Dt(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let i of t.split("/"))if(!(!i||i==="."))if(i===".."){if(n.length===0)return;n.pop()}else n.push(i);let s=n.join("/");return s&&s===t?s:void 0}function Ht(e,t,n="architecture change map"){let s=[];if(!Ne(e))throw new me(n,[{path:"$",message:"must be an object"}]);De(e,["$schema","schemaVersion","files","dependencies"],"$",s);let i=q(e,"$schema","$",s),r=q(e,"schemaVersion","$",s);r&&r!==Fe&&s.push({path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${Fe}`});let o=new Set(t.layers.map(c=>c.name)),p=[],f=new Set;!Array.isArray(e.files)||e.files.length===0?s.push({path:"$.files",message:"must be a non-empty array"}):e.files.forEach((c,d)=>{let u=`$.files[${d}]`;if(!Ne(c)){s.push({path:u,message:"must be an object"});return}De(c,["path","operation","layer"],u,s);let y=q(c,"path",u,s),b=q(c,"operation",u,s),A=q(c,"layer",u,s),R=y?Dt(y):void 0;y&&!R&&s.push({path:`${u}.path`,message:"must be a canonical project-relative path"}),b&&!["create","update","delete"].includes(b)&&s.push({path:`${u}.operation`,message:"must be create, update, or delete"}),A&&!o.has(A)&&s.push({path:`${u}.layer`,message:`references unknown layer ${JSON.stringify(A)}`}),R&&f.has(R)&&s.push({path:`${u}.path`,message:`duplicates planned path ${R}`}),R&&f.add(R);let Ie=R?D(R,t.layers):void 0;R&&A&&o.has(A)&&Ie!==A&&s.push({path:`${u}.layer`,message:Ie?`${R} resolves to ${Ie}, not ${A}`:`${R} is not assigned to an architecture layer`}),R&&b&&["create","update","delete"].includes(b)&&A&&p.push({path:R,operation:b,layer:A})});let g=[],h=new Map(p.map(c=>[c.path,c.operation])),m=new Set,a=e.dependencies??[];if(Array.isArray(a)?a.forEach((c,d)=>{let u=`$.dependencies[${d}]`;if(!Ne(c)){s.push({path:u,message:"must be an object"});return}De(c,["from","to"],u,s);let y=q(c,"from",u,s),b=q(c,"to",u,s);y&&!f.has(y)&&s.push({path:`${u}.from`,message:`must reference a planned file path: ${y}`}),b&&!f.has(b)&&s.push({path:`${u}.to`,message:`must reference a planned file path: ${b}`}),y&&h.get(y)==="delete"&&s.push({path:`${u}.from`,message:`cannot depend from deleted file ${y}`}),b&&h.get(b)==="delete"&&s.push({path:`${u}.to`,message:`cannot depend on deleted file ${b}`}),y&&b&&y===b&&s.push({path:u,message:"must not declare a self dependency"});let A=y&&b?`${y}\0${b}`:void 0;A&&m.has(A)&&s.push({path:u,message:`duplicates dependency ${y} -> ${b}`}),A&&m.add(A),y&&b&&g.push({from:y,to:b})}):s.push({path:"$.dependencies",message:"must be an array"}),s.length>0)throw new me(n,s);let l={$schema:i,schemaVersion:Fe,files:p.sort((c,d)=>c.path.localeCompare(d.path)),dependencies:g.sort((c,d)=>c.from.localeCompare(d.from)||c.to.localeCompare(d.to))};return{map:l,hash:E(C(l))}}function x(e){return`${e.from}->${e.to}`}function ae(e,t,n,s="dependency"){return{id:`${e}:${s}:${x(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${x(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${x(t)}, then preflight again.`}:e==="unplanned"?{nextAction:s==="dependency-removed"?`Restore the removed dependency ${x(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${x(t)} from the candidate, then preflight again.`}:{}}}function oe(e){let t=[],n=new Map(e.changeMap.map.files.map(a=>[a.path,a])),s=new Map(e.changes.map(a=>[a.path,a])),i=new Map(e.changeMap.map.dependencies.map(a=>[x(a),a])),r=new Map(e.baseDependencies.map(a=>[x(a),a])),o=new Map(e.candidateDependencies.map(a=>[x(a),a]));for(let a of[...n.values()].sort((l,c)=>l.path.localeCompare(c.path))){let l=s.get(a.path);l?l.operation!==a.operation?t.push({id:`contradictory:file:${a.path}`,classification:"contradictory",subject:"file",path:a.path,expectedOperation:a.operation,actualOperation:l.operation,message:`${a.path} was planned as ${a.operation} but the actual operation is ${l.operation}.`,nextAction:`Change ${a.path} to the planned ${a.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${a.path}`,classification:"satisfied",subject:"file",path:a.path,expectedOperation:a.operation,actualOperation:l.operation,message:`${a.path} matches the planned ${a.operation} operation.`}):t.push({id:`missing:file:${a.path}`,classification:"missing",subject:"file",path:a.path,expectedOperation:a.operation,message:`${a.path} was planned as ${a.operation} but is absent from the actual change.`,nextAction:`${a.operation[0].toUpperCase()}${a.operation.slice(1)} ${a.path} in the complete change set, then preflight again.`})}for(let a of[...s.values()].sort((l,c)=>l.path.localeCompare(c.path)))n.has(a.path)||t.push({id:`unplanned:file:${a.path}`,classification:"unplanned",subject:"file",path:a.path,actualOperation:a.operation,message:`${a.path} has an unplanned ${a.operation} operation.`,nextAction:`Remove ${a.path} from the change set, then preflight again.`});let p=new Set;for(let a of[...i.values()].sort((l,c)=>x(l).localeCompare(x(c)))){if(o.has(x(a))){t.push(ae("satisfied",a,`${a.from} -> ${a.to} exists in the candidate architecture.`));continue}let l={from:a.to,to:a.from};o.has(x(l))?(p.add(x(l)),t.push(ae("contradictory",a,`${a.from} -> ${a.to} was planned, but the candidate contains the reverse edge.`))):t.push(ae("missing",a,`${a.from} -> ${a.to} is absent from the candidate architecture.`))}let f=new Set([...n.keys(),...s.keys()]);for(let[a,l]of[...o].sort(([c],[d])=>c.localeCompare(d)))r.has(a)||i.has(a)||p.has(a)||!f.has(l.from)&&!f.has(l.to)||t.push({...ae("unplanned",l,`${l.from} -> ${l.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let g=new Set(e.changeMap.map.files.filter(a=>a.operation==="delete").map(a=>a.path));for(let[a,l]of[...r].sort(([c],[d])=>c.localeCompare(d)))o.has(a)||g.has(l.from)||g.has(l.to)||!f.has(l.from)&&!f.has(l.to)||t.push({...ae("unplanned",l,`${l.from} -> ${l.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let h={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((a,l)=>h[a.classification]-h[l.classification]||(a.subject===l.subject?0:a.subject==="file"?-1:1)||a.id.localeCompare(l.id));let m={satisfied:t.filter(a=>a.classification==="satisfied").length,missing:t.filter(a=>a.classification==="missing").length,contradictory:t.filter(a=>a.classification==="contradictory").length,unplanned:t.filter(a=>a.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}}function Q(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function lt(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function at(e,t){if(e.isImportDeclaration(t)){let s=t.importClause;if(!s)return!1;if(s.isTypeOnly)return!0;let i=s.namedBindings;return!!(i&&e.isNamedImports(i)&&i.elements.length>0&&i.elements.every(r=>r.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(s=>s.isTypeOnly))}function ct(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},s=e.createCompilerHost(n,!0);return s.getSourceFile=i=>i===t.fileName?t:void 0,s.fileExists=i=>i===t.fileName,s.readFile=i=>i===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,s).getTypeChecker()}function He(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function Me(e,t,n,s){let i=s.parent&&e.isShorthandPropertyAssignment(s.parent)&&s.parent.name===s,r;try{r=i?t.getShorthandAssignmentValueSymbol(s.parent):He(t,s)}catch{r=void 0}return!!r?.declarations?.some(o=>o.getSourceFile().fileName===n.fileName)}function je(e,t){let n,s=[],i=(o,p,f,g=!1)=>s.push({specifier:f,kind:p,line:lt(t,o),typeOnly:g,unresolved:f===void 0,node:o}),r=o=>{if(e.isImportDeclaration(o))i(o,"import",Q(e,o.moduleSpecifier),at(e,o));else if(e.isExportDeclaration(o)&&o.moduleSpecifier)i(o,"export",Q(e,o.moduleSpecifier),at(e,o));else if(e.isImportEqualsDeclaration(o)&&e.isExternalModuleReference(o.moduleReference))i(o,"require",Q(e,o.moduleReference.expression),o.isTypeOnly===!0);else if(e.isCallExpression(o)){let p=o.expression.kind===e.SyntaxKind.ImportKeyword,g=e.isIdentifier(o.expression)&&o.expression.text==="require"&&!Me(e,n??(n=ct(e,t)),t,o.expression);(p||g)&&i(o,g?"require":"dynamic-import",Q(e,o.arguments[0]))}e.forEachChild(o,r)};return r(t),s}function Mt(e,t){let n=[],s=t;for(;e.isPropertyAccessExpression(s)||e.isElementAccessExpression(s);){if(e.isPropertyAccessExpression(s))n.unshift(s.name.text);else{let i=Q(e,s.argumentExpression);if(i===void 0)return;n.unshift(i)}s=s.expression}if(e.isIdentifier(s))return n.unshift(s.text),{root:s,segments:n}}function jt(e,t){let n=t.parent;return e.isPropertyAccessExpression(n)||e.isElementAccessExpression(n)?!1:e.isExpressionNode(t)&&!e.isInTypeQuery(t)||e.isShorthandPropertyAssignment(n)&&n.name===t}function ot(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let s=n.length;s>=1;s-=1){let i=n.slice(0,s).join(".");if(e.has(i))return i}}function Ve(e,t,n){if(n.length===0)return[];let s=new Set(n),i=ct(e,t),r=new Map,o=new Set;for(let a of t.statements)if(e.isVariableStatement(a))for(let l of a.declarationList.declarations)e.isIdentifier(l.name)&&o.add(l.name.text);let p=a=>{let l=Mt(e,a);if(!l)return;let c=He(i,l.root),d=c?r.get(c):void 0;return d?[...d,...l.segments.slice(1)]:Me(e,i,t,l.root)||o.has(l.root.text)?void 0:l.segments};for(let a of t.statements)if(e.isVariableStatement(a))for(let l of a.declarationList.declarations){if(!l.initializer||!e.isIdentifier(l.name))continue;let c=p(l.initializer),d=He(i,l.name);!c||!d||r.set(d,c)}let f=[],g=new Set,h=(a,l)=>{let c=lt(t,l),d=`${a}:${l.getStart(t)}`;g.has(d)||(g.add(d),f.push({name:a,line:c,node:l}))},m=a=>{let l=a.parent&&(e.isPropertyAccessExpression(a.parent)||e.isElementAccessExpression(a.parent))&&a.parent.expression===a;if((e.isPropertyAccessExpression(a)||e.isElementAccessExpression(a))&&!l){let c=p(a),d=c?ot(s,c):void 0;d&&h(d,a)}else e.isIdentifier(a)&&s.has(a.text)&&jt(e,a)&&!Me(e,i,t,a)&&h(a.text,a);if(e.isVariableDeclaration(a)&&e.isObjectBindingPattern(a.name)&&a.initializer){let c=p(a.initializer);if(c)for(let d of a.name.elements){if(!e.isIdentifier(d.name))continue;let u=d.propertyName?Q(e,d.propertyName)??d.propertyName.text:d.name.text,y=ot(s,[...c,u]);y&&h(y,a.initializer)}}e.forEachChild(a,m)};return m(t),f}function Vt(e,t,n){let s=[];for(let i of n?.dependencies??je(e,t)){if(i.typeOnly||!i.specifier)continue;let r=ne(i.specifier);r&&s.push({capability:r,symbol:i.specifier,line:i.line,source:"import-based"})}for(let i of n?.ambientUses??Ve(e,t,Se)){let r=ie(i.name);r&&s.push({capability:r,symbol:i.name,line:i.line,source:"ambient-global"})}return s.sort((i,r)=>i.line-r.line||i.capability.localeCompare(r.capability)||i.symbol.localeCompare(r.symbol))}var Ge="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",dt=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Ut=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Gt(){let e=[];for(let t of dt)for(let n of dt)t===n||Ut.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var ft=Gt();var V={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},pt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Ge,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:Ge,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:{...V,minItems:1,default:["src"]},exclude:{...V,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:ft,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...V,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:{...V,minItems:1},exclude:V,intentPrefixes:V,description:{type:"string",minLength:1},forbiddenGlobals:V,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:{...V,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}}}}},te=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
|
|
6
|
-
${n.map(
|
|
7
|
-
`)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function ut(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ue(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function ee(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function qt(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function ye(e,t,n,s,i){if(t.$ref){let r=qt(t.$ref,s);if(!r){i.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}ye(e,r,n,s,i);return}if(t.const!==void 0&&!Object.is(e,t.const)){i.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(r=>Object.is(r,e))){i.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!ut(e)){i.push({path:n,message:`must be an object; received ${ee(e)}`});return}let r=t.properties??{};for(let o of t.required??[])e[o]===void 0&&i.push({path:Ue(n,o),message:"is required"});if(t.additionalProperties===!1)for(let o of Object.keys(e))o in r||i.push({path:Ue(n,o),message:"unknown field"});for(let[o,p]of Object.entries(r))e[o]!==void 0&&ye(e[o],p,Ue(n,o),s,i);return}if(t.type==="array"){if(!Array.isArray(e)){i.push({path:n,message:`must be an array; received ${ee(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&i.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let r=e.map(o=>JSON.stringify(o));new Set(r).size!==r.length&&i.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((r,o)=>ye(r,t.items,`${n}[${o}]`,s,i));return}if(t.type==="string"){if(typeof e!="string"){i.push({path:n,message:`must be a string; received ${ee(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&i.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&i.push({path:n,message:`must be a boolean; received ${ee(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){i.push({path:n,message:`must be an integer; received ${ee(e)}`});return}t.minimum!==void 0&&e<t.minimum&&i.push({path:n,message:`must be at least ${t.minimum}`})}}function Bt(e){return{...e,$schema:e.$schema===void 0?Ge: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?ft.map(t=>({...t})):e.rules}}function zt(e,t="ark.config.json"){if(!ut(e))throw new te(t,[{path:"$",message:`must be an object; received ${ee(e)}`}]);let n=e.schemaVersion===void 0?"unversioned":null;if(e.schemaVersion!==void 0&&e.schemaVersion!=="1.0")throw new te(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.0`}]);return{candidate:Bt(e),migratedFrom:n}}function qe(e,t="ark.config.json"){let{candidate:n,migratedFrom:s}=zt(e,t),i=[];if(ye(n,pt,"$",pt,i),i.length>0)throw new te(t,i);return{config:n,migratedFrom:s}}function mt(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(s){throw new te(t,[{path:"$",message:`invalid JSON: ${s instanceof Error?s.message:String(s)}`}])}return qe(n,t)}var yt="1.0";function v(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 k(e){return[...new Set(e??[])].sort()}function B(e,t,n,s,i){let r=k(n),o=k(s),p=new Set(r),f=new Set(o),g=o.filter(m=>!p.has(m)),h=r.filter(m=>!f.has(m));g.length===0&&h.length===0||(g.length>0&&v(e,{kind:"added",path:t,classification:i.added,message:i.addedMessage,before:r,after:o}),h.length>0&&v(e,{kind:"removed",path:t,classification:i.removed,message:i.removedMessage,before:r,after:o}))}function ge(e,t,n,s,i,r,o){if(n===s)return;v(e,{kind:s?"enabled":"disabled",path:t,classification:s?i:i==="strengthening"?"weakening":"strengthening",message:s?r:o,before:n,after:s})}function he(e,t){let n=new Map,s=new Set;for(let i of e){let r=t(i);n.has(r)?s.add(r):n.set(r,i)}return{values:n,duplicates:[...s].sort()}}function Kt(e,t,n){let s=he(t,r=>r.name),i=he(n,r=>r.name);(s.duplicates.length>0||i.duplicates.length>0)&&v(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:s.duplicates,after:i.duplicates});for(let r of[...new Set([...s.values.keys(),...i.values.keys()])].sort()){let o=s.values.get(r),p=i.values.get(r),f=`$.layers[${r}]`;if(!o&&p){v(e,{kind:"layer-added",path:f,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:p});continue}if(o&&!p){v(e,{kind:"layer-removed",path:f,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:o});continue}if(!o||!p)continue;B(e,`${f}.patterns`,o.patterns,p.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),B(e,`${f}.exclude`,o.exclude,p.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let g=fe(o),h=fe(p);B(e,`${f}.forbiddenGlobals`,g.rawGlobals,h.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),B(e,`${f}.capabilities`,g.atoms,h.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)."}),k(o.intentPrefixes).join("\0")!==k(p.intentPrefixes).join("\0")&&v(e,{kind:"intent-prefixes-changed",path:`${f}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:k(o.intentPrefixes),after:k(p.intentPrefixes)}),ge(e,`${f}.mayImportInfrastructure`,o.mayImportInfrastructure===!0,p.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),ge(e,`${f}.optional`,o.optional===!0,p.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 Yt(e,t,n){let s=o=>`${o.from}->${o.to}`,i=he(t,s),r=he(n,s);(i.duplicates.length>0||r.duplicates.length>0)&&v(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:i.duplicates,after:r.duplicates});for(let o of[...new Set([...i.values.keys(),...r.values.keys()])].sort()){let p=i.values.get(o),f=r.values.get(o),g=`$.rules[${o}]`;if(!p&&f){f.allowed===!1&&v(e,{kind:"deny-added",path:g,classification:"strengthening",message:"A denied dependency edge was added.",after:f});continue}if(p&&!f){p.allowed===!1&&v(e,{kind:"deny-removed",path:g,classification:"weakening",message:"A denied dependency edge was removed.",before:p});continue}if(!p||!f)continue;p.allowed!==f.allowed&&v(e,{kind:f.allowed?"deny-disabled":"deny-enabled",path:`${g}.allowed`,classification:f.allowed?"weakening":"strengthening",message:f.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:p.allowed,after:f.allowed});let h=p.peerIsolation===!0,m=f.peerIsolation===!0;if(h!==m){let a=p.from===p.to&&f.from===f.to;v(e,{kind:m?"peer-isolation-enabled":"peer-isolation-disabled",path:`${g}.peerIsolation`,classification:a?m?"strengthening":"weakening":"judgment-required",message:a?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:h,after:m})}k(p.sliceFolders).join("\0")!==k(f.sliceFolders).join("\0")&&v(e,{kind:"slice-folders-changed",path:`${g}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:k(p.sliceFolders),after:k(f.sliceFolders)})}}function Wt(e,t,n){let s=t.safety??{},i=n.safety??{};for(let r of["maxTsSuppressions","maxAnyCasts"]){let o=s[r]??0,p=i[r]??0;o!==p&&v(e,{kind:p>o?"threshold-raised":"threshold-lowered",path:`$.safety.${r}`,classification:p>o?"weakening":"strengthening",message:p>o?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:o,after:p})}for(let r of["allowInMemory","allowDisabledPeerIsolation"])ge(e,`$.safety.${r}`,s[r]===!0,i[r]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}function Jt(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 gt(e,t){let n=[];B(n,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),B(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."}),B(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."}),ge(n,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let s={off:0,soft:1,"framework-soft":1,strict:2},i=e.cyclePolicy??"strict",r=t.cyclePolicy??"strict";if(i!==r){let o=s[r]===s[i]?"judgment-required":s[r]>s[i]?"strengthening":"weakening";v(n,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:o,message:"The cycle enforcement level changed.",before:i,after:r})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&v(n,{kind:"framework-overlay-changed",path:"$.frameworkOverlay",classification:"judgment-required",message:"The framework overlay changed and may alter effective layer matching.",before:e.frameworkOverlay??null,after:t.frameworkOverlay??null}),Kt(n,e.layers,t.layers),Yt(n,e.rules,t.rules),Wt(n,e,t),n.sort((o,p)=>o.path.localeCompare(p.path)||o.id.localeCompare(p.id)),{schemaVersion:yt,classification:Jt(n),findings:n}}function ht(e,t){if(!e||e.schemaVersion!==yt||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(i=>typeof i!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=k(e.findingIds),s=k(t.findingIds);return n.length===s.length&&n.every((i,r)=>i===s[r])}function z(e){let t=[];for(let n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."&&t.length>0&&t.at(-1)!==".."?t.pop():t.push(n));return t.join("/")}function bt(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}function be(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 le(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let s=t,i="";for(t+=1;t<e.length;t+=1){let r=e[t];if(r===n)return{value:i,offset:s,excerpt:e.slice(s,t+1)};r==="\\"&&t+1<e.length?(i+=e[t+1],t+=1):i+=r}}function O(e,t,n){return e.startsWith(t,n)&&!be(e[n-1])&&!be(e[n+t.length])}function At(e,t){let n=$(e,t);if(e[n]!=="{")return!1;n+=1;let s=!1;for(;n<e.length;){if(n=$(e,n),e[n]==="}")return s;if(e[n]===","){n+=1;continue}if(!O(e,"type",n))return!1;let i=$(e,n+4);if(i>=e.length||e[i]===","||e[i]==="}"||O(e,"as",i)||!bt(e[i]))return!1;for(n=i;n<e.length&&be(e[n]);)n+=1;if(n=$(e,n),O(e,"as",n)){if(n=$(e,n+2),!bt(e[n]))return!1;for(;n<e.length&&be(e[n]);)n+=1}s=!0}return!1}function Zt(e,t){if(t=$(e,t+6),e[t]==="(")return le(e,$(e,t+1));let n=!1;if(O(e,"type",t)){let i=$(e,t+4);e[i]!==","&&!O(e,"from",i)&&(n=!0)}else At(e,t)&&(n=!0);let s=Ct(e,t,!0);return s&&n?{...s,typeOnly:!0}:s}function Xt(e,t){t=t+6;let n=$(e,t),s=!1;if(O(e,"type",n)){let r=$(e,n+4);(e[r]==="{"||e[r]==="*")&&(s=!0)}else At(e,n)&&(s=!0);let i=Ct(e,t,!1);return i&&s?{...i,typeOnly:!0}:i}function Ct(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(O(e,"from",t))return le(e,$(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return le(e,t);if(t>0&&(O(e,"import",t)||O(e,"export",t)))return}}function Qt(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 en(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let s=$(e,t+7);if(e[s]!=="(")return;s=$(e,s+1);let i=le(e,s);return i?{...i,requireCall:!0}:void 0}function tn(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(`
|
|
8
|
-
`,n+2),n<0)break;continue}if(
|
|
9
|
-
`).length;
|
|
10
|
-
`).length,p={kind:"import",file:e.path,line:o,excerpt:i.excerpt},f=nn(e.path,r,t);n.push({from:e.path,specifier:r,to:f?.path??null,resolution:f?"resolved":"unresolved",fromLayer:e.layer,toLayer:f?.layer??null,evidence:p})}return{edges:n,capabilityUses:s}}function nn(e,t,n){let s=e.split("/");s.pop();for(let r of t.split("/"))r==="."||r===""||(r===".."?s.pop():s.push(r));let i=s.join("/");for(let r of[i,`${i}.ts`,`${i}.tsx`,`${i}.mts`,`${i}.cts`,`${i}/index.ts`,`${i}/index.tsx`]){let o=n.get(r);if(o)return o}}function Rt(e,t){let n=[];for(let s of e){if(!s.to||!s.fromLayer||!s.toLayer)continue;let i=X(t.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:t.layers});i&&n.push({ruleId:`layer-dependency:${i.from}->${i.to}`,message:i.message??`${i.from} must not depend on ${i.to}.`,edge:s,evidence:s.evidence})}return n}var sn={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 Be(e,t){let n=typeof e=="string"?mt(e,t):qe(e,t);return{...n,policyHash:E(C(n.config))}}function rn(e){let t=Be(e.baseConfig,e.baseSource??"base ark.config.json"),n=Be(e.candidateConfig,e.candidateSource??"candidate ark.config.json"),s=gt(t.config,n.config),i=s.findings.filter(p=>p.classification==="weakening"||p.classification==="judgment-required").map(p=>p.id).sort(),r=i.length>0,o=r&&ht(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:i});return{schemaVersion:s.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:s.classification,findings:s.findings,blockingFindingIds:i,requiresAcknowledgement:r,acknowledged:o,valid:!r||o}}function Ae(e){let t=e.files.map(m=>{let a=z(m.path);return{path:a,content:m.content,contentHash:E(m.content),layer:D(a,e.contract.config.layers)??null}}).sort((m,a)=>m.path.localeCompare(a.path)),n=new Map(t.map(m=>[m.path,m])),s=[],i=[];for(let m of t){let a=It(m,n);s.push(...a.edges),i.push(...a.capabilityUses)}let r=Rt(s,e.contract.config),o=new Map(e.contract.config.layers.map(m=>[m.name,m])),p=new Map(e.contract.config.layers.map(m=>[m.name,new Set(Z(m))]));for(let m of i){let a=n.get(m.file)?.layer;if(!a)continue;let l=o.get(a),c=se(m.symbol,l?.forbiddenGlobals??[]);if(c){r.push({ruleId:"FORBIDDEN_GLOBAL",message:`${a} must not use module "${m.symbol}" because it is the import form of forbidden global "${c}".`,symbol:m.symbol,evidence:m.evidence});continue}p.get(a)?.has(m.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",message:`${a} denies the ${m.capability} capability; found import of "${m.symbol}".`,capability:m.capability,symbol:m.symbol,evidence:m.evidence})}let f=t.length===0?"complete":"partial",g=f==="complete"?[]:[{...sn}],h={schemaVersion:Qe,policyHash:e.contract.policyHash,compilerOptionsHash:E(C(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(m=>m.name),edges:s,capabilityUses:i,violations:r};return{mode:"lexical-compatibility",completeness:f,completenessReasons:g,valid:f==="complete"&&r.length===0,ir:h}}function ze(e){let t=new Map(e.files.map(n=>[z(n.path),n]));for(let n of e.changes){let s=z(n.path);"delete"in n&&n.delete?t.delete(s):"content"in n&&t.set(s,{path:s,content:n.content})}return Ae({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}function an(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 Ce(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 Et(e){return E(C(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}function on(e){let t=Ae(e),n=new Map(t.ir.files.map(l=>[l.path,l])),s=[],i=new Set,r=[];for(let l of e.changes){let c=l.path.replace(/\\/g,"/"),d=z(l.path);if(!d||d===".."||d.startsWith("../")||c.startsWith("/")||/^[A-Za-z]:\//.test(c)||c.includes("\0")){r.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(i.has(d)){r.push({ruleId:"DUPLICATE_CHANGE_PATH",file:d,line:1,message:`The atomic change set contains more than one operation for ${d}.`});continue}i.add(d),"delete"in l&&l.delete&&!n.has(d)&&r.push({ruleId:"DELETE_TARGET_MISSING",file:d,line:1,message:`Cannot delete ${d} because it is not present in the supplied base tree.`}),s.push("delete"in l&&l.delete?{path:d,delete:!0}:{path:d,content:"content"in l?l.content:""})}e.changes.length===0&&r.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let o=ze({...e,changes:s}),p=new Map(o.ir.files.map(l=>[l.path,l])),f=o.ir.violations.filter(l=>l.ruleId==="CAPABILITY_VIOLATION"||l.ruleId==="FORBIDDEN_GLOBAL").map(l=>{let c=p.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}:{},...c?{fromLayer:c}:{},edgeKind:"import",message:l.message}}),g=re({config:e.contract.config,rules:e.contract.config.rules,files:o.ir.files.map(l=>l.path),contentViolations:f,edges:o.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"}))}),h=s.map(l=>{let c=z(l.path),d=n.get(c),u=p.get(c);return{path:c,operation:"delete"in l&&l.delete?"delete":d?"update":"create",...d?{beforeContentHash:d.contentHash}:{},...u?{candidateContentHash:u.contentHash}:{}}}).sort((l,c)=>l.path.localeCompare(c.path)),m=[...r,...g.violations].map(l=>({...l,nextAction:Ce(l)})),a=e.changeMap?oe({changeMap:e.changeMap,changes:h,baseDependencies:t.ir.edges.flatMap(l=>l.to?[{from:l.from,to:l.to}]:[]),candidateDependencies:o.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"&&o.valid&&m.length===0&&(a?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:o.ir.compilerOptionsHash,baseTreeHash:Et(t.ir.files),candidateTreeHash:Et(o.ir.files),baseCompleteness:t.completeness,candidateCompleteness:o.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:o.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...a?{convergence:a}:{},changes:h,violations:m,warnings:g.warnings}}function ln(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let i of t.split("/"))if(!(!i||i==="."))if(i===".."){if(n.length===0)return;n.pop()}else n.push(i);let s=n.join("/");return s&&s===t?s:void 0}function cn(e,t){return[["resolverIdentity",e.resolverIdentity,t.resolverIdentity],["compilerIdentity",e.compilerIdentity,t.compilerIdentity],["evidenceRequirementsHash",e.evidenceRequirementsHash,t.evidenceRequirementsHash],["projectPackageName",e.projectPackageName??"",t.projectPackageName??""]].filter(([,s,i])=>s!==i).map(([s,i,r])=>({ruleId:"FACTS_IDENTITY_MISMATCH",file:"<change-set>",line:1,field:s,before:i,candidate:r,message:`Base and candidate facts must use the same ${s}.`}))}function dn(e,t,n,s){let i=n.get(t),r=s.get(t);return{path:t,operation:"delete"in e&&e.delete?"delete":i?"update":"create",...i?{beforeContentHash:i.contentHash}:{},...r?{candidateContentHash:r.contentHash}:{}}}function pn(e){let t=U(e.baseFacts),n=U(e.candidateFacts),s=ue({contract:e.contract,facts:t}),i=ue({contract:e.contract,facts:n}),r=new Map(t.files.map(a=>[a.path,a])),o=new Map(n.files.map(a=>[a.path,a])),p=cn(t,n),f=new Map,g=[];for(let a of e.changes){let l=ln(a.path);if(!l){p.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(f.has(l)){p.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,a);let c=r.get(l),d=o.get(l);if("delete"in a&&a.delete)c||p.push({ruleId:"DELETE_TARGET_MISSING",file:l,line:1,message:`Cannot delete ${l} because it is not present in the supplied base facts.`}),d&&p.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:l,line:1,message:`Candidate facts still contain deleted file ${l}.`});else{let u="content"in a?a.content:"",y=E(u);d?d.contentHash!==y&&p.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:l,line:1,expectedContentHash:y,candidateContentHash:d.contentHash,message:`Candidate facts for ${l} do not match the declared content.`}):p.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:l,line:1,message:`Candidate facts do not contain changed file ${l}.`})}g.push(dn(a,l,r,o))}e.changes.length===0&&p.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});for(let a of new Set([...r.keys(),...o.keys()])){if(f.has(a))continue;let l=r.get(a),c=o.get(a);l&&c&&C(l)===C(c)||p.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:a,line:1,message:`Candidate facts change ${a}, but the atomic change set does not declare it.`})}let h=e.changeMap?oe({changeMap:e.changeMap,changes:g,baseDependencies:s.ir.edges.flatMap(a=>a.to?[{from:a.from,to:a.to}]:[]),candidateDependencies:i.ir.edges.flatMap(a=>a.to?[{from:a.from,to:a.to}]:[])}):void 0,m=[...p,...i.ir.violations].map(a=>({...a,nextAction:Ce(a)}));return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:s.completeness==="complete"&&i.strictValid&&m.length===0&&(h?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,resolverIdentity:n.resolverIdentity,compilerIdentity:n.compilerIdentity,compilerOptionsHash:n.compilerOptionsHash,tsconfigHash:n.tsconfigHash,baseCompilerOptionsHash:t.compilerOptionsHash,candidateCompilerOptionsHash:n.compilerOptionsHash,baseTsconfigHash:t.tsconfigHash,candidateTsconfigHash:n.tsconfigHash,evidenceRequirementsHash:n.evidenceRequirementsHash,baseFactsHash:t.factsHash,candidateFactsHash:n.factsHash,baseTreeHash:t.candidateTreeHash,candidateTreeHash:n.candidateTreeHash,baseCompleteness:s.completeness,candidateCompleteness:i.completeness,baseCompletenessReasons:s.completenessReasons,candidateCompletenessReasons:i.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...h?{convergence:h}:{},changes:g.sort((a,l)=>a.path<l.path?-1:a.path>l.path?1:0),violations:m,warnings:i.ir.warnings}}var vt=new WeakSet;function St(e){if(!e||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Object.values(e))St(t);return Object.freeze(e)}function Ls(e){let t=St(de(e));return vt.add(t),t}function _s(e){if(!vt.has(e.facts))throw new Error("Trusted resolved analysis requires immutable in-process canonical facts.");return _e(e)}export{Se as AMBIENT_CAPABILITY_ENTRIES,Ee as CAPABILITY_IDS,Oe as DEFAULT_INTENT_PREFIXES,Xe as RESOLVED_CANDIDATE_FACTS_SCHEMA,K as RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,ke as SOURCE_POLICY_MESSAGES,we as ambientCoveredByForbiddenGlobals,oe as analyzeArchitectureConvergence,ze as analyzeChange,rn as analyzePolicyDelta,Ae as analyzeProject,ue as analyzeResolvedProject,_s as analyzeTrustedResolvedProject,ie as capabilityForAmbientName,ne as capabilityForModuleSpecifier,Te as classifyPublishFacts,Le as collectAnalysisConfigWarnings,Vt as collectCapabilityUses,Ve as collectForbiddenCapabilityUses,de as createResolvedCandidateFacts,Ls as createTrustedResolvedCandidateFacts,it as detectArchitectureCycles,E as deterministicHash,Z as effectiveCapabilityDeny,re as evaluateArchitectureGraph,an as explainViolation,je as extractSemanticDependencies,se as forbiddenGlobalForModuleSpecifier,Ht as loadArchitectureChangeMap,Be as loadContract,U as loadResolvedCandidateFacts,st as looksLikeArkIntent,kt as lowerForbiddenGlobal,fe as loweredLayerCoverage,on as preflightChange,pn as preflightResolvedChange,Pe as resolveIntentLayer,ce as resolvedFactsEvidenceRequirementsHash,C as stableSerialize};
|
|
3
|
+
function S(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}function k(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(k).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${k(t[n])}`).join(",")}}`}var ee="1.1";var ot=["network","filesystem","clock","randomness","environment","process","persistence"];function U(e,t){let n=k(e),r=k(t);return n<r?-1:n>r?1:0}function D(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}function ve(e){let t={schemaVersion:"1.1",include:D(e.include??[]),exclude:D(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:D(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:D(n.patterns??[]),exclude:D(n.exclude??[]),forbiddenGlobals:D(n.forbiddenGlobals??[]),intentPrefixes:D(n.intentPrefixes??[]),capabilityDeny:D(n.capabilities?.deny??[]),pure:n.pure===!0})).sort(U),safety:{maxTsSuppressions:e.safety?.maxTsSuppressions??0,maxAnyCasts:e.safety?.maxAnyCasts??0,allowInMemory:e.safety?.allowInMemory===!0,allowDisabledPeerIsolation:e.safety?.allowDisabledPeerIsolation===!0}};return S(k(t))}function en(e){let t=e.completenessReasons.map(i=>({code:i.code,message:i.message,...i.file?{file:i.file}:{}})).sort(U),n=e.files.map(i=>({...i,typeOnlyExportNames:D(i.typeOnlyExportNames)})).sort((i,o)=>i.path<o.path?-1:i.path>o.path?1:0),r=e.dependencies.map(i=>({...i,...i.namedBindings?{namedBindings:D(i.namedBindings)}:{}})).sort(U),s=e.capabilityUses.map(i=>({...i})).sort(U),a=e.ambientUses.map(i=>({...i})).sort(U),l=e.publishCalls.map(i=>({...i})).sort(U),c=e.intentReferences.map(i=>({...i})).sort(U),d=e.safetyUses.map(i=>({...i})).sort(U),b=(e.classShapes??[]).map(i=>({...i,mutatingMethods:[...i.mutatingMethods??[]].map(o=>({...o}))})).sort(U),A=e.files.map(({path:i,contentHash:o})=>({path:i,contentHash:o})).sort((i,o)=>i.path<o.path?-1:i.path>o.path?1:0),g=S(k(A));return{schemaVersion:"1.1",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:r,capabilityUses:s,ambientUses:a,publishCalls:l,intentReferences:c,safetyUses:d,classShapes:b}}function ct(e){let t=en(e);return{...t,factsHash:S(k(t))}}function Ie(e){return ct(pt(F(e,"$"),!1))}function F(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}function L(e,t,n){let r=new Set(t),s=Object.keys(e).find(a=>!r.has(a));if(s)throw new Error(`${n}.${s} is not part of schema ${"1.1"}.`)}function w(e,t,n){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`${n}.${t} must be a non-empty string.`);return r}function te(e,t,n){if(e[t]!==void 0)return w(e,t,n)}function M(e,t,n){let r=w(e,t,n),s=r.replace(/\\/g,"/");if(!s||s.startsWith("/")||/^[A-Za-z]:\//.test(s)||/[\u0000-\u001f\u007f]/.test(s))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let a=[];for(let c of s.split("/"))if(!(!c||c==="."))if(c===".."){if(a.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);a.pop()}else a.push(c);let l=a.join("/");if(!l||l!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return l}function $(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}function dt(e,t,n){let r=e[t];if(!Number.isInteger(r)||Number(r)<0)throw new Error(`${n}.${t} must be a non-negative integer.`);return Number(r)}function ne(e,t,n){let r=dt(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}function H(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}function z(e,t,n,r){let s=e[t];if(typeof s!="string"||!n.includes(s))throw new Error(`${r}.${t} must be one of ${n.join(", ")}.`);return s}function lt(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 tn(e,t,n){let r=new Set;for(let s of e){let a=t(s);if(r.has(a))throw new Error(`${n} must not contain duplicate facts (${a}).`);r.add(a)}}function pt(e,t){L(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","classShapes",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=z(e,"schemaVersion",["1.0","1.1"],"$"),r=z(e,"completeness",["complete","partial","unavailable"],"$"),s=H(e,"completenessReasons","$").map((h,R)=>{let u=`$.completenessReasons[${R}]`,y=F(h,u);L(y,["code","message","file"],u);let v=y.file===void 0?void 0:M(y,"file",u);return{code:w(y,"code",u),message:w(y,"message",u),...v?{file:v}:{}}});if(r==="complete"&&s.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(r!=="complete"&&s.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let a=H(e,"files","$").map((h,R)=>{let u=`$.files[${R}]`,y=F(h,u);return L(y,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],u),{path:M(y,"path",u),contentHash:w(y,"contentHash",u),parseStatus:z(y,"parseStatus",["parsed","invalid"],u),parseDiagnosticCount:dt(y,"parseDiagnosticCount",u),exportsOnlyTypes:$(y,"exportsOnlyTypes",u),typeOnlyExportNames:lt(y.typeOnlyExportNames,`${u}.typeOnlyExportNames`),hasTopLevelSideEffects:$(y,"hasTopLevelSideEffects",u)}}),l=H(e,"dependencies","$").map((h,R)=>{let u=`$.dependencies[${R}]`,y=F(h,u);L(y,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],u);let v=te(y,"specifier",u),E=te(y,"target",u),K=z(y,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],u);if(K==="resolved-project"&&!E)throw new Error(`${u}.target is required for resolved-project dependencies.`);if(K!=="resolved-project"&&E)throw new Error(`${u}.target is only allowed for resolved-project dependencies.`);if(K!=="dynamic"&&!v)throw new Error(`${u}.specifier is required unless resolution is dynamic.`);return{from:M(y,"from",u),...v?{specifier:v}:{},kind:z(y,"kind",["import","export","dynamic-import","require"],u),typeOnly:$(y,"typeOnly",u),line:ne(y,"line",u),resolution:K,...E?{target:M(y,"target",u)}:{},...y.namedBindings!==void 0?{namedBindings:lt(y.namedBindings,`${u}.namedBindings`)}:{},...y.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:$(y,"targetTypeOnlyExports",u)}:{},...y.sourcePureTypeModule!==void 0?{sourcePureTypeModule:$(y,"sourcePureTypeModule",u)}:{},...y.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:$(y,"namedBindingsTypeOnly",u)}:{},...y.portProofEligible!==void 0?{portProofEligible:$(y,"portProofEligible",u)}:{}}}),c=H(e,"capabilityUses","$").map((h,R)=>{let u=`$.capabilityUses[${R}]`,y=F(h,u);return L(y,["file","line","symbol","capability","source"],u),{file:M(y,"file",u),line:ne(y,"line",u),symbol:w(y,"symbol",u),capability:z(y,"capability",ot,u),source:z(y,"source",["ambient-global","import-based"],u)}}),d=H(e,"ambientUses","$").map((h,R)=>{let u=`$.ambientUses[${R}]`,y=F(h,u);return L(y,["file","line","symbol"],u),{file:M(y,"file",u),line:ne(y,"line",u),symbol:w(y,"symbol",u)}}),b=H(e,"publishCalls","$").map((h,R)=>{let u=`$.publishCalls[${R}]`,y=F(h,u);L(y,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],u);let v=te(y,"rawIntentName",u),E=te(y,"sourceIntent",u);return{file:M(y,"file",u),line:ne(y,"line",u),...v?{rawIntentName:v}:{},objectHasIntent:$(y,"objectHasIntent",u),arkPublishCandidate:$(y,"arkPublishCandidate",u),hasSource:$(y,"hasSource",u),...E?{sourceIntent:E}:{}}}),A=H(e,"intentReferences","$").map((h,R)=>{let u=`$.intentReferences[${R}]`,y=F(h,u);return L(y,["file","line","intent"],u),{file:M(y,"file",u),line:ne(y,"line",u),intent:w(y,"intent",u)}}),g=H(e,"safetyUses","$").map((h,R)=>{let u=`$.safetyUses[${R}]`,y=F(h,u);L(y,["file","line","kind","symbol"],u);let v=te(y,"symbol",u),E=z(y,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],u);if(E==="in-memory-store"&&!v)throw new Error(`${u}.symbol is required for in-memory-store facts.`);if(E!=="in-memory-store"&&v)throw new Error(`${u}.symbol is only allowed for in-memory-store facts.`);return{file:M(y,"file",u),line:ne(y,"line",u),kind:E,...v?{symbol:v}:{}}});tn(a,h=>h.path,"$.files");let i=new Set(a.map(h=>h.path));for(let h of a){if(h.parseStatus==="parsed"&&h.parseDiagnosticCount!==0)throw new Error(`$.files[${h.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(h.parseStatus==="invalid"&&h.parseDiagnosticCount===0)throw new Error(`$.files[${h.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&a.some(h=>h.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let h of l)if(!i.has(h.from))throw new Error(`$.dependencies references missing source file ${h.from}.`);for(let[h,R]of[["$.capabilityUses",c],["$.ambientUses",d],["$.publishCalls",b],["$.intentReferences",A],["$.safetyUses",g]])for(let u of R)if(!i.has(u.file))throw new Error(`${h} references missing file ${u.file}.`);let o=te(e,"projectPackageName","$"),p=(e.classShapes===void 0?[]:H(e,"classShapes","$")).map((h,R)=>{let u=`$.classShapes[${R}]`,y=F(h,u);L(y,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],u);let v=H(y,"mutatingMethods",u).map((E,K)=>{let W=`${u}.mutatingMethods[${K}]`,q=F(E,W);return L(q,["name","referencesGuardOrPublish"],W),{name:w(q,"name",W),referencesGuardOrPublish:$(q,"referencesGuardOrPublish",W)}});return{file:M(y,"file",u),className:w(y,"className",u),exported:$(y,"exported",u),hasPublicMutableFields:$(y,"hasPublicMutableFields",u),hasPublicSetters:$(y,"hasPublicSetters",u),hasPublicConstructor:$(y,"hasPublicConstructor",u),hasStaticFactory:$(y,"hasStaticFactory",u),mutatingMethods:v,...y.dataOnly===void 0?{}:{dataOnly:$(y,"dataOnly",u)}}});return{schemaVersion:n,completeness:r,completenessReasons:s,resolverIdentity:w(e,"resolverIdentity","$"),compilerIdentity:w(e,"compilerIdentity","$"),compilerOptionsHash:w(e,"compilerOptionsHash","$"),tsconfigHash:w(e,"tsconfigHash","$"),evidenceRequirementsHash:w(e,"evidenceRequirementsHash","$"),...o?{projectPackageName:o}:{},files:a,dependencies:l,capabilityUses:c,ambientUses:d,publishCalls:b,intentReferences:A,safetyUses:g,classShapes:p}}function Y(e){let t=F(e,"$"),n=w(t,"factsHash","$"),r=w(t,"candidateTreeHash","$"),s=ct(pt(t,!0));if(s.factsHash!==n)throw new Error(`$.factsHash does not match the canonical payload (${s.factsHash}).`);if(r!==s.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${s.candidateTreeHash}).`);return s}var nn=["network","filesystem","clock","randomness","environment","process","persistence"],C={type:"string",minLength:1},re={type:"integer",minimum:1},j={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},ft={$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:{enum:["1.0","1.1"]},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:C,message:C,file:j}}},resolverIdentity:C,compilerIdentity:C,compilerOptionsHash:C,tsconfigHash:C,candidateTreeHash:C,evidenceRequirementsHash:C,projectPackageName:C,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:j,contentHash:C,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:C},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:j,specifier:C,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:re,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:j,namedBindings:{type:"array",items:C},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:j,line:re,symbol:C,capability:{enum:nn},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:j,line:re,symbol:C}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:j,line:re,rawIntentName:C,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:C}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:j,line:re,intent:C}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:j,line:re,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:C},allOf:[{if:{properties:{kind:{const:"in-memory-store"}}},then:{required:["symbol"]},else:{not:{required:["symbol"]}}}]}},classShapes:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods"],properties:{file:j,className:C,exported:{type:"boolean"},hasPublicMutableFields:{type:"boolean"},hasPublicSetters:{type:"boolean"},hasPublicConstructor:{type:"boolean"},hasStaticFactory:{type:"boolean"},dataOnly:{type:"boolean"},mutatingMethods:{type:"array",items:{type:"object",additionalProperties:!1,required:["name","referencesGuardOrPublish"],properties:{name:C,referencesGuardOrPublish:{type:"boolean"}}}}}}},factsHash:C},allOf:[{if:{properties:{completeness:{const:"complete"}}},then:{properties:{completenessReasons:{maxItems:0},files:{items:{properties:{parseStatus:{const:"parsed"}}}}}}},{if:{properties:{completeness:{enum:["partial","unavailable"]}}},then:{properties:{completenessReasons:{minItems:1}}}}]};var ut="1.0";var Ne=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),Ce=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),He=Object.freeze(Object.keys(Ce).sort()),Le=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"}),Me=Object.freeze({process:Object.freeze(["process","node:process"])});function pe(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=Le[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),s=Le[r];if(s)return s;let a=e.indexOf("/",n+1);return a<0?null:Le[e.slice(0,a)]??null}function fe(e,t){for(let n of t)if(Me[n]?.includes(e))return n;return null}function ue(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),s=Ce[r];if(s)return s}return null}function se(e){if(e?.pure===!0)return[...Ne].sort();let n=(e?.capabilities?.deny??[]).filter(r=>Ne.includes(r));return[...new Set(n)].sort()}function De(e,t){if(t.length===0)return!1;let n=new Set(t),r=e.split(".");for(let s=r.length;s>=1;s-=1)if(n.has(r.slice(0,s).join(".")))return!0;return!1}function ke(e){let t=new Set,n=new Set,r=Object.keys(Ce);for(let s of e?.forbiddenGlobals??[]){let a=r.filter(l=>l===s||l.startsWith(`${s}.`));if(a.length===0)n.add(s);else for(let l of a)t.add(`ambient:${l}`);for(let l of Me[s]??[])t.add(`import-exact:${l}`)}for(let s of se(e)){if(t.add(`import:${s}`),s==="process")for(let a of Me.process)t.add(`import-exact:${a}`);for(let a of r)ue(a)===s&&t.add(`ambient:${a}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}function rn(e){let t=new Set,n=ue(e);n&&t.add(n);for(let[r,s]of Object.entries(Ce))(r===e||r.startsWith(`${e}.`))&&t.add(s);return[...t].sort()}var mt=new Map;function yt(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function je(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let s=e[n+1];if("*?{}[],".includes(s)||s==="\\"){t+="\\"+s,n+=1;continue}t+="/";continue}t+=r}return t}function sn(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="{")t+=1;else if(r==="}"&&(t-=1,t<0))return!1}return t===0}function J(e){let t=mt.get(e);if(t)return t;let n=je(e),r=sn(n),s="",a=0;for(let c=0;c<n.length;c+=1){let d=n[c];d==="\\"&&c+1<n.length?(s+=yt(n[c+1]),c+=1):d==="*"?n[c+1]==="*"?n[c+2]==="/"?(s+="(?:.*/)?",c+=2):(s+=".*",c+=1):s+="[^/]*":d==="?"?s+="[^/]":d==="{"&&r?(s+="(?:",a+=1):d==="}"&&r&&a>0?(s+=")",a-=1):d===","&&r&&a>0?s+="|":s+=yt(d)}let l=new RegExp(`^${s}$`);return mt.set(e,l),l}function Ve(e){let t=je(String(e)),r=t.split("*")[0].split("/").filter(Boolean).length,s=t.replace(/\*/g,"").length;return r*1e4+s}function V(e,t){let n=String(e).split(/[/\\]/).join("/"),r,s=-1;for(let a of t??[])if(!(a.exclude??[]).some(l=>J(l).test(n))){for(let l of a.patterns??[])if(J(l).test(n)){let c=Ve(l);c>s&&(s=c,r=a.name)}}return r}function gt(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),r=new Set(t.map(s=>String(s).toLowerCase()));for(let s=0;s<n.length-1;s+=1)if(r.has(n[s].toLowerCase()))return`${n[s].toLowerCase()}/${n[s+1].toLowerCase()}`}function an(e){let t=new Set;for(let n of e??[]){let s=je(String(n)).split("/").filter(Boolean);for(let a=0;a<s.length;a+=1){let l=s[a];if((l==="**"||l==="*")&&a>0){let c=s[a-1];c&&!c.includes("*")&&!c.includes("{")&&!c.includes("}")&&t.add(c)}}}return[...t]}function on(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(s=>typeof s=="string"&&s.length>0);let r=(n??[]).find(s=>s.name===t);return an(r?.patterns)}function ae(e,t,n,r){for(let s of e??[])if(!(s.from!==t||s.to!==n)&&s.allowed===!1){if(s.peerIsolation){let a=r?.fromPath,l=r?.toPath;if(!a||!l)return s;let c=on(s,t,r?.layers);if(c.length===0)return s;let d=gt(a,c),b=gt(l,c);if(!d||!b||d!==b)return s;continue}if(t!==n)return s}}var Ue={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."},Ge=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 qe(e,t){return t.flatMap((r,s)=>(r.prefixes??r.intentPrefixes??[]).map(a=>({layer:r.name,layerIndex:s,prefix:a.endsWith(".")?a:`${a}.`}))).filter(({prefix:r})=>e.startsWith(r)).sort((r,s)=>s.prefix.length-r.prefix.length||r.layerIndex-s.layerIndex)[0]?.layer}function ht(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function ze(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&ht(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:Ue.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:Ue.PUBLISH_MISSING_SOURCE}),t}var bt="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",ln=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","no-anemic-model","invariant-coverage"];var At={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Ir={$schema:"https://json-schema.org/draft/2020-12/schema",$id:bt,title:"ArkGate ArkRules (intra-layer contract)",description:"Per-layer structure sensors and invariant catalog consumed by the ArkGate Effective Contract.",type:"object",additionalProperties:!1,required:["schemaVersion","layer"],properties:{$schema:{type:"string",minLength:1,default:bt},schemaVersion:{type:"string",const:"1.0",default:"1.0"},layer:{type:"string",minLength:1},structure:{type:"array",default:[],items:{$ref:"#/$defs/structureEntry"}},invariants:{type:"array",default:[],items:{$ref:"#/$defs/invariantEntry"}}},$defs:{structureEntry:{type:"object",additionalProperties:!1,required:["id","sensor"],properties:{id:{type:"string",minLength:1},sensor:{type:"string",enum:[...ln]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:At,description:{type:"string",minLength:1}}},invariantEntry:{type:"object",additionalProperties:!1,required:["id","description"],properties:{id:{type:"string",minLength:1},description:{type:"string",minLength:1},aggregate:{type:"string",minLength:1},coverage:{type:"object",additionalProperties:!1,properties:{test:{type:"boolean"},symbol:{type:"string",minLength:1}}},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:At}}}};function me(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}var cn=["no-anemic-model"];function Rt(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function dn(e){let t="";for(let r=0;r<e.length;r+=1){let s=e[r];if(s==="\\"&&r+1<e.length){let a=e[r+1];if("*?{}[],".includes(a)||a==="\\"){t+="\\"+a,r+=1;continue}t+="/";continue}t+=s}let n="";for(let r=0;r<t.length;r+=1){let s=t[r];s==="\\"&&r+1<t.length?(n+=Rt(t[r+1]),r+=1):s==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":s==="?"?n+="[^/]":n+=Rt(s)}return new RegExp(`^${n}$`)}function ye(e,t){return!t||t.length===0?!0:t.some(n=>dn(n).test(e))}function pn(e){return cn.includes(e)}function vt(e){return e.mode==="enforced"&&!pn(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}function ie(e,t,n,r=1){let{severity:s,failsStrict:a}=vt(e);return{ruleId:"ARKRULE_STRUCTURE",code:e.sensor,message:n,file:t,line:r,fromLayer:e.provenance.layer,arkruleId:e.id,arkruleSource:e.provenance.sourceFile,severity:s,sensor:e.sensor,failsStrict:a}}function Ee(e,t,n){return t.filter(r=>{if(!r.exported||!ye(r.file,e.appliesTo))return!1;if(n){let s=n(r.file);if(s&&s!==e.provenance.layer)return!1}return!0})}function fn(e,t,n){let r=[];for(let s of Ee(e,t,n))(s.hasPublicMutableFields||s.hasPublicSetters)&&r.push(ie(e,s.file,`Exported class ${s.className} exposes public mutable state (sensor aggregate-private-state).`));return r}function un(e,t,n){let r=[];for(let s of Ee(e,t,n))s.hasPublicConstructor&&!s.hasStaticFactory&&r.push(ie(e,s.file,`Exported class ${s.className} exposes a public constructor without a static factory (sensor always-valid-factory).`));return r}function mn(e,t,n){let r=[];for(let s of Ee(e,t,n))for(let a of s.mutatingMethods)a.referencesGuardOrPublish||r.push(ie(e,s.file,`Mutating method ${s.className}.${a.name} does not reference a guard or publish symbol (sensor domain-event-on-mutation).`));return r}function yn(e,t){let n=[];for(let r of t.files)if(ye(r,e.appliesTo)){if(t.layerForFile){let s=t.layerForFile(r);if(s&&s!==e.provenance.layer)continue}t.fileHints?.[r]?.orchestrationHeavy&&n.push(ie(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."))}return n}function gn(e,t){let n=[];for(let r of t.files)if(ye(r,e.appliesTo)){if(t.layerForFile){let s=t.layerForFile(r);if(s&&s!==e.provenance.layer)continue}t.fileHints?.[r]?.adapterThick&&n.push(ie(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."))}return n}function hn(e,t,n){let r=[];for(let s of Ee(e,t,n))if(s.dataOnly===!0){let a=ie(e,s.file,`Exported type ${s.className} looks data-only / anemic (sensor no-anemic-model; advisory only).`);r.push({...a,severity:"warning",failsStrict:!1})}return r}function It(e){if(!e.arkRules.structure.length)return[];let t=[];for(let n of e.arkRules.structure)switch(n.sensor){case"aggregate-private-state":t.push(...fn(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...un(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...mn(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...yn(n,e));break;case"thin-adapter":t.push(...gn(n,e));break;case"no-anemic-model":t.push(...hn(n,e.classShapes,e.layerForFile));break;case"invariant-coverage":break;default:break}return t.sort((n,r)=>n.file.localeCompare(r.file)||n.arkruleId.localeCompare(r.arkruleId)||n.message.localeCompare(r.message))}function Ct(e,t){let n=[],r=t.map(s=>s.replace(/\\/g,"/"));for(let s of e.structure){if(!s.appliesTo||s.appliesTo.length===0||r.some(d=>ye(d,s.appliesTo)))continue;let{severity:l,failsStrict:c}=vt(s);n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule structure "${s.id}" appliesTo matched zero governed files (patterns: ${s.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:s.provenance.sourceFile,line:1,fromLayer:s.provenance.layer,arkruleId:s.id,arkruleSource:s.provenance.sourceFile,severity:l,sensor:s.sensor,failsStrict:c})}for(let s of e.invariants??[]){if(!s.appliesTo||s.appliesTo.length===0||r.some(c=>ye(c,s.appliesTo)))continue;let l=s.mode==="enforced";n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule invariant "${s.id}" appliesTo matched zero governed files (patterns: ${s.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:s.provenance.sourceFile,line:1,fromLayer:s.provenance.layer,arkruleId:s.id,arkruleSource:s.provenance.sourceFile,severity:l?"error":"warning",sensor:"invariant-coverage",failsStrict:l})}return n.sort((s,a)=>s.file.localeCompare(a.file)||s.arkruleId.localeCompare(a.arkruleId)||s.message.localeCompare(a.message))}var bn=/\bfrom\s+['"](?:@?prisma\/client|@supabase\/|drizzle-orm|typeorm|knex|mongodb|pg|mysql2|better-sqlite3|ioredis|redis)['"]|require\(\s*['"](?:@?prisma\/client|pg|knex|typeorm)/,An=/\b(?:@Controller|@Get|@Post|@Put|@Delete|Router\(\)|createRouter|express\.Router|fastify\.(?:get|post)|export\s+(?:async\s+)?function\s+(?:GET|POST|PUT|DELETE|PATCH)\b|export\s+const\s+(?:GET|POST|PUT|DELETE|PATCH)\s*=)/,Rn=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,vn=/\b(?:export\s+)?(?:async\s+)?function\s+(?:can|calculate|compute|should|ensure|validate|is|has)[A-Z]\w*|\b(?:export\s+)?const\s+(?:can|calculate|compute|should|ensure|validate|is|has)[A-Z]\w*\s*=/,In=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function Cn(e,t){if(!t||t.length<40)return null;let n=t.match(new RegExp(vn.source,"g"))??[],r=t.match(new RegExp(In.source,"g"))??[],s=(t.match(/\bif\s*\(/g)??[]).length,a=(t.match(/\bswitch\s*\(/g)??[]).length,l=n.length>=2||n.length>=1&&r.length>=2||r.length>=3&&s+a>=6,c=bn.test(t),d=An.test(t)||Rn.test(t),b=n.length>=1||r.length>=2,A=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),g=c&&b||d&&b||c&&A&&(s>=4||n.length>=1)||d&&c;return!l&&!g?null:{...l?{orchestrationHeavy:!0}:{},...g?{adapterThick:!0}:{}}}function kt(e){let t={};for(let[n,r]of Object.entries(e)){let s=Cn(n,r);s&&(t[n.replace(/\\/g,"/")]=s)}return t}function kn(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*['"\`][^'"\`]*${n}[^'"\`]*['"\`]`,"i").test(e)||e.includes(t)}function En(e,t){if(!t)return!1;let n=t.split("."),r=n[n.length-1],s=n.length>1?n[0]:null;for(let a of Object.values(e))if(!(s&&!a.includes(s))&&(new RegExp(`(?:function\\s+|\\b)${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[(<]`).test(a)||a.includes(t)))return!0;return!1}function Et(e){let t=e.arkRules.invariants??[];if(t.length===0)return{coverage:[],violations:[],partial:!1};let n=e.testFiles??[],r=e.testGlobsMissing===!0||n.length===0,s=[],a=[];for(let l of t){let c=[],d=l.coverage?.test!==!1,b=l.coverage?.symbol;if(!r&&d)for(let o of n){let f=e.fileContents[o];if(f&&kn(f,l.id)){c.push("test-title");break}}b&&En(e.fileContents,b)&&c.push("symbol");let g=(l.coverage?.test===!0||!!b||l.coverage===void 0)&&c.length>0||l.coverage?.test===!1&&!b?!0:c.length>0,i=r&&d&&c.length===0;if(s.push({invariantId:l.id,layer:l.provenance.layer,sourceFile:l.provenance.sourceFile,mode:l.mode,covered:g&&!i,evidence:c,partial:i,description:l.description}),!g||i){let o=l.mode==="enforced"&&!i;a.push({ruleId:"INVARIANT_UNCOVERED",message:i?`Invariant ${l.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered.`:`Invariant ${l.id} is not covered by a test title or declared symbol.`,file:l.provenance.sourceFile,line:1,arkruleId:l.id,arkruleSource:l.provenance.sourceFile,fromLayer:l.provenance.layer,severity:o?"error":"warning",failsStrict:o})}}return{coverage:s,violations:a,partial:s.some(l=>l.partial)}}function St(e){return e?e.partial?{ok:!1,reason:"Coverage is partial (missing test globs); cannot promote until evidence is complete."}:e.covered?{ok:!0,reason:`Invariant ${e.invariantId} has coverage evidence.`}:{ok:!1,reason:`Invariant ${e.invariantId} is uncovered; add a test title or symbol before promoting to enforced.`}:{ok:!1,reason:"No coverage evidence supplied for this invariant; evaluate coverage before promoting to enforced."}}function x(e,t,n={}){return{ruleId:e,message:t,...n}}function Be(e){let{config:t,rules:n,files:r,manifest:s}=e,a=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(o=>typeof o!="string"))&&a.push(x("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","dynamicImportAllowlist must be an array of file globs.")),t.safety!==void 0&&(t.safety===null||typeof t.safety!="object"||Array.isArray(t.safety)))a.push(x("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let o of["maxTsSuppressions","maxAnyCasts"]){let f=t.safety[o];f!==void 0&&(!Number.isInteger(f)||f<0)&&a.push(x("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${o} must be a non-negative integer.`))}let l=Array.isArray(t.layers)?t.layers:[],c=Array.isArray(s?.architecture?.layers)?s.architecture.layers:[],d=new Set([...l.map(o=>o.name).filter(Boolean),...c.map(o=>o.name).filter(o=>!!o)]);l.length===0&&a.push(x("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let b=new Set,A=new Set;for(let o of l){if(!o.name){a.push(x("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}b.has(o.name)&&A.add(o.name),b.add(o.name),o.forbiddenGlobals!==void 0&&(!Array.isArray(o.forbiddenGlobals)||o.forbiddenGlobals.some(p=>typeof p!="string"))&&a.push(x("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 f=Array.isArray(o.patterns)?o.patterns:[];if(f.length===0){a.push(x("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${o.name}" has no file patterns and will never classify files.`,{layer:o.name}));continue}for(let p of f){let h;try{h=J(p)}catch(R){a.push(x("CONFIG_INVALID_LAYER_PATTERN",`Layer "${o.name}" has an invalid pattern "${p}": ${R instanceof Error?R.message:String(R)}`,{layer:o.name,pattern:p}));continue}!r.some(R=>h.test(R))&&!o.optional&&a.push(x("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${o.name}" pattern "${p}" matched no included files.`,{layer:o.name,pattern:p,failsStrict:!1}))}}for(let o of A)a.push(x("CONFIG_DUPLICATE_LAYER",`Layer "${o}" is configured more than once.`,{layer:o}));if(d.size>0)for(let o of n??[])o.from&&!d.has(o.from)&&a.push(x("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${o.from}".`,{fromLayer:o.from,toLayer:o.to})),o.to&&!d.has(o.to)&&a.push(x("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${o.to}".`,{fromLayer:o.from,toLayer:o.to}));let g=new Set;if(l.length>1)for(let o of r){let f=-1,p=[];for(let h of l)for(let R of h.patterns??[]){if(!J(R).test(o))continue;let u=Ve(R);u>f?(f=u,p=[h.name]):u===f&&!p.includes(h.name)&&p.push(h.name)}p.length>1&&g.add([...p].sort().join(" + "))}g.size>0&&a.push(x("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...g].join(", ")}.`,{pairs:[...g]}));let i=r.filter(o=>!V(o,l));return i.length>0&&a.push(x("CONFIG_UNCLASSIFIED_FILES",`${i.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:i.length,samples:i.slice(0,5)})),a}function $t(e){let t=0,n=new Map,r=new Map,s=new Set,a=[],l=[],c=d=>{n.set(d,t),r.set(d,t),t+=1,a.push(d),s.add(d);for(let g of[...e.get(d)??[]].sort())e.has(g)&&(n.has(g)?s.has(g)&&r.set(d,Math.min(r.get(d)??0,n.get(g)??0)):(c(g),r.set(d,Math.min(r.get(d)??0,r.get(g)??0))));if(r.get(d)!==n.get(d))return;let b=[],A;do{if(A=a.pop(),A===void 0)break;s.delete(A),b.push(A)}while(A!==d);b.length>1&&l.push(b.sort())};for(let d of[...e.keys()].sort())n.has(d)||c(d);return l.sort((d,b)=>d[0]<b[0]?-1:d[0]>b[0]?1:0).map(d=>({ruleId:"CIRCULAR_DEPENDENCY",file:d[0],line:1,target:d.join(" \u2192 "),message:`Circular dependency among ${d.length} files: ${d.join(" \u2192 ")} \u2192 ${d[0]}.`,cycleKind:"value"}))}function ge(e){let t=e.contentViolations.map(a=>({...a})),n=(e.warnings??[]).map(a=>({...a})),r=new Map(e.files.map(a=>[a,new Set]));for(let a of e.edges){if(a.to&&a.to!==a.from&&!a.typeOnly&&r.has(a.from)&&r.get(a.from)?.add(a.to),!a.to||!a.fromLayer||!a.toLayer)continue;let l=ae(e.rules,a.fromLayer,a.toLayer,{fromPath:a.from,toPath:a.to,layers:e.config.layers});if(!l)continue;let c=!!l.peerIsolation;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:a.from,line:a.line,fromLayer:a.fromLayer,toLayer:a.toLayer,target:a.to,...a.typeOnly?{typeOnly:!0}:{},...a.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...a.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...a.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!c&&a.portProofEligible?{portProofEligible:!0}:{},...a.kind?{edgeKind:a.kind}:{},...c?{peerIsolation:!0}:{},message:l.message??(c?`${a.fromLayer} must not ${a.kind} another slice of ${a.toLayer} (${a.from} \u2192 ${a.to}). Extract shared code or use events/ports across slices.`:`${a.fromLayer} must not ${a.kind} ${a.toLayer}.`)})}let s=String(e.config.cyclePolicy??"strict").toLowerCase();if(s!=="off"){let a=$t(r);s==="soft"||s==="framework-soft"?n.push(...a.map(l=>({...l,message:`${l.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 Sn(e,t){return t.some(n=>{try{return J(n).test(e)}catch{return!1}})}function $n(e,t){let n=e.contract.config.safety??{},r=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,s=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,a=e.contract.config.dynamicImportAllowlist??[],l=t.safetyUses.filter(p=>p.kind==="ts-suppression").map(({file:p,line:h})=>({file:p,line:h})),c=t.safetyUses.filter(p=>p.kind==="any-cast").map(({file:p,line:h})=>({file:p,line:h})),d=t.safetyUses.filter(p=>(p.kind==="dynamic-import"||p.kind==="dynamic-require")&&!Sn(p.file,a)).map(p=>({file:p.file,line:p.line,kind:p.kind==="dynamic-require"?"require":"import"})),b=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"})),A=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})),g={tsSuppressions:l,anyCasts:c,nonLiteralDynamicImports:d,inMemoryProductionStores:b,disabledPeerIsolationRules:A,thresholds:{maxTsSuppressions:r,maxAnyCasts:s}},i=[],o=d.filter(p=>p.kind==="import");if(o.length>0){let p=o[0];i.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:p.file,line:p.line,message:`${o.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let f=d.filter(p=>p.kind==="require");if(f.length>0){let p=f[0];i.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:p.file,line:p.line,message:`${f.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(l.length>r){let p=l[0];i.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:p.file,line:p.line,message:`${l.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${r}).`})}if(c.length>s){let p=c[0];i.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:p.file,line:p.line,message:`${c.length} explicit any cast(s) exceed safety.maxAnyCasts (${s}).`})}if(b.length>0){let p=b[0];i.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:p.file,line:p.line,message:`${b.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 A.length>0&&i.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${A.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:g,warnings:i}}function wn(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}function wt(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return qe(e,n.length>0?n:Ge.map(r=>({name:r.layer,prefixes:r.prefixes})))}function xn(e,t,n){let r=[],s=new Map(e.contract.config.layers.map(a=>[a.name,a]));for(let a of t.ambientUses){let l=n.get(a.file);!l||!wn(a.symbol,s.get(l)?.forbiddenGlobals??[])||r.push({ruleId:"FORBIDDEN_GLOBAL",file:a.file,line:a.line,fromLayer:l,target:a.symbol,message:`${l} must not use the ambient global "${a.symbol}".`})}for(let a of t.capabilityUses){let l=n.get(a.file);if(!l)continue;let c=s.get(l),d=c?.forbiddenGlobals??[],b=a.source==="import-based"?t.dependencies.find(A=>A.from===a.file&&A.line===a.line&&A.specifier===a.symbol&&!A.typeOnly)?.kind:void 0;if(!(a.source==="ambient-global"&&De(a.symbol,d))){if(a.source==="import-based"){let A=fe(a.symbol,d);if(A){r.push({ruleId:"FORBIDDEN_GLOBAL",file:a.file,line:a.line,fromLayer:l,target:a.symbol,...b?{edgeKind:b}:{},message:`${l} must not use module "${a.symbol}" because it is the import form of forbidden global "${A}".`});continue}}se(c).includes(a.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:a.file,line:a.line,fromLayer:l,target:a.symbol,capability:a.capability,...b?{edgeKind:b}:{},message:a.source==="import-based"?`${l} denies the ${a.capability} capability; found import of "${a.symbol}".`:`${l} denies the ${a.capability} capability; found ambient "${a.symbol}".`})}}for(let a of t.publishCalls){let l=n.get(a.file);if(!l)continue;for(let d of ze({publishCall:!0,rawIntentName:a.rawIntentName,objectHasIntent:a.objectHasIntent,arkPublishCandidate:a.arkPublishCandidate,hasSource:a.hasSource}))r.push({ruleId:d.ruleId,file:a.file,line:a.line,...d.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:l}:{},message:d.message});if(!a.sourceIntent)continue;let c=wt(a.sourceIntent,e.contract);!c||c===l||r.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:a.file,line:a.line,fromLayer:l,toLayer:c,target:a.sourceIntent,message:`Publish source "${a.sourceIntent}" resolves to ${c}, but the publishing file is classified as ${l}.`})}for(let a of t.intentReferences){let l=n.get(a.file);if(!l)continue;let c=wt(a.intent,e.contract);if(!c)continue;let d=ae(e.contract.config.rules,l,c);d&&r.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:a.file,line:a.line,fromLayer:l,toLayer:c,target:a.intent,message:d.message??`${l} must not reference ${c} intent ${a.intent}.`})}return r}function Ke(e){let{facts:t}=e,n=ve(e.contract.config),r=t.evidenceRequirementsHash===n,s=r?t.completeness:"unavailable",a=r?t.completenessReasons:[...t.completenessReasons,{code:"EVIDENCE_REQUIREMENTS_MISMATCH",message:"Resolved facts were collected for different policy-controlled evidence requirements."}].sort((m,N)=>{let ce=`${m.code}\0${m.file??""}\0${m.message}`,de=`${N.code}\0${N.file??""}\0${N.message}`;return ce<de?-1:ce>de?1:0}),l=t.files.map(m=>({...m,layer:V(m.path,e.contract.config.layers)??null})),c=new Map(l.map(m=>[m.path,m.layer])),d=t.dependencies.map(m=>{let N=m.target?c.get(m.target)??V(m.target,e.contract.config.layers):void 0;return{from:m.from,fromLayer:c.get(m.from)??null,...m.resolution==="resolved-project"&&m.target?{to:m.target,...N?{toLayer:N}:{}}:{},line:m.line,kind:m.kind,typeOnly:m.typeOnly,...m.targetTypeOnlyExports?{targetTypeOnlyExports:m.targetTypeOnlyExports}:{},...m.sourcePureTypeModule?{sourcePureTypeModule:m.sourcePureTypeModule}:{},...m.namedBindingsTypeOnly?{namedBindingsTypeOnly:m.namedBindingsTypeOnly}:{},...m.portProofEligible?{portProofEligible:m.portProofEligible}:{}}}),b=Be({config:e.contract.config,rules:e.contract.config.rules,files:l.map(m=>m.path)}),A=$n(e,t),g=e.contract.arkRules??me(),i=l.map(m=>m.path),f={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?kt(e.coverageInputs.fileContents):{},...e.fileHints??{}},p=[...It({arkRules:g,classShapes:e.contract.classShapes??t.classShapes??[],files:i,layerForFile:m=>c.get(m)??V(m,e.contract.config.layers),fileHints:f}),...Ct(g,i)],h=p.filter(m=>m.failsStrict).map(m=>({ruleId:m.ruleId,file:m.file,line:m.line,message:m.message,fromLayer:m.fromLayer,arkruleId:m.arkruleId,arkruleSource:m.arkruleSource,nextAction:m.ruleId==="ARKRULE_SCOPE_EMPTY"?`Fix appliesTo globs for ${m.arkruleId} in ${m.arkruleSource} so they match governed files, or remove the rule.`:`Fix the structure or invariant for ${m.arkruleId} (declared in ${m.arkruleSource}), then preflight again.`})),R=p.filter(m=>!m.failsStrict).map(m=>({ruleId:m.ruleId,file:m.file,line:m.line,message:m.message,fromLayer:m.fromLayer,arkruleId:m.arkruleId,arkruleSource:m.arkruleSource,failsStrict:!1,nextAction:m.ruleId==="ARKRULE_SCOPE_EMPTY"?`Review appliesTo for ${m.arkruleId} in ${m.arkruleSource} (zero-match scope; advisory).`:`Review ArkRule ${m.arkruleId} in ${m.arkruleSource} (advisory).`})),y=(g.invariants?.length??0)>0?Et({arkRules:g,fileContents:e.coverageInputs?.fileContents??{},testFiles:e.coverageInputs?.testFiles??[],testGlobsMissing:e.coverageInputs?.testGlobsMissing===!0||e.coverageInputs===void 0||(e.coverageInputs.testFiles?.length??0)===0}):{coverage:[],violations:[],partial:!1},v=y.violations.filter(m=>m.failsStrict).map(m=>({ruleId:m.ruleId,file:m.file,line:m.line,message:m.message,fromLayer:m.fromLayer,arkruleId:m.arkruleId,arkruleSource:m.arkruleSource,nextAction:`Add a test title or declared symbol covering ${m.arkruleId} (declared in ${m.arkruleSource}), then preflight again.`})),E=y.violations.filter(m=>!m.failsStrict).map(m=>({ruleId:m.ruleId,file:m.file,line:m.line,message:m.message,fromLayer:m.fromLayer,arkruleId:m.arkruleId,arkruleSource:m.arkruleSource,failsStrict:!1,nextAction:`Cover invariant ${m.arkruleId} in ${m.arkruleSource} (advisory / partial).`})),W=y.partial&&y.coverage.some(m=>m.mode==="enforced"&&m.partial)?[{code:"INVARIANT_COVERAGE_PARTIAL",message:"Enforced ArkRules invariant coverage cannot be fully proven (missing test globs or empty test set); reporting partial, never covered."}]:[],q=ge({config:e.contract.config,rules:e.contract.config.rules,files:l.filter(m=>m.layer).map(m=>m.path),contentViolations:[...xn(e,t,c),...h,...v],edges:d,warnings:[...b,...A.warnings,...R,...E],safety:A.report}),_e=s==="complete"&&W.length>0?"partial":s,Xt=_e==="complete"?a:[...a,...W].sort((m,N)=>{let ce=`${m.code}\0${m.file??""}\0${m.message}`,de=`${N.code}\0${N.file??""}\0${N.message}`;return ce<de?-1:ce>de?1:0}),it=_e==="complete"&&q.violations.length===0,Qt=it&&q.warnings.every(m=>m.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:_e,completenessReasons:Xt,valid:it,strictValid:Qt,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:A.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:l,layers:e.contract.config.layers.map(m=>m.name),edges:d,capabilityUses:t.capabilityUses,violations:q.violations,warnings:q.warnings}}}function Se(e){return Ke({contract:e.contract,facts:Y(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints})}var We="1.0";var $e=class extends Error{issues;source;constructor(t,n){super(`Invalid architecture change map (${t}):
|
|
4
|
+
${n.map(r=>`- ${r.path}: ${r.message}`).join(`
|
|
5
|
+
`)}`),this.name="ArchitectureChangeMapValidationError",this.source=t,this.issues=n}};function Ye(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Je(e,t,n,r){for(let s of Object.keys(e))t.includes(s)||r.push({path:`${n}.${s}`,message:"unknown field"})}function Z(e,t,n,r){let s=e[t];if(typeof s=="string"&&s.length>0)return s;r.push({path:`${n}.${t}`,message:"must be a non-empty string"})}function On(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let s of t.split("/"))if(!(!s||s==="."))if(s===".."){if(n.length===0)return;n.pop()}else n.push(s);let r=n.join("/");return r&&r===t?r:void 0}function Pn(e,t,n="architecture change map"){let r=[];if(!Ye(e))throw new $e(n,[{path:"$",message:"must be an object"}]);Je(e,["$schema","schemaVersion","files","dependencies"],"$",r);let s=Z(e,"$schema","$",r),a=Z(e,"schemaVersion","$",r);a&&a!==We&&r.push({path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(a)}; expected ${We}`});let l=new Set(t.layers.map(f=>f.name)),c=[],d=new Set;!Array.isArray(e.files)||e.files.length===0?r.push({path:"$.files",message:"must be a non-empty array"}):e.files.forEach((f,p)=>{let h=`$.files[${p}]`;if(!Ye(f)){r.push({path:h,message:"must be an object"});return}Je(f,["path","operation","layer"],h,r);let R=Z(f,"path",h,r),u=Z(f,"operation",h,r),y=Z(f,"layer",h,r),v=R?On(R):void 0;R&&!v&&r.push({path:`${h}.path`,message:"must be a canonical project-relative path"}),u&&!["create","update","delete"].includes(u)&&r.push({path:`${h}.operation`,message:"must be create, update, or delete"}),y&&!l.has(y)&&r.push({path:`${h}.layer`,message:`references unknown layer ${JSON.stringify(y)}`}),v&&d.has(v)&&r.push({path:`${h}.path`,message:`duplicates planned path ${v}`}),v&&d.add(v);let E=v?V(v,t.layers):void 0;v&&y&&l.has(y)&&E!==y&&r.push({path:`${h}.layer`,message:E?`${v} resolves to ${E}, not ${y}`:`${v} is not assigned to an architecture layer`}),v&&u&&["create","update","delete"].includes(u)&&y&&c.push({path:v,operation:u,layer:y})});let b=[],A=new Map(c.map(f=>[f.path,f.operation])),g=new Set,i=e.dependencies??[];if(Array.isArray(i)?i.forEach((f,p)=>{let h=`$.dependencies[${p}]`;if(!Ye(f)){r.push({path:h,message:"must be an object"});return}Je(f,["from","to"],h,r);let R=Z(f,"from",h,r),u=Z(f,"to",h,r);R&&!d.has(R)&&r.push({path:`${h}.from`,message:`must reference a planned file path: ${R}`}),u&&!d.has(u)&&r.push({path:`${h}.to`,message:`must reference a planned file path: ${u}`}),R&&A.get(R)==="delete"&&r.push({path:`${h}.from`,message:`cannot depend from deleted file ${R}`}),u&&A.get(u)==="delete"&&r.push({path:`${h}.to`,message:`cannot depend on deleted file ${u}`}),R&&u&&R===u&&r.push({path:h,message:"must not declare a self dependency"});let y=R&&u?`${R}\0${u}`:void 0;y&&g.has(y)&&r.push({path:h,message:`duplicates dependency ${R} -> ${u}`}),y&&g.add(y),R&&u&&b.push({from:R,to:u})}):r.push({path:"$.dependencies",message:"must be an array"}),r.length>0)throw new $e(n,r);let o={$schema:s,schemaVersion:We,files:c.sort((f,p)=>f.path.localeCompare(p.path)),dependencies:b.sort((f,p)=>f.from.localeCompare(p.from)||f.to.localeCompare(p.to))};return{map:o,hash:S(k(o))}}function O(e){return`${e.from}->${e.to}`}function he(e,t,n,r="dependency"){return{id:`${e}:${r}:${O(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${O(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${O(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${O(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${O(t)} from the candidate, then preflight again.`}:{}}}function be(e){let t=[],n=new Map(e.changeMap.map.files.map(i=>[i.path,i])),r=new Map(e.changes.map(i=>[i.path,i])),s=new Map(e.changeMap.map.dependencies.map(i=>[O(i),i])),a=new Map(e.baseDependencies.map(i=>[O(i),i])),l=new Map(e.candidateDependencies.map(i=>[O(i),i]));for(let i of[...n.values()].sort((o,f)=>o.path.localeCompare(f.path))){let o=r.get(i.path);o?o.operation!==i.operation?t.push({id:`contradictory:file:${i.path}`,classification:"contradictory",subject:"file",path:i.path,expectedOperation:i.operation,actualOperation:o.operation,message:`${i.path} was planned as ${i.operation} but the actual operation is ${o.operation}.`,nextAction:`Change ${i.path} to the planned ${i.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${i.path}`,classification:"satisfied",subject:"file",path:i.path,expectedOperation:i.operation,actualOperation:o.operation,message:`${i.path} matches the planned ${i.operation} operation.`}):t.push({id:`missing:file:${i.path}`,classification:"missing",subject:"file",path:i.path,expectedOperation:i.operation,message:`${i.path} was planned as ${i.operation} but is absent from the actual change.`,nextAction:`${i.operation[0].toUpperCase()}${i.operation.slice(1)} ${i.path} in the complete change set, then preflight again.`})}for(let i of[...r.values()].sort((o,f)=>o.path.localeCompare(f.path)))n.has(i.path)||t.push({id:`unplanned:file:${i.path}`,classification:"unplanned",subject:"file",path:i.path,actualOperation:i.operation,message:`${i.path} has an unplanned ${i.operation} operation.`,nextAction:`Remove ${i.path} from the change set, then preflight again.`});let c=new Set;for(let i of[...s.values()].sort((o,f)=>O(o).localeCompare(O(f)))){if(l.has(O(i))){t.push(he("satisfied",i,`${i.from} -> ${i.to} exists in the candidate architecture.`));continue}let o={from:i.to,to:i.from};l.has(O(o))?(c.add(O(o)),t.push(he("contradictory",i,`${i.from} -> ${i.to} was planned, but the candidate contains the reverse edge.`))):t.push(he("missing",i,`${i.from} -> ${i.to} is absent from the candidate architecture.`))}let d=new Set([...n.keys(),...r.keys()]);for(let[i,o]of[...l].sort(([f],[p])=>f.localeCompare(p)))a.has(i)||s.has(i)||c.has(i)||!d.has(o.from)&&!d.has(o.to)||t.push({...he("unplanned",o,`${o.from} -> ${o.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let b=new Set(e.changeMap.map.files.filter(i=>i.operation==="delete").map(i=>i.path));for(let[i,o]of[...a].sort(([f],[p])=>f.localeCompare(p)))l.has(i)||b.has(o.from)||b.has(o.to)||!d.has(o.from)&&!d.has(o.to)||t.push({...he("unplanned",o,`${o.from} -> ${o.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let A={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((i,o)=>A[i.classification]-A[o.classification]||(i.subject===o.subject?0:i.subject==="file"?-1:1)||i.id.localeCompare(o.id));let g={satisfied:t.filter(i=>i.classification==="satisfied").length,missing:t.filter(i=>i.classification==="missing").length,contradictory:t.filter(i=>i.classification==="contradictory").length,unplanned:t.filter(i=>i.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:g.missing===0&&g.contradictory===0&&g.unplanned===0,behavioralCompletion:"not-evaluated",summary:g,findings:t}}function oe(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function Pt(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function xt(e,t){if(e.isImportDeclaration(t)){let r=t.importClause;if(!r)return!1;if(r.isTypeOnly)return!0;let s=r.namedBindings;return!!(s&&e.isNamedImports(s)&&s.elements.length>0&&s.elements.every(a=>a.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(r=>r.isTypeOnly))}function Ft(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=s=>s===t.fileName?t:void 0,r.fileExists=s=>s===t.fileName,r.readFile=s=>s===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}function Ze(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function Xe(e,t,n,r){let s=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,a;try{a=s?t.getShorthandAssignmentValueSymbol(r.parent):Ze(t,r)}catch{a=void 0}return!!a?.declarations?.some(l=>l.getSourceFile().fileName===n.fileName)}function Qe(e,t){let n,r=[],s=(l,c,d,b=!1)=>r.push({specifier:d,kind:c,line:Pt(t,l),typeOnly:b,unresolved:d===void 0,node:l}),a=l=>{if(e.isImportDeclaration(l))s(l,"import",oe(e,l.moduleSpecifier),xt(e,l));else if(e.isExportDeclaration(l)&&l.moduleSpecifier)s(l,"export",oe(e,l.moduleSpecifier),xt(e,l));else if(e.isImportEqualsDeclaration(l)&&e.isExternalModuleReference(l.moduleReference))s(l,"require",oe(e,l.moduleReference.expression),l.isTypeOnly===!0);else if(e.isCallExpression(l)){let c=l.expression.kind===e.SyntaxKind.ImportKeyword,b=e.isIdentifier(l.expression)&&l.expression.text==="require"&&!Xe(e,n??(n=Ft(e,t)),t,l.expression);(c||b)&&s(l,b?"require":"dynamic-import",oe(e,l.arguments[0]))}e.forEachChild(l,a)};return a(t),r}function Fn(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let s=oe(e,r.argumentExpression);if(s===void 0)return;n.unshift(s)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}function Tn(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 Ot(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let r=n.length;r>=1;r-=1){let s=n.slice(0,r).join(".");if(e.has(s))return s}}function et(e,t,n){if(n.length===0)return[];let r=new Set(n),s=Ft(e,t),a=new Map,l=new Set;for(let i of t.statements)if(e.isVariableStatement(i))for(let o of i.declarationList.declarations)e.isIdentifier(o.name)&&l.add(o.name.text);let c=i=>{let o=Fn(e,i);if(!o)return;let f=Ze(s,o.root),p=f?a.get(f):void 0;return p?[...p,...o.segments.slice(1)]:Xe(e,s,t,o.root)||l.has(o.root.text)?void 0:o.segments};for(let i of t.statements)if(e.isVariableStatement(i))for(let o of i.declarationList.declarations){if(!o.initializer||!e.isIdentifier(o.name))continue;let f=c(o.initializer),p=Ze(s,o.name);!f||!p||a.set(p,f)}let d=[],b=new Set,A=(i,o)=>{let f=Pt(t,o),p=`${i}:${o.getStart(t)}`;b.has(p)||(b.add(p),d.push({name:i,line:f,node:o}))},g=i=>{let o=i.parent&&(e.isPropertyAccessExpression(i.parent)||e.isElementAccessExpression(i.parent))&&i.parent.expression===i;if((e.isPropertyAccessExpression(i)||e.isElementAccessExpression(i))&&!o){let f=c(i),p=f?Ot(r,f):void 0;p&&A(p,i)}else e.isIdentifier(i)&&r.has(i.text)&&Tn(e,i)&&!Xe(e,s,t,i)&&A(i.text,i);if(e.isVariableDeclaration(i)&&e.isObjectBindingPattern(i.name)&&i.initializer){let f=c(i.initializer);if(f)for(let p of i.name.elements){if(!e.isIdentifier(p.name))continue;let h=p.propertyName?oe(e,p.propertyName)??p.propertyName.text:p.name.text,R=Ot(r,[...f,h]);R&&A(R,i.initializer)}}e.forEachChild(i,g)};return g(t),d}function _n(e,t,n){let r=[];for(let s of n?.dependencies??Qe(e,t)){if(s.typeOnly||!s.specifier)continue;let a=pe(s.specifier);a&&r.push({capability:a,symbol:s.specifier,line:s.line,source:"import-based"})}for(let s of n?.ambientUses??et(e,t,He)){let a=ue(s.name);a&&r.push({capability:a,symbol:s.name,line:s.line,source:"ambient-global"})}return r.sort((s,a)=>s.line-a.line||s.capability.localeCompare(a.capability)||s.symbol.localeCompare(a.symbol))}var tt="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",Tt=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Ln=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Nn(){let e=[];for(let t of Tt)for(let n of Tt)t===n||Ln.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var Lt=Nn(),nt=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"}],B={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},_t={$schema:"https://json-schema.org/draft/2020-12/schema",$id:tt,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:tt,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:"1.1",default:"1.1"},name:{type:"string",minLength:1},include:{...B,minItems:1,default:["src"]},exclude:{...B,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:Lt,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...B,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...B,minItems:1},exclude:B,intentPrefixes:B,description:{type:"string",minLength:1},forbiddenGlobals:B,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:{...B,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}}}}},G=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
|
|
6
|
+
${n.map(r=>`- ${r.path}: ${r.message}`).join(`
|
|
7
|
+
`)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function Nt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function we(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function le(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Mn(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function Ae(e,t,n,r,s){if(t.$ref){let a=Mn(t.$ref,r);if(!a){s.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}Ae(e,a,n,r,s);return}if(t.const!==void 0&&!Object.is(e,t.const)){s.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(a=>Object.is(a,e))){s.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!Nt(e)){s.push({path:n,message:`must be an object; received ${le(e)}`});return}let a=t.properties??{};for(let l of t.required??[])e[l]===void 0&&s.push({path:we(n,l),message:"is required"});if(t.additionalProperties===!1)for(let l of Object.keys(e))l in a||s.push({path:we(n,l),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let l=t.additionalProperties;for(let c of Object.keys(e))c in a||Ae(e[c],l,we(n,c),r,s)}for(let[l,c]of Object.entries(a))e[l]!==void 0&&Ae(e[l],c,we(n,l),r,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:n,message:`must be an array; received ${le(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&s.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let a=e.map(l=>JSON.stringify(l));new Set(a).size!==a.length&&s.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((a,l)=>Ae(a,t.items,`${n}[${l}]`,r,s));return}if(t.type==="string"){if(typeof e!="string"){s.push({path:n,message:`must be a string; received ${le(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&s.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&s.push({path:n,message:`must be a boolean; received ${le(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){s.push({path:n,message:`must be an integer; received ${le(e)}`});return}t.minimum!==void 0&&e<t.minimum&&s.push({path:n,message:`must be at least ${t.minimum}`})}}function Hn(e){return{...e,$schema:e.$schema===void 0?tt:e.$schema,schemaVersion:e.schemaVersion===void 0?"1.1":e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?Lt.map(t=>({...t})):e.rules}}function Dn(){let e=new Set(["1.1"]);for(let t of nt)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}function jn(e,t="ark.config.json"){if(!Nt(e))throw new G(t,[{path:"$",message:`must be an object; received ${le(e)}`}]);let n=Dn(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new G(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.1`}]);if(r!=="unversioned"&&!n.has(r))throw new G(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected 1.1`}]);let s=r,a={...e},l=0;for(;s!=="1.1"&&l<nt.length+1;){l+=1;let d=nt.find(b=>b.from===s);if(!d)throw new G(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(s)}; expected 1.1`}]);s=d.to,a.schemaVersion=s}if(s!=="1.1")throw new G(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected 1.1`}]);let c=r==="unversioned"?"unversioned":r==="1.0"?"1.0":null;return{candidate:Hn(a),migratedFrom:c}}function rt(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=jn(e,t),s=[];if(Ae(n,_t,"$",_t,s),s.length>0)throw new G(t,s);return{config:n,migratedFrom:r}}function Mt(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new G(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return rt(n,t)}function Ht(e){return{config:e.config,arkRules:{schemaVersion:e.arkRules.schemaVersion,structure:e.arkRules.structure.map(t=>({id:t.id,sensor:t.sensor,mode:t.mode,appliesTo:t.appliesTo??null,description:t.description??null,provenance:t.provenance})),invariants:e.arkRules.invariants.map(t=>({id:t.id,description:t.description,aggregate:t.aggregate??null,coverage:t.coverage??null,mode:t.mode,appliesTo:t.appliesTo??null,provenance:t.provenance}))}}}var Vt="1.0";function I(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 T(e){return[...new Set(e??[])].sort()}function X(e,t,n,r,s){let a=T(n),l=T(r),c=new Set(a),d=new Set(l),b=l.filter(g=>!c.has(g)),A=a.filter(g=>!d.has(g));b.length===0&&A.length===0||(b.length>0&&I(e,{kind:"added",path:t,classification:s.added,message:s.addedMessage,before:a,after:l}),A.length>0&&I(e,{kind:"removed",path:t,classification:s.removed,message:s.removedMessage,before:a,after:l}))}function xe(e,t,n,r,s,a,l){if(n===r)return;I(e,{kind:r?"enabled":"disabled",path:t,classification:r?s:s==="strengthening"?"weakening":"strengthening",message:r?a:l,before:n,after:r})}function Oe(e,t){let n=new Map,r=new Set;for(let s of e){let a=t(s);n.has(a)?r.add(a):n.set(a,s)}return{values:n,duplicates:[...r].sort()}}function Vn(e,t,n){let r=Oe(t,a=>a.name),s=Oe(n,a=>a.name);(r.duplicates.length>0||s.duplicates.length>0)&&I(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:r.duplicates,after:s.duplicates});for(let a of[...new Set([...r.values.keys(),...s.values.keys()])].sort()){let l=r.values.get(a),c=s.values.get(a),d=`$.layers[${a}]`;if(!l&&c){I(e,{kind:"layer-added",path:d,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:c});continue}if(l&&!c){I(e,{kind:"layer-removed",path:d,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:l});continue}if(!l||!c)continue;X(e,`${d}.patterns`,l.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,`${d}.exclude`,l.exclude,c.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let b=ke(l),A=ke(c);X(e,`${d}.forbiddenGlobals`,b.rawGlobals,A.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,`${d}.capabilities`,b.atoms,A.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)."}),T(l.intentPrefixes).join("\0")!==T(c.intentPrefixes).join("\0")&&I(e,{kind:"intent-prefixes-changed",path:`${d}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:T(l.intentPrefixes),after:T(c.intentPrefixes)}),xe(e,`${d}.mayImportInfrastructure`,l.mayImportInfrastructure===!0,c.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),xe(e,`${d}.optional`,l.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 Un(e,t,n){let r=l=>`${l.from}->${l.to}`,s=Oe(t,r),a=Oe(n,r);(s.duplicates.length>0||a.duplicates.length>0)&&I(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:s.duplicates,after:a.duplicates});for(let l of[...new Set([...s.values.keys(),...a.values.keys()])].sort()){let c=s.values.get(l),d=a.values.get(l),b=`$.rules[${l}]`;if(!c&&d){d.allowed===!1&&I(e,{kind:"deny-added",path:b,classification:"strengthening",message:"A denied dependency edge was added.",after:d});continue}if(c&&!d){c.allowed===!1&&I(e,{kind:"deny-removed",path:b,classification:"weakening",message:"A denied dependency edge was removed.",before:c});continue}if(!c||!d)continue;c.allowed!==d.allowed&&I(e,{kind:d.allowed?"deny-disabled":"deny-enabled",path:`${b}.allowed`,classification:d.allowed?"weakening":"strengthening",message:d.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:c.allowed,after:d.allowed});let A=c.peerIsolation===!0,g=d.peerIsolation===!0;if(A!==g){let i=c.from===c.to&&d.from===d.to;I(e,{kind:g?"peer-isolation-enabled":"peer-isolation-disabled",path:`${b}.peerIsolation`,classification:i?g?"strengthening":"weakening":"judgment-required",message:i?g?"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:A,after:g})}T(c.sliceFolders).join("\0")!==T(d.sliceFolders).join("\0")&&I(e,{kind:"slice-folders-changed",path:`${b}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:T(c.sliceFolders),after:T(d.sliceFolders)})}}function Gn(e,t,n){let r=t.safety??{},s=n.safety??{};for(let a of["maxTsSuppressions","maxAnyCasts"]){let l=r[a]??0,c=s[a]??0;l!==c&&I(e,{kind:c>l?"threshold-raised":"threshold-lowered",path:`$.safety.${a}`,classification:c>l?"weakening":"strengthening",message:c>l?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:l,after:c})}for(let a of["allowInMemory","allowDisabledPeerIsolation"])xe(e,`$.safety.${a}`,r[a]===!0,s[a]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}function qn(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 Dt(e,t){return`${e}::${t}`}function jt(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(Dt(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(Dt(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}function zn(e,t,n,r,s,a){let l=new Map((a??[]).map(i=>[i.invariantId,i])),c=t.arkRules??{},d=n.arkRules??{},b=[...new Set([...Object.keys(c),...Object.keys(d)])].sort();for(let i of b){let o=c[i],f=d[i],p=`$.arkRules[${i}]`;if(o===void 0&&f!==void 0){I(e,{kind:"arkrules-ref-added",path:p,classification:"strengthening",message:`ArkRules reference for layer ${i} was added.`,after:f});continue}if(o!==void 0&&f===void 0){I(e,{kind:"arkrules-ref-removed",path:p,classification:"weakening",message:`ArkRules reference for layer ${i} was removed.`,before:o});continue}o!==f&&I(e,{kind:"arkrules-ref-path-changed",path:p,classification:"judgment-required",message:`ArkRules file path for layer ${i} changed; verify the effective rules still match intent.`,before:o,after:f})}let A=jt(r),g=jt(s);for(let i of[...new Set([...A.structure.keys(),...g.structure.keys()])].sort()){let o=A.structure.get(i),f=g.structure.get(i),p=`$.arkRules.structure[${i}]`;if(!o&&f){I(e,{kind:"arkrule-structure-added",path:p,classification:"strengthening",message:`Structure ArkRule ${f.id} was added (${f.mode}).`,after:f});continue}if(o&&!f){I(e,{kind:"arkrule-structure-removed",path:p,classification:"weakening",message:`Structure ArkRule ${o.id} was removed.`,before:o});continue}if(!(!o||!f)){if(o.mode!==f.mode){let h=o.mode==="advisory"&&f.mode==="enforced";I(e,{kind:h?"arkrule-promoted":"arkrule-demoted",path:`${p}.mode`,classification:h?"strengthening":"weakening",message:h?`Structure ArkRule ${f.id} was promoted to enforced.`:`Structure ArkRule ${f.id} was demoted to advisory.`,before:o.mode,after:f.mode})}o.sensor!==f.sensor&&I(e,{kind:"arkrule-sensor-changed",path:`${p}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${f.id} changed sensor identity.`,before:o.sensor,after:f.sensor})}}for(let i of[...new Set([...A.invariants.keys(),...g.invariants.keys()])].sort()){let o=A.invariants.get(i),f=g.invariants.get(i),p=`$.arkRules.invariants[${i}]`;if(!o&&f){I(e,{kind:"arkrule-invariant-added",path:p,classification:"strengthening",message:`Invariant ${f.id} was added (${f.mode}).`,after:f});continue}if(o&&!f){I(e,{kind:"arkrule-invariant-removed",path:p,classification:"weakening",message:`Invariant ${o.id} was removed.`,before:o});continue}if(!(!o||!f)&&o.mode!==f.mode)if(o.mode==="advisory"&&f.mode==="enforced"){let R=l?.get(f.id),u=St(R);u.ok?I(e,{kind:"arkrule-invariant-promoted",path:`${p}.mode`,classification:"strengthening",message:`Invariant ${f.id} was promoted to enforced (coverage evidence present).`,before:o.mode,after:f.mode}):I(e,{kind:"arkrule-invariant-promote-refused",path:`${p}.mode`,classification:"judgment-required",message:`Invariant ${f.id} cannot be promoted to enforced: ${u.reason}`,before:o.mode,after:f.mode})}else I(e,{kind:"arkrule-invariant-demoted",path:`${p}.mode`,classification:"weakening",message:`Invariant ${f.id} was demoted to advisory.`,before:o.mode,after:f.mode})}}function Ut(e,t,n){let r=[];X(r,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),X(r,"$.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(r,"$.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."}),xe(r,"$.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},a=e.cyclePolicy??"strict",l=t.cyclePolicy??"strict";if(a!==l){let c=s[l]===s[a]?"judgment-required":s[l]>s[a]?"strengthening":"weakening";I(r,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:c,message:"The cycle enforcement level changed.",before:a,after:l})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&I(r,{kind:"framework-overlay-changed",path:"$.frameworkOverlay",classification:"judgment-required",message:"The framework overlay changed and may alter effective layer matching.",before:e.frameworkOverlay??null,after:t.frameworkOverlay??null}),Vn(r,e.layers,t.layers),Un(r,e.rules,t.rules),Gn(r,e,t),zn(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),r.sort((c,d)=>c.path.localeCompare(d.path)||c.id.localeCompare(d.id)),{schemaVersion:Vt,classification:qn(r),findings:r}}function Gt(e,t){if(!e||e.schemaVersion!==Vt||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(s=>typeof s!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=T(e.findingIds),r=T(t.findingIds);return n.length===r.length&&n.every((s,a)=>s===r[a])}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 qt(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}function Pe(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}function P(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 r=t,s="";for(t+=1;t<e.length;t+=1){let a=e[t];if(a===n)return{value:s,offset:r,excerpt:e.slice(r,t+1)};a==="\\"&&t+1<e.length?(s+=e[t+1],t+=1):s+=a}}function _(e,t,n){return e.startsWith(t,n)&&!Pe(e[n-1])&&!Pe(e[n+t.length])}function zt(e,t){let n=P(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=P(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!_(e,"type",n))return!1;let s=P(e,n+4);if(s>=e.length||e[s]===","||e[s]==="}"||_(e,"as",s)||!qt(e[s]))return!1;for(n=s;n<e.length&&Pe(e[n]);)n+=1;if(n=P(e,n),_(e,"as",n)){if(n=P(e,n+2),!qt(e[n]))return!1;for(;n<e.length&&Pe(e[n]);)n+=1}r=!0}return!1}function Bn(e,t){if(t=P(e,t+6),e[t]==="(")return Re(e,P(e,t+1));let n=!1;if(_(e,"type",t)){let s=P(e,t+4);e[s]!==","&&!_(e,"from",s)&&(n=!0)}else zt(e,t)&&(n=!0);let r=Bt(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}function Kn(e,t){t=t+6;let n=P(e,t),r=!1;if(_(e,"type",n)){let a=P(e,n+4);(e[a]==="{"||e[a]==="*")&&(r=!0)}else zt(e,n)&&(r=!0);let s=Bt(e,t,!1);return s&&r?{...s,typeOnly:!0}:s}function Bt(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(_(e,"from",t))return Re(e,P(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return Re(e,t);if(t>0&&(_(e,"import",t)||_(e,"export",t)))return}}function Wn(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 Yn(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=P(e,t+7);if(e[r]!=="(")return;r=P(e,r+1);let s=Re(e,r);return s?{...s,requireCall:!0}:void 0}function Jn(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="/"&&e[n+1]==="/"){if(n=e.indexOf(`
|
|
8
|
+
`,n+2),n<0)break;continue}if(r==="/"&&e[n+1]==="*"){let a=e.indexOf("*/",n+2);if(a<0)break;n=a+1;continue}if(r==="`"){n=Wn(e,n);continue}if(r==="'"||r==='"'){let a=Re(e,n);a&&(n=a.offset+a.excerpt.length-1);continue}let s=r==="i"&&_(e,"import",n)?Bn(e,n):r==="e"&&_(e,"export",n)?Kn(e,n):r==="r"&&_(e,"require",n)?Yn(e,n):void 0;s&&(t.push(s),n=s.offset+s.excerpt.length-1)}return t}function Kt(e,t){let n=[],r=[];for(let s of Jn(e.content)){let a=s.value;if(!a.startsWith(".")){if(s.typeOnly)continue;let b=pe(a);if(!b)continue;let A=e.content.slice(0,s.offset).split(`
|
|
9
|
+
`).length;r.push({file:e.path,symbol:a,capability:b,evidence:{kind:"import",file:e.path,line:A,excerpt:s.excerpt}});continue}let l=e.content.slice(0,s.offset).split(`
|
|
10
|
+
`).length,c={kind:"import",file:e.path,line:l,excerpt:s.excerpt},d=Zn(e.path,a,t);n.push({from:e.path,specifier:a,to:d?.path??null,resolution:d?"resolved":"unresolved",fromLayer:e.layer,toLayer:d?.layer??null,evidence:c})}return{edges:n,capabilityUses:r}}function Zn(e,t,n){let r=e.split("/");r.pop();for(let a of t.split("/"))a==="."||a===""||(a===".."?r.pop():r.push(a));let s=r.join("/");for(let a of[s,`${s}.ts`,`${s}.tsx`,`${s}.mts`,`${s}.cts`,`${s}/index.ts`,`${s}/index.tsx`]){let l=n.get(a);if(l)return l}}function Wt(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let s=ae(t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});s&&n.push({ruleId:`layer-dependency:${s.from}->${s.to}`,message:s.message??`${s.from} must not depend on ${s.to}.`,edge:r,evidence:r.evidence})}return n}var Xn={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 Qn(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}function er(e,t){return Qn(e,t)?S(k(Ht({config:e,arkRules:t,warnings:[]}))):S(k(e))}function st(e,t,n){let r=typeof e=="string"?Mt(e,t):rt(e,t),s=n?.arkRules??me();return{...r,arkRules:s,policyHash:er(r.config,s)}}function tr(e){let t=st(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=st(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=Ut(t.config,n.config,{baseArkRules:t.arkRules,candidateArkRules:n.arkRules,candidateInvariantCoverage:e.candidateInvariantCoverage}),s=r.findings.filter(c=>c.classification==="weakening"||c.classification==="judgment-required").map(c=>c.id).sort(),a=s.length>0,l=a&&Gt(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:s});return{schemaVersion:r.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:r.classification,findings:r.findings,blockingFindingIds:s,requiresAcknowledgement:a,acknowledged:l,valid:!a||l}}function Fe(e){let t=e.files.map(g=>{let i=Q(g.path);return{path:i,content:g.content,contentHash:S(g.content),layer:V(i,e.contract.config.layers)??null}}).sort((g,i)=>g.path.localeCompare(i.path)),n=new Map(t.map(g=>[g.path,g])),r=[],s=[];for(let g of t){let i=Kt(g,n);r.push(...i.edges),s.push(...i.capabilityUses)}let a=Wt(r,e.contract.config),l=new Map(e.contract.config.layers.map(g=>[g.name,g])),c=new Map(e.contract.config.layers.map(g=>[g.name,new Set(se(g))]));for(let g of s){let i=n.get(g.file)?.layer;if(!i)continue;let o=l.get(i),f=fe(g.symbol,o?.forbiddenGlobals??[]);if(f){a.push({ruleId:"FORBIDDEN_GLOBAL",message:`${i} must not use module "${g.symbol}" because it is the import form of forbidden global "${f}".`,symbol:g.symbol,evidence:g.evidence});continue}c.get(i)?.has(g.capability)&&a.push({ruleId:"CAPABILITY_VIOLATION",message:`${i} denies the ${g.capability} capability; found import of "${g.symbol}".`,capability:g.capability,symbol:g.symbol,evidence:g.evidence})}let d=t.length===0?"complete":"partial",b=d==="complete"?[]:[{...Xn}],A={schemaVersion:ut,policyHash:e.contract.policyHash,compilerOptionsHash:S(k(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(g=>g.name),edges:r,capabilityUses:s,violations:a};return{mode:"lexical-compatibility",completeness:d,completenessReasons:b,valid:d==="complete"&&a.length===0,ir:A}}function at(e){let t=new Map(e.files.map(n=>[Q(n.path),n]));for(let n of e.changes){let r=Q(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return Fe({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}function nr(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 Te(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.";case"ARKRULE_STRUCTURE":case"ARKRULE_INVARIANT":case"INVARIANT_UNCOVERED":return`Fix the structure or invariant for ${typeof e.arkruleId=="string"&&e.arkruleId.length>0?e.arkruleId:"the ArkRule"} (declared in ${typeof e.arkruleSource=="string"&&e.arkruleSource.length>0?e.arkruleSource:"arkrules/<Layer>.json"}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`;default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}function Yt(e){return S(k(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}function rr(e){let t=Fe(e),n=new Map(t.ir.files.map(o=>[o.path,o])),r=[],s=new Set,a=[];for(let o of e.changes){let f=o.path.replace(/\\/g,"/"),p=Q(o.path);if(!p||p===".."||p.startsWith("../")||f.startsWith("/")||/^[A-Za-z]:\//.test(f)||f.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(s.has(p)){a.push({ruleId:"DUPLICATE_CHANGE_PATH",file:p,line:1,message:`The atomic change set contains more than one operation for ${p}.`});continue}s.add(p),"delete"in o&&o.delete&&!n.has(p)&&a.push({ruleId:"DELETE_TARGET_MISSING",file:p,line:1,message:`Cannot delete ${p} because it is not present in the supplied base tree.`}),r.push("delete"in o&&o.delete?{path:p,delete:!0}:{path:p,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 l=at({...e,changes:r}),c=new Map(l.ir.files.map(o=>[o.path,o])),d=l.ir.violations.filter(o=>o.ruleId==="CAPABILITY_VIOLATION"||o.ruleId==="FORBIDDEN_GLOBAL").map(o=>{let f=c.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}:{},...f?{fromLayer:f}:{},edgeKind:"import",message:o.message}}),b=ge({config:e.contract.config,rules:e.contract.config.rules,files:l.ir.files.map(o=>o.path),contentViolations:d,edges:l.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"}))}),A=r.map(o=>{let f=Q(o.path),p=n.get(f),h=c.get(f);return{path:f,operation:"delete"in o&&o.delete?"delete":p?"update":"create",...p?{beforeContentHash:p.contentHash}:{},...h?{candidateContentHash:h.contentHash}:{}}}).sort((o,f)=>o.path.localeCompare(f.path)),g=[...a,...b.violations].map(o=>({...o,nextAction:Te(o)})),i=e.changeMap?be({changeMap:e.changeMap,changes:A,baseDependencies:t.ir.edges.flatMap(o=>o.to?[{from:o.from,to:o.to}]:[]),candidateDependencies:l.ir.edges.flatMap(o=>o.to?[{from:o.from,to:o.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&l.valid&&g.length===0&&(i?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:l.ir.compilerOptionsHash,baseTreeHash:Yt(t.ir.files),candidateTreeHash:Yt(l.ir.files),baseCompleteness:t.completeness,candidateCompleteness:l.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:l.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...i?{convergence:i}:{},changes:A,violations:g,warnings:b.warnings}}function sr(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let s of t.split("/"))if(!(!s||s==="."))if(s===".."){if(n.length===0)return;n.pop()}else n.push(s);let r=n.join("/");return r&&r===t?r:void 0}function ar(e,t){return[["resolverIdentity",e.resolverIdentity,t.resolverIdentity],["compilerIdentity",e.compilerIdentity,t.compilerIdentity],["evidenceRequirementsHash",e.evidenceRequirementsHash,t.evidenceRequirementsHash],["projectPackageName",e.projectPackageName??"",t.projectPackageName??""]].filter(([,r,s])=>r!==s).map(([r,s,a])=>({ruleId:"FACTS_IDENTITY_MISMATCH",file:"<change-set>",line:1,field:r,before:s,candidate:a,message:`Base and candidate facts must use the same ${r}.`}))}function ir(e,t,n,r){let s=n.get(t),a=r.get(t);return{path:t,operation:"delete"in e&&e.delete?"delete":s?"update":"create",...s?{beforeContentHash:s.contentHash}:{},...a?{candidateContentHash:a.contentHash}:{}}}function or(e){let t=Y(e.baseFacts),n=Y(e.candidateFacts),r=Se({contract:e.contract,facts:t}),s=Se({contract:e.contract,facts:n}),a=new Map(t.files.map(i=>[i.path,i])),l=new Map(n.files.map(i=>[i.path,i])),c=ar(t,n),d=new Map,b=[];for(let i of e.changes){let o=sr(i.path);if(!o){c.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(d.has(o)){c.push({ruleId:"DUPLICATE_CHANGE_PATH",file:o,line:1,message:`The atomic change set contains more than one operation for ${o}.`});continue}d.set(o,i);let f=a.get(o),p=l.get(o);if("delete"in i&&i.delete)f||c.push({ruleId:"DELETE_TARGET_MISSING",file:o,line:1,message:`Cannot delete ${o} because it is not present in the supplied base facts.`}),p&&c.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:o,line:1,message:`Candidate facts still contain deleted file ${o}.`});else{let h="content"in i?i.content:"",R=S(h);p?p.contentHash!==R&&c.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:o,line:1,expectedContentHash:R,candidateContentHash:p.contentHash,message:`Candidate facts for ${o} do not match the declared content.`}):c.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:o,line:1,message:`Candidate facts do not contain changed file ${o}.`})}b.push(ir(i,o,a,l))}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 i of new Set([...a.keys(),...l.keys()])){if(d.has(i))continue;let o=a.get(i),f=l.get(i);o&&f&&k(o)===k(f)||c.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:i,line:1,message:`Candidate facts change ${i}, but the atomic change set does not declare it.`})}let A=e.changeMap?be({changeMap:e.changeMap,changes:b,baseDependencies:r.ir.edges.flatMap(i=>i.to?[{from:i.from,to:i.to}]:[]),candidateDependencies:s.ir.edges.flatMap(i=>i.to?[{from:i.from,to:i.to}]:[])}):void 0,g=[...c,...s.ir.violations].map(i=>({...i,nextAction:Te(i)}));return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&s.strictValid&&g.length===0&&(A?.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:r.completeness,candidateCompleteness:s.completeness,baseCompletenessReasons:r.completenessReasons,candidateCompletenessReasons:s.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...A?{convergence:A}:{},changes:b.sort((i,o)=>i.path<o.path?-1:i.path>o.path?1:0),violations:g,warnings:s.ir.warnings}}var Jt=new WeakSet;function Zt(e){if(!e||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Object.values(e))Zt(t);return Object.freeze(e)}function qs(e){let t=Zt(Ie(e));return Jt.add(t),t}function zs(e){if(!Jt.has(e.facts))throw new Error("Trusted resolved analysis requires immutable in-process canonical facts.");return Ke(e)}export{He as AMBIENT_CAPABILITY_ENTRIES,Ne as CAPABILITY_IDS,Ge as DEFAULT_INTENT_PREFIXES,ft as RESOLVED_CANDIDATE_FACTS_SCHEMA,ee as RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,Ue as SOURCE_POLICY_MESSAGES,De as ambientCoveredByForbiddenGlobals,be as analyzeArchitectureConvergence,at as analyzeChange,tr as analyzePolicyDelta,Fe as analyzeProject,Se as analyzeResolvedProject,zs as analyzeTrustedResolvedProject,ue as capabilityForAmbientName,pe as capabilityForModuleSpecifier,ze as classifyPublishFacts,Be as collectAnalysisConfigWarnings,_n as collectCapabilityUses,et as collectForbiddenCapabilityUses,Ie as createResolvedCandidateFacts,qs as createTrustedResolvedCandidateFacts,$t as detectArchitectureCycles,S as deterministicHash,se as effectiveCapabilityDeny,ge as evaluateArchitectureGraph,nr as explainViolation,Qe as extractSemanticDependencies,fe as forbiddenGlobalForModuleSpecifier,Pn as loadArchitectureChangeMap,st as loadContract,Y as loadResolvedCandidateFacts,ht as looksLikeArkIntent,rn as lowerForbiddenGlobal,ke as loweredLayerCoverage,rr as preflightChange,or as preflightResolvedChange,qe as resolveIntentLayer,ve as resolvedFactsEvidenceRequirementsHash,k as stableSerialize};
|
|
@@ -10,6 +10,9 @@ import {
|
|
|
10
10
|
} from './analysis-engine.mjs';
|
|
11
11
|
import { effectiveAnalysisConfig } from './analysis-policy.mjs';
|
|
12
12
|
import { resolveCandidateFacts } from './resolved-candidate-facts.mjs';
|
|
13
|
+
import { loadEffectiveArkRulesFromDisk } from './effective-contract-load.mjs';
|
|
14
|
+
import { loadInvariantCoverageInputs } from './invariant-coverage-io.mjs';
|
|
15
|
+
import { loadArkRuleFileHints } from './arkrule-file-hints.mjs';
|
|
13
16
|
|
|
14
17
|
/** Resolve canonical facts and optionally retain filesystem probes for resident invalidation. */
|
|
15
18
|
export function resolveArchitectureSnapshot({
|
|
@@ -47,8 +50,38 @@ export function resolveArchitectureSnapshot({
|
|
|
47
50
|
...(args?.tsconfig ? { tsconfig: args.tsconfig } : {}),
|
|
48
51
|
observeInput,
|
|
49
52
|
});
|
|
50
|
-
const
|
|
51
|
-
|
|
53
|
+
const arkRulesLoad = loadEffectiveArkRulesFromDisk(root, effectiveConfig, {
|
|
54
|
+
observeInput,
|
|
55
|
+
});
|
|
56
|
+
if (arkRulesLoad.errors.length > 0) {
|
|
57
|
+
const message = arkRulesLoad.errors
|
|
58
|
+
.map((issue) => `- ${issue.path}: ${issue.message}`)
|
|
59
|
+
.join('\n');
|
|
60
|
+
const err = new Error(`Invalid Effective Contract (${configPath}):\n${message}`);
|
|
61
|
+
err.code = 'ARKRULES_LOAD_FAILED';
|
|
62
|
+
err.issues = arkRulesLoad.errors;
|
|
63
|
+
throw err;
|
|
64
|
+
}
|
|
65
|
+
const loadedContract = loadContract(effectiveConfig, configPath, {
|
|
66
|
+
arkRules: arkRulesLoad.arkRules,
|
|
67
|
+
});
|
|
68
|
+
const hasInvariants = (arkRulesLoad.arkRules?.invariants?.length ?? 0) > 0;
|
|
69
|
+
const coverageInputs = hasInvariants
|
|
70
|
+
? loadInvariantCoverageInputs(root, facts)
|
|
71
|
+
: undefined;
|
|
72
|
+
// AR07: Tooling fileHints for orchestration-only / thin-adapter (reuse coverage contents when present).
|
|
73
|
+
const fileHints = loadArkRuleFileHints(
|
|
74
|
+
root,
|
|
75
|
+
facts,
|
|
76
|
+
arkRulesLoad.arkRules,
|
|
77
|
+
coverageInputs?.fileContents
|
|
78
|
+
);
|
|
79
|
+
const analyzed = analyzeTrustedResolvedProject({
|
|
80
|
+
contract: loadedContract,
|
|
81
|
+
facts,
|
|
82
|
+
...(coverageInputs ? { coverageInputs } : {}),
|
|
83
|
+
...(fileHints ? { fileHints } : {}),
|
|
84
|
+
});
|
|
52
85
|
const parseHealth = summarizeParseHealth(
|
|
53
86
|
facts.files.map((file) => ({
|
|
54
87
|
relFile: file.path,
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tooling I/O for AR07 orchestration-only / thin-adapter fileHints.
|
|
3
|
+
* Pure derivation lives in Domain (`deriveArkRuleFileHints` / `buildArkRuleFileHints`);
|
|
4
|
+
* this module loads bounded source text when those sensors are active.
|
|
5
|
+
*/
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { buildArkRuleFileHints } from './arkrules-sensors.mjs';
|
|
9
|
+
|
|
10
|
+
const MAX_HINT_FILES = 400;
|
|
11
|
+
const MAX_FILE_BYTES = 256 * 1024;
|
|
12
|
+
|
|
13
|
+
const HINT_SENSORS = new Set(['orchestration-only', 'thin-adapter']);
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* @param {{ structure?: Array<{ sensor?: string }> } | null | undefined} arkRules
|
|
17
|
+
*/
|
|
18
|
+
export function needsArkRuleFileHints(arkRules) {
|
|
19
|
+
return (arkRules?.structure ?? []).some((rule) => HINT_SENSORS.has(rule?.sensor));
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Load governed source contents (bounded) and derive fileHints.
|
|
24
|
+
*
|
|
25
|
+
* @param {string} root
|
|
26
|
+
* @param {{ files?: Array<{ path: string }> }} facts
|
|
27
|
+
* @param {{ structure?: Array<{ sensor?: string }> } | null | undefined} arkRules
|
|
28
|
+
* @param {Readonly<Record<string, string>>} [preloadedContents] optional reuse from coverage I/O
|
|
29
|
+
* @returns {Record<string, { orchestrationHeavy?: boolean, adapterThick?: boolean }> | undefined}
|
|
30
|
+
*/
|
|
31
|
+
export function loadArkRuleFileHints(root, facts, arkRules, preloadedContents) {
|
|
32
|
+
if (!needsArkRuleFileHints(arkRules)) return undefined;
|
|
33
|
+
|
|
34
|
+
const fileContents = { ...(preloadedContents ?? {}) };
|
|
35
|
+
const seen = new Set(Object.keys(fileContents));
|
|
36
|
+
|
|
37
|
+
const rootResolved = path.resolve(root);
|
|
38
|
+
const pushFile = (relPath) => {
|
|
39
|
+
const rel = String(relPath || '')
|
|
40
|
+
.replace(/\\/g, '/')
|
|
41
|
+
.replace(/^\.\//, '');
|
|
42
|
+
if (!rel || seen.has(rel) || seen.size >= MAX_HINT_FILES) return;
|
|
43
|
+
if (!/\.(tsx?|mts|cts|jsx?|mjs|cjs)$/i.test(rel)) return;
|
|
44
|
+
if (rel.includes('node_modules/') || rel.endsWith('.d.ts')) return;
|
|
45
|
+
const absolute = path.resolve(root, rel);
|
|
46
|
+
const relative = path.relative(rootResolved, absolute);
|
|
47
|
+
if (
|
|
48
|
+
relative === '' ||
|
|
49
|
+
relative.startsWith('..') ||
|
|
50
|
+
path.isAbsolute(relative)
|
|
51
|
+
) {
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
try {
|
|
55
|
+
const stat = fs.statSync(absolute);
|
|
56
|
+
if (!stat.isFile() || stat.size > MAX_FILE_BYTES) return;
|
|
57
|
+
fileContents[rel] = fs.readFileSync(absolute, 'utf8');
|
|
58
|
+
seen.add(rel);
|
|
59
|
+
} catch {
|
|
60
|
+
// skip unreadable
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
for (const file of facts?.files ?? []) {
|
|
65
|
+
if (file?.path) pushFile(file.path);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
if (Object.keys(fileContents).length === 0) return undefined;
|
|
69
|
+
const hints = buildArkRuleFileHints(fileContents);
|
|
70
|
+
return Object.keys(hints).length > 0 ? hints : {};
|
|
71
|
+
}
|