arkgate 4.8.9 → 4.8.10

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 (44) hide show
  1. package/CHANGELOG.md +80 -3
  2. package/README.md +4 -4
  3. package/bin/ark-check-runtime.mjs +2 -2
  4. package/bin/ark.mjs +18 -10
  5. package/bin/lib/analysis-engine.mjs +6 -6
  6. package/bin/lib/architecture-scan.mjs +91 -4
  7. package/bin/lib/ark-order-facts.mjs +11 -4
  8. package/bin/lib/arkrule-file-hints.mjs +255 -20
  9. package/bin/lib/arkrules-sensors.mjs +364 -68
  10. package/bin/lib/baseline-key.mjs +45 -1
  11. package/bin/lib/config-contract.mjs +9 -3
  12. package/bin/lib/diagnostic-catalog.mjs +1 -0
  13. package/bin/lib/doctor-human.mjs +3 -3
  14. package/bin/lib/doctor-next-actions.mjs +3 -1
  15. package/bin/lib/field-install.mjs +23 -2
  16. package/bin/lib/first-run-help.mjs +69 -5
  17. package/bin/lib/resolved-candidate-facts.mjs +82 -1
  18. package/bin/lib/rules-inventory.mjs +7 -3
  19. package/bin/lib/upstream-report.mjs +330 -0
  20. package/bin/lib/violations.mjs +51 -15
  21. package/dist/{diagnosticCatalog-BrkOiwCk.d.ts → diagnosticCatalog-biferT4R.d.ts} +9 -3
  22. package/dist/eslint/index.cjs +4 -7
  23. package/dist/eslint/index.js +4 -7
  24. package/dist/index.cjs +28 -31
  25. package/dist/index.d.ts +7 -4
  26. package/dist/index.js +28 -31
  27. package/dist/nestjs/index.cjs +1 -1
  28. package/dist/nestjs/index.js +1 -1
  29. package/dist/runtime/index.cjs +11 -11
  30. package/dist/runtime/index.d.ts +1 -1
  31. package/dist/runtime/index.js +11 -11
  32. package/docs/README.md +3 -3
  33. package/docs/agent-guide.md +25 -1
  34. package/docs/ai-gates.md +8 -0
  35. package/docs/brownfield-adoption.md +30 -0
  36. package/docs/configuration.md +14 -1
  37. package/docs/diagnostics.md +10 -0
  38. package/docs/package-surface.md +4 -3
  39. package/docs/use.md +11 -0
  40. package/package.json +1 -1
  41. package/schemas/ark.config.schema.json +3 -2
  42. package/server.json +2 -2
  43. package/templates/agent-skills/ark-explore/SKILL.md +22 -1
  44. package/templates/skills/ark-explore.md +22 -1
package/dist/index.js CHANGED
@@ -1,51 +1,48 @@
1
- var Oo=Object.defineProperty;var i=(e,t)=>Oo(e,"name",{value:t,configurable:!0});var _o="4.8.9";var xo=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,To=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,No=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function Lo(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),s=String(t?.toLayer??"");return xo.test(n)?"pure-shared":r==="PersistenceAdapters"&&(To.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${s} ${n}`))?"kernel-emit":No.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&s==="PersistenceAdapters"?"use-case":"unknown"}i(Lo,"classifyLayerImportKind");function Po(e){if(e.typeOnly||e.targetTypeOnlyExports||e.namedBindingsTypeOnly)return"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.";if(e.peerIsolation)return"Extract the shared dependency to a shared layer, test at the public interface, then preflight again.";let t=Lo(typeof e.target=="string"?e.target:"",{fromLayer:typeof e.fromLayer=="string"?e.fromLayer:void 0,toLayer:typeof e.toLayer=="string"?e.toLayer:void 0});return t==="pure-shared"?"Adopt the imported constants/types/pure module into DomainModel or SharedKernel (do not inject a port). Then preflight again.":t==="kernel-emit"?"Persistence must not emit. Inject a port or move the event map to SharedTypes; do not import kernel/events/bootstrap from a repository. Then preflight again.":t==="use-case"||e.portProofEligible?`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, test at the public interface, then preflight again.`:"Classify the import: if it is constants/types/pure, adopt into DomainModel or SharedKernel; define a port only if the target is a real use-case. Then preflight again."}i(Po,"layerImportNextAction");function wo(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}i(wo,"arkRunCallSiteName");function Do(e){let t=wo(e),n=typeof e.fromLayer=="string"&&e.fromLayer.length>0?e.fromLayer:void 0;switch(e.ruleId){case"ARKRUN_MISSING_ROOT":return t?`Import createStrictArkKernel from arkgate/runtime and call it in composition root ${t} listed in arkRun.compositionRoots, then preflight again.`:"Import createStrictArkKernel from arkgate/runtime (same npm package; @arkgate/runtime is deprecated) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKRUN_KERNEL_IN_DOMAIN":return t?`Move the kernel import of ${t} out of ${n??"the Domain-role layer"} into a composition root or adapter. Import from arkgate/runtime, then preflight again.`:"Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from arkgate/runtime (same npm package; @arkgate/runtime is deprecated), then preflight again. Never mechanical-safe.";case"ARKRUN_DIRECT_NEW":return t?`Resolve ${t} from the kernel instead of constructing it with new, then preflight again.`:"Resolve the type from the kernel instead of constructing it with new, then preflight again. Never mechanical-safe \u2014 rewiring construction is a design decision.";case"ARKRUN_UNDECLARED_EMIT":return t?`Add ${t} to raises or sends on the managed component, then preflight again.`:"Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment.";case"ARKRUN_UNDECLARED_HANDLE":return t?`Add ${t} to reactsTo on the managed component, then preflight again.`:"Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment.";case"ARKRUN_UNDECLARED_DEPEND":return t?`Add ${t} to uses on the managed component, then preflight again.`:"Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment.";case"ARKRUN_TRANSPORT_BYPASS":return t?`Send through the ArkRun kernel transport instead of importing ${t}, then preflight again.`:"Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe \u2014 homemade buses stay judgment.";default:return`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(Do,"arkRunNextAction");function fe(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return Po(e);case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, test at the public interface, then preflight again.`;case"CAPABILITY_VIOLATION":return`Define a ${String(e.capability??"capability")} port in ${e.fromLayer??"the walled layer"}, bind the implementation outside it, test at the public interface, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, test at the public interface, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"LITERAL_PATH_DRIFT":return typeof e.target=="string"&&e.target.length>0?`Rewrite the literal to ${e.target}, or run \`arkgate-check --path-drift --base-ref <ref> --write\` to apply every anchored replacement.`:"Rewrite the literal to the rename destination, or run `arkgate-check --path-drift --base-ref <ref> --write` to apply every anchored replacement.";case"LITERAL_PATH_UNRESOLVED":return"Read the candidate and decide: fix the path, or leave it. Advisory \u2014 with no rename to anchor it there is no destination to propose, so --write never touches it.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";case"INVARIANT_COVERAGE_OUTSIDE_ROOTS":return"Move the covering test under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json, then run Ark again.";case"ARKRULE_STRUCTURE":case"ARKRULE_INVARIANT":case"INVARIANT_UNCOVERED":return`Fix the structure or invariant for ${typeof e.arkruleId=="string"&&e.arkruleId.length>0?e.arkruleId:"the ArkRule"} (declared in ${typeof e.arkruleSource=="string"&&e.arkruleSource.length>0?e.arkruleSource:"arkrules/<Layer>.json"}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`;case"ARKRUN_MISSING_ROOT":case"ARKRUN_KERNEL_IN_DOMAIN":case"ARKRUN_DIRECT_NEW":case"ARKRUN_UNDECLARED_EMIT":case"ARKRUN_UNDECLARED_HANDLE":case"ARKRUN_UNDECLARED_DEPEND":case"ARKRUN_TRANSPORT_BYPASS":return Do(e);case"ARKORDER_MISSING_PLANE":return typeof e.target=="string"&&e.target.length>0?`Import createOrderPlane from arkgate/order and call it in plane root ${e.target} listed in arkOrder.planeRoots, then preflight again.`:"Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKORDER_KERNEL_IN_DOMAIN":return"Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe.";case"ARKORDER_GENERIC_UPDATE":return"Use release() for the first freeze of \u03BE. Later pattern change is proposeRelease then apply(ProposeResult). Never update/patch/set. Never mechanical-safe.";case"ARKORDER_TOO_MANY_PARAMS":return"Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe.";case"ARKORDER_INGEST_WRITES_XI":return"Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe.";case"ARKORDER_XI_FIELD_WRITE":return typeof e.target=="string"&&e.target.length>0?`Do not persist slow key ${e.target} from a use-case. Absorb the field with ingest() or change the pattern with proposeRelease then apply, then preflight again.`:"Do not persist a declared slow key from a use-case. Absorb the field with ingest() or change the pattern with proposeRelease then apply, then preflight again. Never mechanical-safe.";case"ARKORDER_UNVALVED_RELEASE":return"Change \u03BE with proposeRelease then apply(ProposeResult). release() is only the first freeze. Never mechanical-safe.";default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(fe,"deterministicNextAction");var sn="1.5",Er="docs/diagnostics.md";function O(e){return typeof e=="string"&&e.length>0?e:void 0}i(O,"text");function kr(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}i(kr,"positiveInteger");function on(e){let t=typeof e.ruleId=="string"?e.ruleId:typeof e.code=="string"?e.code:void 0,n=typeof e.file=="string"?e.file:void 0,r=typeof e.fromLayer=="string"?e.fromLayer:void 0,s=typeof e.toLayer=="string"?e.toLayer:void 0,o=typeof e.target=="string"?e.target:void 0;return[t,n,r??"",s??"",o??""].join("|")}i(on,"adapterFindingTargetKey");function nn(e){let t=new Map;return e.map(n=>{let r=on(n),s=(t.get(r)??0)+1;return t.set(r,s),s===1?r:`${r}#${s}`})}i(nn,"adapterFindingOccurrenceTargetKeys");function Ir(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")}`}i(Ir,"adapterFindingRefFromTargetKey");function vr(e){return`${Er}#${e}`}i(vr,"adapterDocsCodePath");function Mo(e,t,n){return fe({ruleId:e,target:O(t.target)??O(n.target)??void 0,fromLayer:O(t.fromLayer)??void 0,toLayer:O(t.toLayer)??void 0,typeOnly:t.typeOnly===!0,targetTypeOnlyExports:t.targetTypeOnlyExports===!0,namedBindingsTypeOnly:t.namedBindingsTypeOnly===!0,portProofEligible:t.portProofEligible===!0,peerIsolation:t.peerIsolation===!0,sourcePureTypeModule:t.sourcePureTypeModule===!0,edgeKind:O(t.edgeKind)??void 0,capability:O(t.capability)??O(n.capability)??void 0,arkruleId:O(t.arkruleId)??void 0,arkruleSource:O(t.arkruleSource)??void 0})}i(Mo,"nextActionForDiagnostic");function rn(e,t="error",n){let r=O(e.ruleId)??O(e.code)??"ARK_UNKNOWN",s=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,o={...O(e.target)?{target:O(e.target)}:{},...O(e.fromLayer)?{fromLayer:O(e.fromLayer)}:{},...O(e.toLayer)?{toLayer:O(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}:{},...O(e.capability)?{capability:O(e.capability)}:{},...O(e.edgeKind)?{edgeKind:O(e.edgeKind)}:{},...O(e.arkruleId)?{arkruleId:O(e.arkruleId)}:{},...O(e.arkruleSource)?{arkruleSource:O(e.arkruleSource)}:{}},a=n??on(e),l=Ir(a);return{ruleId:r,severity:s,message:O(e.message)??r,location:{file:O(e.file)??"<unknown>",line:kr(e.line,1),column:kr(e.column,1)},evidence:o,nextAction:O(e.nextAction)??Mo(r,o,e),findingRef:l,targetKey:a,docsCodePath:vr(r)}}i(rn,"toAdapterDiagnostic");function Fo(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(y=>({code:O(y.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:O(y.message)??`Analysis ${t}: required evidence is incomplete.`,...O(y.file)?{file:O(y.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],s={...O(e.policyHash)?{policyHash:O(e.policyHash)}:{},...O(e.resolverIdentity)?{resolverIdentity:O(e.resolverIdentity)}:{},...O(e.factsHash)?{factsHash:O(e.factsHash)}:{},...O(e.candidateTreeHash)?{candidateTreeHash:O(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let y of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!s[y])throw new Error(`${y} is required for resolved ${t} adapter evidence.`)}let o=e.violations??[],a=e.warnings??[],l=nn(o),c=nn(a),u=[...o.map((y,g)=>rn(y,"error",l[g])),...a.map((y,g)=>rn(y,"warning",c[g]))],m={schemaVersion:sn,completenessReasons:r,diagnostics:u};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...m,mode:n,valid:!1,completeness:t,...s};let y={policyHash:s.policyHash,resolverIdentity:s.resolverIdentity,factsHash:s.factsHash,candidateTreeHash:s.candidateTreeHash};return t==="complete"?{...m,mode:n,valid:e.valid,completeness:t,...y}:{...m,mode:n,valid:!1,completeness:t,...y}}return t==="complete"?{...m,mode:n,valid:e.valid,completeness:t,...s}:{...m,mode:n,valid:!1,completeness:t,...s}}i(Fo,"createAdapterResult");var $o={$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:sn},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},findingRef:{type:"string",minLength:1,pattern:"^fnv1a-[0-9a-f]{8}$"},targetKey:{type:"string",minLength:1},docsCodePath:{type:"string",minLength:1}}}}}};var Ho="1.0",Sr="https://unpkg.com/arkgate@4/schemas/ark.project-identity.schema.json",kt="^sha256:[a-f0-9]{64}$",br={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:kt,description:"Project id previously returned by ark_identity or ark_manifest."}}},Cr={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:kt},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},jo={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Sr,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:kt},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{type:"string",minLength:1},arkgateVersion:{type:"string",minLength:1},contractHash:{type:"string",pattern:kt},contractSource:{enum:["project","default-profile","manifest"]},runtimeId:{type:"string",minLength:1},processStartedAt:{type:"string",format:"date-time"}},$defs:{expectation:br,binding:Cr}};function Vo(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}`}i(Vo,"createProjectId");function Uo(e){return{schemaVersion:"1.0",...e}}i(Uo,"createProjectIdentity");var ln=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),dn=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),un=Object.freeze(Object.keys(dn).sort()),an=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"}),cn=Object.freeze({process:Object.freeze(["process","node:process"])});function Je(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=an[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),s=an[r];if(s)return s;let o=e.indexOf("/",n+1);return o<0?null:an[e.slice(0,o)]??null}i(Je,"capabilityForModuleSpecifier");function Ee(e,t){for(let n of t)if(cn[n]?.includes(e))return n;return null}i(Ee,"forbiddenGlobalForModuleSpecifier");function Et(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),s=dn[r];if(s)return s}return null}i(Et,"capabilityForAmbientName");function De(e){if(e?.pure===!0)return[...ln].sort();let n=(e?.capabilities?.deny??[]).filter(r=>ln.includes(r));return[...new Set(n)].sort()}i(De,"effectiveCapabilityDeny");function Xe(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}i(Xe,"ambientCoveredByForbiddenGlobals");function It(e){let t=new Set,n=new Set,r=Object.keys(dn);for(let s of e?.forbiddenGlobals??[]){let o=r.filter(a=>a===s||a.startsWith(`${s}.`));if(o.length===0)n.add(s);else for(let a of o)t.add(`ambient:${a}`);for(let a of cn[s]??[])t.add(`import-exact:${a}`)}for(let s of De(e)){if(t.add(`import:${s}`),s==="process")for(let o of cn.process)t.add(`import-exact:${o}`);for(let o of r)Et(o)===s&&t.add(`ambient:${o}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}i(It,"loweredLayerCoverage");var Or=new Map;function _r(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(_r,"escapeLiteral");function vt(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}i(vt,"normalizeGlobSeparators");function Ko(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}i(Ko,"bracesBalanced");function me(e){let t=Or.get(e);if(t)return t;let n=vt(e),r=Ko(n),s="",o=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(s+=_r(n[l+1]),l+=1):c==="*"?n[l+1]==="*"?n[l+2]==="/"?(s+="(?:.*/)?",l+=2):(s+=".*",l+=1):s+="[^/]*":c==="?"?s+="[^/]":c==="{"&&r?(s+="(?:",o+=1):c==="}"&&r&&o>0?(s+=")",o-=1):c===","&&r&&o>0?s+="|":s+=_r(c)}let a=new RegExp(`^${s}$`);return Or.set(e,a),a}i(me,"globToRegExp");function Go(e){return vt(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}i(Go,"concreteGlobSegments");function pn(e,t){let n=vt(String(e)),r=Go(n),s=n.replace(/\*/g,"").length,o=r.length*1e4+s;if(t==null||t==="")return o;let a=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return s;let l=0,c=-1;for(let u of r){let m=-1;for(let y=l;y<a.length;y+=1)if(a[y]===u){m=y;break}if(m<0)return o;c=m,l=m+1}return(c+1)*1e6+r.length*1e4+s}i(pn,"patternSpecificity");function de(e,t){let n=String(e).split(/[/\\]/).join("/"),r,s=-1;for(let o of t??[])if(!(o.exclude??[]).some(a=>me(a).test(n))){for(let a of o.patterns??[])if(me(a).test(n)){let l=pn(a,n);l>s&&(s=l,r=o.name)}}return r}i(de,"layerForRelativePath");function xr(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()}`}i(xr,"sliceIdForPath");function Bo(e){let t=new Set;for(let n of e??[]){let s=vt(String(n)).split("/").filter(Boolean);for(let o=0;o<s.length;o+=1){let a=s[o];if((a==="**"||a==="*")&&o>0){let l=s[o-1];l&&!l.includes("*")&&!l.includes("{")&&!l.includes("}")&&t.add(l)}}}return[...t]}i(Bo,"inferSliceFoldersFromPatterns");function zo(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 Bo(r?.patterns)}i(zo,"resolveSliceFolders");function Tr(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}i(Tr,"normalizeSegments");function Pr(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}i(Pr,"trimTrailingSlashes");var qo=["src","app"];function Wo(e){let t=Pr(e.replace(/^[./]+/,""));return t==="*"||t==="**"}i(Wo,"isBlanketRoot");function Nr(e,t){if(!e||!t?.length)return!1;let n=String(e).split(/[/\\]/).join("/"),r=n.toLowerCase(),s=Tr(n);for(let o of t){if(typeof o!="string"||o.length===0||Wo(o))continue;if(o.includes("*")){let c=Pr(o.toLowerCase());if(me(c).test(r)||me(`${c}/**`).test(r))return!0;continue}let a=Tr(o);if(a.length===0)continue;let l=qo.includes(s[0])&&a[0]!==s[0]?[0,1]:[0];for(let c of l){if(c+a.length>s.length)continue;let u=!0;for(let m=0;m<a.length;m+=1)if(s[c+m]!==a[m]){u=!1;break}if(u)return!0}}return!1}i(Nr,"pathUnderSharedRoot");function Lr(e,t){let n=String(e).split(/[/\\]/).filter(Boolean).join("/").toLowerCase();if(!n)return!1;let r=t.toLowerCase();return n===r?!0:!n.includes("/")&&r.endsWith(`/${n}`)}i(Lr,"sliceMatchesDeclaration");function Yo(e,t,n){return!e?.length||!t||!n?!1:e.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&Lr(r.from,t)&&Lr(r.to,n))}i(Yo,"crossSliceEdgeAllowed");function Jo(e){if(!e.fromPath)return{denied:!0,reason:"missing-path"};if(e.folderCount<=0)return{denied:!0,reason:"no-slice-folders"};let t=!!e.fromSlice||e.fromShared===!0;if(!e.toPath)return t?e.fromSlice?{denied:!0,reason:"missing-path"}:{denied:!1}:{denied:!0,reason:"unclassifiable-path"};let n=!!e.toSlice||e.toShared===!0;return!t||!n?{denied:!0,reason:"unclassifiable-path"}:!e.fromSlice||!e.toSlice?{denied:!1}:e.fromSlice===e.toSlice?{denied:!1}:e.crossSliceAllowed?{denied:!1}:{denied:!0,reason:"cross-slice"}}i(Jo,"peerIsolationDecision");function Me(e,t){switch(e){case"cross-slice":return`cross-slice edge ${t.fromSlice??"?"} \u2192 ${t.toSlice??"?"}. Extract the shared code, use events/ports across slices, or declare the edge in the rule's allowedCrossSlice.`;case"unclassifiable-path":{let n=[t.fromSlice?void 0:t.fromPath,t.toSlice?void 0:t.toPath].filter(s=>!!s);return`unclassifiable path${n.length>0?` (${n.join(", ")})`:""} \u2014 ArkGate cannot place it in a slice, so it cannot prove this is not a cross-slice edge. Move it into a slice, or declare its root in the rule's sharedRoots.`}case"no-slice-folders":return"no slice folders \u2014 peerIsolation is on but no slice folder resolves from the rule or the layer patterns. Set sliceFolders on the rule.";default:return"no path evidence for this edge \u2014 peerIsolation needs the importer and importee paths."}}i(Me,"peerIsolationDenyExplanation");function St(e,t,n,r){return be(e,t,n,r)?.rule}i(St,"findDeniedEdgeRule");function be(e,t,n,r){for(let s of e??[])if(!(s.from!==t||s.to!==n)&&s.allowed===!1){if(s.peerIsolation){let o=r?.fromPath,a=r?.toPath,l=zo(s,t,r?.layers),c=o?xr(o,l):void 0,u=a?xr(a,l):void 0,m=Jo({fromPath:o,toPath:a,folderCount:l.length,fromSlice:c,toSlice:u,fromShared:!c&&Nr(o,s.sharedRoots),toShared:!u&&Nr(a,s.sharedRoots),crossSliceAllowed:Yo(s.allowedCrossSlice,c,u)});if(m.denied)return{rule:s,peerIsolationReason:m.reason,fromSlice:c,toSlice:u};continue}if(t!==n)return{rule:s}}}i(be,"findDeniedEdgeDecision");function Fe(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(Fe,"literalText");function Mr(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}i(Mr,"lineOf");function wr(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(o=>o.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))}i(wr,"isTypeOnlyReference");function Fr(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()}i(Fr,"singleFileChecker");function fn(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}i(fn,"symbolAt");function mn(e,t,n,r){let s=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,o;try{o=s?t.getShorthandAssignmentValueSymbol(r.parent):fn(t,r)}catch{o=void 0}return!!o?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}i(mn,"localDeclaration");function $e(e,t){let n,r=[],s=i((a,l,c,u=!1)=>r.push({specifier:c,kind:l,line:Mr(t,a),typeOnly:u,unresolved:c===void 0,node:a}),"add"),o=i(a=>{if(e.isImportDeclaration(a))s(a,"import",Fe(e,a.moduleSpecifier),wr(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)s(a,"export",Fe(e,a.moduleSpecifier),wr(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))s(a,"require",Fe(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let l=a.expression.kind===e.SyntaxKind.ImportKeyword,u=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!mn(e,n??(n=Fr(e,t)),t,a.expression);(l||u)&&s(a,u?"require":"dynamic-import",Fe(e,a.arguments[0]))}e.forEachChild(a,o)},"visit");return o(t),r}i($e,"extractSemanticDependencies");function Xo(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=Fe(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}}i(Xo,"staticAccessPath");function Zo(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}i(Zo,"runtimeIdentifierReference");function Dr(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}}i(Dr,"bestForbiddenMatch");function He(e,t,n){if(n.length===0)return[];let r=new Set(n),s=Fr(e,t),o=new Map,a=new Set;for(let g of t.statements)if(e.isVariableStatement(g))for(let p of g.declarationList.declarations)e.isIdentifier(p.name)&&a.add(p.name.text);let l=i(g=>{let p=Xo(e,g);if(!p)return;let f=fn(s,p.root),A=f?o.get(f):void 0;return A?[...A,...p.segments.slice(1)]:mn(e,s,t,p.root)||a.has(p.root.text)?void 0:p.segments},"resolvePath");for(let g of t.statements)if(e.isVariableStatement(g))for(let p of g.declarationList.declarations){if(!p.initializer||!e.isIdentifier(p.name))continue;let f=l(p.initializer),A=fn(s,p.name);!f||!A||o.set(A,f)}let c=[],u=new Set,m=i((g,p)=>{let f=Mr(t,p),A=`${g}:${p.getStart(t)}`;u.has(A)||(u.add(A),c.push({name:g,line:f,node:p}))},"flag"),y=i(g=>{let p=g.parent&&(e.isPropertyAccessExpression(g.parent)||e.isElementAccessExpression(g.parent))&&g.parent.expression===g;if((e.isPropertyAccessExpression(g)||e.isElementAccessExpression(g))&&!p){let f=l(g),A=f?Dr(r,f):void 0;A&&m(A,g)}else e.isIdentifier(g)&&r.has(g.text)&&Zo(e,g)&&!mn(e,s,t,g)&&m(g.text,g);if(e.isVariableDeclaration(g)&&e.isObjectBindingPattern(g.name)&&g.initializer){let f=l(g.initializer);if(f)for(let A of g.name.elements){if(!e.isIdentifier(A.name))continue;let v=A.propertyName?Fe(e,A.propertyName)??A.propertyName.text:A.name.text,_=Dr(r,[...f,v]);_&&m(_,g.initializer)}}e.forEachChild(g,y)},"visit");return y(t),c}i(He,"collectForbiddenCapabilityUses");function gn(e,t,n){let r=[];for(let s of n?.dependencies??$e(e,t)){if(s.typeOnly||!s.specifier)continue;let o=Je(s.specifier);o&&r.push({capability:o,symbol:s.specifier,line:s.line,source:"import-based"})}for(let s of n?.ambientUses??He(e,t,un)){let o=Et(s.name);o&&r.push({capability:o,symbol:s.name,line:s.line,source:"ambient-global"})}return r.sort((s,o)=>s.line-o.line||s.capability.localeCompare(o.capability)||s.symbol.localeCompare(o.symbol))}i(gn,"collectCapabilityUses");var yn={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."},hn=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 An(e,t){return t.flatMap((r,s)=>(r.prefixes??r.intentPrefixes??[]).map(o=>({layer:r.name,layerIndex:s,prefix:o.endsWith(".")?o:`${o}.`}))).filter(({prefix:r})=>e.startsWith(r)).sort((r,s)=>s.prefix.length-r.prefix.length||r.layerIndex-s.layerIndex)[0]?.layer}i(An,"resolveIntentLayer");function Ce(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}i(Ce,"looksLikeArkIntent");function Ze(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&Ce(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:yn.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:yn.PUBLISH_MISSING_SOURCE}),t}i(Ze,"classifyPublishFacts");function W(e,t,n){return{ruleId:e,code:e,message:t,...n}}i(W,"violation");function je(e,t){return e.slice(0,t).split(`
2
- `).length}i(je,"lineOf");function Qo(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}i(Qo,"extractQuotedStrings");function ea(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 o=s.index+s[0].indexOf(s[1]),a=s[0],l=r.kind==="import"&&/\bimport\s+type\b/.test(a)||r.kind==="export"&&/\bexport\s+type\b/.test(a);t.push({value:s[1],index:o,kind:r.kind,typeOnly:l})}}return t.sort((r,s)=>r.index-s.index)}i(ea,"extractModuleSpecifiers");function ta(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],s=i(o=>{e.isStringLiteralLike(o)&&r.push({value:o.text,index:o.getStart(n)}),e.forEachChild(o,s)},"visit");return s(n),r}i(ta,"extractQuotedStringsAst");function na(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))}i(na,"hasInfrastructureToken");function ra(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}i(ra,"isKnownInfrastructurePackage");function sa(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}i(sa,"layerHasInfrastructureRole");function et(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(et,"tsStringLiteralText");function oa(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}i(oa,"tsPropertyName");function $r(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:oa(e,r.name)===n)}i($r,"tsObjectProperty");function tt(e,t,n){return $r(e,t,n)!==void 0}i(tt,"tsObjectHasProperty");function Qe(e,t,n){let r=$r(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}i(Qe,"tsObjectPropertyValue");function aa(e,t){let n=Qe(e,t,"metadata");return tt(e,n,"source")}i(aa,"tsObjectHasMetadataSource");function Hr(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?Hr(e,t.name):!1:!1}i(Hr,"tsLooksLikeIntentCreatorExpression");function ia(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"}i(ia,"tsIsPublishCall");function la(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=et(e,n);return r!==void 0&&Ce(r)||tt(e,n,"intent")||Hr(e,n)}i(la,"tsIsArkPublishCandidate");function ca(e,t){if(!e.isCallExpression(t))return!1;let[n,r,s]=t.arguments;return aa(e,n)||tt(e,r,"source")||tt(e,s,"source")}i(ca,"tsPublishHasSource");function da(e,t){if(!e.isCallExpression(t))return;let[n,r,s]=t.arguments,o=Qe(e,n,"metadata");return et(e,Qe(e,o,"source"))??et(e,Qe(e,r,"source"))??et(e,Qe(e,s,"source"))}i(da,"tsPublishSourceLiteral");function ua(e,t,n,r){let s=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),o=n,a=o?.filePath,l=o?.layer,c=[],u=i(y=>s.getLineAndCharacterOfPosition(y.getStart(s)).line+1,"lineForNode"),m=i(y=>{if(ia(e,y)){let g=y.arguments[0],p=et(e,g);for(let A of Ze({publishCall:!0,rawIntentName:p,objectHasIntent:tt(e,g,"intent"),arkPublishCandidate:la(e,y),hasSource:ca(e,y)}))c.push(W(A.ruleId,A.message,{line:u(y),filePath:a}));let f=da(e,y);if(r&&l&&f&&Ce(f)){let A=r.resolveLayer(f);A&&A!==l&&c.push(W("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${f}" resolves to ${A}, but the target file is classified as ${l}.`,{line:u(y),filePath:a,target:f,fromLayer:l,toLayer:A}))}}e.forEachChild(y,m)},"visit");return m(s),c}i(ua,"analyzePublishAst");function jr(e={}){let t=new Set((e.intents||[]).map(o=>typeof o=="string"?o:o.name)),n=e.forbiddenPatterns||[],r=new Set(e.infrastructureLayers??[]),s=e.enforceIntentAllowlist??t.size>0;return{validate(o,a){let l=[],c=a,u=c?.filePath,m=c?.layer,y=e.typescript,g=y?y.createSourceFile(u??"generated.ts",o,y.ScriptTarget.Latest,!0):void 0,p=g?$e(e.typescript,g):void 0,f=p?p.filter(R=>R.specifier!==void 0).map(R=>({value:R.specifier,index:R.node.getStart(g),kind:R.kind,typeOnly:R.typeOnly})):ea(o),A=e.typescript?ta(e.typescript,o):Qo(o);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(u))for(let R of p?.filter(({unresolved:I})=>I)??[]){let I=R.kind==="require";l.push(W(I?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${I?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:R.line,filePath:u}))}let v=m!==void 0&&(r.has(m)||sa(m)),_=m!==void 0?` If "${m}" 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 R of n)if(R instanceof RegExp){R.lastIndex=0;let I=R.exec(o);R.lastIndex=0,I&&l.push(W("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${R}`,{line:I.index===void 0?void 0:je(o,I.index),filePath:u,suggestion:"Remove infrastructure imports from domain/application layers."+_}))}else o.includes(R)&&l.push(W("FORBIDDEN_SUBSTRING",`Forbidden substring: ${R}`,{line:je(o,o.indexOf(R)),filePath:u}));for(let R of f){let I=e.resolveImportTarget?.(R.value,u)??(e.resolveImportLayer?{layer:e.resolveImportLayer(R.value,u)}:void 0),b=typeof u=="string"?e.resolveImportTarget?.(u)??(e.resolveImportLayer?{layer:m,relPath:void 0}:void 0):void 0,D=I?.layer;if(D&&m){let k=St(e.architectureProfile?.rules,m,D,{fromPath:b?.relPath,toPath:I?.relPath,layers:e.architectureLayers});if(k){if(R.typeOnly&&!k.peerIsolation)continue;let T=!!k.peerIsolation;l.push(W("LAYER_IMPORT_VIOLATION",k.message??(T?`Layer "${m}" must not import across slices into "${D}".`:`Layer "${m}" must not import "${D}".`),{line:je(o,R.index),source:R.value,target:R.value,filePath:u,fromLayer:m,toLayer:D,suggestion:T?"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:R.kind,peerIsolation:T,...R.typeOnly?{typeOnly:!0}:{}}}));continue}continue}v||R.typeOnly||!na(R.value)&&!ra(R.value)||l.push(W("FORBIDDEN_IMPORT",`Forbidden ${R.kind} target: "${R.value}".`,{line:je(o,R.index),source:R.value,target:R.value,filePath:u,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+_,details:{importKind:R.kind}}))}if(e.policies)for(let R of e.policies){let I=R.check({source:o,context:a});if(I!==!0)if(Array.isArray(I))for(let b of I)l.push(W("POLICY_VIOLATION",b.message,{filePath:u,suggestion:`Fix violation of policy "${R.name}".`}));else I===!1?l.push(W("POLICY_VIOLATION",`Policy ${R.name} failed on generated code`)):l.push(W("POLICY_VIOLATION",I.message))}if(s&&t.size>0)for(let R of A)Ce(R.value)&&!t.has(R.value)&&l.push(W("UNKNOWN_INTENT",`Unknown intent reference: "${R.value}"`,{line:je(o,R.index),filePath:u,target:R.value,suggestion:`Register intent "${R.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&m)for(let R of A){if(!Ce(R.value))continue;let I=e.architectureProfile.resolveLayer(R.value);if(!I)continue;let b=be(e.architectureProfile.rules,m,I,{fromPath:typeof u=="string"?u:void 0,layers:e.architectureLayers});if(b){let D=b.rule.peerIsolation?Me(b.peerIsolationReason??"cross-slice",{fromPath:typeof u=="string"?u:void 0,fromSlice:b.fromSlice,toSlice:b.toSlice}):void 0,k=`Layer "${m}" must not reference "${I}" through "${R.value}".`,T=D&&b.peerIsolationReason!=="cross-slice"?`${k} ${D}`:b.rule.message?D?`${b.rule.message} (${D})`:b.rule.message:k;l.push(W("LAYER_REFERENCE_VIOLATION",T,{line:je(o,R.index),filePath:u,target:R.value,fromLayer:m,toLayer:I,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:b.rule,peerIsolationReason:b.peerIsolationReason}}))}}if(e.extensions)for(let R of e.extensions)try{let I=R.analyze(o,a);l.push(...I)}catch(I){l.push(W("EXTENSION_ERROR",`Extension "${R.name}" failed: ${I instanceof Error?I.message:String(I)}`))}if(e.typescript&&g&&m&&e.forbiddenGlobals?.[m]?.length)try{let R=e.forbiddenGlobals[m];l.push(...He(e.typescript,g,R).map(I=>W("FORBIDDEN_GLOBAL",`${m} must not use the ambient global "${I.name}".`,{line:I.line,filePath:u,target:I.name,fromLayer:m,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let I of p??[]){if(I.typeOnly||!I.specifier)continue;let b=Ee(I.specifier,R);b&&l.push(W("FORBIDDEN_GLOBAL",`${m} must not use module "${I.specifier}" because it is the import form of forbidden global "${b}".`,{line:I.line,filePath:u,source:I.specifier,target:I.specifier,fromLayer:m,details:{importKind:I.kind,forbiddenGlobal:b},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(R){l.push(W("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${R instanceof Error?R.message:String(R)}`))}if(e.typescript&&g&&m&&e.capabilityWalls?.[m]?.length)try{let R=new Set(e.capabilityWalls[m]),I=e.forbiddenGlobals?.[m]??[];for(let b of gn(e.typescript,g))R.has(b.capability)&&(b.source==="ambient-global"&&Xe(b.symbol,I)||b.source==="import-based"&&Ee(b.symbol,I)||l.push(W("CAPABILITY_VIOLATION",b.source==="import-based"?`${m} denies the ${b.capability} capability; found import of "${b.symbol}".`:`${m} denies the ${b.capability} capability; found ambient "${b.symbol}".`,{line:b.line,filePath:u,target:b.symbol,capability:b.capability,fromLayer:m,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(R){l.push(W("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${R instanceof Error?R.message:String(R)}`))}if(e.typescript)try{l.push(...ua(e.typescript,o,a,e.architectureProfile))}catch(R){l.push(W("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${R instanceof Error?R.message:String(R)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:l.length===0,violations:l}}}}i(jr,"createAICodeGate");var Oe={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Vr={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...Oe,default:[]},kernelRoots:{...Oe},managedLayers:{...Oe,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},Ur={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...Oe,default:[]},managedLayers:{...Oe,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...Oe,default:[]},appliesTo:{...Oe,default:[]}}};function nt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(nt,"isObject");function Kr(e){let t=new Set;if(!Array.isArray(e.layers))return t;for(let n of e.layers)nt(n)&&typeof n.name=="string"&&n.name.length>0&&t.add(n.name);return t}i(Kr,"declaredLayerNames");function Gr(e){if(!nt(e))return e;let t={mode:e.mode===void 0?"advisory":e.mode,compositionRoots:e.compositionRoots===void 0?[]:e.compositionRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,requireDeclarations:e.requireDeclarations===void 0?!0:e.requireDeclarations};return e.kernelRoots!==void 0&&(t.kernelRoots=e.kernelRoots),e.ignoreDirectNewForErrors!==void 0&&(t.ignoreDirectNewForErrors=e.ignoreDirectNewForErrors),{...e,...t}}i(Gr,"defaultedArkRun");function Br(e){if(!nt(e))return e;let t=typeof e.maxXiKeys=="number"&&e.maxXiKeys>0?e.maxXiKeys:7;return{...e,mode:e.mode===void 0?"advisory":e.mode,planeRoots:e.planeRoots===void 0?[]:e.planeRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,maxXiKeys:t,xiKeys:e.xiKeys===void 0?[]:e.xiKeys}}i(Br,"defaultedArkOrder");function zr(e,t){let n=e.arkRun;if(n===void 0||!nt(n))return;let r=Kr(e),s=n.managedLayers;if(Array.isArray(s)&&s.forEach((o,a)=>{typeof o=="string"&&o.length>0&&!r.has(o)&&t.push({path:`$.arkRun.managedLayers[${a}]`,message:`layer ${JSON.stringify(o)} is not declared in layers[]`})}),n.mode==="enforced"){let o=n.kernelRoots??n.compositionRoots;(!Array.isArray(o)||o.length===0)&&t.push({path:n.kernelRoots!==void 0?"$.arkRun.kernelRoots":"$.arkRun.compositionRoots",message:"ARKRUN_MISSING_ROOT: enforced mode requires at least one kernel root"}),(!Array.isArray(s)||s.length===0)&&t.push({path:"$.arkRun.managedLayers",message:"enforced mode requires at least one managed layer"})}}i(zr,"validateArkRunExtra");function qr(e,t){let n=e.arkOrder;if(n===void 0||!nt(n))return;let r=Kr(e),s=n.managedLayers;if(Array.isArray(s)&&s.forEach((o,a)=>{typeof o=="string"&&o.length>0&&!r.has(o)&&t.push({path:`$.arkOrder.managedLayers[${a}]`,message:`layer ${JSON.stringify(o)} is not declared in layers[]`})}),n.mode==="enforced"){let o=n.planeRoots;(!Array.isArray(o)||o.length===0)&&t.push({path:"$.arkOrder.planeRoots",message:"ARKORDER_MISSING_PLANE: enforced mode requires at least one plane root"}),(!Array.isArray(s)||s.length===0)&&t.push({path:"$.arkOrder.managedLayers",message:"enforced mode requires at least one managed layer"})}}i(qr,"validateArkOrderExtra");var se="1.3",Ct="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",Wr=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],pa=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function fa(){let e=[];for(let t of Wr)for(let n of Wr)t===n||pa.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}i(fa,"createDefaultRules");var Ot=fa(),Rn=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"},{from:"1.1",to:"1.2"},{from:"1.2",to:"1.3"}],le={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},kn={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Ct,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:Ct,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:se,default:se},name:{type:"string",minLength:1},include:{...le,minItems:1,default:["src"]},exclude:{...le,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:Ot,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...le,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},coverage:{$ref:"#/$defs/coverage"},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},arkRun:{$ref:"#/$defs/arkRun"},arkOrder:{$ref:"#/$defs/arkOrder"},stewards:{...le,default:[]}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...le,minItems:1},exclude:le,intentPrefixes:le,description:{type:"string",minLength:1},forbiddenGlobals:le,capabilities:{type:"object",additionalProperties:!1,properties:{deny:{type:"array",uniqueItems:!0,items:{type:"string",enum:["network","filesystem","clock","randomness","environment","process","persistence"]}}}},pure:{type:"boolean"},mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"},reserved:{type:"boolean"},allowEmpty:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...le,minItems:1},sharedRoots:{...le,minItems:1},allowedCrossSlice:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}},coverage:{type:"object",additionalProperties:!1,description:"Invariant coverage scan controls. testGlobs replaces the built-in test-name heuristic; maxFiles raises or lowers the evidence file budget; coverageRoots declares where the project runs its tests, so a covering test found outside them is reported instead of silently certifying an invariant.",properties:{testGlobs:{...le,minItems:1},maxFiles:{type:"integer",minimum:1},coverageRoots:{...le,minItems:1}}},arkRun:Vr,arkOrder:Ur}},ge=class extends Error{static{i(this,"ArkConfigValidationError")}issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
1
+ var Wo=Object.defineProperty;var i=(e,t)=>Wo(e,"name",{value:t,configurable:!0});var qo="4.8.10";var Yo=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,Xo=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,Jo=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function Zo(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),s=String(t?.toLayer??"");return Yo.test(n)?"pure-shared":r==="PersistenceAdapters"&&(Xo.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${s} ${n}`))?"kernel-emit":Jo.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&s==="PersistenceAdapters"?"use-case":"unknown"}i(Zo,"classifyLayerImportKind");function Qo(e){if(e.typeOnly||e.targetTypeOnlyExports||e.namedBindingsTypeOnly)return"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.";if(e.peerIsolation)return"Extract the shared dependency to a shared layer, test at the public interface, then preflight again.";let t=Zo(typeof e.target=="string"?e.target:"",{fromLayer:typeof e.fromLayer=="string"?e.fromLayer:void 0,toLayer:typeof e.toLayer=="string"?e.toLayer:void 0});return t==="pure-shared"?"Adopt the imported constants/types/pure module into DomainModel or SharedKernel (do not inject a port). Then preflight again.":t==="kernel-emit"?"Persistence must not emit. Inject a port or move the event map to SharedTypes; do not import kernel/events/bootstrap from a repository. Then preflight again.":t==="use-case"||e.portProofEligible?`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, test at the public interface, then preflight again.`:"Classify the import: if it is constants/types/pure, adopt into DomainModel or SharedKernel; define a port only if the target is a real use-case. Then preflight again."}i(Qo,"layerImportNextAction");function ea(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}i(ea,"arkRunCallSiteName");function ta(e){let t=ea(e),n=typeof e.fromLayer=="string"&&e.fromLayer.length>0?e.fromLayer:void 0;switch(e.ruleId){case"ARKRUN_MISSING_ROOT":return t?`Import createStrictArkKernel from arkgate/runtime and call it in composition root ${t} listed in arkRun.compositionRoots, then preflight again.`:"Import createStrictArkKernel from arkgate/runtime (same npm package; @arkgate/runtime is deprecated) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKRUN_KERNEL_IN_DOMAIN":return t?`Move the kernel import of ${t} out of ${n??"the Domain-role layer"} into a composition root or adapter. Import from arkgate/runtime, then preflight again.`:"Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from arkgate/runtime (same npm package; @arkgate/runtime is deprecated), then preflight again. Never mechanical-safe.";case"ARKRUN_DIRECT_NEW":return t?`Resolve ${t} from the kernel instead of constructing it with new, then preflight again.`:"Resolve the type from the kernel instead of constructing it with new, then preflight again. Never mechanical-safe \u2014 rewiring construction is a design decision.";case"ARKRUN_UNDECLARED_EMIT":return t?`Add ${t} to raises or sends on the managed component, then preflight again.`:"Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment.";case"ARKRUN_UNDECLARED_HANDLE":return t?`Add ${t} to reactsTo on the managed component, then preflight again.`:"Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment.";case"ARKRUN_UNDECLARED_DEPEND":return t?`Add ${t} to uses on the managed component, then preflight again.`:"Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment.";case"ARKRUN_TRANSPORT_BYPASS":return t?`Send through the ArkRun kernel transport instead of importing ${t}, then preflight again.`:"Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe \u2014 homemade buses stay judgment.";default:return`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(ta,"arkRunNextAction");function pe(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return Qo(e);case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, test at the public interface, then preflight again.`;case"CAPABILITY_VIOLATION":return`Define a ${String(e.capability??"capability")} port in ${e.fromLayer??"the walled layer"}, bind the implementation outside it, test at the public interface, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, test at the public interface, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"LITERAL_PATH_DRIFT":return typeof e.target=="string"&&e.target.length>0?`Rewrite the literal to ${e.target}, or run \`arkgate-check --path-drift --base-ref <ref> --write\` to apply every anchored replacement.`:"Rewrite the literal to the rename destination, or run `arkgate-check --path-drift --base-ref <ref> --write` to apply every anchored replacement.";case"LITERAL_PATH_UNRESOLVED":return"Read the candidate and decide: fix the path, or leave it. Advisory \u2014 with no rename to anchor it there is no destination to propose, so --write never touches it.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";case"INVARIANT_COVERAGE_OUTSIDE_ROOTS":return"Move the covering test under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json, then run Ark again.";case"ARKRULE_STRUCTURE":case"ARKRULE_INVARIANT":case"INVARIANT_UNCOVERED":return`Fix the structure or invariant for ${typeof e.arkruleId=="string"&&e.arkruleId.length>0?e.arkruleId:"the ArkRule"} (declared in ${typeof e.arkruleSource=="string"&&e.arkruleSource.length>0?e.arkruleSource:"arkrules/<Layer>.json"}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`;case"ARKRUN_MISSING_ROOT":case"ARKRUN_KERNEL_IN_DOMAIN":case"ARKRUN_DIRECT_NEW":case"ARKRUN_UNDECLARED_EMIT":case"ARKRUN_UNDECLARED_HANDLE":case"ARKRUN_UNDECLARED_DEPEND":case"ARKRUN_TRANSPORT_BYPASS":return ta(e);case"ARKORDER_MISSING_PLANE":return typeof e.target=="string"&&e.target.length>0?`Import createOrderPlane from arkgate/order and call it in plane root ${e.target} listed in arkOrder.planeRoots, then preflight again.`:"Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKORDER_KERNEL_IN_DOMAIN":return"Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe.";case"ARKORDER_GENERIC_UPDATE":return"Use release() for the first freeze of \u03BE. Later pattern change is proposeRelease then apply(ProposeResult). Never update/patch/set. Never mechanical-safe.";case"ARKORDER_TOO_MANY_PARAMS":return"Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe.";case"ARKORDER_INGEST_WRITES_XI":return"Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe.";case"ARKORDER_XI_FIELD_WRITE":return typeof e.target=="string"&&e.target.length>0?`Do not persist slow key ${e.target} from a use-case. Absorb the field with ingest() or change the pattern with proposeRelease then apply, then preflight again.`:"Do not persist a declared slow key from a use-case. Absorb the field with ingest() or change the pattern with proposeRelease then apply, then preflight again. Never mechanical-safe.";case"ARKORDER_UNVALVED_RELEASE":return"Change \u03BE with proposeRelease then apply(ProposeResult). release() is only the first freeze. Never mechanical-safe.";default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(pe,"deterministicNextAction");var an="1.5",Lr="docs/diagnostics.md";function _(e){return typeof e=="string"&&e.length>0?e:void 0}i(_,"text");function Nr(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}i(Nr,"positiveInteger");function ln(e){let t=typeof e.ruleId=="string"?e.ruleId:typeof e.code=="string"?e.code:void 0,n=typeof e.file=="string"?e.file:void 0,r=typeof e.fromLayer=="string"?e.fromLayer:void 0,s=typeof e.toLayer=="string"?e.toLayer:void 0,o=typeof e.target=="string"?e.target:void 0;return[t,n,r??"",s??"",o??""].join("|")}i(ln,"adapterFindingTargetKey");function sn(e){let t=new Map;return e.map(n=>{let r=ln(n),s=(t.get(r)??0)+1;return t.set(r,s),s===1?r:`${r}#${s}`})}i(sn,"adapterFindingOccurrenceTargetKeys");function Pr(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")}`}i(Pr,"adapterFindingRefFromTargetKey");function wr(e){return`${Lr}#${e}`}i(wr,"adapterDocsCodePath");function na(e,t,n){return pe({ruleId:e,target:_(t.target)??_(n.target)??void 0,fromLayer:_(t.fromLayer)??void 0,toLayer:_(t.toLayer)??void 0,typeOnly:t.typeOnly===!0,targetTypeOnlyExports:t.targetTypeOnlyExports===!0,namedBindingsTypeOnly:t.namedBindingsTypeOnly===!0,portProofEligible:t.portProofEligible===!0,peerIsolation:t.peerIsolation===!0,sourcePureTypeModule:t.sourcePureTypeModule===!0,edgeKind:_(t.edgeKind)??void 0,capability:_(t.capability)??_(n.capability)??void 0,arkruleId:_(t.arkruleId)??void 0,arkruleSource:_(t.arkruleSource)??void 0})}i(na,"nextActionForDiagnostic");function on(e,t="error",n){let r=_(e.ruleId)??_(e.code)??"ARK_UNKNOWN",s=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,o={..._(e.target)?{target:_(e.target)}:{},..._(e.fromLayer)?{fromLayer:_(e.fromLayer)}:{},..._(e.toLayer)?{toLayer:_(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.capability)?{capability:_(e.capability)}:{},..._(e.edgeKind)?{edgeKind:_(e.edgeKind)}:{},..._(e.arkruleId)?{arkruleId:_(e.arkruleId)}:{},..._(e.arkruleSource)?{arkruleSource:_(e.arkruleSource)}:{}},a=n??ln(e),l=Pr(a);return{ruleId:r,severity:s,message:_(e.message)??r,location:{file:_(e.file)??"<unknown>",line:Nr(e.line,1),column:Nr(e.column,1)},evidence:o,nextAction:_(e.nextAction)??na(r,o,e),findingRef:l,targetKey:a,docsCodePath:wr(r)}}i(on,"toAdapterDiagnostic");function ra(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(y=>({code:_(y.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:_(y.message)??`Analysis ${t}: required evidence is incomplete.`,..._(y.file)?{file:_(y.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],s={..._(e.policyHash)?{policyHash:_(e.policyHash)}:{},..._(e.resolverIdentity)?{resolverIdentity:_(e.resolverIdentity)}:{},..._(e.factsHash)?{factsHash:_(e.factsHash)}:{},..._(e.candidateTreeHash)?{candidateTreeHash:_(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let y of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!s[y])throw new Error(`${y} is required for resolved ${t} adapter evidence.`)}let o=e.violations??[],a=e.warnings??[],l=sn(o),c=sn(a),u=[...o.map((y,g)=>on(y,"error",l[g])),...a.map((y,g)=>on(y,"warning",c[g]))],f={schemaVersion:an,completenessReasons:r,diagnostics:u};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...f,mode:n,valid:!1,completeness:t,...s};let y={policyHash:s.policyHash,resolverIdentity:s.resolverIdentity,factsHash:s.factsHash,candidateTreeHash:s.candidateTreeHash};return t==="complete"?{...f,mode:n,valid:e.valid,completeness:t,...y}:{...f,mode:n,valid:!1,completeness:t,...y}}return t==="complete"?{...f,mode:n,valid:e.valid,completeness:t,...s}:{...f,mode:n,valid:!1,completeness:t,...s}}i(ra,"createAdapterResult");var sa={$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:an},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},findingRef:{type:"string",minLength:1,pattern:"^fnv1a-[0-9a-f]{8}$"},targetKey:{type:"string",minLength:1},docsCodePath:{type:"string",minLength:1}}}}}};var oa="1.0",Dr="https://unpkg.com/arkgate@4/schemas/ark.project-identity.schema.json",Et="^sha256:[a-f0-9]{64}$",Mr={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:Et,description:"Project id previously returned by ark_identity or ark_manifest."}}},Fr={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:Et},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},aa={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Dr,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:Et},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{type:"string",minLength:1},arkgateVersion:{type:"string",minLength:1},contractHash:{type:"string",pattern:Et},contractSource:{enum:["project","default-profile","manifest"]},runtimeId:{type:"string",minLength:1},processStartedAt:{type:"string",format:"date-time"}},$defs:{expectation:Mr,binding:Fr}};function ia(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}`}i(ia,"createProjectId");function la(e){return{schemaVersion:"1.0",...e}}i(la,"createProjectIdentity");var dn=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),pn=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),fn=Object.freeze(Object.keys(pn).sort()),cn=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"}),un=Object.freeze({process:Object.freeze(["process","node:process"])});function Ye(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=cn[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),s=cn[r];if(s)return s;let o=e.indexOf("/",n+1);return o<0?null:cn[e.slice(0,o)]??null}i(Ye,"capabilityForModuleSpecifier");function Ee(e,t){for(let n of t)if(un[n]?.includes(e))return n;return null}i(Ee,"forbiddenGlobalForModuleSpecifier");function It(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),s=pn[r];if(s)return s}return null}i(It,"capabilityForAmbientName");function De(e){if(e?.pure===!0)return[...dn].sort();let n=(e?.capabilities?.deny??[]).filter(r=>dn.includes(r));return[...new Set(n)].sort()}i(De,"effectiveCapabilityDeny");function Xe(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}i(Xe,"ambientCoveredByForbiddenGlobals");function St(e){let t=new Set,n=new Set,r=Object.keys(pn);for(let s of e?.forbiddenGlobals??[]){let o=r.filter(a=>a===s||a.startsWith(`${s}.`));if(o.length===0)n.add(s);else for(let a of o)t.add(`ambient:${a}`);for(let a of un[s]??[])t.add(`import-exact:${a}`)}for(let s of De(e)){if(t.add(`import:${s}`),s==="process")for(let o of un.process)t.add(`import-exact:${o}`);for(let o of r)It(o)===s&&t.add(`ambient:${o}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}i(St,"loweredLayerCoverage");var $r=new Map;function Hr(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(Hr,"escapeLiteral");function bt(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}i(bt,"normalizeGlobSeparators");function ca(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}i(ca,"bracesBalanced");function me(e){let t=$r.get(e);if(t)return t;let n=bt(e),r=ca(n),s="",o=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(s+=Hr(n[l+1]),l+=1):c==="*"?n[l+1]==="*"?n[l+2]==="/"?(s+="(?:.*/)?",l+=2):(s+=".*",l+=1):s+="[^/]*":c==="?"?s+="[^/]":c==="{"&&r?(s+="(?:",o+=1):c==="}"&&r&&o>0?(s+=")",o-=1):c===","&&r&&o>0?s+="|":s+=Hr(c)}let a=new RegExp(`^${s}$`);return $r.set(e,a),a}i(me,"globToRegExp");function da(e){return bt(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}i(da,"concreteGlobSegments");function mn(e,t){let n=bt(String(e)),r=da(n),s=n.replace(/\*/g,"").length,o=r.length*1e4+s;if(t==null||t==="")return o;let a=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return s;let l=0,c=-1;for(let u of r){let f=-1;for(let y=l;y<a.length;y+=1)if(a[y]===u){f=y;break}if(f<0)return o;c=f,l=f+1}return(c+1)*1e6+r.length*1e4+s}i(mn,"patternSpecificity");function de(e,t){let n=String(e).split(/[/\\]/).join("/"),r,s=-1;for(let o of t??[])if(!(o.exclude??[]).some(a=>me(a).test(n))){for(let a of o.patterns??[])if(me(a).test(n)){let l=mn(a,n);l>s&&(s=l,r=o.name)}}return r}i(de,"layerForRelativePath");function jr(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()}`}i(jr,"sliceIdForPath");function ua(e){let t=new Set;for(let n of e??[]){let s=bt(String(n)).split("/").filter(Boolean);for(let o=0;o<s.length;o+=1){let a=s[o];if((a==="**"||a==="*")&&o>0){let l=s[o-1];l&&!l.includes("*")&&!l.includes("{")&&!l.includes("}")&&t.add(l)}}}return[...t]}i(ua,"inferSliceFoldersFromPatterns");function pa(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 ua(r?.patterns)}i(pa,"resolveSliceFolders");function Vr(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}i(Vr,"normalizeSegments");function Gr(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}i(Gr,"trimTrailingSlashes");var fa=["src","app"];function ma(e){let t=Gr(e.replace(/^[./]+/,""));return t==="*"||t==="**"}i(ma,"isBlanketRoot");function Ur(e,t){if(!e||!t?.length)return!1;let n=String(e).split(/[/\\]/).join("/"),r=n.toLowerCase(),s=Vr(n);for(let o of t){if(typeof o!="string"||o.length===0||ma(o))continue;if(o.includes("*")){let c=Gr(o.toLowerCase());if(me(c).test(r)||me(`${c}/**`).test(r))return!0;continue}let a=Vr(o);if(a.length===0)continue;let l=fa.includes(s[0])&&a[0]!==s[0]?[0,1]:[0];for(let c of l){if(c+a.length>s.length)continue;let u=!0;for(let f=0;f<a.length;f+=1)if(s[c+f]!==a[f]){u=!1;break}if(u)return!0}}return!1}i(Ur,"pathUnderSharedRoot");function Kr(e,t){let n=String(e).split(/[/\\]/).filter(Boolean).join("/").toLowerCase();if(!n)return!1;let r=t.toLowerCase();return n===r?!0:!n.includes("/")&&r.endsWith(`/${n}`)}i(Kr,"sliceMatchesDeclaration");function ga(e,t,n){return!e?.length||!t||!n?!1:e.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&Kr(r.from,t)&&Kr(r.to,n))}i(ga,"crossSliceEdgeAllowed");function ya(e){if(!e.fromPath)return{denied:!0,reason:"missing-path"};if(e.folderCount<=0)return{denied:!0,reason:"no-slice-folders"};let t=!!e.fromSlice||e.fromShared===!0;if(!e.toPath)return t?e.fromSlice?{denied:!0,reason:"missing-path"}:{denied:!1}:{denied:!0,reason:"unclassifiable-path"};let n=!!e.toSlice||e.toShared===!0;return!t||!n?{denied:!0,reason:"unclassifiable-path"}:!e.fromSlice||!e.toSlice?{denied:!1}:e.fromSlice===e.toSlice?{denied:!1}:e.crossSliceAllowed?{denied:!1}:{denied:!0,reason:"cross-slice"}}i(ya,"peerIsolationDecision");function Me(e,t){switch(e){case"cross-slice":return`cross-slice edge ${t.fromSlice??"?"} \u2192 ${t.toSlice??"?"}. Extract the shared code, use events/ports across slices, or declare the edge in the rule's allowedCrossSlice.`;case"unclassifiable-path":{let n=[t.fromSlice?void 0:t.fromPath,t.toSlice?void 0:t.toPath].filter(s=>!!s);return`unclassifiable path${n.length>0?` (${n.join(", ")})`:""} \u2014 ArkGate cannot place it in a slice, so it cannot prove this is not a cross-slice edge. Move it into a slice, or declare its root in the rule's sharedRoots.`}case"no-slice-folders":return"no slice folders \u2014 peerIsolation is on but no slice folder resolves from the rule or the layer patterns. Set sliceFolders on the rule.";default:return"no path evidence for this edge \u2014 peerIsolation needs the importer and importee paths."}}i(Me,"peerIsolationDenyExplanation");function vt(e,t,n,r){return Ce(e,t,n,r)?.rule}i(vt,"findDeniedEdgeRule");function Ce(e,t,n,r){for(let s of e??[])if(!(s.from!==t||s.to!==n)&&s.allowed===!1){if(s.peerIsolation){let o=r?.fromPath,a=r?.toPath,l=pa(s,t,r?.layers),c=o?jr(o,l):void 0,u=a?jr(a,l):void 0,f=ya({fromPath:o,toPath:a,folderCount:l.length,fromSlice:c,toSlice:u,fromShared:!c&&Ur(o,s.sharedRoots),toShared:!u&&Ur(a,s.sharedRoots),crossSliceAllowed:ga(s.allowedCrossSlice,c,u)});if(f.denied)return{rule:s,peerIsolationReason:f.reason,fromSlice:c,toSlice:u};continue}if(t!==n)return{rule:s}}}i(Ce,"findDeniedEdgeDecision");function Fe(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(Fe,"literalText");function Wr(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}i(Wr,"lineOf");function Br(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(o=>o.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))}i(Br,"isTypeOnlyReference");function qr(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()}i(qr,"singleFileChecker");function gn(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}i(gn,"symbolAt");function yn(e,t,n,r){let s=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,o;try{o=s?t.getShorthandAssignmentValueSymbol(r.parent):gn(t,r)}catch{o=void 0}return!!o?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}i(yn,"localDeclaration");function $e(e,t){let n,r=[],s=i((a,l,c,u=!1)=>r.push({specifier:c,kind:l,line:Wr(t,a),typeOnly:u,unresolved:c===void 0,node:a}),"add"),o=i(a=>{if(e.isImportDeclaration(a))s(a,"import",Fe(e,a.moduleSpecifier),Br(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)s(a,"export",Fe(e,a.moduleSpecifier),Br(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))s(a,"require",Fe(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let l=a.expression.kind===e.SyntaxKind.ImportKeyword,u=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!yn(e,n??(n=qr(e,t)),t,a.expression);(l||u)&&s(a,u?"require":"dynamic-import",Fe(e,a.arguments[0]))}e.forEachChild(a,o)},"visit");return o(t),r}i($e,"extractSemanticDependencies");function ha(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=Fe(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}}i(ha,"staticAccessPath");function Aa(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}i(Aa,"runtimeIdentifierReference");function zr(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}}i(zr,"bestForbiddenMatch");function He(e,t,n){if(n.length===0)return[];let r=new Set(n),s=qr(e,t),o=new Map,a=new Set;for(let g of t.statements)if(e.isVariableStatement(g))for(let p of g.declarationList.declarations)e.isIdentifier(p.name)&&a.add(p.name.text);let l=i(g=>{let p=ha(e,g);if(!p)return;let m=gn(s,p.root),A=m?o.get(m):void 0;return A?[...A,...p.segments.slice(1)]:yn(e,s,t,p.root)||a.has(p.root.text)?void 0:p.segments},"resolvePath");for(let g of t.statements)if(e.isVariableStatement(g))for(let p of g.declarationList.declarations){if(!p.initializer||!e.isIdentifier(p.name))continue;let m=l(p.initializer),A=gn(s,p.name);!m||!A||o.set(A,m)}let c=[],u=new Set,f=i((g,p)=>{let m=Wr(t,p),A=`${g}:${p.getStart(t)}`;u.has(A)||(u.add(A),c.push({name:g,line:m,node:p}))},"flag"),y=i(g=>{let p=g.parent&&(e.isPropertyAccessExpression(g.parent)||e.isElementAccessExpression(g.parent))&&g.parent.expression===g;if((e.isPropertyAccessExpression(g)||e.isElementAccessExpression(g))&&!p){let m=l(g),A=m?zr(r,m):void 0;A&&f(A,g)}else e.isIdentifier(g)&&r.has(g.text)&&Aa(e,g)&&!yn(e,s,t,g)&&f(g.text,g);if(e.isVariableDeclaration(g)&&e.isObjectBindingPattern(g.name)&&g.initializer){let m=l(g.initializer);if(m)for(let A of g.name.elements){if(!e.isIdentifier(A.name))continue;let S=A.propertyName?Fe(e,A.propertyName)??A.propertyName.text:A.name.text,O=zr(r,[...m,S]);O&&f(O,g.initializer)}}e.forEachChild(g,y)},"visit");return y(t),c}i(He,"collectForbiddenCapabilityUses");function hn(e,t,n){let r=[];for(let s of n?.dependencies??$e(e,t)){if(s.typeOnly||!s.specifier)continue;let o=Ye(s.specifier);o&&r.push({capability:o,symbol:s.specifier,line:s.line,source:"import-based"})}for(let s of n?.ambientUses??He(e,t,fn)){let o=It(s.name);o&&r.push({capability:o,symbol:s.name,line:s.line,source:"ambient-global"})}return r.sort((s,o)=>s.line-o.line||s.capability.localeCompare(o.capability)||s.symbol.localeCompare(o.symbol))}i(hn,"collectCapabilityUses");var An={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."},Rn=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 kn(e,t){return t.flatMap((r,s)=>(r.prefixes??r.intentPrefixes??[]).map(o=>({layer:r.name,layerIndex:s,prefix:o.endsWith(".")?o:`${o}.`}))).filter(({prefix:r})=>e.startsWith(r)).sort((r,s)=>s.prefix.length-r.prefix.length||r.layerIndex-s.layerIndex)[0]?.layer}i(kn,"resolveIntentLayer");function _e(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}i(_e,"looksLikeArkIntent");function Je(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&_e(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:An.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:An.PUBLISH_MISSING_SOURCE}),t}i(Je,"classifyPublishFacts");function W(e,t,n){return{ruleId:e,code:e,message:t,...n}}i(W,"violation");function je(e,t){return e.slice(0,t).split(`
2
+ `).length}i(je,"lineOf");var Ra=new Set(["publish","subscribe","defineIntent","registerHandler"]);function ka(e,t){return e.index+e[0].indexOf(t)}i(ka,"captureIndex");function Ea(e){let t=[],n=new Set,r=i((l,c)=>{!l||n.has(c)||(n.add(c),t.push({value:l,index:c}))},"push"),s=i(l=>{l.lastIndex=0;let c;for(;(c=l.exec(e))!==null;){let u=c[1];u&&r(u,ka(c,u))}},"pushFrom");s(/\b(?:publish|subscribe|defineIntent|registerHandler)\s{0,8}(?:<[^>]{0,120}>)?\s{0,8}\(\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),s(/\b(?:intent|onEvent)\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g);let o=/\breactsTo\s{0,8}:\s{0,8}\[([^\]]{0,2000})\]/g,a;for(;(a=o.exec(e))!==null;){let l=a[1]??"",c=a.index+a[0].indexOf(l),u=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,f;for(;(f=u.exec(l))!==null;){let y=f[1];y&&r(y,c+f.index+f[0].indexOf(y))}}return s(/\bmetadata\s{0,8}:\s{0,8}\{[^}]{0,400}\bsource\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),s(/\bpublish\s{0,8}(?:<[^>]{0,120}>)?\s{0,8}\([^;]{0,400}?\bsource\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),t.sort((l,c)=>l.index-c.index)}i(Ea,"extractQuotedStrings");function Ia(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 o=s.index+s[0].indexOf(s[1]),a=s[0],l=r.kind==="import"&&/\bimport\s+type\b/.test(a)||r.kind==="export"&&/\bexport\s+type\b/.test(a);t.push({value:s[1],index:o,kind:r.kind,typeOnly:l})}}return t.sort((r,s)=>r.index-s.index)}i(Ia,"extractModuleSpecifiers");function Sa(e,t){return!!(t&&(e.isParenthesizedExpression(t)||e.isAsExpression(t)||typeof e.isTypeAssertionExpression=="function"&&e.isTypeAssertionExpression(t)||typeof e.isSatisfiesExpression=="function"&&e.isSatisfiesExpression(t)))}i(Sa,"isSyntaxWrapper");function En(e,t){let n=t;for(;n?.parent&&Sa(e,n.parent);)n=n.parent;return n}i(En,"unwrapWrappers");function In(e,t){if(!t||!e.isCallExpression(t))return;let n=t.expression;if(e.isIdentifier(n))return n.text;if(e.isPropertyAccessExpression(n))return n.name.text}i(In,"callCalleeName");function ba(e,t){let n=t.parent;if(!n||!e.isObjectLiteralExpression(n))return!1;let r=En(e,n),s=r.parent;if(!s)return!1;if(e.isCallExpression(s)&&In(e,s)==="publish"){let o=s.arguments;return o[1]===r||o[2]===r}if(e.isPropertyAssignment(s)&&Sn(e,s.name)==="metadata"){let o=s.parent;if(!o)return!1;let l=En(e,o).parent;return!!(l&&e.isCallExpression(l)&&In(e,l)==="publish")}return!1}i(ba,"isPublishMetadataSource");function Yr(e,t){let n=En(e,t),r=n.parent;if(!r)return!1;if(e.isCallExpression(r)){let s=In(e,r);if(s&&Ra.has(s)&&r.arguments.some(o=>o===n))return!0}if(e.isArrayLiteralExpression(r))return Yr(e,r);if(e.isPropertyAssignment(r)){let s=Sn(e,r.name);if(s==="intent"||s==="onEvent"||s==="reactsTo"||s==="source"&&ba(e,r))return!0}return!1}i(Yr,"isDeclaredIntentSite");function va(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],s=i(o=>{e.isStringLiteralLike(o)&&Yr(e,o)&&r.push({value:o.text,index:o.getStart(n)}),e.forEachChild(o,s)},"visit");return s(n),r}i(va,"extractQuotedStringsAst");function Ca(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))}i(Ca,"hasInfrastructureToken");function _a(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}i(_a,"isKnownInfrastructurePackage");function Oa(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}i(Oa,"layerHasInfrastructureRole");function Qe(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(Qe,"tsStringLiteralText");function Sn(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}i(Sn,"tsPropertyName");function Xr(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:Sn(e,r.name)===n)}i(Xr,"tsObjectProperty");function et(e,t,n){return Xr(e,t,n)!==void 0}i(et,"tsObjectHasProperty");function Ze(e,t,n){let r=Xr(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}i(Ze,"tsObjectPropertyValue");function xa(e,t){let n=Ze(e,t,"metadata");return et(e,n,"source")}i(xa,"tsObjectHasMetadataSource");function Jr(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?Jr(e,t.name):!1:!1}i(Jr,"tsLooksLikeIntentCreatorExpression");function Ta(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"}i(Ta,"tsIsPublishCall");function Na(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=Qe(e,n);return r!==void 0&&_e(r)||et(e,n,"intent")||Jr(e,n)}i(Na,"tsIsArkPublishCandidate");function La(e,t){if(!e.isCallExpression(t))return!1;let[n,r,s]=t.arguments;return xa(e,n)||et(e,r,"source")||et(e,s,"source")}i(La,"tsPublishHasSource");function Pa(e,t){if(!e.isCallExpression(t))return;let[n,r,s]=t.arguments,o=Ze(e,n,"metadata");return Qe(e,Ze(e,o,"source"))??Qe(e,Ze(e,r,"source"))??Qe(e,Ze(e,s,"source"))}i(Pa,"tsPublishSourceLiteral");function wa(e,t,n,r){let s=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),o=n,a=o?.filePath,l=o?.layer,c=[],u=i(y=>s.getLineAndCharacterOfPosition(y.getStart(s)).line+1,"lineForNode"),f=i(y=>{if(Ta(e,y)){let g=y.arguments[0],p=Qe(e,g);for(let A of Je({publishCall:!0,rawIntentName:p,objectHasIntent:et(e,g,"intent"),arkPublishCandidate:Na(e,y),hasSource:La(e,y)}))c.push(W(A.ruleId,A.message,{line:u(y),filePath:a}));let m=Pa(e,y);if(r&&l&&m&&_e(m)){let A=r.resolveLayer(m);A&&A!==l&&c.push(W("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${m}" resolves to ${A}, but the target file is classified as ${l}.`,{line:u(y),filePath:a,target:m,fromLayer:l,toLayer:A}))}}e.forEachChild(y,f)},"visit");return f(s),c}i(wa,"analyzePublishAst");function Zr(e={}){let t=new Set((e.intents||[]).map(o=>typeof o=="string"?o:o.name)),n=e.forbiddenPatterns||[],r=new Set(e.infrastructureLayers??[]),s=e.enforceIntentAllowlist??t.size>0;return{validate(o,a){let l=[],c=a,u=c?.filePath,f=c?.layer,y=e.typescript,g=y?y.createSourceFile(u??"generated.ts",o,y.ScriptTarget.Latest,!0):void 0,p=g?$e(e.typescript,g):void 0,m=p?p.filter(R=>R.specifier!==void 0).map(R=>({value:R.specifier,index:R.node.getStart(g),kind:R.kind,typeOnly:R.typeOnly})):Ia(o),A=e.typescript?va(e.typescript,o):Ea(o);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(u))for(let R of p?.filter(({unresolved:I})=>I)??[]){let I=R.kind==="require";l.push(W(I?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${I?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:R.line,filePath:u}))}let S=f!==void 0&&(r.has(f)||Oa(f)),O=f!==void 0?` If "${f}" 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 R of n)if(R instanceof RegExp){R.lastIndex=0;let I=R.exec(o);R.lastIndex=0,I&&l.push(W("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${R}`,{line:I.index===void 0?void 0:je(o,I.index),filePath:u,suggestion:"Remove infrastructure imports from domain/application layers."+O}))}else o.includes(R)&&l.push(W("FORBIDDEN_SUBSTRING",`Forbidden substring: ${R}`,{line:je(o,o.indexOf(R)),filePath:u}));for(let R of m){let I=e.resolveImportTarget?.(R.value,u)??(e.resolveImportLayer?{layer:e.resolveImportLayer(R.value,u)}:void 0),v=typeof u=="string"?e.resolveImportTarget?.(u)??(e.resolveImportLayer?{layer:f,relPath:void 0}:void 0):void 0,w=I?.layer;if(w&&f){let k=vt(e.architectureProfile?.rules,f,w,{fromPath:v?.relPath,toPath:I?.relPath,layers:e.architectureLayers});if(k){if(R.typeOnly&&!k.peerIsolation)continue;let L=!!k.peerIsolation;l.push(W("LAYER_IMPORT_VIOLATION",k.message??(L?`Layer "${f}" must not import across slices into "${w}".`:`Layer "${f}" must not import "${w}".`),{line:je(o,R.index),source:R.value,target:R.value,filePath:u,fromLayer:f,toLayer:w,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:R.kind,peerIsolation:L,...R.typeOnly?{typeOnly:!0}:{}}}));continue}continue}S||R.typeOnly||!Ca(R.value)&&!_a(R.value)||l.push(W("FORBIDDEN_IMPORT",`Forbidden ${R.kind} target: "${R.value}".`,{line:je(o,R.index),source:R.value,target:R.value,filePath:u,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+O,details:{importKind:R.kind}}))}if(e.policies)for(let R of e.policies){let I=R.check({source:o,context:a});if(I!==!0)if(Array.isArray(I))for(let v of I)l.push(W("POLICY_VIOLATION",v.message,{filePath:u,suggestion:`Fix violation of policy "${R.name}".`}));else I===!1?l.push(W("POLICY_VIOLATION",`Policy ${R.name} failed on generated code`)):l.push(W("POLICY_VIOLATION",I.message))}if(s&&t.size>0)for(let R of A)_e(R.value)&&!t.has(R.value)&&l.push(W("UNKNOWN_INTENT",`Unknown intent reference: "${R.value}"`,{line:je(o,R.index),filePath:u,target:R.value,suggestion:`Register intent "${R.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&f)for(let R of A){if(!_e(R.value))continue;let I=e.architectureProfile.resolveLayer(R.value);if(!I)continue;let v=Ce(e.architectureProfile.rules,f,I,{fromPath:typeof u=="string"?u:void 0,layers:e.architectureLayers});if(v){let w=v.rule.peerIsolation?Me(v.peerIsolationReason??"cross-slice",{fromPath:typeof u=="string"?u:void 0,fromSlice:v.fromSlice,toSlice:v.toSlice}):void 0,k=`Layer "${f}" must not reference "${I}" through "${R.value}".`,L=w&&v.peerIsolationReason!=="cross-slice"?`${k} ${w}`:v.rule.message?w?`${v.rule.message} (${w})`:v.rule.message:k;l.push(W("LAYER_REFERENCE_VIOLATION",L,{line:je(o,R.index),filePath:u,target:R.value,fromLayer:f,toLayer:I,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:v.rule,peerIsolationReason:v.peerIsolationReason}}))}}if(e.extensions)for(let R of e.extensions)try{let I=R.analyze(o,a);l.push(...I)}catch(I){l.push(W("EXTENSION_ERROR",`Extension "${R.name}" failed: ${I instanceof Error?I.message:String(I)}`))}if(e.typescript&&g&&f&&e.forbiddenGlobals?.[f]?.length)try{let R=e.forbiddenGlobals[f];l.push(...He(e.typescript,g,R).map(I=>W("FORBIDDEN_GLOBAL",`${f} must not use the ambient global "${I.name}".`,{line:I.line,filePath:u,target:I.name,fromLayer:f,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let I of p??[]){if(I.typeOnly||!I.specifier)continue;let v=Ee(I.specifier,R);v&&l.push(W("FORBIDDEN_GLOBAL",`${f} must not use module "${I.specifier}" because it is the import form of forbidden global "${v}".`,{line:I.line,filePath:u,source:I.specifier,target:I.specifier,fromLayer:f,details:{importKind:I.kind,forbiddenGlobal:v},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(R){l.push(W("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${R instanceof Error?R.message:String(R)}`))}if(e.typescript&&g&&f&&e.capabilityWalls?.[f]?.length)try{let R=new Set(e.capabilityWalls[f]),I=e.forbiddenGlobals?.[f]??[];for(let v of hn(e.typescript,g))R.has(v.capability)&&(v.source==="ambient-global"&&Xe(v.symbol,I)||v.source==="import-based"&&Ee(v.symbol,I)||l.push(W("CAPABILITY_VIOLATION",v.source==="import-based"?`${f} denies the ${v.capability} capability; found import of "${v.symbol}".`:`${f} denies the ${v.capability} capability; found ambient "${v.symbol}".`,{line:v.line,filePath:u,target:v.symbol,capability:v.capability,fromLayer:f,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(R){l.push(W("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${R instanceof Error?R.message:String(R)}`))}if(e.typescript)try{l.push(...wa(e.typescript,o,a,e.architectureProfile))}catch(R){l.push(W("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${R instanceof Error?R.message:String(R)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:l.length===0,violations:l}}}}i(Zr,"createAICodeGate");var Oe={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Qr={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...Oe,default:[]},kernelRoots:{...Oe},managedLayers:{...Oe,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},es={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...Oe,default:[]},managedLayers:{...Oe,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...Oe,default:[]},appliesTo:{...Oe,default:[]}}};function tt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(tt,"isObject");function ts(e){let t=new Set;if(!Array.isArray(e.layers))return t;for(let n of e.layers)tt(n)&&typeof n.name=="string"&&n.name.length>0&&t.add(n.name);return t}i(ts,"declaredLayerNames");function ns(e){if(!tt(e))return e;let t={mode:e.mode===void 0?"advisory":e.mode,compositionRoots:e.compositionRoots===void 0?[]:e.compositionRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,requireDeclarations:e.requireDeclarations===void 0?!0:e.requireDeclarations};return e.kernelRoots!==void 0&&(t.kernelRoots=e.kernelRoots),e.ignoreDirectNewForErrors!==void 0&&(t.ignoreDirectNewForErrors=e.ignoreDirectNewForErrors),{...e,...t}}i(ns,"defaultedArkRun");function rs(e){if(!tt(e))return e;let t=typeof e.maxXiKeys=="number"&&e.maxXiKeys>0?e.maxXiKeys:7;return{...e,mode:e.mode===void 0?"advisory":e.mode,planeRoots:e.planeRoots===void 0?[]:e.planeRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,maxXiKeys:t,xiKeys:e.xiKeys===void 0?[]:e.xiKeys}}i(rs,"defaultedArkOrder");function ss(e,t){let n=e.arkRun;if(n===void 0||!tt(n))return;let r=ts(e),s=n.managedLayers;if(Array.isArray(s)&&s.forEach((o,a)=>{typeof o=="string"&&o.length>0&&!r.has(o)&&t.push({path:`$.arkRun.managedLayers[${a}]`,message:`layer ${JSON.stringify(o)} is not declared in layers[]`})}),n.mode==="enforced"){let o=n.kernelRoots??n.compositionRoots;(!Array.isArray(o)||o.length===0)&&t.push({path:n.kernelRoots!==void 0?"$.arkRun.kernelRoots":"$.arkRun.compositionRoots",message:"ARKRUN_MISSING_ROOT: enforced mode requires at least one kernel root"}),(!Array.isArray(s)||s.length===0)&&t.push({path:"$.arkRun.managedLayers",message:"enforced mode requires at least one managed layer"})}}i(ss,"validateArkRunExtra");function os(e,t){let n=e.arkOrder;if(n===void 0||!tt(n))return;let r=ts(e),s=n.managedLayers;if(Array.isArray(s)&&s.forEach((o,a)=>{typeof o=="string"&&o.length>0&&!r.has(o)&&t.push({path:`$.arkOrder.managedLayers[${a}]`,message:`layer ${JSON.stringify(o)} is not declared in layers[]`})}),n.mode==="enforced"){let o=n.planeRoots;(!Array.isArray(o)||o.length===0)&&t.push({path:"$.arkOrder.planeRoots",message:"ARKORDER_MISSING_PLANE: enforced mode requires at least one plane root"}),(!Array.isArray(s)||s.length===0)&&t.push({path:"$.arkOrder.managedLayers",message:"enforced mode requires at least one managed layer"})}}i(os,"validateArkOrderExtra");var re="1.3",_t="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",as=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Da=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Ma(){let e=[];for(let t of as)for(let n of as)t===n||Da.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}i(Ma,"createDefaultRules");var Ot=Ma(),bn=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"},{from:"1.1",to:"1.2"},{from:"1.2",to:"1.3"}],ie={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},vn={$schema:"https://json-schema.org/draft/2020-12/schema",$id:_t,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:_t,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:re,default:re},name:{type:"string",minLength:1},include:{...ie,minItems:1,default:["src"]},exclude:{...ie,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:Ot,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...ie,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},coverage:{$ref:"#/$defs/coverage"},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},arkRun:{$ref:"#/$defs/arkRun"},arkOrder:{$ref:"#/$defs/arkOrder"},stewards:{...ie,default:[]}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...ie,minItems:1},exclude:ie,intentPrefixes:ie,description:{type:"string",minLength:1},forbiddenGlobals:ie,capabilities:{type:"object",additionalProperties:!1,properties:{deny:{type:"array",uniqueItems:!0,items:{type:"string",enum:["network","filesystem","clock","randomness","environment","process","persistence"]}}}},pure:{type:"boolean"},mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"},reserved:{type:"boolean"},allowEmpty:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...ie,minItems:1},sharedRoots:{...ie,minItems:1},allowedCrossSlice:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}},coverage:{type:"object",additionalProperties:!1,description:"Invariant coverage scan controls. testGlobs replaces the built-in test-name heuristic; maxFiles raises or lowers the evidence file budget and also bounds structural-hint preload for orchestration-only, thin-adapter, and writes-via-aggregate (default 400; there is no arkrules.hintBudget); coverageRoots declares where the project runs its tests, so a covering test found outside them is reported instead of silently certifying an invariant.",properties:{testGlobs:{...ie,minItems:1},maxFiles:{type:"integer",minimum:1,description:"Evidence file budget (default 400) and structural-hint preload cap for orchestration-only, thin-adapter, and writes-via-aggregate. Raise this when hinted/governed counts show truncated sensors. There is no separate arkrules.hintBudget."},coverageRoots:{...ie,minItems:1}}},arkRun:Qr,arkOrder:es}},ge=class extends Error{static{i(this,"ArkConfigValidationError")}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 Yr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(Yr,"isObject");function bt(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}i(bt,"propertyPath");function Ve(e){return e===null?"null":Array.isArray(e)?"array":typeof e}i(Ve,"valueType");function ma(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}i(ma,"resolveSchemaRef");function rt(e,t,n,r,s){if(t.$ref){let o=ma(t.$ref,r);if(!o){s.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}rt(e,o,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(o=>Object.is(o,e))){s.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!Yr(e)){s.push({path:n,message:`must be an object; received ${Ve(e)}`});return}let o=t.properties??{};for(let a of t.required??[])e[a]===void 0&&s.push({path:bt(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in o||s.push({path:bt(n,a),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let a=t.additionalProperties;for(let l of Object.keys(e))l in o||rt(e[l],a,bt(n,l),r,s)}for(let[a,l]of Object.entries(o))e[a]!==void 0&&rt(e[a],l,bt(n,a),r,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:n,message:`must be an array; received ${Ve(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 o=e.map(a=>JSON.stringify(a));new Set(o).size!==o.length&&s.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((o,a)=>rt(o,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 ${Ve(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 ${Ve(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){s.push({path:n,message:`must be an integer; received ${Ve(e)}`});return}t.minimum!==void 0&&e<t.minimum&&s.push({path:n,message:`must be at least ${t.minimum}`})}}i(rt,"validateNode");function ga(e){let t={...e,$schema:e.$schema===void 0?Ct:e.$schema,schemaVersion:e.schemaVersion===void 0?se:e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?Ot.map(n=>({...n})):e.rules};return e.arkRun!==void 0&&(t.arkRun=Gr(e.arkRun)),e.arkOrder!==void 0&&(t.arkOrder=Br(e.arkOrder)),t}i(ga,"defaultedConfig");function ya(e){return e===se?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}i(ya,"migratedFromOf");function ha(){let e=new Set([se]);for(let t of Rn)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}i(ha,"knownInputVersions");function Aa(e,t="ark.config.json"){if(!Yr(e))throw new ge(t,[{path:"$",message:`must be an object; received ${Ve(e)}`}]);let n=ha(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new ge(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected ${se}`}]);if(r!=="unversioned"&&!n.has(r))throw new ge(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${se}`}]);let s=r,o={...e},a=0;for(;s!==se&&a<Rn.length+1;){a+=1;let l=Rn.find(c=>c.from===s);if(!l)throw new ge(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(s)}; expected ${se}`}]);s=l.to,o.schemaVersion=s}if(s!==se)throw new ge(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${se}`}]);return{candidate:ga(o),migratedFrom:ya(r)}}i(Aa,"migrateArkConfig");function _t(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=Aa(e,t),s=[];if(rt(n,kn,"$",kn,s),zr(n,s),qr(n,s),s.length>0)throw new ge(t,s);return{config:n,migratedFrom:r}}i(_t,"loadArkConfigContract");function En(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new ge(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return _t(n,t)}i(En,"parseArkConfigJson");function Jr(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:Ct,schemaVersion:se};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}i(Jr,"withArkConfigMetadata");function Ra(e){return e.endsWith(".")?e:`${e}.`}i(Ra,"normalizePrefix");function ka(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}i(ka,"byLongestPrefix");function Tt(e){let t=e.layers.map(s=>({...s,prefixes:s.prefixes.map(Ra)})),n=[...t].sort(ka),r=[...e.rules??[]];return{name:e.name,layers:t,rules:r,resolveLayer(s){return t.find(o=>o.match?.(s))?.name??n.find(o=>o.prefixes.some(a=>s.startsWith(a)))?.name}}}i(Tt,"createArchitectureProfile");function Xr(e,t={}){return Tt({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??[]})}i(Xr,"createArchitectureProfileFromArkConfig");var Ea=[{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}],xt=Tt({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:Ea,rules:Ot.map(e=>({...e}))}),Ia={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 Zr(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return Jr({include:e.include??[t],layers:xt.layers.map(s=>({name:s.name,patterns:(Ia[s.name]??[s.name]).map(o=>`${r}${o}/**`),intentPrefixes:s.prefixes,optional:n})),rules:[...xt.rules]})}i(Zr,"createElevenLayerArkConfig");function J(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")}`}i(J,"deterministicHash");function V(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(V).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${V(t[n])}`).join(",")}}`}i(V,"stableSerialize");var _e="1.2";var Qr=["network","filesystem","clock","randomness","environment","process","persistence"];function Y(e,t){let n=V(e),r=V(t);return n<r?-1:n>r?1:0}i(Y,"compareCanonical");function X(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}i(X,"sortedUnique");function st(e){let t={schemaVersion:"1.2",include:X(e.include??[]),exclude:X(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:X(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:X(n.patterns??[]),exclude:X(n.exclude??[]),forbiddenGlobals:X(n.forbiddenGlobals??[]),intentPrefixes:X(n.intentPrefixes??[]),capabilityDeny:X(n.capabilities?.deny??[]),pure:n.pure===!0})).sort(Y),safety:{maxTsSuppressions:e.safety?.maxTsSuppressions??0,maxAnyCasts:e.safety?.maxAnyCasts??0,allowInMemory:e.safety?.allowInMemory===!0,allowDisabledPeerIsolation:e.safety?.allowDisabledPeerIsolation===!0},...e.arkRun?{arkRun:{mode:e.arkRun.mode,compositionRoots:X(e.arkRun.compositionRoots),managedLayers:X(e.arkRun.managedLayers),requireDeclarations:e.arkRun.requireDeclarations===!0}}:{}};return J(V(t))}i(st,"resolvedFactsEvidenceRequirementsHash");function va(e){let t=e.completenessReasons.map(k=>({code:k.code,message:k.message,...k.file?{file:k.file}:{}})).sort(Y),n=e.files.map(k=>({...k,typeOnlyExportNames:X(k.typeOnlyExportNames)})).sort((k,T)=>k.path<T.path?-1:k.path>T.path?1:0),r=e.dependencies.map(k=>({...k,...k.namedBindings?{namedBindings:X(k.namedBindings)}:{}})).sort(Y),s=e.capabilityUses.map(k=>({...k})).sort(Y),o=e.ambientUses.map(k=>({...k})).sort(Y),a=e.publishCalls.map(k=>({...k})).sort(Y),l=e.intentReferences.map(k=>({...k})).sort(Y),c=e.safetyUses.map(k=>({...k})).sort(Y),u=(e.classShapes??[]).map(k=>({...k,mutatingMethods:[...k.mutatingMethods??[]].map(T=>({...T}))})).sort(Y),m=(e.arkRunKernelCalls??[]).map(k=>({...k})).sort(Y),y=(e.arkRunManagedNews??[]).map(k=>({...k})).sort(Y),g=(e.arkRunCompositionRootHits??[]).map(k=>({...k})).sort(Y),p=(e.arkRunDeclarations??[]).map(k=>({...k,uses:X(k.uses),reactsTo:X(k.reactsTo),raises:X(k.raises),sends:X(k.sends)})).sort(Y),f=(e.arkOrderPlaneCalls??[]).map(k=>({...k})).sort(Y),A=(e.arkOrderGenericUpdates??[]).map(k=>({...k})).sort(Y),v=(e.arkOrderRootHits??[]).map(k=>({...k})).sort(Y),_=(e.arkOrderXiFieldWrites??[]).map(k=>({...k})).sort(Y),R=(e.arkOrderIngestWritesXi??[]).map(k=>({...k})).sort(Y),I=(e.arkOrderReleaseKeyCounts??[]).map(k=>({...k})).sort(Y),b=e.files.map(({path:k,contentHash:T})=>({path:k,contentHash:T})).sort((k,T)=>k.path<T.path?-1:k.path>T.path?1:0),D=J(V(b));return{schemaVersion:"1.2",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:D,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:r,capabilityUses:s,ambientUses:o,publishCalls:a,intentReferences:l,safetyUses:c,classShapes:u,arkRunKernelCalls:m,arkRunManagedNews:y,arkRunCompositionRootHits:g,arkRunDeclarations:p,arkOrderPlaneCalls:f,arkOrderGenericUpdates:A,arkOrderRootHits:v,arkOrderXiFieldWrites:_,arkOrderIngestWritesXi:R,arkOrderReleaseKeyCounts:I}}i(va,"canonicalResolvedFactsInput");function es(e){let t=va(e);return{...t,factsHash:J(V(t))}}i(es,"createCanonicalResolvedCandidateFacts");function In(e){return es(ns($(e,"$"),!1))}i(In,"createResolvedCandidateFacts");function $(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}i($,"asRecord");function U(e,t,n){let r=new Set(t),s=Object.keys(e).find(o=>!r.has(o));if(s)throw new Error(`${n}.${s} is not part of schema ${"1.2"}.`)}i(U,"assertOnlyKeys");function F(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}i(F,"requiredText");function ye(e,t,n){if(e[t]!==void 0)return F(e,t,n)}i(ye,"optionalText");function G(e,t,n){let r=F(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 o=[];for(let l of s.split("/"))if(!(!l||l==="."))if(l===".."){if(o.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);o.pop()}else o.push(l);let a=o.join("/");if(!a||a!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return a}i(G,"requiredProjectPath");function B(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}i(B,"requiredBoolean");function ts(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)}i(ts,"requiredInteger");function Q(e,t,n){let r=ts(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}i(Q,"requiredPositiveInteger");function z(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}i(z,"requiredArray");function he(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}i(he,"enumValue");function Ue(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]}i(Ue,"parseStringArray");function Sa(e,t,n){let r=new Set;for(let s of e){let o=t(s);if(r.has(o))throw new Error(`${n} must not contain duplicate facts (${o}).`);r.add(o)}}i(Sa,"assertUnique");function ns(e,t){U(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","classShapes","arkRunKernelCalls","arkRunManagedNews","arkRunCompositionRootHits","arkRunDeclarations","arkOrderPlaneCalls","arkOrderGenericUpdates","arkOrderRootHits","arkOrderXiFieldWrites","arkOrderIngestWritesXi","arkOrderReleaseKeyCounts",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=he(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=he(e,"completeness",["complete","partial","unavailable"],"$"),s=z(e,"completenessReasons","$").map((S,C)=>{let h=`$.completenessReasons[${C}]`,d=$(S,h);U(d,["code","message","file"],h);let P=d.file===void 0?void 0:G(d,"file",h);return{code:F(d,"code",h),message:F(d,"message",h),...P?{file:P}:{}}});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 o=z(e,"files","$").map((S,C)=>{let h=`$.files[${C}]`,d=$(S,h);return U(d,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],h),{path:G(d,"path",h),contentHash:F(d,"contentHash",h),parseStatus:he(d,"parseStatus",["parsed","invalid"],h),parseDiagnosticCount:ts(d,"parseDiagnosticCount",h),exportsOnlyTypes:B(d,"exportsOnlyTypes",h),typeOnlyExportNames:Ue(d.typeOnlyExportNames,`${h}.typeOnlyExportNames`),hasTopLevelSideEffects:B(d,"hasTopLevelSideEffects",h)}}),a=z(e,"dependencies","$").map((S,C)=>{let h=`$.dependencies[${C}]`,d=$(S,h);U(d,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],h);let P=ye(d,"specifier",h),j=ye(d,"target",h),ie=he(d,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],h);if(ie==="resolved-project"&&!j)throw new Error(`${h}.target is required for resolved-project dependencies.`);if(ie!=="resolved-project"&&j)throw new Error(`${h}.target is only allowed for resolved-project dependencies.`);if(ie!=="dynamic"&&!P)throw new Error(`${h}.specifier is required unless resolution is dynamic.`);return{from:G(d,"from",h),...P?{specifier:P}:{},kind:he(d,"kind",["import","export","dynamic-import","require"],h),typeOnly:B(d,"typeOnly",h),line:Q(d,"line",h),resolution:ie,...j?{target:G(d,"target",h)}:{},...d.namedBindings!==void 0?{namedBindings:Ue(d.namedBindings,`${h}.namedBindings`)}:{},...d.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:B(d,"targetTypeOnlyExports",h)}:{},...d.sourcePureTypeModule!==void 0?{sourcePureTypeModule:B(d,"sourcePureTypeModule",h)}:{},...d.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:B(d,"namedBindingsTypeOnly",h)}:{},...d.portProofEligible!==void 0?{portProofEligible:B(d,"portProofEligible",h)}:{}}}),l=z(e,"capabilityUses","$").map((S,C)=>{let h=`$.capabilityUses[${C}]`,d=$(S,h);return U(d,["file","line","symbol","capability","source"],h),{file:G(d,"file",h),line:Q(d,"line",h),symbol:F(d,"symbol",h),capability:he(d,"capability",Qr,h),source:he(d,"source",["ambient-global","import-based"],h)}}),c=z(e,"ambientUses","$").map((S,C)=>{let h=`$.ambientUses[${C}]`,d=$(S,h);return U(d,["file","line","symbol"],h),{file:G(d,"file",h),line:Q(d,"line",h),symbol:F(d,"symbol",h)}}),u=z(e,"publishCalls","$").map((S,C)=>{let h=`$.publishCalls[${C}]`,d=$(S,h);U(d,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],h);let P=ye(d,"rawIntentName",h),j=ye(d,"sourceIntent",h);return{file:G(d,"file",h),line:Q(d,"line",h),...P?{rawIntentName:P}:{},objectHasIntent:B(d,"objectHasIntent",h),arkPublishCandidate:B(d,"arkPublishCandidate",h),hasSource:B(d,"hasSource",h),...j?{sourceIntent:j}:{}}}),m=z(e,"intentReferences","$").map((S,C)=>{let h=`$.intentReferences[${C}]`,d=$(S,h);return U(d,["file","line","intent"],h),{file:G(d,"file",h),line:Q(d,"line",h),intent:F(d,"intent",h)}}),y=z(e,"safetyUses","$").map((S,C)=>{let h=`$.safetyUses[${C}]`,d=$(S,h);U(d,["file","line","kind","symbol"],h);let P=ye(d,"symbol",h),j=he(d,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],h);if(j==="in-memory-store"&&!P)throw new Error(`${h}.symbol is required for in-memory-store facts.`);if(j!=="in-memory-store"&&P)throw new Error(`${h}.symbol is only allowed for in-memory-store facts.`);return{file:G(d,"file",h),line:Q(d,"line",h),kind:j,...P?{symbol:P}:{}}});Sa(o,S=>S.path,"$.files");let g=new Set(o.map(S=>S.path));for(let S of o){if(S.parseStatus==="parsed"&&S.parseDiagnosticCount!==0)throw new Error(`$.files[${S.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(S.parseStatus==="invalid"&&S.parseDiagnosticCount===0)throw new Error(`$.files[${S.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&o.some(S=>S.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let S of a)if(!g.has(S.from))throw new Error(`$.dependencies references missing source file ${S.from}.`);let f=(e.arkRunKernelCalls===void 0?[]:z(e,"arkRunKernelCalls","$")).map((S,C)=>{let h=`$.arkRunKernelCalls[${C}]`,d=$(S,h);U(d,["file","line","kind","callee","viaImport","receiver","nameLiteral"],h);let P=ye(d,"receiver",h),j=ye(d,"nameLiteral",h);return{file:G(d,"file",h),line:Q(d,"line",h),kind:he(d,"kind",["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"],h),callee:F(d,"callee",h),viaImport:B(d,"viaImport",h),...P?{receiver:P}:{},...j?{nameLiteral:j}:{}}}),v=(e.arkRunManagedNews===void 0?[]:z(e,"arkRunManagedNews","$")).map((S,C)=>{let h=`$.arkRunManagedNews[${C}]`,d=$(S,h);U(d,["file","line","typeName","importedFrom"],h);let P=ye(d,"importedFrom",h);return{file:G(d,"file",h),line:Q(d,"line",h),typeName:F(d,"typeName",h),...P?{importedFrom:P}:{}}}),R=(e.arkRunCompositionRootHits===void 0?[]:z(e,"arkRunCompositionRootHits","$")).map((S,C)=>{let h=`$.arkRunCompositionRootHits[${C}]`,d=$(S,h);return U(d,["file","matchedRoot","hasKernelFactory"],h),{file:G(d,"file",h),matchedRoot:F(d,"matchedRoot",h),hasKernelFactory:B(d,"hasKernelFactory",h)}}),I=e.arkRunDeclarations===void 0?[]:z(e,"arkRunDeclarations","$"),D=(e.arkOrderPlaneCalls===void 0?[]:z(e,"arkOrderPlaneCalls","$")).map((S,C)=>{let h=`$.arkOrderPlaneCalls[${C}]`,d=$(S,h);return U(d,["file","line","callee"],h),{file:G(d,"file",h),line:Q(d,"line",h),callee:F(d,"callee",h)}}),T=(e.arkOrderGenericUpdates===void 0?[]:z(e,"arkOrderGenericUpdates","$")).map((S,C)=>{let h=`$.arkOrderGenericUpdates[${C}]`,d=$(S,h);return U(d,["file","line","method"],h),{file:G(d,"file",h),line:Q(d,"line",h),method:F(d,"method",h)}}),x=(e.arkOrderRootHits===void 0?[]:z(e,"arkOrderRootHits","$")).map((S,C)=>{let h=`$.arkOrderRootHits[${C}]`,d=$(S,h);return U(d,["file","matchedRoot","hasPlaneFactory"],h),{file:G(d,"file",h),matchedRoot:F(d,"matchedRoot",h),hasPlaneFactory:B(d,"hasPlaneFactory",h)}}),M=(e.arkOrderXiFieldWrites===void 0?[]:z(e,"arkOrderXiFieldWrites","$")).map((S,C)=>{let h=`$.arkOrderXiFieldWrites[${C}]`,d=$(S,h);return U(d,["file","line","key"],h),{file:G(d,"file",h),line:Q(d,"line",h),key:F(d,"key",h)}}),pe=(e.arkOrderIngestWritesXi===void 0?[]:z(e,"arkOrderIngestWritesXi","$")).map((S,C)=>{let h=`$.arkOrderIngestWritesXi[${C}]`,d=$(S,h);return U(d,["file","line"],h),{file:G(d,"file",h),line:Q(d,"line",h)}}),We=(e.arkOrderReleaseKeyCounts===void 0?[]:z(e,"arkOrderReleaseKeyCounts","$")).map((S,C)=>{let h=`$.arkOrderReleaseKeyCounts[${C}]`,d=$(S,h);return U(d,["file","line","keyCount"],h),{file:G(d,"file",h),line:Q(d,"line",h),keyCount:Q(d,"keyCount",h)}}),Ye=I.map((S,C)=>{let h=`$.arkRunDeclarations[${C}]`,d=$(S,h);return U(d,["file","line","uses","reactsTo","raises","sends"],h),{file:G(d,"file",h),line:Q(d,"line",h),uses:Ue(d.uses,`${h}.uses`),reactsTo:Ue(d.reactsTo,`${h}.reactsTo`),raises:Ue(d.raises,`${h}.raises`),sends:Ue(d.sends,`${h}.sends`)}});for(let[S,C]of[["$.capabilityUses",l],["$.ambientUses",c],["$.publishCalls",u],["$.intentReferences",m],["$.safetyUses",y],["$.arkRunKernelCalls",f],["$.arkRunManagedNews",v],["$.arkRunCompositionRootHits",R],["$.arkRunDeclarations",Ye],["$.arkOrderPlaneCalls",D],["$.arkOrderGenericUpdates",T],["$.arkOrderRootHits",x],["$.arkOrderXiFieldWrites",M],["$.arkOrderIngestWritesXi",pe],["$.arkOrderReleaseKeyCounts",We]])for(let h of C)if(!g.has(h.file))throw new Error(`${S} references missing file ${h.file}.`);let Se=ye(e,"projectPackageName","$"),en=(e.classShapes===void 0?[]:z(e,"classShapes","$")).map((S,C)=>{let h=`$.classShapes[${C}]`,d=$(S,h);U(d,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],h);let P=z(d,"mutatingMethods",h).map((j,ie)=>{let Rt=`${h}.mutatingMethods[${ie}]`,tn=$(j,Rt);return U(tn,["name","referencesGuardOrPublish"],Rt),{name:F(tn,"name",Rt),referencesGuardOrPublish:B(tn,"referencesGuardOrPublish",Rt)}});return{file:G(d,"file",h),className:F(d,"className",h),exported:B(d,"exported",h),hasPublicMutableFields:B(d,"hasPublicMutableFields",h),hasPublicSetters:B(d,"hasPublicSetters",h),hasPublicConstructor:B(d,"hasPublicConstructor",h),hasStaticFactory:B(d,"hasStaticFactory",h),mutatingMethods:P,...d.dataOnly===void 0?{}:{dataOnly:B(d,"dataOnly",h)}}});return{schemaVersion:n,completeness:r,completenessReasons:s,resolverIdentity:F(e,"resolverIdentity","$"),compilerIdentity:F(e,"compilerIdentity","$"),compilerOptionsHash:F(e,"compilerOptionsHash","$"),tsconfigHash:F(e,"tsconfigHash","$"),evidenceRequirementsHash:F(e,"evidenceRequirementsHash","$"),...Se?{projectPackageName:Se}:{},files:o,dependencies:a,capabilityUses:l,ambientUses:c,publishCalls:u,intentReferences:m,safetyUses:y,classShapes:en,arkRunKernelCalls:f,arkRunManagedNews:v,arkRunCompositionRootHits:R,arkRunDeclarations:Ye,arkOrderPlaneCalls:D,arkOrderGenericUpdates:T,arkOrderRootHits:x,arkOrderXiFieldWrites:M,arkOrderIngestWritesXi:pe,arkOrderReleaseKeyCounts:We}}i(ns,"parseResolvedFactsInput");function Ie(e){let t=$(e,"$"),n=F(t,"factsHash","$"),r=F(t,"candidateTreeHash","$"),s=es(ns(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}i(Ie,"loadResolvedCandidateFacts");var ba=["network","filesystem","clock","randomness","environment","process","persistence"],N={type:"string",minLength:1},ne={type:"integer",minimum:1},q={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},vn={$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","1.2"]},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:N,message:N,file:q}}},resolverIdentity:N,compilerIdentity:N,compilerOptionsHash:N,tsconfigHash:N,candidateTreeHash:N,evidenceRequirementsHash:N,projectPackageName:N,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:q,contentHash:N,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:N},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:N,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:ne,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:q,namedBindings:{type:"array",items:N},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:ne,symbol:N,capability:{enum:ba},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:q,line:ne,symbol:N}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:q,line:ne,rawIntentName:N,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:N}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:q,line:ne,intent:N}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:q,line:ne,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:N},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:N,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:N,referencesGuardOrPublish:{type:"boolean"}}}}}}},arkRunKernelCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind","callee","viaImport"],properties:{file:q,line:ne,kind:{enum:["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"]},callee:N,viaImport:{type:"boolean"},receiver:N,nameLiteral:N}}},arkRunManagedNews:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","typeName"],properties:{file:q,line:ne,typeName:N,importedFrom:N}}},arkRunCompositionRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasKernelFactory"],properties:{file:q,matchedRoot:N,hasKernelFactory:{type:"boolean"}}}},arkRunDeclarations:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","uses","reactsTo","raises","sends"],properties:{file:q,line:ne,uses:{type:"array",items:N},reactsTo:{type:"array",items:N},raises:{type:"array",items:N},sends:{type:"array",items:N}}}},arkOrderPlaneCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","callee"],properties:{file:q,line:ne,callee:N}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:q,line:ne,method:N}}},arkOrderRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasPlaneFactory"],properties:{file:q,matchedRoot:N,hasPlaneFactory:{type:"boolean"}}}},arkOrderXiFieldWrites:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:q,line:ne,key:N}}},arkOrderIngestWritesXi:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line"],properties:{file:q,line:ne}}},arkOrderReleaseKeyCounts:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","keyCount"],properties:{file:q,line:ne,keyCount:{type:"integer",minimum:1}}}},factsHash:N},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 Sn="1.0";function oe(e){return`${e.from}->${e.to}`}i(oe,"dependencyKey");function ot(e,t,n,r="dependency"){return{id:`${e}:${r}:${oe(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${oe(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${oe(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${oe(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${oe(t)} from the candidate, then preflight again.`}:{}}}i(ot,"dependencyFinding");function Ke(e){let t=[],n=new Map(e.changeMap.map.files.map(g=>[g.path,g])),r=new Map(e.changes.map(g=>[g.path,g])),s=new Map(e.changeMap.map.dependencies.map(g=>[oe(g),g])),o=new Map(e.baseDependencies.map(g=>[oe(g),g])),a=new Map(e.candidateDependencies.map(g=>[oe(g),g]));for(let g of[...n.values()].sort((p,f)=>p.path.localeCompare(f.path))){let p=r.get(g.path);p?p.operation!==g.operation?t.push({id:`contradictory:file:${g.path}`,classification:"contradictory",subject:"file",path:g.path,expectedOperation:g.operation,actualOperation:p.operation,message:`${g.path} was planned as ${g.operation} but the actual operation is ${p.operation}.`,nextAction:`Change ${g.path} to the planned ${g.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${g.path}`,classification:"satisfied",subject:"file",path:g.path,expectedOperation:g.operation,actualOperation:p.operation,message:`${g.path} matches the planned ${g.operation} operation.`}):t.push({id:`missing:file:${g.path}`,classification:"missing",subject:"file",path:g.path,expectedOperation:g.operation,message:`${g.path} was planned as ${g.operation} but is absent from the actual change.`,nextAction:`${g.operation[0].toUpperCase()}${g.operation.slice(1)} ${g.path} in the complete change set, then preflight again.`})}for(let g of[...r.values()].sort((p,f)=>p.path.localeCompare(f.path)))n.has(g.path)||t.push({id:`unplanned:file:${g.path}`,classification:"unplanned",subject:"file",path:g.path,actualOperation:g.operation,message:`${g.path} has an unplanned ${g.operation} operation.`,nextAction:`Remove ${g.path} from the change set, then preflight again.`});let l=new Set;for(let g of[...s.values()].sort((p,f)=>oe(p).localeCompare(oe(f)))){if(a.has(oe(g))){t.push(ot("satisfied",g,`${g.from} -> ${g.to} exists in the candidate architecture.`));continue}let p={from:g.to,to:g.from};a.has(oe(p))?(l.add(oe(p)),t.push(ot("contradictory",g,`${g.from} -> ${g.to} was planned, but the candidate contains the reverse edge.`))):t.push(ot("missing",g,`${g.from} -> ${g.to} is absent from the candidate architecture.`))}let c=new Set([...n.keys(),...r.keys()]);for(let[g,p]of[...a].sort(([f],[A])=>f.localeCompare(A)))o.has(g)||s.has(g)||l.has(g)||!c.has(p.from)&&!c.has(p.to)||t.push({...ot("unplanned",p,`${p.from} -> ${p.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let u=new Set(e.changeMap.map.files.filter(g=>g.operation==="delete").map(g=>g.path));for(let[g,p]of[...o].sort(([f],[A])=>f.localeCompare(A)))a.has(g)||u.has(p.from)||u.has(p.to)||!c.has(p.from)&&!c.has(p.to)||t.push({...ot("unplanned",p,`${p.from} -> ${p.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let m={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((g,p)=>m[g.classification]-m[p.classification]||(g.subject===p.subject?0:g.subject==="file"?-1:1)||g.id.localeCompare(p.id));let y={satisfied:t.filter(g=>g.classification==="satisfied").length,missing:t.filter(g=>g.classification==="missing").length,contradictory:t.filter(g=>g.classification==="contradictory").length,unplanned:t.filter(g=>g.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:y.missing===0&&y.contradictory===0&&y.unplanned===0,behavioralCompletion:"not-evaluated",summary:y,findings:t}}i(Ke,"analyzeArchitectureConvergence");var Ca="1.0",bn="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",os=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","writes-via-aggregate","no-anemic-model","invariant-coverage"],Oa=["no-anemic-model"],rs={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Cn={$schema:"https://json-schema.org/draft/2020-12/schema",$id:bn,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:bn},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:[...os]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:rs,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:rs}}}},xe=class extends Error{static{i(this,"ArkRulesValidationError")}issues;source;constructor(t,n){super(`Invalid ArkRules (${t}):
4
+ `)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function is(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(is,"isObject");function Ct(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}i(Ct,"propertyPath");function Ve(e){return e===null?"null":Array.isArray(e)?"array":typeof e}i(Ve,"valueType");function Fa(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}i(Fa,"resolveSchemaRef");function nt(e,t,n,r,s){if(t.$ref){let o=Fa(t.$ref,r);if(!o){s.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}nt(e,o,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(o=>Object.is(o,e))){s.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!is(e)){s.push({path:n,message:`must be an object; received ${Ve(e)}`});return}let o=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 o||s.push({path:Ct(n,a),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let a=t.additionalProperties;for(let l of Object.keys(e))l in o||nt(e[l],a,Ct(n,l),r,s)}for(let[a,l]of Object.entries(o))e[a]!==void 0&&nt(e[a],l,Ct(n,a),r,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:n,message:`must be an array; received ${Ve(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 o=e.map(a=>JSON.stringify(a));new Set(o).size!==o.length&&s.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((o,a)=>nt(o,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 ${Ve(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 ${Ve(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){s.push({path:n,message:`must be an integer; received ${Ve(e)}`});return}t.minimum!==void 0&&e<t.minimum&&s.push({path:n,message:`must be at least ${t.minimum}`})}}i(nt,"validateNode");function $a(e){let t={...e,$schema:e.$schema===void 0?_t:e.$schema,schemaVersion:e.schemaVersion===void 0?re:e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?Ot.map(n=>({...n})):e.rules};return e.arkRun!==void 0&&(t.arkRun=ns(e.arkRun)),e.arkOrder!==void 0&&(t.arkOrder=rs(e.arkOrder)),t}i($a,"defaultedConfig");function Ha(e){return e===re?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}i(Ha,"migratedFromOf");function ja(){let e=new Set([re]);for(let t of bn)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}i(ja,"knownInputVersions");function Va(e,t="ark.config.json"){if(!is(e))throw new ge(t,[{path:"$",message:`must be an object; received ${Ve(e)}`}]);let n=ja(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new ge(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected ${re}`}]);if(r!=="unversioned"&&!n.has(r))throw new ge(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${re}`}]);let s=r,o={...e},a=0;for(;s!==re&&a<bn.length+1;){a+=1;let l=bn.find(c=>c.from===s);if(!l)throw new ge(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(s)}; expected ${re}`}]);s=l.to,o.schemaVersion=s}if(s!==re)throw new ge(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${re}`}]);return{candidate:$a(o),migratedFrom:Ha(r)}}i(Va,"migrateArkConfig");function xt(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=Va(e,t),s=[];if(nt(n,vn,"$",vn,s),ss(n,s),os(n,s),s.length>0)throw new ge(t,s);return{config:n,migratedFrom:r}}i(xt,"loadArkConfigContract");function Cn(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new ge(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return xt(n,t)}i(Cn,"parseArkConfigJson");function ls(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:_t,schemaVersion:re};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}i(ls,"withArkConfigMetadata");function Ua(e){return e.endsWith(".")?e:`${e}.`}i(Ua,"normalizePrefix");function Ka(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}i(Ka,"byLongestPrefix");function Nt(e){let t=e.layers.map(s=>({...s,prefixes:s.prefixes.map(Ua)})),n=[...t].sort(Ka),r=[...e.rules??[]];return{name:e.name,layers:t,rules:r,resolveLayer(s){return t.find(o=>o.match?.(s))?.name??n.find(o=>o.prefixes.some(a=>s.startsWith(a)))?.name}}}i(Nt,"createArchitectureProfile");function cs(e,t={}){return Nt({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??[]})}i(cs,"createArchitectureProfileFromArkConfig");var Ga=[{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}],Tt=Nt({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:Ga,rules:Ot.map(e=>({...e}))}),Ba={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 ds(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return ls({include:e.include??[t],layers:Tt.layers.map(s=>({name:s.name,patterns:(Ba[s.name]??[s.name]).map(o=>`${r}${o}/**`),intentPrefixes:s.prefixes,optional:n})),rules:[...Tt.rules]})}i(ds,"createElevenLayerArkConfig");function X(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")}`}i(X,"deterministicHash");function H(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(H).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${H(t[n])}`).join(",")}}`}i(H,"stableSerialize");var xe="1.2";var us=["network","filesystem","clock","randomness","environment","process","persistence"];function q(e,t){let n=H(e),r=H(t);return n<r?-1:n>r?1:0}i(q,"compareCanonical");function J(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}i(J,"sortedUnique");function rt(e){let t={schemaVersion:"1.2",include:J(e.include??[]),exclude:J(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:J(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:J(n.patterns??[]),exclude:J(n.exclude??[]),forbiddenGlobals:J(n.forbiddenGlobals??[]),intentPrefixes:J(n.intentPrefixes??[]),capabilityDeny:J(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},...e.arkRun?{arkRun:{mode:e.arkRun.mode,compositionRoots:J(e.arkRun.compositionRoots),managedLayers:J(e.arkRun.managedLayers),requireDeclarations:e.arkRun.requireDeclarations===!0}}:{}};return X(H(t))}i(rt,"resolvedFactsEvidenceRequirementsHash");function za(e){let t=e.completenessReasons.map(k=>({code:k.code,message:k.message,...k.file?{file:k.file}:{}})).sort(q),n=e.files.map(k=>({...k,typeOnlyExportNames:J(k.typeOnlyExportNames)})).sort((k,L)=>k.path<L.path?-1:k.path>L.path?1:0),r=e.dependencies.map(k=>({...k,...k.namedBindings?{namedBindings:J(k.namedBindings)}:{}})).sort(q),s=e.capabilityUses.map(k=>({...k})).sort(q),o=e.ambientUses.map(k=>({...k})).sort(q),a=e.publishCalls.map(k=>({...k})).sort(q),l=e.intentReferences.map(k=>({...k})).sort(q),c=e.safetyUses.map(k=>({...k})).sort(q),u=(e.classShapes??[]).map(k=>({...k,mutatingMethods:[...k.mutatingMethods??[]].map(L=>({...L}))})).sort(q),f=(e.arkRunKernelCalls??[]).map(k=>({...k})).sort(q),y=(e.arkRunManagedNews??[]).map(k=>({...k})).sort(q),g=(e.arkRunCompositionRootHits??[]).map(k=>({...k})).sort(q),p=(e.arkRunDeclarations??[]).map(k=>({...k,uses:J(k.uses),reactsTo:J(k.reactsTo),raises:J(k.raises),sends:J(k.sends)})).sort(q),m=(e.arkOrderPlaneCalls??[]).map(k=>({...k})).sort(q),A=(e.arkOrderGenericUpdates??[]).map(k=>({...k})).sort(q),S=(e.arkOrderRootHits??[]).map(k=>({...k})).sort(q),O=(e.arkOrderXiFieldWrites??[]).map(k=>({...k})).sort(q),R=(e.arkOrderIngestWritesXi??[]).map(k=>({...k})).sort(q),I=(e.arkOrderReleaseKeyCounts??[]).map(k=>({...k})).sort(q),v=e.files.map(({path:k,contentHash:L})=>({path:k,contentHash:L})).sort((k,L)=>k.path<L.path?-1:k.path>L.path?1:0),w=X(H(v));return{schemaVersion:"1.2",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:w,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:r,capabilityUses:s,ambientUses:o,publishCalls:a,intentReferences:l,safetyUses:c,classShapes:u,arkRunKernelCalls:f,arkRunManagedNews:y,arkRunCompositionRootHits:g,arkRunDeclarations:p,arkOrderPlaneCalls:m,arkOrderGenericUpdates:A,arkOrderRootHits:S,arkOrderXiFieldWrites:O,arkOrderIngestWritesXi:R,arkOrderReleaseKeyCounts:I}}i(za,"canonicalResolvedFactsInput");function ps(e){let t=za(e);return{...t,factsHash:X(H(t))}}i(ps,"createCanonicalResolvedCandidateFacts");function _n(e){return ps(ms(M(e,"$"),!1))}i(_n,"createResolvedCandidateFacts");function M(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}i(M,"asRecord");function j(e,t,n){let r=new Set(t),s=Object.keys(e).find(o=>!r.has(o));if(s)throw new Error(`${n}.${s} is not part of schema ${"1.2"}.`)}i(j,"assertOnlyKeys");function D(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}i(D,"requiredText");function ye(e,t,n){if(e[t]!==void 0)return D(e,t,n)}i(ye,"optionalText");function U(e,t,n){let r=D(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 o=[];for(let l of s.split("/"))if(!(!l||l==="."))if(l===".."){if(o.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);o.pop()}else o.push(l);let a=o.join("/");if(!a||a!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return a}i(U,"requiredProjectPath");function K(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}i(K,"requiredBoolean");function fs(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)}i(fs,"requiredInteger");function Q(e,t,n){let r=fs(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}i(Q,"requiredPositiveInteger");function G(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}i(G,"requiredArray");function he(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}i(he,"enumValue");function Ue(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]}i(Ue,"parseStringArray");function Wa(e,t,n){let r=new Set;for(let s of e){let o=t(s);if(r.has(o))throw new Error(`${n} must not contain duplicate facts (${o}).`);r.add(o)}}i(Wa,"assertUnique");function ms(e,t){j(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","classShapes","arkRunKernelCalls","arkRunManagedNews","arkRunCompositionRootHits","arkRunDeclarations","arkOrderPlaneCalls","arkOrderGenericUpdates","arkOrderRootHits","arkOrderXiFieldWrites","arkOrderIngestWritesXi","arkOrderReleaseKeyCounts",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=he(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=he(e,"completeness",["complete","partial","unavailable"],"$"),s=G(e,"completenessReasons","$").map((b,C)=>{let h=`$.completenessReasons[${C}]`,d=M(b,h);j(d,["code","message","file"],h);let P=d.file===void 0?void 0:U(d,"file",h);return{code:D(d,"code",h),message:D(d,"message",h),...P?{file:P}:{}}});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 o=G(e,"files","$").map((b,C)=>{let h=`$.files[${C}]`,d=M(b,h);return j(d,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],h),{path:U(d,"path",h),contentHash:D(d,"contentHash",h),parseStatus:he(d,"parseStatus",["parsed","invalid"],h),parseDiagnosticCount:fs(d,"parseDiagnosticCount",h),exportsOnlyTypes:K(d,"exportsOnlyTypes",h),typeOnlyExportNames:Ue(d.typeOnlyExportNames,`${h}.typeOnlyExportNames`),hasTopLevelSideEffects:K(d,"hasTopLevelSideEffects",h)}}),a=G(e,"dependencies","$").map((b,C)=>{let h=`$.dependencies[${C}]`,d=M(b,h);j(d,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],h);let P=ye(d,"specifier",h),$=ye(d,"target",h),ae=he(d,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],h);if(ae==="resolved-project"&&!$)throw new Error(`${h}.target is required for resolved-project dependencies.`);if(ae!=="resolved-project"&&$)throw new Error(`${h}.target is only allowed for resolved-project dependencies.`);if(ae!=="dynamic"&&!P)throw new Error(`${h}.specifier is required unless resolution is dynamic.`);return{from:U(d,"from",h),...P?{specifier:P}:{},kind:he(d,"kind",["import","export","dynamic-import","require"],h),typeOnly:K(d,"typeOnly",h),line:Q(d,"line",h),resolution:ae,...$?{target:U(d,"target",h)}:{},...d.namedBindings!==void 0?{namedBindings:Ue(d.namedBindings,`${h}.namedBindings`)}:{},...d.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:K(d,"targetTypeOnlyExports",h)}:{},...d.sourcePureTypeModule!==void 0?{sourcePureTypeModule:K(d,"sourcePureTypeModule",h)}:{},...d.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:K(d,"namedBindingsTypeOnly",h)}:{},...d.portProofEligible!==void 0?{portProofEligible:K(d,"portProofEligible",h)}:{}}}),l=G(e,"capabilityUses","$").map((b,C)=>{let h=`$.capabilityUses[${C}]`,d=M(b,h);return j(d,["file","line","symbol","capability","source"],h),{file:U(d,"file",h),line:Q(d,"line",h),symbol:D(d,"symbol",h),capability:he(d,"capability",us,h),source:he(d,"source",["ambient-global","import-based"],h)}}),c=G(e,"ambientUses","$").map((b,C)=>{let h=`$.ambientUses[${C}]`,d=M(b,h);return j(d,["file","line","symbol"],h),{file:U(d,"file",h),line:Q(d,"line",h),symbol:D(d,"symbol",h)}}),u=G(e,"publishCalls","$").map((b,C)=>{let h=`$.publishCalls[${C}]`,d=M(b,h);j(d,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],h);let P=ye(d,"rawIntentName",h),$=ye(d,"sourceIntent",h);return{file:U(d,"file",h),line:Q(d,"line",h),...P?{rawIntentName:P}:{},objectHasIntent:K(d,"objectHasIntent",h),arkPublishCandidate:K(d,"arkPublishCandidate",h),hasSource:K(d,"hasSource",h),...$?{sourceIntent:$}:{}}}),f=G(e,"intentReferences","$").map((b,C)=>{let h=`$.intentReferences[${C}]`,d=M(b,h);return j(d,["file","line","intent"],h),{file:U(d,"file",h),line:Q(d,"line",h),intent:D(d,"intent",h)}}),y=G(e,"safetyUses","$").map((b,C)=>{let h=`$.safetyUses[${C}]`,d=M(b,h);j(d,["file","line","kind","symbol"],h);let P=ye(d,"symbol",h),$=he(d,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],h);if($==="in-memory-store"&&!P)throw new Error(`${h}.symbol is required for in-memory-store facts.`);if($!=="in-memory-store"&&P)throw new Error(`${h}.symbol is only allowed for in-memory-store facts.`);return{file:U(d,"file",h),line:Q(d,"line",h),kind:$,...P?{symbol:P}:{}}});Wa(o,b=>b.path,"$.files");let g=new Set(o.map(b=>b.path));for(let b of o){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"&&o.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(!g.has(b.from))throw new Error(`$.dependencies references missing source file ${b.from}.`);let m=(e.arkRunKernelCalls===void 0?[]:G(e,"arkRunKernelCalls","$")).map((b,C)=>{let h=`$.arkRunKernelCalls[${C}]`,d=M(b,h);j(d,["file","line","kind","callee","viaImport","receiver","nameLiteral"],h);let P=ye(d,"receiver",h),$=ye(d,"nameLiteral",h);return{file:U(d,"file",h),line:Q(d,"line",h),kind:he(d,"kind",["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"],h),callee:D(d,"callee",h),viaImport:K(d,"viaImport",h),...P?{receiver:P}:{},...$?{nameLiteral:$}:{}}}),S=(e.arkRunManagedNews===void 0?[]:G(e,"arkRunManagedNews","$")).map((b,C)=>{let h=`$.arkRunManagedNews[${C}]`,d=M(b,h);j(d,["file","line","typeName","importedFrom"],h);let P=ye(d,"importedFrom",h);return{file:U(d,"file",h),line:Q(d,"line",h),typeName:D(d,"typeName",h),...P?{importedFrom:P}:{}}}),R=(e.arkRunCompositionRootHits===void 0?[]:G(e,"arkRunCompositionRootHits","$")).map((b,C)=>{let h=`$.arkRunCompositionRootHits[${C}]`,d=M(b,h);return j(d,["file","matchedRoot","hasKernelFactory"],h),{file:U(d,"file",h),matchedRoot:D(d,"matchedRoot",h),hasKernelFactory:K(d,"hasKernelFactory",h)}}),I=e.arkRunDeclarations===void 0?[]:G(e,"arkRunDeclarations","$"),w=(e.arkOrderPlaneCalls===void 0?[]:G(e,"arkOrderPlaneCalls","$")).map((b,C)=>{let h=`$.arkOrderPlaneCalls[${C}]`,d=M(b,h);return j(d,["file","line","callee"],h),{file:U(d,"file",h),line:Q(d,"line",h),callee:D(d,"callee",h)}}),L=(e.arkOrderGenericUpdates===void 0?[]:G(e,"arkOrderGenericUpdates","$")).map((b,C)=>{let h=`$.arkOrderGenericUpdates[${C}]`,d=M(b,h);return j(d,["file","line","method"],h),{file:U(d,"file",h),line:Q(d,"line",h),method:D(d,"method",h)}}),T=(e.arkOrderRootHits===void 0?[]:G(e,"arkOrderRootHits","$")).map((b,C)=>{let h=`$.arkOrderRootHits[${C}]`,d=M(b,h);return j(d,["file","matchedRoot","hasPlaneFactory"],h),{file:U(d,"file",h),matchedRoot:D(d,"matchedRoot",h),hasPlaneFactory:K(d,"hasPlaneFactory",h)}}),F=(e.arkOrderXiFieldWrites===void 0?[]:G(e,"arkOrderXiFieldWrites","$")).map((b,C)=>{let h=`$.arkOrderXiFieldWrites[${C}]`,d=M(b,h);return j(d,["file","line","key"],h),{file:U(d,"file",h),line:Q(d,"line",h),key:D(d,"key",h)}}),fe=(e.arkOrderIngestWritesXi===void 0?[]:G(e,"arkOrderIngestWritesXi","$")).map((b,C)=>{let h=`$.arkOrderIngestWritesXi[${C}]`,d=M(b,h);return j(d,["file","line"],h),{file:U(d,"file",h),line:Q(d,"line",h)}}),we=(e.arkOrderReleaseKeyCounts===void 0?[]:G(e,"arkOrderReleaseKeyCounts","$")).map((b,C)=>{let h=`$.arkOrderReleaseKeyCounts[${C}]`,d=M(b,h);return j(d,["file","line","keyCount"],h),{file:U(d,"file",h),line:Q(d,"line",h),keyCount:Q(d,"keyCount",h)}}),qe=I.map((b,C)=>{let h=`$.arkRunDeclarations[${C}]`,d=M(b,h);return j(d,["file","line","uses","reactsTo","raises","sends"],h),{file:U(d,"file",h),line:Q(d,"line",h),uses:Ue(d.uses,`${h}.uses`),reactsTo:Ue(d.reactsTo,`${h}.reactsTo`),raises:Ue(d.raises,`${h}.raises`),sends:Ue(d.sends,`${h}.sends`)}});for(let[b,C]of[["$.capabilityUses",l],["$.ambientUses",c],["$.publishCalls",u],["$.intentReferences",f],["$.safetyUses",y],["$.arkRunKernelCalls",m],["$.arkRunManagedNews",S],["$.arkRunCompositionRootHits",R],["$.arkRunDeclarations",qe],["$.arkOrderPlaneCalls",w],["$.arkOrderGenericUpdates",L],["$.arkOrderRootHits",T],["$.arkOrderXiFieldWrites",F],["$.arkOrderIngestWritesXi",fe],["$.arkOrderReleaseKeyCounts",we]])for(let h of C)if(!g.has(h.file))throw new Error(`${b} references missing file ${h.file}.`);let ve=ye(e,"projectPackageName","$"),nn=(e.classShapes===void 0?[]:G(e,"classShapes","$")).map((b,C)=>{let h=`$.classShapes[${C}]`,d=M(b,h);j(d,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],h);let P=G(d,"mutatingMethods",h).map(($,ae)=>{let kt=`${h}.mutatingMethods[${ae}]`,rn=M($,kt);return j(rn,["name","referencesGuardOrPublish"],kt),{name:D(rn,"name",kt),referencesGuardOrPublish:K(rn,"referencesGuardOrPublish",kt)}});return{file:U(d,"file",h),className:D(d,"className",h),exported:K(d,"exported",h),hasPublicMutableFields:K(d,"hasPublicMutableFields",h),hasPublicSetters:K(d,"hasPublicSetters",h),hasPublicConstructor:K(d,"hasPublicConstructor",h),hasStaticFactory:K(d,"hasStaticFactory",h),mutatingMethods:P,...d.dataOnly===void 0?{}:{dataOnly:K(d,"dataOnly",h)}}});return{schemaVersion:n,completeness:r,completenessReasons:s,resolverIdentity:D(e,"resolverIdentity","$"),compilerIdentity:D(e,"compilerIdentity","$"),compilerOptionsHash:D(e,"compilerOptionsHash","$"),tsconfigHash:D(e,"tsconfigHash","$"),evidenceRequirementsHash:D(e,"evidenceRequirementsHash","$"),...ve?{projectPackageName:ve}:{},files:o,dependencies:a,capabilityUses:l,ambientUses:c,publishCalls:u,intentReferences:f,safetyUses:y,classShapes:nn,arkRunKernelCalls:m,arkRunManagedNews:S,arkRunCompositionRootHits:R,arkRunDeclarations:qe,arkOrderPlaneCalls:w,arkOrderGenericUpdates:L,arkOrderRootHits:T,arkOrderXiFieldWrites:F,arkOrderIngestWritesXi:fe,arkOrderReleaseKeyCounts:we}}i(ms,"parseResolvedFactsInput");function Ie(e){let t=M(e,"$"),n=D(t,"factsHash","$"),r=D(t,"candidateTreeHash","$"),s=ps(ms(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}i(Ie,"loadResolvedCandidateFacts");var qa=["network","filesystem","clock","randomness","environment","process","persistence"],x={type:"string",minLength:1},te={type:"integer",minimum:1},B={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},On={$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","1.2"]},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:x,message:x,file:B}}},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:B,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:B,specifier:x,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:te,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:B,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:B,line:te,symbol:x,capability:{enum:qa},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:B,line:te,symbol:x}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:B,line:te,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:B,line:te,intent:x}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:B,line:te,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:B,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"}}}}}}},arkRunKernelCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind","callee","viaImport"],properties:{file:B,line:te,kind:{enum:["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"]},callee:x,viaImport:{type:"boolean"},receiver:x,nameLiteral:x}}},arkRunManagedNews:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","typeName"],properties:{file:B,line:te,typeName:x,importedFrom:x}}},arkRunCompositionRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasKernelFactory"],properties:{file:B,matchedRoot:x,hasKernelFactory:{type:"boolean"}}}},arkRunDeclarations:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","uses","reactsTo","raises","sends"],properties:{file:B,line:te,uses:{type:"array",items:x},reactsTo:{type:"array",items:x},raises:{type:"array",items:x},sends:{type:"array",items:x}}}},arkOrderPlaneCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","callee"],properties:{file:B,line:te,callee:x}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:B,line:te,method:x}}},arkOrderRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasPlaneFactory"],properties:{file:B,matchedRoot:x,hasPlaneFactory:{type:"boolean"}}}},arkOrderXiFieldWrites:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:B,line:te,key:x}}},arkOrderIngestWritesXi:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line"],properties:{file:B,line:te}}},arkOrderReleaseKeyCounts:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","keyCount"],properties:{file:B,line:te,keyCount:{type:"integer",minimum:1}}}},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 xn="1.0";function se(e){return`${e.from}->${e.to}`}i(se,"dependencyKey");function st(e,t,n,r="dependency"){return{id:`${e}:${r}:${se(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${se(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${se(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${se(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${se(t)} from the candidate, then preflight again.`}:{}}}i(st,"dependencyFinding");function Ke(e){let t=[],n=new Map(e.changeMap.map.files.map(g=>[g.path,g])),r=new Map(e.changes.map(g=>[g.path,g])),s=new Map(e.changeMap.map.dependencies.map(g=>[se(g),g])),o=new Map(e.baseDependencies.map(g=>[se(g),g])),a=new Map(e.candidateDependencies.map(g=>[se(g),g]));for(let g of[...n.values()].sort((p,m)=>p.path.localeCompare(m.path))){let p=r.get(g.path);p?p.operation!==g.operation?t.push({id:`contradictory:file:${g.path}`,classification:"contradictory",subject:"file",path:g.path,expectedOperation:g.operation,actualOperation:p.operation,message:`${g.path} was planned as ${g.operation} but the actual operation is ${p.operation}.`,nextAction:`Change ${g.path} to the planned ${g.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${g.path}`,classification:"satisfied",subject:"file",path:g.path,expectedOperation:g.operation,actualOperation:p.operation,message:`${g.path} matches the planned ${g.operation} operation.`}):t.push({id:`missing:file:${g.path}`,classification:"missing",subject:"file",path:g.path,expectedOperation:g.operation,message:`${g.path} was planned as ${g.operation} but is absent from the actual change.`,nextAction:`${g.operation[0].toUpperCase()}${g.operation.slice(1)} ${g.path} in the complete change set, then preflight again.`})}for(let g of[...r.values()].sort((p,m)=>p.path.localeCompare(m.path)))n.has(g.path)||t.push({id:`unplanned:file:${g.path}`,classification:"unplanned",subject:"file",path:g.path,actualOperation:g.operation,message:`${g.path} has an unplanned ${g.operation} operation.`,nextAction:`Remove ${g.path} from the change set, then preflight again.`});let l=new Set;for(let g of[...s.values()].sort((p,m)=>se(p).localeCompare(se(m)))){if(a.has(se(g))){t.push(st("satisfied",g,`${g.from} -> ${g.to} exists in the candidate architecture.`));continue}let p={from:g.to,to:g.from};a.has(se(p))?(l.add(se(p)),t.push(st("contradictory",g,`${g.from} -> ${g.to} was planned, but the candidate contains the reverse edge.`))):t.push(st("missing",g,`${g.from} -> ${g.to} is absent from the candidate architecture.`))}let c=new Set([...n.keys(),...r.keys()]);for(let[g,p]of[...a].sort(([m],[A])=>m.localeCompare(A)))o.has(g)||s.has(g)||l.has(g)||!c.has(p.from)&&!c.has(p.to)||t.push({...st("unplanned",p,`${p.from} -> ${p.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let u=new Set(e.changeMap.map.files.filter(g=>g.operation==="delete").map(g=>g.path));for(let[g,p]of[...o].sort(([m],[A])=>m.localeCompare(A)))a.has(g)||u.has(p.from)||u.has(p.to)||!c.has(p.from)&&!c.has(p.to)||t.push({...st("unplanned",p,`${p.from} -> ${p.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let f={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((g,p)=>f[g.classification]-f[p.classification]||(g.subject===p.subject?0:g.subject==="file"?-1:1)||g.id.localeCompare(p.id));let y={satisfied:t.filter(g=>g.classification==="satisfied").length,missing:t.filter(g=>g.classification==="missing").length,contradictory:t.filter(g=>g.classification==="contradictory").length,unplanned:t.filter(g=>g.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:y.missing===0&&y.contradictory===0&&y.unplanned===0,behavioralCompletion:"not-evaluated",summary:y,findings:t}}i(Ke,"analyzeArchitectureConvergence");var Ya="1.0",Tn="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",hs=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","writes-via-aggregate","no-anemic-model","invariant-coverage"],Xa=["no-anemic-model"],gs={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Nn={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Tn,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:Tn},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:[...hs]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:gs,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:gs}}}},Te=class extends Error{static{i(this,"ArkRulesValidationError")}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 lt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(lt,"isObject");function Nt(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}i(Nt,"propertyPath");function at(e){return e===null?"null":Array.isArray(e)?"array":typeof e}i(at,"valueType");function _a(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}i(_a,"resolveSchemaRef");function it(e,t,n,r,s){if(t.$ref){let o=_a(t.$ref,r);if(!o){s.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}it(e,o,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(o=>Object.is(o,e))){s.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!lt(e)){s.push({path:n,message:`must be an object; received ${at(e)}`});return}let o=t.properties??{};for(let a of t.required??[])e[a]===void 0&&s.push({path:Nt(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in o||s.push({path:Nt(n,a),message:"unknown field"});else if(lt(t.additionalProperties)){let a=t.additionalProperties;for(let l of Object.keys(e))l in o||it(e[l],a,Nt(n,l),r,s)}for(let[a,l]of Object.entries(o))e[a]!==void 0&&it(e[a],l,Nt(n,a),r,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:n,message:`must be an array; received ${at(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 o=e.map(a=>JSON.stringify(a));new Set(o).size!==o.length&&s.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((o,a)=>it(o,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 ${at(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 ${at(e)}`})}i(it,"validateNode");function xa(e){return{...e,$schema:e.$schema===void 0?bn: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}}i(xa,"defaultedArkRules");function ss(e){return e==="enforced"?"enforced":"advisory"}i(ss,"normalizeMode");function Ta(e){return Oa.includes(e)}i(Ta,"isTier2Sensor");function Na(e,t){let n=Array.isArray(e.structure)?e.structure:[],r=Array.isArray(e.invariants)?e.invariants:[],s=new Set;n.forEach((o,a)=>{if(!lt(o))return;let l=typeof o.id=="string"?o.id:"";l&&(s.has(l)&&t.push({path:`$.structure[${a}].id`,message:`duplicate rule id ${JSON.stringify(l)}`}),s.add(l)),typeof o.sensor=="string"&&Ta(o.sensor)&&o.mode==="enforced"&&t.push({path:`$.structure[${a}].mode`,message:`${l?`rule ${JSON.stringify(l)} uses sensor `:"sensor "}${JSON.stringify(o.sensor)}, which is Tier-2 advisory-only and cannot be enforced${l?" (arkgate-check --sensors lists which sensors can)":""}`}),Array.isArray(o.appliesTo)&&o.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((o,a)=>{if(!lt(o))return;let l=typeof o.id=="string"?o.id:"";l&&(s.has(l)&&t.push({path:`$.invariants[${a}].id`,message:`duplicate rule id ${JSON.stringify(l)}`}),s.add(l)),Array.isArray(o.appliesTo)&&o.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)"})})}i(Na,"validateSemantics");function Lt(e,t="arkrules.json",n){if(!lt(e))throw new xe(t,[{path:"$",message:`must be an object; received ${at(e)}`}]);let r=xa(e),s=[];if(it(r,Cn,"$",Cn,s),Na(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 xe(t,s);return{config:r}}i(Lt,"loadArkRulesContract");function La(e,t="arkrules.json",n){let r;try{r=JSON.parse(e)}catch(s){throw new xe(t,[{path:"$",message:`invalid JSON: ${s instanceof Error?s.message:String(s)}`}])}return Lt(r,t,n)}i(La,"parseArkRulesJson");function On(e){let t={},n=[],r=[],s=[...e].sort((o,a)=>o.layer.localeCompare(a.layer));for(let o of s){let a=(o.file.structure??[]).map(c=>({...c,mode:ss(c.mode),provenance:{sourceFile:o.sourceFile,ruleId:c.id,layer:o.layer}})),l=(o.file.invariants??[]).map(c=>({...c,mode:ss(c.mode),provenance:{sourceFile:o.sourceFile,ruleId:c.id,layer:o.layer}}));t[o.layer]={sourceFile:o.sourceFile,structure:a,invariants:l},n.push(...a),r.push(...l)}return n.sort((o,a)=>{let l=o.provenance.layer.localeCompare(a.provenance.layer);return l!==0?l:o.id.localeCompare(a.id)}),r.sort((o,a)=>{let l=o.provenance.layer.localeCompare(a.provenance.layer);return l!==0?l:o.id.localeCompare(a.id)}),{schemaVersion:"1.0",byLayer:t,structure:n,invariants:r}}i(On,"buildEffectiveArkRules");function Te(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}i(Te,"emptyEffectiveArkRules");var Pt=class extends Error{static{i(this,"EffectiveContractError")}issues;source;constructor(t,n){super(`Invalid Effective Contract (${t}):
6
+ `)}`),this.name="ArkRulesValidationError",this.source=t,this.issues=n}};function it(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(it,"isObject");function Lt(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}i(Lt,"propertyPath");function ot(e){return e===null?"null":Array.isArray(e)?"array":typeof e}i(ot,"valueType");function Ja(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}i(Ja,"resolveSchemaRef");function at(e,t,n,r,s){if(t.$ref){let o=Ja(t.$ref,r);if(!o){s.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}at(e,o,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(o=>Object.is(o,e))){s.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!it(e)){s.push({path:n,message:`must be an object; received ${ot(e)}`});return}let o=t.properties??{};for(let a of t.required??[])e[a]===void 0&&s.push({path:Lt(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in o||s.push({path:Lt(n,a),message:"unknown field"});else if(it(t.additionalProperties)){let a=t.additionalProperties;for(let l of Object.keys(e))l in o||at(e[l],a,Lt(n,l),r,s)}for(let[a,l]of Object.entries(o))e[a]!==void 0&&at(e[a],l,Lt(n,a),r,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:n,message:`must be an array; received ${ot(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 o=e.map(a=>JSON.stringify(a));new Set(o).size!==o.length&&s.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((o,a)=>at(o,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 ${ot(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 ${ot(e)}`})}i(at,"validateNode");function Za(e){return{...e,$schema:e.$schema===void 0?Tn: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}}i(Za,"defaultedArkRules");function ys(e){return e==="enforced"?"enforced":"advisory"}i(ys,"normalizeMode");function Qa(e){return Xa.includes(e)}i(Qa,"isTier2Sensor");function ei(e,t){let n=Array.isArray(e.structure)?e.structure:[],r=Array.isArray(e.invariants)?e.invariants:[],s=new Set;n.forEach((o,a)=>{if(!it(o))return;let l=typeof o.id=="string"?o.id:"";l&&(s.has(l)&&t.push({path:`$.structure[${a}].id`,message:`duplicate rule id ${JSON.stringify(l)}`}),s.add(l)),typeof o.sensor=="string"&&Qa(o.sensor)&&o.mode==="enforced"&&t.push({path:`$.structure[${a}].mode`,message:`${l?`rule ${JSON.stringify(l)} uses sensor `:"sensor "}${JSON.stringify(o.sensor)}, which is Tier-2 advisory-only and cannot be enforced${l?" (arkgate-check --sensors lists which sensors can)":""}`}),Array.isArray(o.appliesTo)&&o.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((o,a)=>{if(!it(o))return;let l=typeof o.id=="string"?o.id:"";l&&(s.has(l)&&t.push({path:`$.invariants[${a}].id`,message:`duplicate rule id ${JSON.stringify(l)}`}),s.add(l)),Array.isArray(o.appliesTo)&&o.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)"})})}i(ei,"validateSemantics");function Pt(e,t="arkrules.json",n){if(!it(e))throw new Te(t,[{path:"$",message:`must be an object; received ${ot(e)}`}]);let r=Za(e),s=[];if(at(r,Nn,"$",Nn,s),ei(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 Te(t,s);return{config:r}}i(Pt,"loadArkRulesContract");function ti(e,t="arkrules.json",n){let r;try{r=JSON.parse(e)}catch(s){throw new Te(t,[{path:"$",message:`invalid JSON: ${s instanceof Error?s.message:String(s)}`}])}return Pt(r,t,n)}i(ti,"parseArkRulesJson");function Ln(e){let t={},n=[],r=[],s=[...e].sort((o,a)=>o.layer.localeCompare(a.layer));for(let o of s){let a=(o.file.structure??[]).map(c=>({...c,mode:ys(c.mode),provenance:{sourceFile:o.sourceFile,ruleId:c.id,layer:o.layer}})),l=(o.file.invariants??[]).map(c=>({...c,mode:ys(c.mode),provenance:{sourceFile:o.sourceFile,ruleId:c.id,layer:o.layer}}));t[o.layer]={sourceFile:o.sourceFile,structure:a,invariants:l},n.push(...a),r.push(...l)}return n.sort((o,a)=>{let l=o.provenance.layer.localeCompare(a.provenance.layer);return l!==0?l:o.id.localeCompare(a.id)}),r.sort((o,a)=>{let l=o.provenance.layer.localeCompare(a.provenance.layer);return l!==0?l:o.id.localeCompare(a.id)}),{schemaVersion:"1.0",byLayer:t,structure:n,invariants:r}}i(Ln,"buildEffectiveArkRules");function Ne(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}i(Ne,"emptyEffectiveArkRules");var wt=class extends Error{static{i(this,"EffectiveContractError")}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 as(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}i(as,"normalizeRel");function Pa(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 c of[...e.discoveredArkRulesFiles].sort())r.push({path:c,message:`ArkRules file ${JSON.stringify(c)} 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(c=>c.name)),o=[],a=[],l=new Set;for(let c of Object.keys(n).sort()){let u=n[c],m=`$.arkRules[${JSON.stringify(c)}]`;if(typeof u!="string"||u.length===0){o.push({path:m,message:"must be a non-empty relative path string"});continue}if(u.startsWith("/")||/^[A-Za-z]:[\\/]/.test(u)){o.push({path:m,message:"must be a project-relative path (absolute paths are not allowed)"});continue}if(!s.has(c)){o.push({path:m,message:`layer ${JSON.stringify(c)} is not declared in layers[]`});continue}let y=as(u);l.add(y);let g=e.fileContents[y]??e.fileContents[u];if(g===void 0){o.push({path:m,message:`referenced ArkRules file ${JSON.stringify(y)} is missing`});continue}try{let p=Lt(JSON.parse(g),y,c);a.push({layer:c,sourceFile:y,file:p.config})}catch(p){if(p instanceof xe)for(let f of p.issues)o.push({path:`${m}${f.path==="$"?"":f.path.replace(/^\$/,"")}`,message:`${y}: ${f.message}`});else p instanceof SyntaxError?o.push({path:m,message:`referenced ArkRules file ${JSON.stringify(y)} is not valid JSON: ${p.message}`}):o.push({path:m,message:`referenced ArkRules file ${JSON.stringify(y)} failed to load: ${p instanceof Error?p.message:String(p)}`})}}if(e.discoveredArkRulesFiles)for(let c of[...e.discoveredArkRulesFiles].sort()){let u=as(c);l.has(u)||r.push({path:u,message:`ArkRules file ${JSON.stringify(u)} is not referenced by arkRules and will not be enforced`,severity:"advisory"})}if(o.length>0)throw new Pt(t,o);return{config:e.config,arkRules:On(a),warnings:r}}i(Pa,"resolveEffectiveContract");function _n(e){return{...e,layers:e.layers.map(t=>{let{description:n,...r}=t;return r})}}i(_n,"omitLayerDescriptions");function xn(e){let{stewards:t,...n}=_n(e.config);return{config:n,arkRules:{schemaVersion:e.arkRules.schemaVersion,structure:e.arkRules.structure.map(r=>({id:r.id,sensor:r.sensor,mode:r.mode,appliesTo:r.appliesTo??null,description:r.description??null,provenance:r.provenance})),invariants:e.arkRules.invariants.map(r=>({id:r.id,description:r.description,aggregate:r.aggregate??null,coverage:r.coverage??null,mode:r.mode,appliesTo:r.appliesTo??null,provenance:r.provenance}))}}}i(xn,"effectiveContractPolicyPayload");function is(e,t=!1){if(!e)return"";let n=e.discarded,r=[];if(n.budget>0&&!t&&r.push(`${n.budget} past the ${e.maxFiles}-file budget`),n.noInvariantMention>0&&r.push(`${n.noInvariantMention} naming no catalogued invariant`),n.oversize>0&&r.push(`${n.oversize} over the per-file byte cap`),n.unreadable>0&&r.push(`${n.unreadable} unreadable (files or directories)`),n.depthLimited>0&&r.push(`${n.depthLimited} directories past the walk depth limit`),n.outOfRoot>0&&r.push(`${n.outOfRoot} symlinked outside the project root`),r.length===0)return"";let s=t?"":` (loaded ${e.filesLoaded} files, kept ${e.testFilesRetained} tests)`;return` Scan discarded ${r.join(", ")}${s}.`}i(is,"formatCoverageDiscards");function wa(e,t){let n=e.replace(/\\/g,"/").replace(/^\.\//,"");return t.some(r=>{let s=r.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"");return s===""||s==="."?!0:n===s||n.startsWith(`${s}/`)})}i(wa,"isUnderCoverageRoot");function Da(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*['"\`][^'"\`]*${n}[^'"\`]*['"\`]`,"i").test(e)||e.includes(t)}i(Da,"titleMatchesInvariant");function Ma(e,t){if(!t)return!1;let n=t.split("."),r=n[n.length-1],s=n.length>1?n[0]:null;for(let o of Object.values(e))if(!(s&&!o.includes(s))&&(new RegExp(`(?:function\\s+|\\b)${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[(<]`).test(o)||o.includes(t)))return!0;return!1}i(Ma,"symbolPresent");function Tn(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=e.coverageBudgetExhausted===!0,o=e.coverageStats,a=is(o),l=is(o,!0),c=o?`coverage file budget exhausted: ${o.filesLoaded} files loaded at the ${o.maxFiles}-file cap, ${o.testFilesRetained} tests retained, ${o.discarded.budget} files discarded at the cap; raise "coverage.maxFiles" in ark.config.json (the cap bounds files RETAINED as evidence${typeof o.filesRead=="number"?`; ${o.filesRead} were read`:""})`:"coverage file budget exhausted",u=(e.coverageRoots??[]).filter(f=>typeof f=="string"&&f.length>0),m=u.length>0,y=u.join(", "),g=[],p=[];for(let f of t){let A=[],v=f.coverage?.test!==!1,_=f.coverage?.symbol,R,I;if(!r&&v){let T;for(let w of n){let x=e.fileContents[w];if(!(!x||!Da(x,f.id))){if(!m||wa(w,u)){R=w,I=m?!1:void 0;break}T??=w}}R===void 0&&T!==void 0&&(R=T,I=!0),R!==void 0&&A.push("test-title")}_&&Ma(e.fileContents,_)&&A.push("symbol");let D=(f.coverage?.test===!0||!!_||f.coverage===void 0)&&A.length>0||f.coverage?.test===!1&&!_?!0:A.length>0,k=r&&v&&A.length===0;if(g.push({invariantId:f.id,layer:f.provenance.layer,sourceFile:f.provenance.sourceFile,mode:f.mode,covered:D&&!k,evidence:A,partial:k,description:f.description,...R!==void 0?{testEvidenceFile:R}:{},...I!==void 0?{outsideDeclaredRoots:I}:{}}),I===!0&&R!==void 0&&p.push({ruleId:"INVARIANT_COVERAGE_OUTSIDE_ROOTS",message:`Invariant ${f.id} is covered only by ${R}, which is outside the declared coverage roots (${y}). ArkGate matches declared text and never executes tests, so it cannot tell whether that file is run: move the test under a declared root, or add its root to "coverage.coverageRoots" in ark.config.json.`,file:R,line:1,arkruleId:f.id,arkruleSource:f.provenance.sourceFile,fromLayer:f.provenance.layer,severity:"warning",failsStrict:!1}),!D||k){let T=f.mode==="enforced"&&!k,w=r||n.length===0?"never-had-tests":"tests-disappeared";p.push({ruleId:"INVARIANT_UNCOVERED",message:(k?s?`Invariant ${f.id} coverage cannot be proven (${c}); reporting partial, not covered.`:`Invariant ${f.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered (never-had-tests).`:w==="tests-disappeared"?`Invariant ${f.id}: no scanned test names it in a describe/it title and no declared symbol was found (tests-disappeared \u2014 a suite exists). ArkGate matches declared text; it never executes tests.`:`Invariant ${f.id}: no scanned test names it in a describe/it title and no declared symbol was found (never-had-tests \u2014 the scan found no tests at all). ArkGate matches declared text; it never executes tests.`)+(k&&s?l:a),file:f.provenance.sourceFile,line:1,arkruleId:f.id,arkruleSource:f.provenance.sourceFile,fromLayer:f.provenance.layer,severity:T?"error":"warning",failsStrict:T,kind:w})}}return{coverage:g,violations:p,partial:g.some(f=>f.partial)}}i(Tn,"evaluateInvariantCoverage");function Nn(e){return e?e.partial?{ok:!1,reason:"Coverage is partial (missing test globs); cannot promote until evidence is complete."}:e.covered?e.outsideDeclaredRoots===!0?{ok:!1,reason:`Invariant ${e.invariantId} is covered only by ${e.testEvidenceFile??"a test"}, outside the declared coverage roots; ArkGate cannot tell whether that test runs, so it will not promote on it.`}:{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."}}i(Nn,"canPromoteInvariant");var wn="1.0";function L(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}})}i(L,"addFinding");function Z(e){return[...new Set(e??[])].sort()}i(Z,"sortedUnique");function ue(e,t,n,r,s){let o=Z(n),a=Z(r),l=new Set(o),c=new Set(a),u=a.filter(y=>!l.has(y)),m=o.filter(y=>!c.has(y));u.length===0&&m.length===0||(u.length>0&&L(e,{kind:"added",path:t,classification:s.added,message:s.addedMessage,before:o,after:a}),m.length>0&&L(e,{kind:"removed",path:t,classification:s.removed,message:s.removedMessage,before:o,after:a}))}i(ue,"compareStringSets");function ct(e,t,n,r,s,o,a){if(n===r)return;L(e,{kind:r?"enabled":"disabled",path:t,classification:r?s:s==="strengthening"?"weakening":"strengthening",message:r?o:a,before:n,after:r})}i(ct,"compareBoolean");function wt(e,t){let n=new Map,r=new Set;for(let s of e){let o=t(s);n.has(o)?r.add(o):n.set(o,s)}return{values:n,duplicates:[...r].sort()}}i(wt,"keyed");function Fa(e,t,n){let r=wt(t,o=>o.name),s=wt(n,o=>o.name);(r.duplicates.length>0||s.duplicates.length>0)&&L(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 o of[...new Set([...r.values.keys(),...s.values.keys()])].sort()){let a=r.values.get(o),l=s.values.get(o),c=`$.layers[${o}]`;if(!a&&l){L(e,{kind:"layer-added",path:c,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:l});continue}if(a&&!l){L(e,{kind:"layer-removed",path:c,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:a});continue}if(!a||!l)continue;ue(e,`${c}.patterns`,a.patterns,l.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,`${c}.exclude`,a.exclude,l.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let u=It(a),m=It(l);ue(e,`${c}.forbiddenGlobals`,u.rawGlobals,m.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,`${c}.capabilities`,u.atoms,m.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)."}),Z(a.intentPrefixes).join("\0")!==Z(l.intentPrefixes).join("\0")&&L(e,{kind:"intent-prefixes-changed",path:`${c}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:Z(a.intentPrefixes),after:Z(l.intentPrefixes)}),ct(e,`${c}.mayImportInfrastructure`,a.mayImportInfrastructure===!0,l.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),ct(e,`${c}.optional`,a.optional===!0,l.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.")}}i(Fa,"compareLayers");function $a(e,t,n){let r=i(a=>`${a.from}->${a.to}`,"keyOf"),s=wt(t,r),o=wt(n,r);(s.duplicates.length>0||o.duplicates.length>0)&&L(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:s.duplicates,after:o.duplicates});for(let a of[...new Set([...s.values.keys(),...o.values.keys()])].sort()){let l=s.values.get(a),c=o.values.get(a),u=`$.rules[${a}]`;if(!l&&c){c.allowed===!1&&L(e,{kind:"deny-added",path:u,classification:"strengthening",message:"A denied dependency edge was added.",after:c});continue}if(l&&!c){l.allowed===!1&&L(e,{kind:"deny-removed",path:u,classification:"weakening",message:"A denied dependency edge was removed.",before:l});continue}if(!l||!c)continue;l.allowed!==c.allowed&&L(e,{kind:c.allowed?"deny-disabled":"deny-enabled",path:`${u}.allowed`,classification:c.allowed?"weakening":"strengthening",message:c.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:l.allowed,after:c.allowed});let m=l.peerIsolation===!0,y=c.peerIsolation===!0;if(m!==y){let g=l.from===l.to&&c.from===c.to;L(e,{kind:y?"peer-isolation-enabled":"peer-isolation-disabled",path:`${u}.peerIsolation`,classification:g?y?"strengthening":"weakening":"judgment-required",message:g?y?"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:m,after:y})}Z(l.sliceFolders).join("\0")!==Z(c.sliceFolders).join("\0")&&L(e,{kind:"slice-folders-changed",path:`${u}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:Z(l.sliceFolders),after:Z(c.sliceFolders)}),!(!m&&!y)&&(cs(e,`${u}.sharedRoots`,"shared-roots",Z(l.sharedRoots),Z(c.sharedRoots),"Roots declared shared are exempt from the peerIsolation unclassifiable denial.","Roots are no longer declared shared and fall back to the peerIsolation denial."),cs(e,`${u}.allowedCrossSlice`,"cross-slice-allowance",Z((l.allowedCrossSlice??[]).map(ls)),Z((c.allowedCrossSlice??[]).map(ls)),"Directed cross-slice edges are now allowed by declaration.","Directed cross-slice edges are no longer declared and deny again."))}}i($a,"compareRules");function ls(e){return JSON.stringify([e.from,e.to])}i(ls,"crossSliceKey");function cs(e,t,n,r,s,o,a){if(JSON.stringify(r)===JSON.stringify(s))return;let l=s.filter(m=>!r.includes(m)),c=r.filter(m=>!s.includes(m)),u=l.length>0&&c.length>0;L(e,{kind:u?`${n}-changed`:l.length>0?`${n}-added`:`${n}-removed`,path:t,classification:u?"judgment-required":l.length>0?"weakening":"strengthening",message:u?`${o} Entries were added and removed in the same change.`:l.length>0?o:a,before:r,after:s})}i(cs,"compareDeclaredExceptions");function Ha(e,t,n){let r=t.safety??{},s=n.safety??{};for(let o of["maxTsSuppressions","maxAnyCasts"]){let a=r[o]??0,l=s[o]??0;a!==l&&L(e,{kind:l>a?"threshold-raised":"threshold-lowered",path:`$.safety.${o}`,classification:l>a?"weakening":"strengthening",message:l>a?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:a,after:l})}for(let o of["allowInMemory","allowDisabledPeerIsolation"])ct(e,`$.safety.${o}`,r[o]===!0,s[o]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}i(Ha,"compareSafety");function Ln(e){return e.mode==="enforced"?"enforced":"advisory"}i(Ln,"arkRunMode");function Pn(e){return e.mode==="enforced"?"enforced":"advisory"}i(Pn,"arkOrderMode");function ja(e,t,n){let r=t.arkOrder,s=n.arkOrder,o="$.arkOrder";if(!r&&!s)return;if(!r&&s){L(e,{kind:"arkorder-added",path:o,classification:"strengthening",message:`ArkOrder extra was added (${Pn(s)}).`,after:s});return}if(r&&!s){L(e,{kind:"arkorder-removed",path:o,classification:"weakening",message:"ArkOrder extra was removed.",before:r});return}if(!r||!s)return;let a=Pn(r),l=Pn(s);if(a!==l){let c=a==="advisory"&&l==="enforced";L(e,{kind:c?"arkorder-promoted":"arkorder-demoted",path:`${o}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkOrder extra was promoted to enforced.":"ArkOrder extra was demoted to advisory.",before:a,after:l})}ue(e,`${o}.planeRoots`,r.planeRoots,s.planeRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkOrder plane roots are governed.",removedMessage:"ArkOrder plane roots were removed and may skip the plane."}),ue(e,`${o}.managedLayers`,r.managedLayers,s.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkOrder.",removedMessage:"Layers were removed from ArkOrder management."})}i(ja,"compareArkOrder");function Va(e,t,n){let r=t.arkRun,s=n.arkRun,o="$.arkRun";if(!r&&!s)return;if(!r&&s){L(e,{kind:"arkrun-added",path:o,classification:"strengthening",message:`ArkRun extra was added (${Ln(s)}).`,after:s});return}if(r&&!s){L(e,{kind:"arkrun-removed",path:o,classification:"weakening",message:"ArkRun extra was removed.",before:r});return}if(!r||!s)return;let a=Ln(r),l=Ln(s);if(a!==l){let c=a==="advisory"&&l==="enforced";L(e,{kind:c?"arkrun-promoted":"arkrun-demoted",path:`${o}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkRun extra was promoted to enforced.":"ArkRun extra was demoted to advisory.",before:a,after:l})}ue(e,`${o}.compositionRoots`,r.compositionRoots,s.compositionRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkRun composition roots are governed.",removedMessage:"ArkRun composition roots were removed and may skip the kernel."}),ue(e,`${o}.managedLayers`,r.managedLayers,s.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkRun.",removedMessage:"Layers were removed from ArkRun management."}),ct(e,`${o}.requireDeclarations`,r.requireDeclarations!==!1,s.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}i(Va,"compareArkRun");function Ua(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"}i(Ua,"overallClassification");function ds(e,t){return`${e}::${t}`}i(ds,"ruleKey");function us(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(ds(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(ds(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}i(us,"indexEffectiveRules");function Ka(e,t,n,r,s,o){let a=new Map((o??[]).map(g=>[g.invariantId,g])),l=t.arkRules??{},c=n.arkRules??{},u=[...new Set([...Object.keys(l),...Object.keys(c)])].sort();for(let g of u){let p=l[g],f=c[g],A=`$.arkRules[${g}]`;if(p===void 0&&f!==void 0){L(e,{kind:"arkrules-ref-added",path:A,classification:"strengthening",message:`ArkRules reference for layer ${g} was added.`,after:f});continue}if(p!==void 0&&f===void 0){L(e,{kind:"arkrules-ref-removed",path:A,classification:"weakening",message:`ArkRules reference for layer ${g} was removed.`,before:p});continue}p!==f&&L(e,{kind:"arkrules-ref-path-changed",path:A,classification:"judgment-required",message:`ArkRules file path for layer ${g} changed; verify the effective rules still match intent.`,before:p,after:f})}let m=us(r),y=us(s);for(let g of[...new Set([...m.structure.keys(),...y.structure.keys()])].sort()){let p=m.structure.get(g),f=y.structure.get(g),A=`$.arkRules.structure[${g}]`;if(!p&&f){L(e,{kind:"arkrule-structure-added",path:A,classification:"strengthening",message:`Structure ArkRule ${f.id} was added (${f.mode}).`,after:f});continue}if(p&&!f){L(e,{kind:"arkrule-structure-removed",path:A,classification:"weakening",message:`Structure ArkRule ${p.id} was removed.`,before:p});continue}if(!(!p||!f)){if(p.mode!==f.mode){let v=p.mode==="advisory"&&f.mode==="enforced";L(e,{kind:v?"arkrule-promoted":"arkrule-demoted",path:`${A}.mode`,classification:v?"strengthening":"weakening",message:v?`Structure ArkRule ${f.id} was promoted to enforced.`:`Structure ArkRule ${f.id} was demoted to advisory.`,before:p.mode,after:f.mode})}p.sensor!==f.sensor&&L(e,{kind:"arkrule-sensor-changed",path:`${A}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${f.id} changed sensor identity.`,before:p.sensor,after:f.sensor})}}for(let g of[...new Set([...m.invariants.keys(),...y.invariants.keys()])].sort()){let p=m.invariants.get(g),f=y.invariants.get(g),A=`$.arkRules.invariants[${g}]`;if(!p&&f){L(e,{kind:"arkrule-invariant-added",path:A,classification:"strengthening",message:`Invariant ${f.id} was added (${f.mode}).`,after:f});continue}if(p&&!f){L(e,{kind:"arkrule-invariant-removed",path:A,classification:"weakening",message:`Invariant ${p.id} was removed.`,before:p});continue}if(!(!p||!f)&&p.mode!==f.mode)if(p.mode==="advisory"&&f.mode==="enforced"){let _=a?.get(f.id),R=Nn(_);R.ok?L(e,{kind:"arkrule-invariant-promoted",path:`${A}.mode`,classification:"strengthening",message:`Invariant ${f.id} was promoted to enforced (coverage evidence present).`,before:p.mode,after:f.mode}):L(e,{kind:"arkrule-invariant-promote-refused",path:`${A}.mode`,classification:"judgment-required",message:`Invariant ${f.id} cannot be promoted to enforced: ${R.reason}`,before:p.mode,after:f.mode})}else L(e,{kind:"arkrule-invariant-demoted",path:`${A}.mode`,classification:"weakening",message:`Invariant ${f.id} was demoted to advisory.`,before:p.mode,after:f.mode})}}i(Ka,"compareArkRules");function Dn(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."}),ct(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},o=e.cyclePolicy??"strict",a=t.cyclePolicy??"strict";if(o!==a){let l=s[a]===s[o]?"judgment-required":s[a]>s[o]?"strengthening":"weakening";L(r,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:l,message:"The cycle enforcement level changed.",before:o,after:a})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&L(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}),Fa(r,e.layers,t.layers),$a(r,e.rules,t.rules),Ha(r,e,t),Ka(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),Va(r,e,t),ja(r,e,t),r.sort((l,c)=>l.path.localeCompare(c.path)||l.id.localeCompare(c.id)),{schemaVersion:wn,classification:Ua(r),findings:r}}i(Dn,"classifyArkPolicyDelta");function Mn(e,t){if(!e||e.schemaVersion!==wn||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=Z(e.findingIds),r=Z(t.findingIds);return n.length===r.length&&n.every((s,o)=>s===r[o])}i(Mn,"policyDeltaAcknowledgementMatches");function Ne(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("/")}i(Ne,"normalizePath");function ps(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}i(ps,"isIdentifierStart");function Dt(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}i(Dt,"isIdentifierCharacter");function ae(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}i(ae,"skipWhitespace");function dt(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let r=t,s="";for(t+=1;t<e.length;t+=1){let o=e[t];if(o===n)return{value:s,offset:r,excerpt:e.slice(r,t+1)};o==="\\"&&t+1<e.length?(s+=e[t+1],t+=1):s+=o}}i(dt,"readString");function ce(e,t,n){return e.startsWith(t,n)&&!Dt(e[n-1])&&!Dt(e[n+t.length])}i(ce,"isWordAt");function fs(e,t){let n=ae(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=ae(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!ce(e,"type",n))return!1;let s=ae(e,n+4);if(s>=e.length||e[s]===","||e[s]==="}"||ce(e,"as",s)||!ps(e[s]))return!1;for(n=s;n<e.length&&Dt(e[n]);)n+=1;if(n=ae(e,n),ce(e,"as",n)){if(n=ae(e,n+2),!ps(e[n]))return!1;for(;n<e.length&&Dt(e[n]);)n+=1}r=!0}return!1}i(fs,"bracedNamedBindingsAreTypeOnly");function Ga(e,t){if(t=ae(e,t+6),e[t]==="(")return dt(e,ae(e,t+1));let n=!1;if(ce(e,"type",t)){let s=ae(e,t+4);e[s]!==","&&!ce(e,"from",s)&&(n=!0)}else fs(e,t)&&(n=!0);let r=ms(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}i(Ga,"specifierAfterImport");function Ba(e,t){t=t+6;let n=ae(e,t),r=!1;if(ce(e,"type",n)){let o=ae(e,n+4);(e[o]==="{"||e[o]==="*")&&(r=!0)}else fs(e,n)&&(r=!0);let s=ms(e,t,!1);return s&&r?{...s,typeOnly:!0}:s}i(Ba,"specifierAfterExport");function ms(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(ce(e,"from",t))return dt(e,ae(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return dt(e,t);if(t>0&&(ce(e,"import",t)||ce(e,"export",t)))return}}i(ms,"specifierInStaticStatement");function za(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}i(za,"skipTemplateLiteral");function qa(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=ae(e,t+7);if(e[r]!=="(")return;r=ae(e,r+1);let s=dt(e,r);return s?{...s,requireCall:!0}:void 0}i(qa,"specifierAfterRequire");function Wa(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 o=e.indexOf("*/",n+2);if(o<0)break;n=o+1;continue}if(r==="`"){n=za(e,n);continue}if(r==="'"||r==='"'){let o=dt(e,n);o&&(n=o.offset+o.excerpt.length-1);continue}let s=r==="i"&&ce(e,"import",n)?Ga(e,n):r==="e"&&ce(e,"export",n)?Ba(e,n):r==="r"&&ce(e,"require",n)?qa(e,n):void 0;s&&(t.push(s),n=s.offset+s.excerpt.length-1)}return t}i(Wa,"moduleSpecifiers");function gs(e,t){let n=[],r=[];for(let s of Wa(e.content)){let o=s.value;if(!o.startsWith(".")){if(s.typeOnly)continue;let u=Je(o);if(!u)continue;let m=e.content.slice(0,s.offset).split(`
10
- `).length;r.push({file:e.path,symbol:o,capability:u,evidence:{kind:"import",file:e.path,line:m,excerpt:s.excerpt}});continue}let a=e.content.slice(0,s.offset).split(`
11
- `).length,l={kind:"import",file:e.path,line:a,excerpt:s.excerpt},c=Ya(e.path,o,t);n.push({from:e.path,specifier:o,to:c?.path??null,resolution:c?"resolved":"unresolved",fromLayer:e.layer,toLayer:c?.layer??null,evidence:l})}return{edges:n,capabilityUses:r}}i(gs,"moduleFactsFor");function Ya(e,t,n){let r=e.split("/");r.pop();for(let o of t.split("/"))o==="."||o===""||(o===".."?r.pop():r.push(o));let s=r.join("/");for(let o of[s,`${s}.ts`,`${s}.tsx`,`${s}.mts`,`${s}.cts`,`${s}/index.ts`,`${s}/index.tsx`]){let a=n.get(o);if(a)return a}}i(Ya,"resolveSpecifier");function ys(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let s=St(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}i(ys,"violationsFor");var Ja={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 Xa(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}i(Xa,"hasActiveArkRules");function Za(e,t){return Xa(e,t)?J(V(xn({config:e,arkRules:t,warnings:[]}))):J(V(_n(e)))}i(Za,"policyHashFor");function Mt(e,t,n){let r=typeof e=="string"?En(e,t):_t(e,t),s=n?.arkRules??Te();return{...r,arkRules:s,policyHash:Za(r.config,s)}}i(Mt,"loadContract");function hs(e){let t=Mt(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=Mt(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=Dn(t.config,n.config,{baseArkRules:t.arkRules,candidateArkRules:n.arkRules,candidateInvariantCoverage:e.candidateInvariantCoverage}),s=r.findings.filter(l=>l.classification==="weakening"||l.classification==="judgment-required").map(l=>l.id).sort(),o=s.length>0,a=o&&Mn(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:o,acknowledged:a,valid:!o||a}}i(hs,"analyzePolicyDelta");function ut(e){let t=e.files.map(y=>{let g=Ne(y.path);return{path:g,content:y.content,contentHash:J(y.content),layer:de(g,e.contract.config.layers)??null}}).sort((y,g)=>y.path.localeCompare(g.path)),n=new Map(t.map(y=>[y.path,y])),r=[],s=[];for(let y of t){let g=gs(y,n);r.push(...g.edges),s.push(...g.capabilityUses)}let o=ys(r,e.contract.config),a=new Map(e.contract.config.layers.map(y=>[y.name,y])),l=new Map(e.contract.config.layers.map(y=>[y.name,new Set(De(y))]));for(let y of s){let g=n.get(y.file)?.layer;if(!g)continue;let p=a.get(g),f=Ee(y.symbol,p?.forbiddenGlobals??[]);if(f){o.push({ruleId:"FORBIDDEN_GLOBAL",message:`${g} must not use module "${y.symbol}" because it is the import form of forbidden global "${f}".`,symbol:y.symbol,evidence:y.evidence});continue}l.get(g)?.has(y.capability)&&o.push({ruleId:"CAPABILITY_VIOLATION",message:`${g} denies the ${y.capability} capability; found import of "${y.symbol}".`,capability:y.capability,symbol:y.symbol,evidence:y.evidence})}let c=t.length===0?"complete":"partial",u=c==="complete"?[]:[{...Ja}],m={schemaVersion:Sn,policyHash:e.contract.policyHash,compilerOptionsHash:J(V(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(y=>y.name),edges:r,capabilityUses:s,violations:o};return{mode:"lexical-compatibility",completeness:c,completenessReasons:u,valid:c==="complete"&&o.length===0,ir:m}}i(ut,"analyzeProject");function Ft(e){let t=new Map(e.files.map(n=>[Ne(n.path),n]));for(let n of e.changes){let r=Ne(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return ut({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}i(Ft,"analyzeChange");function As(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}`}i(As,"explainViolation");function Fn(e){let t=0,n=new Map,r=new Map,s=new Set,o=[],a=[],l=i(c=>{n.set(c,t),r.set(c,t),t+=1,o.push(c),s.add(c);for(let y of[...e.get(c)??[]].sort())e.has(y)&&(n.has(y)?s.has(y)&&r.set(c,Math.min(r.get(c)??0,n.get(y)??0)):(l(y),r.set(c,Math.min(r.get(c)??0,r.get(y)??0))));if(r.get(c)!==n.get(c))return;let u=[],m;do{if(m=o.pop(),m===void 0)break;s.delete(m),u.push(m)}while(m!==c);u.length>1&&a.push(u.sort())},"connect");for(let c of[...e.keys()].sort())n.has(c)||l(c);return a.sort((c,u)=>c[0]<u[0]?-1:c[0]>u[0]?1:0).map(c=>({ruleId:"CIRCULAR_DEPENDENCY",file:c[0],line:1,target:c.join(" \u2192 "),message:`Circular dependency among ${c.length} files: ${c.join(" \u2192 ")} \u2192 ${c[0]}.`,cycleKind:"value"}))}i(Fn,"detectArchitectureCycles");function Ge(e){let t=e.contentViolations.map(o=>({...o})),n=(e.warnings??[]).map(o=>({...o})),r=new Map(e.files.map(o=>[o,new Set]));for(let o of e.edges){if(o.to&&o.to!==o.from&&!o.typeOnly&&r.has(o.from)&&r.get(o.from)?.add(o.to),!o.to||!o.fromLayer||!o.toLayer)continue;let a=be(e.rules,o.fromLayer,o.toLayer,{fromPath:o.from,toPath:o.to,layers:e.config.layers});if(!a)continue;let l=a.rule,c=!!l.peerIsolation,u=!c&&!!(o.typeOnly||o.namedBindingsTypeOnly),m=c?Me(a.peerIsolationReason??"cross-slice",{fromPath:o.from,toPath:o.to,fromSlice:a.fromSlice,toSlice:a.toSlice}):void 0,y=l.message?m?`${l.message} (${m})`:l.message:m?`${o.fromLayer} must not ${o.kind} another slice of ${o.toLayer} (${o.from} \u2192 ${o.to}): ${m}`:`${o.fromLayer} must not ${o.kind} ${o.toLayer}.`;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:o.from,line:o.line,fromLayer:o.fromLayer,toLayer:o.toLayer,target:o.to,...o.typeOnly?{typeOnly:!0}:{},...o.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...o.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...o.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!c&&o.portProofEligible?{portProofEligible:!0}:{},...o.kind?{edgeKind:o.kind}:{},...c?{peerIsolation:!0}:{},message:u?`${y} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:y,...u?{failsStrict:!1,severity:"warning"}:{}})}let s=String(e.config.cyclePolicy??"strict").toLowerCase();if(s!=="off"){let o=Fn(r);s==="soft"||s==="framework-soft"?n.push(...o.map(a=>({...a,message:`${a.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...o)}return{violations:t,warnings:n,safety:e.safety}}i(Ge,"evaluateArchitectureGraph");var Qa=["no-anemic-model"];function Rs(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(Rs,"escapeGlobLiteral");function ei(e){let t="";for(let r=0;r<e.length;r+=1){let s=e[r];if(s==="\\"&&r+1<e.length){let o=e[r+1];if("*?{}[],".includes(o)||o==="\\"){t+="\\"+o,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+=Rs(t[r+1]),r+=1):s==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":s==="?"?n+="[^/]":n+=Rs(s)}return new RegExp(`^${n}$`)}i(ei,"globToRegExp");function Be(e,t){return!t||t.length===0?!0:t.some(n=>ei(n).test(e))}i(Be,"matchesAppliesTo");function ti(e){return Qa.includes(e)}i(ti,"isTier2");function ks(e){return e.mode==="enforced"&&!ti(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}i(ks,"severityFor");function Le(e,t,n,r=1){let{severity:s,failsStrict:o}=ks(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:o}}i(Le,"baseViolation");function $t(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}i($t,"isInRuleLayer");function Ht(e,t,n){return t.filter(r=>!(!r.exported||!Be(r.file,e.appliesTo)||!$t(r.file,e,n)))}i(Ht,"shapesForRule");function ni(e,t,n){let r=[];for(let s of Ht(e,t,n))(s.hasPublicSetters||s.hasPublicMutableFields)&&r.push(Le(e,s.file,`Exported class ${s.className} exposes public mutable state (sensor aggregate-private-state).`));return r}i(ni,"evaluateAggregatePrivateState");function ri(e,t,n){let r=[];for(let s of Ht(e,t,n))if(s.hasPublicConstructor&&!s.hasStaticFactory){if(!(s.hasPublicMutableFields||s.hasPublicSetters||(s.mutatingMethods?.length??0)>0))continue;r.push(Le(e,s.file,`Exported class ${s.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}return r}i(ri,"evaluateAlwaysValidFactory");function si(e,t,n){let r=[];for(let s of Ht(e,t,n))for(let o of s.mutatingMethods)o.referencesGuardOrPublish||r.push(Le(e,s.file,`Mutating method ${s.className}.${o.name} does not reference a guard or publish symbol (sensor domain-event-on-mutation).`));return r}i(si,"evaluateDomainEventOnMutation");function oi(e,t){let n=[];for(let r of t.files)Be(r,e.appliesTo)&&$t(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(Le(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}i(oi,"evaluateOrchestrationOnly");function ai(e,t){let n=[];for(let r of t.files)Be(r,e.appliesTo)&&$t(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(Le(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}i(ai,"evaluateThinAdapter");function ii(e,t){let n=[];for(let r of t.files)Be(r,e.appliesTo)&&$t(r,e,t.layerForFile)&&t.fileHints?.[r]?.persistenceWrite&&n.push(Le(e,r,"File imports a persistence driver and issues a write; route the write through a Domain aggregate and a persistence adapter (sensor writes-via-aggregate)."));return n}i(ii,"evaluateWritesViaAggregate");function li(e,t,n){let r=[];for(let s of Ht(e,t,n))if(s.dataOnly===!0){let o=Le(e,s.file,`Exported type ${s.className} looks data-only / anemic (sensor no-anemic-model; advisory only).`);r.push({...o,severity:"warning",failsStrict:!1})}return r}i(li,"evaluateNoAnemicModel");function $n(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(...ni(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...ri(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...si(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...oi(n,e));break;case"thin-adapter":t.push(...ai(n,e));break;case"writes-via-aggregate":t.push(...ii(n,e));break;case"no-anemic-model":t.push(...li(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))}i($n,"evaluateArkRuleSensors");function Hn(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(c=>Be(c,s.appliesTo)))continue;let{severity:a,failsStrict:l}=ks(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:l})}for(let s of e.invariants??[]){if(!s.appliesTo||s.appliesTo.length===0||r.some(l=>Be(l,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,o)=>s.file.localeCompare(o.file)||s.arkruleId.localeCompare(o.arkruleId)||s.message.localeCompare(o.message))}i(Hn,"collectEmptyAppliesToFindings");var ci=/\bfrom\s+['"](?:@?prisma\/client|@supabase\/|drizzle-orm|typeorm|knex|mongodb|pg|mysql2|mongoose|better-sqlite3|ioredis|redis|kysely|sequelize)['"]|require\(\s*['"](?:@?prisma\/client|pg|knex|typeorm|mongoose)/,di=/\.(?:insert(?:One|Many)?|update(?:One|Many)?|upsert|delete(?:One|Many)?|createMany|create|replaceOne|findOneAnd(?:Update|Delete|Replace))\s*\(|\bINSERT\s+INTO\b|\bUPDATE\s+[A-Za-z_][\w.]*\s+SET\b|\bDELETE\s+FROM\b/i,ui=/\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*=)/,pi=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,fi=/\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*=/,mi=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function Es(e,t){if(!t||t.length<40)return null;let n=t.match(new RegExp(fi.source,"g"))??[],r=t.match(new RegExp(mi.source,"g"))??[],s=(t.match(/\bif\s*\(/g)??[]).length,o=(t.match(/\bswitch\s*\(/g)??[]).length,a=n.length>=2||n.length>=1&&r.length>=2||r.length>=3&&s+o>=6,l=ci.test(t),c=ui.test(t)||pi.test(t),u=n.length>=1||r.length>=2,m=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),y=l&&u||c&&u||l&&m&&(s>=4||n.length>=1)||c&&l,g=l&&di.test(t);return!a&&!y&&!g?null:{...a?{orchestrationHeavy:!0}:{},...y?{adapterThick:!0}:{},...g?{persistenceWrite:!0}:{}}}i(Es,"deriveArkRuleFileHints");function jn(e){let t={};for(let[n,r]of Object.entries(e)){let s=Es(n,r);s&&(t[n.replace(/\\/g,"/")]=s)}return t}i(jn,"buildArkRuleFileHints");function gi(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 o=s[1],a=s.index+s[0].length,l=1,c=a;for(;c<t.length&&l>0;){let w=t[c];w==="{"?l+=1:w==="}"&&(l-=1),c+=1}let u=t.slice(a,c-1),m=u.split(`
12
- `).map(w=>/^\s*\/\//.test(w)||/^\s*\/\*|\*\//.test(w)?w:w.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
- `),y=/(?:^|\n)\s*(?:public\s+)?[a-zA-Z_][a-zA-Z0-9_]*\s*[:=]/m.test(m.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(m),g=/(?:^|\n)\s*public\s+(?!static|async|get|set|constructor|readonly)[a-zA-Z_]/.test(m)||/(?:^|[\n;])\s*[a-zA-Z_][a-zA-Z0-9_]*\s*:\s*[^=;\n]+[;=]/m.test(m.split(`
14
- `).filter(w=>!/^\s*(private|protected|static|constructor|get |set |async |\/)/.test(w)).join(`
15
- `)),p=/(?:^|[\n;{])\s*(?:public\s+)?set\s+[a-zA-Z_]/.test(u),f=/(?:^|[\n;{])\s*private\s+constructor\s*\(/.test(u),A=/(?:^|[\n;{])\s*(?:public\s+)?constructor\s*\(/.test(u)&&!f,v=/(?:^|[\n;{])\s*static\s+(?:async\s+)?(?:create|of|from|parse|build|make|new)\s*[<(]/.test(u)||/(?:^|[\n;{])\s*static\s+(?:async\s+)?[A-Za-z_][A-Za-z0-9_]*\s*\([^)]*\)\s*:\s*[A-Za-z_]/.test(u),_=[],R=new Set(["if","match","when"]),I=/(?:^|\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,b;for(;(b=I.exec(u))!==null;){let w=b[1];if(R.has(w))continue;let x=b.index+b[0].length,H=1,M=x;for(;M<u.length&&H>0;)u[M]==="{"?H+=1:u[M]==="}"&&(H-=1),M+=1;let te=u.slice(x,M-1);if(!/this\.\w+\s*=/.test(te))continue;let we=/\b(ensureInvariants|assertInvariants|validate|publish|emit|raise|record)\b/.test(te);_.push({name:w,referencesGuardOrPublish:we})}let D=(u.match(/(?:^|\n)\s*(?:public\s+|private\s+|protected\s+)?(?:async\s+)?[a-zA-Z_][a-zA-Z0-9_]*\s*\(/g)??[]).length,k=(m.match(/(?:^|[\n;])\s*(?:public\s+)?(?!constructor|static|get|set|private|protected|readonly)[a-zA-Z_][a-zA-Z0-9_]*\s*[:=]/g)??[]).length,T=D<=1&&k>=2&&(g||y);n.push({file:e,className:o,exported:!0,hasPublicMutableFields:g||y,hasPublicSetters:p,hasPublicConstructor:A,hasStaticFactory:v,mutatingMethods:[..._],dataOnly:T})}return n}i(gi,"extractClassShapesFromSource");var yi=50;function Vn(e){if(!e)return{};let t=typeof e.governedPercent=="number"?e.governedPercent:null,n=typeof e.populatedLayerCount=="number"?e.populatedLayerCount:null;return n==null&&typeof e.classifiedFiles=="number"&&(n=e.classifiedFiles>0?1:0),{governedPercent:t,populatedLayerCount:n}}i(Vn,"normalizeExtraMergeTeethClassification");function Re(e){let t=Vn(e),n=typeof t.governedPercent=="number"?t.governedPercent:null,r=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null;return n==null&&r==null?!0:(n??0)>=50&&(r??0)>=1}i(Re,"extraMergeTeethAllowed");function Un(e){let t=e.length,n=0,r=new Set;for(let s of e){let o=typeof s.layer=="string"&&s.layer.length>0?s.layer:null;o&&(n+=1,r.add(o))}return{governedPercent:t>0?Math.round(n/t*100):0,populatedLayerCount:r.size}}i(Un,"classifyResolvedLayerCoverage");function Kn(e){return typeof e=="string"&&e.startsWith("ARKRUN_")}i(Kn,"isArkRunRuleId");function hi(e){return typeof e=="string"&&e.startsWith("ARKORDER_")}i(hi,"isArkOrderRuleId");function Is(e){if(e?.arkruleId!=null)return!0;let t=typeof e?.ruleId=="string"?e.ruleId:"";return t.startsWith("ARKRULE")||t.startsWith("arkrule")||t.startsWith("ARKRUN_")||t.startsWith("ARKORDER_")}i(Is,"isExtraPlaneFinding");function Ai(e,t={}){if(!Array.isArray(e)||Re(t))return e;for(let n of e)Is(n)&&n.failsStrict!==!1&&(n.failsStrict=!1,n.severity==="error"&&(n.severity="warning"));return e}i(Ai,"demoteExtraPlaneTeethUnderClassificationFloor");var vs="Structure = heuristics; invariants = catalog+coverage evidence (not business runtime); ArkRun = kernel usage + declarations (not a score); ArkOrder = pattern slaving (not a score). Extra planes never merge into one architecture score. Advisory ArkRules \u2260 merge teeth. Advisory ArkRun \u2260 merge teeth. Advisory ArkOrder \u2260 merge teeth.";function Ae(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):0}i(Ae,"countOrZero");function Gn(e={}){let t=Vn(e.classification),n=typeof t.governedPercent=="number"?t.governedPercent:null,r=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null,s=n!=null||r!=null,o=Re(t),a=e.arkRules,l=Ae(a?.structureEnforced),c=Ae(a?.structureTotal),u=typeof a?.structureAdvisory=="number"?Ae(a.structureAdvisory):Math.max(0,c-l),m=Ae(a?.invariantEnforced),y=Ae(a?.invariantTotal),g=typeof a?.invariantAdvisory=="number"?Ae(a.invariantAdvisory):Math.max(0,y-m),p=l>0||m>0,f=e.arkRun?.present===!0,A=e.arkRun?.mode==="enforced"||e.arkRun?.mode==="advisory"?e.arkRun.mode:null,v=Ae(e.arkRun?.residualCount),_=f&&A==="enforced",R=_&&o,I=p||_,b=I&&o,D=I&&s&&!o,k;if(b){let w=[];p&&w.push("enforced structure/invariant findings"),_&&w.push("enforced ArkRun skip findings"),k=`Layer graph failures plus ${w.join(" and ")} (advisory extras never fail merge alone).`}else D?k=`Layer graph only \u2014 enforced ${[p?"ArkRules structure/invariant":null,_?"ArkRun":null].filter(x=>!!x).join(" and ")} findings are demoted under the teeth floor (need \u226550% governed and \u22651 populated layer); they do not merge-block until classification is honest.`:k="Layer graph only \u2014 no enforced ArkRules structure/invariant teeth on this tree. Advisory packs do not arm merge teeth."+(f?A==="advisory"?" Advisory ArkRun never merge-blocks.":" ArkRun extra is present but does not arm merge teeth.":" Absence of arkRun is silent.");let T={layers:{role:"inter-layer-edges",alwaysOnGate:!0,note:"Import/export layer graph \u2014 the default merge plane. Absent arkRules or arkRun changes nothing here."},structureSensors:{role:"intra-layer-heuristics",total:c,enforced:l,advisory:u,note:"Structure sensors are heuristics (prefer false negatives). Only mode:enforced fails merge; noisy sensors stay advisory by default. Advisory-only packs never add merge teeth (FG-ARKRULES-ADVISORY-ONLY)."},invariants:{role:"catalog-plus-coverage",total:y,enforced:m,advisory:g,covered:Ae(a?.covered),uncovered:Ae(a?.uncovered),note:"Invariants are catalog + coverage evidence, not a business runtime. Enforced + proven-uncovered fails merge; absence of enforced rules adds no extra teeth."},arkRun:{role:"kernel-usage-and-declarations",present:f,mode:A,residualCount:v,extraMergeTeeth:R,note:f?A==="enforced"?"Enforced ArkRun arms extra merge teeth only when the layer plane is classified. Residual is a count, never a score.":"Advisory ArkRun never adds merge teeth and never flips valid. Residual is a count, never a score.":"Absence of arkRun is silent \u2014 Layers and ArkRules verdicts unchanged. The extra never becomes a score."},extraMergeTeeth:b,dualPlaneStamp:vs,failMergeWhen:k};return s&&(T.classificationGate={governedPercent:n,populatedLayerCount:r,floorPercent:50,allowsTeeth:o}),T}i(Gn,"composeMergePlanesHonesty");var bs=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"],Ri=["publisher","publish","raise","raiseAsync","send","sendTo","subscribe","registerHandler","resolve","resolveSingleton"],ki=new Set(bs),Ei=new Set(["AggregateError","Array","ArrayBuffer","BigInt64Array","BigUint64Array","Boolean","DataView","Date","Error","EvalError","FinalizationRegistry","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Number","Object","Promise","Proxy","RangeError","ReferenceError","RegExp","Set","SharedArrayBuffer","String","Symbol","SyntaxError","TypeError","URIError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","WeakRef","WeakSet"]),Ii=new Set(["Array","Atomics","Buffer","JSON","Math","Number","Object","Promise","Reflect","String","console","fs","path","url","util"]);function mt(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")}i(mt,"isArkRunKernelModuleSpecifier");var Cs=["events","node:events","eventemitter2","eventemitter3","emittery","kafkajs","kafka-node","amqplib","amqp","bull","bullmq","mqtt","nats","@aws-sdk/client-sqs","@aws-sdk/client-sns","@aws-sdk/client-eventbridge","@google-cloud/pubsub","@azure/service-bus"],Bn=new Set(Cs);function qn(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(Bn.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(Bn.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:Bn.has(e.slice(0,r))}i(qn,"isArkRunTransportBypassSpecifier");function zn(e){if(ki.has(e))return"factory";switch(e){case"publisher":return"publisher";case"publish":return"publish";case"raise":case"raiseAsync":return"raise";case"send":case"sendTo":return"send";case"subscribe":return"subscribe";case"registerHandler":return"register-handler";case"resolve":return"resolve";case"resolveSingleton":return"resolve-singleton";default:return}}i(zn,"arkRunKernelCallKind");function ft(e,t){let n=1;for(let r=0;r<t;r+=1)e.charCodeAt(r)===10&&(n+=1);return n}i(ft,"lineAt");function gt(e){return e.replace(/\/\*[\s\S]*?\*\//g,t=>t.replace(/[^\n]/g," ")).replace(/(^|[^:\\])\/\/.*$/gm,t=>t.replace(/\/\/.*$/,n=>" ".repeat(n.length)))}i(gt,"stripCommentsPreservingLines");function vi(e,t){let n=e.slice(t),r=/^\s*(['"])((?:\\.|[^\\])*?)\1/.exec(n);if(!r)return;let s=r[2]??"";return s.length>0?s:void 0}i(vi,"firstStringLiteralArg");function Ss(e,t,n){let r=Math.max(0,t-n.length-8),s=e.slice(r,t);return new RegExp(`\\b${n}\\s+$`).test(s)}i(Ss,"keywordBefore");function jt(e,t){let n=/\b(?:import|export)(\s+type)?\s+([\s\S]*?)\s+from\s*['"]([^'"]+)['"]/g,r;for(;(r=n.exec(e))!==null;)r[1]||t(r[2]??"",r[3]??"")}i(jt,"parseValueImportClause");function Si(e,t){jt(gt(e),t)}i(Si,"forEachArkRunValueImportClause");function Wn(e,t){let n=gt(t),r=[],s=/\b(?:import|export)(\s+type)?\s+([\s\S]*?)\s+from\s*['"]([^'"]+)['"]/g,o;for(;(o=s.exec(n))!==null;){let l=o[3]??"";if(!l)continue;let c=o[0]??"";r.push({from:e,specifier:l,kind:/^\s*export/.test(c)?"export":"import",typeOnly:!!o[1],line:ft(t,o.index),resolution:"resolved-external"})}let a=/\b(?:require|import)\s*\(\s*['"]([^'"]+)['"]\s*\)/g;for(;(o=a.exec(n))!==null;){let l=o[1]??"";if(!l)continue;let c=o[0]?.startsWith("import")?"dynamic-import":"require";r.push({from:e,specifier:l,kind:c,typeOnly:!1,line:ft(t,o.index),resolution:"resolved-external"})}return r}i(Wn,"extractArkRunValueImportDependenciesFromSource");function Yn(e){let t=[];return Si(e,n=>{let r=/\{([^}]*)\}/.exec(n);if(r?.[1])for(let s of r[1].split(",")){let o=s.trim();if(!o||o.startsWith("type "))continue;let a=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(o),l=a?.[2]??/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(o)?.[1],c=a?.[1]??l;l&&c&&/^[A-Z]/.test(c)&&t.push(l,c)}}),pt(t)}i(Yn,"extractArkRunImportedConstructorNamesFromSource");function bi(e){let t=new Map,n=new Set;return jt(e,(r,s)=>{if(!mt(s))return;let o=/\*\s+as\s+([A-Za-z_][A-Za-z0-9_]*)/.exec(r);o?.[1]&&n.add(o[1]);let a=/^([A-Za-z_][A-Za-z0-9_]*)\s*(?:,|$)/.exec(r.trim());a?.[1]&&t.set(a[1],a[1]);let l=/\{([^}]*)\}/.exec(r);if(l?.[1])for(let c of l[1].split(",")){let u=c.trim();if(!u||u.startsWith("type "))continue;let m=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(u);if(m){t.set(m[2],m[1]);continue}let y=/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(u);y?.[1]&&t.set(y[1],y[1])}}),{named:t,namespaces:n}}i(bi,"collectKernelImportBindings");function Ci(e,t){let n=new Set(t);return jt(e,(r,s)=>{let o=/\{([^}]*)\}/.exec(r);if(o?.[1])for(let a of o[1].split(",")){let l=a.trim();if(!l||l.startsWith("type "))continue;let c=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(l),u=c?.[2]??/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(l)?.[1],m=c?.[1]??u;!u||!m||!/^[A-Z]/.test(m)||(mt(s)||t.has(m)||t.has(u))&&(n.add(u),n.add(m))}}),n}i(Ci,"collectImportedConstructors");function Oi(e,t){let n;return jt(e,(r,s)=>{!n&&new RegExp(`\\b${t}\\b`).test(r)&&(n=s)}),n}i(Oi,"importedFromForName");function Jn(e,t){let n=gt(t),r=bi(n),s=[],o=/\b([A-Za-z_][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,a;for(;(a=o.exec(n))!==null;){let l=a[1],c=a.index;if(Ss(n,c,"function")||Ss(n,c,"class"))continue;let m=n.slice(0,c).match(/([A-Za-z_][A-Za-z0-9_]*)\s*\.\s*$/)?.[1],y=r.named.get(l)??l,g=zn(y)??zn(l);if(!g)continue;let p=r.named.has(l)||m!==void 0&&r.namespaces.has(m);if(g!=="factory"&&(!p&&m===void 0||m&&Ii.has(m)&&!p))continue;let f=vi(n,c+a[0].length);s.push({file:e,line:ft(t,c),kind:g,callee:l,viaImport:p,...m?{receiver:m}:{},...f?{nameLiteral:f}:{}})}return s}i(Jn,"extractArkRunKernelCallsFromSource");function Xn(e,t,n){let r=gt(t),s=Ci(r,n),o=[],a=/\bnew\s+(?:[A-Za-z_][A-Za-z0-9_]*\s*\.\s*)*([A-Z][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,l;for(;(l=a.exec(r))!==null;){let c=l[1];if(Ei.has(c)||!s.has(c))continue;let u=Oi(r,c);o.push({file:e,line:ft(t,l.index),typeName:c,...u?{importedFrom:u}:{}})}return o}i(Xn,"extractArkRunManagedNewsFromSource");function _i(e,t){let n=0,r;for(let s=t;s<e.length;s+=1){let o=e[s];if(r){if(o==="\\"){s+=1;continue}o===r&&(r=void 0);continue}if(o==="'"||o==='"'||o==="`"){r=o;continue}if(o==="[")n+=1;else if(o==="]"&&(n-=1,n===0))return s}return-1}i(_i,"matchingBracketEnd");function xi(e,t,n){let r=e.slice(t+1,n),s=[],o=/(['"])((?:\\.|[^\\])*?)\1/g,a;for(;(a=o.exec(r))!==null;){let l=a[2]??"";l.length>0&&s.push(l)}return s}i(xi,"stringLiteralsInList");function pt(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}i(pt,"uniqueSorted");function Ti(e,t){let n=gt(t),r=/\b(uses|reactsTo|raises|sends)\s*:/g,s=[],o=[],a=[],l=[],c,u;for(;(u=r.exec(n))!==null;){let m=n.slice(u.index+u[0].length),y=/^\s*\[/.exec(m);if(!y)continue;let g=u.index+u[0].length+(y[0].length-1),p=_i(n,g);if(p<0)continue;let f=xi(n,g,p);if(f.length===0)continue;c===void 0&&(c=u.index);let A=u[1];A==="uses"?s.push(...f):A==="reactsTo"?o.push(...f):A==="raises"?a.push(...f):l.push(...f)}return c===void 0?[]:[{file:e,line:ft(t,c),uses:pt(s),reactsTo:pt(o),raises:pt(a),sends:pt(l)}]}i(Ti,"extractArkRunDeclarationsFromSource");var Ni=["arkrun-missing-root","arkrun-kernel-in-domain","arkrun-direct-new","arkrun-undeclared-emit","arkrun-undeclared-handle","arkrun-undeclared-depend","arkrun-transport-bypass"],Li=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],Pi=new Set(Li);function wi(e){return Pi.has(e)}i(wi,"isArkRunEditorSensor");var Zn={"arkrun-missing-root":"ARKRUN_MISSING_ROOT","arkrun-kernel-in-domain":"ARKRUN_KERNEL_IN_DOMAIN","arkrun-direct-new":"ARKRUN_DIRECT_NEW","arkrun-undeclared-emit":"ARKRUN_UNDECLARED_EMIT","arkrun-undeclared-handle":"ARKRUN_UNDECLARED_HANDLE","arkrun-undeclared-depend":"ARKRUN_UNDECLARED_DEPEND","arkrun-transport-bypass":"ARKRUN_TRANSPORT_BYPASS"},xs="ARKRUN_INTERACTION_NAME_INCOMPLETE";function Ts(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)||/^(?:entit(?:y|ies)|aggregates?)(?:$|(?=[A-Z_\-\s]))/i.test(n)?!0:t.some(r=>{let s=r.trim().replace(/\.+$/,"");return s==="Domain"||s.startsWith("Domain.")})}i(Ts,"isDomainRoleLayer");function Di(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}i(Di,"compareFindings");function ke(e,t,n,r,s,o,a){let l=e.mode==="enforced"&&a;return{ruleId:Zn[t],sensor:t,message:s,file:n,line:r,...o?.fromLayer?{fromLayer:o.fromLayer}:{},...o?.target?{target:o.target}:{},severity:l?"error":"warning",failsStrict:l,nextAction:fe({ruleId:Zn[t],fromLayer:o?.fromLayer,target:o?.target})}}i(ke,"finding");function Mi(e,t){let n=[],r=[],s=[],o=[];for(let a of e)a.file===t&&(n.push(...a.uses),r.push(...a.reactsTo),s.push(...a.raises),o.push(...a.sends));return{uses:new Set(n),reactsTo:new Set(r),raises:new Set(s),sends:new Set(o)}}i(Mi,"bagForFile");function Os(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}i(Os,"emitKinds");function _s(e){return e==="subscribe"||e==="register-handler"}i(_s,"handleKinds");function Fi(e){return e==="resolve"||e==="resolve-singleton"}i(Fi,"dependKinds");function $i(e,t,n){let r=[],s=e.kernelRoots??e.compositionRoots;if(s.length===0)return r.push(ke(e,"arkrun-missing-root","ark.config.json",1,"ArkRun kernelRoots is empty; no createArkKernel factory site is declared.",void 0,n)),r;let o=new Map;for(let a of t){let l=o.get(a.matchedRoot)??[];l.push(a),o.set(a.matchedRoot,l)}for(let a of s){let l=[...o.get(a)??[]].sort((u,m)=>u.file.localeCompare(m.file));if(l.length===0){r.push(ke(e,"arkrun-missing-root","ark.config.json",1,`ArkRun kernel root ${JSON.stringify(a)} matched no governed files and has no createArkKernel factory.`,{target:a},n));continue}if(l.some(u=>u.hasKernelFactory))continue;let c=l[0];r.push(ke(e,"arkrun-missing-root",c.file,1,`ArkRun kernel root ${JSON.stringify(a)} has no createArkKernel / createStrictArkKernel factory.`,{target:a},n))}return r}i($i,"evaluateMissingRoot");function Hi(e,t,n,r,s){let o=new Map(t.map(l=>[l.name,l.intentPrefixes??[]])),a=[];for(let l of n){let c=l.specifier;if(!c||!mt(c))continue;let u=r(l.from);u&&Ts(u,o.get(u)??[])&&a.push(ke(e,"arkrun-kernel-in-domain",l.from,l.line,`${u} must not import kernel module ${JSON.stringify(c)}.`,{fromLayer:u,target:c},s))}return a}i(Hi,"evaluateKernelInDomain");function ji(e,t,n,r,s,o){let a=new Set(e.managedLayers);if(a.size===0)return[];let l=new Map(t.map(m=>[m.name,m.intentPrefixes??[]])),c=new Set(r.filter(m=>m.hasKernelFactory).map(m=>m.file)),u=[];for(let m of n){if(c.has(m.file))continue;let y=m.typeName;if(e.ignoreDirectNewForErrors!==!1&&(y.endsWith("Error")||y==="Error")||y.endsWith("DTO")||y.endsWith("VO"))continue;let g=s(m.file);!g||!a.has(g)||Ts(g,l.get(g)??[])||u.push(ke(e,"arkrun-direct-new",m.file,m.line,`${g} must not construct ${m.typeName} with new outside an ArkRun composition-root factory.`,{fromLayer:g,target:m.typeName},o))}return u}i(ji,"evaluateDirectNew");function Vi(e,t,n,r,s){let o=[],a=[];if(e.requireDeclarations!==!0)return{findings:o,completenessReasons:a};let l=new Set(e.managedLayers);if(l.size===0)return{findings:o,completenessReasons:a};for(let c of t){if(!Os(c.kind)&&!_s(c.kind)&&!Fi(c.kind))continue;let u=r(c.file);if(!u||!l.has(u))continue;if(!c.nameLiteral){e.mode==="enforced"&&a.push({code:xs,file:c.file,message:`ArkRun ${c.kind} call in ${c.file} has no string-literal name; enforced extra cannot prove the declaration.`});continue}let m=Mi(n,c.file);if(Os(c.kind)){if(m.raises.has(c.nameLiteral)||m.sends.has(c.nameLiteral))continue;o.push(ke(e,"arkrun-undeclared-emit",c.file,c.line,`Emit ${JSON.stringify(c.nameLiteral)} is not declared in raises or sends.`,{fromLayer:u,target:c.nameLiteral},s));continue}if(_s(c.kind)){if(m.reactsTo.has(c.nameLiteral))continue;o.push(ke(e,"arkrun-undeclared-handle",c.file,c.line,`Handle ${JSON.stringify(c.nameLiteral)} is not declared in reactsTo.`,{fromLayer:u,target:c.nameLiteral},s));continue}m.uses.has(c.nameLiteral)||o.push(ke(e,"arkrun-undeclared-depend",c.file,c.line,`Depend ${JSON.stringify(c.nameLiteral)} is not declared in uses.`,{fromLayer:u,target:c.nameLiteral},s))}return{findings:o,completenessReasons:a}}i(Vi,"evaluateUndeclared");function Ui(e,t,n,r){let s=new Set(e.managedLayers);if(s.size===0)return[];let o=[];for(let a of t){if(a.typeOnly)continue;let l=a.specifier;if(!l||!qn(l))continue;let c=n(a.from);!c||!s.has(c)||o.push(ke(e,"arkrun-transport-bypass",a.from,a.line,`${c} must not import broker/queue/emitter ${JSON.stringify(l)}; use the ArkRun kernel transport.`,{fromLayer:c,target:l},r))}return o}i(Ui,"evaluateTransportBypass");function Vt(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=Re(e.classification),r=Vi(t,e.kernelCalls,e.declarations,e.layerForFile,n),s=[...$i(t,e.compositionRootHits,n),...Hi(t,e.layers,e.dependencies,e.layerForFile,n),...ji(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...Ui(t,e.dependencies,e.layerForFile,n)].sort(Di),o=[...r.completenessReasons].sort((a,l)=>{let c=`${a.code}\0${a.file??""}\0${a.message}`,u=`${l.code}\0${l.file??""}\0${l.message}`;return c<u?-1:c>u?1:0});return{findings:s,completenessReasons:o}}i(Vt,"evaluateArkRunSensors");function Ns(e){return{findings:Vt(e).findings.filter(n=>wi(n.sensor)),completenessReasons:[]}}i(Ns,"evaluateArkRunEditorSensors");function Ki(e,t){if(e===t)return!0;let n=e.indexOf("*");if(n<0)return!1;let r=e.slice(0,n).replace(/\/$/,"");return r.length>0&&(t===r||t.startsWith(`${r}/`))}i(Ki,"fileMatchesCompositionRoot");function Gi(e,t,n){let r=Jn(t,n).some(a=>a.kind==="factory"),s=[],o=e.kernelRoots??e.compositionRoots;for(let a of o)Ki(a,t)&&s.push({file:t,matchedRoot:a,hasKernelFactory:r});return s}i(Gi,"compositionRootHitsForSource");function Bi(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=new Set(Yn(e.source));return Ns({arkRun:t,layers:e.layers,kernelCalls:[],managedNews:Xn(e.file,e.source,n),compositionRootHits:Gi(t,e.file,e.source),declarations:[],dependencies:Wn(e.file,e.source),layerForFile:e.layerForFile,classification:e.classification})}i(Bi,"evaluateArkRunEditorSensorsFromSource");function Ls(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}i(Ls,"isArkOrderModuleSpecifier");var Ps=new Map;function ws(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(ws,"escapeAppliesToLiteral");function zi(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}i(zi,"normalizeAppliesToGlob");function qi(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}i(qi,"appliesToBracesBalanced");function Wi(e){let t=Ps.get(e);if(t)return t;let n=zi(e),r=qi(n),s="",o=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(s+=ws(n[l+1]),l+=1):c==="*"?n[l+1]==="*"?n[l+2]==="/"?(s+="(?:.*/)?",l+=2):(s+=".*",l+=1):s+="[^/]*":c==="?"?s+="[^/]":c==="{"&&r?(s+="(?:",o+=1):c==="}"&&r&&o>0?(s+=")",o-=1):c===","&&r&&o>0?s+="|":s+=ws(c)}let a=new RegExp(`^${s}$`);return Ps.set(e,a),a}i(Wi,"globToRegExp");var Yi=["arkorder-missing-plane","arkorder-kernel-in-domain","arkorder-generic-update","arkorder-too-many-params","arkorder-ingest-writes-xi","arkorder-xi-field-write","arkorder-information-budget","arkorder-xi-ttl"],Qn={"arkorder-missing-plane":"ARKORDER_MISSING_PLANE","arkorder-kernel-in-domain":"ARKORDER_KERNEL_IN_DOMAIN","arkorder-generic-update":"ARKORDER_GENERIC_UPDATE","arkorder-too-many-params":"ARKORDER_TOO_MANY_PARAMS","arkorder-ingest-writes-xi":"ARKORDER_INGEST_WRITES_XI","arkorder-xi-field-write":"ARKORDER_XI_FIELD_WRITE","arkorder-information-budget":"ARKORDER_INFORMATION_BUDGET","arkorder-xi-ttl":"ARKORDER_XI_TTL"};function Ji(e,t){return!t||t.length===0?!0:t.some(n=>Wi(n).test(e))}i(Ji,"matchesArkOrderAppliesTo");function Xi(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)?!0:t.some(r=>{let s=r.trim().replace(/\.+$/,"");return s==="Domain"||s.startsWith("Domain.")})}i(Xi,"isDomainRoleLayer");function ve(e,t,n,r,s,o,a){let l=e.mode==="enforced"&&a;return{ruleId:Qn[t],sensor:t,message:s,file:n,line:r,...o?.fromLayer?{fromLayer:o.fromLayer}:{},...o?.target?{target:o.target}:{},severity:l?"error":"warning",failsStrict:l,nextAction:fe({ruleId:Qn[t],fromLayer:o?.fromLayer,target:o?.target})}}i(ve,"finding");function er(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let n=Re(e.classification),r=[],s=t.planeRoots;if(t.mode==="enforced"&&s.length===0)r.push(ve(t,"arkorder-missing-plane","ark.config.json",1,"ArkOrder planeRoots is empty; no createOrderPlane site is declared.",void 0,n));else{let c=new Map;for(let u of e.planeRootHits){let m=c.get(u.matchedRoot)??[];m.push(u),c.set(u.matchedRoot,m)}for(let u of s){let m=c.get(u)??[];if(m.length===0){r.push(ve(t,"arkorder-missing-plane","ark.config.json",1,`ArkOrder plane root ${JSON.stringify(u)} matched no governed files and has no createOrderPlane factory.`,{target:u},n));continue}m.some(y=>y.hasPlaneFactory)||r.push(ve(t,"arkorder-missing-plane",m[0].file,1,`ArkOrder plane root ${JSON.stringify(u)} has no createOrderPlane factory.`,{target:u},n))}}let o=new Map(e.layers.map(c=>[c.name,c.intentPrefixes??[]]));for(let c of e.dependencies){let u=c.specifier;if(!u||!Ls(u))continue;let m=e.layerForFile(c.from);m&&Xi(m,o.get(m)??[])&&r.push(ve(t,"arkorder-kernel-in-domain",c.from,c.line,"Domain-role layer imports arkgate/order; Domain stays plane-free.",{fromLayer:m,target:u},n))}for(let c of e.genericUpdates)r.push(ve(t,"arkorder-generic-update",c.file,c.line,`Generic ${c.method}() on the order plane rewrites \u03BE; Haken forbids it.`,{target:c.method},n));let a=t.xiKeys??[];for(let c of e.releaseKeyCounts??[])c.keyCount<=t.maxXiKeys||r.push(ve(t,"arkorder-too-many-params",c.file,c.line,`release() freezes ${c.keyCount} keys; maxXiKeys is ${t.maxXiKeys} (few slow modes).`,{target:String(c.keyCount)},n));for(let c of e.ingestWritesXi??[])r.push(ve(t,"arkorder-ingest-writes-xi",c.file,c.line,"ingest() result is assigned into a Release or \u03BE store; ingest may absorb or escalate, never mint a pattern.",void 0,n));let l=new Set(t.managedLayers);for(let c of a.length===0?[]:e.xiFieldWrites??[]){let u=e.layerForFile(c.file);!u||!l.has(u)||Ji(c.file,t.appliesTo)&&r.push(ve(t,"arkorder-xi-field-write",c.file,c.line,`File writes slow key ${JSON.stringify(c.key)} through a persistence driver; route the field through ingest or a pattern change through proposeRelease.`,{fromLayer:u,target:c.key},n))}return r.sort((c,u)=>c.file.localeCompare(u.file)||c.ruleId.localeCompare(u.ruleId)||c.line-u.line),{findings:r,completenessReasons:[]}}i(er,"evaluateArkOrderSensors");function re(e,t,n={}){return{ruleId:e,message:t,...n}}i(re,"configWarning");function Ut(e){let{config:t,rules:n,files:r,manifest:s}=e,o=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(p=>typeof p!="string"))&&o.push(re("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)))o.push(re("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let p of["maxTsSuppressions","maxAnyCasts"]){let f=t.safety[p];f!==void 0&&(!Number.isInteger(f)||f<0)&&o.push(re("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${p} must be a non-negative integer.`))}let a=Array.isArray(t.layers)?t.layers:[],l=Array.isArray(s?.architecture?.layers)?s.architecture.layers:[],c=new Set([...a.map(p=>p.name).filter(Boolean),...l.map(p=>p.name).filter(p=>!!p)]);a.length===0&&o.push(re("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let u=new Set,m=new Set;for(let p of a){if(!p.name){o.push(re("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}u.has(p.name)&&m.add(p.name),u.add(p.name),p.forbiddenGlobals!==void 0&&(!Array.isArray(p.forbiddenGlobals)||p.forbiddenGlobals.some(A=>typeof A!="string"))&&o.push(re("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${p.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:p.name}));let f=Array.isArray(p.patterns)?p.patterns:[];if(f.length===0){o.push(re("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${p.name}" has no file patterns and will never classify files.`,{layer:p.name}));continue}for(let A of f){let v;try{v=me(A)}catch(R){o.push(re("CONFIG_INVALID_LAYER_PATTERN",`Layer "${p.name}" has an invalid pattern "${A}": ${R instanceof Error?R.message:String(R)}`,{layer:p.name,pattern:A}));continue}let _=p.optional===!0||p.reserved===!0||p.allowEmpty===!0;!r.some(R=>v.test(R))&&!_&&o.push(re("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${p.name}" pattern "${A}" matched no included files (possible typo). Mark the layer reserved/allowEmpty if this house is reserved for later.`,{layer:p.name,pattern:A,failsStrict:!1,reserved:!1}))}}for(let p of m)o.push(re("CONFIG_DUPLICATE_LAYER",`Layer "${p}" is configured more than once.`,{layer:p}));if(c.size>0)for(let p of n??[])p.from&&!c.has(p.from)&&o.push(re("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${p.from}".`,{fromLayer:p.from,toLayer:p.to})),p.to&&!c.has(p.to)&&o.push(re("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${p.to}".`,{fromLayer:p.from,toLayer:p.to}));let y=new Set;if(a.length>1)for(let p of r){let f=-1,A=[];for(let v of a)for(let _ of v.patterns??[]){if(!me(_).test(p))continue;let R=pn(_,p);R>f?(f=R,A=[v.name]):R===f&&!A.includes(v.name)&&A.push(v.name)}A.length>1&&y.add([...A].sort().join(" + "))}y.size>0&&o.push(re("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...y].join(", ")}.`,{pairs:[...y]}));let g=r.filter(p=>!de(p,a));return g.length>0&&o.push(re("CONFIG_UNCLASSIFIED_FILES",`${g.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:g.length,samples:g.slice(0,5)})),o}i(Ut,"collectAnalysisConfigWarnings");function Zi(e,t){return t.some(n=>{try{return me(n).test(e)}catch{return!1}})}i(Zi,"matchesAny");function Qi(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,o=e.contract.config.dynamicImportAllowlist??[],a=t.safetyUses.filter(A=>A.kind==="ts-suppression").map(({file:A,line:v})=>({file:A,line:v})),l=t.safetyUses.filter(A=>A.kind==="any-cast").map(({file:A,line:v})=>({file:A,line:v})),c=t.safetyUses.filter(A=>(A.kind==="dynamic-import"||A.kind==="dynamic-require")&&!Zi(A.file,o)).map(A=>({file:A.file,line:A.line,kind:A.kind==="dynamic-require"?"require":"import"})),u=n.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(A=>A.kind==="in-memory-store").map(A=>({file:A.file,line:A.line,store:A.symbol??"in-memory store"})),m=n.allowDisabledPeerIsolation===!0?[]:(e.contract.config.rules??[]).filter(A=>A.peerIsolation===!1||A.allowed===!1&&!!A.from&&A.from===A.to&&A.peerIsolation!==!0).map(A=>({from:A.from,to:A.to})),y={tsSuppressions:a,anyCasts:l,nonLiteralDynamicImports:c,inMemoryProductionStores:u,disabledPeerIsolationRules:m,thresholds:{maxTsSuppressions:r,maxAnyCasts:s}},g=[],p=c.filter(A=>A.kind==="import");if(p.length>0){let A=p[0];g.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:A.file,line:A.line,message:`${p.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let f=c.filter(A=>A.kind==="require");if(f.length>0){let A=f[0];g.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:A.file,line:A.line,message:`${f.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(a.length>r){let A=a[0];g.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:A.file,line:A.line,message:`${a.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${r}).`})}if(l.length>s){let A=l[0];g.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:A.file,line:A.line,message:`${l.length} explicit any cast(s) exceed safety.maxAnyCasts (${s}).`})}if(u.length>0){let A=u[0];g.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:A.file,line:A.line,message:`${u.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 m.length>0&&g.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${m.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:y,warnings:g}}i(Qi,"evaluateSafety");function el(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}i(el,"ambientForbiddenGlobal");function Ds(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return An(e,n.length>0?n:hn.map(r=>({name:r.layer,prefixes:r.prefixes})))}i(Ds,"intentLayer");function tl(e,t,n){let r=[],s=new Map(e.contract.config.layers.map(o=>[o.name,o]));for(let o of t.ambientUses){let a=n.get(o.file);!a||!el(o.symbol,s.get(a)?.forbiddenGlobals??[])||r.push({ruleId:"FORBIDDEN_GLOBAL",file:o.file,line:o.line,fromLayer:a,target:o.symbol,message:`${a} must not use the ambient global "${o.symbol}".`})}for(let o of t.capabilityUses){let a=n.get(o.file);if(!a)continue;let l=s.get(a),c=l?.forbiddenGlobals??[],u=o.source==="import-based"?t.dependencies.find(m=>m.from===o.file&&m.line===o.line&&m.specifier===o.symbol&&!m.typeOnly)?.kind:void 0;if(!(o.source==="ambient-global"&&Xe(o.symbol,c))){if(o.source==="import-based"){let m=Ee(o.symbol,c);if(m){r.push({ruleId:"FORBIDDEN_GLOBAL",file:o.file,line:o.line,fromLayer:a,target:o.symbol,...u?{edgeKind:u}:{},message:`${a} must not use module "${o.symbol}" because it is the import form of forbidden global "${m}".`});continue}}De(l).includes(o.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:o.file,line:o.line,fromLayer:a,target:o.symbol,capability:o.capability,...u?{edgeKind:u}:{},message:o.source==="import-based"?`${a} denies the ${o.capability} capability; found import of "${o.symbol}".`:`${a} denies the ${o.capability} capability; found ambient "${o.symbol}".`})}}for(let o of t.publishCalls){let a=n.get(o.file);if(!a)continue;for(let c of Ze({publishCall:!0,rawIntentName:o.rawIntentName,objectHasIntent:o.objectHasIntent,arkPublishCandidate:o.arkPublishCandidate,hasSource:o.hasSource}))r.push({ruleId:c.ruleId,file:o.file,line:o.line,...c.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:a}:{},message:c.message});if(!o.sourceIntent)continue;let l=Ds(o.sourceIntent,e.contract);!l||l===a||r.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:o.file,line:o.line,fromLayer:a,toLayer:l,target:o.sourceIntent,message:`Publish source "${o.sourceIntent}" resolves to ${l}, but the publishing file is classified as ${a}.`})}for(let o of t.intentReferences){let a=n.get(o.file);if(!a)continue;let l=Ds(o.intent,e.contract);if(!l)continue;let c=be(e.contract.config.rules,a,l,{fromPath:o.file,layers:e.contract.config.layers});if(!c)continue;let u=c.rule.peerIsolation?Me(c.peerIsolationReason??"cross-slice",{fromPath:o.file,fromSlice:c.fromSlice,toSlice:c.toSlice}):void 0,m=`${a} must not reference ${l} intent ${o.intent}.`,y=u&&c.peerIsolationReason!=="cross-slice"?`${m} ${u}`:c.rule.message?u?`${c.rule.message} (${u})`:c.rule.message:m;r.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:o.file,line:o.line,fromLayer:a,toLayer:l,target:o.intent,...c.rule.peerIsolation?{peerIsolation:!0}:{},message:y})}return r}i(tl,"contentViolations");function nl(e){let{facts:t}=e,n=st(e.contract.config),r=t.evidenceRequirementsHash===n,s=r?t.completeness:"unavailable",o=r?t.completenessReasons:[...t.completenessReasons,{code:"EVIDENCE_REQUIREMENTS_MISMATCH",message:"Resolved facts were collected for different policy-controlled evidence requirements."}].sort((d,P)=>{let j=`${d.code}\0${d.file??""}\0${d.message}`,ie=`${P.code}\0${P.file??""}\0${P.message}`;return j<ie?-1:j>ie?1:0}),a=t.files.map(d=>({...d,layer:de(d.path,e.contract.config.layers)??null})),l=new Map(a.map(d=>[d.path,d.layer])),c=t.dependencies.map(d=>{let P=d.target?l.get(d.target)??de(d.target,e.contract.config.layers):void 0;return{from:d.from,fromLayer:l.get(d.from)??null,...d.resolution==="resolved-project"&&d.target?{to:d.target,...P?{toLayer:P}:{}}:{},line:d.line,kind:d.kind,typeOnly:d.typeOnly,...d.targetTypeOnlyExports?{targetTypeOnlyExports:d.targetTypeOnlyExports}:{},...d.sourcePureTypeModule?{sourcePureTypeModule:d.sourcePureTypeModule}:{},...d.namedBindingsTypeOnly?{namedBindingsTypeOnly:d.namedBindingsTypeOnly}:{},...d.portProofEligible?{portProofEligible:d.portProofEligible}:{}}}),u=Ut({config:e.contract.config,rules:e.contract.config.rules,files:a.map(d=>d.path)}),m=Qi(e,t),y=e.contract.arkRules??Te(),g=a.map(d=>d.path),f={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?jn(e.coverageInputs.fileContents):{},...e.fileHints??{}},A=[...$n({arkRules:y,classShapes:e.contract.classShapes??t.classShapes??[],files:g,layerForFile:i(d=>l.get(d)??de(d,e.contract.config.layers),"layerForFile"),fileHints:f}),...Hn(y,g)],v=A.filter(d=>d.failsStrict).map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,arkruleId:d.arkruleId,arkruleSource:d.arkruleSource,nextAction:d.ruleId==="ARKRULE_SCOPE_EMPTY"?`Fix appliesTo globs for ${d.arkruleId} in ${d.arkruleSource} so they match governed files, or remove the rule.`:`Fix the structure or invariant for ${d.arkruleId} (declared in ${d.arkruleSource}), then preflight again.`})),_=A.filter(d=>!d.failsStrict).map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,arkruleId:d.arkruleId,arkruleSource:d.arkruleSource,failsStrict:!1,nextAction:d.ruleId==="ARKRULE_SCOPE_EMPTY"?`Review appliesTo for ${d.arkruleId} in ${d.arkruleSource} (zero-match scope; advisory).`:`Review ArkRule ${d.arkruleId} in ${d.arkruleSource} (advisory).`})),I=(y.invariants?.length??0)>0?Tn({arkRules:y,fileContents:e.coverageInputs?.fileContents??{},testFiles:e.coverageInputs?.testFiles??[],testGlobsMissing:e.coverageInputs?.testGlobsMissing===!0||e.coverageInputs===void 0||(e.coverageInputs.testFiles?.length??0)===0,coverageBudgetExhausted:e.coverageInputs?.coverageBudgetExhausted===!0,...e.coverageInputs?.stats?{coverageStats:e.coverageInputs.stats}:{},...e.coverageInputs?.coverageRoots?{coverageRoots:e.coverageInputs.coverageRoots}:{}}):{coverage:[],violations:[],partial:!1},b=I.violations.filter(d=>d.failsStrict).map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,arkruleId:d.arkruleId,arkruleSource:d.arkruleSource,nextAction:`Add a test title or declared symbol covering ${d.arkruleId} (declared in ${d.arkruleSource}), then preflight again.`})),D=I.violations.filter(d=>!d.failsStrict).map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,arkruleId:d.arkruleId,arkruleSource:d.arkruleSource,failsStrict:!1,nextAction:d.ruleId==="INVARIANT_COVERAGE_OUTSIDE_ROOTS"?`Move ${d.file} under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json.`:`Cover invariant ${d.arkruleId} in ${d.arkruleSource} (advisory / partial).`})),k=Un(a),T=Vt({arkRun:e.contract.config.arkRun,layers:e.contract.config.layers,kernelCalls:t.arkRunKernelCalls,managedNews:t.arkRunManagedNews,compositionRootHits:t.arkRunCompositionRootHits,declarations:t.arkRunDeclarations,dependencies:t.dependencies,layerForFile:i(d=>l.get(d)??de(d,e.contract.config.layers),"layerForFile"),classification:k}),w=e.contract.config.arkRun?.mode,x=T.findings.filter(()=>w==="enforced").map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,target:d.target,nextAction:d.nextAction,sensor:d.sensor,failsStrict:d.failsStrict,...d.severity?{severity:d.severity}:{}})),H=T.findings.filter(()=>w!=="enforced").map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,target:d.target,nextAction:d.nextAction,sensor:d.sensor,failsStrict:!1})),M=er({arkOrder:e.contract.config.arkOrder,layers:e.contract.config.layers,planeCalls:t.arkOrderPlaneCalls,genericUpdates:t.arkOrderGenericUpdates,planeRootHits:t.arkOrderRootHits,xiFieldWrites:t.arkOrderXiFieldWrites,ingestWritesXi:t.arkOrderIngestWritesXi,releaseKeyCounts:t.arkOrderReleaseKeyCounts,dependencies:t.dependencies,layerForFile:i(d=>l.get(d)??de(d,e.contract.config.layers),"layerForFile"),classification:k}),te=e.contract.config.arkOrder?.mode,pe=M.findings.filter(()=>te==="enforced").map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,target:d.target,nextAction:d.nextAction,sensor:d.sensor,failsStrict:d.failsStrict,...d.severity?{severity:d.severity}:{}})),we=M.findings.filter(()=>te!=="enforced").map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,target:d.target,nextAction:d.nextAction,sensor:d.sensor,failsStrict:!1})),Ye=[...I.partial&&I.coverage.some(d=>d.mode==="enforced"&&d.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."}]:[],...T.completenessReasons,...M.completenessReasons],Se=Ge({config:e.contract.config,rules:e.contract.config.rules,files:a.filter(d=>d.layer).map(d=>d.path),contentViolations:[...tl(e,t,l),...v,...b,...x,...pe],edges:c,warnings:[...u,...m.warnings,..._,...D,...H,...we],safety:m.report}),At=s==="complete"&&Ye.length>0?"partial":s,en=At==="complete"?o:[...o,...Ye].sort((d,P)=>{let j=`${d.code}\0${d.file??""}\0${d.message}`,ie=`${P.code}\0${P.file??""}\0${P.message}`;return j<ie?-1:j>ie?1:0}),S=Se.violations.filter(d=>d.failsStrict!==!1),C=At==="complete"&&S.length===0,h=C&&Se.warnings.every(d=>d.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:At,completenessReasons:en,valid:C,strictValid:h,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:m.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:a,layers:e.contract.config.layers.map(d=>d.name),edges:c,capabilityUses:t.capabilityUses,violations:Se.violations,warnings:Se.warnings}}}i(nl,"analyzeCanonicalResolvedProject");function yt(e){return nl({contract:e.contract,facts:Ie(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints})}i(yt,"analyzeResolvedProject");function Ms(e){return J(V(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}i(Ms,"analysisTreeHash");function Fs(e){let t=ut(e),n=new Map(t.ir.files.map(f=>[f.path,f])),r=[],s=new Set,o=[];for(let f of e.changes){let A=f.path.replace(/\\/g,"/"),v=Ne(f.path);if(!v||v===".."||v.startsWith("../")||A.startsWith("/")||/^[A-Za-z]:\//.test(A)||A.includes("\0")){o.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(v)){o.push({ruleId:"DUPLICATE_CHANGE_PATH",file:v,line:1,message:`The atomic change set contains more than one operation for ${v}.`});continue}s.add(v),"delete"in f&&f.delete&&!n.has(v)&&o.push({ruleId:"DELETE_TARGET_MISSING",file:v,line:1,message:`Cannot delete ${v} because it is not present in the supplied base tree.`}),r.push("delete"in f&&f.delete?{path:v,delete:!0}:{path:v,content:"content"in f?f.content:""})}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."});let a=Ft({...e,changes:r}),l=new Map(a.ir.files.map(f=>[f.path,f])),c=a.ir.violations.filter(f=>f.ruleId==="CAPABILITY_VIOLATION"||f.ruleId==="FORBIDDEN_GLOBAL").map(f=>{let A=l.get(f.evidence.file)?.layer;return{ruleId:f.ruleId,file:f.evidence.file,line:f.evidence.line,target:f.symbol,...f.capability?{capability:f.capability}:{},...A?{fromLayer:A}:{},edgeKind:"import",message:f.message}}),u=Ge({config:e.contract.config,rules:e.contract.config.rules,files:a.ir.files.map(f=>f.path),contentViolations:c,edges:a.ir.edges.filter(f=>!!f.fromLayer).map(f=>({from:f.from,fromLayer:f.fromLayer,...f.to?{to:f.to}:{},...f.toLayer?{toLayer:f.toLayer}:{},line:f.evidence.line,kind:"import",...f.typeOnly?{typeOnly:!0}:{},...f.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),m=r.map(f=>{let A=Ne(f.path),v=n.get(A),_=l.get(A);return{path:A,operation:"delete"in f&&f.delete?"delete":v?"update":"create",...v?{beforeContentHash:v.contentHash}:{},..._?{candidateContentHash:_.contentHash}:{}}}).sort((f,A)=>f.path.localeCompare(A.path)),y=[...o,...u.violations].map(f=>({...f,nextAction:fe(f)})),g=y.filter(f=>f.failsStrict!==!1),p=e.changeMap?Ke({changeMap:e.changeMap,changes:m,baseDependencies:t.ir.edges.flatMap(f=>f.to?[{from:f.from,to:f.to}]:[]),candidateDependencies:a.ir.edges.flatMap(f=>f.to?[{from:f.from,to:f.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&a.valid&&g.length===0&&(p?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:a.ir.compilerOptionsHash,baseTreeHash:Ms(t.ir.files),candidateTreeHash:Ms(a.ir.files),baseCompleteness:t.completeness,candidateCompleteness:a.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:a.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...p?{convergence:p}:{},changes:m,violations:y,warnings:u.warnings}}i(Fs,"preflightChange");function rl(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}i(rl,"canonicalChangePath");function sl(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,o])=>({ruleId:"FACTS_IDENTITY_MISMATCH",file:"<change-set>",line:1,field:r,before:s,candidate:o,message:`Base and candidate facts must use the same ${r}.`}))}i(sl,"identityViolations");function ol(e,t,n,r){let s=n.get(t),o=r.get(t);return{path:t,operation:"delete"in e&&e.delete?"delete":s?"update":"create",...s?{beforeContentHash:s.contentHash}:{},...o?{candidateContentHash:o.contentHash}:{}}}i(ol,"preparedChange");function $s(e){let t=Ie(e.baseFacts),n=Ie(e.candidateFacts),r=yt({contract:e.contract,facts:t}),s=yt({contract:e.contract,facts:n}),o=new Map(t.files.map(p=>[p.path,p])),a=new Map(n.files.map(p=>[p.path,p])),l=sl(t,n),c=new Map,u=[];for(let p of e.changes){let f=rl(p.path);if(!f){l.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(c.has(f)){l.push({ruleId:"DUPLICATE_CHANGE_PATH",file:f,line:1,message:`The atomic change set contains more than one operation for ${f}.`});continue}c.set(f,p);let A=o.get(f),v=a.get(f);if("delete"in p&&p.delete)A||l.push({ruleId:"DELETE_TARGET_MISSING",file:f,line:1,message:`Cannot delete ${f} because it is not present in the supplied base facts.`}),v&&l.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:f,line:1,message:`Candidate facts still contain deleted file ${f}.`});else{let _="content"in p?p.content:"",R=J(_);v?v.contentHash!==R&&l.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:f,line:1,expectedContentHash:R,candidateContentHash:v.contentHash,message:`Candidate facts for ${f} do not match the declared content.`}):l.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:f,line:1,message:`Candidate facts do not contain changed file ${f}.`})}u.push(ol(p,f,o,a))}e.changes.length===0&&l.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});for(let p of new Set([...o.keys(),...a.keys()])){if(c.has(p))continue;let f=o.get(p),A=a.get(p);f&&A&&V(f)===V(A)||l.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:p,line:1,message:`Candidate facts change ${p}, but the atomic change set does not declare it.`})}let m=e.changeMap?Ke({changeMap:e.changeMap,changes:u,baseDependencies:r.ir.edges.flatMap(p=>p.to?[{from:p.from,to:p.to}]:[]),candidateDependencies:s.ir.edges.flatMap(p=>p.to?[{from:p.from,to:p.to}]:[])}):void 0,y=[...l,...s.ir.violations].map(p=>({...p,nextAction:fe(p)})),g=y.filter(p=>p.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&s.strictValid&&g.length===0&&(m?.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}:{},...m?{convergence:m}:{},changes:u.sort((p,f)=>p.path<f.path?-1:p.path>f.path?1:0),violations:y,warnings:s.ir.warnings}}i($s,"preflightResolvedChange");var Hs="1.0",al=12;function js(e){return e==="enforced"||e==="advisory"?e:null}i(js,"closedMode");function il(e){let t=new Set;if(!Array.isArray(e))return[];for(let n of e){let r=n?.ruleId;typeof r!="string"||!Kn(r)||t.has(r)||t.add(r)}return[...t].sort((n,r)=>n<r?-1:n>r?1:0)}i(il,"uniqueArkRunRuleIds");function ll(e){return!e||typeof e!="object"?{present:!1,mode:null,roots:0,layers:0,requireDeclarations:null}:{present:!0,mode:js(e.mode),roots:Array.isArray(e.compositionRoots)?e.compositionRoots.length:0,layers:Array.isArray(e.managedLayers)?e.managedLayers.length:0,requireDeclarations:e.requireDeclarations===!0}}i(ll,"extraFromConfig");function cl(e={}){let t=ll(e.arkRun),n=t.present?il(e.findings):[],r=n.slice(0,al),s=n.length,o=Gn({classification:e.classification,arkRules:{active:e.arkRules?.active===!0,structureEnforced:e.arkRules?.structureEnforced,structureTotal:e.arkRules?.structureTotal,structureAdvisory:e.arkRules?.structureAdvisory,invariantEnforced:e.arkRules?.invariantEnforced,invariantTotal:e.arkRules?.invariantTotal,invariantAdvisory:e.arkRules?.invariantAdvisory,covered:e.arkRules?.covered,uncovered:e.arkRules?.uncovered},arkRun:{present:t.present,mode:t.mode,residualCount:s}}),a=t.present&&t.mode==="enforced"&&Re(e.classification),l;return t.present?t.mode==="advisory"?l="Advisory ArkRun residual only \u2014 never flips valid or --strict-merge. Residual is a finding-id count, never a score.":a?l="Enforced ArkRun is on the extra merge plane. Residual is a finding-id count, never a score.":l="Enforced ArkRun extra teeth stay demoted until the layer plane is honestly classified. Residual is a finding-id count, never a score.":l="Absence of arkRun is silent \u2014 Layers and ArkRules verdicts unchanged. Not a score.",{schemaVersion:Hs,notAScore:!0,active:t.present,mode:t.mode,compositionRoots:t.roots,managedLayers:t.layers,requireDeclarations:t.requireDeclarations,residual:{count:s,ruleIds:r},extraMergeTeeth:a,failMergeWhen:o.failMergeWhen,note:l,mergePlanes:o}}i(cl,"summarizeArkRunSection");function tr(e={}){let t=e.present===!0,n=js(e.mode),r=e.residual,s=null;return typeof r=="number"&&Number.isFinite(r)&&r>=0&&(s=Math.floor(r)),t||(s=s??0),{notAScore:!0,present:t,mode:t?n:null,extraMergeTeeth:t&&n==="enforced"&&e.extraMergeTeeth===!0,residual:s}}i(tr,"projectStatusArkRun");function dl(e){if(!e||e.notAScore!==!0)return[];if(e.active!==!0)return["ArkRun extra is off \u2014 silent on Layers/ArkRules (not a score)."];let t=e.mode??"unknown",n=e.extraMergeTeeth===!0?"armed":"not armed",r=[`mode: ${t} \xB7 extra merge teeth ${n} \xB7 not a score`];if(e.residual.count>0){let s=e.residual.ruleIds.join(", "),o=e.residual.count>e.residual.ruleIds.length?` (+${e.residual.count-e.residual.ruleIds.length} more)`:"";r.push(`Residual: ${s}${o}`)}else r.push("Residual: none on this scan (not a score \u2014 green extras \u2260 finished kernel wiring).");return e.failMergeWhen&&r.push(e.failMergeWhen),r}i(dl,"formatArkRunDoctorLines");function Kt(e,t){return e.slice(0,t).split(`
16
- `).length}i(Kt,"lineOf");function Vs(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}i(Vs,"normalizeInventoryPath");function Ks(e,t){return e.some(n=>{let r=n.trim().replace(/\.+$/,"");return t.some(s=>r===s||r.startsWith(`${s}.`))})}i(Ks,"ownsIntent");function Us(e,t=[]){return/domain|entity|aggregate|model/i.test(e)||Ks(t,["Domain"])}i(Us,"isDomainLayer");function ul(e,t=[]){return/application|orchestration|presentation|adapter|framework|interface|delivery|transport|inbound|controller/i.test(e)||Ks(t,["Application","Orchestration","Presentation","Adapter","Interface","Delivery","Transport"])}i(ul,"isControllerEligibleLayer");function pl(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)}i(pl,"isNonPilotSurface");function fl(e){let t=[],n=0,r=new Map(Object.entries(e.fileLayers??{}).map(([c,u])=>[Vs(c),u])),s=new Map((e.layerContexts??[]).map(c=>[c.name,c.intentPrefixes??[]])),o=(e.layerContexts??[]).find(c=>Us(c.name,c.intentPrefixes))?.name??"DomainModel";for(let[c,u]of Object.entries(e.fileContents).sort(([m],[y])=>m.localeCompare(y))){let m=Vs(c);if(pl(m)||/GENERATED FILE\s+[—-]\s+do not edit by hand/i.test(u.slice(0,320)))continue;let y=r.has(m),g=r.get(m),p=g?s.get(g)??[]:[],f=/(?:^|\/)(?:components|ui|layouts|styles|hooks|theme|tokens|i18n|locales?)(?:\/|$)/i.test(m)||/(?:^|\/)(?:src\/)?(?:app|pages)\/.+\.(?:tsx|jsx)$/i.test(m)&&/(?:page|layout|loading|error|template|default)\.(?:tsx|jsx)$/i.test(m),A=/(?:^|\/)(?:app|pages)(?:\/[^/]+)*\/api(?:\/|$)/i.test(m),v=/(?:^|\/)actions?(?:\/|\.|$)/i.test(m)||/['"]use server['"]/.test(u),_=/controller|handler|resolver/i.test(c)||A||v||/route\.(?:ts|js|tsx|jsx)$/i.test(m)&&!f||/@(Controller|Get|Post|Put|Delete|Patch)\b/.test(u)||/\bexport\s+(?:async\s+)?function\s+(?:GET|POST|PUT|DELETE|PATCH)\b/.test(u)||/\bexport\s+const\s+(?:GET|POST|PUT|DELETE|PATCH)\s*=/.test(u),R=y?!!(g&&ul(g,p)&&_):_,I=y?!!(g&&Us(g,p)):/domain|entity|aggregate|model/i.test(c),b=!y||I||R;if(R&&!f){let x=/\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,H;for(;(H=x.exec(u))!==null;)n+=1,t.push({id:`inv-val-${n}`,kind:"validation-in-controller",file:c,line:Kt(u,H.index),message:"Business validation appears in a controller/handler \u2014 extract an invariant or Domain rule.",confidence:"direct-evidence",governedLayer:g,suggestedArkRule:{layer:o,invariantId:`INV-EXTRACT-${n}`,sensor:"invariant-coverage"},neverMechanicalSafe:!0})}let D=/\b(const|let)\s+([A-Z][A-Z0-9_]{2,})\s*=\s*(\d{2,}|['"][^'"]{8,}['"])/g,k,T=i(x=>/^(?: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(x)||/^(?: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(x)||/_(?:ROUTE|PATH|LABEL|TITLE|COLOR|THEME|CLASS|STYLE|ICON|ARIA|MSG|COPY|TIMEOUT|PORT|VERSION|RETRY|DELAY|INTERVAL|TTL|CACHE)$/i.test(x)||/_(?:TIMEOUT(?:_MS)?|MS|BYTES|BUCKET|STORAGE_KEY|WINDOW_MS)$/i.test(x)||/^(?: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(x)||/^(?:FAVORITES_STORAGE|LISTINGS_CACHE|DOCS_PATH|METRICS_INTERVAL)/i.test(x)||/^(?:DEV|DEMO|SEED|FIXTURE)_[A-Z0-9_]+$/i.test(x)||/^(?:PG|POSTGRES|OID)_[A-Z0-9_]+$/i.test(x)||/_(?:OID|OIDS)$/i.test(x)||/^(?:INT2|INT4|INT8|FLOAT4|FLOAT8|NUMERIC|DATE|TIME|TIMESTAMP|TIMESTAMPTZ|JSON|JSONB|UUID)OID$/i.test(x)||/(?:^|_)(?:SCHEMA|PROTOCOL|RESOLVER|FORMAT)_(?:URL|URI|VERSION|ID|IDENTITY)$/i.test(x),"isInfraMagicName"),w=i((x,H)=>{if(/^(?:ERROR|SUCCESS|WARNING|INFO|HINT|HELP|EMPTY|TOAST|SNACK|ALERT|BANNER|DIALOG|MODAL|TOOLTIP|CAPTION|SUBTITLE|HEADLINE|USER|UI|DISPLAY|FEEDBACK)_(?:MSG|MESSAGE|TEXT|COPY|LABEL|TITLE|BODY|DESC|DESCRIPTION|HINT|HELP)?/i.test(x)||/_(?:MSG|MESSAGE|TEXT|COPY|TOAST|SNACK|ALERT|BANNER|CAPTION|HINT|HELP_TEXT|ERROR_TEXT|EMPTY_TEXT|PLACEHOLDER_TEXT|USER_MESSAGE|FEEDBACK)$/i.test(x))return!0;let M=H.replace(/^['"]|['"]$/g,"");return!!(/^['"]/.test(H)&&(/\s/.test(M)||/[.!?…]$/.test(M))&&!/^(?:STATUS|STATE|PHASE|ROLE|TYPE|KIND|ORDER|PAYMENT|CART|INVOICE|POLICY)_[A-Z0-9_]+$/i.test(x))},"isUxMessageConstant");for(;(k=D.exec(u))!==null;){let x=k[2],H=k[3]??"";!b||T(x)||w(x,H)||f&&!I||/(?:^|\/)(?:integrations?|repos?|clients?|infra(?:structure)?|adapters?)(?:\/|$)/i.test(m)&&!I||(n+=1,t.push({id:`inv-magic-${n}`,kind:"magic-business-constant",file:c,line:Kt(u,k.index),message:`Magic business constant ${x} may belong in a Domain policy or invariant catalog.`,confidence:"heuristic",governedLayer:g,suggestedArkRule:{layer:o,invariantId:`INV-${x}`},neverMechanicalSafe:!0}))}if(I){let x=/export\s+class\s+([A-Za-z_][A-Za-z0-9_]*)\s*\{([^}]{0,800})\}/g,H;for(;(H=x.exec(u))!==null;){let M=H[2]??"",te=(M.match(/\b[a-zA-Z_][a-zA-Z0-9_]*\s*\(/g)??[]).length;(M.match(/:\s*[A-Za-z]/g)??[]).length>=2&&te<=1&&(n+=1,t.push({id:`inv-anemic-${n}`,kind:"anemic-entity",file:c,line:Kt(u,H.index),message:`Class ${H[1]} looks anemic (data-heavy, few behaviors).`,confidence:"heuristic",governedLayer:g,suggestedArkRule:{layer:o,structureId:"no-anemic-model",sensor:"no-anemic-model"},neverMechanicalSafe:!0}))}}if(I&&!(/\.error\.(?:ts|js|tsx|jsx)$/i.test(m)||/(?:^|\/)[^/]*(?:-access)?\.error\./i.test(m)||/(?:^|\/)errors?(?:\/|$)/i.test(m))){let H=/this\.\w+\s*=/g,M;for(;(M=H.exec(u))!==null;){let te=u.lastIndexOf("class ",M.index),pe=te>=0?u.indexOf("{",te):-1,we=te>=0&&pe>=te&&pe<M.index?u.slice(te,pe):"";if(/\bextends\s+(?:Error|[A-Za-z_$][A-Za-z0-9_$]*Error)\b/.test(we))continue;let We=u.slice(Math.max(0,M.index-200),M.index+200);if(!/\b(ensureInvariants|assertInvariants|validate|publish|emit)\b/.test(We)){n+=1,t.push({id:`inv-mut-${n}`,kind:"mutation-without-guard",file:c,line:Kt(u,M.index),message:"Domain field mutation without nearby guard/publish call.",confidence:"heuristic",governedLayer:g,suggestedArkRule:{layer:o,structureId:"events-on-mutation",sensor:"domain-event-on-mutation"},neverMechanicalSafe:!0});break}}}}let a=new Set(e.contractedRuleIds??[]);t.sort((c,u)=>+(u.confidence==="direct-evidence")-+(c.confidence==="direct-evidence")||c.file.localeCompare(u.file)||c.line-u.line||c.kind.localeCompare(u.kind)||c.id.localeCompare(u.id));let l=t.filter(c=>c.suggestedArkRule?.invariantId&&a.has(c.suggestedArkRule.invariantId)||c.suggestedArkRule?.structureId&&a.has(c.suggestedArkRule.structureId)).length;return{candidates:t,inventoried:t.length,underContract:l,frozen:(e.frozenKeys??[]).length,notAScore:!0}}i(fl,"buildRulesInventory");function ml(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."}}i(ml,"inventoryToExtractionCard");var gl="1.1";var yl="1.0";var nr="docs/diagnostics.md",hl="1.0";function E(e,t,n,r,s,o){return{ruleId:e,title:n,why:r,fix:s,docsAnchor:e,category:t,...o?.oftenAdvisory?{oftenAdvisory:!0}:{}}}i(E,"entry");var Gt=Object.freeze([E("LAYER_IMPORT_VIOLATION","layer","Layer import not allowed","A module import (or re-export) crosses a layer edge that ark.config.json does not allow. The architecture contract forbids that dependency direction so outer infrastructure cannot leak into pure or inner layers.","Branch by import kind: constants/types/pure \u2192 adopt into DomainModel or SharedKernel (do not invent a port); kernel/events/bootstrap from Persistence \u2192 inject a port or move the map to SharedTypes (Persistence must not emit); define a port only when the target is a real use-case. Type-only edges use `import type`. Then preflight again. Do not weaken the layer rule without a hash-bound policy acknowledgement."),E("LAYER_INTENT_REFERENCE_VIOLATION","layer","Intent referenced across a blocked layer edge","A string intent (or intent-like reference) names a layer that the file\u2019s layer may not reach under the contract rules \u2014 the same plane as import edges, for event/intent coupling.","Reference that intent from a layer allowed to know about it (usually an adapter or application layer), or relocate the reference \u2014 then preflight again."),E("LAYER_REFERENCE_VIOLATION","layer","Layer reference blocked (snippet / AI gate)","Snippet analysis found an intent or string reference that would couple layers in a direction the architecture profile forbids.","Move the reference to an allowed layer or introduce a port/event boundary, then re-run the snippet gate."),E("CIRCULAR_DEPENDENCY","layer","Dependency cycle","Two or more modules import each other in a loop. Cycles make ownership unclear and break stable layer direction.","Extract the shared dependency into a third module, invert one edge behind a port, or merge units that are truly one \u2014 then preflight again."),E("FORBIDDEN_GLOBAL","capability","Forbidden ambient global or dual import","The file\u2019s layer lists this ambient (or its exact import dual, e.g. process / node:process) in forbiddenGlobals. Pure layers must not reach wall-clock, network, process, or similar effects directly.","Inject the capability through a small port (Clock, HttpPort, Config, \u2026), bind the implementation outside the walled layer, then preflight again."),E("CAPABILITY_VIOLATION","capability","Denied effect capability","The layer denies an effect capability (network, filesystem, clock, randomness, environment, process, persistence) and the candidate uses that effect via ambient or import evidence.","Define a capability port in the walled layer, bind the implementation in an adapter layer, then preflight again. Never mechanical-safe \u2014 port shape is a design decision."),E("RAW_EVENT_PUBLISH","publish","Raw event publish","Publish went through a raw string or object instead of a registered intent creator, bypassing Ark intent contracts and tooling.","Publish through a registered intent creator, then run Ark again."),E("PUBLISH_MISSING_SOURCE","publish","Publish missing metadata.source","A strict Ark publish call omitted metadata.source, so the publishing layer cannot be verified.","Add metadata.source to the publish call, then run Ark again."),E("PUBLISH_SOURCE_LAYER_MISMATCH","publish","Publish source layer mismatch","metadata.source resolves to a different layer than the file performing the publish.","Use a source intent owned by the same layer as this file, or move the publish call to the owning layer."),E("UNKNOWN_INTENT","publish","Unknown intent reference","Snippet analysis saw an intent string that is not registered in the intent registry / profile under check.","Register the intent or use a known intent name from the project registry, then re-run the gate."),E("DYNAMIC_IMPORT_NOT_ALLOWLISTED","safety","Non-literal dynamic import","A dynamic import(expr) cannot be resolved statically and the file is not on dynamicImportAllowlist. Unresolved dynamics can hide layer edges.","Rewrite to a static import when possible, or add only reviewed files to dynamicImportAllowlist after human sign-off."),E("DYNAMIC_REQUIRE_NOT_ALLOWLISTED","safety","Non-literal require","A require(expr) cannot be resolved statically and is not allowlisted \u2014 same hide-the-edge risk as dynamic import.","Prefer static import, or allowlist only reviewed files after sign-off."),E("TS_SUPPRESSION_THRESHOLD_EXCEEDED","safety","@ts-ignore / @ts-nocheck threshold","Count of TypeScript suppressions in governed production source exceeds safety.maxTsSuppressions.","Remove suppressions by fixing types, or raise the threshold only with an explicit production exception in ark.config.json."),E("ANY_CAST_THRESHOLD_EXCEEDED","safety","Explicit any cast threshold","Count of explicit any casts exceeds safety.maxAnyCasts.","Replace any with precise types, or raise the threshold only with a documented exception."),E("IN_MEMORY_STORE_IN_PRODUCTION_SOURCE","safety","In-memory store in production source","Governed production source references an Ark InMemory* store without safety.allowInMemory \u2014 durable systems should not ship ephemeral stores by accident.","Provide a durable store implementation, or set safety.allowInMemory only for an explicitly ephemeral service."),E("PEER_ISOLATION_DISABLED","safety","peerIsolation disabled on a rule","A same-layer or peer rule disables peerIsolation (or omits it where required), which allows cross-slice coupling the contract otherwise blocks.","Restore peerIsolation: true, or set safety.allowDisabledPeerIsolation only with a documented production exception."),E("ARKRULE_STRUCTURE","arkrules","ArkRule structure sensor failed","An opt-in ArkRules structure sensor (private state, factory shape, event publish, persistence write outside an aggregate, \u2026) failed on a governed file for a declared arkruleId.","Restore the declared structure for the ArkRule (see arkruleSource), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement."),E("ARKRULE_INVARIANT","arkrules","ArkRule invariant failed","Reserved / remediation-recognized code for invariant-plane failures bound to an ArkRule id (coverage path also emits INVARIANT_UNCOVERED).","Fix the invariant for the ArkRule declared in arkrules/<Layer>.json, then preflight again. Do not demote without acknowledgement."),E("ARKRULE_SCOPE_EMPTY","arkrules","ArkRule appliesTo matched zero files","An ArkRule\u2019s appliesTo globs matched no governed files \u2014 the rule cannot observe what it claims to protect.","Fix appliesTo globs so they match governed files, or remove the rule. Enforced empty scope fails; advisory empty scope warns.",{oftenAdvisory:!0}),E("INVARIANT_UNCOVERED","arkrules","Invariant without coverage evidence","An ArkRules invariant is under contract but no covering test title or declared symbol evidence was found (or coverage is partial). Kind is never-had-tests (adopt residual) vs tests-disappeared (suite exists).","Add a test title or declared symbol covering the arkruleId, then preflight again. Treat never-had-tests as adopt residual; treat tests-disappeared as a regression. Missing test globs report partial \u2014 never fake green. When the message reports an exhausted file budget, raise coverage.maxFiles (or narrow coverage.testGlobs) in ark.config.json."),E("INVARIANT_COVERAGE_OUTSIDE_ROOTS","arkrules","Covering test outside the declared coverage roots","The only test naming this invariant sits outside coverage.coverageRoots \u2014 the places the project declares its runner executes. ArkGate matches declared text and never executes tests, so it cannot tell whether that file is ever run: coverage there is a test that exists, not a test that runs.","Move the test under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json. Advisory: it never fails strict, but promotion to enforced refuses on it.",{oftenAdvisory:!0}),E("ARKRUN_MISSING_ROOT","arkrun","No kernel factory in composition roots","The ArkRun extra is on but no createArkKernel / createStrictArkKernel / createArkKernelFromConfig / createStrictArkKernelFromConfig factory was found in arkRun.compositionRoots, so agents can skip the kernel while the write gate stays green.","Import createStrictArkKernel from arkgate/runtime (same npm package; @arkgate/runtime is deprecated) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision."),E("ARKRUN_KERNEL_IN_DOMAIN","arkrun","Domain-role layer imports the kernel","A Domain-role layer imports arkgate/runtime, @arkgate/runtime, or kernel types. Domain stays kernel-free; composition roots and adapters own the factory.","Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from arkgate/runtime (same npm package; @arkgate/runtime is deprecated), then preflight again. Never mechanical-safe."),E("ARKRUN_DIRECT_NEW","arkrun","Managed type constructed with new","A managed non-Domain file constructs an admitted type with new outside an ArkRun composition-root factory, skipping kernel resolve/registration.","Resolve the type from the kernel instead of constructing it with new, then preflight again. Never mechanical-safe \u2014 rewiring construction is a design decision."),E("ARKRUN_UNDECLARED_EMIT","arkrun","Emit name not in raises/sends","A publisher / publish / raise / send call-site literal is not listed in the file\u2019s raises or sends declaration.","Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment."),E("ARKRUN_UNDECLARED_HANDLE","arkrun","Handle name not in reactsTo","A subscribe / registerHandler call-site literal is not listed in the file\u2019s reactsTo declaration.","Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment."),E("ARKRUN_UNDECLARED_DEPEND","arkrun","Depend name not in uses","A resolve / resolveSingleton call-site literal is not listed in the file\u2019s uses declaration.","Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment."),E("ARKRUN_TRANSPORT_BYPASS","arkrun","Homemade broker or emitter import","A managed layer imports a closed broker/queue/emitter specifier (EventEmitter, queue clients, \u2026) instead of the ArkRun kernel transport.","Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe \u2014 homemade buses stay judgment."),E("ARKORDER_MISSING_PLANE","arkorder","No createOrderPlane in plane roots","The ArkOrder extra is on but no createOrderPlane factory was found in arkOrder.planeRoots, so agents can skip the pattern plane while the write gate stays green.","Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision."),E("ARKORDER_KERNEL_IN_DOMAIN","arkorder","Domain-role layer imports the order plane","A Domain-role layer imports arkgate/order. Domain stays plane-free; planeRoots own the factory.","Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe."),E("ARKORDER_GENERIC_UPDATE","arkorder","Generic update of \u03BE","A call to update/patch/set on the order plane rewrites the slow pattern. Haken slaving forbids generic \u03BE mutation.","Use release() for the first freeze of \u03BE. Later pattern change is proposeRelease then apply(ProposeResult). Never update/patch/set. Never mechanical-safe."),E("ARKORDER_TOO_MANY_PARAMS","arkorder","Too many slow keys","\u03BE has more keys than arkOrder.maxXiKeys. Haken requires a few slow modes, not a dump of microstate.","Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe."),E("ARKORDER_INGEST_WRITES_XI","arkorder","ingest assigned into \u03BE","An ingest() result is written into a Release or \u03BE store. ingest may absorb, escalate_up, or hold; it never mints a pattern.","Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe."),E("ARKORDER_XI_FIELD_WRITE","arkorder","Slow key written around the order plane","A managed-layer file imports a persistence driver and writes a declared arkOrder.xiKeys name. Field events absorb or escalate; they do not PATCH the slow pattern.","Keep invoices, seats, hours, and logs on ingest. Change the slow key with proposeRelease then apply(ProposeResult), then preflight again. Never mechanical-safe."),E("ARKORDER_INFORMATION_BUDGET","arkorder","Projection observes a forbidden kind","h(\u03BE) allowedKinds includes a kind listed in informationBudget.cannotObserve. A scale may not look at what it was told not to see.","Cut that kind from the projector or from cannotObserve, then preflight again. Never mechanical-safe."),E("ARKORDER_XI_TTL","arkorder","Slow key carries a freshness field","\u03BE named ttl/freshUntil/maxAge. Freshness belongs on \u03C3. A slow parameter that expires per transaction is not slow.","Move freshness onto \u03C3 (freshUntil) and keep \u03BE stable, then preflight again. Never mechanical-safe."),E("ARKORDER_STALE_SIGMA","arkorder","\u03C3 is stale","ingest ran after \u03C3.freshUntil (or sigmaMaxAgeMs). \u03BE does not TTL.","Call refreshSigma and ingest again, or proposeRelease then apply(ProposeResult) if the pattern changed. Never mechanical-safe."),E("ARKORDER_UNVALVED_RELEASE","arkorder","Unvalved second freeze of \u03BE","release() ran after a pattern was already frozen and the new \u03BE differs. First freeze is release(); later pattern change is proposeRelease then apply.","Change \u03BE with proposeRelease then apply(ProposeResult). release() is only the first freeze. Never mechanical-safe."),E("INVALID_CHANGE_PATH","preflight","Unsafe change path","A change set entry is not a safe, non-empty project-relative path (absolute, escape, empty, or NUL).","Use canonical project-relative paths only in the atomic change set, then preflight again."),E("DUPLICATE_CHANGE_PATH","preflight","Duplicate path in change set","The atomic change set lists more than one operation for the same path.","Collapse to one create/update/delete per path, then preflight again."),E("DELETE_TARGET_MISSING","preflight","Delete target missing","A delete operation targets a path that is not present in the supplied base tree.","Remove the delete, or include the file in the base tree facts, then preflight again."),E("CHANGE_SET_EMPTY","preflight","Empty change set","Atomic preflight was invoked with no create, update, or delete operations.","Provide at least one change operation, then preflight again."),E("FACTS_IDENTITY_MISMATCH","preflight","Base/candidate facts identity mismatch","Base and candidate resolved facts disagree on resolver, compiler, evidence requirements, or package identity \u2014 verdicts would not be comparable.","Regenerate both fact snapshots with the same resolver/compiler/evidence requirements, then preflight again."),E("CANDIDATE_DELETE_NOT_APPLIED","preflight","Candidate still contains deleted path","Facts claim a delete, but the candidate tree still includes the path.","Ensure the candidate facts apply the delete (path absent), then preflight again."),E("CANDIDATE_CHANGE_MISSING","preflight","Declared change missing from candidate","The change set declares a create/update whose path is missing from candidate facts.","Include the new content in the candidate facts (or drop the operation), then preflight again."),E("CANDIDATE_CONTENT_HASH_MISMATCH","preflight","Candidate content hash mismatch","The candidate file content hash does not match the hash expected for the declared change.","Rebuild candidate facts from the exact proposed content, then preflight again."),E("UNDECLARED_CANDIDATE_CHANGE","preflight","Undeclared candidate change","Candidate facts differ from base for a path that was not listed in the explicit change set.","Declare every path that changes in the atomic change set, then preflight again."),E("ATOMIC_PREFLIGHT_UNAVAILABLE","preflight","Atomic preflight unavailable","The host/MCP path could not run the atomic preflight engine (missing facts, incomplete setup, or unsupported mode).","Use resolved-candidate facts / ark_prepare_change with a complete batch, or fall back to ark-check on disk. Do not treat missing preflight as green."),E("DESIGN_SMELL_REGRESSION","preflight","Design smell regression on base-relative ratchet","Compared to the base ref, the candidate introduces a created-path domain-logic-in-ui file under --strict-merge, or introduces or worsens a blocking design-smell class under --fail-on-new-smells.","Move the new UI business rule out of the created file (or revert a --fail-on-new-smells regression), then re-run with the same base ref."),E("ANALYSIS_PARSE_INCOMPLETE","analysis","Parse incomplete","Governed source could not be fully parsed; evidence includes the TypeScript diagnostic (line + message). Incremental mid-edit parse is normal for agents. Contract exclude paths skip the write hook.","Finish the source or fix the reported syntax error, then re-run `npx arkgate-check`. The write hook does not deny solely on mid-edit parse. Partial never means pass."),E("LEXICAL_EVIDENCE_INCOMPLETE","analysis","Lexical evidence incomplete","Single-file validation cannot prove project module resolution. The write hook is already the verdict.","Re-run `npx arkgate-check --root . --config ark.config.json`, or treat the hook deny as final. Do not call ark_prepare_change from a hook deny."),E("ANALYSIS_COVERS_NO_FILES","analysis","Analysis covered no files","No file matched the contract include and layer patterns under the analyzed root, so the run had nothing to check. Every rule is vacuously satisfied on an empty set: a green here would read exactly like a green over a governed tree while certifying nothing. Usual causes are a --root that is not the tree the contract describes (including a contract found outside the requested root, whose directory is then adopted as the project root), include / exclude patterns that match nothing, or layer patterns written for a different layout.","Point --root at the tree the contract describes, or keep the contract inside that tree, or fix the include / exclude / layer patterns so they match real files \u2014 then re-run `npx arkgate-check --root . --config ark.config.json`. This is a refusal about ArkGate\u2019s own inputs, not a finding about your code; no baseline or policy acknowledgement can suppress it."),E("ANALYSIS_HOST_UNAVAILABLE","analysis","Analysis host unavailable","No usable TypeScript / analysis host was available for this invocation.","Install a supported TypeScript version visible to the project, then re-run. Unavailable analysis is fail-closed."),E("ADAPTER_NOT_ALLOWED_FOR_PORT","adapter","Adapter not allowed for port","Runtime/port wiring selected an adapter implementation that the architecture profile does not allow for that port.","Bind an allowed adapter for the port, or adjust the profile with an explicit policy decision \u2014 then re-run."),E("FORBIDDEN_PATTERN","snippet-policy","Forbidden regex pattern","Snippet content matched a project or profile forbiddenPatterns rule.","Remove or rewrite the matching code so the pattern no longer matches, then re-run the snippet gate."),E("FORBIDDEN_SUBSTRING","snippet-policy","Forbidden substring","Snippet content contained a forbidden substring from the AI gate options/profile.","Remove the forbidden substring, then re-run the snippet gate."),E("FORBIDDEN_IMPORT","snippet-policy","Forbidden import target","Snippet imported or required a module listed as forbidden for the active profile.","Import an allowed module or inject the dependency behind a port, then re-run."),E("POLICY_VIOLATION","snippet-policy","Policy engine violation","A registered Policy failed on the snippet or generated code under evaluation.","Adjust the code to satisfy the named policy, or change the policy only through an explicit contract decision."),E("EXTENSION_ERROR","snippet-policy","AI gate extension error","A registered AICodeGate extension threw while analyzing the snippet.","Fix or remove the failing extension; do not ignore extension failures as pass."),E("AST_ANALYZER_ERROR","snippet-policy","AST analyzer error","Built-in AST/symbol analysis failed (host error or unexpected analyzer exception).","Ensure TypeScript host and snippet are valid; re-run. If the analyzer crashes on valid input, file a bug with a minimal fixture."),E("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","config","Invalid dynamicImportAllowlist","dynamicImportAllowlist is present but not an array of file globs.","Set dynamicImportAllowlist to an array of project-relative globs (or omit it).",{oftenAdvisory:!0}),E("CONFIG_INVALID_SAFETY","config","Invalid safety object","The safety field is present but not an object.","Use a safety object with optional maxTsSuppressions, maxAnyCasts, allowInMemory, allowDisabledPeerIsolation.",{oftenAdvisory:!0}),E("CONFIG_INVALID_SAFETY_THRESHOLD","config","Invalid safety threshold","A safety threshold (maxTsSuppressions / maxAnyCasts) is not a non-negative integer.","Set each threshold to a non-negative integer.",{oftenAdvisory:!0}),E("CONFIG_NO_LAYERS","config","No layers configured","ark.config.json has no file layers, so import-boundary enforcement cannot classify files.","Declare at least one layer with name + patterns (or run ark start / a preset).",{oftenAdvisory:!0}),E("CONFIG_LAYER_WITHOUT_NAME","config","Layer missing name","A configured layer entry has no name.","Give every layer a unique non-empty name.",{oftenAdvisory:!0}),E("CONFIG_INVALID_FORBIDDEN_GLOBALS","config","Invalid forbiddenGlobals","A layer\u2019s forbiddenGlobals is not an array of strings; the entry is ignored.",'Use an array of strings (e.g. ["fetch", "Date.now"]).',{oftenAdvisory:!0}),E("CONFIG_LAYER_WITHOUT_PATTERNS","config","Layer without patterns","A named layer has no file patterns and will never classify files.","Add patterns globs that match the layer\u2019s source tree.",{oftenAdvisory:!0}),E("CONFIG_INVALID_LAYER_PATTERN","config","Invalid layer pattern","A layer pattern is not a valid glob / failed to compile.","Fix the pattern syntax for that layer.",{oftenAdvisory:!0}),E("CONFIG_LAYER_PATTERN_NO_MATCHES","config","Layer pattern matched no files","A layer pattern matched zero included files (often a typo or include mismatch). Reserved/allowEmpty houses do not emit this.","Adjust the pattern or include roots, or mark the layer reserved/allowEmpty if the glob is a future house.",{oftenAdvisory:!0}),E("CONFIG_DUPLICATE_LAYER","config","Duplicate layer name","The same layer name appears more than once in configuration.","Rename or merge duplicate layer entries.",{oftenAdvisory:!0}),E("CONFIG_RULE_UNKNOWN_FROM_LAYER","config","Rule unknown from layer","A dependency rule references a source layer name that is not declared.","Fix the rule\u2019s from field to a declared layer name.",{oftenAdvisory:!0}),E("CONFIG_RULE_UNKNOWN_TO_LAYER","config","Rule unknown to layer","A dependency rule references a target layer name that is not declared.","Fix the rule\u2019s to field to a declared layer name.",{oftenAdvisory:!0}),E("CONFIG_AMBIGUOUS_LAYERS","config","Ambiguous layer classification","Some files match multiple layers at equal specificity; classification falls back to declaration order.","Disambiguate overlapping patterns so each file has one clear layer owner.",{oftenAdvisory:!0}),E("CONFIG_UNCLASSIFIED_FILES","config","Unclassified included files","Included source files match no layer pattern; import rules will not enforce on them.","Extend layer patterns or narrow include so every governed file is classified.",{oftenAdvisory:!0}),E("LITERAL_PATH_DRIFT","drift","Literal path moved by a rename","A repo path written inside a string, a comment or a docstring no longer resolves, and the rename set says where it went. Nothing in the gate sees this class: `tsc` resolves imports, not strings, and ESLint does not either, so the rename compiles green and the reference lies afterwards. It appears in four forms \u2014 the tsconfig alias, a relative literal, a path written without the include-root prefix, and prose \u2014 and a hand sweep reliably covers one of them.","Apply the suggested replacement, or re-run `npx arkgate-check --path-drift --base-ref <ref> --write` to apply every writable anchored replacement at once. The rewrite is mechanical and one-directional: the destination comes from the rename, it must itself resolve and be path-shaped, and the token is rewritten in the form the author wrote it in. A destination that leaves the alias root of the literal is reported with the target only and must be rewritten by hand."),E("LITERAL_PATH_UNRESOLVED","drift","Literal path does not resolve","A literal that looks like a repo path does not resolve under this root, and no rename explains where it went. Unlike LITERAL_PATH_DRIFT this is a candidate, not a verdict: with nothing to anchor it, ArkGate cannot tell a dead reference from an illustrative path in a comment, an example in documentation, or a path belonging to another tree.","Read the candidate and decide: fix the path, or leave it. Advisory only \u2014 it never fails a run and is never rewritten by --write, because there is no destination to propose. Run `--path-drift --all` to list the sweep.",{oftenAdvisory:!0}),E("ARK_UNKNOWN","meta","Unknown diagnostic","A diagnostic lacked a stable ruleId/code; adapters may emit this fallback so agents never see an empty id.","Resolve the underlying finding without weakening ark.config.json, then run Ark again. Prefer fixing the producer to emit a catalogued ruleId.")]),rr=new Map(Gt.map(e=>[e.ruleId,e])),Al=Object.freeze(Gt.map(e=>e.ruleId));function Rl(e){return typeof e=="string"&&e.length>0&&rr.has(e)}i(Rl,"isKnownDiagnosticCode");function kl(e){return typeof e!="string"||e.length===0?!1:rr.has(e)?!0:e.startsWith("ARKRULE_")}i(kl,"isCataloguedOrArkRuleFamily");function Bt(e){if(!(typeof e!="string"||e.length===0))return rr.get(e)}i(Bt,"getDiagnosticCatalogEntry");function Gs(e){return`#${Bt(e)?.docsAnchor??e}`}i(Gs,"diagnosticDocsFragment");function El(e){return`${nr}${Gs(e)}`}i(El,"diagnosticDocsPath");function Il(){return{schemaVersion:"1.0",docsPath:nr,codes:Gt}}i(Il,"serializeDiagnosticCatalog");function vl(e){return Bt(e)?.fix}i(vl,"catalogFixForRuleId");function Sl(e){return Bt(e)?.why}i(Sl,"catalogWhyForRuleId");var sr="1.0",Bs="https://unpkg.com/arkgate@4/schemas/ark.status-manifest.schema.json",zs=["full","subset","unavailable"],qs=["doctor-facts","report-snapshot","none"],zt={FACTS_UNAVAILABLE:"FACTS_UNAVAILABLE",FACTS_PARTIAL:"FACTS_PARTIAL",NO_SESSION_SNAPSHOT:"NO_SESSION_SNAPSHOT"},Ws=/^sha256:[a-f0-9]{64}$/;function Ys(e){let t=e.expectation;if(t==null||t.expectedRoot===void 0&&t.expectedProjectId===void 0)return{status:"matched",authoritative:!!e.resolvedRoot};if(t&&typeof t!="object")return{status:"mismatch",authoritative:!1,code:"INVALID_PROJECT_EXPECTATION",message:"project must be an object containing expectedRoot and/or expectedProjectId."};let n=t.expectedRoot,r=t.expectedProjectId;if(n!==void 0&&(typeof n!="string"||n.trim()===""))return{status:"mismatch",authoritative:!1,code:"INVALID_PROJECT_EXPECTATION",message:"project.expectedRoot must be a non-empty absolute path."};if(r!==void 0&&(typeof r!="string"||!Ws.test(r)))return{status:"mismatch",authoritative:!1,code:"INVALID_PROJECT_EXPECTATION",message:"project.expectedProjectId must be a sha256:<64 lowercase hex> identity."};if(n===void 0&&r!==void 0)return e.projectId&&r!==e.projectId?{status:"mismatch",authoritative:!1,expectedProjectId:r,code:"PROJECT_ID_MISMATCH",message:`Expected project id ${r}, but this process is bound to ${e.projectId}.`}:{status:"unverified",authoritative:!1,expectedProjectId:r,message:"project.expectedProjectId matched or could not be compared, but expectedRoot is required for an authoritative workspace binding."};let s=e.expectedRootRelation??"unknown";return s==="outside"?{status:"mismatch",authoritative:!1,expectedRoot:n,expectedProjectId:r,code:"PROJECT_ROOT_MISMATCH",message:`Expected workspace ${n}, but this process is bound to ${e.resolvedRoot}.`}:s==="unknown"?{status:"unverified",authoritative:!1,expectedRoot:n,expectedProjectId:r,message:"Could not prove expectedRoot against the resolved project root (stale or incomplete path evidence)."}:s==="descendant"&&r===void 0?{status:"unverified",authoritative:!1,expectedRoot:n,message:`Expected workspace ${n} is inside this project, but an exact project root is required for the initial authoritative handshake.`}:r!==void 0&&e.projectId&&r!==e.projectId?{status:"mismatch",authoritative:!1,expectedRoot:n,expectedProjectId:r,code:"PROJECT_ID_MISMATCH",message:`Expected project id ${r}, but this process is bound to ${e.projectId}.`}:s==="exact"||s==="descendant"&&r&&r===e.projectId?{status:"matched",authoritative:!0,...n?{expectedRoot:n}:{},...r?{expectedProjectId:r}:{}}:{status:"unverified",authoritative:!1,expectedRoot:n,expectedProjectId:r,message:"Project expectation could not be fully verified."}}i(Ys,"evaluateStatusBinding");function Js(e){if(e.writePathUnavailable===!0)return"unavailable";if(e.softWriteHost===!0)return"advisory";if(e.hardWriteActive===!0)return"hard";let t=typeof e.activeHost=="string"?e.activeHost.trim().toLowerCase():"";return!t||t==="unknown"?"unavailable":"advisory"}i(Js,"classifyStatusWritePath");function Xs(e,t){let n=t&&t!=="unknown"?t:"unknown-host";return e==="hard"?`Local write is hard for ${n} when the covered PreToolUse path is active; CI --strict-merge remains the merge backstop.`:e==="advisory"?`Local write is advisory for ${n}; hard merge boundary is a required status running arkgate-check --strict-merge (alias ark-check).`:"Write-path activation is unavailable or unverified for this invocation (no active host / incomplete evidence)."}i(Xs,"defaultHonestLabel");function Zs(e,t,n,r,s){return e.nextActionOverride?.id&&e.nextActionOverride.summary?{id:e.nextActionOverride.id,summary:e.nextActionOverride.summary}:t.status==="mismatch"?{id:"rebind-project-identity",summary:t.message||"Project expectation does not match this process \u2014 call ark_identity / ark status with the correct expectedRoot (and projectId for descendants)."}:t.status==="unverified"&&e.expectation?{id:"complete-identity-handshake",summary:t.message||"Supply project.expectedRoot at the exact project root (and expectedProjectId for descendants) for authoritative status."}:e.resolvedConfigPath?r.verdict==="fail"||(r.activeViolations??0)>0?{id:"fix-active-violations",summary:`Clear ${r.activeViolations??"active"} blocking architecture finding(s), then re-run ark-check (or ark-check --doctor).`}:r.verdict==="incomplete"?{id:"restore-complete-analysis",summary:"Last check was incomplete \u2014 restore TypeScript/analysis inputs and re-run ark-check."}:r.verdict==null&&r.at==null?{id:"run-ark-check",summary:"No last-check snapshot yet \u2014 run ark-check --report (or --doctor) to freeze session evidence."}:n.writePath==="unavailable"?{id:"install-write-path",summary:"Write path is unavailable \u2014 install agent gates for your host (ark start / --install-agent-gates) and keep required CI --strict-merge."}:n.writePath==="advisory"?{id:"keep-ci-merge-hard",summary:"Local write is advisory for this host \u2014 keep a required GitHub status on arkgate-check --strict-merge as the hard merge boundary."}:e.leftoverDesignWork===!0?{id:"map-leftover-design",summary:"Leftover design work remains. Map with /ark-explore, then apply one small refactor with /ark-autopilot. Green imports are not done."}:s.arkRulesLoaded&&(s.frozenResidual??0)>0?{id:"review-arkrules-residual",summary:"ArkRules residual remains frozen \u2014 review inventory debt without claiming a score."}:e.arkRun?.present===!0&&(e.arkRun.residual??0)>0?{id:"review-arkrun-residual",summary:"ArkRun residual remains \u2014 wire kernel usage or declarations through arkgate/runtime. Not a score."}:e.adopted==="required-merge"||e.adopted==="advisory-only-acked"?{id:"stay-enforced",summary:"Contract looks enforceable for this session \u2014 keep writing through the gate and re-check after structural edits."}:{id:"require-ci-merge-status",summary:'Make arkgate-check --strict-merge a required GitHub status, or write .ark/adoption-stance.json with stance: "advisory-only".'}:{id:"run-ark-start",summary:"No ark.config.json found \u2014 run ark start (preview) then ark start --apply."}}i(Zs,"resolveStatusNextAction");function bl(e){let t=typeof e.resolvedRoot=="string"&&e.resolvedRoot.length>0?e.resolvedRoot:".",n=typeof e.projectId=="string"&&Ws.test(e.projectId)?e.projectId:null,r=Ys({resolvedRoot:t,projectId:n,expectation:e.expectation,expectedRootRelation:e.expectedRootRelation}),s=typeof e.activeHost=="string"?e.activeHost.trim().toLowerCase():"",o=s&&s!=="unknown"?s:s==="unknown"?"unknown":null,a=Js({hardWriteActive:e.hardWriteActive,softWriteHost:e.softWriteHost,writePathUnavailable:e.writePathUnavailable,activeHost:o}),l=typeof e.honestLabel=="string"&&e.honestLabel.trim().length>0?e.honestLabel.trim():Xs(a,o),c={at:typeof e.lastCheckAt=="string"?e.lastCheckAt:null,verdict:e.lastCheckVerdict==="pass"||e.lastCheckVerdict==="fail"||e.lastCheckVerdict==="incomplete"?e.lastCheckVerdict:null,activeViolations:ht(e.activeViolations),frozenResidual:ht(e.frozenResidual)},u={arkRulesLoaded:e.arkRulesLoaded===!0,inventoried:ht(e.rulesInventoried),underContract:ht(e.rulesUnderContract),frozenResidual:ht(e.rulesFrozenResidual)},m={writePath:a,host:o,honestLabel:l},y={projectId:n,resolvedRoot:t,resolvedConfigPath:typeof e.resolvedConfigPath=="string"&&e.resolvedConfigPath.length>0?e.resolvedConfigPath:null,binding:r.status,authoritative:r.authoritative,...r.code?{code:r.code}:{},...r.message?{message:r.message}:{}},g={schemaVersion:sr,arkgateVersion:typeof e.arkgateVersion=="string"&&e.arkgateVersion.length>0?e.arkgateVersion:"unknown",projectIdentity:y,activation:m,lastCheck:c,rules:u,nextAction:Zs(e,r,m,c,u)},p=eo(e.improvementCompass);return p&&(g.improvementCompass=p),e.vsBase&&typeof e.vsBase.baseRef=="string"&&e.vsBase.baseRef.length>0&&(g.vsBase=e.vsBase),e.arkRun&&typeof e.arkRun=="object"&&(g.arkRun=tr(e.arkRun)),g}i(bl,"buildStatusManifest");var Qs=new Set(zs),Cl=new Set(qs);function or(e){let t=Qs.has(e.mode)?e.mode:"unavailable",n=e.factsSource!=null&&Cl.has(e.factsSource)?e.factsSource:t==="unavailable"?"none":void 0,r=typeof e.contractHash=="string"&&e.contractHash.length>0?e.contractHash:void 0;if(t==="unavailable"){let a={schemaVersion:"1.0",notAScore:!0,mode:"unavailable",topResidual:[],reasonCode:typeof e.reasonCode=="string"&&e.reasonCode.length>0?e.reasonCode:zt.FACTS_UNAVAILABLE,reason:typeof e.reason=="string"&&e.reason.length>0?e.reason:"Improvement compass facts are unavailable \u2014 run ark-check --doctor for residual lenses. Status never invents green.",factsSource:n??"none"};return r&&(a.contractHash=r),a}let s=Array.isArray(e.topResidual)?e.topResidual.filter(a=>typeof a=="string"&&a.length>0).slice(0,15):[],o={schemaVersion:"1.0",notAScore:!0,mode:t,topResidual:s};return t==="subset"?(o.reasonCode=typeof e.reasonCode=="string"&&e.reasonCode.length>0?e.reasonCode:zt.FACTS_PARTIAL,o.reason=typeof e.reason=="string"&&e.reason.length>0?e.reason:"Status compass is a subset of doctor residual \u2014 incomplete session facts; run doctor for full."):typeof e.reasonCode=="string"&&e.reasonCode.length>0&&(o.reasonCode=e.reasonCode),typeof e.reason=="string"&&e.reason.length>0&&t==="full"&&(o.reason=e.reason),n&&(o.factsSource=n),r&&(o.contractHash=r),o}i(or,"projectStatusImprovementCompass");function Ol(e={}){return or({mode:"unavailable",topResidual:[],reasonCode:e.reasonCode??zt.NO_SESSION_SNAPSHOT,reason:e.reason??"No session compass facts yet \u2014 run ark-check --doctor or --report for residual lenses. Status never invents green.",factsSource:"none",contractHash:e.contractHash})}i(Ol,"unavailableStatusImprovementCompass");function eo(e){if(e==null||typeof e!="object")return null;let t=e;if(t.notAScore!==!0||t.schemaVersion!=="1.0"||"score"in t||"valid"in t||"goal"in t)return null;let n;return typeof t.mode=="string"&&Qs.has(t.mode)?n=t.mode:Array.isArray(t.topResidual)?n="subset":n="unavailable",or({mode:n,topResidual:Array.isArray(t.topResidual)?t.topResidual:[],reasonCode:typeof t.reasonCode=="string"?t.reasonCode:null,reason:typeof t.reason=="string"?t.reason:null,factsSource:typeof t.factsSource=="string"?t.factsSource:null,contractHash:typeof t.contractHash=="string"?t.contractHash:null})}i(eo,"normalizeStatusImprovementCompass");function _l(e,t){let n=Array.isArray(e)?e:[],r=new Set(Array.isArray(t)?t:[]);for(let s of n)if(!(typeof s!="string"||s.length===0)&&!r.has(s))return!1;return!0}i(_l,"statusCompassResidualIsSubsetOfDoctor");function ht(e){if(e==null)return null;let t=Number(e);return!Number.isFinite(t)||t<0?null:Math.floor(t)}i(ht,"numberOrNull");var xl={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Bs,title:"ArkGate status manifest",description:"Unified session/project status snapshot for agents (identity, activation honesty, last check, rules counts, next action). Not a score.",type:"object",additionalProperties:!1,required:["schemaVersion","arkgateVersion","projectIdentity","activation","lastCheck","rules","nextAction"],properties:{schemaVersion:{const:sr},arkgateVersion:{type:"string",minLength:1},projectIdentity:{type:"object",additionalProperties:!1,required:["projectId","resolvedRoot","resolvedConfigPath","binding","authoritative"],properties:{projectId:{anyOf:[{type:"string",pattern:"^sha256:[a-f0-9]{64}$"},{type:"null"}]},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{anyOf:[{type:"string",minLength:1},{type:"null"}]},binding:{enum:["matched","unverified","mismatch"]},authoritative:{type:"boolean"},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},activation:{type:"object",additionalProperties:!1,required:["writePath","host","honestLabel"],properties:{writePath:{enum:["hard","advisory","unavailable"]},host:{anyOf:[{type:"string",minLength:1},{type:"null"}]},honestLabel:{type:"string",minLength:1}}},lastCheck:{type:"object",additionalProperties:!1,required:["at","verdict","activeViolations","frozenResidual"],properties:{at:{anyOf:[{type:"string",minLength:1},{type:"null"}]},verdict:{anyOf:[{enum:["pass","fail","incomplete"]},{type:"null"}]},activeViolations:{anyOf:[{type:"integer",minimum:0},{type:"null"}]},frozenResidual:{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}},rules:{type:"object",additionalProperties:!1,required:["arkRulesLoaded","inventoried","underContract","frozenResidual"],properties:{arkRulesLoaded:{type:"boolean"},inventoried:{anyOf:[{type:"integer",minimum:0},{type:"null"}]},underContract:{anyOf:[{type:"integer",minimum:0},{type:"null"}]},frozenResidual:{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}},nextAction:{type:"object",additionalProperties:!1,required:["id","summary"],properties:{id:{type:"string",minLength:1},summary:{type:"string",minLength:1}}},improvementCompass:{type:"object",description:"Thin improvement-compass residual ids with honesty mode (notAScore). full | subset | unavailable. Never a gate input; full lenses on doctor JSON. When full, residual ids \u2286 doctor residual for the same facts. unavailable never invents green residual.",additionalProperties:!1,required:["schemaVersion","notAScore","mode","topResidual"],properties:{schemaVersion:{const:"1.0"},notAScore:{const:!0},mode:{enum:["full","subset","unavailable"]},topResidual:{type:"array",items:{type:"string",minLength:1},maxItems:15},reasonCode:{type:"string",minLength:1},reason:{type:"string",minLength:1},factsSource:{enum:["doctor-facts","report-snapshot","none"]},contractHash:{type:"string",minLength:1}}},vsBase:{type:"object",description:"Checkout vs a git base ref: pin, contract identity, baseline grow. Advisory honesty only \u2014 never a gate input.",additionalProperties:!1,required:["baseRef","line","pinLocal","pinBase","contractEqual","baselineGrew"],properties:{baseRef:{type:"string",minLength:1},line:{type:"string",minLength:1},pinLocal:{anyOf:[{type:"string",minLength:1},{type:"null"}]},pinBase:{anyOf:[{type:"string",minLength:1},{type:"null"}]},contractEqual:{type:"boolean"},baselineGrew:{type:"boolean"}}},arkRun:{type:"object",description:"ArkRun extra residual (notAScore). present/mode from config; residual is a finding-id count (null = unknown, not green). extraMergeTeeth is honesty, never a score.",additionalProperties:!1,required:["notAScore","present","mode","extraMergeTeeth","residual"],properties:{notAScore:{const:!0},present:{type:"boolean"},mode:{anyOf:[{enum:["advisory","enforced"]},{type:"null"}]},extraMergeTeeth:{type:"boolean"},residual:{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}}}};var qt="1.0",Wt=["soc","cohesion","coupling","srp","dip","ocp","encapsulation","modularity","scalability","resilience","security","maintainability","testability","domain","stack"],Yt=5,Pe=["scalability","resilience","security"],ze=new Set(Pe),ar={soc:10,coupling:20,dip:30,domain:40,srp:50,cohesion:60,encapsulation:70,modularity:80,testability:90,maintainability:100,ocp:110,stack:120,scalability:200,resilience:200,security:200},ir={soc:"Separation of concerns",cohesion:"High cohesion",coupling:"Low coupling",srp:"Single responsibility (architecture)",dip:"Dependency inversion",ocp:"Open/closed",encapsulation:"Encapsulation",modularity:"Modularity",scalability:"Scalability / performance",resilience:"Resilience / fault tolerance",security:"Security by design",maintainability:"Maintainability",testability:"Testability",domain:"Domain alignment",stack:"Stack-specific practices"},lr={scalability:"ArkGate does not measure performance or horizontal scale. Use load tests and APM outside Ark.",resilience:"ArkGate does not measure app resilience or chaos readiness. Structural boundaries and optional experimental runtime are not a resilience score.",security:"ArkGate does not run SAST or app-security tooling. Structural least-privilege of effects is partial only \u2014 not a security rating."};function cr(e){return ir[e]??e}i(cr,"improvementCompassHumanLabel");function dr(e){let t=e.id??e.smellId??"";return typeof t=="string"?t.trim():""}i(dr,"smellIdOf");function ur(e){let t=e.ruleId??e.code??"";return typeof t=="string"?t.trim():""}i(ur,"violationRuleId");function K(e,t,n,r){if(!n||e.evidence.some(o=>o.source===t&&o.ref===n))return;let s={source:t,ref:n};r&&r.trim()&&(s.detail=r.trim().slice(0,240)),e.evidence.push(s)}i(K,"pushEvidence");function ee(e,t,n){ze.has(e.id)||(e.status="residual",e.summary=t,n&&(e.nextAction=n))}i(ee,"markResidual");function to(e){switch(e){case"soc":return"No separation-of-concerns residual detected from current sensors.";case"cohesion":return"No cohesion residual (god-module / physical cohesion) from current sensors.";case"coupling":return"No coupling residual (import edges, cycles, peer isolation) from current sensors.";case"srp":return"No single-responsibility residual from current sensors.";case"dip":return"No dependency-inversion residual (pure / capability / forbidden walls) from current sensors.";case"ocp":return"Open/closed is not strongly instrumented \u2014 no switch-chain sensor.";case"encapsulation":return"No encapsulation residual from ArkRules structure sensors.";case"modularity":return"No modularity / placement residual from current sensors.";case"maintainability":return"No maintainability residual (design-weak / baseline honesty) from current sensors.";case"testability":return"No testability residual (impure domain / capability walls) from current sensors.";case"domain":return"No domain-alignment residual from current sensors.";case"stack":return"Stack practices are only partially instrumented (TypeScript / host / Ark idioms).";default:return`${ir[e]} \u2014 no residual from current sensors.`}}i(to,"defaultOkSummary");function no(){return Wt.map(e=>ze.has(e)?{id:e,status:"out-of-scope",summary:lr[e],evidence:[],nextAction:{kind:"docs",ref:"docs/use.md#improvement-compass",summary:"Out of scope for ArkGate \u2014 use dedicated tooling outside the gate."}}:e==="ocp"?{id:e,status:"not-instrumented",summary:to(e),evidence:[]}:{id:e,status:"ok",summary:to(e),evidence:[]})}i(no,"createInitialImprovementCompassLenses");function Tl(e,t){for(let n of t){let r=dr(n);if(!r)continue;let s=n.outcome||n.message||void 0,a=(Array.isArray(n.evidence)?n.evidence:[])[0],l=i((m,y,g)=>{let p=e.get(m);!p||ze.has(m)||(K(p,"designSmells",r,s),a&&K(p,"designSmells",a,r),ee(p,y,g))},"attach"),c={kind:"skill",ref:"/ark-explore",summary:"Map Shape residual (shape-focus), then apply one extraction pilot with /ark-autopilot."},u={kind:"skill",ref:"/ark-autopilot",summary:"Inject a port/adapter for I/O; keep domain pure."};switch(r){case"domain-logic-in-ui":l("soc","Business rules still mix with UI or presentation surfaces.",c),l("domain","Domain logic lives outside Domain \u2014 align rules with Domain ownership.",c);break;case"facade-sql-in-routes":l("soc","Routes/controllers own SQL or ORM access \u2014 concerns are mixed.",c),l("dip","Transport depends on concrete persistence instead of a port.",u);break;case"io-under-application":l("soc","Application/business code reaches I/O directly \u2014 separation is weak.",c),l("dip","I/O is not inverted behind ports/adapters.",u),l("testability","Direct I/O under application code hurts pure unit testing.",u);break;case"handler-in-persistence":l("soc","HTTP/transport handlers live under persistence folders.",c);break;case"god-module":l("cohesion","Large multi-responsibility modules reduce cohesion.",c),l("srp","God modules own too many responsibilities \u2014 split by concern (one pilot).",{kind:"skill",ref:"/ark-autopilot",summary:"One Shape pilot this turn \u2014 never multi-pilot batch."});break;case"mixed-pattern-cluster":l("modularity","Multiple layout styles coexist \u2014 placement is unclear for the next AI turn.",{kind:"skill",ref:"/ark-explore",summary:"Pick a golden pattern and migrate one pilot cluster on touch."}),l("cohesion","Mixed layout styles scatter the same concern across patterns.",c);break;case"soft-contract":l("maintainability","Soft contract walls (layers without deny rules) hide maintainability debt.",{kind:"skill",ref:"/ark-adopt",summary:"Add real layer rules so the AI has hard walls."}),l("coupling","Layers with files but almost no deny rules allow free peer coupling.",{kind:"skill",ref:"/ark-adopt",summary:"Tighten inter-layer allows/denies without weakening enforcement."});break;default:l("maintainability","Design residual remains under an unrecognized smell id \u2014 review evidence.",c);break}}}i(Tl,"mapDesignSmells");function Nl(e){return e.failsStrict===!1||e.typeOnly===!0}i(Nl,"isTypeOnlyPlacementDebt");function Ll(e,t){for(let n of t){let r=ur(n);if(!r)continue;let s=n.message,o=r.toUpperCase(),a=i((c,u,m)=>{let y=e.get(c);!y||ze.has(c)||(K(y,"violations",r,s),n.file&&K(y,"violations",n.file,r),ee(y,u,m))},"attach");if(Nl(n)){a("modularity","Type-only placement debt remains \u2014 prefer SharedTypes / owning layer (not runtime coupling).",{kind:"skill",ref:"/ark-place",summary:"Place shared types in a layer both sides may import; type-only debt is not a value edge."});continue}let l={kind:"skill",ref:"/ark-autopilot",summary:"Clear the active edge residual, then re-doctor."};if(o==="LAYER_IMPORT_VIOLATION"||o.includes("LAYER_IMPORT")||o==="DYNAMIC_IMPORT_VIOLATION"){a("coupling","Import graph edges violate the layer contract.",l);continue}if(o.includes("CYCLE")||o==="CIRCULAR_DEPENDENCY"){a("coupling","Import cycles couple modules tightly.",l);continue}if(o.includes("PEER_ISOLATION")||o==="PEER_ISOLATION_VIOLATION"){a("coupling","Peer isolation residual \u2014 slices import each other freely.",{kind:"skill",ref:"/ark-autopilot",summary:"Peer isolation fixes are judgment-class \u2014 one cluster at a time."});continue}if(o==="FORBIDDEN_GLOBAL"||o.startsWith("FORBIDDEN_")){a("dip","Forbidden globals / effect surfaces break dependency inversion.",{kind:"skill",ref:"/ark-autopilot",summary:"Inject a port instead of the forbidden global."}),a("testability","Forbidden ambient effects reduce pure-domain testability.",{kind:"skill",ref:"/ark-autopilot",summary:"Replace ambient effects with injectable ports."});continue}if(o==="CAPABILITY_VIOLATION"){a("dip","Denied capability use \u2014 invert through an allowed adapter/port.",{kind:"skill",ref:"/ark-autopilot",summary:"Capability walls require port injection (judgment, not mechanical-safe)."}),a("testability","Capability violations couple domain code to I/O \u2014 harder to unit-test.",{kind:"skill",ref:"/ark-autopilot",summary:"Keep pure layers free of denied capabilities."});continue}if(o.startsWith("ARKRULE_")||o==="INVARIANT_UNCOVERED"){a("encapsulation","ArkRules structure / invariant residual inside a layer.",{kind:"skill",ref:"/ark-autopilot",summary:"Label [ArkRules]; structure fixes are judgment \u2014 never invent mechanical-safe."}),a("domain","Intra-layer domain structure or invariant coverage residual.",{kind:"skill",ref:"/ark-explore",summary:"Inventory candidates \u2192 one ArkRules pilot with coverage evidence."});continue}}}i(Ll,"mapViolations");function Pl(e,t){let n=Number(t.cycleCount)||0;if(n>0){let p=e.get("coupling");K(p,"cycles",`count:${n}`),ee(p,"Import cycles couple modules tightly.",{kind:"skill",ref:"/ark-autopilot",summary:"Break cycles with a judgment extraction \u2014 one pilot."})}let r=typeof t.peerIsolationCount=="boolean"?t.peerIsolationCount?1:0:Number(t.peerIsolationCount)||0;if(r>0){let p=e.get("coupling");K(p,"peerIsolation",`count:${r}`),ee(p,"Peer isolation residual remains.",{kind:"skill",ref:"/ark-autopilot",summary:"Peer isolation is judgment-class residual."})}let s=Number(t.physicalCohesionFindingCount)||0;if(s>0){let p=e.get("cohesion");K(p,"physicalCohesion",`findings:${s}`),ee(p,"Physical cohesion residual \u2014 mirrored concept clusters across anchors.",{kind:"skill",ref:"/ark-explore",summary:"Review reshape pilot; one decision-aware pilot at a time."});let f=e.get("srp");K(f,"physicalCohesion",`findings:${s}`),ee(f,"Mirrored clusters suggest split-by-concern residual (architecture SRP).",{kind:"skill",ref:"/ark-autopilot",summary:"One reshape/extraction pilot this turn."})}let o=Number(t.pureOrCapabilityResidual)||0,a=Number(t.forbiddenGlobalResidual)||0;if(o>0||a>0){let p=e.get("dip");o>0&&K(p,"capability",`residual:${o}`),a>0&&K(p,"forbiddenGlobals",`residual:${a}`),ee(p,"Pure / capability / forbidden residual weakens dependency inversion.",{kind:"skill",ref:"/ark-autopilot",summary:"Inject ports; keep pure layers free of effects."});let f=e.get("testability");o>0&&K(f,"capability",`residual:${o}`),a>0&&K(f,"forbiddenGlobals",`residual:${a}`),ee(f,"Impure domain or capability residual reduces testability.",{kind:"skill",ref:"/ark-autopilot",summary:"Prefer ports over concrete I/O in pure/domain modules."})}let l=Number(t.arkRulesStructureResidual)||0;if(l>0){let p=e.get("encapsulation");K(p,"arkRules",`structureResidual:${l}`),ee(p,"ArkRules structure residual \u2014 encapsulation inside the layer.",{kind:"skill",ref:"/ark-autopilot",summary:"Fix structure sensors under [ArkRules] without inventing mechanical-safe."});let f=e.get("domain");K(f,"arkRules",`structureResidual:${l}`),ee(f,"ArkRules residual may mean domain shape is not yet under contract.",{kind:"skill",ref:"/ark-explore",summary:"Map inventory candidates; one pilot rule at a time."})}else t.arkRulesLoaded===!1||t.arkRulesLoaded==null;if(t.designWeak===!0){let p=e.get("maintainability");K(p,"designFitness","design-weak"),ee(p,"Design-weak: checked edges may be clean, but design residual remains \u2014 not finished.",{kind:"skill",ref:"/ark-explore",summary:"Shape door: explore shape-focus \u2192 dual-plan B \u2192 one /ark-autopilot pilot."})}if(t.dirtyBaselineRisk===!0||(Number(t.baselineStale)||0)>0){let p=e.get("maintainability");t.dirtyBaselineRisk===!0&&K(p,"baseline","dirty-freeze-risk"),(Number(t.baselineStale)||0)>0&&K(p,"baseline",`stale:${t.baselineStale}`),ee(p,"Baseline honesty residual \u2014 frozen debt or stale keys need review.",{kind:"command",ref:"ark-check --doctor",summary:"Review baseline freeze honesty; do not freeze new wrong debt."})}let c=Number(t.frozenResidual)||0;if(t.baselineExists===!0&&c>=10&&e.get("maintainability").status!=="residual"){let p=e.get("maintainability");K(p,"baseline",`frozen:${c}`),ee(p,"Substantial frozen residual remains under the baseline \u2014 review debt honestly.",{kind:"command",ref:"ark-check --doctor",summary:"Review freezes; do not freeze new wrong debt to clear residual."})}let u=Number(t.ungovernedDirCount)||0,m=Number(t.emptyLayerCount)||0;if(u>0||m>0){let p=e.get("modularity");u>0&&K(p,"coverage",`ungovernedDirs:${u}`),m>0&&K(p,"coverage",`emptyLayers:${m}`),ee(p,"Placement / modularity residual \u2014 ungoverned dirs or empty layer globs.",{kind:"skill",ref:"/ark-adopt",summary:"Classify ungoverned paths; fix empty layer patterns."})}if(t.designWeak===!0&&t.goldenPatternPresent===!1){let p=e.get("modularity");K(p,"goldenPattern","absent"),ee(p,"Design-weak without a golden pattern \u2014 new code lacks a placement norm for the AI.",{kind:"skill",ref:"/ark-place",summary:"Record an advisory golden pattern for new code (does not clear design-weak)."})}let y=e.get("stack");(t.stackKind??null)==="typescript"?y.status==="ok"&&(y.summary="Stack practices are partially instrumented for TypeScript / host / Ark idioms only \u2014 not a full framework checklist."):(y.status="not-instrumented",y.summary="Stack-specific best practices outside TypeScript/host/Ark idioms are not instrumented.",y.evidence=[],y.nextAction={kind:"docs",ref:"docs/use.md#improvement-compass",summary:"Ark does not score non-TS stack idioms."})}i(Pl,"mapCountsAndFlags");function ro(e,t){if(Array.isArray(t.designSmells)&&t.designSmells.length>0){let n=[...t.designSmells].sort((r,s)=>dr(r).localeCompare(dr(s)));Tl(e,n)}if(Array.isArray(t.violations)&&t.violations.length>0){let n=[...t.violations].sort((r,s)=>{let o=ur(r).localeCompare(ur(s));return o!==0?o:String(r.file??"").localeCompare(String(s.file??""))});Ll(e,n)}Pl(e,t)}i(ro,"projectImprovementCompassFacts");function so(e){for(let t of Pe){let n=e.get(t);n.status="out-of-scope",n.summary=lr[t],n.evidence=[],n.nextAction={kind:"docs",ref:"docs/use.md#improvement-compass",summary:"Out of scope for ArkGate \u2014 use dedicated tooling outside the gate."}}}i(so,"lockImprovementCompassOutOfScope");function oo(e){for(let t of e)t.evidence.sort((n,r)=>{let s=n.source.localeCompare(r.source);return s!==0?s:n.ref.localeCompare(r.ref)})}i(oo,"sortImprovementCompassEvidence");function ao(e){return e.filter(n=>n.status==="residual"&&!ze.has(n.id)).slice().sort((n,r)=>{let s=ar[n.id]??150,o=ar[r.id]??150;return s!==o?s-o:n.id.localeCompare(r.id)}).slice(0,5).map(n=>n.id)}i(ao,"finalizeImprovementCompassTopResidual");function wl(e={}){let t=no(),n=new Map(t.map(s=>[s.id,s]));ro(n,e),so(n),oo(t);let r=ao(t);return{schemaVersion:"1.0",notAScore:!0,lenses:t.map(s=>{let o={id:s.id,status:s.status,summary:s.summary,evidence:s.evidence.map(a=>({...a}))};return s.nextAction&&(o.nextAction={...s.nextAction}),o}),topResidual:r}}i(wl,"buildImprovementCompass");function io(e){return e.topResidual.map(t=>cr(t))}i(io,"formatImprovementCompassResidualLabels");function lo(e){for(let t of e.topResidual){let n=e.lenses.find(r=>r.id===t);if(n?.nextAction)return{...n.nextAction}}return null}i(lo,"primaryImprovementCompassNextAction");function Dl(e){let t=io(e),n=Pe.map(o=>cr(o)),r=lo(e),s=[];return t.length>0?s.push(`Residual: ${t.join(" \xB7 ")}`):s.push("Residual: none on instrumented lenses (not a score \u2014 green edges \u2260 finished design)."),s.push(`Out of scope (honest): ${n.join(" \xB7 ")}`),r&&s.push(`Next: ${r.ref} \u2014 ${r.summary}`),s}i(Dl,"formatImprovementCompassDoctorLines");var Ml="1.0",Fl="<!-- arkgate:agent-projection:begin",co="<!-- arkgate:agent-projection:end -->",uo="This projection is **non-authoritative**. Enforcement is `ark-check` / host write hooks / required CI (`--strict-merge`), not AGENTS.md, skills, or this block.",mr=Object.freeze(["ark-check","host-write-hooks","ci-strict-merge"]),$l=Object.freeze(["LAYER_IMPORT_VIOLATION","LAYER_INTENT_REFERENCE_VIOLATION","CIRCULAR_DEPENDENCY","CAPABILITY_VIOLATION","RAW_EVENT_PUBLISH","ARKRULE_STRUCTURE","ATOMIC_PREFLIGHT_UNAVAILABLE","ANALYSIS_PARSE_INCOMPLETE","ARK_UNKNOWN"]),gr=/<!--\s*arkgate:agent-projection:begin\b([^>]*)-->/i,po=/<!--\s*arkgate:agent-projection:end\s*-->/i,Hl=/\barkgateVersion=([A-Za-z0-9._+-]+)/i,jl=/\bschema=([A-Za-z0-9._+-]+)/i;function Jt(e){let t=String(e??"").replace(/\r\n/g,`
17
- `),n=2166136261;for(let r=0;r<t.length;r+=1)n^=t.charCodeAt(r),n=Math.imul(n,16777619);return`fnv1a-${(n>>>0).toString(16).padStart(8,"0")}`}i(Jt,"agentProjectionContentIdentity");function Xt(e){return String(e??"").replace(/\r\n/g,`
18
- `)}i(Xt,"normalizeNewlines");function qe(e){let t=Xt(e);return t.endsWith(`
8
+ `)}`),this.name="EffectiveContractError",this.source=t,this.issues=n}};function As(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}i(As,"normalizeRel");function ni(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 c of[...e.discoveredArkRulesFiles].sort())r.push({path:c,message:`ArkRules file ${JSON.stringify(c)} is not referenced by arkRules and will not be enforced`,severity:"advisory"});return{config:e.config,arkRules:Ne(),warnings:r}}let s=new Set(e.config.layers.map(c=>c.name)),o=[],a=[],l=new Set;for(let c of Object.keys(n).sort()){let u=n[c],f=`$.arkRules[${JSON.stringify(c)}]`;if(typeof u!="string"||u.length===0){o.push({path:f,message:"must be a non-empty relative path string"});continue}if(u.startsWith("/")||/^[A-Za-z]:[\\/]/.test(u)){o.push({path:f,message:"must be a project-relative path (absolute paths are not allowed)"});continue}if(!s.has(c)){o.push({path:f,message:`layer ${JSON.stringify(c)} is not declared in layers[]`});continue}let y=As(u);l.add(y);let g=e.fileContents[y]??e.fileContents[u];if(g===void 0){o.push({path:f,message:`referenced ArkRules file ${JSON.stringify(y)} is missing`});continue}try{let p=Pt(JSON.parse(g),y,c);a.push({layer:c,sourceFile:y,file:p.config})}catch(p){if(p instanceof Te)for(let m of p.issues)o.push({path:`${f}${m.path==="$"?"":m.path.replace(/^\$/,"")}`,message:`${y}: ${m.message}`});else p instanceof SyntaxError?o.push({path:f,message:`referenced ArkRules file ${JSON.stringify(y)} is not valid JSON: ${p.message}`}):o.push({path:f,message:`referenced ArkRules file ${JSON.stringify(y)} failed to load: ${p instanceof Error?p.message:String(p)}`})}}if(e.discoveredArkRulesFiles)for(let c of[...e.discoveredArkRulesFiles].sort()){let u=As(c);l.has(u)||r.push({path:u,message:`ArkRules file ${JSON.stringify(u)} is not referenced by arkRules and will not be enforced`,severity:"advisory"})}if(o.length>0)throw new wt(t,o);return{config:e.config,arkRules:Ln(a),warnings:r}}i(ni,"resolveEffectiveContract");function Pn(e){return{...e,layers:e.layers.map(t=>{let{description:n,...r}=t;return r})}}i(Pn,"omitLayerDescriptions");function wn(e){let{stewards:t,...n}=Pn(e.config);return{config:n,arkRules:{schemaVersion:e.arkRules.schemaVersion,structure:e.arkRules.structure.map(r=>({id:r.id,sensor:r.sensor,mode:r.mode,appliesTo:r.appliesTo??null,description:r.description??null,provenance:r.provenance})),invariants:e.arkRules.invariants.map(r=>({id:r.id,description:r.description,aggregate:r.aggregate??null,coverage:r.coverage??null,mode:r.mode,appliesTo:r.appliesTo??null,provenance:r.provenance}))}}}i(wn,"effectiveContractPolicyPayload");function Rs(e,t=!1){if(!e)return"";let n=e.discarded,r=[];if(n.budget>0&&!t&&r.push(`${n.budget} past the ${e.maxFiles}-file budget`),n.noInvariantMention>0&&r.push(`${n.noInvariantMention} naming no catalogued invariant`),n.oversize>0&&r.push(`${n.oversize} over the per-file byte cap`),n.unreadable>0&&r.push(`${n.unreadable} unreadable (files or directories)`),n.depthLimited>0&&r.push(`${n.depthLimited} directories past the walk depth limit`),n.outOfRoot>0&&r.push(`${n.outOfRoot} symlinked outside the project root`),r.length===0)return"";let s=t?"":` (loaded ${e.filesLoaded} files, kept ${e.testFilesRetained} tests)`;return` Scan discarded ${r.join(", ")}${s}.`}i(Rs,"formatCoverageDiscards");function ri(e,t){let n=e.replace(/\\/g,"/").replace(/^\.\//,"");return t.some(r=>{let s=r.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"");return s===""||s==="."?!0:n===s||n.startsWith(`${s}/`)})}i(ri,"isUnderCoverageRoot");function si(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*['"\`][^'"\`]*${n}[^'"\`]*['"\`]`,"i").test(e)||e.includes(t)}i(si,"titleMatchesInvariant");function oi(e,t){if(!t)return!1;let n=t.split("."),r=n[n.length-1],s=n.length>1?n[0]:null;for(let o of Object.values(e))if(!(s&&!o.includes(s))&&(new RegExp(`(?:function\\s+|\\b)${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[(<]`).test(o)||o.includes(t)))return!0;return!1}i(oi,"symbolPresent");function Dn(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=e.coverageBudgetExhausted===!0,o=e.coverageStats,a=Rs(o),l=Rs(o,!0),c=o?`coverage file budget exhausted: ${o.filesLoaded} files loaded at the ${o.maxFiles}-file cap, ${o.testFilesRetained} tests retained, ${o.discarded.budget} files discarded at the cap; raise "coverage.maxFiles" in ark.config.json (the cap bounds files RETAINED as evidence${typeof o.filesRead=="number"?`; ${o.filesRead} were read`:""})`:"coverage file budget exhausted",u=(e.coverageRoots??[]).filter(m=>typeof m=="string"&&m.length>0),f=u.length>0,y=u.join(", "),g=[],p=[];for(let m of t){let A=[],S=m.coverage?.test!==!1,O=m.coverage?.symbol,R,I;if(!r&&S){let L;for(let z of n){let T=e.fileContents[z];if(!(!T||!si(T,m.id))){if(!f||ri(z,u)){R=z,I=f?!1:void 0;break}L??=z}}R===void 0&&L!==void 0&&(R=L,I=!0),R!==void 0&&A.push("test-title")}O&&oi(e.fileContents,O)&&A.push("symbol");let w=(m.coverage?.test===!0||!!O||m.coverage===void 0)&&A.length>0||m.coverage?.test===!1&&!O?!0:A.length>0,k=r&&S&&A.length===0;if(g.push({invariantId:m.id,layer:m.provenance.layer,sourceFile:m.provenance.sourceFile,mode:m.mode,covered:w&&!k,evidence:A,partial:k,description:m.description,...R!==void 0?{testEvidenceFile:R}:{},...I!==void 0?{outsideDeclaredRoots:I}:{}}),I===!0&&R!==void 0&&p.push({ruleId:"INVARIANT_COVERAGE_OUTSIDE_ROOTS",message:`Invariant ${m.id} is covered only by ${R}, which is outside the declared coverage roots (${y}). ArkGate matches declared text and never executes tests, so it cannot tell whether that file is run: move the test under a declared root, or add its root to "coverage.coverageRoots" in ark.config.json.`,file:R,line:1,arkruleId:m.id,arkruleSource:m.provenance.sourceFile,fromLayer:m.provenance.layer,severity:"warning",failsStrict:!1}),!w||k){let L=m.mode==="enforced"&&!k,z=r||n.length===0?"never-had-tests":"tests-disappeared";p.push({ruleId:"INVARIANT_UNCOVERED",message:(k?s?`Invariant ${m.id} coverage cannot be proven (${c}); reporting partial, not covered.`:`Invariant ${m.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered (never-had-tests).`:z==="tests-disappeared"?`Invariant ${m.id}: no scanned test names it in a describe/it title and no declared symbol was found (tests-disappeared \u2014 a suite exists). ArkGate matches declared text; it never executes tests.`:`Invariant ${m.id}: no scanned test names it in a describe/it title and no declared symbol was found (never-had-tests \u2014 the scan found no tests at all). ArkGate matches declared text; it never executes tests.`)+(k&&s?l:a),file:m.provenance.sourceFile,line:1,arkruleId:m.id,arkruleSource:m.provenance.sourceFile,fromLayer:m.provenance.layer,severity:L?"error":"warning",failsStrict:L,kind:z})}}return{coverage:g,violations:p,partial:g.some(m=>m.partial)}}i(Dn,"evaluateInvariantCoverage");function Mn(e){return e?e.partial?{ok:!1,reason:"Coverage is partial (missing test globs); cannot promote until evidence is complete."}:e.covered?e.outsideDeclaredRoots===!0?{ok:!1,reason:`Invariant ${e.invariantId} is covered only by ${e.testEvidenceFile??"a test"}, outside the declared coverage roots; ArkGate cannot tell whether that test runs, so it will not promote on it.`}:{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."}}i(Mn,"canPromoteInvariant");var Hn="1.0";function N(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}})}i(N,"addFinding");function Z(e){return[...new Set(e??[])].sort()}i(Z,"sortedUnique");function ue(e,t,n,r,s){let o=Z(n),a=Z(r),l=new Set(o),c=new Set(a),u=a.filter(y=>!l.has(y)),f=o.filter(y=>!c.has(y));u.length===0&&f.length===0||(u.length>0&&N(e,{kind:"added",path:t,classification:s.added,message:s.addedMessage,before:o,after:a}),f.length>0&&N(e,{kind:"removed",path:t,classification:s.removed,message:s.removedMessage,before:o,after:a}))}i(ue,"compareStringSets");function lt(e,t,n,r,s,o,a){if(n===r)return;N(e,{kind:r?"enabled":"disabled",path:t,classification:r?s:s==="strengthening"?"weakening":"strengthening",message:r?o:a,before:n,after:r})}i(lt,"compareBoolean");function Dt(e,t){let n=new Map,r=new Set;for(let s of e){let o=t(s);n.has(o)?r.add(o):n.set(o,s)}return{values:n,duplicates:[...r].sort()}}i(Dt,"keyed");function ai(e,t,n){let r=Dt(t,o=>o.name),s=Dt(n,o=>o.name);(r.duplicates.length>0||s.duplicates.length>0)&&N(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 o of[...new Set([...r.values.keys(),...s.values.keys()])].sort()){let a=r.values.get(o),l=s.values.get(o),c=`$.layers[${o}]`;if(!a&&l){N(e,{kind:"layer-added",path:c,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:l});continue}if(a&&!l){N(e,{kind:"layer-removed",path:c,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:a});continue}if(!a||!l)continue;ue(e,`${c}.patterns`,a.patterns,l.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,`${c}.exclude`,a.exclude,l.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let u=St(a),f=St(l);ue(e,`${c}.forbiddenGlobals`,u.rawGlobals,f.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,`${c}.capabilities`,u.atoms,f.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)."}),Z(a.intentPrefixes).join("\0")!==Z(l.intentPrefixes).join("\0")&&N(e,{kind:"intent-prefixes-changed",path:`${c}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:Z(a.intentPrefixes),after:Z(l.intentPrefixes)}),lt(e,`${c}.mayImportInfrastructure`,a.mayImportInfrastructure===!0,l.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),lt(e,`${c}.optional`,a.optional===!0,l.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.")}}i(ai,"compareLayers");function ii(e,t,n){let r=i(a=>`${a.from}->${a.to}`,"keyOf"),s=Dt(t,r),o=Dt(n,r);(s.duplicates.length>0||o.duplicates.length>0)&&N(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:s.duplicates,after:o.duplicates});for(let a of[...new Set([...s.values.keys(),...o.values.keys()])].sort()){let l=s.values.get(a),c=o.values.get(a),u=`$.rules[${a}]`;if(!l&&c){c.allowed===!1&&N(e,{kind:"deny-added",path:u,classification:"strengthening",message:"A denied dependency edge was added.",after:c});continue}if(l&&!c){l.allowed===!1&&N(e,{kind:"deny-removed",path:u,classification:"weakening",message:"A denied dependency edge was removed.",before:l});continue}if(!l||!c)continue;l.allowed!==c.allowed&&N(e,{kind:c.allowed?"deny-disabled":"deny-enabled",path:`${u}.allowed`,classification:c.allowed?"weakening":"strengthening",message:c.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:l.allowed,after:c.allowed});let f=l.peerIsolation===!0,y=c.peerIsolation===!0;if(f!==y){let g=l.from===l.to&&c.from===c.to;N(e,{kind:y?"peer-isolation-enabled":"peer-isolation-disabled",path:`${u}.peerIsolation`,classification:g?y?"strengthening":"weakening":"judgment-required",message:g?y?"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:f,after:y})}Z(l.sliceFolders).join("\0")!==Z(c.sliceFolders).join("\0")&&N(e,{kind:"slice-folders-changed",path:`${u}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:Z(l.sliceFolders),after:Z(c.sliceFolders)}),!(!f&&!y)&&(Es(e,`${u}.sharedRoots`,"shared-roots",Z(l.sharedRoots),Z(c.sharedRoots),"Roots declared shared are exempt from the peerIsolation unclassifiable denial.","Roots are no longer declared shared and fall back to the peerIsolation denial."),Es(e,`${u}.allowedCrossSlice`,"cross-slice-allowance",Z((l.allowedCrossSlice??[]).map(ks)),Z((c.allowedCrossSlice??[]).map(ks)),"Directed cross-slice edges are now allowed by declaration.","Directed cross-slice edges are no longer declared and deny again."))}}i(ii,"compareRules");function ks(e){return JSON.stringify([e.from,e.to])}i(ks,"crossSliceKey");function Es(e,t,n,r,s,o,a){if(JSON.stringify(r)===JSON.stringify(s))return;let l=s.filter(f=>!r.includes(f)),c=r.filter(f=>!s.includes(f)),u=l.length>0&&c.length>0;N(e,{kind:u?`${n}-changed`:l.length>0?`${n}-added`:`${n}-removed`,path:t,classification:u?"judgment-required":l.length>0?"weakening":"strengthening",message:u?`${o} Entries were added and removed in the same change.`:l.length>0?o:a,before:r,after:s})}i(Es,"compareDeclaredExceptions");function li(e,t,n){let r=t.safety??{},s=n.safety??{};for(let o of["maxTsSuppressions","maxAnyCasts"]){let a=r[o]??0,l=s[o]??0;a!==l&&N(e,{kind:l>a?"threshold-raised":"threshold-lowered",path:`$.safety.${o}`,classification:l>a?"weakening":"strengthening",message:l>a?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:a,after:l})}for(let o of["allowInMemory","allowDisabledPeerIsolation"])lt(e,`$.safety.${o}`,r[o]===!0,s[o]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}i(li,"compareSafety");function Fn(e){return e.mode==="enforced"?"enforced":"advisory"}i(Fn,"arkRunMode");function $n(e){return e.mode==="enforced"?"enforced":"advisory"}i($n,"arkOrderMode");function ci(e,t,n){let r=t.arkOrder,s=n.arkOrder,o="$.arkOrder";if(!r&&!s)return;if(!r&&s){N(e,{kind:"arkorder-added",path:o,classification:"strengthening",message:`ArkOrder extra was added (${$n(s)}).`,after:s});return}if(r&&!s){N(e,{kind:"arkorder-removed",path:o,classification:"weakening",message:"ArkOrder extra was removed.",before:r});return}if(!r||!s)return;let a=$n(r),l=$n(s);if(a!==l){let c=a==="advisory"&&l==="enforced";N(e,{kind:c?"arkorder-promoted":"arkorder-demoted",path:`${o}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkOrder extra was promoted to enforced.":"ArkOrder extra was demoted to advisory.",before:a,after:l})}ue(e,`${o}.planeRoots`,r.planeRoots,s.planeRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkOrder plane roots are governed.",removedMessage:"ArkOrder plane roots were removed and may skip the plane."}),ue(e,`${o}.managedLayers`,r.managedLayers,s.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkOrder.",removedMessage:"Layers were removed from ArkOrder management."})}i(ci,"compareArkOrder");function di(e,t,n){let r=t.arkRun,s=n.arkRun,o="$.arkRun";if(!r&&!s)return;if(!r&&s){N(e,{kind:"arkrun-added",path:o,classification:"strengthening",message:`ArkRun extra was added (${Fn(s)}).`,after:s});return}if(r&&!s){N(e,{kind:"arkrun-removed",path:o,classification:"weakening",message:"ArkRun extra was removed.",before:r});return}if(!r||!s)return;let a=Fn(r),l=Fn(s);if(a!==l){let c=a==="advisory"&&l==="enforced";N(e,{kind:c?"arkrun-promoted":"arkrun-demoted",path:`${o}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkRun extra was promoted to enforced.":"ArkRun extra was demoted to advisory.",before:a,after:l})}ue(e,`${o}.compositionRoots`,r.compositionRoots,s.compositionRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkRun composition roots are governed.",removedMessage:"ArkRun composition roots were removed and may skip the kernel."}),ue(e,`${o}.managedLayers`,r.managedLayers,s.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkRun.",removedMessage:"Layers were removed from ArkRun management."}),lt(e,`${o}.requireDeclarations`,r.requireDeclarations!==!1,s.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}i(di,"compareArkRun");function ui(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"}i(ui,"overallClassification");function Is(e,t){return`${e}::${t}`}i(Is,"ruleKey");function Ss(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(Is(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(Is(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}i(Ss,"indexEffectiveRules");function pi(e,t,n,r,s,o){let a=new Map((o??[]).map(g=>[g.invariantId,g])),l=t.arkRules??{},c=n.arkRules??{},u=[...new Set([...Object.keys(l),...Object.keys(c)])].sort();for(let g of u){let p=l[g],m=c[g],A=`$.arkRules[${g}]`;if(p===void 0&&m!==void 0){N(e,{kind:"arkrules-ref-added",path:A,classification:"strengthening",message:`ArkRules reference for layer ${g} was added.`,after:m});continue}if(p!==void 0&&m===void 0){N(e,{kind:"arkrules-ref-removed",path:A,classification:"weakening",message:`ArkRules reference for layer ${g} was removed.`,before:p});continue}p!==m&&N(e,{kind:"arkrules-ref-path-changed",path:A,classification:"judgment-required",message:`ArkRules file path for layer ${g} changed; verify the effective rules still match intent.`,before:p,after:m})}let f=Ss(r),y=Ss(s);for(let g of[...new Set([...f.structure.keys(),...y.structure.keys()])].sort()){let p=f.structure.get(g),m=y.structure.get(g),A=`$.arkRules.structure[${g}]`;if(!p&&m){N(e,{kind:"arkrule-structure-added",path:A,classification:"strengthening",message:`Structure ArkRule ${m.id} was added (${m.mode}).`,after:m});continue}if(p&&!m){N(e,{kind:"arkrule-structure-removed",path:A,classification:"weakening",message:`Structure ArkRule ${p.id} was removed.`,before:p});continue}if(!(!p||!m)){if(p.mode!==m.mode){let S=p.mode==="advisory"&&m.mode==="enforced";N(e,{kind:S?"arkrule-promoted":"arkrule-demoted",path:`${A}.mode`,classification:S?"strengthening":"weakening",message:S?`Structure ArkRule ${m.id} was promoted to enforced.`:`Structure ArkRule ${m.id} was demoted to advisory.`,before:p.mode,after:m.mode})}p.sensor!==m.sensor&&N(e,{kind:"arkrule-sensor-changed",path:`${A}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${m.id} changed sensor identity.`,before:p.sensor,after:m.sensor})}}for(let g of[...new Set([...f.invariants.keys(),...y.invariants.keys()])].sort()){let p=f.invariants.get(g),m=y.invariants.get(g),A=`$.arkRules.invariants[${g}]`;if(!p&&m){N(e,{kind:"arkrule-invariant-added",path:A,classification:"strengthening",message:`Invariant ${m.id} was added (${m.mode}).`,after:m});continue}if(p&&!m){N(e,{kind:"arkrule-invariant-removed",path:A,classification:"weakening",message:`Invariant ${p.id} was removed.`,before:p});continue}if(!(!p||!m)&&p.mode!==m.mode)if(p.mode==="advisory"&&m.mode==="enforced"){let O=a?.get(m.id),R=Mn(O);R.ok?N(e,{kind:"arkrule-invariant-promoted",path:`${A}.mode`,classification:"strengthening",message:`Invariant ${m.id} was promoted to enforced (coverage evidence present).`,before:p.mode,after:m.mode}):N(e,{kind:"arkrule-invariant-promote-refused",path:`${A}.mode`,classification:"judgment-required",message:`Invariant ${m.id} cannot be promoted to enforced: ${R.reason}`,before:p.mode,after:m.mode})}else N(e,{kind:"arkrule-invariant-demoted",path:`${A}.mode`,classification:"weakening",message:`Invariant ${m.id} was demoted to advisory.`,before:p.mode,after:m.mode})}}i(pi,"compareArkRules");function jn(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."}),lt(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},o=e.cyclePolicy??"strict",a=t.cyclePolicy??"strict";if(o!==a){let l=s[a]===s[o]?"judgment-required":s[a]>s[o]?"strengthening":"weakening";N(r,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:l,message:"The cycle enforcement level changed.",before:o,after:a})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&N(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}),ai(r,e.layers,t.layers),ii(r,e.rules,t.rules),li(r,e,t),pi(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),di(r,e,t),ci(r,e,t),r.sort((l,c)=>l.path.localeCompare(c.path)||l.id.localeCompare(c.id)),{schemaVersion:Hn,classification:ui(r),findings:r}}i(jn,"classifyArkPolicyDelta");function Vn(e,t){if(!e||e.schemaVersion!==Hn||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=Z(e.findingIds),r=Z(t.findingIds);return n.length===r.length&&n.every((s,o)=>s===r[o])}i(Vn,"policyDeltaAcknowledgementMatches");function Le(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("/")}i(Le,"normalizePath");function bs(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}i(bs,"isIdentifierStart");function Mt(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}i(Mt,"isIdentifierCharacter");function oe(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}i(oe,"skipWhitespace");function ct(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let r=t,s="";for(t+=1;t<e.length;t+=1){let o=e[t];if(o===n)return{value:s,offset:r,excerpt:e.slice(r,t+1)};o==="\\"&&t+1<e.length?(s+=e[t+1],t+=1):s+=o}}i(ct,"readString");function le(e,t,n){return e.startsWith(t,n)&&!Mt(e[n-1])&&!Mt(e[n+t.length])}i(le,"isWordAt");function vs(e,t){let n=oe(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=oe(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!le(e,"type",n))return!1;let s=oe(e,n+4);if(s>=e.length||e[s]===","||e[s]==="}"||le(e,"as",s)||!bs(e[s]))return!1;for(n=s;n<e.length&&Mt(e[n]);)n+=1;if(n=oe(e,n),le(e,"as",n)){if(n=oe(e,n+2),!bs(e[n]))return!1;for(;n<e.length&&Mt(e[n]);)n+=1}r=!0}return!1}i(vs,"bracedNamedBindingsAreTypeOnly");function fi(e,t){if(t=oe(e,t+6),e[t]==="(")return ct(e,oe(e,t+1));let n=!1;if(le(e,"type",t)){let s=oe(e,t+4);e[s]!==","&&!le(e,"from",s)&&(n=!0)}else vs(e,t)&&(n=!0);let r=Cs(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}i(fi,"specifierAfterImport");function mi(e,t){t=t+6;let n=oe(e,t),r=!1;if(le(e,"type",n)){let o=oe(e,n+4);(e[o]==="{"||e[o]==="*")&&(r=!0)}else vs(e,n)&&(r=!0);let s=Cs(e,t,!1);return s&&r?{...s,typeOnly:!0}:s}i(mi,"specifierAfterExport");function Cs(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(le(e,"from",t))return ct(e,oe(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return ct(e,t);if(t>0&&(le(e,"import",t)||le(e,"export",t)))return}}i(Cs,"specifierInStaticStatement");function gi(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}i(gi,"skipTemplateLiteral");function yi(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=oe(e,t+7);if(e[r]!=="(")return;r=oe(e,r+1);let s=ct(e,r);return s?{...s,requireCall:!0}:void 0}i(yi,"specifierAfterRequire");function hi(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 o=e.indexOf("*/",n+2);if(o<0)break;n=o+1;continue}if(r==="`"){n=gi(e,n);continue}if(r==="'"||r==='"'){let o=ct(e,n);o&&(n=o.offset+o.excerpt.length-1);continue}let s=r==="i"&&le(e,"import",n)?fi(e,n):r==="e"&&le(e,"export",n)?mi(e,n):r==="r"&&le(e,"require",n)?yi(e,n):void 0;s&&(t.push(s),n=s.offset+s.excerpt.length-1)}return t}i(hi,"moduleSpecifiers");function _s(e,t){let n=[],r=[];for(let s of hi(e.content)){let o=s.value;if(!o.startsWith(".")){if(s.typeOnly)continue;let u=Ye(o);if(!u)continue;let f=e.content.slice(0,s.offset).split(`
10
+ `).length;r.push({file:e.path,symbol:o,capability:u,evidence:{kind:"import",file:e.path,line:f,excerpt:s.excerpt}});continue}let a=e.content.slice(0,s.offset).split(`
11
+ `).length,l={kind:"import",file:e.path,line:a,excerpt:s.excerpt},c=Ai(e.path,o,t);n.push({from:e.path,specifier:o,to:c?.path??null,resolution:c?"resolved":"unresolved",fromLayer:e.layer,toLayer:c?.layer??null,evidence:l})}return{edges:n,capabilityUses:r}}i(_s,"moduleFactsFor");function Ai(e,t,n){let r=e.split("/");r.pop();for(let o of t.split("/"))o==="."||o===""||(o===".."?r.pop():r.push(o));let s=r.join("/");for(let o of[s,`${s}.ts`,`${s}.tsx`,`${s}.mts`,`${s}.cts`,`${s}/index.ts`,`${s}/index.tsx`]){let a=n.get(o);if(a)return a}}i(Ai,"resolveSpecifier");function Os(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let s=vt(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}i(Os,"violationsFor");var Ri={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 ki(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}i(ki,"hasActiveArkRules");function Ei(e,t){return ki(e,t)?X(H(wn({config:e,arkRules:t,warnings:[]}))):X(H(Pn(e)))}i(Ei,"policyHashFor");function Ft(e,t,n){let r=typeof e=="string"?Cn(e,t):xt(e,t),s=n?.arkRules??Ne();return{...r,arkRules:s,policyHash:Ei(r.config,s)}}i(Ft,"loadContract");function xs(e){let t=Ft(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=Ft(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=jn(t.config,n.config,{baseArkRules:t.arkRules,candidateArkRules:n.arkRules,candidateInvariantCoverage:e.candidateInvariantCoverage}),s=r.findings.filter(l=>l.classification==="weakening"||l.classification==="judgment-required").map(l=>l.id).sort(),o=s.length>0,a=o&&Vn(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:o,acknowledged:a,valid:!o||a}}i(xs,"analyzePolicyDelta");function dt(e){let t=e.files.map(y=>{let g=Le(y.path);return{path:g,content:y.content,contentHash:X(y.content),layer:de(g,e.contract.config.layers)??null}}).sort((y,g)=>y.path.localeCompare(g.path)),n=new Map(t.map(y=>[y.path,y])),r=[],s=[];for(let y of t){let g=_s(y,n);r.push(...g.edges),s.push(...g.capabilityUses)}let o=Os(r,e.contract.config),a=new Map(e.contract.config.layers.map(y=>[y.name,y])),l=new Map(e.contract.config.layers.map(y=>[y.name,new Set(De(y))]));for(let y of s){let g=n.get(y.file)?.layer;if(!g)continue;let p=a.get(g),m=Ee(y.symbol,p?.forbiddenGlobals??[]);if(m){o.push({ruleId:"FORBIDDEN_GLOBAL",message:`${g} must not use module "${y.symbol}" because it is the import form of forbidden global "${m}".`,symbol:y.symbol,evidence:y.evidence});continue}l.get(g)?.has(y.capability)&&o.push({ruleId:"CAPABILITY_VIOLATION",message:`${g} denies the ${y.capability} capability; found import of "${y.symbol}".`,capability:y.capability,symbol:y.symbol,evidence:y.evidence})}let c=t.length===0?"complete":"partial",u=c==="complete"?[]:[{...Ri}],f={schemaVersion:xn,policyHash:e.contract.policyHash,compilerOptionsHash:X(H(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(y=>y.name),edges:r,capabilityUses:s,violations:o};return{mode:"lexical-compatibility",completeness:c,completenessReasons:u,valid:c==="complete"&&o.length===0,ir:f}}i(dt,"analyzeProject");function $t(e){let t=new Map(e.files.map(n=>[Le(n.path),n]));for(let n of e.changes){let r=Le(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return dt({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}i($t,"analyzeChange");function Ts(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}`}i(Ts,"explainViolation");function Un(e){let t=0,n=new Map,r=new Map,s=new Set,o=[],a=[],l=i(c=>{n.set(c,t),r.set(c,t),t+=1,o.push(c),s.add(c);for(let y of[...e.get(c)??[]].sort())e.has(y)&&(n.has(y)?s.has(y)&&r.set(c,Math.min(r.get(c)??0,n.get(y)??0)):(l(y),r.set(c,Math.min(r.get(c)??0,r.get(y)??0))));if(r.get(c)!==n.get(c))return;let u=[],f;do{if(f=o.pop(),f===void 0)break;s.delete(f),u.push(f)}while(f!==c);u.length>1&&a.push(u.sort())},"connect");for(let c of[...e.keys()].sort())n.has(c)||l(c);return a.sort((c,u)=>c[0]<u[0]?-1:c[0]>u[0]?1:0).map(c=>({ruleId:"CIRCULAR_DEPENDENCY",file:c[0],line:1,target:c.join(" \u2192 "),message:`Circular dependency among ${c.length} files: ${c.join(" \u2192 ")} \u2192 ${c[0]}.`,cycleKind:"value"}))}i(Un,"detectArchitectureCycles");function Ge(e){let t=e.contentViolations.map(o=>({...o})),n=(e.warnings??[]).map(o=>({...o})),r=new Map(e.files.map(o=>[o,new Set]));for(let o of e.edges){if(o.to&&o.to!==o.from&&!o.typeOnly&&r.has(o.from)&&r.get(o.from)?.add(o.to),!o.to||!o.fromLayer||!o.toLayer)continue;let a=Ce(e.rules,o.fromLayer,o.toLayer,{fromPath:o.from,toPath:o.to,layers:e.config.layers});if(!a)continue;let l=a.rule,c=!!l.peerIsolation,u=!c&&!!(o.typeOnly||o.namedBindingsTypeOnly),f=c?Me(a.peerIsolationReason??"cross-slice",{fromPath:o.from,toPath:o.to,fromSlice:a.fromSlice,toSlice:a.toSlice}):void 0,y=l.message?f?`${l.message} (${f})`:l.message:f?`${o.fromLayer} must not ${o.kind} another slice of ${o.toLayer} (${o.from} \u2192 ${o.to}): ${f}`:`${o.fromLayer} must not ${o.kind} ${o.toLayer}.`;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:o.from,line:o.line,fromLayer:o.fromLayer,toLayer:o.toLayer,target:o.to,...o.typeOnly?{typeOnly:!0}:{},...o.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...o.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...o.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!c&&o.portProofEligible?{portProofEligible:!0}:{},...o.kind?{edgeKind:o.kind}:{},...c?{peerIsolation:!0}:{},message:u?`${y} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:y,...u?{failsStrict:!1,severity:"warning"}:{}})}let s=String(e.config.cyclePolicy??"strict").toLowerCase();if(s!=="off"){let o=Un(r);s==="soft"||s==="framework-soft"?n.push(...o.map(a=>({...a,message:`${a.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...o)}return{violations:t,warnings:n,safety:e.safety}}i(Ge,"evaluateArchitectureGraph");function Ns(e){if(typeof e.target=="string"&&e.target.length>0)return e.target;let t=String(e.sensor||e.code||"").trim();if(!t&&typeof e.message=="string"){let r=e.message.match(/\(sensor ([a-z0-9-]+)\)/i);r?.[1]&&(t=r[1])}let n=String(e.symbol||"").trim();return t?n?`${t}:${n}`:t:n}i(Ns,"structureFreezeTarget");var Ii=["no-anemic-model"],Ms=["ensureInvariants","assertInvariants","validate","publish","emit","raise","record"],Bn=new RegExp(`\\b(${Ms.join("|")})\\b`),Fs="(?:_?pendingEvents|domainEvents|uncommittedEvents|recordedEvents)",zn=new RegExp(`\\bthis\\.${Fs}\\.push\\s*\\(`),Si=new RegExp(`^this\\.${Fs}\\s*=\\s*\\[\\s*\\]`),bi=/^this\.[A-Za-z_][A-Za-z0-9_]*\s*=\s*\[\s*\]/,vi=/\bthis\.[A-Za-z_][A-Za-z0-9_]*\s*=(?!=)/g,$s="truncatedUntil";function Wn(){return`${Ms.join(", ")}, or events-array .push(`}i(Wn,"expectedDomainInvariantWordsPhrase");function Ci(e){return Bn.test(e)||zn.test(e)}i(Ci,"referencesGuardOrPublish");function qn(e,t,n){let r=e.slice(t);if(Si.test(r))return!0;if(!bi.test(r))return!1;if(n&&/^pullEvents$/i.test(n))return!0;let s=t>200?t-200:0;return/\bpullEvents\b/.test(e.slice(s,t+200))}i(qn,"isIdiomaticEventsReset");function _i(e,t){let n=new RegExp(vi.source,"g"),r;for(;(r=n.exec(t))!==null;)if(!qn(t,r.index,e))return!0;return!1}i(_i,"methodAssignsThis");function Oi(e,t){return t==null||Object.defineProperty(e,$s,{value:t,enumerable:!1,configurable:!0}),e}i(Oi,"attachShapeTruncation");function Gn(e){let t=Object.getOwnPropertyDescriptor(e,$s)?.value;return typeof t=="number"?t:void 0}i(Gn,"shapeTruncatedUntil");function xi(e){let t=Gn(e);return t==null?"":` shape analysed until character ${t}`}i(xi,"shapeTruncationSuffix");function Ls(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(Ls,"escapeGlobLiteral");function Ti(e){let t="";for(let r=0;r<e.length;r+=1){let s=e[r];if(s==="\\"&&r+1<e.length){let o=e[r+1];if("*?{}[],".includes(o)||o==="\\"){t+="\\"+o,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+=Ls(t[r+1]),r+=1):s==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":s==="?"?n+="[^/]":n+=Ls(s)}return new RegExp(`^${n}$`)}i(Ti,"globToRegExp");function Be(e,t){return!t||t.length===0?!0:t.some(n=>Ti(n).test(e))}i(Be,"matchesAppliesTo");function Ni(e){return Ii.includes(e)}i(Ni,"isTier2");function Hs(e){return e.mode==="enforced"&&!Ni(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}i(Hs,"severityFor");function Se(e,t,n,r=1){let{severity:s,failsStrict:o}=Hs(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:o}}i(Se,"baseViolation");function jt(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}i(jt,"isInRuleLayer");function Vt(e,t,n){return t.filter(r=>!(!r.exported||!Be(r.file,e.appliesTo)||!jt(r.file,e,n)))}i(Vt,"shapesForRule");function Li(e,t,n){let r=[];for(let s of Vt(e,t,n))(s.hasPublicSetters||s.hasPublicMutableFields)&&r.push(Se(e,s.file,`Exported class ${s.className} exposes public mutable state (sensor aggregate-private-state).`));return r}i(Li,"evaluateAggregatePrivateState");function Pi(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(Se(e,s.file,`Exported class ${s.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}return r}i(Pi,"evaluateAlwaysValidFactory");function wi(e,t,n){let r=[],s=Wn();for(let o of Vt(e,t,n)){let a=xi(o);Gn(o)!=null&&r.push(Se(e,o.file,`Exported class ${o.className} shape analysed until character ${Gn(o)}; later methods may be invisible (sensor domain-event-on-mutation).`));for(let l of o.mutatingMethods)l.referencesGuardOrPublish||r.push(Se(e,o.file,`Mutating method ${o.className}.${l.name} does not reference ${s} (sensor domain-event-on-mutation).${a}`))}return r}i(wi,"evaluateDomainEventOnMutation");function Di(e,t){let n=[];for(let r of t.files)Be(r,e.appliesTo)&&jt(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(Se(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}i(Di,"evaluateOrchestrationOnly");function Mi(e,t){let n=[];for(let r of t.files)Be(r,e.appliesTo)&&jt(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(Se(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}i(Mi,"evaluateThinAdapter");function Fi(e,t){let n=[];for(let r of t.files)Be(r,e.appliesTo)&&jt(r,e,t.layerForFile)&&t.fileHints?.[r]?.persistenceWrite&&n.push(Se(e,r,"File imports a persistence driver and issues a write; route the write through a Domain aggregate and a persistence adapter (sensor writes-via-aggregate)."));return n}i(Fi,"evaluateWritesViaAggregate");function $i(e,t,n){let r=[];for(let s of Vt(e,t,n))if(s.dataOnly===!0){let o=Se(e,s.file,`Exported type ${s.className} looks data-only / anemic (sensor no-anemic-model; advisory only).`);r.push({...o,severity:"warning",failsStrict:!1})}return r}i($i,"evaluateNoAnemicModel");function Yn(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(...Li(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...Pi(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...wi(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...Di(n,e));break;case"thin-adapter":t.push(...Mi(n,e));break;case"writes-via-aggregate":t.push(...Fi(n,e));break;case"no-anemic-model":t.push(...$i(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))}i(Yn,"evaluateArkRuleSensors");function Xn(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(c=>Be(c,s.appliesTo)))continue;let{severity:a,failsStrict:l}=Hs(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:l})}for(let s of e.invariants??[]){if(!s.appliesTo||s.appliesTo.length===0||r.some(l=>Be(l,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,o)=>s.file.localeCompare(o.file)||s.arkruleId.localeCompare(o.arkruleId)||s.message.localeCompare(o.message))}i(Xn,"collectEmptyAppliesToFindings");var Ps=/\bfrom\s+['"](?:@?prisma\/client|@supabase\/|drizzle-orm(?:\/[^'"]+)?|postgres(?:\/[^'"]+)?|typeorm|knex|mongodb|pg|mysql2|mongoose|better-sqlite3|ioredis|redis|kysely|sequelize)['"]|require\(\s*['"](?:@?prisma\/client|pg|postgres(?:\/[^'"]+)?|drizzle-orm(?:\/[^'"]+)?|knex|typeorm|mongoose)/,ws=/\bfrom\s+['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)(?:\.[cm]?[jt]sx?)?['"]|require\(\s*['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)/,Hi=/\b(?:db|tx|client|prisma(?:Client)?|drizzle)\b(?:\s*\.\s*[A-Za-z_]\w*)*\s*\.\s*(?:insert(?:One|Many)?|update(?:One|Many)?|upsert|delete(?:One|Many)?|createMany|create|replaceOne|findOneAnd(?:Update|Delete|Replace))\s*\(|\bINSERT\s+INTO\b|\bUPDATE\s+[A-Za-z_][\w.]*\s+SET\b|\bDELETE\s+FROM\b/i;function ji(e){return e==="PersistenceAdapters"}i(ji,"isPersistenceDriverLayer");function Vi(e,t){if(Ps.test(e)||ws.test(e))return!0;if(!t)return!1;for(let n of t){if(ji(n.layer))return!0;let r=n.specifier;if(!r)continue;let s=`from '${r}'`;if(Ps.test(s)||ws.test(s))return!0}return!1}i(Vi,"sourceImportsPersistenceDriver");var Ui=/\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*=)/,Ki=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,Gi=/\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*=/,Bi=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function js(e,t,n){if(!t)return null;let r=Vi(t,n),s=r&&Hi.test(t);if(t.length<40)return s?{persistenceWrite:!0}:null;let o=t.match(new RegExp(Gi.source,"g"))??[],a=t.match(new RegExp(Bi.source,"g"))??[],l=(t.match(/\bif\s*\(/g)??[]).length,c=(t.match(/\bswitch\s*\(/g)??[]).length,u=o.length>=2||o.length>=1&&a.length>=2||a.length>=3&&l+c>=6,f=Ui.test(t)||Ki.test(t),y=o.length>=1||a.length>=2,g=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),p=r&&y||f&&y||r&&g&&(l>=4||o.length>=1)||f&&r;return!u&&!p&&!s?null:{...u?{orchestrationHeavy:!0}:{},...p?{adapterThick:!0}:{},...s?{persistenceWrite:!0}:{}}}i(js,"deriveArkRuleFileHints");function Jn(e,t){let n={};for(let[r,s]of Object.entries(e)){let o=r.replace(/\\/g,"/"),a=js(r,s,t?.[o]);a&&(n[o]=a)}return n}i(Jn,"buildArkRuleFileHints");var zi=new Set(["public","private","protected","static","async","readonly","abstract","override","declare","get","set"]),Wi=new Set(["if","match","when"]);function Ht(e,t){let n=e[t];if(n==="/"&&e[t+1]==="/"){let r=e.indexOf(`
12
+ `,t);return r===-1?e.length:r}if(n==="/"&&e[t+1]==="*"){let r=e.indexOf("*/",t+2);return r===-1?e.length:r+2}if(n==="'"||n==='"'||n==="`"){let r=t+1;for(;r<e.length;){if(e[r]==="\\"){r+=2;continue}if(e[r]===n)return r+1;r+=1}return e.length}return t}i(Ht,"skipStringOrComment");function ut(e,t){let n=t;for(;n<e.length;){if(/\s/.test(e[n])){n+=1;continue}if(e[n]==="/"&&(e[n+1]==="/"||e[n+1]==="*")){n=Ht(e,n);continue}break}return n}i(ut,"skipWsAndComments");function Ds(e,t){let n=e[t];if(!n||!/[A-Za-z_]/.test(n))return null;let r=t+1;for(;r<e.length&&/[A-Za-z0-9_]/.test(e[r]);)r+=1;return{ident:e.slice(t,r),end:r}}i(Ds,"readIdent");function Kn(e,t,n,r){if(e[t]!==n)return null;let s=1,o=t+1;for(;o<e.length&&s>0;){let a=Ht(e,o);if(a!==o){o=a;continue}let l=e[o];l===n?s+=1:l===r&&(s-=1),o+=1}return s===0?o:null}i(Kn,"skipBalanced");function qi(e){let t=[],n=0,r;for(;n<e.length&&(n=ut(e,n),!(n>=e.length));){if(e[n]===";"){n+=1;continue}let s=[],o=n;for(;;){let f=Ds(e,o);if(!f||!zi.has(f.ident))break;s.push(f.ident),o=ut(e,f.end)}let a=Ds(e,o);if(!a){n+=1;continue}if(o=ut(e,a.end),e[o]==="<"){let f=Kn(e,o,"<",">");if(f==null){r=e.length;break}o=ut(e,f)}if(e[o]==="("){let f=Kn(e,o,"(",")");if(f==null){r=e.length;break}if(o=ut(e,f),e[o]===":")for(o+=1;o<e.length&&e[o]!=="{"&&e[o]!==";";){let y=Ht(e,o);if(y!==o){o=y;continue}o+=1}if(e[o]==="{"){let y=Kn(e,o,"{","}");if(y==null){r=e.length;break}t.push({name:a.ident,modifiers:s,kind:"method",body:e.slice(o+1,y-1)}),n=y;continue}if(e[o]===";"){n=o+1;continue}n=o+1;continue}let l=0,c=0,u=0;for(;o<e.length;){let f=Ht(e,o);if(f!==o){o=f;continue}let y=e[o];if(y==="{")l+=1;else if(y==="}"){if(l===0)break;l-=1}else if(y==="(")c+=1;else if(y===")")c-=1;else if(y==="[")u+=1;else if(y==="]")u-=1;else if(y===";"&&l===0&&c===0&&u===0){o+=1;break}o+=1}t.push({name:a.ident,modifiers:s,kind:"field",body:""}),n=o}return{members:t,truncatedAt:r}}i(qi,"scanClassMembers");function Yi(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 o=s[1],a=s.index+s[0].length,l=1,c=a;for(;c<t.length&&l>0;){let k=t[c];k==="{"?l+=1:k==="}"&&(l-=1),c+=1}let u=t.slice(a,c-1),f=l>0,y=qi(u),g=f?t.length:y.truncatedAt==null?void 0:a+y.truncatedAt,p=y.members.filter(k=>!(k.kind!=="field"||k.name==="constructor"||k.modifiers.includes("private")||k.modifiers.includes("protected")||k.modifiers.includes("readonly")||k.modifiers.includes("static")||k.modifiers.includes("get")||k.modifiers.includes("set"))),m=p.length>0,A=/(?:^|[\n;{])\s*(?:public\s+)?set\s+[a-zA-Z_]/.test(u),S=/(?:^|[\n;{])\s*private\s+constructor\s*\(/.test(u),O=/(?:^|[\n;{])\s*(?:public\s+)?constructor\s*\(/.test(u)&&!S,R=/(?:^|[\n;{])\s*static\s+(?:async\s+)?(?:create|of|from|parse|build|make|new)\s*[<(]/.test(u)||/(?:^|[\n;{])\s*static\s+(?:async\s+)?[A-Za-z_][A-Za-z0-9_]*\s*\([^)]*\)\s*:\s*[A-Za-z_]/.test(u),I=[];for(let k of y.members)k.kind==="method"&&k.name!=="constructor"&&(k.modifiers.includes("static")||k.modifiers.includes("get")||k.modifiers.includes("set")||Wi.has(k.name)||_i(k.name,k.body)&&I.push({name:k.name,referencesGuardOrPublish:Ci(k.body)}));let w=y.members.filter(k=>k.kind==="method").length<=1&&p.length>=2&&m;n.push(Oi({file:e,className:o,exported:!0,hasPublicMutableFields:m,hasPublicSetters:A,hasPublicConstructor:O,hasStaticFactory:R,mutatingMethods:[...I],dataOnly:w},g))}return n}i(Yi,"extractClassShapesFromSource");var Xi=50;function Zn(e){if(!e)return{};let t=typeof e.governedPercent=="number"?e.governedPercent:null,n=typeof e.populatedLayerCount=="number"?e.populatedLayerCount:null;return n==null&&typeof e.classifiedFiles=="number"&&(n=e.classifiedFiles>0?1:0),{governedPercent:t,populatedLayerCount:n}}i(Zn,"normalizeExtraMergeTeethClassification");function Re(e){let t=Zn(e),n=typeof t.governedPercent=="number"?t.governedPercent:null,r=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null;return n==null&&r==null?!0:(n??0)>=50&&(r??0)>=1}i(Re,"extraMergeTeethAllowed");function Qn(e){let t=e.length,n=0,r=new Set;for(let s of e){let o=typeof s.layer=="string"&&s.layer.length>0?s.layer:null;o&&(n+=1,r.add(o))}return{governedPercent:t>0?Math.round(n/t*100):0,populatedLayerCount:r.size}}i(Qn,"classifyResolvedLayerCoverage");function er(e){return typeof e=="string"&&e.startsWith("ARKRUN_")}i(er,"isArkRunRuleId");function Ji(e){return typeof e=="string"&&e.startsWith("ARKORDER_")}i(Ji,"isArkOrderRuleId");function Vs(e){if(e?.arkruleId!=null)return!0;let t=typeof e?.ruleId=="string"?e.ruleId:"";return t.startsWith("ARKRULE")||t.startsWith("arkrule")||t.startsWith("ARKRUN_")||t.startsWith("ARKORDER_")}i(Vs,"isExtraPlaneFinding");function Zi(e,t={}){if(!Array.isArray(e)||Re(t))return e;for(let n of e)Vs(n)&&n.failsStrict!==!1&&(n.failsStrict=!1,n.severity==="error"&&(n.severity="warning"));return e}i(Zi,"demoteExtraPlaneTeethUnderClassificationFloor");var Us="Structure = heuristics; invariants = catalog+coverage evidence (not business runtime); ArkRun = kernel usage + declarations (not a score); ArkOrder = pattern slaving (not a score). Extra planes never merge into one architecture score. Advisory ArkRules \u2260 merge teeth. Advisory ArkRun \u2260 merge teeth. Advisory ArkOrder \u2260 merge teeth.";function Ae(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):0}i(Ae,"countOrZero");function tr(e={}){let t=Zn(e.classification),n=typeof t.governedPercent=="number"?t.governedPercent:null,r=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null,s=n!=null||r!=null,o=Re(t),a=e.arkRules,l=Ae(a?.structureEnforced),c=Ae(a?.structureTotal),u=typeof a?.structureAdvisory=="number"?Ae(a.structureAdvisory):Math.max(0,c-l),f=Ae(a?.invariantEnforced),y=Ae(a?.invariantTotal),g=typeof a?.invariantAdvisory=="number"?Ae(a.invariantAdvisory):Math.max(0,y-f),p=l>0||f>0,m=e.arkRun?.present===!0,A=e.arkRun?.mode==="enforced"||e.arkRun?.mode==="advisory"?e.arkRun.mode:null,S=Ae(e.arkRun?.residualCount),O=m&&A==="enforced",R=O&&o,I=p||O,v=I&&o,w=I&&s&&!o,k;if(v){let z=[];p&&z.push("enforced structure/invariant findings"),O&&z.push("enforced ArkRun skip findings"),k=`Layer graph failures plus ${z.join(" and ")} (advisory extras never fail merge alone).`}else w?k=`Layer graph only \u2014 enforced ${[p?"ArkRules structure/invariant":null,O?"ArkRun":null].filter(T=>!!T).join(" and ")} findings are demoted under the teeth floor (need \u226550% governed and \u22651 populated layer); they do not merge-block until classification is honest.`:k="Layer graph only \u2014 no enforced ArkRules structure/invariant teeth on this tree. Advisory packs do not arm merge teeth."+(m?A==="advisory"?" Advisory ArkRun never merge-blocks.":" ArkRun extra is present but does not arm merge teeth.":" Absence of arkRun is silent.");let L={layers:{role:"inter-layer-edges",alwaysOnGate:!0,note:"Import/export layer graph \u2014 the default merge plane. Absent arkRules or arkRun changes nothing here."},structureSensors:{role:"intra-layer-heuristics",total:c,enforced:l,advisory:u,note:"Structure sensors are heuristics (prefer false negatives). Only mode:enforced fails merge; noisy sensors stay advisory by default. Advisory-only packs never add merge teeth (FG-ARKRULES-ADVISORY-ONLY)."},invariants:{role:"catalog-plus-coverage",total:y,enforced:f,advisory:g,covered:Ae(a?.covered),uncovered:Ae(a?.uncovered),note:"Invariants are catalog + coverage evidence, not a business runtime. Enforced + proven-uncovered fails merge; absence of enforced rules adds no extra teeth."},arkRun:{role:"kernel-usage-and-declarations",present:m,mode:A,residualCount:S,extraMergeTeeth:R,note:m?A==="enforced"?"Enforced ArkRun arms extra merge teeth only when the layer plane is classified. Residual is a count, never a score.":"Advisory ArkRun never adds merge teeth and never flips valid. Residual is a count, never a score.":"Absence of arkRun is silent \u2014 Layers and ArkRules verdicts unchanged. The extra never becomes a score."},extraMergeTeeth:v,dualPlaneStamp:Us,failMergeWhen:k};return s&&(L.classificationGate={governedPercent:n,populatedLayerCount:r,floorPercent:50,allowsTeeth:o}),L}i(tr,"composeMergePlanesHonesty");var Gs=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"],Qi=["publisher","publish","raise","raiseAsync","send","sendTo","subscribe","registerHandler","resolve","resolveSingleton"],el=new Set(Gs),tl=new Set(["AggregateError","Array","ArrayBuffer","BigInt64Array","BigUint64Array","Boolean","DataView","Date","Error","EvalError","FinalizationRegistry","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Number","Object","Promise","Proxy","RangeError","ReferenceError","RegExp","Set","SharedArrayBuffer","String","Symbol","SyntaxError","TypeError","URIError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","WeakRef","WeakSet"]),nl=new Set(["Array","Atomics","Buffer","JSON","Math","Number","Object","Promise","Reflect","String","console","fs","path","url","util"]);function mt(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")}i(mt,"isArkRunKernelModuleSpecifier");var Bs=["events","node:events","eventemitter2","eventemitter3","emittery","kafkajs","kafka-node","amqplib","amqp","bull","bullmq","mqtt","nats","@aws-sdk/client-sqs","@aws-sdk/client-sns","@aws-sdk/client-eventbridge","@google-cloud/pubsub","@azure/service-bus"],nr=new Set(Bs);function sr(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(nr.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(nr.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:nr.has(e.slice(0,r))}i(sr,"isArkRunTransportBypassSpecifier");function rr(e){if(el.has(e))return"factory";switch(e){case"publisher":return"publisher";case"publish":return"publish";case"raise":case"raiseAsync":return"raise";case"send":case"sendTo":return"send";case"subscribe":return"subscribe";case"registerHandler":return"register-handler";case"resolve":return"resolve";case"resolveSingleton":return"resolve-singleton";default:return}}i(rr,"arkRunKernelCallKind");function ft(e,t){let n=1;for(let r=0;r<t;r+=1)e.charCodeAt(r)===10&&(n+=1);return n}i(ft,"lineAt");function gt(e){return e.replace(/\/\*[\s\S]*?\*\//g,t=>t.replace(/[^\n]/g," ")).replace(/(^|[^:\\])\/\/.*$/gm,t=>t.replace(/\/\/.*$/,n=>" ".repeat(n.length)))}i(gt,"stripCommentsPreservingLines");function rl(e,t){let n=e.slice(t),r=/^\s*(['"])((?:\\.|[^\\])*?)\1/.exec(n);if(!r)return;let s=r[2]??"";return s.length>0?s:void 0}i(rl,"firstStringLiteralArg");function Ks(e,t,n){let r=Math.max(0,t-n.length-8),s=e.slice(r,t);return new RegExp(`\\b${n}\\s+$`).test(s)}i(Ks,"keywordBefore");function Ut(e,t){let n=/\b(?:import|export)(\s+type)?\s+([\s\S]*?)\s+from\s*['"]([^'"]+)['"]/g,r;for(;(r=n.exec(e))!==null;)r[1]||t(r[2]??"",r[3]??"")}i(Ut,"parseValueImportClause");function sl(e,t){Ut(gt(e),t)}i(sl,"forEachArkRunValueImportClause");function or(e,t){let n=gt(t),r=[],s=/\b(?:import|export)(\s+type)?\s+([\s\S]*?)\s+from\s*['"]([^'"]+)['"]/g,o;for(;(o=s.exec(n))!==null;){let l=o[3]??"";if(!l)continue;let c=o[0]??"";r.push({from:e,specifier:l,kind:/^\s*export/.test(c)?"export":"import",typeOnly:!!o[1],line:ft(t,o.index),resolution:"resolved-external"})}let a=/\b(?:require|import)\s*\(\s*['"]([^'"]+)['"]\s*\)/g;for(;(o=a.exec(n))!==null;){let l=o[1]??"";if(!l)continue;let c=o[0]?.startsWith("import")?"dynamic-import":"require";r.push({from:e,specifier:l,kind:c,typeOnly:!1,line:ft(t,o.index),resolution:"resolved-external"})}return r}i(or,"extractArkRunValueImportDependenciesFromSource");function ar(e){let t=[];return sl(e,n=>{let r=/\{([^}]*)\}/.exec(n);if(r?.[1])for(let s of r[1].split(",")){let o=s.trim();if(!o||o.startsWith("type "))continue;let a=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(o),l=a?.[2]??/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(o)?.[1],c=a?.[1]??l;l&&c&&/^[A-Z]/.test(c)&&t.push(l,c)}}),pt(t)}i(ar,"extractArkRunImportedConstructorNamesFromSource");function ol(e){let t=new Map,n=new Set;return Ut(e,(r,s)=>{if(!mt(s))return;let o=/\*\s+as\s+([A-Za-z_][A-Za-z0-9_]*)/.exec(r);o?.[1]&&n.add(o[1]);let a=/^([A-Za-z_][A-Za-z0-9_]*)\s*(?:,|$)/.exec(r.trim());a?.[1]&&t.set(a[1],a[1]);let l=/\{([^}]*)\}/.exec(r);if(l?.[1])for(let c of l[1].split(",")){let u=c.trim();if(!u||u.startsWith("type "))continue;let f=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(u);if(f){t.set(f[2],f[1]);continue}let y=/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(u);y?.[1]&&t.set(y[1],y[1])}}),{named:t,namespaces:n}}i(ol,"collectKernelImportBindings");function al(e,t){let n=new Set(t);return Ut(e,(r,s)=>{let o=/\{([^}]*)\}/.exec(r);if(o?.[1])for(let a of o[1].split(",")){let l=a.trim();if(!l||l.startsWith("type "))continue;let c=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(l),u=c?.[2]??/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(l)?.[1],f=c?.[1]??u;!u||!f||!/^[A-Z]/.test(f)||(mt(s)||t.has(f)||t.has(u))&&(n.add(u),n.add(f))}}),n}i(al,"collectImportedConstructors");function il(e,t){let n;return Ut(e,(r,s)=>{!n&&new RegExp(`\\b${t}\\b`).test(r)&&(n=s)}),n}i(il,"importedFromForName");function ir(e,t){let n=gt(t),r=ol(n),s=[],o=/\b([A-Za-z_][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,a;for(;(a=o.exec(n))!==null;){let l=a[1],c=a.index;if(Ks(n,c,"function")||Ks(n,c,"class"))continue;let f=n.slice(0,c).match(/([A-Za-z_][A-Za-z0-9_]*)\s*\.\s*$/)?.[1],y=r.named.get(l)??l,g=rr(y)??rr(l);if(!g)continue;let p=r.named.has(l)||f!==void 0&&r.namespaces.has(f);if(g!=="factory"&&(!p&&f===void 0||f&&nl.has(f)&&!p))continue;let m=rl(n,c+a[0].length);s.push({file:e,line:ft(t,c),kind:g,callee:l,viaImport:p,...f?{receiver:f}:{},...m?{nameLiteral:m}:{}})}return s}i(ir,"extractArkRunKernelCallsFromSource");function lr(e,t,n){let r=gt(t),s=al(r,n),o=[],a=/\bnew\s+(?:[A-Za-z_][A-Za-z0-9_]*\s*\.\s*)*([A-Z][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,l;for(;(l=a.exec(r))!==null;){let c=l[1];if(tl.has(c)||!s.has(c))continue;let u=il(r,c);o.push({file:e,line:ft(t,l.index),typeName:c,...u?{importedFrom:u}:{}})}return o}i(lr,"extractArkRunManagedNewsFromSource");function ll(e,t){let n=0,r;for(let s=t;s<e.length;s+=1){let o=e[s];if(r){if(o==="\\"){s+=1;continue}o===r&&(r=void 0);continue}if(o==="'"||o==='"'||o==="`"){r=o;continue}if(o==="[")n+=1;else if(o==="]"&&(n-=1,n===0))return s}return-1}i(ll,"matchingBracketEnd");function cl(e,t,n){let r=e.slice(t+1,n),s=[],o=/(['"])((?:\\.|[^\\])*?)\1/g,a;for(;(a=o.exec(r))!==null;){let l=a[2]??"";l.length>0&&s.push(l)}return s}i(cl,"stringLiteralsInList");function pt(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}i(pt,"uniqueSorted");function dl(e,t){let n=gt(t),r=/\b(uses|reactsTo|raises|sends)\s*:/g,s=[],o=[],a=[],l=[],c,u;for(;(u=r.exec(n))!==null;){let f=n.slice(u.index+u[0].length),y=/^\s*\[/.exec(f);if(!y)continue;let g=u.index+u[0].length+(y[0].length-1),p=ll(n,g);if(p<0)continue;let m=cl(n,g,p);if(m.length===0)continue;c===void 0&&(c=u.index);let A=u[1];A==="uses"?s.push(...m):A==="reactsTo"?o.push(...m):A==="raises"?a.push(...m):l.push(...m)}return c===void 0?[]:[{file:e,line:ft(t,c),uses:pt(s),reactsTo:pt(o),raises:pt(a),sends:pt(l)}]}i(dl,"extractArkRunDeclarationsFromSource");var ul=["arkrun-missing-root","arkrun-kernel-in-domain","arkrun-direct-new","arkrun-undeclared-emit","arkrun-undeclared-handle","arkrun-undeclared-depend","arkrun-transport-bypass"],pl=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],fl=new Set(pl);function ml(e){return fl.has(e)}i(ml,"isArkRunEditorSensor");var cr={"arkrun-missing-root":"ARKRUN_MISSING_ROOT","arkrun-kernel-in-domain":"ARKRUN_KERNEL_IN_DOMAIN","arkrun-direct-new":"ARKRUN_DIRECT_NEW","arkrun-undeclared-emit":"ARKRUN_UNDECLARED_EMIT","arkrun-undeclared-handle":"ARKRUN_UNDECLARED_HANDLE","arkrun-undeclared-depend":"ARKRUN_UNDECLARED_DEPEND","arkrun-transport-bypass":"ARKRUN_TRANSPORT_BYPASS"},qs="ARKRUN_INTERACTION_NAME_INCOMPLETE";function Ys(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)||/^(?:entit(?:y|ies)|aggregates?)(?:$|(?=[A-Z_\-\s]))/i.test(n)?!0:t.some(r=>{let s=r.trim().replace(/\.+$/,"");return s==="Domain"||s.startsWith("Domain.")})}i(Ys,"isDomainRoleLayer");function gl(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}i(gl,"compareFindings");function ke(e,t,n,r,s,o,a){let l=e.mode==="enforced"&&a;return{ruleId:cr[t],sensor:t,message:s,file:n,line:r,...o?.fromLayer?{fromLayer:o.fromLayer}:{},...o?.target?{target:o.target}:{},severity:l?"error":"warning",failsStrict:l,nextAction:pe({ruleId:cr[t],fromLayer:o?.fromLayer,target:o?.target})}}i(ke,"finding");function yl(e,t){let n=[],r=[],s=[],o=[];for(let a of e)a.file===t&&(n.push(...a.uses),r.push(...a.reactsTo),s.push(...a.raises),o.push(...a.sends));return{uses:new Set(n),reactsTo:new Set(r),raises:new Set(s),sends:new Set(o)}}i(yl,"bagForFile");function zs(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}i(zs,"emitKinds");function Ws(e){return e==="subscribe"||e==="register-handler"}i(Ws,"handleKinds");function hl(e){return e==="resolve"||e==="resolve-singleton"}i(hl,"dependKinds");function Al(e,t,n){let r=[],s=e.kernelRoots??e.compositionRoots;if(s.length===0)return r.push(ke(e,"arkrun-missing-root","ark.config.json",1,"ArkRun kernelRoots is empty; no createArkKernel factory site is declared.",void 0,n)),r;let o=new Map;for(let a of t){let l=o.get(a.matchedRoot)??[];l.push(a),o.set(a.matchedRoot,l)}for(let a of s){let l=[...o.get(a)??[]].sort((u,f)=>u.file.localeCompare(f.file));if(l.length===0){r.push(ke(e,"arkrun-missing-root","ark.config.json",1,`ArkRun kernel root ${JSON.stringify(a)} matched no governed files and has no createArkKernel factory.`,{target:a},n));continue}if(l.some(u=>u.hasKernelFactory))continue;let c=l[0];r.push(ke(e,"arkrun-missing-root",c.file,1,`ArkRun kernel root ${JSON.stringify(a)} has no createArkKernel / createStrictArkKernel factory.`,{target:a},n))}return r}i(Al,"evaluateMissingRoot");function Rl(e,t,n,r,s){let o=new Map(t.map(l=>[l.name,l.intentPrefixes??[]])),a=[];for(let l of n){let c=l.specifier;if(!c||!mt(c))continue;let u=r(l.from);u&&Ys(u,o.get(u)??[])&&a.push(ke(e,"arkrun-kernel-in-domain",l.from,l.line,`${u} must not import kernel module ${JSON.stringify(c)}.`,{fromLayer:u,target:c},s))}return a}i(Rl,"evaluateKernelInDomain");function kl(e,t,n,r,s,o){let a=new Set(e.managedLayers);if(a.size===0)return[];let l=new Map(t.map(f=>[f.name,f.intentPrefixes??[]])),c=new Set(r.filter(f=>f.hasKernelFactory).map(f=>f.file)),u=[];for(let f of n){if(c.has(f.file))continue;let y=f.typeName;if(e.ignoreDirectNewForErrors!==!1&&(y.endsWith("Error")||y==="Error")||y.endsWith("DTO")||y.endsWith("VO"))continue;let g=s(f.file);!g||!a.has(g)||Ys(g,l.get(g)??[])||u.push(ke(e,"arkrun-direct-new",f.file,f.line,`${g} must not construct ${f.typeName} with new outside an ArkRun composition-root factory.`,{fromLayer:g,target:f.typeName},o))}return u}i(kl,"evaluateDirectNew");function El(e,t,n,r,s){let o=[],a=[];if(e.requireDeclarations!==!0)return{findings:o,completenessReasons:a};let l=new Set(e.managedLayers);if(l.size===0)return{findings:o,completenessReasons:a};for(let c of t){if(!zs(c.kind)&&!Ws(c.kind)&&!hl(c.kind))continue;let u=r(c.file);if(!u||!l.has(u))continue;if(!c.nameLiteral){e.mode==="enforced"&&a.push({code:qs,file:c.file,message:`ArkRun ${c.kind} call in ${c.file} has no string-literal name; enforced extra cannot prove the declaration.`});continue}let f=yl(n,c.file);if(zs(c.kind)){if(f.raises.has(c.nameLiteral)||f.sends.has(c.nameLiteral))continue;o.push(ke(e,"arkrun-undeclared-emit",c.file,c.line,`Emit ${JSON.stringify(c.nameLiteral)} is not declared in raises or sends.`,{fromLayer:u,target:c.nameLiteral},s));continue}if(Ws(c.kind)){if(f.reactsTo.has(c.nameLiteral))continue;o.push(ke(e,"arkrun-undeclared-handle",c.file,c.line,`Handle ${JSON.stringify(c.nameLiteral)} is not declared in reactsTo.`,{fromLayer:u,target:c.nameLiteral},s));continue}f.uses.has(c.nameLiteral)||o.push(ke(e,"arkrun-undeclared-depend",c.file,c.line,`Depend ${JSON.stringify(c.nameLiteral)} is not declared in uses.`,{fromLayer:u,target:c.nameLiteral},s))}return{findings:o,completenessReasons:a}}i(El,"evaluateUndeclared");function Il(e,t,n,r){let s=new Set(e.managedLayers);if(s.size===0)return[];let o=[];for(let a of t){if(a.typeOnly)continue;let l=a.specifier;if(!l||!sr(l))continue;let c=n(a.from);!c||!s.has(c)||o.push(ke(e,"arkrun-transport-bypass",a.from,a.line,`${c} must not import broker/queue/emitter ${JSON.stringify(l)}; use the ArkRun kernel transport.`,{fromLayer:c,target:l},r))}return o}i(Il,"evaluateTransportBypass");function Kt(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=Re(e.classification),r=El(t,e.kernelCalls,e.declarations,e.layerForFile,n),s=[...Al(t,e.compositionRootHits,n),...Rl(t,e.layers,e.dependencies,e.layerForFile,n),...kl(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...Il(t,e.dependencies,e.layerForFile,n)].sort(gl),o=[...r.completenessReasons].sort((a,l)=>{let c=`${a.code}\0${a.file??""}\0${a.message}`,u=`${l.code}\0${l.file??""}\0${l.message}`;return c<u?-1:c>u?1:0});return{findings:s,completenessReasons:o}}i(Kt,"evaluateArkRunSensors");function Xs(e){return{findings:Kt(e).findings.filter(n=>ml(n.sensor)),completenessReasons:[]}}i(Xs,"evaluateArkRunEditorSensors");function Sl(e,t){if(e===t)return!0;let n=e.indexOf("*");if(n<0)return!1;let r=e.slice(0,n).replace(/\/$/,"");return r.length>0&&(t===r||t.startsWith(`${r}/`))}i(Sl,"fileMatchesCompositionRoot");function bl(e,t,n){let r=ir(t,n).some(a=>a.kind==="factory"),s=[],o=e.kernelRoots??e.compositionRoots;for(let a of o)Sl(a,t)&&s.push({file:t,matchedRoot:a,hasKernelFactory:r});return s}i(bl,"compositionRootHitsForSource");function vl(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=new Set(ar(e.source));return Xs({arkRun:t,layers:e.layers,kernelCalls:[],managedNews:lr(e.file,e.source,n),compositionRootHits:bl(t,e.file,e.source),declarations:[],dependencies:or(e.file,e.source),layerForFile:e.layerForFile,classification:e.classification})}i(vl,"evaluateArkRunEditorSensorsFromSource");function Js(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}i(Js,"isArkOrderModuleSpecifier");var Zs=new Map;function Qs(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(Qs,"escapeAppliesToLiteral");function Cl(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}i(Cl,"normalizeAppliesToGlob");function _l(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}i(_l,"appliesToBracesBalanced");function Ol(e){let t=Zs.get(e);if(t)return t;let n=Cl(e),r=_l(n),s="",o=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(s+=Qs(n[l+1]),l+=1):c==="*"?n[l+1]==="*"?n[l+2]==="/"?(s+="(?:.*/)?",l+=2):(s+=".*",l+=1):s+="[^/]*":c==="?"?s+="[^/]":c==="{"&&r?(s+="(?:",o+=1):c==="}"&&r&&o>0?(s+=")",o-=1):c===","&&r&&o>0?s+="|":s+=Qs(c)}let a=new RegExp(`^${s}$`);return Zs.set(e,a),a}i(Ol,"globToRegExp");var xl=["arkorder-missing-plane","arkorder-kernel-in-domain","arkorder-generic-update","arkorder-too-many-params","arkorder-ingest-writes-xi","arkorder-xi-field-write","arkorder-information-budget","arkorder-xi-ttl"],dr={"arkorder-missing-plane":"ARKORDER_MISSING_PLANE","arkorder-kernel-in-domain":"ARKORDER_KERNEL_IN_DOMAIN","arkorder-generic-update":"ARKORDER_GENERIC_UPDATE","arkorder-too-many-params":"ARKORDER_TOO_MANY_PARAMS","arkorder-ingest-writes-xi":"ARKORDER_INGEST_WRITES_XI","arkorder-xi-field-write":"ARKORDER_XI_FIELD_WRITE","arkorder-information-budget":"ARKORDER_INFORMATION_BUDGET","arkorder-xi-ttl":"ARKORDER_XI_TTL"};function Tl(e,t){return!t||t.length===0?!0:t.some(n=>Ol(n).test(e))}i(Tl,"matchesArkOrderAppliesTo");function Nl(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)?!0:t.some(r=>{let s=r.trim().replace(/\.+$/,"");return s==="Domain"||s.startsWith("Domain.")})}i(Nl,"isDomainRoleLayer");function be(e,t,n,r,s,o,a){let l=e.mode==="enforced"&&a;return{ruleId:dr[t],sensor:t,message:s,file:n,line:r,...o?.fromLayer?{fromLayer:o.fromLayer}:{},...o?.target?{target:o.target}:{},severity:l?"error":"warning",failsStrict:l,nextAction:pe({ruleId:dr[t],fromLayer:o?.fromLayer,target:o?.target})}}i(be,"finding");function ur(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let n=Re(e.classification),r=[],s=t.planeRoots;if(t.mode==="enforced"&&s.length===0)r.push(be(t,"arkorder-missing-plane","ark.config.json",1,"ArkOrder planeRoots is empty; no createOrderPlane site is declared.",void 0,n));else{let c=new Map;for(let u of e.planeRootHits){let f=c.get(u.matchedRoot)??[];f.push(u),c.set(u.matchedRoot,f)}for(let u of s){let f=c.get(u)??[];if(f.length===0){r.push(be(t,"arkorder-missing-plane","ark.config.json",1,`ArkOrder plane root ${JSON.stringify(u)} matched no governed files and has no createOrderPlane factory.`,{target:u},n));continue}f.some(y=>y.hasPlaneFactory)||r.push(be(t,"arkorder-missing-plane",f[0].file,1,`ArkOrder plane root ${JSON.stringify(u)} has no createOrderPlane factory.`,{target:u},n))}}let o=new Map(e.layers.map(c=>[c.name,c.intentPrefixes??[]]));for(let c of e.dependencies){let u=c.specifier;if(!u||!Js(u))continue;let f=e.layerForFile(c.from);f&&Nl(f,o.get(f)??[])&&r.push(be(t,"arkorder-kernel-in-domain",c.from,c.line,"Domain-role layer imports arkgate/order; Domain stays plane-free.",{fromLayer:f,target:u},n))}for(let c of e.genericUpdates)r.push(be(t,"arkorder-generic-update",c.file,c.line,`Generic ${c.method}() on the order plane rewrites \u03BE; Haken forbids it.`,{target:c.method},n));let a=t.xiKeys??[];for(let c of e.releaseKeyCounts??[])c.keyCount<=t.maxXiKeys||r.push(be(t,"arkorder-too-many-params",c.file,c.line,`release() freezes ${c.keyCount} keys; maxXiKeys is ${t.maxXiKeys} (few slow modes).`,{target:String(c.keyCount)},n));for(let c of e.ingestWritesXi??[])r.push(be(t,"arkorder-ingest-writes-xi",c.file,c.line,"ingest() result is assigned into a Release or \u03BE store; ingest may absorb or escalate, never mint a pattern.",void 0,n));let l=new Set(t.managedLayers);for(let c of a.length===0?[]:e.xiFieldWrites??[]){let u=e.layerForFile(c.file);!u||!l.has(u)||Tl(c.file,t.appliesTo)&&r.push(be(t,"arkorder-xi-field-write",c.file,c.line,`File writes slow key ${JSON.stringify(c.key)} through a persistence driver; route the field through ingest or a pattern change through proposeRelease.`,{fromLayer:u,target:c.key},n))}return r.sort((c,u)=>c.file.localeCompare(u.file)||c.ruleId.localeCompare(u.ruleId)||c.line-u.line),{findings:r,completenessReasons:[]}}i(ur,"evaluateArkOrderSensors");function ne(e,t,n={}){return{ruleId:e,message:t,...n}}i(ne,"configWarning");function Gt(e){let{config:t,rules:n,files:r,manifest:s}=e,o=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(p=>typeof p!="string"))&&o.push(ne("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)))o.push(ne("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let p of["maxTsSuppressions","maxAnyCasts"]){let m=t.safety[p];m!==void 0&&(!Number.isInteger(m)||m<0)&&o.push(ne("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${p} must be a non-negative integer.`))}let a=Array.isArray(t.layers)?t.layers:[],l=Array.isArray(s?.architecture?.layers)?s.architecture.layers:[],c=new Set([...a.map(p=>p.name).filter(Boolean),...l.map(p=>p.name).filter(p=>!!p)]);a.length===0&&o.push(ne("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let u=new Set,f=new Set;for(let p of a){if(!p.name){o.push(ne("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}u.has(p.name)&&f.add(p.name),u.add(p.name),p.forbiddenGlobals!==void 0&&(!Array.isArray(p.forbiddenGlobals)||p.forbiddenGlobals.some(A=>typeof A!="string"))&&o.push(ne("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${p.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:p.name}));let m=Array.isArray(p.patterns)?p.patterns:[];if(m.length===0){o.push(ne("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${p.name}" has no file patterns and will never classify files.`,{layer:p.name}));continue}for(let A of m){let S;try{S=me(A)}catch(R){o.push(ne("CONFIG_INVALID_LAYER_PATTERN",`Layer "${p.name}" has an invalid pattern "${A}": ${R instanceof Error?R.message:String(R)}`,{layer:p.name,pattern:A}));continue}let O=p.optional===!0||p.reserved===!0||p.allowEmpty===!0;!r.some(R=>S.test(R))&&!O&&o.push(ne("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${p.name}" pattern "${A}" matched no included files (possible typo). Mark the layer reserved/allowEmpty if this house is reserved for later.`,{layer:p.name,pattern:A,failsStrict:!1,reserved:!1}))}}for(let p of f)o.push(ne("CONFIG_DUPLICATE_LAYER",`Layer "${p}" is configured more than once.`,{layer:p}));if(c.size>0)for(let p of n??[])p.from&&!c.has(p.from)&&o.push(ne("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${p.from}".`,{fromLayer:p.from,toLayer:p.to})),p.to&&!c.has(p.to)&&o.push(ne("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${p.to}".`,{fromLayer:p.from,toLayer:p.to}));let y=new Set;if(a.length>1)for(let p of r){let m=-1,A=[];for(let S of a)for(let O of S.patterns??[]){if(!me(O).test(p))continue;let R=mn(O,p);R>m?(m=R,A=[S.name]):R===m&&!A.includes(S.name)&&A.push(S.name)}A.length>1&&y.add([...A].sort().join(" + "))}y.size>0&&o.push(ne("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...y].join(", ")}.`,{pairs:[...y]}));let g=r.filter(p=>!de(p,a));return g.length>0&&o.push(ne("CONFIG_UNCLASSIFIED_FILES",`${g.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:g.length,samples:g.slice(0,5)})),o}i(Gt,"collectAnalysisConfigWarnings");function eo(e,t){let n=e.ruleId==="ARKRULE_STRUCTURE",r=e.ruleId==="ARKRULE_SCOPE_EMPTY";return{ruleId:e.ruleId,file:e.file,line:e.line,message:e.message,fromLayer:e.fromLayer,arkruleId:e.arkruleId,arkruleSource:e.arkruleSource,...n?{sensor:e.sensor,code:e.code,target:Ns({sensor:e.sensor,code:e.code})}:{},...r?{freezable:!1}:{},nextAction:t}}i(eo,"toArkRuleEngineViolation");function Ll(e,t){return t.some(n=>{try{return me(n).test(e)}catch{return!1}})}i(Ll,"matchesAny");function Pl(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,o=e.contract.config.dynamicImportAllowlist??[],a=t.safetyUses.filter(A=>A.kind==="ts-suppression").map(({file:A,line:S})=>({file:A,line:S})),l=t.safetyUses.filter(A=>A.kind==="any-cast").map(({file:A,line:S})=>({file:A,line:S})),c=t.safetyUses.filter(A=>(A.kind==="dynamic-import"||A.kind==="dynamic-require")&&!Ll(A.file,o)).map(A=>({file:A.file,line:A.line,kind:A.kind==="dynamic-require"?"require":"import"})),u=n.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(A=>A.kind==="in-memory-store").map(A=>({file:A.file,line:A.line,store:A.symbol??"in-memory store"})),f=n.allowDisabledPeerIsolation===!0?[]:(e.contract.config.rules??[]).filter(A=>A.peerIsolation===!1||A.allowed===!1&&!!A.from&&A.from===A.to&&A.peerIsolation!==!0).map(A=>({from:A.from,to:A.to})),y={tsSuppressions:a,anyCasts:l,nonLiteralDynamicImports:c,inMemoryProductionStores:u,disabledPeerIsolationRules:f,thresholds:{maxTsSuppressions:r,maxAnyCasts:s}},g=[],p=c.filter(A=>A.kind==="import");if(p.length>0){let A=p[0];g.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:A.file,line:A.line,message:`${p.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let m=c.filter(A=>A.kind==="require");if(m.length>0){let A=m[0];g.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:A.file,line:A.line,message:`${m.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(a.length>r){let A=a[0];g.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:A.file,line:A.line,message:`${a.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${r}).`})}if(l.length>s){let A=l[0];g.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:A.file,line:A.line,message:`${l.length} explicit any cast(s) exceed safety.maxAnyCasts (${s}).`})}if(u.length>0){let A=u[0];g.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:A.file,line:A.line,message:`${u.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 f.length>0&&g.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${f.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:y,warnings:g}}i(Pl,"evaluateSafety");function wl(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}i(wl,"ambientForbiddenGlobal");function to(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return kn(e,n.length>0?n:Rn.map(r=>({name:r.layer,prefixes:r.prefixes})))}i(to,"intentLayer");function Dl(e,t,n){let r=[],s=new Map(e.contract.config.layers.map(o=>[o.name,o]));for(let o of t.ambientUses){let a=n.get(o.file);!a||!wl(o.symbol,s.get(a)?.forbiddenGlobals??[])||r.push({ruleId:"FORBIDDEN_GLOBAL",file:o.file,line:o.line,fromLayer:a,target:o.symbol,message:`${a} must not use the ambient global "${o.symbol}".`})}for(let o of t.capabilityUses){let a=n.get(o.file);if(!a)continue;let l=s.get(a),c=l?.forbiddenGlobals??[],u=o.source==="import-based"?t.dependencies.find(f=>f.from===o.file&&f.line===o.line&&f.specifier===o.symbol&&!f.typeOnly)?.kind:void 0;if(!(o.source==="ambient-global"&&Xe(o.symbol,c))){if(o.source==="import-based"){let f=Ee(o.symbol,c);if(f){r.push({ruleId:"FORBIDDEN_GLOBAL",file:o.file,line:o.line,fromLayer:a,target:o.symbol,...u?{edgeKind:u}:{},message:`${a} must not use module "${o.symbol}" because it is the import form of forbidden global "${f}".`});continue}}De(l).includes(o.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:o.file,line:o.line,fromLayer:a,target:o.symbol,capability:o.capability,...u?{edgeKind:u}:{},message:o.source==="import-based"?`${a} denies the ${o.capability} capability; found import of "${o.symbol}".`:`${a} denies the ${o.capability} capability; found ambient "${o.symbol}".`})}}for(let o of t.publishCalls){let a=n.get(o.file);if(!a)continue;for(let c of Je({publishCall:!0,rawIntentName:o.rawIntentName,objectHasIntent:o.objectHasIntent,arkPublishCandidate:o.arkPublishCandidate,hasSource:o.hasSource}))r.push({ruleId:c.ruleId,file:o.file,line:o.line,...c.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:a}:{},message:c.message});if(!o.sourceIntent)continue;let l=to(o.sourceIntent,e.contract);!l||l===a||r.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:o.file,line:o.line,fromLayer:a,toLayer:l,target:o.sourceIntent,message:`Publish source "${o.sourceIntent}" resolves to ${l}, but the publishing file is classified as ${a}.`})}for(let o of t.intentReferences){let a=n.get(o.file);if(!a)continue;let l=to(o.intent,e.contract);if(!l)continue;let c=Ce(e.contract.config.rules,a,l,{fromPath:o.file,layers:e.contract.config.layers});if(!c)continue;let u=c.rule.peerIsolation?Me(c.peerIsolationReason??"cross-slice",{fromPath:o.file,fromSlice:c.fromSlice,toSlice:c.toSlice}):void 0,f=`${a} must not reference ${l} intent ${o.intent}.`,y=u&&c.peerIsolationReason!=="cross-slice"?`${f} ${u}`:c.rule.message?u?`${c.rule.message} (${u})`:c.rule.message:f;r.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:o.file,line:o.line,fromLayer:a,toLayer:l,target:o.intent,...c.rule.peerIsolation?{peerIsolation:!0}:{},message:y})}return r}i(Dl,"contentViolations");function Ml(e){let{facts:t}=e,n=rt(e.contract.config),r=t.evidenceRequirementsHash===n,s=r?t.completeness:"unavailable",o=r?t.completenessReasons:[...t.completenessReasons,{code:"EVIDENCE_REQUIREMENTS_MISMATCH",message:"Resolved facts were collected for different policy-controlled evidence requirements."}].sort((d,P)=>{let $=`${d.code}\0${d.file??""}\0${d.message}`,ae=`${P.code}\0${P.file??""}\0${P.message}`;return $<ae?-1:$>ae?1:0}),a=t.files.map(d=>({...d,layer:de(d.path,e.contract.config.layers)??null})),l=new Map(a.map(d=>[d.path,d.layer])),c=t.dependencies.map(d=>{let P=d.target?l.get(d.target)??de(d.target,e.contract.config.layers):void 0;return{from:d.from,fromLayer:l.get(d.from)??null,...d.resolution==="resolved-project"&&d.target?{to:d.target,...P?{toLayer:P}:{}}:{},line:d.line,kind:d.kind,typeOnly:d.typeOnly,...d.targetTypeOnlyExports?{targetTypeOnlyExports:d.targetTypeOnlyExports}:{},...d.sourcePureTypeModule?{sourcePureTypeModule:d.sourcePureTypeModule}:{},...d.namedBindingsTypeOnly?{namedBindingsTypeOnly:d.namedBindingsTypeOnly}:{},...d.portProofEligible?{portProofEligible:d.portProofEligible}:{}}}),u=Gt({config:e.contract.config,rules:e.contract.config.rules,files:a.map(d=>d.path)}),f=Pl(e,t),y=e.contract.arkRules??Ne(),g=a.map(d=>d.path),m={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?Jn(e.coverageInputs.fileContents):{},...e.fileHints??{}},A=[...Yn({arkRules:y,classShapes:e.contract.classShapes??t.classShapes??[],files:g,layerForFile:i(d=>l.get(d)??de(d,e.contract.config.layers),"layerForFile"),fileHints:m}),...Xn(y,g)],S=A.filter(d=>d.failsStrict).map(d=>eo(d,d.ruleId==="ARKRULE_SCOPE_EMPTY"?`Fix appliesTo globs for ${d.arkruleId} in ${d.arkruleSource} so they match governed files, or remove the rule. ARKRULE_SCOPE_EMPTY is a config diagnostic and is not freezable (even with --force). Land the rule as advisory until the folder exists, then promote.`:`Fix the structure or invariant for ${d.arkruleId} (declared in ${d.arkruleSource}), then preflight again.`)),O=A.filter(d=>!d.failsStrict).map(d=>({...eo(d,d.ruleId==="ARKRULE_SCOPE_EMPTY"?`Review appliesTo for ${d.arkruleId} in ${d.arkruleSource} (zero-match scope; advisory). Empty scope is not freezable; promote only after the folder exists.`:`Review ArkRule ${d.arkruleId} in ${d.arkruleSource} (advisory).`),failsStrict:!1})),I=(y.invariants?.length??0)>0?Dn({arkRules:y,fileContents:e.coverageInputs?.fileContents??{},testFiles:e.coverageInputs?.testFiles??[],testGlobsMissing:e.coverageInputs?.testGlobsMissing===!0||e.coverageInputs===void 0||(e.coverageInputs.testFiles?.length??0)===0,coverageBudgetExhausted:e.coverageInputs?.coverageBudgetExhausted===!0,...e.coverageInputs?.stats?{coverageStats:e.coverageInputs.stats}:{},...e.coverageInputs?.coverageRoots?{coverageRoots:e.coverageInputs.coverageRoots}:{}}):{coverage:[],violations:[],partial:!1},v=I.violations.filter(d=>d.failsStrict).map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,arkruleId:d.arkruleId,arkruleSource:d.arkruleSource,nextAction:`Add a test title or declared symbol covering ${d.arkruleId} (declared in ${d.arkruleSource}), then preflight again.`})),w=I.violations.filter(d=>!d.failsStrict).map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,arkruleId:d.arkruleId,arkruleSource:d.arkruleSource,failsStrict:!1,nextAction:d.ruleId==="INVARIANT_COVERAGE_OUTSIDE_ROOTS"?`Move ${d.file} under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json.`:`Cover invariant ${d.arkruleId} in ${d.arkruleSource} (advisory / partial).`})),k=Qn(a),L=Kt({arkRun:e.contract.config.arkRun,layers:e.contract.config.layers,kernelCalls:t.arkRunKernelCalls,managedNews:t.arkRunManagedNews,compositionRootHits:t.arkRunCompositionRootHits,declarations:t.arkRunDeclarations,dependencies:t.dependencies,layerForFile:i(d=>l.get(d)??de(d,e.contract.config.layers),"layerForFile"),classification:k}),z=e.contract.config.arkRun?.mode,T=L.findings.filter(()=>z==="enforced").map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,target:d.target,nextAction:d.nextAction,sensor:d.sensor,failsStrict:d.failsStrict,...d.severity?{severity:d.severity}:{}})),Y=L.findings.filter(()=>z!=="enforced").map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,target:d.target,nextAction:d.nextAction,sensor:d.sensor,failsStrict:!1})),F=ur({arkOrder:e.contract.config.arkOrder,layers:e.contract.config.layers,planeCalls:t.arkOrderPlaneCalls,genericUpdates:t.arkOrderGenericUpdates,planeRootHits:t.arkOrderRootHits,xiFieldWrites:t.arkOrderXiFieldWrites,ingestWritesXi:t.arkOrderIngestWritesXi,releaseKeyCounts:t.arkOrderReleaseKeyCounts,dependencies:t.dependencies,layerForFile:i(d=>l.get(d)??de(d,e.contract.config.layers),"layerForFile"),classification:k}),ce=e.contract.config.arkOrder?.mode,fe=F.findings.filter(()=>ce==="enforced").map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,target:d.target,nextAction:d.nextAction,sensor:d.sensor,failsStrict:d.failsStrict,...d.severity?{severity:d.severity}:{}})),At=F.findings.filter(()=>ce!=="enforced").map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,target:d.target,nextAction:d.nextAction,sensor:d.sensor,failsStrict:!1})),qe=[...I.partial&&I.coverage.some(d=>d.mode==="enforced"&&d.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."}]:[],...L.completenessReasons,...F.completenessReasons],ve=Ge({config:e.contract.config,rules:e.contract.config.rules,files:a.filter(d=>d.layer).map(d=>d.path),contentViolations:[...Dl(e,t,l),...S,...v,...T,...fe],edges:c,warnings:[...u,...f.warnings,...O,...w,...Y,...At],safety:f.report}),Rt=s==="complete"&&qe.length>0?"partial":s,nn=Rt==="complete"?o:[...o,...qe].sort((d,P)=>{let $=`${d.code}\0${d.file??""}\0${d.message}`,ae=`${P.code}\0${P.file??""}\0${P.message}`;return $<ae?-1:$>ae?1:0}),b=ve.violations.filter(d=>d.failsStrict!==!1),C=Rt==="complete"&&b.length===0,h=C&&ve.warnings.every(d=>d.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:Rt,completenessReasons:nn,valid:C,strictValid:h,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:f.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:a,layers:e.contract.config.layers.map(d=>d.name),edges:c,capabilityUses:t.capabilityUses,violations:ve.violations,warnings:ve.warnings}}}i(Ml,"analyzeCanonicalResolvedProject");function yt(e){return Ml({contract:e.contract,facts:Ie(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints})}i(yt,"analyzeResolvedProject");function no(e){return X(H(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}i(no,"analysisTreeHash");function ro(e){let t=dt(e),n=new Map(t.ir.files.map(m=>[m.path,m])),r=[],s=new Set,o=[];for(let m of e.changes){let A=m.path.replace(/\\/g,"/"),S=Le(m.path);if(!S||S===".."||S.startsWith("../")||A.startsWith("/")||/^[A-Za-z]:\//.test(A)||A.includes("\0")){o.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(S)){o.push({ruleId:"DUPLICATE_CHANGE_PATH",file:S,line:1,message:`The atomic change set contains more than one operation for ${S}.`});continue}s.add(S),"delete"in m&&m.delete&&!n.has(S)&&o.push({ruleId:"DELETE_TARGET_MISSING",file:S,line:1,message:`Cannot delete ${S} because it is not present in the supplied base tree.`}),r.push("delete"in m&&m.delete?{path:S,delete:!0}:{path:S,content:"content"in m?m.content:""})}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."});let a=$t({...e,changes:r}),l=new Map(a.ir.files.map(m=>[m.path,m])),c=a.ir.violations.filter(m=>m.ruleId==="CAPABILITY_VIOLATION"||m.ruleId==="FORBIDDEN_GLOBAL").map(m=>{let A=l.get(m.evidence.file)?.layer;return{ruleId:m.ruleId,file:m.evidence.file,line:m.evidence.line,target:m.symbol,...m.capability?{capability:m.capability}:{},...A?{fromLayer:A}:{},edgeKind:"import",message:m.message}}),u=Ge({config:e.contract.config,rules:e.contract.config.rules,files:a.ir.files.map(m=>m.path),contentViolations:c,edges:a.ir.edges.filter(m=>!!m.fromLayer).map(m=>({from:m.from,fromLayer:m.fromLayer,...m.to?{to:m.to}:{},...m.toLayer?{toLayer:m.toLayer}:{},line:m.evidence.line,kind:"import",...m.typeOnly?{typeOnly:!0}:{},...m.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),f=r.map(m=>{let A=Le(m.path),S=n.get(A),O=l.get(A);return{path:A,operation:"delete"in m&&m.delete?"delete":S?"update":"create",...S?{beforeContentHash:S.contentHash}:{},...O?{candidateContentHash:O.contentHash}:{}}}).sort((m,A)=>m.path.localeCompare(A.path)),y=[...o,...u.violations].map(m=>({...m,nextAction:pe(m)})),g=y.filter(m=>m.failsStrict!==!1),p=e.changeMap?Ke({changeMap:e.changeMap,changes:f,baseDependencies:t.ir.edges.flatMap(m=>m.to?[{from:m.from,to:m.to}]:[]),candidateDependencies:a.ir.edges.flatMap(m=>m.to?[{from:m.from,to:m.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&a.valid&&g.length===0&&(p?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:a.ir.compilerOptionsHash,baseTreeHash:no(t.ir.files),candidateTreeHash:no(a.ir.files),baseCompleteness:t.completeness,candidateCompleteness:a.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:a.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...p?{convergence:p}:{},changes:f,violations:y,warnings:u.warnings}}i(ro,"preflightChange");function Fl(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}i(Fl,"canonicalChangePath");function $l(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,o])=>({ruleId:"FACTS_IDENTITY_MISMATCH",file:"<change-set>",line:1,field:r,before:s,candidate:o,message:`Base and candidate facts must use the same ${r}.`}))}i($l,"identityViolations");function Hl(e,t,n,r){let s=n.get(t),o=r.get(t);return{path:t,operation:"delete"in e&&e.delete?"delete":s?"update":"create",...s?{beforeContentHash:s.contentHash}:{},...o?{candidateContentHash:o.contentHash}:{}}}i(Hl,"preparedChange");function so(e){let t=Ie(e.baseFacts),n=Ie(e.candidateFacts),r=yt({contract:e.contract,facts:t}),s=yt({contract:e.contract,facts:n}),o=new Map(t.files.map(p=>[p.path,p])),a=new Map(n.files.map(p=>[p.path,p])),l=$l(t,n),c=new Map,u=[];for(let p of e.changes){let m=Fl(p.path);if(!m){l.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(c.has(m)){l.push({ruleId:"DUPLICATE_CHANGE_PATH",file:m,line:1,message:`The atomic change set contains more than one operation for ${m}.`});continue}c.set(m,p);let A=o.get(m),S=a.get(m);if("delete"in p&&p.delete)A||l.push({ruleId:"DELETE_TARGET_MISSING",file:m,line:1,message:`Cannot delete ${m} because it is not present in the supplied base facts.`}),S&&l.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:m,line:1,message:`Candidate facts still contain deleted file ${m}.`});else{let O="content"in p?p.content:"",R=X(O);S?S.contentHash!==R&&l.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:m,line:1,expectedContentHash:R,candidateContentHash:S.contentHash,message:`Candidate facts for ${m} do not match the declared content.`}):l.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:m,line:1,message:`Candidate facts do not contain changed file ${m}.`})}u.push(Hl(p,m,o,a))}e.changes.length===0&&l.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});for(let p of new Set([...o.keys(),...a.keys()])){if(c.has(p))continue;let m=o.get(p),A=a.get(p);m&&A&&H(m)===H(A)||l.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:p,line:1,message:`Candidate facts change ${p}, but the atomic change set does not declare it.`})}let f=e.changeMap?Ke({changeMap:e.changeMap,changes:u,baseDependencies:r.ir.edges.flatMap(p=>p.to?[{from:p.from,to:p.to}]:[]),candidateDependencies:s.ir.edges.flatMap(p=>p.to?[{from:p.from,to:p.to}]:[])}):void 0,y=[...l,...s.ir.violations].map(p=>({...p,nextAction:pe(p)})),g=y.filter(p=>p.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&s.strictValid&&g.length===0&&(f?.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}:{},...f?{convergence:f}:{},changes:u.sort((p,m)=>p.path<m.path?-1:p.path>m.path?1:0),violations:y,warnings:s.ir.warnings}}i(so,"preflightResolvedChange");var oo="1.0",jl=12;function ao(e){return e==="enforced"||e==="advisory"?e:null}i(ao,"closedMode");function Vl(e){let t=new Set;if(!Array.isArray(e))return[];for(let n of e){let r=n?.ruleId;typeof r!="string"||!er(r)||t.has(r)||t.add(r)}return[...t].sort((n,r)=>n<r?-1:n>r?1:0)}i(Vl,"uniqueArkRunRuleIds");function Ul(e){return!e||typeof e!="object"?{present:!1,mode:null,roots:0,layers:0,requireDeclarations:null}:{present:!0,mode:ao(e.mode),roots:Array.isArray(e.compositionRoots)?e.compositionRoots.length:0,layers:Array.isArray(e.managedLayers)?e.managedLayers.length:0,requireDeclarations:e.requireDeclarations===!0}}i(Ul,"extraFromConfig");function Kl(e={}){let t=Ul(e.arkRun),n=t.present?Vl(e.findings):[],r=n.slice(0,jl),s=n.length,o=tr({classification:e.classification,arkRules:{active:e.arkRules?.active===!0,structureEnforced:e.arkRules?.structureEnforced,structureTotal:e.arkRules?.structureTotal,structureAdvisory:e.arkRules?.structureAdvisory,invariantEnforced:e.arkRules?.invariantEnforced,invariantTotal:e.arkRules?.invariantTotal,invariantAdvisory:e.arkRules?.invariantAdvisory,covered:e.arkRules?.covered,uncovered:e.arkRules?.uncovered},arkRun:{present:t.present,mode:t.mode,residualCount:s}}),a=t.present&&t.mode==="enforced"&&Re(e.classification),l;return t.present?t.mode==="advisory"?l="Advisory ArkRun residual only \u2014 never flips valid or --strict-merge. Residual is a finding-id count, never a score.":a?l="Enforced ArkRun is on the extra merge plane. Residual is a finding-id count, never a score.":l="Enforced ArkRun extra teeth stay demoted until the layer plane is honestly classified. Residual is a finding-id count, never a score.":l="Absence of arkRun is silent \u2014 Layers and ArkRules verdicts unchanged. Not a score.",{schemaVersion:oo,notAScore:!0,active:t.present,mode:t.mode,compositionRoots:t.roots,managedLayers:t.layers,requireDeclarations:t.requireDeclarations,residual:{count:s,ruleIds:r},extraMergeTeeth:a,failMergeWhen:o.failMergeWhen,note:l,mergePlanes:o}}i(Kl,"summarizeArkRunSection");function pr(e={}){let t=e.present===!0,n=ao(e.mode),r=e.residual,s=null;return typeof r=="number"&&Number.isFinite(r)&&r>=0&&(s=Math.floor(r)),t||(s=s??0),{notAScore:!0,present:t,mode:t?n:null,extraMergeTeeth:t&&n==="enforced"&&e.extraMergeTeeth===!0,residual:s}}i(pr,"projectStatusArkRun");function Gl(e){if(!e||e.notAScore!==!0)return[];if(e.active!==!0)return["ArkRun extra is off \u2014 silent on Layers/ArkRules (not a score)."];let t=e.mode??"unknown",n=e.extraMergeTeeth===!0?"armed":"not armed",r=[`mode: ${t} \xB7 extra merge teeth ${n} \xB7 not a score`];if(e.residual.count>0){let s=e.residual.ruleIds.join(", "),o=e.residual.count>e.residual.ruleIds.length?` (+${e.residual.count-e.residual.ruleIds.length} more)`:"";r.push(`Residual: ${s}${o}`)}else r.push("Residual: none on this scan (not a score \u2014 green extras \u2260 finished kernel wiring).");return e.failMergeWhen&&r.push(e.failMergeWhen),r}i(Gl,"formatArkRunDoctorLines");function Bt(e,t){return e.slice(0,t).split(`
13
+ `).length}i(Bt,"lineOf");function io(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}i(io,"normalizeInventoryPath");function co(e,t){return e.some(n=>{let r=n.trim().replace(/\.+$/,"");return t.some(s=>r===s||r.startsWith(`${s}.`))})}i(co,"ownsIntent");function lo(e,t=[]){return/domain|entity|aggregate|model/i.test(e)||co(t,["Domain"])}i(lo,"isDomainLayer");function Bl(e,t=[]){return/application|orchestration|presentation|adapter|framework|interface|delivery|transport|inbound|controller/i.test(e)||co(t,["Application","Orchestration","Presentation","Adapter","Interface","Delivery","Transport"])}i(Bl,"isControllerEligibleLayer");function zl(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)}i(zl,"isNonPilotSurface");function Wl(e){let t=[],n=0,r=new Map(Object.entries(e.fileLayers??{}).map(([c,u])=>[io(c),u])),s=new Map((e.layerContexts??[]).map(c=>[c.name,c.intentPrefixes??[]])),o=(e.layerContexts??[]).find(c=>lo(c.name,c.intentPrefixes))?.name??"DomainModel";for(let[c,u]of Object.entries(e.fileContents).sort(([f],[y])=>f.localeCompare(y))){let f=io(c);if(zl(f)||/GENERATED FILE\s+[—-]\s+do not edit by hand/i.test(u.slice(0,320)))continue;let y=r.has(f),g=r.get(f),p=g?s.get(g)??[]:[],m=/(?:^|\/)(?:components|ui|layouts|styles|hooks|theme|tokens|i18n|locales?)(?:\/|$)/i.test(f)||/(?:^|\/)(?:src\/)?(?:app|pages)\/.+\.(?:tsx|jsx)$/i.test(f)&&/(?:page|layout|loading|error|template|default)\.(?:tsx|jsx)$/i.test(f),A=/(?:^|\/)(?:app|pages)(?:\/[^/]+)*\/api(?:\/|$)/i.test(f),S=/(?:^|\/)actions?(?:\/|\.|$)/i.test(f)||/['"]use server['"]/.test(u),O=/controller|handler|resolver/i.test(c)||A||S||/route\.(?:ts|js|tsx|jsx)$/i.test(f)&&!m||/@(Controller|Get|Post|Put|Delete|Patch)\b/.test(u)||/\bexport\s+(?:async\s+)?function\s+(?:GET|POST|PUT|DELETE|PATCH)\b/.test(u)||/\bexport\s+const\s+(?:GET|POST|PUT|DELETE|PATCH)\s*=/.test(u),R=y?!!(g&&Bl(g,p)&&O):O,I=y?!!(g&&lo(g,p)):/domain|entity|aggregate|model/i.test(c),v=!y||I||R;if(R&&!m){let T=/\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,Y;for(;(Y=T.exec(u))!==null;)n+=1,t.push({id:`inv-val-${n}`,kind:"validation-in-controller",file:c,line:Bt(u,Y.index),message:"Business validation appears in a controller/handler \u2014 extract an invariant or Domain rule.",confidence:"direct-evidence",governedLayer:g,suggestedArkRule:{layer:o,invariantId:`INV-EXTRACT-${n}`,sensor:"invariant-coverage"},neverMechanicalSafe:!0})}let w=/\b(const|let)\s+([A-Z][A-Z0-9_]{2,})\s*=\s*(\d{2,}|['"][^'"]{8,}['"])/g,k,L=i(T=>/^(?: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(T)||/^(?: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(T)||/_(?:ROUTE|PATH|LABEL|TITLE|COLOR|THEME|CLASS|STYLE|ICON|ARIA|MSG|COPY|TIMEOUT|PORT|VERSION|RETRY|DELAY|INTERVAL|TTL|CACHE)$/i.test(T)||/_(?:TIMEOUT(?:_MS)?|MS|BYTES|BUCKET|STORAGE_KEY|WINDOW_MS)$/i.test(T)||/^(?: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(T)||/^(?:FAVORITES_STORAGE|LISTINGS_CACHE|DOCS_PATH|METRICS_INTERVAL)/i.test(T)||/^(?:DEV|DEMO|SEED|FIXTURE)_[A-Z0-9_]+$/i.test(T)||/^(?:PG|POSTGRES|OID)_[A-Z0-9_]+$/i.test(T)||/_(?:OID|OIDS)$/i.test(T)||/^(?:INT2|INT4|INT8|FLOAT4|FLOAT8|NUMERIC|DATE|TIME|TIMESTAMP|TIMESTAMPTZ|JSON|JSONB|UUID)OID$/i.test(T)||/(?:^|_)(?:SCHEMA|PROTOCOL|RESOLVER|FORMAT)_(?:URL|URI|VERSION|ID|IDENTITY)$/i.test(T),"isInfraMagicName"),z=i((T,Y)=>{if(/^(?:ERROR|SUCCESS|WARNING|INFO|HINT|HELP|EMPTY|TOAST|SNACK|ALERT|BANNER|DIALOG|MODAL|TOOLTIP|CAPTION|SUBTITLE|HEADLINE|USER|UI|DISPLAY|FEEDBACK)_(?:MSG|MESSAGE|TEXT|COPY|LABEL|TITLE|BODY|DESC|DESCRIPTION|HINT|HELP)?/i.test(T)||/_(?:MSG|MESSAGE|TEXT|COPY|TOAST|SNACK|ALERT|BANNER|CAPTION|HINT|HELP_TEXT|ERROR_TEXT|EMPTY_TEXT|PLACEHOLDER_TEXT|USER_MESSAGE|FEEDBACK)$/i.test(T))return!0;let F=Y.replace(/^['"]|['"]$/g,"");return!!(/^['"]/.test(Y)&&(/\s/.test(F)||/[.!?…]$/.test(F))&&!/^(?:STATUS|STATE|PHASE|ROLE|TYPE|KIND|ORDER|PAYMENT|CART|INVOICE|POLICY)_[A-Z0-9_]+$/i.test(T))},"isUxMessageConstant");for(;(k=w.exec(u))!==null;){let T=k[2],Y=k[3]??"";!v||L(T)||z(T,Y)||m&&!I||/(?:^|\/)(?:integrations?|repos?|clients?|infra(?:structure)?|adapters?)(?:\/|$)/i.test(f)&&!I||(n+=1,t.push({id:`inv-magic-${n}`,kind:"magic-business-constant",file:c,line:Bt(u,k.index),message:`Magic business constant ${T} may belong in a Domain policy or invariant catalog.`,confidence:"heuristic",governedLayer:g,suggestedArkRule:{layer:o,invariantId:`INV-${T}`},neverMechanicalSafe:!0}))}if(I){let T=/export\s+class\s+([A-Za-z_][A-Za-z0-9_]*)\s*\{([^}]{0,800})\}/g,Y;for(;(Y=T.exec(u))!==null;){let F=Y[2]??"",ce=(F.match(/\b[a-zA-Z_][a-zA-Z0-9_]*\s*\(/g)??[]).length;(F.match(/:\s*[A-Za-z]/g)??[]).length>=2&&ce<=1&&(n+=1,t.push({id:`inv-anemic-${n}`,kind:"anemic-entity",file:c,line:Bt(u,Y.index),message:`Class ${Y[1]} looks anemic (data-heavy, few behaviors).`,confidence:"heuristic",governedLayer:g,suggestedArkRule:{layer:o,structureId:"no-anemic-model",sensor:"no-anemic-model"},neverMechanicalSafe:!0}))}}if(I&&!(/\.error\.(?:ts|js|tsx|jsx)$/i.test(f)||/(?:^|\/)[^/]*(?:-access)?\.error\./i.test(f)||/(?:^|\/)errors?(?:\/|$)/i.test(f))){let Y=/\bthis\.[A-Za-z_][A-Za-z0-9_]*\s*=(?!=)/g,F;for(;(F=Y.exec(u))!==null;){let ce=u.lastIndexOf("class ",F.index),fe=ce>=0?u.indexOf("{",ce):-1,At=ce>=0&&fe>=ce&&fe<F.index?u.slice(ce,fe):"";if(/\bextends\s+(?:Error|[A-Za-z_$][A-Za-z0-9_$]*Error)\b/.test(At)||qn(u,F.index))continue;let we=u.slice(Math.max(0,F.index-200),F.index+200);if(!Bn.test(we)&&!zn.test(we)){n+=1,t.push({id:`inv-mut-${n}`,kind:"mutation-without-guard",file:c,line:Bt(u,F.index),message:`Domain field mutation without nearby ${Wn()}.`,confidence:"heuristic",governedLayer:g,suggestedArkRule:{layer:o,structureId:"events-on-mutation",sensor:"domain-event-on-mutation"},neverMechanicalSafe:!0});break}}}}let a=new Set(e.contractedRuleIds??[]);t.sort((c,u)=>+(u.confidence==="direct-evidence")-+(c.confidence==="direct-evidence")||c.file.localeCompare(u.file)||c.line-u.line||c.kind.localeCompare(u.kind)||c.id.localeCompare(u.id));let l=t.filter(c=>c.suggestedArkRule?.invariantId&&a.has(c.suggestedArkRule.invariantId)||c.suggestedArkRule?.structureId&&a.has(c.suggestedArkRule.structureId)).length;return{candidates:t,inventoried:t.length,underContract:l,frozen:(e.frozenKeys??[]).length,notAScore:!0}}i(Wl,"buildRulesInventory");function ql(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."}}i(ql,"inventoryToExtractionCard");var Yl="1.1";var Xl="1.0";var fr="docs/diagnostics.md",Jl="1.0";function E(e,t,n,r,s,o){return{ruleId:e,title:n,why:r,fix:s,docsAnchor:e,category:t,...o?.oftenAdvisory?{oftenAdvisory:!0}:{}}}i(E,"entry");var zt=Object.freeze([E("LAYER_IMPORT_VIOLATION","layer","Layer import not allowed","A module import (or re-export) crosses a layer edge that ark.config.json does not allow. The architecture contract forbids that dependency direction so outer infrastructure cannot leak into pure or inner layers.","Branch by import kind: constants/types/pure \u2192 adopt into DomainModel or SharedKernel (do not invent a port); kernel/events/bootstrap from Persistence \u2192 inject a port or move the map to SharedTypes (Persistence must not emit); define a port only when the target is a real use-case. Type-only edges use `import type`. Then preflight again. Do not weaken the layer rule without a hash-bound policy acknowledgement."),E("LAYER_INTENT_REFERENCE_VIOLATION","layer","Intent referenced across a blocked layer edge","A string intent (or intent-like reference) names a layer that the file\u2019s layer may not reach under the contract rules \u2014 the same plane as import edges, for event/intent coupling.","Reference that intent from a layer allowed to know about it (usually an adapter or application layer), or relocate the reference \u2014 then preflight again."),E("LAYER_REFERENCE_VIOLATION","layer","Layer reference blocked (snippet / AI gate)","Snippet analysis found an intent or string reference that would couple layers in a direction the architecture profile forbids.","Move the reference to an allowed layer or introduce a port/event boundary, then re-run the snippet gate."),E("CIRCULAR_DEPENDENCY","layer","Dependency cycle","Two or more modules import each other in a loop. Cycles make ownership unclear and break stable layer direction.","Extract the shared dependency into a third module, invert one edge behind a port, or merge units that are truly one \u2014 then preflight again."),E("FORBIDDEN_GLOBAL","capability","Forbidden ambient global or dual import","The file\u2019s layer lists this ambient (or its exact import dual, e.g. process / node:process) in forbiddenGlobals. Pure layers must not reach wall-clock, network, process, or similar effects directly.","Inject the capability through a small port (Clock, HttpPort, Config, \u2026), bind the implementation outside the walled layer, then preflight again."),E("CAPABILITY_VIOLATION","capability","Denied effect capability","The layer denies an effect capability (network, filesystem, clock, randomness, environment, process, persistence) and the candidate uses that effect via ambient or import evidence.","Define a capability port in the walled layer, bind the implementation in an adapter layer, then preflight again. Never mechanical-safe \u2014 port shape is a design decision."),E("RAW_EVENT_PUBLISH","publish","Raw event publish","Publish went through a raw string or object instead of a registered intent creator, bypassing Ark intent contracts and tooling.","Publish through a registered intent creator, then run Ark again."),E("PUBLISH_MISSING_SOURCE","publish","Publish missing metadata.source","A strict Ark publish call omitted metadata.source, so the publishing layer cannot be verified.","Add metadata.source to the publish call, then run Ark again."),E("PUBLISH_SOURCE_LAYER_MISMATCH","publish","Publish source layer mismatch","metadata.source resolves to a different layer than the file performing the publish.","Use a source intent owned by the same layer as this file, or move the publish call to the owning layer."),E("UNKNOWN_INTENT","publish","Unknown intent reference","Snippet analysis saw an intent string that is not registered in the intent registry / profile under check.","Register the intent or use a known intent name from the project registry, then re-run the gate."),E("DYNAMIC_IMPORT_NOT_ALLOWLISTED","safety","Non-literal dynamic import","A dynamic import(expr) cannot be resolved statically and the file is not on dynamicImportAllowlist. Unresolved dynamics can hide layer edges.","Rewrite to a static import when possible, or add only reviewed files to dynamicImportAllowlist after human sign-off."),E("DYNAMIC_REQUIRE_NOT_ALLOWLISTED","safety","Non-literal require","A require(expr) cannot be resolved statically and is not allowlisted \u2014 same hide-the-edge risk as dynamic import.","Prefer static import, or allowlist only reviewed files after sign-off."),E("TS_SUPPRESSION_THRESHOLD_EXCEEDED","safety","@ts-ignore / @ts-nocheck threshold","Count of TypeScript suppressions in governed production source exceeds safety.maxTsSuppressions.","Remove suppressions by fixing types, or raise the threshold only with an explicit production exception in ark.config.json."),E("ANY_CAST_THRESHOLD_EXCEEDED","safety","Explicit any cast threshold","Count of explicit any casts exceeds safety.maxAnyCasts.","Replace any with precise types, or raise the threshold only with a documented exception."),E("IN_MEMORY_STORE_IN_PRODUCTION_SOURCE","safety","In-memory store in production source","Governed production source references an Ark InMemory* store without safety.allowInMemory \u2014 durable systems should not ship ephemeral stores by accident.","Provide a durable store implementation, or set safety.allowInMemory only for an explicitly ephemeral service."),E("PEER_ISOLATION_DISABLED","safety","peerIsolation disabled on a rule","A same-layer or peer rule disables peerIsolation (or omits it where required), which allows cross-slice coupling the contract otherwise blocks.","Restore peerIsolation: true, or set safety.allowDisabledPeerIsolation only with a documented production exception."),E("ARKRULE_STRUCTURE","arkrules","ArkRule structure sensor failed","An opt-in ArkRules structure sensor (private state, factory shape, event publish, persistence write outside an aggregate, \u2026) failed on a governed file for a declared arkruleId.","Restore the declared structure for the ArkRule (see arkruleSource), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement."),E("ARKRULE_INVARIANT","arkrules","ArkRule invariant failed","Reserved / remediation-recognized code for invariant-plane failures bound to an ArkRule id (coverage path also emits INVARIANT_UNCOVERED).","Fix the invariant for the ArkRule declared in arkrules/<Layer>.json, then preflight again. Do not demote without acknowledgement."),E("ARKRULE_SCOPE_EMPTY","arkrules","ArkRule appliesTo matched zero files","An ArkRule\u2019s appliesTo globs matched no governed files \u2014 the rule cannot observe what it claims to protect.","Fix appliesTo globs so they match governed files, or remove the rule. Enforced empty scope fails; advisory empty scope warns.",{oftenAdvisory:!0}),E("ARKRULE_HINT_BUDGET_EXHAUSTED","arkrules","Structural-hint budget exhausted","orchestration-only, thin-adapter, and writes-via-aggregate only evaluate files the hint loader preloaded. When eligible governed files exceed that budget (coverage.maxFiles, default 400 \u2014 there is no arkrules.hintBudget), those sensors never saw the rest of their scope. Enforced + unreviewed is not green. The finding names exact hinted/governed counts and per-sensor reviewed N/M of scope.","Raise coverage.maxFiles in ark.config.json (this cap also bounds structural-hint preload; --doctor names the coupling) so hinted/governed counts match, then re-run with --strict-config. An enforced hint sensor that cannot see its scope fails strict."),E("INVARIANT_UNCOVERED","arkrules","Invariant without coverage evidence","An ArkRules invariant is under contract but no covering test title or declared symbol evidence was found (or coverage is partial). Kind is never-had-tests (adopt residual) vs tests-disappeared (suite exists).","Add a test title or declared symbol covering the arkruleId, then preflight again. Treat never-had-tests as adopt residual; treat tests-disappeared as a regression. Missing test globs report partial \u2014 never fake green. When the message reports an exhausted file budget, raise coverage.maxFiles (or narrow coverage.testGlobs) in ark.config.json."),E("INVARIANT_COVERAGE_OUTSIDE_ROOTS","arkrules","Covering test outside the declared coverage roots","The only test naming this invariant sits outside coverage.coverageRoots \u2014 the places the project declares its runner executes. ArkGate matches declared text and never executes tests, so it cannot tell whether that file is ever run: coverage there is a test that exists, not a test that runs.","Move the test under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json. Advisory: it never fails strict, but promotion to enforced refuses on it.",{oftenAdvisory:!0}),E("ARKRUN_MISSING_ROOT","arkrun","No kernel factory in composition roots","The ArkRun extra is on but no createArkKernel / createStrictArkKernel / createArkKernelFromConfig / createStrictArkKernelFromConfig factory was found in arkRun.compositionRoots, so agents can skip the kernel while the write gate stays green.","Import createStrictArkKernel from arkgate/runtime (same npm package; @arkgate/runtime is deprecated) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision."),E("ARKRUN_KERNEL_IN_DOMAIN","arkrun","Domain-role layer imports the kernel","A Domain-role layer imports arkgate/runtime, @arkgate/runtime, or kernel types. Domain stays kernel-free; composition roots and adapters own the factory.","Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from arkgate/runtime (same npm package; @arkgate/runtime is deprecated), then preflight again. Never mechanical-safe."),E("ARKRUN_DIRECT_NEW","arkrun","Managed type constructed with new","A managed non-Domain file constructs an admitted type with new outside an ArkRun composition-root factory, skipping kernel resolve/registration.","Resolve the type from the kernel instead of constructing it with new, then preflight again. Never mechanical-safe \u2014 rewiring construction is a design decision."),E("ARKRUN_UNDECLARED_EMIT","arkrun","Emit name not in raises/sends","A publisher / publish / raise / send call-site literal is not listed in the file\u2019s raises or sends declaration.","Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment."),E("ARKRUN_UNDECLARED_HANDLE","arkrun","Handle name not in reactsTo","A subscribe / registerHandler call-site literal is not listed in the file\u2019s reactsTo declaration.","Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment."),E("ARKRUN_UNDECLARED_DEPEND","arkrun","Depend name not in uses","A resolve / resolveSingleton call-site literal is not listed in the file\u2019s uses declaration.","Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment."),E("ARKRUN_TRANSPORT_BYPASS","arkrun","Homemade broker or emitter import","A managed layer imports a closed broker/queue/emitter specifier (EventEmitter, queue clients, \u2026) instead of the ArkRun kernel transport.","Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe \u2014 homemade buses stay judgment."),E("ARKORDER_MISSING_PLANE","arkorder","No createOrderPlane in plane roots","The ArkOrder extra is on but no createOrderPlane factory was found in arkOrder.planeRoots, so agents can skip the pattern plane while the write gate stays green.","Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision."),E("ARKORDER_KERNEL_IN_DOMAIN","arkorder","Domain-role layer imports the order plane","A Domain-role layer imports arkgate/order. Domain stays plane-free; planeRoots own the factory.","Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe."),E("ARKORDER_GENERIC_UPDATE","arkorder","Generic update of \u03BE","A call to update/patch/set on the order plane rewrites the slow pattern. Haken slaving forbids generic \u03BE mutation.","Use release() for the first freeze of \u03BE. Later pattern change is proposeRelease then apply(ProposeResult). Never update/patch/set. Never mechanical-safe."),E("ARKORDER_TOO_MANY_PARAMS","arkorder","Too many slow keys","\u03BE has more keys than arkOrder.maxXiKeys. Haken requires a few slow modes, not a dump of microstate.","Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe."),E("ARKORDER_INGEST_WRITES_XI","arkorder","ingest assigned into \u03BE","An ingest() result is written into a Release or \u03BE store. ingest may absorb, escalate_up, or hold; it never mints a pattern.","Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe."),E("ARKORDER_XI_FIELD_WRITE","arkorder","Slow key written around the order plane","A managed-layer file imports a persistence driver and writes a declared arkOrder.xiKeys name. Field events absorb or escalate; they do not PATCH the slow pattern.","Keep invoices, seats, hours, and logs on ingest. Change the slow key with proposeRelease then apply(ProposeResult), then preflight again. Never mechanical-safe."),E("ARKORDER_INFORMATION_BUDGET","arkorder","Projection observes a forbidden kind","h(\u03BE) allowedKinds includes a kind listed in informationBudget.cannotObserve. A scale may not look at what it was told not to see.","Cut that kind from the projector or from cannotObserve, then preflight again. Never mechanical-safe."),E("ARKORDER_XI_TTL","arkorder","Slow key carries a freshness field","\u03BE named ttl/freshUntil/maxAge. Freshness belongs on \u03C3. A slow parameter that expires per transaction is not slow.","Move freshness onto \u03C3 (freshUntil) and keep \u03BE stable, then preflight again. Never mechanical-safe."),E("ARKORDER_STALE_SIGMA","arkorder","\u03C3 is stale","ingest ran after \u03C3.freshUntil (or sigmaMaxAgeMs). \u03BE does not TTL.","Call refreshSigma and ingest again, or proposeRelease then apply(ProposeResult) if the pattern changed. Never mechanical-safe."),E("ARKORDER_UNVALVED_RELEASE","arkorder","Unvalved second freeze of \u03BE","release() ran after a pattern was already frozen and the new \u03BE differs. First freeze is release(); later pattern change is proposeRelease then apply.","Change \u03BE with proposeRelease then apply(ProposeResult). release() is only the first freeze. Never mechanical-safe."),E("INVALID_CHANGE_PATH","preflight","Unsafe change path","A change set entry is not a safe, non-empty project-relative path (absolute, escape, empty, or NUL).","Use canonical project-relative paths only in the atomic change set, then preflight again."),E("DUPLICATE_CHANGE_PATH","preflight","Duplicate path in change set","The atomic change set lists more than one operation for the same path.","Collapse to one create/update/delete per path, then preflight again."),E("DELETE_TARGET_MISSING","preflight","Delete target missing","A delete operation targets a path that is not present in the supplied base tree.","Remove the delete, or include the file in the base tree facts, then preflight again."),E("CHANGE_SET_EMPTY","preflight","Empty change set","Atomic preflight was invoked with no create, update, or delete operations.","Provide at least one change operation, then preflight again."),E("FACTS_IDENTITY_MISMATCH","preflight","Base/candidate facts identity mismatch","Base and candidate resolved facts disagree on resolver, compiler, evidence requirements, or package identity \u2014 verdicts would not be comparable.","Regenerate both fact snapshots with the same resolver/compiler/evidence requirements, then preflight again."),E("CANDIDATE_DELETE_NOT_APPLIED","preflight","Candidate still contains deleted path","Facts claim a delete, but the candidate tree still includes the path.","Ensure the candidate facts apply the delete (path absent), then preflight again."),E("CANDIDATE_CHANGE_MISSING","preflight","Declared change missing from candidate","The change set declares a create/update whose path is missing from candidate facts.","Include the new content in the candidate facts (or drop the operation), then preflight again."),E("CANDIDATE_CONTENT_HASH_MISMATCH","preflight","Candidate content hash mismatch","The candidate file content hash does not match the hash expected for the declared change.","Rebuild candidate facts from the exact proposed content, then preflight again."),E("UNDECLARED_CANDIDATE_CHANGE","preflight","Undeclared candidate change","Candidate facts differ from base for a path that was not listed in the explicit change set.","Declare every path that changes in the atomic change set, then preflight again."),E("ATOMIC_PREFLIGHT_UNAVAILABLE","preflight","Atomic preflight unavailable","The host/MCP path could not run the atomic preflight engine (missing facts, incomplete setup, or unsupported mode).","Use resolved-candidate facts / ark_prepare_change with a complete batch, or fall back to ark-check on disk. Do not treat missing preflight as green."),E("DESIGN_SMELL_REGRESSION","preflight","Design smell regression on base-relative ratchet","Compared to the base ref, the candidate introduces a created-path domain-logic-in-ui file under --strict-merge, or introduces or worsens a blocking design-smell class under --fail-on-new-smells.","Move the new UI business rule out of the created file (or revert a --fail-on-new-smells regression), then re-run with the same base ref."),E("ANALYSIS_PARSE_INCOMPLETE","analysis","Parse incomplete","Governed source could not be fully parsed; evidence includes the TypeScript diagnostic (line + message). Incremental mid-edit parse is normal for agents. Contract exclude paths skip the write hook.","Finish the source or fix the reported syntax error, then re-run `npx arkgate-check`. The write hook does not deny solely on mid-edit parse. Partial never means pass."),E("LEXICAL_EVIDENCE_INCOMPLETE","analysis","Lexical evidence incomplete","Single-file validation cannot prove project module resolution. The write hook is already the verdict.","Re-run `npx arkgate-check --root . --config ark.config.json`, or treat the hook deny as final. Do not call ark_prepare_change from a hook deny."),E("ANALYSIS_COVERS_NO_FILES","analysis","Analysis covered no files","No file matched the contract include and layer patterns under the analyzed root, so the run had nothing to check. Every rule is vacuously satisfied on an empty set: a green here would read exactly like a green over a governed tree while certifying nothing. Usual causes are a --root that is not the tree the contract describes (including a contract found outside the requested root, whose directory is then adopted as the project root), include / exclude patterns that match nothing, or layer patterns written for a different layout.","Point --root at the tree the contract describes, or keep the contract inside that tree, or fix the include / exclude / layer patterns so they match real files \u2014 then re-run `npx arkgate-check --root . --config ark.config.json`. This is a refusal about ArkGate\u2019s own inputs, not a finding about your code; no baseline or policy acknowledgement can suppress it."),E("ANALYSIS_HOST_UNAVAILABLE","analysis","Analysis host unavailable","No usable TypeScript / analysis host was available for this invocation.","Install a supported TypeScript version visible to the project, then re-run. Unavailable analysis is fail-closed."),E("ADAPTER_NOT_ALLOWED_FOR_PORT","adapter","Adapter not allowed for port","Runtime/port wiring selected an adapter implementation that the architecture profile does not allow for that port.","Bind an allowed adapter for the port, or adjust the profile with an explicit policy decision \u2014 then re-run."),E("FORBIDDEN_PATTERN","snippet-policy","Forbidden regex pattern","Snippet content matched a project or profile forbiddenPatterns rule.","Remove or rewrite the matching code so the pattern no longer matches, then re-run the snippet gate."),E("FORBIDDEN_SUBSTRING","snippet-policy","Forbidden substring","Snippet content contained a forbidden substring from the AI gate options/profile.","Remove the forbidden substring, then re-run the snippet gate."),E("FORBIDDEN_IMPORT","snippet-policy","Forbidden import target","Snippet imported or required a module listed as forbidden for the active profile.","Import an allowed module or inject the dependency behind a port, then re-run."),E("POLICY_VIOLATION","snippet-policy","Policy engine violation","A registered Policy failed on the snippet or generated code under evaluation.","Adjust the code to satisfy the named policy, or change the policy only through an explicit contract decision."),E("EXTENSION_ERROR","snippet-policy","AI gate extension error","A registered AICodeGate extension threw while analyzing the snippet.","Fix or remove the failing extension; do not ignore extension failures as pass."),E("AST_ANALYZER_ERROR","snippet-policy","AST analyzer error","Built-in AST/symbol analysis failed (host error or unexpected analyzer exception).","Ensure TypeScript host and snippet are valid; re-run. If the analyzer crashes on valid input, file a bug with a minimal fixture."),E("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","config","Invalid dynamicImportAllowlist","dynamicImportAllowlist is present but not an array of file globs.","Set dynamicImportAllowlist to an array of project-relative globs (or omit it).",{oftenAdvisory:!0}),E("CONFIG_INVALID_SAFETY","config","Invalid safety object","The safety field is present but not an object.","Use a safety object with optional maxTsSuppressions, maxAnyCasts, allowInMemory, allowDisabledPeerIsolation.",{oftenAdvisory:!0}),E("CONFIG_INVALID_SAFETY_THRESHOLD","config","Invalid safety threshold","A safety threshold (maxTsSuppressions / maxAnyCasts) is not a non-negative integer.","Set each threshold to a non-negative integer.",{oftenAdvisory:!0}),E("CONFIG_NO_LAYERS","config","No layers configured","ark.config.json has no file layers, so import-boundary enforcement cannot classify files.","Declare at least one layer with name + patterns (or run ark start / a preset).",{oftenAdvisory:!0}),E("CONFIG_LAYER_WITHOUT_NAME","config","Layer missing name","A configured layer entry has no name.","Give every layer a unique non-empty name.",{oftenAdvisory:!0}),E("CONFIG_INVALID_FORBIDDEN_GLOBALS","config","Invalid forbiddenGlobals","A layer\u2019s forbiddenGlobals is not an array of strings; the entry is ignored.",'Use an array of strings (e.g. ["fetch", "Date.now"]).',{oftenAdvisory:!0}),E("CONFIG_LAYER_WITHOUT_PATTERNS","config","Layer without patterns","A named layer has no file patterns and will never classify files.","Add patterns globs that match the layer\u2019s source tree.",{oftenAdvisory:!0}),E("CONFIG_INVALID_LAYER_PATTERN","config","Invalid layer pattern","A layer pattern is not a valid glob / failed to compile.","Fix the pattern syntax for that layer.",{oftenAdvisory:!0}),E("CONFIG_LAYER_PATTERN_NO_MATCHES","config","Layer pattern matched no files","A layer pattern matched zero included files (often a typo or include mismatch). Reserved/allowEmpty houses do not emit this.","Adjust the pattern or include roots, or mark the layer reserved/allowEmpty if the glob is a future house.",{oftenAdvisory:!0}),E("CONFIG_DUPLICATE_LAYER","config","Duplicate layer name","The same layer name appears more than once in configuration.","Rename or merge duplicate layer entries.",{oftenAdvisory:!0}),E("CONFIG_RULE_UNKNOWN_FROM_LAYER","config","Rule unknown from layer","A dependency rule references a source layer name that is not declared.","Fix the rule\u2019s from field to a declared layer name.",{oftenAdvisory:!0}),E("CONFIG_RULE_UNKNOWN_TO_LAYER","config","Rule unknown to layer","A dependency rule references a target layer name that is not declared.","Fix the rule\u2019s to field to a declared layer name.",{oftenAdvisory:!0}),E("CONFIG_AMBIGUOUS_LAYERS","config","Ambiguous layer classification","Some files match multiple layers at equal specificity; classification falls back to declaration order.","Disambiguate overlapping patterns so each file has one clear layer owner.",{oftenAdvisory:!0}),E("CONFIG_UNCLASSIFIED_FILES","config","Unclassified included files","Included source files match no layer pattern; import rules will not enforce on them.","Extend layer patterns or narrow include so every governed file is classified.",{oftenAdvisory:!0}),E("LITERAL_PATH_DRIFT","drift","Literal path moved by a rename","A repo path written inside a string, a comment or a docstring no longer resolves, and the rename set says where it went. Nothing in the gate sees this class: `tsc` resolves imports, not strings, and ESLint does not either, so the rename compiles green and the reference lies afterwards. It appears in four forms \u2014 the tsconfig alias, a relative literal, a path written without the include-root prefix, and prose \u2014 and a hand sweep reliably covers one of them.","Apply the suggested replacement, or re-run `npx arkgate-check --path-drift --base-ref <ref> --write` to apply every writable anchored replacement at once. The rewrite is mechanical and one-directional: the destination comes from the rename, it must itself resolve and be path-shaped, and the token is rewritten in the form the author wrote it in. A destination that leaves the alias root of the literal is reported with the target only and must be rewritten by hand."),E("LITERAL_PATH_UNRESOLVED","drift","Literal path does not resolve","A literal that looks like a repo path does not resolve under this root, and no rename explains where it went. Unlike LITERAL_PATH_DRIFT this is a candidate, not a verdict: with nothing to anchor it, ArkGate cannot tell a dead reference from an illustrative path in a comment, an example in documentation, or a path belonging to another tree.","Read the candidate and decide: fix the path, or leave it. Advisory only \u2014 it never fails a run and is never rewritten by --write, because there is no destination to propose. Run `--path-drift --all` to list the sweep.",{oftenAdvisory:!0}),E("ARK_UNKNOWN","meta","Unknown diagnostic","A diagnostic lacked a stable ruleId/code; adapters may emit this fallback so agents never see an empty id.","Resolve the underlying finding without weakening ark.config.json, then run Ark again. Prefer fixing the producer to emit a catalogued ruleId.")]),mr=new Map(zt.map(e=>[e.ruleId,e])),Zl=Object.freeze(zt.map(e=>e.ruleId));function Ql(e){return typeof e=="string"&&e.length>0&&mr.has(e)}i(Ql,"isKnownDiagnosticCode");function ec(e){return typeof e!="string"||e.length===0?!1:mr.has(e)?!0:e.startsWith("ARKRULE_")}i(ec,"isCataloguedOrArkRuleFamily");function Wt(e){if(!(typeof e!="string"||e.length===0))return mr.get(e)}i(Wt,"getDiagnosticCatalogEntry");function uo(e){return`#${Wt(e)?.docsAnchor??e}`}i(uo,"diagnosticDocsFragment");function tc(e){return`${fr}${uo(e)}`}i(tc,"diagnosticDocsPath");function nc(){return{schemaVersion:"1.0",docsPath:fr,codes:zt}}i(nc,"serializeDiagnosticCatalog");function rc(e){return Wt(e)?.fix}i(rc,"catalogFixForRuleId");function sc(e){return Wt(e)?.why}i(sc,"catalogWhyForRuleId");var gr="1.0",po="https://unpkg.com/arkgate@4/schemas/ark.status-manifest.schema.json",fo=["full","subset","unavailable"],mo=["doctor-facts","report-snapshot","none"],qt={FACTS_UNAVAILABLE:"FACTS_UNAVAILABLE",FACTS_PARTIAL:"FACTS_PARTIAL",NO_SESSION_SNAPSHOT:"NO_SESSION_SNAPSHOT"},go=/^sha256:[a-f0-9]{64}$/;function yo(e){let t=e.expectation;if(t==null||t.expectedRoot===void 0&&t.expectedProjectId===void 0)return{status:"matched",authoritative:!!e.resolvedRoot};if(t&&typeof t!="object")return{status:"mismatch",authoritative:!1,code:"INVALID_PROJECT_EXPECTATION",message:"project must be an object containing expectedRoot and/or expectedProjectId."};let n=t.expectedRoot,r=t.expectedProjectId;if(n!==void 0&&(typeof n!="string"||n.trim()===""))return{status:"mismatch",authoritative:!1,code:"INVALID_PROJECT_EXPECTATION",message:"project.expectedRoot must be a non-empty absolute path."};if(r!==void 0&&(typeof r!="string"||!go.test(r)))return{status:"mismatch",authoritative:!1,code:"INVALID_PROJECT_EXPECTATION",message:"project.expectedProjectId must be a sha256:<64 lowercase hex> identity."};if(n===void 0&&r!==void 0)return e.projectId&&r!==e.projectId?{status:"mismatch",authoritative:!1,expectedProjectId:r,code:"PROJECT_ID_MISMATCH",message:`Expected project id ${r}, but this process is bound to ${e.projectId}.`}:{status:"unverified",authoritative:!1,expectedProjectId:r,message:"project.expectedProjectId matched or could not be compared, but expectedRoot is required for an authoritative workspace binding."};let s=e.expectedRootRelation??"unknown";return s==="outside"?{status:"mismatch",authoritative:!1,expectedRoot:n,expectedProjectId:r,code:"PROJECT_ROOT_MISMATCH",message:`Expected workspace ${n}, but this process is bound to ${e.resolvedRoot}.`}:s==="unknown"?{status:"unverified",authoritative:!1,expectedRoot:n,expectedProjectId:r,message:"Could not prove expectedRoot against the resolved project root (stale or incomplete path evidence)."}:s==="descendant"&&r===void 0?{status:"unverified",authoritative:!1,expectedRoot:n,message:`Expected workspace ${n} is inside this project, but an exact project root is required for the initial authoritative handshake.`}:r!==void 0&&e.projectId&&r!==e.projectId?{status:"mismatch",authoritative:!1,expectedRoot:n,expectedProjectId:r,code:"PROJECT_ID_MISMATCH",message:`Expected project id ${r}, but this process is bound to ${e.projectId}.`}:s==="exact"||s==="descendant"&&r&&r===e.projectId?{status:"matched",authoritative:!0,...n?{expectedRoot:n}:{},...r?{expectedProjectId:r}:{}}:{status:"unverified",authoritative:!1,expectedRoot:n,expectedProjectId:r,message:"Project expectation could not be fully verified."}}i(yo,"evaluateStatusBinding");function ho(e){if(e.writePathUnavailable===!0)return"unavailable";if(e.softWriteHost===!0)return"advisory";if(e.hardWriteActive===!0)return"hard";let t=typeof e.activeHost=="string"?e.activeHost.trim().toLowerCase():"";return!t||t==="unknown"?"unavailable":"advisory"}i(ho,"classifyStatusWritePath");function Ao(e,t){let n=t&&t!=="unknown"?t:"unknown-host";return e==="hard"?`Local write is hard for ${n} when the covered PreToolUse path is active; CI --strict-merge remains the merge backstop.`:e==="advisory"?`Local write is advisory for ${n}; hard merge boundary is a required status running arkgate-check --strict-merge (alias ark-check).`:"Write-path activation is unavailable or unverified for this invocation (no active host / incomplete evidence)."}i(Ao,"defaultHonestLabel");function Ro(e,t,n,r,s){return e.nextActionOverride?.id&&e.nextActionOverride.summary?{id:e.nextActionOverride.id,summary:e.nextActionOverride.summary}:t.status==="mismatch"?{id:"rebind-project-identity",summary:t.message||"Project expectation does not match this process \u2014 call ark_identity / ark status with the correct expectedRoot (and projectId for descendants)."}:t.status==="unverified"&&e.expectation?{id:"complete-identity-handshake",summary:t.message||"Supply project.expectedRoot at the exact project root (and expectedProjectId for descendants) for authoritative status."}:e.resolvedConfigPath?r.verdict==="fail"||(r.activeViolations??0)>0?{id:"fix-active-violations",summary:`Clear ${r.activeViolations??"active"} blocking architecture finding(s), then re-run ark-check (or ark-check --doctor).`}:r.verdict==="incomplete"?{id:"restore-complete-analysis",summary:"Last check was incomplete \u2014 restore TypeScript/analysis inputs and re-run ark-check."}:r.verdict==null&&r.at==null?{id:"run-ark-check",summary:"No last-check snapshot yet \u2014 run ark-check --report (or --doctor) to freeze session evidence."}:n.writePath==="unavailable"?{id:"install-write-path",summary:"Write path is unavailable \u2014 install agent gates for your host (ark start / --install-agent-gates) and keep required CI --strict-merge."}:n.writePath==="advisory"?{id:"keep-ci-merge-hard",summary:"Local write is advisory for this host \u2014 keep a required GitHub status on arkgate-check --strict-merge as the hard merge boundary."}:e.leftoverDesignWork===!0?{id:"map-leftover-design",summary:"Leftover design work remains. Map with /ark-explore, then apply one small refactor with /ark-autopilot. Green imports are not done."}:s.arkRulesLoaded&&(s.frozenResidual??0)>0?{id:"review-arkrules-residual",summary:"ArkRules residual remains frozen \u2014 review inventory debt without claiming a score."}:e.arkRun?.present===!0&&(e.arkRun.residual??0)>0?{id:"review-arkrun-residual",summary:"ArkRun residual remains \u2014 wire kernel usage or declarations through arkgate/runtime. Not a score."}:e.adopted==="required-merge"||e.adopted==="advisory-only-acked"?{id:"stay-enforced",summary:"Contract looks enforceable for this session \u2014 keep writing through the gate and re-check after structural edits."}:{id:"require-ci-merge-status",summary:'Make arkgate-check --strict-merge a required GitHub status, or write .ark/adoption-stance.json with stance: "advisory-only".'}:{id:"run-ark-start",summary:"No ark.config.json found \u2014 run ark start (preview) then ark start --apply."}}i(Ro,"resolveStatusNextAction");function oc(e){let t=typeof e.resolvedRoot=="string"&&e.resolvedRoot.length>0?e.resolvedRoot:".",n=typeof e.projectId=="string"&&go.test(e.projectId)?e.projectId:null,r=yo({resolvedRoot:t,projectId:n,expectation:e.expectation,expectedRootRelation:e.expectedRootRelation}),s=typeof e.activeHost=="string"?e.activeHost.trim().toLowerCase():"",o=s&&s!=="unknown"?s:s==="unknown"?"unknown":null,a=ho({hardWriteActive:e.hardWriteActive,softWriteHost:e.softWriteHost,writePathUnavailable:e.writePathUnavailable,activeHost:o}),l=typeof e.honestLabel=="string"&&e.honestLabel.trim().length>0?e.honestLabel.trim():Ao(a,o),c={at:typeof e.lastCheckAt=="string"?e.lastCheckAt:null,verdict:e.lastCheckVerdict==="pass"||e.lastCheckVerdict==="fail"||e.lastCheckVerdict==="incomplete"?e.lastCheckVerdict:null,activeViolations:ht(e.activeViolations),frozenResidual:ht(e.frozenResidual)},u={arkRulesLoaded:e.arkRulesLoaded===!0,inventoried:ht(e.rulesInventoried),underContract:ht(e.rulesUnderContract),frozenResidual:ht(e.rulesFrozenResidual)},f={writePath:a,host:o,honestLabel:l},y={projectId:n,resolvedRoot:t,resolvedConfigPath:typeof e.resolvedConfigPath=="string"&&e.resolvedConfigPath.length>0?e.resolvedConfigPath:null,binding:r.status,authoritative:r.authoritative,...r.code?{code:r.code}:{},...r.message?{message:r.message}:{}},g={schemaVersion:gr,arkgateVersion:typeof e.arkgateVersion=="string"&&e.arkgateVersion.length>0?e.arkgateVersion:"unknown",projectIdentity:y,activation:f,lastCheck:c,rules:u,nextAction:Ro(e,r,f,c,u)},p=Eo(e.improvementCompass);return p&&(g.improvementCompass=p),e.vsBase&&typeof e.vsBase.baseRef=="string"&&e.vsBase.baseRef.length>0&&(g.vsBase=e.vsBase),e.arkRun&&typeof e.arkRun=="object"&&(g.arkRun=pr(e.arkRun)),g}i(oc,"buildStatusManifest");var ko=new Set(fo),ac=new Set(mo);function yr(e){let t=ko.has(e.mode)?e.mode:"unavailable",n=e.factsSource!=null&&ac.has(e.factsSource)?e.factsSource:t==="unavailable"?"none":void 0,r=typeof e.contractHash=="string"&&e.contractHash.length>0?e.contractHash:void 0;if(t==="unavailable"){let a={schemaVersion:"1.0",notAScore:!0,mode:"unavailable",topResidual:[],reasonCode:typeof e.reasonCode=="string"&&e.reasonCode.length>0?e.reasonCode:qt.FACTS_UNAVAILABLE,reason:typeof e.reason=="string"&&e.reason.length>0?e.reason:"Improvement compass facts are unavailable \u2014 run ark-check --doctor for residual lenses. Status never invents green.",factsSource:n??"none"};return r&&(a.contractHash=r),a}let s=Array.isArray(e.topResidual)?e.topResidual.filter(a=>typeof a=="string"&&a.length>0).slice(0,15):[],o={schemaVersion:"1.0",notAScore:!0,mode:t,topResidual:s};return t==="subset"?(o.reasonCode=typeof e.reasonCode=="string"&&e.reasonCode.length>0?e.reasonCode:qt.FACTS_PARTIAL,o.reason=typeof e.reason=="string"&&e.reason.length>0?e.reason:"Status compass is a subset of doctor residual \u2014 incomplete session facts; run doctor for full."):typeof e.reasonCode=="string"&&e.reasonCode.length>0&&(o.reasonCode=e.reasonCode),typeof e.reason=="string"&&e.reason.length>0&&t==="full"&&(o.reason=e.reason),n&&(o.factsSource=n),r&&(o.contractHash=r),o}i(yr,"projectStatusImprovementCompass");function ic(e={}){return yr({mode:"unavailable",topResidual:[],reasonCode:e.reasonCode??qt.NO_SESSION_SNAPSHOT,reason:e.reason??"No session compass facts yet \u2014 run ark-check --doctor or --report for residual lenses. Status never invents green.",factsSource:"none",contractHash:e.contractHash})}i(ic,"unavailableStatusImprovementCompass");function Eo(e){if(e==null||typeof e!="object")return null;let t=e;if(t.notAScore!==!0||t.schemaVersion!=="1.0"||"score"in t||"valid"in t||"goal"in t)return null;let n;return typeof t.mode=="string"&&ko.has(t.mode)?n=t.mode:Array.isArray(t.topResidual)?n="subset":n="unavailable",yr({mode:n,topResidual:Array.isArray(t.topResidual)?t.topResidual:[],reasonCode:typeof t.reasonCode=="string"?t.reasonCode:null,reason:typeof t.reason=="string"?t.reason:null,factsSource:typeof t.factsSource=="string"?t.factsSource:null,contractHash:typeof t.contractHash=="string"?t.contractHash:null})}i(Eo,"normalizeStatusImprovementCompass");function lc(e,t){let n=Array.isArray(e)?e:[],r=new Set(Array.isArray(t)?t:[]);for(let s of n)if(!(typeof s!="string"||s.length===0)&&!r.has(s))return!1;return!0}i(lc,"statusCompassResidualIsSubsetOfDoctor");function ht(e){if(e==null)return null;let t=Number(e);return!Number.isFinite(t)||t<0?null:Math.floor(t)}i(ht,"numberOrNull");var cc={$schema:"https://json-schema.org/draft/2020-12/schema",$id:po,title:"ArkGate status manifest",description:"Unified session/project status snapshot for agents (identity, activation honesty, last check, rules counts, next action). Not a score.",type:"object",additionalProperties:!1,required:["schemaVersion","arkgateVersion","projectIdentity","activation","lastCheck","rules","nextAction"],properties:{schemaVersion:{const:gr},arkgateVersion:{type:"string",minLength:1},projectIdentity:{type:"object",additionalProperties:!1,required:["projectId","resolvedRoot","resolvedConfigPath","binding","authoritative"],properties:{projectId:{anyOf:[{type:"string",pattern:"^sha256:[a-f0-9]{64}$"},{type:"null"}]},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{anyOf:[{type:"string",minLength:1},{type:"null"}]},binding:{enum:["matched","unverified","mismatch"]},authoritative:{type:"boolean"},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},activation:{type:"object",additionalProperties:!1,required:["writePath","host","honestLabel"],properties:{writePath:{enum:["hard","advisory","unavailable"]},host:{anyOf:[{type:"string",minLength:1},{type:"null"}]},honestLabel:{type:"string",minLength:1}}},lastCheck:{type:"object",additionalProperties:!1,required:["at","verdict","activeViolations","frozenResidual"],properties:{at:{anyOf:[{type:"string",minLength:1},{type:"null"}]},verdict:{anyOf:[{enum:["pass","fail","incomplete"]},{type:"null"}]},activeViolations:{anyOf:[{type:"integer",minimum:0},{type:"null"}]},frozenResidual:{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}},rules:{type:"object",additionalProperties:!1,required:["arkRulesLoaded","inventoried","underContract","frozenResidual"],properties:{arkRulesLoaded:{type:"boolean"},inventoried:{anyOf:[{type:"integer",minimum:0},{type:"null"}]},underContract:{anyOf:[{type:"integer",minimum:0},{type:"null"}]},frozenResidual:{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}},nextAction:{type:"object",additionalProperties:!1,required:["id","summary"],properties:{id:{type:"string",minLength:1},summary:{type:"string",minLength:1}}},improvementCompass:{type:"object",description:"Thin improvement-compass residual ids with honesty mode (notAScore). full | subset | unavailable. Never a gate input; full lenses on doctor JSON. When full, residual ids \u2286 doctor residual for the same facts. unavailable never invents green residual.",additionalProperties:!1,required:["schemaVersion","notAScore","mode","topResidual"],properties:{schemaVersion:{const:"1.0"},notAScore:{const:!0},mode:{enum:["full","subset","unavailable"]},topResidual:{type:"array",items:{type:"string",minLength:1},maxItems:15},reasonCode:{type:"string",minLength:1},reason:{type:"string",minLength:1},factsSource:{enum:["doctor-facts","report-snapshot","none"]},contractHash:{type:"string",minLength:1}}},vsBase:{type:"object",description:"Checkout vs a git base ref: pin, contract identity, baseline grow. Advisory honesty only \u2014 never a gate input.",additionalProperties:!1,required:["baseRef","line","pinLocal","pinBase","contractEqual","baselineGrew"],properties:{baseRef:{type:"string",minLength:1},line:{type:"string",minLength:1},pinLocal:{anyOf:[{type:"string",minLength:1},{type:"null"}]},pinBase:{anyOf:[{type:"string",minLength:1},{type:"null"}]},contractEqual:{type:"boolean"},baselineGrew:{type:"boolean"}}},arkRun:{type:"object",description:"ArkRun extra residual (notAScore). present/mode from config; residual is a finding-id count (null = unknown, not green). extraMergeTeeth is honesty, never a score.",additionalProperties:!1,required:["notAScore","present","mode","extraMergeTeeth","residual"],properties:{notAScore:{const:!0},present:{type:"boolean"},mode:{anyOf:[{enum:["advisory","enforced"]},{type:"null"}]},extraMergeTeeth:{type:"boolean"},residual:{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}}}};var Yt="1.0",Xt=["soc","cohesion","coupling","srp","dip","ocp","encapsulation","modularity","scalability","resilience","security","maintainability","testability","domain","stack"],Jt=5,Pe=["scalability","resilience","security"],ze=new Set(Pe),hr={soc:10,coupling:20,dip:30,domain:40,srp:50,cohesion:60,encapsulation:70,modularity:80,testability:90,maintainability:100,ocp:110,stack:120,scalability:200,resilience:200,security:200},Ar={soc:"Separation of concerns",cohesion:"High cohesion",coupling:"Low coupling",srp:"Single responsibility (architecture)",dip:"Dependency inversion",ocp:"Open/closed",encapsulation:"Encapsulation",modularity:"Modularity",scalability:"Scalability / performance",resilience:"Resilience / fault tolerance",security:"Security by design",maintainability:"Maintainability",testability:"Testability",domain:"Domain alignment",stack:"Stack-specific practices"},Rr={scalability:"ArkGate does not measure performance or horizontal scale. Use load tests and APM outside Ark.",resilience:"ArkGate does not measure app resilience or chaos readiness. Structural boundaries and optional experimental runtime are not a resilience score.",security:"ArkGate does not run SAST or app-security tooling. Structural least-privilege of effects is partial only \u2014 not a security rating."};function kr(e){return Ar[e]??e}i(kr,"improvementCompassHumanLabel");function Er(e){let t=e.id??e.smellId??"";return typeof t=="string"?t.trim():""}i(Er,"smellIdOf");function Ir(e){let t=e.ruleId??e.code??"";return typeof t=="string"?t.trim():""}i(Ir,"violationRuleId");function V(e,t,n,r){if(!n||e.evidence.some(o=>o.source===t&&o.ref===n))return;let s={source:t,ref:n};r&&r.trim()&&(s.detail=r.trim().slice(0,240)),e.evidence.push(s)}i(V,"pushEvidence");function ee(e,t,n){ze.has(e.id)||(e.status="residual",e.summary=t,n&&(e.nextAction=n))}i(ee,"markResidual");function Io(e){switch(e){case"soc":return"No separation-of-concerns residual detected from current sensors.";case"cohesion":return"No cohesion residual (god-module / physical cohesion) from current sensors.";case"coupling":return"No coupling residual (import edges, cycles, peer isolation) from current sensors.";case"srp":return"No single-responsibility residual from current sensors.";case"dip":return"No dependency-inversion residual (pure / capability / forbidden walls) from current sensors.";case"ocp":return"Open/closed is not strongly instrumented \u2014 no switch-chain sensor.";case"encapsulation":return"No encapsulation residual from ArkRules structure sensors.";case"modularity":return"No modularity / placement residual from current sensors.";case"maintainability":return"No maintainability residual (design-weak / baseline honesty) from current sensors.";case"testability":return"No testability residual (impure domain / capability walls) from current sensors.";case"domain":return"No domain-alignment residual from current sensors.";case"stack":return"Stack practices are only partially instrumented (TypeScript / host / Ark idioms).";default:return`${Ar[e]} \u2014 no residual from current sensors.`}}i(Io,"defaultOkSummary");function So(){return Xt.map(e=>ze.has(e)?{id:e,status:"out-of-scope",summary:Rr[e],evidence:[],nextAction:{kind:"docs",ref:"docs/use.md#improvement-compass",summary:"Out of scope for ArkGate \u2014 use dedicated tooling outside the gate."}}:e==="ocp"?{id:e,status:"not-instrumented",summary:Io(e),evidence:[]}:{id:e,status:"ok",summary:Io(e),evidence:[]})}i(So,"createInitialImprovementCompassLenses");function dc(e,t){for(let n of t){let r=Er(n);if(!r)continue;let s=n.outcome||n.message||void 0,a=(Array.isArray(n.evidence)?n.evidence:[])[0],l=i((f,y,g)=>{let p=e.get(f);!p||ze.has(f)||(V(p,"designSmells",r,s),a&&V(p,"designSmells",a,r),ee(p,y,g))},"attach"),c={kind:"skill",ref:"/ark-explore",summary:"Map Shape residual (shape-focus), then apply one extraction pilot with /ark-autopilot."},u={kind:"skill",ref:"/ark-autopilot",summary:"Inject a port/adapter for I/O; keep domain pure."};switch(r){case"domain-logic-in-ui":l("soc","Business rules still mix with UI or presentation surfaces.",c),l("domain","Domain logic lives outside Domain \u2014 align rules with Domain ownership.",c);break;case"facade-sql-in-routes":l("soc","Routes/controllers own SQL or ORM access \u2014 concerns are mixed.",c),l("dip","Transport depends on concrete persistence instead of a port.",u);break;case"io-under-application":l("soc","Application/business code reaches I/O directly \u2014 separation is weak.",c),l("dip","I/O is not inverted behind ports/adapters.",u),l("testability","Direct I/O under application code hurts pure unit testing.",u);break;case"handler-in-persistence":l("soc","HTTP/transport handlers live under persistence folders.",c);break;case"god-module":l("cohesion","Large multi-responsibility modules reduce cohesion.",c),l("srp","God modules own too many responsibilities \u2014 split by concern (one pilot).",{kind:"skill",ref:"/ark-autopilot",summary:"One Shape pilot this turn \u2014 never multi-pilot batch."});break;case"mixed-pattern-cluster":l("modularity","Multiple layout styles coexist \u2014 placement is unclear for the next AI turn.",{kind:"skill",ref:"/ark-explore",summary:"Pick a golden pattern and migrate one pilot cluster on touch."}),l("cohesion","Mixed layout styles scatter the same concern across patterns.",c);break;case"soft-contract":l("maintainability","Soft contract walls (layers without deny rules) hide maintainability debt.",{kind:"skill",ref:"/ark-adopt",summary:"Add real layer rules so the AI has hard walls."}),l("coupling","Layers with files but almost no deny rules allow free peer coupling.",{kind:"skill",ref:"/ark-adopt",summary:"Tighten inter-layer allows/denies without weakening enforcement."});break;default:l("maintainability","Design residual remains under an unrecognized smell id \u2014 review evidence.",c);break}}}i(dc,"mapDesignSmells");function uc(e){return e.failsStrict===!1||e.typeOnly===!0}i(uc,"isTypeOnlyPlacementDebt");function pc(e,t){for(let n of t){let r=Ir(n);if(!r)continue;let s=n.message,o=r.toUpperCase(),a=i((c,u,f)=>{let y=e.get(c);!y||ze.has(c)||(V(y,"violations",r,s),n.file&&V(y,"violations",n.file,r),ee(y,u,f))},"attach");if(uc(n)){a("modularity","Type-only placement debt remains \u2014 prefer SharedTypes / owning layer (not runtime coupling).",{kind:"skill",ref:"/ark-place",summary:"Place shared types in a layer both sides may import; type-only debt is not a value edge."});continue}let l={kind:"skill",ref:"/ark-autopilot",summary:"Clear the active edge residual, then re-doctor."};if(o==="LAYER_IMPORT_VIOLATION"||o.includes("LAYER_IMPORT")||o==="DYNAMIC_IMPORT_VIOLATION"){a("coupling","Import graph edges violate the layer contract.",l);continue}if(o.includes("CYCLE")||o==="CIRCULAR_DEPENDENCY"){a("coupling","Import cycles couple modules tightly.",l);continue}if(o.includes("PEER_ISOLATION")||o==="PEER_ISOLATION_VIOLATION"){a("coupling","Peer isolation residual \u2014 slices import each other freely.",{kind:"skill",ref:"/ark-autopilot",summary:"Peer isolation fixes are judgment-class \u2014 one cluster at a time."});continue}if(o==="FORBIDDEN_GLOBAL"||o.startsWith("FORBIDDEN_")){a("dip","Forbidden globals / effect surfaces break dependency inversion.",{kind:"skill",ref:"/ark-autopilot",summary:"Inject a port instead of the forbidden global."}),a("testability","Forbidden ambient effects reduce pure-domain testability.",{kind:"skill",ref:"/ark-autopilot",summary:"Replace ambient effects with injectable ports."});continue}if(o==="CAPABILITY_VIOLATION"){a("dip","Denied capability use \u2014 invert through an allowed adapter/port.",{kind:"skill",ref:"/ark-autopilot",summary:"Capability walls require port injection (judgment, not mechanical-safe)."}),a("testability","Capability violations couple domain code to I/O \u2014 harder to unit-test.",{kind:"skill",ref:"/ark-autopilot",summary:"Keep pure layers free of denied capabilities."});continue}if(o.startsWith("ARKRULE_")||o==="INVARIANT_UNCOVERED"){a("encapsulation","ArkRules structure / invariant residual inside a layer.",{kind:"skill",ref:"/ark-autopilot",summary:"Label [ArkRules]; structure fixes are judgment \u2014 never invent mechanical-safe."}),a("domain","Intra-layer domain structure or invariant coverage residual.",{kind:"skill",ref:"/ark-explore",summary:"Inventory candidates \u2192 one ArkRules pilot with coverage evidence."});continue}}}i(pc,"mapViolations");function fc(e,t){let n=Number(t.cycleCount)||0;if(n>0){let p=e.get("coupling");V(p,"cycles",`count:${n}`),ee(p,"Import cycles couple modules tightly.",{kind:"skill",ref:"/ark-autopilot",summary:"Break cycles with a judgment extraction \u2014 one pilot."})}let r=typeof t.peerIsolationCount=="boolean"?t.peerIsolationCount?1:0:Number(t.peerIsolationCount)||0;if(r>0){let p=e.get("coupling");V(p,"peerIsolation",`count:${r}`),ee(p,"Peer isolation residual remains.",{kind:"skill",ref:"/ark-autopilot",summary:"Peer isolation is judgment-class residual."})}let s=Number(t.physicalCohesionFindingCount)||0;if(s>0){let p=e.get("cohesion");V(p,"physicalCohesion",`findings:${s}`),ee(p,"Physical cohesion residual \u2014 mirrored concept clusters across anchors.",{kind:"skill",ref:"/ark-explore",summary:"Review reshape pilot; one decision-aware pilot at a time."});let m=e.get("srp");V(m,"physicalCohesion",`findings:${s}`),ee(m,"Mirrored clusters suggest split-by-concern residual (architecture SRP).",{kind:"skill",ref:"/ark-autopilot",summary:"One reshape/extraction pilot this turn."})}let o=Number(t.pureOrCapabilityResidual)||0,a=Number(t.forbiddenGlobalResidual)||0;if(o>0||a>0){let p=e.get("dip");o>0&&V(p,"capability",`residual:${o}`),a>0&&V(p,"forbiddenGlobals",`residual:${a}`),ee(p,"Pure / capability / forbidden residual weakens dependency inversion.",{kind:"skill",ref:"/ark-autopilot",summary:"Inject ports; keep pure layers free of effects."});let m=e.get("testability");o>0&&V(m,"capability",`residual:${o}`),a>0&&V(m,"forbiddenGlobals",`residual:${a}`),ee(m,"Impure domain or capability residual reduces testability.",{kind:"skill",ref:"/ark-autopilot",summary:"Prefer ports over concrete I/O in pure/domain modules."})}let l=Number(t.arkRulesStructureResidual)||0;if(l>0){let p=e.get("encapsulation");V(p,"arkRules",`structureResidual:${l}`),ee(p,"ArkRules structure residual \u2014 encapsulation inside the layer.",{kind:"skill",ref:"/ark-autopilot",summary:"Fix structure sensors under [ArkRules] without inventing mechanical-safe."});let m=e.get("domain");V(m,"arkRules",`structureResidual:${l}`),ee(m,"ArkRules residual may mean domain shape is not yet under contract.",{kind:"skill",ref:"/ark-explore",summary:"Map inventory candidates; one pilot rule at a time."})}else t.arkRulesLoaded===!1||t.arkRulesLoaded==null;if(t.designWeak===!0){let p=e.get("maintainability");V(p,"designFitness","design-weak"),ee(p,"Design-weak: checked edges may be clean, but design residual remains \u2014 not finished.",{kind:"skill",ref:"/ark-explore",summary:"Shape door: explore shape-focus \u2192 dual-plan B \u2192 one /ark-autopilot pilot."})}if(t.dirtyBaselineRisk===!0||(Number(t.baselineStale)||0)>0){let p=e.get("maintainability");t.dirtyBaselineRisk===!0&&V(p,"baseline","dirty-freeze-risk"),(Number(t.baselineStale)||0)>0&&V(p,"baseline",`stale:${t.baselineStale}`),ee(p,"Baseline honesty residual \u2014 frozen debt or stale keys need review.",{kind:"command",ref:"ark-check --doctor",summary:"Review baseline freeze honesty; do not freeze new wrong debt."})}let c=Number(t.frozenResidual)||0;if(t.baselineExists===!0&&c>=10&&e.get("maintainability").status!=="residual"){let p=e.get("maintainability");V(p,"baseline",`frozen:${c}`),ee(p,"Substantial frozen residual remains under the baseline \u2014 review debt honestly.",{kind:"command",ref:"ark-check --doctor",summary:"Review freezes; do not freeze new wrong debt to clear residual."})}let u=Number(t.ungovernedDirCount)||0,f=Number(t.emptyLayerCount)||0;if(u>0||f>0){let p=e.get("modularity");u>0&&V(p,"coverage",`ungovernedDirs:${u}`),f>0&&V(p,"coverage",`emptyLayers:${f}`),ee(p,"Placement / modularity residual \u2014 ungoverned dirs or empty layer globs.",{kind:"skill",ref:"/ark-adopt",summary:"Classify ungoverned paths; fix empty layer patterns."})}if(t.designWeak===!0&&t.goldenPatternPresent===!1){let p=e.get("modularity");V(p,"goldenPattern","absent"),ee(p,"Design-weak without a golden pattern \u2014 new code lacks a placement norm for the AI.",{kind:"skill",ref:"/ark-place",summary:"Record an advisory golden pattern for new code (does not clear design-weak)."})}let y=e.get("stack");(t.stackKind??null)==="typescript"?y.status==="ok"&&(y.summary="Stack practices are partially instrumented for TypeScript / host / Ark idioms only \u2014 not a full framework checklist."):(y.status="not-instrumented",y.summary="Stack-specific best practices outside TypeScript/host/Ark idioms are not instrumented.",y.evidence=[],y.nextAction={kind:"docs",ref:"docs/use.md#improvement-compass",summary:"Ark does not score non-TS stack idioms."})}i(fc,"mapCountsAndFlags");function bo(e,t){if(Array.isArray(t.designSmells)&&t.designSmells.length>0){let n=[...t.designSmells].sort((r,s)=>Er(r).localeCompare(Er(s)));dc(e,n)}if(Array.isArray(t.violations)&&t.violations.length>0){let n=[...t.violations].sort((r,s)=>{let o=Ir(r).localeCompare(Ir(s));return o!==0?o:String(r.file??"").localeCompare(String(s.file??""))});pc(e,n)}fc(e,t)}i(bo,"projectImprovementCompassFacts");function vo(e){for(let t of Pe){let n=e.get(t);n.status="out-of-scope",n.summary=Rr[t],n.evidence=[],n.nextAction={kind:"docs",ref:"docs/use.md#improvement-compass",summary:"Out of scope for ArkGate \u2014 use dedicated tooling outside the gate."}}}i(vo,"lockImprovementCompassOutOfScope");function Co(e){for(let t of e)t.evidence.sort((n,r)=>{let s=n.source.localeCompare(r.source);return s!==0?s:n.ref.localeCompare(r.ref)})}i(Co,"sortImprovementCompassEvidence");function _o(e){return e.filter(n=>n.status==="residual"&&!ze.has(n.id)).slice().sort((n,r)=>{let s=hr[n.id]??150,o=hr[r.id]??150;return s!==o?s-o:n.id.localeCompare(r.id)}).slice(0,5).map(n=>n.id)}i(_o,"finalizeImprovementCompassTopResidual");function mc(e={}){let t=So(),n=new Map(t.map(s=>[s.id,s]));bo(n,e),vo(n),Co(t);let r=_o(t);return{schemaVersion:"1.0",notAScore:!0,lenses:t.map(s=>{let o={id:s.id,status:s.status,summary:s.summary,evidence:s.evidence.map(a=>({...a}))};return s.nextAction&&(o.nextAction={...s.nextAction}),o}),topResidual:r}}i(mc,"buildImprovementCompass");function Oo(e){return e.topResidual.map(t=>kr(t))}i(Oo,"formatImprovementCompassResidualLabels");function xo(e){for(let t of e.topResidual){let n=e.lenses.find(r=>r.id===t);if(n?.nextAction)return{...n.nextAction}}return null}i(xo,"primaryImprovementCompassNextAction");function gc(e){let t=Oo(e),n=Pe.map(o=>kr(o)),r=xo(e),s=[];return t.length>0?s.push(`Residual: ${t.join(" \xB7 ")}`):s.push("Residual: none on instrumented lenses (not a score \u2014 green edges \u2260 finished design)."),s.push(`Out of scope (honest): ${n.join(" \xB7 ")}`),r&&s.push(`Next: ${r.ref} \u2014 ${r.summary}`),s}i(gc,"formatImprovementCompassDoctorLines");var yc="1.0",hc="<!-- arkgate:agent-projection:begin",To="<!-- arkgate:agent-projection:end -->",No="This projection is **non-authoritative**. Enforcement is `ark-check` / host write hooks / required CI (`--strict-merge`), not AGENTS.md, skills, or this block.",vr=Object.freeze(["ark-check","host-write-hooks","ci-strict-merge"]),Ac=Object.freeze(["LAYER_IMPORT_VIOLATION","LAYER_INTENT_REFERENCE_VIOLATION","CIRCULAR_DEPENDENCY","CAPABILITY_VIOLATION","RAW_EVENT_PUBLISH","ARKRULE_STRUCTURE","ATOMIC_PREFLIGHT_UNAVAILABLE","ANALYSIS_PARSE_INCOMPLETE","ARK_UNKNOWN"]),Cr=/<!--\s*arkgate:agent-projection:begin\b([^>]*)-->/i,Lo=/<!--\s*arkgate:agent-projection:end\s*-->/i,Rc=/\barkgateVersion=([A-Za-z0-9._+-]+)/i,kc=/\bschema=([A-Za-z0-9._+-]+)/i;function Zt(e){let t=String(e??"").replace(/\r\n/g,`
14
+ `),n=2166136261;for(let r=0;r<t.length;r+=1)n^=t.charCodeAt(r),n=Math.imul(n,16777619);return`fnv1a-${(n>>>0).toString(16).padStart(8,"0")}`}i(Zt,"agentProjectionContentIdentity");function Qt(e){return String(e??"").replace(/\r\n/g,`
15
+ `)}i(Qt,"normalizeNewlines");function We(e){let t=Qt(e);return t.endsWith(`
19
16
  `)?t:`${t}
20
- `}i(qe,"ensureTrailingNewline");function Zt(e){return typeof e!="string"||e.trim().length===0?"unknown":e.trim().replace(/[>\s]/g,"")}i(Zt,"safeVersion");function fo(e){return e==="compact"?"compact":"full"}i(fo,"resolveProfile");function mo(e){let t=Zt(e.arkgateVersion);return`<!-- arkgate:agent-projection:begin schema=${typeof e.schemaVersion=="string"&&e.schemaVersion.trim()?e.schemaVersion.trim():"1.0"} arkgateVersion=${t} nonAuthoritative=true -->`}i(mo,"buildAgentProjectionBeginMarker");function pr(e){return!Array.isArray(e)||e.length===0?"_No project layers loaded \u2014 read `ark.config.json` or run `ark start` / `ark_manifest`._":`| Layer | Patterns | Intent prefixes |
17
+ `}i(We,"ensureTrailingNewline");function en(e){return typeof e!="string"||e.trim().length===0?"unknown":e.trim().replace(/[>\s]/g,"")}i(en,"safeVersion");function Po(e){return e==="compact"?"compact":"full"}i(Po,"resolveProfile");function wo(e){let t=en(e.arkgateVersion);return`<!-- arkgate:agent-projection:begin schema=${typeof e.schemaVersion=="string"&&e.schemaVersion.trim()?e.schemaVersion.trim():"1.0"} arkgateVersion=${t} nonAuthoritative=true -->`}i(wo,"buildAgentProjectionBeginMarker");function Sr(e){return!Array.isArray(e)||e.length===0?"_No project layers loaded \u2014 read `ark.config.json` or run `ark start` / `ark_manifest`._":`| Layer | Patterns | Intent prefixes |
21
18
  |-------|----------|-----------------|
22
19
  ${e.map(n=>{let r=n.name?.trim()||"Unknown",s=n.patterns??[],o=n.intentPrefixes??[],a=s.map(c=>`\`${c}\``).join(", ")||"\u2014",l=o.map(c=>`\`${c}\``).join(", ")||"\u2014";return`| ${r} | ${a} | ${l} |`}).join(`
23
- `)}`}i(pr,"formatAgentProjectionLayers");function go(e,t){let n=t.trim()||"docs/diagnostics.md";return!Array.isArray(e)||e.length===0?`Full public codes: \`${n}\` (and package \`DIAGNOSTIC_CATALOG\`).`:`${e.filter(s=>s&&typeof s.ruleId=="string"&&s.ruleId.length>0).map(s=>{let o=typeof s.title=="string"&&s.title.trim()?s.title.trim():s.ruleId;return`- \`${s.ruleId}\` \u2014 ${o}`}).join(`
20
+ `)}`}i(Sr,"formatAgentProjectionLayers");function Do(e,t){let n=t.trim()||"docs/diagnostics.md";return!Array.isArray(e)||e.length===0?`Full public codes: \`${n}\` (and package \`DIAGNOSTIC_CATALOG\`).`:`${e.filter(s=>s&&typeof s.ruleId=="string"&&s.ruleId.length>0).map(s=>{let o=typeof s.title=="string"&&s.title.trim()?s.title.trim():s.ruleId;return`- \`${s.ruleId}\` \u2014 ${o}`}).join(`
24
21
  `)}
25
22
 
26
- Full catalog: \`${n}\` (\`#RULE_ID\` anchors).`}i(go,"formatAgentProjectionCatalogShortList");function yr(e){let t=Zt(e.arkgateVersion),n=fo(e.profile),r=typeof e.checkCommand=="string"&&e.checkCommand.trim()?e.checkCommand.trim():"ark-check --strict-config",s=typeof e.diagnosticsDocsPath=="string"&&e.diagnosticsDocsPath.trim()?e.diagnosticsDocsPath.trim():"docs/diagnostics.md",o=typeof e.host=="string"?e.host.trim().toLowerCase():"",a=o&&o!=="unknown"?o:null,l=Array.isArray(e.layers)?e.layers:[],c=Array.isArray(e.catalogShortList)?e.catalogShortList:[],u=["## ArkGate agent contract projection","",uo,"",`- **arkgateVersion:** \`${t}\` (must match the installed package; regenerate with \`ark agents-md --write\` after upgrade)`,"- **projectionSchema:** `1.0`",`- **profile:** \`${n}\`${a?` \xB7 **host:** \`${a}\``:""}`,`- **after edits:** \`${r}\``,""];return n==="compact"?u.push("### Primary path","","1. Run doctor (`ark-check --doctor`) \u2014 what is wrong and what to do first. Prefer the project-local CLI; do not wait on MCP \u201Cstill connecting\u201D.","2. Name leftover work in plain language; never \u201Cdone\u201D on green imports alone while leftover design work remains.","3. Identity handshake is optional when the CLI already resolved the project root. Call `ark_identity` only when using MCP evidence.","4. Read the rules file with `ark_manifest` (same expectation) or the local `ark.config.json`. `ark://manifest` is compatibility-only / unverified.","5. Place files inside configured layers; validate; run the check command above on violations \u2014 fix the import, do not weaken the rules file.","6. Single door: illegal imports \u2192 fix; leftover design work \u2192 map then one small refactor with user OK.","","### Layers (summary)","",pr(l),""):u.push("### Contract layers","",pr(l),"","When creating a **new** kind of code that no layer covers, update `ark.config.json` first (`/ark-adopt`), then place the file.","","### Diagnostic codes (short list)","",go(c,s),"","### Session truth","","- Machine snapshot: `ark status --json` (or MCP `ark_status`) \u2014 identity, activation honesty, last check, residual counts. **Not a score.**","- Authoritative contract: local `ark.config.json` / CLI, or `ark_manifest` after a matched `ark_identity` handshake. Identity is optional when CLI already resolved the root.","- Host docs: the same projection schema is merged into `AGENTS.md` and `CLAUDE.md` (`ark agents-md --write`).",""),u.push("### Enforcement surfaces (authoritative)","",mr.map(m=>`- \`${m}\``).join(`
23
+ Full catalog: \`${n}\` (\`#RULE_ID\` anchors).`}i(Do,"formatAgentProjectionCatalogShortList");function _r(e){let t=en(e.arkgateVersion),n=Po(e.profile),r=typeof e.checkCommand=="string"&&e.checkCommand.trim()?e.checkCommand.trim():"ark-check --strict-config",s=typeof e.diagnosticsDocsPath=="string"&&e.diagnosticsDocsPath.trim()?e.diagnosticsDocsPath.trim():"docs/diagnostics.md",o=typeof e.host=="string"?e.host.trim().toLowerCase():"",a=o&&o!=="unknown"?o:null,l=Array.isArray(e.layers)?e.layers:[],c=Array.isArray(e.catalogShortList)?e.catalogShortList:[],u=["## ArkGate agent contract projection","",No,"",`- **arkgateVersion:** \`${t}\` (must match the installed package; regenerate with \`ark agents-md --write\` after upgrade)`,"- **projectionSchema:** `1.0`",`- **profile:** \`${n}\`${a?` \xB7 **host:** \`${a}\``:""}`,`- **after edits:** \`${r}\``,""];return n==="compact"?u.push("### Primary path","","1. Run doctor (`ark-check --doctor`) \u2014 what is wrong and what to do first. Prefer the project-local CLI; do not wait on MCP \u201Cstill connecting\u201D.","2. Name leftover work in plain language; never \u201Cdone\u201D on green imports alone while leftover design work remains.","3. Identity handshake is optional when the CLI already resolved the project root. Call `ark_identity` only when using MCP evidence.","4. Read the rules file with `ark_manifest` (same expectation) or the local `ark.config.json`. `ark://manifest` is compatibility-only / unverified.","5. Place files inside configured layers; validate; run the check command above on violations \u2014 fix the import, do not weaken the rules file.","6. Single door: illegal imports \u2192 fix; leftover design work \u2192 map then one small refactor with user OK.","","### Layers (summary)","",Sr(l),""):u.push("### Contract layers","",Sr(l),"","When creating a **new** kind of code that no layer covers, update `ark.config.json` first (`/ark-adopt`), then place the file.","","### Diagnostic codes (short list)","",Do(c,s),"","### Session truth","","- Machine snapshot: `ark status --json` (or MCP `ark_status`) \u2014 identity, activation honesty, last check, residual counts. **Not a score.**","- Authoritative contract: local `ark.config.json` / CLI, or `ark_manifest` after a matched `ark_identity` handshake. Identity is optional when CLI already resolved the root.","- Host docs: the same projection schema is merged into `AGENTS.md` and `CLAUDE.md` (`ark agents-md --write`).",""),u.push("### Enforcement surfaces (authoritative)","",vr.map(f=>`- \`${f}\``).join(`
27
24
  `),""),u.join(`
28
25
  `).replace(/\n{3,}/g,`
29
26
 
30
27
  `).trimEnd()+`
31
- `}i(yr,"buildAgentProjectionBody");function Vl(e){let t=yr(e);return`${mo({arkgateVersion:e.arkgateVersion,schemaVersion:"1.0"})}
32
- ${t}${co}
33
- `}i(Vl,"buildAgentProjectionBlock");function Ul(e){let t=yr(e),n=Array.isArray(e.layers)?e.layers:[],r=Array.isArray(e.catalogShortList)?e.catalogShortList:[];return{schemaVersion:"1.0",arkgateVersion:Zt(e.arkgateVersion),nonAuthoritative:!0,enforcementSurfaces:[...mr],contentIdentity:Jt(t),layerCount:n.length,catalogCodeCount:r.filter(s=>s?.ruleId).length,profile:fo(e.profile)}}i(Ul,"buildAgentProjectionMeta");function fr(e){let t=Xt(e??""),n=gr.exec(t);if(!n)return{block:null,body:null,before:t,after:"",beginAttrs:null};let r=n.index,s=r+n[0].length,o=t.slice(s),a=po.exec(o);if(!a)return{block:null,body:null,before:t,after:"",beginAttrs:null};let l=a.index,c=l+a[0].length,u=o.slice(0,l);u.startsWith(`
34
- `)&&(u=u.slice(1));let m=t.slice(r,s+c),y=o.slice(c);return{block:m,body:u,before:t.slice(0,r),after:y,beginAttrs:n[1]??""}}i(fr,"extractAgentProjectionBlock");function yo(e){let t=String(e??""),r=gr.exec(t)?.[1]??t,s=Hl.exec(r),o=jl.exec(r),a=/\bnonAuthoritative\s*=\s*true\b/i.test(r);return{arkgateVersion:s?.[1]??null,schemaVersion:o?.[1]??null,nonAuthoritative:a}}i(yo,"parseAgentProjectionStamp");function Kl(e,t){let n=yo(e).arkgateVersion;return n?n===Zt(t):!1}i(Kl,"projectionMatchesPackageVersion");function Gl(e){return String(e??"").includes("non-authoritative")}i(Gl,"projectionHasNonEnforcementLabel");function Bl(e,t){let n=qe(Xt(t)),s=fr(n).body??n.replace(gr,"").replace(po,"").trim()+`
35
- `,o=Jt(s);if(e==null||!String(e).trim())return{content:qe(`# Ark Enforcement
28
+ `}i(_r,"buildAgentProjectionBody");function Ec(e){let t=_r(e);return`${wo({arkgateVersion:e.arkgateVersion,schemaVersion:"1.0"})}
29
+ ${t}${To}
30
+ `}i(Ec,"buildAgentProjectionBlock");function Ic(e){let t=_r(e),n=Array.isArray(e.layers)?e.layers:[],r=Array.isArray(e.catalogShortList)?e.catalogShortList:[];return{schemaVersion:"1.0",arkgateVersion:en(e.arkgateVersion),nonAuthoritative:!0,enforcementSurfaces:[...vr],contentIdentity:Zt(t),layerCount:n.length,catalogCodeCount:r.filter(s=>s?.ruleId).length,profile:Po(e.profile)}}i(Ic,"buildAgentProjectionMeta");function br(e){let t=Qt(e??""),n=Cr.exec(t);if(!n)return{block:null,body:null,before:t,after:"",beginAttrs:null};let r=n.index,s=r+n[0].length,o=t.slice(s),a=Lo.exec(o);if(!a)return{block:null,body:null,before:t,after:"",beginAttrs:null};let l=a.index,c=l+a[0].length,u=o.slice(0,l);u.startsWith(`
31
+ `)&&(u=u.slice(1));let f=t.slice(r,s+c),y=o.slice(c);return{block:f,body:u,before:t.slice(0,r),after:y,beginAttrs:n[1]??""}}i(br,"extractAgentProjectionBlock");function Mo(e){let t=String(e??""),r=Cr.exec(t)?.[1]??t,s=Rc.exec(r),o=kc.exec(r),a=/\bnonAuthoritative\s*=\s*true\b/i.test(r);return{arkgateVersion:s?.[1]??null,schemaVersion:o?.[1]??null,nonAuthoritative:a}}i(Mo,"parseAgentProjectionStamp");function Sc(e,t){let n=Mo(e).arkgateVersion;return n?n===en(t):!1}i(Sc,"projectionMatchesPackageVersion");function bc(e){return String(e??"").includes("non-authoritative")}i(bc,"projectionHasNonEnforcementLabel");function vc(e,t){let n=We(Qt(t)),s=br(n).body??n.replace(Cr,"").replace(Lo,"").trim()+`
32
+ `,o=Zt(s);if(e==null||!String(e).trim())return{content:We(`# Ark Enforcement
36
33
 
37
- ${n}`),action:"created",previousBlock:null,contentIdentity:o,preservedOutsideBlock:!1};let a=Xt(e),l=fr(a);if(l.block!=null){let u=l.body??"";if(Jt(u)===o)return{content:qe(a),action:"unchanged",previousBlock:l.block,contentIdentity:o,preservedOutsideBlock:!0};let m=l.before.replace(/\s*$/,`
34
+ ${n}`),action:"created",previousBlock:null,contentIdentity:o,preservedOutsideBlock:!1};let a=Qt(e),l=br(a);if(l.block!=null){let u=l.body??"";if(Zt(u)===o)return{content:We(a),action:"unchanged",previousBlock:l.block,contentIdentity:o,preservedOutsideBlock:!0};let f=l.before.replace(/\s*$/,`
38
35
 
39
36
  `),y=l.after.replace(/^\s*/,`
40
- `);return{content:qe(`${m}${n.trimEnd()}
41
- ${y}`),action:"block-replaced",previousBlock:l.block,contentIdentity:o,preservedOutsideBlock:!0}}let c=/^(#\s+[^\n]*\n)/m.exec(a);if(c&&c.index!=null){let u=c.index+c[1].length,m=a.slice(0,u).replace(/\s*$/,`
37
+ `);return{content:We(`${f}${n.trimEnd()}
38
+ ${y}`),action:"block-replaced",previousBlock:l.block,contentIdentity:o,preservedOutsideBlock:!0}}let c=/^(#\s+[^\n]*\n)/m.exec(a);if(c&&c.index!=null){let u=c.index+c[1].length,f=a.slice(0,u).replace(/\s*$/,`
42
39
 
43
40
  `),y=a.slice(u).replace(/^\s*/,`
44
- `);return{content:qe(`${m}${n.trimEnd()}
45
- ${y}`),action:"block-inserted",previousBlock:null,contentIdentity:o,preservedOutsideBlock:!0}}return{content:qe(`${n.trimEnd()}
41
+ `);return{content:We(`${f}${n.trimEnd()}
42
+ ${y}`),action:"block-inserted",previousBlock:null,contentIdentity:o,preservedOutsideBlock:!0}}return{content:We(`${n.trimEnd()}
46
43
 
47
- ${a.trimStart()}`),action:"block-inserted",previousBlock:null,contentIdentity:o,preservedOutsideBlock:!0}}i(Bl,"mergeAgentProjectionDocument");var zl="1.0",ho="templates/agent-skills",Ao="templates/skills",Ro="SKILL.md",Qt=Object.freeze(["ark-adopt","ark-architect","ark-autopilot","ark-contract","ark-coverage","ark-explain","ark-explore","ark-fix","ark-loop","ark-place","ark-runtime","ark-think","ark-upgrade"]),ko=Qt.length,ql=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function Eo(e){return typeof e!="string"||e.length<1||e.length>64?!1:ql.test(e)}i(Eo,"isValidAgentSkillName");function Ar(e){return Qt.includes(e)}i(Ar,"isArkSkillName");function Io(e){let t=String(e??"").replace(/^\uFEFF/,""),n=t.includes(`\r
44
+ ${a.trimStart()}`),action:"block-inserted",previousBlock:null,contentIdentity:o,preservedOutsideBlock:!0}}i(vc,"mergeAgentProjectionDocument");var Cc="1.0",Fo="templates/agent-skills",$o="templates/skills",Ho="SKILL.md",tn=Object.freeze(["ark-adopt","ark-architect","ark-autopilot","ark-contract","ark-coverage","ark-explain","ark-explore","ark-fix","ark-loop","ark-place","ark-runtime","ark-think","ark-upgrade"]),jo=tn.length,_c=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function Vo(e){return typeof e!="string"||e.length<1||e.length>64?!1:_c.test(e)}i(Vo,"isValidAgentSkillName");function xr(e){return tn.includes(e)}i(xr,"isArkSkillName");function Uo(e){let t=String(e??"").replace(/^\uFEFF/,""),n=t.includes(`\r
48
45
  `)?`\r
49
46
  `:`
50
- `,r=t.split(/\r?\n/);if(r[0]!=="---")return{hasFrontmatter:!1,frontmatter:null,body:t};let s=r.indexOf("---",1);if(s===-1)return{hasFrontmatter:!1,frontmatter:null,body:t};let o={};for(let m=1;m<s;m+=1){let y=r[m]??"";if(y.trim()===""||y.trimStart().startsWith("#"))continue;let g=y.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);if(!g)continue;let p=g[1],f=g[2]??"";(f.startsWith('"')&&f.endsWith('"')&&f.length>=2||f.startsWith("'")&&f.endsWith("'")&&f.length>=2)&&(f=f.slice(1,-1)),o[p]=f}let a=r.slice(s+1).join(n),l=typeof o.name=="string"&&o.name.length>0?o.name:null,c=typeof o.description=="string"&&o.description.length>0?o.description:null,u=typeof o.license=="string"&&o.license.length>0?o.license:null;return{hasFrontmatter:!0,frontmatter:{fields:o,name:l,description:c,license:u},body:a}}i(Io,"parseSkillDocument");function vo(e){let t=e.requireArkSkillName!==!1,n=e.requireBody!==!1,r=[],s=String(e.directoryName??""),o=Io(e.content);if(!o.hasFrontmatter||!o.frontmatter)return r.push({code:"MISSING_FRONTMATTER",message:`Skill "${s}" is missing YAML frontmatter fences.`,skillName:s||void 0}),r;let{name:a,description:l}=o.frontmatter,c=a??(s||void 0);return!a||!Eo(a)?r.push({code:"INVALID_NAME",message:`Skill name "${a??""}" is invalid (Agent Skills: 1\u201364 chars, [a-z0-9-], no leading/trailing/consecutive hyphens).`,skillName:c}):a!==s?r.push({code:"NAME_DIRECTORY_MISMATCH",message:`Frontmatter name "${a}" must match directory name "${s}".`,skillName:a}):t&&!Ar(a)&&r.push({code:"UNKNOWN_SKILL_NAME",message:`Skill name "${a}" is not in the frozen Ark 13-skill catalog (no new skill names).`,skillName:a}),l?l.length>1024&&r.push({code:"DESCRIPTION_TOO_LONG",message:`Skill "${s}" description exceeds 1024 characters (${l.length}).`,skillName:c}):r.push({code:"MISSING_DESCRIPTION",message:`Skill "${s}" is missing a non-empty description.`,skillName:c}),n&&o.body.trim().length===0&&r.push({code:"EMPTY_BODY",message:`Skill "${s}" has an empty instruction body.`,skillName:c}),r}i(vo,"validateAgentSkillDocument");function Wl(e){let t=[],n=new Set,r=[];for(let s of e){let o=String(s.name??"");if(n.has(o)){t.push({code:"DUPLICATE_SKILL",message:`Duplicate skill entry "${o}".`,skillName:o});continue}n.add(o),r.push(o),t.push(...vo({directoryName:o,content:s.content,requireArkSkillName:!0,requireBody:!0})),s.flatTemplateContent!=null&&hr(s.content)!==hr(s.flatTemplateContent)&&t.push({code:"CONTENT_MISMATCH",message:`Agent Skills SKILL.md for "${o}" does not match flat template templates/skills/${o}.md.`,skillName:o})}for(let s of Qt)n.has(s)||t.push({code:"MISSING_SKILL",message:`Missing frozen skill "${s}" from Agent Skills package.`,skillName:s});for(let s of r)Ar(s)||(t.some(o=>o.code==="UNKNOWN_SKILL_NAME"&&o.skillName===s)?t.push({code:"EXTRA_SKILL",message:`Extra skill "${s}" is not in the frozen Ark 13-skill catalog.`,skillName:s}):t.push({code:"EXTRA_SKILL",message:`Extra skill "${s}" is not in the frozen Ark 13-skill catalog.`,skillName:s}));return r.sort(),{ok:t.length===0,issues:t,names:r,expectedCount:ko,presentCount:r.length}}i(Wl,"validateAgentSkillsPackage");var Rr=/^arkgate@(\S+)\.\s/;function So(e){let t=String(e??"").trim();return t?`arkgate@${t}. `:""}i(So,"skillDescriptionVersionPrefix");function bo(e){return String(e??"").replace(Rr,"")}i(bo,"stripSkillDescriptionVersion");function Yl(e){return String(e??"").match(Rr)?.[1]??null}i(Yl,"parseSkillDescriptionVersion");function Jl(e,t){let n=bo(e),r=typeof t=="string"?t.trim():"";return r?`${So(r)}${n}`:n}i(Jl,"stampSkillDescription");function hr(e){return String(e??"").replace(/^\uFEFF/,"").replace(/\r\n/g,`
51
- `)}i(hr,"normalizeSkillContent");function Co(e){return`${e}/${Ro}`}i(Co,"agentSkillEntryRelativePath");function Xl(e){return`${ho}/${Co(e)}`}i(Xl,"agentSkillPackageFileRelativePath");function Zl(e){return`${Ao}/${e}.md`}i(Zl,"flatSkillTemplateFileRelativePath");export{Er as ADAPTER_DIAGNOSTIC_DOCS_RELATIVE_PATH,Fl as AGENT_PROJECTION_BEGIN_MARKER,co as AGENT_PROJECTION_END_MARKER,mr as AGENT_PROJECTION_ENFORCEMENT_SURFACES,uo as AGENT_PROJECTION_NON_ENFORCEMENT_LABEL,ho as AGENT_SKILLS_PACKAGE_RELATIVE_ROOT,Ro as AGENT_SKILL_ENTRY_FILENAME,Sn as ANALYSIS_IR_SCHEMA_VERSION,Qn as ARKORDER_RULE_IDS,Yi as ARKORDER_TIER1_SENSOR_IDS,xs as ARKRUN_INTERACTION_NAME_INCOMPLETE,bs as ARKRUN_KERNEL_FACTORY_CALLEES,Ri as ARKRUN_KERNEL_INTERACTION_CALLEES,Zn as ARKRUN_RULE_IDS,Ni as ARKRUN_TIER1_SENSOR_IDS,Cs as ARKRUN_TRANSPORT_BYPASS_SPECIFIERS,Ml as ARK_AGENT_PROJECTION_SCHEMA_VERSION,zl as ARK_AGENT_SKILLS_PACKAGE_SCHEMA_VERSION,$o as ARK_ANALYSIS_RESULT_SCHEMA,sn as ARK_ANALYSIS_RESULT_SCHEMA_VERSION,kn as ARK_CONFIG_SCHEMA,se as ARK_CONFIG_SCHEMA_VERSION,yl as ARK_DESIGN_DELTA_SCHEMA_VERSION,gl as ARK_ENFORCEMENT_STATE_SCHEMA_VERSION,qt as ARK_IMPROVEMENT_COMPASS_SCHEMA_VERSION,jo as ARK_PROJECT_IDENTITY_SCHEMA,Sr as ARK_PROJECT_IDENTITY_SCHEMA_URL,Ho as ARK_PROJECT_IDENTITY_SCHEMA_VERSION,Cn as ARK_RULES_SCHEMA,Ca as ARK_RULES_SCHEMA_VERSION,os as ARK_RULE_SENSORS,Hs as ARK_RUN_DOCTOR_SCHEMA_VERSION,Rr as ARK_SKILL_DESCRIPTION_VERSION_PATTERN,Qt as ARK_SKILL_NAMES,ko as ARK_SKILL_NAME_COUNT,xl as ARK_STATUS_MANIFEST_SCHEMA,Bs as ARK_STATUS_MANIFEST_SCHEMA_URL,sr as ARK_STATUS_MANIFEST_SCHEMA_VERSION,$l as DEFAULT_AGENT_PROJECTION_RULE_IDS,Gt as DIAGNOSTIC_CATALOG,hl as DIAGNOSTIC_CATALOG_SCHEMA_VERSION,nr as DIAGNOSTIC_DOCS_RELATIVE_PATH,Al as DIAGNOSTIC_RULE_IDS,yi as EXTRA_MERGE_TEETH_GOVERNED_FLOOR,Pt as EffectiveContractError,Ao as FLAT_SKILL_TEMPLATES_RELATIVE_ROOT,Pe as IMPROVEMENT_COMPASS_OUT_OF_SCOPE_LENSES,Yt as IMPROVEMENT_COMPASS_TOP_RESIDUAL_CAP,Wt as IMPROVEMENT_LENS_IDS,vs as MERGE_PLANES_DUAL_STAMP,wn as POLICY_DELTA_SCHEMA_VERSION,Cr as PROJECT_BINDING_SCHEMA,br as PROJECT_EXPECTATION_SCHEMA,vn as RESOLVED_CANDIDATE_FACTS_SCHEMA,_e as RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,qs as STATUS_COMPASS_FACTS_SOURCES,zs as STATUS_COMPASS_MODES,zt as STATUS_COMPASS_REASON_CODES,vr as adapterDocsCodePath,nn as adapterFindingOccurrenceTargetKeys,Ir as adapterFindingRefFromTargetKey,on as adapterFindingTargetKey,Jt as agentProjectionContentIdentity,Co as agentSkillEntryRelativePath,Xl as agentSkillPackageFileRelativePath,Ke as analyzeArchitectureConvergence,Ft as analyzeChange,hs as analyzePolicyDelta,ut as analyzeProject,yt as analyzeResolvedProject,zn as arkRunKernelCallKind,mo as buildAgentProjectionBeginMarker,Vl as buildAgentProjectionBlock,yr as buildAgentProjectionBody,Ul as buildAgentProjectionMeta,jn as buildArkRuleFileHints,On as buildEffectiveArkRules,wl as buildImprovementCompass,fl as buildRulesInventory,bl as buildStatusManifest,Nn as canPromoteInvariant,vl as catalogFixForRuleId,Sl as catalogWhyForRuleId,Dn as classifyArkPolicyDelta,Un as classifyResolvedLayerCoverage,Js as classifyStatusWritePath,Ut as collectAnalysisConfigWarnings,Hn as collectEmptyAppliesToFindings,He as collectForbiddenCapabilityUses,Gn as composeMergePlanesHonesty,jr as createAICodeGate,Fo as createAdapterResult,Tt as createArchitectureProfile,Xr as createArchitectureProfileFromArkConfig,Zr as createElevenLayerArkConfig,Vo as createProjectId,Uo as createProjectIdentity,In as createResolvedCandidateFacts,Xs as defaultHonestLabel,Ai as demoteExtraPlaneTeethUnderClassificationFloor,Es as deriveArkRuleFileHints,Fn as detectArchitectureCycles,J as deterministicHash,Gs as diagnosticDocsFragment,El as diagnosticDocsPath,xn as effectiveContractPolicyPayload,xt as elevenLayerProfile,Te as emptyEffectiveArkRules,Ge as evaluateArchitectureGraph,er as evaluateArkOrderSensors,$n as evaluateArkRuleSensors,Ns as evaluateArkRunEditorSensors,Bi as evaluateArkRunEditorSensorsFromSource,Vt as evaluateArkRunSensors,Tn as evaluateInvariantCoverage,Ys as evaluateStatusBinding,As as explainViolation,Re as extraMergeTeethAllowed,fr as extractAgentProjectionBlock,Ti as extractArkRunDeclarationsFromSource,Yn as extractArkRunImportedConstructorNamesFromSource,Jn as extractArkRunKernelCallsFromSource,Xn as extractArkRunManagedNewsFromSource,Wn as extractArkRunValueImportDependenciesFromSource,gi as extractClassShapesFromSource,$e as extractSemanticDependencies,Zl as flatSkillTemplateFileRelativePath,go as formatAgentProjectionCatalogShortList,pr as formatAgentProjectionLayers,dl as formatArkRunDoctorLines,Dl as formatImprovementCompassDoctorLines,io as formatImprovementCompassResidualLabels,Bt as getDiagnosticCatalogEntry,ml as inventoryToExtractionCard,hi as isArkOrderRuleId,mt as isArkRunKernelModuleSpecifier,Kn as isArkRunRuleId,qn as isArkRunTransportBypassSpecifier,Ar as isArkSkillName,kl as isCataloguedOrArkRuleFamily,Is as isExtraPlaneFinding,Rl as isKnownDiagnosticCode,Eo as isValidAgentSkillName,_t as loadArkConfigContract,Lt as loadArkRulesContract,Mt as loadContract,Ie as loadResolvedCandidateFacts,Bl as mergeAgentProjectionDocument,Vn as normalizeExtraMergeTeethClassification,hr as normalizeSkillContent,eo as normalizeStatusImprovementCompass,yo as parseAgentProjectionStamp,En as parseArkConfigJson,La as parseArkRulesJson,Yl as parseSkillDescriptionVersion,Io as parseSkillDocument,Mn as policyDeltaAcknowledgementMatches,Fs as preflightChange,$s as preflightResolvedChange,lo as primaryImprovementCompassNextAction,tr as projectStatusArkRun,or as projectStatusImprovementCompass,Gl as projectionHasNonEnforcementLabel,Kl as projectionMatchesPackageVersion,Pa as resolveEffectiveContract,Zs as resolveStatusNextAction,st as resolvedFactsEvidenceRequirementsHash,Il as serializeDiagnosticCatalog,So as skillDescriptionVersionPrefix,V as stableSerialize,Jl as stampSkillDescription,_l as statusCompassResidualIsSubsetOfDoctor,bo as stripSkillDescriptionVersion,cl as summarizeArkRunSection,rn as toAdapterDiagnostic,Ol as unavailableStatusImprovementCompass,vo as validateAgentSkillDocument,Wl as validateAgentSkillsPackage,_o as version};
47
+ `,r=t.split(/\r?\n/);if(r[0]!=="---")return{hasFrontmatter:!1,frontmatter:null,body:t};let s=r.indexOf("---",1);if(s===-1)return{hasFrontmatter:!1,frontmatter:null,body:t};let o={};for(let f=1;f<s;f+=1){let y=r[f]??"";if(y.trim()===""||y.trimStart().startsWith("#"))continue;let g=y.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);if(!g)continue;let p=g[1],m=g[2]??"";(m.startsWith('"')&&m.endsWith('"')&&m.length>=2||m.startsWith("'")&&m.endsWith("'")&&m.length>=2)&&(m=m.slice(1,-1)),o[p]=m}let a=r.slice(s+1).join(n),l=typeof o.name=="string"&&o.name.length>0?o.name:null,c=typeof o.description=="string"&&o.description.length>0?o.description:null,u=typeof o.license=="string"&&o.license.length>0?o.license:null;return{hasFrontmatter:!0,frontmatter:{fields:o,name:l,description:c,license:u},body:a}}i(Uo,"parseSkillDocument");function Ko(e){let t=e.requireArkSkillName!==!1,n=e.requireBody!==!1,r=[],s=String(e.directoryName??""),o=Uo(e.content);if(!o.hasFrontmatter||!o.frontmatter)return r.push({code:"MISSING_FRONTMATTER",message:`Skill "${s}" is missing YAML frontmatter fences.`,skillName:s||void 0}),r;let{name:a,description:l}=o.frontmatter,c=a??(s||void 0);return!a||!Vo(a)?r.push({code:"INVALID_NAME",message:`Skill name "${a??""}" is invalid (Agent Skills: 1\u201364 chars, [a-z0-9-], no leading/trailing/consecutive hyphens).`,skillName:c}):a!==s?r.push({code:"NAME_DIRECTORY_MISMATCH",message:`Frontmatter name "${a}" must match directory name "${s}".`,skillName:a}):t&&!xr(a)&&r.push({code:"UNKNOWN_SKILL_NAME",message:`Skill name "${a}" is not in the frozen Ark 13-skill catalog (no new skill names).`,skillName:a}),l?l.length>1024&&r.push({code:"DESCRIPTION_TOO_LONG",message:`Skill "${s}" description exceeds 1024 characters (${l.length}).`,skillName:c}):r.push({code:"MISSING_DESCRIPTION",message:`Skill "${s}" is missing a non-empty description.`,skillName:c}),n&&o.body.trim().length===0&&r.push({code:"EMPTY_BODY",message:`Skill "${s}" has an empty instruction body.`,skillName:c}),r}i(Ko,"validateAgentSkillDocument");function Oc(e){let t=[],n=new Set,r=[];for(let s of e){let o=String(s.name??"");if(n.has(o)){t.push({code:"DUPLICATE_SKILL",message:`Duplicate skill entry "${o}".`,skillName:o});continue}n.add(o),r.push(o),t.push(...Ko({directoryName:o,content:s.content,requireArkSkillName:!0,requireBody:!0})),s.flatTemplateContent!=null&&Or(s.content)!==Or(s.flatTemplateContent)&&t.push({code:"CONTENT_MISMATCH",message:`Agent Skills SKILL.md for "${o}" does not match flat template templates/skills/${o}.md.`,skillName:o})}for(let s of tn)n.has(s)||t.push({code:"MISSING_SKILL",message:`Missing frozen skill "${s}" from Agent Skills package.`,skillName:s});for(let s of r)xr(s)||(t.some(o=>o.code==="UNKNOWN_SKILL_NAME"&&o.skillName===s)?t.push({code:"EXTRA_SKILL",message:`Extra skill "${s}" is not in the frozen Ark 13-skill catalog.`,skillName:s}):t.push({code:"EXTRA_SKILL",message:`Extra skill "${s}" is not in the frozen Ark 13-skill catalog.`,skillName:s}));return r.sort(),{ok:t.length===0,issues:t,names:r,expectedCount:jo,presentCount:r.length}}i(Oc,"validateAgentSkillsPackage");var Tr=/^arkgate@(\S+)\.\s/;function Go(e){let t=String(e??"").trim();return t?`arkgate@${t}. `:""}i(Go,"skillDescriptionVersionPrefix");function Bo(e){return String(e??"").replace(Tr,"")}i(Bo,"stripSkillDescriptionVersion");function xc(e){return String(e??"").match(Tr)?.[1]??null}i(xc,"parseSkillDescriptionVersion");function Tc(e,t){let n=Bo(e),r=typeof t=="string"?t.trim():"";return r?`${Go(r)}${n}`:n}i(Tc,"stampSkillDescription");function Or(e){return String(e??"").replace(/^\uFEFF/,"").replace(/\r\n/g,`
48
+ `)}i(Or,"normalizeSkillContent");function zo(e){return`${e}/${Ho}`}i(zo,"agentSkillEntryRelativePath");function Nc(e){return`${Fo}/${zo(e)}`}i(Nc,"agentSkillPackageFileRelativePath");function Lc(e){return`${$o}/${e}.md`}i(Lc,"flatSkillTemplateFileRelativePath");export{Lr as ADAPTER_DIAGNOSTIC_DOCS_RELATIVE_PATH,hc as AGENT_PROJECTION_BEGIN_MARKER,To as AGENT_PROJECTION_END_MARKER,vr as AGENT_PROJECTION_ENFORCEMENT_SURFACES,No as AGENT_PROJECTION_NON_ENFORCEMENT_LABEL,Fo as AGENT_SKILLS_PACKAGE_RELATIVE_ROOT,Ho as AGENT_SKILL_ENTRY_FILENAME,xn as ANALYSIS_IR_SCHEMA_VERSION,dr as ARKORDER_RULE_IDS,xl as ARKORDER_TIER1_SENSOR_IDS,qs as ARKRUN_INTERACTION_NAME_INCOMPLETE,Gs as ARKRUN_KERNEL_FACTORY_CALLEES,Qi as ARKRUN_KERNEL_INTERACTION_CALLEES,cr as ARKRUN_RULE_IDS,ul as ARKRUN_TIER1_SENSOR_IDS,Bs as ARKRUN_TRANSPORT_BYPASS_SPECIFIERS,yc as ARK_AGENT_PROJECTION_SCHEMA_VERSION,Cc as ARK_AGENT_SKILLS_PACKAGE_SCHEMA_VERSION,sa as ARK_ANALYSIS_RESULT_SCHEMA,an as ARK_ANALYSIS_RESULT_SCHEMA_VERSION,vn as ARK_CONFIG_SCHEMA,re as ARK_CONFIG_SCHEMA_VERSION,Xl as ARK_DESIGN_DELTA_SCHEMA_VERSION,Yl as ARK_ENFORCEMENT_STATE_SCHEMA_VERSION,Yt as ARK_IMPROVEMENT_COMPASS_SCHEMA_VERSION,aa as ARK_PROJECT_IDENTITY_SCHEMA,Dr as ARK_PROJECT_IDENTITY_SCHEMA_URL,oa as ARK_PROJECT_IDENTITY_SCHEMA_VERSION,Nn as ARK_RULES_SCHEMA,Ya as ARK_RULES_SCHEMA_VERSION,hs as ARK_RULE_SENSORS,oo as ARK_RUN_DOCTOR_SCHEMA_VERSION,Tr as ARK_SKILL_DESCRIPTION_VERSION_PATTERN,tn as ARK_SKILL_NAMES,jo as ARK_SKILL_NAME_COUNT,cc as ARK_STATUS_MANIFEST_SCHEMA,po as ARK_STATUS_MANIFEST_SCHEMA_URL,gr as ARK_STATUS_MANIFEST_SCHEMA_VERSION,Ac as DEFAULT_AGENT_PROJECTION_RULE_IDS,zt as DIAGNOSTIC_CATALOG,Jl as DIAGNOSTIC_CATALOG_SCHEMA_VERSION,fr as DIAGNOSTIC_DOCS_RELATIVE_PATH,Zl as DIAGNOSTIC_RULE_IDS,Xi as EXTRA_MERGE_TEETH_GOVERNED_FLOOR,wt as EffectiveContractError,$o as FLAT_SKILL_TEMPLATES_RELATIVE_ROOT,Pe as IMPROVEMENT_COMPASS_OUT_OF_SCOPE_LENSES,Jt as IMPROVEMENT_COMPASS_TOP_RESIDUAL_CAP,Xt as IMPROVEMENT_LENS_IDS,Us as MERGE_PLANES_DUAL_STAMP,Hn as POLICY_DELTA_SCHEMA_VERSION,Fr as PROJECT_BINDING_SCHEMA,Mr as PROJECT_EXPECTATION_SCHEMA,On as RESOLVED_CANDIDATE_FACTS_SCHEMA,xe as RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,mo as STATUS_COMPASS_FACTS_SOURCES,fo as STATUS_COMPASS_MODES,qt as STATUS_COMPASS_REASON_CODES,wr as adapterDocsCodePath,sn as adapterFindingOccurrenceTargetKeys,Pr as adapterFindingRefFromTargetKey,ln as adapterFindingTargetKey,Zt as agentProjectionContentIdentity,zo as agentSkillEntryRelativePath,Nc as agentSkillPackageFileRelativePath,Ke as analyzeArchitectureConvergence,$t as analyzeChange,xs as analyzePolicyDelta,dt as analyzeProject,yt as analyzeResolvedProject,rr as arkRunKernelCallKind,wo as buildAgentProjectionBeginMarker,Ec as buildAgentProjectionBlock,_r as buildAgentProjectionBody,Ic as buildAgentProjectionMeta,Jn as buildArkRuleFileHints,Ln as buildEffectiveArkRules,mc as buildImprovementCompass,Wl as buildRulesInventory,oc as buildStatusManifest,Mn as canPromoteInvariant,rc as catalogFixForRuleId,sc as catalogWhyForRuleId,jn as classifyArkPolicyDelta,Qn as classifyResolvedLayerCoverage,ho as classifyStatusWritePath,Gt as collectAnalysisConfigWarnings,Xn as collectEmptyAppliesToFindings,He as collectForbiddenCapabilityUses,tr as composeMergePlanesHonesty,Zr as createAICodeGate,ra as createAdapterResult,Nt as createArchitectureProfile,cs as createArchitectureProfileFromArkConfig,ds as createElevenLayerArkConfig,ia as createProjectId,la as createProjectIdentity,_n as createResolvedCandidateFacts,Ao as defaultHonestLabel,Zi as demoteExtraPlaneTeethUnderClassificationFloor,js as deriveArkRuleFileHints,Un as detectArchitectureCycles,X as deterministicHash,uo as diagnosticDocsFragment,tc as diagnosticDocsPath,wn as effectiveContractPolicyPayload,Tt as elevenLayerProfile,Ne as emptyEffectiveArkRules,Ge as evaluateArchitectureGraph,ur as evaluateArkOrderSensors,Yn as evaluateArkRuleSensors,Xs as evaluateArkRunEditorSensors,vl as evaluateArkRunEditorSensorsFromSource,Kt as evaluateArkRunSensors,Dn as evaluateInvariantCoverage,yo as evaluateStatusBinding,Ts as explainViolation,Re as extraMergeTeethAllowed,br as extractAgentProjectionBlock,dl as extractArkRunDeclarationsFromSource,ar as extractArkRunImportedConstructorNamesFromSource,ir as extractArkRunKernelCallsFromSource,lr as extractArkRunManagedNewsFromSource,or as extractArkRunValueImportDependenciesFromSource,Yi as extractClassShapesFromSource,$e as extractSemanticDependencies,Lc as flatSkillTemplateFileRelativePath,Do as formatAgentProjectionCatalogShortList,Sr as formatAgentProjectionLayers,Gl as formatArkRunDoctorLines,gc as formatImprovementCompassDoctorLines,Oo as formatImprovementCompassResidualLabels,Wt as getDiagnosticCatalogEntry,ql as inventoryToExtractionCard,Ji as isArkOrderRuleId,mt as isArkRunKernelModuleSpecifier,er as isArkRunRuleId,sr as isArkRunTransportBypassSpecifier,xr as isArkSkillName,ec as isCataloguedOrArkRuleFamily,Vs as isExtraPlaneFinding,Ql as isKnownDiagnosticCode,Vo as isValidAgentSkillName,xt as loadArkConfigContract,Pt as loadArkRulesContract,Ft as loadContract,Ie as loadResolvedCandidateFacts,vc as mergeAgentProjectionDocument,Zn as normalizeExtraMergeTeethClassification,Or as normalizeSkillContent,Eo as normalizeStatusImprovementCompass,Mo as parseAgentProjectionStamp,Cn as parseArkConfigJson,ti as parseArkRulesJson,xc as parseSkillDescriptionVersion,Uo as parseSkillDocument,Vn as policyDeltaAcknowledgementMatches,ro as preflightChange,so as preflightResolvedChange,xo as primaryImprovementCompassNextAction,pr as projectStatusArkRun,yr as projectStatusImprovementCompass,bc as projectionHasNonEnforcementLabel,Sc as projectionMatchesPackageVersion,ni as resolveEffectiveContract,Ro as resolveStatusNextAction,rt as resolvedFactsEvidenceRequirementsHash,nc as serializeDiagnosticCatalog,Go as skillDescriptionVersionPrefix,H as stableSerialize,Tc as stampSkillDescription,lc as statusCompassResidualIsSubsetOfDoctor,Bo as stripSkillDescriptionVersion,Kl as summarizeArkRunSection,on as toAdapterDiagnostic,ic as unavailableStatusImprovementCompass,Ko as validateAgentSkillDocument,Oc as validateAgentSkillsPackage,qo as version};