arkgate 4.1.0 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/CHANGELOG.md +124 -2
  2. package/README.md +24 -14
  3. package/bin/ark-check-runtime.mjs +16 -5
  4. package/bin/ark-mcp-runtime.mjs +766 -64
  5. package/bin/lib/agent-gates.mjs +1 -0
  6. package/bin/lib/ark-gitignore.mjs +88 -0
  7. package/bin/lib/ci-and-commands.mjs +33 -8
  8. package/bin/lib/codex-home.mjs +90 -8
  9. package/bin/lib/design-smells.mjs +71 -9
  10. package/bin/lib/doctor-plan.mjs +47 -39
  11. package/bin/lib/effective-contract-load.mjs +73 -9
  12. package/bin/lib/enforcement-honesty.mjs +78 -22
  13. package/bin/lib/enforcement-state.mjs +1 -1
  14. package/bin/lib/gate-files.mjs +441 -9
  15. package/bin/lib/github-enforcement.mjs +168 -7
  16. package/bin/lib/hook-templates.mjs +12 -11
  17. package/bin/lib/host-support-matrix.mjs +91 -17
  18. package/bin/lib/html-report-depth.mjs +13 -2
  19. package/bin/lib/html-report-evolution.mjs +114 -0
  20. package/bin/lib/html-report.mjs +18 -97
  21. package/bin/lib/import-resolve.mjs +33 -11
  22. package/bin/lib/install-activation.mjs +87 -0
  23. package/bin/lib/install-migrate.mjs +66 -50
  24. package/bin/lib/managed-upgrade.mjs +10 -41
  25. package/bin/lib/mcp-adoption.mjs +15 -5
  26. package/bin/lib/pilot-loop.mjs +25 -8
  27. package/bin/lib/project-identity.mjs +103 -0
  28. package/bin/lib/report-snapshot-context.mjs +28 -0
  29. package/bin/lib/resident-hook.mjs +33 -9
  30. package/bin/lib/rules-inventory.mjs +100 -8
  31. package/bin/lib/skill-install.mjs +272 -22
  32. package/bin/lib/skill-write.mjs +899 -0
  33. package/bin/lib/start-preview.mjs +84 -1
  34. package/bin/lib/upgrade-command.mjs +2 -5
  35. package/bin/lib/write-path-detect.mjs +2 -2
  36. package/dist/index.cjs +13 -13
  37. package/dist/index.d.ts +194 -2
  38. package/dist/index.js +13 -13
  39. package/docs/README.md +6 -4
  40. package/docs/agent-guide.md +115 -17
  41. package/docs/ai-gates.md +133 -25
  42. package/docs/assets/ark-write-gate.svg +2 -2
  43. package/docs/develop.md +16 -6
  44. package/docs/enthusiast/how-to-agent-gates.md +6 -0
  45. package/docs/package-surface.md +16 -9
  46. package/docs/product-voice.md +22 -4
  47. package/docs/use.md +3 -1
  48. package/package.json +3 -1
  49. package/schemas/ark.project-identity.schema.json +116 -0
  50. package/server.json +2 -2
  51. package/templates/skills/ark-adopt.md +9 -0
  52. package/templates/skills/ark-architect.md +12 -2
  53. package/templates/skills/ark-autopilot.md +9 -0
  54. package/templates/skills/ark-contract.md +11 -1
  55. package/templates/skills/ark-coverage.md +9 -0
  56. package/templates/skills/ark-explain.md +13 -1
  57. package/templates/skills/ark-explore.md +9 -0
  58. package/templates/skills/ark-fix.md +10 -1
  59. package/templates/skills/ark-loop.md +11 -2
  60. package/templates/skills/ark-place.md +17 -6
  61. package/templates/skills/ark-runtime.md +8 -0
  62. package/templates/skills/ark-think.md +14 -2
  63. package/templates/skills/ark-upgrade.md +9 -0
package/dist/index.cjs CHANGED
@@ -1,16 +1,16 @@
1
- "use strict";var kt=Object.defineProperty;var Bn=Object.getOwnPropertyDescriptor;var qn=Object.getOwnPropertyNames;var zn=Object.prototype.hasOwnProperty;var Kn=(e,t)=>{for(var n in t)kt(e,n,{get:t[n],enumerable:!0})},Yn=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of qn(t))!zn.call(e,s)&&s!==n&&kt(e,s,{get:()=>t[s],enumerable:!(r=Bn(t,s))||r.enumerable});return e};var Wn=e=>Yn(kt({},"__esModule",{value:!0}),e);var As={};Kn(As,{ANALYSIS_IR_SCHEMA_VERSION:()=>at,ARK_ANALYSIS_RESULT_SCHEMA:()=>nn,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>en,ARK_CONFIG_SCHEMA:()=>tt,ARK_CONFIG_SCHEMA_VERSION:()=>yn,ARK_DESIGN_DELTA_SCHEMA_VERSION:()=>Gn,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION:()=>Un,ARK_RULES_SCHEMA:()=>lt,ARK_RULES_SCHEMA_VERSION:()=>Cn,ARK_RULE_SENSORS:()=>Bt,EffectiveContractError:()=>Ge,POLICY_DELTA_SCHEMA_VERSION:()=>mt,RESOLVED_CANDIDATE_FACTS_SCHEMA:()=>it,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION:()=>Q,analyzeArchitectureConvergence:()=>oe,analyzeChange:()=>ze,analyzePolicyDelta:()=>qt,analyzeProject:()=>ve,analyzeResolvedProject:()=>Ee,buildArkRuleFileHints:()=>Et,buildEffectiveArkRules:()=>ct,buildRulesInventory:()=>Vn,canPromoteInvariant:()=>ut,classifyArkPolicyDelta:()=>gt,collectAnalysisConfigWarnings:()=>Ye,collectEmptyAppliesToFindings:()=>It,collectForbiddenCapabilityUses:()=>ie,createAICodeGate:()=>Ht,createAdapterResult:()=>tn,createArchitectureProfile:()=>Me,createArchitectureProfileFromArkConfig:()=>jt,createElevenLayerArkConfig:()=>Ut,createResolvedCandidateFacts:()=>st,deriveArkRuleFileHints:()=>Yt,detectArchitectureCycles:()=>bt,deterministicHash:()=>O,effectiveContractPolicyPayload:()=>dt,elevenLayerProfile:()=>Ne,emptyEffectiveArkRules:()=>te,evaluateArchitectureGraph:()=>pe,evaluateArkRuleSensors:()=>vt,evaluateInvariantCoverage:()=>pt,explainViolation:()=>zt,extractClassShapesFromSource:()=>Mn,extractSemanticDependencies:()=>se,inventoryToExtractionCard:()=>jn,loadArkConfigContract:()=>Fe,loadArkRulesContract:()=>Ue,loadContract:()=>qe,loadResolvedCandidateFacts:()=>Z,parseArkConfigJson:()=>rt,parseArkRulesJson:()=>Sn,policyDeltaAcknowledgementMatches:()=>ht,preflightChange:()=>Wt,preflightResolvedChange:()=>Zt,resolveEffectiveContract:()=>xn,resolvedFactsEvidenceRequirementsHash:()=>be,stableSerialize:()=>S,toAdapterDiagnostic:()=>We,version:()=>Xt});module.exports=Wn(As);var Xt="4.1.0";var en="1.4";function I(e){return typeof e=="string"&&e.length>0?e:void 0}function Qt(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function Zn(e,t,n){if(e==="LAYER_IMPORT_VIOLATION")return t.typeOnly||n.targetTypeOnlyExports===!0||n.namedBindingsTypeOnly===!0?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":n.peerIsolation===!0?"Extract the shared dependency to a shared layer, then preflight again.":`Define a port in ${t.fromLayer??"the source layer"}, inject the ${t.toLayer??"outer-layer"} implementation, then preflight again.`;if(e==="FORBIDDEN_GLOBAL")return`Inject ${t.target??"the capability"} through a port, then preflight again.`;if(e==="CAPABILITY_VIOLATION")return`Define a ${I(n.capability)??"capability"} port in ${t.fromLayer??"the walled layer"}, bind the implementation outside it, then preflight again.`;if(e==="CIRCULAR_DEPENDENCY")return"Extract the shared dependency into a third module, then preflight again.";if(e==="RAW_EVENT_PUBLISH")return"Publish through a registered intent creator, then run Ark again.";if(e==="PUBLISH_MISSING_SOURCE")return"Add metadata.source to the publish call, then run Ark again.";if(e==="ARKRULE_STRUCTURE"||e==="ARKRULE_INVARIANT"||e==="INVARIANT_UNCOVERED"||e.startsWith("ARKRULE_")){let r=t.arkruleSource??"arkrules/<Layer>.json";return`Fix the structure or invariant for ${t.arkruleId??"the ArkRule"} (declared in ${r}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`}return`Resolve ${e} without weakening ark.config.json, then run Ark again.`}function We(e,t="error"){let n=I(e.ruleId)??I(e.code)??"ARK_UNKNOWN",r=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,s={...I(e.target)?{target:I(e.target)}:{},...I(e.fromLayer)?{fromLayer:I(e.fromLayer)}:{},...I(e.toLayer)?{toLayer:I(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{},...typeof e.targetTypeOnlyExports=="boolean"?{targetTypeOnlyExports:e.targetTypeOnlyExports}:{},...typeof e.sourcePureTypeModule=="boolean"?{sourcePureTypeModule:e.sourcePureTypeModule}:{},...typeof e.namedBindingsTypeOnly=="boolean"?{namedBindingsTypeOnly:e.namedBindingsTypeOnly}:{},...typeof e.portProofEligible=="boolean"?{portProofEligible:e.portProofEligible}:{},...typeof e.peerIsolation=="boolean"?{peerIsolation:e.peerIsolation}:{},...I(e.capability)?{capability:I(e.capability)}:{},...I(e.edgeKind)?{edgeKind:I(e.edgeKind)}:{},...I(e.arkruleId)?{arkruleId:I(e.arkruleId)}:{},...I(e.arkruleSource)?{arkruleSource:I(e.arkruleSource)}:{}};return{ruleId:n,severity:r,message:I(e.message)??n,location:{file:I(e.file)??"<unknown>",line:Qt(e.line,1),column:Qt(e.column,1)},evidence:s,nextAction:I(e.nextAction)??Zn(n,s,e)}}function tn(e){let t=e.completeness??"complete",n=e.mode??"lexical-compatibility";if(t==="complete"&&(e.completenessReasons?.length??0)>0)throw new Error("completenessReasons must be empty when completeness is complete.");let r=t==="complete"?[]:e.completenessReasons&&e.completenessReasons.length>0?e.completenessReasons.map(o=>({code:I(o.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:I(o.message)??`Analysis ${t}: required evidence is incomplete.`,...I(o.file)?{file:I(o.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],s={...I(e.policyHash)?{policyHash:I(e.policyHash)}:{},...I(e.resolverIdentity)?{resolverIdentity:I(e.resolverIdentity)}:{},...I(e.factsHash)?{factsHash:I(e.factsHash)}:{},...I(e.candidateTreeHash)?{candidateTreeHash:I(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let o of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!s[o])throw new Error(`${o} is required for resolved ${t} adapter evidence.`)}let i=[...(e.violations??[]).map(o=>We(o,"error")),...(e.warnings??[]).map(o=>We(o,"warning"))],a={schemaVersion:"1.4",completenessReasons:r,diagnostics:i};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...a,mode:n,valid:!1,completeness:t,...s};let o={policyHash:s.policyHash,resolverIdentity:s.resolverIdentity,factsHash:s.factsHash,candidateTreeHash:s.candidateTreeHash};return t==="complete"?{...a,mode:n,valid:e.valid,completeness:t,...o}:{...a,mode:n,valid:!1,completeness:t,...o}}return t==="complete"?{...a,mode:n,valid:e.valid,completeness:t,...s}:{...a,mode:n,valid:!1,completeness:t,...s}}var nn={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","mode","valid","completeness","completenessReasons","diagnostics"],allOf:[{if:{properties:{completeness:{enum:["partial","unavailable"]}},required:["completeness"]},then:{properties:{valid:{const:!1}}}},{if:{properties:{mode:{const:"resolved-candidate-facts"},completeness:{enum:["complete","partial"]}},required:["mode","completeness"]},then:{required:["policyHash","resolverIdentity","factsHash","candidateTreeHash"]}},{if:{properties:{completeness:{const:"complete"}},required:["completeness"]},then:{properties:{completenessReasons:{maxItems:0}}},else:{properties:{completenessReasons:{minItems:1}}}}],properties:{schemaVersion:{const:"1.4"},mode:{enum:["lexical-compatibility","resolved-candidate-facts"]},valid:{type:"boolean"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:{type:"string",minLength:1},message:{type:"string",minLength:1},file:{type:"string",minLength:1}}}},policyHash:{type:"string",minLength:1},resolverIdentity:{type:"string",minLength:1},factsHash:{type:"string",minLength:1},candidateTreeHash:{type:"string",minLength:1},diagnostics:{type:"array",items:{type:"object",additionalProperties:!1,required:["ruleId","severity","message","location","evidence"],properties:{ruleId:{type:"string",minLength:1},severity:{enum:["error","warning"]},message:{type:"string",minLength:1},location:{type:"object",additionalProperties:!1,required:["file","line","column"],properties:{file:{type:"string",minLength:1},line:{type:"integer",minimum:1},column:{type:"integer",minimum:1}}},evidence:{type:"object",additionalProperties:!1,properties:{target:{type:"string"},fromLayer:{type:"string"},toLayer:{type:"string"},typeOnly:{type:"boolean"},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"},peerIsolation:{type:"boolean"},capability:{type:"string",minLength:1},edgeKind:{type:"string",minLength:1},arkruleId:{type:"string",minLength:1},arkruleSource:{type:"string",minLength:1}}},nextAction:{type:"string",minLength:1}}}}}};var wt=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),$t=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Pt=Object.freeze(Object.keys($t).sort()),xt=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"}),Ot=Object.freeze({process:Object.freeze(["process","node:process"])});function we(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=xt[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),s=xt[r];if(s)return s;let i=e.indexOf("/",n+1);return i<0?null:xt[e.slice(0,i)]??null}function J(e,t){for(let n of t)if(Ot[n]?.includes(e))return n;return null}function Ze(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),s=$t[r];if(s)return s}return null}function fe(e){if(e?.pure===!0)return[...wt].sort();let n=(e?.capabilities?.deny??[]).filter(r=>wt.includes(r));return[...new Set(n)].sort()}function Oe(e,t){if(t.length===0)return!1;let n=new Set(t),r=e.split(".");for(let s=r.length;s>=1;s-=1)if(n.has(r.slice(0,s).join(".")))return!0;return!1}function Je(e){let t=new Set,n=new Set,r=Object.keys($t);for(let s of e?.forbiddenGlobals??[]){let i=r.filter(a=>a===s||a.startsWith(`${s}.`));if(i.length===0)n.add(s);else for(let a of i)t.add(`ambient:${a}`);for(let a of Ot[s]??[])t.add(`import-exact:${a}`)}for(let s of fe(e)){if(t.add(`import:${s}`),s==="process")for(let i of Ot.process)t.add(`import-exact:${i}`);for(let i of r)Ze(i)===s&&t.add(`ambient:${i}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}var rn=new Map;function sn(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function Xe(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let s=e[n+1];if("*?{}[],".includes(s)||s==="\\"){t+="\\"+s,n+=1;continue}t+="/";continue}t+=r}return t}function Jn(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="{")t+=1;else if(r==="}"&&(t-=1,t<0))return!1}return t===0}function re(e){let t=rn.get(e);if(t)return t;let n=Xe(e),r=Jn(n),s="",i=0;for(let o=0;o<n.length;o+=1){let u=n[o];u==="\\"&&o+1<n.length?(s+=sn(n[o+1]),o+=1):u==="*"?n[o+1]==="*"?n[o+2]==="/"?(s+="(?:.*/)?",o+=2):(s+=".*",o+=1):s+="[^/]*":u==="?"?s+="[^/]":u==="{"&&r?(s+="(?:",i+=1):u==="}"&&r&&i>0?(s+=")",i-=1):u===","&&r&&i>0?s+="|":s+=sn(u)}let a=new RegExp(`^${s}$`);return rn.set(e,a),a}function Xn(e){return Xe(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}function Tt(e,t){let n=Xe(String(e)),r=Xn(n),s=n.replace(/\*/g,"").length,i=r.length*1e4+s;if(t==null||t==="")return i;let a=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return s;let o=0,u=-1;for(let m of r){let h=-1;for(let g=o;g<a.length;g+=1)if(a[g]===m){h=g;break}if(h<0)return i;u=h,o=h+1}return(u+1)*1e6+r.length*1e4+s}function z(e,t){let n=String(e).split(/[/\\]/).join("/"),r,s=-1;for(let i of t??[])if(!(i.exclude??[]).some(a=>re(a).test(n))){for(let a of i.patterns??[])if(re(a).test(n)){let o=Tt(a,n);o>s&&(s=o,r=i.name)}}return r}function an(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),r=new Set(t.map(s=>String(s).toLowerCase()));for(let s=0;s<n.length-1;s+=1)if(r.has(n[s].toLowerCase()))return`${n[s].toLowerCase()}/${n[s+1].toLowerCase()}`}function Qn(e){let t=new Set;for(let n of e??[]){let s=Xe(String(n)).split("/").filter(Boolean);for(let i=0;i<s.length;i+=1){let a=s[i];if((a==="**"||a==="*")&&i>0){let o=s[i-1];o&&!o.includes("*")&&!o.includes("{")&&!o.includes("}")&&t.add(o)}}}return[...t]}function er(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(s=>typeof s=="string"&&s.length>0);let r=(n??[]).find(s=>s.name===t);return Qn(r?.patterns)}function K(e,t,n,r){for(let s of e??[])if(!(s.from!==t||s.to!==n)&&s.allowed===!1){if(s.peerIsolation){let i=r?.fromPath,a=r?.toPath;if(!i||!a)return s;let o=er(s,t,r?.layers);if(o.length===0)return s;let u=an(i,o),m=an(a,o);if(!u||!m||u!==m)return s;continue}if(t!==n)return s}}function ye(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function cn(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function on(e,t){if(e.isImportDeclaration(t)){let r=t.importClause;if(!r)return!1;if(r.isTypeOnly)return!0;let s=r.namedBindings;return!!(s&&e.isNamedImports(s)&&s.elements.length>0&&s.elements.every(i=>i.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(r=>r.isTypeOnly))}function dn(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=s=>s===t.fileName?t:void 0,r.fileExists=s=>s===t.fileName,r.readFile=s=>s===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}function Lt(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function _t(e,t,n,r){let s=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,i;try{i=s?t.getShorthandAssignmentValueSymbol(r.parent):Lt(t,r)}catch{i=void 0}return!!i?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}function se(e,t){let n,r=[],s=(a,o,u,m=!1)=>r.push({specifier:u,kind:o,line:cn(t,a),typeOnly:m,unresolved:u===void 0,node:a}),i=a=>{if(e.isImportDeclaration(a))s(a,"import",ye(e,a.moduleSpecifier),on(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)s(a,"export",ye(e,a.moduleSpecifier),on(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))s(a,"require",ye(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let o=a.expression.kind===e.SyntaxKind.ImportKeyword,m=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!_t(e,n??(n=dn(e,t)),t,a.expression);(o||m)&&s(a,m?"require":"dynamic-import",ye(e,a.arguments[0]))}e.forEachChild(a,i)};return i(t),r}function tr(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let s=ye(e,r.argumentExpression);if(s===void 0)return;n.unshift(s)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}function nr(e,t){let n=t.parent;return e.isPropertyAccessExpression(n)||e.isElementAccessExpression(n)?!1:e.isExpressionNode(t)&&!e.isInTypeQuery(t)||e.isShorthandPropertyAssignment(n)&&n.name===t}function ln(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let r=n.length;r>=1;r-=1){let s=n.slice(0,r).join(".");if(e.has(s))return s}}function ie(e,t,n){if(n.length===0)return[];let r=new Set(n),s=dn(e,t),i=new Map,a=new Set;for(let l of t.statements)if(e.isVariableStatement(l))for(let c of l.declarationList.declarations)e.isIdentifier(c.name)&&a.add(c.name.text);let o=l=>{let c=tr(e,l);if(!c)return;let d=Lt(s,c.root),f=d?i.get(d):void 0;return f?[...f,...c.segments.slice(1)]:_t(e,s,t,c.root)||a.has(c.root.text)?void 0:c.segments};for(let l of t.statements)if(e.isVariableStatement(l))for(let c of l.declarationList.declarations){if(!c.initializer||!e.isIdentifier(c.name))continue;let d=o(c.initializer),f=Lt(s,c.name);!d||!f||i.set(f,d)}let u=[],m=new Set,h=(l,c)=>{let d=cn(t,c),f=`${l}:${c.getStart(t)}`;m.has(f)||(m.add(f),u.push({name:l,line:d,node:c}))},g=l=>{let c=l.parent&&(e.isPropertyAccessExpression(l.parent)||e.isElementAccessExpression(l.parent))&&l.parent.expression===l;if((e.isPropertyAccessExpression(l)||e.isElementAccessExpression(l))&&!c){let d=o(l),f=d?ln(r,d):void 0;f&&h(f,l)}else e.isIdentifier(l)&&r.has(l.text)&&nr(e,l)&&!_t(e,s,t,l)&&h(l.text,l);if(e.isVariableDeclaration(l)&&e.isObjectBindingPattern(l.name)&&l.initializer){let d=o(l.initializer);if(d)for(let f of l.name.elements){if(!e.isIdentifier(f.name))continue;let b=f.propertyName?ye(e,f.propertyName)??f.propertyName.text:f.name.text,R=ln(r,[...d,b]);R&&h(R,l.initializer)}}e.forEachChild(l,g)};return g(t),u}function Ft(e,t,n){let r=[];for(let s of n?.dependencies??se(e,t)){if(s.typeOnly||!s.specifier)continue;let i=we(s.specifier);i&&r.push({capability:i,symbol:s.specifier,line:s.line,source:"import-based"})}for(let s of n?.ambientUses??ie(e,t,Pt)){let i=Ze(s.name);i&&r.push({capability:i,symbol:s.name,line:s.line,source:"ambient-global"})}return r.sort((s,i)=>s.line-i.line||s.capability.localeCompare(i.capability)||s.symbol.localeCompare(i.symbol))}var Nt={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."},Mt=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 Dt(e,t){return t.flatMap((r,s)=>(r.prefixes??r.intentPrefixes??[]).map(i=>({layer:r.name,layerIndex:s,prefix:i.endsWith(".")?i:`${i}.`}))).filter(({prefix:r})=>e.startsWith(r)).sort((r,s)=>s.prefix.length-r.prefix.length||r.layerIndex-s.layerIndex)[0]?.layer}function ae(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function $e(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&ae(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:Nt.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:Nt.PUBLISH_MISSING_SOURCE}),t}function w(e,t,n){return{ruleId:e,code:e,message:t,...n}}function me(e,t){return e.slice(0,t).split(`
2
- `).length}function rr(e){let t=[],n=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,r;for(;(r=n.exec(e))!==null;)t.push({value:r[1],index:r.index});return t}function sr(e){let t=[],n=[{kind:"import",re:/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s*)?['"]([^'"]+)['"]/g},{kind:"export",re:/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s*['"]([^'"]+)['"]/g},{kind:"dynamic-import",re:/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g},{kind:"require",re:/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g}];for(let r of n){let s;for(;(s=r.re.exec(e))!==null;){let i=s.index+s[0].indexOf(s[1]),a=s[0],o=r.kind==="import"&&/\bimport\s+type\b/.test(a)||r.kind==="export"&&/\bexport\s+type\b/.test(a);t.push({value:s[1],index:i,kind:r.kind,typeOnly:o})}}return t.sort((r,s)=>r.index-s.index)}function ir(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],s=i=>{e.isStringLiteralLike(i)&&r.push({value:i.text,index:i.getStart(n)}),e.forEachChild(i,s)};return s(n),r}function ar(e){let t=e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);return["adapter","adapters","infra","infrastructure","persistence","repository","repositories","integration","database","db"].some(n=>t.includes(n))}function or(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}function lr(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}function Te(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function cr(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}function pn(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:cr(e,r.name)===n)}function Le(e,t,n){return pn(e,t,n)!==void 0}function Pe(e,t,n){let r=pn(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}function dr(e,t){let n=Pe(e,t,"metadata");return Le(e,n,"source")}function un(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?un(e,t.name):!1:!1}function pr(e,t){if(!e.isCallExpression(t))return!1;let n=t.expression;return e.isPropertyAccessExpression(n)?n.name.text==="publish":e.isIdentifier(n)&&n.text==="publish"}function ur(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=Te(e,n);return r!==void 0&&ae(r)||Le(e,n,"intent")||un(e,n)}function fr(e,t){if(!e.isCallExpression(t))return!1;let[n,r,s]=t.arguments;return dr(e,n)||Le(e,r,"source")||Le(e,s,"source")}function yr(e,t){if(!e.isCallExpression(t))return;let[n,r,s]=t.arguments,i=Pe(e,n,"metadata");return Te(e,Pe(e,i,"source"))??Te(e,Pe(e,r,"source"))??Te(e,Pe(e,s,"source"))}function mr(e,t,n,r){let s=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),i=n,a=i?.filePath,o=i?.layer,u=[],m=g=>s.getLineAndCharacterOfPosition(g.getStart(s)).line+1,h=g=>{if(pr(e,g)){let l=g.arguments[0],c=Te(e,l);for(let f of $e({publishCall:!0,rawIntentName:c,objectHasIntent:Le(e,l,"intent"),arkPublishCandidate:ur(e,g),hasSource:fr(e,g)}))u.push(w(f.ruleId,f.message,{line:m(g),filePath:a}));let d=yr(e,g);if(r&&o&&d&&ae(d)){let f=r.resolveLayer(d);f&&f!==o&&u.push(w("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${d}" resolves to ${f}, but the target file is classified as ${o}.`,{line:m(g),filePath:a,target:d,fromLayer:o,toLayer:f}))}}e.forEachChild(g,h)};return h(s),u}function Ht(e={}){let t=new Set((e.intents||[]).map(i=>typeof i=="string"?i:i.name)),n=e.forbiddenPatterns||[],r=new Set(e.infrastructureLayers??[]),s=e.enforceIntentAllowlist??t.size>0;return{validate(i,a){let o=[],u=a,m=u?.filePath,h=u?.layer,g=e.typescript,l=g?g.createSourceFile(m??"generated.ts",i,g.ScriptTarget.Latest,!0):void 0,c=l?se(e.typescript,l):void 0,d=c?c.filter(p=>p.specifier!==void 0).map(p=>({value:p.specifier,index:p.node.getStart(l),kind:p.kind,typeOnly:p.typeOnly})):sr(i),f=e.typescript?ir(e.typescript,i):rr(i);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(m))for(let p of c?.filter(({unresolved:y})=>y)??[]){let y=p.kind==="require";o.push(w(y?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${y?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:p.line,filePath:m}))}let b=h!==void 0&&(r.has(h)||lr(h)),R=h!==void 0?` If "${h}" is an infrastructure layer, mark it in ark.config.json with "mayImportInfrastructure": true (or name it with an infra token like Adapters/Persistence/Repository).`:"";for(let p of n)if(p instanceof RegExp){p.lastIndex=0;let y=p.exec(i);p.lastIndex=0,y&&o.push(w("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${p}`,{line:y.index===void 0?void 0:me(i,y.index),filePath:m,suggestion:"Remove infrastructure imports from domain/application layers."+R}))}else i.includes(p)&&o.push(w("FORBIDDEN_SUBSTRING",`Forbidden substring: ${p}`,{line:me(i,i.indexOf(p)),filePath:m}));for(let p of d){let y=e.resolveImportTarget?.(p.value,m)??(e.resolveImportLayer?{layer:e.resolveImportLayer(p.value,m)}:void 0),v=typeof m=="string"?e.resolveImportTarget?.(m)??(e.resolveImportLayer?{layer:h,relPath:void 0}:void 0):void 0,C=y?.layer;if(C&&h){let T=K(e.architectureProfile?.rules,h,C,{fromPath:v?.relPath,toPath:y?.relPath,layers:e.architectureLayers});if(T){if(p.typeOnly&&!T.peerIsolation)continue;let _=!!T.peerIsolation;o.push(w("LAYER_IMPORT_VIOLATION",T.message??(_?`Layer "${h}" must not import across slices into "${C}".`:`Layer "${h}" must not import "${C}".`),{line:me(i,p.index),source:p.value,target:p.value,filePath:m,fromLayer:h,toLayer:C,suggestion:_?"Extract shared code to a shared layer, or coordinate slices via events/ports \u2014 do not import across feature/context slices.":"Depend on a port/interface owned by an inner layer instead, or move this code to a layer allowed to make this import.",details:{importKind:p.kind,peerIsolation:_,...p.typeOnly?{typeOnly:!0}:{}}}));continue}continue}b||p.typeOnly||!ar(p.value)&&!or(p.value)||o.push(w("FORBIDDEN_IMPORT",`Forbidden ${p.kind} target: "${p.value}".`,{line:me(i,p.index),source:p.value,target:p.value,filePath:m,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+R,details:{importKind:p.kind}}))}if(e.policies)for(let p of e.policies){let y=p.check({source:i,context:a});if(y!==!0)if(Array.isArray(y))for(let v of y)o.push(w("POLICY_VIOLATION",v.message,{filePath:m,suggestion:`Fix violation of policy "${p.name}".`}));else y===!1?o.push(w("POLICY_VIOLATION",`Policy ${p.name} failed on generated code`)):o.push(w("POLICY_VIOLATION",y.message))}if(s&&t.size>0)for(let p of f)ae(p.value)&&!t.has(p.value)&&o.push(w("UNKNOWN_INTENT",`Unknown intent reference: "${p.value}"`,{line:me(i,p.index),filePath:m,target:p.value,suggestion:`Register intent "${p.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&h)for(let p of f){if(!ae(p.value))continue;let y=e.architectureProfile.resolveLayer(p.value);if(!y)continue;let v=K(e.architectureProfile.rules,h,y);v&&o.push(w("LAYER_REFERENCE_VIOLATION",v.message??`Layer "${h}" must not reference "${y}" through "${p.value}".`,{line:me(i,p.index),filePath:m,target:p.value,fromLayer:h,toLayer:y,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:v}}))}if(e.extensions)for(let p of e.extensions)try{let y=p.analyze(i,a);o.push(...y)}catch(y){o.push(w("EXTENSION_ERROR",`Extension "${p.name}" failed: ${y instanceof Error?y.message:String(y)}`))}if(e.typescript&&l&&h&&e.forbiddenGlobals?.[h]?.length)try{let p=e.forbiddenGlobals[h];o.push(...ie(e.typescript,l,p).map(y=>w("FORBIDDEN_GLOBAL",`${h} must not use the ambient global "${y.name}".`,{line:y.line,filePath:m,target:y.name,fromLayer:h,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let y of c??[]){if(y.typeOnly||!y.specifier)continue;let v=J(y.specifier,p);v&&o.push(w("FORBIDDEN_GLOBAL",`${h} must not use module "${y.specifier}" because it is the import form of forbidden global "${v}".`,{line:y.line,filePath:m,source:y.specifier,target:y.specifier,fromLayer:h,details:{importKind:y.kind,forbiddenGlobal:v},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(p){o.push(w("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${p instanceof Error?p.message:String(p)}`))}if(e.typescript&&l&&h&&e.capabilityWalls?.[h]?.length)try{let p=new Set(e.capabilityWalls[h]),y=e.forbiddenGlobals?.[h]??[];for(let v of Ft(e.typescript,l))p.has(v.capability)&&(v.source==="ambient-global"&&Oe(v.symbol,y)||v.source==="import-based"&&J(v.symbol,y)||o.push(w("CAPABILITY_VIOLATION",v.source==="import-based"?`${h} denies the ${v.capability} capability; found import of "${v.symbol}".`:`${h} denies the ${v.capability} capability; found ambient "${v.symbol}".`,{line:v.line,filePath:m,target:v.symbol,capability:v.capability,fromLayer:h,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(p){o.push(w("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${p instanceof Error?p.message:String(p)}`))}if(e.typescript)try{o.push(...mr(e.typescript,i,a,e.architectureProfile))}catch(p){o.push(w("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${p instanceof Error?p.message:String(p)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:o.length===0,violations:o}}}}var yn="1.1",et="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",fn=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],gr=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function hr(){let e=[];for(let t of fn)for(let n of fn)t===n||gr.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var nt=hr(),Vt=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"}],X={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},tt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:et,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:et,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:"1.1",default:"1.1"},name:{type:"string",minLength:1},include:{...X,minItems:1,default:["src"]},exclude:{...X,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:nt,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...X,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...X,minItems:1},exclude:X,intentPrefixes:X,description:{type:"string",minLength:1},forbiddenGlobals:X,capabilities:{type:"object",additionalProperties:!1,properties:{deny:{type:"array",uniqueItems:!0,items:{type:"string",enum:["network","filesystem","clock","randomness","environment","process","persistence"]}}}},pure:{type:"boolean"},mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...X,minItems:1}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}}}},Y=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
1
+ "use strict";var Ot=Object.defineProperty;var tr=Object.getOwnPropertyDescriptor;var nr=Object.getOwnPropertyNames;var rr=Object.prototype.hasOwnProperty;var sr=(e,t)=>{for(var n in t)Ot(e,n,{get:t[n],enumerable:!0})},ir=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of nr(t))!rr.call(e,s)&&s!==n&&Ot(e,s,{get:()=>t[s],enumerable:!(r=tr(t,s))||r.enumerable});return e};var ar=e=>ir(Ot({},"__esModule",{value:!0}),e);var ws={};sr(ws,{ANALYSIS_IR_SCHEMA_VERSION:()=>lt,ARK_ANALYSIS_RESULT_SCHEMA:()=>on,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>sn,ARK_CONFIG_SCHEMA:()=>rt,ARK_CONFIG_SCHEMA_VERSION:()=>vn,ARK_DESIGN_DELTA_SCHEMA_VERSION:()=>er,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION:()=>Qn,ARK_PROJECT_IDENTITY_SCHEMA:()=>cn,ARK_PROJECT_IDENTITY_SCHEMA_URL:()=>Tt,ARK_PROJECT_IDENTITY_SCHEMA_VERSION:()=>ln,ARK_RULES_SCHEMA:()=>dt,ARK_RULES_SCHEMA_VERSION:()=>$n,ARK_RULE_SENSORS:()=>Wt,EffectiveContractError:()=>Ge,POLICY_DELTA_SCHEMA_VERSION:()=>ht,PROJECT_BINDING_SCHEMA:()=>wt,PROJECT_EXPECTATION_SCHEMA:()=>Pt,RESOLVED_CANDIDATE_FACTS_SCHEMA:()=>ot,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION:()=>re,analyzeArchitectureConvergence:()=>de,analyzeChange:()=>ze,analyzePolicyDelta:()=>Jt,analyzeProject:()=>Ee,analyzeResolvedProject:()=>Se,buildArkRuleFileHints:()=>St,buildEffectiveArkRules:()=>pt,buildRulesInventory:()=>Zn,canPromoteInvariant:()=>yt,classifyArkPolicyDelta:()=>At,collectAnalysisConfigWarnings:()=>Ye,collectEmptyAppliesToFindings:()=>Ct,collectForbiddenCapabilityUses:()=>le,createAICodeGate:()=>Bt,createAdapterResult:()=>an,createArchitectureProfile:()=>Me,createArchitectureProfileFromArkConfig:()=>zt,createElevenLayerArkConfig:()=>Kt,createProjectId:()=>dn,createProjectIdentity:()=>pn,createResolvedCandidateFacts:()=>at,deriveArkRuleFileHints:()=>Qt,detectArchitectureCycles:()=>It,deterministicHash:()=>P,effectiveContractPolicyPayload:()=>ut,elevenLayerProfile:()=>Fe,emptyEffectiveArkRules:()=>ie,evaluateArchitectureGraph:()=>ye,evaluateArkRuleSensors:()=>Et,evaluateInvariantCoverage:()=>ft,explainViolation:()=>Zt,extractClassShapesFromSource:()=>qn,extractSemanticDependencies:()=>oe,inventoryToExtractionCard:()=>Xn,loadArkConfigContract:()=>Ne,loadArkRulesContract:()=>Ue,loadContract:()=>qe,loadResolvedCandidateFacts:()=>ee,parseArkConfigJson:()=>it,parseArkRulesJson:()=>_n,policyDeltaAcknowledgementMatches:()=>bt,preflightChange:()=>en,preflightResolvedChange:()=>tn,resolveEffectiveContract:()=>Nn,resolvedFactsEvidenceRequirementsHash:()=>Ie,stableSerialize:()=>k,toAdapterDiagnostic:()=>Je,version:()=>nn});module.exports=ar(ws);var nn="4.2.0";var sn="1.4";function E(e){return typeof e=="string"&&e.length>0?e:void 0}function rn(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function or(e,t,n){if(e==="LAYER_IMPORT_VIOLATION")return t.typeOnly||n.targetTypeOnlyExports===!0||n.namedBindingsTypeOnly===!0?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":n.peerIsolation===!0?"Extract the shared dependency to a shared layer, then preflight again.":`Define a port in ${t.fromLayer??"the source layer"}, inject the ${t.toLayer??"outer-layer"} implementation, then preflight again.`;if(e==="FORBIDDEN_GLOBAL")return`Inject ${t.target??"the capability"} through a port, then preflight again.`;if(e==="CAPABILITY_VIOLATION")return`Define a ${E(n.capability)??"capability"} port in ${t.fromLayer??"the walled layer"}, bind the implementation outside it, then preflight again.`;if(e==="CIRCULAR_DEPENDENCY")return"Extract the shared dependency into a third module, then preflight again.";if(e==="RAW_EVENT_PUBLISH")return"Publish through a registered intent creator, then run Ark again.";if(e==="PUBLISH_MISSING_SOURCE")return"Add metadata.source to the publish call, then run Ark again.";if(e==="ARKRULE_STRUCTURE"||e==="ARKRULE_INVARIANT"||e==="INVARIANT_UNCOVERED"||e.startsWith("ARKRULE_")){let r=t.arkruleSource??"arkrules/<Layer>.json";return`Fix the structure or invariant for ${t.arkruleId??"the ArkRule"} (declared in ${r}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`}return`Resolve ${e} without weakening ark.config.json, then run Ark again.`}function Je(e,t="error"){let n=E(e.ruleId)??E(e.code)??"ARK_UNKNOWN",r=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,s={...E(e.target)?{target:E(e.target)}:{},...E(e.fromLayer)?{fromLayer:E(e.fromLayer)}:{},...E(e.toLayer)?{toLayer:E(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}:{},...E(e.capability)?{capability:E(e.capability)}:{},...E(e.edgeKind)?{edgeKind:E(e.edgeKind)}:{},...E(e.arkruleId)?{arkruleId:E(e.arkruleId)}:{},...E(e.arkruleSource)?{arkruleSource:E(e.arkruleSource)}:{}};return{ruleId:n,severity:r,message:E(e.message)??n,location:{file:E(e.file)??"<unknown>",line:rn(e.line,1),column:rn(e.column,1)},evidence:s,nextAction:E(e.nextAction)??or(n,s,e)}}function an(e){let t=e.completeness??"complete",n=e.mode??"lexical-compatibility";if(t==="complete"&&(e.completenessReasons?.length??0)>0)throw new Error("completenessReasons must be empty when completeness is complete.");let r=t==="complete"?[]:e.completenessReasons&&e.completenessReasons.length>0?e.completenessReasons.map(o=>({code:E(o.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:E(o.message)??`Analysis ${t}: required evidence is incomplete.`,...E(o.file)?{file:E(o.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],s={...E(e.policyHash)?{policyHash:E(e.policyHash)}:{},...E(e.resolverIdentity)?{resolverIdentity:E(e.resolverIdentity)}:{},...E(e.factsHash)?{factsHash:E(e.factsHash)}:{},...E(e.candidateTreeHash)?{candidateTreeHash:E(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let o of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!s[o])throw new Error(`${o} is required for resolved ${t} adapter evidence.`)}let i=[...(e.violations??[]).map(o=>Je(o,"error")),...(e.warnings??[]).map(o=>Je(o,"warning"))],a={schemaVersion:"1.4",completenessReasons:r,diagnostics:i};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...a,mode:n,valid:!1,completeness:t,...s};let o={policyHash:s.policyHash,resolverIdentity:s.resolverIdentity,factsHash:s.factsHash,candidateTreeHash:s.candidateTreeHash};return t==="complete"?{...a,mode:n,valid:e.valid,completeness:t,...o}:{...a,mode:n,valid:!1,completeness:t,...o}}return t==="complete"?{...a,mode:n,valid:e.valid,completeness:t,...s}:{...a,mode:n,valid:!1,completeness:t,...s}}var on={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","mode","valid","completeness","completenessReasons","diagnostics"],allOf:[{if:{properties:{completeness:{enum:["partial","unavailable"]}},required:["completeness"]},then:{properties:{valid:{const:!1}}}},{if:{properties:{mode:{const:"resolved-candidate-facts"},completeness:{enum:["complete","partial"]}},required:["mode","completeness"]},then:{required:["policyHash","resolverIdentity","factsHash","candidateTreeHash"]}},{if:{properties:{completeness:{const:"complete"}},required:["completeness"]},then:{properties:{completenessReasons:{maxItems:0}}},else:{properties:{completenessReasons:{minItems:1}}}}],properties:{schemaVersion:{const:"1.4"},mode:{enum:["lexical-compatibility","resolved-candidate-facts"]},valid:{type:"boolean"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:{type:"string",minLength:1},message:{type:"string",minLength:1},file:{type:"string",minLength:1}}}},policyHash:{type:"string",minLength:1},resolverIdentity:{type:"string",minLength:1},factsHash:{type:"string",minLength:1},candidateTreeHash:{type:"string",minLength:1},diagnostics:{type:"array",items:{type:"object",additionalProperties:!1,required:["ruleId","severity","message","location","evidence"],properties:{ruleId:{type:"string",minLength:1},severity:{enum:["error","warning"]},message:{type:"string",minLength:1},location:{type:"object",additionalProperties:!1,required:["file","line","column"],properties:{file:{type:"string",minLength:1},line:{type:"integer",minimum:1},column:{type:"integer",minimum:1}}},evidence:{type:"object",additionalProperties:!1,properties:{target:{type:"string"},fromLayer:{type:"string"},toLayer:{type:"string"},typeOnly:{type:"boolean"},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"},peerIsolation:{type:"boolean"},capability:{type:"string",minLength:1},edgeKind:{type:"string",minLength:1},arkruleId:{type:"string",minLength:1},arkruleSource:{type:"string",minLength:1}}},nextAction:{type:"string",minLength:1}}}}}};var ln="1.0",Tt="https://unpkg.com/arkgate@4/schemas/ark.project-identity.schema.json",Ze="^sha256:[a-f0-9]{64}$",Pt={type:"object",additionalProperties:!1,properties:{expectedRoot:{type:"string",minLength:1,description:"Absolute expected workspace/project directory. The initial authoritative handshake requires the exact project root; descendant calls also require expectedProjectId."},expectedProjectId:{type:"string",pattern:Ze,description:"Project id previously returned by ark_identity or ark_manifest."}}},wt={type:"object",additionalProperties:!1,required:["status","authoritative"],properties:{status:{enum:["matched","unverified","mismatch"]},authoritative:{type:"boolean"},expectedRoot:{type:"string",minLength:1},expectedProjectId:{type:"string",pattern:Ze},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},cn={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Tt,title:"ArkGate MCP project identity",description:"Stable project binding plus separate runtime and architecture-contract evidence.",type:"object",additionalProperties:!1,required:["schemaVersion","projectId","resolvedRoot","resolvedConfigPath","arkgateVersion","contractHash","contractSource","runtimeId","processStartedAt"],properties:{schemaVersion:{const:"1.0"},projectId:{type:"string",pattern:Ze},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{type:"string",minLength:1},arkgateVersion:{type:"string",minLength:1},contractHash:{type:"string",pattern:Ze},contractSource:{enum:["project","default-profile","manifest"]},runtimeId:{type:"string",minLength:1},processStartedAt:{type:"string",format:"date-time"}},$defs:{expectation:Pt,binding:wt}};function dn(e,t,n){if(!e||!t)throw new Error("Project identity requires resolvedRoot and resolvedConfigPath.");let r=n(JSON.stringify({resolvedRoot:e,resolvedConfigPath:t})).toLowerCase();if(!/^[a-f0-9]{64}$/.test(r))throw new Error("Project identity hash adapter must return 64 hexadecimal SHA-256 characters.");return`sha256:${r}`}function pn(e){return{schemaVersion:"1.0",...e}}var _t=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),Nt=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Ft=Object.freeze(Object.keys(Nt).sort()),$t=Object.freeze({fs:"filesystem","node:fs":"filesystem","fs/promises":"filesystem","node:fs/promises":"filesystem","fs-extra":"filesystem","graceful-fs":"filesystem",memfs:"filesystem",chokidar:"filesystem",http:"network",https:"network",http2:"network",net:"network",tls:"network",dgram:"network",dns:"network","node:http":"network","node:https":"network","node:http2":"network","node:net":"network","node:tls":"network","node:dgram":"network","node:dns":"network",axios:"network",undici:"network","node-fetch":"network",got:"network",ky:"network",superagent:"network",ws:"network",process:"process","node:process":"process",child_process:"process","node:child_process":"process","@prisma/client":"persistence",prisma:"persistence",pg:"persistence",mysql:"persistence",mysql2:"persistence",mongodb:"persistence",mongoose:"persistence",sqlite3:"persistence","better-sqlite3":"persistence",redis:"persistence",ioredis:"persistence",typeorm:"persistence",knex:"persistence","drizzle-orm":"persistence",sequelize:"persistence",kysely:"persistence","@supabase/supabase-js":"persistence"}),Lt=Object.freeze({process:Object.freeze(["process","node:process"])});function Oe(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=$t[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),s=$t[r];if(s)return s;let i=e.indexOf("/",n+1);return i<0?null:$t[e.slice(0,i)]??null}function te(e,t){for(let n of t)if(Lt[n]?.includes(e))return n;return null}function Xe(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),s=Nt[r];if(s)return s}return null}function me(e){if(e?.pure===!0)return[..._t].sort();let n=(e?.capabilities?.deny??[]).filter(r=>_t.includes(r));return[...new Set(n)].sort()}function Te(e,t){if(t.length===0)return!1;let n=new Set(t),r=e.split(".");for(let s=r.length;s>=1;s-=1)if(n.has(r.slice(0,s).join(".")))return!0;return!1}function Qe(e){let t=new Set,n=new Set,r=Object.keys(Nt);for(let s of e?.forbiddenGlobals??[]){let i=r.filter(a=>a===s||a.startsWith(`${s}.`));if(i.length===0)n.add(s);else for(let a of i)t.add(`ambient:${a}`);for(let a of Lt[s]??[])t.add(`import-exact:${a}`)}for(let s of me(e)){if(t.add(`import:${s}`),s==="process")for(let i of Lt.process)t.add(`import-exact:${i}`);for(let i of r)Xe(i)===s&&t.add(`ambient:${i}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}var un=new Map;function fn(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function et(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let s=e[n+1];if("*?{}[],".includes(s)||s==="\\"){t+="\\"+s,n+=1;continue}t+="/";continue}t+=r}return t}function lr(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="{")t+=1;else if(r==="}"&&(t-=1,t<0))return!1}return t===0}function ae(e){let t=un.get(e);if(t)return t;let n=et(e),r=lr(n),s="",i=0;for(let o=0;o<n.length;o+=1){let d=n[o];d==="\\"&&o+1<n.length?(s+=fn(n[o+1]),o+=1):d==="*"?n[o+1]==="*"?n[o+2]==="/"?(s+="(?:.*/)?",o+=2):(s+=".*",o+=1):s+="[^/]*":d==="?"?s+="[^/]":d==="{"&&r?(s+="(?:",i+=1):d==="}"&&r&&i>0?(s+=")",i-=1):d===","&&r&&i>0?s+="|":s+=fn(d)}let a=new RegExp(`^${s}$`);return un.set(e,a),a}function cr(e){return et(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}function Mt(e,t){let n=et(String(e)),r=cr(n),s=n.replace(/\*/g,"").length,i=r.length*1e4+s;if(t==null||t==="")return i;let a=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return s;let o=0,d=-1;for(let f of r){let g=-1;for(let h=o;h<a.length;h+=1)if(a[h]===f){g=h;break}if(g<0)return i;d=g,o=g+1}return(d+1)*1e6+r.length*1e4+s}function J(e,t){let n=String(e).split(/[/\\]/).join("/"),r,s=-1;for(let i of t??[])if(!(i.exclude??[]).some(a=>ae(a).test(n))){for(let a of i.patterns??[])if(ae(a).test(n)){let o=Mt(a,n);o>s&&(s=o,r=i.name)}}return r}function yn(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),r=new Set(t.map(s=>String(s).toLowerCase()));for(let s=0;s<n.length-1;s+=1)if(r.has(n[s].toLowerCase()))return`${n[s].toLowerCase()}/${n[s+1].toLowerCase()}`}function dr(e){let t=new Set;for(let n of e??[]){let s=et(String(n)).split("/").filter(Boolean);for(let i=0;i<s.length;i+=1){let a=s[i];if((a==="**"||a==="*")&&i>0){let o=s[i-1];o&&!o.includes("*")&&!o.includes("{")&&!o.includes("}")&&t.add(o)}}}return[...t]}function pr(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(s=>typeof s=="string"&&s.length>0);let r=(n??[]).find(s=>s.name===t);return dr(r?.patterns)}function Z(e,t,n,r){for(let s of e??[])if(!(s.from!==t||s.to!==n)&&s.allowed===!1){if(s.peerIsolation){let i=r?.fromPath,a=r?.toPath;if(!i||!a)return s;let o=pr(s,t,r?.layers);if(o.length===0)return s;let d=yn(i,o),f=yn(a,o);if(!d||!f||d!==f)return s;continue}if(t!==n)return s}}function ge(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function hn(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function mn(e,t){if(e.isImportDeclaration(t)){let r=t.importClause;if(!r)return!1;if(r.isTypeOnly)return!0;let s=r.namedBindings;return!!(s&&e.isNamedImports(s)&&s.elements.length>0&&s.elements.every(i=>i.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(r=>r.isTypeOnly))}function An(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=s=>s===t.fileName?t:void 0,r.fileExists=s=>s===t.fileName,r.readFile=s=>s===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}function Dt(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function Ht(e,t,n,r){let s=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,i;try{i=s?t.getShorthandAssignmentValueSymbol(r.parent):Dt(t,r)}catch{i=void 0}return!!i?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}function oe(e,t){let n,r=[],s=(a,o,d,f=!1)=>r.push({specifier:d,kind:o,line:hn(t,a),typeOnly:f,unresolved:d===void 0,node:a}),i=a=>{if(e.isImportDeclaration(a))s(a,"import",ge(e,a.moduleSpecifier),mn(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)s(a,"export",ge(e,a.moduleSpecifier),mn(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))s(a,"require",ge(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let o=a.expression.kind===e.SyntaxKind.ImportKeyword,f=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!Ht(e,n??(n=An(e,t)),t,a.expression);(o||f)&&s(a,f?"require":"dynamic-import",ge(e,a.arguments[0]))}e.forEachChild(a,i)};return i(t),r}function ur(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let s=ge(e,r.argumentExpression);if(s===void 0)return;n.unshift(s)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}function fr(e,t){let n=t.parent;return e.isPropertyAccessExpression(n)||e.isElementAccessExpression(n)?!1:e.isExpressionNode(t)&&!e.isInTypeQuery(t)||e.isShorthandPropertyAssignment(n)&&n.name===t}function gn(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let r=n.length;r>=1;r-=1){let s=n.slice(0,r).join(".");if(e.has(s))return s}}function le(e,t,n){if(n.length===0)return[];let r=new Set(n),s=An(e,t),i=new Map,a=new Set;for(let l of t.statements)if(e.isVariableStatement(l))for(let c of l.declarationList.declarations)e.isIdentifier(c.name)&&a.add(c.name.text);let o=l=>{let c=ur(e,l);if(!c)return;let p=Dt(s,c.root),y=p?i.get(p):void 0;return y?[...y,...c.segments.slice(1)]:Ht(e,s,t,c.root)||a.has(c.root.text)?void 0:c.segments};for(let l of t.statements)if(e.isVariableStatement(l))for(let c of l.declarationList.declarations){if(!c.initializer||!e.isIdentifier(c.name))continue;let p=o(c.initializer),y=Dt(s,c.name);!p||!y||i.set(y,p)}let d=[],f=new Set,g=(l,c)=>{let p=hn(t,c),y=`${l}:${c.getStart(t)}`;f.has(y)||(f.add(y),d.push({name:l,line:p,node:c}))},h=l=>{let c=l.parent&&(e.isPropertyAccessExpression(l.parent)||e.isElementAccessExpression(l.parent))&&l.parent.expression===l;if((e.isPropertyAccessExpression(l)||e.isElementAccessExpression(l))&&!c){let p=o(l),y=p?gn(r,p):void 0;y&&g(y,l)}else e.isIdentifier(l)&&r.has(l.text)&&fr(e,l)&&!Ht(e,s,t,l)&&g(l.text,l);if(e.isVariableDeclaration(l)&&e.isObjectBindingPattern(l.name)&&l.initializer){let p=o(l.initializer);if(p)for(let y of l.name.elements){if(!e.isIdentifier(y.name))continue;let b=y.propertyName?ge(e,y.propertyName)??y.propertyName.text:y.name.text,I=gn(r,[...p,b]);I&&g(I,l.initializer)}}e.forEachChild(l,h)};return h(t),d}function Vt(e,t,n){let r=[];for(let s of n?.dependencies??oe(e,t)){if(s.typeOnly||!s.specifier)continue;let i=Oe(s.specifier);i&&r.push({capability:i,symbol:s.specifier,line:s.line,source:"import-based"})}for(let s of n?.ambientUses??le(e,t,Ft)){let i=Xe(s.name);i&&r.push({capability:i,symbol:s.name,line:s.line,source:"ambient-global"})}return r.sort((s,i)=>s.line-i.line||s.capability.localeCompare(i.capability)||s.symbol.localeCompare(i.symbol))}var jt={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."},Ut=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 Gt(e,t){return t.flatMap((r,s)=>(r.prefixes??r.intentPrefixes??[]).map(i=>({layer:r.name,layerIndex:s,prefix:i.endsWith(".")?i:`${i}.`}))).filter(({prefix:r})=>e.startsWith(r)).sort((r,s)=>s.prefix.length-r.prefix.length||r.layerIndex-s.layerIndex)[0]?.layer}function ce(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function Pe(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&ce(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:jt.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:jt.PUBLISH_MISSING_SOURCE}),t}function O(e,t,n){return{ruleId:e,code:e,message:t,...n}}function he(e,t){return e.slice(0,t).split(`
2
+ `).length}function yr(e){let t=[],n=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,r;for(;(r=n.exec(e))!==null;)t.push({value:r[1],index:r.index});return t}function mr(e){let t=[],n=[{kind:"import",re:/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s*)?['"]([^'"]+)['"]/g},{kind:"export",re:/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s*['"]([^'"]+)['"]/g},{kind:"dynamic-import",re:/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g},{kind:"require",re:/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g}];for(let r of n){let s;for(;(s=r.re.exec(e))!==null;){let i=s.index+s[0].indexOf(s[1]),a=s[0],o=r.kind==="import"&&/\bimport\s+type\b/.test(a)||r.kind==="export"&&/\bexport\s+type\b/.test(a);t.push({value:s[1],index:i,kind:r.kind,typeOnly:o})}}return t.sort((r,s)=>r.index-s.index)}function gr(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],s=i=>{e.isStringLiteralLike(i)&&r.push({value:i.text,index:i.getStart(n)}),e.forEachChild(i,s)};return s(n),r}function hr(e){let t=e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);return["adapter","adapters","infra","infrastructure","persistence","repository","repositories","integration","database","db"].some(n=>t.includes(n))}function Ar(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}function br(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}function $e(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function Rr(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}function bn(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:Rr(e,r.name)===n)}function _e(e,t,n){return bn(e,t,n)!==void 0}function we(e,t,n){let r=bn(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}function Ir(e,t){let n=we(e,t,"metadata");return _e(e,n,"source")}function Rn(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?Rn(e,t.name):!1:!1}function vr(e,t){if(!e.isCallExpression(t))return!1;let n=t.expression;return e.isPropertyAccessExpression(n)?n.name.text==="publish":e.isIdentifier(n)&&n.text==="publish"}function Er(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=$e(e,n);return r!==void 0&&ce(r)||_e(e,n,"intent")||Rn(e,n)}function Cr(e,t){if(!e.isCallExpression(t))return!1;let[n,r,s]=t.arguments;return Ir(e,n)||_e(e,r,"source")||_e(e,s,"source")}function Sr(e,t){if(!e.isCallExpression(t))return;let[n,r,s]=t.arguments,i=we(e,n,"metadata");return $e(e,we(e,i,"source"))??$e(e,we(e,r,"source"))??$e(e,we(e,s,"source"))}function kr(e,t,n,r){let s=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),i=n,a=i?.filePath,o=i?.layer,d=[],f=h=>s.getLineAndCharacterOfPosition(h.getStart(s)).line+1,g=h=>{if(vr(e,h)){let l=h.arguments[0],c=$e(e,l);for(let y of Pe({publishCall:!0,rawIntentName:c,objectHasIntent:_e(e,l,"intent"),arkPublishCandidate:Er(e,h),hasSource:Cr(e,h)}))d.push(O(y.ruleId,y.message,{line:f(h),filePath:a}));let p=Sr(e,h);if(r&&o&&p&&ce(p)){let y=r.resolveLayer(p);y&&y!==o&&d.push(O("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${p}" resolves to ${y}, but the target file is classified as ${o}.`,{line:f(h),filePath:a,target:p,fromLayer:o,toLayer:y}))}}e.forEachChild(h,g)};return g(s),d}function Bt(e={}){let t=new Set((e.intents||[]).map(i=>typeof i=="string"?i:i.name)),n=e.forbiddenPatterns||[],r=new Set(e.infrastructureLayers??[]),s=e.enforceIntentAllowlist??t.size>0;return{validate(i,a){let o=[],d=a,f=d?.filePath,g=d?.layer,h=e.typescript,l=h?h.createSourceFile(f??"generated.ts",i,h.ScriptTarget.Latest,!0):void 0,c=l?oe(e.typescript,l):void 0,p=c?c.filter(u=>u.specifier!==void 0).map(u=>({value:u.specifier,index:u.node.getStart(l),kind:u.kind,typeOnly:u.typeOnly})):mr(i),y=e.typescript?gr(e.typescript,i):yr(i);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(f))for(let u of c?.filter(({unresolved:m})=>m)??[]){let m=u.kind==="require";o.push(O(m?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${m?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:u.line,filePath:f}))}let b=g!==void 0&&(r.has(g)||br(g)),I=g!==void 0?` If "${g}" is an infrastructure layer, mark it in ark.config.json with "mayImportInfrastructure": true (or name it with an infra token like Adapters/Persistence/Repository).`:"";for(let u of n)if(u instanceof RegExp){u.lastIndex=0;let m=u.exec(i);u.lastIndex=0,m&&o.push(O("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${u}`,{line:m.index===void 0?void 0:he(i,m.index),filePath:f,suggestion:"Remove infrastructure imports from domain/application layers."+I}))}else i.includes(u)&&o.push(O("FORBIDDEN_SUBSTRING",`Forbidden substring: ${u}`,{line:he(i,i.indexOf(u)),filePath:f}));for(let u of p){let m=e.resolveImportTarget?.(u.value,f)??(e.resolveImportLayer?{layer:e.resolveImportLayer(u.value,f)}:void 0),R=typeof f=="string"?e.resolveImportTarget?.(f)??(e.resolveImportLayer?{layer:g,relPath:void 0}:void 0):void 0,S=m?.layer;if(S&&g){let T=Z(e.architectureProfile?.rules,g,S,{fromPath:R?.relPath,toPath:m?.relPath,layers:e.architectureLayers});if(T){if(u.typeOnly&&!T.peerIsolation)continue;let L=!!T.peerIsolation;o.push(O("LAYER_IMPORT_VIOLATION",T.message??(L?`Layer "${g}" must not import across slices into "${S}".`:`Layer "${g}" must not import "${S}".`),{line:he(i,u.index),source:u.value,target:u.value,filePath:f,fromLayer:g,toLayer:S,suggestion:L?"Extract shared code to a shared layer, or coordinate slices via events/ports \u2014 do not import across feature/context slices.":"Depend on a port/interface owned by an inner layer instead, or move this code to a layer allowed to make this import.",details:{importKind:u.kind,peerIsolation:L,...u.typeOnly?{typeOnly:!0}:{}}}));continue}continue}b||u.typeOnly||!hr(u.value)&&!Ar(u.value)||o.push(O("FORBIDDEN_IMPORT",`Forbidden ${u.kind} target: "${u.value}".`,{line:he(i,u.index),source:u.value,target:u.value,filePath:f,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+I,details:{importKind:u.kind}}))}if(e.policies)for(let u of e.policies){let m=u.check({source:i,context:a});if(m!==!0)if(Array.isArray(m))for(let R of m)o.push(O("POLICY_VIOLATION",R.message,{filePath:f,suggestion:`Fix violation of policy "${u.name}".`}));else m===!1?o.push(O("POLICY_VIOLATION",`Policy ${u.name} failed on generated code`)):o.push(O("POLICY_VIOLATION",m.message))}if(s&&t.size>0)for(let u of y)ce(u.value)&&!t.has(u.value)&&o.push(O("UNKNOWN_INTENT",`Unknown intent reference: "${u.value}"`,{line:he(i,u.index),filePath:f,target:u.value,suggestion:`Register intent "${u.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&g)for(let u of y){if(!ce(u.value))continue;let m=e.architectureProfile.resolveLayer(u.value);if(!m)continue;let R=Z(e.architectureProfile.rules,g,m);R&&o.push(O("LAYER_REFERENCE_VIOLATION",R.message??`Layer "${g}" must not reference "${m}" through "${u.value}".`,{line:he(i,u.index),filePath:f,target:u.value,fromLayer:g,toLayer:m,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:R}}))}if(e.extensions)for(let u of e.extensions)try{let m=u.analyze(i,a);o.push(...m)}catch(m){o.push(O("EXTENSION_ERROR",`Extension "${u.name}" failed: ${m instanceof Error?m.message:String(m)}`))}if(e.typescript&&l&&g&&e.forbiddenGlobals?.[g]?.length)try{let u=e.forbiddenGlobals[g];o.push(...le(e.typescript,l,u).map(m=>O("FORBIDDEN_GLOBAL",`${g} must not use the ambient global "${m.name}".`,{line:m.line,filePath:f,target:m.name,fromLayer:g,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let m of c??[]){if(m.typeOnly||!m.specifier)continue;let R=te(m.specifier,u);R&&o.push(O("FORBIDDEN_GLOBAL",`${g} must not use module "${m.specifier}" because it is the import form of forbidden global "${R}".`,{line:m.line,filePath:f,source:m.specifier,target:m.specifier,fromLayer:g,details:{importKind:m.kind,forbiddenGlobal:R},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(u){o.push(O("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${u instanceof Error?u.message:String(u)}`))}if(e.typescript&&l&&g&&e.capabilityWalls?.[g]?.length)try{let u=new Set(e.capabilityWalls[g]),m=e.forbiddenGlobals?.[g]??[];for(let R of Vt(e.typescript,l))u.has(R.capability)&&(R.source==="ambient-global"&&Te(R.symbol,m)||R.source==="import-based"&&te(R.symbol,m)||o.push(O("CAPABILITY_VIOLATION",R.source==="import-based"?`${g} denies the ${R.capability} capability; found import of "${R.symbol}".`:`${g} denies the ${R.capability} capability; found ambient "${R.symbol}".`,{line:R.line,filePath:f,target:R.symbol,capability:R.capability,fromLayer:g,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(u){o.push(O("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${u instanceof Error?u.message:String(u)}`))}if(e.typescript)try{o.push(...kr(e.typescript,i,a,e.architectureProfile))}catch(u){o.push(O("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${u instanceof Error?u.message:String(u)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:o.length===0,violations:o}}}}var vn="1.1",nt="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",In=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],xr=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Or(){let e=[];for(let t of In)for(let n of In)t===n||xr.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var st=Or(),qt=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"}],ne={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},rt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:nt,title:"ArkGate architecture contract",description:"Versioned contract consumed identically by ArkGate CLI, MCP, and ESLint surfaces.",type:"object",additionalProperties:!1,required:["$schema","schemaVersion","include","layers","rules"],properties:{$schema:{type:"string",minLength:1,default:nt,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:"1.1",default:"1.1"},name:{type:"string",minLength:1},include:{...ne,minItems:1,default:["src"]},exclude:{...ne,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:st,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...ne,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...ne,minItems:1},exclude:ne,intentPrefixes:ne,description:{type:"string",minLength:1},forbiddenGlobals:ne,capabilities:{type:"object",additionalProperties:!1,properties:{deny:{type:"array",uniqueItems:!0,items:{type:"string",enum:["network","filesystem","clock","randomness","environment","process","persistence"]}}}},pure:{type:"boolean"},mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...ne,minItems:1}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}}}},X=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
3
3
  ${n.map(r=>`- ${r.path}: ${r.message}`).join(`
4
- `)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function mn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Qe(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function ge(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Ar(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function _e(e,t,n,r,s){if(t.$ref){let i=Ar(t.$ref,r);if(!i){s.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}_e(e,i,n,r,s);return}if(t.const!==void 0&&!Object.is(e,t.const)){s.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(i=>Object.is(i,e))){s.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!mn(e)){s.push({path:n,message:`must be an object; received ${ge(e)}`});return}let i=t.properties??{};for(let a of t.required??[])e[a]===void 0&&s.push({path:Qe(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in i||s.push({path:Qe(n,a),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let a=t.additionalProperties;for(let o of Object.keys(e))o in i||_e(e[o],a,Qe(n,o),r,s)}for(let[a,o]of Object.entries(i))e[a]!==void 0&&_e(e[a],o,Qe(n,a),r,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:n,message:`must be an array; received ${ge(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&s.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let i=e.map(a=>JSON.stringify(a));new Set(i).size!==i.length&&s.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((i,a)=>_e(i,t.items,`${n}[${a}]`,r,s));return}if(t.type==="string"){if(typeof e!="string"){s.push({path:n,message:`must be a string; received ${ge(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&s.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&s.push({path:n,message:`must be a boolean; received ${ge(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){s.push({path:n,message:`must be an integer; received ${ge(e)}`});return}t.minimum!==void 0&&e<t.minimum&&s.push({path:n,message:`must be at least ${t.minimum}`})}}function br(e){return{...e,$schema:e.$schema===void 0?et:e.$schema,schemaVersion:e.schemaVersion===void 0?"1.1":e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?nt.map(t=>({...t})):e.rules}}function Rr(){let e=new Set(["1.1"]);for(let t of Vt)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}function vr(e,t="ark.config.json"){if(!mn(e))throw new Y(t,[{path:"$",message:`must be an object; received ${ge(e)}`}]);let n=Rr(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new Y(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.1`}]);if(r!=="unversioned"&&!n.has(r))throw new Y(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected 1.1`}]);let s=r,i={...e},a=0;for(;s!=="1.1"&&a<Vt.length+1;){a+=1;let u=Vt.find(m=>m.from===s);if(!u)throw new Y(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(s)}; expected 1.1`}]);s=u.to,i.schemaVersion=s}if(s!=="1.1")throw new Y(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected 1.1`}]);let o=r==="unversioned"?"unversioned":r==="1.0"?"1.0":null;return{candidate:br(i),migratedFrom:o}}function Fe(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=vr(e,t),s=[];if(_e(n,tt,"$",tt,s),s.length>0)throw new Y(t,s);return{config:n,migratedFrom:r}}function rt(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new Y(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return Fe(n,t)}function gn(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:et,schemaVersion:"1.1"};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}function Ir(e){return e.endsWith(".")?e:`${e}.`}function Er(e,t){let n=e.prefixes.length?Math.max(...e.prefixes.map(s=>s.length)):0;return(t.prefixes.length?Math.max(...t.prefixes.map(s=>s.length)):0)-n}function Me(e){let t=e.layers.map(s=>({...s,prefixes:s.prefixes.map(Ir)})),n=[...t].sort(Er),r=[...e.rules??[]];return{name:e.name,layers:t,rules:r,resolveLayer(s){return t.find(i=>i.match?.(s))?.name??n.find(i=>i.prefixes.some(a=>s.startsWith(a)))?.name}}}function jt(e,t={}){return Me({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,r)=>({name:n.name,prefixes:n.intentPrefixes??[],description:n.description,order:r+1})),rules:e.rules??[]})}var Cr=[{name:"DomainModel",prefixes:["Domain"],description:"Rich domain model, business rules, and domain events.",order:1},{name:"ApplicationOrchestration",prefixes:["Application"],description:"Use cases and command orchestration.",order:2},{name:"PersistenceAdapters",prefixes:["Adapter.Persistence","Adapter.Repository"],description:"Database, repository, and storage adapters.",order:3},{name:"IntegrationAdapters",prefixes:["Adapter.Integration","Adapter.External"],description:"External systems, APIs, and integration adapters.",order:4},{name:"WorkflowSagaEngine",prefixes:["Workflow"],description:"Sagas, workflows, and long-running processes.",order:5},{name:"BackgroundJobsScheduling",prefixes:["Job"],description:"Background jobs, scheduled work, and async processors.",order:6},{name:"PresentationAdapters",prefixes:["Presentation","Adapter.Presentation","Adapter.Api"],description:"API, UI, controller, and presentation adapters.",order:7},{name:"ReportingReadModels",prefixes:["Reporting"],description:"Read models, projections, and reporting surfaces.",order:8},{name:"ExtensibilityMetadata",prefixes:["Metadata"],description:"Metadata, extensions, and schema contracts.",order:9},{name:"SecurityAuditObservability",prefixes:["Security","Audit","Observability"],description:"Security, audit, and observability concerns.",order:10},{name:"Kernel",prefixes:["Kernel"],description:"Ark-owned governance and kernel signals.",order:11}],Ne=Me({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:Cr,rules:nt.map(e=>({...e}))}),Sr={DomainModel:["domain"],ApplicationOrchestration:["application","app"],PersistenceAdapters:["adapters/persistence","adapters/repository","repositories","infra/persistence"],IntegrationAdapters:["adapters/integration","adapters/external","integrations"],WorkflowSagaEngine:["workflows","sagas"],BackgroundJobsScheduling:["jobs","schedules"],PresentationAdapters:["presentation","adapters/presentation","adapters/api"],ReportingReadModels:["reporting","read-models","projections"],ExtensibilityMetadata:["metadata","extensions"],SecurityAuditObservability:["security","audit","observability"],Kernel:["kernel"]};function Ut(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return gn({include:e.include??[t],layers:Ne.layers.map(s=>({name:s.name,patterns:(Sr[s.name]??[s.name]).map(i=>`${r}${i}/**`),intentPrefixes:s.prefixes,optional:n})),rules:[...Ne.rules]})}function O(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}function S(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(S).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${S(t[n])}`).join(",")}}`}var Q="1.1";var hn=["network","filesystem","clock","randomness","environment","process","persistence"];function W(e,t){let n=S(e),r=S(t);return n<r?-1:n>r?1:0}function B(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}function be(e){let t={schemaVersion:"1.1",include:B(e.include??[]),exclude:B(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:B(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:B(n.patterns??[]),exclude:B(n.exclude??[]),forbiddenGlobals:B(n.forbiddenGlobals??[]),intentPrefixes:B(n.intentPrefixes??[]),capabilityDeny:B(n.capabilities?.deny??[]),pure:n.pure===!0})).sort(W),safety:{maxTsSuppressions:e.safety?.maxTsSuppressions??0,maxAnyCasts:e.safety?.maxAnyCasts??0,allowInMemory:e.safety?.allowInMemory===!0,allowDisabledPeerIsolation:e.safety?.allowDisabledPeerIsolation===!0}};return O(S(t))}function kr(e){let t=e.completenessReasons.map(l=>({code:l.code,message:l.message,...l.file?{file:l.file}:{}})).sort(W),n=e.files.map(l=>({...l,typeOnlyExportNames:B(l.typeOnlyExportNames)})).sort((l,c)=>l.path<c.path?-1:l.path>c.path?1:0),r=e.dependencies.map(l=>({...l,...l.namedBindings?{namedBindings:B(l.namedBindings)}:{}})).sort(W),s=e.capabilityUses.map(l=>({...l})).sort(W),i=e.ambientUses.map(l=>({...l})).sort(W),a=e.publishCalls.map(l=>({...l})).sort(W),o=e.intentReferences.map(l=>({...l})).sort(W),u=e.safetyUses.map(l=>({...l})).sort(W),m=(e.classShapes??[]).map(l=>({...l,mutatingMethods:[...l.mutatingMethods??[]].map(c=>({...c}))})).sort(W),h=e.files.map(({path:l,contentHash:c})=>({path:l,contentHash:c})).sort((l,c)=>l.path<c.path?-1:l.path>c.path?1:0),g=O(S(h));return{schemaVersion:"1.1",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:g,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:r,capabilityUses:s,ambientUses:i,publishCalls:a,intentReferences:o,safetyUses:u,classShapes:m}}function bn(e){let t=kr(e);return{...t,factsHash:O(S(t))}}function st(e){return bn(vn(M(e,"$"),!1))}function M(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}function V(e,t,n){let r=new Set(t),s=Object.keys(e).find(i=>!r.has(i));if(s)throw new Error(`${n}.${s} is not part of schema ${"1.1"}.`)}function P(e,t,n){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`${n}.${t} must be a non-empty string.`);return r}function he(e,t,n){if(e[t]!==void 0)return P(e,t,n)}function U(e,t,n){let r=P(e,t,n),s=r.replace(/\\/g,"/");if(!s||s.startsWith("/")||/^[A-Za-z]:\//.test(s)||/[\u0000-\u001f\u007f]/.test(s))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let i=[];for(let o of s.split("/"))if(!(!o||o==="."))if(o===".."){if(i.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);i.pop()}else i.push(o);let a=i.join("/");if(!a||a!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return a}function $(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}function Rn(e,t,n){let r=e[t];if(!Number.isInteger(r)||Number(r)<0)throw new Error(`${n}.${t} must be a non-negative integer.`);return Number(r)}function Ae(e,t,n){let r=Rn(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}function G(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}function ee(e,t,n,r){let s=e[t];if(typeof s!="string"||!n.includes(s))throw new Error(`${r}.${t} must be one of ${n.join(", ")}.`);return s}function An(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!n))throw new Error(`${t} must be an array of non-empty strings.`);return[...e]}function xr(e,t,n){let r=new Set;for(let s of e){let i=t(s);if(r.has(i))throw new Error(`${n} must not contain duplicate facts (${i}).`);r.add(i)}}function vn(e,t){V(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","classShapes",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=ee(e,"schemaVersion",["1.0","1.1"],"$"),r=ee(e,"completeness",["complete","partial","unavailable"],"$"),s=G(e,"completenessReasons","$").map((b,R)=>{let p=`$.completenessReasons[${R}]`,y=M(b,p);V(y,["code","message","file"],p);let v=y.file===void 0?void 0:U(y,"file",p);return{code:P(y,"code",p),message:P(y,"message",p),...v?{file:v}:{}}});if(r==="complete"&&s.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(r!=="complete"&&s.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let i=G(e,"files","$").map((b,R)=>{let p=`$.files[${R}]`,y=M(b,p);return V(y,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],p),{path:U(y,"path",p),contentHash:P(y,"contentHash",p),parseStatus:ee(y,"parseStatus",["parsed","invalid"],p),parseDiagnosticCount:Rn(y,"parseDiagnosticCount",p),exportsOnlyTypes:$(y,"exportsOnlyTypes",p),typeOnlyExportNames:An(y.typeOnlyExportNames,`${p}.typeOnlyExportNames`),hasTopLevelSideEffects:$(y,"hasTopLevelSideEffects",p)}}),a=G(e,"dependencies","$").map((b,R)=>{let p=`$.dependencies[${R}]`,y=M(b,p);V(y,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],p);let v=he(y,"specifier",p),C=he(y,"target",p),T=ee(y,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],p);if(T==="resolved-project"&&!C)throw new Error(`${p}.target is required for resolved-project dependencies.`);if(T!=="resolved-project"&&C)throw new Error(`${p}.target is only allowed for resolved-project dependencies.`);if(T!=="dynamic"&&!v)throw new Error(`${p}.specifier is required unless resolution is dynamic.`);return{from:U(y,"from",p),...v?{specifier:v}:{},kind:ee(y,"kind",["import","export","dynamic-import","require"],p),typeOnly:$(y,"typeOnly",p),line:Ae(y,"line",p),resolution:T,...C?{target:U(y,"target",p)}:{},...y.namedBindings!==void 0?{namedBindings:An(y.namedBindings,`${p}.namedBindings`)}:{},...y.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:$(y,"targetTypeOnlyExports",p)}:{},...y.sourcePureTypeModule!==void 0?{sourcePureTypeModule:$(y,"sourcePureTypeModule",p)}:{},...y.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:$(y,"namedBindingsTypeOnly",p)}:{},...y.portProofEligible!==void 0?{portProofEligible:$(y,"portProofEligible",p)}:{}}}),o=G(e,"capabilityUses","$").map((b,R)=>{let p=`$.capabilityUses[${R}]`,y=M(b,p);return V(y,["file","line","symbol","capability","source"],p),{file:U(y,"file",p),line:Ae(y,"line",p),symbol:P(y,"symbol",p),capability:ee(y,"capability",hn,p),source:ee(y,"source",["ambient-global","import-based"],p)}}),u=G(e,"ambientUses","$").map((b,R)=>{let p=`$.ambientUses[${R}]`,y=M(b,p);return V(y,["file","line","symbol"],p),{file:U(y,"file",p),line:Ae(y,"line",p),symbol:P(y,"symbol",p)}}),m=G(e,"publishCalls","$").map((b,R)=>{let p=`$.publishCalls[${R}]`,y=M(b,p);V(y,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],p);let v=he(y,"rawIntentName",p),C=he(y,"sourceIntent",p);return{file:U(y,"file",p),line:Ae(y,"line",p),...v?{rawIntentName:v}:{},objectHasIntent:$(y,"objectHasIntent",p),arkPublishCandidate:$(y,"arkPublishCandidate",p),hasSource:$(y,"hasSource",p),...C?{sourceIntent:C}:{}}}),h=G(e,"intentReferences","$").map((b,R)=>{let p=`$.intentReferences[${R}]`,y=M(b,p);return V(y,["file","line","intent"],p),{file:U(y,"file",p),line:Ae(y,"line",p),intent:P(y,"intent",p)}}),g=G(e,"safetyUses","$").map((b,R)=>{let p=`$.safetyUses[${R}]`,y=M(b,p);V(y,["file","line","kind","symbol"],p);let v=he(y,"symbol",p),C=ee(y,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],p);if(C==="in-memory-store"&&!v)throw new Error(`${p}.symbol is required for in-memory-store facts.`);if(C!=="in-memory-store"&&v)throw new Error(`${p}.symbol is only allowed for in-memory-store facts.`);return{file:U(y,"file",p),line:Ae(y,"line",p),kind:C,...v?{symbol:v}:{}}});xr(i,b=>b.path,"$.files");let l=new Set(i.map(b=>b.path));for(let b of i){if(b.parseStatus==="parsed"&&b.parseDiagnosticCount!==0)throw new Error(`$.files[${b.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(b.parseStatus==="invalid"&&b.parseDiagnosticCount===0)throw new Error(`$.files[${b.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&i.some(b=>b.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let b of a)if(!l.has(b.from))throw new Error(`$.dependencies references missing source file ${b.from}.`);for(let[b,R]of[["$.capabilityUses",o],["$.ambientUses",u],["$.publishCalls",m],["$.intentReferences",h],["$.safetyUses",g]])for(let p of R)if(!l.has(p.file))throw new Error(`${b} references missing file ${p.file}.`);let c=he(e,"projectPackageName","$"),f=(e.classShapes===void 0?[]:G(e,"classShapes","$")).map((b,R)=>{let p=`$.classShapes[${R}]`,y=M(b,p);V(y,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],p);let v=G(y,"mutatingMethods",p).map((C,T)=>{let _=`${p}.mutatingMethods[${T}]`,x=M(C,_);return V(x,["name","referencesGuardOrPublish"],_),{name:P(x,"name",_),referencesGuardOrPublish:$(x,"referencesGuardOrPublish",_)}});return{file:U(y,"file",p),className:P(y,"className",p),exported:$(y,"exported",p),hasPublicMutableFields:$(y,"hasPublicMutableFields",p),hasPublicSetters:$(y,"hasPublicSetters",p),hasPublicConstructor:$(y,"hasPublicConstructor",p),hasStaticFactory:$(y,"hasStaticFactory",p),mutatingMethods:v,...y.dataOnly===void 0?{}:{dataOnly:$(y,"dataOnly",p)}}});return{schemaVersion:n,completeness:r,completenessReasons:s,resolverIdentity:P(e,"resolverIdentity","$"),compilerIdentity:P(e,"compilerIdentity","$"),compilerOptionsHash:P(e,"compilerOptionsHash","$"),tsconfigHash:P(e,"tsconfigHash","$"),evidenceRequirementsHash:P(e,"evidenceRequirementsHash","$"),...c?{projectPackageName:c}:{},files:i,dependencies:a,capabilityUses:o,ambientUses:u,publishCalls:m,intentReferences:h,safetyUses:g,classShapes:f}}function Z(e){let t=M(e,"$"),n=P(t,"factsHash","$"),r=P(t,"candidateTreeHash","$"),s=bn(vn(t,!0));if(s.factsHash!==n)throw new Error(`$.factsHash does not match the canonical payload (${s.factsHash}).`);if(r!==s.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${s.candidateTreeHash}).`);return s}var wr=["network","filesystem","clock","randomness","environment","process","persistence"],k={type:"string",minLength:1},Re={type:"integer",minimum:1},q={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},it={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.resolved-candidate-facts.schema.json",title:"ArkGate resolved candidate facts",type:"object",additionalProperties:!1,required:["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","candidateTreeHash","evidenceRequirementsHash","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","factsHash"],properties:{schemaVersion:{enum:["1.0","1.1"]},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:k,message:k,file:q}}},resolverIdentity:k,compilerIdentity:k,compilerOptionsHash:k,tsconfigHash:k,candidateTreeHash:k,evidenceRequirementsHash:k,projectPackageName:k,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:q,contentHash:k,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:k},hasTopLevelSideEffects:{type:"boolean"}},allOf:[{if:{properties:{parseStatus:{const:"parsed"}}},then:{properties:{parseDiagnosticCount:{const:0}}}},{if:{properties:{parseStatus:{const:"invalid"}}},then:{properties:{parseDiagnosticCount:{minimum:1}}}}]}},dependencies:{type:"array",items:{type:"object",additionalProperties:!1,required:["from","kind","typeOnly","line","resolution"],properties:{from:q,specifier:k,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:Re,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:q,namedBindings:{type:"array",items:k},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"}},allOf:[{if:{properties:{resolution:{const:"resolved-project"}}},then:{required:["target"]},else:{not:{required:["target"]}}},{if:{properties:{resolution:{const:"dynamic"}}},else:{required:["specifier"]}}]}},capabilityUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol","capability","source"],properties:{file:q,line:Re,symbol:k,capability:{enum:wr},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:q,line:Re,symbol:k}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:q,line:Re,rawIntentName:k,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:k}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:q,line:Re,intent:k}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:q,line:Re,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:k},allOf:[{if:{properties:{kind:{const:"in-memory-store"}}},then:{required:["symbol"]},else:{not:{required:["symbol"]}}}]}},classShapes:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods"],properties:{file:q,className:k,exported:{type:"boolean"},hasPublicMutableFields:{type:"boolean"},hasPublicSetters:{type:"boolean"},hasPublicConstructor:{type:"boolean"},hasStaticFactory:{type:"boolean"},dataOnly:{type:"boolean"},mutatingMethods:{type:"array",items:{type:"object",additionalProperties:!1,required:["name","referencesGuardOrPublish"],properties:{name:k,referencesGuardOrPublish:{type:"boolean"}}}}}}},factsHash:k},allOf:[{if:{properties:{completeness:{const:"complete"}}},then:{properties:{completenessReasons:{maxItems:0},files:{items:{properties:{parseStatus:{const:"parsed"}}}}}}},{if:{properties:{completeness:{enum:["partial","unavailable"]}}},then:{properties:{completenessReasons:{minItems:1}}}}]};var at="1.0";function F(e){return`${e.from}->${e.to}`}function De(e,t,n,r="dependency"){return{id:`${e}:${r}:${F(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${F(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${F(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${F(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${F(t)} from the candidate, then preflight again.`}:{}}}function oe(e){let t=[],n=new Map(e.changeMap.map.files.map(l=>[l.path,l])),r=new Map(e.changes.map(l=>[l.path,l])),s=new Map(e.changeMap.map.dependencies.map(l=>[F(l),l])),i=new Map(e.baseDependencies.map(l=>[F(l),l])),a=new Map(e.candidateDependencies.map(l=>[F(l),l]));for(let l of[...n.values()].sort((c,d)=>c.path.localeCompare(d.path))){let c=r.get(l.path);c?c.operation!==l.operation?t.push({id:`contradictory:file:${l.path}`,classification:"contradictory",subject:"file",path:l.path,expectedOperation:l.operation,actualOperation:c.operation,message:`${l.path} was planned as ${l.operation} but the actual operation is ${c.operation}.`,nextAction:`Change ${l.path} to the planned ${l.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${l.path}`,classification:"satisfied",subject:"file",path:l.path,expectedOperation:l.operation,actualOperation:c.operation,message:`${l.path} matches the planned ${l.operation} operation.`}):t.push({id:`missing:file:${l.path}`,classification:"missing",subject:"file",path:l.path,expectedOperation:l.operation,message:`${l.path} was planned as ${l.operation} but is absent from the actual change.`,nextAction:`${l.operation[0].toUpperCase()}${l.operation.slice(1)} ${l.path} in the complete change set, then preflight again.`})}for(let l of[...r.values()].sort((c,d)=>c.path.localeCompare(d.path)))n.has(l.path)||t.push({id:`unplanned:file:${l.path}`,classification:"unplanned",subject:"file",path:l.path,actualOperation:l.operation,message:`${l.path} has an unplanned ${l.operation} operation.`,nextAction:`Remove ${l.path} from the change set, then preflight again.`});let o=new Set;for(let l of[...s.values()].sort((c,d)=>F(c).localeCompare(F(d)))){if(a.has(F(l))){t.push(De("satisfied",l,`${l.from} -> ${l.to} exists in the candidate architecture.`));continue}let c={from:l.to,to:l.from};a.has(F(c))?(o.add(F(c)),t.push(De("contradictory",l,`${l.from} -> ${l.to} was planned, but the candidate contains the reverse edge.`))):t.push(De("missing",l,`${l.from} -> ${l.to} is absent from the candidate architecture.`))}let u=new Set([...n.keys(),...r.keys()]);for(let[l,c]of[...a].sort(([d],[f])=>d.localeCompare(f)))i.has(l)||s.has(l)||o.has(l)||!u.has(c.from)&&!u.has(c.to)||t.push({...De("unplanned",c,`${c.from} -> ${c.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let m=new Set(e.changeMap.map.files.filter(l=>l.operation==="delete").map(l=>l.path));for(let[l,c]of[...i].sort(([d],[f])=>d.localeCompare(f)))a.has(l)||m.has(c.from)||m.has(c.to)||!u.has(c.from)&&!u.has(c.to)||t.push({...De("unplanned",c,`${c.from} -> ${c.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let h={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((l,c)=>h[l.classification]-h[c.classification]||(l.subject===c.subject?0:l.subject==="file"?-1:1)||l.id.localeCompare(c.id));let g={satisfied:t.filter(l=>l.classification==="satisfied").length,missing:t.filter(l=>l.classification==="missing").length,contradictory:t.filter(l=>l.classification==="contradictory").length,unplanned:t.filter(l=>l.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:g.missing===0&&g.contradictory===0&&g.unplanned===0,behavioralCompletion:"not-evaluated",summary:g,findings:t}}var Cn="1.0",Gt="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",Bt=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","no-anemic-model","invariant-coverage"],Or=["no-anemic-model"],In={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},lt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Gt,title:"ArkGate ArkRules (intra-layer contract)",description:"Per-layer structure sensors and invariant catalog consumed by the ArkGate Effective Contract.",type:"object",additionalProperties:!1,required:["schemaVersion","layer"],properties:{$schema:{type:"string",minLength:1,default:Gt},schemaVersion:{type:"string",const:"1.0",default:"1.0"},layer:{type:"string",minLength:1},structure:{type:"array",default:[],items:{$ref:"#/$defs/structureEntry"}},invariants:{type:"array",default:[],items:{$ref:"#/$defs/invariantEntry"}}},$defs:{structureEntry:{type:"object",additionalProperties:!1,required:["id","sensor"],properties:{id:{type:"string",minLength:1},sensor:{type:"string",enum:[...Bt]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:In,description:{type:"string",minLength:1}}},invariantEntry:{type:"object",additionalProperties:!1,required:["id","description"],properties:{id:{type:"string",minLength:1},description:{type:"string",minLength:1},aggregate:{type:"string",minLength:1},coverage:{type:"object",additionalProperties:!1,properties:{test:{type:"boolean"},symbol:{type:"string",minLength:1}}},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:In}}}},le=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkRules (${t}):
4
+ `)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function En(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function tt(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function Ae(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Tr(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function Le(e,t,n,r,s){if(t.$ref){let i=Tr(t.$ref,r);if(!i){s.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}Le(e,i,n,r,s);return}if(t.const!==void 0&&!Object.is(e,t.const)){s.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(i=>Object.is(i,e))){s.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!En(e)){s.push({path:n,message:`must be an object; received ${Ae(e)}`});return}let i=t.properties??{};for(let a of t.required??[])e[a]===void 0&&s.push({path:tt(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in i||s.push({path:tt(n,a),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let a=t.additionalProperties;for(let o of Object.keys(e))o in i||Le(e[o],a,tt(n,o),r,s)}for(let[a,o]of Object.entries(i))e[a]!==void 0&&Le(e[a],o,tt(n,a),r,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:n,message:`must be an array; received ${Ae(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&s.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let i=e.map(a=>JSON.stringify(a));new Set(i).size!==i.length&&s.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((i,a)=>Le(i,t.items,`${n}[${a}]`,r,s));return}if(t.type==="string"){if(typeof e!="string"){s.push({path:n,message:`must be a string; received ${Ae(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&s.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&s.push({path:n,message:`must be a boolean; received ${Ae(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){s.push({path:n,message:`must be an integer; received ${Ae(e)}`});return}t.minimum!==void 0&&e<t.minimum&&s.push({path:n,message:`must be at least ${t.minimum}`})}}function Pr(e){return{...e,$schema:e.$schema===void 0?nt:e.$schema,schemaVersion:e.schemaVersion===void 0?"1.1":e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?st.map(t=>({...t})):e.rules}}function wr(){let e=new Set(["1.1"]);for(let t of qt)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}function $r(e,t="ark.config.json"){if(!En(e))throw new X(t,[{path:"$",message:`must be an object; received ${Ae(e)}`}]);let n=wr(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new X(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.1`}]);if(r!=="unversioned"&&!n.has(r))throw new X(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected 1.1`}]);let s=r,i={...e},a=0;for(;s!=="1.1"&&a<qt.length+1;){a+=1;let d=qt.find(f=>f.from===s);if(!d)throw new X(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(s)}; expected 1.1`}]);s=d.to,i.schemaVersion=s}if(s!=="1.1")throw new X(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected 1.1`}]);let o=r==="unversioned"?"unversioned":r==="1.0"?"1.0":null;return{candidate:Pr(i),migratedFrom:o}}function Ne(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=$r(e,t),s=[];if(Le(n,rt,"$",rt,s),s.length>0)throw new X(t,s);return{config:n,migratedFrom:r}}function it(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new X(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return Ne(n,t)}function Cn(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:nt,schemaVersion:"1.1"};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}function _r(e){return e.endsWith(".")?e:`${e}.`}function Lr(e,t){let n=e.prefixes.length?Math.max(...e.prefixes.map(s=>s.length)):0;return(t.prefixes.length?Math.max(...t.prefixes.map(s=>s.length)):0)-n}function Me(e){let t=e.layers.map(s=>({...s,prefixes:s.prefixes.map(_r)})),n=[...t].sort(Lr),r=[...e.rules??[]];return{name:e.name,layers:t,rules:r,resolveLayer(s){return t.find(i=>i.match?.(s))?.name??n.find(i=>i.prefixes.some(a=>s.startsWith(a)))?.name}}}function zt(e,t={}){return Me({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,r)=>({name:n.name,prefixes:n.intentPrefixes??[],description:n.description,order:r+1})),rules:e.rules??[]})}var Nr=[{name:"DomainModel",prefixes:["Domain"],description:"Rich domain model, business rules, and domain events.",order:1},{name:"ApplicationOrchestration",prefixes:["Application"],description:"Use cases and command orchestration.",order:2},{name:"PersistenceAdapters",prefixes:["Adapter.Persistence","Adapter.Repository"],description:"Database, repository, and storage adapters.",order:3},{name:"IntegrationAdapters",prefixes:["Adapter.Integration","Adapter.External"],description:"External systems, APIs, and integration adapters.",order:4},{name:"WorkflowSagaEngine",prefixes:["Workflow"],description:"Sagas, workflows, and long-running processes.",order:5},{name:"BackgroundJobsScheduling",prefixes:["Job"],description:"Background jobs, scheduled work, and async processors.",order:6},{name:"PresentationAdapters",prefixes:["Presentation","Adapter.Presentation","Adapter.Api"],description:"API, UI, controller, and presentation adapters.",order:7},{name:"ReportingReadModels",prefixes:["Reporting"],description:"Read models, projections, and reporting surfaces.",order:8},{name:"ExtensibilityMetadata",prefixes:["Metadata"],description:"Metadata, extensions, and schema contracts.",order:9},{name:"SecurityAuditObservability",prefixes:["Security","Audit","Observability"],description:"Security, audit, and observability concerns.",order:10},{name:"Kernel",prefixes:["Kernel"],description:"Ark-owned governance and kernel signals.",order:11}],Fe=Me({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:Nr,rules:st.map(e=>({...e}))}),Fr={DomainModel:["domain"],ApplicationOrchestration:["application","app"],PersistenceAdapters:["adapters/persistence","adapters/repository","repositories","infra/persistence"],IntegrationAdapters:["adapters/integration","adapters/external","integrations"],WorkflowSagaEngine:["workflows","sagas"],BackgroundJobsScheduling:["jobs","schedules"],PresentationAdapters:["presentation","adapters/presentation","adapters/api"],ReportingReadModels:["reporting","read-models","projections"],ExtensibilityMetadata:["metadata","extensions"],SecurityAuditObservability:["security","audit","observability"],Kernel:["kernel"]};function Kt(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return Cn({include:e.include??[t],layers:Fe.layers.map(s=>({name:s.name,patterns:(Fr[s.name]??[s.name]).map(i=>`${r}${i}/**`),intentPrefixes:s.prefixes,optional:n})),rules:[...Fe.rules]})}function P(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}function k(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(k).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${k(t[n])}`).join(",")}}`}var re="1.1";var Sn=["network","filesystem","clock","randomness","environment","process","persistence"];function Q(e,t){let n=k(e),r=k(t);return n<r?-1:n>r?1:0}function Y(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}function Ie(e){let t={schemaVersion:"1.1",include:Y(e.include??[]),exclude:Y(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:Y(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:Y(n.patterns??[]),exclude:Y(n.exclude??[]),forbiddenGlobals:Y(n.forbiddenGlobals??[]),intentPrefixes:Y(n.intentPrefixes??[]),capabilityDeny:Y(n.capabilities?.deny??[]),pure:n.pure===!0})).sort(Q),safety:{maxTsSuppressions:e.safety?.maxTsSuppressions??0,maxAnyCasts:e.safety?.maxAnyCasts??0,allowInMemory:e.safety?.allowInMemory===!0,allowDisabledPeerIsolation:e.safety?.allowDisabledPeerIsolation===!0}};return P(k(t))}function Mr(e){let t=e.completenessReasons.map(l=>({code:l.code,message:l.message,...l.file?{file:l.file}:{}})).sort(Q),n=e.files.map(l=>({...l,typeOnlyExportNames:Y(l.typeOnlyExportNames)})).sort((l,c)=>l.path<c.path?-1:l.path>c.path?1:0),r=e.dependencies.map(l=>({...l,...l.namedBindings?{namedBindings:Y(l.namedBindings)}:{}})).sort(Q),s=e.capabilityUses.map(l=>({...l})).sort(Q),i=e.ambientUses.map(l=>({...l})).sort(Q),a=e.publishCalls.map(l=>({...l})).sort(Q),o=e.intentReferences.map(l=>({...l})).sort(Q),d=e.safetyUses.map(l=>({...l})).sort(Q),f=(e.classShapes??[]).map(l=>({...l,mutatingMethods:[...l.mutatingMethods??[]].map(c=>({...c}))})).sort(Q),g=e.files.map(({path:l,contentHash:c})=>({path:l,contentHash:c})).sort((l,c)=>l.path<c.path?-1:l.path>c.path?1:0),h=P(k(g));return{schemaVersion:"1.1",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:h,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:r,capabilityUses:s,ambientUses:i,publishCalls:a,intentReferences:o,safetyUses:d,classShapes:f}}function xn(e){let t=Mr(e);return{...t,factsHash:P(k(t))}}function at(e){return xn(Tn(V(e,"$"),!1))}function V(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}function G(e,t,n){let r=new Set(t),s=Object.keys(e).find(i=>!r.has(i));if(s)throw new Error(`${n}.${s} is not part of schema ${"1.1"}.`)}function _(e,t,n){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`${n}.${t} must be a non-empty string.`);return r}function be(e,t,n){if(e[t]!==void 0)return _(e,t,n)}function z(e,t,n){let r=_(e,t,n),s=r.replace(/\\/g,"/");if(!s||s.startsWith("/")||/^[A-Za-z]:\//.test(s)||/[\u0000-\u001f\u007f]/.test(s))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let i=[];for(let o of s.split("/"))if(!(!o||o==="."))if(o===".."){if(i.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);i.pop()}else i.push(o);let a=i.join("/");if(!a||a!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return a}function $(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}function On(e,t,n){let r=e[t];if(!Number.isInteger(r)||Number(r)<0)throw new Error(`${n}.${t} must be a non-negative integer.`);return Number(r)}function Re(e,t,n){let r=On(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}function K(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}function se(e,t,n,r){let s=e[t];if(typeof s!="string"||!n.includes(s))throw new Error(`${r}.${t} must be one of ${n.join(", ")}.`);return s}function kn(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!n))throw new Error(`${t} must be an array of non-empty strings.`);return[...e]}function Dr(e,t,n){let r=new Set;for(let s of e){let i=t(s);if(r.has(i))throw new Error(`${n} must not contain duplicate facts (${i}).`);r.add(i)}}function Tn(e,t){G(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","classShapes",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=se(e,"schemaVersion",["1.0","1.1"],"$"),r=se(e,"completeness",["complete","partial","unavailable"],"$"),s=K(e,"completenessReasons","$").map((b,I)=>{let u=`$.completenessReasons[${I}]`,m=V(b,u);G(m,["code","message","file"],u);let R=m.file===void 0?void 0:z(m,"file",u);return{code:_(m,"code",u),message:_(m,"message",u),...R?{file:R}:{}}});if(r==="complete"&&s.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(r!=="complete"&&s.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let i=K(e,"files","$").map((b,I)=>{let u=`$.files[${I}]`,m=V(b,u);return G(m,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],u),{path:z(m,"path",u),contentHash:_(m,"contentHash",u),parseStatus:se(m,"parseStatus",["parsed","invalid"],u),parseDiagnosticCount:On(m,"parseDiagnosticCount",u),exportsOnlyTypes:$(m,"exportsOnlyTypes",u),typeOnlyExportNames:kn(m.typeOnlyExportNames,`${u}.typeOnlyExportNames`),hasTopLevelSideEffects:$(m,"hasTopLevelSideEffects",u)}}),a=K(e,"dependencies","$").map((b,I)=>{let u=`$.dependencies[${I}]`,m=V(b,u);G(m,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],u);let R=be(m,"specifier",u),S=be(m,"target",u),T=se(m,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],u);if(T==="resolved-project"&&!S)throw new Error(`${u}.target is required for resolved-project dependencies.`);if(T!=="resolved-project"&&S)throw new Error(`${u}.target is only allowed for resolved-project dependencies.`);if(T!=="dynamic"&&!R)throw new Error(`${u}.specifier is required unless resolution is dynamic.`);return{from:z(m,"from",u),...R?{specifier:R}:{},kind:se(m,"kind",["import","export","dynamic-import","require"],u),typeOnly:$(m,"typeOnly",u),line:Re(m,"line",u),resolution:T,...S?{target:z(m,"target",u)}:{},...m.namedBindings!==void 0?{namedBindings:kn(m.namedBindings,`${u}.namedBindings`)}:{},...m.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:$(m,"targetTypeOnlyExports",u)}:{},...m.sourcePureTypeModule!==void 0?{sourcePureTypeModule:$(m,"sourcePureTypeModule",u)}:{},...m.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:$(m,"namedBindingsTypeOnly",u)}:{},...m.portProofEligible!==void 0?{portProofEligible:$(m,"portProofEligible",u)}:{}}}),o=K(e,"capabilityUses","$").map((b,I)=>{let u=`$.capabilityUses[${I}]`,m=V(b,u);return G(m,["file","line","symbol","capability","source"],u),{file:z(m,"file",u),line:Re(m,"line",u),symbol:_(m,"symbol",u),capability:se(m,"capability",Sn,u),source:se(m,"source",["ambient-global","import-based"],u)}}),d=K(e,"ambientUses","$").map((b,I)=>{let u=`$.ambientUses[${I}]`,m=V(b,u);return G(m,["file","line","symbol"],u),{file:z(m,"file",u),line:Re(m,"line",u),symbol:_(m,"symbol",u)}}),f=K(e,"publishCalls","$").map((b,I)=>{let u=`$.publishCalls[${I}]`,m=V(b,u);G(m,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],u);let R=be(m,"rawIntentName",u),S=be(m,"sourceIntent",u);return{file:z(m,"file",u),line:Re(m,"line",u),...R?{rawIntentName:R}:{},objectHasIntent:$(m,"objectHasIntent",u),arkPublishCandidate:$(m,"arkPublishCandidate",u),hasSource:$(m,"hasSource",u),...S?{sourceIntent:S}:{}}}),g=K(e,"intentReferences","$").map((b,I)=>{let u=`$.intentReferences[${I}]`,m=V(b,u);return G(m,["file","line","intent"],u),{file:z(m,"file",u),line:Re(m,"line",u),intent:_(m,"intent",u)}}),h=K(e,"safetyUses","$").map((b,I)=>{let u=`$.safetyUses[${I}]`,m=V(b,u);G(m,["file","line","kind","symbol"],u);let R=be(m,"symbol",u),S=se(m,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],u);if(S==="in-memory-store"&&!R)throw new Error(`${u}.symbol is required for in-memory-store facts.`);if(S!=="in-memory-store"&&R)throw new Error(`${u}.symbol is only allowed for in-memory-store facts.`);return{file:z(m,"file",u),line:Re(m,"line",u),kind:S,...R?{symbol:R}:{}}});Dr(i,b=>b.path,"$.files");let l=new Set(i.map(b=>b.path));for(let b of i){if(b.parseStatus==="parsed"&&b.parseDiagnosticCount!==0)throw new Error(`$.files[${b.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(b.parseStatus==="invalid"&&b.parseDiagnosticCount===0)throw new Error(`$.files[${b.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&i.some(b=>b.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let b of a)if(!l.has(b.from))throw new Error(`$.dependencies references missing source file ${b.from}.`);for(let[b,I]of[["$.capabilityUses",o],["$.ambientUses",d],["$.publishCalls",f],["$.intentReferences",g],["$.safetyUses",h]])for(let u of I)if(!l.has(u.file))throw new Error(`${b} references missing file ${u.file}.`);let c=be(e,"projectPackageName","$"),y=(e.classShapes===void 0?[]:K(e,"classShapes","$")).map((b,I)=>{let u=`$.classShapes[${I}]`,m=V(b,u);G(m,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],u);let R=K(m,"mutatingMethods",u).map((S,T)=>{let L=`${u}.mutatingMethods[${T}]`,v=V(S,L);return G(v,["name","referencesGuardOrPublish"],L),{name:_(v,"name",L),referencesGuardOrPublish:$(v,"referencesGuardOrPublish",L)}});return{file:z(m,"file",u),className:_(m,"className",u),exported:$(m,"exported",u),hasPublicMutableFields:$(m,"hasPublicMutableFields",u),hasPublicSetters:$(m,"hasPublicSetters",u),hasPublicConstructor:$(m,"hasPublicConstructor",u),hasStaticFactory:$(m,"hasStaticFactory",u),mutatingMethods:R,...m.dataOnly===void 0?{}:{dataOnly:$(m,"dataOnly",u)}}});return{schemaVersion:n,completeness:r,completenessReasons:s,resolverIdentity:_(e,"resolverIdentity","$"),compilerIdentity:_(e,"compilerIdentity","$"),compilerOptionsHash:_(e,"compilerOptionsHash","$"),tsconfigHash:_(e,"tsconfigHash","$"),evidenceRequirementsHash:_(e,"evidenceRequirementsHash","$"),...c?{projectPackageName:c}:{},files:i,dependencies:a,capabilityUses:o,ambientUses:d,publishCalls:f,intentReferences:g,safetyUses:h,classShapes:y}}function ee(e){let t=V(e,"$"),n=_(t,"factsHash","$"),r=_(t,"candidateTreeHash","$"),s=xn(Tn(t,!0));if(s.factsHash!==n)throw new Error(`$.factsHash does not match the canonical payload (${s.factsHash}).`);if(r!==s.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${s.candidateTreeHash}).`);return s}var Hr=["network","filesystem","clock","randomness","environment","process","persistence"],x={type:"string",minLength:1},ve={type:"integer",minimum:1},W={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},ot={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.resolved-candidate-facts.schema.json",title:"ArkGate resolved candidate facts",type:"object",additionalProperties:!1,required:["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","candidateTreeHash","evidenceRequirementsHash","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","factsHash"],properties:{schemaVersion:{enum:["1.0","1.1"]},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:x,message:x,file:W}}},resolverIdentity:x,compilerIdentity:x,compilerOptionsHash:x,tsconfigHash:x,candidateTreeHash:x,evidenceRequirementsHash:x,projectPackageName:x,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:W,contentHash:x,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:x},hasTopLevelSideEffects:{type:"boolean"}},allOf:[{if:{properties:{parseStatus:{const:"parsed"}}},then:{properties:{parseDiagnosticCount:{const:0}}}},{if:{properties:{parseStatus:{const:"invalid"}}},then:{properties:{parseDiagnosticCount:{minimum:1}}}}]}},dependencies:{type:"array",items:{type:"object",additionalProperties:!1,required:["from","kind","typeOnly","line","resolution"],properties:{from:W,specifier:x,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:ve,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:W,namedBindings:{type:"array",items:x},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"}},allOf:[{if:{properties:{resolution:{const:"resolved-project"}}},then:{required:["target"]},else:{not:{required:["target"]}}},{if:{properties:{resolution:{const:"dynamic"}}},else:{required:["specifier"]}}]}},capabilityUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol","capability","source"],properties:{file:W,line:ve,symbol:x,capability:{enum:Hr},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:W,line:ve,symbol:x}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:W,line:ve,rawIntentName:x,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:x}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:W,line:ve,intent:x}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:W,line:ve,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:x},allOf:[{if:{properties:{kind:{const:"in-memory-store"}}},then:{required:["symbol"]},else:{not:{required:["symbol"]}}}]}},classShapes:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods"],properties:{file:W,className:x,exported:{type:"boolean"},hasPublicMutableFields:{type:"boolean"},hasPublicSetters:{type:"boolean"},hasPublicConstructor:{type:"boolean"},hasStaticFactory:{type:"boolean"},dataOnly:{type:"boolean"},mutatingMethods:{type:"array",items:{type:"object",additionalProperties:!1,required:["name","referencesGuardOrPublish"],properties:{name:x,referencesGuardOrPublish:{type:"boolean"}}}}}}},factsHash:x},allOf:[{if:{properties:{completeness:{const:"complete"}}},then:{properties:{completenessReasons:{maxItems:0},files:{items:{properties:{parseStatus:{const:"parsed"}}}}}}},{if:{properties:{completeness:{enum:["partial","unavailable"]}}},then:{properties:{completenessReasons:{minItems:1}}}}]};var lt="1.0";function D(e){return`${e.from}->${e.to}`}function De(e,t,n,r="dependency"){return{id:`${e}:${r}:${D(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${D(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${D(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${D(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${D(t)} from the candidate, then preflight again.`}:{}}}function de(e){let t=[],n=new Map(e.changeMap.map.files.map(l=>[l.path,l])),r=new Map(e.changes.map(l=>[l.path,l])),s=new Map(e.changeMap.map.dependencies.map(l=>[D(l),l])),i=new Map(e.baseDependencies.map(l=>[D(l),l])),a=new Map(e.candidateDependencies.map(l=>[D(l),l]));for(let l of[...n.values()].sort((c,p)=>c.path.localeCompare(p.path))){let c=r.get(l.path);c?c.operation!==l.operation?t.push({id:`contradictory:file:${l.path}`,classification:"contradictory",subject:"file",path:l.path,expectedOperation:l.operation,actualOperation:c.operation,message:`${l.path} was planned as ${l.operation} but the actual operation is ${c.operation}.`,nextAction:`Change ${l.path} to the planned ${l.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${l.path}`,classification:"satisfied",subject:"file",path:l.path,expectedOperation:l.operation,actualOperation:c.operation,message:`${l.path} matches the planned ${l.operation} operation.`}):t.push({id:`missing:file:${l.path}`,classification:"missing",subject:"file",path:l.path,expectedOperation:l.operation,message:`${l.path} was planned as ${l.operation} but is absent from the actual change.`,nextAction:`${l.operation[0].toUpperCase()}${l.operation.slice(1)} ${l.path} in the complete change set, then preflight again.`})}for(let l of[...r.values()].sort((c,p)=>c.path.localeCompare(p.path)))n.has(l.path)||t.push({id:`unplanned:file:${l.path}`,classification:"unplanned",subject:"file",path:l.path,actualOperation:l.operation,message:`${l.path} has an unplanned ${l.operation} operation.`,nextAction:`Remove ${l.path} from the change set, then preflight again.`});let o=new Set;for(let l of[...s.values()].sort((c,p)=>D(c).localeCompare(D(p)))){if(a.has(D(l))){t.push(De("satisfied",l,`${l.from} -> ${l.to} exists in the candidate architecture.`));continue}let c={from:l.to,to:l.from};a.has(D(c))?(o.add(D(c)),t.push(De("contradictory",l,`${l.from} -> ${l.to} was planned, but the candidate contains the reverse edge.`))):t.push(De("missing",l,`${l.from} -> ${l.to} is absent from the candidate architecture.`))}let d=new Set([...n.keys(),...r.keys()]);for(let[l,c]of[...a].sort(([p],[y])=>p.localeCompare(y)))i.has(l)||s.has(l)||o.has(l)||!d.has(c.from)&&!d.has(c.to)||t.push({...De("unplanned",c,`${c.from} -> ${c.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let f=new Set(e.changeMap.map.files.filter(l=>l.operation==="delete").map(l=>l.path));for(let[l,c]of[...i].sort(([p],[y])=>p.localeCompare(y)))a.has(l)||f.has(c.from)||f.has(c.to)||!d.has(c.from)&&!d.has(c.to)||t.push({...De("unplanned",c,`${c.from} -> ${c.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let g={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((l,c)=>g[l.classification]-g[c.classification]||(l.subject===c.subject?0:l.subject==="file"?-1:1)||l.id.localeCompare(c.id));let h={satisfied:t.filter(l=>l.classification==="satisfied").length,missing:t.filter(l=>l.classification==="missing").length,contradictory:t.filter(l=>l.classification==="contradictory").length,unplanned:t.filter(l=>l.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:h.missing===0&&h.contradictory===0&&h.unplanned===0,behavioralCompletion:"not-evaluated",summary:h,findings:t}}var $n="1.0",Yt="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",Wt=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","no-anemic-model","invariant-coverage"],Vr=["no-anemic-model"],Pn={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},dt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Yt,title:"ArkGate ArkRules (intra-layer contract)",description:"Per-layer structure sensors and invariant catalog consumed by the ArkGate Effective Contract.",type:"object",additionalProperties:!1,required:["schemaVersion","layer"],properties:{$schema:{type:"string",minLength:1,default:Yt},schemaVersion:{type:"string",const:"1.0",default:"1.0"},layer:{type:"string",minLength:1},structure:{type:"array",default:[],items:{$ref:"#/$defs/structureEntry"}},invariants:{type:"array",default:[],items:{$ref:"#/$defs/invariantEntry"}}},$defs:{structureEntry:{type:"object",additionalProperties:!1,required:["id","sensor"],properties:{id:{type:"string",minLength:1},sensor:{type:"string",enum:[...Wt]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:Pn,description:{type:"string",minLength:1}}},invariantEntry:{type:"object",additionalProperties:!1,required:["id","description"],properties:{id:{type:"string",minLength:1},description:{type:"string",minLength:1},aggregate:{type:"string",minLength:1},coverage:{type:"object",additionalProperties:!1,properties:{test:{type:"boolean"},symbol:{type:"string",minLength:1}}},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:Pn}}}},pe=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkRules (${t}):
5
5
  ${n.map(r=>`- ${r.path}: ${r.message}`).join(`
6
- `)}`),this.name="ArkRulesValidationError",this.source=t,this.issues=n}};function je(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ot(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function He(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function $r(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function Ve(e,t,n,r,s){if(t.$ref){let i=$r(t.$ref,r);if(!i){s.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}Ve(e,i,n,r,s);return}if(t.const!==void 0&&!Object.is(e,t.const)){s.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(i=>Object.is(i,e))){s.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!je(e)){s.push({path:n,message:`must be an object; received ${He(e)}`});return}let i=t.properties??{};for(let a of t.required??[])e[a]===void 0&&s.push({path:ot(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in i||s.push({path:ot(n,a),message:"unknown field"});else if(je(t.additionalProperties)){let a=t.additionalProperties;for(let o of Object.keys(e))o in i||Ve(e[o],a,ot(n,o),r,s)}for(let[a,o]of Object.entries(i))e[a]!==void 0&&Ve(e[a],o,ot(n,a),r,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:n,message:`must be an array; received ${He(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&s.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let i=e.map(a=>JSON.stringify(a));new Set(i).size!==i.length&&s.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((i,a)=>Ve(i,t.items,`${n}[${a}]`,r,s));return}if(t.type==="string"){if(typeof e!="string"){s.push({path:n,message:`must be a string; received ${He(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&s.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}t.type==="boolean"&&typeof e!="boolean"&&s.push({path:n,message:`must be a boolean; received ${He(e)}`})}function Pr(e){return{...e,$schema:e.$schema===void 0?Gt:e.$schema,schemaVersion:e.schemaVersion===void 0?"1.0":e.schemaVersion,structure:e.structure===void 0?[]:e.structure,invariants:e.invariants===void 0?[]:e.invariants}}function En(e){return e==="enforced"?"enforced":"advisory"}function Tr(e){return Or.includes(e)}function Lr(e,t){let n=Array.isArray(e.structure)?e.structure:[],r=Array.isArray(e.invariants)?e.invariants:[],s=new Set;n.forEach((i,a)=>{if(!je(i))return;let o=typeof i.id=="string"?i.id:"";o&&(s.has(o)&&t.push({path:`$.structure[${a}].id`,message:`duplicate rule id ${JSON.stringify(o)}`}),s.add(o)),typeof i.sensor=="string"&&Tr(i.sensor)&&i.mode==="enforced"&&t.push({path:`$.structure[${a}].mode`,message:`sensor ${JSON.stringify(i.sensor)} is Tier-2 advisory-only and cannot be enforced`}),Array.isArray(i.appliesTo)&&i.appliesTo.length===0&&t.push({path:`$.structure[${a}].appliesTo`,message:"must not be an empty array (omit the field to apply to the whole layer)"})}),r.forEach((i,a)=>{if(!je(i))return;let o=typeof i.id=="string"?i.id:"";o&&(s.has(o)&&t.push({path:`$.invariants[${a}].id`,message:`duplicate rule id ${JSON.stringify(o)}`}),s.add(o)),Array.isArray(i.appliesTo)&&i.appliesTo.length===0&&t.push({path:`$.invariants[${a}].appliesTo`,message:"must not be an empty array (omit the field to apply to the whole layer)"})})}function Ue(e,t="arkrules.json",n){if(!je(e))throw new le(t,[{path:"$",message:`must be an object; received ${He(e)}`}]);let r=Pr(e),s=[];if(Ve(r,lt,"$",lt,s),Lr(r,s),n!==void 0&&typeof r.layer=="string"&&r.layer!==n&&s.push({path:"$.layer",message:`must match referencing key ${JSON.stringify(n)}; received ${JSON.stringify(r.layer)}`}),s.length>0)throw new le(t,s);return{config:r}}function Sn(e,t="arkrules.json",n){let r;try{r=JSON.parse(e)}catch(s){throw new le(t,[{path:"$",message:`invalid JSON: ${s instanceof Error?s.message:String(s)}`}])}return Ue(r,t,n)}function ct(e){let t={},n=[],r=[],s=[...e].sort((i,a)=>i.layer.localeCompare(a.layer));for(let i of s){let a=(i.file.structure??[]).map(u=>({...u,mode:En(u.mode),provenance:{sourceFile:i.sourceFile,ruleId:u.id,layer:i.layer}})),o=(i.file.invariants??[]).map(u=>({...u,mode:En(u.mode),provenance:{sourceFile:i.sourceFile,ruleId:u.id,layer:i.layer}}));t[i.layer]={sourceFile:i.sourceFile,structure:a,invariants:o},n.push(...a),r.push(...o)}return n.sort((i,a)=>{let o=i.provenance.layer.localeCompare(a.provenance.layer);return o!==0?o:i.id.localeCompare(a.id)}),r.sort((i,a)=>{let o=i.provenance.layer.localeCompare(a.provenance.layer);return o!==0?o:i.id.localeCompare(a.id)}),{schemaVersion:"1.0",byLayer:t,structure:n,invariants:r}}function te(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}var Ge=class extends Error{issues;source;constructor(t,n){super(`Invalid Effective Contract (${t}):
6
+ `)}`),this.name="ArkRulesValidationError",this.source=t,this.issues=n}};function je(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ct(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function He(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function jr(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function Ve(e,t,n,r,s){if(t.$ref){let i=jr(t.$ref,r);if(!i){s.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}Ve(e,i,n,r,s);return}if(t.const!==void 0&&!Object.is(e,t.const)){s.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(i=>Object.is(i,e))){s.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!je(e)){s.push({path:n,message:`must be an object; received ${He(e)}`});return}let i=t.properties??{};for(let a of t.required??[])e[a]===void 0&&s.push({path:ct(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in i||s.push({path:ct(n,a),message:"unknown field"});else if(je(t.additionalProperties)){let a=t.additionalProperties;for(let o of Object.keys(e))o in i||Ve(e[o],a,ct(n,o),r,s)}for(let[a,o]of Object.entries(i))e[a]!==void 0&&Ve(e[a],o,ct(n,a),r,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:n,message:`must be an array; received ${He(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&s.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let i=e.map(a=>JSON.stringify(a));new Set(i).size!==i.length&&s.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((i,a)=>Ve(i,t.items,`${n}[${a}]`,r,s));return}if(t.type==="string"){if(typeof e!="string"){s.push({path:n,message:`must be a string; received ${He(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&s.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}t.type==="boolean"&&typeof e!="boolean"&&s.push({path:n,message:`must be a boolean; received ${He(e)}`})}function Ur(e){return{...e,$schema:e.$schema===void 0?Yt:e.$schema,schemaVersion:e.schemaVersion===void 0?"1.0":e.schemaVersion,structure:e.structure===void 0?[]:e.structure,invariants:e.invariants===void 0?[]:e.invariants}}function wn(e){return e==="enforced"?"enforced":"advisory"}function Gr(e){return Vr.includes(e)}function Br(e,t){let n=Array.isArray(e.structure)?e.structure:[],r=Array.isArray(e.invariants)?e.invariants:[],s=new Set;n.forEach((i,a)=>{if(!je(i))return;let o=typeof i.id=="string"?i.id:"";o&&(s.has(o)&&t.push({path:`$.structure[${a}].id`,message:`duplicate rule id ${JSON.stringify(o)}`}),s.add(o)),typeof i.sensor=="string"&&Gr(i.sensor)&&i.mode==="enforced"&&t.push({path:`$.structure[${a}].mode`,message:`sensor ${JSON.stringify(i.sensor)} is Tier-2 advisory-only and cannot be enforced`}),Array.isArray(i.appliesTo)&&i.appliesTo.length===0&&t.push({path:`$.structure[${a}].appliesTo`,message:"must not be an empty array (omit the field to apply to the whole layer)"})}),r.forEach((i,a)=>{if(!je(i))return;let o=typeof i.id=="string"?i.id:"";o&&(s.has(o)&&t.push({path:`$.invariants[${a}].id`,message:`duplicate rule id ${JSON.stringify(o)}`}),s.add(o)),Array.isArray(i.appliesTo)&&i.appliesTo.length===0&&t.push({path:`$.invariants[${a}].appliesTo`,message:"must not be an empty array (omit the field to apply to the whole layer)"})})}function Ue(e,t="arkrules.json",n){if(!je(e))throw new pe(t,[{path:"$",message:`must be an object; received ${He(e)}`}]);let r=Ur(e),s=[];if(Ve(r,dt,"$",dt,s),Br(r,s),n!==void 0&&typeof r.layer=="string"&&r.layer!==n&&s.push({path:"$.layer",message:`must match referencing key ${JSON.stringify(n)}; received ${JSON.stringify(r.layer)}`}),s.length>0)throw new pe(t,s);return{config:r}}function _n(e,t="arkrules.json",n){let r;try{r=JSON.parse(e)}catch(s){throw new pe(t,[{path:"$",message:`invalid JSON: ${s instanceof Error?s.message:String(s)}`}])}return Ue(r,t,n)}function pt(e){let t={},n=[],r=[],s=[...e].sort((i,a)=>i.layer.localeCompare(a.layer));for(let i of s){let a=(i.file.structure??[]).map(d=>({...d,mode:wn(d.mode),provenance:{sourceFile:i.sourceFile,ruleId:d.id,layer:i.layer}})),o=(i.file.invariants??[]).map(d=>({...d,mode:wn(d.mode),provenance:{sourceFile:i.sourceFile,ruleId:d.id,layer:i.layer}}));t[i.layer]={sourceFile:i.sourceFile,structure:a,invariants:o},n.push(...a),r.push(...o)}return n.sort((i,a)=>{let o=i.provenance.layer.localeCompare(a.provenance.layer);return o!==0?o:i.id.localeCompare(a.id)}),r.sort((i,a)=>{let o=i.provenance.layer.localeCompare(a.provenance.layer);return o!==0?o:i.id.localeCompare(a.id)}),{schemaVersion:"1.0",byLayer:t,structure:n,invariants:r}}function ie(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}var Ge=class extends Error{issues;source;constructor(t,n){super(`Invalid Effective Contract (${t}):
7
7
  ${n.map(r=>`- ${r.path}: ${r.message}`).join(`
8
- `)}`),this.name="EffectiveContractError",this.source=t,this.issues=n}};function kn(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function xn(e,t="ark.config.json"){let n=e.config.arkRules,r=[];if(!n||Object.keys(n).length===0){if(e.discoveredArkRulesFiles&&e.discoveredArkRulesFiles.length>0)for(let u of[...e.discoveredArkRulesFiles].sort())r.push({path:u,message:`ArkRules file ${JSON.stringify(u)} is not referenced by arkRules and will not be enforced`,severity:"advisory"});return{config:e.config,arkRules:te(),warnings:r}}let s=new Set(e.config.layers.map(u=>u.name)),i=[],a=[],o=new Set;for(let u of Object.keys(n).sort()){let m=n[u],h=`$.arkRules[${JSON.stringify(u)}]`;if(typeof m!="string"||m.length===0){i.push({path:h,message:"must be a non-empty relative path string"});continue}if(m.startsWith("/")||/^[A-Za-z]:[\\/]/.test(m)){i.push({path:h,message:"must be a project-relative path (absolute paths are not allowed)"});continue}if(!s.has(u)){i.push({path:h,message:`layer ${JSON.stringify(u)} is not declared in layers[]`});continue}let g=kn(m);o.add(g);let l=e.fileContents[g]??e.fileContents[m];if(l===void 0){i.push({path:h,message:`referenced ArkRules file ${JSON.stringify(g)} is missing`});continue}try{let c=Ue(JSON.parse(l),g,u);a.push({layer:u,sourceFile:g,file:c.config})}catch(c){if(c instanceof le)for(let d of c.issues)i.push({path:`${h}${d.path==="$"?"":d.path.replace(/^\$/,"")}`,message:`${g}: ${d.message}`});else c instanceof SyntaxError?i.push({path:h,message:`referenced ArkRules file ${JSON.stringify(g)} is not valid JSON: ${c.message}`}):i.push({path:h,message:`referenced ArkRules file ${JSON.stringify(g)} failed to load: ${c instanceof Error?c.message:String(c)}`})}}if(e.discoveredArkRulesFiles)for(let u of[...e.discoveredArkRulesFiles].sort()){let m=kn(u);o.has(m)||r.push({path:m,message:`ArkRules file ${JSON.stringify(m)} is not referenced by arkRules and will not be enforced`,severity:"advisory"})}if(i.length>0)throw new Ge(t,i);return{config:e.config,arkRules:ct(a),warnings:r}}function dt(e){return{config:e.config,arkRules:{schemaVersion:e.arkRules.schemaVersion,structure:e.arkRules.structure.map(t=>({id:t.id,sensor:t.sensor,mode:t.mode,appliesTo:t.appliesTo??null,description:t.description??null,provenance:t.provenance})),invariants:e.arkRules.invariants.map(t=>({id:t.id,description:t.description,aggregate:t.aggregate??null,coverage:t.coverage??null,mode:t.mode,appliesTo:t.appliesTo??null,provenance:t.provenance}))}}}function _r(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*['"\`][^'"\`]*${n}[^'"\`]*['"\`]`,"i").test(e)||e.includes(t)}function Fr(e,t){if(!t)return!1;let n=t.split("."),r=n[n.length-1],s=n.length>1?n[0]:null;for(let i of Object.values(e))if(!(s&&!i.includes(s))&&(new RegExp(`(?:function\\s+|\\b)${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[(<]`).test(i)||i.includes(t)))return!0;return!1}function pt(e){let t=e.arkRules.invariants??[];if(t.length===0)return{coverage:[],violations:[],partial:!1};let n=e.testFiles??[],r=e.testGlobsMissing===!0||n.length===0,s=[],i=[];for(let a of t){let o=[],u=a.coverage?.test!==!1,m=a.coverage?.symbol;if(!r&&u)for(let c of n){let d=e.fileContents[c];if(d&&_r(d,a.id)){o.push("test-title");break}}m&&Fr(e.fileContents,m)&&o.push("symbol");let g=(a.coverage?.test===!0||!!m||a.coverage===void 0)&&o.length>0||a.coverage?.test===!1&&!m?!0:o.length>0,l=r&&u&&o.length===0;if(s.push({invariantId:a.id,layer:a.provenance.layer,sourceFile:a.provenance.sourceFile,mode:a.mode,covered:g&&!l,evidence:o,partial:l,description:a.description}),!g||l){let c=a.mode==="enforced"&&!l;i.push({ruleId:"INVARIANT_UNCOVERED",message:l?`Invariant ${a.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered.`:`Invariant ${a.id} is not covered by a test title or declared symbol.`,file:a.provenance.sourceFile,line:1,arkruleId:a.id,arkruleSource:a.provenance.sourceFile,fromLayer:a.provenance.layer,severity:c?"error":"warning",failsStrict:c})}}return{coverage:s,violations:i,partial:s.some(a=>a.partial)}}function ut(e){return e?e.partial?{ok:!1,reason:"Coverage is partial (missing test globs); cannot promote until evidence is complete."}:e.covered?{ok:!0,reason:`Invariant ${e.invariantId} has coverage evidence.`}:{ok:!1,reason:`Invariant ${e.invariantId} is uncovered; add a test title or symbol before promoting to enforced.`}:{ok:!1,reason:"No coverage evidence supplied for this invariant; evaluate coverage before promoting to enforced."}}var mt="1.0";function E(e,t){e.push({id:`${t.classification}:${t.path}:${t.kind}`,path:t.path,classification:t.classification,message:t.message,...t.classification==="weakening"||t.classification==="judgment-required"?{nextAction:`Restore the previous protection at ${t.path}, then run ArkGate again.`}:{},...t.before===void 0?{}:{before:t.before},...t.after===void 0?{}:{after:t.after}})}function D(e){return[...new Set(e??[])].sort()}function ce(e,t,n,r,s){let i=D(n),a=D(r),o=new Set(i),u=new Set(a),m=a.filter(g=>!o.has(g)),h=i.filter(g=>!u.has(g));m.length===0&&h.length===0||(m.length>0&&E(e,{kind:"added",path:t,classification:s.added,message:s.addedMessage,before:i,after:a}),h.length>0&&E(e,{kind:"removed",path:t,classification:s.removed,message:s.removedMessage,before:i,after:a}))}function ft(e,t,n,r,s,i,a){if(n===r)return;E(e,{kind:r?"enabled":"disabled",path:t,classification:r?s:s==="strengthening"?"weakening":"strengthening",message:r?i:a,before:n,after:r})}function yt(e,t){let n=new Map,r=new Set;for(let s of e){let i=t(s);n.has(i)?r.add(i):n.set(i,s)}return{values:n,duplicates:[...r].sort()}}function Nr(e,t,n){let r=yt(t,i=>i.name),s=yt(n,i=>i.name);(r.duplicates.length>0||s.duplicates.length>0)&&E(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:r.duplicates,after:s.duplicates});for(let i of[...new Set([...r.values.keys(),...s.values.keys()])].sort()){let a=r.values.get(i),o=s.values.get(i),u=`$.layers[${i}]`;if(!a&&o){E(e,{kind:"layer-added",path:u,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:o});continue}if(a&&!o){E(e,{kind:"layer-removed",path:u,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:a});continue}if(!a||!o)continue;ce(e,`${u}.patterns`,a.patterns,o.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),ce(e,`${u}.exclude`,a.exclude,o.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let m=Je(a),h=Je(o);ce(e,`${u}.forbiddenGlobals`,m.rawGlobals,h.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),ce(e,`${u}.capabilities`,m.atoms,h.atoms,{added:"strengthening",removed:"weakening",addedMessage:"Additional ambient/import protection is enforced in this layer (coverage atoms).",removedMessage:"An ambient/import protection was lost from this layer (coverage atoms)."}),D(a.intentPrefixes).join("\0")!==D(o.intentPrefixes).join("\0")&&E(e,{kind:"intent-prefixes-changed",path:`${u}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:D(a.intentPrefixes),after:D(o.intentPrefixes)}),ft(e,`${u}.mayImportInfrastructure`,a.mayImportInfrastructure===!0,o.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),ft(e,`${u}.optional`,a.optional===!0,o.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active.")}}function Mr(e,t,n){let r=a=>`${a.from}->${a.to}`,s=yt(t,r),i=yt(n,r);(s.duplicates.length>0||i.duplicates.length>0)&&E(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:s.duplicates,after:i.duplicates});for(let a of[...new Set([...s.values.keys(),...i.values.keys()])].sort()){let o=s.values.get(a),u=i.values.get(a),m=`$.rules[${a}]`;if(!o&&u){u.allowed===!1&&E(e,{kind:"deny-added",path:m,classification:"strengthening",message:"A denied dependency edge was added.",after:u});continue}if(o&&!u){o.allowed===!1&&E(e,{kind:"deny-removed",path:m,classification:"weakening",message:"A denied dependency edge was removed.",before:o});continue}if(!o||!u)continue;o.allowed!==u.allowed&&E(e,{kind:u.allowed?"deny-disabled":"deny-enabled",path:`${m}.allowed`,classification:u.allowed?"weakening":"strengthening",message:u.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:o.allowed,after:u.allowed});let h=o.peerIsolation===!0,g=u.peerIsolation===!0;if(h!==g){let l=o.from===o.to&&u.from===u.to;E(e,{kind:g?"peer-isolation-enabled":"peer-isolation-disabled",path:`${m}.peerIsolation`,classification:l?g?"strengthening":"weakening":"judgment-required",message:l?g?"Cross-slice dependencies inside this layer are now denied.":"Cross-slice dependencies inside this layer are no longer denied.":"Changing peer isolation on a cross-layer edge changes the denial scope.",before:h,after:g})}D(o.sliceFolders).join("\0")!==D(u.sliceFolders).join("\0")&&E(e,{kind:"slice-folders-changed",path:`${m}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:D(o.sliceFolders),after:D(u.sliceFolders)})}}function Dr(e,t,n){let r=t.safety??{},s=n.safety??{};for(let i of["maxTsSuppressions","maxAnyCasts"]){let a=r[i]??0,o=s[i]??0;a!==o&&E(e,{kind:o>a?"threshold-raised":"threshold-lowered",path:`$.safety.${i}`,classification:o>a?"weakening":"strengthening",message:o>a?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:a,after:o})}for(let i of["allowInMemory","allowDisabledPeerIsolation"])ft(e,`$.safety.${i}`,r[i]===!0,s[i]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}function Hr(e){return e.some(t=>t.classification==="weakening")?"weakening":e.some(t=>t.classification==="judgment-required")?"judgment-required":e.some(t=>t.classification==="strengthening")?"strengthening":"neutral"}function wn(e,t){return`${e}::${t}`}function On(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(wn(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(wn(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}function Vr(e,t,n,r,s,i){let a=new Map((i??[]).map(l=>[l.invariantId,l])),o=t.arkRules??{},u=n.arkRules??{},m=[...new Set([...Object.keys(o),...Object.keys(u)])].sort();for(let l of m){let c=o[l],d=u[l],f=`$.arkRules[${l}]`;if(c===void 0&&d!==void 0){E(e,{kind:"arkrules-ref-added",path:f,classification:"strengthening",message:`ArkRules reference for layer ${l} was added.`,after:d});continue}if(c!==void 0&&d===void 0){E(e,{kind:"arkrules-ref-removed",path:f,classification:"weakening",message:`ArkRules reference for layer ${l} was removed.`,before:c});continue}c!==d&&E(e,{kind:"arkrules-ref-path-changed",path:f,classification:"judgment-required",message:`ArkRules file path for layer ${l} changed; verify the effective rules still match intent.`,before:c,after:d})}let h=On(r),g=On(s);for(let l of[...new Set([...h.structure.keys(),...g.structure.keys()])].sort()){let c=h.structure.get(l),d=g.structure.get(l),f=`$.arkRules.structure[${l}]`;if(!c&&d){E(e,{kind:"arkrule-structure-added",path:f,classification:"strengthening",message:`Structure ArkRule ${d.id} was added (${d.mode}).`,after:d});continue}if(c&&!d){E(e,{kind:"arkrule-structure-removed",path:f,classification:"weakening",message:`Structure ArkRule ${c.id} was removed.`,before:c});continue}if(!(!c||!d)){if(c.mode!==d.mode){let b=c.mode==="advisory"&&d.mode==="enforced";E(e,{kind:b?"arkrule-promoted":"arkrule-demoted",path:`${f}.mode`,classification:b?"strengthening":"weakening",message:b?`Structure ArkRule ${d.id} was promoted to enforced.`:`Structure ArkRule ${d.id} was demoted to advisory.`,before:c.mode,after:d.mode})}c.sensor!==d.sensor&&E(e,{kind:"arkrule-sensor-changed",path:`${f}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${d.id} changed sensor identity.`,before:c.sensor,after:d.sensor})}}for(let l of[...new Set([...h.invariants.keys(),...g.invariants.keys()])].sort()){let c=h.invariants.get(l),d=g.invariants.get(l),f=`$.arkRules.invariants[${l}]`;if(!c&&d){E(e,{kind:"arkrule-invariant-added",path:f,classification:"strengthening",message:`Invariant ${d.id} was added (${d.mode}).`,after:d});continue}if(c&&!d){E(e,{kind:"arkrule-invariant-removed",path:f,classification:"weakening",message:`Invariant ${c.id} was removed.`,before:c});continue}if(!(!c||!d)&&c.mode!==d.mode)if(c.mode==="advisory"&&d.mode==="enforced"){let R=a?.get(d.id),p=ut(R);p.ok?E(e,{kind:"arkrule-invariant-promoted",path:`${f}.mode`,classification:"strengthening",message:`Invariant ${d.id} was promoted to enforced (coverage evidence present).`,before:c.mode,after:d.mode}):E(e,{kind:"arkrule-invariant-promote-refused",path:`${f}.mode`,classification:"judgment-required",message:`Invariant ${d.id} cannot be promoted to enforced: ${p.reason}`,before:c.mode,after:d.mode})}else E(e,{kind:"arkrule-invariant-demoted",path:`${f}.mode`,classification:"weakening",message:`Invariant ${d.id} was demoted to advisory.`,before:c.mode,after:d.mode})}}function gt(e,t,n){let r=[];ce(r,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),ce(r,"$.exclude",e.exclude,t.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional project paths are excluded from governance.",removedMessage:"Fewer project paths are excluded from governance."}),ce(r,"$.dynamicImportAllowlist",e.dynamicImportAllowlist,t.dynamicImportAllowlist,{added:"weakening",removed:"strengthening",addedMessage:"Additional files may use non-literal dynamic imports.",removedMessage:"Fewer files may use non-literal dynamic imports."}),ft(r,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let s={off:0,soft:1,"framework-soft":1,strict:2},i=e.cyclePolicy??"strict",a=t.cyclePolicy??"strict";if(i!==a){let o=s[a]===s[i]?"judgment-required":s[a]>s[i]?"strengthening":"weakening";E(r,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:o,message:"The cycle enforcement level changed.",before:i,after:a})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&E(r,{kind:"framework-overlay-changed",path:"$.frameworkOverlay",classification:"judgment-required",message:"The framework overlay changed and may alter effective layer matching.",before:e.frameworkOverlay??null,after:t.frameworkOverlay??null}),Nr(r,e.layers,t.layers),Mr(r,e.rules,t.rules),Dr(r,e,t),Vr(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),r.sort((o,u)=>o.path.localeCompare(u.path)||o.id.localeCompare(u.id)),{schemaVersion:mt,classification:Hr(r),findings:r}}function ht(e,t){if(!e||e.schemaVersion!==mt||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(s=>typeof s!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=D(e.findingIds),r=D(t.findingIds);return n.length===r.length&&n.every((s,i)=>s===r[i])}function de(e){let t=[];for(let n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."&&t.length>0&&t.at(-1)!==".."?t.pop():t.push(n));return t.join("/")}function $n(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}function At(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}function N(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}function Be(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let r=t,s="";for(t+=1;t<e.length;t+=1){let i=e[t];if(i===n)return{value:s,offset:r,excerpt:e.slice(r,t+1)};i==="\\"&&t+1<e.length?(s+=e[t+1],t+=1):s+=i}}function H(e,t,n){return e.startsWith(t,n)&&!At(e[n-1])&&!At(e[n+t.length])}function Pn(e,t){let n=N(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=N(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!H(e,"type",n))return!1;let s=N(e,n+4);if(s>=e.length||e[s]===","||e[s]==="}"||H(e,"as",s)||!$n(e[s]))return!1;for(n=s;n<e.length&&At(e[n]);)n+=1;if(n=N(e,n),H(e,"as",n)){if(n=N(e,n+2),!$n(e[n]))return!1;for(;n<e.length&&At(e[n]);)n+=1}r=!0}return!1}function jr(e,t){if(t=N(e,t+6),e[t]==="(")return Be(e,N(e,t+1));let n=!1;if(H(e,"type",t)){let s=N(e,t+4);e[s]!==","&&!H(e,"from",s)&&(n=!0)}else Pn(e,t)&&(n=!0);let r=Tn(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}function Ur(e,t){t=t+6;let n=N(e,t),r=!1;if(H(e,"type",n)){let i=N(e,n+4);(e[i]==="{"||e[i]==="*")&&(r=!0)}else Pn(e,n)&&(r=!0);let s=Tn(e,t,!1);return s&&r?{...s,typeOnly:!0}:s}function Tn(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(H(e,"from",t))return Be(e,N(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return Be(e,t);if(t>0&&(H(e,"import",t)||H(e,"export",t)))return}}function Gr(e,t){for(t+=1;t<e.length;t+=1){let n=e[t];if(n==="\\")t+=1;else if(n==="`")return t}return e.length}function Br(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=N(e,t+7);if(e[r]!=="(")return;r=N(e,r+1);let s=Be(e,r);return s?{...s,requireCall:!0}:void 0}function qr(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="/"&&e[n+1]==="/"){if(n=e.indexOf(`
9
- `,n+2),n<0)break;continue}if(r==="/"&&e[n+1]==="*"){let i=e.indexOf("*/",n+2);if(i<0)break;n=i+1;continue}if(r==="`"){n=Gr(e,n);continue}if(r==="'"||r==='"'){let i=Be(e,n);i&&(n=i.offset+i.excerpt.length-1);continue}let s=r==="i"&&H(e,"import",n)?jr(e,n):r==="e"&&H(e,"export",n)?Ur(e,n):r==="r"&&H(e,"require",n)?Br(e,n):void 0;s&&(t.push(s),n=s.offset+s.excerpt.length-1)}return t}function Ln(e,t){let n=[],r=[];for(let s of qr(e.content)){let i=s.value;if(!i.startsWith(".")){if(s.typeOnly)continue;let m=we(i);if(!m)continue;let h=e.content.slice(0,s.offset).split(`
10
- `).length;r.push({file:e.path,symbol:i,capability:m,evidence:{kind:"import",file:e.path,line:h,excerpt:s.excerpt}});continue}let a=e.content.slice(0,s.offset).split(`
11
- `).length,o={kind:"import",file:e.path,line:a,excerpt:s.excerpt},u=zr(e.path,i,t);n.push({from:e.path,specifier:i,to:u?.path??null,resolution:u?"resolved":"unresolved",fromLayer:e.layer,toLayer:u?.layer??null,evidence:o})}return{edges:n,capabilityUses:r}}function zr(e,t,n){let r=e.split("/");r.pop();for(let i of t.split("/"))i==="."||i===""||(i===".."?r.pop():r.push(i));let s=r.join("/");for(let i of[s,`${s}.ts`,`${s}.tsx`,`${s}.mts`,`${s}.cts`,`${s}/index.ts`,`${s}/index.tsx`]){let a=n.get(i);if(a)return a}}function _n(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let s=K(t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});s&&n.push({ruleId:`layer-dependency:${s.from}->${s.to}`,message:s.message??`${s.from} must not depend on ${s.to}.`,edge:r,evidence:r.evidence})}return n}var Kr={code:"LEXICAL_EVIDENCE_INCOMPLETE",message:"Lexical compatibility mode cannot prove parse status, TypeScript/package/symlink resolution, or symbol-aware source-policy and safety evidence. Use the resolved candidate facts APIs for an authoritative verdict."};function Yr(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}function Wr(e,t){return Yr(e,t)?O(S(dt({config:e,arkRules:t,warnings:[]}))):O(S(e))}function qe(e,t,n){let r=typeof e=="string"?rt(e,t):Fe(e,t),s=n?.arkRules??te();return{...r,arkRules:s,policyHash:Wr(r.config,s)}}function qt(e){let t=qe(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=qe(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=gt(t.config,n.config,{baseArkRules:t.arkRules,candidateArkRules:n.arkRules,candidateInvariantCoverage:e.candidateInvariantCoverage}),s=r.findings.filter(o=>o.classification==="weakening"||o.classification==="judgment-required").map(o=>o.id).sort(),i=s.length>0,a=i&&ht(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:s});return{schemaVersion:r.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:r.classification,findings:r.findings,blockingFindingIds:s,requiresAcknowledgement:i,acknowledged:a,valid:!i||a}}function ve(e){let t=e.files.map(g=>{let l=de(g.path);return{path:l,content:g.content,contentHash:O(g.content),layer:z(l,e.contract.config.layers)??null}}).sort((g,l)=>g.path.localeCompare(l.path)),n=new Map(t.map(g=>[g.path,g])),r=[],s=[];for(let g of t){let l=Ln(g,n);r.push(...l.edges),s.push(...l.capabilityUses)}let i=_n(r,e.contract.config),a=new Map(e.contract.config.layers.map(g=>[g.name,g])),o=new Map(e.contract.config.layers.map(g=>[g.name,new Set(fe(g))]));for(let g of s){let l=n.get(g.file)?.layer;if(!l)continue;let c=a.get(l),d=J(g.symbol,c?.forbiddenGlobals??[]);if(d){i.push({ruleId:"FORBIDDEN_GLOBAL",message:`${l} must not use module "${g.symbol}" because it is the import form of forbidden global "${d}".`,symbol:g.symbol,evidence:g.evidence});continue}o.get(l)?.has(g.capability)&&i.push({ruleId:"CAPABILITY_VIOLATION",message:`${l} denies the ${g.capability} capability; found import of "${g.symbol}".`,capability:g.capability,symbol:g.symbol,evidence:g.evidence})}let u=t.length===0?"complete":"partial",m=u==="complete"?[]:[{...Kr}],h={schemaVersion:at,policyHash:e.contract.policyHash,compilerOptionsHash:O(S(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(g=>g.name),edges:r,capabilityUses:s,violations:i};return{mode:"lexical-compatibility",completeness:u,completenessReasons:m,valid:u==="complete"&&i.length===0,ir:h}}function ze(e){let t=new Map(e.files.map(n=>[de(n.path),n]));for(let n of e.changes){let r=de(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return ve({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}function zt(e){let t=`${e.evidence.file}:${e.evidence.line}`;if(!e.edge)return`${e.ruleId} at ${t}: ${e.message}`;let n=e.edge.to??e.edge.specifier;return`${e.ruleId} at ${t}: ${e.edge.from} imports ${n}. ${e.message}`}function bt(e){let t=0,n=new Map,r=new Map,s=new Set,i=[],a=[],o=u=>{n.set(u,t),r.set(u,t),t+=1,i.push(u),s.add(u);for(let g of[...e.get(u)??[]].sort())e.has(g)&&(n.has(g)?s.has(g)&&r.set(u,Math.min(r.get(u)??0,n.get(g)??0)):(o(g),r.set(u,Math.min(r.get(u)??0,r.get(g)??0))));if(r.get(u)!==n.get(u))return;let m=[],h;do{if(h=i.pop(),h===void 0)break;s.delete(h),m.push(h)}while(h!==u);m.length>1&&a.push(m.sort())};for(let u of[...e.keys()].sort())n.has(u)||o(u);return a.sort((u,m)=>u[0]<m[0]?-1:u[0]>m[0]?1:0).map(u=>({ruleId:"CIRCULAR_DEPENDENCY",file:u[0],line:1,target:u.join(" \u2192 "),message:`Circular dependency among ${u.length} files: ${u.join(" \u2192 ")} \u2192 ${u[0]}.`,cycleKind:"value"}))}function pe(e){let t=e.contentViolations.map(i=>({...i})),n=(e.warnings??[]).map(i=>({...i})),r=new Map(e.files.map(i=>[i,new Set]));for(let i of e.edges){if(i.to&&i.to!==i.from&&!i.typeOnly&&r.has(i.from)&&r.get(i.from)?.add(i.to),!i.to||!i.fromLayer||!i.toLayer)continue;let a=K(e.rules,i.fromLayer,i.toLayer,{fromPath:i.from,toPath:i.to,layers:e.config.layers});if(!a)continue;let o=!!a.peerIsolation,u=!o&&!!(i.typeOnly||i.namedBindingsTypeOnly),m=a.message??(o?`${i.fromLayer} must not ${i.kind} another slice of ${i.toLayer} (${i.from} \u2192 ${i.to}). Extract shared code or use events/ports across slices.`:`${i.fromLayer} must not ${i.kind} ${i.toLayer}.`);t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:i.from,line:i.line,fromLayer:i.fromLayer,toLayer:i.toLayer,target:i.to,...i.typeOnly?{typeOnly:!0}:{},...i.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...i.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...i.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!o&&i.portProofEligible?{portProofEligible:!0}:{},...i.kind?{edgeKind:i.kind}:{},...o?{peerIsolation:!0}:{},message:u?`${m} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:m,...u?{failsStrict:!1,severity:"warning"}:{}})}let s=String(e.config.cyclePolicy??"strict").toLowerCase();if(s!=="off"){let i=bt(r);s==="soft"||s==="framework-soft"?n.push(...i.map(a=>({...a,message:`${a.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...i)}return{violations:t,warnings:n,safety:e.safety}}var Zr=["no-anemic-model"];function Fn(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function Jr(e){let t="";for(let r=0;r<e.length;r+=1){let s=e[r];if(s==="\\"&&r+1<e.length){let i=e[r+1];if("*?{}[],".includes(i)||i==="\\"){t+="\\"+i,r+=1;continue}t+="/";continue}t+=s}let n="";for(let r=0;r<t.length;r+=1){let s=t[r];s==="\\"&&r+1<t.length?(n+=Fn(t[r+1]),r+=1):s==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":s==="?"?n+="[^/]":n+=Fn(s)}return new RegExp(`^${n}$`)}function Ke(e,t){return!t||t.length===0?!0:t.some(n=>Jr(n).test(e))}function Xr(e){return Zr.includes(e)}function Nn(e){return e.mode==="enforced"&&!Xr(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}function Ie(e,t,n,r=1){let{severity:s,failsStrict:i}=Nn(e);return{ruleId:"ARKRULE_STRUCTURE",code:e.sensor,message:n,file:t,line:r,fromLayer:e.provenance.layer,arkruleId:e.id,arkruleSource:e.provenance.sourceFile,severity:s,sensor:e.sensor,failsStrict:i}}function Kt(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}function Rt(e,t,n){return t.filter(r=>!(!r.exported||!Ke(r.file,e.appliesTo)||!Kt(r.file,e,n)))}function Qr(e,t,n){let r=[];for(let s of Rt(e,t,n))(s.hasPublicSetters||s.hasPublicMutableFields)&&r.push(Ie(e,s.file,`Exported class ${s.className} exposes public mutable state (sensor aggregate-private-state).`));return r}function es(e,t,n){let r=[];for(let s of Rt(e,t,n))if(s.hasPublicConstructor&&!s.hasStaticFactory){if(!(s.hasPublicMutableFields||s.hasPublicSetters||(s.mutatingMethods?.length??0)>0))continue;r.push(Ie(e,s.file,`Exported class ${s.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}return r}function ts(e,t,n){let r=[];for(let s of Rt(e,t,n))for(let i of s.mutatingMethods)i.referencesGuardOrPublish||r.push(Ie(e,s.file,`Mutating method ${s.className}.${i.name} does not reference a guard or publish symbol (sensor domain-event-on-mutation).`));return r}function ns(e,t){let n=[];for(let r of t.files)Ke(r,e.appliesTo)&&Kt(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(Ie(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}function rs(e,t){let n=[];for(let r of t.files)Ke(r,e.appliesTo)&&Kt(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(Ie(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}function ss(e,t,n){let r=[];for(let s of Rt(e,t,n))if(s.dataOnly===!0){let i=Ie(e,s.file,`Exported type ${s.className} looks data-only / anemic (sensor no-anemic-model; advisory only).`);r.push({...i,severity:"warning",failsStrict:!1})}return r}function vt(e){if(!e.arkRules.structure.length)return[];let t=[];for(let n of e.arkRules.structure)switch(n.sensor){case"aggregate-private-state":t.push(...Qr(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...es(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...ts(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...ns(n,e));break;case"thin-adapter":t.push(...rs(n,e));break;case"no-anemic-model":t.push(...ss(n,e.classShapes,e.layerForFile));break;case"invariant-coverage":break;default:break}return t.sort((n,r)=>n.file.localeCompare(r.file)||n.arkruleId.localeCompare(r.arkruleId)||n.message.localeCompare(r.message))}function It(e,t){let n=[],r=t.map(s=>s.replace(/\\/g,"/"));for(let s of e.structure){if(!s.appliesTo||s.appliesTo.length===0||r.some(u=>Ke(u,s.appliesTo)))continue;let{severity:a,failsStrict:o}=Nn(s);n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule structure "${s.id}" appliesTo matched zero governed files (patterns: ${s.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:s.provenance.sourceFile,line:1,fromLayer:s.provenance.layer,arkruleId:s.id,arkruleSource:s.provenance.sourceFile,severity:a,sensor:s.sensor,failsStrict:o})}for(let s of e.invariants??[]){if(!s.appliesTo||s.appliesTo.length===0||r.some(o=>Ke(o,s.appliesTo)))continue;let a=s.mode==="enforced";n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule invariant "${s.id}" appliesTo matched zero governed files (patterns: ${s.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:s.provenance.sourceFile,line:1,fromLayer:s.provenance.layer,arkruleId:s.id,arkruleSource:s.provenance.sourceFile,severity:a?"error":"warning",sensor:"invariant-coverage",failsStrict:a})}return n.sort((s,i)=>s.file.localeCompare(i.file)||s.arkruleId.localeCompare(i.arkruleId)||s.message.localeCompare(i.message))}var is=/\bfrom\s+['"](?:@?prisma\/client|@supabase\/|drizzle-orm|typeorm|knex|mongodb|pg|mysql2|better-sqlite3|ioredis|redis)['"]|require\(\s*['"](?:@?prisma\/client|pg|knex|typeorm)/,as=/\b(?:@Controller|@Get|@Post|@Put|@Delete|Router\(\)|createRouter|express\.Router|fastify\.(?:get|post)|export\s+(?:async\s+)?function\s+(?:GET|POST|PUT|DELETE|PATCH)\b|export\s+const\s+(?:GET|POST|PUT|DELETE|PATCH)\s*=)/,os=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,ls=/\b(?:export\s+)?(?:async\s+)?function\s+(?:can|calculate|compute|should|ensure|validate|is|has)[A-Z]\w*|\b(?:export\s+)?const\s+(?:can|calculate|compute|should|ensure|validate|is|has)[A-Z]\w*\s*=/,cs=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function Yt(e,t){if(!t||t.length<40)return null;let n=t.match(new RegExp(ls.source,"g"))??[],r=t.match(new RegExp(cs.source,"g"))??[],s=(t.match(/\bif\s*\(/g)??[]).length,i=(t.match(/\bswitch\s*\(/g)??[]).length,a=n.length>=2||n.length>=1&&r.length>=2||r.length>=3&&s+i>=6,o=is.test(t),u=as.test(t)||os.test(t),m=n.length>=1||r.length>=2,h=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),g=o&&m||u&&m||o&&h&&(s>=4||n.length>=1)||u&&o;return!a&&!g?null:{...a?{orchestrationHeavy:!0}:{},...g?{adapterThick:!0}:{}}}function Et(e){let t={};for(let[n,r]of Object.entries(e)){let s=Yt(n,r);s&&(t[n.replace(/\\/g,"/")]=s)}return t}function Mn(e,t){let n=[],r=/export\s+(?:abstract\s+)?class\s+([A-Za-z_][A-Za-z0-9_]*)\s*(?:extends\s+[^{]+)?(?:implements\s+[^{]+)?\{/g,s;for(;(s=r.exec(t))!==null;){let i=s[1],a=s.index+s[0].length,o=1,u=a;for(;u<t.length&&o>0;){let x=t[u];x==="{"?o+=1:x==="}"&&(o-=1),u+=1}let m=t.slice(a,u-1),h=m.split(`
12
- `).map(x=>/^\s*\/\//.test(x)||/^\s*\/\*|\*\//.test(x)?x:x.replace(/(?:public\s+|protected\s+)?readonly\s+[a-zA-Z_][a-zA-Z0-9_]*\s*(?::[^=;]+)?(?:=\s*[^;]+)?[;,]?/g,"").replace(/(?:^|[\s;{])readonly\s+[a-zA-Z_][a-zA-Z0-9_]*\s*(?::[^=;]+)?(?:=\s*[^;]+)?[;,]?/g," ")).join(`
13
- `),g=/(?:^|\n)\s*(?:public\s+)?[a-zA-Z_][a-zA-Z0-9_]*\s*[:=]/m.test(h.replace(/(?:public\s+|private\s+|protected\s+|static\s+|async\s+|get\s+|set\s+)/g,""))&&/(?:^|\n)\s*(public\s+)?(?!constructor|static|get|set|private|protected|readonly)[a-zA-Z_][a-zA-Z0-9_]*\s*[:=]/m.test(h),l=/(?:^|\n)\s*public\s+(?!static|async|get|set|constructor|readonly)[a-zA-Z_]/.test(h)||/(?:^|[\n;])\s*[a-zA-Z_][a-zA-Z0-9_]*\s*:\s*[^=;\n]+[;=]/m.test(h.split(`
14
- `).filter(x=>!/^\s*(private|protected|static|constructor|get |set |async |\/)/.test(x)).join(`
15
- `)),c=/(?:^|[\n;{])\s*(?:public\s+)?set\s+[a-zA-Z_]/.test(m),d=/(?:^|[\n;{])\s*private\s+constructor\s*\(/.test(m),f=/(?:^|[\n;{])\s*(?:public\s+)?constructor\s*\(/.test(m)&&!d,b=/(?:^|[\n;{])\s*static\s+(?:async\s+)?(?:create|of|from|parse|build|make|new)\s*[<(]/.test(m)||/(?:^|[\n;{])\s*static\s+(?:async\s+)?[A-Za-z_][A-Za-z0-9_]*\s*\([^)]*\)\s*:\s*[A-Za-z_]/.test(m),R=[],p=new Set(["if","match","when"]),y=/(?:^|\n)\s*(?:public\s+|private\s+|protected\s+|async\s+)*(?!constructor|get|set|static)([a-zA-Z_][a-zA-Z0-9_]*)\s*\([^)]*\)\s*(?::\s*[^{]+)?\{/g,v;for(;(v=y.exec(m))!==null;){let x=v[1];if(p.has(x))continue;let ue=v.index+v[0].length,Ce=1,ne=ue;for(;ne<m.length&&Ce>0;)m[ne]==="{"?Ce+=1:m[ne]==="}"&&(Ce-=1),ne+=1;let Se=m.slice(ue,ne-1);if(!/this\.\w+\s*=/.test(Se))continue;let A=/\b(ensureInvariants|assertInvariants|validate|publish|emit|raise|record)\b/.test(Se);R.push({name:x,referencesGuardOrPublish:A})}let C=(m.match(/(?:^|\n)\s*(?:public\s+|private\s+|protected\s+)?(?:async\s+)?[a-zA-Z_][a-zA-Z0-9_]*\s*\(/g)??[]).length,T=(h.match(/(?:^|[\n;])\s*(?:public\s+)?(?!constructor|static|get|set|private|protected|readonly)[a-zA-Z_][a-zA-Z0-9_]*\s*[:=]/g)??[]).length,_=C<=1&&T>=2&&(l||g);n.push({file:e,className:i,exported:!0,hasPublicMutableFields:l||g,hasPublicSetters:c,hasPublicConstructor:f,hasStaticFactory:b,mutatingMethods:[...R],dataOnly:_})}return n}function L(e,t,n={}){return{ruleId:e,message:t,...n}}function Ye(e){let{config:t,rules:n,files:r,manifest:s}=e,i=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(c=>typeof c!="string"))&&i.push(L("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","dynamicImportAllowlist must be an array of file globs.")),t.safety!==void 0&&(t.safety===null||typeof t.safety!="object"||Array.isArray(t.safety)))i.push(L("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let c of["maxTsSuppressions","maxAnyCasts"]){let d=t.safety[c];d!==void 0&&(!Number.isInteger(d)||d<0)&&i.push(L("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${c} must be a non-negative integer.`))}let a=Array.isArray(t.layers)?t.layers:[],o=Array.isArray(s?.architecture?.layers)?s.architecture.layers:[],u=new Set([...a.map(c=>c.name).filter(Boolean),...o.map(c=>c.name).filter(c=>!!c)]);a.length===0&&i.push(L("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let m=new Set,h=new Set;for(let c of a){if(!c.name){i.push(L("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}m.has(c.name)&&h.add(c.name),m.add(c.name),c.forbiddenGlobals!==void 0&&(!Array.isArray(c.forbiddenGlobals)||c.forbiddenGlobals.some(f=>typeof f!="string"))&&i.push(L("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${c.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:c.name}));let d=Array.isArray(c.patterns)?c.patterns:[];if(d.length===0){i.push(L("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${c.name}" has no file patterns and will never classify files.`,{layer:c.name}));continue}for(let f of d){let b;try{b=re(f)}catch(R){i.push(L("CONFIG_INVALID_LAYER_PATTERN",`Layer "${c.name}" has an invalid pattern "${f}": ${R instanceof Error?R.message:String(R)}`,{layer:c.name,pattern:f}));continue}!r.some(R=>b.test(R))&&!c.optional&&i.push(L("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${c.name}" pattern "${f}" matched no included files.`,{layer:c.name,pattern:f,failsStrict:!1}))}}for(let c of h)i.push(L("CONFIG_DUPLICATE_LAYER",`Layer "${c}" is configured more than once.`,{layer:c}));if(u.size>0)for(let c of n??[])c.from&&!u.has(c.from)&&i.push(L("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${c.from}".`,{fromLayer:c.from,toLayer:c.to})),c.to&&!u.has(c.to)&&i.push(L("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${c.to}".`,{fromLayer:c.from,toLayer:c.to}));let g=new Set;if(a.length>1)for(let c of r){let d=-1,f=[];for(let b of a)for(let R of b.patterns??[]){if(!re(R).test(c))continue;let p=Tt(R,c);p>d?(d=p,f=[b.name]):p===d&&!f.includes(b.name)&&f.push(b.name)}f.length>1&&g.add([...f].sort().join(" + "))}g.size>0&&i.push(L("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...g].join(", ")}.`,{pairs:[...g]}));let l=r.filter(c=>!z(c,a));return l.length>0&&i.push(L("CONFIG_UNCLASSIFIED_FILES",`${l.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:l.length,samples:l.slice(0,5)})),i}function ds(e,t){return t.some(n=>{try{return re(n).test(e)}catch{return!1}})}function ps(e,t){let n=e.contract.config.safety??{},r=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,s=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,i=e.contract.config.dynamicImportAllowlist??[],a=t.safetyUses.filter(f=>f.kind==="ts-suppression").map(({file:f,line:b})=>({file:f,line:b})),o=t.safetyUses.filter(f=>f.kind==="any-cast").map(({file:f,line:b})=>({file:f,line:b})),u=t.safetyUses.filter(f=>(f.kind==="dynamic-import"||f.kind==="dynamic-require")&&!ds(f.file,i)).map(f=>({file:f.file,line:f.line,kind:f.kind==="dynamic-require"?"require":"import"})),m=n.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(f=>f.kind==="in-memory-store").map(f=>({file:f.file,line:f.line,store:f.symbol??"in-memory store"})),h=n.allowDisabledPeerIsolation===!0?[]:(e.contract.config.rules??[]).filter(f=>f.peerIsolation===!1||f.allowed===!1&&!!f.from&&f.from===f.to&&f.peerIsolation!==!0).map(f=>({from:f.from,to:f.to})),g={tsSuppressions:a,anyCasts:o,nonLiteralDynamicImports:u,inMemoryProductionStores:m,disabledPeerIsolationRules:h,thresholds:{maxTsSuppressions:r,maxAnyCasts:s}},l=[],c=u.filter(f=>f.kind==="import");if(c.length>0){let f=c[0];l.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:f.file,line:f.line,message:`${c.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let d=u.filter(f=>f.kind==="require");if(d.length>0){let f=d[0];l.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:f.file,line:f.line,message:`${d.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(a.length>r){let f=a[0];l.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:f.file,line:f.line,message:`${a.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${r}).`})}if(o.length>s){let f=o[0];l.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:f.file,line:f.line,message:`${o.length} explicit any cast(s) exceed safety.maxAnyCasts (${s}).`})}if(m.length>0){let f=m[0];l.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:f.file,line:f.line,message:`${m.length} ArkGate InMemory store risk(s) appear in governed production source. Provide durable stores or set safety.allowInMemory only for an explicitly ephemeral service.`})}return h.length>0&&l.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${h.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:g,warnings:l}}function us(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}function Dn(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return Dt(e,n.length>0?n:Mt.map(r=>({name:r.layer,prefixes:r.prefixes})))}function fs(e,t,n){let r=[],s=new Map(e.contract.config.layers.map(i=>[i.name,i]));for(let i of t.ambientUses){let a=n.get(i.file);!a||!us(i.symbol,s.get(a)?.forbiddenGlobals??[])||r.push({ruleId:"FORBIDDEN_GLOBAL",file:i.file,line:i.line,fromLayer:a,target:i.symbol,message:`${a} must not use the ambient global "${i.symbol}".`})}for(let i of t.capabilityUses){let a=n.get(i.file);if(!a)continue;let o=s.get(a),u=o?.forbiddenGlobals??[],m=i.source==="import-based"?t.dependencies.find(h=>h.from===i.file&&h.line===i.line&&h.specifier===i.symbol&&!h.typeOnly)?.kind:void 0;if(!(i.source==="ambient-global"&&Oe(i.symbol,u))){if(i.source==="import-based"){let h=J(i.symbol,u);if(h){r.push({ruleId:"FORBIDDEN_GLOBAL",file:i.file,line:i.line,fromLayer:a,target:i.symbol,...m?{edgeKind:m}:{},message:`${a} must not use module "${i.symbol}" because it is the import form of forbidden global "${h}".`});continue}}fe(o).includes(i.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:i.file,line:i.line,fromLayer:a,target:i.symbol,capability:i.capability,...m?{edgeKind:m}:{},message:i.source==="import-based"?`${a} denies the ${i.capability} capability; found import of "${i.symbol}".`:`${a} denies the ${i.capability} capability; found ambient "${i.symbol}".`})}}for(let i of t.publishCalls){let a=n.get(i.file);if(!a)continue;for(let u of $e({publishCall:!0,rawIntentName:i.rawIntentName,objectHasIntent:i.objectHasIntent,arkPublishCandidate:i.arkPublishCandidate,hasSource:i.hasSource}))r.push({ruleId:u.ruleId,file:i.file,line:i.line,...u.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:a}:{},message:u.message});if(!i.sourceIntent)continue;let o=Dn(i.sourceIntent,e.contract);!o||o===a||r.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:i.file,line:i.line,fromLayer:a,toLayer:o,target:i.sourceIntent,message:`Publish source "${i.sourceIntent}" resolves to ${o}, but the publishing file is classified as ${a}.`})}for(let i of t.intentReferences){let a=n.get(i.file);if(!a)continue;let o=Dn(i.intent,e.contract);if(!o)continue;let u=K(e.contract.config.rules,a,o);u&&r.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:i.file,line:i.line,fromLayer:a,toLayer:o,target:i.intent,message:u.message??`${a} must not reference ${o} intent ${i.intent}.`})}return r}function ys(e){let{facts:t}=e,n=be(e.contract.config),r=t.evidenceRequirementsHash===n,s=r?t.completeness:"unavailable",i=r?t.completenessReasons:[...t.completenessReasons,{code:"EVIDENCE_REQUIREMENTS_MISMATCH",message:"Resolved facts were collected for different policy-controlled evidence requirements."}].sort((A,j)=>{let ke=`${A.code}\0${A.file??""}\0${A.message}`,xe=`${j.code}\0${j.file??""}\0${j.message}`;return ke<xe?-1:ke>xe?1:0}),a=t.files.map(A=>({...A,layer:z(A.path,e.contract.config.layers)??null})),o=new Map(a.map(A=>[A.path,A.layer])),u=t.dependencies.map(A=>{let j=A.target?o.get(A.target)??z(A.target,e.contract.config.layers):void 0;return{from:A.from,fromLayer:o.get(A.from)??null,...A.resolution==="resolved-project"&&A.target?{to:A.target,...j?{toLayer:j}:{}}:{},line:A.line,kind:A.kind,typeOnly:A.typeOnly,...A.targetTypeOnlyExports?{targetTypeOnlyExports:A.targetTypeOnlyExports}:{},...A.sourcePureTypeModule?{sourcePureTypeModule:A.sourcePureTypeModule}:{},...A.namedBindingsTypeOnly?{namedBindingsTypeOnly:A.namedBindingsTypeOnly}:{},...A.portProofEligible?{portProofEligible:A.portProofEligible}:{}}}),m=Ye({config:e.contract.config,rules:e.contract.config.rules,files:a.map(A=>A.path)}),h=ps(e,t),g=e.contract.arkRules??te(),l=a.map(A=>A.path),d={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?Et(e.coverageInputs.fileContents):{},...e.fileHints??{}},f=[...vt({arkRules:g,classShapes:e.contract.classShapes??t.classShapes??[],files:l,layerForFile:A=>o.get(A)??z(A,e.contract.config.layers),fileHints:d}),...It(g,l)],b=f.filter(A=>A.failsStrict).map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,arkruleId:A.arkruleId,arkruleSource:A.arkruleSource,nextAction:A.ruleId==="ARKRULE_SCOPE_EMPTY"?`Fix appliesTo globs for ${A.arkruleId} in ${A.arkruleSource} so they match governed files, or remove the rule.`:`Fix the structure or invariant for ${A.arkruleId} (declared in ${A.arkruleSource}), then preflight again.`})),R=f.filter(A=>!A.failsStrict).map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,arkruleId:A.arkruleId,arkruleSource:A.arkruleSource,failsStrict:!1,nextAction:A.ruleId==="ARKRULE_SCOPE_EMPTY"?`Review appliesTo for ${A.arkruleId} in ${A.arkruleSource} (zero-match scope; advisory).`:`Review ArkRule ${A.arkruleId} in ${A.arkruleSource} (advisory).`})),y=(g.invariants?.length??0)>0?pt({arkRules:g,fileContents:e.coverageInputs?.fileContents??{},testFiles:e.coverageInputs?.testFiles??[],testGlobsMissing:e.coverageInputs?.testGlobsMissing===!0||e.coverageInputs===void 0||(e.coverageInputs.testFiles?.length??0)===0}):{coverage:[],violations:[],partial:!1},v=y.violations.filter(A=>A.failsStrict).map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,arkruleId:A.arkruleId,arkruleSource:A.arkruleSource,nextAction:`Add a test title or declared symbol covering ${A.arkruleId} (declared in ${A.arkruleSource}), then preflight again.`})),C=y.violations.filter(A=>!A.failsStrict).map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,arkruleId:A.arkruleId,arkruleSource:A.arkruleSource,failsStrict:!1,nextAction:`Cover invariant ${A.arkruleId} in ${A.arkruleSource} (advisory / partial).`})),_=y.partial&&y.coverage.some(A=>A.mode==="enforced"&&A.partial)?[{code:"INVARIANT_COVERAGE_PARTIAL",message:"Enforced ArkRules invariant coverage cannot be fully proven (missing test globs or empty test set); reporting partial, never covered."}]:[],x=pe({config:e.contract.config,rules:e.contract.config.rules,files:a.filter(A=>A.layer).map(A=>A.path),contentViolations:[...fs(e,t,o),...b,...v],edges:u,warnings:[...m,...h.warnings,...R,...C],safety:h.report}),ue=s==="complete"&&_.length>0?"partial":s,Ce=ue==="complete"?i:[...i,..._].sort((A,j)=>{let ke=`${A.code}\0${A.file??""}\0${A.message}`,xe=`${j.code}\0${j.file??""}\0${j.message}`;return ke<xe?-1:ke>xe?1:0}),ne=x.violations.filter(A=>A.failsStrict!==!1),Se=ue==="complete"&&ne.length===0,Jt=Se&&x.warnings.every(A=>A.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:ue,completenessReasons:Ce,valid:Se,strictValid:Jt,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:h.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:a,layers:e.contract.config.layers.map(A=>A.name),edges:u,capabilityUses:t.capabilityUses,violations:x.violations,warnings:x.warnings}}}function Ee(e){return ys({contract:e.contract,facts:Z(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints})}function Ct(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return e.typeOnly||e.targetTypeOnlyExports||e.namedBindingsTypeOnly?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":e.peerIsolation?"Extract the shared dependency to a shared layer, then preflight again.":`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, then preflight again.`;case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, then preflight again.`;case"CAPABILITY_VIOLATION":return`Define a ${String(e.capability??"capability")} port in ${e.fromLayer??"the walled layer"}, bind the implementation outside it, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";case"ARKRULE_STRUCTURE":case"ARKRULE_INVARIANT":case"INVARIANT_UNCOVERED":return`Fix the structure or invariant for ${typeof e.arkruleId=="string"&&e.arkruleId.length>0?e.arkruleId:"the ArkRule"} (declared in ${typeof e.arkruleSource=="string"&&e.arkruleSource.length>0?e.arkruleSource:"arkrules/<Layer>.json"}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`;default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}function Hn(e){return O(S(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}function Wt(e){let t=ve(e),n=new Map(t.ir.files.map(d=>[d.path,d])),r=[],s=new Set,i=[];for(let d of e.changes){let f=d.path.replace(/\\/g,"/"),b=de(d.path);if(!b||b===".."||b.startsWith("../")||f.startsWith("/")||/^[A-Za-z]:\//.test(f)||f.includes("\0")){i.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(s.has(b)){i.push({ruleId:"DUPLICATE_CHANGE_PATH",file:b,line:1,message:`The atomic change set contains more than one operation for ${b}.`});continue}s.add(b),"delete"in d&&d.delete&&!n.has(b)&&i.push({ruleId:"DELETE_TARGET_MISSING",file:b,line:1,message:`Cannot delete ${b} because it is not present in the supplied base tree.`}),r.push("delete"in d&&d.delete?{path:b,delete:!0}:{path:b,content:"content"in d?d.content:""})}e.changes.length===0&&i.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let a=ze({...e,changes:r}),o=new Map(a.ir.files.map(d=>[d.path,d])),u=a.ir.violations.filter(d=>d.ruleId==="CAPABILITY_VIOLATION"||d.ruleId==="FORBIDDEN_GLOBAL").map(d=>{let f=o.get(d.evidence.file)?.layer;return{ruleId:d.ruleId,file:d.evidence.file,line:d.evidence.line,target:d.symbol,...d.capability?{capability:d.capability}:{},...f?{fromLayer:f}:{},edgeKind:"import",message:d.message}}),m=pe({config:e.contract.config,rules:e.contract.config.rules,files:a.ir.files.map(d=>d.path),contentViolations:u,edges:a.ir.edges.filter(d=>!!d.fromLayer).map(d=>({from:d.from,fromLayer:d.fromLayer,...d.to?{to:d.to}:{},...d.toLayer?{toLayer:d.toLayer}:{},line:d.evidence.line,kind:"import",...d.typeOnly?{typeOnly:!0}:{},...d.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),h=r.map(d=>{let f=de(d.path),b=n.get(f),R=o.get(f);return{path:f,operation:"delete"in d&&d.delete?"delete":b?"update":"create",...b?{beforeContentHash:b.contentHash}:{},...R?{candidateContentHash:R.contentHash}:{}}}).sort((d,f)=>d.path.localeCompare(f.path)),g=[...i,...m.violations].map(d=>({...d,nextAction:Ct(d)})),l=g.filter(d=>d.failsStrict!==!1),c=e.changeMap?oe({changeMap:e.changeMap,changes:h,baseDependencies:t.ir.edges.flatMap(d=>d.to?[{from:d.from,to:d.to}]:[]),candidateDependencies:a.ir.edges.flatMap(d=>d.to?[{from:d.from,to:d.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&a.valid&&l.length===0&&(c?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:a.ir.compilerOptionsHash,baseTreeHash:Hn(t.ir.files),candidateTreeHash:Hn(a.ir.files),baseCompleteness:t.completeness,candidateCompleteness:a.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:a.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...c?{convergence:c}:{},changes:h,violations:g,warnings:m.warnings}}function ms(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let s of t.split("/"))if(!(!s||s==="."))if(s===".."){if(n.length===0)return;n.pop()}else n.push(s);let r=n.join("/");return r&&r===t?r:void 0}function gs(e,t){return[["resolverIdentity",e.resolverIdentity,t.resolverIdentity],["compilerIdentity",e.compilerIdentity,t.compilerIdentity],["evidenceRequirementsHash",e.evidenceRequirementsHash,t.evidenceRequirementsHash],["projectPackageName",e.projectPackageName??"",t.projectPackageName??""]].filter(([,r,s])=>r!==s).map(([r,s,i])=>({ruleId:"FACTS_IDENTITY_MISMATCH",file:"<change-set>",line:1,field:r,before:s,candidate:i,message:`Base and candidate facts must use the same ${r}.`}))}function hs(e,t,n,r){let s=n.get(t),i=r.get(t);return{path:t,operation:"delete"in e&&e.delete?"delete":s?"update":"create",...s?{beforeContentHash:s.contentHash}:{},...i?{candidateContentHash:i.contentHash}:{}}}function Zt(e){let t=Z(e.baseFacts),n=Z(e.candidateFacts),r=Ee({contract:e.contract,facts:t}),s=Ee({contract:e.contract,facts:n}),i=new Map(t.files.map(c=>[c.path,c])),a=new Map(n.files.map(c=>[c.path,c])),o=gs(t,n),u=new Map,m=[];for(let c of e.changes){let d=ms(c.path);if(!d){o.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(u.has(d)){o.push({ruleId:"DUPLICATE_CHANGE_PATH",file:d,line:1,message:`The atomic change set contains more than one operation for ${d}.`});continue}u.set(d,c);let f=i.get(d),b=a.get(d);if("delete"in c&&c.delete)f||o.push({ruleId:"DELETE_TARGET_MISSING",file:d,line:1,message:`Cannot delete ${d} because it is not present in the supplied base facts.`}),b&&o.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:d,line:1,message:`Candidate facts still contain deleted file ${d}.`});else{let R="content"in c?c.content:"",p=O(R);b?b.contentHash!==p&&o.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:d,line:1,expectedContentHash:p,candidateContentHash:b.contentHash,message:`Candidate facts for ${d} do not match the declared content.`}):o.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:d,line:1,message:`Candidate facts do not contain changed file ${d}.`})}m.push(hs(c,d,i,a))}e.changes.length===0&&o.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});for(let c of new Set([...i.keys(),...a.keys()])){if(u.has(c))continue;let d=i.get(c),f=a.get(c);d&&f&&S(d)===S(f)||o.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:c,line:1,message:`Candidate facts change ${c}, but the atomic change set does not declare it.`})}let h=e.changeMap?oe({changeMap:e.changeMap,changes:m,baseDependencies:r.ir.edges.flatMap(c=>c.to?[{from:c.from,to:c.to}]:[]),candidateDependencies:s.ir.edges.flatMap(c=>c.to?[{from:c.from,to:c.to}]:[])}):void 0,g=[...o,...s.ir.violations].map(c=>({...c,nextAction:Ct(c)})),l=g.filter(c=>c.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&s.strictValid&&l.length===0&&(h?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,resolverIdentity:n.resolverIdentity,compilerIdentity:n.compilerIdentity,compilerOptionsHash:n.compilerOptionsHash,tsconfigHash:n.tsconfigHash,baseCompilerOptionsHash:t.compilerOptionsHash,candidateCompilerOptionsHash:n.compilerOptionsHash,baseTsconfigHash:t.tsconfigHash,candidateTsconfigHash:n.tsconfigHash,evidenceRequirementsHash:n.evidenceRequirementsHash,baseFactsHash:t.factsHash,candidateFactsHash:n.factsHash,baseTreeHash:t.candidateTreeHash,candidateTreeHash:n.candidateTreeHash,baseCompleteness:r.completeness,candidateCompleteness:s.completeness,baseCompletenessReasons:r.completenessReasons,candidateCompletenessReasons:s.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...h?{convergence:h}:{},changes:m.sort((c,d)=>c.path<d.path?-1:c.path>d.path?1:0),violations:g,warnings:s.ir.warnings}}function St(e,t){return e.slice(0,t).split(`
16
- `).length}function Vn(e){let t=[],n=0;for(let[i,a]of Object.entries(e.fileContents).sort(([o],[u])=>o.localeCompare(u))){let o=i.replace(/\\/g,"/"),u=/(?:^|\/)(?:components|ui|layouts|styles|hooks|theme|tokens|i18n|locales?)(?:\/|$)/i.test(o)||/(?:^|\/)(?:src\/)?(?:app|pages)\/.+\.(?:tsx|jsx)$/i.test(o)&&/(?:page|layout|loading|error|template|default)\.(?:tsx|jsx)$/i.test(o),m=/(?:^|\/)(?:app|pages)(?:\/[^/]+)*\/api(?:\/|$)/i.test(o),h=/(?:^|\/)actions?(?:\/|\.|$)/i.test(o)||/['"]use server['"]/.test(a),g=/controller|handler|resolver/i.test(i)||m||h||/route\.(?:ts|js|tsx|jsx)$/i.test(o)&&!u||/@(Controller|Get|Post|Put|Delete|Patch)\b/.test(a)||/\bexport\s+(?:async\s+)?function\s+(?:GET|POST|PUT|DELETE|PATCH)\b/.test(a)||/\bexport\s+const\s+(?:GET|POST|PUT|DELETE|PATCH)\s*=/.test(a),l=/domain|entity|aggregate|model/i.test(i);if(g&&!u){let b=/\b(if\s*\([^)]{0,80}(amount|total|price|qty|quantity|balance)[^)]{0,40}\)|throw new (Error|BadRequest|ValidationError)|z\.object\(|yup\.|class-validator|@Is[A-Z])/g,R;for(;(R=b.exec(a))!==null;)n+=1,t.push({id:`inv-val-${n}`,kind:"validation-in-controller",file:i,line:St(a,R.index),message:"Business validation appears in a controller/handler \u2014 extract an invariant or Domain rule.",confidence:"direct-evidence",suggestedArkRule:{layer:"DomainModel",invariantId:`INV-EXTRACT-${n}`,sensor:"invariant-coverage"},neverMechanicalSafe:!0})}let c=/\b(const|let)\s+([A-Z][A-Z0-9_]{2,})\s*=\s*(\d{2,}|['"][^'"]{8,}['"])/g,d,f=b=>/^(?:TEST|SPEC|TIMEOUT|PORT|VERSION|MAX_RETRY|MIN_RETRY|TTL|CACHE|HEADER|COOKIE|MIME|CONTENT_TYPE|HTTP_STATUS|NODE_ENV|LOG_LEVEL|FEATURE_FLAG|ID_PREFIX|Z_INDEX)(?:_|$)/i.test(b)||/^(?:ROUTE|PATH|LABEL|TITLE|HEADING|CLASS|STYLE|COLOR|THEME|BREAKPOINT|QUERY|PARAM|ICON|ARIA|MSG|COPY|I18N|LOCALE|PAGE|NAV|MENU|TAB|BTN|BUTTON|PLACEHOLDER|TOOLTIP|SHADOW|RADIUS|GAP|PADDING|MARGIN|FONT|WIDTH|HEIGHT|OPACITY|DURATION|EASE|ANIM)_/i.test(b)||/_(?:ROUTE|PATH|LABEL|TITLE|COLOR|THEME|CLASS|STYLE|ICON|ARIA|MSG|COPY|TIMEOUT|PORT|VERSION|RETRY|DELAY|INTERVAL|TTL|CACHE)$/i.test(b)||/_(?:TIMEOUT(?:_MS)?|MS|BYTES|BUCKET|STORAGE_KEY|WINDOW_MS)$/i.test(b)||/^(?:DEFAULT_(?:BASE_URL|TIMEOUT(?:_MS)?|RETRY|PORT|HOST|HEADERS?|CACHE|TTL|MS|LOCALE|LANG|TIMEZONE|TZ)|REQUEST_(?:TIMEOUT(?:_MS)?|HEADERS?|RETRY|ID_PREFIX)|STORAGE_(?:KEY|PREFIX|BUCKET)|DAY_MS$|APP_DOMAIN$|BASE_URL$)$/i.test(b)||/^(?:FAVORITES_STORAGE|LISTINGS_CACHE|DOCS_PATH|METRICS_INTERVAL)/i.test(b);for(;(d=c.exec(a))!==null;){let b=d[2];f(b)||u&&!l||/(?:^|\/)(?:integrations?|repos?|clients?|infra(?:structure)?|adapters?)(?:\/|$)/i.test(o)&&!l||(n+=1,t.push({id:`inv-magic-${n}`,kind:"magic-business-constant",file:i,line:St(a,d.index),message:`Magic business constant ${b} may belong in a Domain policy or invariant catalog.`,confidence:"heuristic",suggestedArkRule:{layer:"DomainModel",invariantId:`INV-${b}`},neverMechanicalSafe:!0}))}if(l){let b=/export\s+class\s+([A-Za-z_][A-Za-z0-9_]*)\s*\{([^}]{0,800})\}/g,R;for(;(R=b.exec(a))!==null;){let p=R[2]??"",y=(p.match(/\b[a-zA-Z_][a-zA-Z0-9_]*\s*\(/g)??[]).length;(p.match(/:\s*[A-Za-z]/g)??[]).length>=2&&y<=1&&(n+=1,t.push({id:`inv-anemic-${n}`,kind:"anemic-entity",file:i,line:St(a,R.index),message:`Class ${R[1]} looks anemic (data-heavy, few behaviors).`,confidence:"heuristic",suggestedArkRule:{layer:"DomainModel",structureId:"no-anemic-model",sensor:"no-anemic-model"},neverMechanicalSafe:!0}))}}if(l&&!(/\.error\.(?:ts|js|tsx|jsx)$/i.test(o)||/(?:^|\/)[^/]*(?:-access)?\.error\./i.test(o)||/(?:^|\/)errors?(?:\/|$)/i.test(o))){let R=/this\.\w+\s*=/g,p;for(;(p=R.exec(a))!==null;){let y=a.slice(Math.max(0,p.index-200),p.index+200);if(!/\b(ensureInvariants|assertInvariants|validate|publish|emit)\b/.test(y)){n+=1,t.push({id:`inv-mut-${n}`,kind:"mutation-without-guard",file:i,line:St(a,p.index),message:"Domain field mutation without nearby guard/publish call.",confidence:"heuristic",suggestedArkRule:{layer:"DomainModel",structureId:"events-on-mutation",sensor:"domain-event-on-mutation"},neverMechanicalSafe:!0});break}}}}let r=new Set(e.contractedRuleIds??[]),s=t.filter(i=>i.suggestedArkRule?.invariantId&&r.has(i.suggestedArkRule.invariantId)||i.suggestedArkRule?.structureId&&r.has(i.suggestedArkRule.structureId)).length;return{candidates:t,inventoried:t.length,underContract:s,frozen:(e.frozenKeys??[]).length,notAScore:!0}}function jn(e){return{pilot:`Extract rule candidate ${e.id} (${e.kind})`,pilotTarget:e.file,smellId:e.kind,move:`Declare in arkrules/${e.suggestedArkRule?.layer??"DomainModel"}.json, implement pure Domain logic, add covering test.`,doNot:["Do not auto-apply codemods","Do not promote to enforced without coverage evidence","Do not batch multiple extractions"],successSignal:"Doctor reports candidate under contract; gate green with residual honest.",killSwitch:"Stop if extraction requires multi-module redesign without a clear aggregate owner.",neverMechanicalSafe:!0,class:"judgment",next:"Run ark_prepare_change / preflight, then re-doctor."}}var Un="1.1";var Gn="1.0";0&&(module.exports={ANALYSIS_IR_SCHEMA_VERSION,ARK_ANALYSIS_RESULT_SCHEMA,ARK_ANALYSIS_RESULT_SCHEMA_VERSION,ARK_CONFIG_SCHEMA,ARK_CONFIG_SCHEMA_VERSION,ARK_DESIGN_DELTA_SCHEMA_VERSION,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION,ARK_RULES_SCHEMA,ARK_RULES_SCHEMA_VERSION,ARK_RULE_SENSORS,EffectiveContractError,POLICY_DELTA_SCHEMA_VERSION,RESOLVED_CANDIDATE_FACTS_SCHEMA,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,analyzeArchitectureConvergence,analyzeChange,analyzePolicyDelta,analyzeProject,analyzeResolvedProject,buildArkRuleFileHints,buildEffectiveArkRules,buildRulesInventory,canPromoteInvariant,classifyArkPolicyDelta,collectAnalysisConfigWarnings,collectEmptyAppliesToFindings,collectForbiddenCapabilityUses,createAICodeGate,createAdapterResult,createArchitectureProfile,createArchitectureProfileFromArkConfig,createElevenLayerArkConfig,createResolvedCandidateFacts,deriveArkRuleFileHints,detectArchitectureCycles,deterministicHash,effectiveContractPolicyPayload,elevenLayerProfile,emptyEffectiveArkRules,evaluateArchitectureGraph,evaluateArkRuleSensors,evaluateInvariantCoverage,explainViolation,extractClassShapesFromSource,extractSemanticDependencies,inventoryToExtractionCard,loadArkConfigContract,loadArkRulesContract,loadContract,loadResolvedCandidateFacts,parseArkConfigJson,parseArkRulesJson,policyDeltaAcknowledgementMatches,preflightChange,preflightResolvedChange,resolveEffectiveContract,resolvedFactsEvidenceRequirementsHash,stableSerialize,toAdapterDiagnostic,version});
8
+ `)}`),this.name="EffectiveContractError",this.source=t,this.issues=n}};function Ln(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function Nn(e,t="ark.config.json"){let n=e.config.arkRules,r=[];if(!n||Object.keys(n).length===0){if(e.discoveredArkRulesFiles&&e.discoveredArkRulesFiles.length>0)for(let d of[...e.discoveredArkRulesFiles].sort())r.push({path:d,message:`ArkRules file ${JSON.stringify(d)} is not referenced by arkRules and will not be enforced`,severity:"advisory"});return{config:e.config,arkRules:ie(),warnings:r}}let s=new Set(e.config.layers.map(d=>d.name)),i=[],a=[],o=new Set;for(let d of Object.keys(n).sort()){let f=n[d],g=`$.arkRules[${JSON.stringify(d)}]`;if(typeof f!="string"||f.length===0){i.push({path:g,message:"must be a non-empty relative path string"});continue}if(f.startsWith("/")||/^[A-Za-z]:[\\/]/.test(f)){i.push({path:g,message:"must be a project-relative path (absolute paths are not allowed)"});continue}if(!s.has(d)){i.push({path:g,message:`layer ${JSON.stringify(d)} is not declared in layers[]`});continue}let h=Ln(f);o.add(h);let l=e.fileContents[h]??e.fileContents[f];if(l===void 0){i.push({path:g,message:`referenced ArkRules file ${JSON.stringify(h)} is missing`});continue}try{let c=Ue(JSON.parse(l),h,d);a.push({layer:d,sourceFile:h,file:c.config})}catch(c){if(c instanceof pe)for(let p of c.issues)i.push({path:`${g}${p.path==="$"?"":p.path.replace(/^\$/,"")}`,message:`${h}: ${p.message}`});else c instanceof SyntaxError?i.push({path:g,message:`referenced ArkRules file ${JSON.stringify(h)} is not valid JSON: ${c.message}`}):i.push({path:g,message:`referenced ArkRules file ${JSON.stringify(h)} failed to load: ${c instanceof Error?c.message:String(c)}`})}}if(e.discoveredArkRulesFiles)for(let d of[...e.discoveredArkRulesFiles].sort()){let f=Ln(d);o.has(f)||r.push({path:f,message:`ArkRules file ${JSON.stringify(f)} is not referenced by arkRules and will not be enforced`,severity:"advisory"})}if(i.length>0)throw new Ge(t,i);return{config:e.config,arkRules:pt(a),warnings:r}}function ut(e){return{config:e.config,arkRules:{schemaVersion:e.arkRules.schemaVersion,structure:e.arkRules.structure.map(t=>({id:t.id,sensor:t.sensor,mode:t.mode,appliesTo:t.appliesTo??null,description:t.description??null,provenance:t.provenance})),invariants:e.arkRules.invariants.map(t=>({id:t.id,description:t.description,aggregate:t.aggregate??null,coverage:t.coverage??null,mode:t.mode,appliesTo:t.appliesTo??null,provenance:t.provenance}))}}}function qr(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*['"\`][^'"\`]*${n}[^'"\`]*['"\`]`,"i").test(e)||e.includes(t)}function zr(e,t){if(!t)return!1;let n=t.split("."),r=n[n.length-1],s=n.length>1?n[0]:null;for(let i of Object.values(e))if(!(s&&!i.includes(s))&&(new RegExp(`(?:function\\s+|\\b)${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[(<]`).test(i)||i.includes(t)))return!0;return!1}function ft(e){let t=e.arkRules.invariants??[];if(t.length===0)return{coverage:[],violations:[],partial:!1};let n=e.testFiles??[],r=e.testGlobsMissing===!0||n.length===0,s=[],i=[];for(let a of t){let o=[],d=a.coverage?.test!==!1,f=a.coverage?.symbol;if(!r&&d)for(let c of n){let p=e.fileContents[c];if(p&&qr(p,a.id)){o.push("test-title");break}}f&&zr(e.fileContents,f)&&o.push("symbol");let h=(a.coverage?.test===!0||!!f||a.coverage===void 0)&&o.length>0||a.coverage?.test===!1&&!f?!0:o.length>0,l=r&&d&&o.length===0;if(s.push({invariantId:a.id,layer:a.provenance.layer,sourceFile:a.provenance.sourceFile,mode:a.mode,covered:h&&!l,evidence:o,partial:l,description:a.description}),!h||l){let c=a.mode==="enforced"&&!l;i.push({ruleId:"INVARIANT_UNCOVERED",message:l?`Invariant ${a.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered.`:`Invariant ${a.id} is not covered by a test title or declared symbol.`,file:a.provenance.sourceFile,line:1,arkruleId:a.id,arkruleSource:a.provenance.sourceFile,fromLayer:a.provenance.layer,severity:c?"error":"warning",failsStrict:c})}}return{coverage:s,violations:i,partial:s.some(a=>a.partial)}}function yt(e){return e?e.partial?{ok:!1,reason:"Coverage is partial (missing test globs); cannot promote until evidence is complete."}:e.covered?{ok:!0,reason:`Invariant ${e.invariantId} has coverage evidence.`}:{ok:!1,reason:`Invariant ${e.invariantId} is uncovered; add a test title or symbol before promoting to enforced.`}:{ok:!1,reason:"No coverage evidence supplied for this invariant; evaluate coverage before promoting to enforced."}}var ht="1.0";function C(e,t){e.push({id:`${t.classification}:${t.path}:${t.kind}`,path:t.path,classification:t.classification,message:t.message,...t.classification==="weakening"||t.classification==="judgment-required"?{nextAction:`Restore the previous protection at ${t.path}, then run ArkGate again.`}:{},...t.before===void 0?{}:{before:t.before},...t.after===void 0?{}:{after:t.after}})}function j(e){return[...new Set(e??[])].sort()}function ue(e,t,n,r,s){let i=j(n),a=j(r),o=new Set(i),d=new Set(a),f=a.filter(h=>!o.has(h)),g=i.filter(h=>!d.has(h));f.length===0&&g.length===0||(f.length>0&&C(e,{kind:"added",path:t,classification:s.added,message:s.addedMessage,before:i,after:a}),g.length>0&&C(e,{kind:"removed",path:t,classification:s.removed,message:s.removedMessage,before:i,after:a}))}function mt(e,t,n,r,s,i,a){if(n===r)return;C(e,{kind:r?"enabled":"disabled",path:t,classification:r?s:s==="strengthening"?"weakening":"strengthening",message:r?i:a,before:n,after:r})}function gt(e,t){let n=new Map,r=new Set;for(let s of e){let i=t(s);n.has(i)?r.add(i):n.set(i,s)}return{values:n,duplicates:[...r].sort()}}function Kr(e,t,n){let r=gt(t,i=>i.name),s=gt(n,i=>i.name);(r.duplicates.length>0||s.duplicates.length>0)&&C(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:r.duplicates,after:s.duplicates});for(let i of[...new Set([...r.values.keys(),...s.values.keys()])].sort()){let a=r.values.get(i),o=s.values.get(i),d=`$.layers[${i}]`;if(!a&&o){C(e,{kind:"layer-added",path:d,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:o});continue}if(a&&!o){C(e,{kind:"layer-removed",path:d,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:a});continue}if(!a||!o)continue;ue(e,`${d}.patterns`,a.patterns,o.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),ue(e,`${d}.exclude`,a.exclude,o.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let f=Qe(a),g=Qe(o);ue(e,`${d}.forbiddenGlobals`,f.rawGlobals,g.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),ue(e,`${d}.capabilities`,f.atoms,g.atoms,{added:"strengthening",removed:"weakening",addedMessage:"Additional ambient/import protection is enforced in this layer (coverage atoms).",removedMessage:"An ambient/import protection was lost from this layer (coverage atoms)."}),j(a.intentPrefixes).join("\0")!==j(o.intentPrefixes).join("\0")&&C(e,{kind:"intent-prefixes-changed",path:`${d}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:j(a.intentPrefixes),after:j(o.intentPrefixes)}),mt(e,`${d}.mayImportInfrastructure`,a.mayImportInfrastructure===!0,o.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),mt(e,`${d}.optional`,a.optional===!0,o.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active.")}}function Yr(e,t,n){let r=a=>`${a.from}->${a.to}`,s=gt(t,r),i=gt(n,r);(s.duplicates.length>0||i.duplicates.length>0)&&C(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:s.duplicates,after:i.duplicates});for(let a of[...new Set([...s.values.keys(),...i.values.keys()])].sort()){let o=s.values.get(a),d=i.values.get(a),f=`$.rules[${a}]`;if(!o&&d){d.allowed===!1&&C(e,{kind:"deny-added",path:f,classification:"strengthening",message:"A denied dependency edge was added.",after:d});continue}if(o&&!d){o.allowed===!1&&C(e,{kind:"deny-removed",path:f,classification:"weakening",message:"A denied dependency edge was removed.",before:o});continue}if(!o||!d)continue;o.allowed!==d.allowed&&C(e,{kind:d.allowed?"deny-disabled":"deny-enabled",path:`${f}.allowed`,classification:d.allowed?"weakening":"strengthening",message:d.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:o.allowed,after:d.allowed});let g=o.peerIsolation===!0,h=d.peerIsolation===!0;if(g!==h){let l=o.from===o.to&&d.from===d.to;C(e,{kind:h?"peer-isolation-enabled":"peer-isolation-disabled",path:`${f}.peerIsolation`,classification:l?h?"strengthening":"weakening":"judgment-required",message:l?h?"Cross-slice dependencies inside this layer are now denied.":"Cross-slice dependencies inside this layer are no longer denied.":"Changing peer isolation on a cross-layer edge changes the denial scope.",before:g,after:h})}j(o.sliceFolders).join("\0")!==j(d.sliceFolders).join("\0")&&C(e,{kind:"slice-folders-changed",path:`${f}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:j(o.sliceFolders),after:j(d.sliceFolders)})}}function Wr(e,t,n){let r=t.safety??{},s=n.safety??{};for(let i of["maxTsSuppressions","maxAnyCasts"]){let a=r[i]??0,o=s[i]??0;a!==o&&C(e,{kind:o>a?"threshold-raised":"threshold-lowered",path:`$.safety.${i}`,classification:o>a?"weakening":"strengthening",message:o>a?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:a,after:o})}for(let i of["allowInMemory","allowDisabledPeerIsolation"])mt(e,`$.safety.${i}`,r[i]===!0,s[i]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}function Jr(e){return e.some(t=>t.classification==="weakening")?"weakening":e.some(t=>t.classification==="judgment-required")?"judgment-required":e.some(t=>t.classification==="strengthening")?"strengthening":"neutral"}function Fn(e,t){return`${e}::${t}`}function Mn(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(Fn(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(Fn(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}function Zr(e,t,n,r,s,i){let a=new Map((i??[]).map(l=>[l.invariantId,l])),o=t.arkRules??{},d=n.arkRules??{},f=[...new Set([...Object.keys(o),...Object.keys(d)])].sort();for(let l of f){let c=o[l],p=d[l],y=`$.arkRules[${l}]`;if(c===void 0&&p!==void 0){C(e,{kind:"arkrules-ref-added",path:y,classification:"strengthening",message:`ArkRules reference for layer ${l} was added.`,after:p});continue}if(c!==void 0&&p===void 0){C(e,{kind:"arkrules-ref-removed",path:y,classification:"weakening",message:`ArkRules reference for layer ${l} was removed.`,before:c});continue}c!==p&&C(e,{kind:"arkrules-ref-path-changed",path:y,classification:"judgment-required",message:`ArkRules file path for layer ${l} changed; verify the effective rules still match intent.`,before:c,after:p})}let g=Mn(r),h=Mn(s);for(let l of[...new Set([...g.structure.keys(),...h.structure.keys()])].sort()){let c=g.structure.get(l),p=h.structure.get(l),y=`$.arkRules.structure[${l}]`;if(!c&&p){C(e,{kind:"arkrule-structure-added",path:y,classification:"strengthening",message:`Structure ArkRule ${p.id} was added (${p.mode}).`,after:p});continue}if(c&&!p){C(e,{kind:"arkrule-structure-removed",path:y,classification:"weakening",message:`Structure ArkRule ${c.id} was removed.`,before:c});continue}if(!(!c||!p)){if(c.mode!==p.mode){let b=c.mode==="advisory"&&p.mode==="enforced";C(e,{kind:b?"arkrule-promoted":"arkrule-demoted",path:`${y}.mode`,classification:b?"strengthening":"weakening",message:b?`Structure ArkRule ${p.id} was promoted to enforced.`:`Structure ArkRule ${p.id} was demoted to advisory.`,before:c.mode,after:p.mode})}c.sensor!==p.sensor&&C(e,{kind:"arkrule-sensor-changed",path:`${y}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${p.id} changed sensor identity.`,before:c.sensor,after:p.sensor})}}for(let l of[...new Set([...g.invariants.keys(),...h.invariants.keys()])].sort()){let c=g.invariants.get(l),p=h.invariants.get(l),y=`$.arkRules.invariants[${l}]`;if(!c&&p){C(e,{kind:"arkrule-invariant-added",path:y,classification:"strengthening",message:`Invariant ${p.id} was added (${p.mode}).`,after:p});continue}if(c&&!p){C(e,{kind:"arkrule-invariant-removed",path:y,classification:"weakening",message:`Invariant ${c.id} was removed.`,before:c});continue}if(!(!c||!p)&&c.mode!==p.mode)if(c.mode==="advisory"&&p.mode==="enforced"){let I=a?.get(p.id),u=yt(I);u.ok?C(e,{kind:"arkrule-invariant-promoted",path:`${y}.mode`,classification:"strengthening",message:`Invariant ${p.id} was promoted to enforced (coverage evidence present).`,before:c.mode,after:p.mode}):C(e,{kind:"arkrule-invariant-promote-refused",path:`${y}.mode`,classification:"judgment-required",message:`Invariant ${p.id} cannot be promoted to enforced: ${u.reason}`,before:c.mode,after:p.mode})}else C(e,{kind:"arkrule-invariant-demoted",path:`${y}.mode`,classification:"weakening",message:`Invariant ${p.id} was demoted to advisory.`,before:c.mode,after:p.mode})}}function At(e,t,n){let r=[];ue(r,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),ue(r,"$.exclude",e.exclude,t.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional project paths are excluded from governance.",removedMessage:"Fewer project paths are excluded from governance."}),ue(r,"$.dynamicImportAllowlist",e.dynamicImportAllowlist,t.dynamicImportAllowlist,{added:"weakening",removed:"strengthening",addedMessage:"Additional files may use non-literal dynamic imports.",removedMessage:"Fewer files may use non-literal dynamic imports."}),mt(r,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let s={off:0,soft:1,"framework-soft":1,strict:2},i=e.cyclePolicy??"strict",a=t.cyclePolicy??"strict";if(i!==a){let o=s[a]===s[i]?"judgment-required":s[a]>s[i]?"strengthening":"weakening";C(r,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:o,message:"The cycle enforcement level changed.",before:i,after:a})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&C(r,{kind:"framework-overlay-changed",path:"$.frameworkOverlay",classification:"judgment-required",message:"The framework overlay changed and may alter effective layer matching.",before:e.frameworkOverlay??null,after:t.frameworkOverlay??null}),Kr(r,e.layers,t.layers),Yr(r,e.rules,t.rules),Wr(r,e,t),Zr(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),r.sort((o,d)=>o.path.localeCompare(d.path)||o.id.localeCompare(d.id)),{schemaVersion:ht,classification:Jr(r),findings:r}}function bt(e,t){if(!e||e.schemaVersion!==ht||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(s=>typeof s!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=j(e.findingIds),r=j(t.findingIds);return n.length===r.length&&n.every((s,i)=>s===r[i])}function fe(e){let t=[];for(let n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."&&t.length>0&&t.at(-1)!==".."?t.pop():t.push(n));return t.join("/")}function Dn(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}function Rt(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}function H(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}function Be(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let r=t,s="";for(t+=1;t<e.length;t+=1){let i=e[t];if(i===n)return{value:s,offset:r,excerpt:e.slice(r,t+1)};i==="\\"&&t+1<e.length?(s+=e[t+1],t+=1):s+=i}}function U(e,t,n){return e.startsWith(t,n)&&!Rt(e[n-1])&&!Rt(e[n+t.length])}function Hn(e,t){let n=H(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=H(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!U(e,"type",n))return!1;let s=H(e,n+4);if(s>=e.length||e[s]===","||e[s]==="}"||U(e,"as",s)||!Dn(e[s]))return!1;for(n=s;n<e.length&&Rt(e[n]);)n+=1;if(n=H(e,n),U(e,"as",n)){if(n=H(e,n+2),!Dn(e[n]))return!1;for(;n<e.length&&Rt(e[n]);)n+=1}r=!0}return!1}function Xr(e,t){if(t=H(e,t+6),e[t]==="(")return Be(e,H(e,t+1));let n=!1;if(U(e,"type",t)){let s=H(e,t+4);e[s]!==","&&!U(e,"from",s)&&(n=!0)}else Hn(e,t)&&(n=!0);let r=Vn(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}function Qr(e,t){t=t+6;let n=H(e,t),r=!1;if(U(e,"type",n)){let i=H(e,n+4);(e[i]==="{"||e[i]==="*")&&(r=!0)}else Hn(e,n)&&(r=!0);let s=Vn(e,t,!1);return s&&r?{...s,typeOnly:!0}:s}function Vn(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(U(e,"from",t))return Be(e,H(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return Be(e,t);if(t>0&&(U(e,"import",t)||U(e,"export",t)))return}}function es(e,t){for(t+=1;t<e.length;t+=1){let n=e[t];if(n==="\\")t+=1;else if(n==="`")return t}return e.length}function ts(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=H(e,t+7);if(e[r]!=="(")return;r=H(e,r+1);let s=Be(e,r);return s?{...s,requireCall:!0}:void 0}function ns(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="/"&&e[n+1]==="/"){if(n=e.indexOf(`
9
+ `,n+2),n<0)break;continue}if(r==="/"&&e[n+1]==="*"){let i=e.indexOf("*/",n+2);if(i<0)break;n=i+1;continue}if(r==="`"){n=es(e,n);continue}if(r==="'"||r==='"'){let i=Be(e,n);i&&(n=i.offset+i.excerpt.length-1);continue}let s=r==="i"&&U(e,"import",n)?Xr(e,n):r==="e"&&U(e,"export",n)?Qr(e,n):r==="r"&&U(e,"require",n)?ts(e,n):void 0;s&&(t.push(s),n=s.offset+s.excerpt.length-1)}return t}function jn(e,t){let n=[],r=[];for(let s of ns(e.content)){let i=s.value;if(!i.startsWith(".")){if(s.typeOnly)continue;let f=Oe(i);if(!f)continue;let g=e.content.slice(0,s.offset).split(`
10
+ `).length;r.push({file:e.path,symbol:i,capability:f,evidence:{kind:"import",file:e.path,line:g,excerpt:s.excerpt}});continue}let a=e.content.slice(0,s.offset).split(`
11
+ `).length,o={kind:"import",file:e.path,line:a,excerpt:s.excerpt},d=rs(e.path,i,t);n.push({from:e.path,specifier:i,to:d?.path??null,resolution:d?"resolved":"unresolved",fromLayer:e.layer,toLayer:d?.layer??null,evidence:o})}return{edges:n,capabilityUses:r}}function rs(e,t,n){let r=e.split("/");r.pop();for(let i of t.split("/"))i==="."||i===""||(i===".."?r.pop():r.push(i));let s=r.join("/");for(let i of[s,`${s}.ts`,`${s}.tsx`,`${s}.mts`,`${s}.cts`,`${s}/index.ts`,`${s}/index.tsx`]){let a=n.get(i);if(a)return a}}function Un(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let s=Z(t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});s&&n.push({ruleId:`layer-dependency:${s.from}->${s.to}`,message:s.message??`${s.from} must not depend on ${s.to}.`,edge:r,evidence:r.evidence})}return n}var ss={code:"LEXICAL_EVIDENCE_INCOMPLETE",message:"Lexical compatibility mode cannot prove parse status, TypeScript/package/symlink resolution, or symbol-aware source-policy and safety evidence. Use the resolved candidate facts APIs for an authoritative verdict."};function is(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}function as(e,t){return is(e,t)?P(k(ut({config:e,arkRules:t,warnings:[]}))):P(k(e))}function qe(e,t,n){let r=typeof e=="string"?it(e,t):Ne(e,t),s=n?.arkRules??ie();return{...r,arkRules:s,policyHash:as(r.config,s)}}function Jt(e){let t=qe(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=qe(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=At(t.config,n.config,{baseArkRules:t.arkRules,candidateArkRules:n.arkRules,candidateInvariantCoverage:e.candidateInvariantCoverage}),s=r.findings.filter(o=>o.classification==="weakening"||o.classification==="judgment-required").map(o=>o.id).sort(),i=s.length>0,a=i&&bt(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:s});return{schemaVersion:r.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:r.classification,findings:r.findings,blockingFindingIds:s,requiresAcknowledgement:i,acknowledged:a,valid:!i||a}}function Ee(e){let t=e.files.map(h=>{let l=fe(h.path);return{path:l,content:h.content,contentHash:P(h.content),layer:J(l,e.contract.config.layers)??null}}).sort((h,l)=>h.path.localeCompare(l.path)),n=new Map(t.map(h=>[h.path,h])),r=[],s=[];for(let h of t){let l=jn(h,n);r.push(...l.edges),s.push(...l.capabilityUses)}let i=Un(r,e.contract.config),a=new Map(e.contract.config.layers.map(h=>[h.name,h])),o=new Map(e.contract.config.layers.map(h=>[h.name,new Set(me(h))]));for(let h of s){let l=n.get(h.file)?.layer;if(!l)continue;let c=a.get(l),p=te(h.symbol,c?.forbiddenGlobals??[]);if(p){i.push({ruleId:"FORBIDDEN_GLOBAL",message:`${l} must not use module "${h.symbol}" because it is the import form of forbidden global "${p}".`,symbol:h.symbol,evidence:h.evidence});continue}o.get(l)?.has(h.capability)&&i.push({ruleId:"CAPABILITY_VIOLATION",message:`${l} denies the ${h.capability} capability; found import of "${h.symbol}".`,capability:h.capability,symbol:h.symbol,evidence:h.evidence})}let d=t.length===0?"complete":"partial",f=d==="complete"?[]:[{...ss}],g={schemaVersion:lt,policyHash:e.contract.policyHash,compilerOptionsHash:P(k(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(h=>h.name),edges:r,capabilityUses:s,violations:i};return{mode:"lexical-compatibility",completeness:d,completenessReasons:f,valid:d==="complete"&&i.length===0,ir:g}}function ze(e){let t=new Map(e.files.map(n=>[fe(n.path),n]));for(let n of e.changes){let r=fe(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return Ee({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}function Zt(e){let t=`${e.evidence.file}:${e.evidence.line}`;if(!e.edge)return`${e.ruleId} at ${t}: ${e.message}`;let n=e.edge.to??e.edge.specifier;return`${e.ruleId} at ${t}: ${e.edge.from} imports ${n}. ${e.message}`}function It(e){let t=0,n=new Map,r=new Map,s=new Set,i=[],a=[],o=d=>{n.set(d,t),r.set(d,t),t+=1,i.push(d),s.add(d);for(let h of[...e.get(d)??[]].sort())e.has(h)&&(n.has(h)?s.has(h)&&r.set(d,Math.min(r.get(d)??0,n.get(h)??0)):(o(h),r.set(d,Math.min(r.get(d)??0,r.get(h)??0))));if(r.get(d)!==n.get(d))return;let f=[],g;do{if(g=i.pop(),g===void 0)break;s.delete(g),f.push(g)}while(g!==d);f.length>1&&a.push(f.sort())};for(let d of[...e.keys()].sort())n.has(d)||o(d);return a.sort((d,f)=>d[0]<f[0]?-1:d[0]>f[0]?1:0).map(d=>({ruleId:"CIRCULAR_DEPENDENCY",file:d[0],line:1,target:d.join(" \u2192 "),message:`Circular dependency among ${d.length} files: ${d.join(" \u2192 ")} \u2192 ${d[0]}.`,cycleKind:"value"}))}function ye(e){let t=e.contentViolations.map(i=>({...i})),n=(e.warnings??[]).map(i=>({...i})),r=new Map(e.files.map(i=>[i,new Set]));for(let i of e.edges){if(i.to&&i.to!==i.from&&!i.typeOnly&&r.has(i.from)&&r.get(i.from)?.add(i.to),!i.to||!i.fromLayer||!i.toLayer)continue;let a=Z(e.rules,i.fromLayer,i.toLayer,{fromPath:i.from,toPath:i.to,layers:e.config.layers});if(!a)continue;let o=!!a.peerIsolation,d=!o&&!!(i.typeOnly||i.namedBindingsTypeOnly),f=a.message??(o?`${i.fromLayer} must not ${i.kind} another slice of ${i.toLayer} (${i.from} \u2192 ${i.to}). Extract shared code or use events/ports across slices.`:`${i.fromLayer} must not ${i.kind} ${i.toLayer}.`);t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:i.from,line:i.line,fromLayer:i.fromLayer,toLayer:i.toLayer,target:i.to,...i.typeOnly?{typeOnly:!0}:{},...i.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...i.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...i.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!o&&i.portProofEligible?{portProofEligible:!0}:{},...i.kind?{edgeKind:i.kind}:{},...o?{peerIsolation:!0}:{},message:d?`${f} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:f,...d?{failsStrict:!1,severity:"warning"}:{}})}let s=String(e.config.cyclePolicy??"strict").toLowerCase();if(s!=="off"){let i=It(r);s==="soft"||s==="framework-soft"?n.push(...i.map(a=>({...a,message:`${a.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...i)}return{violations:t,warnings:n,safety:e.safety}}var os=["no-anemic-model"];function Gn(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function ls(e){let t="";for(let r=0;r<e.length;r+=1){let s=e[r];if(s==="\\"&&r+1<e.length){let i=e[r+1];if("*?{}[],".includes(i)||i==="\\"){t+="\\"+i,r+=1;continue}t+="/";continue}t+=s}let n="";for(let r=0;r<t.length;r+=1){let s=t[r];s==="\\"&&r+1<t.length?(n+=Gn(t[r+1]),r+=1):s==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":s==="?"?n+="[^/]":n+=Gn(s)}return new RegExp(`^${n}$`)}function Ke(e,t){return!t||t.length===0?!0:t.some(n=>ls(n).test(e))}function cs(e){return os.includes(e)}function Bn(e){return e.mode==="enforced"&&!cs(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}function Ce(e,t,n,r=1){let{severity:s,failsStrict:i}=Bn(e);return{ruleId:"ARKRULE_STRUCTURE",code:e.sensor,message:n,file:t,line:r,fromLayer:e.provenance.layer,arkruleId:e.id,arkruleSource:e.provenance.sourceFile,severity:s,sensor:e.sensor,failsStrict:i}}function Xt(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}function vt(e,t,n){return t.filter(r=>!(!r.exported||!Ke(r.file,e.appliesTo)||!Xt(r.file,e,n)))}function ds(e,t,n){let r=[];for(let s of vt(e,t,n))(s.hasPublicSetters||s.hasPublicMutableFields)&&r.push(Ce(e,s.file,`Exported class ${s.className} exposes public mutable state (sensor aggregate-private-state).`));return r}function ps(e,t,n){let r=[];for(let s of vt(e,t,n))if(s.hasPublicConstructor&&!s.hasStaticFactory){if(!(s.hasPublicMutableFields||s.hasPublicSetters||(s.mutatingMethods?.length??0)>0))continue;r.push(Ce(e,s.file,`Exported class ${s.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}return r}function us(e,t,n){let r=[];for(let s of vt(e,t,n))for(let i of s.mutatingMethods)i.referencesGuardOrPublish||r.push(Ce(e,s.file,`Mutating method ${s.className}.${i.name} does not reference a guard or publish symbol (sensor domain-event-on-mutation).`));return r}function fs(e,t){let n=[];for(let r of t.files)Ke(r,e.appliesTo)&&Xt(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(Ce(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}function ys(e,t){let n=[];for(let r of t.files)Ke(r,e.appliesTo)&&Xt(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(Ce(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}function ms(e,t,n){let r=[];for(let s of vt(e,t,n))if(s.dataOnly===!0){let i=Ce(e,s.file,`Exported type ${s.className} looks data-only / anemic (sensor no-anemic-model; advisory only).`);r.push({...i,severity:"warning",failsStrict:!1})}return r}function Et(e){if(!e.arkRules.structure.length)return[];let t=[];for(let n of e.arkRules.structure)switch(n.sensor){case"aggregate-private-state":t.push(...ds(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...ps(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...us(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...fs(n,e));break;case"thin-adapter":t.push(...ys(n,e));break;case"no-anemic-model":t.push(...ms(n,e.classShapes,e.layerForFile));break;case"invariant-coverage":break;default:break}return t.sort((n,r)=>n.file.localeCompare(r.file)||n.arkruleId.localeCompare(r.arkruleId)||n.message.localeCompare(r.message))}function Ct(e,t){let n=[],r=t.map(s=>s.replace(/\\/g,"/"));for(let s of e.structure){if(!s.appliesTo||s.appliesTo.length===0||r.some(d=>Ke(d,s.appliesTo)))continue;let{severity:a,failsStrict:o}=Bn(s);n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule structure "${s.id}" appliesTo matched zero governed files (patterns: ${s.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:s.provenance.sourceFile,line:1,fromLayer:s.provenance.layer,arkruleId:s.id,arkruleSource:s.provenance.sourceFile,severity:a,sensor:s.sensor,failsStrict:o})}for(let s of e.invariants??[]){if(!s.appliesTo||s.appliesTo.length===0||r.some(o=>Ke(o,s.appliesTo)))continue;let a=s.mode==="enforced";n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule invariant "${s.id}" appliesTo matched zero governed files (patterns: ${s.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:s.provenance.sourceFile,line:1,fromLayer:s.provenance.layer,arkruleId:s.id,arkruleSource:s.provenance.sourceFile,severity:a?"error":"warning",sensor:"invariant-coverage",failsStrict:a})}return n.sort((s,i)=>s.file.localeCompare(i.file)||s.arkruleId.localeCompare(i.arkruleId)||s.message.localeCompare(i.message))}var gs=/\bfrom\s+['"](?:@?prisma\/client|@supabase\/|drizzle-orm|typeorm|knex|mongodb|pg|mysql2|better-sqlite3|ioredis|redis)['"]|require\(\s*['"](?:@?prisma\/client|pg|knex|typeorm)/,hs=/\b(?:@Controller|@Get|@Post|@Put|@Delete|Router\(\)|createRouter|express\.Router|fastify\.(?:get|post)|export\s+(?:async\s+)?function\s+(?:GET|POST|PUT|DELETE|PATCH)\b|export\s+const\s+(?:GET|POST|PUT|DELETE|PATCH)\s*=)/,As=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,bs=/\b(?:export\s+)?(?:async\s+)?function\s+(?:can|calculate|compute|should|ensure|validate|is|has)[A-Z]\w*|\b(?:export\s+)?const\s+(?:can|calculate|compute|should|ensure|validate|is|has)[A-Z]\w*\s*=/,Rs=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function Qt(e,t){if(!t||t.length<40)return null;let n=t.match(new RegExp(bs.source,"g"))??[],r=t.match(new RegExp(Rs.source,"g"))??[],s=(t.match(/\bif\s*\(/g)??[]).length,i=(t.match(/\bswitch\s*\(/g)??[]).length,a=n.length>=2||n.length>=1&&r.length>=2||r.length>=3&&s+i>=6,o=gs.test(t),d=hs.test(t)||As.test(t),f=n.length>=1||r.length>=2,g=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),h=o&&f||d&&f||o&&g&&(s>=4||n.length>=1)||d&&o;return!a&&!h?null:{...a?{orchestrationHeavy:!0}:{},...h?{adapterThick:!0}:{}}}function St(e){let t={};for(let[n,r]of Object.entries(e)){let s=Qt(n,r);s&&(t[n.replace(/\\/g,"/")]=s)}return t}function qn(e,t){let n=[],r=/export\s+(?:abstract\s+)?class\s+([A-Za-z_][A-Za-z0-9_]*)\s*(?:extends\s+[^{]+)?(?:implements\s+[^{]+)?\{/g,s;for(;(s=r.exec(t))!==null;){let i=s[1],a=s.index+s[0].length,o=1,d=a;for(;d<t.length&&o>0;){let v=t[d];v==="{"?o+=1:v==="}"&&(o-=1),d+=1}let f=t.slice(a,d-1),g=f.split(`
12
+ `).map(v=>/^\s*\/\//.test(v)||/^\s*\/\*|\*\//.test(v)?v:v.replace(/(?:public\s+|protected\s+)?readonly\s+[a-zA-Z_][a-zA-Z0-9_]*\s*(?::[^=;]+)?(?:=\s*[^;]+)?[;,]?/g,"").replace(/(?:^|[\s;{])readonly\s+[a-zA-Z_][a-zA-Z0-9_]*\s*(?::[^=;]+)?(?:=\s*[^;]+)?[;,]?/g," ")).join(`
13
+ `),h=/(?:^|\n)\s*(?:public\s+)?[a-zA-Z_][a-zA-Z0-9_]*\s*[:=]/m.test(g.replace(/(?:public\s+|private\s+|protected\s+|static\s+|async\s+|get\s+|set\s+)/g,""))&&/(?:^|\n)\s*(public\s+)?(?!constructor|static|get|set|private|protected|readonly)[a-zA-Z_][a-zA-Z0-9_]*\s*[:=]/m.test(g),l=/(?:^|\n)\s*public\s+(?!static|async|get|set|constructor|readonly)[a-zA-Z_]/.test(g)||/(?:^|[\n;])\s*[a-zA-Z_][a-zA-Z0-9_]*\s*:\s*[^=;\n]+[;=]/m.test(g.split(`
14
+ `).filter(v=>!/^\s*(private|protected|static|constructor|get |set |async |\/)/.test(v)).join(`
15
+ `)),c=/(?:^|[\n;{])\s*(?:public\s+)?set\s+[a-zA-Z_]/.test(f),p=/(?:^|[\n;{])\s*private\s+constructor\s*\(/.test(f),y=/(?:^|[\n;{])\s*(?:public\s+)?constructor\s*\(/.test(f)&&!p,b=/(?:^|[\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),I=[],u=new Set(["if","match","when"]),m=/(?:^|\n)\s*(?:public\s+|private\s+|protected\s+|async\s+)*(?!constructor|get|set|static)([a-zA-Z_][a-zA-Z0-9_]*)\s*\([^)]*\)\s*(?::\s*[^{]+)?\{/g,R;for(;(R=m.exec(f))!==null;){let v=R[1];if(u.has(v))continue;let w=R.index+R[0].length,N=1,F=w;for(;F<f.length&&N>0;)f[F]==="{"?N+=1:f[F]==="}"&&(N-=1),F+=1;let B=f.slice(w,F-1);if(!/this\.\w+\s*=/.test(B))continue;let A=/\b(ensureInvariants|assertInvariants|validate|publish|emit|raise|record)\b/.test(B);I.push({name:v,referencesGuardOrPublish:A})}let S=(f.match(/(?:^|\n)\s*(?:public\s+|private\s+|protected\s+)?(?:async\s+)?[a-zA-Z_][a-zA-Z0-9_]*\s*\(/g)??[]).length,T=(g.match(/(?:^|[\n;])\s*(?:public\s+)?(?!constructor|static|get|set|private|protected|readonly)[a-zA-Z_][a-zA-Z0-9_]*\s*[:=]/g)??[]).length,L=S<=1&&T>=2&&(l||h);n.push({file:e,className:i,exported:!0,hasPublicMutableFields:l||h,hasPublicSetters:c,hasPublicConstructor:y,hasStaticFactory:b,mutatingMethods:[...I],dataOnly:L})}return n}function M(e,t,n={}){return{ruleId:e,message:t,...n}}function Ye(e){let{config:t,rules:n,files:r,manifest:s}=e,i=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(c=>typeof c!="string"))&&i.push(M("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","dynamicImportAllowlist must be an array of file globs.")),t.safety!==void 0&&(t.safety===null||typeof t.safety!="object"||Array.isArray(t.safety)))i.push(M("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let c of["maxTsSuppressions","maxAnyCasts"]){let p=t.safety[c];p!==void 0&&(!Number.isInteger(p)||p<0)&&i.push(M("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${c} must be a non-negative integer.`))}let a=Array.isArray(t.layers)?t.layers:[],o=Array.isArray(s?.architecture?.layers)?s.architecture.layers:[],d=new Set([...a.map(c=>c.name).filter(Boolean),...o.map(c=>c.name).filter(c=>!!c)]);a.length===0&&i.push(M("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let f=new Set,g=new Set;for(let c of a){if(!c.name){i.push(M("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}f.has(c.name)&&g.add(c.name),f.add(c.name),c.forbiddenGlobals!==void 0&&(!Array.isArray(c.forbiddenGlobals)||c.forbiddenGlobals.some(y=>typeof y!="string"))&&i.push(M("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${c.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:c.name}));let p=Array.isArray(c.patterns)?c.patterns:[];if(p.length===0){i.push(M("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${c.name}" has no file patterns and will never classify files.`,{layer:c.name}));continue}for(let y of p){let b;try{b=ae(y)}catch(I){i.push(M("CONFIG_INVALID_LAYER_PATTERN",`Layer "${c.name}" has an invalid pattern "${y}": ${I instanceof Error?I.message:String(I)}`,{layer:c.name,pattern:y}));continue}!r.some(I=>b.test(I))&&!c.optional&&i.push(M("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${c.name}" pattern "${y}" matched no included files.`,{layer:c.name,pattern:y,failsStrict:!1}))}}for(let c of g)i.push(M("CONFIG_DUPLICATE_LAYER",`Layer "${c}" is configured more than once.`,{layer:c}));if(d.size>0)for(let c of n??[])c.from&&!d.has(c.from)&&i.push(M("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${c.from}".`,{fromLayer:c.from,toLayer:c.to})),c.to&&!d.has(c.to)&&i.push(M("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${c.to}".`,{fromLayer:c.from,toLayer:c.to}));let h=new Set;if(a.length>1)for(let c of r){let p=-1,y=[];for(let b of a)for(let I of b.patterns??[]){if(!ae(I).test(c))continue;let u=Mt(I,c);u>p?(p=u,y=[b.name]):u===p&&!y.includes(b.name)&&y.push(b.name)}y.length>1&&h.add([...y].sort().join(" + "))}h.size>0&&i.push(M("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...h].join(", ")}.`,{pairs:[...h]}));let l=r.filter(c=>!J(c,a));return l.length>0&&i.push(M("CONFIG_UNCLASSIFIED_FILES",`${l.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:l.length,samples:l.slice(0,5)})),i}function Is(e,t){return t.some(n=>{try{return ae(n).test(e)}catch{return!1}})}function vs(e,t){let n=e.contract.config.safety??{},r=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,s=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,i=e.contract.config.dynamicImportAllowlist??[],a=t.safetyUses.filter(y=>y.kind==="ts-suppression").map(({file:y,line:b})=>({file:y,line:b})),o=t.safetyUses.filter(y=>y.kind==="any-cast").map(({file:y,line:b})=>({file:y,line:b})),d=t.safetyUses.filter(y=>(y.kind==="dynamic-import"||y.kind==="dynamic-require")&&!Is(y.file,i)).map(y=>({file:y.file,line:y.line,kind:y.kind==="dynamic-require"?"require":"import"})),f=n.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(y=>y.kind==="in-memory-store").map(y=>({file:y.file,line:y.line,store:y.symbol??"in-memory store"})),g=n.allowDisabledPeerIsolation===!0?[]:(e.contract.config.rules??[]).filter(y=>y.peerIsolation===!1||y.allowed===!1&&!!y.from&&y.from===y.to&&y.peerIsolation!==!0).map(y=>({from:y.from,to:y.to})),h={tsSuppressions:a,anyCasts:o,nonLiteralDynamicImports:d,inMemoryProductionStores:f,disabledPeerIsolationRules:g,thresholds:{maxTsSuppressions:r,maxAnyCasts:s}},l=[],c=d.filter(y=>y.kind==="import");if(c.length>0){let y=c[0];l.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:y.file,line:y.line,message:`${c.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let p=d.filter(y=>y.kind==="require");if(p.length>0){let y=p[0];l.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:y.file,line:y.line,message:`${p.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(a.length>r){let y=a[0];l.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:y.file,line:y.line,message:`${a.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${r}).`})}if(o.length>s){let y=o[0];l.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:y.file,line:y.line,message:`${o.length} explicit any cast(s) exceed safety.maxAnyCasts (${s}).`})}if(f.length>0){let y=f[0];l.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:y.file,line:y.line,message:`${f.length} ArkGate InMemory store risk(s) appear in governed production source. Provide durable stores or set safety.allowInMemory only for an explicitly ephemeral service.`})}return g.length>0&&l.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${g.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:h,warnings:l}}function Es(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}function zn(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return Gt(e,n.length>0?n:Ut.map(r=>({name:r.layer,prefixes:r.prefixes})))}function Cs(e,t,n){let r=[],s=new Map(e.contract.config.layers.map(i=>[i.name,i]));for(let i of t.ambientUses){let a=n.get(i.file);!a||!Es(i.symbol,s.get(a)?.forbiddenGlobals??[])||r.push({ruleId:"FORBIDDEN_GLOBAL",file:i.file,line:i.line,fromLayer:a,target:i.symbol,message:`${a} must not use the ambient global "${i.symbol}".`})}for(let i of t.capabilityUses){let a=n.get(i.file);if(!a)continue;let o=s.get(a),d=o?.forbiddenGlobals??[],f=i.source==="import-based"?t.dependencies.find(g=>g.from===i.file&&g.line===i.line&&g.specifier===i.symbol&&!g.typeOnly)?.kind:void 0;if(!(i.source==="ambient-global"&&Te(i.symbol,d))){if(i.source==="import-based"){let g=te(i.symbol,d);if(g){r.push({ruleId:"FORBIDDEN_GLOBAL",file:i.file,line:i.line,fromLayer:a,target:i.symbol,...f?{edgeKind:f}:{},message:`${a} must not use module "${i.symbol}" because it is the import form of forbidden global "${g}".`});continue}}me(o).includes(i.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:i.file,line:i.line,fromLayer:a,target:i.symbol,capability:i.capability,...f?{edgeKind:f}:{},message:i.source==="import-based"?`${a} denies the ${i.capability} capability; found import of "${i.symbol}".`:`${a} denies the ${i.capability} capability; found ambient "${i.symbol}".`})}}for(let i of t.publishCalls){let a=n.get(i.file);if(!a)continue;for(let d of Pe({publishCall:!0,rawIntentName:i.rawIntentName,objectHasIntent:i.objectHasIntent,arkPublishCandidate:i.arkPublishCandidate,hasSource:i.hasSource}))r.push({ruleId:d.ruleId,file:i.file,line:i.line,...d.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:a}:{},message:d.message});if(!i.sourceIntent)continue;let o=zn(i.sourceIntent,e.contract);!o||o===a||r.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:i.file,line:i.line,fromLayer:a,toLayer:o,target:i.sourceIntent,message:`Publish source "${i.sourceIntent}" resolves to ${o}, but the publishing file is classified as ${a}.`})}for(let i of t.intentReferences){let a=n.get(i.file);if(!a)continue;let o=zn(i.intent,e.contract);if(!o)continue;let d=Z(e.contract.config.rules,a,o);d&&r.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:i.file,line:i.line,fromLayer:a,toLayer:o,target:i.intent,message:d.message??`${a} must not reference ${o} intent ${i.intent}.`})}return r}function Ss(e){let{facts:t}=e,n=Ie(e.contract.config),r=t.evidenceRequirementsHash===n,s=r?t.completeness:"unavailable",i=r?t.completenessReasons:[...t.completenessReasons,{code:"EVIDENCE_REQUIREMENTS_MISMATCH",message:"Resolved facts were collected for different policy-controlled evidence requirements."}].sort((A,q)=>{let ke=`${A.code}\0${A.file??""}\0${A.message}`,xe=`${q.code}\0${q.file??""}\0${q.message}`;return ke<xe?-1:ke>xe?1:0}),a=t.files.map(A=>({...A,layer:J(A.path,e.contract.config.layers)??null})),o=new Map(a.map(A=>[A.path,A.layer])),d=t.dependencies.map(A=>{let q=A.target?o.get(A.target)??J(A.target,e.contract.config.layers):void 0;return{from:A.from,fromLayer:o.get(A.from)??null,...A.resolution==="resolved-project"&&A.target?{to:A.target,...q?{toLayer:q}:{}}:{},line:A.line,kind:A.kind,typeOnly:A.typeOnly,...A.targetTypeOnlyExports?{targetTypeOnlyExports:A.targetTypeOnlyExports}:{},...A.sourcePureTypeModule?{sourcePureTypeModule:A.sourcePureTypeModule}:{},...A.namedBindingsTypeOnly?{namedBindingsTypeOnly:A.namedBindingsTypeOnly}:{},...A.portProofEligible?{portProofEligible:A.portProofEligible}:{}}}),f=Ye({config:e.contract.config,rules:e.contract.config.rules,files:a.map(A=>A.path)}),g=vs(e,t),h=e.contract.arkRules??ie(),l=a.map(A=>A.path),p={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?St(e.coverageInputs.fileContents):{},...e.fileHints??{}},y=[...Et({arkRules:h,classShapes:e.contract.classShapes??t.classShapes??[],files:l,layerForFile:A=>o.get(A)??J(A,e.contract.config.layers),fileHints:p}),...Ct(h,l)],b=y.filter(A=>A.failsStrict).map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,arkruleId:A.arkruleId,arkruleSource:A.arkruleSource,nextAction:A.ruleId==="ARKRULE_SCOPE_EMPTY"?`Fix appliesTo globs for ${A.arkruleId} in ${A.arkruleSource} so they match governed files, or remove the rule.`:`Fix the structure or invariant for ${A.arkruleId} (declared in ${A.arkruleSource}), then preflight again.`})),I=y.filter(A=>!A.failsStrict).map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,arkruleId:A.arkruleId,arkruleSource:A.arkruleSource,failsStrict:!1,nextAction:A.ruleId==="ARKRULE_SCOPE_EMPTY"?`Review appliesTo for ${A.arkruleId} in ${A.arkruleSource} (zero-match scope; advisory).`:`Review ArkRule ${A.arkruleId} in ${A.arkruleSource} (advisory).`})),m=(h.invariants?.length??0)>0?ft({arkRules:h,fileContents:e.coverageInputs?.fileContents??{},testFiles:e.coverageInputs?.testFiles??[],testGlobsMissing:e.coverageInputs?.testGlobsMissing===!0||e.coverageInputs===void 0||(e.coverageInputs.testFiles?.length??0)===0}):{coverage:[],violations:[],partial:!1},R=m.violations.filter(A=>A.failsStrict).map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,arkruleId:A.arkruleId,arkruleSource:A.arkruleSource,nextAction:`Add a test title or declared symbol covering ${A.arkruleId} (declared in ${A.arkruleSource}), then preflight again.`})),S=m.violations.filter(A=>!A.failsStrict).map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,arkruleId:A.arkruleId,arkruleSource:A.arkruleSource,failsStrict:!1,nextAction:`Cover invariant ${A.arkruleId} in ${A.arkruleSource} (advisory / partial).`})),L=m.partial&&m.coverage.some(A=>A.mode==="enforced"&&A.partial)?[{code:"INVARIANT_COVERAGE_PARTIAL",message:"Enforced ArkRules invariant coverage cannot be fully proven (missing test globs or empty test set); reporting partial, never covered."}]:[],v=ye({config:e.contract.config,rules:e.contract.config.rules,files:a.filter(A=>A.layer).map(A=>A.path),contentViolations:[...Cs(e,t,o),...b,...R],edges:d,warnings:[...f,...g.warnings,...I,...S],safety:g.report}),w=s==="complete"&&L.length>0?"partial":s,N=w==="complete"?i:[...i,...L].sort((A,q)=>{let ke=`${A.code}\0${A.file??""}\0${A.message}`,xe=`${q.code}\0${q.file??""}\0${q.message}`;return ke<xe?-1:ke>xe?1:0}),F=v.violations.filter(A=>A.failsStrict!==!1),B=w==="complete"&&F.length===0,We=B&&v.warnings.every(A=>A.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:w,completenessReasons:N,valid:B,strictValid:We,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:g.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:a,layers:e.contract.config.layers.map(A=>A.name),edges:d,capabilityUses:t.capabilityUses,violations:v.violations,warnings:v.warnings}}}function Se(e){return Ss({contract:e.contract,facts:ee(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints})}function kt(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return e.typeOnly||e.targetTypeOnlyExports||e.namedBindingsTypeOnly?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":e.peerIsolation?"Extract the shared dependency to a shared layer, then preflight again.":`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, then preflight again.`;case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, then preflight again.`;case"CAPABILITY_VIOLATION":return`Define a ${String(e.capability??"capability")} port in ${e.fromLayer??"the walled layer"}, bind the implementation outside it, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";case"ARKRULE_STRUCTURE":case"ARKRULE_INVARIANT":case"INVARIANT_UNCOVERED":return`Fix the structure or invariant for ${typeof e.arkruleId=="string"&&e.arkruleId.length>0?e.arkruleId:"the ArkRule"} (declared in ${typeof e.arkruleSource=="string"&&e.arkruleSource.length>0?e.arkruleSource:"arkrules/<Layer>.json"}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`;default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}function Kn(e){return P(k(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}function en(e){let t=Ee(e),n=new Map(t.ir.files.map(p=>[p.path,p])),r=[],s=new Set,i=[];for(let p of e.changes){let y=p.path.replace(/\\/g,"/"),b=fe(p.path);if(!b||b===".."||b.startsWith("../")||y.startsWith("/")||/^[A-Za-z]:\//.test(y)||y.includes("\0")){i.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(s.has(b)){i.push({ruleId:"DUPLICATE_CHANGE_PATH",file:b,line:1,message:`The atomic change set contains more than one operation for ${b}.`});continue}s.add(b),"delete"in p&&p.delete&&!n.has(b)&&i.push({ruleId:"DELETE_TARGET_MISSING",file:b,line:1,message:`Cannot delete ${b} because it is not present in the supplied base tree.`}),r.push("delete"in p&&p.delete?{path:b,delete:!0}:{path:b,content:"content"in p?p.content:""})}e.changes.length===0&&i.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let a=ze({...e,changes:r}),o=new Map(a.ir.files.map(p=>[p.path,p])),d=a.ir.violations.filter(p=>p.ruleId==="CAPABILITY_VIOLATION"||p.ruleId==="FORBIDDEN_GLOBAL").map(p=>{let y=o.get(p.evidence.file)?.layer;return{ruleId:p.ruleId,file:p.evidence.file,line:p.evidence.line,target:p.symbol,...p.capability?{capability:p.capability}:{},...y?{fromLayer:y}:{},edgeKind:"import",message:p.message}}),f=ye({config:e.contract.config,rules:e.contract.config.rules,files:a.ir.files.map(p=>p.path),contentViolations:d,edges:a.ir.edges.filter(p=>!!p.fromLayer).map(p=>({from:p.from,fromLayer:p.fromLayer,...p.to?{to:p.to}:{},...p.toLayer?{toLayer:p.toLayer}:{},line:p.evidence.line,kind:"import",...p.typeOnly?{typeOnly:!0}:{},...p.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),g=r.map(p=>{let y=fe(p.path),b=n.get(y),I=o.get(y);return{path:y,operation:"delete"in p&&p.delete?"delete":b?"update":"create",...b?{beforeContentHash:b.contentHash}:{},...I?{candidateContentHash:I.contentHash}:{}}}).sort((p,y)=>p.path.localeCompare(y.path)),h=[...i,...f.violations].map(p=>({...p,nextAction:kt(p)})),l=h.filter(p=>p.failsStrict!==!1),c=e.changeMap?de({changeMap:e.changeMap,changes:g,baseDependencies:t.ir.edges.flatMap(p=>p.to?[{from:p.from,to:p.to}]:[]),candidateDependencies:a.ir.edges.flatMap(p=>p.to?[{from:p.from,to:p.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&a.valid&&l.length===0&&(c?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:a.ir.compilerOptionsHash,baseTreeHash:Kn(t.ir.files),candidateTreeHash:Kn(a.ir.files),baseCompleteness:t.completeness,candidateCompleteness:a.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:a.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...c?{convergence:c}:{},changes:g,violations:h,warnings:f.warnings}}function ks(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let s of t.split("/"))if(!(!s||s==="."))if(s===".."){if(n.length===0)return;n.pop()}else n.push(s);let r=n.join("/");return r&&r===t?r:void 0}function xs(e,t){return[["resolverIdentity",e.resolverIdentity,t.resolverIdentity],["compilerIdentity",e.compilerIdentity,t.compilerIdentity],["evidenceRequirementsHash",e.evidenceRequirementsHash,t.evidenceRequirementsHash],["projectPackageName",e.projectPackageName??"",t.projectPackageName??""]].filter(([,r,s])=>r!==s).map(([r,s,i])=>({ruleId:"FACTS_IDENTITY_MISMATCH",file:"<change-set>",line:1,field:r,before:s,candidate:i,message:`Base and candidate facts must use the same ${r}.`}))}function Os(e,t,n,r){let s=n.get(t),i=r.get(t);return{path:t,operation:"delete"in e&&e.delete?"delete":s?"update":"create",...s?{beforeContentHash:s.contentHash}:{},...i?{candidateContentHash:i.contentHash}:{}}}function tn(e){let t=ee(e.baseFacts),n=ee(e.candidateFacts),r=Se({contract:e.contract,facts:t}),s=Se({contract:e.contract,facts:n}),i=new Map(t.files.map(c=>[c.path,c])),a=new Map(n.files.map(c=>[c.path,c])),o=xs(t,n),d=new Map,f=[];for(let c of e.changes){let p=ks(c.path);if(!p){o.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(d.has(p)){o.push({ruleId:"DUPLICATE_CHANGE_PATH",file:p,line:1,message:`The atomic change set contains more than one operation for ${p}.`});continue}d.set(p,c);let y=i.get(p),b=a.get(p);if("delete"in c&&c.delete)y||o.push({ruleId:"DELETE_TARGET_MISSING",file:p,line:1,message:`Cannot delete ${p} because it is not present in the supplied base facts.`}),b&&o.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:p,line:1,message:`Candidate facts still contain deleted file ${p}.`});else{let I="content"in c?c.content:"",u=P(I);b?b.contentHash!==u&&o.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:p,line:1,expectedContentHash:u,candidateContentHash:b.contentHash,message:`Candidate facts for ${p} do not match the declared content.`}):o.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:p,line:1,message:`Candidate facts do not contain changed file ${p}.`})}f.push(Os(c,p,i,a))}e.changes.length===0&&o.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});for(let c of new Set([...i.keys(),...a.keys()])){if(d.has(c))continue;let p=i.get(c),y=a.get(c);p&&y&&k(p)===k(y)||o.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:c,line:1,message:`Candidate facts change ${c}, but the atomic change set does not declare it.`})}let g=e.changeMap?de({changeMap:e.changeMap,changes:f,baseDependencies:r.ir.edges.flatMap(c=>c.to?[{from:c.from,to:c.to}]:[]),candidateDependencies:s.ir.edges.flatMap(c=>c.to?[{from:c.from,to:c.to}]:[])}):void 0,h=[...o,...s.ir.violations].map(c=>({...c,nextAction:kt(c)})),l=h.filter(c=>c.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&s.strictValid&&l.length===0&&(g?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,resolverIdentity:n.resolverIdentity,compilerIdentity:n.compilerIdentity,compilerOptionsHash:n.compilerOptionsHash,tsconfigHash:n.tsconfigHash,baseCompilerOptionsHash:t.compilerOptionsHash,candidateCompilerOptionsHash:n.compilerOptionsHash,baseTsconfigHash:t.tsconfigHash,candidateTsconfigHash:n.tsconfigHash,evidenceRequirementsHash:n.evidenceRequirementsHash,baseFactsHash:t.factsHash,candidateFactsHash:n.factsHash,baseTreeHash:t.candidateTreeHash,candidateTreeHash:n.candidateTreeHash,baseCompleteness:r.completeness,candidateCompleteness:s.completeness,baseCompletenessReasons:r.completenessReasons,candidateCompletenessReasons:s.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...g?{convergence:g}:{},changes:f.sort((c,p)=>c.path<p.path?-1:c.path>p.path?1:0),violations:h,warnings:s.ir.warnings}}function xt(e,t){return e.slice(0,t).split(`
16
+ `).length}function Yn(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function Jn(e,t){return e.some(n=>{let r=n.trim().replace(/\.+$/,"");return t.some(s=>r===s||r.startsWith(`${s}.`))})}function Wn(e,t=[]){return/domain|entity|aggregate|model/i.test(e)||Jn(t,["Domain"])}function Ts(e,t=[]){return/application|orchestration|presentation|adapter|framework|interface|delivery|transport|inbound|controller/i.test(e)||Jn(t,["Application","Orchestration","Presentation","Adapter","Interface","Delivery","Transport"])}function Ps(e){return/(?:^|\/)(?:tests?|__tests__|fixtures?|testdata|mocks?|stubs?|examples?|samples?|seeds?|seeders?|migrations?|excluded|exclusions?)(?:\/|$)/i.test(e)||/(?:^|\/)[^/]*\.(?:test|spec|fixture|mock|stub|seed|seeder)\.[^/]+$/i.test(e)||/(?:^|\/)(?:seed|seeder|fixture|mock|stub)\.[^/]+$/i.test(e)}function Zn(e){let t=[],n=0,r=new Map(Object.entries(e.fileLayers??{}).map(([d,f])=>[Yn(d),f])),s=new Map((e.layerContexts??[]).map(d=>[d.name,d.intentPrefixes??[]])),i=(e.layerContexts??[]).find(d=>Wn(d.name,d.intentPrefixes))?.name??"DomainModel";for(let[d,f]of Object.entries(e.fileContents).sort(([g],[h])=>g.localeCompare(h))){let g=Yn(d);if(Ps(g)||/GENERATED FILE\s+[—-]\s+do not edit by hand/i.test(f.slice(0,320)))continue;let h=r.has(g),l=r.get(g),c=l?s.get(l)??[]:[],p=/(?:^|\/)(?:components|ui|layouts|styles|hooks|theme|tokens|i18n|locales?)(?:\/|$)/i.test(g)||/(?:^|\/)(?:src\/)?(?:app|pages)\/.+\.(?:tsx|jsx)$/i.test(g)&&/(?:page|layout|loading|error|template|default)\.(?:tsx|jsx)$/i.test(g),y=/(?:^|\/)(?:app|pages)(?:\/[^/]+)*\/api(?:\/|$)/i.test(g),b=/(?:^|\/)actions?(?:\/|\.|$)/i.test(g)||/['"]use server['"]/.test(f),I=/controller|handler|resolver/i.test(d)||y||b||/route\.(?:ts|js|tsx|jsx)$/i.test(g)&&!p||/@(Controller|Get|Post|Put|Delete|Patch)\b/.test(f)||/\bexport\s+(?:async\s+)?function\s+(?:GET|POST|PUT|DELETE|PATCH)\b/.test(f)||/\bexport\s+const\s+(?:GET|POST|PUT|DELETE|PATCH)\s*=/.test(f),u=h?!!(l&&Ts(l,c)&&I):I,m=h?!!(l&&Wn(l,c)):/domain|entity|aggregate|model/i.test(d),R=!h||m||u;if(u&&!p){let v=/\b(if\s*\([^)]{0,80}(amount|total|price|qty|quantity|balance)[^)]{0,40}\)|throw new (Error|BadRequest|ValidationError)|z\.object\(|yup\.|class-validator|@Is[A-Z])/g,w;for(;(w=v.exec(f))!==null;)n+=1,t.push({id:`inv-val-${n}`,kind:"validation-in-controller",file:d,line:xt(f,w.index),message:"Business validation appears in a controller/handler \u2014 extract an invariant or Domain rule.",confidence:"direct-evidence",governedLayer:l,suggestedArkRule:{layer:i,invariantId:`INV-EXTRACT-${n}`,sensor:"invariant-coverage"},neverMechanicalSafe:!0})}let S=/\b(const|let)\s+([A-Z][A-Z0-9_]{2,})\s*=\s*(\d{2,}|['"][^'"]{8,}['"])/g,T,L=v=>/^(?:TEST|SPEC|TIMEOUT|PORT|VERSION|MAX_RETRY|MIN_RETRY|TTL|CACHE|HEADER|COOKIE|MIME|CONTENT_TYPE|HTTP_STATUS|NODE_ENV|LOG_LEVEL|FEATURE_FLAG|ID_PREFIX|Z_INDEX)(?:_|$)/i.test(v)||/^(?:ROUTE|PATH|LABEL|TITLE|HEADING|CLASS|STYLE|COLOR|THEME|BREAKPOINT|QUERY|PARAM|ICON|ARIA|MSG|COPY|I18N|LOCALE|PAGE|NAV|MENU|TAB|BTN|BUTTON|PLACEHOLDER|TOOLTIP|SHADOW|RADIUS|GAP|PADDING|MARGIN|FONT|WIDTH|HEIGHT|OPACITY|DURATION|EASE|ANIM)_/i.test(v)||/_(?:ROUTE|PATH|LABEL|TITLE|COLOR|THEME|CLASS|STYLE|ICON|ARIA|MSG|COPY|TIMEOUT|PORT|VERSION|RETRY|DELAY|INTERVAL|TTL|CACHE)$/i.test(v)||/_(?:TIMEOUT(?:_MS)?|MS|BYTES|BUCKET|STORAGE_KEY|WINDOW_MS)$/i.test(v)||/^(?:DEFAULT_(?:BASE_URL|TIMEOUT(?:_MS)?|RETRY|PORT|HOST|HEADERS?|CACHE|TTL|MS|LOCALE|LANG|TIMEZONE|TZ)|REQUEST_(?:TIMEOUT(?:_MS)?|HEADERS?|RETRY|ID_PREFIX)|STORAGE_(?:KEY|PREFIX|BUCKET)|DAY_MS$|APP_DOMAIN$|BASE_URL$)$/i.test(v)||/^(?:FAVORITES_STORAGE|LISTINGS_CACHE|DOCS_PATH|METRICS_INTERVAL)/i.test(v)||/^(?:DEV|DEMO|SEED|FIXTURE)_[A-Z0-9_]+$/i.test(v)||/^(?:PG|POSTGRES|OID)_[A-Z0-9_]+$/i.test(v)||/_(?:OID|OIDS)$/i.test(v)||/^(?:INT2|INT4|INT8|FLOAT4|FLOAT8|NUMERIC|DATE|TIME|TIMESTAMP|TIMESTAMPTZ|JSON|JSONB|UUID)OID$/i.test(v)||/(?:^|_)(?:SCHEMA|PROTOCOL|RESOLVER|FORMAT)_(?:URL|URI|VERSION|ID|IDENTITY)$/i.test(v);for(;(T=S.exec(f))!==null;){let v=T[2];!R||L(v)||p&&!m||/(?:^|\/)(?:integrations?|repos?|clients?|infra(?:structure)?|adapters?)(?:\/|$)/i.test(g)&&!m||(n+=1,t.push({id:`inv-magic-${n}`,kind:"magic-business-constant",file:d,line:xt(f,T.index),message:`Magic business constant ${v} may belong in a Domain policy or invariant catalog.`,confidence:"heuristic",governedLayer:l,suggestedArkRule:{layer:i,invariantId:`INV-${v}`},neverMechanicalSafe:!0}))}if(m){let v=/export\s+class\s+([A-Za-z_][A-Za-z0-9_]*)\s*\{([^}]{0,800})\}/g,w;for(;(w=v.exec(f))!==null;){let N=w[2]??"",F=(N.match(/\b[a-zA-Z_][a-zA-Z0-9_]*\s*\(/g)??[]).length;(N.match(/:\s*[A-Za-z]/g)??[]).length>=2&&F<=1&&(n+=1,t.push({id:`inv-anemic-${n}`,kind:"anemic-entity",file:d,line:xt(f,w.index),message:`Class ${w[1]} looks anemic (data-heavy, few behaviors).`,confidence:"heuristic",governedLayer:l,suggestedArkRule:{layer:i,structureId:"no-anemic-model",sensor:"no-anemic-model"},neverMechanicalSafe:!0}))}}if(m&&!(/\.error\.(?:ts|js|tsx|jsx)$/i.test(g)||/(?:^|\/)[^/]*(?:-access)?\.error\./i.test(g)||/(?:^|\/)errors?(?:\/|$)/i.test(g))){let w=/this\.\w+\s*=/g,N;for(;(N=w.exec(f))!==null;){let F=f.lastIndexOf("class ",N.index),B=F>=0?f.indexOf("{",F):-1,We=F>=0&&B>=F&&B<N.index?f.slice(F,B):"";if(/\bextends\s+(?:Error|[A-Za-z_$][A-Za-z0-9_$]*Error)\b/.test(We))continue;let A=f.slice(Math.max(0,N.index-200),N.index+200);if(!/\b(ensureInvariants|assertInvariants|validate|publish|emit)\b/.test(A)){n+=1,t.push({id:`inv-mut-${n}`,kind:"mutation-without-guard",file:d,line:xt(f,N.index),message:"Domain field mutation without nearby guard/publish call.",confidence:"heuristic",governedLayer:l,suggestedArkRule:{layer:i,structureId:"events-on-mutation",sensor:"domain-event-on-mutation"},neverMechanicalSafe:!0});break}}}}let a=new Set(e.contractedRuleIds??[]);t.sort((d,f)=>+(f.confidence==="direct-evidence")-+(d.confidence==="direct-evidence")||d.file.localeCompare(f.file)||d.line-f.line||d.kind.localeCompare(f.kind)||d.id.localeCompare(f.id));let o=t.filter(d=>d.suggestedArkRule?.invariantId&&a.has(d.suggestedArkRule.invariantId)||d.suggestedArkRule?.structureId&&a.has(d.suggestedArkRule.structureId)).length;return{candidates:t,inventoried:t.length,underContract:o,frozen:(e.frozenKeys??[]).length,notAScore:!0}}function Xn(e){return{pilot:`Extract rule candidate ${e.id} (${e.kind})`,pilotTarget:e.file,smellId:e.kind,move:`Declare in arkrules/${e.suggestedArkRule?.layer??"DomainModel"}.json, implement pure Domain logic, add covering test.`,doNot:["Do not auto-apply codemods","Do not promote to enforced without coverage evidence","Do not batch multiple extractions"],successSignal:"Doctor reports candidate under contract; gate green with residual honest.",killSwitch:"Stop if extraction requires multi-module redesign without a clear aggregate owner.",neverMechanicalSafe:!0,class:"judgment",next:"Run ark_prepare_change / preflight, then re-doctor."}}var Qn="1.1";var er="1.0";0&&(module.exports={ANALYSIS_IR_SCHEMA_VERSION,ARK_ANALYSIS_RESULT_SCHEMA,ARK_ANALYSIS_RESULT_SCHEMA_VERSION,ARK_CONFIG_SCHEMA,ARK_CONFIG_SCHEMA_VERSION,ARK_DESIGN_DELTA_SCHEMA_VERSION,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION,ARK_PROJECT_IDENTITY_SCHEMA,ARK_PROJECT_IDENTITY_SCHEMA_URL,ARK_PROJECT_IDENTITY_SCHEMA_VERSION,ARK_RULES_SCHEMA,ARK_RULES_SCHEMA_VERSION,ARK_RULE_SENSORS,EffectiveContractError,POLICY_DELTA_SCHEMA_VERSION,PROJECT_BINDING_SCHEMA,PROJECT_EXPECTATION_SCHEMA,RESOLVED_CANDIDATE_FACTS_SCHEMA,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,analyzeArchitectureConvergence,analyzeChange,analyzePolicyDelta,analyzeProject,analyzeResolvedProject,buildArkRuleFileHints,buildEffectiveArkRules,buildRulesInventory,canPromoteInvariant,classifyArkPolicyDelta,collectAnalysisConfigWarnings,collectEmptyAppliesToFindings,collectForbiddenCapabilityUses,createAICodeGate,createAdapterResult,createArchitectureProfile,createArchitectureProfileFromArkConfig,createElevenLayerArkConfig,createProjectId,createProjectIdentity,createResolvedCandidateFacts,deriveArkRuleFileHints,detectArchitectureCycles,deterministicHash,effectiveContractPolicyPayload,elevenLayerProfile,emptyEffectiveArkRules,evaluateArchitectureGraph,evaluateArkRuleSensors,evaluateInvariantCoverage,explainViolation,extractClassShapesFromSource,extractSemanticDependencies,inventoryToExtractionCard,loadArkConfigContract,loadArkRulesContract,loadContract,loadResolvedCandidateFacts,parseArkConfigJson,parseArkRulesJson,policyDeltaAcknowledgementMatches,preflightChange,preflightResolvedChange,resolveEffectiveContract,resolvedFactsEvidenceRequirementsHash,stableSerialize,toAdapterDiagnostic,version});