arkgate 4.6.0 → 4.6.2

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 (78) hide show
  1. package/CHANGELOG.md +54 -1
  2. package/README.md +11 -5
  3. package/bin/ark-check-runtime.mjs +115 -128
  4. package/bin/ark-mcp-runtime.mjs +86 -48
  5. package/bin/ark.mjs +21 -78
  6. package/bin/lib/agent-projection.mjs +1 -1
  7. package/bin/lib/analysis-engine.mjs +3 -3
  8. package/bin/lib/ci-and-commands.mjs +11 -11
  9. package/bin/lib/config-contract.mjs +2 -0
  10. package/bin/lib/contract-smells.mjs +5 -5
  11. package/bin/lib/design-smells.mjs +1 -1
  12. package/bin/lib/doctor-advisories.mjs +9 -0
  13. package/bin/lib/doctor-next-actions.mjs +92 -0
  14. package/bin/lib/doctor-plan.mjs +61 -71
  15. package/bin/lib/field-install.mjs +1 -1
  16. package/bin/lib/first-run-help.mjs +221 -0
  17. package/bin/lib/html-report-advisories.mjs +20 -0
  18. package/bin/lib/improvement-compass-map.mjs +20 -20
  19. package/bin/lib/pilot-loop.mjs +1 -1
  20. package/bin/lib/post-green-path.mjs +2 -2
  21. package/bin/lib/prepare-change.mjs +9 -0
  22. package/bin/lib/product-copy.mjs +1 -1
  23. package/bin/lib/start-preview.mjs +17 -10
  24. package/bin/lib/status-command.mjs +19 -0
  25. package/bin/lib/status-manifest.mjs +23 -0
  26. package/bin/lib/team-parliament-io.mjs +338 -0
  27. package/bin/lib/team-parliament.mjs +383 -0
  28. package/bin/lib/upgrade-whats-new.mjs +16 -0
  29. package/bin/lib/violations.mjs +8 -4
  30. package/dist/{configTypes-CC0FEXoF.d.ts → configTypes-B8uIcLaG.d.ts} +5 -0
  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 +8 -8
  35. package/dist/index.d.ts +66 -2
  36. package/dist/index.js +8 -8
  37. package/docs/README.md +5 -5
  38. package/docs/agent-guide.md +21 -17
  39. package/docs/configuration.md +36 -2
  40. package/docs/develop.md +13 -1
  41. package/docs/enthusiast/README.md +1 -1
  42. package/docs/enthusiast/how-to-agent-gates.md +3 -3
  43. package/docs/enthusiast/how-to-pick-shape.md +2 -2
  44. package/docs/enthusiast/tutorial-first-project.md +4 -3
  45. package/docs/package-surface.md +5 -3
  46. package/docs/product-voice.md +48 -10
  47. package/docs/use.md +10 -5
  48. package/package.json +2 -2
  49. package/schemas/ark.config.schema.json +9 -0
  50. package/schemas/ark.status-manifest.schema.json +51 -0
  51. package/server.json +3 -3
  52. package/templates/agent-skills/README.md +1 -1
  53. package/templates/agent-skills/ark-adopt/SKILL.md +59 -23
  54. package/templates/agent-skills/ark-architect/SKILL.md +24 -145
  55. package/templates/agent-skills/ark-autopilot/SKILL.md +49 -32
  56. package/templates/agent-skills/ark-contract/SKILL.md +21 -105
  57. package/templates/agent-skills/ark-coverage/SKILL.md +7 -3
  58. package/templates/agent-skills/ark-explain/SKILL.md +8 -4
  59. package/templates/agent-skills/ark-explore/SKILL.md +38 -21
  60. package/templates/agent-skills/ark-fix/SKILL.md +34 -157
  61. package/templates/agent-skills/ark-loop/SKILL.md +31 -153
  62. package/templates/agent-skills/ark-place/SKILL.md +35 -14
  63. package/templates/agent-skills/ark-runtime/SKILL.md +3 -3
  64. package/templates/agent-skills/ark-think/SKILL.md +6 -2
  65. package/templates/agent-skills/ark-upgrade/SKILL.md +21 -10
  66. package/templates/skills/ark-adopt.md +59 -23
  67. package/templates/skills/ark-architect.md +24 -145
  68. package/templates/skills/ark-autopilot.md +49 -32
  69. package/templates/skills/ark-contract.md +21 -105
  70. package/templates/skills/ark-coverage.md +7 -3
  71. package/templates/skills/ark-explain.md +8 -4
  72. package/templates/skills/ark-explore.md +38 -21
  73. package/templates/skills/ark-fix.md +34 -157
  74. package/templates/skills/ark-loop.md +31 -153
  75. package/templates/skills/ark-place.md +35 -14
  76. package/templates/skills/ark-runtime.md +3 -3
  77. package/templates/skills/ark-think.md +6 -2
  78. package/templates/skills/ark-upgrade.md +21 -10
@@ -1,10 +1,10 @@
1
1
  // GENERATED from src/kernel/analysis.ts by scripts/generate-analysis-engine.mjs.
2
2
  // Do not edit this file directly.
3
- function E(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}function S(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(S).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${S(t[n])}`).join(",")}}`}var ee="1.1";var lt=["network","filesystem","clock","randomness","environment","process","persistence"];function U(e,t){let n=S(e),r=S(t);return n<r?-1:n>r?1:0}function D(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}function ve(e){let t={schemaVersion:"1.1",include:D(e.include??[]),exclude:D(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:D(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:D(n.patterns??[]),exclude:D(n.exclude??[]),forbiddenGlobals:D(n.forbiddenGlobals??[]),intentPrefixes:D(n.intentPrefixes??[]),capabilityDeny:D(n.capabilities?.deny??[]),pure:n.pure===!0})).sort(U),safety:{maxTsSuppressions:e.safety?.maxTsSuppressions??0,maxAnyCasts:e.safety?.maxAnyCasts??0,allowInMemory:e.safety?.allowInMemory===!0,allowDisabledPeerIsolation:e.safety?.allowDisabledPeerIsolation===!0}};return E(S(t))}function nn(e){let t=e.completenessReasons.map(o=>({code:o.code,message:o.message,...o.file?{file:o.file}:{}})).sort(U),n=e.files.map(o=>({...o,typeOnlyExportNames:D(o.typeOnlyExportNames)})).sort((o,l)=>o.path<l.path?-1:o.path>l.path?1:0),r=e.dependencies.map(o=>({...o,...o.namedBindings?{namedBindings:D(o.namedBindings)}:{}})).sort(U),s=e.capabilityUses.map(o=>({...o})).sort(U),a=e.ambientUses.map(o=>({...o})).sort(U),i=e.publishCalls.map(o=>({...o})).sort(U),d=e.intentReferences.map(o=>({...o})).sort(U),p=e.safetyUses.map(o=>({...o})).sort(U),b=(e.classShapes??[]).map(o=>({...o,mutatingMethods:[...o.mutatingMethods??[]].map(l=>({...l}))})).sort(U),A=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),h=E(S(A));return{schemaVersion:"1.1",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:h,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:r,capabilityUses:s,ambientUses:a,publishCalls:i,intentReferences:d,safetyUses:p,classShapes:b}}function dt(e){let t=nn(e);return{...t,factsHash:E(S(t))}}function Ie(e){return dt(ft(F(e,"$"),!1))}function F(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}function L(e,t,n){let r=new Set(t),s=Object.keys(e).find(a=>!r.has(a));if(s)throw new Error(`${n}.${s} is not part of schema ${"1.1"}.`)}function w(e,t,n){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`${n}.${t} must be a non-empty string.`);return r}function te(e,t,n){if(e[t]!==void 0)return w(e,t,n)}function M(e,t,n){let r=w(e,t,n),s=r.replace(/\\/g,"/");if(!s||s.startsWith("/")||/^[A-Za-z]:\//.test(s)||/[\u0000-\u001f\u007f]/.test(s))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let a=[];for(let d of s.split("/"))if(!(!d||d==="."))if(d===".."){if(a.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);a.pop()}else a.push(d);let i=a.join("/");if(!i||i!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return i}function $(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}function pt(e,t,n){let r=e[t];if(!Number.isInteger(r)||Number(r)<0)throw new Error(`${n}.${t} must be a non-negative integer.`);return Number(r)}function ne(e,t,n){let r=pt(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}function H(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}function z(e,t,n,r){let s=e[t];if(typeof s!="string"||!n.includes(s))throw new Error(`${r}.${t} must be one of ${n.join(", ")}.`);return s}function ct(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 rn(e,t,n){let r=new Set;for(let s of e){let a=t(s);if(r.has(a))throw new Error(`${n} must not contain duplicate facts (${a}).`);r.add(a)}}function ft(e,t){L(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","classShapes",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=z(e,"schemaVersion",["1.0","1.1"],"$"),r=z(e,"completeness",["complete","partial","unavailable"],"$"),s=H(e,"completenessReasons","$").map((y,R)=>{let u=`$.completenessReasons[${R}]`,g=F(y,u);L(g,["code","message","file"],u);let v=g.file===void 0?void 0:M(g,"file",u);return{code:w(g,"code",u),message:w(g,"message",u),...v?{file:v}:{}}});if(r==="complete"&&s.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(r!=="complete"&&s.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let a=H(e,"files","$").map((y,R)=>{let u=`$.files[${R}]`,g=F(y,u);return L(g,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],u),{path:M(g,"path",u),contentHash:w(g,"contentHash",u),parseStatus:z(g,"parseStatus",["parsed","invalid"],u),parseDiagnosticCount:pt(g,"parseDiagnosticCount",u),exportsOnlyTypes:$(g,"exportsOnlyTypes",u),typeOnlyExportNames:ct(g.typeOnlyExportNames,`${u}.typeOnlyExportNames`),hasTopLevelSideEffects:$(g,"hasTopLevelSideEffects",u)}}),i=H(e,"dependencies","$").map((y,R)=>{let u=`$.dependencies[${R}]`,g=F(y,u);L(g,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],u);let v=te(g,"specifier",u),k=te(g,"target",u),K=z(g,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],u);if(K==="resolved-project"&&!k)throw new Error(`${u}.target is required for resolved-project dependencies.`);if(K!=="resolved-project"&&k)throw new Error(`${u}.target is only allowed for resolved-project dependencies.`);if(K!=="dynamic"&&!v)throw new Error(`${u}.specifier is required unless resolution is dynamic.`);return{from:M(g,"from",u),...v?{specifier:v}:{},kind:z(g,"kind",["import","export","dynamic-import","require"],u),typeOnly:$(g,"typeOnly",u),line:ne(g,"line",u),resolution:K,...k?{target:M(g,"target",u)}:{},...g.namedBindings!==void 0?{namedBindings:ct(g.namedBindings,`${u}.namedBindings`)}:{},...g.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:$(g,"targetTypeOnlyExports",u)}:{},...g.sourcePureTypeModule!==void 0?{sourcePureTypeModule:$(g,"sourcePureTypeModule",u)}:{},...g.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:$(g,"namedBindingsTypeOnly",u)}:{},...g.portProofEligible!==void 0?{portProofEligible:$(g,"portProofEligible",u)}:{}}}),d=H(e,"capabilityUses","$").map((y,R)=>{let u=`$.capabilityUses[${R}]`,g=F(y,u);return L(g,["file","line","symbol","capability","source"],u),{file:M(g,"file",u),line:ne(g,"line",u),symbol:w(g,"symbol",u),capability:z(g,"capability",lt,u),source:z(g,"source",["ambient-global","import-based"],u)}}),p=H(e,"ambientUses","$").map((y,R)=>{let u=`$.ambientUses[${R}]`,g=F(y,u);return L(g,["file","line","symbol"],u),{file:M(g,"file",u),line:ne(g,"line",u),symbol:w(g,"symbol",u)}}),b=H(e,"publishCalls","$").map((y,R)=>{let u=`$.publishCalls[${R}]`,g=F(y,u);L(g,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],u);let v=te(g,"rawIntentName",u),k=te(g,"sourceIntent",u);return{file:M(g,"file",u),line:ne(g,"line",u),...v?{rawIntentName:v}:{},objectHasIntent:$(g,"objectHasIntent",u),arkPublishCandidate:$(g,"arkPublishCandidate",u),hasSource:$(g,"hasSource",u),...k?{sourceIntent:k}:{}}}),A=H(e,"intentReferences","$").map((y,R)=>{let u=`$.intentReferences[${R}]`,g=F(y,u);return L(g,["file","line","intent"],u),{file:M(g,"file",u),line:ne(g,"line",u),intent:w(g,"intent",u)}}),h=H(e,"safetyUses","$").map((y,R)=>{let u=`$.safetyUses[${R}]`,g=F(y,u);L(g,["file","line","kind","symbol"],u);let v=te(g,"symbol",u),k=z(g,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],u);if(k==="in-memory-store"&&!v)throw new Error(`${u}.symbol is required for in-memory-store facts.`);if(k!=="in-memory-store"&&v)throw new Error(`${u}.symbol is only allowed for in-memory-store facts.`);return{file:M(g,"file",u),line:ne(g,"line",u),kind:k,...v?{symbol:v}:{}}});rn(a,y=>y.path,"$.files");let o=new Set(a.map(y=>y.path));for(let y of a){if(y.parseStatus==="parsed"&&y.parseDiagnosticCount!==0)throw new Error(`$.files[${y.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(y.parseStatus==="invalid"&&y.parseDiagnosticCount===0)throw new Error(`$.files[${y.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&a.some(y=>y.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let y of i)if(!o.has(y.from))throw new Error(`$.dependencies references missing source file ${y.from}.`);for(let[y,R]of[["$.capabilityUses",d],["$.ambientUses",p],["$.publishCalls",b],["$.intentReferences",A],["$.safetyUses",h]])for(let u of R)if(!o.has(u.file))throw new Error(`${y} references missing file ${u.file}.`);let l=te(e,"projectPackageName","$"),f=(e.classShapes===void 0?[]:H(e,"classShapes","$")).map((y,R)=>{let u=`$.classShapes[${R}]`,g=F(y,u);L(g,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],u);let v=H(g,"mutatingMethods",u).map((k,K)=>{let Y=`${u}.mutatingMethods[${K}]`,q=F(k,Y);return L(q,["name","referencesGuardOrPublish"],Y),{name:w(q,"name",Y),referencesGuardOrPublish:$(q,"referencesGuardOrPublish",Y)}});return{file:M(g,"file",u),className:w(g,"className",u),exported:$(g,"exported",u),hasPublicMutableFields:$(g,"hasPublicMutableFields",u),hasPublicSetters:$(g,"hasPublicSetters",u),hasPublicConstructor:$(g,"hasPublicConstructor",u),hasStaticFactory:$(g,"hasStaticFactory",u),mutatingMethods:v,...g.dataOnly===void 0?{}:{dataOnly:$(g,"dataOnly",u)}}});return{schemaVersion:n,completeness:r,completenessReasons:s,resolverIdentity:w(e,"resolverIdentity","$"),compilerIdentity:w(e,"compilerIdentity","$"),compilerOptionsHash:w(e,"compilerOptionsHash","$"),tsconfigHash:w(e,"tsconfigHash","$"),evidenceRequirementsHash:w(e,"evidenceRequirementsHash","$"),...l?{projectPackageName:l}:{},files:a,dependencies:i,capabilityUses:d,ambientUses:p,publishCalls:b,intentReferences:A,safetyUses:h,classShapes:f}}function W(e){let t=F(e,"$"),n=w(t,"factsHash","$"),r=w(t,"candidateTreeHash","$"),s=dt(ft(t,!0));if(s.factsHash!==n)throw new Error(`$.factsHash does not match the canonical payload (${s.factsHash}).`);if(r!==s.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${s.candidateTreeHash}).`);return s}var sn=["network","filesystem","clock","randomness","environment","process","persistence"],C={type:"string",minLength:1},re={type:"integer",minimum:1},j={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},ut={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.resolved-candidate-facts.schema.json",title:"ArkGate resolved candidate facts",type:"object",additionalProperties:!1,required:["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","candidateTreeHash","evidenceRequirementsHash","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","factsHash"],properties:{schemaVersion:{enum:["1.0","1.1"]},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:C,message:C,file:j}}},resolverIdentity:C,compilerIdentity:C,compilerOptionsHash:C,tsconfigHash:C,candidateTreeHash:C,evidenceRequirementsHash:C,projectPackageName:C,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:j,contentHash:C,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:C},hasTopLevelSideEffects:{type:"boolean"}},allOf:[{if:{properties:{parseStatus:{const:"parsed"}}},then:{properties:{parseDiagnosticCount:{const:0}}}},{if:{properties:{parseStatus:{const:"invalid"}}},then:{properties:{parseDiagnosticCount:{minimum:1}}}}]}},dependencies:{type:"array",items:{type:"object",additionalProperties:!1,required:["from","kind","typeOnly","line","resolution"],properties:{from:j,specifier:C,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:re,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:j,namedBindings:{type:"array",items:C},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"}},allOf:[{if:{properties:{resolution:{const:"resolved-project"}}},then:{required:["target"]},else:{not:{required:["target"]}}},{if:{properties:{resolution:{const:"dynamic"}}},else:{required:["specifier"]}}]}},capabilityUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol","capability","source"],properties:{file:j,line:re,symbol:C,capability:{enum:sn},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:j,line:re,symbol:C}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:j,line:re,rawIntentName:C,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:C}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:j,line:re,intent:C}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:j,line:re,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:C},allOf:[{if:{properties:{kind:{const:"in-memory-store"}}},then:{required:["symbol"]},else:{not:{required:["symbol"]}}}]}},classShapes:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods"],properties:{file:j,className:C,exported:{type:"boolean"},hasPublicMutableFields:{type:"boolean"},hasPublicSetters:{type:"boolean"},hasPublicConstructor:{type:"boolean"},hasStaticFactory:{type:"boolean"},dataOnly:{type:"boolean"},mutatingMethods:{type:"array",items:{type:"object",additionalProperties:!1,required:["name","referencesGuardOrPublish"],properties:{name:C,referencesGuardOrPublish:{type:"boolean"}}}}}}},factsHash:C},allOf:[{if:{properties:{completeness:{const:"complete"}}},then:{properties:{completenessReasons:{maxItems:0},files:{items:{properties:{parseStatus:{const:"parsed"}}}}}}},{if:{properties:{completeness:{enum:["partial","unavailable"]}}},then:{properties:{completenessReasons:{minItems:1}}}}]};var mt="1.0";var Me=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),Ce=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),De=Object.freeze(Object.keys(Ce).sort()),Ne=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"}),He=Object.freeze({process:Object.freeze(["process","node:process"])});function pe(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=Ne[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),s=Ne[r];if(s)return s;let a=e.indexOf("/",n+1);return a<0?null:Ne[e.slice(0,a)]??null}function fe(e,t){for(let n of t)if(He[n]?.includes(e))return n;return null}function ue(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),s=Ce[r];if(s)return s}return null}function se(e){if(e?.pure===!0)return[...Me].sort();let n=(e?.capabilities?.deny??[]).filter(r=>Me.includes(r));return[...new Set(n)].sort()}function je(e,t){if(t.length===0)return!1;let n=new Set(t),r=e.split(".");for(let s=r.length;s>=1;s-=1)if(n.has(r.slice(0,s).join(".")))return!0;return!1}function Se(e){let t=new Set,n=new Set,r=Object.keys(Ce);for(let s of e?.forbiddenGlobals??[]){let a=r.filter(i=>i===s||i.startsWith(`${s}.`));if(a.length===0)n.add(s);else for(let i of a)t.add(`ambient:${i}`);for(let i of He[s]??[])t.add(`import-exact:${i}`)}for(let s of se(e)){if(t.add(`import:${s}`),s==="process")for(let a of He.process)t.add(`import-exact:${a}`);for(let a of r)ue(a)===s&&t.add(`ambient:${a}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}function an(e){let t=new Set,n=ue(e);n&&t.add(n);for(let[r,s]of Object.entries(Ce))(r===e||r.startsWith(`${e}.`))&&t.add(s);return[...t].sort()}var yt=new Map;function gt(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function ke(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let s=e[n+1];if("*?{}[],".includes(s)||s==="\\"){t+="\\"+s,n+=1;continue}t+="/";continue}t+=r}return t}function on(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="{")t+=1;else if(r==="}"&&(t-=1,t<0))return!1}return t===0}function J(e){let t=yt.get(e);if(t)return t;let n=ke(e),r=on(n),s="",a=0;for(let d=0;d<n.length;d+=1){let p=n[d];p==="\\"&&d+1<n.length?(s+=gt(n[d+1]),d+=1):p==="*"?n[d+1]==="*"?n[d+2]==="/"?(s+="(?:.*/)?",d+=2):(s+=".*",d+=1):s+="[^/]*":p==="?"?s+="[^/]":p==="{"&&r?(s+="(?:",a+=1):p==="}"&&r&&a>0?(s+=")",a-=1):p===","&&r&&a>0?s+="|":s+=gt(p)}let i=new RegExp(`^${s}$`);return yt.set(e,i),i}function ln(e){return ke(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}function Ve(e,t){let n=ke(String(e)),r=ln(n),s=n.replace(/\*/g,"").length,a=r.length*1e4+s;if(t==null||t==="")return a;let i=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return s;let d=0,p=-1;for(let b of r){let A=-1;for(let h=d;h<i.length;h+=1)if(i[h]===b){A=h;break}if(A<0)return a;p=A,d=A+1}return(p+1)*1e6+r.length*1e4+s}function V(e,t){let n=String(e).split(/[/\\]/).join("/"),r,s=-1;for(let a of t??[])if(!(a.exclude??[]).some(i=>J(i).test(n))){for(let i of a.patterns??[])if(J(i).test(n)){let d=Ve(i,n);d>s&&(s=d,r=a.name)}}return r}function ht(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),r=new Set(t.map(s=>String(s).toLowerCase()));for(let s=0;s<n.length-1;s+=1)if(r.has(n[s].toLowerCase()))return`${n[s].toLowerCase()}/${n[s+1].toLowerCase()}`}function cn(e){let t=new Set;for(let n of e??[]){let s=ke(String(n)).split("/").filter(Boolean);for(let a=0;a<s.length;a+=1){let i=s[a];if((i==="**"||i==="*")&&a>0){let d=s[a-1];d&&!d.includes("*")&&!d.includes("{")&&!d.includes("}")&&t.add(d)}}}return[...t]}function dn(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(s=>typeof s=="string"&&s.length>0);let r=(n??[]).find(s=>s.name===t);return cn(r?.patterns)}function pn(e){return!e.fromPath||!e.toPath||e.folderCount<=0||!e.fromSlice||!e.toSlice?!0:e.fromSlice!==e.toSlice}function ae(e,t,n,r){for(let s of e??[])if(!(s.from!==t||s.to!==n)&&s.allowed===!1){if(s.peerIsolation){let a=r?.fromPath,i=r?.toPath,d=dn(s,t,r?.layers),p=a&&i?ht(a,d):void 0,b=a&&i?ht(i,d):void 0;if(pn({fromPath:a,toPath:i,folderCount:d.length,fromSlice:p,toSlice:b}))return s;continue}if(t!==n)return s}}var Ue={RAW_EVENT_PUBLISH:"Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts and tooling.",PUBLISH_MISSING_SOURCE:"Strict Ark publish calls must include metadata.source."},Ge=Object.freeze([{layer:"DomainModel",prefixes:["Domain."]},{layer:"ApplicationOrchestration",prefixes:["Application."]},{layer:"PersistenceAdapters",prefixes:["Adapter.Persistence.","Adapter.Repository."]},{layer:"IntegrationAdapters",prefixes:["Adapter.Integration.","Adapter.External."]},{layer:"WorkflowSagaEngine",prefixes:["Workflow."]},{layer:"BackgroundJobsScheduling",prefixes:["Job."]},{layer:"PresentationAdapters",prefixes:["Presentation.","Adapter.Presentation.","Adapter.Api."]},{layer:"ReportingReadModels",prefixes:["Reporting."]},{layer:"ExtensibilityMetadata",prefixes:["Metadata."]},{layer:"SecurityAuditObservability",prefixes:["Security.","Audit.","Observability."]},{layer:"Kernel",prefixes:["Kernel."]}]);function qe(e,t){return t.flatMap((r,s)=>(r.prefixes??r.intentPrefixes??[]).map(a=>({layer:r.name,layerIndex:s,prefix:a.endsWith(".")?a:`${a}.`}))).filter(({prefix:r})=>e.startsWith(r)).sort((r,s)=>s.prefix.length-r.prefix.length||r.layerIndex-s.layerIndex)[0]?.layer}function bt(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function ze(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&bt(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:Ue.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:Ue.PUBLISH_MISSING_SOURCE}),t}var At="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",fn=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","no-anemic-model","invariant-coverage"];var Rt={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Er={$schema:"https://json-schema.org/draft/2020-12/schema",$id:At,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:At},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:[...fn]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:Rt,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:Rt}}}};function me(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}var un=["no-anemic-model"];function vt(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function mn(e){let t="";for(let r=0;r<e.length;r+=1){let s=e[r];if(s==="\\"&&r+1<e.length){let a=e[r+1];if("*?{}[],".includes(a)||a==="\\"){t+="\\"+a,r+=1;continue}t+="/";continue}t+=s}let n="";for(let r=0;r<t.length;r+=1){let s=t[r];s==="\\"&&r+1<t.length?(n+=vt(t[r+1]),r+=1):s==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":s==="?"?n+="[^/]":n+=vt(s)}return new RegExp(`^${n}$`)}function ye(e,t){return!t||t.length===0?!0:t.some(n=>mn(n).test(e))}function yn(e){return un.includes(e)}function It(e){return e.mode==="enforced"&&!yn(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}function ie(e,t,n,r=1){let{severity:s,failsStrict:a}=It(e);return{ruleId:"ARKRULE_STRUCTURE",code:e.sensor,message:n,file:t,line:r,fromLayer:e.provenance.layer,arkruleId:e.id,arkruleSource:e.provenance.sourceFile,severity:s,sensor:e.sensor,failsStrict:a}}function Be(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}function Ee(e,t,n){return t.filter(r=>!(!r.exported||!ye(r.file,e.appliesTo)||!Be(r.file,e,n)))}function gn(e,t,n){let r=[];for(let s of Ee(e,t,n))(s.hasPublicSetters||s.hasPublicMutableFields)&&r.push(ie(e,s.file,`Exported class ${s.className} exposes public mutable state (sensor aggregate-private-state).`));return r}function hn(e,t,n){let r=[];for(let s of Ee(e,t,n))if(s.hasPublicConstructor&&!s.hasStaticFactory){if(!(s.hasPublicMutableFields||s.hasPublicSetters||(s.mutatingMethods?.length??0)>0))continue;r.push(ie(e,s.file,`Exported class ${s.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}return r}function bn(e,t,n){let r=[];for(let s of Ee(e,t,n))for(let a of s.mutatingMethods)a.referencesGuardOrPublish||r.push(ie(e,s.file,`Mutating method ${s.className}.${a.name} does not reference a guard or publish symbol (sensor domain-event-on-mutation).`));return r}function An(e,t){let n=[];for(let r of t.files)ye(r,e.appliesTo)&&Be(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(ie(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}function Rn(e,t){let n=[];for(let r of t.files)ye(r,e.appliesTo)&&Be(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(ie(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}function vn(e,t,n){let r=[];for(let s of Ee(e,t,n))if(s.dataOnly===!0){let a=ie(e,s.file,`Exported type ${s.className} looks data-only / anemic (sensor no-anemic-model; advisory only).`);r.push({...a,severity:"warning",failsStrict:!1})}return r}function Ct(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(...gn(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...hn(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...bn(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...An(n,e));break;case"thin-adapter":t.push(...Rn(n,e));break;case"no-anemic-model":t.push(...vn(n,e.classShapes,e.layerForFile));break;case"invariant-coverage":break;default:break}return t.sort((n,r)=>n.file.localeCompare(r.file)||n.arkruleId.localeCompare(r.arkruleId)||n.message.localeCompare(r.message))}function St(e,t){let n=[],r=t.map(s=>s.replace(/\\/g,"/"));for(let s of e.structure){if(!s.appliesTo||s.appliesTo.length===0||r.some(p=>ye(p,s.appliesTo)))continue;let{severity:i,failsStrict:d}=It(s);n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule structure "${s.id}" appliesTo matched zero governed files (patterns: ${s.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:s.provenance.sourceFile,line:1,fromLayer:s.provenance.layer,arkruleId:s.id,arkruleSource:s.provenance.sourceFile,severity:i,sensor:s.sensor,failsStrict:d})}for(let s of e.invariants??[]){if(!s.appliesTo||s.appliesTo.length===0||r.some(d=>ye(d,s.appliesTo)))continue;let i=s.mode==="enforced";n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule invariant "${s.id}" appliesTo matched zero governed files (patterns: ${s.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:s.provenance.sourceFile,line:1,fromLayer:s.provenance.layer,arkruleId:s.id,arkruleSource:s.provenance.sourceFile,severity:i?"error":"warning",sensor:"invariant-coverage",failsStrict:i})}return n.sort((s,a)=>s.file.localeCompare(a.file)||s.arkruleId.localeCompare(a.arkruleId)||s.message.localeCompare(a.message))}var In=/\bfrom\s+['"](?:@?prisma\/client|@supabase\/|drizzle-orm|typeorm|knex|mongodb|pg|mysql2|better-sqlite3|ioredis|redis)['"]|require\(\s*['"](?:@?prisma\/client|pg|knex|typeorm)/,Cn=/\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*=)/,Sn=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,kn=/\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*=/,En=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function $n(e,t){if(!t||t.length<40)return null;let n=t.match(new RegExp(kn.source,"g"))??[],r=t.match(new RegExp(En.source,"g"))??[],s=(t.match(/\bif\s*\(/g)??[]).length,a=(t.match(/\bswitch\s*\(/g)??[]).length,i=n.length>=2||n.length>=1&&r.length>=2||r.length>=3&&s+a>=6,d=In.test(t),p=Cn.test(t)||Sn.test(t),b=n.length>=1||r.length>=2,A=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),h=d&&b||p&&b||d&&A&&(s>=4||n.length>=1)||p&&d;return!i&&!h?null:{...i?{orchestrationHeavy:!0}:{},...h?{adapterThick:!0}:{}}}function kt(e){let t={};for(let[n,r]of Object.entries(e)){let s=$n(n,r);s&&(t[n.replace(/\\/g,"/")]=s)}return t}function wn(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*['"\`][^'"\`]*${n}[^'"\`]*['"\`]`,"i").test(e)||e.includes(t)}function xn(e,t){if(!t)return!1;let n=t.split("."),r=n[n.length-1],s=n.length>1?n[0]:null;for(let a of Object.values(e))if(!(s&&!a.includes(s))&&(new RegExp(`(?:function\\s+|\\b)${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[(<]`).test(a)||a.includes(t)))return!0;return!1}function Et(e){let t=e.arkRules.invariants??[];if(t.length===0)return{coverage:[],violations:[],partial:!1};let n=e.testFiles??[],r=e.testGlobsMissing===!0||n.length===0,s=[],a=[];for(let i of t){let d=[],p=i.coverage?.test!==!1,b=i.coverage?.symbol;if(!r&&p)for(let l of n){let c=e.fileContents[l];if(c&&wn(c,i.id)){d.push("test-title");break}}b&&xn(e.fileContents,b)&&d.push("symbol");let h=(i.coverage?.test===!0||!!b||i.coverage===void 0)&&d.length>0||i.coverage?.test===!1&&!b?!0:d.length>0,o=r&&p&&d.length===0;if(s.push({invariantId:i.id,layer:i.provenance.layer,sourceFile:i.provenance.sourceFile,mode:i.mode,covered:h&&!o,evidence:d,partial:o,description:i.description}),!h||o){let l=i.mode==="enforced"&&!o;a.push({ruleId:"INVARIANT_UNCOVERED",message:o?`Invariant ${i.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered.`:`Invariant ${i.id} is not covered by a test title or declared symbol.`,file:i.provenance.sourceFile,line:1,arkruleId:i.id,arkruleSource:i.provenance.sourceFile,fromLayer:i.provenance.layer,severity:l?"error":"warning",failsStrict:l})}}return{coverage:s,violations:a,partial:s.some(i=>i.partial)}}function $t(e){return e?e.partial?{ok:!1,reason:"Coverage is partial (missing test globs); cannot promote until evidence is complete."}:e.covered?{ok:!0,reason:`Invariant ${e.invariantId} has coverage evidence.`}:{ok:!1,reason:`Invariant ${e.invariantId} is uncovered; add a test title or symbol before promoting to enforced.`}:{ok:!1,reason:"No coverage evidence supplied for this invariant; evaluate coverage before promoting to enforced."}}function x(e,t,n={}){return{ruleId:e,message:t,...n}}function Ke(e){let{config:t,rules:n,files:r,manifest:s}=e,a=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(l=>typeof l!="string"))&&a.push(x("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","dynamicImportAllowlist must be an array of file globs.")),t.safety!==void 0&&(t.safety===null||typeof t.safety!="object"||Array.isArray(t.safety)))a.push(x("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let l of["maxTsSuppressions","maxAnyCasts"]){let c=t.safety[l];c!==void 0&&(!Number.isInteger(c)||c<0)&&a.push(x("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${l} must be a non-negative integer.`))}let i=Array.isArray(t.layers)?t.layers:[],d=Array.isArray(s?.architecture?.layers)?s.architecture.layers:[],p=new Set([...i.map(l=>l.name).filter(Boolean),...d.map(l=>l.name).filter(l=>!!l)]);i.length===0&&a.push(x("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let b=new Set,A=new Set;for(let l of i){if(!l.name){a.push(x("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}b.has(l.name)&&A.add(l.name),b.add(l.name),l.forbiddenGlobals!==void 0&&(!Array.isArray(l.forbiddenGlobals)||l.forbiddenGlobals.some(f=>typeof f!="string"))&&a.push(x("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${l.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:l.name}));let c=Array.isArray(l.patterns)?l.patterns:[];if(c.length===0){a.push(x("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${l.name}" has no file patterns and will never classify files.`,{layer:l.name}));continue}for(let f of c){let y;try{y=J(f)}catch(R){a.push(x("CONFIG_INVALID_LAYER_PATTERN",`Layer "${l.name}" has an invalid pattern "${f}": ${R instanceof Error?R.message:String(R)}`,{layer:l.name,pattern:f}));continue}!r.some(R=>y.test(R))&&!l.optional&&a.push(x("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${l.name}" pattern "${f}" matched no included files.`,{layer:l.name,pattern:f,failsStrict:!1}))}}for(let l of A)a.push(x("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)&&a.push(x("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${l.from}".`,{fromLayer:l.from,toLayer:l.to})),l.to&&!p.has(l.to)&&a.push(x("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${l.to}".`,{fromLayer:l.from,toLayer:l.to}));let h=new Set;if(i.length>1)for(let l of r){let c=-1,f=[];for(let y of i)for(let R of y.patterns??[]){if(!J(R).test(l))continue;let u=Ve(R,l);u>c?(c=u,f=[y.name]):u===c&&!f.includes(y.name)&&f.push(y.name)}f.length>1&&h.add([...f].sort().join(" + "))}h.size>0&&a.push(x("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...h].join(", ")}.`,{pairs:[...h]}));let o=r.filter(l=>!V(l,i));return o.length>0&&a.push(x("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)})),a}function wt(e){let t=0,n=new Map,r=new Map,s=new Set,a=[],i=[],d=p=>{n.set(p,t),r.set(p,t),t+=1,a.push(p),s.add(p);for(let h of[...e.get(p)??[]].sort())e.has(h)&&(n.has(h)?s.has(h)&&r.set(p,Math.min(r.get(p)??0,n.get(h)??0)):(d(h),r.set(p,Math.min(r.get(p)??0,r.get(h)??0))));if(r.get(p)!==n.get(p))return;let b=[],A;do{if(A=a.pop(),A===void 0)break;s.delete(A),b.push(A)}while(A!==p);b.length>1&&i.push(b.sort())};for(let p of[...e.keys()].sort())n.has(p)||d(p);return i.sort((p,b)=>p[0]<b[0]?-1:p[0]>b[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 ge(e){let t=e.contentViolations.map(a=>({...a})),n=(e.warnings??[]).map(a=>({...a})),r=new Map(e.files.map(a=>[a,new Set]));for(let a of e.edges){if(a.to&&a.to!==a.from&&!a.typeOnly&&r.has(a.from)&&r.get(a.from)?.add(a.to),!a.to||!a.fromLayer||!a.toLayer)continue;let i=ae(e.rules,a.fromLayer,a.toLayer,{fromPath:a.from,toPath:a.to,layers:e.config.layers});if(!i)continue;let d=!!i.peerIsolation,p=!d&&!!(a.typeOnly||a.namedBindingsTypeOnly),b=i.message??(d?`${a.fromLayer} must not ${a.kind} another slice of ${a.toLayer} (${a.from} \u2192 ${a.to}). Extract shared code or use events/ports across slices.`:`${a.fromLayer} must not ${a.kind} ${a.toLayer}.`);t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:a.from,line:a.line,fromLayer:a.fromLayer,toLayer:a.toLayer,target:a.to,...a.typeOnly?{typeOnly:!0}:{},...a.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...a.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...a.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!d&&a.portProofEligible?{portProofEligible:!0}:{},...a.kind?{edgeKind:a.kind}:{},...d?{peerIsolation:!0}:{},message:p?`${b} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:b,...p?{failsStrict:!1,severity:"warning"}:{}})}let s=String(e.config.cyclePolicy??"strict").toLowerCase();if(s!=="off"){let a=wt(r);s==="soft"||s==="framework-soft"?n.push(...a.map(i=>({...i,message:`${i.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...a)}return{violations:t,warnings:n,safety:e.safety}}function On(e,t){return t.some(n=>{try{return J(n).test(e)}catch{return!1}})}function Pn(e,t){let n=e.contract.config.safety??{},r=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,s=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,a=e.contract.config.dynamicImportAllowlist??[],i=t.safetyUses.filter(f=>f.kind==="ts-suppression").map(({file:f,line:y})=>({file:f,line:y})),d=t.safetyUses.filter(f=>f.kind==="any-cast").map(({file:f,line:y})=>({file:f,line:y})),p=t.safetyUses.filter(f=>(f.kind==="dynamic-import"||f.kind==="dynamic-require")&&!On(f.file,a)).map(f=>({file:f.file,line:f.line,kind:f.kind==="dynamic-require"?"require":"import"})),b=n.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(f=>f.kind==="in-memory-store").map(f=>({file:f.file,line:f.line,store:f.symbol??"in-memory store"})),A=n.allowDisabledPeerIsolation===!0?[]:(e.contract.config.rules??[]).filter(f=>f.peerIsolation===!1||f.allowed===!1&&!!f.from&&f.from===f.to&&f.peerIsolation!==!0).map(f=>({from:f.from,to:f.to})),h={tsSuppressions:i,anyCasts:d,nonLiteralDynamicImports:p,inMemoryProductionStores:b,disabledPeerIsolationRules:A,thresholds:{maxTsSuppressions:r,maxAnyCasts:s}},o=[],l=p.filter(f=>f.kind==="import");if(l.length>0){let f=l[0];o.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:f.file,line:f.line,message:`${l.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let c=p.filter(f=>f.kind==="require");if(c.length>0){let f=c[0];o.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:f.file,line:f.line,message:`${c.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(i.length>r){let f=i[0];o.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:f.file,line:f.line,message:`${i.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${r}).`})}if(d.length>s){let f=d[0];o.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:f.file,line:f.line,message:`${d.length} explicit any cast(s) exceed safety.maxAnyCasts (${s}).`})}if(b.length>0){let f=b[0];o.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:f.file,line:f.line,message:`${b.length} ArkGate InMemory store risk(s) appear in governed production source. Provide durable stores or set safety.allowInMemory only for an explicitly ephemeral service.`})}return A.length>0&&o.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${A.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:h,warnings:o}}function Fn(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}function xt(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return qe(e,n.length>0?n:Ge.map(r=>({name:r.layer,prefixes:r.prefixes})))}function Tn(e,t,n){let r=[],s=new Map(e.contract.config.layers.map(a=>[a.name,a]));for(let a of t.ambientUses){let i=n.get(a.file);!i||!Fn(a.symbol,s.get(i)?.forbiddenGlobals??[])||r.push({ruleId:"FORBIDDEN_GLOBAL",file:a.file,line:a.line,fromLayer:i,target:a.symbol,message:`${i} must not use the ambient global "${a.symbol}".`})}for(let a of t.capabilityUses){let i=n.get(a.file);if(!i)continue;let d=s.get(i),p=d?.forbiddenGlobals??[],b=a.source==="import-based"?t.dependencies.find(A=>A.from===a.file&&A.line===a.line&&A.specifier===a.symbol&&!A.typeOnly)?.kind:void 0;if(!(a.source==="ambient-global"&&je(a.symbol,p))){if(a.source==="import-based"){let A=fe(a.symbol,p);if(A){r.push({ruleId:"FORBIDDEN_GLOBAL",file:a.file,line:a.line,fromLayer:i,target:a.symbol,...b?{edgeKind:b}:{},message:`${i} must not use module "${a.symbol}" because it is the import form of forbidden global "${A}".`});continue}}se(d).includes(a.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:a.file,line:a.line,fromLayer:i,target:a.symbol,capability:a.capability,...b?{edgeKind:b}:{},message:a.source==="import-based"?`${i} denies the ${a.capability} capability; found import of "${a.symbol}".`:`${i} denies the ${a.capability} capability; found ambient "${a.symbol}".`})}}for(let a of t.publishCalls){let i=n.get(a.file);if(!i)continue;for(let p of ze({publishCall:!0,rawIntentName:a.rawIntentName,objectHasIntent:a.objectHasIntent,arkPublishCandidate:a.arkPublishCandidate,hasSource:a.hasSource}))r.push({ruleId:p.ruleId,file:a.file,line:a.line,...p.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:i}:{},message:p.message});if(!a.sourceIntent)continue;let d=xt(a.sourceIntent,e.contract);!d||d===i||r.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:a.file,line:a.line,fromLayer:i,toLayer:d,target:a.sourceIntent,message:`Publish source "${a.sourceIntent}" resolves to ${d}, but the publishing file is classified as ${i}.`})}for(let a of t.intentReferences){let i=n.get(a.file);if(!i)continue;let d=xt(a.intent,e.contract);if(!d)continue;let p=ae(e.contract.config.rules,i,d);p&&r.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:a.file,line:a.line,fromLayer:i,toLayer:d,target:a.intent,message:p.message??`${i} must not reference ${d} intent ${a.intent}.`})}return r}function Ye(e){let{facts:t}=e,n=ve(e.contract.config),r=t.evidenceRequirementsHash===n,s=r?t.completeness:"unavailable",a=r?t.completenessReasons:[...t.completenessReasons,{code:"EVIDENCE_REQUIREMENTS_MISMATCH",message:"Resolved facts were collected for different policy-controlled evidence requirements."}].sort((m,N)=>{let ce=`${m.code}\0${m.file??""}\0${m.message}`,de=`${N.code}\0${N.file??""}\0${N.message}`;return ce<de?-1:ce>de?1:0}),i=t.files.map(m=>({...m,layer:V(m.path,e.contract.config.layers)??null})),d=new Map(i.map(m=>[m.path,m.layer])),p=t.dependencies.map(m=>{let N=m.target?d.get(m.target)??V(m.target,e.contract.config.layers):void 0;return{from:m.from,fromLayer:d.get(m.from)??null,...m.resolution==="resolved-project"&&m.target?{to:m.target,...N?{toLayer:N}:{}}:{},line:m.line,kind:m.kind,typeOnly:m.typeOnly,...m.targetTypeOnlyExports?{targetTypeOnlyExports:m.targetTypeOnlyExports}:{},...m.sourcePureTypeModule?{sourcePureTypeModule:m.sourcePureTypeModule}:{},...m.namedBindingsTypeOnly?{namedBindingsTypeOnly:m.namedBindingsTypeOnly}:{},...m.portProofEligible?{portProofEligible:m.portProofEligible}:{}}}),b=Ke({config:e.contract.config,rules:e.contract.config.rules,files:i.map(m=>m.path)}),A=Pn(e,t),h=e.contract.arkRules??me(),o=i.map(m=>m.path),c={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?kt(e.coverageInputs.fileContents):{},...e.fileHints??{}},f=[...Ct({arkRules:h,classShapes:e.contract.classShapes??t.classShapes??[],files:o,layerForFile:m=>d.get(m)??V(m,e.contract.config.layers),fileHints:c}),...St(h,o)],y=f.filter(m=>m.failsStrict).map(m=>({ruleId:m.ruleId,file:m.file,line:m.line,message:m.message,fromLayer:m.fromLayer,arkruleId:m.arkruleId,arkruleSource:m.arkruleSource,nextAction:m.ruleId==="ARKRULE_SCOPE_EMPTY"?`Fix appliesTo globs for ${m.arkruleId} in ${m.arkruleSource} so they match governed files, or remove the rule.`:`Fix the structure or invariant for ${m.arkruleId} (declared in ${m.arkruleSource}), then preflight again.`})),R=f.filter(m=>!m.failsStrict).map(m=>({ruleId:m.ruleId,file:m.file,line:m.line,message:m.message,fromLayer:m.fromLayer,arkruleId:m.arkruleId,arkruleSource:m.arkruleSource,failsStrict:!1,nextAction:m.ruleId==="ARKRULE_SCOPE_EMPTY"?`Review appliesTo for ${m.arkruleId} in ${m.arkruleSource} (zero-match scope; advisory).`:`Review ArkRule ${m.arkruleId} in ${m.arkruleSource} (advisory).`})),g=(h.invariants?.length??0)>0?Et({arkRules:h,fileContents:e.coverageInputs?.fileContents??{},testFiles:e.coverageInputs?.testFiles??[],testGlobsMissing:e.coverageInputs?.testGlobsMissing===!0||e.coverageInputs===void 0||(e.coverageInputs.testFiles?.length??0)===0}):{coverage:[],violations:[],partial:!1},v=g.violations.filter(m=>m.failsStrict).map(m=>({ruleId:m.ruleId,file:m.file,line:m.line,message:m.message,fromLayer:m.fromLayer,arkruleId:m.arkruleId,arkruleSource:m.arkruleSource,nextAction:`Add a test title or declared symbol covering ${m.arkruleId} (declared in ${m.arkruleSource}), then preflight again.`})),k=g.violations.filter(m=>!m.failsStrict).map(m=>({ruleId:m.ruleId,file:m.file,line:m.line,message:m.message,fromLayer:m.fromLayer,arkruleId:m.arkruleId,arkruleSource:m.arkruleSource,failsStrict:!1,nextAction:`Cover invariant ${m.arkruleId} in ${m.arkruleSource} (advisory / partial).`})),Y=g.partial&&g.coverage.some(m=>m.mode==="enforced"&&m.partial)?[{code:"INVARIANT_COVERAGE_PARTIAL",message:"Enforced ArkRules invariant coverage cannot be fully proven (missing test globs or empty test set); reporting partial, never covered."}]:[],q=ge({config:e.contract.config,rules:e.contract.config.rules,files:i.filter(m=>m.layer).map(m=>m.path),contentViolations:[...Tn(e,t,d),...y,...v],edges:p,warnings:[...b,...A.warnings,...R,...k],safety:A.report}),Le=s==="complete"&&Y.length>0?"partial":s,Qt=Le==="complete"?a:[...a,...Y].sort((m,N)=>{let ce=`${m.code}\0${m.file??""}\0${m.message}`,de=`${N.code}\0${N.file??""}\0${N.message}`;return ce<de?-1:ce>de?1:0}),en=q.violations.filter(m=>m.failsStrict!==!1),ot=Le==="complete"&&en.length===0,tn=ot&&q.warnings.every(m=>m.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:Le,completenessReasons:Qt,valid:ot,strictValid:tn,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:A.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:i,layers:e.contract.config.layers.map(m=>m.name),edges:p,capabilityUses:t.capabilityUses,violations:q.violations,warnings:q.warnings}}}function $e(e){return Ye({contract:e.contract,facts:W(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints})}var We="1.0";var we=class extends Error{issues;source;constructor(t,n){super(`Invalid architecture change map (${t}):
3
+ function E(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}function S(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(S).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${S(t[n])}`).join(",")}}`}var ee="1.1";var lt=["network","filesystem","clock","randomness","environment","process","persistence"];function U(e,t){let n=S(e),r=S(t);return n<r?-1:n>r?1:0}function D(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}function ve(e){let t={schemaVersion:"1.1",include:D(e.include??[]),exclude:D(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:D(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:D(n.patterns??[]),exclude:D(n.exclude??[]),forbiddenGlobals:D(n.forbiddenGlobals??[]),intentPrefixes:D(n.intentPrefixes??[]),capabilityDeny:D(n.capabilities?.deny??[]),pure:n.pure===!0})).sort(U),safety:{maxTsSuppressions:e.safety?.maxTsSuppressions??0,maxAnyCasts:e.safety?.maxAnyCasts??0,allowInMemory:e.safety?.allowInMemory===!0,allowDisabledPeerIsolation:e.safety?.allowDisabledPeerIsolation===!0}};return E(S(t))}function nn(e){let t=e.completenessReasons.map(o=>({code:o.code,message:o.message,...o.file?{file:o.file}:{}})).sort(U),n=e.files.map(o=>({...o,typeOnlyExportNames:D(o.typeOnlyExportNames)})).sort((o,l)=>o.path<l.path?-1:o.path>l.path?1:0),r=e.dependencies.map(o=>({...o,...o.namedBindings?{namedBindings:D(o.namedBindings)}:{}})).sort(U),s=e.capabilityUses.map(o=>({...o})).sort(U),a=e.ambientUses.map(o=>({...o})).sort(U),i=e.publishCalls.map(o=>({...o})).sort(U),d=e.intentReferences.map(o=>({...o})).sort(U),p=e.safetyUses.map(o=>({...o})).sort(U),b=(e.classShapes??[]).map(o=>({...o,mutatingMethods:[...o.mutatingMethods??[]].map(l=>({...l}))})).sort(U),A=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),h=E(S(A));return{schemaVersion:"1.1",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:h,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:r,capabilityUses:s,ambientUses:a,publishCalls:i,intentReferences:d,safetyUses:p,classShapes:b}}function dt(e){let t=nn(e);return{...t,factsHash:E(S(t))}}function Ie(e){return dt(ft(F(e,"$"),!1))}function F(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}function L(e,t,n){let r=new Set(t),s=Object.keys(e).find(a=>!r.has(a));if(s)throw new Error(`${n}.${s} is not part of schema ${"1.1"}.`)}function w(e,t,n){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`${n}.${t} must be a non-empty string.`);return r}function te(e,t,n){if(e[t]!==void 0)return w(e,t,n)}function M(e,t,n){let r=w(e,t,n),s=r.replace(/\\/g,"/");if(!s||s.startsWith("/")||/^[A-Za-z]:\//.test(s)||/[\u0000-\u001f\u007f]/.test(s))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let a=[];for(let d of s.split("/"))if(!(!d||d==="."))if(d===".."){if(a.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);a.pop()}else a.push(d);let i=a.join("/");if(!i||i!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return i}function $(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}function pt(e,t,n){let r=e[t];if(!Number.isInteger(r)||Number(r)<0)throw new Error(`${n}.${t} must be a non-negative integer.`);return Number(r)}function ne(e,t,n){let r=pt(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}function H(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}function B(e,t,n,r){let s=e[t];if(typeof s!="string"||!n.includes(s))throw new Error(`${r}.${t} must be one of ${n.join(", ")}.`);return s}function ct(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 rn(e,t,n){let r=new Set;for(let s of e){let a=t(s);if(r.has(a))throw new Error(`${n} must not contain duplicate facts (${a}).`);r.add(a)}}function ft(e,t){L(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","classShapes",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=B(e,"schemaVersion",["1.0","1.1"],"$"),r=B(e,"completeness",["complete","partial","unavailable"],"$"),s=H(e,"completenessReasons","$").map((y,R)=>{let u=`$.completenessReasons[${R}]`,g=F(y,u);L(g,["code","message","file"],u);let v=g.file===void 0?void 0:M(g,"file",u);return{code:w(g,"code",u),message:w(g,"message",u),...v?{file:v}:{}}});if(r==="complete"&&s.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(r!=="complete"&&s.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let a=H(e,"files","$").map((y,R)=>{let u=`$.files[${R}]`,g=F(y,u);return L(g,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],u),{path:M(g,"path",u),contentHash:w(g,"contentHash",u),parseStatus:B(g,"parseStatus",["parsed","invalid"],u),parseDiagnosticCount:pt(g,"parseDiagnosticCount",u),exportsOnlyTypes:$(g,"exportsOnlyTypes",u),typeOnlyExportNames:ct(g.typeOnlyExportNames,`${u}.typeOnlyExportNames`),hasTopLevelSideEffects:$(g,"hasTopLevelSideEffects",u)}}),i=H(e,"dependencies","$").map((y,R)=>{let u=`$.dependencies[${R}]`,g=F(y,u);L(g,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],u);let v=te(g,"specifier",u),k=te(g,"target",u),K=B(g,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],u);if(K==="resolved-project"&&!k)throw new Error(`${u}.target is required for resolved-project dependencies.`);if(K!=="resolved-project"&&k)throw new Error(`${u}.target is only allowed for resolved-project dependencies.`);if(K!=="dynamic"&&!v)throw new Error(`${u}.specifier is required unless resolution is dynamic.`);return{from:M(g,"from",u),...v?{specifier:v}:{},kind:B(g,"kind",["import","export","dynamic-import","require"],u),typeOnly:$(g,"typeOnly",u),line:ne(g,"line",u),resolution:K,...k?{target:M(g,"target",u)}:{},...g.namedBindings!==void 0?{namedBindings:ct(g.namedBindings,`${u}.namedBindings`)}:{},...g.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:$(g,"targetTypeOnlyExports",u)}:{},...g.sourcePureTypeModule!==void 0?{sourcePureTypeModule:$(g,"sourcePureTypeModule",u)}:{},...g.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:$(g,"namedBindingsTypeOnly",u)}:{},...g.portProofEligible!==void 0?{portProofEligible:$(g,"portProofEligible",u)}:{}}}),d=H(e,"capabilityUses","$").map((y,R)=>{let u=`$.capabilityUses[${R}]`,g=F(y,u);return L(g,["file","line","symbol","capability","source"],u),{file:M(g,"file",u),line:ne(g,"line",u),symbol:w(g,"symbol",u),capability:B(g,"capability",lt,u),source:B(g,"source",["ambient-global","import-based"],u)}}),p=H(e,"ambientUses","$").map((y,R)=>{let u=`$.ambientUses[${R}]`,g=F(y,u);return L(g,["file","line","symbol"],u),{file:M(g,"file",u),line:ne(g,"line",u),symbol:w(g,"symbol",u)}}),b=H(e,"publishCalls","$").map((y,R)=>{let u=`$.publishCalls[${R}]`,g=F(y,u);L(g,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],u);let v=te(g,"rawIntentName",u),k=te(g,"sourceIntent",u);return{file:M(g,"file",u),line:ne(g,"line",u),...v?{rawIntentName:v}:{},objectHasIntent:$(g,"objectHasIntent",u),arkPublishCandidate:$(g,"arkPublishCandidate",u),hasSource:$(g,"hasSource",u),...k?{sourceIntent:k}:{}}}),A=H(e,"intentReferences","$").map((y,R)=>{let u=`$.intentReferences[${R}]`,g=F(y,u);return L(g,["file","line","intent"],u),{file:M(g,"file",u),line:ne(g,"line",u),intent:w(g,"intent",u)}}),h=H(e,"safetyUses","$").map((y,R)=>{let u=`$.safetyUses[${R}]`,g=F(y,u);L(g,["file","line","kind","symbol"],u);let v=te(g,"symbol",u),k=B(g,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],u);if(k==="in-memory-store"&&!v)throw new Error(`${u}.symbol is required for in-memory-store facts.`);if(k!=="in-memory-store"&&v)throw new Error(`${u}.symbol is only allowed for in-memory-store facts.`);return{file:M(g,"file",u),line:ne(g,"line",u),kind:k,...v?{symbol:v}:{}}});rn(a,y=>y.path,"$.files");let o=new Set(a.map(y=>y.path));for(let y of a){if(y.parseStatus==="parsed"&&y.parseDiagnosticCount!==0)throw new Error(`$.files[${y.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(y.parseStatus==="invalid"&&y.parseDiagnosticCount===0)throw new Error(`$.files[${y.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&a.some(y=>y.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let y of i)if(!o.has(y.from))throw new Error(`$.dependencies references missing source file ${y.from}.`);for(let[y,R]of[["$.capabilityUses",d],["$.ambientUses",p],["$.publishCalls",b],["$.intentReferences",A],["$.safetyUses",h]])for(let u of R)if(!o.has(u.file))throw new Error(`${y} references missing file ${u.file}.`);let l=te(e,"projectPackageName","$"),f=(e.classShapes===void 0?[]:H(e,"classShapes","$")).map((y,R)=>{let u=`$.classShapes[${R}]`,g=F(y,u);L(g,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],u);let v=H(g,"mutatingMethods",u).map((k,K)=>{let Y=`${u}.mutatingMethods[${K}]`,z=F(k,Y);return L(z,["name","referencesGuardOrPublish"],Y),{name:w(z,"name",Y),referencesGuardOrPublish:$(z,"referencesGuardOrPublish",Y)}});return{file:M(g,"file",u),className:w(g,"className",u),exported:$(g,"exported",u),hasPublicMutableFields:$(g,"hasPublicMutableFields",u),hasPublicSetters:$(g,"hasPublicSetters",u),hasPublicConstructor:$(g,"hasPublicConstructor",u),hasStaticFactory:$(g,"hasStaticFactory",u),mutatingMethods:v,...g.dataOnly===void 0?{}:{dataOnly:$(g,"dataOnly",u)}}});return{schemaVersion:n,completeness:r,completenessReasons:s,resolverIdentity:w(e,"resolverIdentity","$"),compilerIdentity:w(e,"compilerIdentity","$"),compilerOptionsHash:w(e,"compilerOptionsHash","$"),tsconfigHash:w(e,"tsconfigHash","$"),evidenceRequirementsHash:w(e,"evidenceRequirementsHash","$"),...l?{projectPackageName:l}:{},files:a,dependencies:i,capabilityUses:d,ambientUses:p,publishCalls:b,intentReferences:A,safetyUses:h,classShapes:f}}function W(e){let t=F(e,"$"),n=w(t,"factsHash","$"),r=w(t,"candidateTreeHash","$"),s=dt(ft(t,!0));if(s.factsHash!==n)throw new Error(`$.factsHash does not match the canonical payload (${s.factsHash}).`);if(r!==s.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${s.candidateTreeHash}).`);return s}var sn=["network","filesystem","clock","randomness","environment","process","persistence"],C={type:"string",minLength:1},re={type:"integer",minimum:1},j={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},ut={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.resolved-candidate-facts.schema.json",title:"ArkGate resolved candidate facts",type:"object",additionalProperties:!1,required:["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","candidateTreeHash","evidenceRequirementsHash","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","factsHash"],properties:{schemaVersion:{enum:["1.0","1.1"]},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:C,message:C,file:j}}},resolverIdentity:C,compilerIdentity:C,compilerOptionsHash:C,tsconfigHash:C,candidateTreeHash:C,evidenceRequirementsHash:C,projectPackageName:C,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:j,contentHash:C,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:C},hasTopLevelSideEffects:{type:"boolean"}},allOf:[{if:{properties:{parseStatus:{const:"parsed"}}},then:{properties:{parseDiagnosticCount:{const:0}}}},{if:{properties:{parseStatus:{const:"invalid"}}},then:{properties:{parseDiagnosticCount:{minimum:1}}}}]}},dependencies:{type:"array",items:{type:"object",additionalProperties:!1,required:["from","kind","typeOnly","line","resolution"],properties:{from:j,specifier:C,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:re,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:j,namedBindings:{type:"array",items:C},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"}},allOf:[{if:{properties:{resolution:{const:"resolved-project"}}},then:{required:["target"]},else:{not:{required:["target"]}}},{if:{properties:{resolution:{const:"dynamic"}}},else:{required:["specifier"]}}]}},capabilityUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol","capability","source"],properties:{file:j,line:re,symbol:C,capability:{enum:sn},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:j,line:re,symbol:C}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:j,line:re,rawIntentName:C,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:C}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:j,line:re,intent:C}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:j,line:re,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:C},allOf:[{if:{properties:{kind:{const:"in-memory-store"}}},then:{required:["symbol"]},else:{not:{required:["symbol"]}}}]}},classShapes:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods"],properties:{file:j,className:C,exported:{type:"boolean"},hasPublicMutableFields:{type:"boolean"},hasPublicSetters:{type:"boolean"},hasPublicConstructor:{type:"boolean"},hasStaticFactory:{type:"boolean"},dataOnly:{type:"boolean"},mutatingMethods:{type:"array",items:{type:"object",additionalProperties:!1,required:["name","referencesGuardOrPublish"],properties:{name:C,referencesGuardOrPublish:{type:"boolean"}}}}}}},factsHash:C},allOf:[{if:{properties:{completeness:{const:"complete"}}},then:{properties:{completenessReasons:{maxItems:0},files:{items:{properties:{parseStatus:{const:"parsed"}}}}}}},{if:{properties:{completeness:{enum:["partial","unavailable"]}}},then:{properties:{completenessReasons:{minItems:1}}}}]};var mt="1.0";var Me=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),Ce=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),De=Object.freeze(Object.keys(Ce).sort()),Ne=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"}),He=Object.freeze({process:Object.freeze(["process","node:process"])});function pe(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=Ne[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),s=Ne[r];if(s)return s;let a=e.indexOf("/",n+1);return a<0?null:Ne[e.slice(0,a)]??null}function fe(e,t){for(let n of t)if(He[n]?.includes(e))return n;return null}function ue(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),s=Ce[r];if(s)return s}return null}function se(e){if(e?.pure===!0)return[...Me].sort();let n=(e?.capabilities?.deny??[]).filter(r=>Me.includes(r));return[...new Set(n)].sort()}function je(e,t){if(t.length===0)return!1;let n=new Set(t),r=e.split(".");for(let s=r.length;s>=1;s-=1)if(n.has(r.slice(0,s).join(".")))return!0;return!1}function Se(e){let t=new Set,n=new Set,r=Object.keys(Ce);for(let s of e?.forbiddenGlobals??[]){let a=r.filter(i=>i===s||i.startsWith(`${s}.`));if(a.length===0)n.add(s);else for(let i of a)t.add(`ambient:${i}`);for(let i of He[s]??[])t.add(`import-exact:${i}`)}for(let s of se(e)){if(t.add(`import:${s}`),s==="process")for(let a of He.process)t.add(`import-exact:${a}`);for(let a of r)ue(a)===s&&t.add(`ambient:${a}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}function an(e){let t=new Set,n=ue(e);n&&t.add(n);for(let[r,s]of Object.entries(Ce))(r===e||r.startsWith(`${e}.`))&&t.add(s);return[...t].sort()}var yt=new Map;function gt(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function ke(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let s=e[n+1];if("*?{}[],".includes(s)||s==="\\"){t+="\\"+s,n+=1;continue}t+="/";continue}t+=r}return t}function on(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="{")t+=1;else if(r==="}"&&(t-=1,t<0))return!1}return t===0}function J(e){let t=yt.get(e);if(t)return t;let n=ke(e),r=on(n),s="",a=0;for(let d=0;d<n.length;d+=1){let p=n[d];p==="\\"&&d+1<n.length?(s+=gt(n[d+1]),d+=1):p==="*"?n[d+1]==="*"?n[d+2]==="/"?(s+="(?:.*/)?",d+=2):(s+=".*",d+=1):s+="[^/]*":p==="?"?s+="[^/]":p==="{"&&r?(s+="(?:",a+=1):p==="}"&&r&&a>0?(s+=")",a-=1):p===","&&r&&a>0?s+="|":s+=gt(p)}let i=new RegExp(`^${s}$`);return yt.set(e,i),i}function ln(e){return ke(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}function Ve(e,t){let n=ke(String(e)),r=ln(n),s=n.replace(/\*/g,"").length,a=r.length*1e4+s;if(t==null||t==="")return a;let i=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return s;let d=0,p=-1;for(let b of r){let A=-1;for(let h=d;h<i.length;h+=1)if(i[h]===b){A=h;break}if(A<0)return a;p=A,d=A+1}return(p+1)*1e6+r.length*1e4+s}function V(e,t){let n=String(e).split(/[/\\]/).join("/"),r,s=-1;for(let a of t??[])if(!(a.exclude??[]).some(i=>J(i).test(n))){for(let i of a.patterns??[])if(J(i).test(n)){let d=Ve(i,n);d>s&&(s=d,r=a.name)}}return r}function ht(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),r=new Set(t.map(s=>String(s).toLowerCase()));for(let s=0;s<n.length-1;s+=1)if(r.has(n[s].toLowerCase()))return`${n[s].toLowerCase()}/${n[s+1].toLowerCase()}`}function cn(e){let t=new Set;for(let n of e??[]){let s=ke(String(n)).split("/").filter(Boolean);for(let a=0;a<s.length;a+=1){let i=s[a];if((i==="**"||i==="*")&&a>0){let d=s[a-1];d&&!d.includes("*")&&!d.includes("{")&&!d.includes("}")&&t.add(d)}}}return[...t]}function dn(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(s=>typeof s=="string"&&s.length>0);let r=(n??[]).find(s=>s.name===t);return cn(r?.patterns)}function pn(e){return!e.fromPath||!e.toPath||e.folderCount<=0||!e.fromSlice||!e.toSlice?!0:e.fromSlice!==e.toSlice}function ae(e,t,n,r){for(let s of e??[])if(!(s.from!==t||s.to!==n)&&s.allowed===!1){if(s.peerIsolation){let a=r?.fromPath,i=r?.toPath,d=dn(s,t,r?.layers),p=a&&i?ht(a,d):void 0,b=a&&i?ht(i,d):void 0;if(pn({fromPath:a,toPath:i,folderCount:d.length,fromSlice:p,toSlice:b}))return s;continue}if(t!==n)return s}}var Ue={RAW_EVENT_PUBLISH:"Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts and tooling.",PUBLISH_MISSING_SOURCE:"Strict Ark publish calls must include metadata.source."},Ge=Object.freeze([{layer:"DomainModel",prefixes:["Domain."]},{layer:"ApplicationOrchestration",prefixes:["Application."]},{layer:"PersistenceAdapters",prefixes:["Adapter.Persistence.","Adapter.Repository."]},{layer:"IntegrationAdapters",prefixes:["Adapter.Integration.","Adapter.External."]},{layer:"WorkflowSagaEngine",prefixes:["Workflow."]},{layer:"BackgroundJobsScheduling",prefixes:["Job."]},{layer:"PresentationAdapters",prefixes:["Presentation.","Adapter.Presentation.","Adapter.Api."]},{layer:"ReportingReadModels",prefixes:["Reporting."]},{layer:"ExtensibilityMetadata",prefixes:["Metadata."]},{layer:"SecurityAuditObservability",prefixes:["Security.","Audit.","Observability."]},{layer:"Kernel",prefixes:["Kernel."]}]);function qe(e,t){return t.flatMap((r,s)=>(r.prefixes??r.intentPrefixes??[]).map(a=>({layer:r.name,layerIndex:s,prefix:a.endsWith(".")?a:`${a}.`}))).filter(({prefix:r})=>e.startsWith(r)).sort((r,s)=>s.prefix.length-r.prefix.length||r.layerIndex-s.layerIndex)[0]?.layer}function bt(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function ze(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&bt(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:Ue.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:Ue.PUBLISH_MISSING_SOURCE}),t}var At="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",fn=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","no-anemic-model","invariant-coverage"];var Rt={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Er={$schema:"https://json-schema.org/draft/2020-12/schema",$id:At,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:At},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:[...fn]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:Rt,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:Rt}}}};function me(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}var un=["no-anemic-model"];function vt(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function mn(e){let t="";for(let r=0;r<e.length;r+=1){let s=e[r];if(s==="\\"&&r+1<e.length){let a=e[r+1];if("*?{}[],".includes(a)||a==="\\"){t+="\\"+a,r+=1;continue}t+="/";continue}t+=s}let n="";for(let r=0;r<t.length;r+=1){let s=t[r];s==="\\"&&r+1<t.length?(n+=vt(t[r+1]),r+=1):s==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":s==="?"?n+="[^/]":n+=vt(s)}return new RegExp(`^${n}$`)}function ye(e,t){return!t||t.length===0?!0:t.some(n=>mn(n).test(e))}function yn(e){return un.includes(e)}function It(e){return e.mode==="enforced"&&!yn(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}function ie(e,t,n,r=1){let{severity:s,failsStrict:a}=It(e);return{ruleId:"ARKRULE_STRUCTURE",code:e.sensor,message:n,file:t,line:r,fromLayer:e.provenance.layer,arkruleId:e.id,arkruleSource:e.provenance.sourceFile,severity:s,sensor:e.sensor,failsStrict:a}}function Be(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}function Ee(e,t,n){return t.filter(r=>!(!r.exported||!ye(r.file,e.appliesTo)||!Be(r.file,e,n)))}function gn(e,t,n){let r=[];for(let s of Ee(e,t,n))(s.hasPublicSetters||s.hasPublicMutableFields)&&r.push(ie(e,s.file,`Exported class ${s.className} exposes public mutable state (sensor aggregate-private-state).`));return r}function hn(e,t,n){let r=[];for(let s of Ee(e,t,n))if(s.hasPublicConstructor&&!s.hasStaticFactory){if(!(s.hasPublicMutableFields||s.hasPublicSetters||(s.mutatingMethods?.length??0)>0))continue;r.push(ie(e,s.file,`Exported class ${s.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}return r}function bn(e,t,n){let r=[];for(let s of Ee(e,t,n))for(let a of s.mutatingMethods)a.referencesGuardOrPublish||r.push(ie(e,s.file,`Mutating method ${s.className}.${a.name} does not reference a guard or publish symbol (sensor domain-event-on-mutation).`));return r}function An(e,t){let n=[];for(let r of t.files)ye(r,e.appliesTo)&&Be(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(ie(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}function Rn(e,t){let n=[];for(let r of t.files)ye(r,e.appliesTo)&&Be(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(ie(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}function vn(e,t,n){let r=[];for(let s of Ee(e,t,n))if(s.dataOnly===!0){let a=ie(e,s.file,`Exported type ${s.className} looks data-only / anemic (sensor no-anemic-model; advisory only).`);r.push({...a,severity:"warning",failsStrict:!1})}return r}function Ct(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(...gn(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...hn(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...bn(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...An(n,e));break;case"thin-adapter":t.push(...Rn(n,e));break;case"no-anemic-model":t.push(...vn(n,e.classShapes,e.layerForFile));break;case"invariant-coverage":break;default:break}return t.sort((n,r)=>n.file.localeCompare(r.file)||n.arkruleId.localeCompare(r.arkruleId)||n.message.localeCompare(r.message))}function St(e,t){let n=[],r=t.map(s=>s.replace(/\\/g,"/"));for(let s of e.structure){if(!s.appliesTo||s.appliesTo.length===0||r.some(p=>ye(p,s.appliesTo)))continue;let{severity:i,failsStrict:d}=It(s);n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule structure "${s.id}" appliesTo matched zero governed files (patterns: ${s.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:s.provenance.sourceFile,line:1,fromLayer:s.provenance.layer,arkruleId:s.id,arkruleSource:s.provenance.sourceFile,severity:i,sensor:s.sensor,failsStrict:d})}for(let s of e.invariants??[]){if(!s.appliesTo||s.appliesTo.length===0||r.some(d=>ye(d,s.appliesTo)))continue;let i=s.mode==="enforced";n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule invariant "${s.id}" appliesTo matched zero governed files (patterns: ${s.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:s.provenance.sourceFile,line:1,fromLayer:s.provenance.layer,arkruleId:s.id,arkruleSource:s.provenance.sourceFile,severity:i?"error":"warning",sensor:"invariant-coverage",failsStrict:i})}return n.sort((s,a)=>s.file.localeCompare(a.file)||s.arkruleId.localeCompare(a.arkruleId)||s.message.localeCompare(a.message))}var In=/\bfrom\s+['"](?:@?prisma\/client|@supabase\/|drizzle-orm|typeorm|knex|mongodb|pg|mysql2|better-sqlite3|ioredis|redis)['"]|require\(\s*['"](?:@?prisma\/client|pg|knex|typeorm)/,Cn=/\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*=)/,Sn=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,kn=/\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*=/,En=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function $n(e,t){if(!t||t.length<40)return null;let n=t.match(new RegExp(kn.source,"g"))??[],r=t.match(new RegExp(En.source,"g"))??[],s=(t.match(/\bif\s*\(/g)??[]).length,a=(t.match(/\bswitch\s*\(/g)??[]).length,i=n.length>=2||n.length>=1&&r.length>=2||r.length>=3&&s+a>=6,d=In.test(t),p=Cn.test(t)||Sn.test(t),b=n.length>=1||r.length>=2,A=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),h=d&&b||p&&b||d&&A&&(s>=4||n.length>=1)||p&&d;return!i&&!h?null:{...i?{orchestrationHeavy:!0}:{},...h?{adapterThick:!0}:{}}}function kt(e){let t={};for(let[n,r]of Object.entries(e)){let s=$n(n,r);s&&(t[n.replace(/\\/g,"/")]=s)}return t}function wn(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*['"\`][^'"\`]*${n}[^'"\`]*['"\`]`,"i").test(e)||e.includes(t)}function xn(e,t){if(!t)return!1;let n=t.split("."),r=n[n.length-1],s=n.length>1?n[0]:null;for(let a of Object.values(e))if(!(s&&!a.includes(s))&&(new RegExp(`(?:function\\s+|\\b)${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[(<]`).test(a)||a.includes(t)))return!0;return!1}function Et(e){let t=e.arkRules.invariants??[];if(t.length===0)return{coverage:[],violations:[],partial:!1};let n=e.testFiles??[],r=e.testGlobsMissing===!0||n.length===0,s=[],a=[];for(let i of t){let d=[],p=i.coverage?.test!==!1,b=i.coverage?.symbol;if(!r&&p)for(let l of n){let c=e.fileContents[l];if(c&&wn(c,i.id)){d.push("test-title");break}}b&&xn(e.fileContents,b)&&d.push("symbol");let h=(i.coverage?.test===!0||!!b||i.coverage===void 0)&&d.length>0||i.coverage?.test===!1&&!b?!0:d.length>0,o=r&&p&&d.length===0;if(s.push({invariantId:i.id,layer:i.provenance.layer,sourceFile:i.provenance.sourceFile,mode:i.mode,covered:h&&!o,evidence:d,partial:o,description:i.description}),!h||o){let l=i.mode==="enforced"&&!o;a.push({ruleId:"INVARIANT_UNCOVERED",message:o?`Invariant ${i.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered.`:`Invariant ${i.id} is not covered by a test title or declared symbol.`,file:i.provenance.sourceFile,line:1,arkruleId:i.id,arkruleSource:i.provenance.sourceFile,fromLayer:i.provenance.layer,severity:l?"error":"warning",failsStrict:l})}}return{coverage:s,violations:a,partial:s.some(i=>i.partial)}}function $t(e){return e?e.partial?{ok:!1,reason:"Coverage is partial (missing test globs); cannot promote until evidence is complete."}:e.covered?{ok:!0,reason:`Invariant ${e.invariantId} has coverage evidence.`}:{ok:!1,reason:`Invariant ${e.invariantId} is uncovered; add a test title or symbol before promoting to enforced.`}:{ok:!1,reason:"No coverage evidence supplied for this invariant; evaluate coverage before promoting to enforced."}}function x(e,t,n={}){return{ruleId:e,message:t,...n}}function Ke(e){let{config:t,rules:n,files:r,manifest:s}=e,a=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(l=>typeof l!="string"))&&a.push(x("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","dynamicImportAllowlist must be an array of file globs.")),t.safety!==void 0&&(t.safety===null||typeof t.safety!="object"||Array.isArray(t.safety)))a.push(x("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let l of["maxTsSuppressions","maxAnyCasts"]){let c=t.safety[l];c!==void 0&&(!Number.isInteger(c)||c<0)&&a.push(x("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${l} must be a non-negative integer.`))}let i=Array.isArray(t.layers)?t.layers:[],d=Array.isArray(s?.architecture?.layers)?s.architecture.layers:[],p=new Set([...i.map(l=>l.name).filter(Boolean),...d.map(l=>l.name).filter(l=>!!l)]);i.length===0&&a.push(x("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let b=new Set,A=new Set;for(let l of i){if(!l.name){a.push(x("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}b.has(l.name)&&A.add(l.name),b.add(l.name),l.forbiddenGlobals!==void 0&&(!Array.isArray(l.forbiddenGlobals)||l.forbiddenGlobals.some(f=>typeof f!="string"))&&a.push(x("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${l.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:l.name}));let c=Array.isArray(l.patterns)?l.patterns:[];if(c.length===0){a.push(x("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${l.name}" has no file patterns and will never classify files.`,{layer:l.name}));continue}for(let f of c){let y;try{y=J(f)}catch(R){a.push(x("CONFIG_INVALID_LAYER_PATTERN",`Layer "${l.name}" has an invalid pattern "${f}": ${R instanceof Error?R.message:String(R)}`,{layer:l.name,pattern:f}));continue}!r.some(R=>y.test(R))&&!l.optional&&a.push(x("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${l.name}" pattern "${f}" matched no included files.`,{layer:l.name,pattern:f,failsStrict:!1}))}}for(let l of A)a.push(x("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)&&a.push(x("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${l.from}".`,{fromLayer:l.from,toLayer:l.to})),l.to&&!p.has(l.to)&&a.push(x("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${l.to}".`,{fromLayer:l.from,toLayer:l.to}));let h=new Set;if(i.length>1)for(let l of r){let c=-1,f=[];for(let y of i)for(let R of y.patterns??[]){if(!J(R).test(l))continue;let u=Ve(R,l);u>c?(c=u,f=[y.name]):u===c&&!f.includes(y.name)&&f.push(y.name)}f.length>1&&h.add([...f].sort().join(" + "))}h.size>0&&a.push(x("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...h].join(", ")}.`,{pairs:[...h]}));let o=r.filter(l=>!V(l,i));return o.length>0&&a.push(x("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)})),a}function wt(e){let t=0,n=new Map,r=new Map,s=new Set,a=[],i=[],d=p=>{n.set(p,t),r.set(p,t),t+=1,a.push(p),s.add(p);for(let h of[...e.get(p)??[]].sort())e.has(h)&&(n.has(h)?s.has(h)&&r.set(p,Math.min(r.get(p)??0,n.get(h)??0)):(d(h),r.set(p,Math.min(r.get(p)??0,r.get(h)??0))));if(r.get(p)!==n.get(p))return;let b=[],A;do{if(A=a.pop(),A===void 0)break;s.delete(A),b.push(A)}while(A!==p);b.length>1&&i.push(b.sort())};for(let p of[...e.keys()].sort())n.has(p)||d(p);return i.sort((p,b)=>p[0]<b[0]?-1:p[0]>b[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 ge(e){let t=e.contentViolations.map(a=>({...a})),n=(e.warnings??[]).map(a=>({...a})),r=new Map(e.files.map(a=>[a,new Set]));for(let a of e.edges){if(a.to&&a.to!==a.from&&!a.typeOnly&&r.has(a.from)&&r.get(a.from)?.add(a.to),!a.to||!a.fromLayer||!a.toLayer)continue;let i=ae(e.rules,a.fromLayer,a.toLayer,{fromPath:a.from,toPath:a.to,layers:e.config.layers});if(!i)continue;let d=!!i.peerIsolation,p=!d&&!!(a.typeOnly||a.namedBindingsTypeOnly),b=i.message??(d?`${a.fromLayer} must not ${a.kind} another slice of ${a.toLayer} (${a.from} \u2192 ${a.to}). Extract shared code or use events/ports across slices.`:`${a.fromLayer} must not ${a.kind} ${a.toLayer}.`);t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:a.from,line:a.line,fromLayer:a.fromLayer,toLayer:a.toLayer,target:a.to,...a.typeOnly?{typeOnly:!0}:{},...a.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...a.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...a.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!d&&a.portProofEligible?{portProofEligible:!0}:{},...a.kind?{edgeKind:a.kind}:{},...d?{peerIsolation:!0}:{},message:p?`${b} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:b,...p?{failsStrict:!1,severity:"warning"}:{}})}let s=String(e.config.cyclePolicy??"strict").toLowerCase();if(s!=="off"){let a=wt(r);s==="soft"||s==="framework-soft"?n.push(...a.map(i=>({...i,message:`${i.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...a)}return{violations:t,warnings:n,safety:e.safety}}function On(e,t){return t.some(n=>{try{return J(n).test(e)}catch{return!1}})}function Pn(e,t){let n=e.contract.config.safety??{},r=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,s=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,a=e.contract.config.dynamicImportAllowlist??[],i=t.safetyUses.filter(f=>f.kind==="ts-suppression").map(({file:f,line:y})=>({file:f,line:y})),d=t.safetyUses.filter(f=>f.kind==="any-cast").map(({file:f,line:y})=>({file:f,line:y})),p=t.safetyUses.filter(f=>(f.kind==="dynamic-import"||f.kind==="dynamic-require")&&!On(f.file,a)).map(f=>({file:f.file,line:f.line,kind:f.kind==="dynamic-require"?"require":"import"})),b=n.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(f=>f.kind==="in-memory-store").map(f=>({file:f.file,line:f.line,store:f.symbol??"in-memory store"})),A=n.allowDisabledPeerIsolation===!0?[]:(e.contract.config.rules??[]).filter(f=>f.peerIsolation===!1||f.allowed===!1&&!!f.from&&f.from===f.to&&f.peerIsolation!==!0).map(f=>({from:f.from,to:f.to})),h={tsSuppressions:i,anyCasts:d,nonLiteralDynamicImports:p,inMemoryProductionStores:b,disabledPeerIsolationRules:A,thresholds:{maxTsSuppressions:r,maxAnyCasts:s}},o=[],l=p.filter(f=>f.kind==="import");if(l.length>0){let f=l[0];o.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:f.file,line:f.line,message:`${l.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let c=p.filter(f=>f.kind==="require");if(c.length>0){let f=c[0];o.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:f.file,line:f.line,message:`${c.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(i.length>r){let f=i[0];o.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:f.file,line:f.line,message:`${i.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${r}).`})}if(d.length>s){let f=d[0];o.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:f.file,line:f.line,message:`${d.length} explicit any cast(s) exceed safety.maxAnyCasts (${s}).`})}if(b.length>0){let f=b[0];o.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:f.file,line:f.line,message:`${b.length} ArkGate InMemory store risk(s) appear in governed production source. Provide durable stores or set safety.allowInMemory only for an explicitly ephemeral service.`})}return A.length>0&&o.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${A.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:h,warnings:o}}function Fn(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}function xt(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return qe(e,n.length>0?n:Ge.map(r=>({name:r.layer,prefixes:r.prefixes})))}function Tn(e,t,n){let r=[],s=new Map(e.contract.config.layers.map(a=>[a.name,a]));for(let a of t.ambientUses){let i=n.get(a.file);!i||!Fn(a.symbol,s.get(i)?.forbiddenGlobals??[])||r.push({ruleId:"FORBIDDEN_GLOBAL",file:a.file,line:a.line,fromLayer:i,target:a.symbol,message:`${i} must not use the ambient global "${a.symbol}".`})}for(let a of t.capabilityUses){let i=n.get(a.file);if(!i)continue;let d=s.get(i),p=d?.forbiddenGlobals??[],b=a.source==="import-based"?t.dependencies.find(A=>A.from===a.file&&A.line===a.line&&A.specifier===a.symbol&&!A.typeOnly)?.kind:void 0;if(!(a.source==="ambient-global"&&je(a.symbol,p))){if(a.source==="import-based"){let A=fe(a.symbol,p);if(A){r.push({ruleId:"FORBIDDEN_GLOBAL",file:a.file,line:a.line,fromLayer:i,target:a.symbol,...b?{edgeKind:b}:{},message:`${i} must not use module "${a.symbol}" because it is the import form of forbidden global "${A}".`});continue}}se(d).includes(a.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:a.file,line:a.line,fromLayer:i,target:a.symbol,capability:a.capability,...b?{edgeKind:b}:{},message:a.source==="import-based"?`${i} denies the ${a.capability} capability; found import of "${a.symbol}".`:`${i} denies the ${a.capability} capability; found ambient "${a.symbol}".`})}}for(let a of t.publishCalls){let i=n.get(a.file);if(!i)continue;for(let p of ze({publishCall:!0,rawIntentName:a.rawIntentName,objectHasIntent:a.objectHasIntent,arkPublishCandidate:a.arkPublishCandidate,hasSource:a.hasSource}))r.push({ruleId:p.ruleId,file:a.file,line:a.line,...p.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:i}:{},message:p.message});if(!a.sourceIntent)continue;let d=xt(a.sourceIntent,e.contract);!d||d===i||r.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:a.file,line:a.line,fromLayer:i,toLayer:d,target:a.sourceIntent,message:`Publish source "${a.sourceIntent}" resolves to ${d}, but the publishing file is classified as ${i}.`})}for(let a of t.intentReferences){let i=n.get(a.file);if(!i)continue;let d=xt(a.intent,e.contract);if(!d)continue;let p=ae(e.contract.config.rules,i,d);p&&r.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:a.file,line:a.line,fromLayer:i,toLayer:d,target:a.intent,message:p.message??`${i} must not reference ${d} intent ${a.intent}.`})}return r}function Ye(e){let{facts:t}=e,n=ve(e.contract.config),r=t.evidenceRequirementsHash===n,s=r?t.completeness:"unavailable",a=r?t.completenessReasons:[...t.completenessReasons,{code:"EVIDENCE_REQUIREMENTS_MISMATCH",message:"Resolved facts were collected for different policy-controlled evidence requirements."}].sort((m,N)=>{let ce=`${m.code}\0${m.file??""}\0${m.message}`,de=`${N.code}\0${N.file??""}\0${N.message}`;return ce<de?-1:ce>de?1:0}),i=t.files.map(m=>({...m,layer:V(m.path,e.contract.config.layers)??null})),d=new Map(i.map(m=>[m.path,m.layer])),p=t.dependencies.map(m=>{let N=m.target?d.get(m.target)??V(m.target,e.contract.config.layers):void 0;return{from:m.from,fromLayer:d.get(m.from)??null,...m.resolution==="resolved-project"&&m.target?{to:m.target,...N?{toLayer:N}:{}}:{},line:m.line,kind:m.kind,typeOnly:m.typeOnly,...m.targetTypeOnlyExports?{targetTypeOnlyExports:m.targetTypeOnlyExports}:{},...m.sourcePureTypeModule?{sourcePureTypeModule:m.sourcePureTypeModule}:{},...m.namedBindingsTypeOnly?{namedBindingsTypeOnly:m.namedBindingsTypeOnly}:{},...m.portProofEligible?{portProofEligible:m.portProofEligible}:{}}}),b=Ke({config:e.contract.config,rules:e.contract.config.rules,files:i.map(m=>m.path)}),A=Pn(e,t),h=e.contract.arkRules??me(),o=i.map(m=>m.path),c={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?kt(e.coverageInputs.fileContents):{},...e.fileHints??{}},f=[...Ct({arkRules:h,classShapes:e.contract.classShapes??t.classShapes??[],files:o,layerForFile:m=>d.get(m)??V(m,e.contract.config.layers),fileHints:c}),...St(h,o)],y=f.filter(m=>m.failsStrict).map(m=>({ruleId:m.ruleId,file:m.file,line:m.line,message:m.message,fromLayer:m.fromLayer,arkruleId:m.arkruleId,arkruleSource:m.arkruleSource,nextAction:m.ruleId==="ARKRULE_SCOPE_EMPTY"?`Fix appliesTo globs for ${m.arkruleId} in ${m.arkruleSource} so they match governed files, or remove the rule.`:`Fix the structure or invariant for ${m.arkruleId} (declared in ${m.arkruleSource}), then preflight again.`})),R=f.filter(m=>!m.failsStrict).map(m=>({ruleId:m.ruleId,file:m.file,line:m.line,message:m.message,fromLayer:m.fromLayer,arkruleId:m.arkruleId,arkruleSource:m.arkruleSource,failsStrict:!1,nextAction:m.ruleId==="ARKRULE_SCOPE_EMPTY"?`Review appliesTo for ${m.arkruleId} in ${m.arkruleSource} (zero-match scope; advisory).`:`Review ArkRule ${m.arkruleId} in ${m.arkruleSource} (advisory).`})),g=(h.invariants?.length??0)>0?Et({arkRules:h,fileContents:e.coverageInputs?.fileContents??{},testFiles:e.coverageInputs?.testFiles??[],testGlobsMissing:e.coverageInputs?.testGlobsMissing===!0||e.coverageInputs===void 0||(e.coverageInputs.testFiles?.length??0)===0}):{coverage:[],violations:[],partial:!1},v=g.violations.filter(m=>m.failsStrict).map(m=>({ruleId:m.ruleId,file:m.file,line:m.line,message:m.message,fromLayer:m.fromLayer,arkruleId:m.arkruleId,arkruleSource:m.arkruleSource,nextAction:`Add a test title or declared symbol covering ${m.arkruleId} (declared in ${m.arkruleSource}), then preflight again.`})),k=g.violations.filter(m=>!m.failsStrict).map(m=>({ruleId:m.ruleId,file:m.file,line:m.line,message:m.message,fromLayer:m.fromLayer,arkruleId:m.arkruleId,arkruleSource:m.arkruleSource,failsStrict:!1,nextAction:`Cover invariant ${m.arkruleId} in ${m.arkruleSource} (advisory / partial).`})),Y=g.partial&&g.coverage.some(m=>m.mode==="enforced"&&m.partial)?[{code:"INVARIANT_COVERAGE_PARTIAL",message:"Enforced ArkRules invariant coverage cannot be fully proven (missing test globs or empty test set); reporting partial, never covered."}]:[],z=ge({config:e.contract.config,rules:e.contract.config.rules,files:i.filter(m=>m.layer).map(m=>m.path),contentViolations:[...Tn(e,t,d),...y,...v],edges:p,warnings:[...b,...A.warnings,...R,...k],safety:A.report}),Le=s==="complete"&&Y.length>0?"partial":s,Qt=Le==="complete"?a:[...a,...Y].sort((m,N)=>{let ce=`${m.code}\0${m.file??""}\0${m.message}`,de=`${N.code}\0${N.file??""}\0${N.message}`;return ce<de?-1:ce>de?1:0}),en=z.violations.filter(m=>m.failsStrict!==!1),ot=Le==="complete"&&en.length===0,tn=ot&&z.warnings.every(m=>m.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:Le,completenessReasons:Qt,valid:ot,strictValid:tn,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:A.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:i,layers:e.contract.config.layers.map(m=>m.name),edges:p,capabilityUses:t.capabilityUses,violations:z.violations,warnings:z.warnings}}}function $e(e){return Ye({contract:e.contract,facts:W(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints})}var We="1.0";var we=class extends Error{issues;source;constructor(t,n){super(`Invalid architecture change map (${t}):
4
4
  ${n.map(r=>`- ${r.path}: ${r.message}`).join(`
5
- `)}`),this.name="ArchitectureChangeMapValidationError",this.source=t,this.issues=n}};function Je(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ze(e,t,n,r){for(let s of Object.keys(e))t.includes(s)||r.push({path:`${n}.${s}`,message:"unknown field"})}function Z(e,t,n,r){let s=e[t];if(typeof s=="string"&&s.length>0)return s;r.push({path:`${n}.${t}`,message:"must be a non-empty string"})}function _n(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let s of t.split("/"))if(!(!s||s==="."))if(s===".."){if(n.length===0)return;n.pop()}else n.push(s);let r=n.join("/");return r&&r===t?r:void 0}function Ln(e,t,n="architecture change map"){let r=[];if(!Je(e))throw new we(n,[{path:"$",message:"must be an object"}]);Ze(e,["$schema","schemaVersion","files","dependencies"],"$",r);let s=Z(e,"$schema","$",r),a=Z(e,"schemaVersion","$",r);a&&a!==We&&r.push({path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(a)}; expected ${We}`});let i=new Set(t.layers.map(c=>c.name)),d=[],p=new Set;!Array.isArray(e.files)||e.files.length===0?r.push({path:"$.files",message:"must be a non-empty array"}):e.files.forEach((c,f)=>{let y=`$.files[${f}]`;if(!Je(c)){r.push({path:y,message:"must be an object"});return}Ze(c,["path","operation","layer"],y,r);let R=Z(c,"path",y,r),u=Z(c,"operation",y,r),g=Z(c,"layer",y,r),v=R?_n(R):void 0;R&&!v&&r.push({path:`${y}.path`,message:"must be a canonical project-relative path"}),u&&!["create","update","delete"].includes(u)&&r.push({path:`${y}.operation`,message:"must be create, update, or delete"}),g&&!i.has(g)&&r.push({path:`${y}.layer`,message:`references unknown layer ${JSON.stringify(g)}`}),v&&p.has(v)&&r.push({path:`${y}.path`,message:`duplicates planned path ${v}`}),v&&p.add(v);let k=v?V(v,t.layers):void 0;v&&g&&i.has(g)&&k!==g&&r.push({path:`${y}.layer`,message:k?`${v} resolves to ${k}, not ${g}`:`${v} is not assigned to an architecture layer`}),v&&u&&["create","update","delete"].includes(u)&&g&&d.push({path:v,operation:u,layer:g})});let b=[],A=new Map(d.map(c=>[c.path,c.operation])),h=new Set,o=e.dependencies??[];if(Array.isArray(o)?o.forEach((c,f)=>{let y=`$.dependencies[${f}]`;if(!Je(c)){r.push({path:y,message:"must be an object"});return}Ze(c,["from","to"],y,r);let R=Z(c,"from",y,r),u=Z(c,"to",y,r);R&&!p.has(R)&&r.push({path:`${y}.from`,message:`must reference a planned file path: ${R}`}),u&&!p.has(u)&&r.push({path:`${y}.to`,message:`must reference a planned file path: ${u}`}),R&&A.get(R)==="delete"&&r.push({path:`${y}.from`,message:`cannot depend from deleted file ${R}`}),u&&A.get(u)==="delete"&&r.push({path:`${y}.to`,message:`cannot depend on deleted file ${u}`}),R&&u&&R===u&&r.push({path:y,message:"must not declare a self dependency"});let g=R&&u?`${R}\0${u}`:void 0;g&&h.has(g)&&r.push({path:y,message:`duplicates dependency ${R} -> ${u}`}),g&&h.add(g),R&&u&&b.push({from:R,to:u})}):r.push({path:"$.dependencies",message:"must be an array"}),r.length>0)throw new we(n,r);let l={$schema:s,schemaVersion:We,files:d.sort((c,f)=>c.path.localeCompare(f.path)),dependencies:b.sort((c,f)=>c.from.localeCompare(f.from)||c.to.localeCompare(f.to))};return{map:l,hash:E(S(l))}}function O(e){return`${e.from}->${e.to}`}function he(e,t,n,r="dependency"){return{id:`${e}:${r}:${O(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${O(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${O(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${O(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${O(t)} from the candidate, then preflight again.`}:{}}}function be(e){let t=[],n=new Map(e.changeMap.map.files.map(o=>[o.path,o])),r=new Map(e.changes.map(o=>[o.path,o])),s=new Map(e.changeMap.map.dependencies.map(o=>[O(o),o])),a=new Map(e.baseDependencies.map(o=>[O(o),o])),i=new Map(e.candidateDependencies.map(o=>[O(o),o]));for(let o of[...n.values()].sort((l,c)=>l.path.localeCompare(c.path))){let l=r.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[...r.values()].sort((l,c)=>l.path.localeCompare(c.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 d=new Set;for(let o of[...s.values()].sort((l,c)=>O(l).localeCompare(O(c)))){if(i.has(O(o))){t.push(he("satisfied",o,`${o.from} -> ${o.to} exists in the candidate architecture.`));continue}let l={from:o.to,to:o.from};i.has(O(l))?(d.add(O(l)),t.push(he("contradictory",o,`${o.from} -> ${o.to} was planned, but the candidate contains the reverse edge.`))):t.push(he("missing",o,`${o.from} -> ${o.to} is absent from the candidate architecture.`))}let p=new Set([...n.keys(),...r.keys()]);for(let[o,l]of[...i].sort(([c],[f])=>c.localeCompare(f)))a.has(o)||s.has(o)||d.has(o)||!p.has(l.from)&&!p.has(l.to)||t.push({...he("unplanned",l,`${l.from} -> ${l.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let b=new Set(e.changeMap.map.files.filter(o=>o.operation==="delete").map(o=>o.path));for(let[o,l]of[...a].sort(([c],[f])=>c.localeCompare(f)))i.has(o)||b.has(l.from)||b.has(l.to)||!p.has(l.from)&&!p.has(l.to)||t.push({...he("unplanned",l,`${l.from} -> ${l.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let A={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((o,l)=>A[o.classification]-A[l.classification]||(o.subject===l.subject?0:o.subject==="file"?-1:1)||o.id.localeCompare(l.id));let h={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:h.missing===0&&h.contradictory===0&&h.unplanned===0,behavioralCompletion:"not-evaluated",summary:h,findings:t}}function oe(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function Ft(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function Ot(e,t){if(e.isImportDeclaration(t)){let r=t.importClause;if(!r)return!1;if(r.isTypeOnly)return!0;let s=r.namedBindings;return!!(s&&e.isNamedImports(s)&&s.elements.length>0&&s.elements.every(a=>a.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(r=>r.isTypeOnly))}function Tt(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=s=>s===t.fileName?t:void 0,r.fileExists=s=>s===t.fileName,r.readFile=s=>s===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}function Xe(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function Qe(e,t,n,r){let s=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,a;try{a=s?t.getShorthandAssignmentValueSymbol(r.parent):Xe(t,r)}catch{a=void 0}return!!a?.declarations?.some(i=>i.getSourceFile().fileName===n.fileName)}function et(e,t){let n,r=[],s=(i,d,p,b=!1)=>r.push({specifier:p,kind:d,line:Ft(t,i),typeOnly:b,unresolved:p===void 0,node:i}),a=i=>{if(e.isImportDeclaration(i))s(i,"import",oe(e,i.moduleSpecifier),Ot(e,i));else if(e.isExportDeclaration(i)&&i.moduleSpecifier)s(i,"export",oe(e,i.moduleSpecifier),Ot(e,i));else if(e.isImportEqualsDeclaration(i)&&e.isExternalModuleReference(i.moduleReference))s(i,"require",oe(e,i.moduleReference.expression),i.isTypeOnly===!0);else if(e.isCallExpression(i)){let d=i.expression.kind===e.SyntaxKind.ImportKeyword,b=e.isIdentifier(i.expression)&&i.expression.text==="require"&&!Qe(e,n??(n=Tt(e,t)),t,i.expression);(d||b)&&s(i,b?"require":"dynamic-import",oe(e,i.arguments[0]))}e.forEachChild(i,a)};return a(t),r}function Nn(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let s=oe(e,r.argumentExpression);if(s===void 0)return;n.unshift(s)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}function Mn(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 Pt(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let r=n.length;r>=1;r-=1){let s=n.slice(0,r).join(".");if(e.has(s))return s}}function tt(e,t,n){if(n.length===0)return[];let r=new Set(n),s=Tt(e,t),a=new Map,i=new Set;for(let o of t.statements)if(e.isVariableStatement(o))for(let l of o.declarationList.declarations)e.isIdentifier(l.name)&&i.add(l.name.text);let d=o=>{let l=Nn(e,o);if(!l)return;let c=Xe(s,l.root),f=c?a.get(c):void 0;return f?[...f,...l.segments.slice(1)]:Qe(e,s,t,l.root)||i.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 c=d(l.initializer),f=Xe(s,l.name);!c||!f||a.set(f,c)}let p=[],b=new Set,A=(o,l)=>{let c=Ft(t,l),f=`${o}:${l.getStart(t)}`;b.has(f)||(b.add(f),p.push({name:o,line:c,node:l}))},h=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 c=d(o),f=c?Pt(r,c):void 0;f&&A(f,o)}else e.isIdentifier(o)&&r.has(o.text)&&Mn(e,o)&&!Qe(e,s,t,o)&&A(o.text,o);if(e.isVariableDeclaration(o)&&e.isObjectBindingPattern(o.name)&&o.initializer){let c=d(o.initializer);if(c)for(let f of o.name.elements){if(!e.isIdentifier(f.name))continue;let y=f.propertyName?oe(e,f.propertyName)??f.propertyName.text:f.name.text,R=Pt(r,[...c,y]);R&&A(R,o.initializer)}}e.forEachChild(o,h)};return h(t),p}function Hn(e,t,n){let r=[];for(let s of n?.dependencies??et(e,t)){if(s.typeOnly||!s.specifier)continue;let a=pe(s.specifier);a&&r.push({capability:a,symbol:s.specifier,line:s.line,source:"import-based"})}for(let s of n?.ambientUses??tt(e,t,De)){let a=ue(s.name);a&&r.push({capability:a,symbol:s.name,line:s.line,source:"ambient-global"})}return r.sort((s,a)=>s.line-a.line||s.capability.localeCompare(a.capability)||s.symbol.localeCompare(a.symbol))}var nt="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",_t=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Dn=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function jn(){let e=[];for(let t of _t)for(let n of _t)t===n||Dn.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var Nt=jn(),rt=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"}],B={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Lt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:nt,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:nt,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:"1.1",default:"1.1"},name:{type:"string",minLength:1},include:{...B,minItems:1,default:["src"]},exclude:{...B,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:Nt,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...B,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...B,minItems:1},exclude:B,intentPrefixes:B,description:{type:"string",minLength:1},forbiddenGlobals:B,capabilities:{type:"object",additionalProperties:!1,properties:{deny:{type:"array",uniqueItems:!0,items:{type:"string",enum:["network","filesystem","clock","randomness","environment","process","persistence"]}}}},pure:{type:"boolean"},mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...B,minItems:1}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}}}},G=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
5
+ `)}`),this.name="ArchitectureChangeMapValidationError",this.source=t,this.issues=n}};function Je(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ze(e,t,n,r){for(let s of Object.keys(e))t.includes(s)||r.push({path:`${n}.${s}`,message:"unknown field"})}function Z(e,t,n,r){let s=e[t];if(typeof s=="string"&&s.length>0)return s;r.push({path:`${n}.${t}`,message:"must be a non-empty string"})}function _n(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let s of t.split("/"))if(!(!s||s==="."))if(s===".."){if(n.length===0)return;n.pop()}else n.push(s);let r=n.join("/");return r&&r===t?r:void 0}function Ln(e,t,n="architecture change map"){let r=[];if(!Je(e))throw new we(n,[{path:"$",message:"must be an object"}]);Ze(e,["$schema","schemaVersion","files","dependencies"],"$",r);let s=Z(e,"$schema","$",r),a=Z(e,"schemaVersion","$",r);a&&a!==We&&r.push({path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(a)}; expected ${We}`});let i=new Set(t.layers.map(c=>c.name)),d=[],p=new Set;!Array.isArray(e.files)||e.files.length===0?r.push({path:"$.files",message:"must be a non-empty array"}):e.files.forEach((c,f)=>{let y=`$.files[${f}]`;if(!Je(c)){r.push({path:y,message:"must be an object"});return}Ze(c,["path","operation","layer"],y,r);let R=Z(c,"path",y,r),u=Z(c,"operation",y,r),g=Z(c,"layer",y,r),v=R?_n(R):void 0;R&&!v&&r.push({path:`${y}.path`,message:"must be a canonical project-relative path"}),u&&!["create","update","delete"].includes(u)&&r.push({path:`${y}.operation`,message:"must be create, update, or delete"}),g&&!i.has(g)&&r.push({path:`${y}.layer`,message:`references unknown layer ${JSON.stringify(g)}`}),v&&p.has(v)&&r.push({path:`${y}.path`,message:`duplicates planned path ${v}`}),v&&p.add(v);let k=v?V(v,t.layers):void 0;v&&g&&i.has(g)&&k!==g&&r.push({path:`${y}.layer`,message:k?`${v} resolves to ${k}, not ${g}`:`${v} is not assigned to an architecture layer`}),v&&u&&["create","update","delete"].includes(u)&&g&&d.push({path:v,operation:u,layer:g})});let b=[],A=new Map(d.map(c=>[c.path,c.operation])),h=new Set,o=e.dependencies??[];if(Array.isArray(o)?o.forEach((c,f)=>{let y=`$.dependencies[${f}]`;if(!Je(c)){r.push({path:y,message:"must be an object"});return}Ze(c,["from","to"],y,r);let R=Z(c,"from",y,r),u=Z(c,"to",y,r);R&&!p.has(R)&&r.push({path:`${y}.from`,message:`must reference a planned file path: ${R}`}),u&&!p.has(u)&&r.push({path:`${y}.to`,message:`must reference a planned file path: ${u}`}),R&&A.get(R)==="delete"&&r.push({path:`${y}.from`,message:`cannot depend from deleted file ${R}`}),u&&A.get(u)==="delete"&&r.push({path:`${y}.to`,message:`cannot depend on deleted file ${u}`}),R&&u&&R===u&&r.push({path:y,message:"must not declare a self dependency"});let g=R&&u?`${R}\0${u}`:void 0;g&&h.has(g)&&r.push({path:y,message:`duplicates dependency ${R} -> ${u}`}),g&&h.add(g),R&&u&&b.push({from:R,to:u})}):r.push({path:"$.dependencies",message:"must be an array"}),r.length>0)throw new we(n,r);let l={$schema:s,schemaVersion:We,files:d.sort((c,f)=>c.path.localeCompare(f.path)),dependencies:b.sort((c,f)=>c.from.localeCompare(f.from)||c.to.localeCompare(f.to))};return{map:l,hash:E(S(l))}}function O(e){return`${e.from}->${e.to}`}function he(e,t,n,r="dependency"){return{id:`${e}:${r}:${O(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${O(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${O(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${O(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${O(t)} from the candidate, then preflight again.`}:{}}}function be(e){let t=[],n=new Map(e.changeMap.map.files.map(o=>[o.path,o])),r=new Map(e.changes.map(o=>[o.path,o])),s=new Map(e.changeMap.map.dependencies.map(o=>[O(o),o])),a=new Map(e.baseDependencies.map(o=>[O(o),o])),i=new Map(e.candidateDependencies.map(o=>[O(o),o]));for(let o of[...n.values()].sort((l,c)=>l.path.localeCompare(c.path))){let l=r.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[...r.values()].sort((l,c)=>l.path.localeCompare(c.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 d=new Set;for(let o of[...s.values()].sort((l,c)=>O(l).localeCompare(O(c)))){if(i.has(O(o))){t.push(he("satisfied",o,`${o.from} -> ${o.to} exists in the candidate architecture.`));continue}let l={from:o.to,to:o.from};i.has(O(l))?(d.add(O(l)),t.push(he("contradictory",o,`${o.from} -> ${o.to} was planned, but the candidate contains the reverse edge.`))):t.push(he("missing",o,`${o.from} -> ${o.to} is absent from the candidate architecture.`))}let p=new Set([...n.keys(),...r.keys()]);for(let[o,l]of[...i].sort(([c],[f])=>c.localeCompare(f)))a.has(o)||s.has(o)||d.has(o)||!p.has(l.from)&&!p.has(l.to)||t.push({...he("unplanned",l,`${l.from} -> ${l.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let b=new Set(e.changeMap.map.files.filter(o=>o.operation==="delete").map(o=>o.path));for(let[o,l]of[...a].sort(([c],[f])=>c.localeCompare(f)))i.has(o)||b.has(l.from)||b.has(l.to)||!p.has(l.from)&&!p.has(l.to)||t.push({...he("unplanned",l,`${l.from} -> ${l.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let A={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((o,l)=>A[o.classification]-A[l.classification]||(o.subject===l.subject?0:o.subject==="file"?-1:1)||o.id.localeCompare(l.id));let h={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:h.missing===0&&h.contradictory===0&&h.unplanned===0,behavioralCompletion:"not-evaluated",summary:h,findings:t}}function oe(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function Ft(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function Ot(e,t){if(e.isImportDeclaration(t)){let r=t.importClause;if(!r)return!1;if(r.isTypeOnly)return!0;let s=r.namedBindings;return!!(s&&e.isNamedImports(s)&&s.elements.length>0&&s.elements.every(a=>a.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(r=>r.isTypeOnly))}function Tt(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=s=>s===t.fileName?t:void 0,r.fileExists=s=>s===t.fileName,r.readFile=s=>s===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}function Xe(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function Qe(e,t,n,r){let s=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,a;try{a=s?t.getShorthandAssignmentValueSymbol(r.parent):Xe(t,r)}catch{a=void 0}return!!a?.declarations?.some(i=>i.getSourceFile().fileName===n.fileName)}function et(e,t){let n,r=[],s=(i,d,p,b=!1)=>r.push({specifier:p,kind:d,line:Ft(t,i),typeOnly:b,unresolved:p===void 0,node:i}),a=i=>{if(e.isImportDeclaration(i))s(i,"import",oe(e,i.moduleSpecifier),Ot(e,i));else if(e.isExportDeclaration(i)&&i.moduleSpecifier)s(i,"export",oe(e,i.moduleSpecifier),Ot(e,i));else if(e.isImportEqualsDeclaration(i)&&e.isExternalModuleReference(i.moduleReference))s(i,"require",oe(e,i.moduleReference.expression),i.isTypeOnly===!0);else if(e.isCallExpression(i)){let d=i.expression.kind===e.SyntaxKind.ImportKeyword,b=e.isIdentifier(i.expression)&&i.expression.text==="require"&&!Qe(e,n??(n=Tt(e,t)),t,i.expression);(d||b)&&s(i,b?"require":"dynamic-import",oe(e,i.arguments[0]))}e.forEachChild(i,a)};return a(t),r}function Nn(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let s=oe(e,r.argumentExpression);if(s===void 0)return;n.unshift(s)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}function Mn(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 Pt(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let r=n.length;r>=1;r-=1){let s=n.slice(0,r).join(".");if(e.has(s))return s}}function tt(e,t,n){if(n.length===0)return[];let r=new Set(n),s=Tt(e,t),a=new Map,i=new Set;for(let o of t.statements)if(e.isVariableStatement(o))for(let l of o.declarationList.declarations)e.isIdentifier(l.name)&&i.add(l.name.text);let d=o=>{let l=Nn(e,o);if(!l)return;let c=Xe(s,l.root),f=c?a.get(c):void 0;return f?[...f,...l.segments.slice(1)]:Qe(e,s,t,l.root)||i.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 c=d(l.initializer),f=Xe(s,l.name);!c||!f||a.set(f,c)}let p=[],b=new Set,A=(o,l)=>{let c=Ft(t,l),f=`${o}:${l.getStart(t)}`;b.has(f)||(b.add(f),p.push({name:o,line:c,node:l}))},h=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 c=d(o),f=c?Pt(r,c):void 0;f&&A(f,o)}else e.isIdentifier(o)&&r.has(o.text)&&Mn(e,o)&&!Qe(e,s,t,o)&&A(o.text,o);if(e.isVariableDeclaration(o)&&e.isObjectBindingPattern(o.name)&&o.initializer){let c=d(o.initializer);if(c)for(let f of o.name.elements){if(!e.isIdentifier(f.name))continue;let y=f.propertyName?oe(e,f.propertyName)??f.propertyName.text:f.name.text,R=Pt(r,[...c,y]);R&&A(R,o.initializer)}}e.forEachChild(o,h)};return h(t),p}function Hn(e,t,n){let r=[];for(let s of n?.dependencies??et(e,t)){if(s.typeOnly||!s.specifier)continue;let a=pe(s.specifier);a&&r.push({capability:a,symbol:s.specifier,line:s.line,source:"import-based"})}for(let s of n?.ambientUses??tt(e,t,De)){let a=ue(s.name);a&&r.push({capability:a,symbol:s.name,line:s.line,source:"ambient-global"})}return r.sort((s,a)=>s.line-a.line||s.capability.localeCompare(a.capability)||s.symbol.localeCompare(a.symbol))}var nt="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",_t=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Dn=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function jn(){let e=[];for(let t of _t)for(let n of _t)t===n||Dn.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var Nt=jn(),rt=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"}],G={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Lt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:nt,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:nt,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:{...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:Nt,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}},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},stewards:{...G,default:[]}},$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}}}}},q=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
6
6
  ${n.map(r=>`- ${r.path}: ${r.message}`).join(`
7
- `)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function Mt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function xe(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function le(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Vn(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function Ae(e,t,n,r,s){if(t.$ref){let a=Vn(t.$ref,r);if(!a){s.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}Ae(e,a,n,r,s);return}if(t.const!==void 0&&!Object.is(e,t.const)){s.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(a=>Object.is(a,e))){s.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!Mt(e)){s.push({path:n,message:`must be an object; received ${le(e)}`});return}let a=t.properties??{};for(let i of t.required??[])e[i]===void 0&&s.push({path:xe(n,i),message:"is required"});if(t.additionalProperties===!1)for(let i of Object.keys(e))i in a||s.push({path:xe(n,i),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let i=t.additionalProperties;for(let d of Object.keys(e))d in a||Ae(e[d],i,xe(n,d),r,s)}for(let[i,d]of Object.entries(a))e[i]!==void 0&&Ae(e[i],d,xe(n,i),r,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:n,message:`must be an array; received ${le(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&s.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let a=e.map(i=>JSON.stringify(i));new Set(a).size!==a.length&&s.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((a,i)=>Ae(a,t.items,`${n}[${i}]`,r,s));return}if(t.type==="string"){if(typeof e!="string"){s.push({path:n,message:`must be a string; received ${le(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&s.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&s.push({path:n,message:`must be a boolean; received ${le(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){s.push({path:n,message:`must be an integer; received ${le(e)}`});return}t.minimum!==void 0&&e<t.minimum&&s.push({path:n,message:`must be at least ${t.minimum}`})}}function Un(e){return{...e,$schema:e.$schema===void 0?nt: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?Nt.map(t=>({...t})):e.rules}}function Gn(){let e=new Set(["1.1"]);for(let t of rt)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}function qn(e,t="ark.config.json"){if(!Mt(e))throw new G(t,[{path:"$",message:`must be an object; received ${le(e)}`}]);let n=Gn(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new G(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.1`}]);if(r!=="unversioned"&&!n.has(r))throw new G(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected 1.1`}]);let s=r,a={...e},i=0;for(;s!=="1.1"&&i<rt.length+1;){i+=1;let p=rt.find(b=>b.from===s);if(!p)throw new G(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(s)}; expected 1.1`}]);s=p.to,a.schemaVersion=s}if(s!=="1.1")throw new G(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected 1.1`}]);let d=r==="unversioned"?"unversioned":r==="1.0"?"1.0":null;return{candidate:Un(a),migratedFrom:d}}function st(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=qn(e,t),s=[];if(Ae(n,Lt,"$",Lt,s),s.length>0)throw new G(t,s);return{config:n,migratedFrom:r}}function Ht(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new G(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return st(n,t)}function Dt(e){return{config:e.config,arkRules:{schemaVersion:e.arkRules.schemaVersion,structure:e.arkRules.structure.map(t=>({id:t.id,sensor:t.sensor,mode:t.mode,appliesTo:t.appliesTo??null,description:t.description??null,provenance:t.provenance})),invariants:e.arkRules.invariants.map(t=>({id:t.id,description:t.description,aggregate:t.aggregate??null,coverage:t.coverage??null,mode:t.mode,appliesTo:t.appliesTo??null,provenance:t.provenance}))}}}var Ut="1.0";function I(e,t){e.push({id:`${t.classification}:${t.path}:${t.kind}`,path:t.path,classification:t.classification,message:t.message,...t.classification==="weakening"||t.classification==="judgment-required"?{nextAction:`Restore the previous protection at ${t.path}, then run ArkGate again.`}:{},...t.before===void 0?{}:{before:t.before},...t.after===void 0?{}:{after:t.after}})}function T(e){return[...new Set(e??[])].sort()}function X(e,t,n,r,s){let a=T(n),i=T(r),d=new Set(a),p=new Set(i),b=i.filter(h=>!d.has(h)),A=a.filter(h=>!p.has(h));b.length===0&&A.length===0||(b.length>0&&I(e,{kind:"added",path:t,classification:s.added,message:s.addedMessage,before:a,after:i}),A.length>0&&I(e,{kind:"removed",path:t,classification:s.removed,message:s.removedMessage,before:a,after:i}))}function Oe(e,t,n,r,s,a,i){if(n===r)return;I(e,{kind:r?"enabled":"disabled",path:t,classification:r?s:s==="strengthening"?"weakening":"strengthening",message:r?a:i,before:n,after:r})}function Pe(e,t){let n=new Map,r=new Set;for(let s of e){let a=t(s);n.has(a)?r.add(a):n.set(a,s)}return{values:n,duplicates:[...r].sort()}}function zn(e,t,n){let r=Pe(t,a=>a.name),s=Pe(n,a=>a.name);(r.duplicates.length>0||s.duplicates.length>0)&&I(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:r.duplicates,after:s.duplicates});for(let a of[...new Set([...r.values.keys(),...s.values.keys()])].sort()){let i=r.values.get(a),d=s.values.get(a),p=`$.layers[${a}]`;if(!i&&d){I(e,{kind:"layer-added",path:p,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:d});continue}if(i&&!d){I(e,{kind:"layer-removed",path:p,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:i});continue}if(!i||!d)continue;X(e,`${p}.patterns`,i.patterns,d.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),X(e,`${p}.exclude`,i.exclude,d.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let b=Se(i),A=Se(d);X(e,`${p}.forbiddenGlobals`,b.rawGlobals,A.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),X(e,`${p}.capabilities`,b.atoms,A.atoms,{added:"strengthening",removed:"weakening",addedMessage:"Additional ambient/import protection is enforced in this layer (coverage atoms).",removedMessage:"An ambient/import protection was lost from this layer (coverage atoms)."}),T(i.intentPrefixes).join("\0")!==T(d.intentPrefixes).join("\0")&&I(e,{kind:"intent-prefixes-changed",path:`${p}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:T(i.intentPrefixes),after:T(d.intentPrefixes)}),Oe(e,`${p}.mayImportInfrastructure`,i.mayImportInfrastructure===!0,d.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),Oe(e,`${p}.optional`,i.optional===!0,d.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active.")}}function Bn(e,t,n){let r=i=>`${i.from}->${i.to}`,s=Pe(t,r),a=Pe(n,r);(s.duplicates.length>0||a.duplicates.length>0)&&I(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:s.duplicates,after:a.duplicates});for(let i of[...new Set([...s.values.keys(),...a.values.keys()])].sort()){let d=s.values.get(i),p=a.values.get(i),b=`$.rules[${i}]`;if(!d&&p){p.allowed===!1&&I(e,{kind:"deny-added",path:b,classification:"strengthening",message:"A denied dependency edge was added.",after:p});continue}if(d&&!p){d.allowed===!1&&I(e,{kind:"deny-removed",path:b,classification:"weakening",message:"A denied dependency edge was removed.",before:d});continue}if(!d||!p)continue;d.allowed!==p.allowed&&I(e,{kind:p.allowed?"deny-disabled":"deny-enabled",path:`${b}.allowed`,classification:p.allowed?"weakening":"strengthening",message:p.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:d.allowed,after:p.allowed});let A=d.peerIsolation===!0,h=p.peerIsolation===!0;if(A!==h){let o=d.from===d.to&&p.from===p.to;I(e,{kind:h?"peer-isolation-enabled":"peer-isolation-disabled",path:`${b}.peerIsolation`,classification:o?h?"strengthening":"weakening":"judgment-required",message:o?h?"Cross-slice dependencies inside this layer are now denied.":"Cross-slice dependencies inside this layer are no longer denied.":"Changing peer isolation on a cross-layer edge changes the denial scope.",before:A,after:h})}T(d.sliceFolders).join("\0")!==T(p.sliceFolders).join("\0")&&I(e,{kind:"slice-folders-changed",path:`${b}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:T(d.sliceFolders),after:T(p.sliceFolders)})}}function Kn(e,t,n){let r=t.safety??{},s=n.safety??{};for(let a of["maxTsSuppressions","maxAnyCasts"]){let i=r[a]??0,d=s[a]??0;i!==d&&I(e,{kind:d>i?"threshold-raised":"threshold-lowered",path:`$.safety.${a}`,classification:d>i?"weakening":"strengthening",message:d>i?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:i,after:d})}for(let a of["allowInMemory","allowDisabledPeerIsolation"])Oe(e,`$.safety.${a}`,r[a]===!0,s[a]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}function Yn(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 jt(e,t){return`${e}::${t}`}function Vt(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(jt(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(jt(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}function Wn(e,t,n,r,s,a){let i=new Map((a??[]).map(o=>[o.invariantId,o])),d=t.arkRules??{},p=n.arkRules??{},b=[...new Set([...Object.keys(d),...Object.keys(p)])].sort();for(let o of b){let l=d[o],c=p[o],f=`$.arkRules[${o}]`;if(l===void 0&&c!==void 0){I(e,{kind:"arkrules-ref-added",path:f,classification:"strengthening",message:`ArkRules reference for layer ${o} was added.`,after:c});continue}if(l!==void 0&&c===void 0){I(e,{kind:"arkrules-ref-removed",path:f,classification:"weakening",message:`ArkRules reference for layer ${o} was removed.`,before:l});continue}l!==c&&I(e,{kind:"arkrules-ref-path-changed",path:f,classification:"judgment-required",message:`ArkRules file path for layer ${o} changed; verify the effective rules still match intent.`,before:l,after:c})}let A=Vt(r),h=Vt(s);for(let o of[...new Set([...A.structure.keys(),...h.structure.keys()])].sort()){let l=A.structure.get(o),c=h.structure.get(o),f=`$.arkRules.structure[${o}]`;if(!l&&c){I(e,{kind:"arkrule-structure-added",path:f,classification:"strengthening",message:`Structure ArkRule ${c.id} was added (${c.mode}).`,after:c});continue}if(l&&!c){I(e,{kind:"arkrule-structure-removed",path:f,classification:"weakening",message:`Structure ArkRule ${l.id} was removed.`,before:l});continue}if(!(!l||!c)){if(l.mode!==c.mode){let y=l.mode==="advisory"&&c.mode==="enforced";I(e,{kind:y?"arkrule-promoted":"arkrule-demoted",path:`${f}.mode`,classification:y?"strengthening":"weakening",message:y?`Structure ArkRule ${c.id} was promoted to enforced.`:`Structure ArkRule ${c.id} was demoted to advisory.`,before:l.mode,after:c.mode})}l.sensor!==c.sensor&&I(e,{kind:"arkrule-sensor-changed",path:`${f}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${c.id} changed sensor identity.`,before:l.sensor,after:c.sensor})}}for(let o of[...new Set([...A.invariants.keys(),...h.invariants.keys()])].sort()){let l=A.invariants.get(o),c=h.invariants.get(o),f=`$.arkRules.invariants[${o}]`;if(!l&&c){I(e,{kind:"arkrule-invariant-added",path:f,classification:"strengthening",message:`Invariant ${c.id} was added (${c.mode}).`,after:c});continue}if(l&&!c){I(e,{kind:"arkrule-invariant-removed",path:f,classification:"weakening",message:`Invariant ${l.id} was removed.`,before:l});continue}if(!(!l||!c)&&l.mode!==c.mode)if(l.mode==="advisory"&&c.mode==="enforced"){let R=i?.get(c.id),u=$t(R);u.ok?I(e,{kind:"arkrule-invariant-promoted",path:`${f}.mode`,classification:"strengthening",message:`Invariant ${c.id} was promoted to enforced (coverage evidence present).`,before:l.mode,after:c.mode}):I(e,{kind:"arkrule-invariant-promote-refused",path:`${f}.mode`,classification:"judgment-required",message:`Invariant ${c.id} cannot be promoted to enforced: ${u.reason}`,before:l.mode,after:c.mode})}else I(e,{kind:"arkrule-invariant-demoted",path:`${f}.mode`,classification:"weakening",message:`Invariant ${c.id} was demoted to advisory.`,before:l.mode,after:c.mode})}}function Gt(e,t,n){let r=[];X(r,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),X(r,"$.exclude",e.exclude,t.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional project paths are excluded from governance.",removedMessage:"Fewer project paths are excluded from governance."}),X(r,"$.dynamicImportAllowlist",e.dynamicImportAllowlist,t.dynamicImportAllowlist,{added:"weakening",removed:"strengthening",addedMessage:"Additional files may use non-literal dynamic imports.",removedMessage:"Fewer files may use non-literal dynamic imports."}),Oe(r,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let s={off:0,soft:1,"framework-soft":1,strict:2},a=e.cyclePolicy??"strict",i=t.cyclePolicy??"strict";if(a!==i){let d=s[i]===s[a]?"judgment-required":s[i]>s[a]?"strengthening":"weakening";I(r,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:d,message:"The cycle enforcement level changed.",before:a,after:i})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&I(r,{kind:"framework-overlay-changed",path:"$.frameworkOverlay",classification:"judgment-required",message:"The framework overlay changed and may alter effective layer matching.",before:e.frameworkOverlay??null,after:t.frameworkOverlay??null}),zn(r,e.layers,t.layers),Bn(r,e.rules,t.rules),Kn(r,e,t),Wn(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),r.sort((d,p)=>d.path.localeCompare(p.path)||d.id.localeCompare(p.id)),{schemaVersion:Ut,classification:Yn(r),findings:r}}function qt(e,t){if(!e||e.schemaVersion!==Ut||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(s=>typeof s!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=T(e.findingIds),r=T(t.findingIds);return n.length===r.length&&n.every((s,a)=>s===r[a])}function Q(e){let t=[];for(let n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."&&t.length>0&&t.at(-1)!==".."?t.pop():t.push(n));return t.join("/")}function zt(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}function Fe(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}function P(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}function Re(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let r=t,s="";for(t+=1;t<e.length;t+=1){let a=e[t];if(a===n)return{value:s,offset:r,excerpt:e.slice(r,t+1)};a==="\\"&&t+1<e.length?(s+=e[t+1],t+=1):s+=a}}function _(e,t,n){return e.startsWith(t,n)&&!Fe(e[n-1])&&!Fe(e[n+t.length])}function Bt(e,t){let n=P(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=P(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!_(e,"type",n))return!1;let s=P(e,n+4);if(s>=e.length||e[s]===","||e[s]==="}"||_(e,"as",s)||!zt(e[s]))return!1;for(n=s;n<e.length&&Fe(e[n]);)n+=1;if(n=P(e,n),_(e,"as",n)){if(n=P(e,n+2),!zt(e[n]))return!1;for(;n<e.length&&Fe(e[n]);)n+=1}r=!0}return!1}function Jn(e,t){if(t=P(e,t+6),e[t]==="(")return Re(e,P(e,t+1));let n=!1;if(_(e,"type",t)){let s=P(e,t+4);e[s]!==","&&!_(e,"from",s)&&(n=!0)}else Bt(e,t)&&(n=!0);let r=Kt(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}function Zn(e,t){t=t+6;let n=P(e,t),r=!1;if(_(e,"type",n)){let a=P(e,n+4);(e[a]==="{"||e[a]==="*")&&(r=!0)}else Bt(e,n)&&(r=!0);let s=Kt(e,t,!1);return s&&r?{...s,typeOnly:!0}:s}function Kt(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(_(e,"from",t))return Re(e,P(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return Re(e,t);if(t>0&&(_(e,"import",t)||_(e,"export",t)))return}}function Xn(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 Qn(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=P(e,t+7);if(e[r]!=="(")return;r=P(e,r+1);let s=Re(e,r);return s?{...s,requireCall:!0}:void 0}function er(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="/"&&e[n+1]==="/"){if(n=e.indexOf(`
7
+ `)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function Mt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function xe(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function le(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Vn(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function Ae(e,t,n,r,s){if(t.$ref){let a=Vn(t.$ref,r);if(!a){s.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}Ae(e,a,n,r,s);return}if(t.const!==void 0&&!Object.is(e,t.const)){s.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(a=>Object.is(a,e))){s.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!Mt(e)){s.push({path:n,message:`must be an object; received ${le(e)}`});return}let a=t.properties??{};for(let i of t.required??[])e[i]===void 0&&s.push({path:xe(n,i),message:"is required"});if(t.additionalProperties===!1)for(let i of Object.keys(e))i in a||s.push({path:xe(n,i),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let i=t.additionalProperties;for(let d of Object.keys(e))d in a||Ae(e[d],i,xe(n,d),r,s)}for(let[i,d]of Object.entries(a))e[i]!==void 0&&Ae(e[i],d,xe(n,i),r,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:n,message:`must be an array; received ${le(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&s.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let a=e.map(i=>JSON.stringify(i));new Set(a).size!==a.length&&s.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((a,i)=>Ae(a,t.items,`${n}[${i}]`,r,s));return}if(t.type==="string"){if(typeof e!="string"){s.push({path:n,message:`must be a string; received ${le(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&s.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&s.push({path:n,message:`must be a boolean; received ${le(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){s.push({path:n,message:`must be an integer; received ${le(e)}`});return}t.minimum!==void 0&&e<t.minimum&&s.push({path:n,message:`must be at least ${t.minimum}`})}}function Un(e){return{...e,$schema:e.$schema===void 0?nt: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?Nt.map(t=>({...t})):e.rules}}function Gn(){let e=new Set(["1.1"]);for(let t of rt)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}function qn(e,t="ark.config.json"){if(!Mt(e))throw new q(t,[{path:"$",message:`must be an object; received ${le(e)}`}]);let n=Gn(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new q(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.1`}]);if(r!=="unversioned"&&!n.has(r))throw new q(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected 1.1`}]);let s=r,a={...e},i=0;for(;s!=="1.1"&&i<rt.length+1;){i+=1;let p=rt.find(b=>b.from===s);if(!p)throw new q(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(s)}; expected 1.1`}]);s=p.to,a.schemaVersion=s}if(s!=="1.1")throw new q(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected 1.1`}]);let d=r==="unversioned"?"unversioned":r==="1.0"?"1.0":null;return{candidate:Un(a),migratedFrom:d}}function st(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=qn(e,t),s=[];if(Ae(n,Lt,"$",Lt,s),s.length>0)throw new q(t,s);return{config:n,migratedFrom:r}}function Ht(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new q(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return st(n,t)}function Dt(e){let{stewards:t,...n}=e.config;return{config:n,arkRules:{schemaVersion:e.arkRules.schemaVersion,structure:e.arkRules.structure.map(r=>({id:r.id,sensor:r.sensor,mode:r.mode,appliesTo:r.appliesTo??null,description:r.description??null,provenance:r.provenance})),invariants:e.arkRules.invariants.map(r=>({id:r.id,description:r.description,aggregate:r.aggregate??null,coverage:r.coverage??null,mode:r.mode,appliesTo:r.appliesTo??null,provenance:r.provenance}))}}}var Ut="1.0";function I(e,t){e.push({id:`${t.classification}:${t.path}:${t.kind}`,path:t.path,classification:t.classification,message:t.message,...t.classification==="weakening"||t.classification==="judgment-required"?{nextAction:`Restore the previous protection at ${t.path}, then run ArkGate again.`}:{},...t.before===void 0?{}:{before:t.before},...t.after===void 0?{}:{after:t.after}})}function T(e){return[...new Set(e??[])].sort()}function X(e,t,n,r,s){let a=T(n),i=T(r),d=new Set(a),p=new Set(i),b=i.filter(h=>!d.has(h)),A=a.filter(h=>!p.has(h));b.length===0&&A.length===0||(b.length>0&&I(e,{kind:"added",path:t,classification:s.added,message:s.addedMessage,before:a,after:i}),A.length>0&&I(e,{kind:"removed",path:t,classification:s.removed,message:s.removedMessage,before:a,after:i}))}function Oe(e,t,n,r,s,a,i){if(n===r)return;I(e,{kind:r?"enabled":"disabled",path:t,classification:r?s:s==="strengthening"?"weakening":"strengthening",message:r?a:i,before:n,after:r})}function Pe(e,t){let n=new Map,r=new Set;for(let s of e){let a=t(s);n.has(a)?r.add(a):n.set(a,s)}return{values:n,duplicates:[...r].sort()}}function zn(e,t,n){let r=Pe(t,a=>a.name),s=Pe(n,a=>a.name);(r.duplicates.length>0||s.duplicates.length>0)&&I(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:r.duplicates,after:s.duplicates});for(let a of[...new Set([...r.values.keys(),...s.values.keys()])].sort()){let i=r.values.get(a),d=s.values.get(a),p=`$.layers[${a}]`;if(!i&&d){I(e,{kind:"layer-added",path:p,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:d});continue}if(i&&!d){I(e,{kind:"layer-removed",path:p,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:i});continue}if(!i||!d)continue;X(e,`${p}.patterns`,i.patterns,d.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),X(e,`${p}.exclude`,i.exclude,d.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let b=Se(i),A=Se(d);X(e,`${p}.forbiddenGlobals`,b.rawGlobals,A.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),X(e,`${p}.capabilities`,b.atoms,A.atoms,{added:"strengthening",removed:"weakening",addedMessage:"Additional ambient/import protection is enforced in this layer (coverage atoms).",removedMessage:"An ambient/import protection was lost from this layer (coverage atoms)."}),T(i.intentPrefixes).join("\0")!==T(d.intentPrefixes).join("\0")&&I(e,{kind:"intent-prefixes-changed",path:`${p}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:T(i.intentPrefixes),after:T(d.intentPrefixes)}),Oe(e,`${p}.mayImportInfrastructure`,i.mayImportInfrastructure===!0,d.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),Oe(e,`${p}.optional`,i.optional===!0,d.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active.")}}function Bn(e,t,n){let r=i=>`${i.from}->${i.to}`,s=Pe(t,r),a=Pe(n,r);(s.duplicates.length>0||a.duplicates.length>0)&&I(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:s.duplicates,after:a.duplicates});for(let i of[...new Set([...s.values.keys(),...a.values.keys()])].sort()){let d=s.values.get(i),p=a.values.get(i),b=`$.rules[${i}]`;if(!d&&p){p.allowed===!1&&I(e,{kind:"deny-added",path:b,classification:"strengthening",message:"A denied dependency edge was added.",after:p});continue}if(d&&!p){d.allowed===!1&&I(e,{kind:"deny-removed",path:b,classification:"weakening",message:"A denied dependency edge was removed.",before:d});continue}if(!d||!p)continue;d.allowed!==p.allowed&&I(e,{kind:p.allowed?"deny-disabled":"deny-enabled",path:`${b}.allowed`,classification:p.allowed?"weakening":"strengthening",message:p.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:d.allowed,after:p.allowed});let A=d.peerIsolation===!0,h=p.peerIsolation===!0;if(A!==h){let o=d.from===d.to&&p.from===p.to;I(e,{kind:h?"peer-isolation-enabled":"peer-isolation-disabled",path:`${b}.peerIsolation`,classification:o?h?"strengthening":"weakening":"judgment-required",message:o?h?"Cross-slice dependencies inside this layer are now denied.":"Cross-slice dependencies inside this layer are no longer denied.":"Changing peer isolation on a cross-layer edge changes the denial scope.",before:A,after:h})}T(d.sliceFolders).join("\0")!==T(p.sliceFolders).join("\0")&&I(e,{kind:"slice-folders-changed",path:`${b}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:T(d.sliceFolders),after:T(p.sliceFolders)})}}function Kn(e,t,n){let r=t.safety??{},s=n.safety??{};for(let a of["maxTsSuppressions","maxAnyCasts"]){let i=r[a]??0,d=s[a]??0;i!==d&&I(e,{kind:d>i?"threshold-raised":"threshold-lowered",path:`$.safety.${a}`,classification:d>i?"weakening":"strengthening",message:d>i?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:i,after:d})}for(let a of["allowInMemory","allowDisabledPeerIsolation"])Oe(e,`$.safety.${a}`,r[a]===!0,s[a]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}function Yn(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 jt(e,t){return`${e}::${t}`}function Vt(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(jt(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(jt(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}function Wn(e,t,n,r,s,a){let i=new Map((a??[]).map(o=>[o.invariantId,o])),d=t.arkRules??{},p=n.arkRules??{},b=[...new Set([...Object.keys(d),...Object.keys(p)])].sort();for(let o of b){let l=d[o],c=p[o],f=`$.arkRules[${o}]`;if(l===void 0&&c!==void 0){I(e,{kind:"arkrules-ref-added",path:f,classification:"strengthening",message:`ArkRules reference for layer ${o} was added.`,after:c});continue}if(l!==void 0&&c===void 0){I(e,{kind:"arkrules-ref-removed",path:f,classification:"weakening",message:`ArkRules reference for layer ${o} was removed.`,before:l});continue}l!==c&&I(e,{kind:"arkrules-ref-path-changed",path:f,classification:"judgment-required",message:`ArkRules file path for layer ${o} changed; verify the effective rules still match intent.`,before:l,after:c})}let A=Vt(r),h=Vt(s);for(let o of[...new Set([...A.structure.keys(),...h.structure.keys()])].sort()){let l=A.structure.get(o),c=h.structure.get(o),f=`$.arkRules.structure[${o}]`;if(!l&&c){I(e,{kind:"arkrule-structure-added",path:f,classification:"strengthening",message:`Structure ArkRule ${c.id} was added (${c.mode}).`,after:c});continue}if(l&&!c){I(e,{kind:"arkrule-structure-removed",path:f,classification:"weakening",message:`Structure ArkRule ${l.id} was removed.`,before:l});continue}if(!(!l||!c)){if(l.mode!==c.mode){let y=l.mode==="advisory"&&c.mode==="enforced";I(e,{kind:y?"arkrule-promoted":"arkrule-demoted",path:`${f}.mode`,classification:y?"strengthening":"weakening",message:y?`Structure ArkRule ${c.id} was promoted to enforced.`:`Structure ArkRule ${c.id} was demoted to advisory.`,before:l.mode,after:c.mode})}l.sensor!==c.sensor&&I(e,{kind:"arkrule-sensor-changed",path:`${f}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${c.id} changed sensor identity.`,before:l.sensor,after:c.sensor})}}for(let o of[...new Set([...A.invariants.keys(),...h.invariants.keys()])].sort()){let l=A.invariants.get(o),c=h.invariants.get(o),f=`$.arkRules.invariants[${o}]`;if(!l&&c){I(e,{kind:"arkrule-invariant-added",path:f,classification:"strengthening",message:`Invariant ${c.id} was added (${c.mode}).`,after:c});continue}if(l&&!c){I(e,{kind:"arkrule-invariant-removed",path:f,classification:"weakening",message:`Invariant ${l.id} was removed.`,before:l});continue}if(!(!l||!c)&&l.mode!==c.mode)if(l.mode==="advisory"&&c.mode==="enforced"){let R=i?.get(c.id),u=$t(R);u.ok?I(e,{kind:"arkrule-invariant-promoted",path:`${f}.mode`,classification:"strengthening",message:`Invariant ${c.id} was promoted to enforced (coverage evidence present).`,before:l.mode,after:c.mode}):I(e,{kind:"arkrule-invariant-promote-refused",path:`${f}.mode`,classification:"judgment-required",message:`Invariant ${c.id} cannot be promoted to enforced: ${u.reason}`,before:l.mode,after:c.mode})}else I(e,{kind:"arkrule-invariant-demoted",path:`${f}.mode`,classification:"weakening",message:`Invariant ${c.id} was demoted to advisory.`,before:l.mode,after:c.mode})}}function Gt(e,t,n){let r=[];X(r,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),X(r,"$.exclude",e.exclude,t.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional project paths are excluded from governance.",removedMessage:"Fewer project paths are excluded from governance."}),X(r,"$.dynamicImportAllowlist",e.dynamicImportAllowlist,t.dynamicImportAllowlist,{added:"weakening",removed:"strengthening",addedMessage:"Additional files may use non-literal dynamic imports.",removedMessage:"Fewer files may use non-literal dynamic imports."}),Oe(r,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let s={off:0,soft:1,"framework-soft":1,strict:2},a=e.cyclePolicy??"strict",i=t.cyclePolicy??"strict";if(a!==i){let d=s[i]===s[a]?"judgment-required":s[i]>s[a]?"strengthening":"weakening";I(r,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:d,message:"The cycle enforcement level changed.",before:a,after:i})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&I(r,{kind:"framework-overlay-changed",path:"$.frameworkOverlay",classification:"judgment-required",message:"The framework overlay changed and may alter effective layer matching.",before:e.frameworkOverlay??null,after:t.frameworkOverlay??null}),zn(r,e.layers,t.layers),Bn(r,e.rules,t.rules),Kn(r,e,t),Wn(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),r.sort((d,p)=>d.path.localeCompare(p.path)||d.id.localeCompare(p.id)),{schemaVersion:Ut,classification:Yn(r),findings:r}}function qt(e,t){if(!e||e.schemaVersion!==Ut||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(s=>typeof s!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=T(e.findingIds),r=T(t.findingIds);return n.length===r.length&&n.every((s,a)=>s===r[a])}function Q(e){let t=[];for(let n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."&&t.length>0&&t.at(-1)!==".."?t.pop():t.push(n));return t.join("/")}function zt(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}function Fe(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}function P(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}function Re(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let r=t,s="";for(t+=1;t<e.length;t+=1){let a=e[t];if(a===n)return{value:s,offset:r,excerpt:e.slice(r,t+1)};a==="\\"&&t+1<e.length?(s+=e[t+1],t+=1):s+=a}}function _(e,t,n){return e.startsWith(t,n)&&!Fe(e[n-1])&&!Fe(e[n+t.length])}function Bt(e,t){let n=P(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=P(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!_(e,"type",n))return!1;let s=P(e,n+4);if(s>=e.length||e[s]===","||e[s]==="}"||_(e,"as",s)||!zt(e[s]))return!1;for(n=s;n<e.length&&Fe(e[n]);)n+=1;if(n=P(e,n),_(e,"as",n)){if(n=P(e,n+2),!zt(e[n]))return!1;for(;n<e.length&&Fe(e[n]);)n+=1}r=!0}return!1}function Jn(e,t){if(t=P(e,t+6),e[t]==="(")return Re(e,P(e,t+1));let n=!1;if(_(e,"type",t)){let s=P(e,t+4);e[s]!==","&&!_(e,"from",s)&&(n=!0)}else Bt(e,t)&&(n=!0);let r=Kt(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}function Zn(e,t){t=t+6;let n=P(e,t),r=!1;if(_(e,"type",n)){let a=P(e,n+4);(e[a]==="{"||e[a]==="*")&&(r=!0)}else Bt(e,n)&&(r=!0);let s=Kt(e,t,!1);return s&&r?{...s,typeOnly:!0}:s}function Kt(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(_(e,"from",t))return Re(e,P(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return Re(e,t);if(t>0&&(_(e,"import",t)||_(e,"export",t)))return}}function Xn(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 Qn(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=P(e,t+7);if(e[r]!=="(")return;r=P(e,r+1);let s=Re(e,r);return s?{...s,requireCall:!0}:void 0}function er(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="/"&&e[n+1]==="/"){if(n=e.indexOf(`
8
8
  `,n+2),n<0)break;continue}if(r==="/"&&e[n+1]==="*"){let a=e.indexOf("*/",n+2);if(a<0)break;n=a+1;continue}if(r==="`"){n=Xn(e,n);continue}if(r==="'"||r==='"'){let a=Re(e,n);a&&(n=a.offset+a.excerpt.length-1);continue}let s=r==="i"&&_(e,"import",n)?Jn(e,n):r==="e"&&_(e,"export",n)?Zn(e,n):r==="r"&&_(e,"require",n)?Qn(e,n):void 0;s&&(t.push(s),n=s.offset+s.excerpt.length-1)}return t}function Yt(e,t){let n=[],r=[];for(let s of er(e.content)){let a=s.value;if(!a.startsWith(".")){if(s.typeOnly)continue;let b=pe(a);if(!b)continue;let A=e.content.slice(0,s.offset).split(`
9
9
  `).length;r.push({file:e.path,symbol:a,capability:b,evidence:{kind:"import",file:e.path,line:A,excerpt:s.excerpt}});continue}let i=e.content.slice(0,s.offset).split(`
10
10
  `).length,d={kind:"import",file:e.path,line:i,excerpt:s.excerpt},p=tr(e.path,a,t);n.push({from:e.path,specifier:a,to:p?.path??null,resolution:p?"resolved":"unresolved",fromLayer:e.layer,toLayer:p?.layer??null,evidence:d})}return{edges:n,capabilityUses:r}}function tr(e,t,n){let r=e.split("/");r.pop();for(let a of t.split("/"))a==="."||a===""||(a===".."?r.pop():r.push(a));let s=r.join("/");for(let a of[s,`${s}.ts`,`${s}.tsx`,`${s}.mts`,`${s}.cts`,`${s}/index.ts`,`${s}/index.tsx`]){let i=n.get(a);if(i)return i}}function Wt(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let s=ae(t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});s&&n.push({ruleId:`layer-dependency:${s.from}->${s.to}`,message:s.message??`${s.from} must not depend on ${s.to}.`,edge:r,evidence:r.evidence})}return n}var nr={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 rr(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}function sr(e,t){return rr(e,t)?E(S(Dt({config:e,arkRules:t,warnings:[]}))):E(S(e))}function at(e,t,n){let r=typeof e=="string"?Ht(e,t):st(e,t),s=n?.arkRules??me();return{...r,arkRules:s,policyHash:sr(r.config,s)}}function ar(e){let t=at(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=at(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=Gt(t.config,n.config,{baseArkRules:t.arkRules,candidateArkRules:n.arkRules,candidateInvariantCoverage:e.candidateInvariantCoverage}),s=r.findings.filter(d=>d.classification==="weakening"||d.classification==="judgment-required").map(d=>d.id).sort(),a=s.length>0,i=a&&qt(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:s});return{schemaVersion:r.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:r.classification,findings:r.findings,blockingFindingIds:s,requiresAcknowledgement:a,acknowledged:i,valid:!a||i}}function Te(e){let t=e.files.map(h=>{let o=Q(h.path);return{path:o,content:h.content,contentHash:E(h.content),layer:V(o,e.contract.config.layers)??null}}).sort((h,o)=>h.path.localeCompare(o.path)),n=new Map(t.map(h=>[h.path,h])),r=[],s=[];for(let h of t){let o=Yt(h,n);r.push(...o.edges),s.push(...o.capabilityUses)}let a=Wt(r,e.contract.config),i=new Map(e.contract.config.layers.map(h=>[h.name,h])),d=new Map(e.contract.config.layers.map(h=>[h.name,new Set(se(h))]));for(let h of s){let o=n.get(h.file)?.layer;if(!o)continue;let l=i.get(o),c=fe(h.symbol,l?.forbiddenGlobals??[]);if(c){a.push({ruleId:"FORBIDDEN_GLOBAL",message:`${o} must not use module "${h.symbol}" because it is the import form of forbidden global "${c}".`,symbol:h.symbol,evidence:h.evidence});continue}d.get(o)?.has(h.capability)&&a.push({ruleId:"CAPABILITY_VIOLATION",message:`${o} denies the ${h.capability} capability; found import of "${h.symbol}".`,capability:h.capability,symbol:h.symbol,evidence:h.evidence})}let p=t.length===0?"complete":"partial",b=p==="complete"?[]:[{...nr}],A={schemaVersion:mt,policyHash:e.contract.policyHash,compilerOptionsHash:E(S(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(h=>h.name),edges:r,capabilityUses:s,violations:a};return{mode:"lexical-compatibility",completeness:p,completenessReasons:b,valid:p==="complete"&&a.length===0,ir:A}}function it(e){let t=new Map(e.files.map(n=>[Q(n.path),n]));for(let n of e.changes){let r=Q(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return Te({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}function ir(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 _e(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, test at the public interface, then preflight again.":`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, test at the public interface, then preflight again.`;case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, test at the public interface, 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, test at the public interface, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, test at the public interface, 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 Jt(e){return E(S(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}function or(e){let t=Te(e),n=new Map(t.ir.files.map(c=>[c.path,c])),r=[],s=new Set,a=[];for(let c of e.changes){let f=c.path.replace(/\\/g,"/"),y=Q(c.path);if(!y||y===".."||y.startsWith("../")||f.startsWith("/")||/^[A-Za-z]:\//.test(f)||f.includes("\0")){a.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(s.has(y)){a.push({ruleId:"DUPLICATE_CHANGE_PATH",file:y,line:1,message:`The atomic change set contains more than one operation for ${y}.`});continue}s.add(y),"delete"in c&&c.delete&&!n.has(y)&&a.push({ruleId:"DELETE_TARGET_MISSING",file:y,line:1,message:`Cannot delete ${y} because it is not present in the supplied base tree.`}),r.push("delete"in c&&c.delete?{path:y,delete:!0}:{path:y,content:"content"in c?c.content:""})}e.changes.length===0&&a.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let i=it({...e,changes:r}),d=new Map(i.ir.files.map(c=>[c.path,c])),p=i.ir.violations.filter(c=>c.ruleId==="CAPABILITY_VIOLATION"||c.ruleId==="FORBIDDEN_GLOBAL").map(c=>{let f=d.get(c.evidence.file)?.layer;return{ruleId:c.ruleId,file:c.evidence.file,line:c.evidence.line,target:c.symbol,...c.capability?{capability:c.capability}:{},...f?{fromLayer:f}:{},edgeKind:"import",message:c.message}}),b=ge({config:e.contract.config,rules:e.contract.config.rules,files:i.ir.files.map(c=>c.path),contentViolations:p,edges:i.ir.edges.filter(c=>!!c.fromLayer).map(c=>({from:c.from,fromLayer:c.fromLayer,...c.to?{to:c.to}:{},...c.toLayer?{toLayer:c.toLayer}:{},line:c.evidence.line,kind:"import",...c.typeOnly?{typeOnly:!0}:{},...c.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),A=r.map(c=>{let f=Q(c.path),y=n.get(f),R=d.get(f);return{path:f,operation:"delete"in c&&c.delete?"delete":y?"update":"create",...y?{beforeContentHash:y.contentHash}:{},...R?{candidateContentHash:R.contentHash}:{}}}).sort((c,f)=>c.path.localeCompare(f.path)),h=[...a,...b.violations].map(c=>({...c,nextAction:_e(c)})),o=h.filter(c=>c.failsStrict!==!1),l=e.changeMap?be({changeMap:e.changeMap,changes:A,baseDependencies:t.ir.edges.flatMap(c=>c.to?[{from:c.from,to:c.to}]:[]),candidateDependencies:i.ir.edges.flatMap(c=>c.to?[{from:c.from,to:c.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&i.valid&&o.length===0&&(l?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:i.ir.compilerOptionsHash,baseTreeHash:Jt(t.ir.files),candidateTreeHash:Jt(i.ir.files),baseCompleteness:t.completeness,candidateCompleteness:i.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:i.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...l?{convergence:l}:{},changes:A,violations:h,warnings:b.warnings}}function lr(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let s of t.split("/"))if(!(!s||s==="."))if(s===".."){if(n.length===0)return;n.pop()}else n.push(s);let r=n.join("/");return r&&r===t?r:void 0}function cr(e,t){return[["resolverIdentity",e.resolverIdentity,t.resolverIdentity],["compilerIdentity",e.compilerIdentity,t.compilerIdentity],["evidenceRequirementsHash",e.evidenceRequirementsHash,t.evidenceRequirementsHash],["projectPackageName",e.projectPackageName??"",t.projectPackageName??""]].filter(([,r,s])=>r!==s).map(([r,s,a])=>({ruleId:"FACTS_IDENTITY_MISMATCH",file:"<change-set>",line:1,field:r,before:s,candidate:a,message:`Base and candidate facts must use the same ${r}.`}))}function dr(e,t,n,r){let s=n.get(t),a=r.get(t);return{path:t,operation:"delete"in e&&e.delete?"delete":s?"update":"create",...s?{beforeContentHash:s.contentHash}:{},...a?{candidateContentHash:a.contentHash}:{}}}function pr(e){let t=W(e.baseFacts),n=W(e.candidateFacts),r=$e({contract:e.contract,facts:t}),s=$e({contract:e.contract,facts:n}),a=new Map(t.files.map(l=>[l.path,l])),i=new Map(n.files.map(l=>[l.path,l])),d=cr(t,n),p=new Map,b=[];for(let l of e.changes){let c=lr(l.path);if(!c){d.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(p.has(c)){d.push({ruleId:"DUPLICATE_CHANGE_PATH",file:c,line:1,message:`The atomic change set contains more than one operation for ${c}.`});continue}p.set(c,l);let f=a.get(c),y=i.get(c);if("delete"in l&&l.delete)f||d.push({ruleId:"DELETE_TARGET_MISSING",file:c,line:1,message:`Cannot delete ${c} because it is not present in the supplied base facts.`}),y&&d.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:c,line:1,message:`Candidate facts still contain deleted file ${c}.`});else{let R="content"in l?l.content:"",u=E(R);y?y.contentHash!==u&&d.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:c,line:1,expectedContentHash:u,candidateContentHash:y.contentHash,message:`Candidate facts for ${c} do not match the declared content.`}):d.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:c,line:1,message:`Candidate facts do not contain changed file ${c}.`})}b.push(dr(l,c,a,i))}e.changes.length===0&&d.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});for(let l of new Set([...a.keys(),...i.keys()])){if(p.has(l))continue;let c=a.get(l),f=i.get(l);c&&f&&S(c)===S(f)||d.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:l,line:1,message:`Candidate facts change ${l}, but the atomic change set does not declare it.`})}let A=e.changeMap?be({changeMap:e.changeMap,changes:b,baseDependencies:r.ir.edges.flatMap(l=>l.to?[{from:l.from,to:l.to}]:[]),candidateDependencies:s.ir.edges.flatMap(l=>l.to?[{from:l.from,to:l.to}]:[])}):void 0,h=[...d,...s.ir.violations].map(l=>({...l,nextAction:_e(l)})),o=h.filter(l=>l.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&s.strictValid&&o.length===0&&(A?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,resolverIdentity:n.resolverIdentity,compilerIdentity:n.compilerIdentity,compilerOptionsHash:n.compilerOptionsHash,tsconfigHash:n.tsconfigHash,baseCompilerOptionsHash:t.compilerOptionsHash,candidateCompilerOptionsHash:n.compilerOptionsHash,baseTsconfigHash:t.tsconfigHash,candidateTsconfigHash:n.tsconfigHash,evidenceRequirementsHash:n.evidenceRequirementsHash,baseFactsHash:t.factsHash,candidateFactsHash:n.factsHash,baseTreeHash:t.candidateTreeHash,candidateTreeHash:n.candidateTreeHash,baseCompleteness:r.completeness,candidateCompleteness:s.completeness,baseCompletenessReasons:r.completenessReasons,candidateCompletenessReasons:s.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...A?{convergence:A}:{},changes:b.sort((l,c)=>l.path<c.path?-1:l.path>c.path?1:0),violations:h,warnings:s.ir.warnings}}var Zt=new WeakSet;function Xt(e){if(!e||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Object.values(e))Xt(t);return Object.freeze(e)}function Ys(e){let t=Xt(Ie(e));return Zt.add(t),t}function Ws(e){if(!Zt.has(e.facts))throw new Error("Trusted resolved analysis requires immutable in-process canonical facts.");return Ye(e)}export{De as AMBIENT_CAPABILITY_ENTRIES,Me as CAPABILITY_IDS,Ge as DEFAULT_INTENT_PREFIXES,ut as RESOLVED_CANDIDATE_FACTS_SCHEMA,ee as RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,Ue as SOURCE_POLICY_MESSAGES,je as ambientCoveredByForbiddenGlobals,be as analyzeArchitectureConvergence,it as analyzeChange,ar as analyzePolicyDelta,Te as analyzeProject,$e as analyzeResolvedProject,Ws as analyzeTrustedResolvedProject,ue as capabilityForAmbientName,pe as capabilityForModuleSpecifier,ze as classifyPublishFacts,Ke as collectAnalysisConfigWarnings,Hn as collectCapabilityUses,tt as collectForbiddenCapabilityUses,Ie as createResolvedCandidateFacts,Ys as createTrustedResolvedCandidateFacts,wt as detectArchitectureCycles,E as deterministicHash,se as effectiveCapabilityDeny,ge as evaluateArchitectureGraph,ir as explainViolation,et as extractSemanticDependencies,fe as forbiddenGlobalForModuleSpecifier,Ln as loadArchitectureChangeMap,at as loadContract,W as loadResolvedCandidateFacts,bt as looksLikeArkIntent,an as lowerForbiddenGlobal,Se as loweredLayerCoverage,or as preflightChange,pr as preflightResolvedChange,qe as resolveIntentLayer,ve as resolvedFactsEvidenceRequirementsHash,S as stableSerialize};
@@ -302,7 +302,7 @@ export function agentInstructions(root) {
302
302
 
303
303
  ${placementTable}
304
304
 
305
- When creating a NEW kind of code that no existing layer covers, add a layer to \`ark.config.json\` first (via \`/ark-contract\`), then place the file.`
305
+ When creating a NEW kind of code that no existing layer covers, add a layer to \`ark.config.json\` first (via \`/ark-adopt\`), then place the file.`
306
306
  : `\`ark.config.json\` is authoritative for this project. When creating a NEW kind of code
307
307
  that no existing layer covers (a saga, a background job, a read model, ...), use the
308
308
  default 11-layer placement below and add the layer to \`ark.config.json\` — do not invent
@@ -316,8 +316,8 @@ ${projectionBlock}
316
316
 
317
317
  1. Status anytime: \`${doctorCmd}\` — **control plane** (one status light, one next action; not a mode picker).
318
318
  2. If \`ark.config.json\` is missing: run \`${startCmd}\` once (preview), then \`${startCmd} --apply\`.
319
- 3. Guided end-to-end work (“make architecture sound”): **\`/ark-autopilot\`** — explore → dual plan A (edges) + B (shape) → mechanical-safe fixes; B only with user OK. Day-zero origin is frozen by \`ark start\`/\`ark init\` (or autopilot if missing) **before** agent docs.
320
- 4. After ordinary feature edits: run \`${checkCmd}\`. On violations → **\`/ark-fix\`** (or \`/ark-place\` for new files, \`/ark-contract\` only if the contract itself is wrong).
319
+ 3. Guided end-to-end work (“make architecture sound”): **\`/ark-autopilot\`** — explore → dual plan A (edges) + B (shape) → write mechanical-safe and judgment; one Shape refactor. Day-zero origin is frozen by \`ark start\`/\`ark init\` (or adopt if missing) **before** agent docs.
320
+ 4. After ordinary feature edits: run \`${checkCmd}\` (teams: \`ark-check --changed --base origin/dev\`). On violations → **\`/ark-autopilot\`** (or \`/ark-place\` for new files). **Do not edit** \`ark.config.json\` / \`.ark-baseline.json\` in a product PR — that is a steward \`--contract-session\`. If doctor shows **Stewards (advisory)**, ask who owns the law — do not invent \`stewards[]\`. Leftover names \`/ark-fix\` / \`/ark-loop\` / \`/ark-contract\` are shortcuts to those doors.
321
321
 
322
322
  Do **not** skill-shop the full table for routine work. When unsure, do doctor top action #1 only
323
323
  (re-run doctor after). Do **not** jump to \`/ark-autopilot\` unless #1 or a STOP handoff names it.
@@ -343,14 +343,14 @@ Pick **one** primary skill. Prefer doctor top action #1 when unsure.
343
343
  |------|--------|----------|
344
344
  | Unsure what to do next | **Doctor top action #1** (\`${doctorCmd}\`), then re-run doctor | skill-shopping, defaulting to autopilot |
345
345
  | Make architecture sound (guided apply path) | **/ark-autopilot** | explore-only, coverage-only |
346
- | **Messy / leftover design work after green** | **Single path:** \`/ark-explore\` shape-focus → plan B, then \`/ark-autopilot\` only to apply B with OK | coverage, think, loop-as-done, skill-shopping |
346
+ | **Messy / leftover design work after green** | **Single path:** \`/ark-explore\` shape-focus → plan B, then \`/ark-autopilot\` applies one pilot | coverage, think, loop-as-done, skill-shopping |
347
347
  | Map / residual / dual-plan seed only (no apply, already know you want recon) | \`/ark-explore\` | coverage (fitness only) |
348
- | Greenfield shape / empty tree | \`/ark-architect\` | adopt |
349
- | Brownfield / wrong contract / false-green | \`/ark-adopt\` then \`/ark-contract\` if globs wrong | architect |
350
- | Edit \`ark.config.json\` layers/rules/intents | \`/ark-contract\` | fix/loop for config |
351
- | New file “where does this go?” | \`/ark-place\` | architect (unless greenfield shape missing) |
352
- | Gate violation on a change (small cluster) | \`/ark-fix\` | loop/autopilot unless bulk |
353
- | Drive plan **A** to goal.met | \`/ark-loop\` | explore (unless A empty + design residual → single Shape path above) |
348
+ | Greenfield shape / empty tree | \`/ark-adopt\` | leftover \`/ark-architect\` |
349
+ | Brownfield / wrong config / false-green | \`/ark-adopt\` | leftover architect |
350
+ | Edit \`ark.config.json\` layers/rules/intents | \`/ark-adopt\` (session 0) or \`/ark-autopilot\` | leftover \`/ark-contract\` |
351
+ | New file “where does this go?” | \`/ark-place\` | adopt if the path is missing |
352
+ | Gate violation on a change (small cluster) | \`/ark-autopilot\` | leftover \`/ark-fix\` |
353
+ | Drive plan **A** to goal.met | \`/ark-autopilot\` | leftover \`/ark-loop\` |
354
354
  | Ark **fitness** only (governed%, gates, baseline, install gaps) | \`/ark-coverage\` | leftover design work (use single path above) |
355
355
  | One design decision, 2–3 options | \`/ark-think\` | full Shape residual (use single path) |
356
356
  | Explain / HTML report tour | \`/ark-explain\` | explore |
@@ -412,7 +412,7 @@ ${projectionBlock}
412
412
 
413
413
  **Single door when residual remains:**
414
414
  - **Edges debt** (import/capability violations) → fix with the gate / plan; skill pack only if doctor names a skill.
415
- - **Design leftover / residual shape lenses** (compass leftover while imports may look green) → map first, then guided apply with user OK — never “you’re done” on green imports alone.
415
+ - **Design leftover / residual shape lenses** (compass leftover while imports may look green) → \`/ark-explore\` then \`/ark-autopilot\` (one refactor) — never “you’re done” on green imports alone.
416
416
  - Empty plan A + leftover design work → **not finished**.
417
417
 
418
418
  **Two-axis done (never collapse):**
@@ -112,6 +112,8 @@ export const ARK_CONFIG_SCHEMA = {
112
112
  additionalProperties: { type: 'string', minLength: 1 },
113
113
  default: {},
114
114
  },
115
+ /** Team parliament — GitHub handles or emails who may loosen the law (not part of policy hash). */
116
+ stewards: { ...stringArraySchema, default: [] },
115
117
  },
116
118
  $defs: {
117
119
  layer: {
@@ -403,15 +403,15 @@ function messageFor(id, entries) {
403
403
  function fixFor(id) {
404
404
  switch (id) {
405
405
  case 'contract-bidirectional-allow':
406
- return `Keep one direction (edit via /ark-contract), or record the deliberate loop in ${CONTRACT_SMELL_ACKS_PATH} with a reason.`;
406
+ return `Keep one direction (edit via /ark-adopt), or record the deliberate loop in ${CONTRACT_SMELL_ACKS_PATH} with a reason.`;
407
407
  case 'contract-peripheral-depends-core':
408
- return `Invert the edge: core emits events/ports the peripheral layer consumes (/ark-contract), or acknowledge with a reason in ${CONTRACT_SMELL_ACKS_PATH}.`;
408
+ return `Invert the edge: core emits events/ports the peripheral layer consumes (/ark-adopt), or acknowledge with a reason in ${CONTRACT_SMELL_ACKS_PATH}.`;
409
409
  case 'contract-lateral-adapter-allow':
410
- return `Move shared shapes into Domain/shared kernel and drop the lateral allow (/ark-contract), or acknowledge with a reason in ${CONTRACT_SMELL_ACKS_PATH}.`;
410
+ return `Move shared shapes into Domain/shared kernel and drop the lateral allow (/ark-adopt), or acknowledge with a reason in ${CONTRACT_SMELL_ACKS_PATH}.`;
411
411
  case 'contract-dead-rule':
412
- return 'Fix the layer patterns so the layer matches real files, or delete the stale/self rule via /ark-contract.';
412
+ return 'Fix the layer patterns so the layer matches real files, or delete the stale/self rule via /ark-adopt.';
413
413
  default:
414
- return 'Review the contract edge via /ark-contract; never weaken the gate to silence a smell.';
414
+ return 'Review the contract edge via /ark-adopt; never weaken the gate to silence a smell.';
415
415
  }
416
416
  }
417
417
 
@@ -285,7 +285,7 @@ export function detectDesignSmells(root, config, files = [], coverage = null) {
285
285
  severity: 'warn',
286
286
  message: `Layers classify files but have no deny/allow rule edges: ${withoutRules.join(', ')}. Soft green — peer leaks may go unchecked.`,
287
287
  evidence: withoutRules.map((n) => `layer:${n}`),
288
- fix: 'Add rules via /ark-contract (or a policy pack) so every populated layer participates in enforcement.',
288
+ fix: 'Add rules via /ark-adopt (or a policy pack) so every populated layer participates in enforcement.',
289
289
  })
290
290
  );
291
291
  }