arkgate 3.7.0 → 3.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +113 -1145
- package/README.md +59 -19
- package/bin/ark-check-runtime.mjs +1598 -0
- package/bin/ark-check.mjs +32 -1565
- package/bin/ark-layer-match.mjs +9 -4
- package/bin/ark-mcp-runtime.mjs +1976 -0
- package/bin/ark-mcp.mjs +84 -1495
- package/bin/ark-shared.mjs +34 -38
- package/bin/ark.mjs +33 -66
- package/bin/lib/adapter-contract.mjs +161 -9
- package/bin/lib/agent-gates.mjs +1 -0
- package/bin/lib/analysis-completeness.mjs +28 -0
- package/bin/lib/analysis-engine.mjs +8 -8
- package/bin/lib/analysis-policy.mjs +27 -0
- package/bin/lib/architecture-scan.mjs +70 -357
- package/bin/lib/auto-patch.mjs +76 -8
- package/bin/lib/ci-and-commands.mjs +1 -1
- package/bin/lib/codex-home.mjs +43 -16
- package/bin/lib/design-delta.mjs +4 -0
- package/bin/lib/doctor-advisories.mjs +4 -3
- package/bin/lib/doctor-plan.mjs +40 -41
- package/bin/lib/enforcement-state.mjs +2 -0
- package/bin/lib/github-enforcement.mjs +443 -0
- package/bin/lib/hook-templates.mjs +12 -148
- package/bin/lib/html-report-advisories.mjs +1 -1
- package/bin/lib/html-report-depth.mjs +9 -0
- package/bin/lib/html-report.mjs +5 -5
- package/bin/lib/install-migrate.mjs +83 -79
- package/bin/lib/managed-upgrade.mjs +622 -0
- package/bin/lib/mcp-adoption.mjs +3 -1
- package/bin/lib/parse-health.mjs +6 -5
- package/bin/lib/port-proof.mjs +2 -2
- package/bin/lib/prepare-change.mjs +68 -38
- package/bin/lib/prepare-write.mjs +7 -1
- package/bin/lib/resident-doctor-client.mjs +55 -0
- package/bin/lib/resident-hook.mjs +247 -0
- package/bin/lib/resolved-candidate-facts.mjs +1160 -0
- package/bin/lib/scan-files.mjs +19 -6
- package/bin/lib/snippet-analysis.mjs +119 -0
- package/bin/lib/source-policy.mjs +24 -0
- package/bin/lib/typescript-host.mjs +15 -18
- package/bin/lib/unavailable-analysis.mjs +76 -0
- package/bin/lib/upgrade-command.mjs +115 -0
- package/bin/lib/weakest-link.mjs +21 -179
- package/bin/lib/write-path-capabilities.mjs +167 -16
- package/bin/lib/write-path-detect.mjs +3 -2
- package/dist/eslint/index.cjs +3 -3
- package/dist/eslint/index.d.ts +4 -1
- package/dist/eslint/index.js +3 -3
- package/dist/index.cjs +6 -6
- package/dist/index.d.ts +1111 -151
- package/dist/index.js +7 -7
- package/docs/agent-guide.md +106 -62
- package/docs/ai-gates.md +97 -16
- package/docs/configuration.md +3 -0
- package/docs/demos/01-write-gate-self-correction.md +2 -2
- package/docs/enthusiast/README.md +10 -10
- package/docs/enthusiast/how-to-gallery-starter.md +2 -2
- package/docs/enthusiast/reference-commands.md +18 -1
- package/docs/enthusiast/tutorial-first-project.md +2 -2
- package/docs/package-surface.md +98 -12
- package/docs/typescript-support.md +108 -37
- package/package.json +32 -4
- package/schemas/ark.analysis-result.schema.json +159 -2
- package/schemas/ark.design-delta.schema.json +1 -0
- package/schemas/ark.enforcement-state.schema.json +84 -0
- package/schemas/ark.resolved-candidate-facts.schema.json +1 -0
- package/server.json +2 -2
- package/templates/skills/ark-explore.md +5 -5
- package/templates/skills/ark-fix.md +1 -1
- package/templates/skills/ark-runtime.md +15 -8
- package/templates/skills/ark-upgrade.md +122 -182
- package/bin/lib/ai-velocity.mjs +0 -293
- package/bin/lib/graph-cycles.mjs +0 -6
- package/bin/lib/safety-diagnostics.mjs +0 -284
- package/bin/lib/ts-resolve.mjs +0 -228
- package/dist/configTypes-DAPvBqK6.d.cts +0 -61
- package/dist/eslint/index.d.cts +0 -146
- package/dist/index.d.cts +0 -986
|
@@ -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){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 x(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(x).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${x(t[n])}`).join(",")}}`}var Ce=new Map;function Ie(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function X(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let i=e[n+1];if("*?{}[],".includes(i)||i==="\\"){t+="\\"+i,n+=1;continue}t+="/";continue}t+=r}return t}function Ue(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 D(e){let t=Ce.get(e);if(t)return t;let n=X(e),r=Ue(n),i="",a=0;for(let d=0;d<n.length;d+=1){let l=n[d];l==="\\"&&d+1<n.length?(i+=Ie(n[d+1]),d+=1):l==="*"?n[d+1]==="*"?n[d+2]==="/"?(i+="(?:.*/)?",d+=2):(i+=".*",d+=1):i+="[^/]*":l==="?"?i+="[^/]":l==="{"&&r?(i+="(?:",a+=1):l==="}"&&r&&a>0?(i+=")",a-=1):l===","&&r&&a>0?i+="|":i+=Ie(l)}let o=new RegExp(`^${i}$`);return Ce.set(e,o),o}function Q(e){let t=X(String(e)),r=t.split("*")[0].split("/").filter(Boolean).length,i=t.replace(/\*/g,"").length;return r*1e4+i}function _(e,t){let n=String(e).split(/[/\\]/).join("/"),r,i=-1;for(let a of t??[])if(!(a.exclude??[]).some(o=>D(o).test(n))){for(let o of a.patterns??[])if(D(o).test(n)){let d=Q(o);d>i&&(i=d,r=a.name)}}return r}function ke(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),r=new Set(t.map(i=>String(i).toLowerCase()));for(let i=0;i<n.length-1;i+=1)if(r.has(n[i].toLowerCase()))return`${n[i].toLowerCase()}/${n[i+1].toLowerCase()}`}function Be(e){let t=new Set;for(let n of e??[]){let i=X(String(n)).split("/").filter(Boolean);for(let a=0;a<i.length;a+=1){let o=i[a];if((o==="**"||o==="*")&&a>0){let d=i[a-1];d&&!d.includes("*")&&!d.includes("{")&&!d.includes("}")&&t.add(d)}}}return[...t]}function ze(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(i=>typeof i=="string"&&i.length>0);let r=(n??[]).find(i=>i.name===t);return Be(r?.patterns)}function G(e,t,n,r){for(let i of e??[])if(!(i.from!==t||i.to!==n)&&i.allowed===!1){if(i.peerIsolation){let a=r?.fromPath,o=r?.toPath;if(!a||!o)continue;let d=ze(i,t,r?.layers);if(d.length===0)continue;let l=ke(a,d),u=ke(o,d);if(!l||!u)continue;if(l!==u)return i;continue}if(t!==n)return i}}var ee="1.0";var U=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 te(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ne(e,t,n,r){for(let i of Object.keys(e))t.includes(i)||r.push({path:`${n}.${i}`,message:"unknown field"})}function R(e,t,n,r){let i=e[t];if(typeof i=="string"&&i.length>0)return i;r.push({path:`${n}.${t}`,message:"must be a non-empty string"})}function qe(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 r=n.join("/");return r&&r===t?r:void 0}function Ke(e,t,n="architecture change map"){let r=[];if(!te(e))throw new U(n,[{path:"$",message:"must be an object"}]);ne(e,["$schema","schemaVersion","files","dependencies"],"$",r);let i=R(e,"$schema","$",r),a=R(e,"schemaVersion","$",r);a&&a!==ee&&r.push({path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(a)}; expected ${ee}`});let o=new Set(t.layers.map(p=>p.name)),d=[],l=new Set;!Array.isArray(e.files)||e.files.length===0?r.push({path:"$.files",message:"must be a non-empty array"}):e.files.forEach((p,f)=>{let m=`$.files[${f}]`;if(!te(p)){r.push({path:m,message:"must be an object"});return}ne(p,["path","operation","layer"],m,r);let h=R(p,"path",m,r),A=R(p,"operation",m,r),C=R(p,"layer",m,r),k=h?qe(h):void 0;h&&!k&&r.push({path:`${m}.path`,message:"must be a canonical project-relative path"}),A&&!["create","update","delete"].includes(A)&&r.push({path:`${m}.operation`,message:"must be create, update, or delete"}),C&&!o.has(C)&&r.push({path:`${m}.layer`,message:`references unknown layer ${JSON.stringify(C)}`}),k&&l.has(k)&&r.push({path:`${m}.path`,message:`duplicates planned path ${k}`}),k&&l.add(k);let Z=k?_(k,t.layers):void 0;k&&C&&o.has(C)&&Z!==C&&r.push({path:`${m}.layer`,message:Z?`${k} resolves to ${Z}, not ${C}`:`${k} is not assigned to an architecture layer`}),k&&A&&["create","update","delete"].includes(A)&&C&&d.push({path:k,operation:A,layer:C})});let u=[],y=new Map(d.map(p=>[p.path,p.operation])),g=new Set,c=e.dependencies??[];if(Array.isArray(c)?c.forEach((p,f)=>{let m=`$.dependencies[${f}]`;if(!te(p)){r.push({path:m,message:"must be an object"});return}ne(p,["from","to"],m,r);let h=R(p,"from",m,r),A=R(p,"to",m,r);h&&!l.has(h)&&r.push({path:`${m}.from`,message:`must reference a planned file path: ${h}`}),A&&!l.has(A)&&r.push({path:`${m}.to`,message:`must reference a planned file path: ${A}`}),h&&y.get(h)==="delete"&&r.push({path:`${m}.from`,message:`cannot depend from deleted file ${h}`}),A&&y.get(A)==="delete"&&r.push({path:`${m}.to`,message:`cannot depend on deleted file ${A}`}),h&&A&&h===A&&r.push({path:m,message:"must not declare a self dependency"});let C=h&&A?`${h}\0${A}`:void 0;C&&g.has(C)&&r.push({path:m,message:`duplicates dependency ${h} -> ${A}`}),C&&g.add(C),h&&A&&u.push({from:h,to:A})}):r.push({path:"$.dependencies",message:"must be an array"}),r.length>0)throw new U(n,r);let s={$schema:i,schemaVersion:ee,files:d.sort((p,f)=>p.path.localeCompare(f.path)),dependencies:u.sort((p,f)=>p.from.localeCompare(f.from)||p.to.localeCompare(f.to))};return{map:s,hash:$(x(s))}}function w(e){return`${e.from}->${e.to}`}function F(e,t,n,r="dependency"){return{id:`${e}:${r}:${w(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${w(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${w(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${w(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${w(t)} from the candidate, then preflight again.`}:{}}}function re(e){let t=[],n=new Map(e.changeMap.map.files.map(c=>[c.path,c])),r=new Map(e.changes.map(c=>[c.path,c])),i=new Map(e.changeMap.map.dependencies.map(c=>[w(c),c])),a=new Map(e.baseDependencies.map(c=>[w(c),c])),o=new Map(e.candidateDependencies.map(c=>[w(c),c]));for(let c of[...n.values()].sort((s,p)=>s.path.localeCompare(p.path))){let s=r.get(c.path);s?s.operation!==c.operation?t.push({id:`contradictory:file:${c.path}`,classification:"contradictory",subject:"file",path:c.path,expectedOperation:c.operation,actualOperation:s.operation,message:`${c.path} was planned as ${c.operation} but the actual operation is ${s.operation}.`,nextAction:`Change ${c.path} to the planned ${c.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${c.path}`,classification:"satisfied",subject:"file",path:c.path,expectedOperation:c.operation,actualOperation:s.operation,message:`${c.path} matches the planned ${c.operation} operation.`}):t.push({id:`missing:file:${c.path}`,classification:"missing",subject:"file",path:c.path,expectedOperation:c.operation,message:`${c.path} was planned as ${c.operation} but is absent from the actual change.`,nextAction:`${c.operation[0].toUpperCase()}${c.operation.slice(1)} ${c.path} in the complete change set, then preflight again.`})}for(let c of[...r.values()].sort((s,p)=>s.path.localeCompare(p.path)))n.has(c.path)||t.push({id:`unplanned:file:${c.path}`,classification:"unplanned",subject:"file",path:c.path,actualOperation:c.operation,message:`${c.path} has an unplanned ${c.operation} operation.`,nextAction:`Remove ${c.path} from the change set, then preflight again.`});let d=new Set;for(let c of[...i.values()].sort((s,p)=>w(s).localeCompare(w(p)))){if(o.has(w(c))){t.push(F("satisfied",c,`${c.from} -> ${c.to} exists in the candidate architecture.`));continue}let s={from:c.to,to:c.from};o.has(w(s))?(d.add(w(s)),t.push(F("contradictory",c,`${c.from} -> ${c.to} was planned, but the candidate contains the reverse edge.`))):t.push(F("missing",c,`${c.from} -> ${c.to} is absent from the candidate architecture.`))}let l=new Set([...n.keys(),...r.keys()]);for(let[c,s]of[...o].sort(([p],[f])=>p.localeCompare(f)))a.has(c)||i.has(c)||d.has(c)||!l.has(s.from)&&!l.has(s.to)||t.push({...F("unplanned",s,`${s.from} -> ${s.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let u=new Set(e.changeMap.map.files.filter(c=>c.operation==="delete").map(c=>c.path));for(let[c,s]of[...a].sort(([p],[f])=>p.localeCompare(f)))o.has(c)||u.has(s.from)||u.has(s.to)||!l.has(s.from)&&!l.has(s.to)||t.push({...F("unplanned",s,`${s.from} -> ${s.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let y={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((c,s)=>y[c.classification]-y[s.classification]||(c.subject===s.subject?0:c.subject==="file"?-1:1)||c.id.localeCompare(s.id));let g={satisfied:t.filter(c=>c.classification==="satisfied").length,missing:t.filter(c=>c.classification==="missing").length,contradictory:t.filter(c=>c.classification==="contradictory").length,unplanned:t.filter(c=>c.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:g.missing===0&&g.contradictory===0&&g.unplanned===0,behavioralCompletion:"not-evaluated",summary:g,findings:t}}function M(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function xe(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function we(e,t){if(e.isImportDeclaration(t)){let n=t.importClause;if(!n)return!1;if(n.isTypeOnly)return!0;let r=n.namedBindings;return!!(r&&e.isNamedImports(r)&&r.elements.length>0&&r.elements.every(i=>i.isTypeOnly))}if(e.isExportDeclaration(t)){if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(r=>r.isTypeOnly))}return!1}function Ee(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=i=>i===t.fileName?t:void 0,r.fileExists=i=>i===t.fileName,r.readFile=i=>i===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}function ie(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function ae(e,t,n,r){let i=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,a;try{a=i?t.getShorthandAssignmentValueSymbol(r.parent):ie(t,r)}catch{a=void 0}return!!a?.declarations?.some(o=>o.getSourceFile().fileName===n.fileName)}function se(e,t){let n,r=[],i=(o,d,l,u=!1)=>r.push({specifier:l,kind:d,line:xe(t,o),typeOnly:u,unresolved:l===void 0,node:o}),a=o=>{if(e.isImportDeclaration(o))i(o,"import",M(e,o.moduleSpecifier),we(e,o));else if(e.isExportDeclaration(o)&&o.moduleSpecifier)i(o,"export",M(e,o.moduleSpecifier),we(e,o));else if(e.isImportEqualsDeclaration(o)&&e.isExternalModuleReference(o.moduleReference))i(o,"require",M(e,o.moduleReference.expression),o.isTypeOnly===!0);else if(e.isCallExpression(o)){let d=o.expression.kind===e.SyntaxKind.ImportKeyword,u=e.isIdentifier(o.expression)&&o.expression.text==="require"&&!ae(e,n??(n=Ee(e,t)),t,o.expression);(d||u)&&i(o,u?"require":"dynamic-import",M(e,o.arguments[0]))}e.forEachChild(o,a)};return a(t),r}function Ye(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let i=M(e,r.argumentExpression);if(i===void 0)return;n.unshift(i)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}function We(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 Se(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let r=n.length;r>=1;r-=1){let i=n.slice(0,r).join(".");if(e.has(i))return i}}function oe(e,t,n){if(n.length===0)return[];let r=new Set(n),i=Ee(e,t),a=new Map,o=new Set;for(let c of t.statements)if(e.isVariableStatement(c))for(let s of c.declarationList.declarations)e.isIdentifier(s.name)&&o.add(s.name.text);let d=c=>{let s=Ye(e,c);if(!s)return;let p=ie(i,s.root),f=p?a.get(p):void 0;return f?[...f,...s.segments.slice(1)]:ae(e,i,t,s.root)||o.has(s.root.text)?void 0:s.segments};for(let c of t.statements)if(e.isVariableStatement(c))for(let s of c.declarationList.declarations){if(!s.initializer||!e.isIdentifier(s.name))continue;let p=d(s.initializer),f=ie(i,s.name);!p||!f||a.set(f,p)}let l=[],u=new Set,y=(c,s)=>{let p=xe(t,s),f=`${c}:${s.getStart(t)}`;u.has(f)||(u.add(f),l.push({name:c,line:p,node:s}))},g=c=>{let s=c.parent&&(e.isPropertyAccessExpression(c.parent)||e.isElementAccessExpression(c.parent))&&c.parent.expression===c;if((e.isPropertyAccessExpression(c)||e.isElementAccessExpression(c))&&!s){let p=d(c),f=p?Se(r,p):void 0;f&&y(f,c)}else e.isIdentifier(c)&&r.has(c.text)&&We(e,c)&&!ae(e,i,t,c)&&y(c.text,c);if(e.isVariableDeclaration(c)&&e.isObjectBindingPattern(c.name)&&c.initializer){let p=d(c.initializer);if(p)for(let f of c.name.elements){if(!e.isIdentifier(f.name))continue;let m=f.propertyName?M(e,f.propertyName)??f.propertyName.text:f.name.text,h=Se(r,[...p,m]);h&&y(h,c.initializer)}}e.forEachChild(c,g)};return g(t),l}var ce={RAW_EVENT_PUBLISH:"Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts and tooling.",PUBLISH_MISSING_SOURCE:"Strict Ark publish calls must include metadata.source."};function $e(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function Je(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&$e(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:ce.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:ce.PUBLISH_MISSING_SOURCE}),t}var de=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),B=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),fe=Object.freeze(Object.keys(B).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"}),pe=Object.freeze({process:Object.freeze(["process","node:process"])});function j(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),i=le[r];if(i)return i;let a=e.indexOf("/",n+1);return a<0?null:le[e.slice(0,a)]??null}function ue(e,t){for(let n of t)if(pe[n]?.includes(e))return n;return null}function V(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),i=B[r];if(i)return i}return null}function z(e){if(e?.pure===!0)return[...de].sort();let n=(e?.capabilities?.deny??[]).filter(r=>de.includes(r));return[...new Set(n)].sort()}function Ze(e,t){if(t.length===0)return!1;let n=new Set(t),r=e.split(".");for(let i=r.length;i>=1;i-=1)if(n.has(r.slice(0,i).join(".")))return!0;return!1}function q(e){let t=new Set,n=new Set,r=Object.keys(B);for(let i of e?.forbiddenGlobals??[]){let a=r.filter(o=>o===i||o.startsWith(`${i}.`));if(a.length===0)n.add(i);else for(let o of a)t.add(`ambient:${o}`);for(let o of pe[i]??[])t.add(`import-exact:${o}`)}for(let i of z(e)){if(t.add(`import:${i}`),i==="process")for(let a of pe.process)t.add(`import-exact:${a}`);for(let a of r)V(a)===i&&t.add(`ambient:${a}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}function Xe(e){let t=new Set,n=V(e);n&&t.add(n);for(let[r,i]of Object.entries(B))(r===e||r.startsWith(`${e}.`))&&t.add(i);return[...t].sort()}function Qe(e,t){let n=[];for(let r of se(e,t)){if(r.typeOnly||!r.specifier)continue;let i=j(r.specifier);i&&n.push({capability:i,symbol:r.specifier,line:r.line,source:"import-based"})}for(let r of oe(e,t,fe)){let i=V(r.name);i&&n.push({capability:i,symbol:r.name,line:r.line,source:"ambient-global"})}return n.sort((r,i)=>r.line-i.line||r.capability.localeCompare(i.capability)||r.symbol.localeCompare(i.symbol))}var ye="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",Oe=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],et=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function tt(){let e=[];for(let t of Oe)for(let n of Oe)t===n||et.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var Re=tt();var O={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Le={$schema:"https://json-schema.org/draft/2020-12/schema",$id:ye,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:ye,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:{...O,minItems:1,default:["src"]},exclude:{...O,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:Re,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...O,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:{...O,minItems:1},exclude:O,intentPrefixes:O,description:{type:"string",minLength:1},forbiddenGlobals:O,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:{...O,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}}}}},T=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 Pe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ge(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function N(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function nt(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function K(e,t,n,r,i){if(t.$ref){let a=nt(t.$ref,r);if(!a){i.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}K(e,a,n,r,i);return}if(t.const!==void 0&&!Object.is(e,t.const)){i.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(a=>Object.is(a,e))){i.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!Pe(e)){i.push({path:n,message:`must be an object; received ${N(e)}`});return}let a=t.properties??{};for(let o of t.required??[])e[o]===void 0&&i.push({path:ge(n,o),message:"is required"});if(t.additionalProperties===!1)for(let o of Object.keys(e))o in a||i.push({path:ge(n,o),message:"unknown field"});for(let[o,d]of Object.entries(a))e[o]!==void 0&&K(e[o],d,ge(n,o),r,i);return}if(t.type==="array"){if(!Array.isArray(e)){i.push({path:n,message:`must be an array; received ${N(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&i.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let a=e.map(o=>JSON.stringify(o));new Set(a).size!==a.length&&i.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((a,o)=>K(a,t.items,`${n}[${o}]`,r,i));return}if(t.type==="string"){if(typeof e!="string"){i.push({path:n,message:`must be a string; received ${N(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 ${N(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){i.push({path:n,message:`must be an integer; received ${N(e)}`});return}t.minimum!==void 0&&e<t.minimum&&i.push({path:n,message:`must be at least ${t.minimum}`})}}function rt(e){return{...e,$schema:e.$schema===void 0?ye:e.$schema,schemaVersion:e.schemaVersion===void 0?"1.0":e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?Re.map(t=>({...t})):e.rules}}function it(e,t="ark.config.json"){if(!Pe(e))throw new T(t,[{path:"$",message:`must be an object; received ${N(e)}`}]);let n=e.schemaVersion===void 0?"unversioned":null;if(e.schemaVersion!==void 0&&e.schemaVersion!=="1.0")throw new T(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.0`}]);return{candidate:rt(e),migratedFrom:n}}function me(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=it(e,t),i=[];if(K(n,Le,"$",Le,i),i.length>0)throw new T(t,i);return{config:n,migratedFrom:r}}function ve(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new T(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return me(n,t)}var _e="1.0";function b(e,t){e.push({id:`${t.classification}:${t.path}:${t.kind}`,path:t.path,classification:t.classification,message:t.message,...t.classification==="weakening"||t.classification==="judgment-required"?{nextAction:`Restore the previous protection at ${t.path}, then run ArkGate again.`}:{},...t.before===void 0?{}:{before:t.before},...t.after===void 0?{}:{after:t.after}})}function S(e){return[...new Set(e??[])].sort()}function P(e,t,n,r,i){let a=S(n),o=S(r),d=new Set(a),l=new Set(o),u=o.filter(g=>!d.has(g)),y=a.filter(g=>!l.has(g));u.length===0&&y.length===0||(u.length>0&&b(e,{kind:"added",path:t,classification:i.added,message:i.addedMessage,before:a,after:o}),y.length>0&&b(e,{kind:"removed",path:t,classification:i.removed,message:i.removedMessage,before:a,after:o}))}function Y(e,t,n,r,i,a,o){if(n===r)return;b(e,{kind:r?"enabled":"disabled",path:t,classification:r?i:i==="strengthening"?"weakening":"strengthening",message:r?a:o,before:n,after:r})}function W(e,t){let n=new Map,r=new Set;for(let i of e){let a=t(i);n.has(a)?r.add(a):n.set(a,i)}return{values:n,duplicates:[...r].sort()}}function at(e,t,n){let r=W(t,a=>a.name),i=W(n,a=>a.name);(r.duplicates.length>0||i.duplicates.length>0)&&b(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:r.duplicates,after:i.duplicates});for(let a of[...new Set([...r.values.keys(),...i.values.keys()])].sort()){let o=r.values.get(a),d=i.values.get(a),l=`$.layers[${a}]`;if(!o&&d){b(e,{kind:"layer-added",path:l,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:d});continue}if(o&&!d){b(e,{kind:"layer-removed",path:l,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:o});continue}if(!o||!d)continue;P(e,`${l}.patterns`,o.patterns,d.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),P(e,`${l}.exclude`,o.exclude,d.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let u=q(o),y=q(d);P(e,`${l}.forbiddenGlobals`,u.rawGlobals,y.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),P(e,`${l}.capabilities`,u.atoms,y.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)."}),S(o.intentPrefixes).join("\0")!==S(d.intentPrefixes).join("\0")&&b(e,{kind:"intent-prefixes-changed",path:`${l}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:S(o.intentPrefixes),after:S(d.intentPrefixes)}),Y(e,`${l}.mayImportInfrastructure`,o.mayImportInfrastructure===!0,d.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),Y(e,`${l}.optional`,o.optional===!0,d.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 st(e,t,n){let r=o=>`${o.from}->${o.to}`,i=W(t,r),a=W(n,r);(i.duplicates.length>0||a.duplicates.length>0)&&b(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:i.duplicates,after:a.duplicates});for(let o of[...new Set([...i.values.keys(),...a.values.keys()])].sort()){let d=i.values.get(o),l=a.values.get(o),u=`$.rules[${o}]`;if(!d&&l){l.allowed===!1&&b(e,{kind:"deny-added",path:u,classification:"strengthening",message:"A denied dependency edge was added.",after:l});continue}if(d&&!l){d.allowed===!1&&b(e,{kind:"deny-removed",path:u,classification:"weakening",message:"A denied dependency edge was removed.",before:d});continue}if(!d||!l)continue;d.allowed!==l.allowed&&b(e,{kind:l.allowed?"deny-disabled":"deny-enabled",path:`${u}.allowed`,classification:l.allowed?"weakening":"strengthening",message:l.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:d.allowed,after:l.allowed});let y=d.peerIsolation===!0,g=l.peerIsolation===!0;if(y!==g){let c=d.from===d.to&&l.from===l.to;b(e,{kind:g?"peer-isolation-enabled":"peer-isolation-disabled",path:`${u}.peerIsolation`,classification:c?g?"strengthening":"weakening":"judgment-required",message:c?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:y,after:g})}S(d.sliceFolders).join("\0")!==S(l.sliceFolders).join("\0")&&b(e,{kind:"slice-folders-changed",path:`${u}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:S(d.sliceFolders),after:S(l.sliceFolders)})}}function ot(e,t,n){let r=t.safety??{},i=n.safety??{};for(let a of["maxTsSuppressions","maxAnyCasts"]){let o=r[a]??0,d=i[a]??0;o!==d&&b(e,{kind:d>o?"threshold-raised":"threshold-lowered",path:`$.safety.${a}`,classification:d>o?"weakening":"strengthening",message:d>o?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:o,after:d})}for(let a of["allowInMemory","allowDisabledPeerIsolation"])Y(e,`$.safety.${a}`,r[a]===!0,i[a]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}function ct(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 Me(e,t){let n=[];P(n,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),P(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."}),P(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."}),Y(n,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let r={off:0,soft:1,"framework-soft":1,strict:2},i=e.cyclePolicy??"strict",a=t.cyclePolicy??"strict";if(i!==a){let o=r[a]===r[i]?"judgment-required":r[a]>r[i]?"strengthening":"weakening";b(n,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:o,message:"The cycle enforcement level changed.",before:i,after:a})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&b(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}),at(n,e.layers,t.layers),st(n,e.rules,t.rules),ot(n,e,t),n.sort((o,d)=>o.path.localeCompare(d.path)||o.id.localeCompare(d.id)),{schemaVersion:_e,classification:ct(n),findings:n}}function Ne(e,t){if(!e||e.schemaVersion!==_e||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=S(e.findingIds),r=S(t.findingIds);return n.length===r.length&&n.every((i,a)=>i===r[a])}function v(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 Te(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}function L(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}function H(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let r=t,i="";for(t+=1;t<e.length;t+=1){let a=e[t];if(a===n)return{value:i,offset:r,excerpt:e.slice(r,t+1)};a==="\\"&&t+1<e.length?(i+=e[t+1],t+=1):i+=a}}function E(e,t,n){return e.startsWith(t,n)&&!Te(e[n-1])&&!Te(e[n+t.length])}function lt(e,t){if(t=L(e,t+6),e[t]==="(")return H(e,L(e,t+1));let n=!1;if(E(e,"type",t)){let i=L(e,t+4);e[i]!==","&&!E(e,"from",i)&&(n=!0)}let r=De(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}function dt(e,t){t=t+6;let n=L(e,t),r=!1;if(E(e,"type",n)){let a=L(e,n+4);(e[a]==="{"||e[a]==="*")&&(r=!0)}let i=De(e,t,!1);return i&&r?{...i,typeOnly:!0}:i}function De(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(E(e,"from",t))return H(e,L(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return H(e,t);if(t>0&&(E(e,"import",t)||E(e,"export",t)))return}}function pt(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 ft(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=L(e,t+7);if(e[r]!=="(")return;r=L(e,r+1);let i=H(e,r);return i?{...i,requireCall:!0}:void 0}function ut(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(
|
|
9
|
-
`).length;
|
|
10
|
-
`).length,d={kind:"import",file:e.path,line:o,excerpt:i.excerpt},l=gt(e.path,a,t);n.push({from:e.path,specifier:a,to:l?.path??null,resolution:l?"resolved":"unresolved",fromLayer:e.layer,toLayer:l?.layer??null,evidence:d})}return{edges:n,capabilityUses:r}}function gt(e,t,n){let r=e.split("/");r.pop();for(let a of t.split("/"))a==="."||a===""||(a===".."?r.pop():r.push(a));let i=r.join("/");for(let a of[i,`${i}.ts`,`${i}.tsx`,`${i}.mts`,`${i}.cts`,`${i}/index.ts`,`${i}/index.tsx`]){let o=n.get(a);if(o)return o}}function je(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let i=G(t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});i&&n.push({ruleId:`layer-dependency:${i.from}->${i.to}`,message:i.message??`${i.from} must not depend on ${i.to}.`,edge:r,evidence:r.evidence})}return n}function he(e,t){let n=typeof e=="string"?ve(e,t):me(e,t);return{...n,policyHash:$(x(n.config))}}function mt(e){let t=he(e.baseConfig,e.baseSource??"base ark.config.json"),n=he(e.candidateConfig,e.candidateSource??"candidate ark.config.json"),r=Me(t.config,n.config),i=r.findings.filter(d=>d.classification==="weakening"||d.classification==="judgment-required").map(d=>d.id).sort(),a=i.length>0,o=a&&Ne(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:i});return{schemaVersion:r.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:r.classification,findings:r.findings,blockingFindingIds:i,requiresAcknowledgement:a,acknowledged:o,valid:!a||o}}function J(e){let t=e.files.map(l=>{let u=v(l.path);return{path:u,content:l.content,contentHash:$(l.content),layer:_(u,e.contract.config.layers)??null}}).sort((l,u)=>l.path.localeCompare(u.path)),n=new Map(t.map(l=>[l.path,l])),r=[],i=[];for(let l of t){let u=Fe(l,n);r.push(...u.edges),i.push(...u.capabilityUses)}let a=je(r,e.contract.config),o=new Map(e.contract.config.layers.map(l=>[l.name,l])),d=new Map(e.contract.config.layers.map(l=>[l.name,new Set(z(l))]));for(let l of i){let u=n.get(l.file)?.layer;if(!u)continue;let y=o.get(u),g=ue(l.symbol,y?.forbiddenGlobals??[]);if(g){a.push({ruleId:"FORBIDDEN_GLOBAL",message:`${u} must not use module "${l.symbol}" because it is the import form of forbidden global "${g}".`,symbol:l.symbol,evidence:l.evidence});continue}d.get(u)?.has(l.capability)&&a.push({ruleId:"CAPABILITY_VIOLATION",message:`${u} denies the ${l.capability} capability; found import of "${l.symbol}".`,capability:l.capability,symbol:l.symbol,evidence:l.evidence})}return{ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:$(x(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(l=>l.name),edges:r,capabilityUses:i,violations:a}}}function Ae(e){let t=new Map(e.files.map(n=>[v(n.path),n]));for(let n of e.changes){let r=v(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return J({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}function ht(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 Ve(e){let t=0,n=new Map,r=new Map,i=new Set,a=[],o=[],d=l=>{n.set(l,t),r.set(l,t),t+=1,a.push(l),i.add(l);for(let g of[...e.get(l)??[]].sort())e.has(g)&&(n.has(g)?i.has(g)&&r.set(l,Math.min(r.get(l)??0,n.get(g)??0)):(d(g),r.set(l,Math.min(r.get(l)??0,r.get(g)??0))));if(r.get(l)!==n.get(l))return;let u=[],y;do{if(y=a.pop(),y===void 0)break;i.delete(y),u.push(y)}while(y!==l);u.length>1&&o.push(u.sort())};for(let l of[...e.keys()].sort())n.has(l)||d(l);return o.sort((l,u)=>l[0].localeCompare(u[0])).map(l=>({ruleId:"CIRCULAR_DEPENDENCY",file:l[0],line:1,target:l.join(" \u2192 "),message:`Circular dependency among ${l.length} files: ${l.join(" \u2192 ")} \u2192 ${l[0]}.`,cycleKind:"value"}))}function be(e){let t=e.contentViolations.map(a=>({...a})),n=(e.warnings??[]).map(a=>({...a})),r=new Map(e.files.map(a=>[a,new Set]));for(let a of e.edges){if(a.to&&a.to!==a.from&&!a.typeOnly&&r.has(a.from)&&r.get(a.from)?.add(a.to),!a.to||!a.toLayer)continue;let o=G(e.rules,a.fromLayer,a.toLayer,{fromPath:a.from,toPath:a.to,layers:e.config.layers});if(!o)continue;let d=!!o.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}:{},...!d&&a.portProofEligible?{portProofEligible:!0}:{},...a.kind?{edgeKind:a.kind}:{},...d?{peerIsolation:!0}:{},message:o.message??(d?`${a.fromLayer} must not ${a.kind} another slice of ${a.toLayer} (${a.from} \u2192 ${a.to}). Extract shared code or use events/ports across slices.`:`${a.fromLayer} must not ${a.kind} ${a.toLayer}.`)})}let i=String(e.config.cyclePolicy??"strict").toLowerCase();if(i!=="off"){let a=Ve(r);i==="soft"||i==="framework-soft"?n.push(...a.map(o=>({...o,message:`${o.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 He(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 Ge(e){return $(x(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}function At(e){let t=J(e),n=new Map(t.ir.files.map(s=>[s.path,s])),r=[],i=new Set,a=[];for(let s of e.changes){let p=s.path.replace(/\\/g,"/"),f=v(s.path);if(!f||f===".."||f.startsWith("../")||p.startsWith("/")||/^[A-Za-z]:\//.test(p)||p.includes("\0")){a.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(i.has(f)){a.push({ruleId:"DUPLICATE_CHANGE_PATH",file:f,line:1,message:`The atomic change set contains more than one operation for ${f}.`});continue}i.add(f),"delete"in s&&s.delete&&!n.has(f)&&a.push({ruleId:"DELETE_TARGET_MISSING",file:f,line:1,message:`Cannot delete ${f} because it is not present in the supplied base tree.`}),r.push("delete"in s&&s.delete?{path:f,delete:!0}:{path:f,content:"content"in s?s.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 o=Ae({...e,changes:r}),d=new Map(o.ir.files.map(s=>[s.path,s])),l=o.ir.violations.filter(s=>s.ruleId==="CAPABILITY_VIOLATION"||s.ruleId==="FORBIDDEN_GLOBAL").map(s=>{let p=d.get(s.evidence.file)?.layer;return{ruleId:s.ruleId,file:s.evidence.file,line:s.evidence.line,target:s.symbol,...s.capability?{capability:s.capability}:{},...p?{fromLayer:p}:{},edgeKind:"import",message:s.message}}),u=be({config:e.contract.config,rules:e.contract.config.rules,files:o.ir.files.map(s=>s.path),contentViolations:l,edges:o.ir.edges.filter(s=>!!s.fromLayer).map(s=>({from:s.from,fromLayer:s.fromLayer,...s.to?{to:s.to}:{},...s.toLayer?{toLayer:s.toLayer}:{},line:s.evidence.line,kind:"import"}))}),y=r.map(s=>{let p=v(s.path),f=n.get(p),m=d.get(p);return{path:p,operation:"delete"in s&&s.delete?"delete":f?"update":"create",...f?{beforeContentHash:f.contentHash}:{},...m?{candidateContentHash:m.contentHash}:{}}}).sort((s,p)=>s.path.localeCompare(p.path)),g=[...a,...u.violations].map(s=>({...s,nextAction:He(s)})),c=e.changeMap?re({changeMap:e.changeMap,changes:y,baseDependencies:t.ir.edges.flatMap(s=>s.to?[{from:s.from,to:s.to}]:[]),candidateDependencies:o.ir.edges.flatMap(s=>s.to?[{from:s.from,to:s.to}]:[])}):void 0;return{schemaVersion:"1.0",valid:g.length===0&&(c?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:o.ir.compilerOptionsHash,baseTreeHash:Ge(t.ir.files),candidateTreeHash:Ge(o.ir.files),...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...c?{convergence:c}:{},changes:y,violations:g,warnings:u.warnings}}function I(e,t,n={}){return{ruleId:e,message:t,...n}}function bt(e){let{config:t,rules:n,files:r,manifest:i}=e,a=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(s=>typeof s!="string"))&&a.push(I("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","dynamicImportAllowlist must be an array of file globs.")),t.safety!==void 0&&(t.safety===null||typeof t.safety!="object"||Array.isArray(t.safety)))a.push(I("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let s of["maxTsSuppressions","maxAnyCasts"]){let p=t.safety[s];p!==void 0&&(!Number.isInteger(p)||p<0)&&a.push(I("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${s} must be a non-negative integer.`))}let o=Array.isArray(t.layers)?t.layers:[],d=Array.isArray(i?.architecture?.layers)?i.architecture.layers:[],l=new Set([...o.map(s=>s.name).filter(Boolean),...d.map(s=>s.name).filter(s=>!!s)]);o.length===0&&a.push(I("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let u=new Set,y=new Set;for(let s of o){if(!s.name){a.push(I("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}u.has(s.name)&&y.add(s.name),u.add(s.name),s.forbiddenGlobals!==void 0&&(!Array.isArray(s.forbiddenGlobals)||s.forbiddenGlobals.some(f=>typeof f!="string"))&&a.push(I("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${s.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:s.name}));let p=Array.isArray(s.patterns)?s.patterns:[];if(p.length===0){a.push(I("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${s.name}" has no file patterns and will never classify files.`,{layer:s.name}));continue}for(let f of p){let m;try{m=D(f)}catch(h){a.push(I("CONFIG_INVALID_LAYER_PATTERN",`Layer "${s.name}" has an invalid pattern "${f}": ${h instanceof Error?h.message:String(h)}`,{layer:s.name,pattern:f}));continue}!r.some(h=>m.test(h))&&!s.optional&&a.push(I("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${s.name}" pattern "${f}" matched no included files.`,{layer:s.name,pattern:f,failsStrict:!1}))}}for(let s of y)a.push(I("CONFIG_DUPLICATE_LAYER",`Layer "${s}" is configured more than once.`,{layer:s}));if(l.size>0)for(let s of n??[])s.from&&!l.has(s.from)&&a.push(I("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${s.from}".`,{fromLayer:s.from,toLayer:s.to})),s.to&&!l.has(s.to)&&a.push(I("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${s.to}".`,{fromLayer:s.from,toLayer:s.to}));let g=new Set;if(o.length>1)for(let s of r){let p=-1,f=[];for(let m of o)for(let h of m.patterns??[]){if(!D(h).test(s))continue;let A=Q(h);A>p?(p=A,f=[m.name]):A===p&&!f.includes(m.name)&&f.push(m.name)}f.length>1&&g.add([...f].sort().join(" + "))}g.size>0&&a.push(I("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...g].join(", ")}.`,{pairs:[...g]}));let c=r.filter(s=>!_(s,o));return c.length>0&&a.push(I("CONFIG_UNCLASSIFIED_FILES",`${c.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:c.length,samples:c.slice(0,5)})),a}export{fe as AMBIENT_CAPABILITY_ENTRIES,de as CAPABILITY_IDS,ce as SOURCE_POLICY_MESSAGES,Ze as ambientCoveredByForbiddenGlobals,re as analyzeArchitectureConvergence,Ae as analyzeChange,mt as analyzePolicyDelta,J as analyzeProject,V as capabilityForAmbientName,j as capabilityForModuleSpecifier,Je as classifyPublishFacts,bt as collectAnalysisConfigWarnings,Qe as collectCapabilityUses,oe as collectForbiddenCapabilityUses,Ve as detectArchitectureCycles,z as effectiveCapabilityDeny,be as evaluateArchitectureGraph,ht as explainViolation,se as extractSemanticDependencies,ue as forbiddenGlobalForModuleSpecifier,Ke as loadArchitectureChangeMap,he as loadContract,$e as looksLikeArkIntent,Xe as lowerForbiddenGlobal,q as loweredLayerCoverage,At as preflightChange};
|
|
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(s=>`- ${s.path}: ${s.message}`).join(`
|
|
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(s=>`- ${s.path}: ${s.message}`).join(`
|
|
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(s==="/"&&e[n+1]==="*"){let r=e.indexOf("*/",n+2);if(r<0)break;n=r+1;continue}if(s==="`"){n=Qt(e,n);continue}if(s==="'"||s==='"'){let r=le(e,n);r&&(n=r.offset+r.excerpt.length-1);continue}let i=s==="i"&&O(e,"import",n)?Zt(e,n):s==="e"&&O(e,"export",n)?Xt(e,n):s==="r"&&O(e,"require",n)?en(e,n):void 0;i&&(t.push(i),n=i.offset+i.excerpt.length-1)}return t}function It(e,t){let n=[],s=[];for(let i of tn(e.content)){let r=i.value;if(!r.startsWith(".")){if(i.typeOnly)continue;let g=ne(r);if(!g)continue;let h=e.content.slice(0,i.offset).split(`
|
|
9
|
+
`).length;s.push({file:e.path,symbol:r,capability:g,evidence:{kind:"import",file:e.path,line:h,excerpt:i.excerpt}});continue}let o=e.content.slice(0,i.offset).split(`
|
|
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};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/** Build the one effective policy consumed by resolved Tooling adapters. */
|
|
2
|
+
export function effectiveAnalysisConfig(config, manifest) {
|
|
3
|
+
const manifestRules = manifest?.architecture?.rules;
|
|
4
|
+
const manifestLayers = manifest?.architecture?.layers;
|
|
5
|
+
const hasManifestIntentLayers = Array.isArray(manifestLayers);
|
|
6
|
+
const prefixesByLayer = new Map(
|
|
7
|
+
hasManifestIntentLayers
|
|
8
|
+
? manifestLayers
|
|
9
|
+
.filter((layer) => layer && typeof layer.name === 'string')
|
|
10
|
+
.map((layer) => [
|
|
11
|
+
layer.name,
|
|
12
|
+
Array.isArray(layer.prefixes)
|
|
13
|
+
? layer.prefixes.filter((prefix) => typeof prefix === 'string')
|
|
14
|
+
: [],
|
|
15
|
+
])
|
|
16
|
+
: []
|
|
17
|
+
);
|
|
18
|
+
return {
|
|
19
|
+
...config,
|
|
20
|
+
layers: config.layers.map((layer) =>
|
|
21
|
+
hasManifestIntentLayers
|
|
22
|
+
? { ...layer, intentPrefixes: prefixesByLayer.get(layer.name) ?? [] }
|
|
23
|
+
: { ...layer }
|
|
24
|
+
),
|
|
25
|
+
rules: Array.isArray(manifestRules) ? manifestRules : config.rules,
|
|
26
|
+
};
|
|
27
|
+
}
|