arkgate 4.8.20 → 4.8.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/CHANGELOG.md +124 -5
  2. package/README.md +107 -117
  3. package/bin/ark-check-runtime.mjs +3 -4
  4. package/bin/ark-layer-match.mjs +110 -18
  5. package/bin/lib/analysis-engine.mjs +13 -6
  6. package/bin/lib/config-contract.mjs +5 -0
  7. package/bin/lib/diagnostic-catalog.mjs +1 -0
  8. package/bin/lib/doctor-advisories.mjs +20 -0
  9. package/bin/lib/doctor-human.mjs +11 -9
  10. package/bin/lib/doctor-plan.mjs +15 -14
  11. package/bin/lib/first-run-help.mjs +7 -1
  12. package/bin/lib/html-report-advisories.mjs +8 -0
  13. package/bin/lib/html-report-depth.mjs +9 -8
  14. package/bin/lib/invariant-coverage.mjs +396 -75
  15. package/bin/lib/managed-upgrade.mjs +59 -14
  16. package/bin/lib/pilot-loop.mjs +183 -37
  17. package/bin/lib/upgrade-behavior-changes.mjs +83 -0
  18. package/bin/lib/upgrade-command.mjs +69 -31
  19. package/bin/lib/upgrade-outcome.mjs +359 -0
  20. package/bin/lib/violations.mjs +109 -0
  21. package/dist/{configTypes-VVknqcTJ.d.ts → configTypes-CTELo87-.d.ts} +7 -0
  22. package/dist/{diagnosticCatalog-BPYWNyJR.d.ts → diagnosticCatalog-B7BXlet6.d.ts} +73 -5
  23. package/dist/eslint/index.cjs +4 -4
  24. package/dist/eslint/index.d.ts +26 -3
  25. package/dist/eslint/index.js +4 -4
  26. package/dist/index.cjs +24 -17
  27. package/dist/index.d.ts +9 -4
  28. package/dist/index.js +25 -18
  29. package/dist/nestjs/index.cjs +9 -9
  30. package/dist/nestjs/index.d.ts +3 -3
  31. package/dist/nestjs/index.js +9 -9
  32. package/dist/runtime/index.cjs +18 -11
  33. package/dist/runtime/index.d.ts +6 -6
  34. package/dist/runtime/index.js +18 -11
  35. package/dist/{types-p_fCp6P-.d.ts → types-fQ9-KrBj.d.ts} +1 -1
  36. package/dist/{types-Cs-46DRu.d.ts → types-yDNEQ603.d.ts} +1 -1
  37. package/docs/README.md +4 -3
  38. package/docs/agent-guide.md +15 -7
  39. package/docs/brownfield-adoption.md +4 -3
  40. package/docs/configuration.md +34 -11
  41. package/docs/diagnostics.md +12 -2
  42. package/docs/package-surface.md +3 -2
  43. package/docs/product-voice.md +11 -3
  44. package/package.json +1 -1
  45. package/schemas/ark.config.schema.json +8 -0
  46. package/server.json +2 -2
  47. package/templates/agent-skills/README.md +1 -1
  48. package/templates/agent-skills/ark-adopt/SKILL.md +5 -2
  49. package/templates/agent-skills/ark-architect/SKILL.md +2 -0
  50. package/templates/agent-skills/ark-autopilot/SKILL.md +6 -4
  51. package/templates/agent-skills/ark-contract/SKILL.md +2 -0
  52. package/templates/agent-skills/ark-coverage/SKILL.md +2 -0
  53. package/templates/agent-skills/ark-explain/SKILL.md +2 -0
  54. package/templates/agent-skills/ark-explore/SKILL.md +4 -2
  55. package/templates/agent-skills/ark-fix/SKILL.md +2 -0
  56. package/templates/agent-skills/ark-loop/SKILL.md +2 -0
  57. package/templates/agent-skills/ark-order/SKILL.md +2 -0
  58. package/templates/agent-skills/ark-place/SKILL.md +2 -0
  59. package/templates/agent-skills/ark-runtime/SKILL.md +2 -0
  60. package/templates/agent-skills/ark-think/SKILL.md +2 -0
  61. package/templates/agent-skills/ark-upgrade/SKILL.md +20 -7
  62. package/templates/skills/ark-adopt.md +5 -2
  63. package/templates/skills/ark-architect.md +2 -0
  64. package/templates/skills/ark-autopilot.md +6 -4
  65. package/templates/skills/ark-contract.md +2 -0
  66. package/templates/skills/ark-coverage.md +2 -0
  67. package/templates/skills/ark-explain.md +2 -0
  68. package/templates/skills/ark-explore.md +4 -2
  69. package/templates/skills/ark-fix.md +2 -0
  70. package/templates/skills/ark-loop.md +2 -0
  71. package/templates/skills/ark-order.md +2 -0
  72. package/templates/skills/ark-place.md +2 -0
  73. package/templates/skills/ark-runtime.md +2 -0
  74. package/templates/skills/ark-think.md +2 -0
  75. package/templates/skills/ark-upgrade.md +20 -7
@@ -1,5 +1,5 @@
1
- var Mt=Object.defineProperty;var l=(e,t)=>Mt(e,"name",{value:t,configurable:!0});import C from"fs";import m from"path";var Ne=new Map;function Ce(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}l(Ce,"escapeLiteral");function Z(e){let t="";for(let r=0;r<e.length;r+=1){let n=e[r];if(n==="\\"&&r+1<e.length){let s=e[r+1];if("*?{}[],".includes(s)||s==="\\"){t+="\\"+s,r+=1;continue}t+="/";continue}t+=n}return t}l(Z,"normalizeGlobSeparators");function $t(e){let t=0;for(let r=0;r<e.length;r+=1){let n=e[r];if(n==="\\"){r+=1;continue}if(n==="{")t+=1;else if(n==="}"&&(t-=1,t<0))return!1}return t===0}l($t,"bracesBalanced");function _(e){let t=Ne.get(e);if(t)return t;let r=Z(e),n=$t(r),s="",o=0;for(let a=0;a<r.length;a+=1){let c=r[a];c==="\\"&&a+1<r.length?(s+=Ce(r[a+1]),a+=1):c==="*"?r[a+1]==="*"?r[a+2]==="/"?(s+="(?:.*/)?",a+=2):(s+=".*",a+=1):s+="[^/]*":c==="?"?s+="[^/]":c==="{"&&n?(s+="(?:",o+=1):c==="}"&&n&&o>0?(s+=")",o-=1):c===","&&n&&o>0?s+="|":s+=Ce(c)}let i=new RegExp(`^${s}$`);return Ne.set(e,i),i}l(_,"globToRegExp");function Ut(e){return Z(String(e)).split("/").filter(Boolean).filter(r=>r!=="**"&&r!=="*"&&!r.includes("*")&&!r.includes("?")&&!r.includes("{")&&!r.includes("["))}l(Ut,"concreteGlobSegments");function De(e,t){let r=Z(String(e)),n=Ut(r),s=r.replace(/\*/g,"").length,o=n.length*1e4+s;if(t==null||t==="")return o;let i=String(t).split(/[/\\]/).filter(Boolean);if(n.length===0)return s;let a=0,c=-1;for(let f of n){let d=-1;for(let u=a;u<i.length;u+=1)if(i[u]===f){d=u;break}if(d<0)return o;c=d,a=d+1}return(c+1)*1e6+n.length*1e4+s}l(De,"patternSpecificity");function S(e,t){let r=String(e).split(/[/\\]/).join("/"),n,s=-1;for(let o of t??[])if(!(o.exclude??[]).some(i=>_(i).test(r))){for(let i of o.patterns??[])if(_(i).test(r)){let a=De(i,r);a>s&&(s=a,n=o.name)}}return n}l(S,"layerForRelativePath");function Oe(e,t){if(!t?.length)return;let r=String(e).split(/[/\\]/).filter(Boolean);if(r.length===0)return;let n=new Set;for(let s of t)if(!(typeof s!="string"||s.length===0)){if(jt(s)){let o=Ht(r,s);if(o)return o;continue}!s.includes("/")&&!s.includes("\\")&&!s.includes("*")&&n.add(s.toLowerCase())}return Gt(r,n)}l(Oe,"sliceIdForPath");function jt(e){let t=e.split(/[/\\]/).filter(r=>r.length>0);return t.length<2||t[0]==="*"||t[0]==="**"?!1:t.some(r=>r==="*")}l(jt,"isAnchoredSliceEntry");function Ht(e,t){let r=t.split(/[/\\]/).filter(s=>s.length>0).map(s=>s.toLowerCase()),n=Pe(e,r[0]??"");for(let s of n){let o=Vt(e,r,s);if(o)return o}}l(Ht,"anchoredSliceId");function Vt(e,t,r){let n=[],s=r;for(let o=0;o<t.length;o+=1){let i=t[o];if(i==="*"){if(s>=e.length-1){for(let a=o;a<t.length;a+=1)if(t[a]!=="*")return;break}n.push(e[s].toLowerCase()),s+=1;continue}if(i==="**"||s>=e.length||e[s].toLowerCase()!==i)return;n.push(e[s].toLowerCase()),s+=1}return n.length>0?n.join("/"):void 0}l(Vt,"bindAnchoredSlice");function Gt(e,t){if(t.size!==0){for(let r=0;r<e.length-1;r+=1)if(t.has(e[r].toLowerCase())&&!(r+1>=e.length-1))return`${e[r].toLowerCase()}/${e[r+1].toLowerCase()}`}}l(Gt,"bareSliceId");function Bt(e){let t=new Set;for(let r of e??[]){let s=Z(String(r)).split("/").filter(Boolean);for(let o=0;o<s.length;o+=1){let i=s[o];if((i==="**"||i==="*")&&o>0){let a=s[o-1];a&&!a.includes("*")&&!a.includes("{")&&!a.includes("}")&&t.add(a)}}}return[...t]}l(Bt,"inferSliceFoldersFromPatterns");function Wt(e,t,r){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(s=>typeof s=="string"&&s.length>0);let n=(r??[]).find(s=>s.name===t);return Bt(n?.patterns)}l(Wt,"resolveSliceFolders");function ve(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}l(ve,"normalizeSegments");function Fe(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}l(Fe,"trimTrailingSlashes");var zt=["src","app"];function Pe(e,t){let r=(e[0]??"").toLowerCase(),n=t.toLowerCase();return zt.includes(r)&&n!==r?[0,1]:[0]}l(Pe,"anchorOffsets");function qt(e){let t=Fe(e.replace(/^[./]+/,""));return t==="*"||t==="**"}l(qt,"isBlanketRoot");function Te(e,t){if(!e||!t?.length)return!1;let r=String(e).split(/[/\\]/).join("/"),n=r.toLowerCase(),s=ve(r);for(let o of t){if(typeof o!="string"||o.length===0||qt(o))continue;if(o.includes("*")){let c=Fe(o.toLowerCase());if(_(c).test(n)||_(`${c}/**`).test(n))return!0;continue}let i=ve(o);if(i.length===0)continue;let a=Pe(s,i[0]??"");for(let c of a){if(c+i.length>s.length)continue;let f=!0;for(let d=0;d<i.length;d+=1)if(s[c+d]!==i[d]){f=!1;break}if(f)return!0}}return!1}l(Te,"pathUnderSharedRoot");function Le(e,t){let r=String(e).split(/[/\\]/).filter(Boolean).join("/").toLowerCase();if(!r)return!1;let n=t.toLowerCase();return r===n?!0:!r.includes("/")&&n.endsWith(`/${r}`)}l(Le,"sliceMatchesDeclaration");function Zt(e,t,r){return!e?.length||!t||!r?!1:e.some(n=>n&&typeof n.from=="string"&&typeof n.to=="string"&&Le(n.from,t)&&Le(n.to,r))}l(Zt,"crossSliceEdgeAllowed");function Yt(e){if(!e.fromPath)return{denied:!0,reason:"missing-path"};if(e.folderCount<=0)return{denied:!0,reason:"no-slice-folders"};let t=!!e.fromSlice||e.fromShared===!0;if(!e.toPath)return t?e.fromSlice?{denied:!0,reason:"missing-path"}:{denied:!1}:{denied:!0,reason:"unclassifiable-path"};let r=!!e.toSlice||e.toShared===!0;return!t||!r?{denied:!0,reason:"unclassifiable-path"}:e.sharedImportsSlice==="deny"&&e.fromShared===!0&&e.toSlice&&!e.fromSlice?{denied:!0,reason:"shared-imports-slice"}:!e.fromSlice||!e.toSlice?{denied:!1}:e.fromSlice===e.toSlice?{denied:!1}:e.crossSliceAllowed?{denied:!1}:{denied:!0,reason:"cross-slice"}}l(Yt,"peerIsolationDecision");function Ke(e,t){switch(e){case"cross-slice":return`cross-slice edge ${t.fromSlice??"?"} \u2192 ${t.toSlice??"?"}. Extract the shared code, use events/ports across slices, or declare the edge in the rule's allowedCrossSlice.`;case"shared-imports-slice":return`shared root imports slice ${t.toSlice??"?"} (${t.fromPath??"?"} \u2192 ${t.toPath??"?"}). The wall is direct-only.`;case"unclassifiable-path":{let r=[t.fromSlice?void 0:t.fromPath,t.toSlice?void 0:t.toPath].filter(s=>!!s);return`unclassifiable path${r.length>0?` (${r.join(", ")})`:""} \u2014 ArkGate cannot place it in a slice, so it cannot prove this is not a cross-slice edge. Move it into a slice, or declare its root in the rule's sharedRoots.`}case"no-slice-folders":return"no slice folders \u2014 peerIsolation is on but no slice folder resolves from the rule or the layer patterns. Set sliceFolders on the rule.";default:return"no path evidence for this edge \u2014 peerIsolation needs the importer and importee paths."}}l(Ke,"peerIsolationDenyExplanation");function Xt(e,t,r,n){return ae(e,t,r,n)?.rule}l(Xt,"findDeniedEdgeRule");function ae(e,t,r,n){for(let s of e??[])if(!(s.from!==t||s.to!==r)&&s.allowed===!1){if(s.peerIsolation){let o=n?.fromPath,i=n?.toPath,a=Wt(s,t,n?.layers),c=o?Oe(o,a):void 0,f=i?Oe(i,a):void 0,d=Yt({fromPath:o,toPath:i,folderCount:a.length,fromSlice:c,toSlice:f,fromShared:!c&&Te(o,s.sharedRoots),toShared:!f&&Te(i,s.sharedRoots),crossSliceAllowed:Zt(s.allowedCrossSlice,c,f),sharedImportsSlice:s.sharedImportsSlice});if(d.denied)return{rule:s,peerIsolationReason:d.reason,fromSlice:c,toSlice:f};continue}if(t!==r)return{rule:s}}}l(ae,"findDeniedEdgeDecision");function Jt(e,t,r,n){return Xt(e,t,r,n)!==void 0}l(Jt,"isEdgeDenied");var Qt=["**/*.gen.ts","**/*.gen.tsx","**/*.generated.ts","**/*.generated.tsx"];function er(e){let t=Array.isArray(e?.exclude)?e.exclude.filter(n=>typeof n=="string"):[];return[...e?.excludeGenerated===!1?[]:Qt,...t]}l(er,"scanExcludePatterns");function Me(e,t){let r=String(e).split(/[/\\]/).join("/");return er(t).some(n=>_(n).test(r))}l(Me,"isScanExcludedRelative");var $e=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),tr=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Jn=Object.freeze(Object.keys(tr).sort()),le=Object.freeze({fs:"filesystem","node:fs":"filesystem","fs/promises":"filesystem","node:fs/promises":"filesystem","fs-extra":"filesystem","graceful-fs":"filesystem",memfs:"filesystem",chokidar:"filesystem",http:"network",https:"network",http2:"network",net:"network",tls:"network",dgram:"network",dns:"network","node:http":"network","node:https":"network","node:http2":"network","node:net":"network","node:tls":"network","node:dgram":"network","node:dns":"network",axios:"network",undici:"network","node-fetch":"network",got:"network",ky:"network",superagent:"network",ws:"network",process:"process","node:process":"process",child_process:"process","node:child_process":"process","@prisma/client":"persistence",prisma:"persistence",pg:"persistence",mysql:"persistence",mysql2:"persistence",mongodb:"persistence",mongoose:"persistence",sqlite3:"persistence","better-sqlite3":"persistence",redis:"persistence",ioredis:"persistence",typeorm:"persistence",knex:"persistence","drizzle-orm":"persistence",sequelize:"persistence",kysely:"persistence","@supabase/supabase-js":"persistence"}),rr=Object.freeze({process:Object.freeze(["process","node:process"])});function Ue(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=le[e];if(t)return t;let r=e.indexOf("/");if(r<0)return null;let n=e.slice(0,r),s=le[n];if(s)return s;let o=e.indexOf("/",r+1);return o<0?null:le[e.slice(0,o)]??null}l(Ue,"capabilityForModuleSpecifier");function ce(e,t){for(let r of t)if(rr[r]?.includes(e))return r;return null}l(ce,"forbiddenGlobalForModuleSpecifier");function je(e){if(e?.pure===!0)return[...$e].sort();let r=(e?.capabilities?.deny??[]).filter(n=>$e.includes(n));return[...new Set(r)].sort()}l(je,"effectiveCapabilityDeny");var v={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},He={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...v,default:[]},kernelRoots:{...v},managedLayers:{...v,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},Ve={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...v,default:[]},managedLayers:{...v,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...v,default:[]},appliesTo:{...v,default:[]}}};function $(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}l($,"isObject");function Ge(e){let t=new Set;if(!Array.isArray(e.layers))return t;for(let r of e.layers)$(r)&&typeof r.name=="string"&&r.name.length>0&&t.add(r.name);return t}l(Ge,"declaredLayerNames");function Be(e){if(!$(e))return e;let t={mode:e.mode===void 0?"advisory":e.mode,compositionRoots:e.compositionRoots===void 0?[]:e.compositionRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,requireDeclarations:e.requireDeclarations===void 0?!0:e.requireDeclarations};return e.kernelRoots!==void 0&&(t.kernelRoots=e.kernelRoots),e.ignoreDirectNewForErrors!==void 0&&(t.ignoreDirectNewForErrors=e.ignoreDirectNewForErrors),{...e,...t}}l(Be,"defaultedArkRun");function We(e){if(!$(e))return e;let t=typeof e.maxXiKeys=="number"&&e.maxXiKeys>0?e.maxXiKeys:7;return{...e,mode:e.mode===void 0?"advisory":e.mode,planeRoots:e.planeRoots===void 0?[]:e.planeRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,maxXiKeys:t,xiKeys:e.xiKeys===void 0?[]:e.xiKeys}}l(We,"defaultedArkOrder");function ze(e,t){let r=e.arkRun;if(r===void 0||!$(r))return;let n=Ge(e),s=r.managedLayers;if(Array.isArray(s)&&s.forEach((o,i)=>{typeof o=="string"&&o.length>0&&!n.has(o)&&t.push({path:`$.arkRun.managedLayers[${i}]`,message:`layer ${JSON.stringify(o)} is not declared in layers[]`})}),r.mode==="enforced"){let o=r.kernelRoots??r.compositionRoots;(!Array.isArray(o)||o.length===0)&&t.push({path:r.kernelRoots!==void 0?"$.arkRun.kernelRoots":"$.arkRun.compositionRoots",message:"ARKRUN_MISSING_ROOT: enforced mode requires at least one kernel root"}),(!Array.isArray(s)||s.length===0)&&t.push({path:"$.arkRun.managedLayers",message:"enforced mode requires at least one managed layer"})}}l(ze,"validateArkRunExtra");function qe(e,t){let r=e.arkOrder;if(r===void 0||!$(r))return;let n=Ge(e),s=r.managedLayers;if(Array.isArray(s)&&s.forEach((o,i)=>{typeof o=="string"&&o.length>0&&!n.has(o)&&t.push({path:`$.arkOrder.managedLayers[${i}]`,message:`layer ${JSON.stringify(o)} is not declared in layers[]`})}),r.mode==="enforced"){let o=r.planeRoots;(!Array.isArray(o)||o.length===0)&&t.push({path:"$.arkOrder.planeRoots",message:"ARKORDER_MISSING_PLANE: enforced mode requires at least one plane root"}),(!Array.isArray(s)||s.length===0)&&t.push({path:"$.arkOrder.managedLayers",message:"enforced mode requires at least one managed layer"})}}l(qe,"validateArkOrderExtra");function Y(e){if(typeof e!="string")return null;let t=e.trim().replace(/^@/,"").toLowerCase();return t.length>0?t:null}l(Y,"normalizeStewardId");function Ze(e){let t=Y(e);return!t||de(t)||t.includes(" ")||t.includes("@")?!1:/^(?!-)[a-z0-9-]{1,39}(?<!-)$/.test(t)}l(Ze,"isGitHubHandle");function nr(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();return!t.includes("@")||t.includes(" ")||de(t)?!1:/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}l(nr,"isGitHubEmail");function sr(e){if(typeof e!="string")return null;let t=e.trim().match(/^(?:\d+\+)?([^@]+)@users\.noreply\.github\.com$/i);return t&&Ze(t[1])?Y(t[1]):null}l(sr,"githubHandleFromEmail");function Ye(e){let t=sr(e);if(t)return t;let r=Y(e);return!r||de(r)?null:Ze(r)||nr(r)?r:null}l(Ye,"canonicalStewardId");var or=/bot\b|\[bot\]|dependabot|renovate|github-actions|imgbot|codecov/i;function de(e){let t=Y(e);return!t||or.test(t)}l(de,"isAutomationAuthor");var I="1.3",ir=["public","auth","admin","internal"];var ue="https://unpkg.com/arkgate@4/schemas/ark.config.schema.json",Xe=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],ar=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function lr(){let e=[];for(let t of Xe)for(let r of Xe)t===r||ar.has(`${t}->${r}`)||e.push({from:t,to:r,allowed:!1});return e}l(lr,"createDefaultRules");var Qe=lr(),fe=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"},{from:"1.1",to:"1.2"},{from:"1.2",to:"1.3"}],E={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Je={$schema:"https://json-schema.org/draft/2020-12/schema",$id:ue,title:"ArkGate architecture contract",description:"Versioned contract consumed identically by ArkGate CLI, MCP, and ESLint surfaces.",type:"object",additionalProperties:!1,required:["$schema","schemaVersion","include","layers","rules"],properties:{$schema:{type:"string",minLength:1,default:ue,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:I,default:I},name:{type:"string",minLength:1},include:{...E,minItems:1,default:["src"]},exclude:{...E,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:Qe,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...E,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},coverage:{$ref:"#/$defs/coverage"},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},arkRun:{$ref:"#/$defs/arkRun"},arkOrder:{$ref:"#/$defs/arkOrder"},stewards:{...E,default:[]},requireLayerOwners:{type:"boolean"}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...E,minItems:1},exclude:E,intentPrefixes:E,description:{type:"string",minLength:1},trustBoundary:{type:"string",enum:[...ir]},owners:{...E,minItems:1},forbiddenGlobals:E,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"},reserved:{type:"boolean"},allowEmpty:{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:{...E,minItems:1},sharedRoots:{...E,minItems:1},allowedCrossSlice:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}},sharedImportsSlice:{type:"string",enum:["deny"]}}},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}}},coverage:{type:"object",additionalProperties:!1,description:"Invariant coverage scan controls. testGlobs replaces the built-in test-name heuristic; maxFiles raises or lowers the evidence file budget and also bounds structural-hint preload for orchestration-only, thin-adapter, and writes-via-aggregate (default 400; there is no arkrules.hintBudget); coverageRoots declares where the project runs its tests, so a covering test found outside them is reported instead of silently certifying an invariant. When any invariant is enforced, missing coverageRoots fails closed.",properties:{testGlobs:{...E,minItems:1},maxFiles:{type:"integer",minimum:1,description:"Evidence file budget (default 400) and structural-hint preload cap for orchestration-only, thin-adapter, and writes-via-aggregate. Raise this when hinted/governed counts show truncated sensors. There is no separate arkrules.hintBudget."},coverageRoots:{...E,minItems:1}}},arkRun:He,arkOrder:Ve}},x=class extends Error{static{l(this,"ArkConfigValidationError")}issues;source;constructor(t,r){super(`Invalid ArkGate config (${t}):
1
+ var $t=Object.defineProperty;var l=(e,t)=>$t(e,"name",{value:t,configurable:!0});import C from"fs";import m from"path";var Ne=new Map;function Ce(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}l(Ce,"escapeLiteral");function Z(e){let t="";for(let r=0;r<e.length;r+=1){let n=e[r];if(n==="\\"&&r+1<e.length){let s=e[r+1];if("*?{}[],".includes(s)||s==="\\"){t+="\\"+s,r+=1;continue}t+="/";continue}t+=n}return t}l(Z,"normalizeGlobSeparators");function Mt(e){let t=0;for(let r=0;r<e.length;r+=1){let n=e[r];if(n==="\\"){r+=1;continue}if(n==="{")t+=1;else if(n==="}"&&(t-=1,t<0))return!1}return t===0}l(Mt,"bracesBalanced");function _(e){let t=Ne.get(e);if(t)return t;let r=Z(e),n=Mt(r),s="",o=0;for(let a=0;a<r.length;a+=1){let c=r[a];c==="\\"&&a+1<r.length?(s+=Ce(r[a+1]),a+=1):c==="*"?r[a+1]==="*"?r[a+2]==="/"?(s+="(?:.*/)?",a+=2):(s+=".*",a+=1):s+="[^/]*":c==="?"?s+="[^/]":c==="{"&&n?(s+="(?:",o+=1):c==="}"&&n&&o>0?(s+=")",o-=1):c===","&&n&&o>0?s+="|":s+=Ce(c)}let i=new RegExp(`^${s}$`);return Ne.set(e,i),i}l(_,"globToRegExp");function Ut(e){return Z(String(e)).split("/").filter(Boolean).filter(r=>r!=="**"&&r!=="*"&&!r.includes("*")&&!r.includes("?")&&!r.includes("{")&&!r.includes("["))}l(Ut,"concreteGlobSegments");function De(e,t){let r=Z(String(e)),n=Ut(r),s=r.replace(/\*/g,"").length,o=n.length*1e4+s;if(t==null||t==="")return o;let i=String(t).split(/[/\\]/).filter(Boolean);if(n.length===0)return s;let a=0,c=-1;for(let f of n){let d=-1;for(let u=a;u<i.length;u+=1)if(i[u]===f){d=u;break}if(d<0)return o;c=d,a=d+1}return(c+1)*1e6+n.length*1e4+s}l(De,"patternSpecificity");function S(e,t){let r=String(e).split(/[/\\]/).join("/"),n,s=-1;for(let o of t??[])if(!(o.exclude??[]).some(i=>_(i).test(r))){for(let i of o.patterns??[])if(_(i).test(r)){let a=De(i,r);a>s&&(s=a,n=o.name)}}return n}l(S,"layerForRelativePath");function Oe(e,t,r){if(!t?.length)return;let n=r==="stars"?"stars":"path",s=String(e).split(/[/\\]/).filter(Boolean);if(s.length===0)return;let o=new Set;for(let i of t)if(!(typeof i!="string"||i.length===0)){if(jt(i)){let a=Ht(s,i,n);if(a)return a;continue}!i.includes("/")&&!i.includes("\\")&&!i.includes("*")&&o.add(i.toLowerCase())}return Gt(s,o)}l(Oe,"sliceIdForPath");function jt(e){let t=e.split(/[/\\]/).filter(r=>r.length>0);return t.length<2||t[0]==="*"||t[0]==="**"?!1:t.some(r=>r==="*")}l(jt,"isAnchoredSliceEntry");function Ht(e,t,r){let n=t.split(/[/\\]/).filter(o=>o.length>0).map(o=>o.toLowerCase()),s=Pe(e,n[0]??"");for(let o of s){let i=Vt(e,n,o,r);if(i)return i}}l(Ht,"anchoredSliceId");function Vt(e,t,r,n="path"){let s=[],o=-1,i=r;for(let a=0;a<t.length;a+=1){let c=t[a];if(c==="*"){if(i>=e.length-1){for(let f=a;f<t.length;f+=1)if(t[f]!=="*")return;break}s.push(e[i].toLowerCase()),i+=1;continue}if(c==="**"||i>=e.length||e[i].toLowerCase()!==c)return;s.push(e[i].toLowerCase()),o=s.length-1,i+=1}if(s.length!==0)return n==="stars"?o<0?void 0:s.slice(o).join("/"):s.join("/")}l(Vt,"bindAnchoredSlice");function Gt(e,t){if(t.size!==0){for(let r=0;r<e.length-1;r+=1)if(t.has(e[r].toLowerCase())&&!(r+1>=e.length-1))return`${e[r].toLowerCase()}/${e[r+1].toLowerCase()}`}}l(Gt,"bareSliceId");function Bt(e){let t=new Set;for(let r of e??[]){let s=Z(String(r)).split("/").filter(Boolean);for(let o=0;o<s.length;o+=1){let i=s[o];if((i==="**"||i==="*")&&o>0){let a=s[o-1];a&&!a.includes("*")&&!a.includes("{")&&!a.includes("}")&&t.add(a)}}}return[...t]}l(Bt,"inferSliceFoldersFromPatterns");function Wt(e,t,r){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(s=>typeof s=="string"&&s.length>0);let n=(r??[]).find(s=>s.name===t);return Bt(n?.patterns)}l(Wt,"resolveSliceFolders");function ve(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}l(ve,"normalizeSegments");function Fe(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}l(Fe,"trimTrailingSlashes");var zt=["src","app"];function Pe(e,t){let r=(e[0]??"").toLowerCase(),n=t.toLowerCase();return zt.includes(r)&&n!==r?[0,1]:[0]}l(Pe,"anchorOffsets");function qt(e){let t=Fe(e.replace(/^[./]+/,""));return t==="*"||t==="**"}l(qt,"isBlanketRoot");function Te(e,t){if(!e||!t?.length)return!1;let r=String(e).split(/[/\\]/).join("/"),n=r.toLowerCase(),s=ve(r);for(let o of t){if(typeof o!="string"||o.length===0||qt(o))continue;if(o.includes("*")){let c=Fe(o.toLowerCase());if(_(c).test(n)||_(`${c}/**`).test(n))return!0;continue}let i=ve(o);if(i.length===0)continue;let a=Pe(s,i[0]??"");for(let c of a){if(c+i.length>s.length)continue;let f=!0;for(let d=0;d<i.length;d+=1)if(s[c+d]!==i[d]){f=!1;break}if(f)return!0}}return!1}l(Te,"pathUnderSharedRoot");function Le(e,t){let r=String(e).split(/[/\\]/).filter(Boolean).join("/").toLowerCase();if(!r)return!1;let n=t.toLowerCase();return r===n?!0:!r.includes("/")&&n.endsWith(`/${r}`)}l(Le,"sliceMatchesDeclaration");function Zt(e,t,r){return!e?.length||!t||!r?!1:e.some(n=>n&&typeof n.from=="string"&&typeof n.to=="string"&&Le(n.from,t)&&Le(n.to,r))}l(Zt,"crossSliceEdgeAllowed");function Yt(e){if(!e.fromPath)return{denied:!0,reason:"missing-path"};if(e.folderCount<=0)return{denied:!0,reason:"no-slice-folders"};let t=!!e.fromSlice||e.fromShared===!0;if(!e.toPath)return t?e.fromSlice?{denied:!0,reason:"missing-path"}:{denied:!1}:{denied:!0,reason:"unclassifiable-path"};let r=!!e.toSlice||e.toShared===!0;return!t||!r?{denied:!0,reason:"unclassifiable-path"}:e.sharedImportsSlice==="deny"&&e.fromShared===!0&&e.toSlice&&!e.fromSlice?{denied:!0,reason:"shared-imports-slice"}:!e.fromSlice||!e.toSlice?{denied:!1}:e.fromSlice===e.toSlice?{denied:!1}:e.crossSliceAllowed?{denied:!1}:{denied:!0,reason:"cross-slice"}}l(Yt,"peerIsolationDecision");function Ke(e,t){switch(e){case"cross-slice":return`cross-slice edge ${t.fromSlice??"?"} \u2192 ${t.toSlice??"?"}. Extract the shared code, use events/ports across slices, or declare the edge in the rule's allowedCrossSlice.`;case"shared-imports-slice":return`shared root imports slice ${t.toSlice??"?"} (${t.fromPath??"?"} \u2192 ${t.toPath??"?"}). The wall is direct-only.`;case"unclassifiable-path":{let r=[t.fromSlice?void 0:t.fromPath,t.toSlice?void 0:t.toPath].filter(s=>!!s);return`unclassifiable path${r.length>0?` (${r.join(", ")})`:""} \u2014 ArkGate cannot place it in a slice, so it cannot prove this is not a cross-slice edge. Move it into a slice, or declare its root in the rule's sharedRoots.`}case"no-slice-folders":return"no slice folders \u2014 peerIsolation is on but no slice folder resolves from the rule or the layer patterns. Set sliceFolders on the rule.";default:return"no path evidence for this edge \u2014 peerIsolation needs the importer and importee paths."}}l(Ke,"peerIsolationDenyExplanation");function Xt(e,t,r,n){return ae(e,t,r,n)?.rule}l(Xt,"findDeniedEdgeRule");function ae(e,t,r,n){for(let s of e??[])if(!(s.from!==t||s.to!==r)&&s.allowed===!1){if(s.peerIsolation){let o=n?.fromPath,i=n?.toPath,a=Wt(s,t,n?.layers),c=o?Oe(o,a,s.sliceIdentity):void 0,f=i?Oe(i,a,s.sliceIdentity):void 0,d=Yt({fromPath:o,toPath:i,folderCount:a.length,fromSlice:c,toSlice:f,fromShared:!c&&Te(o,s.sharedRoots),toShared:!f&&Te(i,s.sharedRoots),crossSliceAllowed:Zt(s.allowedCrossSlice,c,f),sharedImportsSlice:s.sharedImportsSlice});if(d.denied)return{rule:s,peerIsolationReason:d.reason,fromSlice:c,toSlice:f};continue}if(t!==r)return{rule:s}}}l(ae,"findDeniedEdgeDecision");function Jt(e,t,r,n){return Xt(e,t,r,n)!==void 0}l(Jt,"isEdgeDenied");var Qt=["**/*.gen.ts","**/*.gen.tsx","**/*.generated.ts","**/*.generated.tsx"];function er(e){let t=Array.isArray(e?.exclude)?e.exclude.filter(n=>typeof n=="string"):[];return[...e?.excludeGenerated===!1?[]:Qt,...t]}l(er,"scanExcludePatterns");function $e(e,t){let r=String(e).split(/[/\\]/).join("/");return er(t).some(n=>_(n).test(r))}l($e,"isScanExcludedRelative");var Me=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),tr=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Jn=Object.freeze(Object.keys(tr).sort()),le=Object.freeze({fs:"filesystem","node:fs":"filesystem","fs/promises":"filesystem","node:fs/promises":"filesystem","fs-extra":"filesystem","graceful-fs":"filesystem",memfs:"filesystem",chokidar:"filesystem",http:"network",https:"network",http2:"network",net:"network",tls:"network",dgram:"network",dns:"network","node:http":"network","node:https":"network","node:http2":"network","node:net":"network","node:tls":"network","node:dgram":"network","node:dns":"network",axios:"network",undici:"network","node-fetch":"network",got:"network",ky:"network",superagent:"network",ws:"network",process:"process","node:process":"process",child_process:"process","node:child_process":"process","@prisma/client":"persistence",prisma:"persistence",pg:"persistence",mysql:"persistence",mysql2:"persistence",mongodb:"persistence",mongoose:"persistence",sqlite3:"persistence","better-sqlite3":"persistence",redis:"persistence",ioredis:"persistence",typeorm:"persistence",knex:"persistence","drizzle-orm":"persistence",sequelize:"persistence",kysely:"persistence","@supabase/supabase-js":"persistence"}),rr=Object.freeze({process:Object.freeze(["process","node:process"])});function Ue(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=le[e];if(t)return t;let r=e.indexOf("/");if(r<0)return null;let n=e.slice(0,r),s=le[n];if(s)return s;let o=e.indexOf("/",r+1);return o<0?null:le[e.slice(0,o)]??null}l(Ue,"capabilityForModuleSpecifier");function ce(e,t){for(let r of t)if(rr[r]?.includes(e))return r;return null}l(ce,"forbiddenGlobalForModuleSpecifier");function je(e){if(e?.pure===!0)return[...Me].sort();let r=(e?.capabilities?.deny??[]).filter(n=>Me.includes(n));return[...new Set(r)].sort()}l(je,"effectiveCapabilityDeny");var v={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},He={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...v,default:[]},kernelRoots:{...v},managedLayers:{...v,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},Ve={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...v,default:[]},managedLayers:{...v,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...v,default:[]},appliesTo:{...v,default:[]}}};function M(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}l(M,"isObject");function Ge(e){let t=new Set;if(!Array.isArray(e.layers))return t;for(let r of e.layers)M(r)&&typeof r.name=="string"&&r.name.length>0&&t.add(r.name);return t}l(Ge,"declaredLayerNames");function Be(e){if(!M(e))return e;let t={mode:e.mode===void 0?"advisory":e.mode,compositionRoots:e.compositionRoots===void 0?[]:e.compositionRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,requireDeclarations:e.requireDeclarations===void 0?!0:e.requireDeclarations};return e.kernelRoots!==void 0&&(t.kernelRoots=e.kernelRoots),e.ignoreDirectNewForErrors!==void 0&&(t.ignoreDirectNewForErrors=e.ignoreDirectNewForErrors),{...e,...t}}l(Be,"defaultedArkRun");function We(e){if(!M(e))return e;let t=typeof e.maxXiKeys=="number"&&e.maxXiKeys>0?e.maxXiKeys:7;return{...e,mode:e.mode===void 0?"advisory":e.mode,planeRoots:e.planeRoots===void 0?[]:e.planeRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,maxXiKeys:t,xiKeys:e.xiKeys===void 0?[]:e.xiKeys}}l(We,"defaultedArkOrder");function ze(e,t){let r=e.arkRun;if(r===void 0||!M(r))return;let n=Ge(e),s=r.managedLayers;if(Array.isArray(s)&&s.forEach((o,i)=>{typeof o=="string"&&o.length>0&&!n.has(o)&&t.push({path:`$.arkRun.managedLayers[${i}]`,message:`layer ${JSON.stringify(o)} is not declared in layers[]`})}),r.mode==="enforced"){let o=r.kernelRoots??r.compositionRoots;(!Array.isArray(o)||o.length===0)&&t.push({path:r.kernelRoots!==void 0?"$.arkRun.kernelRoots":"$.arkRun.compositionRoots",message:"ARKRUN_MISSING_ROOT: enforced mode requires at least one kernel root"}),(!Array.isArray(s)||s.length===0)&&t.push({path:"$.arkRun.managedLayers",message:"enforced mode requires at least one managed layer"})}}l(ze,"validateArkRunExtra");function qe(e,t){let r=e.arkOrder;if(r===void 0||!M(r))return;let n=Ge(e),s=r.managedLayers;if(Array.isArray(s)&&s.forEach((o,i)=>{typeof o=="string"&&o.length>0&&!n.has(o)&&t.push({path:`$.arkOrder.managedLayers[${i}]`,message:`layer ${JSON.stringify(o)} is not declared in layers[]`})}),r.mode==="enforced"){let o=r.planeRoots;(!Array.isArray(o)||o.length===0)&&t.push({path:"$.arkOrder.planeRoots",message:"ARKORDER_MISSING_PLANE: enforced mode requires at least one plane root"}),(!Array.isArray(s)||s.length===0)&&t.push({path:"$.arkOrder.managedLayers",message:"enforced mode requires at least one managed layer"})}}l(qe,"validateArkOrderExtra");function Y(e){if(typeof e!="string")return null;let t=e.trim().replace(/^@/,"").toLowerCase();return t.length>0?t:null}l(Y,"normalizeStewardId");function Ze(e){let t=Y(e);return!t||de(t)||t.includes(" ")||t.includes("@")?!1:/^(?!-)[a-z0-9-]{1,39}(?<!-)$/.test(t)}l(Ze,"isGitHubHandle");function nr(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();return!t.includes("@")||t.includes(" ")||de(t)?!1:/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}l(nr,"isGitHubEmail");function sr(e){if(typeof e!="string")return null;let t=e.trim().match(/^(?:\d+\+)?([^@]+)@users\.noreply\.github\.com$/i);return t&&Ze(t[1])?Y(t[1]):null}l(sr,"githubHandleFromEmail");function Ye(e){let t=sr(e);if(t)return t;let r=Y(e);return!r||de(r)?null:Ze(r)||nr(r)?r:null}l(Ye,"canonicalStewardId");var or=/bot\b|\[bot\]|dependabot|renovate|github-actions|imgbot|codecov/i;function de(e){let t=Y(e);return!t||or.test(t)}l(de,"isAutomationAuthor");var I="1.3",ir=["public","auth","admin","internal"];var ue="https://unpkg.com/arkgate@4/schemas/ark.config.schema.json",Xe=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],ar=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function lr(){let e=[];for(let t of Xe)for(let r of Xe)t===r||ar.has(`${t}->${r}`)||e.push({from:t,to:r,allowed:!1});return e}l(lr,"createDefaultRules");var Qe=lr(),fe=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"},{from:"1.1",to:"1.2"},{from:"1.2",to:"1.3"}],E={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Je={$schema:"https://json-schema.org/draft/2020-12/schema",$id:ue,title:"ArkGate architecture contract",description:"Versioned contract consumed identically by ArkGate CLI, MCP, and ESLint surfaces.",type:"object",additionalProperties:!1,required:["$schema","schemaVersion","include","layers","rules"],properties:{$schema:{type:"string",minLength:1,default:ue,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:I,default:I},name:{type:"string",minLength:1},include:{...E,minItems:1,default:["src"]},exclude:{...E,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:Qe,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...E,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},coverage:{$ref:"#/$defs/coverage"},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},arkRun:{$ref:"#/$defs/arkRun"},arkOrder:{$ref:"#/$defs/arkOrder"},stewards:{...E,default:[]},requireLayerOwners:{type:"boolean"}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...E,minItems:1},exclude:E,intentPrefixes:E,description:{type:"string",minLength:1},trustBoundary:{type:"string",enum:[...ir]},owners:{...E,minItems:1},forbiddenGlobals:E,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"},reserved:{type:"boolean"},allowEmpty:{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:{...E,minItems:1},sliceIdentity:{type:"string",enum:["path","stars"],description:"How a starred sliceFolders prefix is named. Absent and path keep today's ids (every literal and star binding). stars keeps the last literal plus the star bindings, so parallel trees share one feature id. Bare names are unchanged."},sharedRoots:{...E,minItems:1},allowedCrossSlice:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}},sharedImportsSlice:{type:"string",enum:["deny"]}}},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}}},coverage:{type:"object",additionalProperties:!1,description:"Invariant coverage scan controls. testGlobs replaces the built-in test-name heuristic; maxFiles raises or lowers the evidence file budget and also bounds structural-hint preload for orchestration-only, thin-adapter, and writes-via-aggregate (default 400; there is no arkrules.hintBudget); coverageRoots declares where the project runs its tests, so a covering test found outside them is reported instead of silently certifying an invariant. When any invariant is enforced, missing coverageRoots fails closed.",properties:{testGlobs:{...E,minItems:1},maxFiles:{type:"integer",minimum:1,description:"Evidence file budget (default 400) and structural-hint preload cap for orchestration-only, thin-adapter, and writes-via-aggregate. Raise this when hinted/governed counts show truncated sensors. There is no separate arkrules.hintBudget."},coverageRoots:{...E,minItems:1}}},arkRun:He,arkOrder:Ve}},x=class extends Error{static{l(this,"ArkConfigValidationError")}issues;source;constructor(t,r){super(`Invalid ArkGate config (${t}):
2
2
  ${r.map(n=>`- ${n.path}: ${n.message}`).join(`
3
- `)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=r}};function et(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}l(et,"isObject");function X(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}l(X,"propertyPath");function P(e){return e===null?"null":Array.isArray(e)?"array":typeof e}l(P,"valueType");function cr(e,t){let r="#/$defs/";if(e.startsWith(r))return t.$defs[e.slice(r.length)]}l(cr,"resolveSchemaRef");function U(e,t,r,n,s){if(t.$ref){let o=cr(t.$ref,n);if(!o){s.push({path:r,message:`schema reference ${t.$ref} cannot be resolved`});return}U(e,o,r,n,s);return}if(t.const!==void 0&&!Object.is(e,t.const)){s.push({path:r,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(o=>Object.is(o,e))){s.push({path:r,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!et(e)){s.push({path:r,message:`must be an object; received ${P(e)}`});return}let o=t.properties??{};for(let i of t.required??[])e[i]===void 0&&s.push({path:X(r,i),message:"is required"});if(t.additionalProperties===!1)for(let i of Object.keys(e))i in o||s.push({path:X(r,i),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let i=t.additionalProperties;for(let a of Object.keys(e))a in o||U(e[a],i,X(r,a),n,s)}for(let[i,a]of Object.entries(o))e[i]!==void 0&&U(e[i],a,X(r,i),n,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:r,message:`must be an array; received ${P(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&s.push({path:r,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let o=e.map(i=>JSON.stringify(i));new Set(o).size!==o.length&&s.push({path:r,message:"must not contain duplicate items"})}t.items&&e.forEach((o,i)=>U(o,t.items,`${r}[${i}]`,n,s));return}if(t.type==="string"){if(typeof e!="string"){s.push({path:r,message:`must be a string; received ${P(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&s.push({path:r,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&s.push({path:r,message:`must be a boolean; received ${P(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){s.push({path:r,message:`must be an integer; received ${P(e)}`});return}t.minimum!==void 0&&e<t.minimum&&s.push({path:r,message:`must be at least ${t.minimum}`})}}l(U,"validateNode");function dr(e,t){let r=e.layers;Array.isArray(r)&&r.forEach((n,s)=>{if(!n||typeof n!="object"||Array.isArray(n)||!("owners"in n))return;let o=n.owners;Array.isArray(o)&&o.forEach((i,a)=>{typeof i=="string"&&(Ye(i)||t.push({path:`$.layers[${s}].owners[${a}]`,message:"must be a GitHub handle or email (not a display name)"}))})})}l(dr,"validateLayerOwners");function ur(e){let t={...e,$schema:e.$schema===void 0?ue:e.$schema,schemaVersion:e.schemaVersion===void 0?I:e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?Qe.map(r=>({...r})):e.rules};return e.arkRun!==void 0&&(t.arkRun=Be(e.arkRun)),e.arkOrder!==void 0&&(t.arkOrder=We(e.arkOrder)),t}l(ur,"defaultedConfig");function fr(e){return e===I?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}l(fr,"migratedFromOf");function pr(){let e=new Set([I]);for(let t of fe)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}l(pr,"knownInputVersions");function gr(e,t="ark.config.json"){if(!et(e))throw new x(t,[{path:"$",message:`must be an object; received ${P(e)}`}]);let r=pr(),n=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(n===null)throw new x(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected ${I}`}]);if(n!=="unversioned"&&!r.has(n))throw new x(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(n)}; expected ${I}`}]);let s=n,o={...e},i=0;for(;s!==I&&i<fe.length+1;){i+=1;let a=fe.find(c=>c.from===s);if(!a)throw new x(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(s)}; expected ${I}`}]);s=a.to,o.schemaVersion=s}if(s!==I)throw new x(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(n)}; expected ${I}`}]);return{candidate:ur(o),migratedFrom:fr(n)}}l(gr,"migrateArkConfig");function mr(e,t="ark.config.json"){let{candidate:r,migratedFrom:n}=gr(e,t),s=[];if(U(r,Je,"$",Je,s),ze(r,s),qe(r,s),dr(r,s),s.length>0)throw new x(t,s);return{config:r,migratedFrom:n}}l(mr,"loadArkConfigContract");function tt(e,t="ark.config.json"){let r;try{r=JSON.parse(e)}catch(n){throw new x(t,[{path:"$",message:`invalid JSON: ${n instanceof Error?n.message:String(n)}`}])}return mr(r,t)}l(tt,"parseArkConfigJson");var yr=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,hr=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,Rr=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function Ar(e,t){let r=String(e??"").replace(/\\/g,"/").trim(),n=String(t?.fromLayer??""),s=String(t?.toLayer??"");return yr.test(r)?"pure-shared":n==="PersistenceAdapters"&&(hr.test(r)||/events?|intents?|kernel|bootstrap/i.test(`${s} ${r}`))?"kernel-emit":Rr.test(r)||(n==="DomainModel"||n==="ApplicationOrchestration")&&s==="PersistenceAdapters"?"use-case":"unknown"}l(Ar,"classifyLayerImportKind");function kr(e){if(e.typeOnly||e.targetTypeOnlyExports||e.namedBindingsTypeOnly)return"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.";if(e.peerIsolation)return"Extract the shared dependency to a shared layer, test at the public interface, then preflight again.";let t=Ar(typeof e.target=="string"?e.target:"",{fromLayer:typeof e.fromLayer=="string"?e.fromLayer:void 0,toLayer:typeof e.toLayer=="string"?e.toLayer:void 0});return t==="pure-shared"?"Adopt the imported constants/types/pure module into DomainModel or SharedKernel (do not inject a port). Then preflight again.":t==="kernel-emit"?"Persistence must not emit. Inject a port or move the event map to SharedTypes; do not import kernel/events/bootstrap from a repository. Then preflight again.":t==="use-case"||e.portProofEligible?`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, test at the public interface, then preflight again.`:"Classify the import: if it is constants/types/pure, adopt into DomainModel or SharedKernel; define a port only if the target is a real use-case. Then preflight again."}l(kr,"layerImportNextAction");function br(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}l(br,"arkRunCallSiteName");function Er(e){let t=br(e),r=typeof e.fromLayer=="string"&&e.fromLayer.length>0?e.fromLayer:void 0;switch(e.ruleId){case"ARKRUN_MISSING_ROOT":return t?`Import createStrictArkKernel from arkgate/runtime and call it in composition root ${t} listed in arkRun.compositionRoots, then preflight again.`:"Import createStrictArkKernel from arkgate/runtime (same npm package; @arkgate/runtime is deprecated) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKRUN_KERNEL_IN_DOMAIN":return t?`Move the kernel import of ${t} out of ${r??"the Domain-role layer"} into a composition root or adapter. Import from arkgate/runtime, then preflight again.`:"Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from arkgate/runtime (same npm package; @arkgate/runtime is deprecated), then preflight again. Never mechanical-safe.";case"ARKRUN_DIRECT_NEW":return t?`Resolve ${t} from the kernel instead of constructing it with new, then preflight again.`:"Resolve the type from the kernel instead of constructing it with new, then preflight again. Never mechanical-safe \u2014 rewiring construction is a design decision.";case"ARKRUN_UNDECLARED_EMIT":return t?`Add ${t} to raises or sends on the managed component, then preflight again.`:"Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment.";case"ARKRUN_UNDECLARED_HANDLE":return t?`Add ${t} to reactsTo on the managed component, then preflight again.`:"Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment.";case"ARKRUN_UNDECLARED_DEPEND":return t?`Add ${t} to uses on the managed component, then preflight again.`:"Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment.";case"ARKRUN_TRANSPORT_BYPASS":return t?`Send through the ArkRun kernel transport instead of importing ${t}, then preflight again.`:"Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe \u2014 homemade buses stay judgment.";default:return`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}l(Er,"arkRunNextAction");function K(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return kr(e);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"LITERAL_PATH_DRIFT":return typeof e.target=="string"&&e.target.length>0?`Rewrite the literal to ${e.target}, or run \`arkgate-check --path-drift --base-ref <ref> --write\` to apply every anchored replacement.`:"Rewrite the literal to the rename destination, or run `arkgate-check --path-drift --base-ref <ref> --write` to apply every anchored replacement.";case"LITERAL_PATH_UNRESOLVED":return"Read the candidate and decide: fix the path, or leave it. Advisory \u2014 with no rename to anchor it there is no destination to propose, so --write never touches it.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";case"INVARIANT_COVERAGE_OUTSIDE_ROOTS":return"Move the covering test under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json, then run Ark again.";case"INVARIANT_CATALOG_EMPTY":return typeof e.file=="string"&&e.file.length>0?`Add 1\u20132 short phrases to invariants[] in ${e.file}, then run ark-check --doctor. Starters show the shape.`:"Add 1\u20132 short phrases to invariants[] in arkrules/<Domain>.json, then run ark-check --doctor. Starters show the shape.";case"INVARIANT_TESTS_PATH_MISSING":return"Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present.";case"INVARIANT_COVERAGE_ROOTS_MISSING":return"Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. An enforced invariant fails closed until that path is present.";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.`;case"ARKRUN_MISSING_ROOT":case"ARKRUN_KERNEL_IN_DOMAIN":case"ARKRUN_DIRECT_NEW":case"ARKRUN_UNDECLARED_EMIT":case"ARKRUN_UNDECLARED_HANDLE":case"ARKRUN_UNDECLARED_DEPEND":case"ARKRUN_TRANSPORT_BYPASS":return Er(e);case"ARKORDER_MISSING_PLANE":return typeof e.target=="string"&&e.target.length>0?`Import createOrderPlane from arkgate/order and call it in plane root ${e.target} listed in arkOrder.planeRoots, then preflight again.`:"Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKORDER_KERNEL_IN_DOMAIN":return"Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe.";case"ARKORDER_GENERIC_UPDATE":return"Don't use a generic update. First freeze with release(). Later, propose the change, then apply it.";case"ARKORDER_TOO_MANY_PARAMS":return"Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe.";case"ARKORDER_INGEST_WRITES_XI":return"Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe.";case"ARKORDER_XI_FIELD_WRITE":return typeof e.target=="string"&&e.target.length>0?`Don't write ${e.target} from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.`:"Don't write a named product choice from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.";case"ARKORDER_UNVALVED_RELEASE":return"Change the choice with proposeRelease then apply. release() is only the first freeze. Never mechanical-safe.";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.`}}l(K,"deterministicNextAction");var pe="docs/diagnostics.md";function ge(e){let t=typeof e.ruleId=="string"?e.ruleId:typeof e.code=="string"?e.code:void 0,r=typeof e.file=="string"?e.file:void 0,n=typeof e.fromLayer=="string"?e.fromLayer:void 0,s=typeof e.toLayer=="string"?e.toLayer:void 0,o=typeof e.target=="string"?e.target:void 0;return[t,r,n??"",s??"",o??""].join("|")}l(ge,"adapterFindingTargetKey");function me(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}l(me,"adapterFindingRefFromTargetKey");function ye(e){return`${pe}#${e}`}l(ye,"adapterDocsCodePath");function h(e){return typeof e=="string"&&e.length>0?e:void 0}l(h,"text");function rt(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}l(rt,"positiveInteger");function xr(e,t,r){return K({ruleId:e,target:h(t.target)??h(r.target)??void 0,fromLayer:h(t.fromLayer)??void 0,toLayer:h(t.toLayer)??void 0,typeOnly:t.typeOnly===!0,targetTypeOnlyExports:t.targetTypeOnlyExports===!0,namedBindingsTypeOnly:t.namedBindingsTypeOnly===!0,portProofEligible:t.portProofEligible===!0,peerIsolation:t.peerIsolation===!0,sourcePureTypeModule:t.sourcePureTypeModule===!0,edgeKind:h(t.edgeKind)??void 0,capability:h(t.capability)??h(r.capability)??void 0,arkruleId:h(t.arkruleId)??void 0,arkruleSource:h(t.arkruleSource)??void 0})}l(xr,"nextActionForDiagnostic");function nt(e,t="error",r){let n=h(e.ruleId)??h(e.code)??"ARK_UNKNOWN",s=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,o={...h(e.target)?{target:h(e.target)}:{},...h(e.fromLayer)?{fromLayer:h(e.fromLayer)}:{},...h(e.toLayer)?{toLayer:h(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{},...typeof e.targetTypeOnlyExports=="boolean"?{targetTypeOnlyExports:e.targetTypeOnlyExports}:{},...typeof e.sourcePureTypeModule=="boolean"?{sourcePureTypeModule:e.sourcePureTypeModule}:{},...typeof e.namedBindingsTypeOnly=="boolean"?{namedBindingsTypeOnly:e.namedBindingsTypeOnly}:{},...typeof e.portProofEligible=="boolean"?{portProofEligible:e.portProofEligible}:{},...typeof e.peerIsolation=="boolean"?{peerIsolation:e.peerIsolation}:{},...h(e.capability)?{capability:h(e.capability)}:{},...h(e.edgeKind)?{edgeKind:h(e.edgeKind)}:{},...h(e.arkruleId)?{arkruleId:h(e.arkruleId)}:{},...h(e.arkruleSource)?{arkruleSource:h(e.arkruleSource)}:{}},i=r??ge(e),a=me(i);return{ruleId:n,severity:s,message:h(e.message)??n,location:{file:h(e.file)??"<unknown>",line:rt(e.line,1),column:rt(e.column,1)},evidence:o,nextAction:h(e.nextAction)??xr(n,o,e),findingRef:a,targetKey:i,docsCodePath:ye(n)}}l(nt,"toAdapterDiagnostic");var st={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."},Ss=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 wr(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}l(wr,"looksLikeArkIntent");function he(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&wr(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:st.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:st.PUBLISH_MISSING_SOURCE}),t}l(he,"classifyPublishFacts");import yt from"fs";import T from"path";var _r=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"];var Nr=new Set(_r),Cr=new Set(["AggregateError","Array","ArrayBuffer","BigInt64Array","BigUint64Array","Boolean","DataView","Date","Error","EvalError","FinalizationRegistry","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Number","Object","Promise","Proxy","RangeError","ReferenceError","RegExp","Set","SharedArrayBuffer","String","Symbol","SyntaxError","TypeError","URIError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","WeakRef","WeakSet"]),Or=new Set(["Array","Atomics","Buffer","JSON","Math","Number","Object","Promise","Reflect","String","console","fs","path","url","util"]);function M(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")}l(M,"isArkRunKernelModuleSpecifier");var vr=["events","node:events","eventemitter2","eventemitter3","emittery","kafkajs","kafka-node","amqplib","amqp","bull","bullmq","mqtt","nats","@aws-sdk/client-sqs","@aws-sdk/client-sns","@aws-sdk/client-eventbridge","@google-cloud/pubsub","@azure/service-bus"],Re=new Set(vr);function at(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(Re.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let r=e.slice(0,t);if(Re.has(r))return!0;let n=e.indexOf("/",t+1);return n<0?!1:Re.has(e.slice(0,n))}l(at,"isArkRunTransportBypassSpecifier");function ot(e){if(Nr.has(e))return"factory";switch(e){case"publisher":return"publisher";case"publish":return"publish";case"raise":case"raiseAsync":return"raise";case"send":case"sendTo":return"send";case"subscribe":return"subscribe";case"registerHandler":return"register-handler";case"resolve":return"resolve";case"resolveSingleton":return"resolve-singleton";default:return}}l(ot,"arkRunKernelCallKind");function lt(e,t){let r=1;for(let n=0;n<t;n+=1)e.charCodeAt(n)===10&&(r+=1);return r}l(lt,"lineAt");function Ae(e){return e.replace(/\/\*[\s\S]*?\*\//g,t=>t.replace(/[^\n]/g," ")).replace(/(^|[^:\\])\/\/.*$/gm,t=>t.replace(/\/\/.*$/,r=>" ".repeat(r.length)))}l(Ae,"stripCommentsPreservingLines");function Tr(e,t){let r=e.slice(t),n=/^\s*(['"])((?:\\.|[^\\])*?)\1/.exec(r);if(!n)return;let s=n[2]??"";return s.length>0?s:void 0}l(Tr,"firstStringLiteralArg");function it(e,t,r){let n=Math.max(0,t-r.length-8),s=e.slice(n,t);return new RegExp(`\\b${r}\\s+$`).test(s)}l(it,"keywordBefore");function J(e,t){let r=/\b(?:import|export)(\s+type)?\s+([\s\S]*?)\s+from\s*['"]([^'"]+)['"]/g,n;for(;(n=r.exec(e))!==null;)n[1]||t(n[2]??"",n[3]??"")}l(J,"parseValueImportClause");function ct(e,t){J(Ae(e),t)}l(ct,"forEachArkRunValueImportClause");function Lr(e){let t=new Map,r=new Set;return J(e,(n,s)=>{if(!M(s))return;let o=/\*\s+as\s+([A-Za-z_][A-Za-z0-9_]*)/.exec(n);o?.[1]&&r.add(o[1]);let i=/^([A-Za-z_][A-Za-z0-9_]*)\s*(?:,|$)/.exec(n.trim());i?.[1]&&t.set(i[1],i[1]);let a=/\{([^}]*)\}/.exec(n);if(a?.[1])for(let c of a[1].split(",")){let f=c.trim();if(!f||f.startsWith("type "))continue;let d=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(f);if(d){t.set(d[2],d[1]);continue}let u=/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(f);u?.[1]&&t.set(u[1],u[1])}}),{named:t,namespaces:r}}l(Lr,"collectKernelImportBindings");function Dr(e,t){let r=new Set(t);return J(e,(n,s)=>{let o=/\{([^}]*)\}/.exec(n);if(o?.[1])for(let i of o[1].split(",")){let a=i.trim();if(!a||a.startsWith("type "))continue;let c=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(a),f=c?.[2]??/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(a)?.[1],d=c?.[1]??f;!f||!d||!/^[A-Z]/.test(d)||(M(s)||t.has(d)||t.has(f))&&(r.add(f),r.add(d))}}),r}l(Dr,"collectImportedConstructors");function Fr(e,t){let r;return J(e,(n,s)=>{!r&&new RegExp(`\\b${t}\\b`).test(n)&&(r=s)}),r}l(Fr,"importedFromForName");function Q(e,t){let r=Ae(t),n=Lr(r),s=[],o=/\b([A-Za-z_][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,i;for(;(i=o.exec(r))!==null;){let a=i[1],c=i.index;if(it(r,c,"function")||it(r,c,"class"))continue;let d=r.slice(0,c).match(/([A-Za-z_][A-Za-z0-9_]*)\s*\.\s*$/)?.[1],u=n.named.get(a)??a,p=ot(u)??ot(a);if(!p)continue;let g=n.named.has(a)||d!==void 0&&n.namespaces.has(d);if(p!=="factory"&&(!g&&d===void 0||d&&Or.has(d)&&!g))continue;let y=Tr(r,c+i[0].length);s.push({file:e,line:lt(t,c),kind:p,callee:a,viaImport:g,...d?{receiver:d}:{},...y?{nameLiteral:y}:{}})}return s}l(Q,"extractArkRunKernelCallsFromSource");function ke(e,t,r){let n=Ae(t),s=Dr(n,r),o=[],i=/\bnew\s+(?:[A-Za-z_][A-Za-z0-9_]*\s*\.\s*)*([A-Z][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,a;for(;(a=i.exec(n))!==null;){let c=a[1];if(Cr.has(c)||!s.has(c))continue;let f=Fr(n,c);o.push({file:e,line:lt(t,a.index),typeName:c,...f?{importedFrom:f}:{}})}return o}l(ke,"extractArkRunManagedNewsFromSource");var Pr=["ensureInvariants","assertInvariants","validate","publish","emit","raise","record"],Kr=new RegExp(`\\b(${Pr.join("|")})\\b`),ut="(?:_?pendingEvents|domainEvents|uncommittedEvents|recordedEvents)",Mr=new RegExp(`\\bthis\\.${ut}\\.push\\s*\\(`),$r=new RegExp(`^this\\.${ut}\\s*=\\s*\\[\\s*\\]`),Ur=/^this\.[A-Za-z_][A-Za-z0-9_]*\s*=\s*\[\s*\]/,jr=/\bthis\.[A-Za-z_][A-Za-z0-9_]*\s*=(?!=)/g,Hr="truncatedUntil";function Vr(e){return Kr.test(e)||Mr.test(e)}l(Vr,"referencesGuardOrPublish");function Gr(e,t,r){let n=e.slice(t);if($r.test(n))return!0;if(!Ur.test(n))return!1;if(r&&/^pullEvents$/i.test(r))return!0;let s=t>200?t-200:0;return/\bpullEvents\b/.test(e.slice(s,t+200))}l(Gr,"isIdiomaticEventsReset");function Br(e,t){let r=new RegExp(jr.source,"g"),n;for(;(n=r.exec(t))!==null;)if(!Gr(t,n.index,e))return!0;return!1}l(Br,"methodAssignsThis");function Wr(e,t){return t==null||Object.defineProperty(e,Hr,{value:t,enumerable:!1,configurable:!0}),e}l(Wr,"attachShapeTruncation");var zr=new Set(["public","private","protected","static","async","readonly","abstract","override","declare","get","set"]),qr=new Set(["if","match","when"]);function ee(e,t){let r=e[t];if(r==="/"&&e[t+1]==="/"){let n=e.indexOf(`
4
- `,t);return n===-1?e.length:n}if(r==="/"&&e[t+1]==="*"){let n=e.indexOf("*/",t+2);return n===-1?e.length:n+2}if(r==="'"||r==='"'||r==="`"){let n=t+1;for(;n<e.length;){if(e[n]==="\\"){n+=2;continue}if(e[n]===r)return n+1;n+=1}return e.length}return t}l(ee,"skipStringOrComment");function j(e,t){let r=t;for(;r<e.length;){if(/\s/.test(e[r])){r+=1;continue}if(e[r]==="/"&&(e[r+1]==="/"||e[r+1]==="*")){r=ee(e,r);continue}break}return r}l(j,"skipWsAndComments");function dt(e,t){let r=e[t];if(!r||!/[A-Za-z_]/.test(r))return null;let n=t+1;for(;n<e.length&&/[A-Za-z0-9_]/.test(e[n]);)n+=1;return{ident:e.slice(t,n),end:n}}l(dt,"readIdent");function be(e,t,r,n){if(e[t]!==r)return null;let s=1,o=t+1;for(;o<e.length&&s>0;){let i=ee(e,o);if(i!==o){o=i;continue}let a=e[o];a===r?s+=1:a===n&&(s-=1),o+=1}return s===0?o:null}l(be,"skipBalanced");function Zr(e){let t=[],r=0,n;for(;r<e.length&&(r=j(e,r),!(r>=e.length));){if(e[r]===";"){r+=1;continue}let s=[],o=r;for(;;){let d=dt(e,o);if(!d||!zr.has(d.ident))break;s.push(d.ident),o=j(e,d.end)}let i=dt(e,o);if(!i){r+=1;continue}if(o=j(e,i.end),e[o]==="<"){let d=be(e,o,"<",">");if(d==null){n=e.length;break}o=j(e,d)}if(e[o]==="("){let d=be(e,o,"(",")");if(d==null){n=e.length;break}if(o=j(e,d),e[o]===":")for(o+=1;o<e.length&&e[o]!=="{"&&e[o]!==";";){let u=ee(e,o);if(u!==o){o=u;continue}o+=1}if(e[o]==="{"){let u=be(e,o,"{","}");if(u==null){n=e.length;break}t.push({name:i.ident,modifiers:s,kind:"method",body:e.slice(o+1,u-1)}),r=u;continue}if(e[o]===";"){r=o+1;continue}r=o+1;continue}let a=0,c=0,f=0;for(;o<e.length;){let d=ee(e,o);if(d!==o){o=d;continue}let u=e[o];if(u==="{")a+=1;else if(u==="}"){if(a===0)break;a-=1}else if(u==="(")c+=1;else if(u===")")c-=1;else if(u==="[")f+=1;else if(u==="]")f-=1;else if(u===";"&&a===0&&c===0&&f===0){o+=1;break}o+=1}t.push({name:i.ident,modifiers:s,kind:"field",body:""}),r=o}return{members:t,truncatedAt:n}}l(Zr,"scanClassMembers");function Ee(e,t){let r=[],n=/export\s+(?:abstract\s+)?class\s+([A-Za-z_][A-Za-z0-9_]*)\s*(?:extends\s+[^{]+)?(?:implements\s+[^{]+)?\{/g,s;for(;(s=n.exec(t))!==null;){let o=s[1],i=s.index+s[0].length,a=1,c=i;for(;c<t.length&&a>0;){let A=t[c];A==="{"?a+=1:A==="}"&&(a-=1),c+=1}let f=t.slice(i,c-1),d=a>0,u=Zr(f),p=d?t.length:u.truncatedAt==null?void 0:i+u.truncatedAt,g=u.members.filter(A=>!(A.kind!=="field"||A.name==="constructor"||A.modifiers.includes("private")||A.modifiers.includes("protected")||A.modifiers.includes("readonly")||A.modifiers.includes("static")||A.modifiers.includes("get")||A.modifiers.includes("set"))),y=g.length>0,R=/(?:^|[\n;{])\s*(?:public\s+)?set\s+[a-zA-Z_]/.test(f),k=/(?:^|[\n;{])\s*private\s+constructor\s*\(/.test(f),b=/(?:^|[\n;{])\s*(?:public\s+)?constructor\s*\(/.test(f)&&!k,q=/(?:^|[\n;{])\s*static\s+(?:async\s+)?(?:create|of|from|parse|build|make|new)\s*[<(]/.test(f)||/(?:^|[\n;{])\s*static\s+(?:async\s+)?[A-Za-z_][A-Za-z0-9_]*\s*\([^)]*\)\s*:\s*[A-Za-z_]/.test(f),D=[];for(let A of u.members)A.kind==="method"&&A.name!=="constructor"&&(A.modifiers.includes("static")||A.modifiers.includes("get")||A.modifiers.includes("set")||qr.has(A.name)||Br(A.name,A.body)&&D.push({name:A.name,referencesGuardOrPublish:Vr(A.body)}));let F=u.members.filter(A=>A.kind==="method").length<=1&&g.length>=2&&y;r.push(Wr({file:e,className:o,exported:!0,hasPublicMutableFields:y,hasPublicSetters:R,hasPublicConstructor:b,hasStaticFactory:q,mutatingMethods:[...D],dataOnly:F},p))}return r}l(Ee,"extractClassShapesFromSource");function Yr(e){if(!e)return{};let t=typeof e.governedPercent=="number"?e.governedPercent:null,r=typeof e.populatedLayerCount=="number"?e.populatedLayerCount:null;return r==null&&typeof e.classifiedFiles=="number"&&(r=e.classifiedFiles>0?1:0),{governedPercent:t,populatedLayerCount:r}}l(Yr,"normalizeExtraMergeTeethClassification");function te(e){let t=Yr(e),r=typeof t.governedPercent=="number"?t.governedPercent:null,n=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null;return r==null&&n==null?!0:(r??0)>=50&&(n??0)>=1}l(te,"extraMergeTeethAllowed");var Xr=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],Jr=new Set(Xr);function Qr(e){return Jr.has(e)}l(Qr,"isArkRunEditorSensor");var ft={"arkrun-missing-root":"ARKRUN_MISSING_ROOT","arkrun-kernel-in-domain":"ARKRUN_KERNEL_IN_DOMAIN","arkrun-direct-new":"ARKRUN_DIRECT_NEW","arkrun-undeclared-emit":"ARKRUN_UNDECLARED_EMIT","arkrun-undeclared-handle":"ARKRUN_UNDECLARED_HANDLE","arkrun-undeclared-depend":"ARKRUN_UNDECLARED_DEPEND","arkrun-transport-bypass":"ARKRUN_TRANSPORT_BYPASS"},en="ARKRUN_INTERACTION_NAME_INCOMPLETE";function mt(e,t=[]){let r=e.trim();return/^domain(?:model)?$/i.test(r)||/^domain(?=[A-Z_\-\s])/i.test(r)||/^(?:entit(?:y|ies)|aggregates?)(?:$|(?=[A-Z_\-\s]))/i.test(r)?!0:t.some(n=>{let s=n.trim().replace(/\.+$/,"");return s==="Domain"||s.startsWith("Domain.")})}l(mt,"isDomainRoleLayer");function tn(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}l(tn,"compareFindings");function w(e,t,r,n,s,o,i){let a=e.mode==="enforced"&&i;return{ruleId:ft[t],sensor:t,message:s,file:r,line:n,...o?.fromLayer?{fromLayer:o.fromLayer}:{},...o?.target?{target:o.target}:{},severity:a?"error":"warning",failsStrict:a,nextAction:K({ruleId:ft[t],fromLayer:o?.fromLayer,target:o?.target})}}l(w,"finding");function rn(e,t){let r=[],n=[],s=[],o=[];for(let i of e)i.file===t&&(r.push(...i.uses),n.push(...i.reactsTo),s.push(...i.raises),o.push(...i.sends));return{uses:new Set(r),reactsTo:new Set(n),raises:new Set(s),sends:new Set(o)}}l(rn,"bagForFile");function pt(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}l(pt,"emitKinds");function gt(e){return e==="subscribe"||e==="register-handler"}l(gt,"handleKinds");function nn(e){return e==="resolve"||e==="resolve-singleton"}l(nn,"dependKinds");function sn(e,t,r){let n=[],s=e.kernelRoots??e.compositionRoots;if(s.length===0)return n.push(w(e,"arkrun-missing-root","ark.config.json",1,"ArkRun kernelRoots is empty; no createArkKernel factory site is declared.",void 0,r)),n;let o=new Map;for(let i of t){let a=o.get(i.matchedRoot)??[];a.push(i),o.set(i.matchedRoot,a)}for(let i of s){let a=[...o.get(i)??[]].sort((f,d)=>f.file.localeCompare(d.file));if(a.length===0){n.push(w(e,"arkrun-missing-root","ark.config.json",1,`ArkRun kernel root ${JSON.stringify(i)} matched no governed files and has no createArkKernel factory.`,{target:i},r));continue}if(a.some(f=>f.hasKernelFactory))continue;let c=a[0];n.push(w(e,"arkrun-missing-root",c.file,1,`ArkRun kernel root ${JSON.stringify(i)} has no createArkKernel / createStrictArkKernel factory.`,{target:i},r))}return n}l(sn,"evaluateMissingRoot");function on(e,t,r,n,s){let o=new Map(t.map(a=>[a.name,a.intentPrefixes??[]])),i=[];for(let a of r){let c=a.specifier;if(!c||!M(c))continue;let f=n(a.from);f&&mt(f,o.get(f)??[])&&i.push(w(e,"arkrun-kernel-in-domain",a.from,a.line,`${f} must not import kernel module ${JSON.stringify(c)}.`,{fromLayer:f,target:c},s))}return i}l(on,"evaluateKernelInDomain");function an(e,t,r,n,s,o){let i=new Set(e.managedLayers);if(i.size===0)return[];let a=new Map(t.map(d=>[d.name,d.intentPrefixes??[]])),c=new Set(n.filter(d=>d.hasKernelFactory).map(d=>d.file)),f=[];for(let d of r){if(c.has(d.file))continue;let u=d.typeName;if(e.ignoreDirectNewForErrors!==!1&&(u.endsWith("Error")||u==="Error")||u.endsWith("DTO")||u.endsWith("VO"))continue;let p=s(d.file);!p||!i.has(p)||mt(p,a.get(p)??[])||f.push(w(e,"arkrun-direct-new",d.file,d.line,`${p} must not construct ${d.typeName} with new outside an ArkRun composition-root factory.`,{fromLayer:p,target:d.typeName},o))}return f}l(an,"evaluateDirectNew");function ln(e,t,r,n,s){let o=[],i=[];if(e.requireDeclarations!==!0)return{findings:o,completenessReasons:i};let a=new Set(e.managedLayers);if(a.size===0)return{findings:o,completenessReasons:i};for(let c of t){if(!pt(c.kind)&&!gt(c.kind)&&!nn(c.kind))continue;let f=n(c.file);if(!f||!a.has(f))continue;if(!c.nameLiteral){e.mode==="enforced"&&i.push({code:en,file:c.file,message:`ArkRun ${c.kind} call in ${c.file} has no string-literal name; enforced extra cannot prove the declaration.`});continue}let d=rn(r,c.file);if(pt(c.kind)){if(d.raises.has(c.nameLiteral)||d.sends.has(c.nameLiteral))continue;o.push(w(e,"arkrun-undeclared-emit",c.file,c.line,`Emit ${JSON.stringify(c.nameLiteral)} is not declared in raises or sends.`,{fromLayer:f,target:c.nameLiteral},s));continue}if(gt(c.kind)){if(d.reactsTo.has(c.nameLiteral))continue;o.push(w(e,"arkrun-undeclared-handle",c.file,c.line,`Handle ${JSON.stringify(c.nameLiteral)} is not declared in reactsTo.`,{fromLayer:f,target:c.nameLiteral},s));continue}d.uses.has(c.nameLiteral)||o.push(w(e,"arkrun-undeclared-depend",c.file,c.line,`Depend ${JSON.stringify(c.nameLiteral)} is not declared in uses.`,{fromLayer:f,target:c.nameLiteral},s))}return{findings:o,completenessReasons:i}}l(ln,"evaluateUndeclared");function cn(e,t,r,n){let s=new Set(e.managedLayers);if(s.size===0)return[];let o=[];for(let i of t){if(i.typeOnly)continue;let a=i.specifier;if(!a||!at(a))continue;let c=r(i.from);!c||!s.has(c)||o.push(w(e,"arkrun-transport-bypass",i.from,i.line,`${c} must not import broker/queue/emitter ${JSON.stringify(a)}; use the ArkRun kernel transport.`,{fromLayer:c,target:a},n))}return o}l(cn,"evaluateTransportBypass");function dn(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let r=te(e.classification),n=ln(t,e.kernelCalls,e.declarations,e.layerForFile,r),s=[...sn(t,e.compositionRootHits,r),...on(t,e.layers,e.dependencies,e.layerForFile,r),...an(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,r),...n.findings,...cn(t,e.dependencies,e.layerForFile,r)].sort(tn),o=[...n.completenessReasons].sort((i,a)=>{let c=`${i.code}\0${i.file??""}\0${i.message}`,f=`${a.code}\0${a.file??""}\0${a.message}`;return c<f?-1:c>f?1:0});return{findings:s,completenessReasons:o}}l(dn,"evaluateArkRunSensors");function Se(e){return{findings:dn(e).findings.filter(r=>Qr(r.sensor)),completenessReasons:[]}}l(Se,"evaluateArkRunEditorSensors");function un(e){if(e.importKind==="type"||e.exportKind==="type")return!0;let t=e.specifiers??[];return t.length===0?!1:t.every(r=>r.type==="ImportSpecifier")?t.every(r=>r.importKind==="type"):t.every(r=>r.exportKind==="type")}l(un,"declarationIsTypeOnly");function Rt(e){try{return yt.existsSync(e)?yt.readFileSync(e,"utf8"):null}catch{return null}}l(Rt,"readUtf8");function ht(e,t){let r=e.lintedFilename(t),n=e.findConfigPath(r),s=n?e.loadArkConfig(n):null;if(!s?.arkRun||!n||!r)return null;let o=T.dirname(n),i=T.isAbsolute(r)?r:T.resolve(r),a=T.relative(o,i).split(T.sep).join("/");if(!e.sourceIsInAnalysisScope(s,a))return null;let c=S(a,s.layers);return c?{extra:s.arkRun,config:s,root:o,absFile:i,relFile:a,fromLayer:c}:null}l(ht,"loadEditorFile");function fn(e,t,r){let n=Q(t,r).some(o=>o.kind==="factory"),s=[];for(let o of e.compositionRoots){try{if(!_(o).test(t))continue}catch{continue}s.push({file:t,matchedRoot:o,hasKernelFactory:n})}return s}l(fn,"compositionRootHitsForFile");function pn(e,t,r){let n=new Set(Ee(t.relFile,r).map(s=>s.className));return ct(r,(s,o)=>{if(M(o))return;let i=e.resolveImportSpecifier(t.absFile,o,t.root);if(!i)return;let a=T.relative(t.root,i).split(T.sep).join("/");if(a.startsWith(".."))return;let c=Rt(i);if(c!==null)for(let f of Ee(a,c))n.add(f.className)}),n}l(pn,"admittedTypeNamesForEditor");function At(e,t,r,n,s,o){e.reportAdapterDiagnostic(t,r,n,{ruleId:s.ruleId,file:s.file,fromLayer:s.fromLayer,target:s.target,message:s.message,line:s.line,severity:s.severity,failsStrict:s.failsStrict,nextAction:s.nextAction},o)}l(At,"reportFinding");function gn(e){let t=e.callee;if(t?.type==="Identifier"&&t.name&&/^[A-Z]/.test(t.name))return t.name;let r=t?.property?.name;if(r&&/^[A-Z]/.test(r)&&t?.computed!==!0)return r}l(gn,"constructedTypeName");function mn(e,t){return e.type?.startsWith("Export")?"export":t}l(mn,"specifierEdgeKind");function yn(e,t,r,n,s){let o=l((i,a,c,f)=>{if(typeof a!="string"||a.length===0)return;let d=i.loc?.start?.line??1,u={from:r.relFile,specifier:a,kind:f,typeOnly:c,line:d,resolution:"resolved-external"},{findings:p}=Se({arkRun:r.extra,layers:r.config.layers,kernelCalls:[],managedNews:[],compositionRootHits:[],declarations:[],dependencies:[u],layerForFile:l(g=>g===r.relFile?r.fromLayer:S(g,r.config.layers),"layerForFile")});for(let g of p)g.sensor===n&&At(e,t,i,s,g,{fromLayer:g.fromLayer??r.fromLayer,specifier:a,target:g.target??a})},"check");return{ImportDeclaration(i){let a=i,c=(a.specifiers??[]).filter(d=>d.type==="ImportSpecifier"),f=c.length>0&&c.length===(a.specifiers??[]).length&&c.every(d=>d.importKind==="type");o(i,a.source?.value,a.importKind==="type"||f||un(i),"import")},ImportExpression(i){let a=i;a.source?.type==="Literal"&&o(i,a.source.value,!1,"dynamic-import")},TSImportEqualsDeclaration(i){let a=i;o(i,a.moduleReference?.expression?.value,a.importKind==="type"||a.isTypeOnly===!0,"require")},ExportNamedDeclaration(i){let a=i;if(!a.source)return;let c=a.specifiers??[],f=c.length>0&&c.every(d=>d.exportKind==="type");o(i,a.source.value,a.exportKind==="type"||f,mn(i,"export"))},ExportAllDeclaration(i){let a=i;o(i,a.source?.value,a.exportKind==="type","export")},CallExpression(i){let a=i;a.callee?.type==="Identifier"&&a.callee.name==="require"&&a.arguments?.[0]?.type==="Literal"&&!e.isLocallyBound(t,i,"require")&&o(i,a.arguments[0].value,!1,"require")}}}l(yn,"importListeners");function hn(e,t,r){let n=Rt(r.absFile)??"",s=pn(e,r,n),o=ke(r.relFile,n,s),{findings:i}=Se({arkRun:r.extra,layers:r.config.layers,kernelCalls:Q(r.relFile,n),managedNews:o,compositionRootHits:fn(r.extra,r.relFile,n),declarations:[],dependencies:[],layerForFile:l(c=>c===r.relFile?r.fromLayer:S(c,r.config.layers),"layerForFile")}),a=i.filter(c=>c.sensor==="arkrun-direct-new");return{NewExpression(c){let f=gn(c);if(!f)return;let d=c.loc?.start?.line,u=a.find(p=>p.target===f&&(d===void 0||p.line===d))??a.find(p=>p.target===f);u&&At(e,t,c,"directNew",u,{fromLayer:u.fromLayer??r.fromLayer,typeName:f,target:u.target??f})}}}l(hn,"directNewListener");function kt(e){let t=l((r,n,s,o)=>({meta:{type:"problem",docs:{description:n},messages:{[s]:o},schema:[]},create(i){let a=ht(e,i);return a?yn(e,i,a,r,s):{}}}),"createImportRule");return{noArkRunKernelInDomain:t("arkrun-kernel-in-domain","Disallow Domain-role imports of arkgate/runtime when arkRun is on (same sensor as ark-check).","kernelInDomain",'{{fromLayer}} must not import kernel module "{{specifier}}".'),noArkRunTransportBypass:t("arkrun-transport-bypass","Disallow homemade broker/queue/emitter imports in arkRun managed layers (same sensor as ark-check).","transportBypass",'{{fromLayer}} must not import broker/queue/emitter "{{specifier}}"; use the ArkRun kernel transport.'),noArkRunDirectNew:{meta:{type:"problem",docs:{description:"Disallow `new` of ArkRun-admitted types outside a composition-root factory (on-disk import/`new` envelope)."},messages:{directNew:"{{fromLayer}} must not construct {{typeName}} with new outside an ArkRun composition-root factory."},schema:[]},create(r){let n=ht(e,r);return n?hn(e,r,n):{}}}}}l(kt,"createArkRunEslintRules");var Rn="createOrderPlane";var An=/\bfrom\s+['"](?:@?prisma\/client|@supabase\/|drizzle-orm(?:\/[^'"]+)?|postgres(?:\/[^'"]+)?|typeorm|knex|mongodb|pg|mysql2|mongoose|better-sqlite3|ioredis|redis|kysely|sequelize)['"]|require\(\s*['"](?:@?prisma\/client|pg|postgres(?:\/[^'"]+)?|drizzle-orm(?:\/[^'"]+)?|knex|typeorm|mongoose)/,kn=/\bfrom\s+['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)(?:\.[cm]?[jt]sx?)?['"]|require\(\s*['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)/,bn=/\b(?:db|tx|client|prisma(?:Client)?|drizzle)\b(?:\s*\.\s*[A-Za-z_]\w*)*\s*\.\s*(?:insert(?:One|Many)?|update(?:One|Many)?|upsert|delete(?:One|Many)?|createMany|create|replaceOne|findOneAnd(?:Update|Delete|Replace))\s*\(|\bINSERT\s+INTO\b|\bUPDATE\s+[A-Za-z_][\w.]*\s+SET\b|\bDELETE\s+FROM\b/i;function En(e){return An.test(e)||kn.test(e)}l(En,"sourceImportsPersistenceDriver");function re(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}l(re,"escapeRegExp");function ne(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}l(ne,"isArkOrderModuleSpecifier");function H(e,t){let r=1;for(let n=0;n<t&&n<e.length;n+=1)e[n]===`
5
- `&&(r+=1);return r}l(H,"lineAt");function V(e){return e.replace(/\/\*[\s\S]*?\*\//g,t=>t.replace(/[^\n]/g," ")).replace(/(^|[^:])\/\/.*$/gm,t=>t.replace(/\/\/.*$/,r=>" ".repeat(r.length)))}l(V,"stripCommentsPreservingLines");function bt(e,t){let r=V(t),n=[],s=/\bcreateOrderPlane\s*(?:<[^>]*>)?\s*\(/g,o;for(;(o=s.exec(r))!==null;)n.push({file:e,line:H(t,o.index),callee:Rn});return n}l(bt,"extractArkOrderPlaneCallsFromSource");function Et(e,t){let r=V(t),n=[],s=/\.((?:update|patch|set|mutate))\s*\(/g,o;for(;(o=s.exec(r))!==null;){let i=o[1],a=r.slice(Math.max(0,o.index-80),o.index);!/\b(?:plane|orderPlane)\s*(?:\?|!)?$/.test(a)&&!/\bcreateOrderPlane\b/.test(r)||n.push({file:e,line:H(t,o.index),method:i})}return n}l(Et,"extractArkOrderGenericUpdatesFromSource");function St(e,t,r){if(r.length===0)return[];let n=V(t);if(!En(n)||!bn.test(n))return[];let s=[],o=new Set;for(let i of r){if(!i)continue;let a=new RegExp(`(?:\\b${re(i)}\\s*:\\s*(?!string\\b|number\\b|boolean\\b|null\\b|[A-Z])|['"]${re(i)}['"]\\s*:|[{\\,]\\s*${re(i)}\\s*[\\,}]|\\.${re(i)}\\s*=)`,"g"),c;for(;(c=a.exec(n))!==null;){let f=`${i}:${c.index}`;if(!o.has(f)){o.add(f),s.push({file:e,line:H(t,c.index),key:i});break}}}return s}l(St,"extractArkOrderXiFieldWritesFromSource");function It(e,t){let r=V(t),n=[],s=/(?:\b(?:xi|release|current|pattern|house)\w*|\.xi)\s*=\s*[^\n;]{0,160}?\bingest\s*\(/gi,o;for(;(o=s.exec(r))!==null;)n.push({file:e,line:H(t,o.index)});return n}l(It,"extractArkOrderIngestWritesXiFromSource");function xt(e,t){let r=V(t),n=[],s=/\.release\s*\(\s*\{([^}]*)\}/g,o;for(;(o=s.exec(r))!==null;){let a=(o[1]??"").match(/\b[A-Za-z_][\w]*\s*:/g)??[];a.length!==0&&n.push({file:e,line:H(t,o.index),keyCount:a.length})}return n}l(xt,"extractArkOrderReleaseKeyCountsFromSource");var wt=new Map;function _t(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}l(_t,"escapeAppliesToLiteral");function Sn(e){let t="";for(let r=0;r<e.length;r+=1){let n=e[r];if(n==="\\"&&r+1<e.length){let s=e[r+1];if("*?{}[],".includes(s)||s==="\\"){t+="\\"+s,r+=1;continue}t+="/";continue}t+=n}return t}l(Sn,"normalizeAppliesToGlob");function In(e){let t=0;for(let r=0;r<e.length;r+=1){let n=e[r];if(n==="\\"){r+=1;continue}if(n==="{")t+=1;else if(n==="}"&&(t-=1,t<0))return!1}return t===0}l(In,"appliesToBracesBalanced");function xn(e){let t=wt.get(e);if(t)return t;let r=Sn(e),n=In(r),s="",o=0;for(let a=0;a<r.length;a+=1){let c=r[a];c==="\\"&&a+1<r.length?(s+=_t(r[a+1]),a+=1):c==="*"?r[a+1]==="*"?r[a+2]==="/"?(s+="(?:.*/)?",a+=2):(s+=".*",a+=1):s+="[^/]*":c==="?"?s+="[^/]":c==="{"&&n?(s+="(?:",o+=1):c==="}"&&n&&o>0?(s+=")",o-=1):c===","&&n&&o>0?s+="|":s+=_t(c)}let i=new RegExp(`^${s}$`);return wt.set(e,i),i}l(xn,"globToRegExp");var Nt={"arkorder-missing-plane":"ARKORDER_MISSING_PLANE","arkorder-kernel-in-domain":"ARKORDER_KERNEL_IN_DOMAIN","arkorder-generic-update":"ARKORDER_GENERIC_UPDATE","arkorder-too-many-params":"ARKORDER_TOO_MANY_PARAMS","arkorder-ingest-writes-xi":"ARKORDER_INGEST_WRITES_XI","arkorder-xi-field-write":"ARKORDER_XI_FIELD_WRITE","arkorder-information-budget":"ARKORDER_INFORMATION_BUDGET","arkorder-xi-ttl":"ARKORDER_XI_TTL"};function wn(e,t){return!t||t.length===0?!0:t.some(r=>xn(r).test(e))}l(wn,"matchesArkOrderAppliesTo");function _n(e,t=[]){let r=e.trim();return/^domain(?:model)?$/i.test(r)||/^domain(?=[A-Z_\-\s])/i.test(r)?!0:t.some(n=>{let s=n.trim().replace(/\.+$/,"");return s==="Domain"||s.startsWith("Domain.")})}l(_n,"isDomainRoleLayer");function N(e,t,r,n,s,o,i){let a=e.mode==="enforced"&&i;return{ruleId:Nt[t],sensor:t,message:s,file:r,line:n,...o?.fromLayer?{fromLayer:o.fromLayer}:{},...o?.target?{target:o.target}:{},severity:a?"error":"warning",failsStrict:a,nextAction:K({ruleId:Nt[t],fromLayer:o?.fromLayer,target:o?.target})}}l(N,"finding");function Nn(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let r=te(e.classification),n=[],s=t.planeRoots;if(t.mode==="enforced"&&s.length===0)n.push(N(t,"arkorder-missing-plane","ark.config.json",1,"ArkOrder planeRoots is empty; no createOrderPlane site is declared.",void 0,r));else{let c=new Map;for(let f of e.planeRootHits){let d=c.get(f.matchedRoot)??[];d.push(f),c.set(f.matchedRoot,d)}for(let f of s){let d=c.get(f)??[];if(d.length===0){n.push(N(t,"arkorder-missing-plane","ark.config.json",1,`ArkOrder plane root ${JSON.stringify(f)} matched no governed files and has no createOrderPlane factory.`,{target:f},r));continue}d.some(u=>u.hasPlaneFactory)||n.push(N(t,"arkorder-missing-plane",d[0].file,1,`ArkOrder plane root ${JSON.stringify(f)} has no createOrderPlane factory.`,{target:f},r))}}let o=new Map(e.layers.map(c=>[c.name,c.intentPrefixes??[]]));for(let c of e.dependencies){let f=c.specifier;if(!f||!ne(f))continue;let d=e.layerForFile(c.from);d&&_n(d,o.get(d)??[])&&n.push(N(t,"arkorder-kernel-in-domain",c.from,c.line,"Domain-role layer imports arkgate/order; Domain stays plane-free.",{fromLayer:d,target:f},r))}for(let c of e.genericUpdates)n.push(N(t,"arkorder-generic-update",c.file,c.line,`Generic ${c.method}() on the order plane rewrites \u03BE; Haken forbids it.`,{target:c.method},r));let i=t.xiKeys??[];for(let c of e.releaseKeyCounts??[])c.keyCount<=t.maxXiKeys||n.push(N(t,"arkorder-too-many-params",c.file,c.line,`release() freezes ${c.keyCount} keys; maxXiKeys is ${t.maxXiKeys} (few slow modes).`,{target:String(c.keyCount)},r));for(let c of e.ingestWritesXi??[])n.push(N(t,"arkorder-ingest-writes-xi",c.file,c.line,"ingest() result is assigned into a Release or \u03BE store; ingest may absorb or escalate, never mint a pattern.",void 0,r));let a=new Set(t.managedLayers);for(let c of i.length===0?[]:e.xiFieldWrites??[]){let f=e.layerForFile(c.file);!f||!a.has(f)||wn(c.file,t.appliesTo)&&n.push(N(t,"arkorder-xi-field-write",c.file,c.line,`This file writes ${JSON.stringify(c.key)} the same way it would write a seat count. Take the event in, or change that choice through the valve (propose, then apply).`,{fromLayer:f,target:c.key},r))}return n.sort((c,f)=>c.file.localeCompare(f.file)||c.ruleId.localeCompare(f.ruleId)||c.line-f.line),{findings:n,completenessReasons:[]}}l(Nn,"evaluateArkOrderSensors");function Ct(e){if(!e.arkOrder)return[];let t=bt(e.file,e.source),r=Et(e.file,e.source),n=e.arkOrder.xiKeys??[];return Nn({arkOrder:e.arkOrder,layers:[],planeCalls:t,genericUpdates:r,planeRootHits:[],xiFieldWrites:St(e.file,e.source,n),ingestWritesXi:It(e.file,e.source),releaseKeyCounts:xt(e.file,e.source),dependencies:[],layerForFile:l(()=>e.fromLayer,"layerForFile")}).findings.filter(s=>s.sensor==="arkorder-generic-update"||s.sensor==="arkorder-kernel-in-domain"||s.sensor==="arkorder-xi-field-write"||s.sensor==="arkorder-ingest-writes-xi"||s.sensor==="arkorder-too-many-params")}l(Ct,"evaluateArkOrderEditorSensors");function Cn(e){let t=e;return t.sourceCode?.getText?.()??t.getSourceCode?.()?.getText?.()??""}l(Cn,"eslintSourceText");function Ot(e){function t(r){return{meta:{type:"problem",docs:{description:r},messages:{denied:"{{message}}"},schema:[]},create(n){let s=e.lintedFilename(n),o=e.findConfigPath(s),i=o?e.loadArkConfig(o):null;if(!i?.arkOrder)return{};let a=e.toProjectRelative(o,s);if(!e.sourceIsInAnalysisScope(i,a))return{};let c=S(a,i.layers);return{ImportDeclaration(f){let d=typeof f.source?.value=="string"?f.source.value:"";if(r==="ARKORDER_KERNEL_IN_DOMAIN"){if(!ne(d)||c!=="DomainModel"&&!/^domain/i.test(c??""))return;e.reportAdapterDiagnostic(n,f,"denied",{ruleId:r,file:a,line:f.loc?.start?.line??1,message:"Domain-role layer imports arkgate/order; Domain stays plane-free."})}},Program(){if(r!=="ARKORDER_GENERIC_UPDATE")return;let f=Cn(n),d=Ct({arkOrder:i.arkOrder,file:a,source:f,fromLayer:c}).filter(u=>u.ruleId!=="ARKORDER_KERNEL_IN_DOMAIN");for(let u of d)e.reportAdapterDiagnostic(n,{loc:{start:{line:u.line}}},"denied",{ruleId:u.ruleId,file:u.file,line:u.line,message:u.message})}}}}}return l(t,"createImportRule"),{noArkOrderKernelInDomain:t("ARKORDER_KERNEL_IN_DOMAIN"),noArkOrderGenericUpdate:t("ARKORDER_GENERIC_UPDATE")}}l(Ot,"createArkOrderEslintRules");function L(e){if(typeof e.physicalFilename=="string"&&e.physicalFilename.length>0)return e.physicalFilename;if(typeof e.filename=="string"&&e.filename.length>0)return e.filename;if(typeof e.getFilename=="function")try{let t=e.getFilename();if(typeof t=="string"&&t.length>0)return t}catch{}return""}l(L,"lintedFilename");function O(e,t,r,n,s){let o=nt({...n,line:n.line??t.loc?.start?.line,column:n.column??(typeof t.loc?.start?.column=="number"?t.loc.start.column+1:void 0)});return e.report({node:t,messageId:r,...s?{data:s}:{},diagnostic:o}),o}l(O,"reportAdapterDiagnostic");function B(e){if(!e||e==="<input>"||e.startsWith("stdin"))return null;let t=m.dirname(m.resolve(e));for(;;){let r=m.join(t,"ark.config.json");if(C.existsSync(r))return r;let n=m.dirname(t);if(n===t)return null;t=n}}l(B,"findConfigPath");var vt=new Map;function W(e){if(!C.existsSync(e))return null;let t=C.readFileSync(e,"utf8"),r=vt.get(e);if(r?.source===t)return r.config;let n=tt(t,e).config;return vt.set(e,{source:t,config:n}),n}l(W,"loadArkConfig");function z(e,t){return(e.include??[]).some(n=>{let s=String(n).replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/$/,"");return s==="."||t===s||t.startsWith(`${s}/`)})&&!Me(t,e)}l(z,"sourceIsInAnalysisScope");function Tt(e){let t=[e,`${e}.ts`,`${e}.tsx`,`${e}.mts`,`${e}.cts`,`${e}.js`,`${e}.jsx`,m.join(e,"index.ts"),m.join(e,"index.tsx"),m.join(e,"index.js")];for(let r of t)try{if(C.existsSync(r)&&C.statSync(r).isFile())return r}catch{}return null}l(Tt,"existingSourceFile");function On(e){let t=m.resolve(e),r=null;for(;;){let f=m.join(t,"tsconfig.json");if(C.existsSync(f)){r=f;break}let d=m.dirname(t);if(d===t)break;t=d}if(!r)return{baseUrl:e,aliases:[]};let n=l(f=>{try{let d=C.readFileSync(f,"utf8");return d=d.replace(/\/\*[\s\S]*?\*\//g,"").replace(/(^|[^:])\/\/.*$/gm,"$1"),JSON.parse(d)}catch{return null}},"loadJsonc"),s=l((f,d)=>{if(d>4)return{};let u=n(f);if(!u)return{};let p=u.compilerOptions??{},g=p.baseUrl,y=p.paths,R=u.extends;if(typeof R=="string"&&!R.startsWith("@")){let k=m.resolve(m.dirname(f),R.endsWith(".json")?R:`${R}.json`);if(C.existsSync(k)){let b=s(k,d+1);g=g??b.baseUrl,y={...b.paths??{},...y??{}}}}return{baseUrl:g,paths:y}},"mergePaths"),o=s(r,0),i=m.dirname(r),a=m.resolve(i,o.baseUrl||"."),c=[];for(let[f,d]of Object.entries(o.paths||{})){if(!Array.isArray(d)||d.length===0)continue;let u=f.replace(/\*$/,"");u&&c.push({from:u,to:String(d[0]).replace(/\*$/,"")})}return c.sort((f,d)=>d.from.length-f.from.length),{baseUrl:a,aliases:c}}l(On,"readTsconfigPathAliases");function vn(e,t){if(!t.startsWith("."))return null;let r=m.resolve(m.dirname(e),t);return Tt(r)}l(vn,"resolveRelativeImport");function Lt(e,t,r){if(!t)return null;if(t.startsWith("."))return vn(e,t);let n=r||m.dirname(e),{baseUrl:s,aliases:o}=On(n),i=o.find(c=>t.startsWith(c.from));if(!i)return null;let a=m.resolve(s,`${i.to}${t.slice(i.from.length)}`);return Tt(a)}l(Lt,"resolveImportSpecifier");function oe(e){return typeof e?.value=="string"?e.value:void 0}l(oe,"stringValue");function we(e){return e?.name??oe(e)}l(we,"propertyName");function _e(e){return e.sourceCode??e.getSourceCode?.()}l(_e,"sourceCodeFor");function Dt(e,t){let r=_e(e)?.getScope?.(t);for(;r;){let n=r.references?.find(s=>s.identifier===t);if(n)return n;r=r.upper??void 0}}l(Dt,"referenceFor");function G(e,t,r){let n=Dt(e,t);if(n?.resolved)return(n.resolved.defs?.length??0)>0;let s=_e(e)?.getScope?.(t);for(;s;){let o=s.set?.get(r);if(o)return(o.defs?.length??0)>0;s=s.upper??void 0}return!1}l(G,"isLocallyBound");function Tn(e,t){let r=Dt(e,t);return r?r.isValueReference!==!1:t.parent?.type==="VariableDeclarator"&&t.parent.init===t}l(Tn,"isValueIdentifierReference");function Ft(e){if(e?.type==="Identifier"&&e.name)return{root:e,segments:[e.name]};if(!e||!(e.type==="MemberExpression"||!!(e.object&&e.property))||e.computed===!0)return;let r=Ft(e.object),n=we(e.property);if(!(!r||!n))return{root:r.root,segments:[...r.segments,n]}}l(Ft,"memberExpressionPath");function Ln(e){return we(e.callee?.property)}l(Ln,"calleePropertyName");function Pt(e,t){return e?.properties?.find(r=>we(r.key)===t)}l(Pt,"objectProperty");function se(e,t){return Pt(e,t)!==void 0}l(se,"objectHasProperty");function Dn(e){let t=Pt(e,"metadata")?.value;return se(t,"source")}l(Dn,"objectHasMetadataSource");function Kt(e){return Ln(e)==="publish"}l(Kt,"isPublishCall");function Ie(e){if(e.importKind==="type"||e.exportKind==="type")return!0;let t=e.specifiers??[];return t.length===0?!1:t.every(r=>r.type==="ImportSpecifier")?t.every(r=>r.importKind==="type"):t.every(r=>r.exportKind==="type")}l(Ie,"declarationIsTypeOnly");function Fn(e){let t=e;for(;t?.parent;)t=t.parent;return t?.type==="Program"?t:void 0}l(Fn,"containingProgram");function Pn(e){let t=Fn(e)?.body;if(!t)return!1;let r=!1;for(let n of t){if(n.type==="ImportDeclaration"){if(!Ie(n))return!1;continue}if(!(n.type==="TSInterfaceDeclaration"||n.type==="TSTypeAliasDeclaration")){if(n.type==="ExportNamedDeclaration"){if(n.declaration){if(n.declaration.type!=="TSInterfaceDeclaration"&&n.declaration.type!=="TSTypeAliasDeclaration")return!1}else if(!Ie(n))return!1;r=!0;continue}return!1}}return r}l(Pn,"sourceProgramExportsOnlyTypes");var Kn={meta:{type:"problem",docs:{description:"Disallow imports that violate ark.config.json layer rules (same contract as arkgate-check)."},messages:{forbiddenImport:"Architecture: {{fromLayer}} must not import {{toLayer}} (ark.config.json). Specifier: {{specifier}}",forbiddenImportHeuristic:"Domain code must not import infrastructure, adapters, repositories, or database modules."},schema:[]},create(e){let t=L(e),r=B(t),n=r?W(r):null,s=r?m.dirname(r):null,o=l(i=>{let a=oe(i.source);if(a&&n&&s&&t){let c=m.isAbsolute(t)?t:m.resolve(t),f=m.relative(s,c).split(m.sep).join("/");if(!z(n,f))return;let d=S(f,n.layers);if(!d)return;let u=Lt(c,a,s);if(!u)return;let p=m.relative(s,u).split(m.sep).join("/");if(p.startsWith(".."))return;let g=S(p,n.layers);if(!g)return;let y={fromPath:f,toPath:p,layers:n.layers},R=ae(n.rules,d,g,y),k=R?.rule;if(k){let b=i.type?.startsWith("Export")?"export":"import",q=Ie(i),D=!!k?.peerIsolation,ie=q&&!D,F=D&&R?Ke(R.peerIsolationReason??"cross-slice",{fromPath:f,toPath:p,fromSlice:R.fromSlice,toSlice:R.toSlice}):void 0,A=k?.message?F?`${k.message} (${F})`:k.message:F?`${d} must not ${b} another slice of ${g} (${f} \u2192 ${p}): ${F}`:`${d} must not ${b} ${g}.`;O(e,i,"forbiddenImport",{ruleId:"LAYER_IMPORT_VIOLATION",file:f,fromLayer:d,toLayer:g,target:p,edgeKind:b,...D?{peerIsolation:!0}:{},...q?{typeOnly:!0}:{},...ie?{severity:"warning"}:{},...Pn(i)?{sourcePureTypeModule:!0}:{},message:ie?`${A} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:A},{fromLayer:d,toLayer:g,specifier:a})}return}},"check");return{ImportDeclaration:o,ExportNamedDeclaration:o,ExportAllDeclaration:o}}},Mn={meta:{type:"problem",docs:{description:"Require event bus publish calls to use registered intent creators instead of raw event objects or intent strings."},messages:{rawPublish:"Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts."},schema:[]},create(e){return{CallExpression(t){let r=t.arguments?.[0],n=oe(r),s=he({publishCall:Kt(t),rawIntentName:n,objectHasIntent:se(r,"intent"),arkPublishCandidate:!1,hasSource:!0});if(s.some(o=>o.ruleId==="RAW_EVENT_PUBLISH")){let o=s.find(i=>i.ruleId==="RAW_EVENT_PUBLISH");O(e,t,"rawPublish",{...o,file:L(e)})}}}}},$n={meta:{type:"problem",docs:{description:"Require event bus publish calls to include source metadata."},messages:{missingSource:"Strict Ark publish calls must include metadata.source."},schema:[]},create(e){return{CallExpression(t){let r=t.arguments?.[0],n=t.arguments?.[2],o=he({publishCall:Kt(t),rawIntentName:oe(r),objectHasIntent:se(r,"intent"),arkPublishCandidate:!0,hasSource:Dn(r)||se(n,"source")}).find(i=>i.ruleId==="PUBLISH_MISSING_SOURCE");o&&O(e,t,"missingSource",{...o,file:L(e)})}}}},Un={meta:{type:"problem",docs:{description:"Disallow ambient globals from the layer\u2019s forbiddenGlobals in ark.config.json (same purity surface as ark-check). Option `globals` is a standalone fallback when no project config applies."},messages:{forbiddenGlobal:'Ambient global "{{name}}" is forbidden in {{layer}} (ark.config.json); inject the capability through a port instead.',forbiddenGlobalDefault:'Ambient global "{{name}}" is forbidden here; inject the capability through a port instead.',forbiddenModule:'{{layer}} must not use module "{{specifier}}" because it is the import form of forbidden global "{{name}}".'},schema:[{type:"object",properties:{globals:{type:"array",items:{type:"string"}}},additionalProperties:!1}]},create(e){let t=L(e),r=e.options?.[0],n=B(t),s=n?W(n):null,o=n?m.dirname(n):null,i=null,a="this layer";if(s&&o&&t){let u=m.isAbsolute(t)?t:m.resolve(t),p=m.relative(o,u).split(m.sep).join("/");if(!z(s,p))return{};let g=s.layers?.find(y=>y.name===S(p,s.layers));g?.forbiddenGlobals?.length?(i=new Set(g.forbiddenGlobals),a=g.name):i=null}else r?.globals&&(i=new Set(r.globals));if(!i)return{};let c=typeof _e(e)?.getScope=="function",f=l((u,p)=>{let g=m.isAbsolute(t)?t:m.resolve(t),y=o?m.relative(o,g).split(m.sep).join("/"):t;O(e,u,s?"forbiddenGlobal":"forbiddenGlobalDefault",{ruleId:"FORBIDDEN_GLOBAL",file:y,fromLayer:a,target:p,message:`${a} must not use the ambient global "${p}".`},{name:p,layer:a})},"report"),d=l((u,p,g,y)=>{if(g||typeof p!="string")return;let R=ce(p,i);if(!R)return;let k=m.isAbsolute(t)?t:m.resolve(t),b=o?m.relative(o,k).split(m.sep).join("/"):t;O(e,u,"forbiddenModule",{ruleId:"FORBIDDEN_GLOBAL",file:b,fromLayer:a,target:p,edgeKind:y,message:`${a} must not use module "${p}" because it is the import form of forbidden global "${R}".`},{layer:a,name:R,specifier:p,importKind:y})},"reportModule");return{MemberExpression(u){if(u.parent?.type==="MemberExpression"&&u.parent.object===u)return;let p=Ft(u);if(!p||G(e,p.root,p.segments[0]))return;let g=p.segments[0]==="globalThis",y=g?p.segments.slice(1):p.segments,R;for(let k=y.length;k>=(g?1:2);k-=1){let b=y.slice(0,k).join(".");if(i.has(b)){R=b;break}}R?f(u,R):!c&&i.has(p.segments[0])&&f(u,p.segments[0])},CallExpression(u){let p=u;if(p.callee?.type==="Identifier"&&p.callee.name==="require"&&p.arguments?.[0]?.type==="Literal"&&!G(e,u,"require")&&d(u,p.arguments[0].value,!1,"require"),c)return;let g=p.callee?.type==="Identifier"?p.callee.name:void 0;g&&i.has(g)&&f(u,g)},ImportDeclaration(u){let p=u,g=(p.specifiers??[]).filter(R=>R.type==="ImportSpecifier"),y=g.length>0&&g.length===(p.specifiers??[]).length&&g.every(R=>R.importKind==="type");d(u,p.source?.value,p.importKind==="type"||y,"import")},ImportExpression(u){let p=u;p.source?.type==="Literal"&&d(u,p.source.value,!1,"dynamic-import")},TSImportEqualsDeclaration(u){let p=u;d(u,p.moduleReference?.expression?.value,p.importKind==="type"||p.isTypeOnly===!0,"require")},ExportNamedDeclaration(u){let p=u;if(!p.source)return;let g=p.specifiers??[],y=g.length>0&&g.every(R=>R.exportKind==="type");d(u,p.source.value,p.exportKind==="type"||y,"export")},ExportAllDeclaration(u){let p=u;d(u,p.source?.value,p.exportKind==="type","export")},NewExpression(u){if(c)return;let p=u.callee?.type==="Identifier"?u.callee.name:void 0;p&&i.has(p)&&f(u,p)},Identifier(u){!c||!u.name||!i.has(u.name)||!Tn(e,u)||G(e,u,u.name)||f(u,u.name)}}}},jn={meta:{type:"problem",docs:{description:"Disallow importing modules whose effect capability the layer denies (ark.config.json capabilities.deny / pure \u2014 same wall surface as ark-check). Import dimension only: ambient globals stay with no-forbidden-globals and the CLI/hook symbol path."},messages:{deniedCapability:'{{layer}} denies the {{capability}} capability (ark.config.json); "{{specifier}}" imports it. Define a port and bind the implementation in an adapter layer.'},schema:[]},create(e){let t=L(e),r=B(t),n=r?W(r):null,s=r?m.dirname(r):null;if(!n||!s||!t)return{};let o=m.isAbsolute(t)?t:m.resolve(t),i=m.relative(s,o).split(m.sep).join("/");if(!z(n,i))return{};let a=n.layers?.find(d=>d.name===S(i,n.layers));if(!a)return{};let c=new Set(je(a));if(c.size===0)return{};let f=l((d,u,p,g)=>{if(p||typeof u!="string"||ce(u,a.forbiddenGlobals??[]))return;let y=Ue(u);!y||!c.has(y)||O(e,d,"deniedCapability",{ruleId:"CAPABILITY_VIOLATION",file:i,fromLayer:a.name,target:u,capability:y,edgeKind:g,message:`${a.name} denies the ${y} capability; found import of "${u}".`},{layer:a.name,capability:y,specifier:u})},"check");return{ImportDeclaration(d){let u=d,p=(u.specifiers??[]).filter(y=>y.type==="ImportSpecifier"),g=p.length>0&&p.length===(u.specifiers??[]).length&&p.every(y=>y.importKind==="type");f(d,u.source?.value,u.importKind==="type"||g,"import")},ImportExpression(d){let u=d;u.source?.type==="Literal"&&f(d,u.source.value,!1,"dynamic-import")},TSImportEqualsDeclaration(d){let u=d;f(d,u.moduleReference?.expression?.value,u.importKind==="type"||u.isTypeOnly===!0,"require")},ExportNamedDeclaration(d){let u=d;if(!u.source)return;let p=u.specifiers??[],g=p.length>0&&p.every(y=>y.exportKind==="type");f(d,u.source.value,u.exportKind==="type"||g,"export")},ExportAllDeclaration(d){let u=d;f(d,u.source?.value,u.exportKind==="type","export")},CallExpression(d){let u=d;u.callee?.type==="Identifier"&&u.callee.name==="require"&&u.arguments?.[0]?.type==="Literal"&&!G(e,d,"require")&&f(d,u.arguments[0].value,!1,"require")}}}},{noArkRunKernelInDomain:Hn,noArkRunDirectNew:Vn,noArkRunTransportBypass:Gn}=kt({findConfigPath:B,loadArkConfig:W,resolveImportSpecifier:Lt,lintedFilename:L,sourceIsInAnalysisScope:z,isLocallyBound:G,reportAdapterDiagnostic:O});function Bn(e,t){let r=m.dirname(m.resolve(e));return m.relative(r,m.resolve(t)).split(m.sep).join("/")}l(Bn,"toProjectRelative");var{noArkOrderKernelInDomain:Wn,noArkOrderGenericUpdate:zn}=Ot({findConfigPath:B,loadArkConfig:W,lintedFilename:L,sourceIsInAnalysisScope:z,reportAdapterDiagnostic:O,toProjectRelative:Bn});var qn={"no-domain-infra-imports":Kn,"no-raw-event-publish":Mn,"require-publish-source":$n,"no-forbidden-globals":Un,"no-denied-capabilities":jn,"no-arkrun-kernel-in-domain":Hn,"no-arkrun-direct-new":Vn,"no-arkrun-transport-bypass":Gn,"no-arkorder-kernel-in-domain":Wn,"no-arkorder-generic-update":zn},xe={rules:qn};xe.configs={recommended:{plugins:{ark:xe},rules:{"ark/no-domain-infra-imports":"error","ark/no-raw-event-publish":"error","ark/require-publish-source":"error","ark/no-forbidden-globals":"error","ark/no-denied-capabilities":"error","ark/no-arkrun-kernel-in-domain":"error","ark/no-arkrun-direct-new":"error","ark/no-arkrun-transport-bypass":"error","ark/no-arkorder-kernel-in-domain":"error","ark/no-arkorder-generic-update":"error"}}};var yo=xe;export{yo as default,B as findConfigPath,_ as globToRegExp,Jt as isEdgeDenied,S as layerForRelativePath,W as loadArkConfig,zn as noArkOrderGenericUpdate,Wn as noArkOrderKernelInDomain,Vn as noArkRunDirectNew,Hn as noArkRunKernelInDomain,Gn as noArkRunTransportBypass,jn as noDeniedCapabilities,Kn as noDomainInfraImports,Un as noForbiddenGlobals,Mn as noRawEventPublish,De as patternSpecificity,xe as plugin,On as readTsconfigPathAliases,$n as requirePublishSource,Lt as resolveImportSpecifier,vn as resolveRelativeImport};
3
+ `)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=r}};function et(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}l(et,"isObject");function X(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}l(X,"propertyPath");function P(e){return e===null?"null":Array.isArray(e)?"array":typeof e}l(P,"valueType");function cr(e,t){let r="#/$defs/";if(e.startsWith(r))return t.$defs[e.slice(r.length)]}l(cr,"resolveSchemaRef");function U(e,t,r,n,s){if(t.$ref){let o=cr(t.$ref,n);if(!o){s.push({path:r,message:`schema reference ${t.$ref} cannot be resolved`});return}U(e,o,r,n,s);return}if(t.const!==void 0&&!Object.is(e,t.const)){s.push({path:r,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(o=>Object.is(o,e))){s.push({path:r,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!et(e)){s.push({path:r,message:`must be an object; received ${P(e)}`});return}let o=t.properties??{};for(let i of t.required??[])e[i]===void 0&&s.push({path:X(r,i),message:"is required"});if(t.additionalProperties===!1)for(let i of Object.keys(e))i in o||s.push({path:X(r,i),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let i=t.additionalProperties;for(let a of Object.keys(e))a in o||U(e[a],i,X(r,a),n,s)}for(let[i,a]of Object.entries(o))e[i]!==void 0&&U(e[i],a,X(r,i),n,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:r,message:`must be an array; received ${P(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&s.push({path:r,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let o=e.map(i=>JSON.stringify(i));new Set(o).size!==o.length&&s.push({path:r,message:"must not contain duplicate items"})}t.items&&e.forEach((o,i)=>U(o,t.items,`${r}[${i}]`,n,s));return}if(t.type==="string"){if(typeof e!="string"){s.push({path:r,message:`must be a string; received ${P(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&s.push({path:r,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&s.push({path:r,message:`must be a boolean; received ${P(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){s.push({path:r,message:`must be an integer; received ${P(e)}`});return}t.minimum!==void 0&&e<t.minimum&&s.push({path:r,message:`must be at least ${t.minimum}`})}}l(U,"validateNode");function dr(e,t){let r=e.layers;Array.isArray(r)&&r.forEach((n,s)=>{if(!n||typeof n!="object"||Array.isArray(n)||!("owners"in n))return;let o=n.owners;Array.isArray(o)&&o.forEach((i,a)=>{typeof i=="string"&&(Ye(i)||t.push({path:`$.layers[${s}].owners[${a}]`,message:"must be a GitHub handle or email (not a display name)"}))})})}l(dr,"validateLayerOwners");function ur(e){let t={...e,$schema:e.$schema===void 0?ue:e.$schema,schemaVersion:e.schemaVersion===void 0?I:e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?Qe.map(r=>({...r})):e.rules};return e.arkRun!==void 0&&(t.arkRun=Be(e.arkRun)),e.arkOrder!==void 0&&(t.arkOrder=We(e.arkOrder)),t}l(ur,"defaultedConfig");function fr(e){return e===I?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}l(fr,"migratedFromOf");function pr(){let e=new Set([I]);for(let t of fe)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}l(pr,"knownInputVersions");function gr(e,t="ark.config.json"){if(!et(e))throw new x(t,[{path:"$",message:`must be an object; received ${P(e)}`}]);let r=pr(),n=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(n===null)throw new x(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected ${I}`}]);if(n!=="unversioned"&&!r.has(n))throw new x(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(n)}; expected ${I}`}]);let s=n,o={...e},i=0;for(;s!==I&&i<fe.length+1;){i+=1;let a=fe.find(c=>c.from===s);if(!a)throw new x(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(s)}; expected ${I}`}]);s=a.to,o.schemaVersion=s}if(s!==I)throw new x(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(n)}; expected ${I}`}]);return{candidate:ur(o),migratedFrom:fr(n)}}l(gr,"migrateArkConfig");function mr(e,t="ark.config.json"){let{candidate:r,migratedFrom:n}=gr(e,t),s=[];if(U(r,Je,"$",Je,s),ze(r,s),qe(r,s),dr(r,s),s.length>0)throw new x(t,s);return{config:r,migratedFrom:n}}l(mr,"loadArkConfigContract");function tt(e,t="ark.config.json"){let r;try{r=JSON.parse(e)}catch(n){throw new x(t,[{path:"$",message:`invalid JSON: ${n instanceof Error?n.message:String(n)}`}])}return mr(r,t)}l(tt,"parseArkConfigJson");var yr=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,hr=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,Rr=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function Ar(e,t){let r=String(e??"").replace(/\\/g,"/").trim(),n=String(t?.fromLayer??""),s=String(t?.toLayer??"");return yr.test(r)?"pure-shared":n==="PersistenceAdapters"&&(hr.test(r)||/events?|intents?|kernel|bootstrap/i.test(`${s} ${r}`))?"kernel-emit":Rr.test(r)||(n==="DomainModel"||n==="ApplicationOrchestration")&&s==="PersistenceAdapters"?"use-case":"unknown"}l(Ar,"classifyLayerImportKind");function kr(e){if(e.typeOnly||e.targetTypeOnlyExports||e.namedBindingsTypeOnly)return"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.";if(e.peerIsolation)return"Extract the shared dependency to a shared layer, test at the public interface, then preflight again.";let t=Ar(typeof e.target=="string"?e.target:"",{fromLayer:typeof e.fromLayer=="string"?e.fromLayer:void 0,toLayer:typeof e.toLayer=="string"?e.toLayer:void 0});return t==="pure-shared"?"Adopt the imported constants/types/pure module into DomainModel or SharedKernel (do not inject a port). Then preflight again.":t==="kernel-emit"?"Persistence must not emit. Inject a port or move the event map to SharedTypes; do not import kernel/events/bootstrap from a repository. Then preflight again.":t==="use-case"||e.portProofEligible?`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, test at the public interface, then preflight again.`:"Classify the import: if it is constants/types/pure, adopt into DomainModel or SharedKernel; define a port only if the target is a real use-case. Then preflight again."}l(kr,"layerImportNextAction");function br(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}l(br,"arkRunCallSiteName");function Er(e){let t=br(e),r=typeof e.fromLayer=="string"&&e.fromLayer.length>0?e.fromLayer:void 0;switch(e.ruleId){case"ARKRUN_MISSING_ROOT":return t?`Import createStrictArkKernel from arkgate/runtime and call it in composition root ${t} listed in arkRun.compositionRoots, then preflight again.`:"Import createStrictArkKernel from arkgate/runtime (same npm package; @arkgate/runtime is deprecated) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKRUN_KERNEL_IN_DOMAIN":return t?`Move the kernel import of ${t} out of ${r??"the Domain-role layer"} into a composition root or adapter. Import from arkgate/runtime, then preflight again.`:"Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from arkgate/runtime (same npm package; @arkgate/runtime is deprecated), then preflight again. Never mechanical-safe.";case"ARKRUN_DIRECT_NEW":return t?`Resolve ${t} from the kernel instead of constructing it with new, then preflight again.`:"Resolve the type from the kernel instead of constructing it with new, then preflight again. Never mechanical-safe \u2014 rewiring construction is a design decision.";case"ARKRUN_UNDECLARED_EMIT":return t?`Add ${t} to raises or sends on the managed component, then preflight again.`:"Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment.";case"ARKRUN_UNDECLARED_HANDLE":return t?`Add ${t} to reactsTo on the managed component, then preflight again.`:"Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment.";case"ARKRUN_UNDECLARED_DEPEND":return t?`Add ${t} to uses on the managed component, then preflight again.`:"Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment.";case"ARKRUN_TRANSPORT_BYPASS":return t?`Send through the ArkRun kernel transport instead of importing ${t}, then preflight again.`:"Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe \u2014 homemade buses stay judgment.";default:return`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}l(Er,"arkRunNextAction");function K(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return kr(e);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"LITERAL_PATH_DRIFT":return typeof e.target=="string"&&e.target.length>0?`Rewrite the literal to ${e.target}, or run \`arkgate-check --path-drift --base-ref <ref> --write\` to apply every anchored replacement.`:"Rewrite the literal to the rename destination, or run `arkgate-check --path-drift --base-ref <ref> --write` to apply every anchored replacement.";case"LITERAL_PATH_UNRESOLVED":return"Read the candidate and decide: fix the path, or leave it. Advisory \u2014 with no rename to anchor it there is no destination to propose, so --write never touches it.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";case"INVARIANT_COVERAGE_OUTSIDE_ROOTS":return"Move the covering test under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json, then run Ark again.";case"INVARIANT_CATALOG_EMPTY":return typeof e.file=="string"&&e.file.length>0?`Add 1\u20132 short phrases to invariants[] in ${e.file}, then run ark-check --doctor. Starters show the shape.`:"Add 1\u20132 short phrases to invariants[] in arkrules/<Domain>.json, then run ark-check --doctor. Starters show the shape.";case"INVARIANT_TESTS_PATH_MISSING":return"Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present.";case"INVARIANT_COVERAGE_ROOTS_MISSING":return"Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. An enforced invariant fails closed until that path is present.";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.`;case"ARKRUN_MISSING_ROOT":case"ARKRUN_KERNEL_IN_DOMAIN":case"ARKRUN_DIRECT_NEW":case"ARKRUN_UNDECLARED_EMIT":case"ARKRUN_UNDECLARED_HANDLE":case"ARKRUN_UNDECLARED_DEPEND":case"ARKRUN_TRANSPORT_BYPASS":return Er(e);case"ARKORDER_MISSING_PLANE":return typeof e.target=="string"&&e.target.length>0?`Import createOrderPlane from arkgate/order and call it in plane root ${e.target} listed in arkOrder.planeRoots, then preflight again.`:"Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKORDER_KERNEL_IN_DOMAIN":return"Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe.";case"ARKORDER_GENERIC_UPDATE":return"Don't use a generic update. First freeze with release(). Later, propose the change, then apply it.";case"ARKORDER_TOO_MANY_PARAMS":return"Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe.";case"ARKORDER_INGEST_WRITES_XI":return"Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe.";case"ARKORDER_XI_FIELD_WRITE":return typeof e.target=="string"&&e.target.length>0?`Don't write ${e.target} from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.`:"Don't write a named product choice from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.";case"ARKORDER_UNVALVED_RELEASE":return"Change the choice with proposeRelease then apply. release() is only the first freeze. Never mechanical-safe.";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.`}}l(K,"deterministicNextAction");var pe="docs/diagnostics.md";function ge(e){let t=typeof e.ruleId=="string"?e.ruleId:typeof e.code=="string"?e.code:void 0,r=typeof e.file=="string"?e.file:void 0,n=typeof e.fromLayer=="string"?e.fromLayer:void 0,s=typeof e.toLayer=="string"?e.toLayer:void 0,o=typeof e.target=="string"?e.target:void 0;return[t,r,n??"",s??"",o??""].join("|")}l(ge,"adapterFindingTargetKey");function me(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}l(me,"adapterFindingRefFromTargetKey");function ye(e){return`${pe}#${e}`}l(ye,"adapterDocsCodePath");function h(e){return typeof e=="string"&&e.length>0?e:void 0}l(h,"text");function rt(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}l(rt,"positiveInteger");function xr(e,t,r){return K({ruleId:e,target:h(t.target)??h(r.target)??void 0,fromLayer:h(t.fromLayer)??void 0,toLayer:h(t.toLayer)??void 0,typeOnly:t.typeOnly===!0,targetTypeOnlyExports:t.targetTypeOnlyExports===!0,namedBindingsTypeOnly:t.namedBindingsTypeOnly===!0,portProofEligible:t.portProofEligible===!0,peerIsolation:t.peerIsolation===!0,sourcePureTypeModule:t.sourcePureTypeModule===!0,edgeKind:h(t.edgeKind)??void 0,capability:h(t.capability)??h(r.capability)??void 0,arkruleId:h(t.arkruleId)??void 0,arkruleSource:h(t.arkruleSource)??void 0})}l(xr,"nextActionForDiagnostic");function nt(e,t="error",r){let n=h(e.ruleId)??h(e.code)??"ARK_UNKNOWN",s=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,o={...h(e.target)?{target:h(e.target)}:{},...h(e.fromLayer)?{fromLayer:h(e.fromLayer)}:{},...h(e.toLayer)?{toLayer:h(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{},...typeof e.targetTypeOnlyExports=="boolean"?{targetTypeOnlyExports:e.targetTypeOnlyExports}:{},...typeof e.sourcePureTypeModule=="boolean"?{sourcePureTypeModule:e.sourcePureTypeModule}:{},...typeof e.namedBindingsTypeOnly=="boolean"?{namedBindingsTypeOnly:e.namedBindingsTypeOnly}:{},...typeof e.portProofEligible=="boolean"?{portProofEligible:e.portProofEligible}:{},...typeof e.peerIsolation=="boolean"?{peerIsolation:e.peerIsolation}:{},...h(e.capability)?{capability:h(e.capability)}:{},...h(e.edgeKind)?{edgeKind:h(e.edgeKind)}:{},...h(e.arkruleId)?{arkruleId:h(e.arkruleId)}:{},...h(e.arkruleSource)?{arkruleSource:h(e.arkruleSource)}:{}},i=r??ge(e),a=me(i);return{ruleId:n,severity:s,message:h(e.message)??n,location:{file:h(e.file)??"<unknown>",line:rt(e.line,1),column:rt(e.column,1)},evidence:o,nextAction:h(e.nextAction)??xr(n,o,e),findingRef:a,targetKey:i,docsCodePath:ye(n)}}l(nt,"toAdapterDiagnostic");var st={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."},Ss=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 wr(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}l(wr,"looksLikeArkIntent");function he(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&wr(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:st.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:st.PUBLISH_MISSING_SOURCE}),t}l(he,"classifyPublishFacts");import yt from"fs";import T from"path";var _r=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"];var Nr=new Set(_r),Cr=new Set(["AggregateError","Array","ArrayBuffer","BigInt64Array","BigUint64Array","Boolean","DataView","Date","Error","EvalError","FinalizationRegistry","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Number","Object","Promise","Proxy","RangeError","ReferenceError","RegExp","Set","SharedArrayBuffer","String","Symbol","SyntaxError","TypeError","URIError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","WeakRef","WeakSet"]),Or=new Set(["Array","Atomics","Buffer","JSON","Math","Number","Object","Promise","Reflect","String","console","fs","path","url","util"]);function $(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")}l($,"isArkRunKernelModuleSpecifier");var vr=["events","node:events","eventemitter2","eventemitter3","emittery","kafkajs","kafka-node","amqplib","amqp","bull","bullmq","mqtt","nats","@aws-sdk/client-sqs","@aws-sdk/client-sns","@aws-sdk/client-eventbridge","@google-cloud/pubsub","@azure/service-bus"],Re=new Set(vr);function at(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(Re.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let r=e.slice(0,t);if(Re.has(r))return!0;let n=e.indexOf("/",t+1);return n<0?!1:Re.has(e.slice(0,n))}l(at,"isArkRunTransportBypassSpecifier");function ot(e){if(Nr.has(e))return"factory";switch(e){case"publisher":return"publisher";case"publish":return"publish";case"raise":case"raiseAsync":return"raise";case"send":case"sendTo":return"send";case"subscribe":return"subscribe";case"registerHandler":return"register-handler";case"resolve":return"resolve";case"resolveSingleton":return"resolve-singleton";default:return}}l(ot,"arkRunKernelCallKind");function lt(e,t){let r=1;for(let n=0;n<t;n+=1)e.charCodeAt(n)===10&&(r+=1);return r}l(lt,"lineAt");function Ae(e){return e.replace(/\/\*[\s\S]*?\*\//g,t=>t.replace(/[^\n]/g," ")).replace(/(^|[^:\\])\/\/.*$/gm,t=>t.replace(/\/\/.*$/,r=>" ".repeat(r.length)))}l(Ae,"stripCommentsPreservingLines");function Tr(e,t){let r=e.slice(t),n=/^\s*(['"])((?:\\.|[^\\])*?)\1/.exec(r);if(!n)return;let s=n[2]??"";return s.length>0?s:void 0}l(Tr,"firstStringLiteralArg");function it(e,t,r){let n=Math.max(0,t-r.length-8),s=e.slice(n,t);return new RegExp(`\\b${r}\\s+$`).test(s)}l(it,"keywordBefore");function J(e,t){let r=/\b(?:import|export)(\s+type)?\s+([\s\S]*?)\s+from\s*['"]([^'"]+)['"]/g,n;for(;(n=r.exec(e))!==null;)n[1]||t(n[2]??"",n[3]??"")}l(J,"parseValueImportClause");function ct(e,t){J(Ae(e),t)}l(ct,"forEachArkRunValueImportClause");function Lr(e){let t=new Map,r=new Set;return J(e,(n,s)=>{if(!$(s))return;let o=/\*\s+as\s+([A-Za-z_][A-Za-z0-9_]*)/.exec(n);o?.[1]&&r.add(o[1]);let i=/^([A-Za-z_][A-Za-z0-9_]*)\s*(?:,|$)/.exec(n.trim());i?.[1]&&t.set(i[1],i[1]);let a=/\{([^}]*)\}/.exec(n);if(a?.[1])for(let c of a[1].split(",")){let f=c.trim();if(!f||f.startsWith("type "))continue;let d=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(f);if(d){t.set(d[2],d[1]);continue}let u=/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(f);u?.[1]&&t.set(u[1],u[1])}}),{named:t,namespaces:r}}l(Lr,"collectKernelImportBindings");function Dr(e,t){let r=new Set(t);return J(e,(n,s)=>{let o=/\{([^}]*)\}/.exec(n);if(o?.[1])for(let i of o[1].split(",")){let a=i.trim();if(!a||a.startsWith("type "))continue;let c=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(a),f=c?.[2]??/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(a)?.[1],d=c?.[1]??f;!f||!d||!/^[A-Z]/.test(d)||($(s)||t.has(d)||t.has(f))&&(r.add(f),r.add(d))}}),r}l(Dr,"collectImportedConstructors");function Fr(e,t){let r;return J(e,(n,s)=>{!r&&new RegExp(`\\b${t}\\b`).test(n)&&(r=s)}),r}l(Fr,"importedFromForName");function Q(e,t){let r=Ae(t),n=Lr(r),s=[],o=/\b([A-Za-z_][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,i;for(;(i=o.exec(r))!==null;){let a=i[1],c=i.index;if(it(r,c,"function")||it(r,c,"class"))continue;let d=r.slice(0,c).match(/([A-Za-z_][A-Za-z0-9_]*)\s*\.\s*$/)?.[1],u=n.named.get(a)??a,p=ot(u)??ot(a);if(!p)continue;let g=n.named.has(a)||d!==void 0&&n.namespaces.has(d);if(p!=="factory"&&(!g&&d===void 0||d&&Or.has(d)&&!g))continue;let y=Tr(r,c+i[0].length);s.push({file:e,line:lt(t,c),kind:p,callee:a,viaImport:g,...d?{receiver:d}:{},...y?{nameLiteral:y}:{}})}return s}l(Q,"extractArkRunKernelCallsFromSource");function ke(e,t,r){let n=Ae(t),s=Dr(n,r),o=[],i=/\bnew\s+(?:[A-Za-z_][A-Za-z0-9_]*\s*\.\s*)*([A-Z][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,a;for(;(a=i.exec(n))!==null;){let c=a[1];if(Cr.has(c)||!s.has(c))continue;let f=Fr(n,c);o.push({file:e,line:lt(t,a.index),typeName:c,...f?{importedFrom:f}:{}})}return o}l(ke,"extractArkRunManagedNewsFromSource");var Pr=["ensureInvariants","assertInvariants","validate","publish","emit","raise","record"],Kr=new RegExp(`\\b(${Pr.join("|")})\\b`),ut="(?:_?pendingEvents|domainEvents|uncommittedEvents|recordedEvents)",$r=new RegExp(`\\bthis\\.${ut}\\.push\\s*\\(`),Mr=new RegExp(`^this\\.${ut}\\s*=\\s*\\[\\s*\\]`),Ur=/^this\.[A-Za-z_][A-Za-z0-9_]*\s*=\s*\[\s*\]/,jr=/\bthis\.[A-Za-z_][A-Za-z0-9_]*\s*=(?!=)/g,Hr="truncatedUntil";function Vr(e){return Kr.test(e)||$r.test(e)}l(Vr,"referencesGuardOrPublish");function Gr(e,t,r){let n=e.slice(t);if(Mr.test(n))return!0;if(!Ur.test(n))return!1;if(r&&/^pullEvents$/i.test(r))return!0;let s=t>200?t-200:0;return/\bpullEvents\b/.test(e.slice(s,t+200))}l(Gr,"isIdiomaticEventsReset");function Br(e,t){let r=new RegExp(jr.source,"g"),n;for(;(n=r.exec(t))!==null;)if(!Gr(t,n.index,e))return!0;return!1}l(Br,"methodAssignsThis");function Wr(e,t){return t==null||Object.defineProperty(e,Hr,{value:t,enumerable:!1,configurable:!0}),e}l(Wr,"attachShapeTruncation");var zr=new Set(["public","private","protected","static","async","readonly","abstract","override","declare","get","set"]),qr=new Set(["if","match","when"]);function ee(e,t){let r=e[t];if(r==="/"&&e[t+1]==="/"){let n=e.indexOf(`
4
+ `,t);return n===-1?e.length:n}if(r==="/"&&e[t+1]==="*"){let n=e.indexOf("*/",t+2);return n===-1?e.length:n+2}if(r==="'"||r==='"'||r==="`"){let n=t+1;for(;n<e.length;){if(e[n]==="\\"){n+=2;continue}if(e[n]===r)return n+1;n+=1}return e.length}return t}l(ee,"skipStringOrComment");function j(e,t){let r=t;for(;r<e.length;){if(/\s/.test(e[r])){r+=1;continue}if(e[r]==="/"&&(e[r+1]==="/"||e[r+1]==="*")){r=ee(e,r);continue}break}return r}l(j,"skipWsAndComments");function dt(e,t){let r=e[t];if(!r||!/[A-Za-z_]/.test(r))return null;let n=t+1;for(;n<e.length&&/[A-Za-z0-9_]/.test(e[n]);)n+=1;return{ident:e.slice(t,n),end:n}}l(dt,"readIdent");function be(e,t,r,n){if(e[t]!==r)return null;let s=1,o=t+1;for(;o<e.length&&s>0;){let i=ee(e,o);if(i!==o){o=i;continue}let a=e[o];a===r?s+=1:a===n&&(s-=1),o+=1}return s===0?o:null}l(be,"skipBalanced");function Zr(e){let t=[],r=0,n;for(;r<e.length&&(r=j(e,r),!(r>=e.length));){if(e[r]===";"){r+=1;continue}let s=[],o=r;for(;;){let d=dt(e,o);if(!d||!zr.has(d.ident))break;s.push(d.ident),o=j(e,d.end)}let i=dt(e,o);if(!i){r+=1;continue}if(o=j(e,i.end),e[o]==="<"){let d=be(e,o,"<",">");if(d==null){n=e.length;break}o=j(e,d)}if(e[o]==="("){let d=be(e,o,"(",")");if(d==null){n=e.length;break}if(o=j(e,d),e[o]===":")for(o+=1;o<e.length&&e[o]!=="{"&&e[o]!==";";){let u=ee(e,o);if(u!==o){o=u;continue}o+=1}if(e[o]==="{"){let u=be(e,o,"{","}");if(u==null){n=e.length;break}t.push({name:i.ident,modifiers:s,kind:"method",body:e.slice(o+1,u-1)}),r=u;continue}if(e[o]===";"){r=o+1;continue}r=o+1;continue}let a=0,c=0,f=0;for(;o<e.length;){let d=ee(e,o);if(d!==o){o=d;continue}let u=e[o];if(u==="{")a+=1;else if(u==="}"){if(a===0)break;a-=1}else if(u==="(")c+=1;else if(u===")")c-=1;else if(u==="[")f+=1;else if(u==="]")f-=1;else if(u===";"&&a===0&&c===0&&f===0){o+=1;break}o+=1}t.push({name:i.ident,modifiers:s,kind:"field",body:""}),r=o}return{members:t,truncatedAt:n}}l(Zr,"scanClassMembers");function Ee(e,t){let r=[],n=/export\s+(?:abstract\s+)?class\s+([A-Za-z_][A-Za-z0-9_]*)\s*(?:extends\s+[^{]+)?(?:implements\s+[^{]+)?\{/g,s;for(;(s=n.exec(t))!==null;){let o=s[1],i=s.index+s[0].length,a=1,c=i;for(;c<t.length&&a>0;){let A=t[c];A==="{"?a+=1:A==="}"&&(a-=1),c+=1}let f=t.slice(i,c-1),d=a>0,u=Zr(f),p=d?t.length:u.truncatedAt==null?void 0:i+u.truncatedAt,g=u.members.filter(A=>!(A.kind!=="field"||A.name==="constructor"||A.modifiers.includes("private")||A.modifiers.includes("protected")||A.modifiers.includes("readonly")||A.modifiers.includes("static")||A.modifiers.includes("get")||A.modifiers.includes("set"))),y=g.length>0,R=/(?:^|[\n;{])\s*(?:public\s+)?set\s+[a-zA-Z_]/.test(f),k=/(?:^|[\n;{])\s*private\s+constructor\s*\(/.test(f),b=/(?:^|[\n;{])\s*(?:public\s+)?constructor\s*\(/.test(f)&&!k,q=/(?:^|[\n;{])\s*static\s+(?:async\s+)?(?:create|of|from|parse|build|make|new)\s*[<(]/.test(f)||/(?:^|[\n;{])\s*static\s+(?:async\s+)?[A-Za-z_][A-Za-z0-9_]*\s*\([^)]*\)\s*:\s*[A-Za-z_]/.test(f),D=[];for(let A of u.members)A.kind==="method"&&A.name!=="constructor"&&(A.modifiers.includes("static")||A.modifiers.includes("get")||A.modifiers.includes("set")||qr.has(A.name)||Br(A.name,A.body)&&D.push({name:A.name,referencesGuardOrPublish:Vr(A.body)}));let F=u.members.filter(A=>A.kind==="method").length<=1&&g.length>=2&&y;r.push(Wr({file:e,className:o,exported:!0,hasPublicMutableFields:y,hasPublicSetters:R,hasPublicConstructor:b,hasStaticFactory:q,mutatingMethods:[...D],dataOnly:F},p))}return r}l(Ee,"extractClassShapesFromSource");function Yr(e){if(!e)return{};let t=typeof e.governedPercent=="number"?e.governedPercent:null,r=typeof e.populatedLayerCount=="number"?e.populatedLayerCount:null;return r==null&&typeof e.classifiedFiles=="number"&&(r=e.classifiedFiles>0?1:0),{governedPercent:t,populatedLayerCount:r}}l(Yr,"normalizeExtraMergeTeethClassification");function te(e){let t=Yr(e),r=typeof t.governedPercent=="number"?t.governedPercent:null,n=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null;return r==null&&n==null?!0:(r??0)>=50&&(n??0)>=1}l(te,"extraMergeTeethAllowed");var Xr=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],Jr=new Set(Xr);function Qr(e){return Jr.has(e)}l(Qr,"isArkRunEditorSensor");var ft={"arkrun-missing-root":"ARKRUN_MISSING_ROOT","arkrun-kernel-in-domain":"ARKRUN_KERNEL_IN_DOMAIN","arkrun-direct-new":"ARKRUN_DIRECT_NEW","arkrun-undeclared-emit":"ARKRUN_UNDECLARED_EMIT","arkrun-undeclared-handle":"ARKRUN_UNDECLARED_HANDLE","arkrun-undeclared-depend":"ARKRUN_UNDECLARED_DEPEND","arkrun-transport-bypass":"ARKRUN_TRANSPORT_BYPASS"},en="ARKRUN_INTERACTION_NAME_INCOMPLETE";function mt(e,t=[]){let r=e.trim();return/^domain(?:model)?$/i.test(r)||/^domain(?=[A-Z_\-\s])/i.test(r)||/^(?:entit(?:y|ies)|aggregates?)(?:$|(?=[A-Z_\-\s]))/i.test(r)?!0:t.some(n=>{let s=n.trim().replace(/\.+$/,"");return s==="Domain"||s.startsWith("Domain.")})}l(mt,"isDomainRoleLayer");function tn(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}l(tn,"compareFindings");function w(e,t,r,n,s,o,i){let a=e.mode==="enforced"&&i;return{ruleId:ft[t],sensor:t,message:s,file:r,line:n,...o?.fromLayer?{fromLayer:o.fromLayer}:{},...o?.target?{target:o.target}:{},severity:a?"error":"warning",failsStrict:a,nextAction:K({ruleId:ft[t],fromLayer:o?.fromLayer,target:o?.target})}}l(w,"finding");function rn(e,t){let r=[],n=[],s=[],o=[];for(let i of e)i.file===t&&(r.push(...i.uses),n.push(...i.reactsTo),s.push(...i.raises),o.push(...i.sends));return{uses:new Set(r),reactsTo:new Set(n),raises:new Set(s),sends:new Set(o)}}l(rn,"bagForFile");function pt(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}l(pt,"emitKinds");function gt(e){return e==="subscribe"||e==="register-handler"}l(gt,"handleKinds");function nn(e){return e==="resolve"||e==="resolve-singleton"}l(nn,"dependKinds");function sn(e,t,r){let n=[],s=e.kernelRoots??e.compositionRoots;if(s.length===0)return n.push(w(e,"arkrun-missing-root","ark.config.json",1,"ArkRun kernelRoots is empty; no createArkKernel factory site is declared.",void 0,r)),n;let o=new Map;for(let i of t){let a=o.get(i.matchedRoot)??[];a.push(i),o.set(i.matchedRoot,a)}for(let i of s){let a=[...o.get(i)??[]].sort((f,d)=>f.file.localeCompare(d.file));if(a.length===0){n.push(w(e,"arkrun-missing-root","ark.config.json",1,`ArkRun kernel root ${JSON.stringify(i)} matched no governed files and has no createArkKernel factory.`,{target:i},r));continue}if(a.some(f=>f.hasKernelFactory))continue;let c=a[0];n.push(w(e,"arkrun-missing-root",c.file,1,`ArkRun kernel root ${JSON.stringify(i)} has no createArkKernel / createStrictArkKernel factory.`,{target:i},r))}return n}l(sn,"evaluateMissingRoot");function on(e,t,r,n,s){let o=new Map(t.map(a=>[a.name,a.intentPrefixes??[]])),i=[];for(let a of r){let c=a.specifier;if(!c||!$(c))continue;let f=n(a.from);f&&mt(f,o.get(f)??[])&&i.push(w(e,"arkrun-kernel-in-domain",a.from,a.line,`${f} must not import kernel module ${JSON.stringify(c)}.`,{fromLayer:f,target:c},s))}return i}l(on,"evaluateKernelInDomain");function an(e,t,r,n,s,o){let i=new Set(e.managedLayers);if(i.size===0)return[];let a=new Map(t.map(d=>[d.name,d.intentPrefixes??[]])),c=new Set(n.filter(d=>d.hasKernelFactory).map(d=>d.file)),f=[];for(let d of r){if(c.has(d.file))continue;let u=d.typeName;if(e.ignoreDirectNewForErrors!==!1&&(u.endsWith("Error")||u==="Error")||u.endsWith("DTO")||u.endsWith("VO"))continue;let p=s(d.file);!p||!i.has(p)||mt(p,a.get(p)??[])||f.push(w(e,"arkrun-direct-new",d.file,d.line,`${p} must not construct ${d.typeName} with new outside an ArkRun composition-root factory.`,{fromLayer:p,target:d.typeName},o))}return f}l(an,"evaluateDirectNew");function ln(e,t,r,n,s){let o=[],i=[];if(e.requireDeclarations!==!0)return{findings:o,completenessReasons:i};let a=new Set(e.managedLayers);if(a.size===0)return{findings:o,completenessReasons:i};for(let c of t){if(!pt(c.kind)&&!gt(c.kind)&&!nn(c.kind))continue;let f=n(c.file);if(!f||!a.has(f))continue;if(!c.nameLiteral){e.mode==="enforced"&&i.push({code:en,file:c.file,message:`ArkRun ${c.kind} call in ${c.file} has no string-literal name; enforced extra cannot prove the declaration.`});continue}let d=rn(r,c.file);if(pt(c.kind)){if(d.raises.has(c.nameLiteral)||d.sends.has(c.nameLiteral))continue;o.push(w(e,"arkrun-undeclared-emit",c.file,c.line,`Emit ${JSON.stringify(c.nameLiteral)} is not declared in raises or sends.`,{fromLayer:f,target:c.nameLiteral},s));continue}if(gt(c.kind)){if(d.reactsTo.has(c.nameLiteral))continue;o.push(w(e,"arkrun-undeclared-handle",c.file,c.line,`Handle ${JSON.stringify(c.nameLiteral)} is not declared in reactsTo.`,{fromLayer:f,target:c.nameLiteral},s));continue}d.uses.has(c.nameLiteral)||o.push(w(e,"arkrun-undeclared-depend",c.file,c.line,`Depend ${JSON.stringify(c.nameLiteral)} is not declared in uses.`,{fromLayer:f,target:c.nameLiteral},s))}return{findings:o,completenessReasons:i}}l(ln,"evaluateUndeclared");function cn(e,t,r,n){let s=new Set(e.managedLayers);if(s.size===0)return[];let o=[];for(let i of t){if(i.typeOnly)continue;let a=i.specifier;if(!a||!at(a))continue;let c=r(i.from);!c||!s.has(c)||o.push(w(e,"arkrun-transport-bypass",i.from,i.line,`${c} must not import broker/queue/emitter ${JSON.stringify(a)}; use the ArkRun kernel transport.`,{fromLayer:c,target:a},n))}return o}l(cn,"evaluateTransportBypass");function dn(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let r=te(e.classification),n=ln(t,e.kernelCalls,e.declarations,e.layerForFile,r),s=[...sn(t,e.compositionRootHits,r),...on(t,e.layers,e.dependencies,e.layerForFile,r),...an(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,r),...n.findings,...cn(t,e.dependencies,e.layerForFile,r)].sort(tn),o=[...n.completenessReasons].sort((i,a)=>{let c=`${i.code}\0${i.file??""}\0${i.message}`,f=`${a.code}\0${a.file??""}\0${a.message}`;return c<f?-1:c>f?1:0});return{findings:s,completenessReasons:o}}l(dn,"evaluateArkRunSensors");function Se(e){return{findings:dn(e).findings.filter(r=>Qr(r.sensor)),completenessReasons:[]}}l(Se,"evaluateArkRunEditorSensors");function un(e){if(e.importKind==="type"||e.exportKind==="type")return!0;let t=e.specifiers??[];return t.length===0?!1:t.every(r=>r.type==="ImportSpecifier")?t.every(r=>r.importKind==="type"):t.every(r=>r.exportKind==="type")}l(un,"declarationIsTypeOnly");function Rt(e){try{return yt.existsSync(e)?yt.readFileSync(e,"utf8"):null}catch{return null}}l(Rt,"readUtf8");function ht(e,t){let r=e.lintedFilename(t),n=e.findConfigPath(r),s=n?e.loadArkConfig(n):null;if(!s?.arkRun||!n||!r)return null;let o=T.dirname(n),i=T.isAbsolute(r)?r:T.resolve(r),a=T.relative(o,i).split(T.sep).join("/");if(!e.sourceIsInAnalysisScope(s,a))return null;let c=S(a,s.layers);return c?{extra:s.arkRun,config:s,root:o,absFile:i,relFile:a,fromLayer:c}:null}l(ht,"loadEditorFile");function fn(e,t,r){let n=Q(t,r).some(o=>o.kind==="factory"),s=[];for(let o of e.compositionRoots){try{if(!_(o).test(t))continue}catch{continue}s.push({file:t,matchedRoot:o,hasKernelFactory:n})}return s}l(fn,"compositionRootHitsForFile");function pn(e,t,r){let n=new Set(Ee(t.relFile,r).map(s=>s.className));return ct(r,(s,o)=>{if($(o))return;let i=e.resolveImportSpecifier(t.absFile,o,t.root);if(!i)return;let a=T.relative(t.root,i).split(T.sep).join("/");if(a.startsWith(".."))return;let c=Rt(i);if(c!==null)for(let f of Ee(a,c))n.add(f.className)}),n}l(pn,"admittedTypeNamesForEditor");function At(e,t,r,n,s,o){e.reportAdapterDiagnostic(t,r,n,{ruleId:s.ruleId,file:s.file,fromLayer:s.fromLayer,target:s.target,message:s.message,line:s.line,severity:s.severity,failsStrict:s.failsStrict,nextAction:s.nextAction},o)}l(At,"reportFinding");function gn(e){let t=e.callee;if(t?.type==="Identifier"&&t.name&&/^[A-Z]/.test(t.name))return t.name;let r=t?.property?.name;if(r&&/^[A-Z]/.test(r)&&t?.computed!==!0)return r}l(gn,"constructedTypeName");function mn(e,t){return e.type?.startsWith("Export")?"export":t}l(mn,"specifierEdgeKind");function yn(e,t,r,n,s){let o=l((i,a,c,f)=>{if(typeof a!="string"||a.length===0)return;let d=i.loc?.start?.line??1,u={from:r.relFile,specifier:a,kind:f,typeOnly:c,line:d,resolution:"resolved-external"},{findings:p}=Se({arkRun:r.extra,layers:r.config.layers,kernelCalls:[],managedNews:[],compositionRootHits:[],declarations:[],dependencies:[u],layerForFile:l(g=>g===r.relFile?r.fromLayer:S(g,r.config.layers),"layerForFile")});for(let g of p)g.sensor===n&&At(e,t,i,s,g,{fromLayer:g.fromLayer??r.fromLayer,specifier:a,target:g.target??a})},"check");return{ImportDeclaration(i){let a=i,c=(a.specifiers??[]).filter(d=>d.type==="ImportSpecifier"),f=c.length>0&&c.length===(a.specifiers??[]).length&&c.every(d=>d.importKind==="type");o(i,a.source?.value,a.importKind==="type"||f||un(i),"import")},ImportExpression(i){let a=i;a.source?.type==="Literal"&&o(i,a.source.value,!1,"dynamic-import")},TSImportEqualsDeclaration(i){let a=i;o(i,a.moduleReference?.expression?.value,a.importKind==="type"||a.isTypeOnly===!0,"require")},ExportNamedDeclaration(i){let a=i;if(!a.source)return;let c=a.specifiers??[],f=c.length>0&&c.every(d=>d.exportKind==="type");o(i,a.source.value,a.exportKind==="type"||f,mn(i,"export"))},ExportAllDeclaration(i){let a=i;o(i,a.source?.value,a.exportKind==="type","export")},CallExpression(i){let a=i;a.callee?.type==="Identifier"&&a.callee.name==="require"&&a.arguments?.[0]?.type==="Literal"&&!e.isLocallyBound(t,i,"require")&&o(i,a.arguments[0].value,!1,"require")}}}l(yn,"importListeners");function hn(e,t,r){let n=Rt(r.absFile)??"",s=pn(e,r,n),o=ke(r.relFile,n,s),{findings:i}=Se({arkRun:r.extra,layers:r.config.layers,kernelCalls:Q(r.relFile,n),managedNews:o,compositionRootHits:fn(r.extra,r.relFile,n),declarations:[],dependencies:[],layerForFile:l(c=>c===r.relFile?r.fromLayer:S(c,r.config.layers),"layerForFile")}),a=i.filter(c=>c.sensor==="arkrun-direct-new");return{NewExpression(c){let f=gn(c);if(!f)return;let d=c.loc?.start?.line,u=a.find(p=>p.target===f&&(d===void 0||p.line===d))??a.find(p=>p.target===f);u&&At(e,t,c,"directNew",u,{fromLayer:u.fromLayer??r.fromLayer,typeName:f,target:u.target??f})}}}l(hn,"directNewListener");function kt(e){let t=l((r,n,s,o)=>({meta:{type:"problem",docs:{description:n},messages:{[s]:o},schema:[]},create(i){let a=ht(e,i);return a?yn(e,i,a,r,s):{}}}),"createImportRule");return{noArkRunKernelInDomain:t("arkrun-kernel-in-domain","Disallow Domain-role imports of arkgate/runtime when arkRun is on (same sensor as ark-check).","kernelInDomain",'{{fromLayer}} must not import kernel module "{{specifier}}".'),noArkRunTransportBypass:t("arkrun-transport-bypass","Disallow homemade broker/queue/emitter imports in arkRun managed layers (same sensor as ark-check).","transportBypass",'{{fromLayer}} must not import broker/queue/emitter "{{specifier}}"; use the ArkRun kernel transport.'),noArkRunDirectNew:{meta:{type:"problem",docs:{description:"Disallow `new` of ArkRun-admitted types outside a composition-root factory (on-disk import/`new` envelope)."},messages:{directNew:"{{fromLayer}} must not construct {{typeName}} with new outside an ArkRun composition-root factory."},schema:[]},create(r){let n=ht(e,r);return n?hn(e,r,n):{}}}}}l(kt,"createArkRunEslintRules");var Rn="createOrderPlane";var An=/\bfrom\s+['"](?:@?prisma\/client|@supabase\/|drizzle-orm(?:\/[^'"]+)?|postgres(?:\/[^'"]+)?|typeorm|knex|mongodb|pg|mysql2|mongoose|better-sqlite3|ioredis|redis|kysely|sequelize)['"]|require\(\s*['"](?:@?prisma\/client|pg|postgres(?:\/[^'"]+)?|drizzle-orm(?:\/[^'"]+)?|knex|typeorm|mongoose)/,kn=/\bfrom\s+['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)(?:\.[cm]?[jt]sx?)?['"]|require\(\s*['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)/,bn=/\b(?:db|tx|client|prisma(?:Client)?|drizzle)\b(?:\s*\.\s*[A-Za-z_]\w*)*\s*\.\s*(?:insert(?:One|Many)?|update(?:One|Many)?|upsert|delete(?:One|Many)?|createMany|create|replaceOne|findOneAnd(?:Update|Delete|Replace))\s*\(|\bINSERT\s+INTO\b|\bUPDATE\s+[A-Za-z_][\w.]*\s+SET\b|\bDELETE\s+FROM\b/i;function En(e){return An.test(e)||kn.test(e)}l(En,"sourceImportsPersistenceDriver");function re(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}l(re,"escapeRegExp");function ne(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}l(ne,"isArkOrderModuleSpecifier");function H(e,t){let r=1;for(let n=0;n<t&&n<e.length;n+=1)e[n]===`
5
+ `&&(r+=1);return r}l(H,"lineAt");function V(e){return e.replace(/\/\*[\s\S]*?\*\//g,t=>t.replace(/[^\n]/g," ")).replace(/(^|[^:])\/\/.*$/gm,t=>t.replace(/\/\/.*$/,r=>" ".repeat(r.length)))}l(V,"stripCommentsPreservingLines");function bt(e,t){let r=V(t),n=[],s=/\bcreateOrderPlane\s*(?:<[^>]*>)?\s*\(/g,o;for(;(o=s.exec(r))!==null;)n.push({file:e,line:H(t,o.index),callee:Rn});return n}l(bt,"extractArkOrderPlaneCallsFromSource");function Et(e,t){let r=V(t),n=[],s=/\.((?:update|patch|set|mutate))\s*\(/g,o;for(;(o=s.exec(r))!==null;){let i=o[1],a=r.slice(Math.max(0,o.index-80),o.index);!/\b(?:plane|orderPlane)\s*(?:\?|!)?$/.test(a)&&!/\bcreateOrderPlane\b/.test(r)||n.push({file:e,line:H(t,o.index),method:i})}return n}l(Et,"extractArkOrderGenericUpdatesFromSource");function St(e,t,r){if(r.length===0)return[];let n=V(t);if(!En(n)||!bn.test(n))return[];let s=[],o=new Set;for(let i of r){if(!i)continue;let a=new RegExp(`(?:\\b${re(i)}\\s*:\\s*(?!string\\b|number\\b|boolean\\b|null\\b|[A-Z])|['"]${re(i)}['"]\\s*:|[{\\,]\\s*${re(i)}\\s*[\\,}]|\\.${re(i)}\\s*=)`,"g"),c;for(;(c=a.exec(n))!==null;){let f=`${i}:${c.index}`;if(!o.has(f)){o.add(f),s.push({file:e,line:H(t,c.index),key:i});break}}}return s}l(St,"extractArkOrderXiFieldWritesFromSource");function It(e,t){let r=V(t),n=[],s=/(?:\b(?:xi|release|current|pattern|house)\w*|\.xi)\s*=\s*[^\n;]{0,160}?\bingest\s*\(/gi,o;for(;(o=s.exec(r))!==null;)n.push({file:e,line:H(t,o.index)});return n}l(It,"extractArkOrderIngestWritesXiFromSource");function xt(e,t){let r=V(t),n=[],s=/\.release\s*\(\s*\{([^}]*)\}/g,o;for(;(o=s.exec(r))!==null;){let a=(o[1]??"").match(/\b[A-Za-z_][\w]*\s*:/g)??[];a.length!==0&&n.push({file:e,line:H(t,o.index),keyCount:a.length})}return n}l(xt,"extractArkOrderReleaseKeyCountsFromSource");var wt=new Map;function _t(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}l(_t,"escapeAppliesToLiteral");function Sn(e){let t="";for(let r=0;r<e.length;r+=1){let n=e[r];if(n==="\\"&&r+1<e.length){let s=e[r+1];if("*?{}[],".includes(s)||s==="\\"){t+="\\"+s,r+=1;continue}t+="/";continue}t+=n}return t}l(Sn,"normalizeAppliesToGlob");function In(e){let t=0;for(let r=0;r<e.length;r+=1){let n=e[r];if(n==="\\"){r+=1;continue}if(n==="{")t+=1;else if(n==="}"&&(t-=1,t<0))return!1}return t===0}l(In,"appliesToBracesBalanced");function xn(e){let t=wt.get(e);if(t)return t;let r=Sn(e),n=In(r),s="",o=0;for(let a=0;a<r.length;a+=1){let c=r[a];c==="\\"&&a+1<r.length?(s+=_t(r[a+1]),a+=1):c==="*"?r[a+1]==="*"?r[a+2]==="/"?(s+="(?:.*/)?",a+=2):(s+=".*",a+=1):s+="[^/]*":c==="?"?s+="[^/]":c==="{"&&n?(s+="(?:",o+=1):c==="}"&&n&&o>0?(s+=")",o-=1):c===","&&n&&o>0?s+="|":s+=_t(c)}let i=new RegExp(`^${s}$`);return wt.set(e,i),i}l(xn,"globToRegExp");var Nt={"arkorder-missing-plane":"ARKORDER_MISSING_PLANE","arkorder-kernel-in-domain":"ARKORDER_KERNEL_IN_DOMAIN","arkorder-generic-update":"ARKORDER_GENERIC_UPDATE","arkorder-too-many-params":"ARKORDER_TOO_MANY_PARAMS","arkorder-ingest-writes-xi":"ARKORDER_INGEST_WRITES_XI","arkorder-xi-field-write":"ARKORDER_XI_FIELD_WRITE","arkorder-information-budget":"ARKORDER_INFORMATION_BUDGET","arkorder-xi-ttl":"ARKORDER_XI_TTL"};function wn(e,t){return!t||t.length===0?!0:t.some(r=>xn(r).test(e))}l(wn,"matchesArkOrderAppliesTo");function _n(e,t=[]){let r=e.trim();return/^domain(?:model)?$/i.test(r)||/^domain(?=[A-Z_\-\s])/i.test(r)?!0:t.some(n=>{let s=n.trim().replace(/\.+$/,"");return s==="Domain"||s.startsWith("Domain.")})}l(_n,"isDomainRoleLayer");function N(e,t,r,n,s,o,i){let a=e.mode==="enforced"&&i;return{ruleId:Nt[t],sensor:t,message:s,file:r,line:n,...o?.fromLayer?{fromLayer:o.fromLayer}:{},...o?.target?{target:o.target}:{},severity:a?"error":"warning",failsStrict:a,nextAction:K({ruleId:Nt[t],fromLayer:o?.fromLayer,target:o?.target})}}l(N,"finding");function Nn(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let r=te(e.classification),n=[],s=t.planeRoots;if(t.mode==="enforced"&&s.length===0)n.push(N(t,"arkorder-missing-plane","ark.config.json",1,"ArkOrder planeRoots is empty; no createOrderPlane site is declared.",void 0,r));else{let c=new Map;for(let f of e.planeRootHits){let d=c.get(f.matchedRoot)??[];d.push(f),c.set(f.matchedRoot,d)}for(let f of s){let d=c.get(f)??[];if(d.length===0){n.push(N(t,"arkorder-missing-plane","ark.config.json",1,`ArkOrder plane root ${JSON.stringify(f)} matched no governed files and has no createOrderPlane factory.`,{target:f},r));continue}d.some(u=>u.hasPlaneFactory)||n.push(N(t,"arkorder-missing-plane",d[0].file,1,`ArkOrder plane root ${JSON.stringify(f)} has no createOrderPlane factory.`,{target:f},r))}}let o=new Map(e.layers.map(c=>[c.name,c.intentPrefixes??[]]));for(let c of e.dependencies){let f=c.specifier;if(!f||!ne(f))continue;let d=e.layerForFile(c.from);d&&_n(d,o.get(d)??[])&&n.push(N(t,"arkorder-kernel-in-domain",c.from,c.line,"Domain-role layer imports arkgate/order; Domain stays plane-free.",{fromLayer:d,target:f},r))}for(let c of e.genericUpdates)n.push(N(t,"arkorder-generic-update",c.file,c.line,`Generic ${c.method}() on the order plane rewrites \u03BE; Haken forbids it.`,{target:c.method},r));let i=t.xiKeys??[];for(let c of e.releaseKeyCounts??[])c.keyCount<=t.maxXiKeys||n.push(N(t,"arkorder-too-many-params",c.file,c.line,`release() freezes ${c.keyCount} keys; maxXiKeys is ${t.maxXiKeys} (few slow modes).`,{target:String(c.keyCount)},r));for(let c of e.ingestWritesXi??[])n.push(N(t,"arkorder-ingest-writes-xi",c.file,c.line,"ingest() result is assigned into a Release or \u03BE store; ingest may absorb or escalate, never mint a pattern.",void 0,r));let a=new Set(t.managedLayers);for(let c of i.length===0?[]:e.xiFieldWrites??[]){let f=e.layerForFile(c.file);!f||!a.has(f)||wn(c.file,t.appliesTo)&&n.push(N(t,"arkorder-xi-field-write",c.file,c.line,`This file writes ${JSON.stringify(c.key)} the same way it would write a seat count. Take the event in, or change that choice through the valve (propose, then apply).`,{fromLayer:f,target:c.key},r))}return n.sort((c,f)=>c.file.localeCompare(f.file)||c.ruleId.localeCompare(f.ruleId)||c.line-f.line),{findings:n,completenessReasons:[]}}l(Nn,"evaluateArkOrderSensors");function Ct(e){if(!e.arkOrder)return[];let t=bt(e.file,e.source),r=Et(e.file,e.source),n=e.arkOrder.xiKeys??[];return Nn({arkOrder:e.arkOrder,layers:[],planeCalls:t,genericUpdates:r,planeRootHits:[],xiFieldWrites:St(e.file,e.source,n),ingestWritesXi:It(e.file,e.source),releaseKeyCounts:xt(e.file,e.source),dependencies:[],layerForFile:l(()=>e.fromLayer,"layerForFile")}).findings.filter(s=>s.sensor==="arkorder-generic-update"||s.sensor==="arkorder-kernel-in-domain"||s.sensor==="arkorder-xi-field-write"||s.sensor==="arkorder-ingest-writes-xi"||s.sensor==="arkorder-too-many-params")}l(Ct,"evaluateArkOrderEditorSensors");function Cn(e){let t=e;return t.sourceCode?.getText?.()??t.getSourceCode?.()?.getText?.()??""}l(Cn,"eslintSourceText");function Ot(e){function t(r){return{meta:{type:"problem",docs:{description:r},messages:{denied:"{{message}}"},schema:[]},create(n){let s=e.lintedFilename(n),o=e.findConfigPath(s),i=o?e.loadArkConfig(o):null;if(!i?.arkOrder)return{};let a=e.toProjectRelative(o,s);if(!e.sourceIsInAnalysisScope(i,a))return{};let c=S(a,i.layers);return{ImportDeclaration(f){let d=typeof f.source?.value=="string"?f.source.value:"";if(r==="ARKORDER_KERNEL_IN_DOMAIN"){if(!ne(d)||c!=="DomainModel"&&!/^domain/i.test(c??""))return;e.reportAdapterDiagnostic(n,f,"denied",{ruleId:r,file:a,line:f.loc?.start?.line??1,message:"Domain-role layer imports arkgate/order; Domain stays plane-free."})}},Program(){if(r!=="ARKORDER_GENERIC_UPDATE")return;let f=Cn(n),d=Ct({arkOrder:i.arkOrder,file:a,source:f,fromLayer:c}).filter(u=>u.ruleId!=="ARKORDER_KERNEL_IN_DOMAIN");for(let u of d)e.reportAdapterDiagnostic(n,{loc:{start:{line:u.line}}},"denied",{ruleId:u.ruleId,file:u.file,line:u.line,message:u.message})}}}}}return l(t,"createImportRule"),{noArkOrderKernelInDomain:t("ARKORDER_KERNEL_IN_DOMAIN"),noArkOrderGenericUpdate:t("ARKORDER_GENERIC_UPDATE")}}l(Ot,"createArkOrderEslintRules");function L(e){if(typeof e.physicalFilename=="string"&&e.physicalFilename.length>0)return e.physicalFilename;if(typeof e.filename=="string"&&e.filename.length>0)return e.filename;if(typeof e.getFilename=="function")try{let t=e.getFilename();if(typeof t=="string"&&t.length>0)return t}catch{}return""}l(L,"lintedFilename");function O(e,t,r,n,s){let o=nt({...n,line:n.line??t.loc?.start?.line,column:n.column??(typeof t.loc?.start?.column=="number"?t.loc.start.column+1:void 0)});return e.report({node:t,messageId:r,...s?{data:s}:{},diagnostic:o}),o}l(O,"reportAdapterDiagnostic");function B(e){if(!e||e==="<input>"||e.startsWith("stdin"))return null;let t=m.dirname(m.resolve(e));for(;;){let r=m.join(t,"ark.config.json");if(C.existsSync(r))return r;let n=m.dirname(t);if(n===t)return null;t=n}}l(B,"findConfigPath");var vt=new Map;function W(e){if(!C.existsSync(e))return null;let t=C.readFileSync(e,"utf8"),r=vt.get(e);if(r?.source===t)return r.config;let n=tt(t,e).config;return vt.set(e,{source:t,config:n}),n}l(W,"loadArkConfig");function z(e,t){return(e.include??[]).some(n=>{let s=String(n).replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/$/,"");return s==="."||t===s||t.startsWith(`${s}/`)})&&!$e(t,e)}l(z,"sourceIsInAnalysisScope");function Tt(e){let t=[e,`${e}.ts`,`${e}.tsx`,`${e}.mts`,`${e}.cts`,`${e}.js`,`${e}.jsx`,m.join(e,"index.ts"),m.join(e,"index.tsx"),m.join(e,"index.js")];for(let r of t)try{if(C.existsSync(r)&&C.statSync(r).isFile())return r}catch{}return null}l(Tt,"existingSourceFile");function On(e){let t=m.resolve(e),r=null;for(;;){let f=m.join(t,"tsconfig.json");if(C.existsSync(f)){r=f;break}let d=m.dirname(t);if(d===t)break;t=d}if(!r)return{baseUrl:e,aliases:[]};let n=l(f=>{try{let d=C.readFileSync(f,"utf8");return d=d.replace(/\/\*[\s\S]*?\*\//g,"").replace(/(^|[^:])\/\/.*$/gm,"$1"),JSON.parse(d)}catch{return null}},"loadJsonc"),s=l((f,d)=>{if(d>4)return{};let u=n(f);if(!u)return{};let p=u.compilerOptions??{},g=p.baseUrl,y=p.paths,R=u.extends;if(typeof R=="string"&&!R.startsWith("@")){let k=m.resolve(m.dirname(f),R.endsWith(".json")?R:`${R}.json`);if(C.existsSync(k)){let b=s(k,d+1);g=g??b.baseUrl,y={...b.paths??{},...y??{}}}}return{baseUrl:g,paths:y}},"mergePaths"),o=s(r,0),i=m.dirname(r),a=m.resolve(i,o.baseUrl||"."),c=[];for(let[f,d]of Object.entries(o.paths||{})){if(!Array.isArray(d)||d.length===0)continue;let u=f.replace(/\*$/,"");u&&c.push({from:u,to:String(d[0]).replace(/\*$/,"")})}return c.sort((f,d)=>d.from.length-f.from.length),{baseUrl:a,aliases:c}}l(On,"readTsconfigPathAliases");function vn(e,t){if(!t.startsWith("."))return null;let r=m.resolve(m.dirname(e),t);return Tt(r)}l(vn,"resolveRelativeImport");function Lt(e,t,r){if(!t)return null;if(t.startsWith("."))return vn(e,t);let n=r||m.dirname(e),{baseUrl:s,aliases:o}=On(n),i=o.find(c=>t.startsWith(c.from));if(!i)return null;let a=m.resolve(s,`${i.to}${t.slice(i.from.length)}`);return Tt(a)}l(Lt,"resolveImportSpecifier");function oe(e){return typeof e?.value=="string"?e.value:void 0}l(oe,"stringValue");function we(e){return e?.name??oe(e)}l(we,"propertyName");function _e(e){return e.sourceCode??e.getSourceCode?.()}l(_e,"sourceCodeFor");function Dt(e,t){let r=_e(e)?.getScope?.(t);for(;r;){let n=r.references?.find(s=>s.identifier===t);if(n)return n;r=r.upper??void 0}}l(Dt,"referenceFor");function G(e,t,r){let n=Dt(e,t);if(n?.resolved)return(n.resolved.defs?.length??0)>0;let s=_e(e)?.getScope?.(t);for(;s;){let o=s.set?.get(r);if(o)return(o.defs?.length??0)>0;s=s.upper??void 0}return!1}l(G,"isLocallyBound");function Tn(e,t){let r=Dt(e,t);return r?r.isValueReference!==!1:t.parent?.type==="VariableDeclarator"&&t.parent.init===t}l(Tn,"isValueIdentifierReference");function Ft(e){if(e?.type==="Identifier"&&e.name)return{root:e,segments:[e.name]};if(!e||!(e.type==="MemberExpression"||!!(e.object&&e.property))||e.computed===!0)return;let r=Ft(e.object),n=we(e.property);if(!(!r||!n))return{root:r.root,segments:[...r.segments,n]}}l(Ft,"memberExpressionPath");function Ln(e){return we(e.callee?.property)}l(Ln,"calleePropertyName");function Pt(e,t){return e?.properties?.find(r=>we(r.key)===t)}l(Pt,"objectProperty");function se(e,t){return Pt(e,t)!==void 0}l(se,"objectHasProperty");function Dn(e){let t=Pt(e,"metadata")?.value;return se(t,"source")}l(Dn,"objectHasMetadataSource");function Kt(e){return Ln(e)==="publish"}l(Kt,"isPublishCall");function Ie(e){if(e.importKind==="type"||e.exportKind==="type")return!0;let t=e.specifiers??[];return t.length===0?!1:t.every(r=>r.type==="ImportSpecifier")?t.every(r=>r.importKind==="type"):t.every(r=>r.exportKind==="type")}l(Ie,"declarationIsTypeOnly");function Fn(e){let t=e;for(;t?.parent;)t=t.parent;return t?.type==="Program"?t:void 0}l(Fn,"containingProgram");function Pn(e){let t=Fn(e)?.body;if(!t)return!1;let r=!1;for(let n of t){if(n.type==="ImportDeclaration"){if(!Ie(n))return!1;continue}if(!(n.type==="TSInterfaceDeclaration"||n.type==="TSTypeAliasDeclaration")){if(n.type==="ExportNamedDeclaration"){if(n.declaration){if(n.declaration.type!=="TSInterfaceDeclaration"&&n.declaration.type!=="TSTypeAliasDeclaration")return!1}else if(!Ie(n))return!1;r=!0;continue}return!1}}return r}l(Pn,"sourceProgramExportsOnlyTypes");var Kn={meta:{type:"problem",docs:{description:"Disallow imports that violate ark.config.json layer rules (same contract as arkgate-check)."},messages:{forbiddenImport:"Architecture: {{fromLayer}} must not import {{toLayer}} (ark.config.json). Specifier: {{specifier}}",forbiddenImportHeuristic:"Domain code must not import infrastructure, adapters, repositories, or database modules."},schema:[]},create(e){let t=L(e),r=B(t),n=r?W(r):null,s=r?m.dirname(r):null,o=l(i=>{let a=oe(i.source);if(a&&n&&s&&t){let c=m.isAbsolute(t)?t:m.resolve(t),f=m.relative(s,c).split(m.sep).join("/");if(!z(n,f))return;let d=S(f,n.layers);if(!d)return;let u=Lt(c,a,s);if(!u)return;let p=m.relative(s,u).split(m.sep).join("/");if(p.startsWith(".."))return;let g=S(p,n.layers);if(!g)return;let y={fromPath:f,toPath:p,layers:n.layers},R=ae(n.rules,d,g,y),k=R?.rule;if(k){let b=i.type?.startsWith("Export")?"export":"import",q=Ie(i),D=!!k?.peerIsolation,ie=q&&!D,F=D&&R?Ke(R.peerIsolationReason??"cross-slice",{fromPath:f,toPath:p,fromSlice:R.fromSlice,toSlice:R.toSlice}):void 0,A=k?.message?F?`${k.message} (${F})`:k.message:F?`${d} must not ${b} another slice of ${g} (${f} \u2192 ${p}): ${F}`:`${d} must not ${b} ${g}.`;O(e,i,"forbiddenImport",{ruleId:"LAYER_IMPORT_VIOLATION",file:f,fromLayer:d,toLayer:g,target:p,edgeKind:b,...D?{peerIsolation:!0}:{},...q?{typeOnly:!0}:{},...ie?{severity:"warning"}:{},...Pn(i)?{sourcePureTypeModule:!0}:{},message:ie?`${A} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:A},{fromLayer:d,toLayer:g,specifier:a})}return}},"check");return{ImportDeclaration:o,ExportNamedDeclaration:o,ExportAllDeclaration:o}}},$n={meta:{type:"problem",docs:{description:"Require event bus publish calls to use registered intent creators instead of raw event objects or intent strings."},messages:{rawPublish:"Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts."},schema:[]},create(e){return{CallExpression(t){let r=t.arguments?.[0],n=oe(r),s=he({publishCall:Kt(t),rawIntentName:n,objectHasIntent:se(r,"intent"),arkPublishCandidate:!1,hasSource:!0});if(s.some(o=>o.ruleId==="RAW_EVENT_PUBLISH")){let o=s.find(i=>i.ruleId==="RAW_EVENT_PUBLISH");O(e,t,"rawPublish",{...o,file:L(e)})}}}}},Mn={meta:{type:"problem",docs:{description:"Require event bus publish calls to include source metadata."},messages:{missingSource:"Strict Ark publish calls must include metadata.source."},schema:[]},create(e){return{CallExpression(t){let r=t.arguments?.[0],n=t.arguments?.[2],o=he({publishCall:Kt(t),rawIntentName:oe(r),objectHasIntent:se(r,"intent"),arkPublishCandidate:!0,hasSource:Dn(r)||se(n,"source")}).find(i=>i.ruleId==="PUBLISH_MISSING_SOURCE");o&&O(e,t,"missingSource",{...o,file:L(e)})}}}},Un={meta:{type:"problem",docs:{description:"Disallow ambient globals from the layer\u2019s forbiddenGlobals in ark.config.json (same purity surface as ark-check). Option `globals` is a standalone fallback when no project config applies."},messages:{forbiddenGlobal:'Ambient global "{{name}}" is forbidden in {{layer}} (ark.config.json); inject the capability through a port instead.',forbiddenGlobalDefault:'Ambient global "{{name}}" is forbidden here; inject the capability through a port instead.',forbiddenModule:'{{layer}} must not use module "{{specifier}}" because it is the import form of forbidden global "{{name}}".'},schema:[{type:"object",properties:{globals:{type:"array",items:{type:"string"}}},additionalProperties:!1}]},create(e){let t=L(e),r=e.options?.[0],n=B(t),s=n?W(n):null,o=n?m.dirname(n):null,i=null,a="this layer";if(s&&o&&t){let u=m.isAbsolute(t)?t:m.resolve(t),p=m.relative(o,u).split(m.sep).join("/");if(!z(s,p))return{};let g=s.layers?.find(y=>y.name===S(p,s.layers));g?.forbiddenGlobals?.length?(i=new Set(g.forbiddenGlobals),a=g.name):i=null}else r?.globals&&(i=new Set(r.globals));if(!i)return{};let c=typeof _e(e)?.getScope=="function",f=l((u,p)=>{let g=m.isAbsolute(t)?t:m.resolve(t),y=o?m.relative(o,g).split(m.sep).join("/"):t;O(e,u,s?"forbiddenGlobal":"forbiddenGlobalDefault",{ruleId:"FORBIDDEN_GLOBAL",file:y,fromLayer:a,target:p,message:`${a} must not use the ambient global "${p}".`},{name:p,layer:a})},"report"),d=l((u,p,g,y)=>{if(g||typeof p!="string")return;let R=ce(p,i);if(!R)return;let k=m.isAbsolute(t)?t:m.resolve(t),b=o?m.relative(o,k).split(m.sep).join("/"):t;O(e,u,"forbiddenModule",{ruleId:"FORBIDDEN_GLOBAL",file:b,fromLayer:a,target:p,edgeKind:y,message:`${a} must not use module "${p}" because it is the import form of forbidden global "${R}".`},{layer:a,name:R,specifier:p,importKind:y})},"reportModule");return{MemberExpression(u){if(u.parent?.type==="MemberExpression"&&u.parent.object===u)return;let p=Ft(u);if(!p||G(e,p.root,p.segments[0]))return;let g=p.segments[0]==="globalThis",y=g?p.segments.slice(1):p.segments,R;for(let k=y.length;k>=(g?1:2);k-=1){let b=y.slice(0,k).join(".");if(i.has(b)){R=b;break}}R?f(u,R):!c&&i.has(p.segments[0])&&f(u,p.segments[0])},CallExpression(u){let p=u;if(p.callee?.type==="Identifier"&&p.callee.name==="require"&&p.arguments?.[0]?.type==="Literal"&&!G(e,u,"require")&&d(u,p.arguments[0].value,!1,"require"),c)return;let g=p.callee?.type==="Identifier"?p.callee.name:void 0;g&&i.has(g)&&f(u,g)},ImportDeclaration(u){let p=u,g=(p.specifiers??[]).filter(R=>R.type==="ImportSpecifier"),y=g.length>0&&g.length===(p.specifiers??[]).length&&g.every(R=>R.importKind==="type");d(u,p.source?.value,p.importKind==="type"||y,"import")},ImportExpression(u){let p=u;p.source?.type==="Literal"&&d(u,p.source.value,!1,"dynamic-import")},TSImportEqualsDeclaration(u){let p=u;d(u,p.moduleReference?.expression?.value,p.importKind==="type"||p.isTypeOnly===!0,"require")},ExportNamedDeclaration(u){let p=u;if(!p.source)return;let g=p.specifiers??[],y=g.length>0&&g.every(R=>R.exportKind==="type");d(u,p.source.value,p.exportKind==="type"||y,"export")},ExportAllDeclaration(u){let p=u;d(u,p.source?.value,p.exportKind==="type","export")},NewExpression(u){if(c)return;let p=u.callee?.type==="Identifier"?u.callee.name:void 0;p&&i.has(p)&&f(u,p)},Identifier(u){!c||!u.name||!i.has(u.name)||!Tn(e,u)||G(e,u,u.name)||f(u,u.name)}}}},jn={meta:{type:"problem",docs:{description:"Disallow importing modules whose effect capability the layer denies (ark.config.json capabilities.deny / pure \u2014 same wall surface as ark-check). Import dimension only: ambient globals stay with no-forbidden-globals and the CLI/hook symbol path."},messages:{deniedCapability:'{{layer}} denies the {{capability}} capability (ark.config.json); "{{specifier}}" imports it. Define a port and bind the implementation in an adapter layer.'},schema:[]},create(e){let t=L(e),r=B(t),n=r?W(r):null,s=r?m.dirname(r):null;if(!n||!s||!t)return{};let o=m.isAbsolute(t)?t:m.resolve(t),i=m.relative(s,o).split(m.sep).join("/");if(!z(n,i))return{};let a=n.layers?.find(d=>d.name===S(i,n.layers));if(!a)return{};let c=new Set(je(a));if(c.size===0)return{};let f=l((d,u,p,g)=>{if(p||typeof u!="string"||ce(u,a.forbiddenGlobals??[]))return;let y=Ue(u);!y||!c.has(y)||O(e,d,"deniedCapability",{ruleId:"CAPABILITY_VIOLATION",file:i,fromLayer:a.name,target:u,capability:y,edgeKind:g,message:`${a.name} denies the ${y} capability; found import of "${u}".`},{layer:a.name,capability:y,specifier:u})},"check");return{ImportDeclaration(d){let u=d,p=(u.specifiers??[]).filter(y=>y.type==="ImportSpecifier"),g=p.length>0&&p.length===(u.specifiers??[]).length&&p.every(y=>y.importKind==="type");f(d,u.source?.value,u.importKind==="type"||g,"import")},ImportExpression(d){let u=d;u.source?.type==="Literal"&&f(d,u.source.value,!1,"dynamic-import")},TSImportEqualsDeclaration(d){let u=d;f(d,u.moduleReference?.expression?.value,u.importKind==="type"||u.isTypeOnly===!0,"require")},ExportNamedDeclaration(d){let u=d;if(!u.source)return;let p=u.specifiers??[],g=p.length>0&&p.every(y=>y.exportKind==="type");f(d,u.source.value,u.exportKind==="type"||g,"export")},ExportAllDeclaration(d){let u=d;f(d,u.source?.value,u.exportKind==="type","export")},CallExpression(d){let u=d;u.callee?.type==="Identifier"&&u.callee.name==="require"&&u.arguments?.[0]?.type==="Literal"&&!G(e,d,"require")&&f(d,u.arguments[0].value,!1,"require")}}}},{noArkRunKernelInDomain:Hn,noArkRunDirectNew:Vn,noArkRunTransportBypass:Gn}=kt({findConfigPath:B,loadArkConfig:W,resolveImportSpecifier:Lt,lintedFilename:L,sourceIsInAnalysisScope:z,isLocallyBound:G,reportAdapterDiagnostic:O});function Bn(e,t){let r=m.dirname(m.resolve(e));return m.relative(r,m.resolve(t)).split(m.sep).join("/")}l(Bn,"toProjectRelative");var{noArkOrderKernelInDomain:Wn,noArkOrderGenericUpdate:zn}=Ot({findConfigPath:B,loadArkConfig:W,lintedFilename:L,sourceIsInAnalysisScope:z,reportAdapterDiagnostic:O,toProjectRelative:Bn});var qn={"no-domain-infra-imports":Kn,"no-raw-event-publish":$n,"require-publish-source":Mn,"no-forbidden-globals":Un,"no-denied-capabilities":jn,"no-arkrun-kernel-in-domain":Hn,"no-arkrun-direct-new":Vn,"no-arkrun-transport-bypass":Gn,"no-arkorder-kernel-in-domain":Wn,"no-arkorder-generic-update":zn},xe={rules:qn};xe.configs={recommended:{plugins:{ark:xe},rules:{"ark/no-domain-infra-imports":"error","ark/no-raw-event-publish":"error","ark/require-publish-source":"error","ark/no-forbidden-globals":"error","ark/no-denied-capabilities":"error","ark/no-arkrun-kernel-in-domain":"error","ark/no-arkrun-direct-new":"error","ark/no-arkrun-transport-bypass":"error","ark/no-arkorder-kernel-in-domain":"error","ark/no-arkorder-generic-update":"error"}}};var yo=xe;export{yo as default,B as findConfigPath,_ as globToRegExp,Jt as isEdgeDenied,S as layerForRelativePath,W as loadArkConfig,zn as noArkOrderGenericUpdate,Wn as noArkOrderKernelInDomain,Vn as noArkRunDirectNew,Hn as noArkRunKernelInDomain,Gn as noArkRunTransportBypass,jn as noDeniedCapabilities,Kn as noDomainInfraImports,Un as noForbiddenGlobals,$n as noRawEventPublish,De as patternSpecificity,xe as plugin,On as readTsconfigPathAliases,Mn as requirePublishSource,Lt as resolveImportSpecifier,vn as resolveRelativeImport};