arkgate 3.7.0 → 3.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/CHANGELOG.md +76 -1145
  2. package/README.md +59 -19
  3. package/bin/ark-check-runtime.mjs +1598 -0
  4. package/bin/ark-check.mjs +32 -1565
  5. package/bin/ark-mcp-runtime.mjs +1976 -0
  6. package/bin/ark-mcp.mjs +84 -1495
  7. package/bin/ark-shared.mjs +34 -38
  8. package/bin/ark.mjs +33 -66
  9. package/bin/lib/adapter-contract.mjs +161 -9
  10. package/bin/lib/agent-gates.mjs +1 -0
  11. package/bin/lib/analysis-completeness.mjs +28 -0
  12. package/bin/lib/analysis-engine.mjs +8 -8
  13. package/bin/lib/analysis-policy.mjs +27 -0
  14. package/bin/lib/architecture-scan.mjs +70 -357
  15. package/bin/lib/auto-patch.mjs +76 -8
  16. package/bin/lib/ci-and-commands.mjs +1 -1
  17. package/bin/lib/codex-home.mjs +43 -16
  18. package/bin/lib/design-delta.mjs +4 -0
  19. package/bin/lib/doctor-advisories.mjs +4 -3
  20. package/bin/lib/doctor-plan.mjs +40 -41
  21. package/bin/lib/enforcement-state.mjs +2 -0
  22. package/bin/lib/github-enforcement.mjs +443 -0
  23. package/bin/lib/hook-templates.mjs +12 -148
  24. package/bin/lib/html-report-advisories.mjs +1 -1
  25. package/bin/lib/html-report-depth.mjs +9 -0
  26. package/bin/lib/html-report.mjs +5 -5
  27. package/bin/lib/install-migrate.mjs +83 -79
  28. package/bin/lib/managed-upgrade.mjs +622 -0
  29. package/bin/lib/mcp-adoption.mjs +3 -1
  30. package/bin/lib/parse-health.mjs +6 -5
  31. package/bin/lib/port-proof.mjs +2 -2
  32. package/bin/lib/prepare-change.mjs +68 -38
  33. package/bin/lib/prepare-write.mjs +7 -1
  34. package/bin/lib/resident-doctor-client.mjs +55 -0
  35. package/bin/lib/resident-hook.mjs +247 -0
  36. package/bin/lib/resolved-candidate-facts.mjs +1160 -0
  37. package/bin/lib/scan-files.mjs +19 -6
  38. package/bin/lib/snippet-analysis.mjs +119 -0
  39. package/bin/lib/source-policy.mjs +24 -0
  40. package/bin/lib/typescript-host.mjs +15 -18
  41. package/bin/lib/unavailable-analysis.mjs +76 -0
  42. package/bin/lib/upgrade-command.mjs +115 -0
  43. package/bin/lib/weakest-link.mjs +21 -179
  44. package/bin/lib/write-path-capabilities.mjs +167 -16
  45. package/bin/lib/write-path-detect.mjs +3 -2
  46. package/dist/eslint/index.cjs +3 -3
  47. package/dist/eslint/index.d.ts +3 -0
  48. package/dist/eslint/index.js +3 -3
  49. package/dist/index.cjs +7 -7
  50. package/dist/index.d.ts +1073 -141
  51. package/dist/index.js +7 -7
  52. package/docs/agent-guide.md +103 -59
  53. package/docs/ai-gates.md +97 -16
  54. package/docs/demos/01-write-gate-self-correction.md +2 -2
  55. package/docs/enthusiast/README.md +10 -10
  56. package/docs/enthusiast/how-to-gallery-starter.md +2 -2
  57. package/docs/enthusiast/reference-commands.md +18 -1
  58. package/docs/enthusiast/tutorial-first-project.md +2 -2
  59. package/docs/package-surface.md +98 -12
  60. package/docs/typescript-support.md +109 -37
  61. package/package.json +32 -4
  62. package/schemas/ark.analysis-result.schema.json +159 -2
  63. package/schemas/ark.design-delta.schema.json +1 -0
  64. package/schemas/ark.enforcement-state.schema.json +84 -0
  65. package/schemas/ark.resolved-candidate-facts.schema.json +1 -0
  66. package/server.json +2 -2
  67. package/templates/skills/ark-explore.md +5 -5
  68. package/templates/skills/ark-fix.md +1 -1
  69. package/templates/skills/ark-runtime.md +15 -8
  70. package/templates/skills/ark-upgrade.md +122 -182
  71. package/bin/lib/ai-velocity.mjs +0 -293
  72. package/bin/lib/graph-cycles.mjs +0 -6
  73. package/bin/lib/safety-diagnostics.mjs +0 -284
  74. package/bin/lib/ts-resolve.mjs +0 -228
  75. package/dist/configTypes-DAPvBqK6.d.cts +0 -61
  76. package/dist/eslint/index.d.cts +0 -146
  77. 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(r=>`- ${r.path}: ${r.message}`).join(`
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(r=>`- ${r.path}: ${r.message}`).join(`
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(r==="/"&&e[n+1]==="*"){let a=e.indexOf("*/",n+2);if(a<0)break;n=a+1;continue}if(r==="`"){n=pt(e,n);continue}if(r==="'"||r==='"'){let a=H(e,n);a&&(n=a.offset+a.excerpt.length-1);continue}let i=r==="i"&&E(e,"import",n)?lt(e,n):r==="e"&&E(e,"export",n)?dt(e,n):r==="r"&&E(e,"require",n)?ft(e,n):void 0;i&&(t.push(i),n=i.offset+i.excerpt.length-1)}return t}function Fe(e,t){let n=[],r=[];for(let i of ut(e.content)){let a=i.value;if(i.requireCall&&a.startsWith("."))continue;if(!a.startsWith(".")){if(i.typeOnly)continue;let u=j(a);if(!u)continue;let y=e.content.slice(0,i.offset).split(`
9
- `).length;r.push({file:e.path,symbol:a,capability:u,evidence:{kind:"import",file:e.path,line:y,excerpt:i.excerpt}});continue}let o=e.content.slice(0,i.offset).split(`
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
+ var It="1.0",ze=["network","filesystem","clock","randomness","environment","process","persistence"];function S(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}function R(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(R).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${R(t[n])}`).join(",")}}`}function H(e,t){let n=R(e),s=R(t);return n<s?-1:n>s?1:0}function O(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}function be(e){let t={schemaVersion:"1.0",include:O(e.include??[]),exclude:O(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:O(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:O(n.patterns??[]),exclude:O(n.exclude??[]),forbiddenGlobals:O(n.forbiddenGlobals??[]),intentPrefixes:O(n.intentPrefixes??[]),capabilityDeny:O(n.capabilities?.deny??[]),pure:n.pure===!0})).sort(H),safety:{maxTsSuppressions:e.safety?.maxTsSuppressions??0,maxAnyCasts:e.safety?.maxAnyCasts??0,allowInMemory:e.safety?.allowInMemory===!0,allowDisabledPeerIsolation:e.safety?.allowDisabledPeerIsolation===!0}};return S(R(t))}function Rt(e){let t=e.completenessReasons.map(m=>({code:m.code,message:m.message,...m.file?{file:m.file}:{}})).sort(H),n=e.files.map(m=>({...m,typeOnlyExportNames:O(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:O(m.namedBindings)}:{}})).sort(H),r=e.capabilityUses.map(m=>({...m})).sort(H),i=e.ambientUses.map(m=>({...m})).sort(H),o=e.publishCalls.map(m=>({...m})).sort(H),p=e.intentReferences.map(m=>({...m})).sort(H),f=e.safetyUses.map(m=>({...m})).sort(H),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=S(R(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:r,ambientUses:i,publishCalls:o,intentReferences:p,safetyUses:f}}function Ke(e){let t=Rt(e);return{...t,factsHash:S(R(t))}}function Ae(e){return Ke(We(P(e,"$"),!1))}function P(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}function T(e,t,n){let s=new Set(t),r=Object.keys(e).find(i=>!s.has(i));if(r)throw new Error(`${n}.${r} is not part of schema 1.0.`)}function v(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 z(e,t,n){if(e[t]!==void 0)return v(e,t,n)}function L(e,t,n){let s=v(e,t,n),r=s.replace(/\\/g,"/");if(!r||r.startsWith("/")||/^[A-Za-z]:\//.test(r)||/[\u0000-\u001f\u007f]/.test(r))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let i=[];for(let p of r.split("/"))if(!(!p||p==="."))if(p===".."){if(i.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);i.pop()}else i.push(p);let o=i.join("/");if(!o||o!==s)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return o}function k(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}function Ye(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 K(e,t,n){let s=Ye(e,t,n);if(s===0)throw new Error(`${n}.${t} must be a positive integer.`);return s}function D(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 r=e[t];if(typeof r!="string"||!n.includes(r))throw new Error(`${s}.${t} must be one of ${n.join(", ")}.`);return r}function Be(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 Et(e,t,n){let s=new Set;for(let r of e){let i=t(r);if(s.has(i))throw new Error(`${n} must not contain duplicate facts (${i}).`);s.add(i)}}function We(e,t){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"],"$"),r=D(e,"completenessReasons","$").map((c,d)=>{let u=`$.completenessReasons[${d}]`,y=P(c,u);T(y,["code","message","file"],u);let b=y.file===void 0?void 0:L(y,"file",u);return{code:v(y,"code",u),message:v(y,"message",u),...b?{file:b}:{}}});if(s==="complete"&&r.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(s!=="complete"&&r.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let i=D(e,"files","$").map((c,d)=>{let u=`$.files[${d}]`,y=P(c,u);return T(y,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],u),{path:L(y,"path",u),contentHash:v(y,"contentHash",u),parseStatus:M(y,"parseStatus",["parsed","invalid"],u),parseDiagnosticCount:Ye(y,"parseDiagnosticCount",u),exportsOnlyTypes:k(y,"exportsOnlyTypes",u),typeOnlyExportNames:Be(y.typeOnlyExportNames,`${u}.typeOnlyExportNames`),hasTopLevelSideEffects:k(y,"hasTopLevelSideEffects",u)}}),o=D(e,"dependencies","$").map((c,d)=>{let u=`$.dependencies[${d}]`,y=P(c,u);T(y,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],u);let b=z(y,"specifier",u),A=z(y,"target",u),I=M(y,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],u);if(I==="resolved-project"&&!A)throw new Error(`${u}.target is required for resolved-project dependencies.`);if(I!=="resolved-project"&&A)throw new Error(`${u}.target is only allowed for resolved-project dependencies.`);if(I!=="dynamic"&&!b)throw new Error(`${u}.specifier is required unless resolution is dynamic.`);return{from:L(y,"from",u),...b?{specifier:b}:{},kind:M(y,"kind",["import","export","dynamic-import","require"],u),typeOnly:k(y,"typeOnly",u),line:K(y,"line",u),resolution:I,...A?{target:L(y,"target",u)}:{},...y.namedBindings!==void 0?{namedBindings:Be(y.namedBindings,`${u}.namedBindings`)}:{},...y.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:k(y,"targetTypeOnlyExports",u)}:{},...y.sourcePureTypeModule!==void 0?{sourcePureTypeModule:k(y,"sourcePureTypeModule",u)}:{},...y.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:k(y,"namedBindingsTypeOnly",u)}:{},...y.portProofEligible!==void 0?{portProofEligible:k(y,"portProofEligible",u)}:{}}}),p=D(e,"capabilityUses","$").map((c,d)=>{let u=`$.capabilityUses[${d}]`,y=P(c,u);return T(y,["file","line","symbol","capability","source"],u),{file:L(y,"file",u),line:K(y,"line",u),symbol:v(y,"symbol",u),capability:M(y,"capability",ze,u),source:M(y,"source",["ambient-global","import-based"],u)}}),f=D(e,"ambientUses","$").map((c,d)=>{let u=`$.ambientUses[${d}]`,y=P(c,u);return T(y,["file","line","symbol"],u),{file:L(y,"file",u),line:K(y,"line",u),symbol:v(y,"symbol",u)}}),g=D(e,"publishCalls","$").map((c,d)=>{let u=`$.publishCalls[${d}]`,y=P(c,u);T(y,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],u);let b=z(y,"rawIntentName",u),A=z(y,"sourceIntent",u);return{file:L(y,"file",u),line:K(y,"line",u),...b?{rawIntentName:b}:{},objectHasIntent:k(y,"objectHasIntent",u),arkPublishCandidate:k(y,"arkPublishCandidate",u),hasSource:k(y,"hasSource",u),...A?{sourceIntent:A}:{}}}),h=D(e,"intentReferences","$").map((c,d)=>{let u=`$.intentReferences[${d}]`,y=P(c,u);return T(y,["file","line","intent"],u),{file:L(y,"file",u),line:K(y,"line",u),intent:v(y,"intent",u)}}),m=D(e,"safetyUses","$").map((c,d)=>{let u=`$.safetyUses[${d}]`,y=P(c,u);T(y,["file","line","kind","symbol"],u);let b=z(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:L(y,"file",u),line:K(y,"line",u),kind:A,...b?{symbol:b}:{}}});Et(i,c=>c.path,"$.files");let a=new Set(i.map(c=>c.path));for(let c of i){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"&&i.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=z(e,"projectPackageName","$");return{schemaVersion:n,completeness:s,completenessReasons:r,resolverIdentity:v(e,"resolverIdentity","$"),compilerIdentity:v(e,"compilerIdentity","$"),compilerOptionsHash:v(e,"compilerOptionsHash","$"),tsconfigHash:v(e,"tsconfigHash","$"),evidenceRequirementsHash:v(e,"evidenceRequirementsHash","$"),...l?{projectPackageName:l}:{},files:i,dependencies:o,capabilityUses:p,ambientUses:f,publishCalls:g,intentReferences:h,safetyUses:m}}function W(e){let t=P(e,"$"),n=v(t,"factsHash","$"),s=v(t,"candidateTreeHash","$"),r=Ke(We(t,!0));if(r.factsHash!==n)throw new Error(`$.factsHash does not match the canonical payload (${r.factsHash}).`);if(s!==r.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${r.candidateTreeHash}).`);return r}var C={type:"string",minLength:1},Y={type:"integer",minimum:1},_={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},vt={$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:C,message:C,file:_}}},resolverIdentity:C,compilerIdentity:C,compilerOptionsHash:C,tsconfigHash:C,candidateTreeHash:C,evidenceRequirementsHash:C,projectPackageName:C,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:_,contentHash:C,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:C},hasTopLevelSideEffects:{type:"boolean"}},allOf:[{if:{properties:{parseStatus:{const:"parsed"}}},then:{properties:{parseDiagnosticCount:{const:0}}}},{if:{properties:{parseStatus:{const:"invalid"}}},then:{properties:{parseDiagnosticCount:{minimum:1}}}}]}},dependencies:{type:"array",items:{type:"object",additionalProperties:!1,required:["from","kind","typeOnly","line","resolution"],properties:{from:_,specifier:C,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:Y,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:_,namedBindings:{type:"array",items:C},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"}},allOf:[{if:{properties:{resolution:{const:"resolved-project"}}},then:{required:["target"]},else:{not:{required:["target"]}}},{if:{properties:{resolution:{const:"dynamic"}}},else:{required:["specifier"]}}]}},capabilityUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol","capability","source"],properties:{file:_,line:Y,symbol:C,capability:{enum:ze},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:_,line:Y,symbol:C}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:_,line:Y,rawIntentName:C,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:C}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:_,line:Y,intent:C}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:_,line:Y,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:C},allOf:[{if:{properties:{kind:{const:"in-memory-store"}}},then:{required:["symbol"]},else:{not:{required:["symbol"]}}}]}},factsHash:C},allOf:[{if:{properties:{completeness:{const:"complete"}}},then:{properties:{completenessReasons:{maxItems:0},files:{items:{properties:{parseStatus:{const:"parsed"}}}}}}},{if:{properties:{completeness:{enum:["partial","unavailable"]}}},then:{properties:{completenessReasons:{minItems:1}}}}]};var Ie=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),le=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Ee=Object.freeze(Object.keys(le).sort()),Ce=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"}),Re=Object.freeze({process:Object.freeze(["process","node:process"])});function te(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=Ce[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let s=e.slice(0,n),r=Ce[s];if(r)return r;let i=e.indexOf("/",n+1);return i<0?null:Ce[e.slice(0,i)]??null}function ne(e,t){for(let n of t)if(Re[n]?.includes(e))return n;return null}function se(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let s=t.slice(0,n).join("."),r=le[s];if(r)return r}return null}function J(e){if(e?.pure===!0)return[...Ie].sort();let n=(e?.capabilities?.deny??[]).filter(s=>Ie.includes(s));return[...new Set(n)].sort()}function ve(e,t){if(t.length===0)return!1;let n=new Set(t),s=e.split(".");for(let r=s.length;r>=1;r-=1)if(n.has(s.slice(0,r).join(".")))return!0;return!1}function ce(e){let t=new Set,n=new Set,s=Object.keys(le);for(let r of e?.forbiddenGlobals??[]){let i=s.filter(o=>o===r||o.startsWith(`${r}.`));if(i.length===0)n.add(r);else for(let o of i)t.add(`ambient:${o}`);for(let o of Re[r]??[])t.add(`import-exact:${o}`)}for(let r of J(e)){if(t.add(`import:${r}`),r==="process")for(let i of Re.process)t.add(`import-exact:${i}`);for(let i of s)se(i)===r&&t.add(`ambient:${i}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}function St(e){let t=new Set,n=se(e);n&&t.add(n);for(let[s,r]of Object.entries(le))(s===e||s.startsWith(`${e}.`))&&t.add(r);return[...t].sort()}var Je=new Map;function Xe(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function Se(e){let t="";for(let n=0;n<e.length;n+=1){let s=e[n];if(s==="\\"&&n+1<e.length){let r=e[n+1];if("*?{}[],".includes(r)||r==="\\"){t+="\\"+r,n+=1;continue}t+="/";continue}t+=s}return t}function wt(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 U(e){let t=Je.get(e);if(t)return t;let n=Se(e),s=wt(n),r="",i=0;for(let p=0;p<n.length;p+=1){let f=n[p];f==="\\"&&p+1<n.length?(r+=Xe(n[p+1]),p+=1):f==="*"?n[p+1]==="*"?n[p+2]==="/"?(r+="(?:.*/)?",p+=2):(r+=".*",p+=1):r+="[^/]*":f==="?"?r+="[^/]":f==="{"&&s?(r+="(?:",i+=1):f==="}"&&s&&i>0?(r+=")",i-=1):f===","&&s&&i>0?r+="|":r+=Xe(f)}let o=new RegExp(`^${r}$`);return Je.set(e,o),o}function we(e){let t=Se(String(e)),s=t.split("*")[0].split("/").filter(Boolean).length,r=t.replace(/\*/g,"").length;return s*1e4+r}function F(e,t){let n=String(e).split(/[/\\]/).join("/"),s,r=-1;for(let i of t??[])if(!(i.exclude??[]).some(o=>U(o).test(n))){for(let o of i.patterns??[])if(U(o).test(n)){let p=we(o);p>r&&(r=p,s=i.name)}}return s}function Ze(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),s=new Set(t.map(r=>String(r).toLowerCase()));for(let r=0;r<n.length-1;r+=1)if(s.has(n[r].toLowerCase()))return`${n[r].toLowerCase()}/${n[r+1].toLowerCase()}`}function xt(e){let t=new Set;for(let n of e??[]){let r=Se(String(n)).split("/").filter(Boolean);for(let i=0;i<r.length;i+=1){let o=r[i];if((o==="**"||o==="*")&&i>0){let p=r[i-1];p&&!p.includes("*")&&!p.includes("{")&&!p.includes("}")&&t.add(p)}}}return[...t]}function $t(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(r=>typeof r=="string"&&r.length>0);let s=(n??[]).find(r=>r.name===t);return xt(s?.patterns)}function X(e,t,n,s){for(let r of e??[])if(!(r.from!==t||r.to!==n)&&r.allowed===!1){if(r.peerIsolation){let i=s?.fromPath,o=s?.toPath;if(!i||!o)continue;let p=$t(r,t,s?.layers);if(p.length===0)continue;let f=Ze(i,p),g=Ze(o,p);if(!f||!g)continue;if(f!==g)return r;continue}if(t!==n)return r}}var xe={RAW_EVENT_PUBLISH:"Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts and tooling.",PUBLISH_MISSING_SOURCE:"Strict Ark publish calls must include metadata.source."},$e=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 ke(e,t){return t.flatMap((s,r)=>(s.prefixes??s.intentPrefixes??[]).map(i=>({layer:s.name,layerIndex:r,prefix:i.endsWith(".")?i:`${i}.`}))).filter(({prefix:s})=>e.startsWith(s)).sort((s,r)=>r.prefix.length-s.prefix.length||s.layerIndex-r.layerIndex)[0]?.layer}function Qe(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function Oe(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&Qe(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:xe.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:xe.PUBLISH_MISSING_SOURCE}),t}function w(e,t,n={}){return{ruleId:e,message:t,...n}}function Pe(e){let{config:t,rules:n,files:s,manifest:r}=e,i=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(l=>typeof l!="string"))&&i.push(w("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","dynamicImportAllowlist must be an array of file globs.")),t.safety!==void 0&&(t.safety===null||typeof t.safety!="object"||Array.isArray(t.safety)))i.push(w("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let l of["maxTsSuppressions","maxAnyCasts"]){let c=t.safety[l];c!==void 0&&(!Number.isInteger(c)||c<0)&&i.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(r?.architecture?.layers)?r.architecture.layers:[],f=new Set([...o.map(l=>l.name).filter(Boolean),...p.map(l=>l.name).filter(l=>!!l)]);o.length===0&&i.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){i.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"))&&i.push(w("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${l.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:l.name}));let c=Array.isArray(l.patterns)?l.patterns:[];if(c.length===0){i.push(w("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${l.name}" has no file patterns and will never classify files.`,{layer:l.name}));continue}for(let d of c){let u;try{u=U(d)}catch(y){i.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&&i.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)i.push(w("CONFIG_DUPLICATE_LAYER",`Layer "${l}" is configured more than once.`,{layer:l}));if(f.size>0)for(let l of n??[])l.from&&!f.has(l.from)&&i.push(w("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${l.from}".`,{fromLayer:l.from,toLayer:l.to})),l.to&&!f.has(l.to)&&i.push(w("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${l.to}".`,{fromLayer:l.from,toLayer:l.to}));let 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(!U(y).test(l))continue;let b=we(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&&i.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=>!F(l,o));return a.length>0&&i.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)})),i}function et(e){let t=0,n=new Map,s=new Map,r=new Set,i=[],o=[],p=f=>{n.set(f,t),s.set(f,t),t+=1,i.push(f),r.add(f);for(let m of[...e.get(f)??[]].sort())e.has(m)&&(n.has(m)?r.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=i.pop(),h===void 0)break;r.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 ie(e){let t=e.contentViolations.map(i=>({...i})),n=(e.warnings??[]).map(i=>({...i})),s=new Map(e.files.map(i=>[i,new Set]));for(let i of e.edges){if(i.to&&i.to!==i.from&&!i.typeOnly&&s.has(i.from)&&s.get(i.from)?.add(i.to),!i.to||!i.fromLayer||!i.toLayer)continue;let o=X(e.rules,i.fromLayer,i.toLayer,{fromPath:i.from,toPath:i.to,layers:e.config.layers});if(!o)continue;let p=!!o.peerIsolation;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:i.from,line:i.line,fromLayer:i.fromLayer,toLayer:i.toLayer,target:i.to,...i.typeOnly?{typeOnly:!0}:{},...i.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...i.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...i.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!p&&i.portProofEligible?{portProofEligible:!0}:{},...i.kind?{edgeKind:i.kind}:{},...p?{peerIsolation:!0}:{},message:o.message??(p?`${i.fromLayer} must not ${i.kind} another slice of ${i.toLayer} (${i.from} \u2192 ${i.to}). Extract shared code or use events/ports across slices.`:`${i.fromLayer} must not ${i.kind} ${i.toLayer}.`)})}let r=String(e.config.cyclePolicy??"strict").toLowerCase();if(r!=="off"){let i=et(s);r==="soft"||r==="framework-soft"?n.push(...i.map(o=>({...o,message:`${o.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...i)}return{violations:t,warnings:n,safety:e.safety}}function kt(e,t){return t.some(n=>{try{return U(n).test(e)}catch{return!1}})}function Ot(e,t){let n=e.contract.config.safety??{},s=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,r=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,i=e.contract.config.dynamicImportAllowlist??[],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")&&!kt(d.file,i)).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:r}},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>r){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 (${r}).`})}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 Pt(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,s)=>s.length-n.length)[0]}function tt(e,t){let n=t.config.layers.filter(s=>(s.intentPrefixes??[]).length>0);return ke(e,n.length>0?n:$e.map(s=>({name:s.layer,prefixes:s.prefixes})))}function Tt(e,t,n){let s=[],r=new Map(e.contract.config.layers.map(i=>[i.name,i]));for(let i of t.ambientUses){let o=n.get(i.file);!o||!Pt(i.symbol,r.get(o)?.forbiddenGlobals??[])||s.push({ruleId:"FORBIDDEN_GLOBAL",file:i.file,line:i.line,fromLayer:o,target:i.symbol,message:`${o} must not use the ambient global "${i.symbol}".`})}for(let i of t.capabilityUses){let o=n.get(i.file);if(!o)continue;let p=r.get(o),f=p?.forbiddenGlobals??[],g=i.source==="import-based"?t.dependencies.find(h=>h.from===i.file&&h.line===i.line&&h.specifier===i.symbol&&!h.typeOnly)?.kind:void 0;if(!(i.source==="ambient-global"&&ve(i.symbol,f))){if(i.source==="import-based"){let h=ne(i.symbol,f);if(h){s.push({ruleId:"FORBIDDEN_GLOBAL",file:i.file,line:i.line,fromLayer:o,target:i.symbol,...g?{edgeKind:g}:{},message:`${o} must not use module "${i.symbol}" because it is the import form of forbidden global "${h}".`});continue}}J(p).includes(i.capability)&&s.push({ruleId:"CAPABILITY_VIOLATION",file:i.file,line:i.line,fromLayer:o,target:i.symbol,capability:i.capability,...g?{edgeKind:g}:{},message:i.source==="import-based"?`${o} denies the ${i.capability} capability; found import of "${i.symbol}".`:`${o} denies the ${i.capability} capability; found ambient "${i.symbol}".`})}}for(let i of t.publishCalls){let o=n.get(i.file);if(!o)continue;for(let f of Oe({publishCall:!0,rawIntentName:i.rawIntentName,objectHasIntent:i.objectHasIntent,arkPublishCandidate:i.arkPublishCandidate,hasSource:i.hasSource}))s.push({ruleId:f.ruleId,file:i.file,line:i.line,...f.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:o}:{},message:f.message});if(!i.sourceIntent)continue;let p=tt(i.sourceIntent,e.contract);!p||p===o||s.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:i.file,line:i.line,fromLayer:o,toLayer:p,target:i.sourceIntent,message:`Publish source "${i.sourceIntent}" resolves to ${p}, but the publishing file is classified as ${o}.`})}for(let i of t.intentReferences){let o=n.get(i.file);if(!o)continue;let p=tt(i.intent,e.contract);if(!p)continue;let f=X(e.contract.config.rules,o,p);f&&s.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:i.file,line:i.line,fromLayer:o,toLayer:p,target:i.intent,message:f.message??`${o} must not reference ${p} intent ${i.intent}.`})}return s}function Te(e){let{facts:t}=e,n=be(e.contract.config),s=t.evidenceRequirementsHash===n,r=s?t.completeness:"unavailable",i=s?t.completenessReasons:[...t.completenessReasons,{code:"EVIDENCE_REQUIREMENTS_MISMATCH",message:"Resolved facts were collected for different policy-controlled evidence requirements."}].sort((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:F(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)??F(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=Pe({config:e.contract.config,rules:e.contract.config.rules,files:o.map(c=>c.path)}),h=Ot(e,t),m=ie({config:e.contract.config,rules:e.contract.config.rules,files:o.filter(c=>c.layer).map(c=>c.path),contentViolations:Tt(e,t,p),edges:f,warnings:[...g,...h.warnings],safety:h.report}),a=r==="complete"&&m.violations.length===0,l=a&&m.warnings.every(c=>c.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:r,completenessReasons:i,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 de(e){return Te({contract:e.contract,facts:W(e.facts)})}var Le="1.0";var pe=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 _e(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Fe(e,t,n,s){for(let r of Object.keys(e))t.includes(r)||s.push({path:`${n}.${r}`,message:"unknown field"})}function G(e,t,n,s){let r=e[t];if(typeof r=="string"&&r.length>0)return r;s.push({path:`${n}.${t}`,message:"must be a non-empty string"})}function Lt(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let r of t.split("/"))if(!(!r||r==="."))if(r===".."){if(n.length===0)return;n.pop()}else n.push(r);let s=n.join("/");return s&&s===t?s:void 0}function _t(e,t,n="architecture change map"){let s=[];if(!_e(e))throw new pe(n,[{path:"$",message:"must be an object"}]);Fe(e,["$schema","schemaVersion","files","dependencies"],"$",s);let r=G(e,"$schema","$",s),i=G(e,"schemaVersion","$",s);i&&i!==Le&&s.push({path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(i)}; expected ${Le}`});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(!_e(c)){s.push({path:u,message:"must be an object"});return}Fe(c,["path","operation","layer"],u,s);let y=G(c,"path",u,s),b=G(c,"operation",u,s),A=G(c,"layer",u,s),I=y?Lt(y):void 0;y&&!I&&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)}`}),I&&f.has(I)&&s.push({path:`${u}.path`,message:`duplicates planned path ${I}`}),I&&f.add(I);let he=I?F(I,t.layers):void 0;I&&A&&o.has(A)&&he!==A&&s.push({path:`${u}.layer`,message:he?`${I} resolves to ${he}, not ${A}`:`${I} is not assigned to an architecture layer`}),I&&b&&["create","update","delete"].includes(b)&&A&&p.push({path:I,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(!_e(c)){s.push({path:u,message:"must be an object"});return}Fe(c,["from","to"],u,s);let y=G(c,"from",u,s),b=G(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 pe(n,s);let l={$schema:r,schemaVersion:Le,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:S(R(l))}}function x(e){return`${e.from}->${e.to}`}function re(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 ae(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])),r=new Map(e.changeMap.map.dependencies.map(a=>[x(a),a])),i=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[...r.values()].sort((l,c)=>x(l).localeCompare(x(c)))){if(o.has(x(a))){t.push(re("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(re("contradictory",a,`${a.from} -> ${a.to} was planned, but the candidate contains the reverse edge.`))):t.push(re("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)))i.has(a)||r.has(a)||p.has(a)||!f.has(l.from)&&!f.has(l.to)||t.push({...re("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[...i].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({...re("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 Z(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function it(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function nt(e,t){if(e.isImportDeclaration(t)){let s=t.importClause;if(!s)return!1;if(s.isTypeOnly)return!0;let r=s.namedBindings;return!!(r&&e.isNamedImports(r)&&r.elements.length>0&&r.elements.every(i=>i.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(s=>s.isTypeOnly))}function rt(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},s=e.createCompilerHost(n,!0);return s.getSourceFile=r=>r===t.fileName?t:void 0,s.fileExists=r=>r===t.fileName,s.readFile=r=>r===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,s).getTypeChecker()}function Ne(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function De(e,t,n,s){let r=s.parent&&e.isShorthandPropertyAssignment(s.parent)&&s.parent.name===s,i;try{i=r?t.getShorthandAssignmentValueSymbol(s.parent):Ne(t,s)}catch{i=void 0}return!!i?.declarations?.some(o=>o.getSourceFile().fileName===n.fileName)}function Me(e,t){let n,s=[],r=(o,p,f,g=!1)=>s.push({specifier:f,kind:p,line:it(t,o),typeOnly:g,unresolved:f===void 0,node:o}),i=o=>{if(e.isImportDeclaration(o))r(o,"import",Z(e,o.moduleSpecifier),nt(e,o));else if(e.isExportDeclaration(o)&&o.moduleSpecifier)r(o,"export",Z(e,o.moduleSpecifier),nt(e,o));else if(e.isImportEqualsDeclaration(o)&&e.isExternalModuleReference(o.moduleReference))r(o,"require",Z(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"&&!De(e,n??(n=rt(e,t)),t,o.expression);(p||g)&&r(o,g?"require":"dynamic-import",Z(e,o.arguments[0]))}e.forEachChild(o,i)};return i(t),s}function Ft(e,t){let n=[],s=t;for(;e.isPropertyAccessExpression(s)||e.isElementAccessExpression(s);){if(e.isPropertyAccessExpression(s))n.unshift(s.name.text);else{let r=Z(e,s.argumentExpression);if(r===void 0)return;n.unshift(r)}s=s.expression}if(e.isIdentifier(s))return n.unshift(s.text),{root:s,segments:n}}function Nt(e,t){let n=t.parent;return e.isPropertyAccessExpression(n)||e.isElementAccessExpression(n)?!1:e.isExpressionNode(t)&&!e.isInTypeQuery(t)||e.isShorthandPropertyAssignment(n)&&n.name===t}function st(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let s=n.length;s>=1;s-=1){let r=n.slice(0,s).join(".");if(e.has(r))return r}}function He(e,t,n){if(n.length===0)return[];let s=new Set(n),r=rt(e,t),i=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=Ft(e,a);if(!l)return;let c=Ne(r,l.root),d=c?i.get(c):void 0;return d?[...d,...l.segments.slice(1)]:De(e,r,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=Ne(r,l.name);!c||!d||i.set(d,c)}let f=[],g=new Set,h=(a,l)=>{let c=it(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?st(s,c):void 0;d&&h(d,a)}else e.isIdentifier(a)&&s.has(a.text)&&Nt(e,a)&&!De(e,r,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?Z(e,d.propertyName)??d.propertyName.text:d.name.text,y=st(s,[...c,u]);y&&h(y,a.initializer)}}e.forEachChild(a,m)};return m(t),f}function Dt(e,t,n){let s=[];for(let r of n?.dependencies??Me(e,t)){if(r.typeOnly||!r.specifier)continue;let i=te(r.specifier);i&&s.push({capability:i,symbol:r.specifier,line:r.line,source:"import-based"})}for(let r of n?.ambientUses??He(e,t,Ee)){let i=se(r.name);i&&s.push({capability:i,symbol:r.name,line:r.line,source:"ambient-global"})}return s.sort((r,i)=>r.line-i.line||r.capability.localeCompare(i.capability)||r.symbol.localeCompare(i.symbol))}var Ve="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",at=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Mt=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Ht(){let e=[];for(let t of at)for(let n of at)t===n||Mt.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var lt=Ht();var j={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},ot={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Ve,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:Ve,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:"1.0",default:"1.0"},name:{type:"string",minLength:1},include:{...j,minItems:1,default:["src"]},exclude:{...j,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:lt,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...j,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...j,minItems:1},exclude:j,intentPrefixes:j,description:{type:"string",minLength:1},forbiddenGlobals:j,capabilities:{type:"object",additionalProperties:!1,properties:{deny:{type:"array",uniqueItems:!0,items:{type:"string",enum:["network","filesystem","clock","randomness","environment","process","persistence"]}}}},pure:{type:"boolean"},mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...j,minItems:1}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}}}},ee=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 ct(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function je(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function Q(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function jt(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function fe(e,t,n,s,r){if(t.$ref){let i=jt(t.$ref,s);if(!i){r.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}fe(e,i,n,s,r);return}if(t.const!==void 0&&!Object.is(e,t.const)){r.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(i=>Object.is(i,e))){r.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!ct(e)){r.push({path:n,message:`must be an object; received ${Q(e)}`});return}let i=t.properties??{};for(let o of t.required??[])e[o]===void 0&&r.push({path:je(n,o),message:"is required"});if(t.additionalProperties===!1)for(let o of Object.keys(e))o in i||r.push({path:je(n,o),message:"unknown field"});for(let[o,p]of Object.entries(i))e[o]!==void 0&&fe(e[o],p,je(n,o),s,r);return}if(t.type==="array"){if(!Array.isArray(e)){r.push({path:n,message:`must be an array; received ${Q(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&r.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let i=e.map(o=>JSON.stringify(o));new Set(i).size!==i.length&&r.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((i,o)=>fe(i,t.items,`${n}[${o}]`,s,r));return}if(t.type==="string"){if(typeof e!="string"){r.push({path:n,message:`must be a string; received ${Q(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&r.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&r.push({path:n,message:`must be a boolean; received ${Q(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){r.push({path:n,message:`must be an integer; received ${Q(e)}`});return}t.minimum!==void 0&&e<t.minimum&&r.push({path:n,message:`must be at least ${t.minimum}`})}}function Vt(e){return{...e,$schema:e.$schema===void 0?Ve: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?lt.map(t=>({...t})):e.rules}}function Ut(e,t="ark.config.json"){if(!ct(e))throw new ee(t,[{path:"$",message:`must be an object; received ${Q(e)}`}]);let n=e.schemaVersion===void 0?"unversioned":null;if(e.schemaVersion!==void 0&&e.schemaVersion!=="1.0")throw new ee(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.0`}]);return{candidate:Vt(e),migratedFrom:n}}function Ue(e,t="ark.config.json"){let{candidate:n,migratedFrom:s}=Ut(e,t),r=[];if(fe(n,ot,"$",ot,r),r.length>0)throw new ee(t,r);return{config:n,migratedFrom:s}}function dt(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(s){throw new ee(t,[{path:"$",message:`invalid JSON: ${s instanceof Error?s.message:String(s)}`}])}return Ue(n,t)}var pt="1.0";function E(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 $(e){return[...new Set(e??[])].sort()}function q(e,t,n,s,r){let i=$(n),o=$(s),p=new Set(i),f=new Set(o),g=o.filter(m=>!p.has(m)),h=i.filter(m=>!f.has(m));g.length===0&&h.length===0||(g.length>0&&E(e,{kind:"added",path:t,classification:r.added,message:r.addedMessage,before:i,after:o}),h.length>0&&E(e,{kind:"removed",path:t,classification:r.removed,message:r.removedMessage,before:i,after:o}))}function ue(e,t,n,s,r,i,o){if(n===s)return;E(e,{kind:s?"enabled":"disabled",path:t,classification:s?r:r==="strengthening"?"weakening":"strengthening",message:s?i:o,before:n,after:s})}function me(e,t){let n=new Map,s=new Set;for(let r of e){let i=t(r);n.has(i)?s.add(i):n.set(i,r)}return{values:n,duplicates:[...s].sort()}}function Gt(e,t,n){let s=me(t,i=>i.name),r=me(n,i=>i.name);(s.duplicates.length>0||r.duplicates.length>0)&&E(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:s.duplicates,after:r.duplicates});for(let i of[...new Set([...s.values.keys(),...r.values.keys()])].sort()){let o=s.values.get(i),p=r.values.get(i),f=`$.layers[${i}]`;if(!o&&p){E(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){E(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;q(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."}),q(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=ce(o),h=ce(p);q(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."}),q(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)."}),$(o.intentPrefixes).join("\0")!==$(p.intentPrefixes).join("\0")&&E(e,{kind:"intent-prefixes-changed",path:`${f}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:$(o.intentPrefixes),after:$(p.intentPrefixes)}),ue(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."),ue(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 qt(e,t,n){let s=o=>`${o.from}->${o.to}`,r=me(t,s),i=me(n,s);(r.duplicates.length>0||i.duplicates.length>0)&&E(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:r.duplicates,after:i.duplicates});for(let o of[...new Set([...r.values.keys(),...i.values.keys()])].sort()){let p=r.values.get(o),f=i.values.get(o),g=`$.rules[${o}]`;if(!p&&f){f.allowed===!1&&E(e,{kind:"deny-added",path:g,classification:"strengthening",message:"A denied dependency edge was added.",after:f});continue}if(p&&!f){p.allowed===!1&&E(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&&E(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;E(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})}$(p.sliceFolders).join("\0")!==$(f.sliceFolders).join("\0")&&E(e,{kind:"slice-folders-changed",path:`${g}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:$(p.sliceFolders),after:$(f.sliceFolders)})}}function Bt(e,t,n){let s=t.safety??{},r=n.safety??{};for(let i of["maxTsSuppressions","maxAnyCasts"]){let o=s[i]??0,p=r[i]??0;o!==p&&E(e,{kind:p>o?"threshold-raised":"threshold-lowered",path:`$.safety.${i}`,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 i of["allowInMemory","allowDisabledPeerIsolation"])ue(e,`$.safety.${i}`,s[i]===!0,r[i]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}function zt(e){return e.some(t=>t.classification==="weakening")?"weakening":e.some(t=>t.classification==="judgment-required")?"judgment-required":e.some(t=>t.classification==="strengthening")?"strengthening":"neutral"}function ft(e,t){let n=[];q(n,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),q(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."}),q(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."}),ue(n,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let s={off:0,soft:1,"framework-soft":1,strict:2},r=e.cyclePolicy??"strict",i=t.cyclePolicy??"strict";if(r!==i){let o=s[i]===s[r]?"judgment-required":s[i]>s[r]?"strengthening":"weakening";E(n,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:o,message:"The cycle enforcement level changed.",before:r,after:i})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&E(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}),Gt(n,e.layers,t.layers),qt(n,e.rules,t.rules),Bt(n,e,t),n.sort((o,p)=>o.path.localeCompare(p.path)||o.id.localeCompare(p.id)),{schemaVersion:pt,classification:zt(n),findings:n}}function ut(e,t){if(!e||e.schemaVersion!==pt||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(r=>typeof r!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=$(e.findingIds),s=$(t.findingIds);return n.length===s.length&&n.every((r,i)=>r===s[i])}function B(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 mt(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}function V(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}function oe(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let s=t,r="";for(t+=1;t<e.length;t+=1){let i=e[t];if(i===n)return{value:r,offset:s,excerpt:e.slice(s,t+1)};i==="\\"&&t+1<e.length?(r+=e[t+1],t+=1):r+=i}}function N(e,t,n){return e.startsWith(t,n)&&!mt(e[n-1])&&!mt(e[n+t.length])}function Kt(e,t){if(t=V(e,t+6),e[t]==="(")return oe(e,V(e,t+1));let n=!1;if(N(e,"type",t)){let r=V(e,t+4);e[r]!==","&&!N(e,"from",r)&&(n=!0)}let s=yt(e,t,!0);return s&&n?{...s,typeOnly:!0}:s}function Yt(e,t){t=t+6;let n=V(e,t),s=!1;if(N(e,"type",n)){let i=V(e,n+4);(e[i]==="{"||e[i]==="*")&&(s=!0)}let r=yt(e,t,!1);return r&&s?{...r,typeOnly:!0}:r}function yt(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(N(e,"from",t))return oe(e,V(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return oe(e,t);if(t>0&&(N(e,"import",t)||N(e,"export",t)))return}}function Wt(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 Jt(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let s=V(e,t+7);if(e[s]!=="(")return;s=V(e,s+1);let r=oe(e,s);return r?{...r,requireCall:!0}:void 0}function Xt(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 i=e.indexOf("*/",n+2);if(i<0)break;n=i+1;continue}if(s==="`"){n=Wt(e,n);continue}if(s==="'"||s==='"'){let i=oe(e,n);i&&(n=i.offset+i.excerpt.length-1);continue}let r=s==="i"&&N(e,"import",n)?Kt(e,n):s==="e"&&N(e,"export",n)?Yt(e,n):s==="r"&&N(e,"require",n)?Jt(e,n):void 0;r&&(t.push(r),n=r.offset+r.excerpt.length-1)}return t}function gt(e,t){let n=[],s=[];for(let r of Xt(e.content)){let i=r.value;if(r.requireCall&&i.startsWith("."))continue;if(!i.startsWith(".")){if(r.typeOnly)continue;let g=te(i);if(!g)continue;let h=e.content.slice(0,r.offset).split(`
9
+ `).length;s.push({file:e.path,symbol:i,capability:g,evidence:{kind:"import",file:e.path,line:h,excerpt:r.excerpt}});continue}let o=e.content.slice(0,r.offset).split(`
10
+ `).length,p={kind:"import",file:e.path,line:o,excerpt:r.excerpt},f=Zt(e.path,i,t);n.push({from:e.path,specifier:i,to:f?.path??null,resolution:f?"resolved":"unresolved",fromLayer:e.layer,toLayer:f?.layer??null,evidence:p})}return{edges:n,capabilityUses:s}}function Zt(e,t,n){let s=e.split("/");s.pop();for(let i of t.split("/"))i==="."||i===""||(i===".."?s.pop():s.push(i));let r=s.join("/");for(let i of[r,`${r}.ts`,`${r}.tsx`,`${r}.mts`,`${r}.cts`,`${r}/index.ts`,`${r}/index.tsx`]){let o=n.get(i);if(o)return o}}function ht(e,t){let n=[];for(let s of e){if(!s.to||!s.fromLayer||!s.toLayer)continue;let r=X(t.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:t.layers});r&&n.push({ruleId:`layer-dependency:${r.from}->${r.to}`,message:r.message??`${r.from} must not depend on ${r.to}.`,edge:s,evidence:s.evidence})}return n}var en={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 Ge(e,t){let n=typeof e=="string"?dt(e,t):Ue(e,t);return{...n,policyHash:S(R(n.config))}}function tn(e){let t=Ge(e.baseConfig,e.baseSource??"base ark.config.json"),n=Ge(e.candidateConfig,e.candidateSource??"candidate ark.config.json"),s=ft(t.config,n.config),r=s.findings.filter(p=>p.classification==="weakening"||p.classification==="judgment-required").map(p=>p.id).sort(),i=r.length>0,o=i&&ut(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:r});return{schemaVersion:s.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:s.classification,findings:s.findings,blockingFindingIds:r,requiresAcknowledgement:i,acknowledged:o,valid:!i||o}}function ye(e){let t=e.files.map(m=>{let a=B(m.path);return{path:a,content:m.content,contentHash:S(m.content),layer:F(a,e.contract.config.layers)??null}}).sort((m,a)=>m.path.localeCompare(a.path)),n=new Map(t.map(m=>[m.path,m])),s=[],r=[];for(let m of t){let a=gt(m,n);s.push(...a.edges),r.push(...a.capabilityUses)}let i=ht(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(J(m))]));for(let m of r){let a=n.get(m.file)?.layer;if(!a)continue;let l=o.get(a),c=ne(m.symbol,l?.forbiddenGlobals??[]);if(c){i.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)&&i.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"?[]:[{...en}],h={schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:S(R(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(m=>m.name),edges:s,capabilityUses:r,violations:i};return{mode:"lexical-compatibility",completeness:f,completenessReasons:g,valid:f==="complete"&&i.length===0,ir:h}}function qe(e){let t=new Map(e.files.map(n=>[B(n.path),n]));for(let n of e.changes){let s=B(n.path);"delete"in n&&n.delete?t.delete(s):"content"in n&&t.set(s,{path:s,content:n.content})}return ye({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}function nn(e){let t=`${e.evidence.file}:${e.evidence.line}`;if(!e.edge)return`${e.ruleId} at ${t}: ${e.message}`;let n=e.edge.to??e.edge.specifier;return`${e.ruleId} at ${t}: ${e.edge.from} imports ${n}. ${e.message}`}function ge(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return e.typeOnly||e.targetTypeOnlyExports||e.namedBindingsTypeOnly?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":e.peerIsolation?"Extract the shared dependency to a shared layer, then preflight again.":`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, then preflight again.`;case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, then preflight again.`;case"CAPABILITY_VIOLATION":return`Define a ${String(e.capability??"capability")} port in ${e.fromLayer??"the walled layer"}, bind the implementation outside it, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";default:return`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}function bt(e){return S(R(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}function sn(e){let t=ye(e),n=new Map(t.ir.files.map(l=>[l.path,l])),s=[],r=new Set,i=[];for(let l of e.changes){let c=l.path.replace(/\\/g,"/"),d=B(l.path);if(!d||d===".."||d.startsWith("../")||c.startsWith("/")||/^[A-Za-z]:\//.test(c)||c.includes("\0")){i.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(r.has(d)){i.push({ruleId:"DUPLICATE_CHANGE_PATH",file:d,line:1,message:`The atomic change set contains more than one operation for ${d}.`});continue}r.add(d),"delete"in l&&l.delete&&!n.has(d)&&i.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&&i.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let o=qe({...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=ie({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=B(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=[...i,...g.violations].map(l=>({...l,nextAction:ge(l)})),a=e.changeMap?ae({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:bt(t.ir.files),candidateTreeHash:bt(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 rn(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let r of t.split("/"))if(!(!r||r==="."))if(r===".."){if(n.length===0)return;n.pop()}else n.push(r);let s=n.join("/");return s&&s===t?s:void 0}function an(e,t){return[["resolverIdentity",e.resolverIdentity,t.resolverIdentity],["compilerIdentity",e.compilerIdentity,t.compilerIdentity],["evidenceRequirementsHash",e.evidenceRequirementsHash,t.evidenceRequirementsHash],["projectPackageName",e.projectPackageName??"",t.projectPackageName??""]].filter(([,s,r])=>s!==r).map(([s,r,i])=>({ruleId:"FACTS_IDENTITY_MISMATCH",file:"<change-set>",line:1,field:s,before:r,candidate:i,message:`Base and candidate facts must use the same ${s}.`}))}function on(e,t,n,s){let r=n.get(t),i=s.get(t);return{path:t,operation:"delete"in e&&e.delete?"delete":r?"update":"create",...r?{beforeContentHash:r.contentHash}:{},...i?{candidateContentHash:i.contentHash}:{}}}function ln(e){let t=W(e.baseFacts),n=W(e.candidateFacts),s=de({contract:e.contract,facts:t}),r=de({contract:e.contract,facts:n}),i=new Map(t.files.map(a=>[a.path,a])),o=new Map(n.files.map(a=>[a.path,a])),p=an(t,n),f=new Map,g=[];for(let a of e.changes){let l=rn(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=i.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=S(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(on(a,l,i,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([...i.keys(),...o.keys()])){if(f.has(a))continue;let l=i.get(a),c=o.get(a);l&&c&&R(l)===R(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?ae({changeMap:e.changeMap,changes:g,baseDependencies:s.ir.edges.flatMap(a=>a.to?[{from:a.from,to:a.to}]:[]),candidateDependencies:r.ir.edges.flatMap(a=>a.to?[{from:a.from,to:a.to}]:[])}):void 0,m=[...p,...r.ir.violations].map(a=>({...a,nextAction:ge(a)}));return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:s.completeness==="complete"&&r.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:r.completeness,baseCompletenessReasons:s.completenessReasons,candidateCompletenessReasons:r.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:r.ir.warnings}}var At=new WeakSet;function Ct(e){if(!e||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Object.values(e))Ct(t);return Object.freeze(e)}function Cs(e){let t=Ct(Ae(e));return At.add(t),t}function Is(e){if(!At.has(e.facts))throw new Error("Trusted resolved analysis requires immutable in-process canonical facts.");return Te(e)}export{Ee as AMBIENT_CAPABILITY_ENTRIES,Ie as CAPABILITY_IDS,$e as DEFAULT_INTENT_PREFIXES,vt as RESOLVED_CANDIDATE_FACTS_SCHEMA,It as RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,xe as SOURCE_POLICY_MESSAGES,ve as ambientCoveredByForbiddenGlobals,ae as analyzeArchitectureConvergence,qe as analyzeChange,tn as analyzePolicyDelta,ye as analyzeProject,de as analyzeResolvedProject,Is as analyzeTrustedResolvedProject,se as capabilityForAmbientName,te as capabilityForModuleSpecifier,Oe as classifyPublishFacts,Pe as collectAnalysisConfigWarnings,Dt as collectCapabilityUses,He as collectForbiddenCapabilityUses,Ae as createResolvedCandidateFacts,Cs as createTrustedResolvedCandidateFacts,et as detectArchitectureCycles,S as deterministicHash,J as effectiveCapabilityDeny,ie as evaluateArchitectureGraph,nn as explainViolation,Me as extractSemanticDependencies,ne as forbiddenGlobalForModuleSpecifier,_t as loadArchitectureChangeMap,Ge as loadContract,W as loadResolvedCandidateFacts,Qe as looksLikeArkIntent,St as lowerForbiddenGlobal,ce as loweredLayerCoverage,sn as preflightChange,ln as preflightResolvedChange,ke as resolveIntentLayer,be as resolvedFactsEvidenceRequirementsHash,R 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
+ }