arkgate 3.9.2 → 4.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/CHANGELOG.md +125 -0
  2. package/README.md +16 -4
  3. package/bin/ark-check-runtime.mjs +75 -3
  4. package/bin/ark-mcp-runtime.mjs +94 -0
  5. package/bin/lib/adapter-contract.mjs +14 -1
  6. package/bin/lib/analysis-engine.mjs +8 -8
  7. package/bin/lib/architecture-scan.mjs +35 -2
  8. package/bin/lib/arkrule-file-hints.mjs +71 -0
  9. package/bin/lib/arkrules-contract.mjs +382 -0
  10. package/bin/lib/arkrules-sensors.mjs +411 -0
  11. package/bin/lib/config-contract.mjs +85 -6
  12. package/bin/lib/doctor-advisories.mjs +14 -1
  13. package/bin/lib/doctor-plan.mjs +21 -0
  14. package/bin/lib/effective-contract-load.mjs +116 -0
  15. package/bin/lib/field-install.mjs +104 -0
  16. package/bin/lib/graph-blind.mjs +20 -1
  17. package/bin/lib/html-report-advisories.mjs +12 -5
  18. package/bin/lib/install-migrate.mjs +20 -2
  19. package/bin/lib/invariant-coverage-io.mjs +157 -0
  20. package/bin/lib/invariant-coverage.mjs +127 -0
  21. package/bin/lib/managed-upgrade.mjs +1 -1
  22. package/bin/lib/policy-delta-io.mjs +33 -0
  23. package/bin/lib/presets.mjs +241 -1
  24. package/bin/lib/remediation.mjs +28 -0
  25. package/bin/lib/resolved-candidate-facts.mjs +14 -1
  26. package/bin/lib/rules-inventory.mjs +144 -0
  27. package/bin/lib/rules-under-contract.mjs +320 -0
  28. package/bin/lib/start-preview.mjs +24 -7
  29. package/bin/lib/upgrade-command.mjs +373 -16
  30. package/dist/{configTypes-DAPvBqK6.d.ts → configTypes-CC0FEXoF.d.ts} +16 -3
  31. package/dist/eslint/index.cjs +2 -2
  32. package/dist/eslint/index.d.ts +1 -1
  33. package/dist/eslint/index.js +2 -2
  34. package/dist/index.cjs +14 -7
  35. package/dist/index.d.ts +615 -20
  36. package/dist/index.js +13 -6
  37. package/docs/README.md +5 -3
  38. package/docs/agent-guide.md +7 -3
  39. package/docs/ai-gates.md +6 -1
  40. package/docs/brownfield-adoption.md +22 -0
  41. package/docs/configuration.md +53 -4
  42. package/docs/develop.md +8 -2
  43. package/docs/enthusiast/README.md +11 -0
  44. package/docs/package-surface.md +13 -10
  45. package/docs/product-voice.md +11 -2
  46. package/docs/use.md +11 -0
  47. package/package.json +4 -17
  48. package/schemas/ark.analysis-result.schema.json +9 -1
  49. package/schemas/ark.arkrules.schema.json +141 -0
  50. package/schemas/ark.config.schema.json +10 -2
  51. package/schemas/ark.resolved-candidate-facts.schema.json +1 -1
  52. package/server.json +2 -2
  53. package/templates/arkrules/ApplicationOrchestration.json +14 -0
  54. package/templates/arkrules/DomainModel.json +32 -0
  55. package/templates/arkrules/PersistenceAdapters.json +14 -0
  56. package/templates/arkrules/PresentationAdapters.json +14 -0
  57. package/templates/skills/ark-adopt.md +28 -1
  58. package/templates/skills/ark-architect.md +23 -0
  59. package/templates/skills/ark-autopilot.md +27 -1
  60. package/templates/skills/ark-contract.md +27 -1
  61. package/templates/skills/ark-coverage.md +23 -0
  62. package/templates/skills/ark-explain.md +39 -3
  63. package/templates/skills/ark-explore.md +26 -1
  64. package/templates/skills/ark-fix.md +23 -0
  65. package/templates/skills/ark-loop.md +23 -0
  66. package/templates/skills/ark-place.md +26 -0
  67. package/templates/skills/ark-runtime.md +4 -0
  68. package/templates/skills/ark-think.md +24 -1
  69. package/templates/skills/ark-upgrade.md +80 -11
  70. package/compat/nestjs.cjs +0 -2
  71. package/compat/nestjs.d.ts +0 -2
  72. package/compat/nestjs.js +0 -1
  73. package/compat/runtime.cjs +0 -2
  74. package/compat/runtime.d.ts +0 -2
  75. package/compat/runtime.js +0 -1
package/dist/index.js CHANGED
@@ -1,7 +1,14 @@
1
- var jt="3.9.2";var Gt="1.3";function I(e){return typeof e=="string"&&e.length>0?e:void 0}function ct(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function Ut(e,t,n){return e==="LAYER_IMPORT_VIOLATION"?t.typeOnly||n.targetTypeOnlyExports===!0||n.namedBindingsTypeOnly===!0?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":n.peerIsolation===!0?"Extract the shared dependency to a shared layer, then preflight again.":`Define a port in ${t.fromLayer??"the source layer"}, inject the ${t.toLayer??"outer-layer"} implementation, then preflight again.`:e==="FORBIDDEN_GLOBAL"?`Inject ${t.target??"the capability"} through a port, then preflight again.`:e==="CAPABILITY_VIOLATION"?`Define a ${I(n.capability)??"capability"} port in ${t.fromLayer??"the walled layer"}, bind the implementation outside it, then preflight again.`:e==="CIRCULAR_DEPENDENCY"?"Extract the shared dependency into a third module, then preflight again.":e==="RAW_EVENT_PUBLISH"?"Publish through a registered intent creator, then run Ark again.":e==="PUBLISH_MISSING_SOURCE"?"Add metadata.source to the publish call, then run Ark again.":`Resolve ${e} without weakening ark.config.json, then run Ark again.`}function He(e,t="error"){let n=I(e.ruleId)??I(e.code)??"ARK_UNKNOWN",s=e.severity==="warning"?"warning":t,r={...I(e.target)?{target:I(e.target)}:{},...I(e.fromLayer)?{fromLayer:I(e.fromLayer)}:{},...I(e.toLayer)?{toLayer:I(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{},...typeof e.targetTypeOnlyExports=="boolean"?{targetTypeOnlyExports:e.targetTypeOnlyExports}:{},...typeof e.sourcePureTypeModule=="boolean"?{sourcePureTypeModule:e.sourcePureTypeModule}:{},...typeof e.namedBindingsTypeOnly=="boolean"?{namedBindingsTypeOnly:e.namedBindingsTypeOnly}:{},...typeof e.portProofEligible=="boolean"?{portProofEligible:e.portProofEligible}:{},...typeof e.peerIsolation=="boolean"?{peerIsolation:e.peerIsolation}:{},...I(e.capability)?{capability:I(e.capability)}:{},...I(e.edgeKind)?{edgeKind:I(e.edgeKind)}:{}};return{ruleId:n,severity:s,message:I(e.message)??n,location:{file:I(e.file)??"<unknown>",line:ct(e.line,1),column:ct(e.column,1)},evidence:r,nextAction:I(e.nextAction)??Ut(n,r,e)}}function Bt(e){let t=e.completeness??"complete",n=e.mode??"lexical-compatibility";if(t==="complete"&&(e.completenessReasons?.length??0)>0)throw new Error("completenessReasons must be empty when completeness is complete.");let s=t==="complete"?[]:e.completenessReasons&&e.completenessReasons.length>0?e.completenessReasons.map(c=>({code:I(c.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:I(c.message)??`Analysis ${t}: required evidence is incomplete.`,...I(c.file)?{file:I(c.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],r={...I(e.policyHash)?{policyHash:I(e.policyHash)}:{},...I(e.resolverIdentity)?{resolverIdentity:I(e.resolverIdentity)}:{},...I(e.factsHash)?{factsHash:I(e.factsHash)}:{},...I(e.candidateTreeHash)?{candidateTreeHash:I(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let c of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!r[c])throw new Error(`${c} is required for resolved ${t} adapter evidence.`)}let i=[...(e.violations??[]).map(c=>He(c,"error")),...(e.warnings??[]).map(c=>He(c,"warning"))],a={schemaVersion:"1.3",completenessReasons:s,diagnostics:i};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...a,mode:n,valid:!1,completeness:t,...r};let c={policyHash:r.policyHash,resolverIdentity:r.resolverIdentity,factsHash:r.factsHash,candidateTreeHash:r.candidateTreeHash};return t==="complete"?{...a,mode:n,valid:e.valid,completeness:t,...c}:{...a,mode:n,valid:!1,completeness:t,...c}}return t==="complete"?{...a,mode:n,valid:e.valid,completeness:t,...r}:{...a,mode:n,valid:!1,completeness:t,...r}}var qt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","mode","valid","completeness","completenessReasons","diagnostics"],allOf:[{if:{properties:{completeness:{enum:["partial","unavailable"]}},required:["completeness"]},then:{properties:{valid:{const:!1}}}},{if:{properties:{mode:{const:"resolved-candidate-facts"},completeness:{enum:["complete","partial"]}},required:["mode","completeness"]},then:{required:["policyHash","resolverIdentity","factsHash","candidateTreeHash"]}},{if:{properties:{completeness:{const:"complete"}},required:["completeness"]},then:{properties:{completenessReasons:{maxItems:0}}},else:{properties:{completenessReasons:{minItems:1}}}}],properties:{schemaVersion:{const:"1.3"},mode:{enum:["lexical-compatibility","resolved-candidate-facts"]},valid:{type:"boolean"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:{type:"string",minLength:1},message:{type:"string",minLength:1},file:{type:"string",minLength:1}}}},policyHash:{type:"string",minLength:1},resolverIdentity:{type:"string",minLength:1},factsHash:{type:"string",minLength:1},candidateTreeHash:{type:"string",minLength:1},diagnostics:{type:"array",items:{type:"object",additionalProperties:!1,required:["ruleId","severity","message","location","evidence"],properties:{ruleId:{type:"string",minLength:1},severity:{enum:["error","warning"]},message:{type:"string",minLength:1},location:{type:"object",additionalProperties:!1,required:["file","line","column"],properties:{file:{type:"string",minLength:1},line:{type:"integer",minimum:1},column:{type:"integer",minimum:1}}},evidence:{type:"object",additionalProperties:!1,properties:{target:{type:"string"},fromLayer:{type:"string"},toLayer:{type:"string"},typeOnly:{type:"boolean"},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"},peerIsolation:{type:"boolean"},capability:{type:"string",minLength:1},edgeKind:{type:"string",minLength:1}}},nextAction:{type:"string",minLength:1}}}}}};var je=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),Ue=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Be=Object.freeze(Object.keys(Ue).sort()),Ve=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"}),Ge=Object.freeze({process:Object.freeze(["process","node:process"])});function pe(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=Ve[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let s=e.slice(0,n),r=Ve[s];if(r)return r;let i=e.indexOf("/",n+1);return i<0?null:Ve[e.slice(0,i)]??null}function V(e,t){for(let n of t)if(Ge[n]?.includes(e))return n;return null}function Re(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let s=t.slice(0,n).join("."),r=Ue[s];if(r)return r}return null}function X(e){if(e?.pure===!0)return[...je].sort();let n=(e?.capabilities?.deny??[]).filter(s=>je.includes(s));return[...new Set(n)].sort()}function fe(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 ve(e){let t=new Set,n=new Set,s=Object.keys(Ue);for(let r of e?.forbiddenGlobals??[]){let i=s.filter(a=>a===r||a.startsWith(`${r}.`));if(i.length===0)n.add(r);else for(let a of i)t.add(`ambient:${a}`);for(let a of Ge[r]??[])t.add(`import-exact:${a}`)}for(let r of X(e)){if(t.add(`import:${r}`),r==="process")for(let i of Ge.process)t.add(`import-exact:${i}`);for(let i of s)Re(i)===r&&t.add(`ambient:${i}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}var dt=new Map;function pt(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function qe(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 zt(e){let t=0;for(let n=0;n<e.length;n+=1){let s=e[n];if(s==="\\"){n+=1;continue}if(s==="{")t+=1;else if(s==="}"&&(t-=1,t<0))return!1}return t===0}function K(e){let t=dt.get(e);if(t)return t;let n=qe(e),s=zt(n),r="",i=0;for(let c=0;c<n.length;c+=1){let f=n[c];f==="\\"&&c+1<n.length?(r+=pt(n[c+1]),c+=1):f==="*"?n[c+1]==="*"?n[c+2]==="/"?(r+="(?:.*/)?",c+=2):(r+=".*",c+=1):r+="[^/]*":f==="?"?r+="[^/]":f==="{"&&s?(r+="(?:",i+=1):f==="}"&&s&&i>0?(r+=")",i-=1):f===","&&s&&i>0?r+="|":r+=pt(f)}let a=new RegExp(`^${r}$`);return dt.set(e,a),a}function ze(e){let t=qe(String(e)),s=t.split("*")[0].split("/").filter(Boolean).length,r=t.replace(/\*/g,"").length;return s*1e4+r}function j(e,t){let n=String(e).split(/[/\\]/).join("/"),s,r=-1;for(let i of t??[])if(!(i.exclude??[]).some(a=>K(a).test(n))){for(let a of i.patterns??[])if(K(a).test(n)){let c=ze(a);c>r&&(r=c,s=i.name)}}return s}function ft(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 Kt(e){let t=new Set;for(let n of e??[]){let r=qe(String(n)).split("/").filter(Boolean);for(let i=0;i<r.length;i+=1){let a=r[i];if((a==="**"||a==="*")&&i>0){let c=r[i-1];c&&!c.includes("*")&&!c.includes("{")&&!c.includes("}")&&t.add(c)}}}return[...t]}function Yt(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 Kt(s?.patterns)}function N(e,t,n,s){for(let r of e??[])if(!(r.from!==t||r.to!==n)&&r.allowed===!1){if(r.peerIsolation){let i=s?.fromPath,a=s?.toPath;if(!i||!a)return r;let c=Yt(r,t,s?.layers);if(c.length===0)return r;let f=ft(i,c),A=ft(a,c);if(!f||!A||f!==A)return r;continue}if(t!==n)return r}}function Q(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function mt(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function ut(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 gt(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 Ke(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function Ye(e,t,n,s){let r=s.parent&&e.isShorthandPropertyAssignment(s.parent)&&s.parent.name===s,i;try{i=r?t.getShorthandAssignmentValueSymbol(s.parent):Ke(t,s)}catch{i=void 0}return!!i?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}function ee(e,t){let n,s=[],r=(a,c,f,A=!1)=>s.push({specifier:f,kind:c,line:mt(t,a),typeOnly:A,unresolved:f===void 0,node:a}),i=a=>{if(e.isImportDeclaration(a))r(a,"import",Q(e,a.moduleSpecifier),ut(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)r(a,"export",Q(e,a.moduleSpecifier),ut(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))r(a,"require",Q(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let c=a.expression.kind===e.SyntaxKind.ImportKeyword,A=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!Ye(e,n??(n=gt(e,t)),t,a.expression);(c||A)&&r(a,A?"require":"dynamic-import",Q(e,a.arguments[0]))}e.forEachChild(a,i)};return i(t),s}function Wt(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=Q(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 Jt(e,t){let n=t.parent;return e.isPropertyAccessExpression(n)||e.isElementAccessExpression(n)?!1:e.isExpressionNode(t)&&!e.isInTypeQuery(t)||e.isShorthandPropertyAssignment(n)&&n.name===t}function yt(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 te(e,t,n){if(n.length===0)return[];let s=new Set(n),r=gt(e,t),i=new Map,a=new Set;for(let o of t.statements)if(e.isVariableStatement(o))for(let l of o.declarationList.declarations)e.isIdentifier(l.name)&&a.add(l.name.text);let c=o=>{let l=Wt(e,o);if(!l)return;let p=Ke(r,l.root),d=p?i.get(p):void 0;return d?[...d,...l.segments.slice(1)]:Ye(e,r,t,l.root)||a.has(l.root.text)?void 0:l.segments};for(let o of t.statements)if(e.isVariableStatement(o))for(let l of o.declarationList.declarations){if(!l.initializer||!e.isIdentifier(l.name))continue;let p=c(l.initializer),d=Ke(r,l.name);!p||!d||i.set(d,p)}let f=[],A=new Set,g=(o,l)=>{let p=mt(t,l),d=`${o}:${l.getStart(t)}`;A.has(d)||(A.add(d),f.push({name:o,line:p,node:l}))},u=o=>{let l=o.parent&&(e.isPropertyAccessExpression(o.parent)||e.isElementAccessExpression(o.parent))&&o.parent.expression===o;if((e.isPropertyAccessExpression(o)||e.isElementAccessExpression(o))&&!l){let p=c(o),d=p?yt(s,p):void 0;d&&g(d,o)}else e.isIdentifier(o)&&s.has(o.text)&&Jt(e,o)&&!Ye(e,r,t,o)&&g(o.text,o);if(e.isVariableDeclaration(o)&&e.isObjectBindingPattern(o.name)&&o.initializer){let p=c(o.initializer);if(p)for(let d of o.name.elements){if(!e.isIdentifier(d.name))continue;let y=d.propertyName?Q(e,d.propertyName)??d.propertyName.text:d.name.text,h=yt(s,[...p,y]);h&&g(h,o.initializer)}}e.forEachChild(o,u)};return u(t),f}function We(e,t,n){let s=[];for(let r of n?.dependencies??ee(e,t)){if(r.typeOnly||!r.specifier)continue;let i=pe(r.specifier);i&&s.push({capability:i,symbol:r.specifier,line:r.line,source:"import-based"})}for(let r of n?.ambientUses??te(e,t,Be)){let i=Re(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 Je={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."},Ze=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 Xe(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 Y(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function ue(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&Y(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:Je.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:Je.PUBLISH_MISSING_SOURCE}),t}function v(e,t,n){return{ruleId:e,code:e,message:t,...n}}function ne(e,t){return e.slice(0,t).split(`
2
- `).length}function Zt(e){let t=[],n=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,s;for(;(s=n.exec(e))!==null;)t.push({value:s[1],index:s.index});return t}function Xt(e){let t=[],n=[{kind:"import",re:/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s*)?['"]([^'"]+)['"]/g},{kind:"export",re:/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s*['"]([^'"]+)['"]/g},{kind:"dynamic-import",re:/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g},{kind:"require",re:/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g}];for(let s of n){let r;for(;(r=s.re.exec(e))!==null;){let i=r.index+r[0].indexOf(r[1]),a=r[0],c=s.kind==="import"&&/\bimport\s+type\b/.test(a)||s.kind==="export"&&/\bexport\s+type\b/.test(a);t.push({value:r[1],index:i,kind:s.kind,typeOnly:c})}}return t.sort((s,r)=>s.index-r.index)}function Qt(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),s=[],r=i=>{e.isStringLiteralLike(i)&&s.push({value:i.text,index:i.getStart(n)}),e.forEachChild(i,r)};return r(n),s}function en(e){let t=e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);return["adapter","adapters","infra","infrastructure","persistence","repository","repositories","integration","database","db"].some(n=>t.includes(n))}function tn(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}function nn(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}function me(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function rn(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}function ht(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(s=>!e.isPropertyAssignment(s)&&!e.isShorthandPropertyAssignment(s)?!1:rn(e,s.name)===n)}function ge(e,t,n){return ht(e,t,n)!==void 0}function ye(e,t,n){let s=ht(e,t,n);return s&&e.isPropertyAssignment(s)?s.initializer:void 0}function sn(e,t){let n=ye(e,t,"metadata");return ge(e,n,"source")}function At(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?At(e,t.name):!1:!1}function an(e,t){if(!e.isCallExpression(t))return!1;let n=t.expression;return e.isPropertyAccessExpression(n)?n.name.text==="publish":e.isIdentifier(n)&&n.text==="publish"}function on(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],s=me(e,n);return s!==void 0&&Y(s)||ge(e,n,"intent")||At(e,n)}function ln(e,t){if(!e.isCallExpression(t))return!1;let[n,s,r]=t.arguments;return sn(e,n)||ge(e,s,"source")||ge(e,r,"source")}function cn(e,t){if(!e.isCallExpression(t))return;let[n,s,r]=t.arguments,i=ye(e,n,"metadata");return me(e,ye(e,i,"source"))??me(e,ye(e,s,"source"))??me(e,ye(e,r,"source"))}function dn(e,t,n,s){let r=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),i=n,a=i?.filePath,c=i?.layer,f=[],A=u=>r.getLineAndCharacterOfPosition(u.getStart(r)).line+1,g=u=>{if(an(e,u)){let o=u.arguments[0],l=me(e,o);for(let d of ue({publishCall:!0,rawIntentName:l,objectHasIntent:ge(e,o,"intent"),arkPublishCandidate:on(e,u),hasSource:ln(e,u)}))f.push(v(d.ruleId,d.message,{line:A(u),filePath:a}));let p=cn(e,u);if(s&&c&&p&&Y(p)){let d=s.resolveLayer(p);d&&d!==c&&f.push(v("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${p}" resolves to ${d}, but the target file is classified as ${c}.`,{line:A(u),filePath:a,target:p,fromLayer:c,toLayer:d}))}}e.forEachChild(u,g)};return g(r),f}function bt(e={}){let t=new Set((e.intents||[]).map(i=>typeof i=="string"?i:i.name)),n=e.forbiddenPatterns||[],s=new Set(e.infrastructureLayers??[]),r=e.enforceIntentAllowlist??t.size>0;return{validate(i,a){let c=[],f=a,A=f?.filePath,g=f?.layer,u=e.typescript,o=u?u.createSourceFile(A??"generated.ts",i,u.ScriptTarget.Latest,!0):void 0,l=o?ee(e.typescript,o):void 0,p=l?l.filter(m=>m.specifier!==void 0).map(m=>({value:m.specifier,index:m.node.getStart(o),kind:m.kind,typeOnly:m.typeOnly})):Xt(i),d=e.typescript?Qt(e.typescript,i):Zt(i);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(A))for(let m of l?.filter(({unresolved:b})=>b)??[]){let b=m.kind==="require";c.push(v(b?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${b?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:m.line,filePath:A}))}let y=g!==void 0&&(s.has(g)||nn(g)),h=g!==void 0?` If "${g}" is an infrastructure layer, mark it in ark.config.json with "mayImportInfrastructure": true (or name it with an infra token like Adapters/Persistence/Repository).`:"";for(let m of n)if(m instanceof RegExp){m.lastIndex=0;let b=m.exec(i);m.lastIndex=0,b&&c.push(v("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${m}`,{line:b.index===void 0?void 0:ne(i,b.index),filePath:A,suggestion:"Remove infrastructure imports from domain/application layers."+h}))}else i.includes(m)&&c.push(v("FORBIDDEN_SUBSTRING",`Forbidden substring: ${m}`,{line:ne(i,i.indexOf(m)),filePath:A}));for(let m of p){let b=e.resolveImportTarget?.(m.value,A)??(e.resolveImportLayer?{layer:e.resolveImportLayer(m.value,A)}:void 0),C=typeof A=="string"?e.resolveImportTarget?.(A)??(e.resolveImportLayer?{layer:g,relPath:void 0}:void 0):void 0,de=b?.layer;if(de&&g){let Ee=N(e.architectureProfile?.rules,g,de,{fromPath:C?.relPath,toPath:b?.relPath,layers:e.architectureLayers});if(Ee){if(m.typeOnly&&!Ee.peerIsolation)continue;let Me=!!Ee.peerIsolation;c.push(v("LAYER_IMPORT_VIOLATION",Ee.message??(Me?`Layer "${g}" must not import across slices into "${de}".`:`Layer "${g}" must not import "${de}".`),{line:ne(i,m.index),source:m.value,target:m.value,filePath:A,fromLayer:g,toLayer:de,suggestion:Me?"Extract shared code to a shared layer, or coordinate slices via events/ports \u2014 do not import across feature/context slices.":"Depend on a port/interface owned by an inner layer instead, or move this code to a layer allowed to make this import.",details:{importKind:m.kind,peerIsolation:Me,...m.typeOnly?{typeOnly:!0}:{}}}));continue}continue}y||m.typeOnly||!en(m.value)&&!tn(m.value)||c.push(v("FORBIDDEN_IMPORT",`Forbidden ${m.kind} target: "${m.value}".`,{line:ne(i,m.index),source:m.value,target:m.value,filePath:A,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+h,details:{importKind:m.kind}}))}if(e.policies)for(let m of e.policies){let b=m.check({source:i,context:a});if(b!==!0)if(Array.isArray(b))for(let C of b)c.push(v("POLICY_VIOLATION",C.message,{filePath:A,suggestion:`Fix violation of policy "${m.name}".`}));else b===!1?c.push(v("POLICY_VIOLATION",`Policy ${m.name} failed on generated code`)):c.push(v("POLICY_VIOLATION",b.message))}if(r&&t.size>0)for(let m of d)Y(m.value)&&!t.has(m.value)&&c.push(v("UNKNOWN_INTENT",`Unknown intent reference: "${m.value}"`,{line:ne(i,m.index),filePath:A,target:m.value,suggestion:`Register intent "${m.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&g)for(let m of d){if(!Y(m.value))continue;let b=e.architectureProfile.resolveLayer(m.value);if(!b)continue;let C=N(e.architectureProfile.rules,g,b);C&&c.push(v("LAYER_REFERENCE_VIOLATION",C.message??`Layer "${g}" must not reference "${b}" through "${m.value}".`,{line:ne(i,m.index),filePath:A,target:m.value,fromLayer:g,toLayer:b,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:C}}))}if(e.extensions)for(let m of e.extensions)try{let b=m.analyze(i,a);c.push(...b)}catch(b){c.push(v("EXTENSION_ERROR",`Extension "${m.name}" failed: ${b instanceof Error?b.message:String(b)}`))}if(e.typescript&&o&&g&&e.forbiddenGlobals?.[g]?.length)try{let m=e.forbiddenGlobals[g];c.push(...te(e.typescript,o,m).map(b=>v("FORBIDDEN_GLOBAL",`${g} must not use the ambient global "${b.name}".`,{line:b.line,filePath:A,target:b.name,fromLayer:g,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let b of l??[]){if(b.typeOnly||!b.specifier)continue;let C=V(b.specifier,m);C&&c.push(v("FORBIDDEN_GLOBAL",`${g} must not use module "${b.specifier}" because it is the import form of forbidden global "${C}".`,{line:b.line,filePath:A,source:b.specifier,target:b.specifier,fromLayer:g,details:{importKind:b.kind,forbiddenGlobal:C},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(m){c.push(v("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${m instanceof Error?m.message:String(m)}`))}if(e.typescript&&o&&g&&e.capabilityWalls?.[g]?.length)try{let m=new Set(e.capabilityWalls[g]),b=e.forbiddenGlobals?.[g]??[];for(let C of We(e.typescript,o))m.has(C.capability)&&(C.source==="ambient-global"&&fe(C.symbol,b)||C.source==="import-based"&&V(C.symbol,b)||c.push(v("CAPABILITY_VIOLATION",C.source==="import-based"?`${g} denies the ${C.capability} capability; found import of "${C.symbol}".`:`${g} denies the ${C.capability} capability; found ambient "${C.symbol}".`,{line:C.line,filePath:A,target:C.symbol,capability:C.capability,fromLayer:g,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(m){c.push(v("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${m instanceof Error?m.message:String(m)}`))}if(e.typescript)try{c.push(...dn(e.typescript,i,a,e.architectureProfile))}catch(m){c.push(v("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${m instanceof Error?m.message:String(m)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:c.length===0,violations:c}}}}var pn="1.0",xe="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",Ct=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],fn=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function un(){let e=[];for(let t of Ct)for(let n of Ct)t===n||fn.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var ke=un();var G={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},et={$schema:"https://json-schema.org/draft/2020-12/schema",$id:xe,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:xe,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:{...G,minItems:1,default:["src"]},exclude:{...G,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:ke,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...G,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:{...G,minItems:1},exclude:G,intentPrefixes:G,description:{type:"string",minLength:1},forbiddenGlobals:G,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:{...G,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}}}}},ie=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
1
+ var wn="4.0.1";var $n="1.4";function I(e){return typeof e=="string"&&e.length>0?e:void 0}function Ht(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function Pn(e,t,n){if(e==="LAYER_IMPORT_VIOLATION")return t.typeOnly||n.targetTypeOnlyExports===!0||n.namedBindingsTypeOnly===!0?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":n.peerIsolation===!0?"Extract the shared dependency to a shared layer, then preflight again.":`Define a port in ${t.fromLayer??"the source layer"}, inject the ${t.toLayer??"outer-layer"} implementation, then preflight again.`;if(e==="FORBIDDEN_GLOBAL")return`Inject ${t.target??"the capability"} through a port, then preflight again.`;if(e==="CAPABILITY_VIOLATION")return`Define a ${I(n.capability)??"capability"} port in ${t.fromLayer??"the walled layer"}, bind the implementation outside it, then preflight again.`;if(e==="CIRCULAR_DEPENDENCY")return"Extract the shared dependency into a third module, then preflight again.";if(e==="RAW_EVENT_PUBLISH")return"Publish through a registered intent creator, then run Ark again.";if(e==="PUBLISH_MISSING_SOURCE")return"Add metadata.source to the publish call, then run Ark again.";if(e==="ARKRULE_STRUCTURE"||e==="ARKRULE_INVARIANT"||e==="INVARIANT_UNCOVERED"||e.startsWith("ARKRULE_")){let s=t.arkruleSource??"arkrules/<Layer>.json";return`Fix the structure or invariant for ${t.arkruleId??"the ArkRule"} (declared in ${s}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`}return`Resolve ${e} without weakening ark.config.json, then run Ark again.`}function it(e,t="error"){let n=I(e.ruleId)??I(e.code)??"ARK_UNKNOWN",s=e.severity==="warning"?"warning":t,r={...I(e.target)?{target:I(e.target)}:{},...I(e.fromLayer)?{fromLayer:I(e.fromLayer)}:{},...I(e.toLayer)?{toLayer:I(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{},...typeof e.targetTypeOnlyExports=="boolean"?{targetTypeOnlyExports:e.targetTypeOnlyExports}:{},...typeof e.sourcePureTypeModule=="boolean"?{sourcePureTypeModule:e.sourcePureTypeModule}:{},...typeof e.namedBindingsTypeOnly=="boolean"?{namedBindingsTypeOnly:e.namedBindingsTypeOnly}:{},...typeof e.portProofEligible=="boolean"?{portProofEligible:e.portProofEligible}:{},...typeof e.peerIsolation=="boolean"?{peerIsolation:e.peerIsolation}:{},...I(e.capability)?{capability:I(e.capability)}:{},...I(e.edgeKind)?{edgeKind:I(e.edgeKind)}:{},...I(e.arkruleId)?{arkruleId:I(e.arkruleId)}:{},...I(e.arkruleSource)?{arkruleSource:I(e.arkruleSource)}:{}};return{ruleId:n,severity:s,message:I(e.message)??n,location:{file:I(e.file)??"<unknown>",line:Ht(e.line,1),column:Ht(e.column,1)},evidence:r,nextAction:I(e.nextAction)??Pn(n,r,e)}}function On(e){let t=e.completeness??"complete",n=e.mode??"lexical-compatibility";if(t==="complete"&&(e.completenessReasons?.length??0)>0)throw new Error("completenessReasons must be empty when completeness is complete.");let s=t==="complete"?[]:e.completenessReasons&&e.completenessReasons.length>0?e.completenessReasons.map(c=>({code:I(c.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:I(c.message)??`Analysis ${t}: required evidence is incomplete.`,...I(c.file)?{file:I(c.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],r={...I(e.policyHash)?{policyHash:I(e.policyHash)}:{},...I(e.resolverIdentity)?{resolverIdentity:I(e.resolverIdentity)}:{},...I(e.factsHash)?{factsHash:I(e.factsHash)}:{},...I(e.candidateTreeHash)?{candidateTreeHash:I(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let c of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!r[c])throw new Error(`${c} is required for resolved ${t} adapter evidence.`)}let i=[...(e.violations??[]).map(c=>it(c,"error")),...(e.warnings??[]).map(c=>it(c,"warning"))],a={schemaVersion:"1.4",completenessReasons:s,diagnostics:i};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...a,mode:n,valid:!1,completeness:t,...r};let c={policyHash:r.policyHash,resolverIdentity:r.resolverIdentity,factsHash:r.factsHash,candidateTreeHash:r.candidateTreeHash};return t==="complete"?{...a,mode:n,valid:e.valid,completeness:t,...c}:{...a,mode:n,valid:!1,completeness:t,...c}}return t==="complete"?{...a,mode:n,valid:e.valid,completeness:t,...r}:{...a,mode:n,valid:!1,completeness:t,...r}}var Ln={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","mode","valid","completeness","completenessReasons","diagnostics"],allOf:[{if:{properties:{completeness:{enum:["partial","unavailable"]}},required:["completeness"]},then:{properties:{valid:{const:!1}}}},{if:{properties:{mode:{const:"resolved-candidate-facts"},completeness:{enum:["complete","partial"]}},required:["mode","completeness"]},then:{required:["policyHash","resolverIdentity","factsHash","candidateTreeHash"]}},{if:{properties:{completeness:{const:"complete"}},required:["completeness"]},then:{properties:{completenessReasons:{maxItems:0}}},else:{properties:{completenessReasons:{minItems:1}}}}],properties:{schemaVersion:{const:"1.4"},mode:{enum:["lexical-compatibility","resolved-candidate-facts"]},valid:{type:"boolean"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:{type:"string",minLength:1},message:{type:"string",minLength:1},file:{type:"string",minLength:1}}}},policyHash:{type:"string",minLength:1},resolverIdentity:{type:"string",minLength:1},factsHash:{type:"string",minLength:1},candidateTreeHash:{type:"string",minLength:1},diagnostics:{type:"array",items:{type:"object",additionalProperties:!1,required:["ruleId","severity","message","location","evidence"],properties:{ruleId:{type:"string",minLength:1},severity:{enum:["error","warning"]},message:{type:"string",minLength:1},location:{type:"object",additionalProperties:!1,required:["file","line","column"],properties:{file:{type:"string",minLength:1},line:{type:"integer",minimum:1},column:{type:"integer",minimum:1}}},evidence:{type:"object",additionalProperties:!1,properties:{target:{type:"string"},fromLayer:{type:"string"},toLayer:{type:"string"},typeOnly:{type:"boolean"},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"},peerIsolation:{type:"boolean"},capability:{type:"string",minLength:1},edgeKind:{type:"string",minLength:1},arkruleId:{type:"string",minLength:1},arkruleSource:{type:"string",minLength:1}}},nextAction:{type:"string",minLength:1}}}}}};var ot=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),ct=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),dt=Object.freeze(Object.keys(ct).sort()),at=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"}),lt=Object.freeze({process:Object.freeze(["process","node:process"])});function Ie(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=at[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let s=e.slice(0,n),r=at[s];if(r)return r;let i=e.indexOf("/",n+1);return i<0?null:at[e.slice(0,i)]??null}function J(e,t){for(let n of t)if(lt[n]?.includes(e))return n;return null}function He(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let s=t.slice(0,n).join("."),r=ct[s];if(r)return r}return null}function le(e){if(e?.pure===!0)return[...ot].sort();let n=(e?.capabilities?.deny??[]).filter(s=>ot.includes(s));return[...new Set(n)].sort()}function Ce(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 Ve(e){let t=new Set,n=new Set,s=Object.keys(ct);for(let r of e?.forbiddenGlobals??[]){let i=s.filter(a=>a===r||a.startsWith(`${r}.`));if(i.length===0)n.add(r);else for(let a of i)t.add(`ambient:${a}`);for(let a of lt[r]??[])t.add(`import-exact:${a}`)}for(let r of le(e)){if(t.add(`import:${r}`),r==="process")for(let i of lt.process)t.add(`import-exact:${i}`);for(let i of s)He(i)===r&&t.add(`ambient:${i}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}var Vt=new Map;function jt(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function pt(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 _n(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 ee(e){let t=Vt.get(e);if(t)return t;let n=pt(e),s=_n(n),r="",i=0;for(let c=0;c<n.length;c+=1){let p=n[c];p==="\\"&&c+1<n.length?(r+=jt(n[c+1]),c+=1):p==="*"?n[c+1]==="*"?n[c+2]==="/"?(r+="(?:.*/)?",c+=2):(r+=".*",c+=1):r+="[^/]*":p==="?"?r+="[^/]":p==="{"&&s?(r+="(?:",i+=1):p==="}"&&s&&i>0?(r+=")",i-=1):p===","&&s&&i>0?r+="|":r+=jt(p)}let a=new RegExp(`^${r}$`);return Vt.set(e,a),a}function ut(e){let t=pt(String(e)),s=t.split("*")[0].split("/").filter(Boolean).length,r=t.replace(/\*/g,"").length;return s*1e4+r}function z(e,t){let n=String(e).split(/[/\\]/).join("/"),s,r=-1;for(let i of t??[])if(!(i.exclude??[]).some(a=>ee(a).test(n))){for(let a of i.patterns??[])if(ee(a).test(n)){let c=ut(a);c>r&&(r=c,s=i.name)}}return s}function Ut(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),s=new Set(t.map(r=>String(r).toLowerCase()));for(let r=0;r<n.length-1;r+=1)if(s.has(n[r].toLowerCase()))return`${n[r].toLowerCase()}/${n[r+1].toLowerCase()}`}function Tn(e){let t=new Set;for(let n of e??[]){let r=pt(String(n)).split("/").filter(Boolean);for(let i=0;i<r.length;i+=1){let a=r[i];if((a==="**"||a==="*")&&i>0){let c=r[i-1];c&&!c.includes("*")&&!c.includes("{")&&!c.includes("}")&&t.add(c)}}}return[...t]}function Fn(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(r=>typeof r=="string"&&r.length>0);let s=(n??[]).find(r=>r.name===t);return Tn(s?.patterns)}function K(e,t,n,s){for(let r of e??[])if(!(r.from!==t||r.to!==n)&&r.allowed===!1){if(r.peerIsolation){let i=s?.fromPath,a=s?.toPath;if(!i||!a)return r;let c=Fn(r,t,s?.layers);if(c.length===0)return r;let p=Ut(i,c),y=Ut(a,c);if(!p||!y||p!==y)return r;continue}if(t!==n)return r}}function ce(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function qt(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function Gt(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 zt(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 ft(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function yt(e,t,n,s){let r=s.parent&&e.isShorthandPropertyAssignment(s.parent)&&s.parent.name===s,i;try{i=r?t.getShorthandAssignmentValueSymbol(s.parent):ft(t,s)}catch{i=void 0}return!!i?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}function de(e,t){let n,s=[],r=(a,c,p,y=!1)=>s.push({specifier:p,kind:c,line:qt(t,a),typeOnly:y,unresolved:p===void 0,node:a}),i=a=>{if(e.isImportDeclaration(a))r(a,"import",ce(e,a.moduleSpecifier),Gt(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)r(a,"export",ce(e,a.moduleSpecifier),Gt(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))r(a,"require",ce(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let c=a.expression.kind===e.SyntaxKind.ImportKeyword,y=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!yt(e,n??(n=zt(e,t)),t,a.expression);(c||y)&&r(a,y?"require":"dynamic-import",ce(e,a.arguments[0]))}e.forEachChild(a,i)};return i(t),s}function Nn(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=ce(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 Dn(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 Bt(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 pe(e,t,n){if(n.length===0)return[];let s=new Set(n),r=zt(e,t),i=new Map,a=new Set;for(let o of t.statements)if(e.isVariableStatement(o))for(let l of o.declarationList.declarations)e.isIdentifier(l.name)&&a.add(l.name.text);let c=o=>{let l=Nn(e,o);if(!l)return;let g=ft(r,l.root),u=g?i.get(g):void 0;return u?[...u,...l.segments.slice(1)]:yt(e,r,t,l.root)||a.has(l.root.text)?void 0:l.segments};for(let o of t.statements)if(e.isVariableStatement(o))for(let l of o.declarationList.declarations){if(!l.initializer||!e.isIdentifier(l.name))continue;let g=c(l.initializer),u=ft(r,l.name);!g||!u||i.set(u,g)}let p=[],y=new Set,h=(o,l)=>{let g=qt(t,l),u=`${o}:${l.getStart(t)}`;y.has(u)||(y.add(u),p.push({name:o,line:g,node:l}))},m=o=>{let l=o.parent&&(e.isPropertyAccessExpression(o.parent)||e.isElementAccessExpression(o.parent))&&o.parent.expression===o;if((e.isPropertyAccessExpression(o)||e.isElementAccessExpression(o))&&!l){let g=c(o),u=g?Bt(s,g):void 0;u&&h(u,o)}else e.isIdentifier(o)&&s.has(o.text)&&Dn(e,o)&&!yt(e,r,t,o)&&h(o.text,o);if(e.isVariableDeclaration(o)&&e.isObjectBindingPattern(o.name)&&o.initializer){let g=c(o.initializer);if(g)for(let u of o.name.elements){if(!e.isIdentifier(u.name))continue;let b=u.propertyName?ce(e,u.propertyName)??u.propertyName.text:u.name.text,v=Bt(s,[...g,b]);v&&h(v,o.initializer)}}e.forEachChild(o,m)};return m(t),p}function mt(e,t,n){let s=[];for(let r of n?.dependencies??de(e,t)){if(r.typeOnly||!r.specifier)continue;let i=Ie(r.specifier);i&&s.push({capability:i,symbol:r.specifier,line:r.line,source:"import-based"})}for(let r of n?.ambientUses??pe(e,t,dt)){let i=He(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 gt={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."},ht=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 At(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 te(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function Ee(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&te(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:gt.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:gt.PUBLISH_MISSING_SOURCE}),t}function x(e,t,n){return{ruleId:e,code:e,message:t,...n}}function ue(e,t){return e.slice(0,t).split(`
2
+ `).length}function Mn(e){let t=[],n=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,s;for(;(s=n.exec(e))!==null;)t.push({value:s[1],index:s.index});return t}function Hn(e){let t=[],n=[{kind:"import",re:/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s*)?['"]([^'"]+)['"]/g},{kind:"export",re:/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s*['"]([^'"]+)['"]/g},{kind:"dynamic-import",re:/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g},{kind:"require",re:/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g}];for(let s of n){let r;for(;(r=s.re.exec(e))!==null;){let i=r.index+r[0].indexOf(r[1]),a=r[0],c=s.kind==="import"&&/\bimport\s+type\b/.test(a)||s.kind==="export"&&/\bexport\s+type\b/.test(a);t.push({value:r[1],index:i,kind:s.kind,typeOnly:c})}}return t.sort((s,r)=>s.index-r.index)}function Vn(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),s=[],r=i=>{e.isStringLiteralLike(i)&&s.push({value:i.text,index:i.getStart(n)}),e.forEachChild(i,r)};return r(n),s}function jn(e){let t=e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);return["adapter","adapters","infra","infrastructure","persistence","repository","repositories","integration","database","db"].some(n=>t.includes(n))}function Un(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}function Gn(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}function ke(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function Bn(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}function Kt(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(s=>!e.isPropertyAssignment(s)&&!e.isShorthandPropertyAssignment(s)?!1:Bn(e,s.name)===n)}function xe(e,t,n){return Kt(e,t,n)!==void 0}function Se(e,t,n){let s=Kt(e,t,n);return s&&e.isPropertyAssignment(s)?s.initializer:void 0}function qn(e,t){let n=Se(e,t,"metadata");return xe(e,n,"source")}function Yt(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?Yt(e,t.name):!1:!1}function zn(e,t){if(!e.isCallExpression(t))return!1;let n=t.expression;return e.isPropertyAccessExpression(n)?n.name.text==="publish":e.isIdentifier(n)&&n.text==="publish"}function Kn(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],s=ke(e,n);return s!==void 0&&te(s)||xe(e,n,"intent")||Yt(e,n)}function Yn(e,t){if(!e.isCallExpression(t))return!1;let[n,s,r]=t.arguments;return qn(e,n)||xe(e,s,"source")||xe(e,r,"source")}function Wn(e,t){if(!e.isCallExpression(t))return;let[n,s,r]=t.arguments,i=Se(e,n,"metadata");return ke(e,Se(e,i,"source"))??ke(e,Se(e,s,"source"))??ke(e,Se(e,r,"source"))}function Jn(e,t,n,s){let r=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),i=n,a=i?.filePath,c=i?.layer,p=[],y=m=>r.getLineAndCharacterOfPosition(m.getStart(r)).line+1,h=m=>{if(zn(e,m)){let o=m.arguments[0],l=ke(e,o);for(let u of Ee({publishCall:!0,rawIntentName:l,objectHasIntent:xe(e,o,"intent"),arkPublishCandidate:Kn(e,m),hasSource:Yn(e,m)}))p.push(x(u.ruleId,u.message,{line:y(m),filePath:a}));let g=Wn(e,m);if(s&&c&&g&&te(g)){let u=s.resolveLayer(g);u&&u!==c&&p.push(x("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${g}" resolves to ${u}, but the target file is classified as ${c}.`,{line:y(m),filePath:a,target:g,fromLayer:c,toLayer:u}))}}e.forEachChild(m,h)};return h(r),p}function Wt(e={}){let t=new Set((e.intents||[]).map(i=>typeof i=="string"?i:i.name)),n=e.forbiddenPatterns||[],s=new Set(e.infrastructureLayers??[]),r=e.enforceIntentAllowlist??t.size>0;return{validate(i,a){let c=[],p=a,y=p?.filePath,h=p?.layer,m=e.typescript,o=m?m.createSourceFile(y??"generated.ts",i,m.ScriptTarget.Latest,!0):void 0,l=o?de(e.typescript,o):void 0,g=l?l.filter(d=>d.specifier!==void 0).map(d=>({value:d.specifier,index:d.node.getStart(o),kind:d.kind,typeOnly:d.typeOnly})):Hn(i),u=e.typescript?Vn(e.typescript,i):Mn(i);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(y))for(let d of l?.filter(({unresolved:f})=>f)??[]){let f=d.kind==="require";c.push(x(f?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${f?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:d.line,filePath:y}))}let b=h!==void 0&&(s.has(h)||Gn(h)),v=h!==void 0?` If "${h}" is an infrastructure layer, mark it in ark.config.json with "mayImportInfrastructure": true (or name it with an infra token like Adapters/Persistence/Repository).`:"";for(let d of n)if(d instanceof RegExp){d.lastIndex=0;let f=d.exec(i);d.lastIndex=0,f&&c.push(x("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${d}`,{line:f.index===void 0?void 0:ue(i,f.index),filePath:y,suggestion:"Remove infrastructure imports from domain/application layers."+v}))}else i.includes(d)&&c.push(x("FORBIDDEN_SUBSTRING",`Forbidden substring: ${d}`,{line:ue(i,i.indexOf(d)),filePath:y}));for(let d of g){let f=e.resolveImportTarget?.(d.value,y)??(e.resolveImportLayer?{layer:e.resolveImportLayer(d.value,y)}:void 0),R=typeof y=="string"?e.resolveImportTarget?.(y)??(e.resolveImportLayer?{layer:h,relPath:void 0}:void 0):void 0,E=f?.layer;if(E&&h){let O=K(e.architectureProfile?.rules,h,E,{fromPath:R?.relPath,toPath:f?.relPath,layers:e.architectureLayers});if(O){if(d.typeOnly&&!O.peerIsolation)continue;let L=!!O.peerIsolation;c.push(x("LAYER_IMPORT_VIOLATION",O.message??(L?`Layer "${h}" must not import across slices into "${E}".`:`Layer "${h}" must not import "${E}".`),{line:ue(i,d.index),source:d.value,target:d.value,filePath:y,fromLayer:h,toLayer:E,suggestion:L?"Extract shared code to a shared layer, or coordinate slices via events/ports \u2014 do not import across feature/context slices.":"Depend on a port/interface owned by an inner layer instead, or move this code to a layer allowed to make this import.",details:{importKind:d.kind,peerIsolation:L,...d.typeOnly?{typeOnly:!0}:{}}}));continue}continue}b||d.typeOnly||!jn(d.value)&&!Un(d.value)||c.push(x("FORBIDDEN_IMPORT",`Forbidden ${d.kind} target: "${d.value}".`,{line:ue(i,d.index),source:d.value,target:d.value,filePath:y,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+v,details:{importKind:d.kind}}))}if(e.policies)for(let d of e.policies){let f=d.check({source:i,context:a});if(f!==!0)if(Array.isArray(f))for(let R of f)c.push(x("POLICY_VIOLATION",R.message,{filePath:y,suggestion:`Fix violation of policy "${d.name}".`}));else f===!1?c.push(x("POLICY_VIOLATION",`Policy ${d.name} failed on generated code`)):c.push(x("POLICY_VIOLATION",f.message))}if(r&&t.size>0)for(let d of u)te(d.value)&&!t.has(d.value)&&c.push(x("UNKNOWN_INTENT",`Unknown intent reference: "${d.value}"`,{line:ue(i,d.index),filePath:y,target:d.value,suggestion:`Register intent "${d.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&h)for(let d of u){if(!te(d.value))continue;let f=e.architectureProfile.resolveLayer(d.value);if(!f)continue;let R=K(e.architectureProfile.rules,h,f);R&&c.push(x("LAYER_REFERENCE_VIOLATION",R.message??`Layer "${h}" must not reference "${f}" through "${d.value}".`,{line:ue(i,d.index),filePath:y,target:d.value,fromLayer:h,toLayer:f,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:R}}))}if(e.extensions)for(let d of e.extensions)try{let f=d.analyze(i,a);c.push(...f)}catch(f){c.push(x("EXTENSION_ERROR",`Extension "${d.name}" failed: ${f instanceof Error?f.message:String(f)}`))}if(e.typescript&&o&&h&&e.forbiddenGlobals?.[h]?.length)try{let d=e.forbiddenGlobals[h];c.push(...pe(e.typescript,o,d).map(f=>x("FORBIDDEN_GLOBAL",`${h} must not use the ambient global "${f.name}".`,{line:f.line,filePath:y,target:f.name,fromLayer:h,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let f of l??[]){if(f.typeOnly||!f.specifier)continue;let R=J(f.specifier,d);R&&c.push(x("FORBIDDEN_GLOBAL",`${h} must not use module "${f.specifier}" because it is the import form of forbidden global "${R}".`,{line:f.line,filePath:y,source:f.specifier,target:f.specifier,fromLayer:h,details:{importKind:f.kind,forbiddenGlobal:R},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(d){c.push(x("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${d instanceof Error?d.message:String(d)}`))}if(e.typescript&&o&&h&&e.capabilityWalls?.[h]?.length)try{let d=new Set(e.capabilityWalls[h]),f=e.forbiddenGlobals?.[h]??[];for(let R of mt(e.typescript,o))d.has(R.capability)&&(R.source==="ambient-global"&&Ce(R.symbol,f)||R.source==="import-based"&&J(R.symbol,f)||c.push(x("CAPABILITY_VIOLATION",R.source==="import-based"?`${h} denies the ${R.capability} capability; found import of "${R.symbol}".`:`${h} denies the ${R.capability} capability; found ambient "${R.symbol}".`,{line:R.line,filePath:y,target:R.symbol,capability:R.capability,fromLayer:h,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(d){c.push(x("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${d instanceof Error?d.message:String(d)}`))}if(e.typescript)try{c.push(...Jn(e.typescript,i,a,e.architectureProfile))}catch(d){c.push(x("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${d instanceof Error?d.message:String(d)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:c.length===0,violations:c}}}}var Zn="1.1",Ue="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",Jt=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Xn=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Qn(){let e=[];for(let t of Jt)for(let n of Jt)t===n||Xn.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var Ge=Qn(),bt=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"}],Z={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Rt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Ue,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:Ue,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:"1.1",default:"1.1"},name:{type:"string",minLength:1},include:{...Z,minItems:1,default:["src"]},exclude:{...Z,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:Ge,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...Z,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...Z,minItems:1},exclude:Z,intentPrefixes:Z,description:{type:"string",minLength:1},forbiddenGlobals:Z,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:{...Z,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}}}}},Y=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
3
3
  ${n.map(s=>`- ${s.path}: ${s.message}`).join(`
4
- `)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function It(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Qe(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function re(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function yn(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function Se(e,t,n,s,r){if(t.$ref){let i=yn(t.$ref,s);if(!i){r.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}Se(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(!It(e)){r.push({path:n,message:`must be an object; received ${re(e)}`});return}let i=t.properties??{};for(let a of t.required??[])e[a]===void 0&&r.push({path:Qe(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in i||r.push({path:Qe(n,a),message:"unknown field"});for(let[a,c]of Object.entries(i))e[a]!==void 0&&Se(e[a],c,Qe(n,a),s,r);return}if(t.type==="array"){if(!Array.isArray(e)){r.push({path:n,message:`must be an array; received ${re(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&r.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let i=e.map(a=>JSON.stringify(a));new Set(i).size!==i.length&&r.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((i,a)=>Se(i,t.items,`${n}[${a}]`,s,r));return}if(t.type==="string"){if(typeof e!="string"){r.push({path:n,message:`must be a string; received ${re(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 ${re(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){r.push({path:n,message:`must be an integer; received ${re(e)}`});return}t.minimum!==void 0&&e<t.minimum&&r.push({path:n,message:`must be at least ${t.minimum}`})}}function mn(e){return{...e,$schema:e.$schema===void 0?xe: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?ke.map(t=>({...t})):e.rules}}function gn(e,t="ark.config.json"){if(!It(e))throw new ie(t,[{path:"$",message:`must be an object; received ${re(e)}`}]);let n=e.schemaVersion===void 0?"unversioned":null;if(e.schemaVersion!==void 0&&e.schemaVersion!=="1.0")throw new ie(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.0`}]);return{candidate:mn(e),migratedFrom:n}}function we(e,t="ark.config.json"){let{candidate:n,migratedFrom:s}=gn(e,t),r=[];if(Se(n,et,"$",et,r),r.length>0)throw new ie(t,r);return{config:n,migratedFrom:s}}function tt(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(s){throw new ie(t,[{path:"$",message:`invalid JSON: ${s instanceof Error?s.message:String(s)}`}])}return we(n,t)}function Et(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:xe,schemaVersion:"1.0"};for(let[n,s]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=s);return t}function hn(e){return e.endsWith(".")?e:`${e}.`}function An(e,t){let n=e.prefixes.length?Math.max(...e.prefixes.map(r=>r.length)):0;return(t.prefixes.length?Math.max(...t.prefixes.map(r=>r.length)):0)-n}function Oe(e){let t=e.layers.map(r=>({...r,prefixes:r.prefixes.map(hn)})),n=[...t].sort(An),s=[...e.rules??[]];return{name:e.name,layers:t,rules:s,resolveLayer(r){return t.find(i=>i.match?.(r))?.name??n.find(i=>i.prefixes.some(a=>r.startsWith(a)))?.name}}}function Rt(e,t={}){return Oe({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,s)=>({name:n.name,prefixes:n.intentPrefixes??[],description:n.description,order:s+1})),rules:e.rules??[]})}var bn=[{name:"DomainModel",prefixes:["Domain"],description:"Rich domain model, business rules, and domain events.",order:1},{name:"ApplicationOrchestration",prefixes:["Application"],description:"Use cases and command orchestration.",order:2},{name:"PersistenceAdapters",prefixes:["Adapter.Persistence","Adapter.Repository"],description:"Database, repository, and storage adapters.",order:3},{name:"IntegrationAdapters",prefixes:["Adapter.Integration","Adapter.External"],description:"External systems, APIs, and integration adapters.",order:4},{name:"WorkflowSagaEngine",prefixes:["Workflow"],description:"Sagas, workflows, and long-running processes.",order:5},{name:"BackgroundJobsScheduling",prefixes:["Job"],description:"Background jobs, scheduled work, and async processors.",order:6},{name:"PresentationAdapters",prefixes:["Presentation","Adapter.Presentation","Adapter.Api"],description:"API, UI, controller, and presentation adapters.",order:7},{name:"ReportingReadModels",prefixes:["Reporting"],description:"Read models, projections, and reporting surfaces.",order:8},{name:"ExtensibilityMetadata",prefixes:["Metadata"],description:"Metadata, extensions, and schema contracts.",order:9},{name:"SecurityAuditObservability",prefixes:["Security","Audit","Observability"],description:"Security, audit, and observability concerns.",order:10},{name:"Kernel",prefixes:["Kernel"],description:"Ark-owned governance and kernel signals.",order:11}],Pe=Oe({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:bn,rules:ke.map(e=>({...e}))}),Cn={DomainModel:["domain"],ApplicationOrchestration:["application","app"],PersistenceAdapters:["adapters/persistence","adapters/repository","repositories","infra/persistence"],IntegrationAdapters:["adapters/integration","adapters/external","integrations"],WorkflowSagaEngine:["workflows","sagas"],BackgroundJobsScheduling:["jobs","schedules"],PresentationAdapters:["presentation","adapters/presentation","adapters/api"],ReportingReadModels:["reporting","read-models","projections"],ExtensibilityMetadata:["metadata","extensions"],SecurityAuditObservability:["security","audit","observability"],Kernel:["kernel"]};function vt(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,s=t==="."?"":`${t}/`;return Et({include:e.include??[t],layers:Pe.layers.map(r=>({name:r.name,patterns:(Cn[r.name]??[r.name]).map(i=>`${s}${i}/**`),intentPrefixes:r.prefixes,optional:n})),rules:[...Pe.rules]})}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 E(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(E).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${E(t[n])}`).join(",")}}`}var W="1.0",St=["network","filesystem","clock","randomness","environment","process","persistence"];function q(e,t){let n=E(e),s=E(t);return n<s?-1:n>s?1:0}function T(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}function he(e){let t={schemaVersion:"1.0",include:T(e.include??[]),exclude:T(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:T(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:T(n.patterns??[]),exclude:T(n.exclude??[]),forbiddenGlobals:T(n.forbiddenGlobals??[]),intentPrefixes:T(n.intentPrefixes??[]),capabilityDeny:T(n.capabilities?.deny??[]),pure:n.pure===!0})).sort(q),safety:{maxTsSuppressions:e.safety?.maxTsSuppressions??0,maxAnyCasts:e.safety?.maxAnyCasts??0,allowInMemory:e.safety?.allowInMemory===!0,allowDisabledPeerIsolation:e.safety?.allowDisabledPeerIsolation===!0}};return S(E(t))}function In(e){let t=e.completenessReasons.map(u=>({code:u.code,message:u.message,...u.file?{file:u.file}:{}})).sort(q),n=e.files.map(u=>({...u,typeOnlyExportNames:T(u.typeOnlyExportNames)})).sort((u,o)=>u.path<o.path?-1:u.path>o.path?1:0),s=e.dependencies.map(u=>({...u,...u.namedBindings?{namedBindings:T(u.namedBindings)}:{}})).sort(q),r=e.capabilityUses.map(u=>({...u})).sort(q),i=e.ambientUses.map(u=>({...u})).sort(q),a=e.publishCalls.map(u=>({...u})).sort(q),c=e.intentReferences.map(u=>({...u})).sort(q),f=e.safetyUses.map(u=>({...u})).sort(q),A=e.files.map(({path:u,contentHash:o})=>({path:u,contentHash:o})).sort((u,o)=>u.path<o.path?-1:u.path>o.path?1:0),g=S(E(A));return{schemaVersion:"1.0",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:g,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:s,capabilityUses:r,ambientUses:i,publishCalls:a,intentReferences:c,safetyUses:f}}function kt(e){let t=In(e);return{...t,factsHash:S(E(t))}}function nt(e){return kt(Pt(D(e,"$"),!1))}function D(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}function F(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 k(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 se(e,t,n){if(e[t]!==void 0)return k(e,t,n)}function M(e,t,n){let s=k(e,t,n),r=s.replace(/\\/g,"/");if(!r||r.startsWith("/")||/^[A-Za-z]:\//.test(r)||/[\u0000-\u001f\u007f]/.test(r))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let i=[];for(let c of r.split("/"))if(!(!c||c==="."))if(c===".."){if(i.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);i.pop()}else i.push(c);let a=i.join("/");if(!a||a!==s)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return a}function _(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}function wt(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 ae(e,t,n){let s=wt(e,t,n);if(s===0)throw new Error(`${n}.${t} must be a positive integer.`);return s}function U(e,t,n){let s=e[t];if(!Array.isArray(s))throw new Error(`${n}.${t} must be an array.`);return s}function B(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 xt(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 En(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 Pt(e,t){F(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=B(e,"schemaVersion",["1.0"],"$"),s=B(e,"completeness",["complete","partial","unavailable"],"$"),r=U(e,"completenessReasons","$").map((p,d)=>{let y=`$.completenessReasons[${d}]`,h=D(p,y);F(h,["code","message","file"],y);let m=h.file===void 0?void 0:M(h,"file",y);return{code:k(h,"code",y),message:k(h,"message",y),...m?{file:m}:{}}});if(s==="complete"&&r.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(s!=="complete"&&r.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let i=U(e,"files","$").map((p,d)=>{let y=`$.files[${d}]`,h=D(p,y);return F(h,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],y),{path:M(h,"path",y),contentHash:k(h,"contentHash",y),parseStatus:B(h,"parseStatus",["parsed","invalid"],y),parseDiagnosticCount:wt(h,"parseDiagnosticCount",y),exportsOnlyTypes:_(h,"exportsOnlyTypes",y),typeOnlyExportNames:xt(h.typeOnlyExportNames,`${y}.typeOnlyExportNames`),hasTopLevelSideEffects:_(h,"hasTopLevelSideEffects",y)}}),a=U(e,"dependencies","$").map((p,d)=>{let y=`$.dependencies[${d}]`,h=D(p,y);F(h,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],y);let m=se(h,"specifier",y),b=se(h,"target",y),C=B(h,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],y);if(C==="resolved-project"&&!b)throw new Error(`${y}.target is required for resolved-project dependencies.`);if(C!=="resolved-project"&&b)throw new Error(`${y}.target is only allowed for resolved-project dependencies.`);if(C!=="dynamic"&&!m)throw new Error(`${y}.specifier is required unless resolution is dynamic.`);return{from:M(h,"from",y),...m?{specifier:m}:{},kind:B(h,"kind",["import","export","dynamic-import","require"],y),typeOnly:_(h,"typeOnly",y),line:ae(h,"line",y),resolution:C,...b?{target:M(h,"target",y)}:{},...h.namedBindings!==void 0?{namedBindings:xt(h.namedBindings,`${y}.namedBindings`)}:{},...h.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:_(h,"targetTypeOnlyExports",y)}:{},...h.sourcePureTypeModule!==void 0?{sourcePureTypeModule:_(h,"sourcePureTypeModule",y)}:{},...h.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:_(h,"namedBindingsTypeOnly",y)}:{},...h.portProofEligible!==void 0?{portProofEligible:_(h,"portProofEligible",y)}:{}}}),c=U(e,"capabilityUses","$").map((p,d)=>{let y=`$.capabilityUses[${d}]`,h=D(p,y);return F(h,["file","line","symbol","capability","source"],y),{file:M(h,"file",y),line:ae(h,"line",y),symbol:k(h,"symbol",y),capability:B(h,"capability",St,y),source:B(h,"source",["ambient-global","import-based"],y)}}),f=U(e,"ambientUses","$").map((p,d)=>{let y=`$.ambientUses[${d}]`,h=D(p,y);return F(h,["file","line","symbol"],y),{file:M(h,"file",y),line:ae(h,"line",y),symbol:k(h,"symbol",y)}}),A=U(e,"publishCalls","$").map((p,d)=>{let y=`$.publishCalls[${d}]`,h=D(p,y);F(h,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],y);let m=se(h,"rawIntentName",y),b=se(h,"sourceIntent",y);return{file:M(h,"file",y),line:ae(h,"line",y),...m?{rawIntentName:m}:{},objectHasIntent:_(h,"objectHasIntent",y),arkPublishCandidate:_(h,"arkPublishCandidate",y),hasSource:_(h,"hasSource",y),...b?{sourceIntent:b}:{}}}),g=U(e,"intentReferences","$").map((p,d)=>{let y=`$.intentReferences[${d}]`,h=D(p,y);return F(h,["file","line","intent"],y),{file:M(h,"file",y),line:ae(h,"line",y),intent:k(h,"intent",y)}}),u=U(e,"safetyUses","$").map((p,d)=>{let y=`$.safetyUses[${d}]`,h=D(p,y);F(h,["file","line","kind","symbol"],y);let m=se(h,"symbol",y),b=B(h,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],y);if(b==="in-memory-store"&&!m)throw new Error(`${y}.symbol is required for in-memory-store facts.`);if(b!=="in-memory-store"&&m)throw new Error(`${y}.symbol is only allowed for in-memory-store facts.`);return{file:M(h,"file",y),line:ae(h,"line",y),kind:b,...m?{symbol:m}:{}}});En(i,p=>p.path,"$.files");let o=new Set(i.map(p=>p.path));for(let p of i){if(p.parseStatus==="parsed"&&p.parseDiagnosticCount!==0)throw new Error(`$.files[${p.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(p.parseStatus==="invalid"&&p.parseDiagnosticCount===0)throw new Error(`$.files[${p.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(s==="complete"&&i.some(p=>p.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let p of a)if(!o.has(p.from))throw new Error(`$.dependencies references missing source file ${p.from}.`);for(let[p,d]of[["$.capabilityUses",c],["$.ambientUses",f],["$.publishCalls",A],["$.intentReferences",g],["$.safetyUses",u]])for(let y of d)if(!o.has(y.file))throw new Error(`${p} references missing file ${y.file}.`);let l=se(e,"projectPackageName","$");return{schemaVersion:n,completeness:s,completenessReasons:r,resolverIdentity:k(e,"resolverIdentity","$"),compilerIdentity:k(e,"compilerIdentity","$"),compilerOptionsHash:k(e,"compilerOptionsHash","$"),tsconfigHash:k(e,"tsconfigHash","$"),evidenceRequirementsHash:k(e,"evidenceRequirementsHash","$"),...l?{projectPackageName:l}:{},files:i,dependencies:a,capabilityUses:c,ambientUses:f,publishCalls:A,intentReferences:g,safetyUses:u}}function z(e){let t=D(e,"$"),n=k(t,"factsHash","$"),s=k(t,"candidateTreeHash","$"),r=kt(Pt(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 Rn=["network","filesystem","clock","randomness","environment","process","persistence"],R={type:"string",minLength:1},oe={type:"integer",minimum:1},H={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},rt={$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:R,message:R,file:H}}},resolverIdentity:R,compilerIdentity:R,compilerOptionsHash:R,tsconfigHash:R,candidateTreeHash:R,evidenceRequirementsHash:R,projectPackageName:R,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:H,contentHash:R,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:R},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:H,specifier:R,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:oe,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:H,namedBindings:{type:"array",items:R},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:H,line:oe,symbol:R,capability:{enum:Rn},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:H,line:oe,symbol:R}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:H,line:oe,rawIntentName:R,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:R}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:H,line:oe,intent:R}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:H,line:oe,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:R},allOf:[{if:{properties:{kind:{const:"in-memory-store"}}},then:{required:["symbol"]},else:{not:{required:["symbol"]}}}]}},factsHash:R},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 it="1.0";function P(e){return`${e.from}->${e.to}`}function Ae(e,t,n,s="dependency"){return{id:`${e}:${s}:${P(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${P(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${P(t)}, then preflight again.`}:e==="unplanned"?{nextAction:s==="dependency-removed"?`Restore the removed dependency ${P(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${P(t)} from the candidate, then preflight again.`}:{}}}function le(e){let t=[],n=new Map(e.changeMap.map.files.map(o=>[o.path,o])),s=new Map(e.changes.map(o=>[o.path,o])),r=new Map(e.changeMap.map.dependencies.map(o=>[P(o),o])),i=new Map(e.baseDependencies.map(o=>[P(o),o])),a=new Map(e.candidateDependencies.map(o=>[P(o),o]));for(let o of[...n.values()].sort((l,p)=>l.path.localeCompare(p.path))){let l=s.get(o.path);l?l.operation!==o.operation?t.push({id:`contradictory:file:${o.path}`,classification:"contradictory",subject:"file",path:o.path,expectedOperation:o.operation,actualOperation:l.operation,message:`${o.path} was planned as ${o.operation} but the actual operation is ${l.operation}.`,nextAction:`Change ${o.path} to the planned ${o.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${o.path}`,classification:"satisfied",subject:"file",path:o.path,expectedOperation:o.operation,actualOperation:l.operation,message:`${o.path} matches the planned ${o.operation} operation.`}):t.push({id:`missing:file:${o.path}`,classification:"missing",subject:"file",path:o.path,expectedOperation:o.operation,message:`${o.path} was planned as ${o.operation} but is absent from the actual change.`,nextAction:`${o.operation[0].toUpperCase()}${o.operation.slice(1)} ${o.path} in the complete change set, then preflight again.`})}for(let o of[...s.values()].sort((l,p)=>l.path.localeCompare(p.path)))n.has(o.path)||t.push({id:`unplanned:file:${o.path}`,classification:"unplanned",subject:"file",path:o.path,actualOperation:o.operation,message:`${o.path} has an unplanned ${o.operation} operation.`,nextAction:`Remove ${o.path} from the change set, then preflight again.`});let c=new Set;for(let o of[...r.values()].sort((l,p)=>P(l).localeCompare(P(p)))){if(a.has(P(o))){t.push(Ae("satisfied",o,`${o.from} -> ${o.to} exists in the candidate architecture.`));continue}let l={from:o.to,to:o.from};a.has(P(l))?(c.add(P(l)),t.push(Ae("contradictory",o,`${o.from} -> ${o.to} was planned, but the candidate contains the reverse edge.`))):t.push(Ae("missing",o,`${o.from} -> ${o.to} is absent from the candidate architecture.`))}let f=new Set([...n.keys(),...s.keys()]);for(let[o,l]of[...a].sort(([p],[d])=>p.localeCompare(d)))i.has(o)||r.has(o)||c.has(o)||!f.has(l.from)&&!f.has(l.to)||t.push({...Ae("unplanned",l,`${l.from} -> ${l.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let A=new Set(e.changeMap.map.files.filter(o=>o.operation==="delete").map(o=>o.path));for(let[o,l]of[...i].sort(([p],[d])=>p.localeCompare(d)))a.has(o)||A.has(l.from)||A.has(l.to)||!f.has(l.from)&&!f.has(l.to)||t.push({...Ae("unplanned",l,`${l.from} -> ${l.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let g={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((o,l)=>g[o.classification]-g[l.classification]||(o.subject===l.subject?0:o.subject==="file"?-1:1)||o.id.localeCompare(l.id));let u={satisfied:t.filter(o=>o.classification==="satisfied").length,missing:t.filter(o=>o.classification==="missing").length,contradictory:t.filter(o=>o.classification==="contradictory").length,unplanned:t.filter(o=>o.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:u.missing===0&&u.contradictory===0&&u.unplanned===0,behavioralCompletion:"not-evaluated",summary:u,findings:t}}var st="1.0";function x(e,t){e.push({id:`${t.classification}:${t.path}:${t.kind}`,path:t.path,classification:t.classification,message:t.message,...t.classification==="weakening"||t.classification==="judgment-required"?{nextAction:`Restore the previous protection at ${t.path}, then run ArkGate again.`}:{},...t.before===void 0?{}:{before:t.before},...t.after===void 0?{}:{after:t.after}})}function L(e){return[...new Set(e??[])].sort()}function J(e,t,n,s,r){let i=L(n),a=L(s),c=new Set(i),f=new Set(a),A=a.filter(u=>!c.has(u)),g=i.filter(u=>!f.has(u));A.length===0&&g.length===0||(A.length>0&&x(e,{kind:"added",path:t,classification:r.added,message:r.addedMessage,before:i,after:a}),g.length>0&&x(e,{kind:"removed",path:t,classification:r.removed,message:r.removedMessage,before:i,after:a}))}function Le(e,t,n,s,r,i,a){if(n===s)return;x(e,{kind:s?"enabled":"disabled",path:t,classification:s?r:r==="strengthening"?"weakening":"strengthening",message:s?i:a,before:n,after:s})}function $e(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 vn(e,t,n){let s=$e(t,i=>i.name),r=$e(n,i=>i.name);(s.duplicates.length>0||r.duplicates.length>0)&&x(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:s.duplicates,after:r.duplicates});for(let i of[...new Set([...s.values.keys(),...r.values.keys()])].sort()){let a=s.values.get(i),c=r.values.get(i),f=`$.layers[${i}]`;if(!a&&c){x(e,{kind:"layer-added",path:f,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:c});continue}if(a&&!c){x(e,{kind:"layer-removed",path:f,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:a});continue}if(!a||!c)continue;J(e,`${f}.patterns`,a.patterns,c.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),J(e,`${f}.exclude`,a.exclude,c.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let A=ve(a),g=ve(c);J(e,`${f}.forbiddenGlobals`,A.rawGlobals,g.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),J(e,`${f}.capabilities`,A.atoms,g.atoms,{added:"strengthening",removed:"weakening",addedMessage:"Additional ambient/import protection is enforced in this layer (coverage atoms).",removedMessage:"An ambient/import protection was lost from this layer (coverage atoms)."}),L(a.intentPrefixes).join("\0")!==L(c.intentPrefixes).join("\0")&&x(e,{kind:"intent-prefixes-changed",path:`${f}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:L(a.intentPrefixes),after:L(c.intentPrefixes)}),Le(e,`${f}.mayImportInfrastructure`,a.mayImportInfrastructure===!0,c.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),Le(e,`${f}.optional`,a.optional===!0,c.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active.")}}function Sn(e,t,n){let s=a=>`${a.from}->${a.to}`,r=$e(t,s),i=$e(n,s);(r.duplicates.length>0||i.duplicates.length>0)&&x(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:r.duplicates,after:i.duplicates});for(let a of[...new Set([...r.values.keys(),...i.values.keys()])].sort()){let c=r.values.get(a),f=i.values.get(a),A=`$.rules[${a}]`;if(!c&&f){f.allowed===!1&&x(e,{kind:"deny-added",path:A,classification:"strengthening",message:"A denied dependency edge was added.",after:f});continue}if(c&&!f){c.allowed===!1&&x(e,{kind:"deny-removed",path:A,classification:"weakening",message:"A denied dependency edge was removed.",before:c});continue}if(!c||!f)continue;c.allowed!==f.allowed&&x(e,{kind:f.allowed?"deny-disabled":"deny-enabled",path:`${A}.allowed`,classification:f.allowed?"weakening":"strengthening",message:f.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:c.allowed,after:f.allowed});let g=c.peerIsolation===!0,u=f.peerIsolation===!0;if(g!==u){let o=c.from===c.to&&f.from===f.to;x(e,{kind:u?"peer-isolation-enabled":"peer-isolation-disabled",path:`${A}.peerIsolation`,classification:o?u?"strengthening":"weakening":"judgment-required",message:o?u?"Cross-slice dependencies inside this layer are now denied.":"Cross-slice dependencies inside this layer are no longer denied.":"Changing peer isolation on a cross-layer edge changes the denial scope.",before:g,after:u})}L(c.sliceFolders).join("\0")!==L(f.sliceFolders).join("\0")&&x(e,{kind:"slice-folders-changed",path:`${A}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:L(c.sliceFolders),after:L(f.sliceFolders)})}}function xn(e,t,n){let s=t.safety??{},r=n.safety??{};for(let i of["maxTsSuppressions","maxAnyCasts"]){let a=s[i]??0,c=r[i]??0;a!==c&&x(e,{kind:c>a?"threshold-raised":"threshold-lowered",path:`$.safety.${i}`,classification:c>a?"weakening":"strengthening",message:c>a?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:a,after:c})}for(let i of["allowInMemory","allowDisabledPeerIsolation"])Le(e,`$.safety.${i}`,s[i]===!0,r[i]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}function kn(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 at(e,t){let n=[];J(n,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),J(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."}),J(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."}),Le(n,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let s={off:0,soft:1,"framework-soft":1,strict:2},r=e.cyclePolicy??"strict",i=t.cyclePolicy??"strict";if(r!==i){let a=s[i]===s[r]?"judgment-required":s[i]>s[r]?"strengthening":"weakening";x(n,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:a,message:"The cycle enforcement level changed.",before:r,after:i})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&x(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}),vn(n,e.layers,t.layers),Sn(n,e.rules,t.rules),xn(n,e,t),n.sort((a,c)=>a.path.localeCompare(c.path)||a.id.localeCompare(c.id)),{schemaVersion:st,classification:kn(n),findings:n}}function ot(e,t){if(!e||e.schemaVersion!==st||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(r=>typeof r!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=L(e.findingIds),s=L(t.findingIds);return n.length===s.length&&n.every((r,i)=>r===s[i])}function Z(e){let t=[];for(let n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."&&t.length>0&&t.at(-1)!==".."?t.pop():t.push(n));return t.join("/")}function Ot(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}function _e(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}function O(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}function be(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 $(e,t,n){return e.startsWith(t,n)&&!_e(e[n-1])&&!_e(e[n+t.length])}function Lt(e,t){let n=O(e,t);if(e[n]!=="{")return!1;n+=1;let s=!1;for(;n<e.length;){if(n=O(e,n),e[n]==="}")return s;if(e[n]===","){n+=1;continue}if(!$(e,"type",n))return!1;let r=O(e,n+4);if(r>=e.length||e[r]===","||e[r]==="}"||$(e,"as",r)||!Ot(e[r]))return!1;for(n=r;n<e.length&&_e(e[n]);)n+=1;if(n=O(e,n),$(e,"as",n)){if(n=O(e,n+2),!Ot(e[n]))return!1;for(;n<e.length&&_e(e[n]);)n+=1}s=!0}return!1}function wn(e,t){if(t=O(e,t+6),e[t]==="(")return be(e,O(e,t+1));let n=!1;if($(e,"type",t)){let r=O(e,t+4);e[r]!==","&&!$(e,"from",r)&&(n=!0)}else Lt(e,t)&&(n=!0);let s=$t(e,t,!0);return s&&n?{...s,typeOnly:!0}:s}function Pn(e,t){t=t+6;let n=O(e,t),s=!1;if($(e,"type",n)){let i=O(e,n+4);(e[i]==="{"||e[i]==="*")&&(s=!0)}else Lt(e,n)&&(s=!0);let r=$t(e,t,!1);return r&&s?{...r,typeOnly:!0}:r}function $t(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if($(e,"from",t))return be(e,O(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return be(e,t);if(t>0&&($(e,"import",t)||$(e,"export",t)))return}}function On(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 Ln(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let s=O(e,t+7);if(e[s]!=="(")return;s=O(e,s+1);let r=be(e,s);return r?{...r,requireCall:!0}:void 0}function $n(e){let t=[];for(let n=0;n<e.length;n+=1){let s=e[n];if(s==="/"&&e[n+1]==="/"){if(n=e.indexOf(`
5
- `,n+2),n<0)break;continue}if(s==="/"&&e[n+1]==="*"){let i=e.indexOf("*/",n+2);if(i<0)break;n=i+1;continue}if(s==="`"){n=On(e,n);continue}if(s==="'"||s==='"'){let i=be(e,n);i&&(n=i.offset+i.excerpt.length-1);continue}let r=s==="i"&&$(e,"import",n)?wn(e,n):s==="e"&&$(e,"export",n)?Pn(e,n):s==="r"&&$(e,"require",n)?Ln(e,n):void 0;r&&(t.push(r),n=r.offset+r.excerpt.length-1)}return t}function _t(e,t){let n=[],s=[];for(let r of $n(e.content)){let i=r.value;if(!i.startsWith(".")){if(r.typeOnly)continue;let A=pe(i);if(!A)continue;let g=e.content.slice(0,r.offset).split(`
6
- `).length;s.push({file:e.path,symbol:i,capability:A,evidence:{kind:"import",file:e.path,line:g,excerpt:r.excerpt}});continue}let a=e.content.slice(0,r.offset).split(`
7
- `).length,c={kind:"import",file:e.path,line:a,excerpt:r.excerpt},f=_n(e.path,i,t);n.push({from:e.path,specifier:i,to:f?.path??null,resolution:f?"resolved":"unresolved",fromLayer:e.layer,toLayer:f?.layer??null,evidence:c})}return{edges:n,capabilityUses:s}}function _n(e,t,n){let s=e.split("/");s.pop();for(let i of t.split("/"))i==="."||i===""||(i===".."?s.pop():s.push(i));let r=s.join("/");for(let i of[r,`${r}.ts`,`${r}.tsx`,`${r}.mts`,`${r}.cts`,`${r}/index.ts`,`${r}/index.tsx`]){let a=n.get(i);if(a)return a}}function Tt(e,t){let n=[];for(let s of e){if(!s.to||!s.fromLayer||!s.toLayer)continue;let r=N(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 Tn={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 Te(e,t){let n=typeof e=="string"?tt(e,t):we(e,t);return{...n,policyHash:S(E(n.config))}}function Dt(e){let t=Te(e.baseConfig,e.baseSource??"base ark.config.json"),n=Te(e.candidateConfig,e.candidateSource??"candidate ark.config.json"),s=at(t.config,n.config),r=s.findings.filter(c=>c.classification==="weakening"||c.classification==="judgment-required").map(c=>c.id).sort(),i=r.length>0,a=i&&ot(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:r});return{schemaVersion:s.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:s.classification,findings:s.findings,blockingFindingIds:r,requiresAcknowledgement:i,acknowledged:a,valid:!i||a}}function Ce(e){let t=e.files.map(u=>{let o=Z(u.path);return{path:o,content:u.content,contentHash:S(u.content),layer:j(o,e.contract.config.layers)??null}}).sort((u,o)=>u.path.localeCompare(o.path)),n=new Map(t.map(u=>[u.path,u])),s=[],r=[];for(let u of t){let o=_t(u,n);s.push(...o.edges),r.push(...o.capabilityUses)}let i=Tt(s,e.contract.config),a=new Map(e.contract.config.layers.map(u=>[u.name,u])),c=new Map(e.contract.config.layers.map(u=>[u.name,new Set(X(u))]));for(let u of r){let o=n.get(u.file)?.layer;if(!o)continue;let l=a.get(o),p=V(u.symbol,l?.forbiddenGlobals??[]);if(p){i.push({ruleId:"FORBIDDEN_GLOBAL",message:`${o} must not use module "${u.symbol}" because it is the import form of forbidden global "${p}".`,symbol:u.symbol,evidence:u.evidence});continue}c.get(o)?.has(u.capability)&&i.push({ruleId:"CAPABILITY_VIOLATION",message:`${o} denies the ${u.capability} capability; found import of "${u.symbol}".`,capability:u.capability,symbol:u.symbol,evidence:u.evidence})}let f=t.length===0?"complete":"partial",A=f==="complete"?[]:[{...Tn}],g={schemaVersion:it,policyHash:e.contract.policyHash,compilerOptionsHash:S(E(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(u=>u.name),edges:s,capabilityUses:r,violations:i};return{mode:"lexical-compatibility",completeness:f,completenessReasons:A,valid:f==="complete"&&i.length===0,ir:g}}function De(e){let t=new Map(e.files.map(n=>[Z(n.path),n]));for(let n of e.changes){let s=Z(n.path);"delete"in n&&n.delete?t.delete(s):"content"in n&&t.set(s,{path:s,content:n.content})}return Ce({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}function Nt(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 lt(e){let t=0,n=new Map,s=new Map,r=new Set,i=[],a=[],c=f=>{n.set(f,t),s.set(f,t),t+=1,i.push(f),r.add(f);for(let u of[...e.get(f)??[]].sort())e.has(u)&&(n.has(u)?r.has(u)&&s.set(f,Math.min(s.get(f)??0,n.get(u)??0)):(c(u),s.set(f,Math.min(s.get(f)??0,s.get(u)??0))));if(s.get(f)!==n.get(f))return;let A=[],g;do{if(g=i.pop(),g===void 0)break;r.delete(g),A.push(g)}while(g!==f);A.length>1&&a.push(A.sort())};for(let f of[...e.keys()].sort())n.has(f)||c(f);return a.sort((f,A)=>f[0]<A[0]?-1:f[0]>A[0]?1:0).map(f=>({ruleId:"CIRCULAR_DEPENDENCY",file:f[0],line:1,target:f.join(" \u2192 "),message:`Circular dependency among ${f.length} files: ${f.join(" \u2192 ")} \u2192 ${f[0]}.`,cycleKind:"value"}))}function ce(e){let t=e.contentViolations.map(i=>({...i})),n=(e.warnings??[]).map(i=>({...i})),s=new Map(e.files.map(i=>[i,new Set]));for(let i of e.edges){if(i.to&&i.to!==i.from&&!i.typeOnly&&s.has(i.from)&&s.get(i.from)?.add(i.to),!i.to||!i.fromLayer||!i.toLayer)continue;let a=N(e.rules,i.fromLayer,i.toLayer,{fromPath:i.from,toPath:i.to,layers:e.config.layers});if(!a)continue;let c=!!a.peerIsolation;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:i.from,line:i.line,fromLayer:i.fromLayer,toLayer:i.toLayer,target:i.to,...i.typeOnly?{typeOnly:!0}:{},...i.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...i.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...i.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!c&&i.portProofEligible?{portProofEligible:!0}:{},...i.kind?{edgeKind:i.kind}:{},...c?{peerIsolation:!0}:{},message:a.message??(c?`${i.fromLayer} must not ${i.kind} another slice of ${i.toLayer} (${i.from} \u2192 ${i.to}). Extract shared code or use events/ports across slices.`:`${i.fromLayer} must not ${i.kind} ${i.toLayer}.`)})}let r=String(e.config.cyclePolicy??"strict").toLowerCase();if(r!=="off"){let i=lt(s);r==="soft"||r==="framework-soft"?n.push(...i.map(a=>({...a,message:`${a.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...i)}return{violations:t,warnings:n,safety:e.safety}}function w(e,t,n={}){return{ruleId:e,message:t,...n}}function Ne(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 p=t.safety[l];p!==void 0&&(!Number.isInteger(p)||p<0)&&i.push(w("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${l} must be a non-negative integer.`))}let a=Array.isArray(t.layers)?t.layers:[],c=Array.isArray(r?.architecture?.layers)?r.architecture.layers:[],f=new Set([...a.map(l=>l.name).filter(Boolean),...c.map(l=>l.name).filter(l=>!!l)]);a.length===0&&i.push(w("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let A=new Set,g=new Set;for(let l of a){if(!l.name){i.push(w("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}A.has(l.name)&&g.add(l.name),A.add(l.name),l.forbiddenGlobals!==void 0&&(!Array.isArray(l.forbiddenGlobals)||l.forbiddenGlobals.some(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 p=Array.isArray(l.patterns)?l.patterns:[];if(p.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 p){let y;try{y=K(d)}catch(h){i.push(w("CONFIG_INVALID_LAYER_PATTERN",`Layer "${l.name}" has an invalid pattern "${d}": ${h instanceof Error?h.message:String(h)}`,{layer:l.name,pattern:d}));continue}!s.some(h=>y.test(h))&&!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 g)i.push(w("CONFIG_DUPLICATE_LAYER",`Layer "${l}" is configured more than once.`,{layer:l}));if(f.size>0)for(let l of n??[])l.from&&!f.has(l.from)&&i.push(w("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${l.from}".`,{fromLayer:l.from,toLayer:l.to})),l.to&&!f.has(l.to)&&i.push(w("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${l.to}".`,{fromLayer:l.from,toLayer:l.to}));let u=new Set;if(a.length>1)for(let l of s){let p=-1,d=[];for(let y of a)for(let h of y.patterns??[]){if(!K(h).test(l))continue;let m=ze(h);m>p?(p=m,d=[y.name]):m===p&&!d.includes(y.name)&&d.push(y.name)}d.length>1&&u.add([...d].sort().join(" + "))}u.size>0&&i.push(w("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...u].join(", ")}.`,{pairs:[...u]}));let o=s.filter(l=>!j(l,a));return o.length>0&&i.push(w("CONFIG_UNCLASSIFIED_FILES",`${o.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:o.length,samples:o.slice(0,5)})),i}function Dn(e,t){return t.some(n=>{try{return K(n).test(e)}catch{return!1}})}function Nn(e,t){let n=e.contract.config.safety??{},s=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,r=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,i=e.contract.config.dynamicImportAllowlist??[],a=t.safetyUses.filter(d=>d.kind==="ts-suppression").map(({file:d,line:y})=>({file:d,line:y})),c=t.safetyUses.filter(d=>d.kind==="any-cast").map(({file:d,line:y})=>({file:d,line:y})),f=t.safetyUses.filter(d=>(d.kind==="dynamic-import"||d.kind==="dynamic-require")&&!Dn(d.file,i)).map(d=>({file:d.file,line:d.line,kind:d.kind==="dynamic-require"?"require":"import"})),A=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"})),g=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})),u={tsSuppressions:a,anyCasts:c,nonLiteralDynamicImports:f,inMemoryProductionStores:A,disabledPeerIsolationRules:g,thresholds:{maxTsSuppressions:s,maxAnyCasts:r}},o=[],l=f.filter(d=>d.kind==="import");if(l.length>0){let d=l[0];o.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 p=f.filter(d=>d.kind==="require");if(p.length>0){let d=p[0];o.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:d.file,line:d.line,message:`${p.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(a.length>s){let d=a[0];o.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:d.file,line:d.line,message:`${a.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${s}).`})}if(c.length>r){let d=c[0];o.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:d.file,line:d.line,message:`${c.length} explicit any cast(s) exceed safety.maxAnyCasts (${r}).`})}if(A.length>0){let d=A[0];o.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:d.file,line:d.line,message:`${A.length} ArkGate InMemory store risk(s) appear in governed production source. Provide durable stores or set safety.allowInMemory only for an explicitly ephemeral service.`})}return g.length>0&&o.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${g.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:u,warnings:o}}function Fn(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,s)=>s.length-n.length)[0]}function Ft(e,t){let n=t.config.layers.filter(s=>(s.intentPrefixes??[]).length>0);return Xe(e,n.length>0?n:Ze.map(s=>({name:s.layer,prefixes:s.prefixes})))}function Mn(e,t,n){let s=[],r=new Map(e.contract.config.layers.map(i=>[i.name,i]));for(let i of t.ambientUses){let a=n.get(i.file);!a||!Fn(i.symbol,r.get(a)?.forbiddenGlobals??[])||s.push({ruleId:"FORBIDDEN_GLOBAL",file:i.file,line:i.line,fromLayer:a,target:i.symbol,message:`${a} must not use the ambient global "${i.symbol}".`})}for(let i of t.capabilityUses){let a=n.get(i.file);if(!a)continue;let c=r.get(a),f=c?.forbiddenGlobals??[],A=i.source==="import-based"?t.dependencies.find(g=>g.from===i.file&&g.line===i.line&&g.specifier===i.symbol&&!g.typeOnly)?.kind:void 0;if(!(i.source==="ambient-global"&&fe(i.symbol,f))){if(i.source==="import-based"){let g=V(i.symbol,f);if(g){s.push({ruleId:"FORBIDDEN_GLOBAL",file:i.file,line:i.line,fromLayer:a,target:i.symbol,...A?{edgeKind:A}:{},message:`${a} must not use module "${i.symbol}" because it is the import form of forbidden global "${g}".`});continue}}X(c).includes(i.capability)&&s.push({ruleId:"CAPABILITY_VIOLATION",file:i.file,line:i.line,fromLayer:a,target:i.symbol,capability:i.capability,...A?{edgeKind:A}:{},message:i.source==="import-based"?`${a} denies the ${i.capability} capability; found import of "${i.symbol}".`:`${a} denies the ${i.capability} capability; found ambient "${i.symbol}".`})}}for(let i of t.publishCalls){let a=n.get(i.file);if(!a)continue;for(let f of ue({publishCall:!0,rawIntentName:i.rawIntentName,objectHasIntent:i.objectHasIntent,arkPublishCandidate:i.arkPublishCandidate,hasSource:i.hasSource}))s.push({ruleId:f.ruleId,file:i.file,line:i.line,...f.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:a}:{},message:f.message});if(!i.sourceIntent)continue;let c=Ft(i.sourceIntent,e.contract);!c||c===a||s.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:i.file,line:i.line,fromLayer:a,toLayer:c,target:i.sourceIntent,message:`Publish source "${i.sourceIntent}" resolves to ${c}, but the publishing file is classified as ${a}.`})}for(let i of t.intentReferences){let a=n.get(i.file);if(!a)continue;let c=Ft(i.intent,e.contract);if(!c)continue;let f=N(e.contract.config.rules,a,c);f&&s.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:i.file,line:i.line,fromLayer:a,toLayer:c,target:i.intent,message:f.message??`${a} must not reference ${c} intent ${i.intent}.`})}return s}function Hn(e){let{facts:t}=e,n=he(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((p,d)=>{let y=`${p.code}\0${p.file??""}\0${p.message}`,h=`${d.code}\0${d.file??""}\0${d.message}`;return y<h?-1:y>h?1:0}),a=t.files.map(p=>({...p,layer:j(p.path,e.contract.config.layers)??null})),c=new Map(a.map(p=>[p.path,p.layer])),f=t.dependencies.map(p=>{let d=p.target?c.get(p.target)??j(p.target,e.contract.config.layers):void 0;return{from:p.from,fromLayer:c.get(p.from)??null,...p.resolution==="resolved-project"&&p.target?{to:p.target,...d?{toLayer:d}:{}}:{},line:p.line,kind:p.kind,typeOnly:p.typeOnly,...p.targetTypeOnlyExports?{targetTypeOnlyExports:p.targetTypeOnlyExports}:{},...p.sourcePureTypeModule?{sourcePureTypeModule:p.sourcePureTypeModule}:{},...p.namedBindingsTypeOnly?{namedBindingsTypeOnly:p.namedBindingsTypeOnly}:{},...p.portProofEligible?{portProofEligible:p.portProofEligible}:{}}}),A=Ne({config:e.contract.config,rules:e.contract.config.rules,files:a.map(p=>p.path)}),g=Nn(e,t),u=ce({config:e.contract.config,rules:e.contract.config.rules,files:a.filter(p=>p.layer).map(p=>p.path),contentViolations:Mn(e,t,c),edges:f,warnings:[...A,...g.warnings],safety:g.report}),o=r==="complete"&&u.violations.length===0,l=o&&u.warnings.every(p=>p.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:r,completenessReasons:i,valid:o,strictValid:l,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:g.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:a,layers:e.contract.config.layers.map(p=>p.name),edges:f,capabilityUses:t.capabilityUses,violations:u.violations,warnings:u.warnings}}}function Ie(e){return Hn({contract:e.contract,facts:z(e.facts)})}function Fe(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 Mt(e){return S(E(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}function Ht(e){let t=Ce(e),n=new Map(t.ir.files.map(l=>[l.path,l])),s=[],r=new Set,i=[];for(let l of e.changes){let p=l.path.replace(/\\/g,"/"),d=Z(l.path);if(!d||d===".."||d.startsWith("../")||p.startsWith("/")||/^[A-Za-z]:\//.test(p)||p.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 a=De({...e,changes:s}),c=new Map(a.ir.files.map(l=>[l.path,l])),f=a.ir.violations.filter(l=>l.ruleId==="CAPABILITY_VIOLATION"||l.ruleId==="FORBIDDEN_GLOBAL").map(l=>{let p=c.get(l.evidence.file)?.layer;return{ruleId:l.ruleId,file:l.evidence.file,line:l.evidence.line,target:l.symbol,...l.capability?{capability:l.capability}:{},...p?{fromLayer:p}:{},edgeKind:"import",message:l.message}}),A=ce({config:e.contract.config,rules:e.contract.config.rules,files:a.ir.files.map(l=>l.path),contentViolations:f,edges:a.ir.edges.filter(l=>!!l.fromLayer).map(l=>({from:l.from,fromLayer:l.fromLayer,...l.to?{to:l.to}:{},...l.toLayer?{toLayer:l.toLayer}:{},line:l.evidence.line,kind:"import"}))}),g=s.map(l=>{let p=Z(l.path),d=n.get(p),y=c.get(p);return{path:p,operation:"delete"in l&&l.delete?"delete":d?"update":"create",...d?{beforeContentHash:d.contentHash}:{},...y?{candidateContentHash:y.contentHash}:{}}}).sort((l,p)=>l.path.localeCompare(p.path)),u=[...i,...A.violations].map(l=>({...l,nextAction:Fe(l)})),o=e.changeMap?le({changeMap:e.changeMap,changes:g,baseDependencies:t.ir.edges.flatMap(l=>l.to?[{from:l.from,to:l.to}]:[]),candidateDependencies:a.ir.edges.flatMap(l=>l.to?[{from:l.from,to:l.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&a.valid&&u.length===0&&(o?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:a.ir.compilerOptionsHash,baseTreeHash:Mt(t.ir.files),candidateTreeHash:Mt(a.ir.files),baseCompleteness:t.completeness,candidateCompleteness:a.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:a.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...o?{convergence:o}:{},changes:g,violations:u,warnings:A.warnings}}function Vn(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 jn(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 Gn(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 Vt(e){let t=z(e.baseFacts),n=z(e.candidateFacts),s=Ie({contract:e.contract,facts:t}),r=Ie({contract:e.contract,facts:n}),i=new Map(t.files.map(o=>[o.path,o])),a=new Map(n.files.map(o=>[o.path,o])),c=jn(t,n),f=new Map,A=[];for(let o of e.changes){let l=Vn(o.path);if(!l){c.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(f.has(l)){c.push({ruleId:"DUPLICATE_CHANGE_PATH",file:l,line:1,message:`The atomic change set contains more than one operation for ${l}.`});continue}f.set(l,o);let p=i.get(l),d=a.get(l);if("delete"in o&&o.delete)p||c.push({ruleId:"DELETE_TARGET_MISSING",file:l,line:1,message:`Cannot delete ${l} because it is not present in the supplied base facts.`}),d&&c.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:l,line:1,message:`Candidate facts still contain deleted file ${l}.`});else{let y="content"in o?o.content:"",h=S(y);d?d.contentHash!==h&&c.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:l,line:1,expectedContentHash:h,candidateContentHash:d.contentHash,message:`Candidate facts for ${l} do not match the declared content.`}):c.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:l,line:1,message:`Candidate facts do not contain changed file ${l}.`})}A.push(Gn(o,l,i,a))}e.changes.length===0&&c.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});for(let o of new Set([...i.keys(),...a.keys()])){if(f.has(o))continue;let l=i.get(o),p=a.get(o);l&&p&&E(l)===E(p)||c.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:o,line:1,message:`Candidate facts change ${o}, but the atomic change set does not declare it.`})}let g=e.changeMap?le({changeMap:e.changeMap,changes:A,baseDependencies:s.ir.edges.flatMap(o=>o.to?[{from:o.from,to:o.to}]:[]),candidateDependencies:r.ir.edges.flatMap(o=>o.to?[{from:o.from,to:o.to}]:[])}):void 0,u=[...c,...r.ir.violations].map(o=>({...o,nextAction:Fe(o)}));return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:s.completeness==="complete"&&r.strictValid&&u.length===0&&(g?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,resolverIdentity:n.resolverIdentity,compilerIdentity:n.compilerIdentity,compilerOptionsHash:n.compilerOptionsHash,tsconfigHash:n.tsconfigHash,baseCompilerOptionsHash:t.compilerOptionsHash,candidateCompilerOptionsHash:n.compilerOptionsHash,baseTsconfigHash:t.tsconfigHash,candidateTsconfigHash:n.tsconfigHash,evidenceRequirementsHash:n.evidenceRequirementsHash,baseFactsHash:t.factsHash,candidateFactsHash:n.factsHash,baseTreeHash:t.candidateTreeHash,candidateTreeHash:n.candidateTreeHash,baseCompleteness:s.completeness,candidateCompleteness:r.completeness,baseCompletenessReasons:s.completenessReasons,candidateCompletenessReasons:r.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...g?{convergence:g}:{},changes:A.sort((o,l)=>o.path<l.path?-1:o.path>l.path?1:0),violations:u,warnings:r.ir.warnings}}var Un="1.1";var Bn="1.0";export{it as ANALYSIS_IR_SCHEMA_VERSION,qt as ARK_ANALYSIS_RESULT_SCHEMA,Gt as ARK_ANALYSIS_RESULT_SCHEMA_VERSION,et as ARK_CONFIG_SCHEMA,pn as ARK_CONFIG_SCHEMA_VERSION,Bn as ARK_DESIGN_DELTA_SCHEMA_VERSION,Un as ARK_ENFORCEMENT_STATE_SCHEMA_VERSION,st as POLICY_DELTA_SCHEMA_VERSION,rt as RESOLVED_CANDIDATE_FACTS_SCHEMA,W as RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,le as analyzeArchitectureConvergence,De as analyzeChange,Dt as analyzePolicyDelta,Ce as analyzeProject,Ie as analyzeResolvedProject,at as classifyArkPolicyDelta,Ne as collectAnalysisConfigWarnings,te as collectForbiddenCapabilityUses,bt as createAICodeGate,Bt as createAdapterResult,Oe as createArchitectureProfile,Rt as createArchitectureProfileFromArkConfig,vt as createElevenLayerArkConfig,nt as createResolvedCandidateFacts,lt as detectArchitectureCycles,S as deterministicHash,Pe as elevenLayerProfile,ce as evaluateArchitectureGraph,Nt as explainViolation,ee as extractSemanticDependencies,we as loadArkConfigContract,Te as loadContract,z as loadResolvedCandidateFacts,tt as parseArkConfigJson,ot as policyDeltaAcknowledgementMatches,Ht as preflightChange,Vt as preflightResolvedChange,he as resolvedFactsEvidenceRequirementsHash,E as stableSerialize,He as toAdapterDiagnostic,jt as version};
4
+ `)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function Zt(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 fe(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function er(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function we(e,t,n,s,r){if(t.$ref){let i=er(t.$ref,s);if(!i){r.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}we(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(!Zt(e)){r.push({path:n,message:`must be an object; received ${fe(e)}`});return}let i=t.properties??{};for(let a of t.required??[])e[a]===void 0&&r.push({path:je(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in i||r.push({path:je(n,a),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let a=t.additionalProperties;for(let c of Object.keys(e))c in i||we(e[c],a,je(n,c),s,r)}for(let[a,c]of Object.entries(i))e[a]!==void 0&&we(e[a],c,je(n,a),s,r);return}if(t.type==="array"){if(!Array.isArray(e)){r.push({path:n,message:`must be an array; received ${fe(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&r.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let i=e.map(a=>JSON.stringify(a));new Set(i).size!==i.length&&r.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((i,a)=>we(i,t.items,`${n}[${a}]`,s,r));return}if(t.type==="string"){if(typeof e!="string"){r.push({path:n,message:`must be a string; received ${fe(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 ${fe(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){r.push({path:n,message:`must be an integer; received ${fe(e)}`});return}t.minimum!==void 0&&e<t.minimum&&r.push({path:n,message:`must be at least ${t.minimum}`})}}function tr(e){return{...e,$schema:e.$schema===void 0?Ue:e.$schema,schemaVersion:e.schemaVersion===void 0?"1.1":e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?Ge.map(t=>({...t})):e.rules}}function nr(){let e=new Set(["1.1"]);for(let t of bt)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}function rr(e,t="ark.config.json"){if(!Zt(e))throw new Y(t,[{path:"$",message:`must be an object; received ${fe(e)}`}]);let n=nr(),s=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(s===null)throw new Y(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.1`}]);if(s!=="unversioned"&&!n.has(s))throw new Y(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(s)}; expected 1.1`}]);let r=s,i={...e},a=0;for(;r!=="1.1"&&a<bt.length+1;){a+=1;let p=bt.find(y=>y.from===r);if(!p)throw new Y(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected 1.1`}]);r=p.to,i.schemaVersion=r}if(r!=="1.1")throw new Y(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(s)}; expected 1.1`}]);let c=s==="unversioned"?"unversioned":s==="1.0"?"1.0":null;return{candidate:tr(i),migratedFrom:c}}function Be(e,t="ark.config.json"){let{candidate:n,migratedFrom:s}=rr(e,t),r=[];if(we(n,Rt,"$",Rt,r),r.length>0)throw new Y(t,r);return{config:n,migratedFrom:s}}function vt(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(s){throw new Y(t,[{path:"$",message:`invalid JSON: ${s instanceof Error?s.message:String(s)}`}])}return Be(n,t)}function Xt(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:Ue,schemaVersion:"1.1"};for(let[n,s]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=s);return t}function sr(e){return e.endsWith(".")?e:`${e}.`}function ir(e,t){let n=e.prefixes.length?Math.max(...e.prefixes.map(r=>r.length)):0;return(t.prefixes.length?Math.max(...t.prefixes.map(r=>r.length)):0)-n}function ze(e){let t=e.layers.map(r=>({...r,prefixes:r.prefixes.map(sr)})),n=[...t].sort(ir),s=[...e.rules??[]];return{name:e.name,layers:t,rules:s,resolveLayer(r){return t.find(i=>i.match?.(r))?.name??n.find(i=>i.prefixes.some(a=>r.startsWith(a)))?.name}}}function Qt(e,t={}){return ze({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,s)=>({name:n.name,prefixes:n.intentPrefixes??[],description:n.description,order:s+1})),rules:e.rules??[]})}var ar=[{name:"DomainModel",prefixes:["Domain"],description:"Rich domain model, business rules, and domain events.",order:1},{name:"ApplicationOrchestration",prefixes:["Application"],description:"Use cases and command orchestration.",order:2},{name:"PersistenceAdapters",prefixes:["Adapter.Persistence","Adapter.Repository"],description:"Database, repository, and storage adapters.",order:3},{name:"IntegrationAdapters",prefixes:["Adapter.Integration","Adapter.External"],description:"External systems, APIs, and integration adapters.",order:4},{name:"WorkflowSagaEngine",prefixes:["Workflow"],description:"Sagas, workflows, and long-running processes.",order:5},{name:"BackgroundJobsScheduling",prefixes:["Job"],description:"Background jobs, scheduled work, and async processors.",order:6},{name:"PresentationAdapters",prefixes:["Presentation","Adapter.Presentation","Adapter.Api"],description:"API, UI, controller, and presentation adapters.",order:7},{name:"ReportingReadModels",prefixes:["Reporting"],description:"Read models, projections, and reporting surfaces.",order:8},{name:"ExtensibilityMetadata",prefixes:["Metadata"],description:"Metadata, extensions, and schema contracts.",order:9},{name:"SecurityAuditObservability",prefixes:["Security","Audit","Observability"],description:"Security, audit, and observability concerns.",order:10},{name:"Kernel",prefixes:["Kernel"],description:"Ark-owned governance and kernel signals.",order:11}],qe=ze({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:ar,rules:Ge.map(e=>({...e}))}),or={DomainModel:["domain"],ApplicationOrchestration:["application","app"],PersistenceAdapters:["adapters/persistence","adapters/repository","repositories","infra/persistence"],IntegrationAdapters:["adapters/integration","adapters/external","integrations"],WorkflowSagaEngine:["workflows","sagas"],BackgroundJobsScheduling:["jobs","schedules"],PresentationAdapters:["presentation","adapters/presentation","adapters/api"],ReportingReadModels:["reporting","read-models","projections"],ExtensibilityMetadata:["metadata","extensions"],SecurityAuditObservability:["security","audit","observability"],Kernel:["kernel"]};function en(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,s=t==="."?"":`${t}/`;return Xt({include:e.include??[t],layers:qe.layers.map(r=>({name:r.name,patterns:(or[r.name]??[r.name]).map(i=>`${s}${i}/**`),intentPrefixes:r.prefixes,optional:n})),rules:[...qe.rules]})}function w(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}function k(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(k).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${k(t[n])}`).join(",")}}`}var ne="1.1";var tn=["network","filesystem","clock","randomness","environment","process","persistence"];function W(e,t){let n=k(e),s=k(t);return n<s?-1:n>s?1:0}function B(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}function $e(e){let t={schemaVersion:"1.1",include:B(e.include??[]),exclude:B(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:B(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:B(n.patterns??[]),exclude:B(n.exclude??[]),forbiddenGlobals:B(n.forbiddenGlobals??[]),intentPrefixes:B(n.intentPrefixes??[]),capabilityDeny:B(n.capabilities?.deny??[]),pure:n.pure===!0})).sort(W),safety:{maxTsSuppressions:e.safety?.maxTsSuppressions??0,maxAnyCasts:e.safety?.maxAnyCasts??0,allowInMemory:e.safety?.allowInMemory===!0,allowDisabledPeerIsolation:e.safety?.allowDisabledPeerIsolation===!0}};return w(k(t))}function lr(e){let t=e.completenessReasons.map(o=>({code:o.code,message:o.message,...o.file?{file:o.file}:{}})).sort(W),n=e.files.map(o=>({...o,typeOnlyExportNames:B(o.typeOnlyExportNames)})).sort((o,l)=>o.path<l.path?-1:o.path>l.path?1:0),s=e.dependencies.map(o=>({...o,...o.namedBindings?{namedBindings:B(o.namedBindings)}:{}})).sort(W),r=e.capabilityUses.map(o=>({...o})).sort(W),i=e.ambientUses.map(o=>({...o})).sort(W),a=e.publishCalls.map(o=>({...o})).sort(W),c=e.intentReferences.map(o=>({...o})).sort(W),p=e.safetyUses.map(o=>({...o})).sort(W),y=(e.classShapes??[]).map(o=>({...o,mutatingMethods:[...o.mutatingMethods??[]].map(l=>({...l}))})).sort(W),h=e.files.map(({path:o,contentHash:l})=>({path:o,contentHash:l})).sort((o,l)=>o.path<l.path?-1:o.path>l.path?1:0),m=w(k(h));return{schemaVersion:"1.1",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:m,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:s,capabilityUses:r,ambientUses:i,publishCalls:a,intentReferences:c,safetyUses:p,classShapes:y}}function rn(e){let t=lr(e);return{...t,factsHash:w(k(t))}}function It(e){return rn(an(D(e,"$"),!1))}function D(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}function V(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.1"}.`)}function P(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 ye(e,t,n){if(e[t]!==void 0)return P(e,t,n)}function U(e,t,n){let s=P(e,t,n),r=s.replace(/\\/g,"/");if(!r||r.startsWith("/")||/^[A-Za-z]:\//.test(r)||/[\u0000-\u001f\u007f]/.test(r))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let i=[];for(let c of r.split("/"))if(!(!c||c==="."))if(c===".."){if(i.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);i.pop()}else i.push(c);let a=i.join("/");if(!a||a!==s)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return a}function $(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}function sn(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 me(e,t,n){let s=sn(e,t,n);if(s===0)throw new Error(`${n}.${t} must be a positive integer.`);return s}function G(e,t,n){let s=e[t];if(!Array.isArray(s))throw new Error(`${n}.${t} must be an array.`);return s}function X(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 nn(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 cr(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 an(e,t){V(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","classShapes",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=X(e,"schemaVersion",["1.0","1.1"],"$"),s=X(e,"completeness",["complete","partial","unavailable"],"$"),r=G(e,"completenessReasons","$").map((b,v)=>{let d=`$.completenessReasons[${v}]`,f=D(b,d);V(f,["code","message","file"],d);let R=f.file===void 0?void 0:U(f,"file",d);return{code:P(f,"code",d),message:P(f,"message",d),...R?{file:R}:{}}});if(s==="complete"&&r.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(s!=="complete"&&r.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let i=G(e,"files","$").map((b,v)=>{let d=`$.files[${v}]`,f=D(b,d);return V(f,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],d),{path:U(f,"path",d),contentHash:P(f,"contentHash",d),parseStatus:X(f,"parseStatus",["parsed","invalid"],d),parseDiagnosticCount:sn(f,"parseDiagnosticCount",d),exportsOnlyTypes:$(f,"exportsOnlyTypes",d),typeOnlyExportNames:nn(f.typeOnlyExportNames,`${d}.typeOnlyExportNames`),hasTopLevelSideEffects:$(f,"hasTopLevelSideEffects",d)}}),a=G(e,"dependencies","$").map((b,v)=>{let d=`$.dependencies[${v}]`,f=D(b,d);V(f,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],d);let R=ye(f,"specifier",d),E=ye(f,"target",d),O=X(f,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],d);if(O==="resolved-project"&&!E)throw new Error(`${d}.target is required for resolved-project dependencies.`);if(O!=="resolved-project"&&E)throw new Error(`${d}.target is only allowed for resolved-project dependencies.`);if(O!=="dynamic"&&!R)throw new Error(`${d}.specifier is required unless resolution is dynamic.`);return{from:U(f,"from",d),...R?{specifier:R}:{},kind:X(f,"kind",["import","export","dynamic-import","require"],d),typeOnly:$(f,"typeOnly",d),line:me(f,"line",d),resolution:O,...E?{target:U(f,"target",d)}:{},...f.namedBindings!==void 0?{namedBindings:nn(f.namedBindings,`${d}.namedBindings`)}:{},...f.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:$(f,"targetTypeOnlyExports",d)}:{},...f.sourcePureTypeModule!==void 0?{sourcePureTypeModule:$(f,"sourcePureTypeModule",d)}:{},...f.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:$(f,"namedBindingsTypeOnly",d)}:{},...f.portProofEligible!==void 0?{portProofEligible:$(f,"portProofEligible",d)}:{}}}),c=G(e,"capabilityUses","$").map((b,v)=>{let d=`$.capabilityUses[${v}]`,f=D(b,d);return V(f,["file","line","symbol","capability","source"],d),{file:U(f,"file",d),line:me(f,"line",d),symbol:P(f,"symbol",d),capability:X(f,"capability",tn,d),source:X(f,"source",["ambient-global","import-based"],d)}}),p=G(e,"ambientUses","$").map((b,v)=>{let d=`$.ambientUses[${v}]`,f=D(b,d);return V(f,["file","line","symbol"],d),{file:U(f,"file",d),line:me(f,"line",d),symbol:P(f,"symbol",d)}}),y=G(e,"publishCalls","$").map((b,v)=>{let d=`$.publishCalls[${v}]`,f=D(b,d);V(f,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],d);let R=ye(f,"rawIntentName",d),E=ye(f,"sourceIntent",d);return{file:U(f,"file",d),line:me(f,"line",d),...R?{rawIntentName:R}:{},objectHasIntent:$(f,"objectHasIntent",d),arkPublishCandidate:$(f,"arkPublishCandidate",d),hasSource:$(f,"hasSource",d),...E?{sourceIntent:E}:{}}}),h=G(e,"intentReferences","$").map((b,v)=>{let d=`$.intentReferences[${v}]`,f=D(b,d);return V(f,["file","line","intent"],d),{file:U(f,"file",d),line:me(f,"line",d),intent:P(f,"intent",d)}}),m=G(e,"safetyUses","$").map((b,v)=>{let d=`$.safetyUses[${v}]`,f=D(b,d);V(f,["file","line","kind","symbol"],d);let R=ye(f,"symbol",d),E=X(f,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],d);if(E==="in-memory-store"&&!R)throw new Error(`${d}.symbol is required for in-memory-store facts.`);if(E!=="in-memory-store"&&R)throw new Error(`${d}.symbol is only allowed for in-memory-store facts.`);return{file:U(f,"file",d),line:me(f,"line",d),kind:E,...R?{symbol:R}:{}}});cr(i,b=>b.path,"$.files");let o=new Set(i.map(b=>b.path));for(let b of i){if(b.parseStatus==="parsed"&&b.parseDiagnosticCount!==0)throw new Error(`$.files[${b.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(b.parseStatus==="invalid"&&b.parseDiagnosticCount===0)throw new Error(`$.files[${b.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(s==="complete"&&i.some(b=>b.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let b of a)if(!o.has(b.from))throw new Error(`$.dependencies references missing source file ${b.from}.`);for(let[b,v]of[["$.capabilityUses",c],["$.ambientUses",p],["$.publishCalls",y],["$.intentReferences",h],["$.safetyUses",m]])for(let d of v)if(!o.has(d.file))throw new Error(`${b} references missing file ${d.file}.`);let l=ye(e,"projectPackageName","$"),u=(e.classShapes===void 0?[]:G(e,"classShapes","$")).map((b,v)=>{let d=`$.classShapes[${v}]`,f=D(b,d);V(f,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],d);let R=G(f,"mutatingMethods",d).map((E,O)=>{let L=`${d}.mutatingMethods[${O}]`,_=D(E,L);return V(_,["name","referencesGuardOrPublish"],L),{name:P(_,"name",L),referencesGuardOrPublish:$(_,"referencesGuardOrPublish",L)}});return{file:U(f,"file",d),className:P(f,"className",d),exported:$(f,"exported",d),hasPublicMutableFields:$(f,"hasPublicMutableFields",d),hasPublicSetters:$(f,"hasPublicSetters",d),hasPublicConstructor:$(f,"hasPublicConstructor",d),hasStaticFactory:$(f,"hasStaticFactory",d),mutatingMethods:R,...f.dataOnly===void 0?{}:{dataOnly:$(f,"dataOnly",d)}}});return{schemaVersion:n,completeness:s,completenessReasons:r,resolverIdentity:P(e,"resolverIdentity","$"),compilerIdentity:P(e,"compilerIdentity","$"),compilerOptionsHash:P(e,"compilerOptionsHash","$"),tsconfigHash:P(e,"tsconfigHash","$"),evidenceRequirementsHash:P(e,"evidenceRequirementsHash","$"),...l?{projectPackageName:l}:{},files:i,dependencies:a,capabilityUses:c,ambientUses:p,publishCalls:y,intentReferences:h,safetyUses:m,classShapes:u}}function Q(e){let t=D(e,"$"),n=P(t,"factsHash","$"),s=P(t,"candidateTreeHash","$"),r=rn(an(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 dr=["network","filesystem","clock","randomness","environment","process","persistence"],S={type:"string",minLength:1},ge={type:"integer",minimum:1},q={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},Ct={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.resolved-candidate-facts.schema.json",title:"ArkGate resolved candidate facts",type:"object",additionalProperties:!1,required:["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","candidateTreeHash","evidenceRequirementsHash","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","factsHash"],properties:{schemaVersion:{enum:["1.0","1.1"]},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:S,message:S,file:q}}},resolverIdentity:S,compilerIdentity:S,compilerOptionsHash:S,tsconfigHash:S,candidateTreeHash:S,evidenceRequirementsHash:S,projectPackageName:S,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:q,contentHash:S,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:S},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:q,specifier:S,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:ge,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:q,namedBindings:{type:"array",items:S},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:q,line:ge,symbol:S,capability:{enum:dr},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:q,line:ge,symbol:S}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:q,line:ge,rawIntentName:S,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:S}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:q,line:ge,intent:S}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:q,line:ge,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:S},allOf:[{if:{properties:{kind:{const:"in-memory-store"}}},then:{required:["symbol"]},else:{not:{required:["symbol"]}}}]}},classShapes:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods"],properties:{file:q,className:S,exported:{type:"boolean"},hasPublicMutableFields:{type:"boolean"},hasPublicSetters:{type:"boolean"},hasPublicConstructor:{type:"boolean"},hasStaticFactory:{type:"boolean"},dataOnly:{type:"boolean"},mutatingMethods:{type:"array",items:{type:"object",additionalProperties:!1,required:["name","referencesGuardOrPublish"],properties:{name:S,referencesGuardOrPublish:{type:"boolean"}}}}}}},factsHash:S},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 Et="1.0";function F(e){return`${e.from}->${e.to}`}function Pe(e,t,n,s="dependency"){return{id:`${e}:${s}:${F(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${F(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${F(t)}, then preflight again.`}:e==="unplanned"?{nextAction:s==="dependency-removed"?`Restore the removed dependency ${F(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${F(t)} from the candidate, then preflight again.`}:{}}}function he(e){let t=[],n=new Map(e.changeMap.map.files.map(o=>[o.path,o])),s=new Map(e.changes.map(o=>[o.path,o])),r=new Map(e.changeMap.map.dependencies.map(o=>[F(o),o])),i=new Map(e.baseDependencies.map(o=>[F(o),o])),a=new Map(e.candidateDependencies.map(o=>[F(o),o]));for(let o of[...n.values()].sort((l,g)=>l.path.localeCompare(g.path))){let l=s.get(o.path);l?l.operation!==o.operation?t.push({id:`contradictory:file:${o.path}`,classification:"contradictory",subject:"file",path:o.path,expectedOperation:o.operation,actualOperation:l.operation,message:`${o.path} was planned as ${o.operation} but the actual operation is ${l.operation}.`,nextAction:`Change ${o.path} to the planned ${o.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${o.path}`,classification:"satisfied",subject:"file",path:o.path,expectedOperation:o.operation,actualOperation:l.operation,message:`${o.path} matches the planned ${o.operation} operation.`}):t.push({id:`missing:file:${o.path}`,classification:"missing",subject:"file",path:o.path,expectedOperation:o.operation,message:`${o.path} was planned as ${o.operation} but is absent from the actual change.`,nextAction:`${o.operation[0].toUpperCase()}${o.operation.slice(1)} ${o.path} in the complete change set, then preflight again.`})}for(let o of[...s.values()].sort((l,g)=>l.path.localeCompare(g.path)))n.has(o.path)||t.push({id:`unplanned:file:${o.path}`,classification:"unplanned",subject:"file",path:o.path,actualOperation:o.operation,message:`${o.path} has an unplanned ${o.operation} operation.`,nextAction:`Remove ${o.path} from the change set, then preflight again.`});let c=new Set;for(let o of[...r.values()].sort((l,g)=>F(l).localeCompare(F(g)))){if(a.has(F(o))){t.push(Pe("satisfied",o,`${o.from} -> ${o.to} exists in the candidate architecture.`));continue}let l={from:o.to,to:o.from};a.has(F(l))?(c.add(F(l)),t.push(Pe("contradictory",o,`${o.from} -> ${o.to} was planned, but the candidate contains the reverse edge.`))):t.push(Pe("missing",o,`${o.from} -> ${o.to} is absent from the candidate architecture.`))}let p=new Set([...n.keys(),...s.keys()]);for(let[o,l]of[...a].sort(([g],[u])=>g.localeCompare(u)))i.has(o)||r.has(o)||c.has(o)||!p.has(l.from)&&!p.has(l.to)||t.push({...Pe("unplanned",l,`${l.from} -> ${l.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let y=new Set(e.changeMap.map.files.filter(o=>o.operation==="delete").map(o=>o.path));for(let[o,l]of[...i].sort(([g],[u])=>g.localeCompare(u)))a.has(o)||y.has(l.from)||y.has(l.to)||!p.has(l.from)&&!p.has(l.to)||t.push({...Pe("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((o,l)=>h[o.classification]-h[l.classification]||(o.subject===l.subject?0:o.subject==="file"?-1:1)||o.id.localeCompare(l.id));let m={satisfied:t.filter(o=>o.classification==="satisfied").length,missing:t.filter(o=>o.classification==="missing").length,contradictory:t.filter(o=>o.classification==="contradictory").length,unplanned:t.filter(o=>o.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:m.missing===0&&m.contradictory===0&&m.unplanned===0,behavioralCompletion:"not-evaluated",summary:m,findings:t}}var pr="1.0",St="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",cn=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","no-anemic-model","invariant-coverage"],ur=["no-anemic-model"],on={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},kt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:St,title:"ArkGate ArkRules (intra-layer contract)",description:"Per-layer structure sensors and invariant catalog consumed by the ArkGate Effective Contract.",type:"object",additionalProperties:!1,required:["schemaVersion","layer"],properties:{$schema:{type:"string",minLength:1,default:St},schemaVersion:{type:"string",const:"1.0",default:"1.0"},layer:{type:"string",minLength:1},structure:{type:"array",default:[],items:{$ref:"#/$defs/structureEntry"}},invariants:{type:"array",default:[],items:{$ref:"#/$defs/invariantEntry"}}},$defs:{structureEntry:{type:"object",additionalProperties:!1,required:["id","sensor"],properties:{id:{type:"string",minLength:1},sensor:{type:"string",enum:[...cn]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:on,description:{type:"string",minLength:1}}},invariantEntry:{type:"object",additionalProperties:!1,required:["id","description"],properties:{id:{type:"string",minLength:1},description:{type:"string",minLength:1},aggregate:{type:"string",minLength:1},coverage:{type:"object",additionalProperties:!1,properties:{test:{type:"boolean"},symbol:{type:"string",minLength:1}}},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:on}}}},re=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkRules (${t}):
5
+ ${n.map(s=>`- ${s.path}: ${s.message}`).join(`
6
+ `)}`),this.name="ArkRulesValidationError",this.source=t,this.issues=n}};function _e(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ke(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function Oe(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function fr(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function Le(e,t,n,s,r){if(t.$ref){let i=fr(t.$ref,s);if(!i){r.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}Le(e,i,n,s,r);return}if(t.const!==void 0&&!Object.is(e,t.const)){r.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(i=>Object.is(i,e))){r.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!_e(e)){r.push({path:n,message:`must be an object; received ${Oe(e)}`});return}let i=t.properties??{};for(let a of t.required??[])e[a]===void 0&&r.push({path:Ke(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in i||r.push({path:Ke(n,a),message:"unknown field"});else if(_e(t.additionalProperties)){let a=t.additionalProperties;for(let c of Object.keys(e))c in i||Le(e[c],a,Ke(n,c),s,r)}for(let[a,c]of Object.entries(i))e[a]!==void 0&&Le(e[a],c,Ke(n,a),s,r);return}if(t.type==="array"){if(!Array.isArray(e)){r.push({path:n,message:`must be an array; received ${Oe(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&r.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let i=e.map(a=>JSON.stringify(a));new Set(i).size!==i.length&&r.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((i,a)=>Le(i,t.items,`${n}[${a}]`,s,r));return}if(t.type==="string"){if(typeof e!="string"){r.push({path:n,message:`must be a string; received ${Oe(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&r.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}t.type==="boolean"&&typeof e!="boolean"&&r.push({path:n,message:`must be a boolean; received ${Oe(e)}`})}function yr(e){return{...e,$schema:e.$schema===void 0?St:e.$schema,schemaVersion:e.schemaVersion===void 0?"1.0":e.schemaVersion,structure:e.structure===void 0?[]:e.structure,invariants:e.invariants===void 0?[]:e.invariants}}function ln(e){return e==="enforced"?"enforced":"advisory"}function mr(e){return ur.includes(e)}function gr(e,t){let n=Array.isArray(e.structure)?e.structure:[],s=Array.isArray(e.invariants)?e.invariants:[],r=new Set;n.forEach((i,a)=>{if(!_e(i))return;let c=typeof i.id=="string"?i.id:"";c&&(r.has(c)&&t.push({path:`$.structure[${a}].id`,message:`duplicate rule id ${JSON.stringify(c)}`}),r.add(c)),typeof i.sensor=="string"&&mr(i.sensor)&&i.mode==="enforced"&&t.push({path:`$.structure[${a}].mode`,message:`sensor ${JSON.stringify(i.sensor)} is Tier-2 advisory-only and cannot be enforced`}),Array.isArray(i.appliesTo)&&i.appliesTo.length===0&&t.push({path:`$.structure[${a}].appliesTo`,message:"must not be an empty array (omit the field to apply to the whole layer)"})}),s.forEach((i,a)=>{if(!_e(i))return;let c=typeof i.id=="string"?i.id:"";c&&(r.has(c)&&t.push({path:`$.invariants[${a}].id`,message:`duplicate rule id ${JSON.stringify(c)}`}),r.add(c)),Array.isArray(i.appliesTo)&&i.appliesTo.length===0&&t.push({path:`$.invariants[${a}].appliesTo`,message:"must not be an empty array (omit the field to apply to the whole layer)"})})}function Ye(e,t="arkrules.json",n){if(!_e(e))throw new re(t,[{path:"$",message:`must be an object; received ${Oe(e)}`}]);let s=yr(e),r=[];if(Le(s,kt,"$",kt,r),gr(s,r),n!==void 0&&typeof s.layer=="string"&&s.layer!==n&&r.push({path:"$.layer",message:`must match referencing key ${JSON.stringify(n)}; received ${JSON.stringify(s.layer)}`}),r.length>0)throw new re(t,r);return{config:s}}function hr(e,t="arkrules.json",n){let s;try{s=JSON.parse(e)}catch(r){throw new re(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return Ye(s,t,n)}function xt(e){let t={},n=[],s=[],r=[...e].sort((i,a)=>i.layer.localeCompare(a.layer));for(let i of r){let a=(i.file.structure??[]).map(p=>({...p,mode:ln(p.mode),provenance:{sourceFile:i.sourceFile,ruleId:p.id,layer:i.layer}})),c=(i.file.invariants??[]).map(p=>({...p,mode:ln(p.mode),provenance:{sourceFile:i.sourceFile,ruleId:p.id,layer:i.layer}}));t[i.layer]={sourceFile:i.sourceFile,structure:a,invariants:c},n.push(...a),s.push(...c)}return n.sort((i,a)=>{let c=i.provenance.layer.localeCompare(a.provenance.layer);return c!==0?c:i.id.localeCompare(a.id)}),s.sort((i,a)=>{let c=i.provenance.layer.localeCompare(a.provenance.layer);return c!==0?c:i.id.localeCompare(a.id)}),{schemaVersion:"1.0",byLayer:t,structure:n,invariants:s}}function se(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}var We=class extends Error{issues;source;constructor(t,n){super(`Invalid Effective Contract (${t}):
7
+ ${n.map(s=>`- ${s.path}: ${s.message}`).join(`
8
+ `)}`),this.name="EffectiveContractError",this.source=t,this.issues=n}};function dn(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function Ar(e,t="ark.config.json"){let n=e.config.arkRules,s=[];if(!n||Object.keys(n).length===0){if(e.discoveredArkRulesFiles&&e.discoveredArkRulesFiles.length>0)for(let p of[...e.discoveredArkRulesFiles].sort())s.push({path:p,message:`ArkRules file ${JSON.stringify(p)} is not referenced by arkRules and will not be enforced`,severity:"advisory"});return{config:e.config,arkRules:se(),warnings:s}}let r=new Set(e.config.layers.map(p=>p.name)),i=[],a=[],c=new Set;for(let p of Object.keys(n).sort()){let y=n[p],h=`$.arkRules[${JSON.stringify(p)}]`;if(typeof y!="string"||y.length===0){i.push({path:h,message:"must be a non-empty relative path string"});continue}if(y.startsWith("/")||/^[A-Za-z]:[\\/]/.test(y)){i.push({path:h,message:"must be a project-relative path (absolute paths are not allowed)"});continue}if(!r.has(p)){i.push({path:h,message:`layer ${JSON.stringify(p)} is not declared in layers[]`});continue}let m=dn(y);c.add(m);let o=e.fileContents[m]??e.fileContents[y];if(o===void 0){i.push({path:h,message:`referenced ArkRules file ${JSON.stringify(m)} is missing`});continue}try{let l=Ye(JSON.parse(o),m,p);a.push({layer:p,sourceFile:m,file:l.config})}catch(l){if(l instanceof re)for(let g of l.issues)i.push({path:`${h}${g.path==="$"?"":g.path.replace(/^\$/,"")}`,message:`${m}: ${g.message}`});else l instanceof SyntaxError?i.push({path:h,message:`referenced ArkRules file ${JSON.stringify(m)} is not valid JSON: ${l.message}`}):i.push({path:h,message:`referenced ArkRules file ${JSON.stringify(m)} failed to load: ${l instanceof Error?l.message:String(l)}`})}}if(e.discoveredArkRulesFiles)for(let p of[...e.discoveredArkRulesFiles].sort()){let y=dn(p);c.has(y)||s.push({path:y,message:`ArkRules file ${JSON.stringify(y)} is not referenced by arkRules and will not be enforced`,severity:"advisory"})}if(i.length>0)throw new We(t,i);return{config:e.config,arkRules:xt(a),warnings:s}}function wt(e){return{config:e.config,arkRules:{schemaVersion:e.arkRules.schemaVersion,structure:e.arkRules.structure.map(t=>({id:t.id,sensor:t.sensor,mode:t.mode,appliesTo:t.appliesTo??null,description:t.description??null,provenance:t.provenance})),invariants:e.arkRules.invariants.map(t=>({id:t.id,description:t.description,aggregate:t.aggregate??null,coverage:t.coverage??null,mode:t.mode,appliesTo:t.appliesTo??null,provenance:t.provenance}))}}}function br(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*['"\`][^'"\`]*${n}[^'"\`]*['"\`]`,"i").test(e)||e.includes(t)}function Rr(e,t){if(!t)return!1;let n=t.split("."),s=n[n.length-1],r=n.length>1?n[0]:null;for(let i of Object.values(e))if(!(r&&!i.includes(r))&&(new RegExp(`(?:function\\s+|\\b)${s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[(<]`).test(i)||i.includes(t)))return!0;return!1}function $t(e){let t=e.arkRules.invariants??[];if(t.length===0)return{coverage:[],violations:[],partial:!1};let n=e.testFiles??[],s=e.testGlobsMissing===!0||n.length===0,r=[],i=[];for(let a of t){let c=[],p=a.coverage?.test!==!1,y=a.coverage?.symbol;if(!s&&p)for(let l of n){let g=e.fileContents[l];if(g&&br(g,a.id)){c.push("test-title");break}}y&&Rr(e.fileContents,y)&&c.push("symbol");let m=(a.coverage?.test===!0||!!y||a.coverage===void 0)&&c.length>0||a.coverage?.test===!1&&!y?!0:c.length>0,o=s&&p&&c.length===0;if(r.push({invariantId:a.id,layer:a.provenance.layer,sourceFile:a.provenance.sourceFile,mode:a.mode,covered:m&&!o,evidence:c,partial:o,description:a.description}),!m||o){let l=a.mode==="enforced"&&!o;i.push({ruleId:"INVARIANT_UNCOVERED",message:o?`Invariant ${a.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered.`:`Invariant ${a.id} is not covered by a test title or declared symbol.`,file:a.provenance.sourceFile,line:1,arkruleId:a.id,arkruleSource:a.provenance.sourceFile,fromLayer:a.provenance.layer,severity:l?"error":"warning",failsStrict:l})}}return{coverage:r,violations:i,partial:r.some(a=>a.partial)}}function Pt(e){return e?e.partial?{ok:!1,reason:"Coverage is partial (missing test globs); cannot promote until evidence is complete."}:e.covered?{ok:!0,reason:`Invariant ${e.invariantId} has coverage evidence.`}:{ok:!1,reason:`Invariant ${e.invariantId} is uncovered; add a test title or symbol before promoting to enforced.`}:{ok:!1,reason:"No coverage evidence supplied for this invariant; evaluate coverage before promoting to enforced."}}var Ot="1.0";function C(e,t){e.push({id:`${t.classification}:${t.path}:${t.kind}`,path:t.path,classification:t.classification,message:t.message,...t.classification==="weakening"||t.classification==="judgment-required"?{nextAction:`Restore the previous protection at ${t.path}, then run ArkGate again.`}:{},...t.before===void 0?{}:{before:t.before},...t.after===void 0?{}:{after:t.after}})}function M(e){return[...new Set(e??[])].sort()}function ie(e,t,n,s,r){let i=M(n),a=M(s),c=new Set(i),p=new Set(a),y=a.filter(m=>!c.has(m)),h=i.filter(m=>!p.has(m));y.length===0&&h.length===0||(y.length>0&&C(e,{kind:"added",path:t,classification:r.added,message:r.addedMessage,before:i,after:a}),h.length>0&&C(e,{kind:"removed",path:t,classification:r.removed,message:r.removedMessage,before:i,after:a}))}function Je(e,t,n,s,r,i,a){if(n===s)return;C(e,{kind:s?"enabled":"disabled",path:t,classification:s?r:r==="strengthening"?"weakening":"strengthening",message:s?i:a,before:n,after:s})}function Ze(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 vr(e,t,n){let s=Ze(t,i=>i.name),r=Ze(n,i=>i.name);(s.duplicates.length>0||r.duplicates.length>0)&&C(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:s.duplicates,after:r.duplicates});for(let i of[...new Set([...s.values.keys(),...r.values.keys()])].sort()){let a=s.values.get(i),c=r.values.get(i),p=`$.layers[${i}]`;if(!a&&c){C(e,{kind:"layer-added",path:p,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:c});continue}if(a&&!c){C(e,{kind:"layer-removed",path:p,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:a});continue}if(!a||!c)continue;ie(e,`${p}.patterns`,a.patterns,c.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),ie(e,`${p}.exclude`,a.exclude,c.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let y=Ve(a),h=Ve(c);ie(e,`${p}.forbiddenGlobals`,y.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."}),ie(e,`${p}.capabilities`,y.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)."}),M(a.intentPrefixes).join("\0")!==M(c.intentPrefixes).join("\0")&&C(e,{kind:"intent-prefixes-changed",path:`${p}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:M(a.intentPrefixes),after:M(c.intentPrefixes)}),Je(e,`${p}.mayImportInfrastructure`,a.mayImportInfrastructure===!0,c.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),Je(e,`${p}.optional`,a.optional===!0,c.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active.")}}function Ir(e,t,n){let s=a=>`${a.from}->${a.to}`,r=Ze(t,s),i=Ze(n,s);(r.duplicates.length>0||i.duplicates.length>0)&&C(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:r.duplicates,after:i.duplicates});for(let a of[...new Set([...r.values.keys(),...i.values.keys()])].sort()){let c=r.values.get(a),p=i.values.get(a),y=`$.rules[${a}]`;if(!c&&p){p.allowed===!1&&C(e,{kind:"deny-added",path:y,classification:"strengthening",message:"A denied dependency edge was added.",after:p});continue}if(c&&!p){c.allowed===!1&&C(e,{kind:"deny-removed",path:y,classification:"weakening",message:"A denied dependency edge was removed.",before:c});continue}if(!c||!p)continue;c.allowed!==p.allowed&&C(e,{kind:p.allowed?"deny-disabled":"deny-enabled",path:`${y}.allowed`,classification:p.allowed?"weakening":"strengthening",message:p.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:c.allowed,after:p.allowed});let h=c.peerIsolation===!0,m=p.peerIsolation===!0;if(h!==m){let o=c.from===c.to&&p.from===p.to;C(e,{kind:m?"peer-isolation-enabled":"peer-isolation-disabled",path:`${y}.peerIsolation`,classification:o?m?"strengthening":"weakening":"judgment-required",message:o?m?"Cross-slice dependencies inside this layer are now denied.":"Cross-slice dependencies inside this layer are no longer denied.":"Changing peer isolation on a cross-layer edge changes the denial scope.",before:h,after:m})}M(c.sliceFolders).join("\0")!==M(p.sliceFolders).join("\0")&&C(e,{kind:"slice-folders-changed",path:`${y}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:M(c.sliceFolders),after:M(p.sliceFolders)})}}function Cr(e,t,n){let s=t.safety??{},r=n.safety??{};for(let i of["maxTsSuppressions","maxAnyCasts"]){let a=s[i]??0,c=r[i]??0;a!==c&&C(e,{kind:c>a?"threshold-raised":"threshold-lowered",path:`$.safety.${i}`,classification:c>a?"weakening":"strengthening",message:c>a?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:a,after:c})}for(let i of["allowInMemory","allowDisabledPeerIsolation"])Je(e,`$.safety.${i}`,s[i]===!0,r[i]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}function Er(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 pn(e,t){return`${e}::${t}`}function un(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let s of e.structure)t.set(pn(s.provenance.layer,s.id),s);for(let s of e.invariants)n.set(pn(s.provenance.layer,s.id),s);return{structure:t,invariants:n}}function Sr(e,t,n,s,r,i){let a=new Map((i??[]).map(o=>[o.invariantId,o])),c=t.arkRules??{},p=n.arkRules??{},y=[...new Set([...Object.keys(c),...Object.keys(p)])].sort();for(let o of y){let l=c[o],g=p[o],u=`$.arkRules[${o}]`;if(l===void 0&&g!==void 0){C(e,{kind:"arkrules-ref-added",path:u,classification:"strengthening",message:`ArkRules reference for layer ${o} was added.`,after:g});continue}if(l!==void 0&&g===void 0){C(e,{kind:"arkrules-ref-removed",path:u,classification:"weakening",message:`ArkRules reference for layer ${o} was removed.`,before:l});continue}l!==g&&C(e,{kind:"arkrules-ref-path-changed",path:u,classification:"judgment-required",message:`ArkRules file path for layer ${o} changed; verify the effective rules still match intent.`,before:l,after:g})}let h=un(s),m=un(r);for(let o of[...new Set([...h.structure.keys(),...m.structure.keys()])].sort()){let l=h.structure.get(o),g=m.structure.get(o),u=`$.arkRules.structure[${o}]`;if(!l&&g){C(e,{kind:"arkrule-structure-added",path:u,classification:"strengthening",message:`Structure ArkRule ${g.id} was added (${g.mode}).`,after:g});continue}if(l&&!g){C(e,{kind:"arkrule-structure-removed",path:u,classification:"weakening",message:`Structure ArkRule ${l.id} was removed.`,before:l});continue}if(!(!l||!g)){if(l.mode!==g.mode){let b=l.mode==="advisory"&&g.mode==="enforced";C(e,{kind:b?"arkrule-promoted":"arkrule-demoted",path:`${u}.mode`,classification:b?"strengthening":"weakening",message:b?`Structure ArkRule ${g.id} was promoted to enforced.`:`Structure ArkRule ${g.id} was demoted to advisory.`,before:l.mode,after:g.mode})}l.sensor!==g.sensor&&C(e,{kind:"arkrule-sensor-changed",path:`${u}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${g.id} changed sensor identity.`,before:l.sensor,after:g.sensor})}}for(let o of[...new Set([...h.invariants.keys(),...m.invariants.keys()])].sort()){let l=h.invariants.get(o),g=m.invariants.get(o),u=`$.arkRules.invariants[${o}]`;if(!l&&g){C(e,{kind:"arkrule-invariant-added",path:u,classification:"strengthening",message:`Invariant ${g.id} was added (${g.mode}).`,after:g});continue}if(l&&!g){C(e,{kind:"arkrule-invariant-removed",path:u,classification:"weakening",message:`Invariant ${l.id} was removed.`,before:l});continue}if(!(!l||!g)&&l.mode!==g.mode)if(l.mode==="advisory"&&g.mode==="enforced"){let v=a?.get(g.id),d=Pt(v);d.ok?C(e,{kind:"arkrule-invariant-promoted",path:`${u}.mode`,classification:"strengthening",message:`Invariant ${g.id} was promoted to enforced (coverage evidence present).`,before:l.mode,after:g.mode}):C(e,{kind:"arkrule-invariant-promote-refused",path:`${u}.mode`,classification:"judgment-required",message:`Invariant ${g.id} cannot be promoted to enforced: ${d.reason}`,before:l.mode,after:g.mode})}else C(e,{kind:"arkrule-invariant-demoted",path:`${u}.mode`,classification:"weakening",message:`Invariant ${g.id} was demoted to advisory.`,before:l.mode,after:g.mode})}}function Lt(e,t,n){let s=[];ie(s,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),ie(s,"$.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."}),ie(s,"$.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."}),Je(s,"$.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 c=r[a]===r[i]?"judgment-required":r[a]>r[i]?"strengthening":"weakening";C(s,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:c,message:"The cycle enforcement level changed.",before:i,after:a})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&C(s,{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}),vr(s,e.layers,t.layers),Ir(s,e.rules,t.rules),Cr(s,e,t),Sr(s,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),s.sort((c,p)=>c.path.localeCompare(p.path)||c.id.localeCompare(p.id)),{schemaVersion:Ot,classification:Er(s),findings:s}}function _t(e,t){if(!e||e.schemaVersion!==Ot||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=M(e.findingIds),s=M(t.findingIds);return n.length===s.length&&n.every((r,i)=>r===s[i])}function ae(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 fn(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}function Xe(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}function N(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}function Te(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let 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 H(e,t,n){return e.startsWith(t,n)&&!Xe(e[n-1])&&!Xe(e[n+t.length])}function yn(e,t){let n=N(e,t);if(e[n]!=="{")return!1;n+=1;let s=!1;for(;n<e.length;){if(n=N(e,n),e[n]==="}")return s;if(e[n]===","){n+=1;continue}if(!H(e,"type",n))return!1;let r=N(e,n+4);if(r>=e.length||e[r]===","||e[r]==="}"||H(e,"as",r)||!fn(e[r]))return!1;for(n=r;n<e.length&&Xe(e[n]);)n+=1;if(n=N(e,n),H(e,"as",n)){if(n=N(e,n+2),!fn(e[n]))return!1;for(;n<e.length&&Xe(e[n]);)n+=1}s=!0}return!1}function kr(e,t){if(t=N(e,t+6),e[t]==="(")return Te(e,N(e,t+1));let n=!1;if(H(e,"type",t)){let r=N(e,t+4);e[r]!==","&&!H(e,"from",r)&&(n=!0)}else yn(e,t)&&(n=!0);let s=mn(e,t,!0);return s&&n?{...s,typeOnly:!0}:s}function xr(e,t){t=t+6;let n=N(e,t),s=!1;if(H(e,"type",n)){let i=N(e,n+4);(e[i]==="{"||e[i]==="*")&&(s=!0)}else yn(e,n)&&(s=!0);let r=mn(e,t,!1);return r&&s?{...r,typeOnly:!0}:r}function mn(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(H(e,"from",t))return Te(e,N(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return Te(e,t);if(t>0&&(H(e,"import",t)||H(e,"export",t)))return}}function wr(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 $r(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let s=N(e,t+7);if(e[s]!=="(")return;s=N(e,s+1);let r=Te(e,s);return r?{...r,requireCall:!0}:void 0}function Pr(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(`
9
+ `,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=wr(e,n);continue}if(s==="'"||s==='"'){let i=Te(e,n);i&&(n=i.offset+i.excerpt.length-1);continue}let r=s==="i"&&H(e,"import",n)?kr(e,n):s==="e"&&H(e,"export",n)?xr(e,n):s==="r"&&H(e,"require",n)?$r(e,n):void 0;r&&(t.push(r),n=r.offset+r.excerpt.length-1)}return t}function gn(e,t){let n=[],s=[];for(let r of Pr(e.content)){let i=r.value;if(!i.startsWith(".")){if(r.typeOnly)continue;let y=Ie(i);if(!y)continue;let h=e.content.slice(0,r.offset).split(`
10
+ `).length;s.push({file:e.path,symbol:i,capability:y,evidence:{kind:"import",file:e.path,line:h,excerpt:r.excerpt}});continue}let a=e.content.slice(0,r.offset).split(`
11
+ `).length,c={kind:"import",file:e.path,line:a,excerpt:r.excerpt},p=Or(e.path,i,t);n.push({from:e.path,specifier:i,to:p?.path??null,resolution:p?"resolved":"unresolved",fromLayer:e.layer,toLayer:p?.layer??null,evidence:c})}return{edges:n,capabilityUses:s}}function Or(e,t,n){let s=e.split("/");s.pop();for(let i of t.split("/"))i==="."||i===""||(i===".."?s.pop():s.push(i));let r=s.join("/");for(let i of[r,`${r}.ts`,`${r}.tsx`,`${r}.mts`,`${r}.cts`,`${r}/index.ts`,`${r}/index.tsx`]){let a=n.get(i);if(a)return a}}function hn(e,t){let n=[];for(let s of e){if(!s.to||!s.fromLayer||!s.toLayer)continue;let r=K(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 Lr={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 _r(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}function Tr(e,t){return _r(e,t)?w(k(wt({config:e,arkRules:t,warnings:[]}))):w(k(e))}function Qe(e,t,n){let s=typeof e=="string"?vt(e,t):Be(e,t),r=n?.arkRules??se();return{...s,arkRules:r,policyHash:Tr(s.config,r)}}function An(e){let t=Qe(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=Qe(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),s=Lt(t.config,n.config,{baseArkRules:t.arkRules,candidateArkRules:n.arkRules,candidateInvariantCoverage:e.candidateInvariantCoverage}),r=s.findings.filter(c=>c.classification==="weakening"||c.classification==="judgment-required").map(c=>c.id).sort(),i=r.length>0,a=i&&_t(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:r});return{schemaVersion:s.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:s.classification,findings:s.findings,blockingFindingIds:r,requiresAcknowledgement:i,acknowledged:a,valid:!i||a}}function Fe(e){let t=e.files.map(m=>{let o=ae(m.path);return{path:o,content:m.content,contentHash:w(m.content),layer:z(o,e.contract.config.layers)??null}}).sort((m,o)=>m.path.localeCompare(o.path)),n=new Map(t.map(m=>[m.path,m])),s=[],r=[];for(let m of t){let o=gn(m,n);s.push(...o.edges),r.push(...o.capabilityUses)}let i=hn(s,e.contract.config),a=new Map(e.contract.config.layers.map(m=>[m.name,m])),c=new Map(e.contract.config.layers.map(m=>[m.name,new Set(le(m))]));for(let m of r){let o=n.get(m.file)?.layer;if(!o)continue;let l=a.get(o),g=J(m.symbol,l?.forbiddenGlobals??[]);if(g){i.push({ruleId:"FORBIDDEN_GLOBAL",message:`${o} must not use module "${m.symbol}" because it is the import form of forbidden global "${g}".`,symbol:m.symbol,evidence:m.evidence});continue}c.get(o)?.has(m.capability)&&i.push({ruleId:"CAPABILITY_VIOLATION",message:`${o} denies the ${m.capability} capability; found import of "${m.symbol}".`,capability:m.capability,symbol:m.symbol,evidence:m.evidence})}let p=t.length===0?"complete":"partial",y=p==="complete"?[]:[{...Lr}],h={schemaVersion:Et,policyHash:e.contract.policyHash,compilerOptionsHash:w(k(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(m=>m.name),edges:s,capabilityUses:r,violations:i};return{mode:"lexical-compatibility",completeness:p,completenessReasons:y,valid:p==="complete"&&i.length===0,ir:h}}function et(e){let t=new Map(e.files.map(n=>[ae(n.path),n]));for(let n of e.changes){let s=ae(n.path);"delete"in n&&n.delete?t.delete(s):"content"in n&&t.set(s,{path:s,content:n.content})}return Fe({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}function bn(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 Tt(e){let t=0,n=new Map,s=new Map,r=new Set,i=[],a=[],c=p=>{n.set(p,t),s.set(p,t),t+=1,i.push(p),r.add(p);for(let m of[...e.get(p)??[]].sort())e.has(m)&&(n.has(m)?r.has(m)&&s.set(p,Math.min(s.get(p)??0,n.get(m)??0)):(c(m),s.set(p,Math.min(s.get(p)??0,s.get(m)??0))));if(s.get(p)!==n.get(p))return;let y=[],h;do{if(h=i.pop(),h===void 0)break;r.delete(h),y.push(h)}while(h!==p);y.length>1&&a.push(y.sort())};for(let p of[...e.keys()].sort())n.has(p)||c(p);return a.sort((p,y)=>p[0]<y[0]?-1:p[0]>y[0]?1:0).map(p=>({ruleId:"CIRCULAR_DEPENDENCY",file:p[0],line:1,target:p.join(" \u2192 "),message:`Circular dependency among ${p.length} files: ${p.join(" \u2192 ")} \u2192 ${p[0]}.`,cycleKind:"value"}))}function Ae(e){let t=e.contentViolations.map(i=>({...i})),n=(e.warnings??[]).map(i=>({...i})),s=new Map(e.files.map(i=>[i,new Set]));for(let i of e.edges){if(i.to&&i.to!==i.from&&!i.typeOnly&&s.has(i.from)&&s.get(i.from)?.add(i.to),!i.to||!i.fromLayer||!i.toLayer)continue;let a=K(e.rules,i.fromLayer,i.toLayer,{fromPath:i.from,toPath:i.to,layers:e.config.layers});if(!a)continue;let c=!!a.peerIsolation;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:i.from,line:i.line,fromLayer:i.fromLayer,toLayer:i.toLayer,target:i.to,...i.typeOnly?{typeOnly:!0}:{},...i.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...i.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...i.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!c&&i.portProofEligible?{portProofEligible:!0}:{},...i.kind?{edgeKind:i.kind}:{},...c?{peerIsolation:!0}:{},message:a.message??(c?`${i.fromLayer} must not ${i.kind} another slice of ${i.toLayer} (${i.from} \u2192 ${i.to}). Extract shared code or use events/ports across slices.`:`${i.fromLayer} must not ${i.kind} ${i.toLayer}.`)})}let r=String(e.config.cyclePolicy??"strict").toLowerCase();if(r!=="off"){let i=Tt(s);r==="soft"||r==="framework-soft"?n.push(...i.map(a=>({...a,message:`${a.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...i)}return{violations:t,warnings:n,safety:e.safety}}var Fr=["no-anemic-model"];function Rn(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function Nr(e){let t="";for(let s=0;s<e.length;s+=1){let r=e[s];if(r==="\\"&&s+1<e.length){let i=e[s+1];if("*?{}[],".includes(i)||i==="\\"){t+="\\"+i,s+=1;continue}t+="/";continue}t+=r}let n="";for(let s=0;s<t.length;s+=1){let r=t[s];r==="\\"&&s+1<t.length?(n+=Rn(t[s+1]),s+=1):r==="*"?t[s+1]==="*"?t[s+2]==="/"?(n+="(?:.*/)?",s+=2):(n+=".*",s+=1):n+="[^/]*":r==="?"?n+="[^/]":n+=Rn(r)}return new RegExp(`^${n}$`)}function Ne(e,t){return!t||t.length===0?!0:t.some(n=>Nr(n).test(e))}function Dr(e){return Fr.includes(e)}function vn(e){return e.mode==="enforced"&&!Dr(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}function be(e,t,n,s=1){let{severity:r,failsStrict:i}=vn(e);return{ruleId:"ARKRULE_STRUCTURE",code:e.sensor,message:n,file:t,line:s,fromLayer:e.provenance.layer,arkruleId:e.id,arkruleSource:e.provenance.sourceFile,severity:r,sensor:e.sensor,failsStrict:i}}function tt(e,t,n){return t.filter(s=>{if(!s.exported||!Ne(s.file,e.appliesTo))return!1;if(n){let r=n(s.file);if(r&&r!==e.provenance.layer)return!1}return!0})}function Mr(e,t,n){let s=[];for(let r of tt(e,t,n))(r.hasPublicMutableFields||r.hasPublicSetters)&&s.push(be(e,r.file,`Exported class ${r.className} exposes public mutable state (sensor aggregate-private-state).`));return s}function Hr(e,t,n){let s=[];for(let r of tt(e,t,n))r.hasPublicConstructor&&!r.hasStaticFactory&&s.push(be(e,r.file,`Exported class ${r.className} exposes a public constructor without a static factory (sensor always-valid-factory).`));return s}function Vr(e,t,n){let s=[];for(let r of tt(e,t,n))for(let i of r.mutatingMethods)i.referencesGuardOrPublish||s.push(be(e,r.file,`Mutating method ${r.className}.${i.name} does not reference a guard or publish symbol (sensor domain-event-on-mutation).`));return s}function jr(e,t){let n=[];for(let s of t.files)if(Ne(s,e.appliesTo)){if(t.layerForFile){let r=t.layerForFile(s);if(r&&r!==e.provenance.layer)continue}t.fileHints?.[s]?.orchestrationHeavy&&n.push(be(e,s,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."))}return n}function Ur(e,t){let n=[];for(let s of t.files)if(Ne(s,e.appliesTo)){if(t.layerForFile){let r=t.layerForFile(s);if(r&&r!==e.provenance.layer)continue}t.fileHints?.[s]?.adapterThick&&n.push(be(e,s,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."))}return n}function Gr(e,t,n){let s=[];for(let r of tt(e,t,n))if(r.dataOnly===!0){let i=be(e,r.file,`Exported type ${r.className} looks data-only / anemic (sensor no-anemic-model; advisory only).`);s.push({...i,severity:"warning",failsStrict:!1})}return s}function Ft(e){if(!e.arkRules.structure.length)return[];let t=[];for(let n of e.arkRules.structure)switch(n.sensor){case"aggregate-private-state":t.push(...Mr(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...Hr(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...Vr(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...jr(n,e));break;case"thin-adapter":t.push(...Ur(n,e));break;case"no-anemic-model":t.push(...Gr(n,e.classShapes,e.layerForFile));break;case"invariant-coverage":break;default:break}return t.sort((n,s)=>n.file.localeCompare(s.file)||n.arkruleId.localeCompare(s.arkruleId)||n.message.localeCompare(s.message))}function Nt(e,t){let n=[],s=t.map(r=>r.replace(/\\/g,"/"));for(let r of e.structure){if(!r.appliesTo||r.appliesTo.length===0||s.some(p=>Ne(p,r.appliesTo)))continue;let{severity:a,failsStrict:c}=vn(r);n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule structure "${r.id}" appliesTo matched zero governed files (patterns: ${r.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:r.provenance.sourceFile,line:1,fromLayer:r.provenance.layer,arkruleId:r.id,arkruleSource:r.provenance.sourceFile,severity:a,sensor:r.sensor,failsStrict:c})}for(let r of e.invariants??[]){if(!r.appliesTo||r.appliesTo.length===0||s.some(c=>Ne(c,r.appliesTo)))continue;let a=r.mode==="enforced";n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule invariant "${r.id}" appliesTo matched zero governed files (patterns: ${r.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:r.provenance.sourceFile,line:1,fromLayer:r.provenance.layer,arkruleId:r.id,arkruleSource:r.provenance.sourceFile,severity:a?"error":"warning",sensor:"invariant-coverage",failsStrict:a})}return n.sort((r,i)=>r.file.localeCompare(i.file)||r.arkruleId.localeCompare(i.arkruleId)||r.message.localeCompare(i.message))}var Br=/\bfrom\s+['"](?:@?prisma\/client|@supabase\/|drizzle-orm|typeorm|knex|mongodb|pg|mysql2|better-sqlite3|ioredis|redis)['"]|require\(\s*['"](?:@?prisma\/client|pg|knex|typeorm)/,qr=/\b(?:@Controller|@Get|@Post|@Put|@Delete|Router\(\)|createRouter|express\.Router|fastify\.(?:get|post)|export\s+(?:async\s+)?function\s+(?:GET|POST|PUT|DELETE|PATCH)\b|export\s+const\s+(?:GET|POST|PUT|DELETE|PATCH)\s*=)/,zr=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,Kr=/\b(?:export\s+)?(?:async\s+)?function\s+(?:can|calculate|compute|should|ensure|validate|is|has)[A-Z]\w*|\b(?:export\s+)?const\s+(?:can|calculate|compute|should|ensure|validate|is|has)[A-Z]\w*\s*=/,Yr=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function In(e,t){if(!t||t.length<40)return null;let n=t.match(new RegExp(Kr.source,"g"))??[],s=t.match(new RegExp(Yr.source,"g"))??[],r=(t.match(/\bif\s*\(/g)??[]).length,i=(t.match(/\bswitch\s*\(/g)??[]).length,a=n.length>=2||n.length>=1&&s.length>=2||s.length>=3&&r+i>=6,c=Br.test(t),p=qr.test(t)||zr.test(t),y=n.length>=1||s.length>=2,h=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),m=c&&y||p&&y||c&&h&&(r>=4||n.length>=1)||p&&c;return!a&&!m?null:{...a?{orchestrationHeavy:!0}:{},...m?{adapterThick:!0}:{}}}function Dt(e){let t={};for(let[n,s]of Object.entries(e)){let r=In(n,s);r&&(t[n.replace(/\\/g,"/")]=r)}return t}function Wr(e,t){let n=[],s=/export\s+(?:abstract\s+)?class\s+([A-Za-z_][A-Za-z0-9_]*)\s*(?:extends\s+[^{]+)?(?:implements\s+[^{]+)?\{/g,r;for(;(r=s.exec(t))!==null;){let i=r[1],a=r.index+r[0].length,c=1,p=a;for(;p<t.length&&c>0;){let E=t[p];E==="{"?c+=1:E==="}"&&(c-=1),p+=1}let y=t.slice(a,p-1),h=/(?:^|\n)\s*(?:public\s+)?(?:readonly\s+)?[a-zA-Z_][a-zA-Z0-9_]*\s*[:=]/m.test(y.replace(/(?:public\s+|private\s+|protected\s+|readonly\s+|static\s+|async\s+|get\s+|set\s+)/g,""))&&/(?:^|\n)\s*(public\s+)?(?!constructor|static|get|set|private|protected|readonly)[a-zA-Z_][a-zA-Z0-9_]*\s*[:=]/m.test(y),m=/(?:^|\n)\s*public\s+(?!static|async|get|set|constructor)[a-zA-Z_]/.test(y)||/(?:^|\n)\s*[a-zA-Z_][a-zA-Z0-9_]*\s*:\s*[^=;\n]+[;=]/m.test(y.split(`
12
+ `).filter(E=>!/^\s*(private|protected|static|constructor|get |set |async |\/)/.test(E)).join(`
13
+ `)),o=/(?:^|[\n;{])\s*(?:public\s+)?set\s+[a-zA-Z_]/.test(y),l=/(?:^|[\n;{])\s*private\s+constructor\s*\(/.test(y),g=/(?:^|[\n;{])\s*(?:public\s+)?constructor\s*\(/.test(y)&&!l,u=/(?:^|[\n;{])\s*static\s+(?:async\s+)?(?:create|of|from|parse|build|make|new)\s*[<(]/.test(y)||/(?:^|[\n;{])\s*static\s+(?:async\s+)?[A-Za-z_][A-Za-z0-9_]*\s*\([^)]*\)\s*:\s*[A-Za-z_]/.test(y),b=[],v=/(?:^|\n)\s*(?:public\s+|private\s+|protected\s+|async\s+)*(?!constructor|get|set|static)([a-zA-Z_][a-zA-Z0-9_]*)\s*\([^)]*\)\s*(?::\s*[^{]+)?\{/g,d;for(;(d=v.exec(y))!==null;){let E=d[1],O=d.index+d[0].length,L=1,_=O;for(;_<y.length&&L>0;)y[_]==="{"?L+=1:y[_]==="}"&&(L-=1),_+=1;let oe=y.slice(O,_-1);if(!/this\.\w+\s*=/.test(oe))continue;let Me=/\b(ensureInvariants|assertInvariants|validate|publish|emit|raise|record)\b/.test(oe);b.push({name:E,referencesGuardOrPublish:Me})}let R=(y.match(/(?:^|\n)\s*(?:public\s+|private\s+|protected\s+)?(?:async\s+)?[a-zA-Z_][a-zA-Z0-9_]*\s*\(/g)??[]).length<=1&&(m||h);n.push({file:e,className:i,exported:!0,hasPublicMutableFields:m||h,hasPublicSetters:o,hasPublicConstructor:g,hasStaticFactory:u,mutatingMethods:[...b],dataOnly:R})}return n}function T(e,t,n={}){return{ruleId:e,message:t,...n}}function nt(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(T("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(T("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let l of["maxTsSuppressions","maxAnyCasts"]){let g=t.safety[l];g!==void 0&&(!Number.isInteger(g)||g<0)&&i.push(T("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${l} must be a non-negative integer.`))}let a=Array.isArray(t.layers)?t.layers:[],c=Array.isArray(r?.architecture?.layers)?r.architecture.layers:[],p=new Set([...a.map(l=>l.name).filter(Boolean),...c.map(l=>l.name).filter(l=>!!l)]);a.length===0&&i.push(T("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let y=new Set,h=new Set;for(let l of a){if(!l.name){i.push(T("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}y.has(l.name)&&h.add(l.name),y.add(l.name),l.forbiddenGlobals!==void 0&&(!Array.isArray(l.forbiddenGlobals)||l.forbiddenGlobals.some(u=>typeof u!="string"))&&i.push(T("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 g=Array.isArray(l.patterns)?l.patterns:[];if(g.length===0){i.push(T("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${l.name}" has no file patterns and will never classify files.`,{layer:l.name}));continue}for(let u of g){let b;try{b=ee(u)}catch(v){i.push(T("CONFIG_INVALID_LAYER_PATTERN",`Layer "${l.name}" has an invalid pattern "${u}": ${v instanceof Error?v.message:String(v)}`,{layer:l.name,pattern:u}));continue}!s.some(v=>b.test(v))&&!l.optional&&i.push(T("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${l.name}" pattern "${u}" matched no included files.`,{layer:l.name,pattern:u,failsStrict:!1}))}}for(let l of h)i.push(T("CONFIG_DUPLICATE_LAYER",`Layer "${l}" is configured more than once.`,{layer:l}));if(p.size>0)for(let l of n??[])l.from&&!p.has(l.from)&&i.push(T("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${l.from}".`,{fromLayer:l.from,toLayer:l.to})),l.to&&!p.has(l.to)&&i.push(T("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${l.to}".`,{fromLayer:l.from,toLayer:l.to}));let m=new Set;if(a.length>1)for(let l of s){let g=-1,u=[];for(let b of a)for(let v of b.patterns??[]){if(!ee(v).test(l))continue;let d=ut(v);d>g?(g=d,u=[b.name]):d===g&&!u.includes(b.name)&&u.push(b.name)}u.length>1&&m.add([...u].sort().join(" + "))}m.size>0&&i.push(T("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...m].join(", ")}.`,{pairs:[...m]}));let o=s.filter(l=>!z(l,a));return o.length>0&&i.push(T("CONFIG_UNCLASSIFIED_FILES",`${o.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:o.length,samples:o.slice(0,5)})),i}function Jr(e,t){return t.some(n=>{try{return ee(n).test(e)}catch{return!1}})}function Zr(e,t){let n=e.contract.config.safety??{},s=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,r=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,i=e.contract.config.dynamicImportAllowlist??[],a=t.safetyUses.filter(u=>u.kind==="ts-suppression").map(({file:u,line:b})=>({file:u,line:b})),c=t.safetyUses.filter(u=>u.kind==="any-cast").map(({file:u,line:b})=>({file:u,line:b})),p=t.safetyUses.filter(u=>(u.kind==="dynamic-import"||u.kind==="dynamic-require")&&!Jr(u.file,i)).map(u=>({file:u.file,line:u.line,kind:u.kind==="dynamic-require"?"require":"import"})),y=n.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(u=>u.kind==="in-memory-store").map(u=>({file:u.file,line:u.line,store:u.symbol??"in-memory store"})),h=n.allowDisabledPeerIsolation===!0?[]:(e.contract.config.rules??[]).filter(u=>u.peerIsolation===!1||u.allowed===!1&&!!u.from&&u.from===u.to&&u.peerIsolation!==!0).map(u=>({from:u.from,to:u.to})),m={tsSuppressions:a,anyCasts:c,nonLiteralDynamicImports:p,inMemoryProductionStores:y,disabledPeerIsolationRules:h,thresholds:{maxTsSuppressions:s,maxAnyCasts:r}},o=[],l=p.filter(u=>u.kind==="import");if(l.length>0){let u=l[0];o.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:u.file,line:u.line,message:`${l.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let g=p.filter(u=>u.kind==="require");if(g.length>0){let u=g[0];o.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:u.file,line:u.line,message:`${g.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(a.length>s){let u=a[0];o.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:u.file,line:u.line,message:`${a.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${s}).`})}if(c.length>r){let u=c[0];o.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:u.file,line:u.line,message:`${c.length} explicit any cast(s) exceed safety.maxAnyCasts (${r}).`})}if(y.length>0){let u=y[0];o.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:u.file,line:u.line,message:`${y.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&&o.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:o}}function Xr(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,s)=>s.length-n.length)[0]}function Cn(e,t){let n=t.config.layers.filter(s=>(s.intentPrefixes??[]).length>0);return At(e,n.length>0?n:ht.map(s=>({name:s.layer,prefixes:s.prefixes})))}function Qr(e,t,n){let s=[],r=new Map(e.contract.config.layers.map(i=>[i.name,i]));for(let i of t.ambientUses){let a=n.get(i.file);!a||!Xr(i.symbol,r.get(a)?.forbiddenGlobals??[])||s.push({ruleId:"FORBIDDEN_GLOBAL",file:i.file,line:i.line,fromLayer:a,target:i.symbol,message:`${a} must not use the ambient global "${i.symbol}".`})}for(let i of t.capabilityUses){let a=n.get(i.file);if(!a)continue;let c=r.get(a),p=c?.forbiddenGlobals??[],y=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"&&Ce(i.symbol,p))){if(i.source==="import-based"){let h=J(i.symbol,p);if(h){s.push({ruleId:"FORBIDDEN_GLOBAL",file:i.file,line:i.line,fromLayer:a,target:i.symbol,...y?{edgeKind:y}:{},message:`${a} must not use module "${i.symbol}" because it is the import form of forbidden global "${h}".`});continue}}le(c).includes(i.capability)&&s.push({ruleId:"CAPABILITY_VIOLATION",file:i.file,line:i.line,fromLayer:a,target:i.symbol,capability:i.capability,...y?{edgeKind:y}:{},message:i.source==="import-based"?`${a} denies the ${i.capability} capability; found import of "${i.symbol}".`:`${a} denies the ${i.capability} capability; found ambient "${i.symbol}".`})}}for(let i of t.publishCalls){let a=n.get(i.file);if(!a)continue;for(let p of Ee({publishCall:!0,rawIntentName:i.rawIntentName,objectHasIntent:i.objectHasIntent,arkPublishCandidate:i.arkPublishCandidate,hasSource:i.hasSource}))s.push({ruleId:p.ruleId,file:i.file,line:i.line,...p.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:a}:{},message:p.message});if(!i.sourceIntent)continue;let c=Cn(i.sourceIntent,e.contract);!c||c===a||s.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:i.file,line:i.line,fromLayer:a,toLayer:c,target:i.sourceIntent,message:`Publish source "${i.sourceIntent}" resolves to ${c}, but the publishing file is classified as ${a}.`})}for(let i of t.intentReferences){let a=n.get(i.file);if(!a)continue;let c=Cn(i.intent,e.contract);if(!c)continue;let p=K(e.contract.config.rules,a,c);p&&s.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:i.file,line:i.line,fromLayer:a,toLayer:c,target:i.intent,message:p.message??`${a} must not reference ${c} intent ${i.intent}.`})}return s}function es(e){let{facts:t}=e,n=$e(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((A,j)=>{let Re=`${A.code}\0${A.file??""}\0${A.message}`,ve=`${j.code}\0${j.file??""}\0${j.message}`;return Re<ve?-1:Re>ve?1:0}),a=t.files.map(A=>({...A,layer:z(A.path,e.contract.config.layers)??null})),c=new Map(a.map(A=>[A.path,A.layer])),p=t.dependencies.map(A=>{let j=A.target?c.get(A.target)??z(A.target,e.contract.config.layers):void 0;return{from:A.from,fromLayer:c.get(A.from)??null,...A.resolution==="resolved-project"&&A.target?{to:A.target,...j?{toLayer:j}:{}}:{},line:A.line,kind:A.kind,typeOnly:A.typeOnly,...A.targetTypeOnlyExports?{targetTypeOnlyExports:A.targetTypeOnlyExports}:{},...A.sourcePureTypeModule?{sourcePureTypeModule:A.sourcePureTypeModule}:{},...A.namedBindingsTypeOnly?{namedBindingsTypeOnly:A.namedBindingsTypeOnly}:{},...A.portProofEligible?{portProofEligible:A.portProofEligible}:{}}}),y=nt({config:e.contract.config,rules:e.contract.config.rules,files:a.map(A=>A.path)}),h=Zr(e,t),m=e.contract.arkRules??se(),o=a.map(A=>A.path),g={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?Dt(e.coverageInputs.fileContents):{},...e.fileHints??{}},u=[...Ft({arkRules:m,classShapes:e.contract.classShapes??t.classShapes??[],files:o,layerForFile:A=>c.get(A)??z(A,e.contract.config.layers),fileHints:g}),...Nt(m,o)],b=u.filter(A=>A.failsStrict).map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,arkruleId:A.arkruleId,arkruleSource:A.arkruleSource,nextAction:A.ruleId==="ARKRULE_SCOPE_EMPTY"?`Fix appliesTo globs for ${A.arkruleId} in ${A.arkruleSource} so they match governed files, or remove the rule.`:`Fix the structure or invariant for ${A.arkruleId} (declared in ${A.arkruleSource}), then preflight again.`})),v=u.filter(A=>!A.failsStrict).map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,arkruleId:A.arkruleId,arkruleSource:A.arkruleSource,failsStrict:!1,nextAction:A.ruleId==="ARKRULE_SCOPE_EMPTY"?`Review appliesTo for ${A.arkruleId} in ${A.arkruleSource} (zero-match scope; advisory).`:`Review ArkRule ${A.arkruleId} in ${A.arkruleSource} (advisory).`})),f=(m.invariants?.length??0)>0?$t({arkRules:m,fileContents:e.coverageInputs?.fileContents??{},testFiles:e.coverageInputs?.testFiles??[],testGlobsMissing:e.coverageInputs?.testGlobsMissing===!0||e.coverageInputs===void 0||(e.coverageInputs.testFiles?.length??0)===0}):{coverage:[],violations:[],partial:!1},R=f.violations.filter(A=>A.failsStrict).map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,arkruleId:A.arkruleId,arkruleSource:A.arkruleSource,nextAction:`Add a test title or declared symbol covering ${A.arkruleId} (declared in ${A.arkruleSource}), then preflight again.`})),E=f.violations.filter(A=>!A.failsStrict).map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,arkruleId:A.arkruleId,arkruleSource:A.arkruleSource,failsStrict:!1,nextAction:`Cover invariant ${A.arkruleId} in ${A.arkruleSource} (advisory / partial).`})),L=f.partial&&f.coverage.some(A=>A.mode==="enforced"&&A.partial)?[{code:"INVARIANT_COVERAGE_PARTIAL",message:"Enforced ArkRules invariant coverage cannot be fully proven (missing test globs or empty test set); reporting partial, never covered."}]:[],_=Ae({config:e.contract.config,rules:e.contract.config.rules,files:a.filter(A=>A.layer).map(A=>A.path),contentViolations:[...Qr(e,t,c),...b,...R],edges:p,warnings:[...y,...h.warnings,...v,...E],safety:h.report}),oe=r==="complete"&&L.length>0?"partial":r,Mt=oe==="complete"?i:[...i,...L].sort((A,j)=>{let Re=`${A.code}\0${A.file??""}\0${A.message}`,ve=`${j.code}\0${j.file??""}\0${j.message}`;return Re<ve?-1:Re>ve?1:0}),Me=oe==="complete"&&_.violations.length===0,xn=Me&&_.warnings.every(A=>A.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:oe,completenessReasons:Mt,valid:Me,strictValid:xn,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:a,layers:e.contract.config.layers.map(A=>A.name),edges:p,capabilityUses:t.capabilityUses,violations:_.violations,warnings:_.warnings}}}function De(e){return es({contract:e.contract,facts:Q(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints})}function rt(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return e.typeOnly||e.targetTypeOnlyExports||e.namedBindingsTypeOnly?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":e.peerIsolation?"Extract the shared dependency to a shared layer, then preflight again.":`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, then preflight again.`;case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, then preflight again.`;case"CAPABILITY_VIOLATION":return`Define a ${String(e.capability??"capability")} port in ${e.fromLayer??"the walled layer"}, bind the implementation outside it, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";case"ARKRULE_STRUCTURE":case"ARKRULE_INVARIANT":case"INVARIANT_UNCOVERED":return`Fix the structure or invariant for ${typeof e.arkruleId=="string"&&e.arkruleId.length>0?e.arkruleId:"the ArkRule"} (declared in ${typeof e.arkruleSource=="string"&&e.arkruleSource.length>0?e.arkruleSource:"arkrules/<Layer>.json"}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`;default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}function En(e){return w(k(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}function Sn(e){let t=Fe(e),n=new Map(t.ir.files.map(l=>[l.path,l])),s=[],r=new Set,i=[];for(let l of e.changes){let g=l.path.replace(/\\/g,"/"),u=ae(l.path);if(!u||u===".."||u.startsWith("../")||g.startsWith("/")||/^[A-Za-z]:\//.test(g)||g.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(u)){i.push({ruleId:"DUPLICATE_CHANGE_PATH",file:u,line:1,message:`The atomic change set contains more than one operation for ${u}.`});continue}r.add(u),"delete"in l&&l.delete&&!n.has(u)&&i.push({ruleId:"DELETE_TARGET_MISSING",file:u,line:1,message:`Cannot delete ${u} because it is not present in the supplied base tree.`}),s.push("delete"in l&&l.delete?{path:u,delete:!0}:{path:u,content:"content"in l?l.content:""})}e.changes.length===0&&i.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let a=et({...e,changes:s}),c=new Map(a.ir.files.map(l=>[l.path,l])),p=a.ir.violations.filter(l=>l.ruleId==="CAPABILITY_VIOLATION"||l.ruleId==="FORBIDDEN_GLOBAL").map(l=>{let g=c.get(l.evidence.file)?.layer;return{ruleId:l.ruleId,file:l.evidence.file,line:l.evidence.line,target:l.symbol,...l.capability?{capability:l.capability}:{},...g?{fromLayer:g}:{},edgeKind:"import",message:l.message}}),y=Ae({config:e.contract.config,rules:e.contract.config.rules,files:a.ir.files.map(l=>l.path),contentViolations:p,edges:a.ir.edges.filter(l=>!!l.fromLayer).map(l=>({from:l.from,fromLayer:l.fromLayer,...l.to?{to:l.to}:{},...l.toLayer?{toLayer:l.toLayer}:{},line:l.evidence.line,kind:"import"}))}),h=s.map(l=>{let g=ae(l.path),u=n.get(g),b=c.get(g);return{path:g,operation:"delete"in l&&l.delete?"delete":u?"update":"create",...u?{beforeContentHash:u.contentHash}:{},...b?{candidateContentHash:b.contentHash}:{}}}).sort((l,g)=>l.path.localeCompare(g.path)),m=[...i,...y.violations].map(l=>({...l,nextAction:rt(l)})),o=e.changeMap?he({changeMap:e.changeMap,changes:h,baseDependencies:t.ir.edges.flatMap(l=>l.to?[{from:l.from,to:l.to}]:[]),candidateDependencies:a.ir.edges.flatMap(l=>l.to?[{from:l.from,to:l.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&a.valid&&m.length===0&&(o?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:a.ir.compilerOptionsHash,baseTreeHash:En(t.ir.files),candidateTreeHash:En(a.ir.files),baseCompleteness:t.completeness,candidateCompleteness:a.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:a.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...o?{convergence:o}:{},changes:h,violations:m,warnings:y.warnings}}function ts(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 ns(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 rs(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 kn(e){let t=Q(e.baseFacts),n=Q(e.candidateFacts),s=De({contract:e.contract,facts:t}),r=De({contract:e.contract,facts:n}),i=new Map(t.files.map(o=>[o.path,o])),a=new Map(n.files.map(o=>[o.path,o])),c=ns(t,n),p=new Map,y=[];for(let o of e.changes){let l=ts(o.path);if(!l){c.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(p.has(l)){c.push({ruleId:"DUPLICATE_CHANGE_PATH",file:l,line:1,message:`The atomic change set contains more than one operation for ${l}.`});continue}p.set(l,o);let g=i.get(l),u=a.get(l);if("delete"in o&&o.delete)g||c.push({ruleId:"DELETE_TARGET_MISSING",file:l,line:1,message:`Cannot delete ${l} because it is not present in the supplied base facts.`}),u&&c.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:l,line:1,message:`Candidate facts still contain deleted file ${l}.`});else{let b="content"in o?o.content:"",v=w(b);u?u.contentHash!==v&&c.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:l,line:1,expectedContentHash:v,candidateContentHash:u.contentHash,message:`Candidate facts for ${l} do not match the declared content.`}):c.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:l,line:1,message:`Candidate facts do not contain changed file ${l}.`})}y.push(rs(o,l,i,a))}e.changes.length===0&&c.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});for(let o of new Set([...i.keys(),...a.keys()])){if(p.has(o))continue;let l=i.get(o),g=a.get(o);l&&g&&k(l)===k(g)||c.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:o,line:1,message:`Candidate facts change ${o}, but the atomic change set does not declare it.`})}let h=e.changeMap?he({changeMap:e.changeMap,changes:y,baseDependencies:s.ir.edges.flatMap(o=>o.to?[{from:o.from,to:o.to}]:[]),candidateDependencies:r.ir.edges.flatMap(o=>o.to?[{from:o.from,to:o.to}]:[])}):void 0,m=[...c,...r.ir.violations].map(o=>({...o,nextAction:rt(o)}));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:y.sort((o,l)=>o.path<l.path?-1:o.path>l.path?1:0),violations:m,warnings:r.ir.warnings}}function st(e,t){return e.slice(0,t).split(`
14
+ `).length}function ss(e){let t=[],n=0;for(let[i,a]of Object.entries(e.fileContents).sort(([c],[p])=>c.localeCompare(p))){let c=/controller|route|handler|resolver/i.test(i)||/@(Controller|Get|Post|Put|Delete|Patch)\b/.test(a),p=/domain|entity|aggregate|model/i.test(i);if(c){let m=/\b(if\s*\([^)]{0,80}(amount|total|price|qty|quantity|balance)[^)]{0,40}\)|throw new (Error|BadRequest|ValidationError)|z\.object\(|yup\.|class-validator|@Is[A-Z])/g,o;for(;(o=m.exec(a))!==null;)n+=1,t.push({id:`inv-val-${n}`,kind:"validation-in-controller",file:i,line:st(a,o.index),message:"Business validation appears in a controller/handler \u2014 extract an invariant or Domain rule.",confidence:"direct-evidence",suggestedArkRule:{layer:"DomainModel",invariantId:`INV-EXTRACT-${n}`,sensor:"invariant-coverage"},neverMechanicalSafe:!0})}let y=/\b(const|let)\s+([A-Z][A-Z0-9_]{2,})\s*=\s*(\d{2,}|['"][^'"]{8,}['"])/g,h;for(;(h=y.exec(a))!==null;)/TEST|SPEC|TIMEOUT|PORT|VERSION|MAX_RETRY/i.test(h[2])||(n+=1,t.push({id:`inv-magic-${n}`,kind:"magic-business-constant",file:i,line:st(a,h.index),message:`Magic business constant ${h[2]} may belong in a Domain policy or invariant catalog.`,confidence:"heuristic",suggestedArkRule:{layer:"DomainModel",invariantId:`INV-${h[2]}`},neverMechanicalSafe:!0}));if(p){let m=/export\s+class\s+([A-Za-z_][A-Za-z0-9_]*)\s*\{([^}]{0,800})\}/g,o;for(;(o=m.exec(a))!==null;){let l=o[2]??"",g=(l.match(/\b[a-zA-Z_][a-zA-Z0-9_]*\s*\(/g)??[]).length;(l.match(/:\s*[A-Za-z]/g)??[]).length>=2&&g<=1&&(n+=1,t.push({id:`inv-anemic-${n}`,kind:"anemic-entity",file:i,line:st(a,o.index),message:`Class ${o[1]} looks anemic (data-heavy, few behaviors).`,confidence:"heuristic",suggestedArkRule:{layer:"DomainModel",structureId:"no-anemic-model",sensor:"no-anemic-model"},neverMechanicalSafe:!0}))}}if(p){let m=/this\.\w+\s*=/g,o;for(;(o=m.exec(a))!==null;){let l=a.slice(Math.max(0,o.index-200),o.index+200);if(!/\b(ensureInvariants|assertInvariants|validate|publish|emit)\b/.test(l)){n+=1,t.push({id:`inv-mut-${n}`,kind:"mutation-without-guard",file:i,line:st(a,o.index),message:"Domain field mutation without nearby guard/publish call.",confidence:"heuristic",suggestedArkRule:{layer:"DomainModel",structureId:"events-on-mutation",sensor:"domain-event-on-mutation"},neverMechanicalSafe:!0});break}}}}let s=new Set(e.contractedRuleIds??[]),r=t.filter(i=>i.suggestedArkRule?.invariantId&&s.has(i.suggestedArkRule.invariantId)||i.suggestedArkRule?.structureId&&s.has(i.suggestedArkRule.structureId)).length;return{candidates:t,inventoried:t.length,underContract:r,frozen:(e.frozenKeys??[]).length,notAScore:!0}}function is(e){return{pilot:`Extract rule candidate ${e.id} (${e.kind})`,pilotTarget:e.file,smellId:e.kind,move:`Declare in arkrules/${e.suggestedArkRule?.layer??"DomainModel"}.json, implement pure Domain logic, add covering test.`,doNot:["Do not auto-apply codemods","Do not promote to enforced without coverage evidence","Do not batch multiple extractions"],successSignal:"Doctor reports candidate under contract; gate green with residual honest.",killSwitch:"Stop if extraction requires multi-module redesign without a clear aggregate owner.",neverMechanicalSafe:!0,class:"judgment",next:"Run ark_prepare_change / preflight, then re-doctor."}}var as="1.1";var os="1.0";export{Et as ANALYSIS_IR_SCHEMA_VERSION,Ln as ARK_ANALYSIS_RESULT_SCHEMA,$n as ARK_ANALYSIS_RESULT_SCHEMA_VERSION,Rt as ARK_CONFIG_SCHEMA,Zn as ARK_CONFIG_SCHEMA_VERSION,os as ARK_DESIGN_DELTA_SCHEMA_VERSION,as as ARK_ENFORCEMENT_STATE_SCHEMA_VERSION,kt as ARK_RULES_SCHEMA,pr as ARK_RULES_SCHEMA_VERSION,cn as ARK_RULE_SENSORS,We as EffectiveContractError,Ot as POLICY_DELTA_SCHEMA_VERSION,Ct as RESOLVED_CANDIDATE_FACTS_SCHEMA,ne as RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,he as analyzeArchitectureConvergence,et as analyzeChange,An as analyzePolicyDelta,Fe as analyzeProject,De as analyzeResolvedProject,Dt as buildArkRuleFileHints,xt as buildEffectiveArkRules,ss as buildRulesInventory,Pt as canPromoteInvariant,Lt as classifyArkPolicyDelta,nt as collectAnalysisConfigWarnings,Nt as collectEmptyAppliesToFindings,pe as collectForbiddenCapabilityUses,Wt as createAICodeGate,On as createAdapterResult,ze as createArchitectureProfile,Qt as createArchitectureProfileFromArkConfig,en as createElevenLayerArkConfig,It as createResolvedCandidateFacts,In as deriveArkRuleFileHints,Tt as detectArchitectureCycles,w as deterministicHash,wt as effectiveContractPolicyPayload,qe as elevenLayerProfile,se as emptyEffectiveArkRules,Ae as evaluateArchitectureGraph,Ft as evaluateArkRuleSensors,$t as evaluateInvariantCoverage,bn as explainViolation,Wr as extractClassShapesFromSource,de as extractSemanticDependencies,is as inventoryToExtractionCard,Be as loadArkConfigContract,Ye as loadArkRulesContract,Qe as loadContract,Q as loadResolvedCandidateFacts,vt as parseArkConfigJson,hr as parseArkRulesJson,_t as policyDeltaAcknowledgementMatches,Sn as preflightChange,kn as preflightResolvedChange,Ar as resolveEffectiveContract,$e as resolvedFactsEvidenceRequirementsHash,k as stableSerialize,it as toAdapterDiagnostic,wn as version};