arkgate 4.8.21 → 4.8.23

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 (42) hide show
  1. package/CHANGELOG.md +71 -0
  2. package/README.md +2 -2
  3. package/bin/ark-check-runtime.mjs +4 -2
  4. package/bin/ark-layer-match.mjs +606 -11
  5. package/bin/lib/analysis-engine.mjs +11 -11
  6. package/bin/lib/config-contract.mjs +492 -1
  7. package/bin/lib/diagnostic-catalog.mjs +32 -0
  8. package/bin/lib/doctor-advisories.mjs +60 -1
  9. package/bin/lib/doctor-plan.mjs +2 -2
  10. package/bin/lib/enforcement-honesty.mjs +22 -0
  11. package/bin/lib/flat-parent-pilot.mjs +252 -0
  12. package/bin/lib/html-report-advisories.mjs +2 -0
  13. package/bin/lib/html-report-depth.mjs +3 -1
  14. package/bin/lib/invariant-coverage.mjs +27 -3
  15. package/bin/lib/physical-cohesion.mjs +16 -18
  16. package/bin/lib/pilot-loop.mjs +21 -8
  17. package/bin/lib/team-parliament-io.mjs +4 -2
  18. package/dist/{configTypes-CTELo87-.d.ts → configTypes-Bbf_MFGe.d.ts} +36 -2
  19. package/dist/{diagnosticCatalog-B7BXlet6.d.ts → diagnosticCatalog-35mrwAHe.d.ts} +20 -5
  20. package/dist/eslint/index.cjs +4 -4
  21. package/dist/eslint/index.d.ts +51 -5
  22. package/dist/eslint/index.js +4 -4
  23. package/dist/index.cjs +36 -36
  24. package/dist/index.d.ts +104 -5
  25. package/dist/index.js +36 -36
  26. package/dist/nestjs/index.cjs +9 -9
  27. package/dist/nestjs/index.d.ts +3 -3
  28. package/dist/nestjs/index.js +9 -9
  29. package/dist/runtime/index.cjs +19 -19
  30. package/dist/runtime/index.d.ts +6 -6
  31. package/dist/runtime/index.js +19 -19
  32. package/dist/{types-yDNEQ603.d.ts → types-Bdj32QwA.d.ts} +1 -1
  33. package/dist/{types-fQ9-KrBj.d.ts → types-Ik_OakcI.d.ts} +1 -1
  34. package/docs/README.md +3 -1
  35. package/docs/agent-guide.md +9 -1
  36. package/docs/configuration.md +92 -1
  37. package/docs/diagnostics.md +32 -0
  38. package/docs/product-voice.md +1 -1
  39. package/package.json +2 -1
  40. package/schemas/ark.config.schema.json +124 -2
  41. package/server.json +2 -2
  42. package/templates/agent-skills/README.md +1 -1
package/dist/index.js CHANGED
@@ -1,55 +1,55 @@
1
- var za=Object.defineProperty;var i=(e,t)=>za(e,"name",{value:t,configurable:!0});var Wa="4.8.21";var qa=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,Ya=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,Ja=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function Xa(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),o=String(t?.toLayer??"");return qa.test(n)?"pure-shared":r==="PersistenceAdapters"&&(Ya.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${o} ${n}`))?"kernel-emit":Ja.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&o==="PersistenceAdapters"?"use-case":"unknown"}i(Xa,"classifyLayerImportKind");function Za(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=Xa(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(Za,"layerImportNextAction");function Qa(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}i(Qa,"arkRunCallSiteName");function ei(e){let t=Qa(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(ei,"arkRunNextAction");function ye(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return Za(e);case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, test at the public interface, then preflight again.`;case"CAPABILITY_VIOLATION":return`Define a ${String(e.capability??"capability")} port in ${e.fromLayer??"the walled layer"}, bind the implementation outside it, test at the public interface, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, test at the public interface, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"LITERAL_PATH_DRIFT":return typeof e.target=="string"&&e.target.length>0?`Rewrite the literal to ${e.target}, or run \`arkgate-check --path-drift --base-ref <ref> --write\` to apply every anchored replacement.`:"Rewrite the literal to the rename destination, or run `arkgate-check --path-drift --base-ref <ref> --write` to apply every anchored replacement.";case"LITERAL_PATH_UNRESOLVED":return"Read the candidate and decide: fix the path, or leave it. Advisory \u2014 with no rename to anchor it there is no destination to propose, so --write never touches it.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";case"INVARIANT_COVERAGE_OUTSIDE_ROOTS":return"Move the covering test under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json, then run Ark again.";case"INVARIANT_CATALOG_EMPTY":return typeof e.file=="string"&&e.file.length>0?`Add 1\u20132 short phrases to invariants[] in ${e.file}, then run ark-check --doctor. Starters show the shape.`:"Add 1\u20132 short phrases to invariants[] in arkrules/<Domain>.json, then run ark-check --doctor. Starters show the shape.";case"INVARIANT_TESTS_PATH_MISSING":return"Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present.";case"INVARIANT_COVERAGE_ROOTS_MISSING":return"Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. An enforced invariant fails closed until that path is present.";case"ARKRULE_STRUCTURE":case"ARKRULE_INVARIANT":case"INVARIANT_UNCOVERED":return`Fix the structure or invariant for ${typeof e.arkruleId=="string"&&e.arkruleId.length>0?e.arkruleId:"the ArkRule"} (declared in ${typeof e.arkruleSource=="string"&&e.arkruleSource.length>0?e.arkruleSource:"arkrules/<Layer>.json"}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`;case"ARKRUN_MISSING_ROOT":case"ARKRUN_KERNEL_IN_DOMAIN":case"ARKRUN_DIRECT_NEW":case"ARKRUN_UNDECLARED_EMIT":case"ARKRUN_UNDECLARED_HANDLE":case"ARKRUN_UNDECLARED_DEPEND":case"ARKRUN_TRANSPORT_BYPASS":return ei(e);case"ARKORDER_MISSING_PLANE":return typeof e.target=="string"&&e.target.length>0?`Import createOrderPlane from arkgate/order and call it in plane root ${e.target} listed in arkOrder.planeRoots, then preflight again.`:"Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKORDER_KERNEL_IN_DOMAIN":return"Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe.";case"ARKORDER_GENERIC_UPDATE":return"Don't use a generic update. First freeze with release(). Later, propose the change, then apply it.";case"ARKORDER_TOO_MANY_PARAMS":return"Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe.";case"ARKORDER_INGEST_WRITES_XI":return"Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe.";case"ARKORDER_XI_FIELD_WRITE":return typeof e.target=="string"&&e.target.length>0?`Don't write ${e.target} from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.`:"Don't write a named product choice from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.";case"ARKORDER_UNVALVED_RELEASE":return"Change the choice with proposeRelease then apply. release() is only the first freeze. Never mechanical-safe.";default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(ye,"deterministicNextAction");var Nt="1.5",wt="docs/diagnostics.md",ns={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","mode","valid","completeness","completenessReasons","diagnostics"],allOf:[{if:{properties:{completeness:{enum:["partial","unavailable"]}},required:["completeness"]},then:{properties:{valid:{const:!1}}}},{if:{properties:{mode:{const:"resolved-candidate-facts"},completeness:{enum:["complete","partial"]}},required:["mode","completeness"]},then:{required:["policyHash","resolverIdentity","factsHash","candidateTreeHash"]}},{if:{properties:{completeness:{const:"complete"}},required:["completeness"]},then:{properties:{completenessReasons:{maxItems:0}}},else:{properties:{completenessReasons:{minItems:1}}}}],properties:{schemaVersion:{const:"1.5"},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}}}}}};function nt(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,o=typeof e.toLayer=="string"?e.toLayer:void 0,s=typeof e.target=="string"?e.target:void 0;return[t,n,r??"",o??"",s??""].join("|")}i(nt,"adapterFindingTargetKey");function rt(e){let t=new Map;return e.map(n=>{let r=nt(n),o=(t.get(r)??0)+1;return t.set(r,o),o===1?r:`${r}#${o}`})}i(rt,"adapterFindingOccurrenceTargetKeys");function Pt(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(Pt,"adapterFindingRefFromTargetKey");function Lt(e){return`${wt}#${e}`}i(Lt,"adapterDocsCodePath");function O(e){return typeof e=="string"&&e.length>0?e:void 0}i(O,"text");function rs(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}i(rs,"positiveInteger");function ti(e,t,n){return ye({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(ti,"nextActionForDiagnostic");function bn(e,t="error",n){let r=O(e.ruleId)??O(e.code)??"ARK_UNKNOWN",o=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,s={...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??nt(e),c=Pt(a);return{ruleId:r,severity:o,message:O(e.message)??r,location:{file:O(e.file)??"<unknown>",line:rs(e.line,1),column:rs(e.column,1)},evidence:s,nextAction:O(e.nextAction)??ti(r,s,e),findingRef:c,targetKey:a,docsCodePath:Lt(r)}}i(bn,"toAdapterDiagnostic");function ni(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(g=>({code:O(g.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:O(g.message)??`Analysis ${t}: required evidence is incomplete.`,...O(g.file)?{file:O(g.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],o={...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 g of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!o[g])throw new Error(`${g} is required for resolved ${t} adapter evidence.`)}let s=e.violations??[],a=e.warnings??[],c=rt(s),l=rt(a),u=[...s.map((g,f)=>bn(g,"error",c[f])),...a.map((g,f)=>bn(g,"warning",l[f]))],p={schemaVersion:"1.5",completenessReasons:r,diagnostics:u};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...p,mode:n,valid:!1,completeness:t,...o};let g={policyHash:o.policyHash,resolverIdentity:o.resolverIdentity,factsHash:o.factsHash,candidateTreeHash:o.candidateTreeHash};return t==="complete"?{...p,mode:n,valid:e.valid,completeness:t,...g}:{...p,mode:n,valid:!1,completeness:t,...g}}return t==="complete"?{...p,mode:n,valid:e.valid,completeness:t,...o}:{...p,mode:n,valid:!1,completeness:t,...o}}i(ni,"createAdapterResult");var ri="1.0",ss="https://unpkg.com/arkgate@4/schemas/ark.project-identity.schema.json",Dt="^sha256:[a-f0-9]{64}$",os={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:Dt,description:"Project id previously returned by ark_identity or ark_manifest."}}},as={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:Dt},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},si={$schema:"https://json-schema.org/draft/2020-12/schema",$id:ss,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:Dt},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{type:"string",minLength:1},arkgateVersion:{type:"string",minLength:1},contractHash:{type:"string",pattern:Dt},contractSource:{enum:["project","default-profile","manifest"]},runtimeId:{type:"string",minLength:1},processStartedAt:{type:"string",format:"date-time"}},$defs:{expectation:os,binding:as}};function oi(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(oi,"createProjectId");function ai(e){return{schemaVersion:"1.0",...e}}i(ai,"createProjectIdentity");var Cn=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),On=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),xn=Object.freeze(Object.keys(On).sort()),vn=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"}),_n=Object.freeze({process:Object.freeze(["process","node:process"])});function st(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=vn[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),o=vn[r];if(o)return o;let s=e.indexOf("/",n+1);return s<0?null:vn[e.slice(0,s)]??null}i(st,"capabilityForModuleSpecifier");function Ce(e,t){for(let n of t)if(_n[n]?.includes(e))return n;return null}i(Ce,"forbiddenGlobalForModuleSpecifier");function Mt(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),o=On[r];if(o)return o}return null}i(Mt,"capabilityForAmbientName");function je(e){if(e?.pure===!0)return[...Cn].sort();let n=(e?.capabilities?.deny??[]).filter(r=>Cn.includes(r));return[...new Set(n)].sort()}i(je,"effectiveCapabilityDeny");function ot(e,t){if(t.length===0)return!1;let n=new Set(t),r=e.split(".");for(let o=r.length;o>=1;o-=1)if(n.has(r.slice(0,o).join(".")))return!0;return!1}i(ot,"ambientCoveredByForbiddenGlobals");function Ft(e){let t=new Set,n=new Set,r=Object.keys(On);for(let o of e?.forbiddenGlobals??[]){let s=r.filter(a=>a===o||a.startsWith(`${o}.`));if(s.length===0)n.add(o);else for(let a of s)t.add(`ambient:${a}`);for(let a of _n[o]??[])t.add(`import-exact:${a}`)}for(let o of je(e)){if(t.add(`import:${o}`),o==="process")for(let s of _n.process)t.add(`import-exact:${s}`);for(let s of r)Mt(s)===o&&t.add(`ambient:${s}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}i(Ft,"loweredLayerCoverage");var is=new Map;function ls(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(ls,"escapeLiteral");function Ht(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let o=e[n+1];if("*?{}[],".includes(o)||o==="\\"){t+="\\"+o,n+=1;continue}t+="/";continue}t+=r}return t}i(Ht,"normalizeGlobSeparators");function ii(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(ii,"bracesBalanced");function ke(e){let t=is.get(e);if(t)return t;let n=Ht(e),r=ii(n),o="",s=0;for(let c=0;c<n.length;c+=1){let l=n[c];l==="\\"&&c+1<n.length?(o+=ls(n[c+1]),c+=1):l==="*"?n[c+1]==="*"?n[c+2]==="/"?(o+="(?:.*/)?",c+=2):(o+=".*",c+=1):o+="[^/]*":l==="?"?o+="[^/]":l==="{"&&r?(o+="(?:",s+=1):l==="}"&&r&&s>0?(o+=")",s-=1):l===","&&r&&s>0?o+="|":o+=ls(l)}let a=new RegExp(`^${o}$`);return is.set(e,a),a}i(ke,"globToRegExp");function li(e){return Ht(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}i(li,"concreteGlobSegments");function Nn(e,t){let n=Ht(String(e)),r=li(n),o=n.replace(/\*/g,"").length,s=r.length*1e4+o;if(t==null||t==="")return s;let a=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return o;let c=0,l=-1;for(let u of r){let p=-1;for(let g=c;g<a.length;g+=1)if(a[g]===u){p=g;break}if(p<0)return s;l=p,c=p+1}return(l+1)*1e6+r.length*1e4+o}i(Nn,"patternSpecificity");function fe(e,t){let n=String(e).split(/[/\\]/).join("/"),r,o=-1;for(let s of t??[])if(!(s.exclude??[]).some(a=>ke(a).test(n))){for(let a of s.patterns??[])if(ke(a).test(n)){let c=Nn(a,n);c>o&&(o=c,r=s.name)}}return r}i(fe,"layerForRelativePath");function $t(e,t,n){if(!t?.length)return;let r=n==="stars"?"stars":"path",o=String(e).split(/[/\\]/).filter(Boolean);if(o.length===0)return;let s=new Set;for(let a of t)if(!(typeof a!="string"||a.length===0)){if(us(a)){let c=ci(o,a,r);if(c)return c;continue}!a.includes("/")&&!a.includes("\\")&&!a.includes("*")&&s.add(a.toLowerCase())}return fi(o,s)}i($t,"sliceIdForPath");function us(e){let t=e.split(/[/\\]/).filter(n=>n.length>0);return t.length<2||t[0]==="*"||t[0]==="**"?!1:t.some(n=>n==="*")}i(us,"isAnchoredSliceEntry");function ci(e,t,n){let r=t.split(/[/\\]/).filter(s=>s.length>0).map(s=>s.toLowerCase()),o=gs(e,r[0]??"");for(let s of o){let a=di(e,r,s,n);if(a)return a}}i(ci,"anchoredSliceId");function di(e,t,n,r="path"){let o=[],s=-1,a=n;for(let c=0;c<t.length;c+=1){let l=t[c];if(l==="*"){if(a>=e.length-1){for(let u=c;u<t.length;u+=1)if(t[u]!=="*")return;break}o.push(e[a].toLowerCase()),a+=1;continue}if(l==="**"||a>=e.length||e[a].toLowerCase()!==l)return;o.push(e[a].toLowerCase()),s=o.length-1,a+=1}if(o.length!==0)return r==="stars"?s<0?void 0:o.slice(s).join("/"):o.join("/")}i(di,"bindAnchoredSlice");function ps(e){let t=[];for(let n of e??[]){if(!n||n.sliceIdentity!=="stars")continue;let r=new Map,o=new Map;for(let s of n.sliceFolders??[]){if(typeof s!="string"||s.length===0)continue;let a=ui(s);if(!a)continue;let c=s.split(/[/\\]/).filter(p=>p.length>0).join("/").toLowerCase(),l=o.get(a)??new Set;if(l.has(c))continue;l.add(c),o.set(a,l);let u=r.get(a)??[];u.push(s),r.set(a,u)}for(let[s,a]of r)a.length<2||t.push({from:n.from,to:n.to,stem:s,paths:a,message:pi(n.from,n.to,a,s)})}return t}i(ps,"sliceIdentityCollisions");function ui(e){if(!us(e))return;let t=e.split(/[/\\]/).filter(o=>o.length>0).map(o=>o.toLowerCase()),n=-1;for(let o=0;o<t.length;o+=1){let s=t[o]??"";if(s==="**")return;s!=="*"&&(n=o)}if(n<0)return;let r=t.slice(n);if(!r.some((o,s)=>s>0&&o!=="*"))return r.join("/")}i(ui,"starsIdentityStem");function pi(e,t,n,r){let o=n.length===2?`${n[0]} and ${n[1]}`:`${n.slice(0,-1).join(", ")}, and ${n[n.length-1]}`;return`${e} \u2192 ${t}: sliceIdentity "stars" gives one slice id to ${o}. They bind as ${r}.`}i(pi,"formatSliceIdentityCollision");function fi(e,t){if(t.size!==0){for(let n=0;n<e.length-1;n+=1)if(t.has(e[n].toLowerCase())&&!(n+1>=e.length-1))return`${e[n].toLowerCase()}/${e[n+1].toLowerCase()}`}}i(fi,"bareSliceId");function mi(e){let t=new Set;for(let n of e??[]){let o=Ht(String(n)).split("/").filter(Boolean);for(let s=0;s<o.length;s+=1){let a=o[s];if((a==="**"||a==="*")&&s>0){let c=o[s-1];c&&!c.includes("*")&&!c.includes("{")&&!c.includes("}")&&t.add(c)}}}return[...t]}i(mi,"inferSliceFoldersFromPatterns");function fs(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(o=>typeof o=="string"&&o.length>0);let r=(n??[]).find(o=>o.name===t);return mi(r?.patterns)}i(fs,"resolveSliceFolders");function cs(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}i(cs,"normalizeSegments");function ms(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}i(ms,"trimTrailingSlashes");var gi=["src","app"];function gs(e,t){let n=(e[0]??"").toLowerCase(),r=t.toLowerCase();return gi.includes(n)&&r!==n?[0,1]:[0]}i(gs,"anchorOffsets");function yi(e){let t=ms(e.replace(/^[./]+/,""));return t==="*"||t==="**"}i(yi,"isBlanketRoot");function Tn(e,t){if(!e||!t?.length)return!1;let n=String(e).split(/[/\\]/).join("/"),r=n.toLowerCase(),o=cs(n);for(let s of t){if(typeof s!="string"||s.length===0||yi(s))continue;if(s.includes("*")){let l=ms(s.toLowerCase());if(ke(l).test(r)||ke(`${l}/**`).test(r))return!0;continue}let a=cs(s);if(a.length===0)continue;let c=gs(o,a[0]??"");for(let l of c){if(l+a.length>o.length)continue;let u=!0;for(let p=0;p<a.length;p+=1)if(o[l+p]!==a[p]){u=!1;break}if(u)return!0}}return!1}i(Tn,"pathUnderSharedRoot");function ds(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(ds,"sliceMatchesDeclaration");function hi(e,t,n){return!e?.length||!t||!n?!1:e.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&ds(r.from,t)&&ds(r.to,n))}i(hi,"crossSliceEdgeAllowed");function Ai(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.sharedImportsSlice==="deny"&&e.fromShared===!0&&e.toSlice&&!e.fromSlice?{denied:!0,reason:"shared-imports-slice"}:!e.fromSlice||!e.toSlice?{denied:!1}:e.fromSlice===e.toSlice?{denied:!1}:e.crossSliceAllowed?{denied:!1}:{denied:!0,reason:"cross-slice"}}i(Ai,"peerIsolationDecision");function Ke(e,t){switch(e){case"cross-slice":return`cross-slice edge ${t.fromSlice??"?"} \u2192 ${t.toSlice??"?"}. Extract the shared code, use events/ports across slices, or declare the edge in the rule's allowedCrossSlice.`;case"shared-imports-slice":return`shared root imports slice ${t.toSlice??"?"} (${t.fromPath??"?"} \u2192 ${t.toPath??"?"}). The wall is direct-only.`;case"unclassifiable-path":{let n=[t.fromSlice?void 0:t.fromPath,t.toSlice?void 0:t.toPath].filter(o=>!!o);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(Ke,"peerIsolationDenyExplanation");function jt(e,t,n,r){return Te(e,t,n,r)?.rule}i(jt,"findDeniedEdgeRule");function Te(e,t,n,r){for(let o of e??[])if(!(o.from!==t||o.to!==n)&&o.allowed===!1){if(o.peerIsolation){let s=r?.fromPath,a=r?.toPath,c=fs(o,t,r?.layers),l=s?$t(s,c,o.sliceIdentity):void 0,u=a?$t(a,c,o.sliceIdentity):void 0,p=Ai({fromPath:s,toPath:a,folderCount:c.length,fromSlice:l,toSlice:u,fromShared:!l&&Tn(s,o.sharedRoots),toShared:!u&&Tn(a,o.sharedRoots),crossSliceAllowed:hi(o.allowedCrossSlice,l,u),sharedImportsSlice:o.sharedImportsSlice});if(p.denied)return{rule:o,peerIsolationReason:p.reason,fromSlice:l,toSlice:u};continue}if(t!==n)return{rule:o}}}i(Te,"findDeniedEdgeDecision");function ys(e,t,n,r){let o=r?.fromPath,s=r?.toPath;if(!(!o||!s))for(let a of e??[]){if(a.from!==t||a.to!==n||a.allowed!==!1||!a.peerIsolation||a.sharedImportsSlice==="deny")continue;let c=fs(a,t,r?.layers),l=$t(o,c,a.sliceIdentity),u=$t(s,c,a.sliceIdentity);if(!(l||!u)&&Tn(o,a.sharedRoots))return{fromPath:o,toPath:s,toSlice:u}}}i(ys,"findSharedImportsSliceBridge");function Ve(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(Ve,"literalText");function Rs(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}i(Rs,"lineOf");function hs(e,t){if(e.isImportDeclaration(t)){let r=t.importClause;if(!r)return!1;if(r.isTypeOnly)return!0;let o=r.namedBindings;return!!(o&&e.isNamedImports(o)&&o.elements.length>0&&o.elements.every(s=>s.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(hs,"isTypeOnlyReference");function ks(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=o=>o===t.fileName?t:void 0,r.fileExists=o=>o===t.fileName,r.readFile=o=>o===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}i(ks,"singleFileChecker");function wn(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}i(wn,"symbolAt");function Pn(e,t,n,r){let o=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,s;try{s=o?t.getShorthandAssignmentValueSymbol(r.parent):wn(t,r)}catch{s=void 0}return!!s?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}i(Pn,"localDeclaration");function Ue(e,t){let n,r=[],o=i((a,c,l,u=!1)=>r.push({specifier:l,kind:c,line:Rs(t,a),typeOnly:u,unresolved:l===void 0,node:a}),"add"),s=i(a=>{if(e.isImportDeclaration(a))o(a,"import",Ve(e,a.moduleSpecifier),hs(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)o(a,"export",Ve(e,a.moduleSpecifier),hs(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))o(a,"require",Ve(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let c=a.expression.kind===e.SyntaxKind.ImportKeyword,u=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!Pn(e,n??(n=ks(e,t)),t,a.expression);(c||u)&&o(a,u?"require":"dynamic-import",Ve(e,a.arguments[0]))}e.forEachChild(a,s)},"visit");return s(t),r}i(Ue,"extractSemanticDependencies");function Ri(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let o=Ve(e,r.argumentExpression);if(o===void 0)return;n.unshift(o)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}i(Ri,"staticAccessPath");function ki(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(ki,"runtimeIdentifierReference");function As(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let r=n.length;r>=1;r-=1){let o=n.slice(0,r).join(".");if(e.has(o))return o}}i(As,"bestForbiddenMatch");function Ge(e,t,n){if(n.length===0)return[];let r=new Set(n),o=ks(e,t),s=new Map,a=new Set;for(let f of t.statements)if(e.isVariableStatement(f))for(let m of f.declarationList.declarations)e.isIdentifier(m.name)&&a.add(m.name.text);let c=i(f=>{let m=Ri(e,f);if(!m)return;let d=wn(o,m.root),y=d?s.get(d):void 0;return y?[...y,...m.segments.slice(1)]:Pn(e,o,t,m.root)||a.has(m.root.text)?void 0:m.segments},"resolvePath");for(let f of t.statements)if(e.isVariableStatement(f))for(let m of f.declarationList.declarations){if(!m.initializer||!e.isIdentifier(m.name))continue;let d=c(m.initializer),y=wn(o,m.name);!d||!y||s.set(y,d)}let l=[],u=new Set,p=i((f,m)=>{let d=Rs(t,m),y=`${f}:${m.getStart(t)}`;u.has(y)||(u.add(y),l.push({name:f,line:d,node:m}))},"flag"),g=i(f=>{let m=f.parent&&(e.isPropertyAccessExpression(f.parent)||e.isElementAccessExpression(f.parent))&&f.parent.expression===f;if((e.isPropertyAccessExpression(f)||e.isElementAccessExpression(f))&&!m){let d=c(f),y=d?As(r,d):void 0;y&&p(y,f)}else e.isIdentifier(f)&&r.has(f.text)&&ki(e,f)&&!Pn(e,o,t,f)&&p(f.text,f);if(e.isVariableDeclaration(f)&&e.isObjectBindingPattern(f.name)&&f.initializer){let d=c(f.initializer);if(d)for(let y of f.name.elements){if(!e.isIdentifier(y.name))continue;let b=y.propertyName?Ve(e,y.propertyName)??y.propertyName.text:y.name.text,x=As(r,[...d,b]);x&&p(x,f.initializer)}}e.forEachChild(f,g)},"visit");return g(t),l}i(Ge,"collectForbiddenCapabilityUses");function Ln(e,t,n){let r=[];for(let o of n?.dependencies??Ue(e,t)){if(o.typeOnly||!o.specifier)continue;let s=st(o.specifier);s&&r.push({capability:s,symbol:o.specifier,line:o.line,source:"import-based"})}for(let o of n?.ambientUses??Ge(e,t,xn)){let s=Mt(o.name);s&&r.push({capability:s,symbol:o.name,line:o.line,source:"ambient-global"})}return r.sort((o,s)=>o.line-s.line||o.capability.localeCompare(s.capability)||o.symbol.localeCompare(s.symbol))}i(Ln,"collectCapabilityUses");var Dn={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."},Mn=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 Fn(e,t){return t.flatMap((r,o)=>(r.prefixes??r.intentPrefixes??[]).map(s=>({layer:r.name,layerIndex:o,prefix:s.endsWith(".")?s:`${s}.`}))).filter(({prefix:r})=>e.startsWith(r)).sort((r,o)=>o.prefix.length-r.prefix.length||r.layerIndex-o.layerIndex)[0]?.layer}i(Fn,"resolveIntentLayer");function Ne(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}i(Ne,"looksLikeArkIntent");function at(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&Ne(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:Dn.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:Dn.PUBLISH_MISSING_SOURCE}),t}i(at,"classifyPublishFacts");function Y(e,t,n){return{ruleId:e,code:e,message:t,...n}}i(Y,"violation");function Be(e,t){return e.slice(0,t).split(`
2
- `).length}i(Be,"lineOf");var Si=new Set(["publish","subscribe","defineIntent","registerHandler"]);function Ii(e,t){return e.index+e[0].indexOf(t)}i(Ii,"captureIndex");function Ei(e){let t=[],n=new Set,r=i((c,l)=>{!c||n.has(l)||(n.add(l),t.push({value:c,index:l}))},"push"),o=i(c=>{c.lastIndex=0;let l;for(;(l=c.exec(e))!==null;){let u=l[1];u&&r(u,Ii(l,u))}},"pushFrom");o(/\b(?:publish|subscribe|defineIntent|registerHandler)\s{0,8}(?:<[^>]{0,120}>)?\s{0,8}\(\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),o(/\b(?:intent|onEvent)\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g);let s=/\breactsTo\s{0,8}:\s{0,8}\[([^\]]{0,2000})\]/g,a;for(;(a=s.exec(e))!==null;){let c=a[1]??"",l=a.index+a[0].indexOf(c),u=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,p;for(;(p=u.exec(c))!==null;){let g=p[1];g&&r(g,l+p.index+p[0].indexOf(g))}}return o(/\bmetadata\s{0,8}:\s{0,8}\{[^}]{0,400}\bsource\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),o(/\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((c,l)=>c.index-l.index)}i(Ei,"extractQuotedStrings");function bi(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 o;for(;(o=r.re.exec(e))!==null;){let s=o.index+o[0].indexOf(o[1]),a=o[0],c=r.kind==="import"&&/\bimport\s+type\b/.test(a)||r.kind==="export"&&/\bexport\s+type\b/.test(a);t.push({value:o[1],index:s,kind:r.kind,typeOnly:c})}}return t.sort((r,o)=>r.index-o.index)}i(bi,"extractModuleSpecifiers");function vi(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(vi,"isSyntaxWrapper");function $n(e,t){let n=t;for(;n?.parent&&vi(e,n.parent);)n=n.parent;return n}i($n,"unwrapWrappers");function Hn(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(Hn,"callCalleeName");function Ci(e,t){let n=t.parent;if(!n||!e.isObjectLiteralExpression(n))return!1;let r=$n(e,n),o=r.parent;if(!o)return!1;if(e.isCallExpression(o)&&Hn(e,o)==="publish"){let s=o.arguments;return s[1]===r||s[2]===r}if(e.isPropertyAssignment(o)&&jn(e,o.name)==="metadata"){let s=o.parent;if(!s)return!1;let c=$n(e,s).parent;return!!(c&&e.isCallExpression(c)&&Hn(e,c)==="publish")}return!1}i(Ci,"isPublishMetadataSource");function Ss(e,t){let n=$n(e,t),r=n.parent;if(!r)return!1;if(e.isCallExpression(r)){let o=Hn(e,r);if(o&&Si.has(o)&&r.arguments.some(s=>s===n))return!0}if(e.isArrayLiteralExpression(r))return Ss(e,r);if(e.isPropertyAssignment(r)){let o=jn(e,r.name);if(o==="intent"||o==="onEvent"||o==="reactsTo"||o==="source"&&Ci(e,r))return!0}return!1}i(Ss,"isDeclaredIntentSite");function _i(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],o=i(s=>{e.isStringLiteralLike(s)&&Ss(e,s)&&r.push({value:s.text,index:s.getStart(n)}),e.forEachChild(s,o)},"visit");return o(n),r}i(_i,"extractQuotedStringsAst");function Oi(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(Oi,"hasInfrastructureToken");function xi(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}i(xi,"isKnownInfrastructurePackage");function Ti(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}i(Ti,"layerHasInfrastructureRole");function lt(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(lt,"tsStringLiteralText");function jn(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}i(jn,"tsPropertyName");function Is(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:jn(e,r.name)===n)}i(Is,"tsObjectProperty");function ct(e,t,n){return Is(e,t,n)!==void 0}i(ct,"tsObjectHasProperty");function it(e,t,n){let r=Is(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}i(it,"tsObjectPropertyValue");function Ni(e,t){let n=it(e,t,"metadata");return ct(e,n,"source")}i(Ni,"tsObjectHasMetadataSource");function Es(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?Es(e,t.name):!1:!1}i(Es,"tsLooksLikeIntentCreatorExpression");function wi(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(wi,"tsIsPublishCall");function Pi(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=lt(e,n);return r!==void 0&&Ne(r)||ct(e,n,"intent")||Es(e,n)}i(Pi,"tsIsArkPublishCandidate");function Li(e,t){if(!e.isCallExpression(t))return!1;let[n,r,o]=t.arguments;return Ni(e,n)||ct(e,r,"source")||ct(e,o,"source")}i(Li,"tsPublishHasSource");function Di(e,t){if(!e.isCallExpression(t))return;let[n,r,o]=t.arguments,s=it(e,n,"metadata");return lt(e,it(e,s,"source"))??lt(e,it(e,r,"source"))??lt(e,it(e,o,"source"))}i(Di,"tsPublishSourceLiteral");function Mi(e,t,n,r){let o=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),s=n,a=s?.filePath,c=s?.layer,l=[],u=i(g=>o.getLineAndCharacterOfPosition(g.getStart(o)).line+1,"lineForNode"),p=i(g=>{if(wi(e,g)){let f=g.arguments[0],m=lt(e,f);for(let y of at({publishCall:!0,rawIntentName:m,objectHasIntent:ct(e,f,"intent"),arkPublishCandidate:Pi(e,g),hasSource:Li(e,g)}))l.push(Y(y.ruleId,y.message,{line:u(g),filePath:a}));let d=Di(e,g);if(r&&c&&d&&Ne(d)){let y=r.resolveLayer(d);y&&y!==c&&l.push(Y("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${d}" resolves to ${y}, but the target file is classified as ${c}.`,{line:u(g),filePath:a,target:d,fromLayer:c,toLayer:y}))}}e.forEachChild(g,p)},"visit");return p(o),l}i(Mi,"analyzePublishAst");function bs(e={}){let t=new Set((e.intents||[]).map(s=>typeof s=="string"?s:s.name)),n=e.forbiddenPatterns||[],r=new Set(e.infrastructureLayers??[]),o=e.enforceIntentAllowlist??t.size>0;return{validate(s,a){let c=[],l=a,u=l?.filePath,p=l?.layer,g=e.typescript,f=g?g.createSourceFile(u??"generated.ts",s,g.ScriptTarget.Latest,!0):void 0,m=f?Ue(e.typescript,f):void 0,d=m?m.filter(S=>S.specifier!==void 0).map(S=>({value:S.specifier,index:S.node.getStart(f),kind:S.kind,typeOnly:S.typeOnly})):bi(s),y=e.typescript?_i(e.typescript,s):Ei(s);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(u))for(let S of m?.filter(({unresolved:E})=>E)??[]){let E=S.kind==="require";c.push(Y(E?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${E?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:S.line,filePath:u}))}let b=p!==void 0&&(r.has(p)||Ti(p)),x=p!==void 0?` If "${p}" 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 S of n)if(S instanceof RegExp){S.lastIndex=0;let E=S.exec(s);S.lastIndex=0,E&&c.push(Y("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${S}`,{line:E.index===void 0?void 0:Be(s,E.index),filePath:u,suggestion:"Remove infrastructure imports from domain/application layers."+x}))}else s.includes(S)&&c.push(Y("FORBIDDEN_SUBSTRING",`Forbidden substring: ${S}`,{line:Be(s,s.indexOf(S)),filePath:u}));for(let S of d){let E=e.resolveImportTarget?.(S.value,u)??(e.resolveImportLayer?{layer:e.resolveImportLayer(S.value,u)}:void 0),C=typeof u=="string"?e.resolveImportTarget?.(u)??(e.resolveImportLayer?{layer:p,relPath:void 0}:void 0):void 0,D=E?.layer;if(D&&p){let k=jt(e.architectureProfile?.rules,p,D,{fromPath:C?.relPath,toPath:E?.relPath,layers:e.architectureLayers});if(k){if(S.typeOnly&&!k.peerIsolation)continue;let P=!!k.peerIsolation;c.push(Y("LAYER_IMPORT_VIOLATION",k.message??(P?`Layer "${p}" must not import across slices into "${D}".`:`Layer "${p}" must not import "${D}".`),{line:Be(s,S.index),source:S.value,target:S.value,filePath:u,fromLayer:p,toLayer:D,suggestion:P?"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:S.kind,peerIsolation:P,...S.typeOnly?{typeOnly:!0}:{}}}));continue}continue}b||S.typeOnly||!Oi(S.value)&&!xi(S.value)||c.push(Y("FORBIDDEN_IMPORT",`Forbidden ${S.kind} target: "${S.value}".`,{line:Be(s,S.index),source:S.value,target:S.value,filePath:u,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+x,details:{importKind:S.kind}}))}if(e.policies)for(let S of e.policies){let E=S.check({source:s,context:a});if(E!==!0)if(Array.isArray(E))for(let C of E)c.push(Y("POLICY_VIOLATION",C.message,{filePath:u,suggestion:`Fix violation of policy "${S.name}".`}));else E===!1?c.push(Y("POLICY_VIOLATION",`Policy ${S.name} failed on generated code`)):c.push(Y("POLICY_VIOLATION",E.message))}if(o&&t.size>0)for(let S of y)Ne(S.value)&&!t.has(S.value)&&c.push(Y("UNKNOWN_INTENT",`Unknown intent reference: "${S.value}"`,{line:Be(s,S.index),filePath:u,target:S.value,suggestion:`Register intent "${S.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&p)for(let S of y){if(!Ne(S.value))continue;let E=e.architectureProfile.resolveLayer(S.value);if(!E)continue;let C=Te(e.architectureProfile.rules,p,E,{fromPath:typeof u=="string"?u:void 0,layers:e.architectureLayers});if(C){let D=C.rule.peerIsolation?Ke(C.peerIsolationReason??"cross-slice",{fromPath:typeof u=="string"?u:void 0,fromSlice:C.fromSlice,toSlice:C.toSlice}):void 0,k=`Layer "${p}" must not reference "${E}" through "${S.value}".`,P=D&&C.peerIsolationReason!=="cross-slice"?`${k} ${D}`:C.rule.message?D?`${C.rule.message} (${D})`:C.rule.message:k;c.push(Y("LAYER_REFERENCE_VIOLATION",P,{line:Be(s,S.index),filePath:u,target:S.value,fromLayer:p,toLayer:E,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:C.rule,peerIsolationReason:C.peerIsolationReason}}))}}if(e.extensions)for(let S of e.extensions)try{let E=S.analyze(s,a);c.push(...E)}catch(E){c.push(Y("EXTENSION_ERROR",`Extension "${S.name}" failed: ${E instanceof Error?E.message:String(E)}`))}if(e.typescript&&f&&p&&e.forbiddenGlobals?.[p]?.length)try{let S=e.forbiddenGlobals[p];c.push(...Ge(e.typescript,f,S).map(E=>Y("FORBIDDEN_GLOBAL",`${p} must not use the ambient global "${E.name}".`,{line:E.line,filePath:u,target:E.name,fromLayer:p,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let E of m??[]){if(E.typeOnly||!E.specifier)continue;let C=Ce(E.specifier,S);C&&c.push(Y("FORBIDDEN_GLOBAL",`${p} must not use module "${E.specifier}" because it is the import form of forbidden global "${C}".`,{line:E.line,filePath:u,source:E.specifier,target:E.specifier,fromLayer:p,details:{importKind:E.kind,forbiddenGlobal:C},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(S){c.push(Y("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${S instanceof Error?S.message:String(S)}`))}if(e.typescript&&f&&p&&e.capabilityWalls?.[p]?.length)try{let S=new Set(e.capabilityWalls[p]),E=e.forbiddenGlobals?.[p]??[];for(let C of Ln(e.typescript,f))S.has(C.capability)&&(C.source==="ambient-global"&&ot(C.symbol,E)||C.source==="import-based"&&Ce(C.symbol,E)||c.push(Y("CAPABILITY_VIOLATION",C.source==="import-based"?`${p} denies the ${C.capability} capability; found import of "${C.symbol}".`:`${p} denies the ${C.capability} capability; found ambient "${C.symbol}".`,{line:C.line,filePath:u,target:C.symbol,capability:C.capability,fromLayer:p,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(S){c.push(Y("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${S instanceof Error?S.message:String(S)}`))}if(e.typescript)try{c.push(...Mi(e.typescript,s,a,e.architectureProfile))}catch(S){c.push(Y("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${S instanceof Error?S.message:String(S)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:c.length===0,violations:c}}}}i(bs,"createAICodeGate");var we={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},vs={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...we,default:[]},kernelRoots:{...we},managedLayers:{...we,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},Cs={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...we,default:[]},managedLayers:{...we,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...we,default:[]},appliesTo:{...we,default:[]}}};function dt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(dt,"isObject");function _s(e){let t=new Set;if(!Array.isArray(e.layers))return t;for(let n of e.layers)dt(n)&&typeof n.name=="string"&&n.name.length>0&&t.add(n.name);return t}i(_s,"declaredLayerNames");function Os(e){if(!dt(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(Os,"defaultedArkRun");function xs(e){if(!dt(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(xs,"defaultedArkOrder");function Ts(e,t){let n=e.arkRun;if(n===void 0||!dt(n))return;let r=_s(e),o=n.managedLayers;if(Array.isArray(o)&&o.forEach((s,a)=>{typeof s=="string"&&s.length>0&&!r.has(s)&&t.push({path:`$.arkRun.managedLayers[${a}]`,message:`layer ${JSON.stringify(s)} is not declared in layers[]`})}),n.mode==="enforced"){let s=n.kernelRoots??n.compositionRoots;(!Array.isArray(s)||s.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(o)||o.length===0)&&t.push({path:"$.arkRun.managedLayers",message:"enforced mode requires at least one managed layer"})}}i(Ts,"validateArkRunExtra");function Ns(e,t){let n=e.arkOrder;if(n===void 0||!dt(n))return;let r=_s(e),o=n.managedLayers;if(Array.isArray(o)&&o.forEach((s,a)=>{typeof s=="string"&&s.length>0&&!r.has(s)&&t.push({path:`$.arkOrder.managedLayers[${a}]`,message:`layer ${JSON.stringify(s)} is not declared in layers[]`})}),n.mode==="enforced"){let s=n.planeRoots;(!Array.isArray(s)||s.length===0)&&t.push({path:"$.arkOrder.planeRoots",message:"ARKORDER_MISSING_PLANE: enforced mode requires at least one plane root"}),(!Array.isArray(o)||o.length===0)&&t.push({path:"$.arkOrder.managedLayers",message:"enforced mode requires at least one managed layer"})}}i(Ns,"validateArkOrderExtra");function Kt(e){if(typeof e!="string")return null;let t=e.trim().replace(/^@/,"").toLowerCase();return t.length>0?t:null}i(Kt,"normalizeStewardId");function ws(e){let t=Kt(e);return!t||Kn(t)||t.includes(" ")||t.includes("@")?!1:/^(?!-)[a-z0-9-]{1,39}(?<!-)$/.test(t)}i(ws,"isGitHubHandle");function Fi(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();return!t.includes("@")||t.includes(" ")||Kn(t)?!1:/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}i(Fi,"isGitHubEmail");function $i(e){if(typeof e!="string")return null;let t=e.trim().match(/^(?:\d+\+)?([^@]+)@users\.noreply\.github\.com$/i);return t&&ws(t[1])?Kt(t[1]):null}i($i,"githubHandleFromEmail");function Ps(e){let t=$i(e);if(t)return t;let n=Kt(e);return!n||Kn(n)?null:ws(n)||Fi(n)?n:null}i(Ps,"canonicalStewardId");var Hi=/bot\b|\[bot\]|dependabot|renovate|github-actions|imgbot|codecov/i;function Kn(e){let t=Kt(e);return!t||Hi.test(t)}i(Kn,"isAutomationAuthor");var ie="1.3",ji=["public","auth","admin","internal"];function Ki(e){return e?.optional===!0||e?.reserved===!0||e?.allowEmpty===!0}i(Ki,"isFutureHouseLayer");function Vi(e){let t=e&&typeof e=="object"?e.owners:void 0;if(!Array.isArray(t)||t.length===0)return;let n=t.filter(r=>typeof r=="string"&&r.length>0);return n.length>0?n:void 0}i(Vi,"layerOwnersList");function Ds(e){return e?.requireLayerOwners!==!0||!Array.isArray(e.layers)?[]:e.layers.filter(t=>!Ki(t)&&!Vi(t)).map(t=>t.name)}i(Ds,"layersMissingRequiredOwners");function Ms(e){return`Add a GitHub handle or email to ${e}'s owners in ark.config.json (/ark-adopt).`}i(Ms,"missingLayerOwnersNextAction");var Ut="https://unpkg.com/arkgate@4/schemas/ark.config.schema.json",Ls=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Ui=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Gi(){let e=[];for(let t of Ls)for(let n of Ls)t===n||Ui.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}i(Gi,"createDefaultRules");var Gt=Gi(),Vn=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"},{from:"1.1",to:"1.2"},{from:"1.2",to:"1.3"}],ae={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Un={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Ut,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:Ut,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:ie,default:ie},name:{type:"string",minLength:1},include:{...ae,minItems:1,default:["src"]},exclude:{...ae,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:Gt,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...ae,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:{...ae,default:[]},requireLayerOwners:{type:"boolean"}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...ae,minItems:1},exclude:ae,intentPrefixes:ae,description:{type:"string",minLength:1},trustBoundary:{type:"string",enum:[...ji]},owners:{...ae,minItems:1},forbiddenGlobals:ae,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:{...ae,minItems:1},sliceIdentity:{type:"string",enum:["path","stars"],description:"How a starred sliceFolders prefix is named. Absent and path keep today's ids (every literal and star binding). stars keeps the last literal plus the star bindings, so parallel trees share one feature id. Bare names are unchanged."},sharedRoots:{...ae,minItems:1},allowedCrossSlice:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}},sharedImportsSlice:{type:"string",enum:["deny"]}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}},coverage:{type:"object",additionalProperties:!1,description:"Invariant coverage scan controls. testGlobs replaces the built-in test-name heuristic; maxFiles raises or lowers the evidence file budget and also bounds structural-hint preload for orchestration-only, thin-adapter, and writes-via-aggregate (default 400; there is no arkrules.hintBudget); coverageRoots declares where the project runs its tests, so a covering test found outside them is reported instead of silently certifying an invariant. When any invariant is enforced, missing coverageRoots fails closed.",properties:{testGlobs:{...ae,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:{...ae,minItems:1}}},arkRun:vs,arkOrder:Cs}},Se=class extends Error{static{i(this,"ArkConfigValidationError")}issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
1
+ var Ia=Object.defineProperty;var a=(e,t)=>Ia(e,"name",{value:t,configurable:!0});var Ea="4.8.23";var ba=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,va=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,Ca=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function _a(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),o=String(t?.toLayer??"");return ba.test(n)?"pure-shared":r==="PersistenceAdapters"&&(va.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${o} ${n}`))?"kernel-emit":Ca.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&o==="PersistenceAdapters"?"use-case":"unknown"}a(_a,"classifyLayerImportKind");function Oa(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=_a(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."}a(Oa,"layerImportNextAction");function xa(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}a(xa,"arkRunCallSiteName");function Ta(e){let t=xa(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.`}}a(Ta,"arkRunNextAction");function ye(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return Oa(e);case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, test at the public interface, then preflight again.`;case"CAPABILITY_VIOLATION":return`Define a ${String(e.capability??"capability")} port in ${e.fromLayer??"the walled layer"}, bind the implementation outside it, test at the public interface, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, test at the public interface, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"LITERAL_PATH_DRIFT":return typeof e.target=="string"&&e.target.length>0?`Rewrite the literal to ${e.target}, or run \`arkgate-check --path-drift --base-ref <ref> --write\` to apply every anchored replacement.`:"Rewrite the literal to the rename destination, or run `arkgate-check --path-drift --base-ref <ref> --write` to apply every anchored replacement.";case"LITERAL_PATH_UNRESOLVED":return"Read the candidate and decide: fix the path, or leave it. Advisory \u2014 with no rename to anchor it there is no destination to propose, so --write never touches it.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";case"INVARIANT_COVERAGE_OUTSIDE_ROOTS":return"Move the covering test under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json, then run Ark again.";case"INVARIANT_CATALOG_EMPTY":return typeof e.file=="string"&&e.file.length>0?`Add 1\u20132 short phrases to invariants[] in ${e.file}, then run ark-check --doctor. Starters show the shape.`:"Add 1\u20132 short phrases to invariants[] in arkrules/<Domain>.json, then run ark-check --doctor. Starters show the shape.";case"INVARIANT_TESTS_PATH_MISSING":return"Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present.";case"INVARIANT_COVERAGE_ROOTS_MISSING":return"Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. An enforced invariant fails closed until that path is present.";case"ARKRULE_STRUCTURE":case"ARKRULE_INVARIANT":case"INVARIANT_UNCOVERED":return`Fix the structure or invariant for ${typeof e.arkruleId=="string"&&e.arkruleId.length>0?e.arkruleId:"the ArkRule"} (declared in ${typeof e.arkruleSource=="string"&&e.arkruleSource.length>0?e.arkruleSource:"arkrules/<Layer>.json"}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`;case"ARKRUN_MISSING_ROOT":case"ARKRUN_KERNEL_IN_DOMAIN":case"ARKRUN_DIRECT_NEW":case"ARKRUN_UNDECLARED_EMIT":case"ARKRUN_UNDECLARED_HANDLE":case"ARKRUN_UNDECLARED_DEPEND":case"ARKRUN_TRANSPORT_BYPASS":return 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"Don't use a generic update. First freeze with release(). Later, propose the change, then apply it.";case"ARKORDER_TOO_MANY_PARAMS":return"Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe.";case"ARKORDER_INGEST_WRITES_XI":return"Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe.";case"ARKORDER_XI_FIELD_WRITE":return typeof e.target=="string"&&e.target.length>0?`Don't write ${e.target} from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.`:"Don't write a named product choice from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.";case"ARKORDER_UNVALVED_RELEASE":return"Change the choice with proposeRelease then apply. release() is only the first freeze. Never mechanical-safe.";default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}a(ye,"deterministicNextAction");var Gt="1.5",Bt="docs/diagnostics.md",Ss={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","mode","valid","completeness","completenessReasons","diagnostics"],allOf:[{if:{properties:{completeness:{enum:["partial","unavailable"]}},required:["completeness"]},then:{properties:{valid:{const:!1}}}},{if:{properties:{mode:{const:"resolved-candidate-facts"},completeness:{enum:["complete","partial"]}},required:["mode","completeness"]},then:{required:["policyHash","resolverIdentity","factsHash","candidateTreeHash"]}},{if:{properties:{completeness:{const:"complete"}},required:["completeness"]},then:{properties:{completenessReasons:{maxItems:0}}},else:{properties:{completenessReasons:{minItems:1}}}}],properties:{schemaVersion:{const:"1.5"},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}}}}}};function ut(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,o=typeof e.toLayer=="string"?e.toLayer:void 0,s=typeof e.target=="string"?e.target:void 0;return[t,n,r??"",o??"",s??""].join("|")}a(ut,"adapterFindingTargetKey");function pt(e){let t=new Map;return e.map(n=>{let r=ut(n),o=(t.get(r)??0)+1;return t.set(r,o),o===1?r:`${r}#${o}`})}a(pt,"adapterFindingOccurrenceTargetKeys");function zt(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")}`}a(zt,"adapterFindingRefFromTargetKey");function Wt(e){return`${Bt}#${e}`}a(Wt,"adapterDocsCodePath");function w(e){return typeof e=="string"&&e.length>0?e:void 0}a(w,"text");function Is(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}a(Is,"positiveInteger");function wa(e,t,n){return ye({ruleId:e,target:w(t.target)??w(n.target)??void 0,fromLayer:w(t.fromLayer)??void 0,toLayer:w(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:w(t.edgeKind)??void 0,capability:w(t.capability)??w(n.capability)??void 0,arkruleId:w(t.arkruleId)??void 0,arkruleSource:w(t.arkruleSource)??void 0})}a(wa,"nextActionForDiagnostic");function Fn(e,t="error",n){let r=w(e.ruleId)??w(e.code)??"ARK_UNKNOWN",o=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,s={...w(e.target)?{target:w(e.target)}:{},...w(e.fromLayer)?{fromLayer:w(e.fromLayer)}:{},...w(e.toLayer)?{toLayer:w(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}:{},...w(e.capability)?{capability:w(e.capability)}:{},...w(e.edgeKind)?{edgeKind:w(e.edgeKind)}:{},...w(e.arkruleId)?{arkruleId:w(e.arkruleId)}:{},...w(e.arkruleSource)?{arkruleSource:w(e.arkruleSource)}:{}},i=n??ut(e),l=zt(i);return{ruleId:r,severity:o,message:w(e.message)??r,location:{file:w(e.file)??"<unknown>",line:Is(e.line,1),column:Is(e.column,1)},evidence:s,nextAction:w(e.nextAction)??wa(r,s,e),findingRef:l,targetKey:i,docsCodePath:Wt(r)}}a(Fn,"toAdapterDiagnostic");function Na(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(m=>({code:w(m.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:w(m.message)??`Analysis ${t}: required evidence is incomplete.`,...w(m.file)?{file:w(m.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],o={...w(e.policyHash)?{policyHash:w(e.policyHash)}:{},...w(e.resolverIdentity)?{resolverIdentity:w(e.resolverIdentity)}:{},...w(e.factsHash)?{factsHash:w(e.factsHash)}:{},...w(e.candidateTreeHash)?{candidateTreeHash:w(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let m of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!o[m])throw new Error(`${m} is required for resolved ${t} adapter evidence.`)}let s=e.violations??[],i=e.warnings??[],l=pt(s),c=pt(i),u=[...s.map((m,f)=>Fn(m,"error",l[f])),...i.map((m,f)=>Fn(m,"warning",c[f]))],p={schemaVersion:"1.5",completenessReasons:r,diagnostics:u};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...p,mode:n,valid:!1,completeness:t,...o};let m={policyHash:o.policyHash,resolverIdentity:o.resolverIdentity,factsHash:o.factsHash,candidateTreeHash:o.candidateTreeHash};return t==="complete"?{...p,mode:n,valid:e.valid,completeness:t,...m}:{...p,mode:n,valid:!1,completeness:t,...m}}return t==="complete"?{...p,mode:n,valid:e.valid,completeness:t,...o}:{...p,mode:n,valid:!1,completeness:t,...o}}a(Na,"createAdapterResult");var La="1.0",Es="https://unpkg.com/arkgate@4/schemas/ark.project-identity.schema.json",qt="^sha256:[a-f0-9]{64}$",bs={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:qt,description:"Project id previously returned by ark_identity or ark_manifest."}}},vs={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:qt},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},Pa={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Es,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:qt},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{type:"string",minLength:1},arkgateVersion:{type:"string",minLength:1},contractHash:{type:"string",pattern:qt},contractSource:{enum:["project","default-profile","manifest"]},runtimeId:{type:"string",minLength:1},processStartedAt:{type:"string",format:"date-time"}},$defs:{expectation:bs,binding:vs}};function Da(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}`}a(Da,"createProjectId");function Ma(e){return{schemaVersion:"1.0",...e}}a(Ma,"createProjectIdentity");var Hn=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),Vn=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Kn=Object.freeze(Object.keys(Vn).sort()),$n=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"}),jn=Object.freeze({process:Object.freeze(["process","node:process"])});function ft(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=$n[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),o=$n[r];if(o)return o;let s=e.indexOf("/",n+1);return s<0?null:$n[e.slice(0,s)]??null}a(ft,"capabilityForModuleSpecifier");function _e(e,t){for(let n of t)if(jn[n]?.includes(e))return n;return null}a(_e,"forbiddenGlobalForModuleSpecifier");function Yt(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),o=Vn[r];if(o)return o}return null}a(Yt,"capabilityForAmbientName");function Ge(e){if(e?.pure===!0)return[...Hn].sort();let n=(e?.capabilities?.deny??[]).filter(r=>Hn.includes(r));return[...new Set(n)].sort()}a(Ge,"effectiveCapabilityDeny");function gt(e,t){if(t.length===0)return!1;let n=new Set(t),r=e.split(".");for(let o=r.length;o>=1;o-=1)if(n.has(r.slice(0,o).join(".")))return!0;return!1}a(gt,"ambientCoveredByForbiddenGlobals");function Jt(e){let t=new Set,n=new Set,r=Object.keys(Vn);for(let o of e?.forbiddenGlobals??[]){let s=r.filter(i=>i===o||i.startsWith(`${o}.`));if(s.length===0)n.add(o);else for(let i of s)t.add(`ambient:${i}`);for(let i of jn[o]??[])t.add(`import-exact:${i}`)}for(let o of Ge(e)){if(t.add(`import:${o}`),o==="process")for(let s of jn.process)t.add(`import-exact:${s}`);for(let s of r)Yt(s)===o&&t.add(`ambient:${s}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}a(Jt,"loweredLayerCoverage");var Cs="4.8.22",_s=new Map;function Os(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(Os,"escapeLiteral");function Qt(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let o=e[n+1];if("*?{}[],".includes(o)||o==="\\"){t+="\\"+o,n+=1;continue}t+="/";continue}t+=r}return t}a(Qt,"normalizeGlobSeparators");function Fa(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}a(Fa,"bracesBalanced");function Ae(e){let t=_s.get(e);if(t)return t;let n=Qt(e),r=Fa(n),o="",s=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(o+=Os(n[l+1]),l+=1):c==="*"?n[l+1]==="*"?n[l+2]==="/"?(o+="(?:.*/)?",l+=2):(o+=".*",l+=1):o+="[^/]*":c==="?"?o+="[^/]":c==="{"&&r?(o+="(?:",s+=1):c==="}"&&r&&s>0?(o+=")",s-=1):c===","&&r&&s>0?o+="|":o+=Os(c)}let i=new RegExp(`^${o}$`);return _s.set(e,i),i}a(Ae,"globToRegExp");function $a(e){return Qt(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}a($a,"concreteGlobSegments");function Gn(e,t){let n=Qt(String(e)),r=$a(n),o=n.replace(/\*/g,"").length,s=r.length*1e4+o;if(t==null||t==="")return s;let i=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return o;let l=0,c=-1;for(let u of r){let p=-1;for(let m=l;m<i.length;m+=1)if(i[m]===u){p=m;break}if(p<0)return s;c=p,l=p+1}return(c+1)*1e6+r.length*1e4+o}a(Gn,"patternSpecificity");function ge(e,t){let n=String(e).split(/[/\\]/).join("/"),r,o=-1;for(let s of t??[])if(!(s.exclude??[]).some(i=>Ae(i).test(n))){for(let i of s.patterns??[])if(Ae(i).test(n)){let l=Gn(i,n);l>o&&(o=l,r=s.name)}}return r}a(ge,"layerForRelativePath");function Bn(e,t,n){if(!t?.length)return;let r=n==="stars"?"stars":"path",o=String(e).split(/[/\\]/).filter(Boolean);if(o.length===0)return;let s=new Set;for(let i of t)if(!(typeof i!="string"||i.length===0)){if(Ns(i)){let l=Ha(o,i,r);if(l)return l;continue}!i.includes("/")&&!i.includes("\\")&&!i.includes("*")&&s.add(i.toLowerCase())}return Ua(o,s)}a(Bn,"sliceIdForPath");function Ns(e){let t=e.split(/[/\\]/).filter(n=>n.length>0);return t.length<2||t[0]==="*"||t[0]==="**"?!1:t.some(n=>n==="*")}a(Ns,"isAnchoredSliceEntry");function Ha(e,t,n){let r=t.split(/[/\\]/).filter(s=>s.length>0).map(s=>s.toLowerCase()),o=Ps(e,r[0]??"");for(let s of o){let i=ja(e,r,s,n);if(i)return i}}a(Ha,"anchoredSliceId");function ja(e,t,n,r="path"){let o=[],s=-1,i=n;for(let l=0;l<t.length;l+=1){let c=t[l];if(c==="*"){if(i>=e.length-1){for(let u=l;u<t.length;u+=1)if(t[u]!=="*")return;break}o.push(e[i].toLowerCase()),i+=1;continue}if(c==="**"||i>=e.length||e[i].toLowerCase()!==c)return;o.push(e[i].toLowerCase()),s=o.length-1,i+=1}if(o.length!==0)return r==="stars"?s<0?void 0:o.slice(s).join("/"):o.join("/")}a(ja,"bindAnchoredSlice");function Ls(e){let t=[];for(let n of e??[]){if(!n||n.sliceIdentity!=="stars")continue;let r=new Map,o=new Map;for(let s of n.sliceFolders??[]){if(typeof s!="string"||s.length===0)continue;let i=Va(s);if(!i)continue;let l=s.split(/[/\\]/).filter(p=>p.length>0).join("/").toLowerCase(),c=o.get(i)??new Set;if(c.has(l))continue;c.add(l),o.set(i,c);let u=r.get(i)??[];u.push(s),r.set(i,u)}for(let[s,i]of r)i.length<2||t.push({from:n.from,to:n.to,stem:s,paths:i,message:Ka(n.from,n.to,i,s)})}return t}a(Ls,"sliceIdentityCollisions");function Va(e){if(!Ns(e))return;let t=e.split(/[/\\]/).filter(o=>o.length>0).map(o=>o.toLowerCase()),n=-1;for(let o=0;o<t.length;o+=1){let s=t[o]??"";if(s==="**")return;s!=="*"&&(n=o)}if(n<0)return;let r=t.slice(n);if(!r.some((o,s)=>s>0&&o!=="*"))return r.join("/")}a(Va,"starsIdentityStem");function Ka(e,t,n,r){let o=n.length===2?`${n[0]} and ${n[1]}`:`${n.slice(0,-1).join(", ")}, and ${n[n.length-1]}`;return`${e} \u2192 ${t}: sliceIdentity "stars" gives one slice id to ${o}. They bind as ${r}.`}a(Ka,"formatSliceIdentityCollision");function Ua(e,t){if(t.size!==0){for(let n=0;n<e.length-1;n+=1)if(t.has(e[n].toLowerCase())&&!(n+1>=e.length-1))return`${e[n].toLowerCase()}/${e[n+1].toLowerCase()}`}}a(Ua,"bareSliceId");function Ga(e){let t=new Set;for(let n of e??[]){let o=Qt(String(n)).split("/").filter(Boolean);for(let s=0;s<o.length;s+=1){let i=o[s];if((i==="**"||i==="*")&&s>0){let l=o[s-1];l&&!l.includes("*")&&!l.includes("{")&&!l.includes("}")&&t.add(l)}}}return[...t]}a(Ga,"inferSliceFoldersFromPatterns");function zn(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(o=>typeof o=="string"&&o.length>0);let r=(n??[]).find(o=>o.name===t);return Ga(r?.patterns)}a(zn,"resolveSliceFolders");function xs(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}a(xs,"normalizeSegments");function yt(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}a(yt,"trimTrailingSlashes");var Ba=["src","app"];function Ps(e,t){let n=(e[0]??"").toLowerCase(),r=t.toLowerCase();return Ba.includes(n)&&r!==n?[0,1]:[0]}a(Ps,"anchorOffsets");function za(e){let t=yt(e.replace(/^[./]+/,""));return t==="*"||t==="**"}a(za,"isBlanketRoot");function mt(e,t){if(!e||!t?.length)return!1;let n=String(e).split(/[/\\]/).join("/"),r=n.toLowerCase(),o=xs(n);for(let s of t){if(typeof s!="string"||s.length===0||za(s))continue;if(s.includes("*")){let c=yt(s.toLowerCase());if(Ae(c).test(r)||Ae(`${c}/**`).test(r))return!0;continue}let i=xs(s);if(i.length===0)continue;let l=Ps(o,i[0]??"");for(let c of l){if(c+i.length>o.length)continue;let u=!0;for(let p=0;p<i.length;p+=1)if(o[c+p]!==i[p]){u=!1;break}if(u)return!0}}return!1}a(mt,"pathUnderSharedRoot");function Ts(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}`)}a(Ts,"sliceMatchesDeclaration");function Wa(e,t,n){return!e?.length||!t||!n?!1:e.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&Ts(r.from,t)&&Ts(r.to,n))}a(Wa,"crossSliceEdgeAllowed");function qa(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.sharedImportsSlice==="deny"&&e.fromShared===!0&&e.toSlice&&!e.fromSlice?{denied:!0,reason:"shared-imports-slice"}:!e.fromSlice||!e.toSlice?{denied:!1}:e.fromSlice===e.toSlice?{denied:!1}:e.crossSliceAllowed?{denied:!1}:{denied:!0,reason:"cross-slice"}}a(qa,"peerIsolationDecision");function Ds(e){return yt(e.trim().replace(/\\/g,"/")).toLowerCase()}a(Ds,"aliasGlobPattern");function Ya(e,t){let n=Ds(e);if(!n||n==="*"||n==="**")return!1;let r=String(t).replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase(),o=Un(r),s=Ae(n);return s.test(r)||o!==r&&s.test(o)}a(Ya,"aliasGlobMatches");function Ja(e){let t=Ds(e).split("/").filter(Boolean);return t.length<2||t.some(n=>n.includes("*")||n==="."||n==="..")?null:{universeId:t.slice(0,-1).join("/"),childId:t.join("/")}}a(Ja,"splitAliasTarget");function Xa(e,t){for(let n of t.childSlices?.sliceAliases??[])if(!(!n||typeof n.from!="string"||typeof n.to!="string")&&Ya(n.from,e))return Ja(n.to);return null}a(Xa,"firstSliceAlias");function Be(e,t,n){if(!e)return{};let r=n??t.sliceFolders,o=Bn(e,r?[...r]:void 0,t.sliceIdentity),s=Xt(e,o,t.childSlices);if(o||s.childId||s.mismatched)return s.childId?{universeId:o,childId:s.childId}:{universeId:o};let i=Xa(e,t);return i?{universeId:i.universeId,childId:i.childId}:{}}a(Be,"resolveGovernedSlice");function Za(e,t){switch(e){case"cross-slice":return`cross-slice edge ${t.fromSlice??"?"} \u2192 ${t.toSlice??"?"}. Extract the shared code, use events/ports across slices, or declare the edge in the rule's allowedCrossSlice.`;case"shared-imports-slice":return`shared root imports slice ${t.toSlice??"?"} (${t.fromPath??"?"} \u2192 ${t.toPath??"?"}). The wall is direct-only.`;case"unclassifiable-path":{let n=[t.fromSlice?void 0:t.fromPath,t.toSlice?void 0:t.toPath].filter(o=>!!o);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."}}a(Za,"peerIsolationDenyExplanation");function Qa(e,t){return`cross-parent slice ${e??"?"} \u2192 ${t??"?"}. The child wall cannot allow another universe.`}a(Qa,"crossParentExplanation");function el(e,t,n){return`cross-sibling slice ${e} \u2192 ${t} inside ${n}.`}a(el,"crossSiblingExplanation");function tl(e){return`universe common imports child ${e}. parentMayImportChild is off.`}a(tl,"parentImportsChildExplanation");function ht(e){if(!e)return;let t=e.split("/").filter(Boolean);return t.length>0?t[t.length-1]:void 0}a(ht,"universePairLabel");function nl(e){return String(e).split(/[/\\]/).filter(Boolean).slice(0,-1)}a(nl,"directorySegments");function rl(e,t){if(!t?.length)return!1;let n=new Set;for(let r of t)typeof r=="string"&&r.length>0&&n.add(r.toLowerCase());return n.size===0?!1:nl(e).some(r=>n.has(r.toLowerCase()))}a(rl,"pathHasCommonFolder");function Xt(e,t,n){if(!e||!n?.sliceFolders?.length)return{};if(rl(e,n.commonFolders))return{};let r=Bn(e,n.sliceFolders,n.sliceIdentity);if(!r||!t)return{};let o=r.toLowerCase(),s=t.toLowerCase();return o===s?{}:o.startsWith(`${s}/`)?{childId:r}:{mismatched:{childId:r,universeId:t}}}a(Xt,"resolveChildSliceId");function sl(e){return yt(e.trim().replace(/\\/g,"/")).toLowerCase()}a(sl,"siblingEntryKey");function Un(e){return e.replace(/^(?:src|app)\//,"")}a(Un,"stripSrcOrApp");function ol(e,t){let n=e.replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase(),r=Un(t);if(!r)return!1;let o=Un(n);return n===r||n.startsWith(`${r}/`)||o===r||o.startsWith(`${r}/`)}a(ol,"pathUnderSubtree");function il(e,t,n){if(!t||!n?.length)return!1;let r=t.toLowerCase();for(let o of n){if(typeof o!="string")continue;let s=sl(o);if(!(!s||s.includes("*"))&&(r===s||e&&ol(e,s)))return!0}return!1}a(il,"importerInEnforcedSubtree");function al(e,t,n){return e==null||e==="deny"?!1:e==="advisory"?!0:e.default==="deny"?!1:!il(t,n,e.enforce)}a(al,"siblingCrossingAdvisory");function Zt(e){if(typeof e!="string")return null;let t=yt(e.trim().replace(/\\/g,"/")).toLowerCase();if(!t.includes("/"))return null;let n=t.split("/");for(let r of n)if(r.length===0||r==="."||r===".."||r.includes("*")&&r!=="*")return null;return n}a(Zt,"childSlicePatternSegments");function ws(e,t){let n=Zt(e),r=Zt(t);if(!n||!r||n.length!==r.length)return!1;for(let o=0;o<n.length;o+=1){let s=n[o];if(s!=="*"&&s!==r[o])return!1}return!0}a(ws,"childSlicePatternMatches");function ll(e,t,n){if(!e?.length)return!1;for(let r of e)if(!(!r||typeof r.from!="string"||typeof r.to!="string")&&ws(r.from,t)&&ws(r.to,n))return!0;return!1}a(ll,"childCrossSliceAllowed");function cl(e,t){let n=Zt(e),r=Zt(t);if(!n||!r)return!1;let o=n.slice(0,-1),s=r.slice(0,-1);if(o.length!==s.length)return!0;for(let i=0;i<o.length;i+=1){let l=o[i],c=s[i];if(l==="*"||c==="*"||l!==c)return!0}return!1}a(cl,"childAllowanceSpansUniverses");function dl(e){let t=qa({fromPath:e.fromPath,toPath:e.toPath,folderCount:e.folderCount,fromSlice:e.fromSlice,toSlice:e.toSlice,fromShared:e.fromShared,toShared:e.toShared,crossSliceAllowed:e.crossSliceAllowed,sharedImportsSlice:e.rule.sharedImportsSlice});if(t.denied){let i=!!e.rule.childSlices&&t.reason==="cross-slice";return{crossing:t.reason==="cross-slice"?"cross-parent":"fail-closed",decision:"deny",...i?{reasonId:"CROSS_PARENT_SLICE"}:{},explanation:i?Qa(e.fromSlice,e.toSlice):Za(t.reason??"missing-path",{fromPath:e.fromPath,toPath:e.toPath,fromSlice:e.fromSlice,toSlice:e.toSlice}),peerIsolationReason:t.reason,fromUniverse:e.fromSlice,toUniverse:e.toSlice}}let n=e.rule.childSlices;if(!n||!e.fromSlice||!e.toSlice||e.fromSlice!==e.toSlice||!e.toPath)return{crossing:"none",decision:"allow",fromUniverse:e.fromSlice,toUniverse:e.toSlice};let r=e.fromChild??Xt(e.fromPath,e.fromSlice,n).childId,o=e.toChild??Xt(e.toPath,e.toSlice,n).childId,s={crossing:"none",decision:"allow",fromUniverse:e.fromSlice,toUniverse:e.toSlice};return r&&o&&r!==o?ll(n.allowedCrossSlice,r,o)?s:{crossing:"cross-sibling",decision:al(n.siblings,e.fromPath,r)?"advisory":"deny",reasonId:"CROSS_SIBLING_SLICE",explanation:el(r,o,e.fromSlice),fromUniverse:e.fromSlice,toUniverse:e.toSlice}:!r&&o&&n.parentMayImportChild!==!0?{crossing:"parent-imports-child",decision:"deny",explanation:tl(o),fromUniverse:e.fromSlice,toUniverse:e.toSlice}:s}a(dl,"evaluateNestedSliceWall");function ze(e){let t=e.verdict.explanation;if(e.surface==="intent"){let n=e.defaultMessage??`${e.fromLayer} must not reference ${e.toLayer} intent.`;return e.verdict.reasonId&&t?`${n} ${t}`:t&&e.verdict.peerIsolationReason!=="cross-slice"?`${n} ${t}`:e.ruleMessage?t?`${e.ruleMessage} (${t})`:e.ruleMessage:n}if(e.ruleMessage)return t?`${e.ruleMessage} (${t})`:e.ruleMessage;if(t){let n=e.kind??"import";return`${e.fromLayer} must not ${n} another slice of ${e.toLayer} (${e.fromPath} \u2192 ${e.toPath}): ${t}`}return`${e.fromLayer} must not ${e.kind??"import"} ${e.toLayer}.`}a(ze,"composeSliceDenialMessage");function Ne(e){if(!e||e.decision==="allow")return{};let t=ht(e.fromUniverse),n=ht(e.toUniverse);return{...e.reasonId?{reasonId:e.reasonId}:{},...e.reasonId&&t&&n?{universeFrom:t,universeTo:n}:{},...e.decision==="advisory"?{failsStrict:!1,severity:"warning"}:{}}}a(Ne,"sliceFindingExtras");function Ms(e,t){let n=[],r=!1,o=new Set,s=new Set;for(let i of e??[])if(i?.childSlices&&(r||(r=!0,n.push({ruleId:"CONFIG_CHILD_SLICES_VERSION",failsStrict:!1,message:`childSlices needs an arkgate newer than ${Cs}. Version ${Cs} and older reject the key because the rule schema sets additionalProperties: false.`})),!!i.peerIsolation)){for(let l of t){let c=Bn(l,i.sliceFolders,i.sliceIdentity),u=Xt(l,c,i.childSlices);if(!u.mismatched)continue;let p=`${i.from}\0${i.to}\0${u.mismatched.universeId}\0${u.mismatched.childId}`;o.has(p)||(o.add(p),n.push({ruleId:"CONFIG_CHILD_SLICE_EXTENDS",failsStrict:!1,fromLayer:i.from,toLayer:i.to,path:l,message:`${i.from} \u2192 ${i.to}: child id ${u.mismatched.childId} does not extend universe id ${u.mismatched.universeId} (${l}).`}))}for(let l of i.childSlices.allowedCrossSlice??[]){if(!l||typeof l.from!="string"||typeof l.to!="string"||!cl(l.from,l.to))continue;let c=`${l.from.trim().toLowerCase()}\0${l.to.trim().toLowerCase()}`;s.has(c)||(s.add(c),n.push({ruleId:"CONFIG_CHILD_SLICE_CROSS_UNIVERSE",failsStrict:!1,fromLayer:i.from,toLayer:i.to,message:`childSlices.allowedCrossSlice ${l.from} \u2192 ${l.to} cannot cross the universe wall. The universe wall still denies that edge.`}))}}return n}a(Ms,"childSliceConfigFindings");function Fs(e,t,n,r){return Oe(e,t,n,r)?.rule}a(Fs,"findDeniedEdgeRule");function Oe(e,t,n,r){for(let o of e??[])if(!(o.from!==t||o.to!==n)&&o.allowed===!1){if(o.peerIsolation){let s=r?.fromPath,i=r?.toPath,l=zn(o,t,r?.layers),c=Be(s,o,l),u=Be(i,o,l),p=c.universeId,m=u.universeId,f=dl({rule:o,fromPath:s,toPath:i,folderCount:l.length,fromSlice:p,toSlice:m,fromChild:c.childId,toChild:u.childId,fromShared:!p&&mt(s,o.sharedRoots),toShared:!m&&mt(i,o.sharedRoots),crossSliceAllowed:Wa(o.allowedCrossSlice,p,m)});if(f.decision!=="allow")return{rule:o,peerIsolationReason:f.peerIsolationReason,fromSlice:p,toSlice:m,sliceVerdict:f};continue}if(t!==n)return{rule:o}}}a(Oe,"findDeniedEdgeDecision");function $s(e,t,n,r){let o=r?.fromPath,s=r?.toPath;if(!(!o||!s))for(let i of e??[]){if(i.from!==t||i.to!==n||i.allowed!==!1||!i.peerIsolation||i.sharedImportsSlice==="deny")continue;let l=zn(i,t,r?.layers),c=Be(o,i,l).universeId,u=Be(s,i,l).universeId;if(!(c||!u)&&mt(o,i.sharedRoots))return{fromPath:o,toPath:s,toSlice:u}}}a($s,"findSharedImportsSliceBridge");function Hs(e,t,n){return zn(e,t,n)}a(Hs,"peerSliceFolders");function We(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}a(We,"literalText");function Ks(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}a(Ks,"lineOf");function js(e,t){if(e.isImportDeclaration(t)){let r=t.importClause;if(!r)return!1;if(r.isTypeOnly)return!0;let o=r.namedBindings;return!!(o&&e.isNamedImports(o)&&o.elements.length>0&&o.elements.every(s=>s.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))}a(js,"isTypeOnlyReference");function Us(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=o=>o===t.fileName?t:void 0,r.fileExists=o=>o===t.fileName,r.readFile=o=>o===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}a(Us,"singleFileChecker");function Wn(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}a(Wn,"symbolAt");function qn(e,t,n,r){let o=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,s;try{s=o?t.getShorthandAssignmentValueSymbol(r.parent):Wn(t,r)}catch{s=void 0}return!!s?.declarations?.some(i=>i.getSourceFile().fileName===n.fileName)}a(qn,"localDeclaration");function qe(e,t){let n,r=[],o=a((i,l,c,u=!1)=>r.push({specifier:c,kind:l,line:Ks(t,i),typeOnly:u,unresolved:c===void 0,node:i}),"add"),s=a(i=>{if(e.isImportDeclaration(i))o(i,"import",We(e,i.moduleSpecifier),js(e,i));else if(e.isExportDeclaration(i)&&i.moduleSpecifier)o(i,"export",We(e,i.moduleSpecifier),js(e,i));else if(e.isImportEqualsDeclaration(i)&&e.isExternalModuleReference(i.moduleReference))o(i,"require",We(e,i.moduleReference.expression),i.isTypeOnly===!0);else if(e.isCallExpression(i)){let l=i.expression.kind===e.SyntaxKind.ImportKeyword,u=e.isIdentifier(i.expression)&&i.expression.text==="require"&&!qn(e,n??(n=Us(e,t)),t,i.expression);(l||u)&&o(i,u?"require":"dynamic-import",We(e,i.arguments[0]))}e.forEachChild(i,s)},"visit");return s(t),r}a(qe,"extractSemanticDependencies");function ul(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let o=We(e,r.argumentExpression);if(o===void 0)return;n.unshift(o)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}a(ul,"staticAccessPath");function pl(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}a(pl,"runtimeIdentifierReference");function Vs(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let r=n.length;r>=1;r-=1){let o=n.slice(0,r).join(".");if(e.has(o))return o}}a(Vs,"bestForbiddenMatch");function Ye(e,t,n){if(n.length===0)return[];let r=new Set(n),o=Us(e,t),s=new Map,i=new Set;for(let f of t.statements)if(e.isVariableStatement(f))for(let g of f.declarationList.declarations)e.isIdentifier(g.name)&&i.add(g.name.text);let l=a(f=>{let g=ul(e,f);if(!g)return;let d=Wn(o,g.root),h=d?s.get(d):void 0;return h?[...h,...g.segments.slice(1)]:qn(e,o,t,g.root)||i.has(g.root.text)?void 0:g.segments},"resolvePath");for(let f of t.statements)if(e.isVariableStatement(f))for(let g of f.declarationList.declarations){if(!g.initializer||!e.isIdentifier(g.name))continue;let d=l(g.initializer),h=Wn(o,g.name);!d||!h||s.set(h,d)}let c=[],u=new Set,p=a((f,g)=>{let d=Ks(t,g),h=`${f}:${g.getStart(t)}`;u.has(h)||(u.add(h),c.push({name:f,line:d,node:g}))},"flag"),m=a(f=>{let g=f.parent&&(e.isPropertyAccessExpression(f.parent)||e.isElementAccessExpression(f.parent))&&f.parent.expression===f;if((e.isPropertyAccessExpression(f)||e.isElementAccessExpression(f))&&!g){let d=l(f),h=d?Vs(r,d):void 0;h&&p(h,f)}else e.isIdentifier(f)&&r.has(f.text)&&pl(e,f)&&!qn(e,o,t,f)&&p(f.text,f);if(e.isVariableDeclaration(f)&&e.isObjectBindingPattern(f.name)&&f.initializer){let d=l(f.initializer);if(d)for(let h of f.name.elements){if(!e.isIdentifier(h.name))continue;let E=h.propertyName?We(e,h.propertyName)??h.propertyName.text:h.name.text,_=Vs(r,[...d,E]);_&&p(_,f.initializer)}}e.forEachChild(f,m)},"visit");return m(t),c}a(Ye,"collectForbiddenCapabilityUses");function Yn(e,t,n){let r=[];for(let o of n?.dependencies??qe(e,t)){if(o.typeOnly||!o.specifier)continue;let s=ft(o.specifier);s&&r.push({capability:s,symbol:o.specifier,line:o.line,source:"import-based"})}for(let o of n?.ambientUses??Ye(e,t,Kn)){let s=Yt(o.name);s&&r.push({capability:s,symbol:o.name,line:o.line,source:"ambient-global"})}return r.sort((o,s)=>o.line-s.line||o.capability.localeCompare(s.capability)||o.symbol.localeCompare(s.symbol))}a(Yn,"collectCapabilityUses");var Jn={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."},Xn=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 Zn(e,t){return t.flatMap((r,o)=>(r.prefixes??r.intentPrefixes??[]).map(s=>({layer:r.name,layerIndex:o,prefix:s.endsWith(".")?s:`${s}.`}))).filter(({prefix:r})=>e.startsWith(r)).sort((r,o)=>o.prefix.length-r.prefix.length||r.layerIndex-o.layerIndex)[0]?.layer}a(Zn,"resolveIntentLayer");function Le(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}a(Le,"looksLikeArkIntent");function At(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&Le(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:Jn.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:Jn.PUBLISH_MISSING_SOURCE}),t}a(At,"classifyPublishFacts");function X(e,t,n){return{ruleId:e,code:e,message:t,...n}}a(X,"violation");function Je(e,t){return e.slice(0,t).split(`
2
+ `).length}a(Je,"lineOf");var fl=new Set(["publish","subscribe","defineIntent","registerHandler"]);function gl(e,t){return e.index+e[0].indexOf(t)}a(gl,"captureIndex");function ml(e){let t=[],n=new Set,r=a((l,c)=>{!l||n.has(c)||(n.add(c),t.push({value:l,index:c}))},"push"),o=a(l=>{l.lastIndex=0;let c;for(;(c=l.exec(e))!==null;){let u=c[1];u&&r(u,gl(c,u))}},"pushFrom");o(/\b(?:publish|subscribe|defineIntent|registerHandler)\s{0,8}(?:<[^>]{0,120}>)?\s{0,8}\(\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),o(/\b(?:intent|onEvent)\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g);let s=/\breactsTo\s{0,8}:\s{0,8}\[([^\]]{0,2000})\]/g,i;for(;(i=s.exec(e))!==null;){let l=i[1]??"",c=i.index+i[0].indexOf(l),u=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,p;for(;(p=u.exec(l))!==null;){let m=p[1];m&&r(m,c+p.index+p[0].indexOf(m))}}return o(/\bmetadata\s{0,8}:\s{0,8}\{[^}]{0,400}\bsource\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),o(/\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)}a(ml,"extractQuotedStrings");function hl(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 o;for(;(o=r.re.exec(e))!==null;){let s=o.index+o[0].indexOf(o[1]),i=o[0],l=r.kind==="import"&&/\bimport\s+type\b/.test(i)||r.kind==="export"&&/\bexport\s+type\b/.test(i);t.push({value:o[1],index:s,kind:r.kind,typeOnly:l})}}return t.sort((r,o)=>r.index-o.index)}a(hl,"extractModuleSpecifiers");function yl(e,t){return!!(t&&(e.isParenthesizedExpression(t)||e.isAsExpression(t)||typeof e.isTypeAssertionExpression=="function"&&e.isTypeAssertionExpression(t)||typeof e.isSatisfiesExpression=="function"&&e.isSatisfiesExpression(t)))}a(yl,"isSyntaxWrapper");function Qn(e,t){let n=t;for(;n?.parent&&yl(e,n.parent);)n=n.parent;return n}a(Qn,"unwrapWrappers");function er(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}a(er,"callCalleeName");function Al(e,t){let n=t.parent;if(!n||!e.isObjectLiteralExpression(n))return!1;let r=Qn(e,n),o=r.parent;if(!o)return!1;if(e.isCallExpression(o)&&er(e,o)==="publish"){let s=o.arguments;return s[1]===r||s[2]===r}if(e.isPropertyAssignment(o)&&tr(e,o.name)==="metadata"){let s=o.parent;if(!s)return!1;let l=Qn(e,s).parent;return!!(l&&e.isCallExpression(l)&&er(e,l)==="publish")}return!1}a(Al,"isPublishMetadataSource");function Gs(e,t){let n=Qn(e,t),r=n.parent;if(!r)return!1;if(e.isCallExpression(r)){let o=er(e,r);if(o&&fl.has(o)&&r.arguments.some(s=>s===n))return!0}if(e.isArrayLiteralExpression(r))return Gs(e,r);if(e.isPropertyAssignment(r)){let o=tr(e,r.name);if(o==="intent"||o==="onEvent"||o==="reactsTo"||o==="source"&&Al(e,r))return!0}return!1}a(Gs,"isDeclaredIntentSite");function Rl(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],o=a(s=>{e.isStringLiteralLike(s)&&Gs(e,s)&&r.push({value:s.text,index:s.getStart(n)}),e.forEachChild(s,o)},"visit");return o(n),r}a(Rl,"extractQuotedStringsAst");function kl(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))}a(kl,"hasInfrastructureToken");function Sl(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}a(Sl,"isKnownInfrastructurePackage");function Il(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}a(Il,"layerHasInfrastructureRole");function kt(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}a(kt,"tsStringLiteralText");function tr(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}a(tr,"tsPropertyName");function Bs(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:tr(e,r.name)===n)}a(Bs,"tsObjectProperty");function St(e,t,n){return Bs(e,t,n)!==void 0}a(St,"tsObjectHasProperty");function Rt(e,t,n){let r=Bs(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}a(Rt,"tsObjectPropertyValue");function El(e,t){let n=Rt(e,t,"metadata");return St(e,n,"source")}a(El,"tsObjectHasMetadataSource");function zs(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?zs(e,t.name):!1:!1}a(zs,"tsLooksLikeIntentCreatorExpression");function bl(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"}a(bl,"tsIsPublishCall");function vl(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=kt(e,n);return r!==void 0&&Le(r)||St(e,n,"intent")||zs(e,n)}a(vl,"tsIsArkPublishCandidate");function Cl(e,t){if(!e.isCallExpression(t))return!1;let[n,r,o]=t.arguments;return El(e,n)||St(e,r,"source")||St(e,o,"source")}a(Cl,"tsPublishHasSource");function _l(e,t){if(!e.isCallExpression(t))return;let[n,r,o]=t.arguments,s=Rt(e,n,"metadata");return kt(e,Rt(e,s,"source"))??kt(e,Rt(e,r,"source"))??kt(e,Rt(e,o,"source"))}a(_l,"tsPublishSourceLiteral");function Ol(e,t,n,r){let o=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),s=n,i=s?.filePath,l=s?.layer,c=[],u=a(m=>o.getLineAndCharacterOfPosition(m.getStart(o)).line+1,"lineForNode"),p=a(m=>{if(bl(e,m)){let f=m.arguments[0],g=kt(e,f);for(let h of At({publishCall:!0,rawIntentName:g,objectHasIntent:St(e,f,"intent"),arkPublishCandidate:vl(e,m),hasSource:Cl(e,m)}))c.push(X(h.ruleId,h.message,{line:u(m),filePath:i}));let d=_l(e,m);if(r&&l&&d&&Le(d)){let h=r.resolveLayer(d);h&&h!==l&&c.push(X("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${d}" resolves to ${h}, but the target file is classified as ${l}.`,{line:u(m),filePath:i,target:d,fromLayer:l,toLayer:h}))}}e.forEachChild(m,p)},"visit");return p(o),c}a(Ol,"analyzePublishAst");function Ws(e={}){let t=new Set((e.intents||[]).map(s=>typeof s=="string"?s:s.name)),n=e.forbiddenPatterns||[],r=new Set(e.infrastructureLayers??[]),o=e.enforceIntentAllowlist??t.size>0;return{validate(s,i){let l=[],c=i,u=c?.filePath,p=c?.layer,m=e.typescript,f=m?m.createSourceFile(u??"generated.ts",s,m.ScriptTarget.Latest,!0):void 0,g=f?qe(e.typescript,f):void 0,d=g?g.filter(k=>k.specifier!==void 0).map(k=>({value:k.specifier,index:k.node.getStart(f),kind:k.kind,typeOnly:k.typeOnly})):hl(s),h=e.typescript?Rl(e.typescript,s):ml(s);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(u))for(let k of g?.filter(({unresolved:b})=>b)??[]){let b=k.kind==="require";l.push(X(b?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${b?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:k.line,filePath:u}))}let E=p!==void 0&&(r.has(p)||Il(p)),_=p!==void 0?` If "${p}" 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 k of n)if(k instanceof RegExp){k.lastIndex=0;let b=k.exec(s);k.lastIndex=0,b&&l.push(X("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${k}`,{line:b.index===void 0?void 0:Je(s,b.index),filePath:u,suggestion:"Remove infrastructure imports from domain/application layers."+_}))}else s.includes(k)&&l.push(X("FORBIDDEN_SUBSTRING",`Forbidden substring: ${k}`,{line:Je(s,s.indexOf(k)),filePath:u}));for(let k of d){let b=e.resolveImportTarget?.(k.value,u)??(e.resolveImportLayer?{layer:e.resolveImportLayer(k.value,u)}:void 0),O=typeof u=="string"?e.resolveImportTarget?.(u)??(e.resolveImportLayer?{layer:p,relPath:void 0}:void 0):void 0,D=b?.layer;if(D&&p){let S=Oe(e.architectureProfile?.rules,p,D,{fromPath:O?.relPath,toPath:b?.relPath,layers:e.architectureLayers});if(S){let L=S.rule;if(k.typeOnly&&!L.peerIsolation)continue;let j=!!L.peerIsolation,T=Ne(S.sliceVerdict),M=L.message??(j?`Layer "${p}" must not import across slices into "${D}".`:`Layer "${p}" must not import "${D}".`),P=T.reasonId||j&&!S.peerIsolationReason?S.sliceVerdict?.explanation:void 0;l.push(X("LAYER_IMPORT_VIOLATION",P?`${M} ${P}`:M,{line:Je(s,k.index),source:k.value,target:k.value,filePath:u,fromLayer:p,toLayer:D,...T.reasonId?{reasonId:T.reasonId}:{},...T.failsStrict===!1?{failsStrict:!1}:{},suggestion:j?"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:k.kind,peerIsolation:j,...k.typeOnly?{typeOnly:!0}:{},...T.reasonId?{reasonId:T.reasonId}:{}}}));continue}continue}E||k.typeOnly||!kl(k.value)&&!Sl(k.value)||l.push(X("FORBIDDEN_IMPORT",`Forbidden ${k.kind} target: "${k.value}".`,{line:Je(s,k.index),source:k.value,target:k.value,filePath:u,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+_,details:{importKind:k.kind}}))}if(e.policies)for(let k of e.policies){let b=k.check({source:s,context:i});if(b!==!0)if(Array.isArray(b))for(let O of b)l.push(X("POLICY_VIOLATION",O.message,{filePath:u,suggestion:`Fix violation of policy "${k.name}".`}));else b===!1?l.push(X("POLICY_VIOLATION",`Policy ${k.name} failed on generated code`)):l.push(X("POLICY_VIOLATION",b.message))}if(o&&t.size>0)for(let k of h)Le(k.value)&&!t.has(k.value)&&l.push(X("UNKNOWN_INTENT",`Unknown intent reference: "${k.value}"`,{line:Je(s,k.index),filePath:u,target:k.value,suggestion:`Register intent "${k.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&p)for(let k of h){if(!Le(k.value))continue;let b=e.architectureProfile.resolveLayer(k.value);if(!b)continue;let O=Oe(e.architectureProfile.rules,p,b,{fromPath:typeof u=="string"?u:void 0,layers:e.architectureLayers});if(O){let D=O.sliceVerdict,S=`Layer "${p}" must not reference "${b}" through "${k.value}".`,L=D?ze({surface:"intent",verdict:D,fromLayer:p,toLayer:b,fromPath:typeof u=="string"?u:void 0,ruleMessage:O.rule.message,defaultMessage:S}):O.rule.message??S,j=Ne(D);l.push(X("LAYER_REFERENCE_VIOLATION",L,{line:Je(s,k.index),filePath:u,target:k.value,fromLayer:p,toLayer:b,...j.reasonId?{reasonId:j.reasonId}:{},...j.failsStrict===!1?{failsStrict:!1}:{},suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:O.rule,peerIsolationReason:O.peerIsolationReason,...j.reasonId?{reasonId:j.reasonId}:{}}}))}}if(e.extensions)for(let k of e.extensions)try{let b=k.analyze(s,i);l.push(...b)}catch(b){l.push(X("EXTENSION_ERROR",`Extension "${k.name}" failed: ${b instanceof Error?b.message:String(b)}`))}if(e.typescript&&f&&p&&e.forbiddenGlobals?.[p]?.length)try{let k=e.forbiddenGlobals[p];l.push(...Ye(e.typescript,f,k).map(b=>X("FORBIDDEN_GLOBAL",`${p} must not use the ambient global "${b.name}".`,{line:b.line,filePath:u,target:b.name,fromLayer:p,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let b of g??[]){if(b.typeOnly||!b.specifier)continue;let O=_e(b.specifier,k);O&&l.push(X("FORBIDDEN_GLOBAL",`${p} must not use module "${b.specifier}" because it is the import form of forbidden global "${O}".`,{line:b.line,filePath:u,source:b.specifier,target:b.specifier,fromLayer:p,details:{importKind:b.kind,forbiddenGlobal:O},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(k){l.push(X("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${k instanceof Error?k.message:String(k)}`))}if(e.typescript&&f&&p&&e.capabilityWalls?.[p]?.length)try{let k=new Set(e.capabilityWalls[p]),b=e.forbiddenGlobals?.[p]??[];for(let O of Yn(e.typescript,f))k.has(O.capability)&&(O.source==="ambient-global"&&gt(O.symbol,b)||O.source==="import-based"&&_e(O.symbol,b)||l.push(X("CAPABILITY_VIOLATION",O.source==="import-based"?`${p} denies the ${O.capability} capability; found import of "${O.symbol}".`:`${p} denies the ${O.capability} capability; found ambient "${O.symbol}".`,{line:O.line,filePath:u,target:O.symbol,capability:O.capability,fromLayer:p,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(k){l.push(X("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${k instanceof Error?k.message:String(k)}`))}if(e.typescript)try{l.push(...Ol(e.typescript,s,i,e.architectureProfile))}catch(k){l.push(X("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${k instanceof Error?k.message:String(k)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:!l.some(k=>k.failsStrict!==!1),violations:l}}}}a(Ws,"createAICodeGate");var Pe={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},qs={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...Pe,default:[]},kernelRoots:{...Pe},managedLayers:{...Pe,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},Ys={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...Pe,default:[]},managedLayers:{...Pe,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...Pe,default:[]},appliesTo:{...Pe,default:[]}}};function It(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(It,"isObject");function Js(e){let t=new Set;if(!Array.isArray(e.layers))return t;for(let n of e.layers)It(n)&&typeof n.name=="string"&&n.name.length>0&&t.add(n.name);return t}a(Js,"declaredLayerNames");function Xs(e){if(!It(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}}a(Xs,"defaultedArkRun");function Zs(e){if(!It(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}}a(Zs,"defaultedArkOrder");function Qs(e,t){let n=e.arkRun;if(n===void 0||!It(n))return;let r=Js(e),o=n.managedLayers;if(Array.isArray(o)&&o.forEach((s,i)=>{typeof s=="string"&&s.length>0&&!r.has(s)&&t.push({path:`$.arkRun.managedLayers[${i}]`,message:`layer ${JSON.stringify(s)} is not declared in layers[]`})}),n.mode==="enforced"){let s=n.kernelRoots??n.compositionRoots;(!Array.isArray(s)||s.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(o)||o.length===0)&&t.push({path:"$.arkRun.managedLayers",message:"enforced mode requires at least one managed layer"})}}a(Qs,"validateArkRunExtra");function eo(e,t){let n=e.arkOrder;if(n===void 0||!It(n))return;let r=Js(e),o=n.managedLayers;if(Array.isArray(o)&&o.forEach((s,i)=>{typeof s=="string"&&s.length>0&&!r.has(s)&&t.push({path:`$.arkOrder.managedLayers[${i}]`,message:`layer ${JSON.stringify(s)} is not declared in layers[]`})}),n.mode==="enforced"){let s=n.planeRoots;(!Array.isArray(s)||s.length===0)&&t.push({path:"$.arkOrder.planeRoots",message:"ARKORDER_MISSING_PLANE: enforced mode requires at least one plane root"}),(!Array.isArray(o)||o.length===0)&&t.push({path:"$.arkOrder.managedLayers",message:"enforced mode requires at least one managed layer"})}}a(eo,"validateArkOrderExtra");function en(e){if(typeof e!="string")return null;let t=e.trim().replace(/^@/,"").toLowerCase();return t.length>0?t:null}a(en,"normalizeStewardId");function to(e){let t=en(e);return!t||nr(t)||t.includes(" ")||t.includes("@")?!1:/^(?!-)[a-z0-9-]{1,39}(?<!-)$/.test(t)}a(to,"isGitHubHandle");function xl(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();return!t.includes("@")||t.includes(" ")||nr(t)?!1:/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}a(xl,"isGitHubEmail");function Tl(e){if(typeof e!="string")return null;let t=e.trim().match(/^(?:\d+\+)?([^@]+)@users\.noreply\.github\.com$/i);return t&&to(t[1])?en(t[1]):null}a(Tl,"githubHandleFromEmail");function no(e){let t=Tl(e);if(t)return t;let n=en(e);return!n||nr(n)?null:to(n)||xl(n)?n:null}a(no,"canonicalStewardId");var wl=/bot\b|\[bot\]|dependabot|renovate|github-actions|imgbot|codecov/i;function nr(e){let t=en(e);return!t||wl.test(t)}a(nr,"isAutomationAuthor");var le="1.3",Nl=["public","auth","admin","internal"];function Ll(e){return e?.optional===!0||e?.reserved===!0||e?.allowEmpty===!0}a(Ll,"isFutureHouseLayer");function Pl(e){let t=e&&typeof e=="object"?e.owners:void 0;if(!Array.isArray(t)||t.length===0)return;let n=t.filter(r=>typeof r=="string"&&r.length>0);return n.length>0?n:void 0}a(Pl,"layerOwnersList");function lo(e){return e?.requireLayerOwners!==!0||!Array.isArray(e.layers)?[]:e.layers.filter(t=>!Ll(t)&&!Pl(t)).map(t=>t.name)}a(lo,"layersMissingRequiredOwners");function co(e){return`Add a GitHub handle or email to ${e}'s owners in ark.config.json (/ark-adopt).`}a(co,"missingLayerOwnersNextAction");var tn="https://unpkg.com/arkgate@4/schemas/ark.config.schema.json",ro=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Dl=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Ml(){let e=[];for(let t of ro)for(let n of ro)t===n||Dl.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}a(Ml,"createDefaultRules");var nn=Ml(),rr=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"},{from:"1.1",to:"1.2"},{from:"1.2",to:"1.3"}],ne={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},sr={$schema:"https://json-schema.org/draft/2020-12/schema",$id:tn,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:tn,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:le,default:le},name:{type:"string",minLength:1},include:{...ne,minItems:1,default:["src"]},exclude:{...ne,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:nn,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...ne,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},coverage:{$ref:"#/$defs/coverage"},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},arkRun:{$ref:"#/$defs/arkRun"},arkOrder:{$ref:"#/$defs/arkOrder"},stewards:{...ne,default:[]},requireLayerOwners:{type:"boolean"}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...ne,minItems:1},exclude:ne,intentPrefixes:ne,description:{type:"string",minLength:1},trustBoundary:{type:"string",enum:[...Nl]},owners:{...ne,minItems:1},forbiddenGlobals:ne,capabilities:{type:"object",additionalProperties:!1,properties:{deny:{type:"array",uniqueItems:!0,items:{type:"string",enum:["network","filesystem","clock","randomness","environment","process","persistence"]}}}},pure:{type:"boolean"},mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"},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:{...ne,minItems:1},sliceIdentity:{type:"string",enum:["path","stars"],description:"How a starred sliceFolders prefix is named. Absent and path keep today's ids (every literal and star binding). stars keeps the last literal plus the star bindings, so parallel trees share one feature id. Bare names are unchanged."},sharedRoots:{...ne,minItems:1},allowedCrossSlice:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}},sharedImportsSlice:{type:"string",enum:["deny","deny-cross-parent"],description:"deny blocks every shared-root import of a slice. deny-cross-parent leaves that hop as a warning and, in ark-check and CI only, reports a slice that reaches another universe through a shared root. The write hook and ESLint see one edge and do not block it. arkgate 4.8.22 and older reject deny-cross-parent."},childSlices:{type:"object",additionalProperties:!1,required:["sliceFolders"],description:`Optional inner wall under this rule. Absent keeps today's universe wall. sliceFolders names children. commonFolders and flat files are universe common. siblings is "deny" (default), "advisory", or { default, enforce }. parentMayImportChild defaults to false. allowedCrossSlice may use a whole-segment *. It clears only a sibling crossing. Cross-parent has no advisory knob. arkgate 4.8.22 and older reject this key. A build that still rejects unknown childSlices fields rejects allowedCrossSlice at config load. A build that still types siblings as a string enum rejects the object at config load.`,properties:{sliceFolders:{...ne,minItems:1},sliceIdentity:{type:"string",enum:["path","stars"]},commonFolders:{...ne,minItems:1},siblings:{description:'"deny" or "advisory", or { default, enforce } so listed subtrees are errors while the default stays advisory. A string-enum build rejects the object at config load (must be one of deny, advisory).',oneOf:[{type:"string",enum:["deny","advisory"]},{type:"object",additionalProperties:!1,required:["default"],properties:{default:{type:"string",enum:["deny","advisory"]},enforce:{...ne}}}]},parentMayImportChild:{type:"boolean"},sliceAliases:{type:"array",minItems:1,description:"Maps a source path glob onto a child slice id (universe id plus one child segment) so files outside the slice trees take that universe and child for both walls. A bare name, a universe id alone, an unknown universe, and a wildcard in to are rejected. The glob may not overlap a slice folder, and two aliases may not match the same file. Doctor lists each alias as an owed move. A build that rejects unknown childSlices fields fails at config load (unknown field). arkgate 4.8.22 and older reject childSlices.",items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}},allowedCrossSlice:{type:"array",minItems:1,description:"Directed child-slice allowances. * matches one whole path segment (features/projects/*). ** and a partial segment are rejected. A bare name is rejected. This list clears only CROSS_SIBLING_SLICE. It cannot clear CROSS_PARENT_SLICE or CROSS_PARENT_VIA_SHARED. The universe allowedCrossSlice still treats * as a literal. A build that rejects unknown childSlices fields fails at config load (unknown field).",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. When any invariant is enforced, missing coverageRoots fails closed.",properties:{testGlobs:{...ne,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:{...ne,minItems:1}}},arkRun:qs,arkOrder:Ys}},Ie=class extends Error{static{a(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 Fs(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(Fs,"isObject");function Vt(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}i(Vt,"propertyPath");function ze(e){return e===null?"null":Array.isArray(e)?"array":typeof e}i(ze,"valueType");function Bi(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}i(Bi,"resolveSchemaRef");function ut(e,t,n,r,o){if(t.$ref){let s=Bi(t.$ref,r);if(!s){o.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}ut(e,s,n,r,o);return}if(t.const!==void 0&&!Object.is(e,t.const)){o.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(s=>Object.is(s,e))){o.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!Fs(e)){o.push({path:n,message:`must be an object; received ${ze(e)}`});return}let s=t.properties??{};for(let a of t.required??[])e[a]===void 0&&o.push({path:Vt(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in s||o.push({path:Vt(n,a),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let a=t.additionalProperties;for(let c of Object.keys(e))c in s||ut(e[c],a,Vt(n,c),r,o)}for(let[a,c]of Object.entries(s))e[a]!==void 0&&ut(e[a],c,Vt(n,a),r,o);return}if(t.type==="array"){if(!Array.isArray(e)){o.push({path:n,message:`must be an array; received ${ze(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&o.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let s=e.map(a=>JSON.stringify(a));new Set(s).size!==s.length&&o.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((s,a)=>ut(s,t.items,`${n}[${a}]`,r,o));return}if(t.type==="string"){if(typeof e!="string"){o.push({path:n,message:`must be a string; received ${ze(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&o.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&o.push({path:n,message:`must be a boolean; received ${ze(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){o.push({path:n,message:`must be an integer; received ${ze(e)}`});return}t.minimum!==void 0&&e<t.minimum&&o.push({path:n,message:`must be at least ${t.minimum}`})}}i(ut,"validateNode");function zi(e,t){let n=e.layers;Array.isArray(n)&&n.forEach((r,o)=>{if(!r||typeof r!="object"||Array.isArray(r)||!("owners"in r))return;let s=r.owners;Array.isArray(s)&&s.forEach((a,c)=>{typeof a=="string"&&(Ps(a)||t.push({path:`$.layers[${o}].owners[${c}]`,message:"must be a GitHub handle or email (not a display name)"}))})})}i(zi,"validateLayerOwners");function Wi(e){let t={...e,$schema:e.$schema===void 0?Ut:e.$schema,schemaVersion:e.schemaVersion===void 0?ie:e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?Gt.map(n=>({...n})):e.rules};return e.arkRun!==void 0&&(t.arkRun=Os(e.arkRun)),e.arkOrder!==void 0&&(t.arkOrder=xs(e.arkOrder)),t}i(Wi,"defaultedConfig");function qi(e){return e===ie?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}i(qi,"migratedFromOf");function Yi(){let e=new Set([ie]);for(let t of Vn)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}i(Yi,"knownInputVersions");function Ji(e,t="ark.config.json"){if(!Fs(e))throw new Se(t,[{path:"$",message:`must be an object; received ${ze(e)}`}]);let n=Yi(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new Se(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected ${ie}`}]);if(r!=="unversioned"&&!n.has(r))throw new Se(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${ie}`}]);let o=r,s={...e},a=0;for(;o!==ie&&a<Vn.length+1;){a+=1;let c=Vn.find(l=>l.from===o);if(!c)throw new Se(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(o)}; expected ${ie}`}]);o=c.to,s.schemaVersion=o}if(o!==ie)throw new Se(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${ie}`}]);return{candidate:Wi(s),migratedFrom:qi(r)}}i(Ji,"migrateArkConfig");function Bt(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=Ji(e,t),o=[];if(ut(n,Un,"$",Un,o),Ts(n,o),Ns(n,o),zi(n,o),o.length>0)throw new Se(t,o);return{config:n,migratedFrom:r}}i(Bt,"loadArkConfigContract");function Gn(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new Se(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return Bt(n,t)}i(Gn,"parseArkConfigJson");function $s(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:Ut,schemaVersion:ie};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}i($s,"withArkConfigMetadata");function Xi(e){return e.endsWith(".")?e:`${e}.`}i(Xi,"normalizePrefix");function Zi(e,t){let n=e.prefixes.length?Math.max(...e.prefixes.map(o=>o.length)):0;return(t.prefixes.length?Math.max(...t.prefixes.map(o=>o.length)):0)-n}i(Zi,"byLongestPrefix");function Wt(e){let t=e.layers.map(o=>({...o,prefixes:o.prefixes.map(Xi)})),n=[...t].sort(Zi),r=[...e.rules??[]];return{name:e.name,layers:t,rules:r,resolveLayer(o){return t.find(s=>s.match?.(o))?.name??n.find(s=>s.prefixes.some(a=>o.startsWith(a)))?.name}}}i(Wt,"createArchitectureProfile");function Hs(e,t={}){return Wt({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,r)=>({name:n.name,prefixes:n.intentPrefixes??[],description:n.description,trustBoundary:n.trustBoundary,owners:n.owners,order:r+1})),rules:e.rules??[]})}i(Hs,"createArchitectureProfileFromArkConfig");var Qi=[{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}],zt=Wt({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:Qi,rules:Gt.map(e=>({...e}))}),el={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 js(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return $s({include:e.include??[t],layers:zt.layers.map(o=>({name:o.name,patterns:(el[o.name]??[o.name]).map(s=>`${r}${s}/**`),intentPrefixes:o.prefixes,optional:n})),rules:[...zt.rules]})}i(js,"createElevenLayerArkConfig");function Z(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(Z,"deterministicHash");function K(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(K).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${K(t[n])}`).join(",")}}`}i(K,"stableSerialize");var Pe="1.2";var Ks=["network","filesystem","clock","randomness","environment","process","persistence"];function J(e,t){let n=K(e),r=K(t);return n<r?-1:n>r?1:0}i(J,"compareCanonical");function Q(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}i(Q,"sortedUnique");function pt(e){let t={schemaVersion:"1.2",include:Q(e.include??[]),exclude:Q(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:Q(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:Q(n.patterns??[]),exclude:Q(n.exclude??[]),forbiddenGlobals:Q(n.forbiddenGlobals??[]),intentPrefixes:Q(n.intentPrefixes??[]),capabilityDeny:Q(n.capabilities?.deny??[]),pure:n.pure===!0})).sort(J),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:Q(e.arkRun.compositionRoots),managedLayers:Q(e.arkRun.managedLayers),requireDeclarations:e.arkRun.requireDeclarations===!0}}:{}};return Z(K(t))}i(pt,"resolvedFactsEvidenceRequirementsHash");function tl(e){let t=e.completenessReasons.map(k=>({code:k.code,message:k.message,...k.file?{file:k.file}:{}})).sort(J),n=e.files.map(k=>({...k,typeOnlyExportNames:Q(k.typeOnlyExportNames)})).sort((k,P)=>k.path<P.path?-1:k.path>P.path?1:0),r=e.dependencies.map(k=>({...k,...k.namedBindings?{namedBindings:Q(k.namedBindings)}:{}})).sort(J),o=e.capabilityUses.map(k=>({...k})).sort(J),s=e.ambientUses.map(k=>({...k})).sort(J),a=e.publishCalls.map(k=>({...k})).sort(J),c=e.intentReferences.map(k=>({...k})).sort(J),l=e.safetyUses.map(k=>({...k})).sort(J),u=(e.classShapes??[]).map(k=>({...k,mutatingMethods:[...k.mutatingMethods??[]].map(P=>({...P}))})).sort(J),p=(e.arkRunKernelCalls??[]).map(k=>({...k})).sort(J),g=(e.arkRunManagedNews??[]).map(k=>({...k})).sort(J),f=(e.arkRunCompositionRootHits??[]).map(k=>({...k})).sort(J),m=(e.arkRunDeclarations??[]).map(k=>({...k,uses:Q(k.uses),reactsTo:Q(k.reactsTo),raises:Q(k.raises),sends:Q(k.sends)})).sort(J),d=(e.arkOrderPlaneCalls??[]).map(k=>({...k})).sort(J),y=(e.arkOrderGenericUpdates??[]).map(k=>({...k})).sort(J),b=(e.arkOrderRootHits??[]).map(k=>({...k})).sort(J),x=(e.arkOrderXiFieldWrites??[]).map(k=>({...k})).sort(J),S=(e.arkOrderIngestWritesXi??[]).map(k=>({...k})).sort(J),E=(e.arkOrderReleaseKeyCounts??[]).map(k=>({...k})).sort(J),C=e.files.map(({path:k,contentHash:P})=>({path:k,contentHash:P})).sort((k,P)=>k.path<P.path?-1:k.path>P.path?1:0),D=Z(K(C));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:o,ambientUses:s,publishCalls:a,intentReferences:c,safetyUses:l,classShapes:u,arkRunKernelCalls:p,arkRunManagedNews:g,arkRunCompositionRootHits:f,arkRunDeclarations:m,arkOrderPlaneCalls:d,arkOrderGenericUpdates:y,arkOrderRootHits:b,arkOrderXiFieldWrites:x,arkOrderIngestWritesXi:S,arkOrderReleaseKeyCounts:E}}i(tl,"canonicalResolvedFactsInput");function Vs(e){let t=tl(e);return{...t,factsHash:Z(K(t))}}i(Vs,"createCanonicalResolvedCandidateFacts");function Bn(e){return Vs(Gs($(e,"$"),!1))}i(Bn,"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 V(e,t,n){let r=new Set(t),o=Object.keys(e).find(s=>!r.has(s));if(o)throw new Error(`${n}.${o} is not part of schema ${"1.2"}.`)}i(V,"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 Ie(e,t,n){if(e[t]!==void 0)return F(e,t,n)}i(Ie,"optionalText");function B(e,t,n){let r=F(e,t,n),o=r.replace(/\\/g,"/");if(!o||o.startsWith("/")||/^[A-Za-z]:\//.test(o)||/[\u0000-\u001f\u007f]/.test(o))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let s=[];for(let c of o.split("/"))if(!(!c||c==="."))if(c===".."){if(s.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);s.pop()}else s.push(c);let a=s.join("/");if(!a||a!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return a}i(B,"requiredProjectPath");function z(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}i(z,"requiredBoolean");function Us(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(Us,"requiredInteger");function ne(e,t,n){let r=Us(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}i(ne,"requiredPositiveInteger");function W(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}i(W,"requiredArray");function Ee(e,t,n,r){let o=e[t];if(typeof o!="string"||!n.includes(o))throw new Error(`${r}.${t} must be one of ${n.join(", ")}.`);return o}i(Ee,"enumValue");function We(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(We,"parseStringArray");function nl(e,t,n){let r=new Set;for(let o of e){let s=t(o);if(r.has(s))throw new Error(`${n} must not contain duplicate facts (${s}).`);r.add(s)}}i(nl,"assertUnique");function Gs(e,t){V(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=Ee(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=Ee(e,"completeness",["complete","partial","unavailable"],"$"),o=W(e,"completenessReasons","$").map((v,_)=>{let h=`$.completenessReasons[${_}]`,R=$(v,h);V(R,["code","message","file"],h);let M=R.file===void 0?void 0:B(R,"file",h);return{code:F(R,"code",h),message:F(R,"message",h),...M?{file:M}:{}}});if(r==="complete"&&o.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(r!=="complete"&&o.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let s=W(e,"files","$").map((v,_)=>{let h=`$.files[${_}]`,R=$(v,h);return V(R,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],h),{path:B(R,"path",h),contentHash:F(R,"contentHash",h),parseStatus:Ee(R,"parseStatus",["parsed","invalid"],h),parseDiagnosticCount:Us(R,"parseDiagnosticCount",h),exportsOnlyTypes:z(R,"exportsOnlyTypes",h),typeOnlyExportNames:We(R.typeOnlyExportNames,`${h}.typeOnlyExportNames`),hasTopLevelSideEffects:z(R,"hasTopLevelSideEffects",h)}}),a=W(e,"dependencies","$").map((v,_)=>{let h=`$.dependencies[${_}]`,R=$(v,h);V(R,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],h);let M=Ie(R,"specifier",h),X=Ie(R,"target",h),ve=Ee(R,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],h);if(ve==="resolved-project"&&!X)throw new Error(`${h}.target is required for resolved-project dependencies.`);if(ve!=="resolved-project"&&X)throw new Error(`${h}.target is only allowed for resolved-project dependencies.`);if(ve!=="dynamic"&&!M)throw new Error(`${h}.specifier is required unless resolution is dynamic.`);return{from:B(R,"from",h),...M?{specifier:M}:{},kind:Ee(R,"kind",["import","export","dynamic-import","require"],h),typeOnly:z(R,"typeOnly",h),line:ne(R,"line",h),resolution:ve,...X?{target:B(R,"target",h)}:{},...R.namedBindings!==void 0?{namedBindings:We(R.namedBindings,`${h}.namedBindings`)}:{},...R.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:z(R,"targetTypeOnlyExports",h)}:{},...R.sourcePureTypeModule!==void 0?{sourcePureTypeModule:z(R,"sourcePureTypeModule",h)}:{},...R.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:z(R,"namedBindingsTypeOnly",h)}:{},...R.portProofEligible!==void 0?{portProofEligible:z(R,"portProofEligible",h)}:{}}}),c=W(e,"capabilityUses","$").map((v,_)=>{let h=`$.capabilityUses[${_}]`,R=$(v,h);return V(R,["file","line","symbol","capability","source"],h),{file:B(R,"file",h),line:ne(R,"line",h),symbol:F(R,"symbol",h),capability:Ee(R,"capability",Ks,h),source:Ee(R,"source",["ambient-global","import-based"],h)}}),l=W(e,"ambientUses","$").map((v,_)=>{let h=`$.ambientUses[${_}]`,R=$(v,h);return V(R,["file","line","symbol"],h),{file:B(R,"file",h),line:ne(R,"line",h),symbol:F(R,"symbol",h)}}),u=W(e,"publishCalls","$").map((v,_)=>{let h=`$.publishCalls[${_}]`,R=$(v,h);V(R,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],h);let M=Ie(R,"rawIntentName",h),X=Ie(R,"sourceIntent",h);return{file:B(R,"file",h),line:ne(R,"line",h),...M?{rawIntentName:M}:{},objectHasIntent:z(R,"objectHasIntent",h),arkPublishCandidate:z(R,"arkPublishCandidate",h),hasSource:z(R,"hasSource",h),...X?{sourceIntent:X}:{}}}),p=W(e,"intentReferences","$").map((v,_)=>{let h=`$.intentReferences[${_}]`,R=$(v,h);return V(R,["file","line","intent"],h),{file:B(R,"file",h),line:ne(R,"line",h),intent:F(R,"intent",h)}}),g=W(e,"safetyUses","$").map((v,_)=>{let h=`$.safetyUses[${_}]`,R=$(v,h);V(R,["file","line","kind","symbol"],h);let M=Ie(R,"symbol",h),X=Ee(R,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],h);if(X==="in-memory-store"&&!M)throw new Error(`${h}.symbol is required for in-memory-store facts.`);if(X!=="in-memory-store"&&M)throw new Error(`${h}.symbol is only allowed for in-memory-store facts.`);return{file:B(R,"file",h),line:ne(R,"line",h),kind:X,...M?{symbol:M}:{}}});nl(s,v=>v.path,"$.files");let f=new Set(s.map(v=>v.path));for(let v of s){if(v.parseStatus==="parsed"&&v.parseDiagnosticCount!==0)throw new Error(`$.files[${v.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(v.parseStatus==="invalid"&&v.parseDiagnosticCount===0)throw new Error(`$.files[${v.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&s.some(v=>v.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let v of a)if(!f.has(v.from))throw new Error(`$.dependencies references missing source file ${v.from}.`);let d=(e.arkRunKernelCalls===void 0?[]:W(e,"arkRunKernelCalls","$")).map((v,_)=>{let h=`$.arkRunKernelCalls[${_}]`,R=$(v,h);V(R,["file","line","kind","callee","viaImport","receiver","nameLiteral"],h);let M=Ie(R,"receiver",h),X=Ie(R,"nameLiteral",h);return{file:B(R,"file",h),line:ne(R,"line",h),kind:Ee(R,"kind",["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"],h),callee:F(R,"callee",h),viaImport:z(R,"viaImport",h),...M?{receiver:M}:{},...X?{nameLiteral:X}:{}}}),b=(e.arkRunManagedNews===void 0?[]:W(e,"arkRunManagedNews","$")).map((v,_)=>{let h=`$.arkRunManagedNews[${_}]`,R=$(v,h);V(R,["file","line","typeName","importedFrom"],h);let M=Ie(R,"importedFrom",h);return{file:B(R,"file",h),line:ne(R,"line",h),typeName:F(R,"typeName",h),...M?{importedFrom:M}:{}}}),S=(e.arkRunCompositionRootHits===void 0?[]:W(e,"arkRunCompositionRootHits","$")).map((v,_)=>{let h=`$.arkRunCompositionRootHits[${_}]`,R=$(v,h);return V(R,["file","matchedRoot","hasKernelFactory"],h),{file:B(R,"file",h),matchedRoot:F(R,"matchedRoot",h),hasKernelFactory:z(R,"hasKernelFactory",h)}}),E=e.arkRunDeclarations===void 0?[]:W(e,"arkRunDeclarations","$"),D=(e.arkOrderPlaneCalls===void 0?[]:W(e,"arkOrderPlaneCalls","$")).map((v,_)=>{let h=`$.arkOrderPlaneCalls[${_}]`,R=$(v,h);return V(R,["file","line","callee"],h),{file:B(R,"file",h),line:ne(R,"line",h),callee:F(R,"callee",h)}}),P=(e.arkOrderGenericUpdates===void 0?[]:W(e,"arkOrderGenericUpdates","$")).map((v,_)=>{let h=`$.arkOrderGenericUpdates[${_}]`,R=$(v,h);return V(R,["file","line","method"],h),{file:B(R,"file",h),line:ne(R,"line",h),method:F(R,"method",h)}}),N=(e.arkOrderRootHits===void 0?[]:W(e,"arkOrderRootHits","$")).map((v,_)=>{let h=`$.arkOrderRootHits[${_}]`,R=$(v,h);return V(R,["file","matchedRoot","hasPlaneFactory"],h),{file:B(R,"file",h),matchedRoot:F(R,"matchedRoot",h),hasPlaneFactory:z(R,"hasPlaneFactory",h)}}),L=(e.arkOrderXiFieldWrites===void 0?[]:W(e,"arkOrderXiFieldWrites","$")).map((v,_)=>{let h=`$.arkOrderXiFieldWrites[${_}]`,R=$(v,h);return V(R,["file","line","key"],h),{file:B(R,"file",h),line:ne(R,"line",h),key:F(R,"key",h)}}),G=(e.arkOrderIngestWritesXi===void 0?[]:W(e,"arkOrderIngestWritesXi","$")).map((v,_)=>{let h=`$.arkOrderIngestWritesXi[${_}]`,R=$(v,h);return V(R,["file","line"],h),{file:B(R,"file",h),line:ne(R,"line",h)}}),Re=(e.arkOrderReleaseKeyCounts===void 0?[]:W(e,"arkOrderReleaseKeyCounts","$")).map((v,_)=>{let h=`$.arkOrderReleaseKeyCounts[${_}]`,R=$(v,h);return V(R,["file","line","keyCount"],h),{file:B(R,"file",h),line:ne(R,"line",h),keyCount:ne(R,"keyCount",h)}}),Qe=E.map((v,_)=>{let h=`$.arkRunDeclarations[${_}]`,R=$(v,h);return V(R,["file","line","uses","reactsTo","raises","sends"],h),{file:B(R,"file",h),line:ne(R,"line",h),uses:We(R.uses,`${h}.uses`),reactsTo:We(R.reactsTo,`${h}.reactsTo`),raises:We(R.raises,`${h}.raises`),sends:We(R.sends,`${h}.sends`)}});for(let[v,_]of[["$.capabilityUses",c],["$.ambientUses",l],["$.publishCalls",u],["$.intentReferences",p],["$.safetyUses",g],["$.arkRunKernelCalls",d],["$.arkRunManagedNews",b],["$.arkRunCompositionRootHits",S],["$.arkRunDeclarations",Qe],["$.arkOrderPlaneCalls",D],["$.arkOrderGenericUpdates",P],["$.arkOrderRootHits",N],["$.arkOrderXiFieldWrites",L],["$.arkOrderIngestWritesXi",G],["$.arkOrderReleaseKeyCounts",Re]])for(let h of _)if(!f.has(h.file))throw new Error(`${v} references missing file ${h.file}.`);let Tt=Ie(e,"projectPackageName","$"),ts=(e.classShapes===void 0?[]:W(e,"classShapes","$")).map((v,_)=>{let h=`$.classShapes[${_}]`,R=$(v,h);V(R,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],h);let M=W(R,"mutatingMethods",h).map((X,ve)=>{let A=`${h}.mutatingMethods[${ve}]`,se=$(X,A);return V(se,["name","referencesGuardOrPublish"],A),{name:F(se,"name",A),referencesGuardOrPublish:z(se,"referencesGuardOrPublish",A)}});return{file:B(R,"file",h),className:F(R,"className",h),exported:z(R,"exported",h),hasPublicMutableFields:z(R,"hasPublicMutableFields",h),hasPublicSetters:z(R,"hasPublicSetters",h),hasPublicConstructor:z(R,"hasPublicConstructor",h),hasStaticFactory:z(R,"hasStaticFactory",h),mutatingMethods:M,...R.dataOnly===void 0?{}:{dataOnly:z(R,"dataOnly",h)}}});return{schemaVersion:n,completeness:r,completenessReasons:o,resolverIdentity:F(e,"resolverIdentity","$"),compilerIdentity:F(e,"compilerIdentity","$"),compilerOptionsHash:F(e,"compilerOptionsHash","$"),tsconfigHash:F(e,"tsconfigHash","$"),evidenceRequirementsHash:F(e,"evidenceRequirementsHash","$"),...Tt?{projectPackageName:Tt}:{},files:s,dependencies:a,capabilityUses:c,ambientUses:l,publishCalls:u,intentReferences:p,safetyUses:g,classShapes:ts,arkRunKernelCalls:d,arkRunManagedNews:b,arkRunCompositionRootHits:S,arkRunDeclarations:Qe,arkOrderPlaneCalls:D,arkOrderGenericUpdates:P,arkOrderRootHits:N,arkOrderXiFieldWrites:L,arkOrderIngestWritesXi:G,arkOrderReleaseKeyCounts:Re}}i(Gs,"parseResolvedFactsInput");function _e(e){let t=$(e,"$"),n=F(t,"factsHash","$"),r=F(t,"candidateTreeHash","$"),o=Vs(Gs(t,!0));if(o.factsHash!==n)throw new Error(`$.factsHash does not match the canonical payload (${o.factsHash}).`);if(r!==o.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${o.candidateTreeHash}).`);return o}i(_e,"loadResolvedCandidateFacts");var rl=["network","filesystem","clock","randomness","environment","process","persistence"],w={type:"string",minLength:1},oe={type:"integer",minimum:1},q={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},zn={$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:w,message:w,file:q}}},resolverIdentity:w,compilerIdentity:w,compilerOptionsHash:w,tsconfigHash:w,candidateTreeHash:w,evidenceRequirementsHash:w,projectPackageName:w,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:q,contentHash:w,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:w},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:w,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:oe,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:q,namedBindings:{type:"array",items:w},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:oe,symbol:w,capability:{enum:rl},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:q,line:oe,symbol:w}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:q,line:oe,rawIntentName:w,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:w}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:q,line:oe,intent:w}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:q,line:oe,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:w},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:w,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:w,referencesGuardOrPublish:{type:"boolean"}}}}}}},arkRunKernelCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind","callee","viaImport"],properties:{file:q,line:oe,kind:{enum:["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"]},callee:w,viaImport:{type:"boolean"},receiver:w,nameLiteral:w}}},arkRunManagedNews:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","typeName"],properties:{file:q,line:oe,typeName:w,importedFrom:w}}},arkRunCompositionRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasKernelFactory"],properties:{file:q,matchedRoot:w,hasKernelFactory:{type:"boolean"}}}},arkRunDeclarations:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","uses","reactsTo","raises","sends"],properties:{file:q,line:oe,uses:{type:"array",items:w},reactsTo:{type:"array",items:w},raises:{type:"array",items:w},sends:{type:"array",items:w}}}},arkOrderPlaneCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","callee"],properties:{file:q,line:oe,callee:w}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:q,line:oe,method:w}}},arkOrderRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasPlaneFactory"],properties:{file:q,matchedRoot:w,hasPlaneFactory:{type:"boolean"}}}},arkOrderXiFieldWrites:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:q,line:oe,key:w}}},arkOrderIngestWritesXi:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line"],properties:{file:q,line:oe}}},arkOrderReleaseKeyCounts:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","keyCount"],properties:{file:q,line:oe,keyCount:{type:"integer",minimum:1}}}},factsHash:w},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 Wn="1.0";function le(e){return`${e.from}->${e.to}`}i(le,"dependencyKey");function ft(e,t,n,r="dependency"){return{id:`${e}:${r}:${le(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${le(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${le(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${le(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${le(t)} from the candidate, then preflight again.`}:{}}}i(ft,"dependencyFinding");function qe(e){let t=[],n=new Map(e.changeMap.map.files.map(f=>[f.path,f])),r=new Map(e.changes.map(f=>[f.path,f])),o=new Map(e.changeMap.map.dependencies.map(f=>[le(f),f])),s=new Map(e.baseDependencies.map(f=>[le(f),f])),a=new Map(e.candidateDependencies.map(f=>[le(f),f]));for(let f of[...n.values()].sort((m,d)=>m.path.localeCompare(d.path))){let m=r.get(f.path);m?m.operation!==f.operation?t.push({id:`contradictory:file:${f.path}`,classification:"contradictory",subject:"file",path:f.path,expectedOperation:f.operation,actualOperation:m.operation,message:`${f.path} was planned as ${f.operation} but the actual operation is ${m.operation}.`,nextAction:`Change ${f.path} to the planned ${f.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${f.path}`,classification:"satisfied",subject:"file",path:f.path,expectedOperation:f.operation,actualOperation:m.operation,message:`${f.path} matches the planned ${f.operation} operation.`}):t.push({id:`missing:file:${f.path}`,classification:"missing",subject:"file",path:f.path,expectedOperation:f.operation,message:`${f.path} was planned as ${f.operation} but is absent from the actual change.`,nextAction:`${f.operation[0].toUpperCase()}${f.operation.slice(1)} ${f.path} in the complete change set, then preflight again.`})}for(let f of[...r.values()].sort((m,d)=>m.path.localeCompare(d.path)))n.has(f.path)||t.push({id:`unplanned:file:${f.path}`,classification:"unplanned",subject:"file",path:f.path,actualOperation:f.operation,message:`${f.path} has an unplanned ${f.operation} operation.`,nextAction:`Remove ${f.path} from the change set, then preflight again.`});let c=new Set;for(let f of[...o.values()].sort((m,d)=>le(m).localeCompare(le(d)))){if(a.has(le(f))){t.push(ft("satisfied",f,`${f.from} -> ${f.to} exists in the candidate architecture.`));continue}let m={from:f.to,to:f.from};a.has(le(m))?(c.add(le(m)),t.push(ft("contradictory",f,`${f.from} -> ${f.to} was planned, but the candidate contains the reverse edge.`))):t.push(ft("missing",f,`${f.from} -> ${f.to} is absent from the candidate architecture.`))}let l=new Set([...n.keys(),...r.keys()]);for(let[f,m]of[...a].sort(([d],[y])=>d.localeCompare(y)))s.has(f)||o.has(f)||c.has(f)||!l.has(m.from)&&!l.has(m.to)||t.push({...ft("unplanned",m,`${m.from} -> ${m.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let u=new Set(e.changeMap.map.files.filter(f=>f.operation==="delete").map(f=>f.path));for(let[f,m]of[...s].sort(([d],[y])=>d.localeCompare(y)))a.has(f)||u.has(m.from)||u.has(m.to)||!l.has(m.from)&&!l.has(m.to)||t.push({...ft("unplanned",m,`${m.from} -> ${m.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let p={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((f,m)=>p[f.classification]-p[m.classification]||(f.subject===m.subject?0:f.subject==="file"?-1:1)||f.id.localeCompare(m.id));let g={satisfied:t.filter(f=>f.classification==="satisfied").length,missing:t.filter(f=>f.classification==="missing").length,contradictory:t.filter(f=>f.classification==="contradictory").length,unplanned:t.filter(f=>f.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:g.missing===0&&g.contradictory===0&&g.unplanned===0,behavioralCompletion:"not-evaluated",summary:g,findings:t}}i(qe,"analyzeArchitectureConvergence");var sl="1.0",qn="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",Ws=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","writes-via-aggregate","no-anemic-model","invariant-coverage"],ol=["no-anemic-model"],Bs={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Yn={$schema:"https://json-schema.org/draft/2020-12/schema",$id:qn,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:qn},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:[...Ws]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:Bs,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:Bs}}}},Le=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 me(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(me,"isObject");function Me(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}a(Me,"propertyPath");function Xe(e){return e===null?"null":Array.isArray(e)?"array":typeof e}a(Xe,"valueType");function Fl(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}a(Fl,"resolveSchemaRef");function bt(e,t,n,r,o){if(t.$ref){let s=Fl(t.$ref,r);if(!s){o.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}bt(e,s,n,r,o);return}if(t.const!==void 0&&!Object.is(e,t.const)){o.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(s=>Object.is(s,e))){o.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!me(e)){o.push({path:n,message:`must be an object; received ${Xe(e)}`});return}let s=t.properties??{};for(let i of t.required??[])e[i]===void 0&&o.push({path:Me(n,i),message:"is required"});if(t.additionalProperties===!1)for(let i of Object.keys(e))i in s||o.push({path:Me(n,i),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let i=t.additionalProperties;for(let l of Object.keys(e))l in s||bt(e[l],i,Me(n,l),r,o)}for(let[i,l]of Object.entries(s))e[i]!==void 0&&bt(e[i],l,Me(n,i),r,o);return}if(t.type==="array"){if(!Array.isArray(e)){o.push({path:n,message:`must be an array; received ${Xe(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&o.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let s=e.map(i=>JSON.stringify(i));new Set(s).size!==s.length&&o.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((s,i)=>bt(s,t.items,`${n}[${i}]`,r,o));return}if(t.type==="string"){if(typeof e!="string"){o.push({path:n,message:`must be a string; received ${Xe(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&o.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&o.push({path:n,message:`must be a boolean; received ${Xe(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){o.push({path:n,message:`must be an integer; received ${Xe(e)}`});return}t.minimum!==void 0&&e<t.minimum&&o.push({path:n,message:`must be at least ${t.minimum}`})}}a(bt,"validateNode");var $l=["deny","advisory"],so='must be "deny", "advisory", or { "default": "deny" | "advisory", "enforce": ["<child id or subtree path>"] }';function Hl(e,t){let n=e.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!me(r))return;let s=r.childSlices;if(!me(s)||s.siblings===void 0)return;let i=s.siblings,l=`$.rules[${o}].childSlices.siblings`;if(typeof i=="string"){$l.includes(i)||t.push({path:l,message:so});return}if(!me(i)){t.push({path:l,message:so});return}for(let u of Object.keys(i))u!=="default"&&u!=="enforce"&&t.push({path:Me(l,u),message:"unknown field"});if(i.default===void 0?t.push({path:`${l}.default`,message:"is required"}):i.default!=="deny"&&i.default!=="advisory"&&t.push({path:`${l}.default`,message:"must be deny or advisory"}),i.enforce===void 0)return;if(!Array.isArray(i.enforce)){t.push({path:`${l}.enforce`,message:"must be an array of child slice ids or subtree paths"});return}let c=new Set;i.enforce.forEach((u,p)=>{let m=`${l}.enforce[${p}]`;if(typeof u!="string"||u.trim().length===0){t.push({path:m,message:"must be a non-empty child slice id or subtree path"});return}let f=Qe(u.trim().replace(/\\/g,"/"));if(f.split("/").some(g=>g.length===0||g==="."||g==="..")){t.push({path:m,message:"must be a child slice id or subtree path without . or .."});return}if(f.includes("*")){t.push({path:m,message:"must be a child slice id or subtree path. * is not a wildcard on siblings.enforce"});return}if(c.has(f)){t.push({path:m,message:"duplicate enforce entry"});return}c.add(f)})})}a(Hl,"validateChildSliceSiblings");var jl="must be a slice id with a slash. A bare name is ambiguous across universes.",Vl="* matches one whole path segment. ** and a partial segment are not wildcards.";function Kl(e){let t=Qe(e.trim().replace(/\\/g,"/"));if(t.length===0)return"must be a non-empty slice id";if(!t.includes("/"))return jl;let n=t.split("/");for(let r of n){if(r.length===0||r==="."||r==="..")return"must be a slice id without empty, . or .. segments";if(r.includes("*")&&r!=="*")return Vl}return null}a(Kl,"childCrossSlicePatternIssue");function oo(e){return Qe(e.trim().replace(/\\/g,"/")).toLowerCase()}a(oo,"childCrossSlicePatternKey");function Ul(e,t){let n=e.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!me(r))return;let s=r.childSlices;if(!me(s)||s.allowedCrossSlice===void 0)return;let i=s.allowedCrossSlice,l=`$.rules[${o}].childSlices.allowedCrossSlice`;if(!Array.isArray(i)){t.push({path:l,message:"must be an array of { from, to } child slice ids"});return}let c=new Set;i.forEach((u,p)=>{let m=`${l}[${p}]`;if(!me(u)){t.push({path:m,message:"must be an object with from and to"});return}for(let g of Object.keys(u))g!=="from"&&g!=="to"&&t.push({path:Me(m,g),message:"unknown field"});for(let g of["from","to"]){let d=u[g],h=`${m}.${g}`;if(typeof d!="string"||d.trim().length===0){t.push({path:h,message:"must be a non-empty slice id"});continue}let E=Kl(d);E&&t.push({path:h,message:E})}if(typeof u.from!="string"||typeof u.to!="string")return;let f=`${oo(u.from)}\0${oo(u.to)}`;if(!f.startsWith("\0")&&!f.endsWith("\0")){if(c.has(f)){t.push({path:m,message:"duplicate child slice allowance"});return}c.add(f)}})})}a(Ul,"validateChildSliceAllowedCrossSlice");var Ze="must be a child of an existing universe (the universe id this rule already names, plus one child segment). A bare name, a universe id alone, an unknown universe, and a wildcard are rejected.",Gl="overlaps a slice folder. An alias covers only files outside the slice trees.",Bl="two slice aliases match the same file";function zl(e){return Qe(e.trim().replace(/\\/g,"/")).toLowerCase().split("/").filter(t=>t.length>0)}a(zl,"aliasPathSegments");function uo(e){let t=[];for(let n of e){if(n.includes("*"))break;t.push(n)}return t}a(uo,"concreteGlobPrefix");function Et(e,t){if(e.length>t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}a(Et,"segmentsArePrefix");function Wl(e){let t=e.split(/[/\\]/).filter(Boolean).map(r=>r.toLowerCase());if(t.length<2||t[0]==="*"||t[0]==="**"||!t.some(r=>r==="*"))return null;let n=[];for(let r of t){if(r==="*"||r==="**")break;if(r.includes("*"))return null;n.push(r)}return n.length>0?n:null}a(Wl,"anchoredSlicePrefix");function ql(e,t){let n=uo(e),r=n.length<e.length,o=n[0]==="src"||n[0]==="app"?n.slice(1):n;return Et(t,n)||Et(t,o)?!0:r?Et(n,t)&&n.length<t.length||Et(n,["src",...t])&&n.length<t.length+1||Et(n,["app",...t])&&n.length<t.length+1:!1}a(ql,"globOverlapsAnchored");function Yl(e,t){for(let r=0;r<e.length;r+=1){if(e[r]!==t&&e[r]!=="*")continue;let o=e.slice(r+1);if(o.length>=2||o.some(s=>s==="*"||s==="**"))return!0}let n=uo(e);return n.length<e.length&&(n.length===0||n.length===1&&(n[0]==="src"||n[0]==="app"))}a(Yl,"globOverlapsBare");function Jl(e,t){let n=t.split(/[/\\]/).filter(Boolean).map(o=>o.toLowerCase());if(n.length===1&&n[0]&&!n[0].includes("*"))return Yl(e,n[0]);let r=Wl(t);return r?ql(e,r):!1}a(Jl,"globOverlapsSliceEntry");function Xl(e){let t=Qe(e.trim().replace(/\\/g,"/"));if(t.length===0)return"must be a non-empty path glob";if(t==="*"||t==="**")return"must not cover the whole tree";for(let n of t.split("/")){if(n.length===0||n==="."||n==="..")return"must be a path glob without empty, . or .. segments";if(!(n==="*"||n==="**")&&(n.includes("*")||n.includes("?")||n.includes("{")||n.includes("[")))return"* matches one whole path segment. ** is a whole segment. A partial segment is not a wildcard."}return null}a(Xl,"aliasGlobIssue");function Zl(e,t){let n=[];if(!Array.isArray(e))return n;let r=t==="stars";for(let o of e){if(typeof o!="string"||o.length===0)continue;let s=o.split(/[/\\]/).filter(Boolean).map(i=>i.toLowerCase());if(s.length===1&&s[0]&&!s[0].includes("*")){n.push({literals:[s[0],null]});continue}if(!s.some(i=>i==="**"||i.includes("*")&&i!=="*")&&s.includes("*")){if(r){let i=-1;for(let l=0;l<s.length;l+=1)s[l]!=="*"&&(i=l);if(i<0)continue;n.push({literals:s.slice(i).map(l=>l==="*"?null:l)});continue}n.push({literals:s.map(i=>i==="*"?null:i)})}}return n}a(Zl,"universeShapes");function io(e,t){return e.literals.length!==t.length?!1:e.literals.every((n,r)=>n===null||n===t[r])}a(io,"shapeMatches");function Ql(e,t){let n=Qe(e.trim().replace(/\\/g,"/"));if(n.length===0||n.split("/").some(o=>o.length===0||o==="."||o==="..")||n.includes("*")||!n.includes("/"))return Ze;let r=n.split("/").map(o=>o.toLowerCase());return t.length===0||t.some(o=>io(o,r))?Ze:t.some(o=>io(o,r.slice(0,-1)))?null:Ze}a(Ql,"aliasTargetIssue");function ao(e){let t=e[0];return(t==="src"||t==="app")&&e.length>1?[e,e.slice(1)]:[e]}a(ao,"aliasGlobVariants");function ec(e,t){let n=ao(e),r=ao(t);for(let o of n)if(De(o,t,0,0,new Map))return!0;for(let o of r)if(De(e,o,0,0,new Map))return!0;return!1}a(ec,"aliasesCanMatchSameFile");function De(e,t,n,r,o){let s=`${n}:${r}`,i=o.get(s);if(i!==void 0)return i;let l=!1;if(n===e.length&&r===t.length)l=!0;else if(n<e.length&&e[n]==="**")l=De(e,t,n+1,r,o)||r<t.length&&De(e,t,n,r+1,o);else if(r<t.length&&t[r]==="**")l=De(e,t,n,r+1,o)||n<e.length&&De(e,t,n+1,r,o);else if(n<e.length&&r<t.length){let c=e[n],u=t[r];(c===u||c==="*"||u==="*")&&(l=De(e,t,n+1,r+1,o))}return o.set(s,l),l}a(De,"globsCanMatchSame");function tc(e,t){let n=e.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!me(r))return;let s=r.childSlices;if(!me(s)||s.sliceAliases===void 0)return;let i=s.sliceAliases,l=`$.rules[${o}].childSlices.sliceAliases`;if(!Array.isArray(i)){t.push({path:l,message:"must be an array of { from, to } slice aliases"});return}let c=Zl(r.sliceFolders,r.sliceIdentity),u=[...Array.isArray(r.sliceFolders)?r.sliceFolders:[],...Array.isArray(s.sliceFolders)?s.sliceFolders:[]].filter(m=>typeof m=="string"&&m.length>0),p=[];i.forEach((m,f)=>{let g=`${l}[${f}]`;if(!me(m)){t.push({path:g,message:"must be an object with from and to"});return}for(let E of Object.keys(m))E!=="from"&&E!=="to"&&t.push({path:Me(g,E),message:"unknown field"});let d=m.from,h=m.to;if(typeof d!="string"||d.trim().length===0)t.push({path:`${g}.from`,message:"must be a non-empty path glob"});else{let E=Xl(d);if(E)t.push({path:`${g}.from`,message:E});else{let _=zl(d);u.some(k=>Jl(_,k))&&t.push({path:`${g}.from`,message:Gl});for(let k of p)if(ec(k,_)){t.push({path:g,message:Bl});break}p.push(_)}}if(typeof h!="string"||h.trim().length===0)t.push({path:`${g}.to`,message:Ze});else{let E=Ql(h,c);E&&t.push({path:`${g}.to`,message:E})}})})}a(tc,"validateChildSliceAliases");function nc(e,t){let n=e.layers;Array.isArray(n)&&n.forEach((r,o)=>{if(!r||typeof r!="object"||Array.isArray(r)||!("owners"in r))return;let s=r.owners;Array.isArray(s)&&s.forEach((i,l)=>{typeof i=="string"&&(no(i)||t.push({path:`$.layers[${o}].owners[${l}]`,message:"must be a GitHub handle or email (not a display name)"}))})})}a(nc,"validateLayerOwners");function rc(e){let t={...e,$schema:e.$schema===void 0?tn:e.$schema,schemaVersion:e.schemaVersion===void 0?le:e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?nn.map(n=>({...n})):e.rules};return e.arkRun!==void 0&&(t.arkRun=Xs(e.arkRun)),e.arkOrder!==void 0&&(t.arkOrder=Zs(e.arkOrder)),t}a(rc,"defaultedConfig");function sc(e){return e===le?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}a(sc,"migratedFromOf");function oc(){let e=new Set([le]);for(let t of rr)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}a(oc,"knownInputVersions");function ic(e,t="ark.config.json"){if(!me(e))throw new Ie(t,[{path:"$",message:`must be an object; received ${Xe(e)}`}]);let n=oc(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new Ie(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected ${le}`}]);if(r!=="unversioned"&&!n.has(r))throw new Ie(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${le}`}]);let o=r,s={...e},i=0;for(;o!==le&&i<rr.length+1;){i+=1;let l=rr.find(c=>c.from===o);if(!l)throw new Ie(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(o)}; expected ${le}`}]);o=l.to,s.schemaVersion=o}if(o!==le)throw new Ie(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${le}`}]);return{candidate:rc(s),migratedFrom:sc(r)}}a(ic,"migrateArkConfig");function rn(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=ic(e,t),o=[];if(bt(n,sr,"$",sr,o),Qs(n,o),eo(n,o),nc(n,o),Hl(n,o),Ul(n,o),tc(n,o),o.length>0)throw new Ie(t,o);return{config:n,migratedFrom:r}}a(rn,"loadArkConfigContract");function or(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new Ie(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return rn(n,t)}a(or,"parseArkConfigJson");function po(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:tn,schemaVersion:le};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}a(po,"withArkConfigMetadata");function Qe(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}a(Qe,"trimTrailingSlashes");function ac(e){return e.endsWith(".")?e:`${e}.`}a(ac,"normalizePrefix");function lc(e,t){let n=e.prefixes.length?Math.max(...e.prefixes.map(o=>o.length)):0;return(t.prefixes.length?Math.max(...t.prefixes.map(o=>o.length)):0)-n}a(lc,"byLongestPrefix");function on(e){let t=e.layers.map(o=>({...o,prefixes:o.prefixes.map(ac)})),n=[...t].sort(lc),r=[...e.rules??[]];return{name:e.name,layers:t,rules:r,resolveLayer(o){return t.find(s=>s.match?.(o))?.name??n.find(s=>s.prefixes.some(i=>o.startsWith(i)))?.name}}}a(on,"createArchitectureProfile");function fo(e,t={}){return on({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,r)=>({name:n.name,prefixes:n.intentPrefixes??[],description:n.description,trustBoundary:n.trustBoundary,owners:n.owners,order:r+1})),rules:e.rules??[]})}a(fo,"createArchitectureProfileFromArkConfig");var cc=[{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}],sn=on({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:cc,rules:nn.map(e=>({...e}))}),dc={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 go(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return po({include:e.include??[t],layers:sn.layers.map(o=>({name:o.name,patterns:(dc[o.name]??[o.name]).map(s=>`${r}${s}/**`),intentPrefixes:o.prefixes,optional:n})),rules:[...sn.rules]})}a(go,"createElevenLayerArkConfig");function ee(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")}`}a(ee,"deterministicHash");function K(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(K).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${K(t[n])}`).join(",")}}`}a(K,"stableSerialize");var Fe="1.2";var mo=["network","filesystem","clock","randomness","environment","process","persistence"];function Z(e,t){let n=K(e),r=K(t);return n<r?-1:n>r?1:0}a(Z,"compareCanonical");function re(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}a(re,"sortedUnique");function vt(e){let t={schemaVersion:"1.2",include:re(e.include??[]),exclude:re(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:re(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:re(n.patterns??[]),exclude:re(n.exclude??[]),forbiddenGlobals:re(n.forbiddenGlobals??[]),intentPrefixes:re(n.intentPrefixes??[]),capabilityDeny:re(n.capabilities?.deny??[]),pure:n.pure===!0})).sort(Z),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:re(e.arkRun.compositionRoots),managedLayers:re(e.arkRun.managedLayers),requireDeclarations:e.arkRun.requireDeclarations===!0}}:{}};return ee(K(t))}a(vt,"resolvedFactsEvidenceRequirementsHash");function uc(e){let t=e.completenessReasons.map(S=>({code:S.code,message:S.message,...S.file?{file:S.file}:{}})).sort(Z),n=e.files.map(S=>({...S,typeOnlyExportNames:re(S.typeOnlyExportNames)})).sort((S,L)=>S.path<L.path?-1:S.path>L.path?1:0),r=e.dependencies.map(S=>({...S,...S.namedBindings?{namedBindings:re(S.namedBindings)}:{}})).sort(Z),o=e.capabilityUses.map(S=>({...S})).sort(Z),s=e.ambientUses.map(S=>({...S})).sort(Z),i=e.publishCalls.map(S=>({...S})).sort(Z),l=e.intentReferences.map(S=>({...S})).sort(Z),c=e.safetyUses.map(S=>({...S})).sort(Z),u=(e.classShapes??[]).map(S=>({...S,mutatingMethods:[...S.mutatingMethods??[]].map(L=>({...L}))})).sort(Z),p=(e.arkRunKernelCalls??[]).map(S=>({...S})).sort(Z),m=(e.arkRunManagedNews??[]).map(S=>({...S})).sort(Z),f=(e.arkRunCompositionRootHits??[]).map(S=>({...S})).sort(Z),g=(e.arkRunDeclarations??[]).map(S=>({...S,uses:re(S.uses),reactsTo:re(S.reactsTo),raises:re(S.raises),sends:re(S.sends)})).sort(Z),d=(e.arkOrderPlaneCalls??[]).map(S=>({...S})).sort(Z),h=(e.arkOrderGenericUpdates??[]).map(S=>({...S})).sort(Z),E=(e.arkOrderRootHits??[]).map(S=>({...S})).sort(Z),_=(e.arkOrderXiFieldWrites??[]).map(S=>({...S})).sort(Z),k=(e.arkOrderIngestWritesXi??[]).map(S=>({...S})).sort(Z),b=(e.arkOrderReleaseKeyCounts??[]).map(S=>({...S})).sort(Z),O=e.files.map(({path:S,contentHash:L})=>({path:S,contentHash:L})).sort((S,L)=>S.path<L.path?-1:S.path>L.path?1:0),D=ee(K(O));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:o,ambientUses:s,publishCalls:i,intentReferences:l,safetyUses:c,classShapes:u,arkRunKernelCalls:p,arkRunManagedNews:m,arkRunCompositionRootHits:f,arkRunDeclarations:g,arkOrderPlaneCalls:d,arkOrderGenericUpdates:h,arkOrderRootHits:E,arkOrderXiFieldWrites:_,arkOrderIngestWritesXi:k,arkOrderReleaseKeyCounts:b}}a(uc,"canonicalResolvedFactsInput");function ho(e){let t=uc(e);return{...t,factsHash:ee(K(t))}}a(ho,"createCanonicalResolvedCandidateFacts");function ir(e){return ho(Ao(H(e,"$"),!1))}a(ir,"createResolvedCandidateFacts");function H(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}a(H,"asRecord");function U(e,t,n){let r=new Set(t),o=Object.keys(e).find(s=>!r.has(s));if(o)throw new Error(`${n}.${o} is not part of schema ${"1.2"}.`)}a(U,"assertOnlyKeys");function $(e,t,n){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`${n}.${t} must be a non-empty string.`);return r}a($,"requiredText");function Ee(e,t,n){if(e[t]!==void 0)return $(e,t,n)}a(Ee,"optionalText");function W(e,t,n){let r=$(e,t,n),o=r.replace(/\\/g,"/");if(!o||o.startsWith("/")||/^[A-Za-z]:\//.test(o)||/[\u0000-\u001f\u007f]/.test(o))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let s=[];for(let l of o.split("/"))if(!(!l||l==="."))if(l===".."){if(s.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);s.pop()}else s.push(l);let i=s.join("/");if(!i||i!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return i}a(W,"requiredProjectPath");function q(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}a(q,"requiredBoolean");function yo(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)}a(yo,"requiredInteger");function se(e,t,n){let r=yo(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}a(se,"requiredPositiveInteger");function Y(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}a(Y,"requiredArray");function be(e,t,n,r){let o=e[t];if(typeof o!="string"||!n.includes(o))throw new Error(`${r}.${t} must be one of ${n.join(", ")}.`);return o}a(be,"enumValue");function et(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]}a(et,"parseStringArray");function pc(e,t,n){let r=new Set;for(let o of e){let s=t(o);if(r.has(s))throw new Error(`${n} must not contain duplicate facts (${s}).`);r.add(s)}}a(pc,"assertUnique");function Ao(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=be(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=be(e,"completeness",["complete","partial","unavailable"],"$"),o=Y(e,"completenessReasons","$").map((v,x)=>{let y=`$.completenessReasons[${x}]`,R=H(v,y);U(R,["code","message","file"],y);let F=R.file===void 0?void 0:W(R,"file",y);return{code:$(R,"code",y),message:$(R,"message",y),...F?{file:F}:{}}});if(r==="complete"&&o.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(r!=="complete"&&o.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let s=Y(e,"files","$").map((v,x)=>{let y=`$.files[${x}]`,R=H(v,y);return U(R,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],y),{path:W(R,"path",y),contentHash:$(R,"contentHash",y),parseStatus:be(R,"parseStatus",["parsed","invalid"],y),parseDiagnosticCount:yo(R,"parseDiagnosticCount",y),exportsOnlyTypes:q(R,"exportsOnlyTypes",y),typeOnlyExportNames:et(R.typeOnlyExportNames,`${y}.typeOnlyExportNames`),hasTopLevelSideEffects:q(R,"hasTopLevelSideEffects",y)}}),i=Y(e,"dependencies","$").map((v,x)=>{let y=`$.dependencies[${x}]`,R=H(v,y);U(R,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],y);let F=Ee(R,"specifier",y),Q=Ee(R,"target",y),Ce=be(R,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],y);if(Ce==="resolved-project"&&!Q)throw new Error(`${y}.target is required for resolved-project dependencies.`);if(Ce!=="resolved-project"&&Q)throw new Error(`${y}.target is only allowed for resolved-project dependencies.`);if(Ce!=="dynamic"&&!F)throw new Error(`${y}.specifier is required unless resolution is dynamic.`);return{from:W(R,"from",y),...F?{specifier:F}:{},kind:be(R,"kind",["import","export","dynamic-import","require"],y),typeOnly:q(R,"typeOnly",y),line:se(R,"line",y),resolution:Ce,...Q?{target:W(R,"target",y)}:{},...R.namedBindings!==void 0?{namedBindings:et(R.namedBindings,`${y}.namedBindings`)}:{},...R.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:q(R,"targetTypeOnlyExports",y)}:{},...R.sourcePureTypeModule!==void 0?{sourcePureTypeModule:q(R,"sourcePureTypeModule",y)}:{},...R.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:q(R,"namedBindingsTypeOnly",y)}:{},...R.portProofEligible!==void 0?{portProofEligible:q(R,"portProofEligible",y)}:{}}}),l=Y(e,"capabilityUses","$").map((v,x)=>{let y=`$.capabilityUses[${x}]`,R=H(v,y);return U(R,["file","line","symbol","capability","source"],y),{file:W(R,"file",y),line:se(R,"line",y),symbol:$(R,"symbol",y),capability:be(R,"capability",mo,y),source:be(R,"source",["ambient-global","import-based"],y)}}),c=Y(e,"ambientUses","$").map((v,x)=>{let y=`$.ambientUses[${x}]`,R=H(v,y);return U(R,["file","line","symbol"],y),{file:W(R,"file",y),line:se(R,"line",y),symbol:$(R,"symbol",y)}}),u=Y(e,"publishCalls","$").map((v,x)=>{let y=`$.publishCalls[${x}]`,R=H(v,y);U(R,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],y);let F=Ee(R,"rawIntentName",y),Q=Ee(R,"sourceIntent",y);return{file:W(R,"file",y),line:se(R,"line",y),...F?{rawIntentName:F}:{},objectHasIntent:q(R,"objectHasIntent",y),arkPublishCandidate:q(R,"arkPublishCandidate",y),hasSource:q(R,"hasSource",y),...Q?{sourceIntent:Q}:{}}}),p=Y(e,"intentReferences","$").map((v,x)=>{let y=`$.intentReferences[${x}]`,R=H(v,y);return U(R,["file","line","intent"],y),{file:W(R,"file",y),line:se(R,"line",y),intent:$(R,"intent",y)}}),m=Y(e,"safetyUses","$").map((v,x)=>{let y=`$.safetyUses[${x}]`,R=H(v,y);U(R,["file","line","kind","symbol"],y);let F=Ee(R,"symbol",y),Q=be(R,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],y);if(Q==="in-memory-store"&&!F)throw new Error(`${y}.symbol is required for in-memory-store facts.`);if(Q!=="in-memory-store"&&F)throw new Error(`${y}.symbol is only allowed for in-memory-store facts.`);return{file:W(R,"file",y),line:se(R,"line",y),kind:Q,...F?{symbol:F}:{}}});pc(s,v=>v.path,"$.files");let f=new Set(s.map(v=>v.path));for(let v of s){if(v.parseStatus==="parsed"&&v.parseDiagnosticCount!==0)throw new Error(`$.files[${v.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(v.parseStatus==="invalid"&&v.parseDiagnosticCount===0)throw new Error(`$.files[${v.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&s.some(v=>v.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let v of i)if(!f.has(v.from))throw new Error(`$.dependencies references missing source file ${v.from}.`);let d=(e.arkRunKernelCalls===void 0?[]:Y(e,"arkRunKernelCalls","$")).map((v,x)=>{let y=`$.arkRunKernelCalls[${x}]`,R=H(v,y);U(R,["file","line","kind","callee","viaImport","receiver","nameLiteral"],y);let F=Ee(R,"receiver",y),Q=Ee(R,"nameLiteral",y);return{file:W(R,"file",y),line:se(R,"line",y),kind:be(R,"kind",["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"],y),callee:$(R,"callee",y),viaImport:q(R,"viaImport",y),...F?{receiver:F}:{},...Q?{nameLiteral:Q}:{}}}),E=(e.arkRunManagedNews===void 0?[]:Y(e,"arkRunManagedNews","$")).map((v,x)=>{let y=`$.arkRunManagedNews[${x}]`,R=H(v,y);U(R,["file","line","typeName","importedFrom"],y);let F=Ee(R,"importedFrom",y);return{file:W(R,"file",y),line:se(R,"line",y),typeName:$(R,"typeName",y),...F?{importedFrom:F}:{}}}),k=(e.arkRunCompositionRootHits===void 0?[]:Y(e,"arkRunCompositionRootHits","$")).map((v,x)=>{let y=`$.arkRunCompositionRootHits[${x}]`,R=H(v,y);return U(R,["file","matchedRoot","hasKernelFactory"],y),{file:W(R,"file",y),matchedRoot:$(R,"matchedRoot",y),hasKernelFactory:q(R,"hasKernelFactory",y)}}),b=e.arkRunDeclarations===void 0?[]:Y(e,"arkRunDeclarations","$"),D=(e.arkOrderPlaneCalls===void 0?[]:Y(e,"arkOrderPlaneCalls","$")).map((v,x)=>{let y=`$.arkOrderPlaneCalls[${x}]`,R=H(v,y);return U(R,["file","line","callee"],y),{file:W(R,"file",y),line:se(R,"line",y),callee:$(R,"callee",y)}}),L=(e.arkOrderGenericUpdates===void 0?[]:Y(e,"arkOrderGenericUpdates","$")).map((v,x)=>{let y=`$.arkOrderGenericUpdates[${x}]`,R=H(v,y);return U(R,["file","line","method"],y),{file:W(R,"file",y),line:se(R,"line",y),method:$(R,"method",y)}}),T=(e.arkOrderRootHits===void 0?[]:Y(e,"arkOrderRootHits","$")).map((v,x)=>{let y=`$.arkOrderRootHits[${x}]`,R=H(v,y);return U(R,["file","matchedRoot","hasPlaneFactory"],y),{file:W(R,"file",y),matchedRoot:$(R,"matchedRoot",y),hasPlaneFactory:q(R,"hasPlaneFactory",y)}}),P=(e.arkOrderXiFieldWrites===void 0?[]:Y(e,"arkOrderXiFieldWrites","$")).map((v,x)=>{let y=`$.arkOrderXiFieldWrites[${x}]`,R=H(v,y);return U(R,["file","line","key"],y),{file:W(R,"file",y),line:se(R,"line",y),key:$(R,"key",y)}}),z=(e.arkOrderIngestWritesXi===void 0?[]:Y(e,"arkOrderIngestWritesXi","$")).map((v,x)=>{let y=`$.arkOrderIngestWritesXi[${x}]`,R=H(v,y);return U(R,["file","line"],y),{file:W(R,"file",y),line:se(R,"line",y)}}),Se=(e.arkOrderReleaseKeyCounts===void 0?[]:Y(e,"arkOrderReleaseKeyCounts","$")).map((v,x)=>{let y=`$.arkOrderReleaseKeyCounts[${x}]`,R=H(v,y);return U(R,["file","line","keyCount"],y),{file:W(R,"file",y),line:se(R,"line",y),keyCount:se(R,"keyCount",y)}}),lt=b.map((v,x)=>{let y=`$.arkRunDeclarations[${x}]`,R=H(v,y);return U(R,["file","line","uses","reactsTo","raises","sends"],y),{file:W(R,"file",y),line:se(R,"line",y),uses:et(R.uses,`${y}.uses`),reactsTo:et(R.reactsTo,`${y}.reactsTo`),raises:et(R.raises,`${y}.raises`),sends:et(R.sends,`${y}.sends`)}});for(let[v,x]of[["$.capabilityUses",l],["$.ambientUses",c],["$.publishCalls",u],["$.intentReferences",p],["$.safetyUses",m],["$.arkRunKernelCalls",d],["$.arkRunManagedNews",E],["$.arkRunCompositionRootHits",k],["$.arkRunDeclarations",lt],["$.arkOrderPlaneCalls",D],["$.arkOrderGenericUpdates",L],["$.arkOrderRootHits",T],["$.arkOrderXiFieldWrites",P],["$.arkOrderIngestWritesXi",z],["$.arkOrderReleaseKeyCounts",Se]])for(let y of x)if(!f.has(y.file))throw new Error(`${v} references missing file ${y.file}.`);let Ut=Ee(e,"projectPackageName","$"),ks=(e.classShapes===void 0?[]:Y(e,"classShapes","$")).map((v,x)=>{let y=`$.classShapes[${x}]`,R=H(v,y);U(R,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],y);let F=Y(R,"mutatingMethods",y).map((Q,Ce)=>{let A=`${y}.mutatingMethods[${Ce}]`,ie=H(Q,A);return U(ie,["name","referencesGuardOrPublish"],A),{name:$(ie,"name",A),referencesGuardOrPublish:q(ie,"referencesGuardOrPublish",A)}});return{file:W(R,"file",y),className:$(R,"className",y),exported:q(R,"exported",y),hasPublicMutableFields:q(R,"hasPublicMutableFields",y),hasPublicSetters:q(R,"hasPublicSetters",y),hasPublicConstructor:q(R,"hasPublicConstructor",y),hasStaticFactory:q(R,"hasStaticFactory",y),mutatingMethods:F,...R.dataOnly===void 0?{}:{dataOnly:q(R,"dataOnly",y)}}});return{schemaVersion:n,completeness:r,completenessReasons:o,resolverIdentity:$(e,"resolverIdentity","$"),compilerIdentity:$(e,"compilerIdentity","$"),compilerOptionsHash:$(e,"compilerOptionsHash","$"),tsconfigHash:$(e,"tsconfigHash","$"),evidenceRequirementsHash:$(e,"evidenceRequirementsHash","$"),...Ut?{projectPackageName:Ut}:{},files:s,dependencies:i,capabilityUses:l,ambientUses:c,publishCalls:u,intentReferences:p,safetyUses:m,classShapes:ks,arkRunKernelCalls:d,arkRunManagedNews:E,arkRunCompositionRootHits:k,arkRunDeclarations:lt,arkOrderPlaneCalls:D,arkOrderGenericUpdates:L,arkOrderRootHits:T,arkOrderXiFieldWrites:P,arkOrderIngestWritesXi:z,arkOrderReleaseKeyCounts:Se}}a(Ao,"parseResolvedFactsInput");function xe(e){let t=H(e,"$"),n=$(t,"factsHash","$"),r=$(t,"candidateTreeHash","$"),o=ho(Ao(t,!0));if(o.factsHash!==n)throw new Error(`$.factsHash does not match the canonical payload (${o.factsHash}).`);if(r!==o.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${o.candidateTreeHash}).`);return o}a(xe,"loadResolvedCandidateFacts");var fc=["network","filesystem","clock","randomness","environment","process","persistence"],N={type:"string",minLength:1},ae={type:"integer",minimum:1},J={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},ar={$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:J}}},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:J,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:J,specifier:N,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:ae,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:J,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:J,line:ae,symbol:N,capability:{enum:fc},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:J,line:ae,symbol:N}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:J,line:ae,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:J,line:ae,intent:N}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:J,line:ae,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:J,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:J,line:ae,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:J,line:ae,typeName:N,importedFrom:N}}},arkRunCompositionRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasKernelFactory"],properties:{file:J,matchedRoot:N,hasKernelFactory:{type:"boolean"}}}},arkRunDeclarations:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","uses","reactsTo","raises","sends"],properties:{file:J,line:ae,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:J,line:ae,callee:N}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:J,line:ae,method:N}}},arkOrderRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasPlaneFactory"],properties:{file:J,matchedRoot:N,hasPlaneFactory:{type:"boolean"}}}},arkOrderXiFieldWrites:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:J,line:ae,key:N}}},arkOrderIngestWritesXi:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line"],properties:{file:J,line:ae}}},arkOrderReleaseKeyCounts:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","keyCount"],properties:{file:J,line:ae,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 lr="1.0";function ce(e){return`${e.from}->${e.to}`}a(ce,"dependencyKey");function Ct(e,t,n,r="dependency"){return{id:`${e}:${r}:${ce(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${ce(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${ce(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${ce(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${ce(t)} from the candidate, then preflight again.`}:{}}}a(Ct,"dependencyFinding");function tt(e){let t=[],n=new Map(e.changeMap.map.files.map(f=>[f.path,f])),r=new Map(e.changes.map(f=>[f.path,f])),o=new Map(e.changeMap.map.dependencies.map(f=>[ce(f),f])),s=new Map(e.baseDependencies.map(f=>[ce(f),f])),i=new Map(e.candidateDependencies.map(f=>[ce(f),f]));for(let f of[...n.values()].sort((g,d)=>g.path.localeCompare(d.path))){let g=r.get(f.path);g?g.operation!==f.operation?t.push({id:`contradictory:file:${f.path}`,classification:"contradictory",subject:"file",path:f.path,expectedOperation:f.operation,actualOperation:g.operation,message:`${f.path} was planned as ${f.operation} but the actual operation is ${g.operation}.`,nextAction:`Change ${f.path} to the planned ${f.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${f.path}`,classification:"satisfied",subject:"file",path:f.path,expectedOperation:f.operation,actualOperation:g.operation,message:`${f.path} matches the planned ${f.operation} operation.`}):t.push({id:`missing:file:${f.path}`,classification:"missing",subject:"file",path:f.path,expectedOperation:f.operation,message:`${f.path} was planned as ${f.operation} but is absent from the actual change.`,nextAction:`${f.operation[0].toUpperCase()}${f.operation.slice(1)} ${f.path} in the complete change set, then preflight again.`})}for(let f of[...r.values()].sort((g,d)=>g.path.localeCompare(d.path)))n.has(f.path)||t.push({id:`unplanned:file:${f.path}`,classification:"unplanned",subject:"file",path:f.path,actualOperation:f.operation,message:`${f.path} has an unplanned ${f.operation} operation.`,nextAction:`Remove ${f.path} from the change set, then preflight again.`});let l=new Set;for(let f of[...o.values()].sort((g,d)=>ce(g).localeCompare(ce(d)))){if(i.has(ce(f))){t.push(Ct("satisfied",f,`${f.from} -> ${f.to} exists in the candidate architecture.`));continue}let g={from:f.to,to:f.from};i.has(ce(g))?(l.add(ce(g)),t.push(Ct("contradictory",f,`${f.from} -> ${f.to} was planned, but the candidate contains the reverse edge.`))):t.push(Ct("missing",f,`${f.from} -> ${f.to} is absent from the candidate architecture.`))}let c=new Set([...n.keys(),...r.keys()]);for(let[f,g]of[...i].sort(([d],[h])=>d.localeCompare(h)))s.has(f)||o.has(f)||l.has(f)||!c.has(g.from)&&!c.has(g.to)||t.push({...Ct("unplanned",g,`${g.from} -> ${g.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let u=new Set(e.changeMap.map.files.filter(f=>f.operation==="delete").map(f=>f.path));for(let[f,g]of[...s].sort(([d],[h])=>d.localeCompare(h)))i.has(f)||u.has(g.from)||u.has(g.to)||!c.has(g.from)&&!c.has(g.to)||t.push({...Ct("unplanned",g,`${g.from} -> ${g.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let p={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((f,g)=>p[f.classification]-p[g.classification]||(f.subject===g.subject?0:f.subject==="file"?-1:1)||f.id.localeCompare(g.id));let m={satisfied:t.filter(f=>f.classification==="satisfied").length,missing:t.filter(f=>f.classification==="missing").length,contradictory:t.filter(f=>f.classification==="contradictory").length,unplanned:t.filter(f=>f.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:m.missing===0&&m.contradictory===0&&m.unplanned===0,behavioralCompletion:"not-evaluated",summary:m,findings:t}}a(tt,"analyzeArchitectureConvergence");var gc="1.0",cr="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",So=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","writes-via-aggregate","no-anemic-model","invariant-coverage"],mc=["no-anemic-model"],Ro={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},dr={$schema:"https://json-schema.org/draft/2020-12/schema",$id:cr,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:cr},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:[...So]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:Ro,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:Ro}}}},$e=class extends Error{static{a(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 yt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(yt,"isObject");function qt(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}i(qt,"propertyPath");function mt(e){return e===null?"null":Array.isArray(e)?"array":typeof e}i(mt,"valueType");function al(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}i(al,"resolveSchemaRef");function gt(e,t,n,r,o){if(t.$ref){let s=al(t.$ref,r);if(!s){o.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}gt(e,s,n,r,o);return}if(t.const!==void 0&&!Object.is(e,t.const)){o.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(s=>Object.is(s,e))){o.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!yt(e)){o.push({path:n,message:`must be an object; received ${mt(e)}`});return}let s=t.properties??{};for(let a of t.required??[])e[a]===void 0&&o.push({path:qt(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in s||o.push({path:qt(n,a),message:"unknown field"});else if(yt(t.additionalProperties)){let a=t.additionalProperties;for(let c of Object.keys(e))c in s||gt(e[c],a,qt(n,c),r,o)}for(let[a,c]of Object.entries(s))e[a]!==void 0&&gt(e[a],c,qt(n,a),r,o);return}if(t.type==="array"){if(!Array.isArray(e)){o.push({path:n,message:`must be an array; received ${mt(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&o.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let s=e.map(a=>JSON.stringify(a));new Set(s).size!==s.length&&o.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((s,a)=>gt(s,t.items,`${n}[${a}]`,r,o));return}if(t.type==="string"){if(typeof e!="string"){o.push({path:n,message:`must be a string; received ${mt(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&o.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}t.type==="boolean"&&typeof e!="boolean"&&o.push({path:n,message:`must be a boolean; received ${mt(e)}`})}i(gt,"validateNode");function il(e){return{...e,$schema:e.$schema===void 0?qn: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(il,"defaultedArkRules");function zs(e){return e==="enforced"?"enforced":"advisory"}i(zs,"normalizeMode");function ll(e){return ol.includes(e)}i(ll,"isTier2Sensor");function cl(e,t){let n=Array.isArray(e.structure)?e.structure:[],r=Array.isArray(e.invariants)?e.invariants:[],o=new Set;n.forEach((s,a)=>{if(!yt(s))return;let c=typeof s.id=="string"?s.id:"";c&&(o.has(c)&&t.push({path:`$.structure[${a}].id`,message:`duplicate rule id ${JSON.stringify(c)}`}),o.add(c)),typeof s.sensor=="string"&&ll(s.sensor)&&s.mode==="enforced"&&t.push({path:`$.structure[${a}].mode`,message:`${c?`rule ${JSON.stringify(c)} uses sensor `:"sensor "}${JSON.stringify(s.sensor)}, which is Tier-2 advisory-only and cannot be enforced${c?" (arkgate-check --sensors lists which sensors can)":""}`}),Array.isArray(s.appliesTo)&&s.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((s,a)=>{if(!yt(s))return;let c=typeof s.id=="string"?s.id:"";c&&(o.has(c)&&t.push({path:`$.invariants[${a}].id`,message:`duplicate rule id ${JSON.stringify(c)}`}),o.add(c)),Array.isArray(s.appliesTo)&&s.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(cl,"validateSemantics");function Yt(e,t="arkrules.json",n){if(!yt(e))throw new Le(t,[{path:"$",message:`must be an object; received ${mt(e)}`}]);let r=il(e),o=[];if(gt(r,Yn,"$",Yn,o),cl(r,o),n!==void 0&&typeof r.layer=="string"&&r.layer!==n&&o.push({path:"$.layer",message:`must match referencing key ${JSON.stringify(n)}; received ${JSON.stringify(r.layer)}`}),o.length>0)throw new Le(t,o);return{config:r}}i(Yt,"loadArkRulesContract");function dl(e,t="arkrules.json",n){let r;try{r=JSON.parse(e)}catch(o){throw new Le(t,[{path:"$",message:`invalid JSON: ${o instanceof Error?o.message:String(o)}`}])}return Yt(r,t,n)}i(dl,"parseArkRulesJson");function Jn(e){let t={},n=[],r=[],o=[...e].sort((s,a)=>s.layer.localeCompare(a.layer));for(let s of o){let a=(s.file.structure??[]).map(l=>({...l,mode:zs(l.mode),provenance:{sourceFile:s.sourceFile,ruleId:l.id,layer:s.layer}})),c=(s.file.invariants??[]).map(l=>({...l,mode:zs(l.mode),provenance:{sourceFile:s.sourceFile,ruleId:l.id,layer:s.layer}}));t[s.layer]={sourceFile:s.sourceFile,structure:a,invariants:c},n.push(...a),r.push(...c)}return n.sort((s,a)=>{let c=s.provenance.layer.localeCompare(a.provenance.layer);return c!==0?c:s.id.localeCompare(a.id)}),r.sort((s,a)=>{let c=s.provenance.layer.localeCompare(a.provenance.layer);return c!==0?c:s.id.localeCompare(a.id)}),{schemaVersion:"1.0",byLayer:t,structure:n,invariants:r}}i(Jn,"buildEffectiveArkRules");function De(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}i(De,"emptyEffectiveArkRules");var Jt=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 xt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(xt,"isObject");function an(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}a(an,"propertyPath");function _t(e){return e===null?"null":Array.isArray(e)?"array":typeof e}a(_t,"valueType");function hc(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}a(hc,"resolveSchemaRef");function Ot(e,t,n,r,o){if(t.$ref){let s=hc(t.$ref,r);if(!s){o.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}Ot(e,s,n,r,o);return}if(t.const!==void 0&&!Object.is(e,t.const)){o.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(s=>Object.is(s,e))){o.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!xt(e)){o.push({path:n,message:`must be an object; received ${_t(e)}`});return}let s=t.properties??{};for(let i of t.required??[])e[i]===void 0&&o.push({path:an(n,i),message:"is required"});if(t.additionalProperties===!1)for(let i of Object.keys(e))i in s||o.push({path:an(n,i),message:"unknown field"});else if(xt(t.additionalProperties)){let i=t.additionalProperties;for(let l of Object.keys(e))l in s||Ot(e[l],i,an(n,l),r,o)}for(let[i,l]of Object.entries(s))e[i]!==void 0&&Ot(e[i],l,an(n,i),r,o);return}if(t.type==="array"){if(!Array.isArray(e)){o.push({path:n,message:`must be an array; received ${_t(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&o.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let s=e.map(i=>JSON.stringify(i));new Set(s).size!==s.length&&o.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((s,i)=>Ot(s,t.items,`${n}[${i}]`,r,o));return}if(t.type==="string"){if(typeof e!="string"){o.push({path:n,message:`must be a string; received ${_t(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&o.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}t.type==="boolean"&&typeof e!="boolean"&&o.push({path:n,message:`must be a boolean; received ${_t(e)}`})}a(Ot,"validateNode");function yc(e){return{...e,$schema:e.$schema===void 0?cr: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}}a(yc,"defaultedArkRules");function ko(e){return e==="enforced"?"enforced":"advisory"}a(ko,"normalizeMode");function Ac(e){return mc.includes(e)}a(Ac,"isTier2Sensor");function Rc(e,t){let n=Array.isArray(e.structure)?e.structure:[],r=Array.isArray(e.invariants)?e.invariants:[],o=new Set;n.forEach((s,i)=>{if(!xt(s))return;let l=typeof s.id=="string"?s.id:"";l&&(o.has(l)&&t.push({path:`$.structure[${i}].id`,message:`duplicate rule id ${JSON.stringify(l)}`}),o.add(l)),typeof s.sensor=="string"&&Ac(s.sensor)&&s.mode==="enforced"&&t.push({path:`$.structure[${i}].mode`,message:`${l?`rule ${JSON.stringify(l)} uses sensor `:"sensor "}${JSON.stringify(s.sensor)}, which is Tier-2 advisory-only and cannot be enforced${l?" (arkgate-check --sensors lists which sensors can)":""}`}),Array.isArray(s.appliesTo)&&s.appliesTo.length===0&&t.push({path:`$.structure[${i}].appliesTo`,message:"must not be an empty array (omit the field to apply to the whole layer)"})}),r.forEach((s,i)=>{if(!xt(s))return;let l=typeof s.id=="string"?s.id:"";l&&(o.has(l)&&t.push({path:`$.invariants[${i}].id`,message:`duplicate rule id ${JSON.stringify(l)}`}),o.add(l)),Array.isArray(s.appliesTo)&&s.appliesTo.length===0&&t.push({path:`$.invariants[${i}].appliesTo`,message:"must not be an empty array (omit the field to apply to the whole layer)"})})}a(Rc,"validateSemantics");function ln(e,t="arkrules.json",n){if(!xt(e))throw new $e(t,[{path:"$",message:`must be an object; received ${_t(e)}`}]);let r=yc(e),o=[];if(Ot(r,dr,"$",dr,o),Rc(r,o),n!==void 0&&typeof r.layer=="string"&&r.layer!==n&&o.push({path:"$.layer",message:`must match referencing key ${JSON.stringify(n)}; received ${JSON.stringify(r.layer)}`}),o.length>0)throw new $e(t,o);return{config:r}}a(ln,"loadArkRulesContract");function kc(e,t="arkrules.json",n){let r;try{r=JSON.parse(e)}catch(o){throw new $e(t,[{path:"$",message:`invalid JSON: ${o instanceof Error?o.message:String(o)}`}])}return ln(r,t,n)}a(kc,"parseArkRulesJson");function ur(e){let t={},n=[],r=[],o=[...e].sort((s,i)=>s.layer.localeCompare(i.layer));for(let s of o){let i=(s.file.structure??[]).map(c=>({...c,mode:ko(c.mode),provenance:{sourceFile:s.sourceFile,ruleId:c.id,layer:s.layer}})),l=(s.file.invariants??[]).map(c=>({...c,mode:ko(c.mode),provenance:{sourceFile:s.sourceFile,ruleId:c.id,layer:s.layer}}));t[s.layer]={sourceFile:s.sourceFile,structure:i,invariants:l},n.push(...i),r.push(...l)}return n.sort((s,i)=>{let l=s.provenance.layer.localeCompare(i.provenance.layer);return l!==0?l:s.id.localeCompare(i.id)}),r.sort((s,i)=>{let l=s.provenance.layer.localeCompare(i.provenance.layer);return l!==0?l:s.id.localeCompare(i.id)}),{schemaVersion:"1.0",byLayer:t,structure:n,invariants:r}}a(ur,"buildEffectiveArkRules");function He(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}a(He,"emptyEffectiveArkRules");var cn=class extends Error{static{a(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 qs(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}i(qs,"normalizeRel");function ul(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 l of[...e.discoveredArkRulesFiles].sort())r.push({path:l,message:`ArkRules file ${JSON.stringify(l)} is not referenced by arkRules and will not be enforced`,severity:"advisory"});return{config:e.config,arkRules:De(),warnings:r}}let o=new Set(e.config.layers.map(l=>l.name)),s=[],a=[],c=new Set;for(let l of Object.keys(n).sort()){let u=n[l],p=`$.arkRules[${JSON.stringify(l)}]`;if(typeof u!="string"||u.length===0){s.push({path:p,message:"must be a non-empty relative path string"});continue}if(u.startsWith("/")||/^[A-Za-z]:[\\/]/.test(u)){s.push({path:p,message:"must be a project-relative path (absolute paths are not allowed)"});continue}if(!o.has(l)){s.push({path:p,message:`layer ${JSON.stringify(l)} is not declared in layers[]`});continue}let g=qs(u);c.add(g);let f=e.fileContents[g]??e.fileContents[u];if(f===void 0){s.push({path:p,message:`referenced ArkRules file ${JSON.stringify(g)} is missing`});continue}try{let m=Yt(JSON.parse(f),g,l);a.push({layer:l,sourceFile:g,file:m.config})}catch(m){if(m instanceof Le)for(let d of m.issues)s.push({path:`${p}${d.path==="$"?"":d.path.replace(/^\$/,"")}`,message:`${g}: ${d.message}`});else m instanceof SyntaxError?s.push({path:p,message:`referenced ArkRules file ${JSON.stringify(g)} is not valid JSON: ${m.message}`}):s.push({path:p,message:`referenced ArkRules file ${JSON.stringify(g)} failed to load: ${m instanceof Error?m.message:String(m)}`})}}if(e.discoveredArkRulesFiles)for(let l of[...e.discoveredArkRulesFiles].sort()){let u=qs(l);c.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(s.length>0)throw new Jt(t,s);return{config:e.config,arkRules:Jn(a),warnings:r}}i(ul,"resolveEffectiveContract");function Xn(e){return{...e,layers:e.layers.map(t=>{let{description:n,trustBoundary:r,owners:o,...s}=t;return s})}}i(Xn,"omitLayerDescriptions");function Zn(e){let{stewards:t,...n}=Xn(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(Zn,"effectiveContractPolicyPayload");var pl="INVARIANT_TESTS_PATH_MISSING",fl="This project is adopted and has domain invariants, but ark.config.json does not name a real tests path. Add coverage.testGlobs or coverage.coverageRoots pointing at the folder where those tests live, then re-run. Without that path, coverage is an empty checkbox.",ml="INVARIANT_COVERAGE_ROOTS_MISSING",gl="A domain invariant is enforced, but ark.config.json does not name coverage.coverageRoots \u2014 the folders where this project's test runner actually goes. Add coverage.coverageRoots pointing at that folder, then re-run. Without it, coverage can certify a test no runner runs.";function Ys(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 o=t?"":` (loaded ${e.filesLoaded} files, kept ${e.testFilesRetained} tests)`;return` Scan discarded ${r.join(", ")}${o}.`}i(Ys,"formatCoverageDiscards");function Zs(e,t){let n=e.replace(/\\/g,"/").replace(/^\.\//,"");return t.some(r=>{let o=r.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"");return o===""||o==="."?!0:n===o||n.startsWith(`${o}/`)})}i(Zs,"isUnderCoverageRoot");function Qs(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}i(Qs,"escapeRegExp");function Qn(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}i(Qn,"normalizePath");function eo(e,t){let n=[],r=0,o=e.length;for(;r<o;){let s=e[r],a=e[r+1];if(s==="/"&&a==="/"){for(;r<o&&e[r]!==`
9
- `;)n.push(" "),r+=1;continue}if(s==="/"&&a==="*"){for(n.push(" "," "),r+=2;r<o&&!(e[r]==="*"&&e[r+1]==="/");)n.push(e[r]===`
8
+ `)}`),this.name="EffectiveContractError",this.source=t,this.issues=n}};function Io(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}a(Io,"normalizeRel");function Sc(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:He(),warnings:r}}let o=new Set(e.config.layers.map(c=>c.name)),s=[],i=[],l=new Set;for(let c of Object.keys(n).sort()){let u=n[c],p=`$.arkRules[${JSON.stringify(c)}]`;if(typeof u!="string"||u.length===0){s.push({path:p,message:"must be a non-empty relative path string"});continue}if(u.startsWith("/")||/^[A-Za-z]:[\\/]/.test(u)){s.push({path:p,message:"must be a project-relative path (absolute paths are not allowed)"});continue}if(!o.has(c)){s.push({path:p,message:`layer ${JSON.stringify(c)} is not declared in layers[]`});continue}let m=Io(u);l.add(m);let f=e.fileContents[m]??e.fileContents[u];if(f===void 0){s.push({path:p,message:`referenced ArkRules file ${JSON.stringify(m)} is missing`});continue}try{let g=ln(JSON.parse(f),m,c);i.push({layer:c,sourceFile:m,file:g.config})}catch(g){if(g instanceof $e)for(let d of g.issues)s.push({path:`${p}${d.path==="$"?"":d.path.replace(/^\$/,"")}`,message:`${m}: ${d.message}`});else g instanceof SyntaxError?s.push({path:p,message:`referenced ArkRules file ${JSON.stringify(m)} is not valid JSON: ${g.message}`}):s.push({path:p,message:`referenced ArkRules file ${JSON.stringify(m)} failed to load: ${g instanceof Error?g.message:String(g)}`})}}if(e.discoveredArkRulesFiles)for(let c of[...e.discoveredArkRulesFiles].sort()){let u=Io(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(s.length>0)throw new cn(t,s);return{config:e.config,arkRules:ur(i),warnings:r}}a(Sc,"resolveEffectiveContract");function pr(e){return{...e,layers:e.layers.map(t=>{let{description:n,trustBoundary:r,owners:o,...s}=t;return s})}}a(pr,"omitLayerDescriptions");function fr(e){let{stewards:t,...n}=pr(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}))}}}a(fr,"effectiveContractPolicyPayload");var Ic="INVARIANT_TESTS_PATH_MISSING",Ec="This project is adopted and has domain invariants, but ark.config.json does not name a real tests path. Add coverage.testGlobs or coverage.coverageRoots pointing at the folder where those tests live, then re-run. Without that path, coverage is an empty checkbox.",bc="INVARIANT_COVERAGE_ROOTS_MISSING",vc="A domain invariant is enforced, but ark.config.json does not name coverage.coverageRoots \u2014 the folders where this project's test runner actually goes. Add coverage.coverageRoots pointing at that folder, then re-run. Without it, coverage can certify a test no runner runs.";function Eo(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 o=t?"":` (loaded ${e.filesLoaded} files, kept ${e.testFilesRetained} tests)`;return` Scan discarded ${r.join(", ")}${o}.`}a(Eo,"formatCoverageDiscards");function Co(e,t){let n=e.replace(/\\/g,"/").replace(/^\.\//,"");return t.some(r=>{let o=r.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"");return o===""||o==="."?!0:n===o||n.startsWith(`${o}/`)})}a(Co,"isUnderCoverageRoot");function mr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}a(mr,"escapeRegExp");function nt(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}a(nt,"normalizePath");function hr(e,t){let n=[],r=0,o=e.length;for(;r<o;){let s=e[r],i=e[r+1];if(s==="/"&&i==="/"){for(;r<o&&e[r]!==`
9
+ `;)n.push(" "),r+=1;continue}if(s==="/"&&i==="*"){for(n.push(" "," "),r+=2;r<o&&!(e[r]==="*"&&e[r+1]==="/");)n.push(e[r]===`
10
10
  `?`
11
- `:" "),r+=1;r<o&&(n.push(" "," "),r+=2);continue}if(s==='"'||s==="'"||s==="`"){let c=s;for(n.push(t?" ":s),r+=1;r<o;){let l=e[r];if(l==="\\"){let u=e[r+1];t?n.push(" ",u===void 0?"":" "):(n.push("\\"),u!==void 0&&n.push(u)),r+=u===void 0?1:2;continue}if(l===c){n.push(t?" ":l),r+=1;break}n.push(t&&l!==`
12
- `?" ":l),r+=1}continue}n.push(s),r+=1}return n.join("")}i(eo,"maskNonCode");function yl(e,t){if(!t)return;let n=Qs(t),s=new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*(['"\`])([^'"\`]*${n}[^'"\`]*)\\1`,"i").exec(eo(e,!1))?.[2];return s===void 0?void 0:s}i(yl,"matchTestTitle");function hl(e,t){if(!t)return;let n=Qs(t),r=eo(e,!0),o=[{shape:"function",source:`(?:^|[\\s;{}])(?:export\\s+(?:default\\s+)?)?(?:declare\\s+)?(?:async\\s+)?function\\s*\\*?\\s*${n}\\s*[(<]`},{shape:"class",source:`(?:^|[\\s;{}])(?:export\\s+(?:default\\s+)?)?(?:abstract\\s+)?class\\s+${n}\\b`},{shape:"const",source:`(?:^|[\\s;{}])export\\s+(?:const|let|var)\\s+${n}\\s*=`},{shape:"type",source:`(?:^|[\\s;{}])(?:export\\s+)?(?:declare\\s+)?type\\s+${n}\\b`},{shape:"interface",source:`(?:^|[\\s;{}])(?:export\\s+)?(?:declare\\s+)?interface\\s+${n}\\b`},{shape:"enum",source:`(?:^|[\\s;{}])(?:export\\s+)?(?:declare\\s+)?(?:const\\s+)?enum\\s+${n}\\b`},{shape:"method",source:`(?:^|[\\n;{}])\\s*(?:(?:public|private|protected|static|async|readonly|override|abstract|get|set|declare)\\s+)*${n}\\s*(?:<[^>\\n]*>)?\\s*\\([^;{}]*\\)\\s*(?::\\s*[^;{]+)?\\s*\\{`}];for(let s of o)if(new RegExp(s.source).test(r))return s.shape}i(hl,"declarationShape");function Al(e,t){let n=e.lastIndexOf(`
11
+ `:" "),r+=1;r<o&&(n.push(" "," "),r+=2);continue}if(s==='"'||s==="'"||s==="`"){let l=s;for(n.push(t?" ":s),r+=1;r<o;){let c=e[r];if(c==="\\"){let u=e[r+1];t?n.push(" ",u===void 0?"":" "):(n.push("\\"),u!==void 0&&n.push(u)),r+=u===void 0?1:2;continue}if(c===l){n.push(t?" ":c),r+=1;break}n.push(t&&c!==`
12
+ `?" ":c),r+=1}continue}n.push(s),r+=1}return n.join("")}a(hr,"maskNonCode");function Cc(e,t){if(!t)return;let n=mr(t),s=new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*(['"\`])((?:(?!\\1)[^\\\\]|\\\\.)*?${n}(?:(?!\\1)[^\\\\]|\\\\.)*?)\\1`,"i").exec(hr(e,!1))?.[2];return s===void 0?void 0:s}a(Cc,"matchTestTitle");function _c(e,t){if(!t)return;let n=mr(t),r=hr(e,!0),o=[{shape:"function",source:`(?:^|[\\s;{}])(?:export\\s+(?:default\\s+)?)?(?:declare\\s+)?(?:async\\s+)?function\\s*\\*?\\s*${n}\\s*[(<]`},{shape:"class",source:`(?:^|[\\s;{}])(?:export\\s+(?:default\\s+)?)?(?:abstract\\s+)?class\\s+${n}\\b`},{shape:"const",source:`(?:^|[\\s;{}])export\\s+(?:const|let|var)\\s+${n}(?:\\s*:(?:[^=]|=>)+?)?\\s*=(?!>)`},{shape:"type",source:`(?:^|[\\s;{}])(?:export\\s+)?(?:declare\\s+)?type\\s+${n}\\b`},{shape:"interface",source:`(?:^|[\\s;{}])(?:export\\s+)?(?:declare\\s+)?interface\\s+${n}\\b`},{shape:"enum",source:`(?:^|[\\s;{}])(?:export\\s+)?(?:declare\\s+)?(?:const\\s+)?enum\\s+${n}\\b`},{shape:"method",source:`(?:^|[\\n;{}])\\s*(?:(?:public|private|protected|static|async|readonly|override|abstract|get|set|declare)\\s+)*${n}\\s*(?:<[^>\\n]*>)?\\s*\\([^;{}]*\\)\\s*(?::\\s*[^;{]+)?\\s*\\{`}];for(let s of o)if(new RegExp(s.source).test(r))return s.shape}a(_c,"declarationShape");function Oc(e,t){let n=e.lastIndexOf(`
13
13
  `,t-1)+1,r=e.indexOf(`
14
- `,t);return e.slice(n,r===-1?e.length:r)}i(Al,"lineAt");function Rl(e){let t=e.trim();return/^import\b/.test(t)||/^export\s+/.test(t)&&/\bfrom\b/.test(t)?!0:/\brequire\s*\(/.test(t)}i(Rl,"isImportLine");function Js(e,t,n){if(!t||!e.includes(t))return;let r=new Set,o=0,s=e.length,a=i((c,l)=>{if(e.startsWith(t,c)){if(l==="comment"){r.add("comment");return}if(l==="string"){r.add("string");return}if(Rl(Al(e,c))){r.add("import");return}n&&r.add("test-body")}},"note");for(;o<s;){let c=e[o],l=e[o+1];if(c==="/"&&l==="/"){for(;o<s&&e[o]!==`
15
- `;)a(o,"comment"),o+=1;continue}if(c==="/"&&l==="*"){for(a(o,"comment"),a(o+1,"comment"),o+=2;o<s&&!(e[o]==="*"&&e[o+1]==="/");)a(o,"comment"),o+=1;o<s&&(a(o,"comment"),a(o+1,"comment"),o+=2);continue}if(c==='"'||c==="'"||c==="`"){let u=c;for(a(o,"string"),o+=1;o<s;){let p=e[o];if(p==="\\"){a(o,"string"),e[o+1]!==void 0&&a(o+1,"string"),o+=e[o+1]===void 0?1:2;continue}if(p===u){a(o,"string"),o+=1;break}a(o,"string"),o+=1}continue}a(o,"code"),o+=1}if(r.has("comment"))return"comment";if(r.has("string"))return"string";if(r.has("test-body"))return"test-body";if(r.has("import"))return"import"}i(Js,"mentionContext");function to(e){if(!e)return;let t=e.split("."),n=t[t.length-1]??"";return n?{className:t.length>1?t[0]??null:null,name:n}:void 0}i(to,"symbolNeedle");function kl(e){return to(e.coverage?.symbol)?.name??e.id}i(kl,"declaredLabel");function Xs(e){return Object.keys(e).sort((t,n)=>t<n?-1:t>n?1:0)}i(Xs,"sortedContentFiles");function no(e,t,n=!0){let r=t.testFiles??[],o=new Set(r.map(m=>Qn(m))),s=(t.coverageRoots??[]).filter(m=>typeof m=="string"&&m.length>0),a=e.coverage?.test!==!1&&n,c=to(e.coverage?.symbol??void 0),l,u;if(a){for(let m of r){let d=t.fileContents[m];if(!d)continue;let y=yl(d,e.id);if(y!==void 0){if(s.length===0||Zs(m,s)){l={file:m,title:y};break}u??={file:m,title:y}}}l??=u}let p;if(c)for(let m of Xs(t.fileContents)){if(o.has(Qn(m)))continue;let d=t.fileContents[m];if(!d||c.className&&!d.includes(c.className))continue;let y=hl(d,c.name);if(y){p={file:m,shape:y};break}}let g;if(!l&&!p){if(a)for(let m of r){let d=t.fileContents[m];if(!d)continue;let y=Js(d,e.id,!0);if(y){g={file:m,context:y};break}}if(!g&&c)for(let m of Xs(t.fileContents)){if(o.has(Qn(m)))continue;let d=t.fileContents[m];if(!d)continue;let y=Js(d,c.name,!1);if(y){g={file:m,context:y};break}}}return{best:l?{kind:"test-title",file:l.file,title:l.title}:p?{kind:"declaration",file:p.file,shape:p.shape}:g?{kind:"mention-only",file:g.file,context:g.context}:{kind:"none"},...l?{testTitle:l}:{},...p?{declaration:p}:{}}}i(no,"rankCoverage");function Sl(e,t){return no(e,t).best}i(Sl,"classifyCoverage");function ro(e){switch(e.kind){case"test-title":case"declaration":return!0;case"mention-only":case"none":return!1}}i(ro,"countsAsCoverage");function Il(e){switch(e){case"test-body":return"a test body";case"comment":return"a comment";case"string":return"a string";case"import":return"an import"}}i(Il,"mentionWhere");function so(e,t){switch(t.kind){case"test-title":return`found \`${t.title}\` in a describe/it title in ${t.file}`;case"declaration":return`found \`${t.shape} ${kl(e)}\` in ${t.file}`;case"mention-only":return`${e.id} appears only in ${Il(t.context)} in ${t.file}; put it in a describe/it title`;case"none":return"no scanned test names it in a describe/it title and no declared symbol was found"}}i(so,"describeCoverage");function tr(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,o=e.coverageBudgetExhausted===!0,s=e.coverageStats,a=Ys(s),c=Ys(s,!0),l=s?`coverage file budget exhausted: ${s.filesLoaded} files loaded at the ${s.maxFiles}-file cap, ${s.testFilesRetained} tests retained, ${s.discarded.budget} files discarded at the cap; raise "coverage.maxFiles" in ark.config.json (the cap bounds files RETAINED as evidence${typeof s.filesRead=="number"?`; ${s.filesRead} were read`:""})`:"coverage file budget exhausted",u=(e.coverageRoots??[]).filter(d=>typeof d=="string"&&d.length>0),p=u.length>0,g=u.join(", "),f=[],m=[];for(let d of t){let y=d.coverage?.test!==!1,b=d.coverage?.symbol,x=!r&&y,S=no(d,{fileContents:e.fileContents,testFiles:n,coverageRoots:u},x),E=S.best,C=[];x&&S.testTitle&&C.push("test-title"),S.declaration&&C.push("symbol");let D=ro(E),k,P;x&&S.testTitle&&(k=S.testTitle.file,p&&(P=!Zs(k,u)));let ge=S.declaration?.file,N=S.declaration?.shape,L=(d.coverage?.test===!0||!!b||d.coverage===void 0)&&D||d.coverage?.test===!1&&!b?!0:D,j=r&&y&&!D;if(f.push({invariantId:d.id,layer:d.provenance.layer,sourceFile:d.provenance.sourceFile,mode:d.mode,covered:L&&!j,evidence:C,partial:j,description:d.description,...k!==void 0?{testEvidenceFile:k}:{},...ge!==void 0?{symbolEvidenceFile:ge}:{},...N!==void 0?{shape:N}:{},...P!==void 0?{outsideDeclaredRoots:P}:{},coverageRootsDeclared:p}),P===!0&&k!==void 0&&m.push({ruleId:"INVARIANT_COVERAGE_OUTSIDE_ROOTS",message:`Invariant ${d.id} is covered only by ${k}, which is outside the declared coverage roots (${g}). 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:k,line:1,arkruleId:d.id,arkruleSource:d.provenance.sourceFile,fromLayer:d.provenance.layer,severity:"warning",failsStrict:!1}),!L||j){let G=d.mode==="enforced"&&!j,pe=r||n.length===0?"never-had-tests":"tests-disappeared";m.push({ruleId:"INVARIANT_UNCOVERED",message:(j?o?`Invariant ${d.id} coverage cannot be proven (${l}); reporting partial, not covered.`:`Invariant ${d.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered (never-had-tests).`:`Invariant ${d.id}: ${so(d,E)} (${pe==="tests-disappeared"?"tests-disappeared \u2014 a suite exists":"never-had-tests \u2014 the scan found no tests at all"}). ArkGate matches declared text; it never executes tests.`)+(j&&o?c:a),file:d.provenance.sourceFile,line:1,arkruleId:d.id,arkruleSource:d.provenance.sourceFile,fromLayer:d.provenance.layer,severity:G?"error":"warning",failsStrict:G,kind:pe})}}return{coverage:f,violations:m,partial:f.some(d=>d.partial)}}i(tr,"evaluateInvariantCoverage");function nr(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.`}:e.coverageRootsDeclared===!1?{ok:!1,reason:`Declare coverage.coverageRoots in ark.config.json before promoting ${e.invariantId} to enforced. Without that, ArkGate cannot tell whether a covering test is one the runner executes.`}:{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(nr,"canPromoteInvariant");function er(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!="string")continue;let r=n.trim();r.length>0&&t.push(r)}return t}i(er,"nonEmptyPathStrings");function El(e){return!e||typeof e!="object"?[]:[...er(e.testGlobs),...er(e.coverageRoots)]}i(El,"configuredInvariantTestsPaths");function bl(e){return El(e).length>0}i(bl,"hasConfiguredInvariantTestsPath");function rr(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.coverage?.test!==!1)}i(rr,"catalogDemandsInvariantTestsPath");function oo(e){let t=e.hasDomainInvariants===!0||e.hasDomainInvariants!==!1&&rr(e.invariants);return e.adopted!==!0||!t?[]:bl(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:pl,message:fl,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]}i(oo,"collectMissingInvariantTestsPathFindings");function vl(e){return!e||typeof e!="object"?[]:er(e.coverageRoots)}i(vl,"configuredCoverageRoots");function Cl(e){return vl(e).length>0}i(Cl,"hasConfiguredCoverageRoots");function sr(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.mode==="enforced")}i(sr,"catalogHasEnforcedInvariant");function ao(e){return e.hasEnforcedInvariant===!0||e.hasEnforcedInvariant!==!1&&sr(e.invariants)?Cl(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:ml,message:gl,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]:[]}i(ao,"collectMissingCoverageRootsFindings");var ir="1.0",_l="add a short note under docs/adr/ (or docs/decisions/) and put that file path in --policy-ack as adrPath.";function T(e,t){let n=t.classification==="weakening"||t.classification==="judgment-required"?`Restore the previous protection at ${t.path}, or ${_l}`:void 0,r=t.nextAction??n;e.push({id:`${t.classification}:${t.path}:${t.kind}`,path:t.path,classification:t.classification,message:t.message,...r?{nextAction:r}:{},...t.before===void 0?{}:{before:t.before},...t.after===void 0?{}:{after:t.after}})}i(T,"addFinding");function ee(e){return[...new Set(e??[])].sort()}i(ee,"sortedUnique");function me(e,t,n,r,o){let s=ee(n),a=ee(r),c=new Set(s),l=new Set(a),u=a.filter(g=>!c.has(g)),p=s.filter(g=>!l.has(g));u.length===0&&p.length===0||(u.length>0&&T(e,{kind:"added",path:t,classification:o.added,message:o.addedMessage,before:s,after:a}),p.length>0&&T(e,{kind:"removed",path:t,classification:o.removed,message:o.removedMessage,before:s,after:a}))}i(me,"compareStringSets");function ht(e,t,n,r,o,s,a){if(n===r)return;T(e,{kind:r?"enabled":"disabled",path:t,classification:r?o:o==="strengthening"?"weakening":"strengthening",message:r?s:a,before:n,after:r})}i(ht,"compareBoolean");function Xt(e,t){let n=new Map,r=new Set;for(let o of e){let s=t(o);n.has(s)?r.add(s):n.set(s,o)}return{values:n,duplicates:[...r].sort()}}i(Xt,"keyed");function Ol(e,t,n){let r=Xt(t,s=>s.name),o=Xt(n,s=>s.name);(r.duplicates.length>0||o.duplicates.length>0)&&T(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:r.duplicates,after:o.duplicates});for(let s of[...new Set([...r.values.keys(),...o.values.keys()])].sort()){let a=r.values.get(s),c=o.values.get(s),l=`$.layers[${s}]`;if(!a&&c){T(e,{kind:"layer-added",path:l,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",nextAction:"Write a short note under docs/adr/ (or docs/decisions/) for this new layer and put that file path in --policy-ack as adrPath.",after:c});continue}if(a&&!c){T(e,{kind:"layer-removed",path:l,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:a});continue}if(!a||!c)continue;me(e,`${l}.patterns`,a.patterns,c.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),me(e,`${l}.exclude`,a.exclude,c.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let u=Ft(a),p=Ft(c);me(e,`${l}.forbiddenGlobals`,u.rawGlobals,p.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),me(e,`${l}.capabilities`,u.atoms,p.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)."}),ee(a.intentPrefixes).join("\0")!==ee(c.intentPrefixes).join("\0")&&T(e,{kind:"intent-prefixes-changed",path:`${l}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:ee(a.intentPrefixes),after:ee(c.intentPrefixes)}),ht(e,`${l}.mayImportInfrastructure`,a.mayImportInfrastructure===!0,c.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),ht(e,`${l}.optional`,a.optional===!0,c.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active.")}}i(Ol,"compareLayers");function xl(e,t,n){let r=i(a=>`${a.from}->${a.to}`,"keyOf"),o=Xt(t,r),s=Xt(n,r);(o.duplicates.length>0||s.duplicates.length>0)&&T(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:o.duplicates,after:s.duplicates});for(let a of[...new Set([...o.values.keys(),...s.values.keys()])].sort()){let c=o.values.get(a),l=s.values.get(a),u=`$.rules[${a}]`;if(!c&&l){l.allowed===!1?T(e,{kind:"deny-added",path:u,classification:"strengthening",message:"A denied dependency edge was added.",after:l}):T(e,{kind:"allow-added",path:u,classification:"judgment-required",message:"A new import edge was added; confirm this house should import that one.",nextAction:"Write a short note under docs/adr/ (or docs/decisions/) for this new import edge and put that file path in --policy-ack as adrPath.",after:l});continue}if(c&&!l){c.allowed===!1&&T(e,{kind:"deny-removed",path:u,classification:"weakening",message:"A denied dependency edge was removed.",before:c});continue}if(!c||!l)continue;c.allowed!==l.allowed&&T(e,{kind:l.allowed?"deny-disabled":"deny-enabled",path:`${u}.allowed`,classification:l.allowed?"weakening":"strengthening",message:l.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:c.allowed,after:l.allowed});let p=c.peerIsolation===!0,g=l.peerIsolation===!0;if(p!==g){let d=c.from===c.to&&l.from===l.to;T(e,{kind:g?"peer-isolation-enabled":"peer-isolation-disabled",path:`${u}.peerIsolation`,classification:d?g?"strengthening":"weakening":"judgment-required",message:d?g?"Cross-slice dependencies inside this layer are now denied.":"Cross-slice dependencies inside this layer are no longer denied.":"Changing peer isolation on a cross-layer edge changes the denial scope.",before:p,after:g})}ee(c.sliceFolders).join("\0")!==ee(l.sliceFolders).join("\0")&&T(e,{kind:"slice-folders-changed",path:`${u}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:ee(c.sliceFolders),after:ee(l.sliceFolders)});let f=c.sliceIdentity??"path",m=l.sliceIdentity??"path";if(f!==m&&T(e,{kind:"slice-identity-changed",path:`${u}.sliceIdentity`,classification:"judgment-required",message:"Slice identity changed and can reclassify existing slice ids. Baselines and allowedCrossSlice use those ids.",before:f,after:m}),!(!p&&!g)&&(lo(e,`${u}.sharedRoots`,"shared-roots",ee(c.sharedRoots),ee(l.sharedRoots),"Roots declared shared are exempt from the peerIsolation unclassifiable denial.","Roots are no longer declared shared and fall back to the peerIsolation denial."),lo(e,`${u}.allowedCrossSlice`,"cross-slice-allowance",ee((c.allowedCrossSlice??[]).map(io)),ee((l.allowedCrossSlice??[]).map(io)),"Directed cross-slice edges are now allowed by declaration.","Directed cross-slice edges are no longer declared and deny again."),(c.sharedImportsSlice??null)!==(l.sharedImportsSlice??null))){let d=l.sharedImportsSlice==="deny";T(e,{kind:"shared-imports-slice",path:`${u}.sharedImportsSlice`,classification:d?"strengthening":"weakening",message:d?"A shared root may no longer import a slice.":"A shared root may import a slice again.",before:c.sharedImportsSlice??null,after:l.sharedImportsSlice??null})}}}i(xl,"compareRules");function io(e){return JSON.stringify([e.from,e.to])}i(io,"crossSliceKey");function lo(e,t,n,r,o,s,a){if(JSON.stringify(r)===JSON.stringify(o))return;let c=o.filter(p=>!r.includes(p)),l=r.filter(p=>!o.includes(p)),u=c.length>0&&l.length>0;T(e,{kind:u?`${n}-changed`:c.length>0?`${n}-added`:`${n}-removed`,path:t,classification:u?"judgment-required":c.length>0?"weakening":"strengthening",message:u?`${s} Entries were added and removed in the same change.`:c.length>0?s:a,before:r,after:o})}i(lo,"compareDeclaredExceptions");function Tl(e,t,n){let r=t.safety??{},o=n.safety??{};for(let s of["maxTsSuppressions","maxAnyCasts"]){let a=r[s]??0,c=o[s]??0;a!==c&&T(e,{kind:c>a?"threshold-raised":"threshold-lowered",path:`$.safety.${s}`,classification:c>a?"weakening":"strengthening",message:c>a?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:a,after:c})}for(let s of["allowInMemory","allowDisabledPeerIsolation"])ht(e,`$.safety.${s}`,r[s]===!0,o[s]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}i(Tl,"compareSafety");function or(e){return e.mode==="enforced"?"enforced":"advisory"}i(or,"arkRunMode");function ar(e){return e.mode==="enforced"?"enforced":"advisory"}i(ar,"arkOrderMode");function Nl(e,t,n){let r=t.arkOrder,o=n.arkOrder,s="$.arkOrder";if(!r&&!o)return;if(!r&&o){T(e,{kind:"arkorder-added",path:s,classification:"strengthening",message:`ArkOrder extra was added (${ar(o)}).`,after:o});return}if(r&&!o){T(e,{kind:"arkorder-removed",path:s,classification:"weakening",message:"ArkOrder extra was removed.",before:r});return}if(!r||!o)return;let a=ar(r),c=ar(o);if(a!==c){let l=a==="advisory"&&c==="enforced";T(e,{kind:l?"arkorder-promoted":"arkorder-demoted",path:`${s}.mode`,classification:l?"strengthening":"weakening",message:l?"ArkOrder extra was promoted to enforced.":"ArkOrder extra was demoted to advisory.",before:a,after:c})}me(e,`${s}.planeRoots`,r.planeRoots,o.planeRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkOrder plane roots are governed.",removedMessage:"ArkOrder plane roots were removed and may skip the plane."}),me(e,`${s}.managedLayers`,r.managedLayers,o.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkOrder.",removedMessage:"Layers were removed from ArkOrder management."})}i(Nl,"compareArkOrder");function wl(e,t,n){let r=t.arkRun,o=n.arkRun,s="$.arkRun";if(!r&&!o)return;if(!r&&o){T(e,{kind:"arkrun-added",path:s,classification:"strengthening",message:`ArkRun extra was added (${or(o)}).`,after:o});return}if(r&&!o){T(e,{kind:"arkrun-removed",path:s,classification:"weakening",message:"ArkRun extra was removed.",before:r});return}if(!r||!o)return;let a=or(r),c=or(o);if(a!==c){let l=a==="advisory"&&c==="enforced";T(e,{kind:l?"arkrun-promoted":"arkrun-demoted",path:`${s}.mode`,classification:l?"strengthening":"weakening",message:l?"ArkRun extra was promoted to enforced.":"ArkRun extra was demoted to advisory.",before:a,after:c})}me(e,`${s}.compositionRoots`,r.compositionRoots,o.compositionRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkRun composition roots are governed.",removedMessage:"ArkRun composition roots were removed and may skip the kernel."}),me(e,`${s}.managedLayers`,r.managedLayers,o.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkRun.",removedMessage:"Layers were removed from ArkRun management."}),ht(e,`${s}.requireDeclarations`,r.requireDeclarations!==!1,o.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}i(wl,"compareArkRun");function Pl(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(Pl,"overallClassification");function co(e,t){return`${e}::${t}`}i(co,"ruleKey");function uo(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(co(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(co(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}i(uo,"indexEffectiveRules");function Ll(e,t,n,r,o,s){let a=new Map((s??[]).map(f=>[f.invariantId,f])),c=t.arkRules??{},l=n.arkRules??{},u=[...new Set([...Object.keys(c),...Object.keys(l)])].sort();for(let f of u){let m=c[f],d=l[f],y=`$.arkRules[${f}]`;if(m===void 0&&d!==void 0){T(e,{kind:"arkrules-ref-added",path:y,classification:"strengthening",message:`ArkRules reference for layer ${f} was added.`,after:d});continue}if(m!==void 0&&d===void 0){T(e,{kind:"arkrules-ref-removed",path:y,classification:"weakening",message:`ArkRules reference for layer ${f} was removed.`,before:m});continue}m!==d&&T(e,{kind:"arkrules-ref-path-changed",path:y,classification:"judgment-required",message:`ArkRules file path for layer ${f} changed; verify the effective rules still match intent.`,before:m,after:d})}let p=uo(r),g=uo(o);for(let f of[...new Set([...p.structure.keys(),...g.structure.keys()])].sort()){let m=p.structure.get(f),d=g.structure.get(f),y=`$.arkRules.structure[${f}]`;if(!m&&d){T(e,{kind:"arkrule-structure-added",path:y,classification:"strengthening",message:`Structure ArkRule ${d.id} was added (${d.mode}).`,after:d});continue}if(m&&!d){T(e,{kind:"arkrule-structure-removed",path:y,classification:"weakening",message:`Structure ArkRule ${m.id} was removed.`,before:m});continue}if(!(!m||!d)){if(m.mode!==d.mode){let b=m.mode==="advisory"&&d.mode==="enforced";T(e,{kind:b?"arkrule-promoted":"arkrule-demoted",path:`${y}.mode`,classification:b?"strengthening":"weakening",message:b?`Structure ArkRule ${d.id} was promoted to enforced.`:`Structure ArkRule ${d.id} was demoted to advisory.`,before:m.mode,after:d.mode})}m.sensor!==d.sensor&&T(e,{kind:"arkrule-sensor-changed",path:`${y}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${d.id} changed sensor identity.`,before:m.sensor,after:d.sensor})}}for(let f of[...new Set([...p.invariants.keys(),...g.invariants.keys()])].sort()){let m=p.invariants.get(f),d=g.invariants.get(f),y=`$.arkRules.invariants[${f}]`;if(!m&&d){T(e,{kind:"arkrule-invariant-added",path:y,classification:"strengthening",message:`Invariant ${d.id} was added (${d.mode}).`,after:d});continue}if(m&&!d){T(e,{kind:"arkrule-invariant-removed",path:y,classification:"weakening",message:`Invariant ${m.id} was removed.`,before:m});continue}if(!(!m||!d)&&m.mode!==d.mode)if(m.mode==="advisory"&&d.mode==="enforced"){let x=a?.get(d.id),S=nr(x);S.ok?T(e,{kind:"arkrule-invariant-promoted",path:`${y}.mode`,classification:"strengthening",message:`Invariant ${d.id} was promoted to enforced (coverage evidence present).`,before:m.mode,after:d.mode}):T(e,{kind:"arkrule-invariant-promote-refused",path:`${y}.mode`,classification:"judgment-required",message:`Invariant ${d.id} cannot be promoted to enforced: ${S.reason}`,before:m.mode,after:d.mode})}else T(e,{kind:"arkrule-invariant-demoted",path:`${y}.mode`,classification:"weakening",message:`Invariant ${d.id} was demoted to advisory.`,before:m.mode,after:d.mode})}}i(Ll,"compareArkRules");function lr(e,t,n){let r=[];me(r,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),me(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."}),me(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."}),ht(r,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let o={off:0,soft:1,"framework-soft":1,strict:2},s=e.cyclePolicy??"strict",a=t.cyclePolicy??"strict";if(s!==a){let c=o[a]===o[s]?"judgment-required":o[a]>o[s]?"strengthening":"weakening";T(r,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:c,message:"The cycle enforcement level changed.",before:s,after:a})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&T(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}),Ol(r,e.layers,t.layers),xl(r,e.rules,t.rules),Tl(r,e,t),Ll(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),wl(r,e,t),Nl(r,e,t),r.sort((c,l)=>c.path.localeCompare(l.path)||c.id.localeCompare(l.id)),{schemaVersion:ir,classification:Pl(r),findings:r}}i(lr,"classifyArkPolicyDelta");function cr(e,t){if(!e||e.schemaVersion!==ir||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(o=>typeof o!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=ee(e.findingIds),r=ee(t.findingIds);return n.length===r.length&&n.every((o,s)=>o===r[s])}i(cr,"policyDeltaAcknowledgementMatches");function Me(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(Me,"normalizePath");function po(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}i(po,"isIdentifierStart");function Zt(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}i(Zt,"isIdentifierCharacter");function ce(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}i(ce,"skipWhitespace");function At(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let r=t,o="";for(t+=1;t<e.length;t+=1){let s=e[t];if(s===n)return{value:o,offset:r,excerpt:e.slice(r,t+1)};s==="\\"&&t+1<e.length?(o+=e[t+1],t+=1):o+=s}}i(At,"readString");function de(e,t,n){return e.startsWith(t,n)&&!Zt(e[n-1])&&!Zt(e[n+t.length])}i(de,"isWordAt");function fo(e,t){let n=ce(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=ce(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!de(e,"type",n))return!1;let o=ce(e,n+4);if(o>=e.length||e[o]===","||e[o]==="}"||de(e,"as",o)||!po(e[o]))return!1;for(n=o;n<e.length&&Zt(e[n]);)n+=1;if(n=ce(e,n),de(e,"as",n)){if(n=ce(e,n+2),!po(e[n]))return!1;for(;n<e.length&&Zt(e[n]);)n+=1}r=!0}return!1}i(fo,"bracedNamedBindingsAreTypeOnly");function Dl(e,t){if(t=ce(e,t+6),e[t]==="(")return At(e,ce(e,t+1));let n=!1;if(de(e,"type",t)){let o=ce(e,t+4);e[o]!==","&&!de(e,"from",o)&&(n=!0)}else fo(e,t)&&(n=!0);let r=mo(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}i(Dl,"specifierAfterImport");function Ml(e,t){t=t+6;let n=ce(e,t),r=!1;if(de(e,"type",n)){let s=ce(e,n+4);(e[s]==="{"||e[s]==="*")&&(r=!0)}else fo(e,n)&&(r=!0);let o=mo(e,t,!1);return o&&r?{...o,typeOnly:!0}:o}i(Ml,"specifierAfterExport");function mo(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(de(e,"from",t))return At(e,ce(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return At(e,t);if(t>0&&(de(e,"import",t)||de(e,"export",t)))return}}i(mo,"specifierInStaticStatement");function Fl(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(Fl,"skipTemplateLiteral");function $l(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=ce(e,t+7);if(e[r]!=="(")return;r=ce(e,r+1);let o=At(e,r);return o?{...o,requireCall:!0}:void 0}i($l,"specifierAfterRequire");function Hl(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(`
16
- `,n+2),n<0)break;continue}if(r==="/"&&e[n+1]==="*"){let s=e.indexOf("*/",n+2);if(s<0)break;n=s+1;continue}if(r==="`"){n=Fl(e,n);continue}if(r==="'"||r==='"'){let s=At(e,n);s&&(n=s.offset+s.excerpt.length-1);continue}let o=r==="i"&&de(e,"import",n)?Dl(e,n):r==="e"&&de(e,"export",n)?Ml(e,n):r==="r"&&de(e,"require",n)?$l(e,n):void 0;o&&(t.push(o),n=o.offset+o.excerpt.length-1)}return t}i(Hl,"moduleSpecifiers");function go(e,t){let n=[],r=[];for(let o of Hl(e.content)){let s=o.value;if(!s.startsWith(".")){if(o.typeOnly)continue;let u=st(s);if(!u)continue;let p=e.content.slice(0,o.offset).split(`
17
- `).length;r.push({file:e.path,symbol:s,capability:u,evidence:{kind:"import",file:e.path,line:p,excerpt:o.excerpt}});continue}let a=e.content.slice(0,o.offset).split(`
18
- `).length,c={kind:"import",file:e.path,line:a,excerpt:o.excerpt},l=jl(e.path,s,t);n.push({from:e.path,specifier:s,to:l?.path??null,resolution:l?"resolved":"unresolved",fromLayer:e.layer,toLayer:l?.layer??null,evidence:c})}return{edges:n,capabilityUses:r}}i(go,"moduleFactsFor");function jl(e,t,n){let r=e.split("/");r.pop();for(let s of t.split("/"))s==="."||s===""||(s===".."?r.pop():r.push(s));let o=r.join("/");for(let s of[o,`${o}.ts`,`${o}.tsx`,`${o}.mts`,`${o}.cts`,`${o}/index.ts`,`${o}/index.tsx`]){let a=n.get(s);if(a)return a}}i(jl,"resolveSpecifier");function yo(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let o=jt(t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});o&&n.push({ruleId:`layer-dependency:${o.from}->${o.to}`,message:o.message??`${o.from} must not depend on ${o.to}.`,edge:r,evidence:r.evidence})}return n}i(yo,"violationsFor");var Kl={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 Vl(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}i(Vl,"hasActiveArkRules");function Ul(e,t){return Vl(e,t)?Z(K(Zn({config:e,arkRules:t,warnings:[]}))):Z(K(Xn(e)))}i(Ul,"policyHashFor");function Qt(e,t,n){let r=typeof e=="string"?Gn(e,t):Bt(e,t),o=n?.arkRules??De();return{...r,arkRules:o,policyHash:Ul(r.config,o)}}i(Qt,"loadContract");function ho(e){let t=Qt(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=Qt(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=lr(t.config,n.config,{baseArkRules:t.arkRules,candidateArkRules:n.arkRules,candidateInvariantCoverage:e.candidateInvariantCoverage}),o=r.findings.filter(c=>c.classification==="weakening"||c.classification==="judgment-required").map(c=>c.id).sort(),s=o.length>0,a=s&&cr(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:o});return{schemaVersion:r.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:r.classification,findings:r.findings,blockingFindingIds:o,requiresAcknowledgement:s,acknowledged:a,valid:!s||a}}i(ho,"analyzePolicyDelta");function Rt(e){let t=e.files.map(g=>{let f=Me(g.path);return{path:f,content:g.content,contentHash:Z(g.content),layer:fe(f,e.contract.config.layers)??null}}).sort((g,f)=>g.path.localeCompare(f.path)),n=new Map(t.map(g=>[g.path,g])),r=[],o=[];for(let g of t){let f=go(g,n);r.push(...f.edges),o.push(...f.capabilityUses)}let s=yo(r,e.contract.config),a=new Map(e.contract.config.layers.map(g=>[g.name,g])),c=new Map(e.contract.config.layers.map(g=>[g.name,new Set(je(g))]));for(let g of o){let f=n.get(g.file)?.layer;if(!f)continue;let m=a.get(f),d=Ce(g.symbol,m?.forbiddenGlobals??[]);if(d){s.push({ruleId:"FORBIDDEN_GLOBAL",message:`${f} must not use module "${g.symbol}" because it is the import form of forbidden global "${d}".`,symbol:g.symbol,evidence:g.evidence});continue}c.get(f)?.has(g.capability)&&s.push({ruleId:"CAPABILITY_VIOLATION",message:`${f} denies the ${g.capability} capability; found import of "${g.symbol}".`,capability:g.capability,symbol:g.symbol,evidence:g.evidence})}let l=t.length===0?"complete":"partial",u=l==="complete"?[]:[{...Kl}],p={schemaVersion:Wn,policyHash:e.contract.policyHash,compilerOptionsHash:Z(K(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(g=>g.name),edges:r,capabilityUses:o,violations:s};return{mode:"lexical-compatibility",completeness:l,completenessReasons:u,valid:l==="complete"&&s.length===0,ir:p}}i(Rt,"analyzeProject");function en(e){let t=new Map(e.files.map(n=>[Me(n.path),n]));for(let n of e.changes){let r=Me(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return Rt({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}i(en,"analyzeChange");function Ao(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(Ao,"explainViolation");function dr(e){let t=0,n=new Map,r=new Map,o=new Set,s=[],a=[],c=i(l=>{n.set(l,t),r.set(l,t),t+=1,s.push(l),o.add(l);for(let g of[...e.get(l)??[]].sort())e.has(g)&&(n.has(g)?o.has(g)&&r.set(l,Math.min(r.get(l)??0,n.get(g)??0)):(c(g),r.set(l,Math.min(r.get(l)??0,r.get(g)??0))));if(r.get(l)!==n.get(l))return;let u=[],p;do{if(p=s.pop(),p===void 0)break;o.delete(p),u.push(p)}while(p!==l);u.length>1&&a.push(u.sort())},"connect");for(let l of[...e.keys()].sort())n.has(l)||c(l);return a.sort((l,u)=>l[0]<u[0]?-1:l[0]>u[0]?1:0).map(l=>({ruleId:"CIRCULAR_DEPENDENCY",file:l[0],line:1,target:l.join(" \u2192 "),message:`Circular dependency among ${l.length} files: ${l.join(" \u2192 ")} \u2192 ${l[0]}.`,cycleKind:"value"}))}i(dr,"detectArchitectureCycles");function Ye(e){let t=e.contentViolations.map(s=>({...s})),n=(e.warnings??[]).map(s=>({...s})),r=new Map(e.files.map(s=>[s,new Set]));for(let s of e.edges){if(s.to&&s.to!==s.from&&!s.typeOnly&&r.has(s.from)&&r.get(s.from)?.add(s.to),!s.to||!s.fromLayer||!s.toLayer)continue;let a=Te(e.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:e.config.layers});if(!a){let f=ys(e.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:e.config.layers});f&&n.push({ruleId:"SHARED_IMPORTS_SLICE",file:f.fromPath,line:s.line,fromLayer:s.fromLayer,toLayer:s.toLayer,target:f.toPath,toSlice:f.toSlice,failsStrict:!1,severity:"warning",message:`shared root ${f.fromPath} \u2192 slice ${f.toSlice} (${f.toPath}). The wall is direct-only.`});continue}let c=a.rule,l=!!c.peerIsolation,u=!l&&!!(s.typeOnly||s.namedBindingsTypeOnly),p=l?Ke(a.peerIsolationReason??"cross-slice",{fromPath:s.from,toPath:s.to,fromSlice:a.fromSlice,toSlice:a.toSlice}):void 0,g=c.message?p?`${c.message} (${p})`:c.message:p?`${s.fromLayer} must not ${s.kind} another slice of ${s.toLayer} (${s.from} \u2192 ${s.to}): ${p}`:`${s.fromLayer} must not ${s.kind} ${s.toLayer}.`;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:s.from,line:s.line,fromLayer:s.fromLayer,toLayer:s.toLayer,target:s.to,...s.typeOnly?{typeOnly:!0}:{},...s.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...s.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...s.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!l&&s.portProofEligible?{portProofEligible:!0}:{},...s.kind?{edgeKind:s.kind}:{},...l?{peerIsolation:!0}:{},message:u?`${g} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:g,...u?{failsStrict:!1,severity:"warning"}:{}})}let o=String(e.config.cyclePolicy??"strict").toLowerCase();if(o!=="off"){let s=dr(r);o==="soft"||o==="framework-soft"?n.push(...s.map(a=>({...a,message:`${a.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...s)}return{violations:t,warnings:n,safety:e.safety}}i(Ye,"evaluateArchitectureGraph");function Ro(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(Ro,"structureFreezeTarget");var Gl=["no-anemic-model"],vo=["ensureInvariants","assertInvariants","validate","publish","emit","raise","record"],fr=new RegExp(`\\b(${vo.join("|")})\\b`),Co="(?:_?pendingEvents|domainEvents|uncommittedEvents|recordedEvents)",mr=new RegExp(`\\bthis\\.${Co}\\.push\\s*\\(`),Bl=new RegExp(`^this\\.${Co}\\s*=\\s*\\[\\s*\\]`),zl=/^this\.[A-Za-z_][A-Za-z0-9_]*\s*=\s*\[\s*\]/,Wl=/\bthis\.[A-Za-z_][A-Za-z0-9_]*\s*=(?!=)/g,_o="truncatedUntil";function gr(){return`${vo.join(", ")}, or events-array .push(`}i(gr,"expectedDomainInvariantWordsPhrase");function ql(e){return fr.test(e)||mr.test(e)}i(ql,"referencesGuardOrPublish");function yr(e,t,n){let r=e.slice(t);if(Bl.test(r))return!0;if(!zl.test(r))return!1;if(n&&/^pullEvents$/i.test(n))return!0;let o=t>200?t-200:0;return/\bpullEvents\b/.test(e.slice(o,t+200))}i(yr,"isIdiomaticEventsReset");function Yl(e,t){let n=new RegExp(Wl.source,"g"),r;for(;(r=n.exec(t))!==null;)if(!yr(t,r.index,e))return!0;return!1}i(Yl,"methodAssignsThis");function Jl(e,t){return t==null||Object.defineProperty(e,_o,{value:t,enumerable:!1,configurable:!0}),e}i(Jl,"attachShapeTruncation");function pr(e){let t=Object.getOwnPropertyDescriptor(e,_o)?.value;return typeof t=="number"?t:void 0}i(pr,"shapeTruncatedUntil");function Xl(e){let t=pr(e);return t==null?"":` shape analysed until character ${t}`}i(Xl,"shapeTruncationSuffix");function ko(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(ko,"escapeGlobLiteral");function Zl(e){let t="";for(let r=0;r<e.length;r+=1){let o=e[r];if(o==="\\"&&r+1<e.length){let s=e[r+1];if("*?{}[],".includes(s)||s==="\\"){t+="\\"+s,r+=1;continue}t+="/";continue}t+=o}let n="";for(let r=0;r<t.length;r+=1){let o=t[r];o==="\\"&&r+1<t.length?(n+=ko(t[r+1]),r+=1):o==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":o==="?"?n+="[^/]":n+=ko(o)}return new RegExp(`^${n}$`)}i(Zl,"globToRegExp");function Je(e,t){return!t||t.length===0?!0:t.some(n=>Zl(n).test(e))}i(Je,"matchesAppliesTo");function Oo(e){return Gl.includes(e)}i(Oo,"isTier2");function xo(e){return e.mode==="enforced"&&!Oo(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}i(xo,"severityFor");function Oe(e,t,n,r=1){let{severity:o,failsStrict:s}=xo(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:o,sensor:e.sensor,failsStrict:s}}i(Oe,"baseViolation");function nn(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}i(nn,"isInRuleLayer");function rn(e,t,n){return t.filter(r=>!(!r.exported||!Je(r.file,e.appliesTo)||!nn(r.file,e,n)))}i(rn,"shapesForRule");function Ql(e,t,n){let r=[];for(let o of rn(e,t,n))(o.hasPublicSetters||o.hasPublicMutableFields)&&r.push(Oe(e,o.file,`Exported class ${o.className} exposes public mutable state (sensor aggregate-private-state).`));return r}i(Ql,"evaluateAggregatePrivateState");function ec(e,t,n){let r=[];for(let o of rn(e,t,n))if(o.hasPublicConstructor&&!o.hasStaticFactory){if(!(o.hasPublicMutableFields||o.hasPublicSetters||(o.mutatingMethods?.length??0)>0))continue;r.push(Oe(e,o.file,`Exported class ${o.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}return r}i(ec,"evaluateAlwaysValidFactory");function tc(e,t,n){let r=[],o=gr();for(let s of rn(e,t,n)){let a=Xl(s);pr(s)!=null&&r.push(Oe(e,s.file,`Exported class ${s.className} shape analysed until character ${pr(s)}; later methods may be invisible (sensor domain-event-on-mutation).`));for(let c of s.mutatingMethods)c.referencesGuardOrPublish||r.push(Oe(e,s.file,`Mutating method ${s.className}.${c.name} does not reference ${o} (sensor domain-event-on-mutation).${a}`))}return r}i(tc,"evaluateDomainEventOnMutation");function nc(e,t){let n=[];for(let r of t.files)Je(r,e.appliesTo)&&nn(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(Oe(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}i(nc,"evaluateOrchestrationOnly");function rc(e,t){let n=[];for(let r of t.files)Je(r,e.appliesTo)&&nn(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(Oe(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}i(rc,"evaluateThinAdapter");function sc(e,t){let n=[];for(let r of t.files)Je(r,e.appliesTo)&&nn(r,e,t.layerForFile)&&t.fileHints?.[r]?.persistenceWrite&&n.push(Oe(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(sc,"evaluateWritesViaAggregate");function oc(e,t,n){let r=[];for(let o of rn(e,t,n))if(o.dataOnly===!0){let s=Oe(e,o.file,`Exported type ${o.className} looks data-only / anemic (sensor no-anemic-model; advisory only).`);r.push({...s,severity:"warning",failsStrict:!1})}return r}i(oc,"evaluateNoAnemicModel");function hr(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(...Ql(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...ec(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...tc(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...nc(n,e));break;case"thin-adapter":t.push(...rc(n,e));break;case"writes-via-aggregate":t.push(...sc(n,e));break;case"no-anemic-model":t.push(...oc(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(hr,"evaluateArkRuleSensors");function Ar(e,t){let n=[],r=t.map(o=>o.replace(/\\/g,"/"));for(let o of e.structure){if(!o.appliesTo||o.appliesTo.length===0||r.some(l=>Je(l,o.appliesTo)))continue;let{severity:a,failsStrict:c}=xo(o);n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule structure "${o.id}" appliesTo matched zero governed files (patterns: ${o.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:o.provenance.sourceFile,line:1,fromLayer:o.provenance.layer,arkruleId:o.id,arkruleSource:o.provenance.sourceFile,severity:a,sensor:o.sensor,failsStrict:c})}for(let o of e.invariants??[]){if(!o.appliesTo||o.appliesTo.length===0||r.some(c=>Je(c,o.appliesTo)))continue;let a=o.mode==="enforced";n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule invariant "${o.id}" appliesTo matched zero governed files (patterns: ${o.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:o.provenance.sourceFile,line:1,fromLayer:o.provenance.layer,arkruleId:o.id,arkruleSource:o.provenance.sourceFile,severity:a?"error":"warning",sensor:"invariant-coverage",failsStrict:a})}return n.sort((o,s)=>o.file.localeCompare(s.file)||o.arkruleId.localeCompare(s.arkruleId)||o.message.localeCompare(s.message))}i(Ar,"collectEmptyAppliesToFindings");var So=64;function ac(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===46;)t-=1;return t===e.length?e:e.slice(0,t)}i(ac,"stripTrailingDots");function ic(e){let t=e.trim(),n=t.length>So?t.slice(0,So):t;return ac(n)}i(ic,"normalizeIntentPrefix");function lc(e){let t=e.toLowerCase();return t.includes("domain")||t.includes("entity")||t.includes("aggregate")||t.includes("model")}i(lc,"layerNameLooksDomain");function cc(e){return e.some(t=>{let n=ic(t);return n==="Domain"||n.startsWith("Domain.")})}i(cc,"ownsDomainIntent");function dc(e,t=[]){return lc(e)||cc(t)}i(dc,"isDomainRoleLayerName");function To(e){if(e.arkRulesActive!==!0)return[];let t=(e.layers??[]).filter(l=>dc(l.name,l.intentPrefixes??[])).map(l=>l.name);if(t.length===0)return[];let n=new Set(t);if(!(e.files??[]).some(l=>{let u=typeof l.layer=="string"?l.layer:"";return u.length>0&&n.has(u)}))return[];if((e.arkRules.invariants??[]).filter(l=>n.has(l.provenance.layer)).length>0)return[];let s=t.find(l=>e.arkRules.byLayer?.[l])??t[0],a=e.arkRules.byLayer?.[s]?.sourceFile??`arkrules/${s}.json`,c=(e.arkRules.structure??[]).some(l=>l.mode==="enforced"&&n.has(l.provenance.layer)&&!Oo(l.sensor));return[{ruleId:"INVARIANT_CATALOG_EMPTY",code:"invariant-catalog-empty",message:`ArkRules is on and ${s} has code, but invariants[] is empty \u2014 there are no phrases the code must preserve. Add 1\u20132 short phrases in ${a}.`,file:a,line:1,fromLayer:s,arkruleId:"invariant-catalog",arkruleSource:a,severity:c?"error":"warning",sensor:"invariant-coverage",failsStrict:c}]}i(To,"collectEmptyInvariantCatalogFindings");var Io=/\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)/,Eo=/\bfrom\s+['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)(?:\.[cm]?[jt]sx?)?['"]|require\(\s*['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)/,uc=/\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 pc(e){return e==="PersistenceAdapters"}i(pc,"isPersistenceDriverLayer");function fc(e,t){if(Io.test(e)||Eo.test(e))return!0;if(!t)return!1;for(let n of t){if(pc(n.layer))return!0;let r=n.specifier;if(!r)continue;let o=`from '${r}'`;if(Io.test(o)||Eo.test(o))return!0}return!1}i(fc,"sourceImportsPersistenceDriver");var mc=/\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*=)/,gc=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,yc=/\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*=/,hc=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function No(e,t,n){if(!t)return null;let r=fc(t,n),o=r&&uc.test(t);if(t.length<40)return o?{persistenceWrite:!0}:null;let s=t.match(new RegExp(yc.source,"g"))??[],a=t.match(new RegExp(hc.source,"g"))??[],c=(t.match(/\bif\s*\(/g)??[]).length,l=(t.match(/\bswitch\s*\(/g)??[]).length,u=s.length>=2||s.length>=1&&a.length>=2||a.length>=3&&c+l>=6,p=mc.test(t)||gc.test(t),g=s.length>=1||a.length>=2,f=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),m=r&&g||p&&g||r&&f&&(c>=4||s.length>=1)||p&&r;return!u&&!m&&!o?null:{...u?{orchestrationHeavy:!0}:{},...m?{adapterThick:!0}:{},...o?{persistenceWrite:!0}:{}}}i(No,"deriveArkRuleFileHints");function Rr(e,t){let n={};for(let[r,o]of Object.entries(e)){let s=r.replace(/\\/g,"/"),a=No(r,o,t?.[s]);a&&(n[s]=a)}return n}i(Rr,"buildArkRuleFileHints");var Ac=new Set(["public","private","protected","static","async","readonly","abstract","override","declare","get","set"]),Rc=new Set(["if","match","when"]);function tn(e,t){let n=e[t];if(n==="/"&&e[t+1]==="/"){let r=e.indexOf(`
19
- `,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(tn,"skipStringOrComment");function kt(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=tn(e,n);continue}break}return n}i(kt,"skipWsAndComments");function bo(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(bo,"readIdent");function ur(e,t,n,r){if(e[t]!==n)return null;let o=1,s=t+1;for(;s<e.length&&o>0;){let a=tn(e,s);if(a!==s){s=a;continue}let c=e[s];c===n?o+=1:c===r&&(o-=1),s+=1}return o===0?s:null}i(ur,"skipBalanced");function kc(e){let t=[],n=0,r;for(;n<e.length&&(n=kt(e,n),!(n>=e.length));){if(e[n]===";"){n+=1;continue}let o=[],s=n;for(;;){let p=bo(e,s);if(!p||!Ac.has(p.ident))break;o.push(p.ident),s=kt(e,p.end)}let a=bo(e,s);if(!a){n+=1;continue}if(s=kt(e,a.end),e[s]==="<"){let p=ur(e,s,"<",">");if(p==null){r=e.length;break}s=kt(e,p)}if(e[s]==="("){let p=ur(e,s,"(",")");if(p==null){r=e.length;break}if(s=kt(e,p),e[s]===":")for(s+=1;s<e.length&&e[s]!=="{"&&e[s]!==";";){let g=tn(e,s);if(g!==s){s=g;continue}s+=1}if(e[s]==="{"){let g=ur(e,s,"{","}");if(g==null){r=e.length;break}t.push({name:a.ident,modifiers:o,kind:"method",body:e.slice(s+1,g-1)}),n=g;continue}if(e[s]===";"){n=s+1;continue}n=s+1;continue}let c=0,l=0,u=0;for(;s<e.length;){let p=tn(e,s);if(p!==s){s=p;continue}let g=e[s];if(g==="{")c+=1;else if(g==="}"){if(c===0)break;c-=1}else if(g==="(")l+=1;else if(g===")")l-=1;else if(g==="[")u+=1;else if(g==="]")u-=1;else if(g===";"&&c===0&&l===0&&u===0){s+=1;break}s+=1}t.push({name:a.ident,modifiers:o,kind:"field",body:""}),n=s}return{members:t,truncatedAt:r}}i(kc,"scanClassMembers");function Sc(e,t){let n=[],r=/export\s+(?:abstract\s+)?class\s+([A-Za-z_][A-Za-z0-9_]*)\s*(?:extends\s+[^{]+)?(?:implements\s+[^{]+)?\{/g,o;for(;(o=r.exec(t))!==null;){let s=o[1],a=o.index+o[0].length,c=1,l=a;for(;l<t.length&&c>0;){let k=t[l];k==="{"?c+=1:k==="}"&&(c-=1),l+=1}let u=t.slice(a,l-1),p=c>0,g=kc(u),f=p?t.length:g.truncatedAt==null?void 0:a+g.truncatedAt,m=g.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"))),d=m.length>0,y=/(?:^|[\n;{])\s*(?:public\s+)?set\s+[a-zA-Z_]/.test(u),b=/(?:^|[\n;{])\s*private\s+constructor\s*\(/.test(u),x=/(?:^|[\n;{])\s*(?:public\s+)?constructor\s*\(/.test(u)&&!b,S=/(?:^|[\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),E=[];for(let k of g.members)k.kind==="method"&&k.name!=="constructor"&&(k.modifiers.includes("static")||k.modifiers.includes("get")||k.modifiers.includes("set")||Rc.has(k.name)||Yl(k.name,k.body)&&E.push({name:k.name,referencesGuardOrPublish:ql(k.body)}));let D=g.members.filter(k=>k.kind==="method").length<=1&&m.length>=2&&d;n.push(Jl({file:e,className:s,exported:!0,hasPublicMutableFields:d,hasPublicSetters:y,hasPublicConstructor:x,hasStaticFactory:S,mutatingMethods:[...E],dataOnly:D},f))}return n}i(Sc,"extractClassShapesFromSource");var Ic=50;function kr(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(kr,"normalizeExtraMergeTeethClassification");function Ae(e){let t=kr(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(Ae,"extraMergeTeethAllowed");function Sr(e){let t=e.length,n=0,r=new Set;for(let o of e){let s=typeof o.layer=="string"&&o.layer.length>0?o.layer:null;s&&(n+=1,r.add(s))}return{governedPercent:t>0?Math.round(n/t*100):0,populatedLayerCount:r.size}}i(Sr,"classifyResolvedLayerCoverage");function Ir(e){return typeof e=="string"&&e.startsWith("ARKRUN_")}i(Ir,"isArkRunRuleId");function wo(e){return typeof e=="string"&&e.startsWith("ARKORDER_")}i(wo,"isArkOrderRuleId");function Po(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(Po,"isExtraPlaneFinding");function Ec(e,t={}){if(!Array.isArray(e)||Ae(t))return e;for(let n of e)Po(n)&&n.failsStrict!==!1&&(n.failsStrict=!1,n.severity==="error"&&(n.severity="warning"));return e}i(Ec,"demoteExtraPlaneTeethUnderClassificationFloor");var Lo="Structure = heuristics; invariants = catalog+coverage evidence (not business runtime); ArkRun = kernel usage + declarations (not a score); ArkOrder = the few big product choices (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 he(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):0}i(he,"countOrZero");function sn(e={}){let t=kr(e.classification),n=typeof t.governedPercent=="number"?t.governedPercent:null,r=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null,o=n!=null||r!=null,s=Ae(t),a=e.arkRules,c=he(a?.structureEnforced),l=he(a?.structureTotal),u=typeof a?.structureAdvisory=="number"?he(a.structureAdvisory):Math.max(0,l-c),p=he(a?.invariantEnforced),g=he(a?.invariantTotal),f=typeof a?.invariantAdvisory=="number"?he(a.invariantAdvisory):Math.max(0,g-p),m=c>0||p>0,d=e.arkRun?.present===!0,y=e.arkRun?.mode==="enforced"||e.arkRun?.mode==="advisory"?e.arkRun.mode:null,b=he(e.arkRun?.residualCount),x=d&&y==="enforced",S=x&&s,E=e.arkOrder?.present===!0,C=e.arkOrder?.mode==="enforced"||e.arkOrder?.mode==="advisory"?e.arkOrder.mode:null,D=he(e.arkOrder?.residualCount),k=E&&C==="enforced",P=k&&s,ge=m||x||k,N=ge&&s,H=ge&&o&&!s,L;if(N){let G=[];m&&G.push("enforced structure/invariant findings"),x&&G.push("enforced ArkRun skip findings"),k&&G.push("enforced ArkOrder skip findings"),L=`Layer graph failures plus ${G.join(" and ")} (advisory extras never fail merge alone).`}else if(H)L=`Layer graph only \u2014 enforced ${[m?"ArkRules structure/invariant":null,x?"ArkRun":null,k?"ArkOrder":null].filter(pe=>!!pe).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.`;else{let G=d?y==="advisory"?" Advisory ArkRun never merge-blocks.":" ArkRun extra is present but does not arm merge teeth.":" Absence of arkRun is silent.",pe=E?C==="advisory"?" Advisory ArkOrder never merge-blocks.":" ArkOrder extra is present but does not arm merge teeth.":" Absence of arkOrder is silent.";L="Layer graph only \u2014 no enforced ArkRules structure/invariant teeth on this tree. Advisory packs do not arm merge teeth."+G+pe}let j={layers:{role:"inter-layer-edges",alwaysOnGate:!0,note:"Import/export layer graph \u2014 the default merge plane. Absent extras change nothing here."},structureSensors:{role:"intra-layer-heuristics",total:l,enforced:c,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:g,enforced:p,advisory:f,covered:he(a?.covered),uncovered:he(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:d,mode:y,residualCount:b,extraMergeTeeth:S,note:d?y==="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."},arkOrder:{role:"pattern-slaving",present:E,mode:C,residualCount:D,extraMergeTeeth:P,note:E?C==="enforced"?"Enforced ArkOrder arms extra merge teeth only when the layer plane is classified. Residual is a count, never a score.":"Advisory ArkOrder never adds merge teeth and never flips valid. Residual is a count, never a score.":"Absence of arkOrder is silent \u2014 Layers verdicts unchanged. The extra never becomes a score."},extraMergeTeeth:N,dualPlaneStamp:Lo,failMergeWhen:L};return o&&(j.classificationGate={governedPercent:n,populatedLayerCount:r,floorPercent:50,allowsTeeth:s}),j}i(sn,"composeMergePlanesHonesty");var Mo=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"],bc=["publisher","publish","raise","raiseAsync","send","sendTo","subscribe","registerHandler","resolve","resolveSingleton"],vc=new Set(Mo),Cc=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"]),_c=new Set(["Array","Atomics","Buffer","JSON","Math","Number","Object","Promise","Reflect","String","console","fs","path","url","util"]);function Et(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")}i(Et,"isArkRunKernelModuleSpecifier");var Fo=["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"],Er=new Set(Fo);function vr(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(Er.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(Er.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:Er.has(e.slice(0,r))}i(vr,"isArkRunTransportBypassSpecifier");function br(e){if(vc.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(br,"arkRunKernelCallKind");function It(e,t){let n=1;for(let r=0;r<t;r+=1)e.charCodeAt(r)===10&&(n+=1);return n}i(It,"lineAt");function bt(e){return e.replace(/\/\*[\s\S]*?\*\//g,t=>t.replace(/[^\n]/g," ")).replace(/(^|[^:\\])\/\/.*$/gm,t=>t.replace(/\/\/.*$/,n=>" ".repeat(n.length)))}i(bt,"stripCommentsPreservingLines");function Oc(e,t){let n=e.slice(t),r=/^\s*(['"])((?:\\.|[^\\])*?)\1/.exec(n);if(!r)return;let o=r[2]??"";return o.length>0?o:void 0}i(Oc,"firstStringLiteralArg");function Do(e,t,n){let r=Math.max(0,t-n.length-8),o=e.slice(r,t);return new RegExp(`\\b${n}\\s+$`).test(o)}i(Do,"keywordBefore");function on(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(on,"parseValueImportClause");function xc(e,t){on(bt(e),t)}i(xc,"forEachArkRunValueImportClause");function Cr(e,t){let n=bt(t),r=[],o=/\b(?:import|export)(\s+type)?\s+([\s\S]*?)\s+from\s*['"]([^'"]+)['"]/g,s;for(;(s=o.exec(n))!==null;){let c=s[3]??"";if(!c)continue;let l=s[0]??"";r.push({from:e,specifier:c,kind:/^\s*export/.test(l)?"export":"import",typeOnly:!!s[1],line:It(t,s.index),resolution:"resolved-external"})}let a=/\b(?:require|import)\s*\(\s*['"]([^'"]+)['"]\s*\)/g;for(;(s=a.exec(n))!==null;){let c=s[1]??"";if(!c)continue;let l=s[0]?.startsWith("import")?"dynamic-import":"require";r.push({from:e,specifier:c,kind:l,typeOnly:!1,line:It(t,s.index),resolution:"resolved-external"})}return r}i(Cr,"extractArkRunValueImportDependenciesFromSource");function _r(e){let t=[];return xc(e,n=>{let r=/\{([^}]*)\}/.exec(n);if(r?.[1])for(let o of r[1].split(",")){let s=o.trim();if(!s||s.startsWith("type "))continue;let a=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(s),c=a?.[2]??/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(s)?.[1],l=a?.[1]??c;c&&l&&/^[A-Z]/.test(l)&&t.push(c,l)}}),St(t)}i(_r,"extractArkRunImportedConstructorNamesFromSource");function Tc(e){let t=new Map,n=new Set;return on(e,(r,o)=>{if(!Et(o))return;let s=/\*\s+as\s+([A-Za-z_][A-Za-z0-9_]*)/.exec(r);s?.[1]&&n.add(s[1]);let a=/^([A-Za-z_][A-Za-z0-9_]*)\s*(?:,|$)/.exec(r.trim());a?.[1]&&t.set(a[1],a[1]);let c=/\{([^}]*)\}/.exec(r);if(c?.[1])for(let l of c[1].split(",")){let u=l.trim();if(!u||u.startsWith("type "))continue;let p=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(u);if(p){t.set(p[2],p[1]);continue}let g=/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(u);g?.[1]&&t.set(g[1],g[1])}}),{named:t,namespaces:n}}i(Tc,"collectKernelImportBindings");function Nc(e,t){let n=new Set(t);return on(e,(r,o)=>{let s=/\{([^}]*)\}/.exec(r);if(s?.[1])for(let a of s[1].split(",")){let c=a.trim();if(!c||c.startsWith("type "))continue;let l=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(c),u=l?.[2]??/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(c)?.[1],p=l?.[1]??u;!u||!p||!/^[A-Z]/.test(p)||(Et(o)||t.has(p)||t.has(u))&&(n.add(u),n.add(p))}}),n}i(Nc,"collectImportedConstructors");function wc(e,t){let n;return on(e,(r,o)=>{!n&&new RegExp(`\\b${t}\\b`).test(r)&&(n=o)}),n}i(wc,"importedFromForName");function Or(e,t){let n=bt(t),r=Tc(n),o=[],s=/\b([A-Za-z_][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,a;for(;(a=s.exec(n))!==null;){let c=a[1],l=a.index;if(Do(n,l,"function")||Do(n,l,"class"))continue;let p=n.slice(0,l).match(/([A-Za-z_][A-Za-z0-9_]*)\s*\.\s*$/)?.[1],g=r.named.get(c)??c,f=br(g)??br(c);if(!f)continue;let m=r.named.has(c)||p!==void 0&&r.namespaces.has(p);if(f!=="factory"&&(!m&&p===void 0||p&&_c.has(p)&&!m))continue;let d=Oc(n,l+a[0].length);o.push({file:e,line:It(t,l),kind:f,callee:c,viaImport:m,...p?{receiver:p}:{},...d?{nameLiteral:d}:{}})}return o}i(Or,"extractArkRunKernelCallsFromSource");function xr(e,t,n){let r=bt(t),o=Nc(r,n),s=[],a=/\bnew\s+(?:[A-Za-z_][A-Za-z0-9_]*\s*\.\s*)*([A-Z][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,c;for(;(c=a.exec(r))!==null;){let l=c[1];if(Cc.has(l)||!o.has(l))continue;let u=wc(r,l);s.push({file:e,line:It(t,c.index),typeName:l,...u?{importedFrom:u}:{}})}return s}i(xr,"extractArkRunManagedNewsFromSource");function Pc(e,t){let n=0,r;for(let o=t;o<e.length;o+=1){let s=e[o];if(r){if(s==="\\"){o+=1;continue}s===r&&(r=void 0);continue}if(s==="'"||s==='"'||s==="`"){r=s;continue}if(s==="[")n+=1;else if(s==="]"&&(n-=1,n===0))return o}return-1}i(Pc,"matchingBracketEnd");function Lc(e,t,n){let r=e.slice(t+1,n),o=[],s=/(['"])((?:\\.|[^\\])*?)\1/g,a;for(;(a=s.exec(r))!==null;){let c=a[2]??"";c.length>0&&o.push(c)}return o}i(Lc,"stringLiteralsInList");function St(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}i(St,"uniqueSorted");function Dc(e,t){let n=bt(t),r=/\b(uses|reactsTo|raises|sends)\s*:/g,o=[],s=[],a=[],c=[],l,u;for(;(u=r.exec(n))!==null;){let p=n.slice(u.index+u[0].length),g=/^\s*\[/.exec(p);if(!g)continue;let f=u.index+u[0].length+(g[0].length-1),m=Pc(n,f);if(m<0)continue;let d=Lc(n,f,m);if(d.length===0)continue;l===void 0&&(l=u.index);let y=u[1];y==="uses"?o.push(...d):y==="reactsTo"?s.push(...d):y==="raises"?a.push(...d):c.push(...d)}return l===void 0?[]:[{file:e,line:It(t,l),uses:St(o),reactsTo:St(s),raises:St(a),sends:St(c)}]}i(Dc,"extractArkRunDeclarationsFromSource");var Mc=["arkrun-missing-root","arkrun-kernel-in-domain","arkrun-direct-new","arkrun-undeclared-emit","arkrun-undeclared-handle","arkrun-undeclared-depend","arkrun-transport-bypass"],Fc=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],$c=new Set(Fc);function Hc(e){return $c.has(e)}i(Hc,"isArkRunEditorSensor");var Tr={"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"},jo="ARKRUN_INTERACTION_NAME_INCOMPLETE";function Ko(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 o=r.trim().replace(/\.+$/,"");return o==="Domain"||o.startsWith("Domain.")})}i(Ko,"isDomainRoleLayer");function jc(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}i(jc,"compareFindings");function be(e,t,n,r,o,s,a){let c=e.mode==="enforced"&&a;return{ruleId:Tr[t],sensor:t,message:o,file:n,line:r,...s?.fromLayer?{fromLayer:s.fromLayer}:{},...s?.target?{target:s.target}:{},severity:c?"error":"warning",failsStrict:c,nextAction:ye({ruleId:Tr[t],fromLayer:s?.fromLayer,target:s?.target})}}i(be,"finding");function Kc(e,t){let n=[],r=[],o=[],s=[];for(let a of e)a.file===t&&(n.push(...a.uses),r.push(...a.reactsTo),o.push(...a.raises),s.push(...a.sends));return{uses:new Set(n),reactsTo:new Set(r),raises:new Set(o),sends:new Set(s)}}i(Kc,"bagForFile");function $o(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}i($o,"emitKinds");function Ho(e){return e==="subscribe"||e==="register-handler"}i(Ho,"handleKinds");function Vc(e){return e==="resolve"||e==="resolve-singleton"}i(Vc,"dependKinds");function Uc(e,t,n){let r=[],o=e.kernelRoots??e.compositionRoots;if(o.length===0)return r.push(be(e,"arkrun-missing-root","ark.config.json",1,"ArkRun kernelRoots is empty; no createArkKernel factory site is declared.",void 0,n)),r;let s=new Map;for(let a of t){let c=s.get(a.matchedRoot)??[];c.push(a),s.set(a.matchedRoot,c)}for(let a of o){let c=[...s.get(a)??[]].sort((u,p)=>u.file.localeCompare(p.file));if(c.length===0){r.push(be(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(c.some(u=>u.hasKernelFactory))continue;let l=c[0];r.push(be(e,"arkrun-missing-root",l.file,1,`ArkRun kernel root ${JSON.stringify(a)} has no createArkKernel / createStrictArkKernel factory.`,{target:a},n))}return r}i(Uc,"evaluateMissingRoot");function Gc(e,t,n,r,o){let s=new Map(t.map(c=>[c.name,c.intentPrefixes??[]])),a=[];for(let c of n){let l=c.specifier;if(!l||!Et(l))continue;let u=r(c.from);u&&Ko(u,s.get(u)??[])&&a.push(be(e,"arkrun-kernel-in-domain",c.from,c.line,`${u} must not import kernel module ${JSON.stringify(l)}.`,{fromLayer:u,target:l},o))}return a}i(Gc,"evaluateKernelInDomain");function Bc(e,t,n,r,o,s){let a=new Set(e.managedLayers);if(a.size===0)return[];let c=new Map(t.map(p=>[p.name,p.intentPrefixes??[]])),l=new Set(r.filter(p=>p.hasKernelFactory).map(p=>p.file)),u=[];for(let p of n){if(l.has(p.file))continue;let g=p.typeName;if(e.ignoreDirectNewForErrors!==!1&&(g.endsWith("Error")||g==="Error")||g.endsWith("DTO")||g.endsWith("VO"))continue;let f=o(p.file);!f||!a.has(f)||Ko(f,c.get(f)??[])||u.push(be(e,"arkrun-direct-new",p.file,p.line,`${f} must not construct ${p.typeName} with new outside an ArkRun composition-root factory.`,{fromLayer:f,target:p.typeName},s))}return u}i(Bc,"evaluateDirectNew");function zc(e,t,n,r,o){let s=[],a=[];if(e.requireDeclarations!==!0)return{findings:s,completenessReasons:a};let c=new Set(e.managedLayers);if(c.size===0)return{findings:s,completenessReasons:a};for(let l of t){if(!$o(l.kind)&&!Ho(l.kind)&&!Vc(l.kind))continue;let u=r(l.file);if(!u||!c.has(u))continue;if(!l.nameLiteral){e.mode==="enforced"&&a.push({code:jo,file:l.file,message:`ArkRun ${l.kind} call in ${l.file} has no string-literal name; enforced extra cannot prove the declaration.`});continue}let p=Kc(n,l.file);if($o(l.kind)){if(p.raises.has(l.nameLiteral)||p.sends.has(l.nameLiteral))continue;s.push(be(e,"arkrun-undeclared-emit",l.file,l.line,`Emit ${JSON.stringify(l.nameLiteral)} is not declared in raises or sends.`,{fromLayer:u,target:l.nameLiteral},o));continue}if(Ho(l.kind)){if(p.reactsTo.has(l.nameLiteral))continue;s.push(be(e,"arkrun-undeclared-handle",l.file,l.line,`Handle ${JSON.stringify(l.nameLiteral)} is not declared in reactsTo.`,{fromLayer:u,target:l.nameLiteral},o));continue}p.uses.has(l.nameLiteral)||s.push(be(e,"arkrun-undeclared-depend",l.file,l.line,`Depend ${JSON.stringify(l.nameLiteral)} is not declared in uses.`,{fromLayer:u,target:l.nameLiteral},o))}return{findings:s,completenessReasons:a}}i(zc,"evaluateUndeclared");function Wc(e,t,n,r){let o=new Set(e.managedLayers);if(o.size===0)return[];let s=[];for(let a of t){if(a.typeOnly)continue;let c=a.specifier;if(!c||!vr(c))continue;let l=n(a.from);!l||!o.has(l)||s.push(be(e,"arkrun-transport-bypass",a.from,a.line,`${l} must not import broker/queue/emitter ${JSON.stringify(c)}; use the ArkRun kernel transport.`,{fromLayer:l,target:c},r))}return s}i(Wc,"evaluateTransportBypass");function an(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=Ae(e.classification),r=zc(t,e.kernelCalls,e.declarations,e.layerForFile,n),o=[...Uc(t,e.compositionRootHits,n),...Gc(t,e.layers,e.dependencies,e.layerForFile,n),...Bc(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...Wc(t,e.dependencies,e.layerForFile,n)].sort(jc),s=[...r.completenessReasons].sort((a,c)=>{let l=`${a.code}\0${a.file??""}\0${a.message}`,u=`${c.code}\0${c.file??""}\0${c.message}`;return l<u?-1:l>u?1:0});return{findings:o,completenessReasons:s}}i(an,"evaluateArkRunSensors");function Vo(e){return{findings:an(e).findings.filter(n=>Hc(n.sensor)),completenessReasons:[]}}i(Vo,"evaluateArkRunEditorSensors");function qc(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(qc,"fileMatchesCompositionRoot");function Yc(e,t,n){let r=Or(t,n).some(a=>a.kind==="factory"),o=[],s=e.kernelRoots??e.compositionRoots;for(let a of s)qc(a,t)&&o.push({file:t,matchedRoot:a,hasKernelFactory:r});return o}i(Yc,"compositionRootHitsForSource");function Jc(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=new Set(_r(e.source));return Vo({arkRun:t,layers:e.layers,kernelCalls:[],managedNews:xr(e.file,e.source,n),compositionRootHits:Yc(t,e.file,e.source),declarations:[],dependencies:Cr(e.file,e.source),layerForFile:e.layerForFile,classification:e.classification})}i(Jc,"evaluateArkRunEditorSensorsFromSource");function Uo(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}i(Uo,"isArkOrderModuleSpecifier");var Go=new Map;function Bo(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(Bo,"escapeAppliesToLiteral");function Xc(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let o=e[n+1];if("*?{}[],".includes(o)||o==="\\"){t+="\\"+o,n+=1;continue}t+="/";continue}t+=r}return t}i(Xc,"normalizeAppliesToGlob");function Zc(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(Zc,"appliesToBracesBalanced");function Qc(e){let t=Go.get(e);if(t)return t;let n=Xc(e),r=Zc(n),o="",s=0;for(let c=0;c<n.length;c+=1){let l=n[c];l==="\\"&&c+1<n.length?(o+=Bo(n[c+1]),c+=1):l==="*"?n[c+1]==="*"?n[c+2]==="/"?(o+="(?:.*/)?",c+=2):(o+=".*",c+=1):o+="[^/]*":l==="?"?o+="[^/]":l==="{"&&r?(o+="(?:",s+=1):l==="}"&&r&&s>0?(o+=")",s-=1):l===","&&r&&s>0?o+="|":o+=Bo(l)}let a=new RegExp(`^${o}$`);return Go.set(e,a),a}i(Qc,"globToRegExp");var ed=["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"],Nr={"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 td(e,t){return!t||t.length===0?!0:t.some(n=>Qc(n).test(e))}i(td,"matchesArkOrderAppliesTo");function nd(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)?!0:t.some(r=>{let o=r.trim().replace(/\.+$/,"");return o==="Domain"||o.startsWith("Domain.")})}i(nd,"isDomainRoleLayer");function xe(e,t,n,r,o,s,a){let c=e.mode==="enforced"&&a;return{ruleId:Nr[t],sensor:t,message:o,file:n,line:r,...s?.fromLayer?{fromLayer:s.fromLayer}:{},...s?.target?{target:s.target}:{},severity:c?"error":"warning",failsStrict:c,nextAction:ye({ruleId:Nr[t],fromLayer:s?.fromLayer,target:s?.target})}}i(xe,"finding");function wr(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let n=Ae(e.classification),r=[],o=t.planeRoots;if(t.mode==="enforced"&&o.length===0)r.push(xe(t,"arkorder-missing-plane","ark.config.json",1,"ArkOrder planeRoots is empty; no createOrderPlane site is declared.",void 0,n));else{let l=new Map;for(let u of e.planeRootHits){let p=l.get(u.matchedRoot)??[];p.push(u),l.set(u.matchedRoot,p)}for(let u of o){let p=l.get(u)??[];if(p.length===0){r.push(xe(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}p.some(g=>g.hasPlaneFactory)||r.push(xe(t,"arkorder-missing-plane",p[0].file,1,`ArkOrder plane root ${JSON.stringify(u)} has no createOrderPlane factory.`,{target:u},n))}}let s=new Map(e.layers.map(l=>[l.name,l.intentPrefixes??[]]));for(let l of e.dependencies){let u=l.specifier;if(!u||!Uo(u))continue;let p=e.layerForFile(l.from);p&&nd(p,s.get(p)??[])&&r.push(xe(t,"arkorder-kernel-in-domain",l.from,l.line,"Domain-role layer imports arkgate/order; Domain stays plane-free.",{fromLayer:p,target:u},n))}for(let l of e.genericUpdates)r.push(xe(t,"arkorder-generic-update",l.file,l.line,`Generic ${l.method}() on the order plane rewrites \u03BE; Haken forbids it.`,{target:l.method},n));let a=t.xiKeys??[];for(let l of e.releaseKeyCounts??[])l.keyCount<=t.maxXiKeys||r.push(xe(t,"arkorder-too-many-params",l.file,l.line,`release() freezes ${l.keyCount} keys; maxXiKeys is ${t.maxXiKeys} (few slow modes).`,{target:String(l.keyCount)},n));for(let l of e.ingestWritesXi??[])r.push(xe(t,"arkorder-ingest-writes-xi",l.file,l.line,"ingest() result is assigned into a Release or \u03BE store; ingest may absorb or escalate, never mint a pattern.",void 0,n));let c=new Set(t.managedLayers);for(let l of a.length===0?[]:e.xiFieldWrites??[]){let u=e.layerForFile(l.file);!u||!c.has(u)||td(l.file,t.appliesTo)&&r.push(xe(t,"arkorder-xi-field-write",l.file,l.line,`This file writes ${JSON.stringify(l.key)} the same way it would write a seat count. Take the event in, or change that choice through the valve (propose, then apply).`,{fromLayer:u,target:l.key},n))}return r.sort((l,u)=>l.file.localeCompare(u.file)||l.ruleId.localeCompare(u.ruleId)||l.line-u.line),{findings:r,completenessReasons:[]}}i(wr,"evaluateArkOrderSensors");function te(e,t,n={}){return{ruleId:e,message:t,...n}}i(te,"configWarning");function ln(e){let{config:t,rules:n,files:r,manifest:o}=e,s=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(d=>typeof d!="string"))&&s.push(te("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)))s.push(te("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let d of["maxTsSuppressions","maxAnyCasts"]){let y=t.safety[d];y!==void 0&&(!Number.isInteger(y)||y<0)&&s.push(te("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${d} must be a non-negative integer.`))}let a=Array.isArray(t.layers)?t.layers:[],c=Array.isArray(o?.architecture?.layers)?o.architecture.layers:[],l=new Set([...a.map(d=>d.name).filter(Boolean),...c.map(d=>d.name).filter(d=>!!d)]);a.length===0&&s.push(te("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let u=new Set,p=new Set;for(let d of a){if(!d.name){s.push(te("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}u.has(d.name)&&p.add(d.name),u.add(d.name),d.forbiddenGlobals!==void 0&&(!Array.isArray(d.forbiddenGlobals)||d.forbiddenGlobals.some(b=>typeof b!="string"))&&s.push(te("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${d.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:d.name}));let y=Array.isArray(d.patterns)?d.patterns:[];if(y.length===0){s.push(te("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${d.name}" has no file patterns and will never classify files.`,{layer:d.name}));continue}for(let b of y){let x;try{x=ke(b)}catch(E){s.push(te("CONFIG_INVALID_LAYER_PATTERN",`Layer "${d.name}" has an invalid pattern "${b}": ${E instanceof Error?E.message:String(E)}`,{layer:d.name,pattern:b}));continue}let S=d.optional===!0||d.reserved===!0||d.allowEmpty===!0;!r.some(E=>x.test(E))&&!S&&s.push(te("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${d.name}" pattern "${b}" matched no included files (possible typo). Mark the layer reserved/allowEmpty if this house is reserved for later.`,{layer:d.name,pattern:b,failsStrict:!1,reserved:!1}))}}for(let d of p)s.push(te("CONFIG_DUPLICATE_LAYER",`Layer "${d}" is configured more than once.`,{layer:d}));if(l.size>0)for(let d of n??[])d.from&&!l.has(d.from)&&s.push(te("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${d.from}".`,{fromLayer:d.from,toLayer:d.to})),d.to&&!l.has(d.to)&&s.push(te("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${d.to}".`,{fromLayer:d.from,toLayer:d.to}));let g=new Set;if(a.length>1)for(let d of r){let y=-1,b=[];for(let x of a)for(let S of x.patterns??[]){if(!ke(S).test(d))continue;let E=Nn(S,d);E>y?(y=E,b=[x.name]):E===y&&!b.includes(x.name)&&b.push(x.name)}b.length>1&&g.add([...b].sort().join(" + "))}g.size>0&&s.push(te("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...g].join(", ")}.`,{pairs:[...g]}));let f=r.filter(d=>!fe(d,a));f.length>0&&s.push(te("CONFIG_UNCLASSIFIED_FILES",`${f.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:f.length,samples:f.slice(0,5)}));for(let d of ps(n))s.push(te("CONFIG_SLICE_IDENTITY_COLLISION",d.message,{paths:[...d.paths],fromLayer:d.from,toLayer:d.to,failsStrict:!1}));let m=Ds(t);if(m.length>0){let d=m[0]??"this layer";s.push(te("CONFIG_LAYER_MISSING_OWNER",`${d} has no owner. Add a GitHub handle or email to layers[].owners so this house has a name on the door.`,{layers:m,nextAction:Ms(d)}))}return s}i(ln,"collectAnalysisConfigWarnings");function zo(e,t){let n=e.ruleId==="ARKRULE_STRUCTURE",r=e.ruleId==="ARKRULE_SCOPE_EMPTY",o=e.ruleId==="INVARIANT_CATALOG_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:Ro({sensor:e.sensor,code:e.code})}:{},...r||o?{freezable:!1}:{},nextAction:t}}i(zo,"toArkRuleEngineViolation");function rd(e){let t=e.arkRules;return!!(t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0)}i(rd,"arkRulesMapIsOn");function Wo(e,t){return e.ruleId==="INVARIANT_CATALOG_EMPTY"?t?`Add 1\u20132 short phrases to invariants[] in ${e.arkruleSource} so Domain has policies the code must preserve (advisory \u2014 does not fail the merge until a domain structure rule is enforced).`:`Add 1\u20132 short phrases to invariants[] in ${e.arkruleSource} so Domain has policies the code must preserve. Empty catalog fails --strict-merge because a domain structure rule is already enforced.`:e.ruleId==="ARKRULE_SCOPE_EMPTY"?t?`Review appliesTo for ${e.arkruleId} in ${e.arkruleSource} (zero-match scope; advisory). Empty scope is not freezable; promote only after the folder exists.`:`Fix appliesTo globs for ${e.arkruleId} in ${e.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.`:t?`Review ArkRule ${e.arkruleId} in ${e.arkruleSource} (advisory).`:`Fix the structure or invariant for ${e.arkruleId} (declared in ${e.arkruleSource}), then preflight again.`}i(Wo,"arkRuleFindingNextAction");function sd(e,t){return t.some(n=>{try{return ke(n).test(e)}catch{return!1}})}i(sd,"matchesAny");function od(e,t){let n=e.contract.config.safety??{},r=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,o=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,s=e.contract.config.dynamicImportAllowlist??[],a=t.safetyUses.filter(y=>y.kind==="ts-suppression").map(({file:y,line:b})=>({file:y,line:b})),c=t.safetyUses.filter(y=>y.kind==="any-cast").map(({file:y,line:b})=>({file:y,line:b})),l=t.safetyUses.filter(y=>(y.kind==="dynamic-import"||y.kind==="dynamic-require")&&!sd(y.file,s)).map(y=>({file:y.file,line:y.line,kind:y.kind==="dynamic-require"?"require":"import"})),u=n.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(y=>y.kind==="in-memory-store").map(y=>({file:y.file,line:y.line,store:y.symbol??"in-memory store"})),p=n.allowDisabledPeerIsolation===!0?[]:(e.contract.config.rules??[]).filter(y=>y.peerIsolation===!1||y.allowed===!1&&!!y.from&&y.from===y.to&&y.peerIsolation!==!0).map(y=>({from:y.from,to:y.to})),g={tsSuppressions:a,anyCasts:c,nonLiteralDynamicImports:l,inMemoryProductionStores:u,disabledPeerIsolationRules:p,thresholds:{maxTsSuppressions:r,maxAnyCasts:o}},f=[],m=l.filter(y=>y.kind==="import");if(m.length>0){let y=m[0];f.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:y.file,line:y.line,message:`${m.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let d=l.filter(y=>y.kind==="require");if(d.length>0){let y=d[0];f.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:y.file,line:y.line,message:`${d.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(a.length>r){let y=a[0];f.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:y.file,line:y.line,message:`${a.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${r}).`})}if(c.length>o){let y=c[0];f.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:y.file,line:y.line,message:`${c.length} explicit any cast(s) exceed safety.maxAnyCasts (${o}).`})}if(u.length>0){let y=u[0];f.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:y.file,line:y.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 p.length>0&&f.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${p.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:g,warnings:f}}i(od,"evaluateSafety");function ad(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}i(ad,"ambientForbiddenGlobal");function qo(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return Fn(e,n.length>0?n:Mn.map(r=>({name:r.layer,prefixes:r.prefixes})))}i(qo,"intentLayer");function id(e,t,n){let r=[],o=new Map(e.contract.config.layers.map(s=>[s.name,s]));for(let s of t.ambientUses){let a=n.get(s.file);!a||!ad(s.symbol,o.get(a)?.forbiddenGlobals??[])||r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:a,target:s.symbol,message:`${a} must not use the ambient global "${s.symbol}".`})}for(let s of t.capabilityUses){let a=n.get(s.file);if(!a)continue;let c=o.get(a),l=c?.forbiddenGlobals??[],u=s.source==="import-based"?t.dependencies.find(p=>p.from===s.file&&p.line===s.line&&p.specifier===s.symbol&&!p.typeOnly)?.kind:void 0;if(!(s.source==="ambient-global"&&ot(s.symbol,l))){if(s.source==="import-based"){let p=Ce(s.symbol,l);if(p){r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:a,target:s.symbol,...u?{edgeKind:u}:{},message:`${a} must not use module "${s.symbol}" because it is the import form of forbidden global "${p}".`});continue}}je(c).includes(s.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:s.file,line:s.line,fromLayer:a,target:s.symbol,capability:s.capability,...u?{edgeKind:u}:{},message:s.source==="import-based"?`${a} denies the ${s.capability} capability; found import of "${s.symbol}".`:`${a} denies the ${s.capability} capability; found ambient "${s.symbol}".`})}}for(let s of t.publishCalls){let a=n.get(s.file);if(!a)continue;for(let l of at({publishCall:!0,rawIntentName:s.rawIntentName,objectHasIntent:s.objectHasIntent,arkPublishCandidate:s.arkPublishCandidate,hasSource:s.hasSource}))r.push({ruleId:l.ruleId,file:s.file,line:s.line,...l.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:a}:{},message:l.message});if(!s.sourceIntent)continue;let c=qo(s.sourceIntent,e.contract);!c||c===a||r.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:s.file,line:s.line,fromLayer:a,toLayer:c,target:s.sourceIntent,message:`Publish source "${s.sourceIntent}" resolves to ${c}, but the publishing file is classified as ${a}.`})}for(let s of t.intentReferences){let a=n.get(s.file);if(!a)continue;let c=qo(s.intent,e.contract);if(!c)continue;let l=Te(e.contract.config.rules,a,c,{fromPath:s.file,layers:e.contract.config.layers});if(!l)continue;let u=l.rule.peerIsolation?Ke(l.peerIsolationReason??"cross-slice",{fromPath:s.file,fromSlice:l.fromSlice,toSlice:l.toSlice}):void 0,p=`${a} must not reference ${c} intent ${s.intent}.`,g=u&&l.peerIsolationReason!=="cross-slice"?`${p} ${u}`:l.rule.message?u?`${l.rule.message} (${u})`:l.rule.message:p;r.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:s.file,line:s.line,fromLayer:a,toLayer:c,target:s.intent,...l.rule.peerIsolation?{peerIsolation:!0}:{},message:g})}return r}i(id,"contentViolations");function ld(e){let{facts:t}=e,n=pt(e.contract.config),r=t.evidenceRequirementsHash===n,o=r?t.completeness:"unavailable",s=r?t.completenessReasons:[...t.completenessReasons,{code:"EVIDENCE_REQUIREMENTS_MISMATCH",message:"Resolved facts were collected for different policy-controlled evidence requirements."}].sort((A,se)=>{let et=`${A.code}\0${A.file??""}\0${A.message}`,tt=`${se.code}\0${se.file??""}\0${se.message}`;return et<tt?-1:et>tt?1:0}),a=t.files.map(A=>({...A,layer:fe(A.path,e.contract.config.layers)??null})),c=new Map(a.map(A=>[A.path,A.layer])),l=t.dependencies.map(A=>{let se=A.target?c.get(A.target)??fe(A.target,e.contract.config.layers):void 0;return{from:A.from,fromLayer:c.get(A.from)??null,...A.resolution==="resolved-project"&&A.target?{to:A.target,...se?{toLayer:se}:{}}:{},line:A.line,kind:A.kind,typeOnly:A.typeOnly,...A.targetTypeOnlyExports?{targetTypeOnlyExports:A.targetTypeOnlyExports}:{},...A.sourcePureTypeModule?{sourcePureTypeModule:A.sourcePureTypeModule}:{},...A.namedBindingsTypeOnly?{namedBindingsTypeOnly:A.namedBindingsTypeOnly}:{},...A.portProofEligible?{portProofEligible:A.portProofEligible}:{}}}),u=ln({config:e.contract.config,rules:e.contract.config.rules,files:a.map(A=>A.path)}),p=od(e,t),g=e.contract.arkRules??De(),f=a.map(A=>A.path),d={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?Rr(e.coverageInputs.fileContents):{},...e.fileHints??{}},y=i(A=>c.get(A)??fe(A,e.contract.config.layers),"resolveLayer"),b=[...hr({arkRules:g,classShapes:e.contract.classShapes??t.classShapes??[],files:f,layerForFile:y,fileHints:d}),...Ar(g,f),...To({arkRulesActive:rd(e.contract.config),arkRules:g,layers:e.contract.config.layers??[],files:f.map(A=>({path:A,layer:y(A)}))})],x=(g.invariants?.length??0)>0,S=ao({hasEnforcedInvariant:sr(g.invariants),coverage:e.contract.config.coverage,...e.coverageRootsPresent===!1?{declaredPathPresent:!1}:{}}),E=S.length>0?[]:oo({adopted:e.adopted===!0,hasDomainInvariants:rr(g.invariants),coverage:e.contract.config.coverage,...e.invariantTestsPathPresent===!1?{declaredPathPresent:!1}:{}}),C=[...S.map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,nextAction:"Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. An enforced invariant fails closed until that path is present.",failsStrict:!0,freezable:!1})),...E.map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,nextAction:"Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present.",failsStrict:!0,freezable:!1}))],D=b.filter(A=>A.failsStrict).map(A=>zo(A,Wo(A,!1))),k=b.filter(A=>!A.failsStrict).map(A=>({...zo(A,Wo(A,!0)),failsStrict:!1})),P=x?tr({arkRules:g,fileContents:e.coverageInputs?.fileContents??{},testFiles:e.coverageInputs?.testFiles??[],testGlobsMissing:e.coverageInputs?.testGlobsMissing===!0||e.coverageInputs===void 0||(e.coverageInputs.testFiles?.length??0)===0,coverageBudgetExhausted:e.coverageInputs?.coverageBudgetExhausted===!0,...e.coverageInputs?.stats?{coverageStats:e.coverageInputs.stats}:{},...e.coverageInputs?.coverageRoots?{coverageRoots:e.coverageInputs.coverageRoots}:{}}):{coverage:[],violations:[],partial:!1},ge=P.violations.filter(A=>A.failsStrict).map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,arkruleId:A.arkruleId,arkruleSource:A.arkruleSource,nextAction:`Add a test title or declared symbol covering ${A.arkruleId} (declared in ${A.arkruleSource}), then preflight again.`})),N=P.violations.filter(A=>!A.failsStrict).map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,arkruleId:A.arkruleId,arkruleSource:A.arkruleSource,failsStrict:!1,nextAction:A.ruleId==="INVARIANT_COVERAGE_OUTSIDE_ROOTS"?`Move ${A.file} under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json.`:`Cover invariant ${A.arkruleId} in ${A.arkruleSource} (advisory / partial).`})),H=Sr(a),L=an({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(A=>c.get(A)??fe(A,e.contract.config.layers),"layerForFile"),classification:H}),j=e.contract.config.arkRun?.mode,G=L.findings.filter(()=>j==="enforced").map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,target:A.target,nextAction:A.nextAction,sensor:A.sensor,failsStrict:A.failsStrict,...A.severity?{severity:A.severity}:{}})),pe=L.findings.filter(()=>j!=="enforced").map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,target:A.target,nextAction:A.nextAction,sensor:A.sensor,failsStrict:!1})),Re=wr({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(A=>c.get(A)??fe(A,e.contract.config.layers),"layerForFile"),classification:H}),Qe=e.contract.config.arkOrder?.mode,Tt=Re.findings.filter(()=>Qe==="enforced").map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,target:A.target,nextAction:A.nextAction,sensor:A.sensor,failsStrict:A.failsStrict,...A.severity?{severity:A.severity}:{}})),es=Re.findings.filter(()=>Qe!=="enforced").map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,target:A.target,nextAction:A.nextAction,sensor:A.sensor,failsStrict:!1})),v=[...P.partial&&P.coverage.some(A=>A.mode==="enforced"&&A.partial)?[{code:"INVARIANT_COVERAGE_PARTIAL",message:"Enforced ArkRules invariant coverage cannot be fully proven (missing test globs or empty test set); reporting partial, never covered."}]:[],...L.completenessReasons,...Re.completenessReasons],_=Ye({config:e.contract.config,rules:e.contract.config.rules,files:a.filter(A=>A.layer).map(A=>A.path),contentViolations:[...id(e,t,c),...D,...C,...ge,...G,...Tt],edges:l,warnings:[...u,...p.warnings,...k,...N,...pe,...es],safety:p.report}),h=o==="complete"&&v.length>0?"partial":o,R=h==="complete"?s:[...s,...v].sort((A,se)=>{let et=`${A.code}\0${A.file??""}\0${A.message}`,tt=`${se.code}\0${se.file??""}\0${se.message}`;return et<tt?-1:et>tt?1:0}),M=_.violations.filter(A=>A.failsStrict!==!1),X=h==="complete"&&M.length===0,ve=X&&_.warnings.every(A=>A.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:h,completenessReasons:R,valid:X,strictValid:ve,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:p.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:a,layers:e.contract.config.layers.map(A=>A.name),edges:l,capabilityUses:t.capabilityUses,violations:_.violations,warnings:_.warnings}}}i(ld,"analyzeCanonicalResolvedProject");function vt(e){return ld({contract:e.contract,facts:_e(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints,adopted:e.adopted,invariantTestsPathPresent:e.invariantTestsPathPresent,coverageRootsPresent:e.coverageRootsPresent})}i(vt,"analyzeResolvedProject");function Yo(e){return Z(K(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}i(Yo,"analysisTreeHash");function Jo(e){let t=Rt(e),n=new Map(t.ir.files.map(d=>[d.path,d])),r=[],o=new Set,s=[];for(let d of e.changes){let y=d.path.replace(/\\/g,"/"),b=Me(d.path);if(!b||b===".."||b.startsWith("../")||y.startsWith("/")||/^[A-Za-z]:\//.test(y)||y.includes("\0")){s.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(o.has(b)){s.push({ruleId:"DUPLICATE_CHANGE_PATH",file:b,line:1,message:`The atomic change set contains more than one operation for ${b}.`});continue}o.add(b),"delete"in d&&d.delete&&!n.has(b)&&s.push({ruleId:"DELETE_TARGET_MISSING",file:b,line:1,message:`Cannot delete ${b} because it is not present in the supplied base tree.`}),r.push("delete"in d&&d.delete?{path:b,delete:!0}:{path:b,content:"content"in d?d.content:""})}e.changes.length===0&&s.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let a=en({...e,changes:r}),c=new Map(a.ir.files.map(d=>[d.path,d])),l=a.ir.violations.filter(d=>d.ruleId==="CAPABILITY_VIOLATION"||d.ruleId==="FORBIDDEN_GLOBAL").map(d=>{let y=c.get(d.evidence.file)?.layer;return{ruleId:d.ruleId,file:d.evidence.file,line:d.evidence.line,target:d.symbol,...d.capability?{capability:d.capability}:{},...y?{fromLayer:y}:{},edgeKind:"import",message:d.message}}),u=Ye({config:e.contract.config,rules:e.contract.config.rules,files:a.ir.files.map(d=>d.path),contentViolations:l,edges:a.ir.edges.filter(d=>!!d.fromLayer).map(d=>({from:d.from,fromLayer:d.fromLayer,...d.to?{to:d.to}:{},...d.toLayer?{toLayer:d.toLayer}:{},line:d.evidence.line,kind:"import",...d.typeOnly?{typeOnly:!0}:{},...d.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),p=r.map(d=>{let y=Me(d.path),b=n.get(y),x=c.get(y);return{path:y,operation:"delete"in d&&d.delete?"delete":b?"update":"create",...b?{beforeContentHash:b.contentHash}:{},...x?{candidateContentHash:x.contentHash}:{}}}).sort((d,y)=>d.path.localeCompare(y.path)),g=[...s,...u.violations].map(d=>({...d,nextAction:ye(d)})),f=g.filter(d=>d.failsStrict!==!1),m=e.changeMap?qe({changeMap:e.changeMap,changes:p,baseDependencies:t.ir.edges.flatMap(d=>d.to?[{from:d.from,to:d.to}]:[]),candidateDependencies:a.ir.edges.flatMap(d=>d.to?[{from:d.from,to:d.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&a.valid&&f.length===0&&(m?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:a.ir.compilerOptionsHash,baseTreeHash:Yo(t.ir.files),candidateTreeHash:Yo(a.ir.files),baseCompleteness:t.completeness,candidateCompleteness:a.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:a.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...m?{convergence:m}:{},changes:p,violations:g,warnings:u.warnings}}i(Jo,"preflightChange");function cd(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let o of t.split("/"))if(!(!o||o==="."))if(o===".."){if(n.length===0)return;n.pop()}else n.push(o);let r=n.join("/");return r&&r===t?r:void 0}i(cd,"canonicalChangePath");function dd(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,o])=>r!==o).map(([r,o,s])=>({ruleId:"FACTS_IDENTITY_MISMATCH",file:"<change-set>",line:1,field:r,before:o,candidate:s,message:`Base and candidate facts must use the same ${r}.`}))}i(dd,"identityViolations");function ud(e,t,n,r){let o=n.get(t),s=r.get(t);return{path:t,operation:"delete"in e&&e.delete?"delete":o?"update":"create",...o?{beforeContentHash:o.contentHash}:{},...s?{candidateContentHash:s.contentHash}:{}}}i(ud,"preparedChange");function Xo(e){let t=_e(e.baseFacts),n=_e(e.candidateFacts),r=vt({contract:e.contract,facts:t}),o=vt({contract:e.contract,facts:n}),s=new Map(t.files.map(m=>[m.path,m])),a=new Map(n.files.map(m=>[m.path,m])),c=dd(t,n),l=new Map,u=[];for(let m of e.changes){let d=cd(m.path);if(!d){c.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(l.has(d)){c.push({ruleId:"DUPLICATE_CHANGE_PATH",file:d,line:1,message:`The atomic change set contains more than one operation for ${d}.`});continue}l.set(d,m);let y=s.get(d),b=a.get(d);if("delete"in m&&m.delete)y||c.push({ruleId:"DELETE_TARGET_MISSING",file:d,line:1,message:`Cannot delete ${d} because it is not present in the supplied base facts.`}),b&&c.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:d,line:1,message:`Candidate facts still contain deleted file ${d}.`});else{let x="content"in m?m.content:"",S=Z(x);b?b.contentHash!==S&&c.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:d,line:1,expectedContentHash:S,candidateContentHash:b.contentHash,message:`Candidate facts for ${d} do not match the declared content.`}):c.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:d,line:1,message:`Candidate facts do not contain changed file ${d}.`})}u.push(ud(m,d,s,a))}e.changes.length===0&&c.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});for(let m of new Set([...s.keys(),...a.keys()])){if(l.has(m))continue;let d=s.get(m),y=a.get(m);d&&y&&K(d)===K(y)||c.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:m,line:1,message:`Candidate facts change ${m}, but the atomic change set does not declare it.`})}let p=e.changeMap?qe({changeMap:e.changeMap,changes:u,baseDependencies:r.ir.edges.flatMap(m=>m.to?[{from:m.from,to:m.to}]:[]),candidateDependencies:o.ir.edges.flatMap(m=>m.to?[{from:m.from,to:m.to}]:[])}):void 0,g=[...c,...o.ir.violations].map(m=>({...m,nextAction:ye(m)})),f=g.filter(m=>m.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&o.strictValid&&f.length===0&&(p?.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:o.completeness,baseCompletenessReasons:r.completenessReasons,candidateCompletenessReasons:o.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...p?{convergence:p}:{},changes:u.sort((m,d)=>m.path<d.path?-1:m.path>d.path?1:0),violations:g,warnings:o.ir.warnings}}i(Xo,"preflightResolvedChange");var Zo="1.0",pd=12,fd="Layers stop a bad import. ArkRun is an optional experimental runtime \u2014 in-memory, not Postgres. Data is gone on restart.",md="Next: /ark-runtime to wire one candidate.";function Qo(e){return e==="enforced"||e==="advisory"?e:null}i(Qo,"closedMode");function gd(e){let t=new Set;if(!Array.isArray(e))return[];for(let n of e){let r=n?.ruleId;typeof r!="string"||!Ir(r)||t.has(r)||t.add(r)}return[...t].sort((n,r)=>n<r?-1:n>r?1:0)}i(gd,"uniqueArkRunRuleIds");function yd(e){return!e||typeof e!="object"?{present:!1,mode:null,roots:0,layers:0,requireDeclarations:null}:{present:!0,mode:Qo(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(yd,"extraFromConfig");function hd(e={}){let t=yd(e.arkRun),n=t.present?gd(e.findings):[],r=n.slice(0,pd),o=n.length,s=sn({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:o}}),a=t.present&&t.mode==="enforced"&&Ae(e.classification),c;return t.present?t.mode==="advisory"?c="Advisory ArkRun residual only \u2014 never flips valid or --strict-merge. Residual is a finding-id count, never a score.":a?c="Enforced ArkRun is on the extra merge plane. Residual is a finding-id count, never a score.":c="Enforced ArkRun extra teeth stay demoted until the layer plane is honestly classified. Residual is a finding-id count, never a score.":c="Absence of arkRun is silent \u2014 Layers and ArkRules verdicts unchanged. Not a score.",{schemaVersion:Zo,notAScore:!0,active:t.present,mode:t.mode,compositionRoots:t.roots,managedLayers:t.layers,requireDeclarations:t.requireDeclarations,residual:{count:o,ruleIds:r},extraMergeTeeth:a,failMergeWhen:s.failMergeWhen,note:c,mergePlanes:s}}i(hd,"summarizeArkRunSection");function Pr(e={}){let t=e.present===!0,n=Qo(e.mode),r=e.residual,o=null;return typeof r=="number"&&Number.isFinite(r)&&r>=0&&(o=Math.floor(r)),t||(o=o??0),{notAScore:!0,present:t,mode:t?n:null,extraMergeTeeth:t&&n==="enforced"&&e.extraMergeTeeth===!0,residual:o}}i(Pr,"projectStatusArkRun");function Ad(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=[fd,`mode: ${t} \xB7 extra merge teeth ${n} \xB7 not a score`];if(e.residual.count>0){let o=e.residual.ruleIds.join(", "),s=e.residual.count>e.residual.ruleIds.length?` (+${e.residual.count-e.residual.ruleIds.length} more)`:"";r.push(`Residual: ${o}${s}`),r.push(md)}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(Ad,"formatArkRunDoctorLines");function cn(e,t){return e.slice(0,t).split(`
20
- `).length}i(cn,"lineOf");function ea(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}i(ea,"normalizeInventoryPath");function na(e,t){return e.some(n=>{let r=n.trim().replace(/\.+$/,"");return t.some(o=>r===o||r.startsWith(`${o}.`))})}i(na,"ownsIntent");function ta(e,t=[]){return/domain|entity|aggregate|model/i.test(e)||na(t,["Domain"])}i(ta,"isDomainLayer");function Rd(e,t=[]){return/application|orchestration|presentation|adapter|framework|interface|delivery|transport|inbound|controller/i.test(e)||na(t,["Application","Orchestration","Presentation","Adapter","Interface","Delivery","Transport"])}i(Rd,"isControllerEligibleLayer");function kd(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(kd,"isNonPilotSurface");function Sd(e){let t=[],n=0,r=new Map(Object.entries(e.fileLayers??{}).map(([l,u])=>[ea(l),u])),o=new Map((e.layerContexts??[]).map(l=>[l.name,l.intentPrefixes??[]])),s=(e.layerContexts??[]).find(l=>ta(l.name,l.intentPrefixes))?.name??"DomainModel";for(let[l,u]of Object.entries(e.fileContents).sort(([p],[g])=>p.localeCompare(g))){let p=ea(l);if(kd(p)||/GENERATED FILE\s+[—-]\s+do not edit by hand/i.test(u.slice(0,320)))continue;let g=r.has(p),f=r.get(p),m=f?o.get(f)??[]:[],d=/(?:^|\/)(?:components|ui|layouts|styles|hooks|theme|tokens|i18n|locales?)(?:\/|$)/i.test(p)||/(?:^|\/)(?:src\/)?(?:app|pages)\/.+\.(?:tsx|jsx)$/i.test(p)&&/(?:page|layout|loading|error|template|default)\.(?:tsx|jsx)$/i.test(p),y=/(?:^|\/)(?:app|pages)(?:\/[^/]+)*\/api(?:\/|$)/i.test(p),b=/(?:^|\/)actions?(?:\/|\.|$)/i.test(p)||/['"]use server['"]/.test(u),x=/controller|handler|resolver/i.test(l)||y||b||/route\.(?:ts|js|tsx|jsx)$/i.test(p)&&!d||/@(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),S=g?!!(f&&Rd(f,m)&&x):x,E=g?!!(f&&ta(f,m)):/domain|entity|aggregate|model/i.test(l),C=!g||E||S;if(S&&!d){let N=/\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=N.exec(u))!==null;)n+=1,t.push({id:`inv-val-${n}`,kind:"validation-in-controller",file:l,line:cn(u,H.index),message:"Business validation appears in a controller/handler \u2014 extract an invariant or Domain rule.",confidence:"direct-evidence",governedLayer:f,suggestedArkRule:{layer:s,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,P=i(N=>/^(?: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(N)||/^(?: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(N)||/_(?:ROUTE|PATH|LABEL|TITLE|COLOR|THEME|CLASS|STYLE|ICON|ARIA|MSG|COPY|TIMEOUT|PORT|VERSION|RETRY|DELAY|INTERVAL|TTL|CACHE)$/i.test(N)||/_(?:TIMEOUT(?:_MS)?|MS|BYTES|BUCKET|STORAGE_KEY|WINDOW_MS)$/i.test(N)||/^(?: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(N)||/^(?:FAVORITES_STORAGE|LISTINGS_CACHE|DOCS_PATH|METRICS_INTERVAL)/i.test(N)||/^(?:DEV|DEMO|SEED|FIXTURE)_[A-Z0-9_]+$/i.test(N)||/^(?:PG|POSTGRES|OID)_[A-Z0-9_]+$/i.test(N)||/_(?:OID|OIDS)$/i.test(N)||/^(?:INT2|INT4|INT8|FLOAT4|FLOAT8|NUMERIC|DATE|TIME|TIMESTAMP|TIMESTAMPTZ|JSON|JSONB|UUID)OID$/i.test(N)||/(?:^|_)(?:SCHEMA|PROTOCOL|RESOLVER|FORMAT)_(?:URL|URI|VERSION|ID|IDENTITY)$/i.test(N),"isInfraMagicName"),ge=i((N,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(N)||/_(?:MSG|MESSAGE|TEXT|COPY|TOAST|SNACK|ALERT|BANNER|CAPTION|HINT|HELP_TEXT|ERROR_TEXT|EMPTY_TEXT|PLACEHOLDER_TEXT|USER_MESSAGE|FEEDBACK)$/i.test(N))return!0;let L=H.replace(/^['"]|['"]$/g,"");return!!(/^['"]/.test(H)&&(/\s/.test(L)||/[.!?…]$/.test(L))&&!/^(?:STATUS|STATE|PHASE|ROLE|TYPE|KIND|ORDER|PAYMENT|CART|INVOICE|POLICY)_[A-Z0-9_]+$/i.test(N))},"isUxMessageConstant");for(;(k=D.exec(u))!==null;){let N=k[2],H=k[3]??"";!C||P(N)||ge(N,H)||d&&!E||/(?:^|\/)(?:integrations?|repos?|clients?|infra(?:structure)?|adapters?)(?:\/|$)/i.test(p)&&!E||(n+=1,t.push({id:`inv-magic-${n}`,kind:"magic-business-constant",file:l,line:cn(u,k.index),message:`Magic business constant ${N} may belong in a Domain policy or invariant catalog.`,confidence:"heuristic",governedLayer:f,suggestedArkRule:{layer:s,invariantId:`INV-${N}`},neverMechanicalSafe:!0}))}if(E){let N=/export\s+class\s+([A-Za-z_][A-Za-z0-9_]*)\s*\{([^}]{0,800})\}/g,H;for(;(H=N.exec(u))!==null;){let L=H[2]??"",j=(L.match(/\b[a-zA-Z_][a-zA-Z0-9_]*\s*\(/g)??[]).length;(L.match(/:\s*[A-Za-z]/g)??[]).length>=2&&j<=1&&(n+=1,t.push({id:`inv-anemic-${n}`,kind:"anemic-entity",file:l,line:cn(u,H.index),message:`Class ${H[1]} looks anemic (data-heavy, few behaviors).`,confidence:"heuristic",governedLayer:f,suggestedArkRule:{layer:s,structureId:"no-anemic-model",sensor:"no-anemic-model"},neverMechanicalSafe:!0}))}}if(E&&!(/\.error\.(?:ts|js|tsx|jsx)$/i.test(p)||/(?:^|\/)[^/]*(?:-access)?\.error\./i.test(p)||/(?:^|\/)errors?(?:\/|$)/i.test(p))){let H=/\bthis\.[A-Za-z_][A-Za-z0-9_]*\s*=(?!=)/g,L;for(;(L=H.exec(u))!==null;){let j=u.lastIndexOf("class ",L.index),G=j>=0?u.indexOf("{",j):-1,pe=j>=0&&G>=j&&G<L.index?u.slice(j,G):"";if(/\bextends\s+(?:Error|[A-Za-z_$][A-Za-z0-9_$]*Error)\b/.test(pe)||yr(u,L.index))continue;let Re=u.slice(Math.max(0,L.index-200),L.index+200);if(!fr.test(Re)&&!mr.test(Re)){n+=1,t.push({id:`inv-mut-${n}`,kind:"mutation-without-guard",file:l,line:cn(u,L.index),message:`Domain field mutation without nearby ${gr()}.`,confidence:"heuristic",governedLayer:f,suggestedArkRule:{layer:s,structureId:"events-on-mutation",sensor:"domain-event-on-mutation"},neverMechanicalSafe:!0});break}}}}let a=new Set(e.contractedRuleIds??[]);t.sort((l,u)=>+(u.confidence==="direct-evidence")-+(l.confidence==="direct-evidence")||l.file.localeCompare(u.file)||l.line-u.line||l.kind.localeCompare(u.kind)||l.id.localeCompare(u.id));let c=t.filter(l=>l.suggestedArkRule?.invariantId&&a.has(l.suggestedArkRule.invariantId)||l.suggestedArkRule?.structureId&&a.has(l.suggestedArkRule.structureId)).length;return{candidates:t,inventoried:t.length,underContract:c,frozen:(e.frozenKeys??[]).length,notAScore:!0}}i(Sd,"buildRulesInventory");function Id(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(Id,"inventoryToExtractionCard");var Ed="1.1";var bd="1.0";var Lr="docs/diagnostics.md",vd="1.0";function I(e,t,n,r,o,s){return{ruleId:e,title:n,why:r,fix:o,docsAnchor:e,category:t,...s?.oftenAdvisory?{oftenAdvisory:!0}:{}}}i(I,"entry");var dn=Object.freeze([I("LAYER_IMPORT_VIOLATION","layer","This import is not allowed","This file imported a folder it may not reach. The write doesn\u2019t land. The same check fails the pull request.","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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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}),I("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."),I("INVARIANT_CATALOG_EMPTY","arkrules","Domain invariant catalog is empty","ArkRules is on and a Domain-role layer has code, but invariants[] has no phrases the code must preserve. Empty looks like \u201Cdone\u201D until someone fills the catalog.","Add 1\u20132 short phrases to invariants[] in arkrules/<Domain>.json (or the mapped file). Starters show the shape. Advisory unless a domain structure rule is already enforced \u2014 then --strict-merge can refuse. Do not freeze this finding.",{oftenAdvisory:!0}),I("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."),I("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}),I("INVARIANT_TESTS_PATH_MISSING","arkrules","Domain-invariant tests path missing under adopted","The project is adopted (required CI or explicit advisory) and has domain invariants that want test evidence, but ark.config.json does not name where those tests live. Green coverage without a real tests path is an empty checkbox.","Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present. Not freezable."),I("INVARIANT_COVERAGE_ROOTS_MISSING","arkrules","Coverage roots missing while an invariant is enforced","A catalogued domain invariant is enforced, but ark.config.json does not name coverage.coverageRoots \u2014 the folders where the project says its test runner actually goes. Without that declaration, INVARIANT_COVERAGE_OUTSIDE_ROOTS cannot fire and coverage can certify a test no runner runs.","Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. testGlobs alone is not enough. Fail-closed until that path is present. Not freezable."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("ARKORDER_GENERIC_UPDATE","arkorder","Generic update of a big product choice","A call to update/patch/set rewrites a named product choice (like billing plan) as if it were a seat count.","Don't use a generic update. First freeze with release(). Later, propose the change, then apply it."),I("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."),I("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."),I("ARKORDER_XI_FIELD_WRITE","arkorder","Big product choice written like a seat count","A use-case writes a named product choice (like billing plan) through a database update. Invoices and seats can flow. That choice cannot.","Keep invoices and seats as events. Change the choice through the valve (proposeRelease then apply), not a generic update."),I("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."),I("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."),I("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."),I("ARKORDER_UNVALVED_RELEASE","arkorder","Second freeze without the valve","release() already froze the big choice. A later release() with a different value does not land. First freeze is release(); later change is proposeRelease then apply.","Change the choice with proposeRelease then apply. release() is only the first freeze. Never mechanical-safe."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("LEXICAL_EVIDENCE_INCOMPLETE","analysis","Lexical evidence incomplete","This check only saw one file, so it cannot fully prove how the import resolves. The result is provisional \u2014 `ark-check` on the project is the authority.","Run `npx arkgate-check --root . --config ark.config.json` to confirm. Do not call ark_prepare_change from a hook deny."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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}),I("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}),I("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}),I("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}),I("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}),I("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}),I("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}),I("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}),I("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}),I("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}),I("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}),I("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}),I("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}),I("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}),I("CONFIG_LAYER_MISSING_OWNER","config","Layer missing owner","requireLayerOwners is on and this layer has no owners. Writes to that house fail closed, like a folder with no name on the door.","Add a GitHub handle or email to that layer\u2019s owners in ark.config.json (/ark-adopt), then re-run. Reserved/allowEmpty houses may stay unnamed. Turn the flag off only if you no longer want owners required."),I("CONFIG_SLICE_IDENTITY_COLLISION","config","Starred slice prefixes share one id","sliceIdentity is stars and two different sliceFolders prefixes bind as the same slice id. Parallel trees of one feature do that on purpose; unrelated trees that share the last folder name merge by accident.","Keep stars when those prefixes are one feature. Otherwise use path, or rename the last literal so the prefixes do not bind as the same id. Doctor names both paths.",{oftenAdvisory:!0}),I("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."),I("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}),I("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.")]),Dr=new Map(dn.map(e=>[e.ruleId,e])),Cd=Object.freeze(dn.map(e=>e.ruleId));function _d(e){return typeof e=="string"&&e.length>0&&Dr.has(e)}i(_d,"isKnownDiagnosticCode");function Od(e){return typeof e!="string"||e.length===0?!1:Dr.has(e)?!0:e.startsWith("ARKRULE_")}i(Od,"isCataloguedOrArkRuleFamily");function un(e){if(!(typeof e!="string"||e.length===0))return Dr.get(e)}i(un,"getDiagnosticCatalogEntry");function ra(e){return`#${un(e)?.docsAnchor??e}`}i(ra,"diagnosticDocsFragment");function xd(e){return`${Lr}${ra(e)}`}i(xd,"diagnosticDocsPath");function Td(){return{schemaVersion:"1.0",docsPath:Lr,codes:dn}}i(Td,"serializeDiagnosticCatalog");function Nd(e){return un(e)?.fix}i(Nd,"catalogFixForRuleId");function wd(e){return un(e)?.why}i(wd,"catalogWhyForRuleId");function Pd(e){return e==="enforced"||e==="advisory"?e:null}i(Pd,"closedMode");function sa(e={}){let t=e.present===!0,n=Pd(e.mode),r=e.residual,o=null;return typeof r=="number"&&Number.isFinite(r)&&r>=0&&(o=Math.floor(r)),t||(o=o??0),{notAScore:!0,present:t,mode:t?n:null,extraMergeTeeth:t&&n==="enforced"&&e.extraMergeTeeth===!0,residual:o}}i(sa,"projectStatusArkOrder");var Mr="1.0",oa="https://unpkg.com/arkgate@4/schemas/ark.status-manifest.schema.json",aa=["full","subset","unavailable"],ia=["doctor-facts","report-snapshot","none"],pn={FACTS_UNAVAILABLE:"FACTS_UNAVAILABLE",FACTS_PARTIAL:"FACTS_PARTIAL",NO_SESSION_SNAPSHOT:"NO_SESSION_SNAPSHOT"},la=/^sha256:[a-f0-9]{64}$/;function ca(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"||!la.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 o=e.expectedRootRelation??"unknown";return o==="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}.`}:o==="unknown"?{status:"unverified",authoritative:!1,expectedRoot:n,expectedProjectId:r,message:"Could not prove expectedRoot against the resolved project root (stale or incomplete path evidence)."}:o==="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}.`}:o==="exact"||o==="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(ca,"evaluateStatusBinding");function da(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(da,"classifyStatusWritePath");function ua(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(ua,"defaultHonestLabel");function pa(e,t,n,r,o){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."}:o.arkRulesLoaded&&(o.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.arkOrder?.present===!0&&(e.arkOrder.residual??0)>0?{id:"review-arkorder-residual",summary:"ArkOrder leftover remains \u2014 change that product choice through the valve (proposeRelease then apply), not a generic update. 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(pa,"resolveStatusNextAction");function Ld(e){let t=typeof e.resolvedRoot=="string"&&e.resolvedRoot.length>0?e.resolvedRoot:".",n=typeof e.projectId=="string"&&la.test(e.projectId)?e.projectId:null,r=ca({resolvedRoot:t,projectId:n,expectation:e.expectation,expectedRootRelation:e.expectedRootRelation}),o=typeof e.activeHost=="string"?e.activeHost.trim().toLowerCase():"",s=o&&o!=="unknown"?o:o==="unknown"?"unknown":null,a=da({hardWriteActive:e.hardWriteActive,softWriteHost:e.softWriteHost,writePathUnavailable:e.writePathUnavailable,activeHost:s}),c=typeof e.honestLabel=="string"&&e.honestLabel.trim().length>0?e.honestLabel.trim():ua(a,s),l={at:typeof e.lastCheckAt=="string"?e.lastCheckAt:null,verdict:e.lastCheckVerdict==="pass"||e.lastCheckVerdict==="fail"||e.lastCheckVerdict==="incomplete"?e.lastCheckVerdict:null,activeViolations:Ct(e.activeViolations),frozenResidual:Ct(e.frozenResidual)},u={arkRulesLoaded:e.arkRulesLoaded===!0,inventoried:Ct(e.rulesInventoried),underContract:Ct(e.rulesUnderContract),frozenResidual:Ct(e.rulesFrozenResidual)},p={writePath:a,host:s,honestLabel:c},g={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}:{}},f={schemaVersion:Mr,arkgateVersion:typeof e.arkgateVersion=="string"&&e.arkgateVersion.length>0?e.arkgateVersion:"unknown",projectIdentity:g,activation:p,lastCheck:l,rules:u,nextAction:pa(e,r,p,l,u)},m=ma(e.improvementCompass);return m&&(f.improvementCompass=m),e.vsBase&&typeof e.vsBase.baseRef=="string"&&e.vsBase.baseRef.length>0&&(f.vsBase=e.vsBase),e.arkRun&&typeof e.arkRun=="object"&&(f.arkRun=Pr(e.arkRun)),e.arkOrder&&typeof e.arkOrder=="object"&&(f.arkOrder=sa(e.arkOrder)),f}i(Ld,"buildStatusManifest");var fa=new Set(aa),Dd=new Set(ia);function Fr(e){let t=fa.has(e.mode)?e.mode:"unavailable",n=e.factsSource!=null&&Dd.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:pn.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 o=Array.isArray(e.topResidual)?e.topResidual.filter(a=>typeof a=="string"&&a.length>0).slice(0,15):[],s={schemaVersion:"1.0",notAScore:!0,mode:t,topResidual:o};return t==="subset"?(s.reasonCode=typeof e.reasonCode=="string"&&e.reasonCode.length>0?e.reasonCode:pn.FACTS_PARTIAL,s.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&&(s.reasonCode=e.reasonCode),typeof e.reason=="string"&&e.reason.length>0&&t==="full"&&(s.reason=e.reason),n&&(s.factsSource=n),r&&(s.contractHash=r),s}i(Fr,"projectStatusImprovementCompass");function Md(e={}){return Fr({mode:"unavailable",topResidual:[],reasonCode:e.reasonCode??pn.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(Md,"unavailableStatusImprovementCompass");function ma(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"&&fa.has(t.mode)?n=t.mode:Array.isArray(t.topResidual)?n="subset":n="unavailable",Fr({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(ma,"normalizeStatusImprovementCompass");function Fd(e,t){let n=Array.isArray(e)?e:[],r=new Set(Array.isArray(t)?t:[]);for(let o of n)if(!(typeof o!="string"||o.length===0)&&!r.has(o))return!1;return!0}i(Fd,"statusCompassResidualIsSubsetOfDoctor");function Ct(e){if(e==null)return null;let t=Number(e);return!Number.isFinite(t)||t<0?null:Math.floor(t)}i(Ct,"numberOrNull");var $d={$schema:"https://json-schema.org/draft/2020-12/schema",$id:oa,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:Mr},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"}]}}},arkOrder:{type:"object",description:"ArkOrder 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 fn="1.0",mn=["soc","cohesion","coupling","srp","dip","ocp","encapsulation","modularity","scalability","resilience","security","maintainability","testability","domain","stack"],gn=5,Fe=["scalability","resilience","security"],Xe=new Set(Fe),$r={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},Hr={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"},jr={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 Hr[e]??e}i(Kr,"improvementCompassHumanLabel");function Vr(e){let t=e.id??e.smellId??"";return typeof t=="string"?t.trim():""}i(Vr,"smellIdOf");function Ur(e){let t=e.ruleId??e.code??"";return typeof t=="string"?t.trim():""}i(Ur,"violationRuleId");function U(e,t,n,r){if(!n||e.evidence.some(s=>s.source===t&&s.ref===n))return;let o={source:t,ref:n};r&&r.trim()&&(o.detail=r.trim().slice(0,240)),e.evidence.push(o)}i(U,"pushEvidence");function re(e,t,n){Xe.has(e.id)||(e.status="residual",e.summary=t,n&&(e.nextAction=n))}i(re,"markResidual");function ga(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`${Hr[e]} \u2014 no residual from current sensors.`}}i(ga,"defaultOkSummary");function ya(){return mn.map(e=>Xe.has(e)?{id:e,status:"out-of-scope",summary:jr[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:ga(e),evidence:[]}:{id:e,status:"ok",summary:ga(e),evidence:[]})}i(ya,"createInitialImprovementCompassLenses");function Hd(e,t){for(let n of t){let r=Vr(n);if(!r)continue;let o=n.outcome||n.message||void 0,a=(Array.isArray(n.evidence)?n.evidence:[])[0],c=i((p,g,f)=>{let m=e.get(p);!m||Xe.has(p)||(U(m,"designSmells",r,o),a&&U(m,"designSmells",a,r),re(m,g,f))},"attach"),l={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":c("soc","Business rules still mix with UI or presentation surfaces.",l),c("domain","Domain logic lives outside Domain \u2014 align rules with Domain ownership.",l);break;case"facade-sql-in-routes":c("soc","Routes/controllers own SQL or ORM access \u2014 concerns are mixed.",l),c("dip","Transport depends on concrete persistence instead of a port.",u);break;case"io-under-application":c("soc","Application/business code reaches I/O directly \u2014 separation is weak.",l),c("dip","I/O is not inverted behind ports/adapters.",u),c("testability","Direct I/O under application code hurts pure unit testing.",u);break;case"handler-in-persistence":c("soc","HTTP/transport handlers live under persistence folders.",l);break;case"god-module":c("cohesion","Large multi-responsibility modules reduce cohesion.",l),c("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":c("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."}),c("cohesion","Mixed layout styles scatter the same concern across patterns.",l);break;case"soft-contract":c("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."}),c("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:c("maintainability","Design residual remains under an unrecognized smell id \u2014 review evidence.",l);break}}}i(Hd,"mapDesignSmells");function jd(e){return e.failsStrict===!1||e.typeOnly===!0}i(jd,"isTypeOnlyPlacementDebt");function Kd(e,t){for(let n of t){let r=Ur(n);if(!r)continue;let o=n.message,s=r.toUpperCase(),a=i((l,u,p)=>{let g=e.get(l);!g||Xe.has(l)||(U(g,"violations",r,o),n.file&&U(g,"violations",n.file,r),re(g,u,p))},"attach");if(jd(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 c={kind:"skill",ref:"/ark-autopilot",summary:"Clear the active edge residual, then re-doctor."};if(s==="LAYER_IMPORT_VIOLATION"||s.includes("LAYER_IMPORT")||s==="DYNAMIC_IMPORT_VIOLATION"){a("coupling","Import graph edges violate the layer contract.",c);continue}if(s.includes("CYCLE")||s==="CIRCULAR_DEPENDENCY"){a("coupling","Import cycles couple modules tightly.",c);continue}if(s.includes("PEER_ISOLATION")||s==="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(s==="FORBIDDEN_GLOBAL"||s.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(s==="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(s.startsWith("ARKRULE_")||s==="INVARIANT_UNCOVERED"||s==="INVARIANT_CATALOG_EMPTY"||s==="INVARIANT_TESTS_PATH_MISSING"||s==="INVARIANT_COVERAGE_ROOTS_MISSING"){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(Kd,"mapViolations");function Vd(e,t){let n=Number(t.cycleCount)||0;if(n>0){let m=e.get("coupling");U(m,"cycles",`count:${n}`),re(m,"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 m=e.get("coupling");U(m,"peerIsolation",`count:${r}`),re(m,"Peer isolation residual remains.",{kind:"skill",ref:"/ark-autopilot",summary:"Peer isolation is judgment-class residual."})}let o=Number(t.physicalCohesionFindingCount)||0;if(o>0){let m=e.get("cohesion");U(m,"physicalCohesion",`findings:${o}`),re(m,"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 d=e.get("srp");U(d,"physicalCohesion",`findings:${o}`),re(d,"Mirrored clusters suggest split-by-concern residual (architecture SRP).",{kind:"skill",ref:"/ark-autopilot",summary:"One reshape/extraction pilot this turn."})}let s=Number(t.pureOrCapabilityResidual)||0,a=Number(t.forbiddenGlobalResidual)||0;if(s>0||a>0){let m=e.get("dip");s>0&&U(m,"capability",`residual:${s}`),a>0&&U(m,"forbiddenGlobals",`residual:${a}`),re(m,"Pure / capability / forbidden residual weakens dependency inversion.",{kind:"skill",ref:"/ark-autopilot",summary:"Inject ports; keep pure layers free of effects."});let d=e.get("testability");s>0&&U(d,"capability",`residual:${s}`),a>0&&U(d,"forbiddenGlobals",`residual:${a}`),re(d,"Impure domain or capability residual reduces testability.",{kind:"skill",ref:"/ark-autopilot",summary:"Prefer ports over concrete I/O in pure/domain modules."})}let c=Number(t.arkRulesStructureResidual)||0;if(c>0){let m=e.get("encapsulation");U(m,"arkRules",`structureResidual:${c}`),re(m,"ArkRules structure residual \u2014 encapsulation inside the layer.",{kind:"skill",ref:"/ark-autopilot",summary:"Fix structure sensors under [ArkRules] without inventing mechanical-safe."});let d=e.get("domain");U(d,"arkRules",`structureResidual:${c}`),re(d,"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 m=e.get("maintainability");U(m,"designFitness","design-weak"),re(m,"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 m=e.get("maintainability");t.dirtyBaselineRisk===!0&&U(m,"baseline","dirty-freeze-risk"),(Number(t.baselineStale)||0)>0&&U(m,"baseline",`stale:${t.baselineStale}`),re(m,"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 l=Number(t.frozenResidual)||0;if(t.baselineExists===!0&&l>=10&&e.get("maintainability").status!=="residual"){let m=e.get("maintainability");U(m,"baseline",`frozen:${l}`),re(m,"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,p=Number(t.emptyLayerCount)||0;if(u>0||p>0){let m=e.get("modularity");u>0&&U(m,"coverage",`ungovernedDirs:${u}`),p>0&&U(m,"coverage",`emptyLayers:${p}`),re(m,"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 m=e.get("modularity");U(m,"goldenPattern","absent"),re(m,"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 g=e.get("stack");(t.stackKind??null)==="typescript"?g.status==="ok"&&(g.summary="Stack practices are partially instrumented for TypeScript / host / Ark idioms only \u2014 not a full framework checklist."):(g.status="not-instrumented",g.summary="Stack-specific best practices outside TypeScript/host/Ark idioms are not instrumented.",g.evidence=[],g.nextAction={kind:"docs",ref:"docs/use.md#improvement-compass",summary:"Ark does not score non-TS stack idioms."})}i(Vd,"mapCountsAndFlags");function ha(e,t){if(Array.isArray(t.designSmells)&&t.designSmells.length>0){let n=[...t.designSmells].sort((r,o)=>Vr(r).localeCompare(Vr(o)));Hd(e,n)}if(Array.isArray(t.violations)&&t.violations.length>0){let n=[...t.violations].sort((r,o)=>{let s=Ur(r).localeCompare(Ur(o));return s!==0?s:String(r.file??"").localeCompare(String(o.file??""))});Kd(e,n)}Vd(e,t)}i(ha,"projectImprovementCompassFacts");function Aa(e){for(let t of Fe){let n=e.get(t);n.status="out-of-scope",n.summary=jr[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(Aa,"lockImprovementCompassOutOfScope");function Ra(e){for(let t of e)t.evidence.sort((n,r)=>{let o=n.source.localeCompare(r.source);return o!==0?o:n.ref.localeCompare(r.ref)})}i(Ra,"sortImprovementCompassEvidence");function ka(e){return e.filter(n=>n.status==="residual"&&!Xe.has(n.id)).slice().sort((n,r)=>{let o=$r[n.id]??150,s=$r[r.id]??150;return o!==s?o-s:n.id.localeCompare(r.id)}).slice(0,5).map(n=>n.id)}i(ka,"finalizeImprovementCompassTopResidual");function Ud(e={}){let t=ya(),n=new Map(t.map(o=>[o.id,o]));ha(n,e),Aa(n),Ra(t);let r=ka(t);return{schemaVersion:"1.0",notAScore:!0,lenses:t.map(o=>{let s={id:o.id,status:o.status,summary:o.summary,evidence:o.evidence.map(a=>({...a}))};return o.nextAction&&(s.nextAction={...o.nextAction}),s}),topResidual:r}}i(Ud,"buildImprovementCompass");function Sa(e){return e.topResidual.map(t=>Kr(t))}i(Sa,"formatImprovementCompassResidualLabels");function Ia(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(Ia,"primaryImprovementCompassNextAction");function Gd(e){let t=Sa(e),n=Fe.map(s=>Kr(s)),r=Ia(e),o=[];return t.length>0?o.push(`Residual: ${t.join(" \xB7 ")}`):o.push("Residual: none on instrumented lenses (not a score \u2014 green edges \u2260 finished design)."),o.push(`Out of scope (honest): ${n.join(" \xB7 ")}`),r&&o.push(`Next: ${r.ref} \u2014 ${r.summary}`),o}i(Gd,"formatImprovementCompassDoctorLines");var $e="1.0",Ea="<!-- arkgate:agent-projection:begin",yn="<!-- arkgate:agent-projection:end -->",hn="This projection is **non-authoritative**. Enforcement is `ark-check` / host write hooks / required CI (`--strict-merge`), not AGENTS.md, skills, or this block.",_t=Object.freeze(["ark-check","host-write-hooks","ci-strict-merge"]),ba=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"]);function Ze(e){let t=String(e??"").replace(/\r\n/g,`
21
- `),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(Ze,"agentProjectionContentIdentity");function Ot(e){return String(e??"").replace(/\r\n/g,`
22
- `)}i(Ot,"normalizeNewlines");function He(e){let t=Ot(e);return t.endsWith(`
14
+ `,t);return e.slice(n,r===-1?e.length:r)}a(Oc,"lineAt");function xc(e){let t=e.trim();return/^import\b/.test(t)||/^export\s+/.test(t)&&/\bfrom\b/.test(t)?!0:/\brequire\s*\(/.test(t)}a(xc,"isImportLine");function bo(e,t,n){if(!t||!e.includes(t))return;let r=new Set,o=0,s=e.length,i=a((l,c)=>{if(e.startsWith(t,l)){if(c==="comment"){r.add("comment");return}if(c==="string"){r.add("string");return}if(xc(Oc(e,l))){r.add("import");return}n&&r.add("test-body")}},"note");for(;o<s;){let l=e[o],c=e[o+1];if(l==="/"&&c==="/"){for(;o<s&&e[o]!==`
15
+ `;)i(o,"comment"),o+=1;continue}if(l==="/"&&c==="*"){for(i(o,"comment"),i(o+1,"comment"),o+=2;o<s&&!(e[o]==="*"&&e[o+1]==="/");)i(o,"comment"),o+=1;o<s&&(i(o,"comment"),i(o+1,"comment"),o+=2);continue}if(l==='"'||l==="'"||l==="`"){let u=l;for(i(o,"string"),o+=1;o<s;){let p=e[o];if(p==="\\"){i(o,"string"),e[o+1]!==void 0&&i(o+1,"string"),o+=e[o+1]===void 0?1:2;continue}if(p===u){i(o,"string"),o+=1;break}i(o,"string"),o+=1}continue}i(o,"code"),o+=1}if(r.has("comment"))return"comment";if(r.has("string"))return"string";if(r.has("test-body"))return"test-body";if(r.has("import"))return"import"}a(bo,"mentionContext");function _o(e){if(!e)return;let t=e.split("."),n=t[t.length-1]??"";return n?{className:t.length>1?t[0]??null:null,name:n}:void 0}a(_o,"symbolNeedle");function Tc(e){return _o(e.coverage?.symbol)?.name??e.id}a(Tc,"declaredLabel");function vo(e){return Object.keys(e).sort((t,n)=>t<n?-1:t>n?1:0)}a(vo,"sortedContentFiles");function Oo(e,t,n=!0){let r=t.testFiles??[],o=new Set(r.map(g=>nt(g))),s=(t.coverageRoots??[]).filter(g=>typeof g=="string"&&g.length>0),i=e.coverage?.test!==!1&&n,l=_o(e.coverage?.symbol??void 0),c,u;if(i){for(let g of r){let d=t.fileContents[g];if(!d)continue;let h=Cc(d,e.id);if(h!==void 0){if(s.length===0||Co(g,s)){c={file:g,title:h};break}u??={file:g,title:h}}}c??=u}let p;if(l)for(let g of vo(t.fileContents)){if(o.has(nt(g)))continue;let d=t.fileContents[g];if(!d||l.className&&!d.includes(l.className))continue;let h=_c(d,l.name);if(h){p={file:g,shape:h};break}}let m;if(!c&&!p){if(i)for(let g of r){let d=t.fileContents[g];if(!d)continue;let h=bo(d,e.id,!0);if(h){m={file:g,context:h};break}}if(!m&&l)for(let g of vo(t.fileContents)){if(o.has(nt(g)))continue;let d=t.fileContents[g];if(!d)continue;let h=bo(d,l.name,!1);if(h){m={file:g,context:h};break}}}let f=c?{kind:"test-title",file:c.file,title:c.title}:p?{kind:"declaration",file:p.file,shape:p.shape}:m?{kind:"mention-only",file:m.file,context:m.context}:{kind:"none"};return f.kind==="mention-only"&&f.context==="comment"&&l&&wc(t.fileContents,o,l.name,f.file)&&(f={kind:"declaration-miss",symbol:l.name}),{best:f,...c?{testTitle:c}:{},...p?{declaration:p}:{}}}a(Oo,"rankCoverage");function wc(e,t,n,r){let o=new RegExp(`(?:^|[^A-Za-z0-9_$])${mr(n)}(?=$|[^A-Za-z0-9_$])`),s=nt(r);for(let i of Object.keys(e)){if(t.has(nt(i))||nt(i)===s)continue;let l=e[i];if(l&&o.test(hr(l,!0)))return!0}return!1}a(wc,"symbolInCodeElsewhere");function Nc(e,t){return Oo(e,t).best}a(Nc,"classifyCoverage");function xo(e){switch(e.kind){case"test-title":case"declaration":return!0;case"mention-only":case"declaration-miss":case"none":return!1}}a(xo,"countsAsCoverage");function Lc(e){switch(e){case"test-body":return"a test body";case"comment":return"a comment";case"string":return"a string";case"import":return"an import"}}a(Lc,"mentionWhere");function To(e,t){switch(t.kind){case"test-title":return`found \`${t.title}\` in a describe/it title in ${t.file}`;case"declaration":return`found \`${t.shape} ${Tc(e)}\` in ${t.file}`;case"mention-only":return`${e.id} appears only in ${Lc(t.context)} in ${t.file}; put it in a describe/it title`;case"declaration-miss":return`no declaration matched \`${t.symbol}\``;case"none":return"no scanned test names it in a describe/it title and no declared symbol was found"}}a(To,"describeCoverage");function yr(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,o=e.coverageBudgetExhausted===!0,s=e.coverageStats,i=Eo(s),l=Eo(s,!0),c=s?`coverage file budget exhausted: ${s.filesLoaded} files loaded at the ${s.maxFiles}-file cap, ${s.testFilesRetained} tests retained, ${s.discarded.budget} files discarded at the cap; raise "coverage.maxFiles" in ark.config.json (the cap bounds files RETAINED as evidence${typeof s.filesRead=="number"?`; ${s.filesRead} were read`:""})`:"coverage file budget exhausted",u=(e.coverageRoots??[]).filter(d=>typeof d=="string"&&d.length>0),p=u.length>0,m=u.join(", "),f=[],g=[];for(let d of t){let h=d.coverage?.test!==!1,E=d.coverage?.symbol,_=!r&&h,k=Oo(d,{fileContents:e.fileContents,testFiles:n,coverageRoots:u},_),b=k.best,O=[];_&&k.testTitle&&O.push("test-title"),k.declaration&&O.push("symbol");let D=xo(b),S,L;_&&k.testTitle&&(S=k.testTitle.file,p&&(L=!Co(S,u)));let j=k.declaration?.file,T=k.declaration?.shape,P=(d.coverage?.test===!0||!!E||d.coverage===void 0)&&D||d.coverage?.test===!1&&!E?!0:D,V=r&&h&&!D;if(f.push({invariantId:d.id,layer:d.provenance.layer,sourceFile:d.provenance.sourceFile,mode:d.mode,covered:P&&!V,evidence:O,partial:V,description:d.description,...S!==void 0?{testEvidenceFile:S}:{},...j!==void 0?{symbolEvidenceFile:j}:{},...T!==void 0?{shape:T}:{},...L!==void 0?{outsideDeclaredRoots:L}:{},coverageRootsDeclared:p}),L===!0&&S!==void 0&&g.push({ruleId:"INVARIANT_COVERAGE_OUTSIDE_ROOTS",message:`Invariant ${d.id} is covered only by ${S}, which is outside the declared coverage roots (${m}). 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:S,line:1,arkruleId:d.id,arkruleSource:d.provenance.sourceFile,fromLayer:d.provenance.layer,severity:"warning",failsStrict:!1}),!P||V){let z=d.mode==="enforced"&&!V,fe=r||n.length===0?"never-had-tests":"tests-disappeared";g.push({ruleId:"INVARIANT_UNCOVERED",message:(V?o?`Invariant ${d.id} coverage cannot be proven (${c}); reporting partial, not covered.`:`Invariant ${d.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered (never-had-tests).`:`Invariant ${d.id}: ${To(d,b)} (${fe==="tests-disappeared"?"tests-disappeared \u2014 a suite exists":"never-had-tests \u2014 the scan found no tests at all"}). ArkGate matches declared text; it never executes tests.`)+(V&&o?l:i),file:d.provenance.sourceFile,line:1,arkruleId:d.id,arkruleSource:d.provenance.sourceFile,fromLayer:d.provenance.layer,severity:z?"error":"warning",failsStrict:z,kind:fe})}}return{coverage:f,violations:g,partial:f.some(d=>d.partial)}}a(yr,"evaluateInvariantCoverage");function Ar(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.`}:e.coverageRootsDeclared===!1?{ok:!1,reason:`Declare coverage.coverageRoots in ark.config.json before promoting ${e.invariantId} to enforced. Without that, ArkGate cannot tell whether a covering test is one the runner executes.`}:{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."}}a(Ar,"canPromoteInvariant");function gr(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!="string")continue;let r=n.trim();r.length>0&&t.push(r)}return t}a(gr,"nonEmptyPathStrings");function Pc(e){return!e||typeof e!="object"?[]:[...gr(e.testGlobs),...gr(e.coverageRoots)]}a(Pc,"configuredInvariantTestsPaths");function Dc(e){return Pc(e).length>0}a(Dc,"hasConfiguredInvariantTestsPath");function Rr(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.coverage?.test!==!1)}a(Rr,"catalogDemandsInvariantTestsPath");function wo(e){let t=e.hasDomainInvariants===!0||e.hasDomainInvariants!==!1&&Rr(e.invariants);return e.adopted!==!0||!t?[]:Dc(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:Ic,message:Ec,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]}a(wo,"collectMissingInvariantTestsPathFindings");function Mc(e){return!e||typeof e!="object"?[]:gr(e.coverageRoots)}a(Mc,"configuredCoverageRoots");function Fc(e){return Mc(e).length>0}a(Fc,"hasConfiguredCoverageRoots");function kr(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.mode==="enforced")}a(kr,"catalogHasEnforcedInvariant");function No(e){return e.hasEnforcedInvariant===!0||e.hasEnforcedInvariant!==!1&&kr(e.invariants)?Fc(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:bc,message:vc,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]:[]}a(No,"collectMissingCoverageRootsFindings");var vr="1.0",$c="add a short note under docs/adr/ (or docs/decisions/) and put that file path in --policy-ack as adrPath.";function C(e,t){let n=t.classification==="weakening"||t.classification==="judgment-required"?`Restore the previous protection at ${t.path}, or ${$c}`:void 0,r=t.nextAction??n;e.push({id:`${t.classification}:${t.path}:${t.kind}`,path:t.path,classification:t.classification,message:t.message,...r?{nextAction:r}:{},...t.before===void 0?{}:{before:t.before},...t.after===void 0?{}:{after:t.after}})}a(C,"addFinding");function G(e){return[...new Set(e??[])].sort()}a(G,"sortedUnique");function he(e,t,n,r,o){let s=G(n),i=G(r),l=new Set(s),c=new Set(i),u=i.filter(m=>!l.has(m)),p=s.filter(m=>!c.has(m));u.length===0&&p.length===0||(u.length>0&&C(e,{kind:"added",path:t,classification:o.added,message:o.addedMessage,before:s,after:i}),p.length>0&&C(e,{kind:"removed",path:t,classification:o.removed,message:o.removedMessage,before:s,after:i}))}a(he,"compareStringSets");function Tt(e,t,n,r,o,s,i){if(n===r)return;C(e,{kind:r?"enabled":"disabled",path:t,classification:r?o:o==="strengthening"?"weakening":"strengthening",message:r?s:i,before:n,after:r})}a(Tt,"compareBoolean");function dn(e,t){let n=new Map,r=new Set;for(let o of e){let s=t(o);n.has(s)?r.add(s):n.set(s,o)}return{values:n,duplicates:[...r].sort()}}a(dn,"keyed");function Hc(e,t,n){let r=dn(t,s=>s.name),o=dn(n,s=>s.name);(r.duplicates.length>0||o.duplicates.length>0)&&C(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:r.duplicates,after:o.duplicates});for(let s of[...new Set([...r.values.keys(),...o.values.keys()])].sort()){let i=r.values.get(s),l=o.values.get(s),c=`$.layers[${s}]`;if(!i&&l){C(e,{kind:"layer-added",path:c,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",nextAction:"Write a short note under docs/adr/ (or docs/decisions/) for this new layer and put that file path in --policy-ack as adrPath.",after:l});continue}if(i&&!l){C(e,{kind:"layer-removed",path:c,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:i});continue}if(!i||!l)continue;he(e,`${c}.patterns`,i.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."}),he(e,`${c}.exclude`,i.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=Jt(i),p=Jt(l);he(e,`${c}.forbiddenGlobals`,u.rawGlobals,p.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),he(e,`${c}.capabilities`,u.atoms,p.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)."}),G(i.intentPrefixes).join("\0")!==G(l.intentPrefixes).join("\0")&&C(e,{kind:"intent-prefixes-changed",path:`${c}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:G(i.intentPrefixes),after:G(l.intentPrefixes)}),Tt(e,`${c}.mayImportInfrastructure`,i.mayImportInfrastructure===!0,l.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),Tt(e,`${c}.optional`,i.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.")}}a(Hc,"compareLayers");function jc(e,t,n){let r=a(i=>`${i.from}->${i.to}`,"keyOf"),o=dn(t,r),s=dn(n,r);(o.duplicates.length>0||s.duplicates.length>0)&&C(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:o.duplicates,after:s.duplicates});for(let i of[...new Set([...o.values.keys(),...s.values.keys()])].sort()){let l=o.values.get(i),c=s.values.get(i),u=`$.rules[${i}]`;if(!l&&c){c.allowed===!1?C(e,{kind:"deny-added",path:u,classification:"strengthening",message:"A denied dependency edge was added.",after:c}):C(e,{kind:"allow-added",path:u,classification:"judgment-required",message:"A new import edge was added; confirm this house should import that one.",nextAction:"Write a short note under docs/adr/ (or docs/decisions/) for this new import edge and put that file path in --policy-ack as adrPath.",after:c});continue}if(l&&!c){l.allowed===!1&&C(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&&C(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 p=l.peerIsolation===!0,m=c.peerIsolation===!0;if(p!==m){let d=l.from===l.to&&c.from===c.to;C(e,{kind:m?"peer-isolation-enabled":"peer-isolation-disabled",path:`${u}.peerIsolation`,classification:d?m?"strengthening":"weakening":"judgment-required",message:d?m?"Cross-slice dependencies inside this layer are now denied.":"Cross-slice dependencies inside this layer are no longer denied.":"Changing peer isolation on a cross-layer edge changes the denial scope.",before:p,after:m})}G(l.sliceFolders).join("\0")!==G(c.sliceFolders).join("\0")&&C(e,{kind:"slice-folders-changed",path:`${u}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:G(l.sliceFolders),after:G(c.sliceFolders)});let f=l.sliceIdentity??"path",g=c.sliceIdentity??"path";if(f!==g&&C(e,{kind:"slice-identity-changed",path:`${u}.sliceIdentity`,classification:"judgment-required",message:"Slice identity changed and can reclassify existing slice ids. Baselines and allowedCrossSlice use those ids.",before:f,after:g}),!(!p&&!m)){if(br(e,`${u}.sharedRoots`,"shared-roots",G(l.sharedRoots),G(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."),br(e,`${u}.allowedCrossSlice`,"cross-slice-allowance",G((l.allowedCrossSlice??[]).map(Er)),G((c.allowedCrossSlice??[]).map(Er)),"Directed cross-slice edges are now allowed by declaration.","Directed cross-slice edges are no longer declared and deny again."),(l.sharedImportsSlice??null)!==(c.sharedImportsSlice??null)){let d=l.sharedImportsSlice??null,h=c.sharedImportsSlice??null,E=jo(h)>jo(d);C(e,{kind:"shared-imports-slice",path:`${u}.sharedImportsSlice`,classification:E?"strengthening":"weakening",message:Qc(d,h),before:d,after:h})}Kc(e,u,l,c)}}}a(jc,"compareRules");function Lo(e){let t=e.childSlices;return t?JSON.stringify([G(t.sliceFolders??[]),t.sliceIdentity??"path",G(t.commonFolders??[])]):""}a(Lo,"childSliceFoldersKey");function Vc(e){return G((e??[]).map(t=>un(t.trim().replace(/\\/g,"/")).toLowerCase()))}a(Vc,"enforceKeys");function Po(e){if(!e.childSlices)return null;let t=e.childSlices.siblings;return t==null||t==="deny"?{mode:"deny",enforce:[]}:t==="advisory"?{mode:"advisory",enforce:[]}:t.default==="deny"?{mode:"deny",enforce:[]}:{mode:"advisory",enforce:Vc(t.enforce)}}a(Po,"childSliceSiblingPolicy");function Kc(e,t,n,r){let o=Po(n),s=Po(r);if(o===null&&s===null)return;if(o===null&&s!==null){C(e,{kind:"child-slices-added",path:`${t}.childSlices`,classification:s.mode==="advisory"?"judgment-required":"strengthening",message:s.mode==="advisory"?"A child slice wall was added with advisory sibling crossings.":"A child slice wall was added. Sibling crossings inside a universe are now denied.",after:r.childSlices});return}if(o!==null&&s===null){C(e,{kind:"child-slices-removed",path:`${t}.childSlices`,classification:"weakening",message:"The child slice wall was removed. Sibling crossings inside a universe are allowed again.",before:n.childSlices});return}if(Lo(n)!==Lo(r)){C(e,{kind:"child-slices-changed",path:`${t}.childSlices`,classification:"judgment-required",message:"Child slice folders changed and can reclassify edges inside a universe.",before:n.childSlices,after:r.childSlices});return}if(o===null||s===null)return;if(o.mode!==s.mode){let c=s.mode==="advisory";C(e,{kind:"child-slices-siblings",path:`${t}.childSlices.siblings`,classification:c?"weakening":"strengthening",message:c?s.enforce.length>0?"Sibling crossings outside the enforce list are now advisory.":"Sibling crossings inside a universe are now advisory.":"Sibling crossings inside a universe are now denied.",before:o.mode,after:s.mode})}else o.mode==="advisory"&&Uc(e,`${t}.childSlices.siblings.enforce`,o.enforce,s.enforce);let i=n.childSlices?.parentMayImportChild===!0,l=r.childSlices?.parentMayImportChild===!0;i!==l&&C(e,{kind:"child-slices-parent-import",path:`${t}.childSlices.parentMayImportChild`,classification:l?"weakening":"strengthening",message:l?"Universe common may now import a child slice.":"Universe common may no longer import a child slice.",before:i,after:l}),Wc(e,t,n,r),zc(e,t,n,r)}a(Kc,"compareChildSlices");function Uc(e,t,n,r){if(JSON.stringify(n)===JSON.stringify(r))return;let o=r.filter(l=>!n.includes(l)),s=n.filter(l=>!r.includes(l)),i=o.length>0&&s.length>0;C(e,{kind:i?"child-slices-siblings-enforce-changed":"child-slices-siblings-enforce",path:t,classification:i?"judgment-required":o.length>0?"strengthening":"weakening",message:i?"Enforced sibling subtrees were added and removed in the same change.":o.length>0?"Sibling crossings from these subtrees are now errors.":"Sibling crossings from these subtrees are advisory again.",before:n,after:r})}a(Uc,"compareSiblingEnforceList");function Er(e){return JSON.stringify([e.from,e.to])}a(Er,"crossSliceKey");function Do(e){return G((e.childSlices?.allowedCrossSlice??[]).map(Er))}a(Do,"childCrossSliceKeys");function rt(e){return un(e.trim().replace(/\\/g,"/")).toLowerCase().split("/").filter(t=>t.length>0)}a(rt,"allowanceSegments");function Mo(e,t){let n=rt(e),r=rt(t);if(n.length===0||n.length!==r.length)return!1;let o=!1;for(let s=0;s<n.length;s+=1)if(n[s]!==r[s]){if(n[s]==="*"&&r[s]!=="*"){o=!0;continue}return!1}return o}a(Mo,"patternWidens");function Gc(e,t){let n=JSON.parse(e),r=JSON.parse(t),o=rt(n[0]).join("/")===rt(r[0]).join("/"),s=rt(n[1]).join("/")===rt(r[1]).join("/"),i=Mo(n[0],r[0]),l=Mo(n[1],r[1]);return!(o||i)||!(s||l)?!1:i||l}a(Gc,"allowanceWidens");function Bc(e){return JSON.stringify([un(e.from.trim().replace(/\\/g,"/")).toLowerCase(),un(e.to.trim().replace(/\\/g,"/")).toLowerCase()])}a(Bc,"aliasEntryKey");function Fo(e){return G((e.childSlices?.sliceAliases??[]).map(Bc))}a(Fo,"sliceAliasKeys");function zc(e,t,n,r){let o=Fo(n),s=Fo(r);if(JSON.stringify(o)===JSON.stringify(s))return;let i=s.filter(u=>!o.includes(u)),l=o.filter(u=>!s.includes(u)),c=i.length>0&&l.length>0;C(e,{kind:c?"slice-aliases-changed":i.length>0?"slice-aliases-added":"slice-aliases-removed",path:`${t}.childSlices.sliceAliases`,classification:c?"judgment-required":i.length>0?"strengthening":"weakening",message:c?"Slice aliases were added and removed in the same change.":i.length>0?"Unclassified files are now under the slice walls.":"Aliased files leave the slice walls.",before:o,after:s})}a(zc,"compareSliceAliases");function Wc(e,t,n,r){let o=Do(n),s=Do(r);if(JSON.stringify(o)===JSON.stringify(s))return;let i=s.filter(c=>!o.includes(c)),l=o.filter(c=>!s.includes(c));if(i.length>0&&l.length>0&&l.filter(u=>!i.some(p=>Gc(p,u))).length===0){C(e,{kind:"child-slices-cross-slice-allowance-added",path:`${t}.childSlices.allowedCrossSlice`,classification:"weakening",message:"A wildcard widened a declared sibling allowance.",before:o,after:s});return}br(e,`${t}.childSlices.allowedCrossSlice`,"child-slices-cross-slice-allowance",o,s,"Sibling crossings inside a universe are now allowed by declaration.","Declared sibling crossings inside a universe deny again.")}a(Wc,"compareChildCrossSliceAllowances");function br(e,t,n,r,o,s,i){if(JSON.stringify(r)===JSON.stringify(o))return;let l=o.filter(p=>!r.includes(p)),c=r.filter(p=>!o.includes(p)),u=l.length>0&&c.length>0;C(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?`${s} Entries were added and removed in the same change.`:l.length>0?s:i,before:r,after:o})}a(br,"compareDeclaredExceptions");function qc(e,t,n){let r=t.safety??{},o=n.safety??{};for(let s of["maxTsSuppressions","maxAnyCasts"]){let i=r[s]??0,l=o[s]??0;i!==l&&C(e,{kind:l>i?"threshold-raised":"threshold-lowered",path:`$.safety.${s}`,classification:l>i?"weakening":"strengthening",message:l>i?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:i,after:l})}for(let s of["allowInMemory","allowDisabledPeerIsolation"])Tt(e,`$.safety.${s}`,r[s]===!0,o[s]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}a(qc,"compareSafety");function Sr(e){return e.mode==="enforced"?"enforced":"advisory"}a(Sr,"arkRunMode");function Ir(e){return e.mode==="enforced"?"enforced":"advisory"}a(Ir,"arkOrderMode");function Yc(e,t,n){let r=t.arkOrder,o=n.arkOrder,s="$.arkOrder";if(!r&&!o)return;if(!r&&o){C(e,{kind:"arkorder-added",path:s,classification:"strengthening",message:`ArkOrder extra was added (${Ir(o)}).`,after:o});return}if(r&&!o){C(e,{kind:"arkorder-removed",path:s,classification:"weakening",message:"ArkOrder extra was removed.",before:r});return}if(!r||!o)return;let i=Ir(r),l=Ir(o);if(i!==l){let c=i==="advisory"&&l==="enforced";C(e,{kind:c?"arkorder-promoted":"arkorder-demoted",path:`${s}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkOrder extra was promoted to enforced.":"ArkOrder extra was demoted to advisory.",before:i,after:l})}he(e,`${s}.planeRoots`,r.planeRoots,o.planeRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkOrder plane roots are governed.",removedMessage:"ArkOrder plane roots were removed and may skip the plane."}),he(e,`${s}.managedLayers`,r.managedLayers,o.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkOrder.",removedMessage:"Layers were removed from ArkOrder management."})}a(Yc,"compareArkOrder");function Jc(e,t,n){let r=t.arkRun,o=n.arkRun,s="$.arkRun";if(!r&&!o)return;if(!r&&o){C(e,{kind:"arkrun-added",path:s,classification:"strengthening",message:`ArkRun extra was added (${Sr(o)}).`,after:o});return}if(r&&!o){C(e,{kind:"arkrun-removed",path:s,classification:"weakening",message:"ArkRun extra was removed.",before:r});return}if(!r||!o)return;let i=Sr(r),l=Sr(o);if(i!==l){let c=i==="advisory"&&l==="enforced";C(e,{kind:c?"arkrun-promoted":"arkrun-demoted",path:`${s}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkRun extra was promoted to enforced.":"ArkRun extra was demoted to advisory.",before:i,after:l})}he(e,`${s}.compositionRoots`,r.compositionRoots,o.compositionRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkRun composition roots are governed.",removedMessage:"ArkRun composition roots were removed and may skip the kernel."}),he(e,`${s}.managedLayers`,r.managedLayers,o.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkRun.",removedMessage:"Layers were removed from ArkRun management."}),Tt(e,`${s}.requireDeclarations`,r.requireDeclarations!==!1,o.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}a(Jc,"compareArkRun");function Xc(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"}a(Xc,"overallClassification");function $o(e,t){return`${e}::${t}`}a($o,"ruleKey");function Ho(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set($o(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set($o(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}a(Ho,"indexEffectiveRules");function Zc(e,t,n,r,o,s){let i=new Map((s??[]).map(f=>[f.invariantId,f])),l=t.arkRules??{},c=n.arkRules??{},u=[...new Set([...Object.keys(l),...Object.keys(c)])].sort();for(let f of u){let g=l[f],d=c[f],h=`$.arkRules[${f}]`;if(g===void 0&&d!==void 0){C(e,{kind:"arkrules-ref-added",path:h,classification:"strengthening",message:`ArkRules reference for layer ${f} was added.`,after:d});continue}if(g!==void 0&&d===void 0){C(e,{kind:"arkrules-ref-removed",path:h,classification:"weakening",message:`ArkRules reference for layer ${f} was removed.`,before:g});continue}g!==d&&C(e,{kind:"arkrules-ref-path-changed",path:h,classification:"judgment-required",message:`ArkRules file path for layer ${f} changed; verify the effective rules still match intent.`,before:g,after:d})}let p=Ho(r),m=Ho(o);for(let f of[...new Set([...p.structure.keys(),...m.structure.keys()])].sort()){let g=p.structure.get(f),d=m.structure.get(f),h=`$.arkRules.structure[${f}]`;if(!g&&d){C(e,{kind:"arkrule-structure-added",path:h,classification:"strengthening",message:`Structure ArkRule ${d.id} was added (${d.mode}).`,after:d});continue}if(g&&!d){C(e,{kind:"arkrule-structure-removed",path:h,classification:"weakening",message:`Structure ArkRule ${g.id} was removed.`,before:g});continue}if(!(!g||!d)){if(g.mode!==d.mode){let E=g.mode==="advisory"&&d.mode==="enforced";C(e,{kind:E?"arkrule-promoted":"arkrule-demoted",path:`${h}.mode`,classification:E?"strengthening":"weakening",message:E?`Structure ArkRule ${d.id} was promoted to enforced.`:`Structure ArkRule ${d.id} was demoted to advisory.`,before:g.mode,after:d.mode})}g.sensor!==d.sensor&&C(e,{kind:"arkrule-sensor-changed",path:`${h}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${d.id} changed sensor identity.`,before:g.sensor,after:d.sensor})}}for(let f of[...new Set([...p.invariants.keys(),...m.invariants.keys()])].sort()){let g=p.invariants.get(f),d=m.invariants.get(f),h=`$.arkRules.invariants[${f}]`;if(!g&&d){C(e,{kind:"arkrule-invariant-added",path:h,classification:"strengthening",message:`Invariant ${d.id} was added (${d.mode}).`,after:d});continue}if(g&&!d){C(e,{kind:"arkrule-invariant-removed",path:h,classification:"weakening",message:`Invariant ${g.id} was removed.`,before:g});continue}if(!(!g||!d)&&g.mode!==d.mode)if(g.mode==="advisory"&&d.mode==="enforced"){let _=i?.get(d.id),k=Ar(_);k.ok?C(e,{kind:"arkrule-invariant-promoted",path:`${h}.mode`,classification:"strengthening",message:`Invariant ${d.id} was promoted to enforced (coverage evidence present).`,before:g.mode,after:d.mode}):C(e,{kind:"arkrule-invariant-promote-refused",path:`${h}.mode`,classification:"judgment-required",message:`Invariant ${d.id} cannot be promoted to enforced: ${k.reason}`,before:g.mode,after:d.mode})}else C(e,{kind:"arkrule-invariant-demoted",path:`${h}.mode`,classification:"weakening",message:`Invariant ${d.id} was demoted to advisory.`,before:g.mode,after:d.mode})}}a(Zc,"compareArkRules");function Cr(e,t,n){let r=[];he(r,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),he(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."}),he(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."}),Tt(r,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let o={off:0,soft:1,"framework-soft":1,strict:2},s=e.cyclePolicy??"strict",i=t.cyclePolicy??"strict";if(s!==i){let l=o[i]===o[s]?"judgment-required":o[i]>o[s]?"strengthening":"weakening";C(r,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:l,message:"The cycle enforcement level changed.",before:s,after:i})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&C(r,{kind:"framework-overlay-changed",path:"$.frameworkOverlay",classification:"judgment-required",message:"The framework overlay changed and may alter effective layer matching.",before:e.frameworkOverlay??null,after:t.frameworkOverlay??null}),Hc(r,e.layers,t.layers),jc(r,e.rules,t.rules),qc(r,e,t),Zc(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),Jc(r,e,t),Yc(r,e,t),r.sort((l,c)=>l.path.localeCompare(c.path)||l.id.localeCompare(c.id)),{schemaVersion:vr,classification:Xc(r),findings:r}}a(Cr,"classifyArkPolicyDelta");function _r(e,t){if(!e||e.schemaVersion!==vr||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(o=>typeof o!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=G(e.findingIds),r=G(t.findingIds);return n.length===r.length&&n.every((o,s)=>o===r[s])}a(_r,"policyDeltaAcknowledgementMatches");function un(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}a(un,"trimTrailingSlashes");function jo(e){return e==="deny"?2:e==="deny-cross-parent"?1:0}a(jo,"sharedImportsSliceRank");function Qc(e,t){return t==="deny"?"A shared root may no longer import a slice.":e==="deny"&&t==="deny-cross-parent"?"A shared root may import a slice again, except when that hop carries another universe.":e==="deny"?"A shared root may import a slice again.":t==="deny-cross-parent"?"A slice may no longer reach another universe through a shared root. ark-check and CI report that path. The write hook and ESLint see one edge at a time and do not block it.":"A slice may reach another universe through a shared root again."}a(Qc,"sharedImportsSliceMessage");function je(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("/")}a(je,"normalizePath");function Vo(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}a(Vo,"isIdentifierStart");function pn(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}a(pn,"isIdentifierCharacter");function de(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}a(de,"skipWhitespace");function wt(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let r=t,o="";for(t+=1;t<e.length;t+=1){let s=e[t];if(s===n)return{value:o,offset:r,excerpt:e.slice(r,t+1)};s==="\\"&&t+1<e.length?(o+=e[t+1],t+=1):o+=s}}a(wt,"readString");function ue(e,t,n){return e.startsWith(t,n)&&!pn(e[n-1])&&!pn(e[n+t.length])}a(ue,"isWordAt");function Ko(e,t){let n=de(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=de(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!ue(e,"type",n))return!1;let o=de(e,n+4);if(o>=e.length||e[o]===","||e[o]==="}"||ue(e,"as",o)||!Vo(e[o]))return!1;for(n=o;n<e.length&&pn(e[n]);)n+=1;if(n=de(e,n),ue(e,"as",n)){if(n=de(e,n+2),!Vo(e[n]))return!1;for(;n<e.length&&pn(e[n]);)n+=1}r=!0}return!1}a(Ko,"bracedNamedBindingsAreTypeOnly");function ed(e,t){if(t=de(e,t+6),e[t]==="(")return wt(e,de(e,t+1));let n=!1;if(ue(e,"type",t)){let o=de(e,t+4);e[o]!==","&&!ue(e,"from",o)&&(n=!0)}else Ko(e,t)&&(n=!0);let r=Uo(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}a(ed,"specifierAfterImport");function td(e,t){t=t+6;let n=de(e,t),r=!1;if(ue(e,"type",n)){let s=de(e,n+4);(e[s]==="{"||e[s]==="*")&&(r=!0)}else Ko(e,n)&&(r=!0);let o=Uo(e,t,!1);return o&&r?{...o,typeOnly:!0}:o}a(td,"specifierAfterExport");function Uo(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(ue(e,"from",t))return wt(e,de(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return wt(e,t);if(t>0&&(ue(e,"import",t)||ue(e,"export",t)))return}}a(Uo,"specifierInStaticStatement");function nd(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}a(nd,"skipTemplateLiteral");function rd(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=de(e,t+7);if(e[r]!=="(")return;r=de(e,r+1);let o=wt(e,r);return o?{...o,requireCall:!0}:void 0}a(rd,"specifierAfterRequire");function sd(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(`
16
+ `,n+2),n<0)break;continue}if(r==="/"&&e[n+1]==="*"){let s=e.indexOf("*/",n+2);if(s<0)break;n=s+1;continue}if(r==="`"){n=nd(e,n);continue}if(r==="'"||r==='"'){let s=wt(e,n);s&&(n=s.offset+s.excerpt.length-1);continue}let o=r==="i"&&ue(e,"import",n)?ed(e,n):r==="e"&&ue(e,"export",n)?td(e,n):r==="r"&&ue(e,"require",n)?rd(e,n):void 0;o&&(t.push(o),n=o.offset+o.excerpt.length-1)}return t}a(sd,"moduleSpecifiers");function Go(e,t){let n=[],r=[];for(let o of sd(e.content)){let s=o.value;if(!s.startsWith(".")){if(o.typeOnly)continue;let u=ft(s);if(!u)continue;let p=e.content.slice(0,o.offset).split(`
17
+ `).length;r.push({file:e.path,symbol:s,capability:u,evidence:{kind:"import",file:e.path,line:p,excerpt:o.excerpt}});continue}let i=e.content.slice(0,o.offset).split(`
18
+ `).length,l={kind:"import",file:e.path,line:i,excerpt:o.excerpt},c=od(e.path,s,t);n.push({from:e.path,specifier:s,to:c?.path??null,resolution:c?"resolved":"unresolved",fromLayer:e.layer,toLayer:c?.layer??null,evidence:l})}return{edges:n,capabilityUses:r}}a(Go,"moduleFactsFor");function od(e,t,n){let r=e.split("/");r.pop();for(let s of t.split("/"))s==="."||s===""||(s===".."?r.pop():r.push(s));let o=r.join("/");for(let s of[o,`${o}.ts`,`${o}.tsx`,`${o}.mts`,`${o}.cts`,`${o}/index.ts`,`${o}/index.tsx`]){let i=n.get(s);if(i)return i}}a(od,"resolveSpecifier");function Bo(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let o=Fs(t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});o&&n.push({ruleId:`layer-dependency:${o.from}->${o.to}`,message:o.message??`${o.from} must not depend on ${o.to}.`,edge:r,evidence:r.evidence})}return n}a(Bo,"violationsFor");var id={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 ad(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}a(ad,"hasActiveArkRules");function ld(e,t){return ad(e,t)?ee(K(fr({config:e,arkRules:t,warnings:[]}))):ee(K(pr(e)))}a(ld,"policyHashFor");function fn(e,t,n){let r=typeof e=="string"?or(e,t):rn(e,t),o=n?.arkRules??He();return{...r,arkRules:o,policyHash:ld(r.config,o)}}a(fn,"loadContract");function zo(e){let t=fn(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=fn(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=Cr(t.config,n.config,{baseArkRules:t.arkRules,candidateArkRules:n.arkRules,candidateInvariantCoverage:e.candidateInvariantCoverage}),o=r.findings.filter(l=>l.classification==="weakening"||l.classification==="judgment-required").map(l=>l.id).sort(),s=o.length>0,i=s&&_r(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:o});return{schemaVersion:r.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:r.classification,findings:r.findings,blockingFindingIds:o,requiresAcknowledgement:s,acknowledged:i,valid:!s||i}}a(zo,"analyzePolicyDelta");function Nt(e){let t=e.files.map(m=>{let f=je(m.path);return{path:f,content:m.content,contentHash:ee(m.content),layer:ge(f,e.contract.config.layers)??null}}).sort((m,f)=>m.path.localeCompare(f.path)),n=new Map(t.map(m=>[m.path,m])),r=[],o=[];for(let m of t){let f=Go(m,n);r.push(...f.edges),o.push(...f.capabilityUses)}let s=Bo(r,e.contract.config),i=new Map(e.contract.config.layers.map(m=>[m.name,m])),l=new Map(e.contract.config.layers.map(m=>[m.name,new Set(Ge(m))]));for(let m of o){let f=n.get(m.file)?.layer;if(!f)continue;let g=i.get(f),d=_e(m.symbol,g?.forbiddenGlobals??[]);if(d){s.push({ruleId:"FORBIDDEN_GLOBAL",message:`${f} must not use module "${m.symbol}" because it is the import form of forbidden global "${d}".`,symbol:m.symbol,evidence:m.evidence});continue}l.get(f)?.has(m.capability)&&s.push({ruleId:"CAPABILITY_VIOLATION",message:`${f} denies the ${m.capability} capability; found import of "${m.symbol}".`,capability:m.capability,symbol:m.symbol,evidence:m.evidence})}let c=t.length===0?"complete":"partial",u=c==="complete"?[]:[{...id}],p={schemaVersion:lr,policyHash:e.contract.policyHash,compilerOptionsHash:ee(K(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(m=>m.name),edges:r,capabilityUses:o,violations:s};return{mode:"lexical-compatibility",completeness:c,completenessReasons:u,valid:c==="complete"&&s.length===0,ir:p}}a(Nt,"analyzeProject");function gn(e){let t=new Map(e.files.map(n=>[je(n.path),n]));for(let n of e.changes){let r=je(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return Nt({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}a(gn,"analyzeChange");function Wo(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}`}a(Wo,"explainViolation");function xr(e){let t=0,n=new Map,r=new Map,o=new Set,s=[],i=[],l=a(c=>{n.set(c,t),r.set(c,t),t+=1,s.push(c),o.add(c);for(let m of[...e.get(c)??[]].sort())e.has(m)&&(n.has(m)?o.has(m)&&r.set(c,Math.min(r.get(c)??0,n.get(m)??0)):(l(m),r.set(c,Math.min(r.get(c)??0,r.get(m)??0))));if(r.get(c)!==n.get(c))return;let u=[],p;do{if(p=s.pop(),p===void 0)break;o.delete(p),u.push(p)}while(p!==c);u.length>1&&i.push(u.sort())},"connect");for(let c of[...e.keys()].sort())n.has(c)||l(c);return i.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"}))}a(xr,"detectArchitectureCycles");function st(e){let t=e.contentViolations.map(s=>({...s})),n=(e.warnings??[]).map(s=>({...s})),r=new Map(e.files.map(s=>[s,new Set]));for(let s of e.edges){if(s.to&&s.to!==s.from&&!s.typeOnly&&r.has(s.from)&&r.get(s.from)?.add(s.to),!s.to||!s.fromLayer||!s.toLayer)continue;let i=Oe(e.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:e.config.layers});if(!i){let f=$s(e.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:e.config.layers});f&&n.push({ruleId:"SHARED_IMPORTS_SLICE",file:f.fromPath,line:s.line,fromLayer:s.fromLayer,toLayer:s.toLayer,target:f.toPath,toSlice:f.toSlice,failsStrict:!1,severity:"warning",message:`shared root ${f.fromPath} \u2192 slice ${f.toSlice} (${f.toPath}). The wall is direct-only.`});continue}let l=i.rule,c=!!l.peerIsolation,u=!c&&!!(s.typeOnly||s.namedBindingsTypeOnly),p=i.sliceVerdict,m=p?ze({surface:"import",verdict:p,fromLayer:s.fromLayer,toLayer:s.toLayer,kind:s.kind,fromPath:s.from,toPath:s.to,ruleMessage:l.message}):l.message??`${s.fromLayer} must not ${s.kind} ${s.toLayer}.`;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:s.from,line:s.line,fromLayer:s.fromLayer,toLayer:s.toLayer,target:s.to,...s.typeOnly?{typeOnly:!0}:{},...s.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...s.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...s.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!c&&s.portProofEligible?{portProofEligible:!0}:{},...s.kind?{edgeKind:s.kind}:{},...c?{peerIsolation:!0}:{},...Ne(p),message:u?`${m} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:m,...u?{failsStrict:!1,severity:"warning"}:{}})}t.push(...ud(e));let o=String(e.config.cyclePolicy??"strict").toLowerCase();if(o!=="off"){let s=xr(r);o==="soft"||o==="framework-soft"?n.push(...s.map(i=>({...i,message:`${i.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...s)}return{violations:t,warnings:n,safety:e.safety}}a(st,"evaluateArchitectureGraph");var cd="CROSS_PARENT_VIA_SHARED",dd="ark-check and CI report this path. The write hook and ESLint see one edge at a time and do not block it.";function qo(e,t,n){for(let r of e??[])if(!(r.from!==t||r.to!==n)&&!(r.allowed!==!1||!r.peerIsolation)&&r.sharedImportsSlice==="deny-cross-parent")return r}a(qo,"denyingCrossParentRule");function Or(e,t,n,r){let o=Be(n,e,Hs(e,t,r)).universeId;return o?{kind:"slice",id:o}:mt(n,e.sharedRoots)?{kind:"shared"}:{kind:"other"}}a(Or,"placeFile");function ud(e){let t=e.rules??[];if(!t.some(s=>s.sharedImportsSlice==="deny-cross-parent"))return[];let n=new Map;for(let s of e.edges){let i=pd(s);if(!i)continue;let l=n.get(i.from);l?l.push(i):n.set(i.from,[i])}for(let s of n.values())s.sort((i,l)=>i.to<l.to?-1:i.to>l.to?1:i.line-l.line);let r=new Map,o=[...n.values()].flat();o.sort((s,i)=>s.from<i.from?-1:s.from>i.from?1:s.to<i.to?-1:s.to>i.to?1:0);for(let s of o){let i=qo(t,s.fromLayer,s.toLayer);if(!i)continue;let l=Or(i,s.fromLayer,s.from,e.config.layers),c=Or(i,s.fromLayer,s.to,e.config.layers);if(l.kind!=="slice"||c.kind!=="shared")continue;let u=[{file:s.to,path:[s.from,s.to]}],p=new Set([s.to]);for(;u.length>0;){let m=u.shift();if(!m)break;for(let f of n.get(m.file)??[]){let g=qo(t,f.fromLayer,f.toLayer);if(!g)continue;let d=Or(g,f.fromLayer,f.to,e.config.layers);if(d.kind==="shared"){if(p.has(f.to))continue;p.add(f.to),u.push({file:f.to,path:[...m.path,f.to]});continue}if(d.kind!=="slice"||d.id.toLowerCase()===l.id.toLowerCase())continue;let h=[...m.path,f.to],E=`${s.from}\0${f.to}`,_={file:s.from,target:f.to,line:s.line,fromLayer:s.fromLayer,toLayer:f.toLayer,fromSlice:l.id,toSlice:d.id,path:h},k=r.get(E);(!k||h.length<k.path.length||h.length===k.path.length&&h.join("\0")<k.path.join("\0"))&&r.set(E,_)}}}return[...r.values()].sort((s,i)=>s.file<i.file?-1:s.file>i.file?1:s.target<i.target?-1:s.target>i.target?1:0).map(s=>{let i=ht(s.fromSlice),l=ht(s.toSlice);return{ruleId:"LAYER_IMPORT_VIOLATION",reasonId:cd,file:s.file,line:s.line,fromLayer:s.fromLayer,toLayer:s.toLayer,target:s.target,peerIsolation:!0,...i&&l?{universeFrom:i,universeTo:l}:{},message:`${s.fromLayer} reaches ${s.toLayer} in another universe through a shared root (${s.path.join(" \u2192 ")}): cross-parent via shared ${s.fromSlice} \u2192 ${s.toSlice}. ${dd}`}})}a(ud,"crossParentViaSharedViolations");function pd(e){if(!(!e.to||e.to===e.from||!e.fromLayer||!e.toLayer))return{from:e.from,to:e.to,line:e.line,fromLayer:e.fromLayer,toLayer:e.toLayer}}a(pd,"valueHop");function Yo(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}a(Yo,"structureFreezeTarget");var fd=["no-anemic-model"],ti=["ensureInvariants","assertInvariants","validate","publish","emit","raise","record"],Nr=new RegExp(`\\b(${ti.join("|")})\\b`),ni="(?:_?pendingEvents|domainEvents|uncommittedEvents|recordedEvents)",Lr=new RegExp(`\\bthis\\.${ni}\\.push\\s*\\(`),gd=new RegExp(`^this\\.${ni}\\s*=\\s*\\[\\s*\\]`),md=/^this\.[A-Za-z_][A-Za-z0-9_]*\s*=\s*\[\s*\]/,hd=/\bthis\.[A-Za-z_][A-Za-z0-9_]*\s*=(?!=)/g,ri="truncatedUntil";function Pr(){return`${ti.join(", ")}, or events-array .push(`}a(Pr,"expectedDomainInvariantWordsPhrase");function yd(e){return Nr.test(e)||Lr.test(e)}a(yd,"referencesGuardOrPublish");function Dr(e,t,n){let r=e.slice(t);if(gd.test(r))return!0;if(!md.test(r))return!1;if(n&&/^pullEvents$/i.test(n))return!0;let o=t>200?t-200:0;return/\bpullEvents\b/.test(e.slice(o,t+200))}a(Dr,"isIdiomaticEventsReset");function Ad(e,t){let n=new RegExp(hd.source,"g"),r;for(;(r=n.exec(t))!==null;)if(!Dr(t,r.index,e))return!0;return!1}a(Ad,"methodAssignsThis");function Rd(e,t){return t==null||Object.defineProperty(e,ri,{value:t,enumerable:!1,configurable:!0}),e}a(Rd,"attachShapeTruncation");function wr(e){let t=Object.getOwnPropertyDescriptor(e,ri)?.value;return typeof t=="number"?t:void 0}a(wr,"shapeTruncatedUntil");function kd(e){let t=wr(e);return t==null?"":` shape analysed until character ${t}`}a(kd,"shapeTruncationSuffix");function Jo(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(Jo,"escapeGlobLiteral");function Sd(e){let t="";for(let r=0;r<e.length;r+=1){let o=e[r];if(o==="\\"&&r+1<e.length){let s=e[r+1];if("*?{}[],".includes(s)||s==="\\"){t+="\\"+s,r+=1;continue}t+="/";continue}t+=o}let n="";for(let r=0;r<t.length;r+=1){let o=t[r];o==="\\"&&r+1<t.length?(n+=Jo(t[r+1]),r+=1):o==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":o==="?"?n+="[^/]":n+=Jo(o)}return new RegExp(`^${n}$`)}a(Sd,"globToRegExp");function ot(e,t){return!t||t.length===0?!0:t.some(n=>Sd(n).test(e))}a(ot,"matchesAppliesTo");function si(e){return fd.includes(e)}a(si,"isTier2");function oi(e){return e.mode==="enforced"&&!si(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}a(oi,"severityFor");function Te(e,t,n,r=1){let{severity:o,failsStrict:s}=oi(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:o,sensor:e.sensor,failsStrict:s}}a(Te,"baseViolation");function hn(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}a(hn,"isInRuleLayer");function yn(e,t,n){return t.filter(r=>!(!r.exported||!ot(r.file,e.appliesTo)||!hn(r.file,e,n)))}a(yn,"shapesForRule");function Id(e,t,n){let r=[];for(let o of yn(e,t,n))(o.hasPublicSetters||o.hasPublicMutableFields)&&r.push(Te(e,o.file,`Exported class ${o.className} exposes public mutable state (sensor aggregate-private-state).`));return r}a(Id,"evaluateAggregatePrivateState");function Ed(e,t,n){let r=[];for(let o of yn(e,t,n))if(o.hasPublicConstructor&&!o.hasStaticFactory){if(!(o.hasPublicMutableFields||o.hasPublicSetters||(o.mutatingMethods?.length??0)>0))continue;r.push(Te(e,o.file,`Exported class ${o.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}return r}a(Ed,"evaluateAlwaysValidFactory");function bd(e,t,n){let r=[],o=Pr();for(let s of yn(e,t,n)){let i=kd(s);wr(s)!=null&&r.push(Te(e,s.file,`Exported class ${s.className} shape analysed until character ${wr(s)}; later methods may be invisible (sensor domain-event-on-mutation).`));for(let l of s.mutatingMethods)l.referencesGuardOrPublish||r.push(Te(e,s.file,`Mutating method ${s.className}.${l.name} does not reference ${o} (sensor domain-event-on-mutation).${i}`))}return r}a(bd,"evaluateDomainEventOnMutation");function vd(e,t){let n=[];for(let r of t.files)ot(r,e.appliesTo)&&hn(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(Te(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}a(vd,"evaluateOrchestrationOnly");function Cd(e,t){let n=[];for(let r of t.files)ot(r,e.appliesTo)&&hn(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(Te(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}a(Cd,"evaluateThinAdapter");function _d(e,t){let n=[];for(let r of t.files)ot(r,e.appliesTo)&&hn(r,e,t.layerForFile)&&t.fileHints?.[r]?.persistenceWrite&&n.push(Te(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}a(_d,"evaluateWritesViaAggregate");function Od(e,t,n){let r=[];for(let o of yn(e,t,n))if(o.dataOnly===!0){let s=Te(e,o.file,`Exported type ${o.className} looks data-only / anemic (sensor no-anemic-model; advisory only).`);r.push({...s,severity:"warning",failsStrict:!1})}return r}a(Od,"evaluateNoAnemicModel");function Mr(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(...Id(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...Ed(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...bd(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...vd(n,e));break;case"thin-adapter":t.push(...Cd(n,e));break;case"writes-via-aggregate":t.push(..._d(n,e));break;case"no-anemic-model":t.push(...Od(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))}a(Mr,"evaluateArkRuleSensors");function Fr(e,t){let n=[],r=t.map(o=>o.replace(/\\/g,"/"));for(let o of e.structure){if(!o.appliesTo||o.appliesTo.length===0||r.some(c=>ot(c,o.appliesTo)))continue;let{severity:i,failsStrict:l}=oi(o);n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule structure "${o.id}" appliesTo matched zero governed files (patterns: ${o.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:o.provenance.sourceFile,line:1,fromLayer:o.provenance.layer,arkruleId:o.id,arkruleSource:o.provenance.sourceFile,severity:i,sensor:o.sensor,failsStrict:l})}for(let o of e.invariants??[]){if(!o.appliesTo||o.appliesTo.length===0||r.some(l=>ot(l,o.appliesTo)))continue;let i=o.mode==="enforced";n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule invariant "${o.id}" appliesTo matched zero governed files (patterns: ${o.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:o.provenance.sourceFile,line:1,fromLayer:o.provenance.layer,arkruleId:o.id,arkruleSource:o.provenance.sourceFile,severity:i?"error":"warning",sensor:"invariant-coverage",failsStrict:i})}return n.sort((o,s)=>o.file.localeCompare(s.file)||o.arkruleId.localeCompare(s.arkruleId)||o.message.localeCompare(s.message))}a(Fr,"collectEmptyAppliesToFindings");var Xo=64;function xd(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===46;)t-=1;return t===e.length?e:e.slice(0,t)}a(xd,"stripTrailingDots");function Td(e){let t=e.trim(),n=t.length>Xo?t.slice(0,Xo):t;return xd(n)}a(Td,"normalizeIntentPrefix");function wd(e){let t=e.toLowerCase();return t.includes("domain")||t.includes("entity")||t.includes("aggregate")||t.includes("model")}a(wd,"layerNameLooksDomain");function Nd(e){return e.some(t=>{let n=Td(t);return n==="Domain"||n.startsWith("Domain.")})}a(Nd,"ownsDomainIntent");function Ld(e,t=[]){return wd(e)||Nd(t)}a(Ld,"isDomainRoleLayerName");function ii(e){if(e.arkRulesActive!==!0)return[];let t=(e.layers??[]).filter(c=>Ld(c.name,c.intentPrefixes??[])).map(c=>c.name);if(t.length===0)return[];let n=new Set(t);if(!(e.files??[]).some(c=>{let u=typeof c.layer=="string"?c.layer:"";return u.length>0&&n.has(u)}))return[];if((e.arkRules.invariants??[]).filter(c=>n.has(c.provenance.layer)).length>0)return[];let s=t.find(c=>e.arkRules.byLayer?.[c])??t[0],i=e.arkRules.byLayer?.[s]?.sourceFile??`arkrules/${s}.json`,l=(e.arkRules.structure??[]).some(c=>c.mode==="enforced"&&n.has(c.provenance.layer)&&!si(c.sensor));return[{ruleId:"INVARIANT_CATALOG_EMPTY",code:"invariant-catalog-empty",message:`ArkRules is on and ${s} has code, but invariants[] is empty \u2014 there are no phrases the code must preserve. Add 1\u20132 short phrases in ${i}.`,file:i,line:1,fromLayer:s,arkruleId:"invariant-catalog",arkruleSource:i,severity:l?"error":"warning",sensor:"invariant-coverage",failsStrict:l}]}a(ii,"collectEmptyInvariantCatalogFindings");var Zo=/\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)/,Qo=/\bfrom\s+['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)(?:\.[cm]?[jt]sx?)?['"]|require\(\s*['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)/,Pd=/\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 Dd(e){return e==="PersistenceAdapters"}a(Dd,"isPersistenceDriverLayer");function Md(e,t){if(Zo.test(e)||Qo.test(e))return!0;if(!t)return!1;for(let n of t){if(Dd(n.layer))return!0;let r=n.specifier;if(!r)continue;let o=`from '${r}'`;if(Zo.test(o)||Qo.test(o))return!0}return!1}a(Md,"sourceImportsPersistenceDriver");var Fd=/\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*=)/,$d=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,Hd=/\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*=/,jd=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function ai(e,t,n){if(!t)return null;let r=Md(t,n),o=r&&Pd.test(t);if(t.length<40)return o?{persistenceWrite:!0}:null;let s=t.match(new RegExp(Hd.source,"g"))??[],i=t.match(new RegExp(jd.source,"g"))??[],l=(t.match(/\bif\s*\(/g)??[]).length,c=(t.match(/\bswitch\s*\(/g)??[]).length,u=s.length>=2||s.length>=1&&i.length>=2||i.length>=3&&l+c>=6,p=Fd.test(t)||$d.test(t),m=s.length>=1||i.length>=2,f=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),g=r&&m||p&&m||r&&f&&(l>=4||s.length>=1)||p&&r;return!u&&!g&&!o?null:{...u?{orchestrationHeavy:!0}:{},...g?{adapterThick:!0}:{},...o?{persistenceWrite:!0}:{}}}a(ai,"deriveArkRuleFileHints");function $r(e,t){let n={};for(let[r,o]of Object.entries(e)){let s=r.replace(/\\/g,"/"),i=ai(r,o,t?.[s]);i&&(n[s]=i)}return n}a($r,"buildArkRuleFileHints");var Vd=new Set(["public","private","protected","static","async","readonly","abstract","override","declare","get","set"]),Kd=new Set(["if","match","when"]);function mn(e,t){let n=e[t];if(n==="/"&&e[t+1]==="/"){let r=e.indexOf(`
19
+ `,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}a(mn,"skipStringOrComment");function Lt(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=mn(e,n);continue}break}return n}a(Lt,"skipWsAndComments");function ei(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}}a(ei,"readIdent");function Tr(e,t,n,r){if(e[t]!==n)return null;let o=1,s=t+1;for(;s<e.length&&o>0;){let i=mn(e,s);if(i!==s){s=i;continue}let l=e[s];l===n?o+=1:l===r&&(o-=1),s+=1}return o===0?s:null}a(Tr,"skipBalanced");function Ud(e){let t=[],n=0,r;for(;n<e.length&&(n=Lt(e,n),!(n>=e.length));){if(e[n]===";"){n+=1;continue}let o=[],s=n;for(;;){let p=ei(e,s);if(!p||!Vd.has(p.ident))break;o.push(p.ident),s=Lt(e,p.end)}let i=ei(e,s);if(!i){n+=1;continue}if(s=Lt(e,i.end),e[s]==="<"){let p=Tr(e,s,"<",">");if(p==null){r=e.length;break}s=Lt(e,p)}if(e[s]==="("){let p=Tr(e,s,"(",")");if(p==null){r=e.length;break}if(s=Lt(e,p),e[s]===":")for(s+=1;s<e.length&&e[s]!=="{"&&e[s]!==";";){let m=mn(e,s);if(m!==s){s=m;continue}s+=1}if(e[s]==="{"){let m=Tr(e,s,"{","}");if(m==null){r=e.length;break}t.push({name:i.ident,modifiers:o,kind:"method",body:e.slice(s+1,m-1)}),n=m;continue}if(e[s]===";"){n=s+1;continue}n=s+1;continue}let l=0,c=0,u=0;for(;s<e.length;){let p=mn(e,s);if(p!==s){s=p;continue}let m=e[s];if(m==="{")l+=1;else if(m==="}"){if(l===0)break;l-=1}else if(m==="(")c+=1;else if(m===")")c-=1;else if(m==="[")u+=1;else if(m==="]")u-=1;else if(m===";"&&l===0&&c===0&&u===0){s+=1;break}s+=1}t.push({name:i.ident,modifiers:o,kind:"field",body:""}),n=s}return{members:t,truncatedAt:r}}a(Ud,"scanClassMembers");function Gd(e,t){let n=[],r=/export\s+(?:abstract\s+)?class\s+([A-Za-z_][A-Za-z0-9_]*)\s*(?:extends\s+[^{]+)?(?:implements\s+[^{]+)?\{/g,o;for(;(o=r.exec(t))!==null;){let s=o[1],i=o.index+o[0].length,l=1,c=i;for(;c<t.length&&l>0;){let S=t[c];S==="{"?l+=1:S==="}"&&(l-=1),c+=1}let u=t.slice(i,c-1),p=l>0,m=Ud(u),f=p?t.length:m.truncatedAt==null?void 0:i+m.truncatedAt,g=m.members.filter(S=>!(S.kind!=="field"||S.name==="constructor"||S.modifiers.includes("private")||S.modifiers.includes("protected")||S.modifiers.includes("readonly")||S.modifiers.includes("static")||S.modifiers.includes("get")||S.modifiers.includes("set"))),d=g.length>0,h=/(?:^|[\n;{])\s*(?:public\s+)?set\s+[a-zA-Z_]/.test(u),E=/(?:^|[\n;{])\s*private\s+constructor\s*\(/.test(u),_=/(?:^|[\n;{])\s*(?:public\s+)?constructor\s*\(/.test(u)&&!E,k=/(?:^|[\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),b=[];for(let S of m.members)S.kind==="method"&&S.name!=="constructor"&&(S.modifiers.includes("static")||S.modifiers.includes("get")||S.modifiers.includes("set")||Kd.has(S.name)||Ad(S.name,S.body)&&b.push({name:S.name,referencesGuardOrPublish:yd(S.body)}));let D=m.members.filter(S=>S.kind==="method").length<=1&&g.length>=2&&d;n.push(Rd({file:e,className:s,exported:!0,hasPublicMutableFields:d,hasPublicSetters:h,hasPublicConstructor:_,hasStaticFactory:k,mutatingMethods:[...b],dataOnly:D},f))}return n}a(Gd,"extractClassShapesFromSource");var Bd=50;function Hr(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}}a(Hr,"normalizeExtraMergeTeethClassification");function ke(e){let t=Hr(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}a(ke,"extraMergeTeethAllowed");function jr(e){let t=e.length,n=0,r=new Set;for(let o of e){let s=typeof o.layer=="string"&&o.layer.length>0?o.layer:null;s&&(n+=1,r.add(s))}return{governedPercent:t>0?Math.round(n/t*100):0,populatedLayerCount:r.size}}a(jr,"classifyResolvedLayerCoverage");function Vr(e){return typeof e=="string"&&e.startsWith("ARKRUN_")}a(Vr,"isArkRunRuleId");function li(e){return typeof e=="string"&&e.startsWith("ARKORDER_")}a(li,"isArkOrderRuleId");function ci(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_")}a(ci,"isExtraPlaneFinding");function zd(e,t={}){if(!Array.isArray(e)||ke(t))return e;for(let n of e)ci(n)&&n.failsStrict!==!1&&(n.failsStrict=!1,n.severity==="error"&&(n.severity="warning"));return e}a(zd,"demoteExtraPlaneTeethUnderClassificationFloor");var di="Structure = heuristics; invariants = catalog+coverage evidence (not business runtime); ArkRun = kernel usage + declarations (not a score); ArkOrder = the few big product choices (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 Re(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):0}a(Re,"countOrZero");function An(e={}){let t=Hr(e.classification),n=typeof t.governedPercent=="number"?t.governedPercent:null,r=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null,o=n!=null||r!=null,s=ke(t),i=e.arkRules,l=Re(i?.structureEnforced),c=Re(i?.structureTotal),u=typeof i?.structureAdvisory=="number"?Re(i.structureAdvisory):Math.max(0,c-l),p=Re(i?.invariantEnforced),m=Re(i?.invariantTotal),f=typeof i?.invariantAdvisory=="number"?Re(i.invariantAdvisory):Math.max(0,m-p),g=l>0||p>0,d=e.arkRun?.present===!0,h=e.arkRun?.mode==="enforced"||e.arkRun?.mode==="advisory"?e.arkRun.mode:null,E=Re(e.arkRun?.residualCount),_=d&&h==="enforced",k=_&&s,b=e.arkOrder?.present===!0,O=e.arkOrder?.mode==="enforced"||e.arkOrder?.mode==="advisory"?e.arkOrder.mode:null,D=Re(e.arkOrder?.residualCount),S=b&&O==="enforced",L=S&&s,j=g||_||S,T=j&&s,M=j&&o&&!s,P;if(T){let z=[];g&&z.push("enforced structure/invariant findings"),_&&z.push("enforced ArkRun skip findings"),S&&z.push("enforced ArkOrder skip findings"),P=`Layer graph failures plus ${z.join(" and ")} (advisory extras never fail merge alone).`}else if(M)P=`Layer graph only \u2014 enforced ${[g?"ArkRules structure/invariant":null,_?"ArkRun":null,S?"ArkOrder":null].filter(fe=>!!fe).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.`;else{let z=d?h==="advisory"?" Advisory ArkRun never merge-blocks.":" ArkRun extra is present but does not arm merge teeth.":" Absence of arkRun is silent.",fe=b?O==="advisory"?" Advisory ArkOrder never merge-blocks.":" ArkOrder extra is present but does not arm merge teeth.":" Absence of arkOrder is silent.";P="Layer graph only \u2014 no enforced ArkRules structure/invariant teeth on this tree. Advisory packs do not arm merge teeth."+z+fe}let V={layers:{role:"inter-layer-edges",alwaysOnGate:!0,note:"Import/export layer graph \u2014 the default merge plane. Absent extras change 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:m,enforced:p,advisory:f,covered:Re(i?.covered),uncovered:Re(i?.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:d,mode:h,residualCount:E,extraMergeTeeth:k,note:d?h==="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."},arkOrder:{role:"pattern-slaving",present:b,mode:O,residualCount:D,extraMergeTeeth:L,note:b?O==="enforced"?"Enforced ArkOrder arms extra merge teeth only when the layer plane is classified. Residual is a count, never a score.":"Advisory ArkOrder never adds merge teeth and never flips valid. Residual is a count, never a score.":"Absence of arkOrder is silent \u2014 Layers verdicts unchanged. The extra never becomes a score."},extraMergeTeeth:T,dualPlaneStamp:di,failMergeWhen:P};return o&&(V.classificationGate={governedPercent:n,populatedLayerCount:r,floorPercent:50,allowsTeeth:s}),V}a(An,"composeMergePlanesHonesty");var pi=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"],Wd=["publisher","publish","raise","raiseAsync","send","sendTo","subscribe","registerHandler","resolve","resolveSingleton"],qd=new Set(pi),Yd=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"]),Jd=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/")}a(Mt,"isArkRunKernelModuleSpecifier");var fi=["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"],Kr=new Set(fi);function Gr(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(Kr.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(Kr.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:Kr.has(e.slice(0,r))}a(Gr,"isArkRunTransportBypassSpecifier");function Ur(e){if(qd.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}}a(Ur,"arkRunKernelCallKind");function Dt(e,t){let n=1;for(let r=0;r<t;r+=1)e.charCodeAt(r)===10&&(n+=1);return n}a(Dt,"lineAt");function Ft(e){return e.replace(/\/\*[\s\S]*?\*\//g,t=>t.replace(/[^\n]/g," ")).replace(/(^|[^:\\])\/\/.*$/gm,t=>t.replace(/\/\/.*$/,n=>" ".repeat(n.length)))}a(Ft,"stripCommentsPreservingLines");function Xd(e,t){let n=e.slice(t),r=/^\s*(['"])((?:\\.|[^\\])*?)\1/.exec(n);if(!r)return;let o=r[2]??"";return o.length>0?o:void 0}a(Xd,"firstStringLiteralArg");function ui(e,t,n){let r=Math.max(0,t-n.length-8),o=e.slice(r,t);return new RegExp(`\\b${n}\\s+$`).test(o)}a(ui,"keywordBefore");function Rn(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]??"")}a(Rn,"parseValueImportClause");function Zd(e,t){Rn(Ft(e),t)}a(Zd,"forEachArkRunValueImportClause");function Br(e,t){let n=Ft(t),r=[],o=/\b(?:import|export)(\s+type)?\s+([\s\S]*?)\s+from\s*['"]([^'"]+)['"]/g,s;for(;(s=o.exec(n))!==null;){let l=s[3]??"";if(!l)continue;let c=s[0]??"";r.push({from:e,specifier:l,kind:/^\s*export/.test(c)?"export":"import",typeOnly:!!s[1],line:Dt(t,s.index),resolution:"resolved-external"})}let i=/\b(?:require|import)\s*\(\s*['"]([^'"]+)['"]\s*\)/g;for(;(s=i.exec(n))!==null;){let l=s[1]??"";if(!l)continue;let c=s[0]?.startsWith("import")?"dynamic-import":"require";r.push({from:e,specifier:l,kind:c,typeOnly:!1,line:Dt(t,s.index),resolution:"resolved-external"})}return r}a(Br,"extractArkRunValueImportDependenciesFromSource");function zr(e){let t=[];return Zd(e,n=>{let r=/\{([^}]*)\}/.exec(n);if(r?.[1])for(let o of r[1].split(",")){let s=o.trim();if(!s||s.startsWith("type "))continue;let i=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(s),l=i?.[2]??/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(s)?.[1],c=i?.[1]??l;l&&c&&/^[A-Z]/.test(c)&&t.push(l,c)}}),Pt(t)}a(zr,"extractArkRunImportedConstructorNamesFromSource");function Qd(e){let t=new Map,n=new Set;return Rn(e,(r,o)=>{if(!Mt(o))return;let s=/\*\s+as\s+([A-Za-z_][A-Za-z0-9_]*)/.exec(r);s?.[1]&&n.add(s[1]);let i=/^([A-Za-z_][A-Za-z0-9_]*)\s*(?:,|$)/.exec(r.trim());i?.[1]&&t.set(i[1],i[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 p=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(u);if(p){t.set(p[2],p[1]);continue}let m=/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(u);m?.[1]&&t.set(m[1],m[1])}}),{named:t,namespaces:n}}a(Qd,"collectKernelImportBindings");function eu(e,t){let n=new Set(t);return Rn(e,(r,o)=>{let s=/\{([^}]*)\}/.exec(r);if(s?.[1])for(let i of s[1].split(",")){let l=i.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],p=c?.[1]??u;!u||!p||!/^[A-Z]/.test(p)||(Mt(o)||t.has(p)||t.has(u))&&(n.add(u),n.add(p))}}),n}a(eu,"collectImportedConstructors");function tu(e,t){let n;return Rn(e,(r,o)=>{!n&&new RegExp(`\\b${t}\\b`).test(r)&&(n=o)}),n}a(tu,"importedFromForName");function Wr(e,t){let n=Ft(t),r=Qd(n),o=[],s=/\b([A-Za-z_][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,i;for(;(i=s.exec(n))!==null;){let l=i[1],c=i.index;if(ui(n,c,"function")||ui(n,c,"class"))continue;let p=n.slice(0,c).match(/([A-Za-z_][A-Za-z0-9_]*)\s*\.\s*$/)?.[1],m=r.named.get(l)??l,f=Ur(m)??Ur(l);if(!f)continue;let g=r.named.has(l)||p!==void 0&&r.namespaces.has(p);if(f!=="factory"&&(!g&&p===void 0||p&&Jd.has(p)&&!g))continue;let d=Xd(n,c+i[0].length);o.push({file:e,line:Dt(t,c),kind:f,callee:l,viaImport:g,...p?{receiver:p}:{},...d?{nameLiteral:d}:{}})}return o}a(Wr,"extractArkRunKernelCallsFromSource");function qr(e,t,n){let r=Ft(t),o=eu(r,n),s=[],i=/\bnew\s+(?:[A-Za-z_][A-Za-z0-9_]*\s*\.\s*)*([A-Z][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,l;for(;(l=i.exec(r))!==null;){let c=l[1];if(Yd.has(c)||!o.has(c))continue;let u=tu(r,c);s.push({file:e,line:Dt(t,l.index),typeName:c,...u?{importedFrom:u}:{}})}return s}a(qr,"extractArkRunManagedNewsFromSource");function nu(e,t){let n=0,r;for(let o=t;o<e.length;o+=1){let s=e[o];if(r){if(s==="\\"){o+=1;continue}s===r&&(r=void 0);continue}if(s==="'"||s==='"'||s==="`"){r=s;continue}if(s==="[")n+=1;else if(s==="]"&&(n-=1,n===0))return o}return-1}a(nu,"matchingBracketEnd");function ru(e,t,n){let r=e.slice(t+1,n),o=[],s=/(['"])((?:\\.|[^\\])*?)\1/g,i;for(;(i=s.exec(r))!==null;){let l=i[2]??"";l.length>0&&o.push(l)}return o}a(ru,"stringLiteralsInList");function Pt(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}a(Pt,"uniqueSorted");function su(e,t){let n=Ft(t),r=/\b(uses|reactsTo|raises|sends)\s*:/g,o=[],s=[],i=[],l=[],c,u;for(;(u=r.exec(n))!==null;){let p=n.slice(u.index+u[0].length),m=/^\s*\[/.exec(p);if(!m)continue;let f=u.index+u[0].length+(m[0].length-1),g=nu(n,f);if(g<0)continue;let d=ru(n,f,g);if(d.length===0)continue;c===void 0&&(c=u.index);let h=u[1];h==="uses"?o.push(...d):h==="reactsTo"?s.push(...d):h==="raises"?i.push(...d):l.push(...d)}return c===void 0?[]:[{file:e,line:Dt(t,c),uses:Pt(o),reactsTo:Pt(s),raises:Pt(i),sends:Pt(l)}]}a(su,"extractArkRunDeclarationsFromSource");var ou=["arkrun-missing-root","arkrun-kernel-in-domain","arkrun-direct-new","arkrun-undeclared-emit","arkrun-undeclared-handle","arkrun-undeclared-depend","arkrun-transport-bypass"],iu=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],au=new Set(iu);function lu(e){return au.has(e)}a(lu,"isArkRunEditorSensor");var Yr={"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"},hi="ARKRUN_INTERACTION_NAME_INCOMPLETE";function yi(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 o=r.trim().replace(/\.+$/,"");return o==="Domain"||o.startsWith("Domain.")})}a(yi,"isDomainRoleLayer");function cu(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}a(cu,"compareFindings");function ve(e,t,n,r,o,s,i){let l=e.mode==="enforced"&&i;return{ruleId:Yr[t],sensor:t,message:o,file:n,line:r,...s?.fromLayer?{fromLayer:s.fromLayer}:{},...s?.target?{target:s.target}:{},severity:l?"error":"warning",failsStrict:l,nextAction:ye({ruleId:Yr[t],fromLayer:s?.fromLayer,target:s?.target})}}a(ve,"finding");function du(e,t){let n=[],r=[],o=[],s=[];for(let i of e)i.file===t&&(n.push(...i.uses),r.push(...i.reactsTo),o.push(...i.raises),s.push(...i.sends));return{uses:new Set(n),reactsTo:new Set(r),raises:new Set(o),sends:new Set(s)}}a(du,"bagForFile");function gi(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}a(gi,"emitKinds");function mi(e){return e==="subscribe"||e==="register-handler"}a(mi,"handleKinds");function uu(e){return e==="resolve"||e==="resolve-singleton"}a(uu,"dependKinds");function pu(e,t,n){let r=[],o=e.kernelRoots??e.compositionRoots;if(o.length===0)return r.push(ve(e,"arkrun-missing-root","ark.config.json",1,"ArkRun kernelRoots is empty; no createArkKernel factory site is declared.",void 0,n)),r;let s=new Map;for(let i of t){let l=s.get(i.matchedRoot)??[];l.push(i),s.set(i.matchedRoot,l)}for(let i of o){let l=[...s.get(i)??[]].sort((u,p)=>u.file.localeCompare(p.file));if(l.length===0){r.push(ve(e,"arkrun-missing-root","ark.config.json",1,`ArkRun kernel root ${JSON.stringify(i)} matched no governed files and has no createArkKernel factory.`,{target:i},n));continue}if(l.some(u=>u.hasKernelFactory))continue;let c=l[0];r.push(ve(e,"arkrun-missing-root",c.file,1,`ArkRun kernel root ${JSON.stringify(i)} has no createArkKernel / createStrictArkKernel factory.`,{target:i},n))}return r}a(pu,"evaluateMissingRoot");function fu(e,t,n,r,o){let s=new Map(t.map(l=>[l.name,l.intentPrefixes??[]])),i=[];for(let l of n){let c=l.specifier;if(!c||!Mt(c))continue;let u=r(l.from);u&&yi(u,s.get(u)??[])&&i.push(ve(e,"arkrun-kernel-in-domain",l.from,l.line,`${u} must not import kernel module ${JSON.stringify(c)}.`,{fromLayer:u,target:c},o))}return i}a(fu,"evaluateKernelInDomain");function gu(e,t,n,r,o,s){let i=new Set(e.managedLayers);if(i.size===0)return[];let l=new Map(t.map(p=>[p.name,p.intentPrefixes??[]])),c=new Set(r.filter(p=>p.hasKernelFactory).map(p=>p.file)),u=[];for(let p of n){if(c.has(p.file))continue;let m=p.typeName;if(e.ignoreDirectNewForErrors!==!1&&(m.endsWith("Error")||m==="Error")||m.endsWith("DTO")||m.endsWith("VO"))continue;let f=o(p.file);!f||!i.has(f)||yi(f,l.get(f)??[])||u.push(ve(e,"arkrun-direct-new",p.file,p.line,`${f} must not construct ${p.typeName} with new outside an ArkRun composition-root factory.`,{fromLayer:f,target:p.typeName},s))}return u}a(gu,"evaluateDirectNew");function mu(e,t,n,r,o){let s=[],i=[];if(e.requireDeclarations!==!0)return{findings:s,completenessReasons:i};let l=new Set(e.managedLayers);if(l.size===0)return{findings:s,completenessReasons:i};for(let c of t){if(!gi(c.kind)&&!mi(c.kind)&&!uu(c.kind))continue;let u=r(c.file);if(!u||!l.has(u))continue;if(!c.nameLiteral){e.mode==="enforced"&&i.push({code:hi,file:c.file,message:`ArkRun ${c.kind} call in ${c.file} has no string-literal name; enforced extra cannot prove the declaration.`});continue}let p=du(n,c.file);if(gi(c.kind)){if(p.raises.has(c.nameLiteral)||p.sends.has(c.nameLiteral))continue;s.push(ve(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},o));continue}if(mi(c.kind)){if(p.reactsTo.has(c.nameLiteral))continue;s.push(ve(e,"arkrun-undeclared-handle",c.file,c.line,`Handle ${JSON.stringify(c.nameLiteral)} is not declared in reactsTo.`,{fromLayer:u,target:c.nameLiteral},o));continue}p.uses.has(c.nameLiteral)||s.push(ve(e,"arkrun-undeclared-depend",c.file,c.line,`Depend ${JSON.stringify(c.nameLiteral)} is not declared in uses.`,{fromLayer:u,target:c.nameLiteral},o))}return{findings:s,completenessReasons:i}}a(mu,"evaluateUndeclared");function hu(e,t,n,r){let o=new Set(e.managedLayers);if(o.size===0)return[];let s=[];for(let i of t){if(i.typeOnly)continue;let l=i.specifier;if(!l||!Gr(l))continue;let c=n(i.from);!c||!o.has(c)||s.push(ve(e,"arkrun-transport-bypass",i.from,i.line,`${c} must not import broker/queue/emitter ${JSON.stringify(l)}; use the ArkRun kernel transport.`,{fromLayer:c,target:l},r))}return s}a(hu,"evaluateTransportBypass");function kn(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=ke(e.classification),r=mu(t,e.kernelCalls,e.declarations,e.layerForFile,n),o=[...pu(t,e.compositionRootHits,n),...fu(t,e.layers,e.dependencies,e.layerForFile,n),...gu(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...hu(t,e.dependencies,e.layerForFile,n)].sort(cu),s=[...r.completenessReasons].sort((i,l)=>{let c=`${i.code}\0${i.file??""}\0${i.message}`,u=`${l.code}\0${l.file??""}\0${l.message}`;return c<u?-1:c>u?1:0});return{findings:o,completenessReasons:s}}a(kn,"evaluateArkRunSensors");function Ai(e){return{findings:kn(e).findings.filter(n=>lu(n.sensor)),completenessReasons:[]}}a(Ai,"evaluateArkRunEditorSensors");function yu(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}/`))}a(yu,"fileMatchesCompositionRoot");function Au(e,t,n){let r=Wr(t,n).some(i=>i.kind==="factory"),o=[],s=e.kernelRoots??e.compositionRoots;for(let i of s)yu(i,t)&&o.push({file:t,matchedRoot:i,hasKernelFactory:r});return o}a(Au,"compositionRootHitsForSource");function Ru(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=new Set(zr(e.source));return Ai({arkRun:t,layers:e.layers,kernelCalls:[],managedNews:qr(e.file,e.source,n),compositionRootHits:Au(t,e.file,e.source),declarations:[],dependencies:Br(e.file,e.source),layerForFile:e.layerForFile,classification:e.classification})}a(Ru,"evaluateArkRunEditorSensorsFromSource");function Ri(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}a(Ri,"isArkOrderModuleSpecifier");var ki=new Map;function Si(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(Si,"escapeAppliesToLiteral");function ku(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let o=e[n+1];if("*?{}[],".includes(o)||o==="\\"){t+="\\"+o,n+=1;continue}t+="/";continue}t+=r}return t}a(ku,"normalizeAppliesToGlob");function Su(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}a(Su,"appliesToBracesBalanced");function Iu(e){let t=ki.get(e);if(t)return t;let n=ku(e),r=Su(n),o="",s=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(o+=Si(n[l+1]),l+=1):c==="*"?n[l+1]==="*"?n[l+2]==="/"?(o+="(?:.*/)?",l+=2):(o+=".*",l+=1):o+="[^/]*":c==="?"?o+="[^/]":c==="{"&&r?(o+="(?:",s+=1):c==="}"&&r&&s>0?(o+=")",s-=1):c===","&&r&&s>0?o+="|":o+=Si(c)}let i=new RegExp(`^${o}$`);return ki.set(e,i),i}a(Iu,"globToRegExp");var Eu=["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"],Jr={"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 bu(e,t){return!t||t.length===0?!0:t.some(n=>Iu(n).test(e))}a(bu,"matchesArkOrderAppliesTo");function vu(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)?!0:t.some(r=>{let o=r.trim().replace(/\.+$/,"");return o==="Domain"||o.startsWith("Domain.")})}a(vu,"isDomainRoleLayer");function we(e,t,n,r,o,s,i){let l=e.mode==="enforced"&&i;return{ruleId:Jr[t],sensor:t,message:o,file:n,line:r,...s?.fromLayer?{fromLayer:s.fromLayer}:{},...s?.target?{target:s.target}:{},severity:l?"error":"warning",failsStrict:l,nextAction:ye({ruleId:Jr[t],fromLayer:s?.fromLayer,target:s?.target})}}a(we,"finding");function Xr(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let n=ke(e.classification),r=[],o=t.planeRoots;if(t.mode==="enforced"&&o.length===0)r.push(we(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 p=c.get(u.matchedRoot)??[];p.push(u),c.set(u.matchedRoot,p)}for(let u of o){let p=c.get(u)??[];if(p.length===0){r.push(we(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}p.some(m=>m.hasPlaneFactory)||r.push(we(t,"arkorder-missing-plane",p[0].file,1,`ArkOrder plane root ${JSON.stringify(u)} has no createOrderPlane factory.`,{target:u},n))}}let s=new Map(e.layers.map(c=>[c.name,c.intentPrefixes??[]]));for(let c of e.dependencies){let u=c.specifier;if(!u||!Ri(u))continue;let p=e.layerForFile(c.from);p&&vu(p,s.get(p)??[])&&r.push(we(t,"arkorder-kernel-in-domain",c.from,c.line,"Domain-role layer imports arkgate/order; Domain stays plane-free.",{fromLayer:p,target:u},n))}for(let c of e.genericUpdates)r.push(we(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 i=t.xiKeys??[];for(let c of e.releaseKeyCounts??[])c.keyCount<=t.maxXiKeys||r.push(we(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(we(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 i.length===0?[]:e.xiFieldWrites??[]){let u=e.layerForFile(c.file);!u||!l.has(u)||bu(c.file,t.appliesTo)&&r.push(we(t,"arkorder-xi-field-write",c.file,c.line,`This file writes ${JSON.stringify(c.key)} the same way it would write a seat count. Take the event in, or change that choice through the valve (propose, then apply).`,{fromLayer: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:[]}}a(Xr,"evaluateArkOrderSensors");function te(e,t,n={}){return{ruleId:e,message:t,...n}}a(te,"configWarning");function Sn(e){let{config:t,rules:n,files:r,manifest:o}=e,s=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(d=>typeof d!="string"))&&s.push(te("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)))s.push(te("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let d of["maxTsSuppressions","maxAnyCasts"]){let h=t.safety[d];h!==void 0&&(!Number.isInteger(h)||h<0)&&s.push(te("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${d} must be a non-negative integer.`))}let i=Array.isArray(t.layers)?t.layers:[],l=Array.isArray(o?.architecture?.layers)?o.architecture.layers:[],c=new Set([...i.map(d=>d.name).filter(Boolean),...l.map(d=>d.name).filter(d=>!!d)]);i.length===0&&s.push(te("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let u=new Set,p=new Set;for(let d of i){if(!d.name){s.push(te("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}u.has(d.name)&&p.add(d.name),u.add(d.name),d.forbiddenGlobals!==void 0&&(!Array.isArray(d.forbiddenGlobals)||d.forbiddenGlobals.some(E=>typeof E!="string"))&&s.push(te("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${d.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:d.name}));let h=Array.isArray(d.patterns)?d.patterns:[];if(h.length===0){s.push(te("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${d.name}" has no file patterns and will never classify files.`,{layer:d.name}));continue}for(let E of h){let _;try{_=Ae(E)}catch(b){s.push(te("CONFIG_INVALID_LAYER_PATTERN",`Layer "${d.name}" has an invalid pattern "${E}": ${b instanceof Error?b.message:String(b)}`,{layer:d.name,pattern:E}));continue}let k=d.optional===!0||d.reserved===!0||d.allowEmpty===!0;!r.some(b=>_.test(b))&&!k&&s.push(te("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${d.name}" pattern "${E}" matched no included files (possible typo). Mark the layer reserved/allowEmpty if this house is reserved for later.`,{layer:d.name,pattern:E,failsStrict:!1,reserved:!1}))}}for(let d of p)s.push(te("CONFIG_DUPLICATE_LAYER",`Layer "${d}" is configured more than once.`,{layer:d}));if(c.size>0)for(let d of n??[])d.from&&!c.has(d.from)&&s.push(te("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${d.from}".`,{fromLayer:d.from,toLayer:d.to})),d.to&&!c.has(d.to)&&s.push(te("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${d.to}".`,{fromLayer:d.from,toLayer:d.to}));let m=new Set;if(i.length>1)for(let d of r){let h=-1,E=[];for(let _ of i)for(let k of _.patterns??[]){if(!Ae(k).test(d))continue;let b=Gn(k,d);b>h?(h=b,E=[_.name]):b===h&&!E.includes(_.name)&&E.push(_.name)}E.length>1&&m.add([...E].sort().join(" + "))}m.size>0&&s.push(te("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...m].join(", ")}.`,{pairs:[...m]}));let f=r.filter(d=>!ge(d,i));f.length>0&&s.push(te("CONFIG_UNCLASSIFIED_FILES",`${f.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:f.length,samples:f.slice(0,5)}));for(let d of Ls(n))s.push(te("CONFIG_SLICE_IDENTITY_COLLISION",d.message,{paths:[...d.paths],fromLayer:d.from,toLayer:d.to,failsStrict:!1}));for(let d of Ms(n,r))s.push(te(d.ruleId,d.message,{failsStrict:!1,...d.path?{file:d.path}:{},...d.fromLayer?{fromLayer:d.fromLayer}:{},...d.toLayer?{toLayer:d.toLayer}:{}}));let g=lo(t);if(g.length>0){let d=g[0]??"this layer";s.push(te("CONFIG_LAYER_MISSING_OWNER",`${d} has no owner. Add a GitHub handle or email to layers[].owners so this house has a name on the door.`,{layers:g,nextAction:co(d)}))}return s}a(Sn,"collectAnalysisConfigWarnings");function Ii(e,t){let n=e.ruleId==="ARKRULE_STRUCTURE",r=e.ruleId==="ARKRULE_SCOPE_EMPTY",o=e.ruleId==="INVARIANT_CATALOG_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:Yo({sensor:e.sensor,code:e.code})}:{},...r||o?{freezable:!1}:{},nextAction:t}}a(Ii,"toArkRuleEngineViolation");function Cu(e){let t=e.arkRules;return!!(t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0)}a(Cu,"arkRulesMapIsOn");function Ei(e,t){return e.ruleId==="INVARIANT_CATALOG_EMPTY"?t?`Add 1\u20132 short phrases to invariants[] in ${e.arkruleSource} so Domain has policies the code must preserve (advisory \u2014 does not fail the merge until a domain structure rule is enforced).`:`Add 1\u20132 short phrases to invariants[] in ${e.arkruleSource} so Domain has policies the code must preserve. Empty catalog fails --strict-merge because a domain structure rule is already enforced.`:e.ruleId==="ARKRULE_SCOPE_EMPTY"?t?`Review appliesTo for ${e.arkruleId} in ${e.arkruleSource} (zero-match scope; advisory). Empty scope is not freezable; promote only after the folder exists.`:`Fix appliesTo globs for ${e.arkruleId} in ${e.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.`:t?`Review ArkRule ${e.arkruleId} in ${e.arkruleSource} (advisory).`:`Fix the structure or invariant for ${e.arkruleId} (declared in ${e.arkruleSource}), then preflight again.`}a(Ei,"arkRuleFindingNextAction");function _u(e,t){return t.some(n=>{try{return Ae(n).test(e)}catch{return!1}})}a(_u,"matchesAny");function Ou(e,t){let n=e.contract.config.safety??{},r=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,o=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,s=e.contract.config.dynamicImportAllowlist??[],i=t.safetyUses.filter(h=>h.kind==="ts-suppression").map(({file:h,line:E})=>({file:h,line:E})),l=t.safetyUses.filter(h=>h.kind==="any-cast").map(({file:h,line:E})=>({file:h,line:E})),c=t.safetyUses.filter(h=>(h.kind==="dynamic-import"||h.kind==="dynamic-require")&&!_u(h.file,s)).map(h=>({file:h.file,line:h.line,kind:h.kind==="dynamic-require"?"require":"import"})),u=n.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(h=>h.kind==="in-memory-store").map(h=>({file:h.file,line:h.line,store:h.symbol??"in-memory store"})),p=n.allowDisabledPeerIsolation===!0?[]:(e.contract.config.rules??[]).filter(h=>h.peerIsolation===!1||h.allowed===!1&&!!h.from&&h.from===h.to&&h.peerIsolation!==!0).map(h=>({from:h.from,to:h.to})),m={tsSuppressions:i,anyCasts:l,nonLiteralDynamicImports:c,inMemoryProductionStores:u,disabledPeerIsolationRules:p,thresholds:{maxTsSuppressions:r,maxAnyCasts:o}},f=[],g=c.filter(h=>h.kind==="import");if(g.length>0){let h=g[0];f.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:h.file,line:h.line,message:`${g.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let d=c.filter(h=>h.kind==="require");if(d.length>0){let h=d[0];f.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:h.file,line:h.line,message:`${d.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(i.length>r){let h=i[0];f.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:h.file,line:h.line,message:`${i.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${r}).`})}if(l.length>o){let h=l[0];f.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:h.file,line:h.line,message:`${l.length} explicit any cast(s) exceed safety.maxAnyCasts (${o}).`})}if(u.length>0){let h=u[0];f.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:h.file,line:h.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 p.length>0&&f.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${p.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:m,warnings:f}}a(Ou,"evaluateSafety");function xu(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}a(xu,"ambientForbiddenGlobal");function bi(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return Zn(e,n.length>0?n:Xn.map(r=>({name:r.layer,prefixes:r.prefixes})))}a(bi,"intentLayer");function Tu(e,t,n){let r=[],o=new Map(e.contract.config.layers.map(s=>[s.name,s]));for(let s of t.ambientUses){let i=n.get(s.file);!i||!xu(s.symbol,o.get(i)?.forbiddenGlobals??[])||r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:i,target:s.symbol,message:`${i} must not use the ambient global "${s.symbol}".`})}for(let s of t.capabilityUses){let i=n.get(s.file);if(!i)continue;let l=o.get(i),c=l?.forbiddenGlobals??[],u=s.source==="import-based"?t.dependencies.find(p=>p.from===s.file&&p.line===s.line&&p.specifier===s.symbol&&!p.typeOnly)?.kind:void 0;if(!(s.source==="ambient-global"&&gt(s.symbol,c))){if(s.source==="import-based"){let p=_e(s.symbol,c);if(p){r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:i,target:s.symbol,...u?{edgeKind:u}:{},message:`${i} must not use module "${s.symbol}" because it is the import form of forbidden global "${p}".`});continue}}Ge(l).includes(s.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:s.file,line:s.line,fromLayer:i,target:s.symbol,capability:s.capability,...u?{edgeKind:u}:{},message:s.source==="import-based"?`${i} denies the ${s.capability} capability; found import of "${s.symbol}".`:`${i} denies the ${s.capability} capability; found ambient "${s.symbol}".`})}}for(let s of t.publishCalls){let i=n.get(s.file);if(!i)continue;for(let c of At({publishCall:!0,rawIntentName:s.rawIntentName,objectHasIntent:s.objectHasIntent,arkPublishCandidate:s.arkPublishCandidate,hasSource:s.hasSource}))r.push({ruleId:c.ruleId,file:s.file,line:s.line,...c.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:i}:{},message:c.message});if(!s.sourceIntent)continue;let l=bi(s.sourceIntent,e.contract);!l||l===i||r.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:s.file,line:s.line,fromLayer:i,toLayer:l,target:s.sourceIntent,message:`Publish source "${s.sourceIntent}" resolves to ${l}, but the publishing file is classified as ${i}.`})}for(let s of t.intentReferences){let i=n.get(s.file);if(!i)continue;let l=bi(s.intent,e.contract);if(!l)continue;let c=Oe(e.contract.config.rules,i,l,{fromPath:s.file,layers:e.contract.config.layers});if(!c)continue;let u=c.sliceVerdict,p=`${i} must not reference ${l} intent ${s.intent}.`,m=u?ze({surface:"intent",verdict:u,fromLayer:i,toLayer:l,fromPath:s.file,ruleMessage:c.rule.message,defaultMessage:p}):c.rule.message??p;r.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:s.file,line:s.line,fromLayer:i,toLayer:l,target:s.intent,...c.rule.peerIsolation?{peerIsolation:!0}:{},...Ne(u),message:m})}return r}a(Tu,"contentViolations");function wu(e){let{facts:t}=e,n=vt(e.contract.config),r=t.evidenceRequirementsHash===n,o=r?t.completeness:"unavailable",s=r?t.completenessReasons:[...t.completenessReasons,{code:"EVIDENCE_REQUIREMENTS_MISMATCH",message:"Resolved facts were collected for different policy-controlled evidence requirements."}].sort((A,ie)=>{let ct=`${A.code}\0${A.file??""}\0${A.message}`,dt=`${ie.code}\0${ie.file??""}\0${ie.message}`;return ct<dt?-1:ct>dt?1:0}),i=t.files.map(A=>({...A,layer:ge(A.path,e.contract.config.layers)??null})),l=new Map(i.map(A=>[A.path,A.layer])),c=t.dependencies.map(A=>{let ie=A.target?l.get(A.target)??ge(A.target,e.contract.config.layers):void 0;return{from:A.from,fromLayer:l.get(A.from)??null,...A.resolution==="resolved-project"&&A.target?{to:A.target,...ie?{toLayer:ie}:{}}:{},line:A.line,kind:A.kind,typeOnly:A.typeOnly,...A.targetTypeOnlyExports?{targetTypeOnlyExports:A.targetTypeOnlyExports}:{},...A.sourcePureTypeModule?{sourcePureTypeModule:A.sourcePureTypeModule}:{},...A.namedBindingsTypeOnly?{namedBindingsTypeOnly:A.namedBindingsTypeOnly}:{},...A.portProofEligible?{portProofEligible:A.portProofEligible}:{}}}),u=Sn({config:e.contract.config,rules:e.contract.config.rules,files:i.map(A=>A.path)}),p=Ou(e,t),m=e.contract.arkRules??He(),f=i.map(A=>A.path),d={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?$r(e.coverageInputs.fileContents):{},...e.fileHints??{}},h=a(A=>l.get(A)??ge(A,e.contract.config.layers),"resolveLayer"),E=[...Mr({arkRules:m,classShapes:e.contract.classShapes??t.classShapes??[],files:f,layerForFile:h,fileHints:d}),...Fr(m,f),...ii({arkRulesActive:Cu(e.contract.config),arkRules:m,layers:e.contract.config.layers??[],files:f.map(A=>({path:A,layer:h(A)}))})],_=(m.invariants?.length??0)>0,k=No({hasEnforcedInvariant:kr(m.invariants),coverage:e.contract.config.coverage,...e.coverageRootsPresent===!1?{declaredPathPresent:!1}:{}}),b=k.length>0?[]:wo({adopted:e.adopted===!0,hasDomainInvariants:Rr(m.invariants),coverage:e.contract.config.coverage,...e.invariantTestsPathPresent===!1?{declaredPathPresent:!1}:{}}),O=[...k.map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,nextAction:"Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. An enforced invariant fails closed until that path is present.",failsStrict:!0,freezable:!1})),...b.map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,nextAction:"Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present.",failsStrict:!0,freezable:!1}))],D=E.filter(A=>A.failsStrict).map(A=>Ii(A,Ei(A,!1))),S=E.filter(A=>!A.failsStrict).map(A=>({...Ii(A,Ei(A,!0)),failsStrict:!1})),L=_?yr({arkRules:m,fileContents:e.coverageInputs?.fileContents??{},testFiles:e.coverageInputs?.testFiles??[],testGlobsMissing:e.coverageInputs?.testGlobsMissing===!0||e.coverageInputs===void 0||(e.coverageInputs.testFiles?.length??0)===0,coverageBudgetExhausted:e.coverageInputs?.coverageBudgetExhausted===!0,...e.coverageInputs?.stats?{coverageStats:e.coverageInputs.stats}:{},...e.coverageInputs?.coverageRoots?{coverageRoots:e.coverageInputs.coverageRoots}:{}}):{coverage:[],violations:[],partial:!1},j=L.violations.filter(A=>A.failsStrict).map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,arkruleId:A.arkruleId,arkruleSource:A.arkruleSource,nextAction:`Add a test title or declared symbol covering ${A.arkruleId} (declared in ${A.arkruleSource}), then preflight again.`})),T=L.violations.filter(A=>!A.failsStrict).map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,arkruleId:A.arkruleId,arkruleSource:A.arkruleSource,failsStrict:!1,nextAction:A.ruleId==="INVARIANT_COVERAGE_OUTSIDE_ROOTS"?`Move ${A.file} under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json.`:`Cover invariant ${A.arkruleId} in ${A.arkruleSource} (advisory / partial).`})),M=jr(i),P=kn({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:a(A=>l.get(A)??ge(A,e.contract.config.layers),"layerForFile"),classification:M}),V=e.contract.config.arkRun?.mode,z=P.findings.filter(()=>V==="enforced").map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,target:A.target,nextAction:A.nextAction,sensor:A.sensor,failsStrict:A.failsStrict,...A.severity?{severity:A.severity}:{}})),fe=P.findings.filter(()=>V!=="enforced").map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,target:A.target,nextAction:A.nextAction,sensor:A.sensor,failsStrict:!1})),Se=Xr({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:a(A=>l.get(A)??ge(A,e.contract.config.layers),"layerForFile"),classification:M}),lt=e.contract.config.arkOrder?.mode,Ut=Se.findings.filter(()=>lt==="enforced").map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,target:A.target,nextAction:A.nextAction,sensor:A.sensor,failsStrict:A.failsStrict,...A.severity?{severity:A.severity}:{}})),Rs=Se.findings.filter(()=>lt!=="enforced").map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,target:A.target,nextAction:A.nextAction,sensor:A.sensor,failsStrict:!1})),v=[...L.partial&&L.coverage.some(A=>A.mode==="enforced"&&A.partial)?[{code:"INVARIANT_COVERAGE_PARTIAL",message:"Enforced ArkRules invariant coverage cannot be fully proven (missing test globs or empty test set); reporting partial, never covered."}]:[],...P.completenessReasons,...Se.completenessReasons],x=st({config:e.contract.config,rules:e.contract.config.rules,files:i.filter(A=>A.layer).map(A=>A.path),contentViolations:[...Tu(e,t,l),...D,...O,...j,...z,...Ut],edges:c,warnings:[...u,...p.warnings,...S,...T,...fe,...Rs],safety:p.report}),y=o==="complete"&&v.length>0?"partial":o,R=y==="complete"?s:[...s,...v].sort((A,ie)=>{let ct=`${A.code}\0${A.file??""}\0${A.message}`,dt=`${ie.code}\0${ie.file??""}\0${ie.message}`;return ct<dt?-1:ct>dt?1:0}),F=x.violations.filter(A=>A.failsStrict!==!1),Q=y==="complete"&&F.length===0,Ce=Q&&x.warnings.every(A=>A.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:y,completenessReasons:R,valid:Q,strictValid:Ce,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:p.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:i,layers:e.contract.config.layers.map(A=>A.name),edges:c,capabilityUses:t.capabilityUses,violations:x.violations,warnings:x.warnings}}}a(wu,"analyzeCanonicalResolvedProject");function $t(e){return wu({contract:e.contract,facts:xe(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints,adopted:e.adopted,invariantTestsPathPresent:e.invariantTestsPathPresent,coverageRootsPresent:e.coverageRootsPresent})}a($t,"analyzeResolvedProject");function vi(e){return ee(K(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}a(vi,"analysisTreeHash");function Ci(e){let t=Nt(e),n=new Map(t.ir.files.map(d=>[d.path,d])),r=[],o=new Set,s=[];for(let d of e.changes){let h=d.path.replace(/\\/g,"/"),E=je(d.path);if(!E||E===".."||E.startsWith("../")||h.startsWith("/")||/^[A-Za-z]:\//.test(h)||h.includes("\0")){s.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(o.has(E)){s.push({ruleId:"DUPLICATE_CHANGE_PATH",file:E,line:1,message:`The atomic change set contains more than one operation for ${E}.`});continue}o.add(E),"delete"in d&&d.delete&&!n.has(E)&&s.push({ruleId:"DELETE_TARGET_MISSING",file:E,line:1,message:`Cannot delete ${E} because it is not present in the supplied base tree.`}),r.push("delete"in d&&d.delete?{path:E,delete:!0}:{path:E,content:"content"in d?d.content:""})}e.changes.length===0&&s.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let i=gn({...e,changes:r}),l=new Map(i.ir.files.map(d=>[d.path,d])),c=i.ir.violations.filter(d=>d.ruleId==="CAPABILITY_VIOLATION"||d.ruleId==="FORBIDDEN_GLOBAL").map(d=>{let h=l.get(d.evidence.file)?.layer;return{ruleId:d.ruleId,file:d.evidence.file,line:d.evidence.line,target:d.symbol,...d.capability?{capability:d.capability}:{},...h?{fromLayer:h}:{},edgeKind:"import",message:d.message}}),u=st({config:e.contract.config,rules:e.contract.config.rules,files:i.ir.files.map(d=>d.path),contentViolations:c,edges:i.ir.edges.filter(d=>!!d.fromLayer).map(d=>({from:d.from,fromLayer:d.fromLayer,...d.to?{to:d.to}:{},...d.toLayer?{toLayer:d.toLayer}:{},line:d.evidence.line,kind:"import",...d.typeOnly?{typeOnly:!0}:{},...d.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),p=r.map(d=>{let h=je(d.path),E=n.get(h),_=l.get(h);return{path:h,operation:"delete"in d&&d.delete?"delete":E?"update":"create",...E?{beforeContentHash:E.contentHash}:{},..._?{candidateContentHash:_.contentHash}:{}}}).sort((d,h)=>d.path.localeCompare(h.path)),m=[...s,...u.violations].map(d=>({...d,nextAction:ye(d)})),f=m.filter(d=>d.failsStrict!==!1),g=e.changeMap?tt({changeMap:e.changeMap,changes:p,baseDependencies:t.ir.edges.flatMap(d=>d.to?[{from:d.from,to:d.to}]:[]),candidateDependencies:i.ir.edges.flatMap(d=>d.to?[{from:d.from,to:d.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&i.valid&&f.length===0&&(g?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:i.ir.compilerOptionsHash,baseTreeHash:vi(t.ir.files),candidateTreeHash:vi(i.ir.files),baseCompleteness:t.completeness,candidateCompleteness:i.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:i.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...g?{convergence:g}:{},changes:p,violations:m,warnings:u.warnings}}a(Ci,"preflightChange");function Nu(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let o of t.split("/"))if(!(!o||o==="."))if(o===".."){if(n.length===0)return;n.pop()}else n.push(o);let r=n.join("/");return r&&r===t?r:void 0}a(Nu,"canonicalChangePath");function Lu(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,o])=>r!==o).map(([r,o,s])=>({ruleId:"FACTS_IDENTITY_MISMATCH",file:"<change-set>",line:1,field:r,before:o,candidate:s,message:`Base and candidate facts must use the same ${r}.`}))}a(Lu,"identityViolations");function Pu(e,t,n,r){let o=n.get(t),s=r.get(t);return{path:t,operation:"delete"in e&&e.delete?"delete":o?"update":"create",...o?{beforeContentHash:o.contentHash}:{},...s?{candidateContentHash:s.contentHash}:{}}}a(Pu,"preparedChange");function _i(e){let t=xe(e.baseFacts),n=xe(e.candidateFacts),r=$t({contract:e.contract,facts:t}),o=$t({contract:e.contract,facts:n}),s=new Map(t.files.map(g=>[g.path,g])),i=new Map(n.files.map(g=>[g.path,g])),l=Lu(t,n),c=new Map,u=[];for(let g of e.changes){let d=Nu(g.path);if(!d){l.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(c.has(d)){l.push({ruleId:"DUPLICATE_CHANGE_PATH",file:d,line:1,message:`The atomic change set contains more than one operation for ${d}.`});continue}c.set(d,g);let h=s.get(d),E=i.get(d);if("delete"in g&&g.delete)h||l.push({ruleId:"DELETE_TARGET_MISSING",file:d,line:1,message:`Cannot delete ${d} because it is not present in the supplied base facts.`}),E&&l.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:d,line:1,message:`Candidate facts still contain deleted file ${d}.`});else{let _="content"in g?g.content:"",k=ee(_);E?E.contentHash!==k&&l.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:d,line:1,expectedContentHash:k,candidateContentHash:E.contentHash,message:`Candidate facts for ${d} do not match the declared content.`}):l.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:d,line:1,message:`Candidate facts do not contain changed file ${d}.`})}u.push(Pu(g,d,s,i))}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 g of new Set([...s.keys(),...i.keys()])){if(c.has(g))continue;let d=s.get(g),h=i.get(g);d&&h&&K(d)===K(h)||l.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:g,line:1,message:`Candidate facts change ${g}, but the atomic change set does not declare it.`})}let p=e.changeMap?tt({changeMap:e.changeMap,changes:u,baseDependencies:r.ir.edges.flatMap(g=>g.to?[{from:g.from,to:g.to}]:[]),candidateDependencies:o.ir.edges.flatMap(g=>g.to?[{from:g.from,to:g.to}]:[])}):void 0,m=[...l,...o.ir.violations].map(g=>({...g,nextAction:ye(g)})),f=m.filter(g=>g.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&o.strictValid&&f.length===0&&(p?.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:o.completeness,baseCompletenessReasons:r.completenessReasons,candidateCompletenessReasons:o.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...p?{convergence:p}:{},changes:u.sort((g,d)=>g.path<d.path?-1:g.path>d.path?1:0),violations:m,warnings:o.ir.warnings}}a(_i,"preflightResolvedChange");var Oi="1.0",Du=12,Mu="Layers stop a bad import. ArkRun is an optional experimental runtime \u2014 in-memory, not Postgres. Data is gone on restart.",Fu="Next: /ark-runtime to wire one candidate.";function xi(e){return e==="enforced"||e==="advisory"?e:null}a(xi,"closedMode");function $u(e){let t=new Set;if(!Array.isArray(e))return[];for(let n of e){let r=n?.ruleId;typeof r!="string"||!Vr(r)||t.has(r)||t.add(r)}return[...t].sort((n,r)=>n<r?-1:n>r?1:0)}a($u,"uniqueArkRunRuleIds");function Hu(e){return!e||typeof e!="object"?{present:!1,mode:null,roots:0,layers:0,requireDeclarations:null}:{present:!0,mode:xi(e.mode),roots:Array.isArray(e.compositionRoots)?e.compositionRoots.length:0,layers:Array.isArray(e.managedLayers)?e.managedLayers.length:0,requireDeclarations:e.requireDeclarations===!0}}a(Hu,"extraFromConfig");function ju(e={}){let t=Hu(e.arkRun),n=t.present?$u(e.findings):[],r=n.slice(0,Du),o=n.length,s=An({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:o}}),i=t.present&&t.mode==="enforced"&&ke(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.":i?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:Oi,notAScore:!0,active:t.present,mode:t.mode,compositionRoots:t.roots,managedLayers:t.layers,requireDeclarations:t.requireDeclarations,residual:{count:o,ruleIds:r},extraMergeTeeth:i,failMergeWhen:s.failMergeWhen,note:l,mergePlanes:s}}a(ju,"summarizeArkRunSection");function Zr(e={}){let t=e.present===!0,n=xi(e.mode),r=e.residual,o=null;return typeof r=="number"&&Number.isFinite(r)&&r>=0&&(o=Math.floor(r)),t||(o=o??0),{notAScore:!0,present:t,mode:t?n:null,extraMergeTeeth:t&&n==="enforced"&&e.extraMergeTeeth===!0,residual:o}}a(Zr,"projectStatusArkRun");function Vu(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=[Mu,`mode: ${t} \xB7 extra merge teeth ${n} \xB7 not a score`];if(e.residual.count>0){let o=e.residual.ruleIds.join(", "),s=e.residual.count>e.residual.ruleIds.length?` (+${e.residual.count-e.residual.ruleIds.length} more)`:"";r.push(`Residual: ${o}${s}`),r.push(Fu)}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}a(Vu,"formatArkRunDoctorLines");function In(e,t){return e.slice(0,t).split(`
20
+ `).length}a(In,"lineOf");function Ti(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}a(Ti,"normalizeInventoryPath");function Ni(e,t){return e.some(n=>{let r=n.trim().replace(/\.+$/,"");return t.some(o=>r===o||r.startsWith(`${o}.`))})}a(Ni,"ownsIntent");function wi(e,t=[]){return/domain|entity|aggregate|model/i.test(e)||Ni(t,["Domain"])}a(wi,"isDomainLayer");function Ku(e,t=[]){return/application|orchestration|presentation|adapter|framework|interface|delivery|transport|inbound|controller/i.test(e)||Ni(t,["Application","Orchestration","Presentation","Adapter","Interface","Delivery","Transport"])}a(Ku,"isControllerEligibleLayer");function Uu(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)}a(Uu,"isNonPilotSurface");function Gu(e){let t=[],n=0,r=new Map(Object.entries(e.fileLayers??{}).map(([c,u])=>[Ti(c),u])),o=new Map((e.layerContexts??[]).map(c=>[c.name,c.intentPrefixes??[]])),s=(e.layerContexts??[]).find(c=>wi(c.name,c.intentPrefixes))?.name??"DomainModel";for(let[c,u]of Object.entries(e.fileContents).sort(([p],[m])=>p.localeCompare(m))){let p=Ti(c);if(Uu(p)||/GENERATED FILE\s+[—-]\s+do not edit by hand/i.test(u.slice(0,320)))continue;let m=r.has(p),f=r.get(p),g=f?o.get(f)??[]:[],d=/(?:^|\/)(?:components|ui|layouts|styles|hooks|theme|tokens|i18n|locales?)(?:\/|$)/i.test(p)||/(?:^|\/)(?:src\/)?(?:app|pages)\/.+\.(?:tsx|jsx)$/i.test(p)&&/(?:page|layout|loading|error|template|default)\.(?:tsx|jsx)$/i.test(p),h=/(?:^|\/)(?:app|pages)(?:\/[^/]+)*\/api(?:\/|$)/i.test(p),E=/(?:^|\/)actions?(?:\/|\.|$)/i.test(p)||/['"]use server['"]/.test(u),_=/controller|handler|resolver/i.test(c)||h||E||/route\.(?:ts|js|tsx|jsx)$/i.test(p)&&!d||/@(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),k=m?!!(f&&Ku(f,g)&&_):_,b=m?!!(f&&wi(f,g)):/domain|entity|aggregate|model/i.test(c),O=!m||b||k;if(k&&!d){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,M;for(;(M=T.exec(u))!==null;)n+=1,t.push({id:`inv-val-${n}`,kind:"validation-in-controller",file:c,line:In(u,M.index),message:"Business validation appears in a controller/handler \u2014 extract an invariant or Domain rule.",confidence:"direct-evidence",governedLayer:f,suggestedArkRule:{layer:s,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,S,L=a(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"),j=a((T,M)=>{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 P=M.replace(/^['"]|['"]$/g,"");return!!(/^['"]/.test(M)&&(/\s/.test(P)||/[.!?…]$/.test(P))&&!/^(?:STATUS|STATE|PHASE|ROLE|TYPE|KIND|ORDER|PAYMENT|CART|INVOICE|POLICY)_[A-Z0-9_]+$/i.test(T))},"isUxMessageConstant");for(;(S=D.exec(u))!==null;){let T=S[2],M=S[3]??"";!O||L(T)||j(T,M)||d&&!b||/(?:^|\/)(?:integrations?|repos?|clients?|infra(?:structure)?|adapters?)(?:\/|$)/i.test(p)&&!b||(n+=1,t.push({id:`inv-magic-${n}`,kind:"magic-business-constant",file:c,line:In(u,S.index),message:`Magic business constant ${T} may belong in a Domain policy or invariant catalog.`,confidence:"heuristic",governedLayer:f,suggestedArkRule:{layer:s,invariantId:`INV-${T}`},neverMechanicalSafe:!0}))}if(b){let T=/export\s+class\s+([A-Za-z_][A-Za-z0-9_]*)\s*\{([^}]{0,800})\}/g,M;for(;(M=T.exec(u))!==null;){let P=M[2]??"",V=(P.match(/\b[a-zA-Z_][a-zA-Z0-9_]*\s*\(/g)??[]).length;(P.match(/:\s*[A-Za-z]/g)??[]).length>=2&&V<=1&&(n+=1,t.push({id:`inv-anemic-${n}`,kind:"anemic-entity",file:c,line:In(u,M.index),message:`Class ${M[1]} looks anemic (data-heavy, few behaviors).`,confidence:"heuristic",governedLayer:f,suggestedArkRule:{layer:s,structureId:"no-anemic-model",sensor:"no-anemic-model"},neverMechanicalSafe:!0}))}}if(b&&!(/\.error\.(?:ts|js|tsx|jsx)$/i.test(p)||/(?:^|\/)[^/]*(?:-access)?\.error\./i.test(p)||/(?:^|\/)errors?(?:\/|$)/i.test(p))){let M=/\bthis\.[A-Za-z_][A-Za-z0-9_]*\s*=(?!=)/g,P;for(;(P=M.exec(u))!==null;){let V=u.lastIndexOf("class ",P.index),z=V>=0?u.indexOf("{",V):-1,fe=V>=0&&z>=V&&z<P.index?u.slice(V,z):"";if(/\bextends\s+(?:Error|[A-Za-z_$][A-Za-z0-9_$]*Error)\b/.test(fe)||Dr(u,P.index))continue;let Se=u.slice(Math.max(0,P.index-200),P.index+200);if(!Nr.test(Se)&&!Lr.test(Se)){n+=1,t.push({id:`inv-mut-${n}`,kind:"mutation-without-guard",file:c,line:In(u,P.index),message:`Domain field mutation without nearby ${Pr()}.`,confidence:"heuristic",governedLayer:f,suggestedArkRule:{layer:s,structureId:"events-on-mutation",sensor:"domain-event-on-mutation"},neverMechanicalSafe:!0});break}}}}let i=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&&i.has(c.suggestedArkRule.invariantId)||c.suggestedArkRule?.structureId&&i.has(c.suggestedArkRule.structureId)).length;return{candidates:t,inventoried:t.length,underContract:l,frozen:(e.frozenKeys??[]).length,notAScore:!0}}a(Gu,"buildRulesInventory");function Bu(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."}}a(Bu,"inventoryToExtractionCard");var zu="1.1";var Wu="1.0";var Qr="docs/diagnostics.md",qu="1.0";function I(e,t,n,r,o,s){return{ruleId:e,title:n,why:r,fix:o,docsAnchor:e,category:t,...s?.oftenAdvisory?{oftenAdvisory:!0}:{}}}a(I,"entry");var En=Object.freeze([I("LAYER_IMPORT_VIOLATION","layer","This import is not allowed","This file imported a folder it may not reach. The write doesn\u2019t land. The same check fails the pull request.","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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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}),I("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."),I("INVARIANT_CATALOG_EMPTY","arkrules","Domain invariant catalog is empty","ArkRules is on and a Domain-role layer has code, but invariants[] has no phrases the code must preserve. Empty looks like \u201Cdone\u201D until someone fills the catalog.","Add 1\u20132 short phrases to invariants[] in arkrules/<Domain>.json (or the mapped file). Starters show the shape. Advisory unless a domain structure rule is already enforced \u2014 then --strict-merge can refuse. Do not freeze this finding.",{oftenAdvisory:!0}),I("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."),I("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}),I("INVARIANT_TESTS_PATH_MISSING","arkrules","Domain-invariant tests path missing under adopted","The project is adopted (required CI or explicit advisory) and has domain invariants that want test evidence, but ark.config.json does not name where those tests live. Green coverage without a real tests path is an empty checkbox.","Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present. Not freezable."),I("INVARIANT_COVERAGE_ROOTS_MISSING","arkrules","Coverage roots missing while an invariant is enforced","A catalogued domain invariant is enforced, but ark.config.json does not name coverage.coverageRoots \u2014 the folders where the project says its test runner actually goes. Without that declaration, INVARIANT_COVERAGE_OUTSIDE_ROOTS cannot fire and coverage can certify a test no runner runs.","Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. testGlobs alone is not enough. Fail-closed until that path is present. Not freezable."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("ARKORDER_GENERIC_UPDATE","arkorder","Generic update of a big product choice","A call to update/patch/set rewrites a named product choice (like billing plan) as if it were a seat count.","Don't use a generic update. First freeze with release(). Later, propose the change, then apply it."),I("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."),I("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."),I("ARKORDER_XI_FIELD_WRITE","arkorder","Big product choice written like a seat count","A use-case writes a named product choice (like billing plan) through a database update. Invoices and seats can flow. That choice cannot.","Keep invoices and seats as events. Change the choice through the valve (proposeRelease then apply), not a generic update."),I("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."),I("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."),I("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."),I("ARKORDER_UNVALVED_RELEASE","arkorder","Second freeze without the valve","release() already froze the big choice. A later release() with a different value does not land. First freeze is release(); later change is proposeRelease then apply.","Change the choice with proposeRelease then apply. release() is only the first freeze. Never mechanical-safe."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("LEXICAL_EVIDENCE_INCOMPLETE","analysis","Lexical evidence incomplete","This check only saw one file, so it cannot fully prove how the import resolves. The result is provisional \u2014 `ark-check` on the project is the authority.","Run `npx arkgate-check --root . --config ark.config.json` to confirm. Do not call ark_prepare_change from a hook deny."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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}),I("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}),I("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}),I("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}),I("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}),I("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}),I("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}),I("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}),I("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}),I("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}),I("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}),I("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}),I("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}),I("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}),I("CONFIG_LAYER_MISSING_OWNER","config","Layer missing owner","requireLayerOwners is on and this layer has no owners. Writes to that house fail closed, like a folder with no name on the door.","Add a GitHub handle or email to that layer\u2019s owners in ark.config.json (/ark-adopt), then re-run. Reserved/allowEmpty houses may stay unnamed. Turn the flag off only if you no longer want owners required."),I("CONFIG_SLICE_IDENTITY_COLLISION","config","Starred slice prefixes share one id","sliceIdentity is stars and two different sliceFolders prefixes bind as the same slice id. Parallel trees of one feature do that on purpose; unrelated trees that share the last folder name merge by accident.","Keep stars when those prefixes are one feature. Otherwise use path, or rename the last literal so the prefixes do not bind as the same id. Doctor names both paths.",{oftenAdvisory:!0}),I("CONFIG_CHILD_SLICES_VERSION","config","childSlices needs a newer arkgate","The rule schema sets additionalProperties to false. arkgate 4.8.22 and older reject a config that contains childSlices instead of ignoring the key.","Pin arkgate newer than 4.8.22 before shipping a config that sets childSlices. This warning does not fail the check.",{oftenAdvisory:!0}),I("CONFIG_CHILD_SLICE_EXTENDS","config","Child slice id does not extend its universe","A path resolved a child id that is not the universe id plus a further segment. The child wall does not treat that id as a child, so the edge is universe common until the folders line up.","Point childSlices.sliceFolders at children under the same universe id the outer sliceFolders already names. Doctor names the path.",{oftenAdvisory:!0}),I("CONFIG_CHILD_SLICE_CROSS_UNIVERSE","config","Child slice allowance cannot cross the universe wall","childSlices.allowedCrossSlice names a pattern that can match two universes. That list clears only a sibling crossing inside one universe. The universe wall still denies the edge.","Narrow the pattern so both sides share one universe prefix (features/projects/* to features/projects/d2d-item), or remove the entry. This warning does not fail the check.",{oftenAdvisory:!0}),I("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."),I("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}),I("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.")]),es=new Map(En.map(e=>[e.ruleId,e])),Yu=Object.freeze(En.map(e=>e.ruleId));function Ju(e){return typeof e=="string"&&e.length>0&&es.has(e)}a(Ju,"isKnownDiagnosticCode");function Xu(e){return typeof e!="string"||e.length===0?!1:es.has(e)?!0:e.startsWith("ARKRULE_")}a(Xu,"isCataloguedOrArkRuleFamily");function bn(e){if(!(typeof e!="string"||e.length===0))return es.get(e)}a(bn,"getDiagnosticCatalogEntry");function Li(e){return`#${bn(e)?.docsAnchor??e}`}a(Li,"diagnosticDocsFragment");function Zu(e){return`${Qr}${Li(e)}`}a(Zu,"diagnosticDocsPath");function Qu(){return{schemaVersion:"1.0",docsPath:Qr,codes:En}}a(Qu,"serializeDiagnosticCatalog");function ep(e){return bn(e)?.fix}a(ep,"catalogFixForRuleId");function tp(e){return bn(e)?.why}a(tp,"catalogWhyForRuleId");var np=Object.freeze([Object.freeze({reasonId:"CROSS_PARENT_SLICE",ruleId:"LAYER_IMPORT_VIOLATION",title:"Cross-universe slice",why:"This import crosses two universe slices. The child wall cannot allow another universe.",fix:"Keep the import inside one universe, or move the shared code into a folder both universes may use."}),Object.freeze({reasonId:"CROSS_SIBLING_SLICE",ruleId:"LAYER_IMPORT_VIOLATION",title:"Cross-sibling slice",why:"This import crosses two feature slices inside one universe.",fix:"Import universe-common code, or move the shared piece into the feature that owns it. An enforce list makes those importer subtrees errors. Other sibling crossings stay warnings, and a new one past the baseline still fails."}),Object.freeze({reasonId:"CROSS_PARENT_VIA_SHARED",ruleId:"LAYER_IMPORT_VIOLATION",title:"Cross-universe through a shared root",why:"A slice reaches another universe only through a shared root. ark-check and CI report this path. The write hook and ESLint see one edge at a time and do not block it.",fix:"Stop the shared root from importing the other universe, or move that import into the universe that owns it. A shared hop that stays inside one universe is allowed."})]),qm=new Map(np.map(e=>[e.reasonId,e]));function rp(e){return e==="enforced"||e==="advisory"?e:null}a(rp,"closedMode");function Pi(e={}){let t=e.present===!0,n=rp(e.mode),r=e.residual,o=null;return typeof r=="number"&&Number.isFinite(r)&&r>=0&&(o=Math.floor(r)),t||(o=o??0),{notAScore:!0,present:t,mode:t?n:null,extraMergeTeeth:t&&n==="enforced"&&e.extraMergeTeeth===!0,residual:o}}a(Pi,"projectStatusArkOrder");var ts="1.0",Di="https://unpkg.com/arkgate@4/schemas/ark.status-manifest.schema.json",Mi=["full","subset","unavailable"],Fi=["doctor-facts","report-snapshot","none"],vn={FACTS_UNAVAILABLE:"FACTS_UNAVAILABLE",FACTS_PARTIAL:"FACTS_PARTIAL",NO_SESSION_SNAPSHOT:"NO_SESSION_SNAPSHOT"},$i=/^sha256:[a-f0-9]{64}$/;function Hi(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"||!$i.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 o=e.expectedRootRelation??"unknown";return o==="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}.`}:o==="unknown"?{status:"unverified",authoritative:!1,expectedRoot:n,expectedProjectId:r,message:"Could not prove expectedRoot against the resolved project root (stale or incomplete path evidence)."}:o==="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}.`}:o==="exact"||o==="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."}}a(Hi,"evaluateStatusBinding");function ji(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"}a(ji,"classifyStatusWritePath");function Vi(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)."}a(Vi,"defaultHonestLabel");function Ki(e,t,n,r,o){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."}:o.arkRulesLoaded&&(o.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.arkOrder?.present===!0&&(e.arkOrder.residual??0)>0?{id:"review-arkorder-residual",summary:"ArkOrder leftover remains \u2014 change that product choice through the valve (proposeRelease then apply), not a generic update. 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."}}a(Ki,"resolveStatusNextAction");function sp(e){let t=typeof e.resolvedRoot=="string"&&e.resolvedRoot.length>0?e.resolvedRoot:".",n=typeof e.projectId=="string"&&$i.test(e.projectId)?e.projectId:null,r=Hi({resolvedRoot:t,projectId:n,expectation:e.expectation,expectedRootRelation:e.expectedRootRelation}),o=typeof e.activeHost=="string"?e.activeHost.trim().toLowerCase():"",s=o&&o!=="unknown"?o:o==="unknown"?"unknown":null,i=ji({hardWriteActive:e.hardWriteActive,softWriteHost:e.softWriteHost,writePathUnavailable:e.writePathUnavailable,activeHost:s}),l=typeof e.honestLabel=="string"&&e.honestLabel.trim().length>0?e.honestLabel.trim():Vi(i,s),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)},p={writePath:i,host:s,honestLabel:l},m={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}:{}},f={schemaVersion:ts,arkgateVersion:typeof e.arkgateVersion=="string"&&e.arkgateVersion.length>0?e.arkgateVersion:"unknown",projectIdentity:m,activation:p,lastCheck:c,rules:u,nextAction:Ki(e,r,p,c,u)},g=Gi(e.improvementCompass);return g&&(f.improvementCompass=g),e.vsBase&&typeof e.vsBase.baseRef=="string"&&e.vsBase.baseRef.length>0&&(f.vsBase=e.vsBase),e.arkRun&&typeof e.arkRun=="object"&&(f.arkRun=Zr(e.arkRun)),e.arkOrder&&typeof e.arkOrder=="object"&&(f.arkOrder=Pi(e.arkOrder)),f}a(sp,"buildStatusManifest");var Ui=new Set(Mi),op=new Set(Fi);function ns(e){let t=Ui.has(e.mode)?e.mode:"unavailable",n=e.factsSource!=null&&op.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 i={schemaVersion:"1.0",notAScore:!0,mode:"unavailable",topResidual:[],reasonCode:typeof e.reasonCode=="string"&&e.reasonCode.length>0?e.reasonCode:vn.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&&(i.contractHash=r),i}let o=Array.isArray(e.topResidual)?e.topResidual.filter(i=>typeof i=="string"&&i.length>0).slice(0,15):[],s={schemaVersion:"1.0",notAScore:!0,mode:t,topResidual:o};return t==="subset"?(s.reasonCode=typeof e.reasonCode=="string"&&e.reasonCode.length>0?e.reasonCode:vn.FACTS_PARTIAL,s.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&&(s.reasonCode=e.reasonCode),typeof e.reason=="string"&&e.reason.length>0&&t==="full"&&(s.reason=e.reason),n&&(s.factsSource=n),r&&(s.contractHash=r),s}a(ns,"projectStatusImprovementCompass");function ip(e={}){return ns({mode:"unavailable",topResidual:[],reasonCode:e.reasonCode??vn.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})}a(ip,"unavailableStatusImprovementCompass");function Gi(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"&&Ui.has(t.mode)?n=t.mode:Array.isArray(t.topResidual)?n="subset":n="unavailable",ns({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})}a(Gi,"normalizeStatusImprovementCompass");function ap(e,t){let n=Array.isArray(e)?e:[],r=new Set(Array.isArray(t)?t:[]);for(let o of n)if(!(typeof o!="string"||o.length===0)&&!r.has(o))return!1;return!0}a(ap,"statusCompassResidualIsSubsetOfDoctor");function Ht(e){if(e==null)return null;let t=Number(e);return!Number.isFinite(t)||t<0?null:Math.floor(t)}a(Ht,"numberOrNull");var lp={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Di,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:ts},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"}]}}},arkOrder:{type:"object",description:"ArkOrder 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 Cn="1.0",_n=["soc","cohesion","coupling","srp","dip","ocp","encapsulation","modularity","scalability","resilience","security","maintainability","testability","domain","stack"],On=5,Ve=["scalability","resilience","security"],it=new Set(Ve),rs={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},ss={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"},os={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 is(e){return ss[e]??e}a(is,"improvementCompassHumanLabel");function as(e){let t=e.id??e.smellId??"";return typeof t=="string"?t.trim():""}a(as,"smellIdOf");function ls(e){let t=e.ruleId??e.code??"";return typeof t=="string"?t.trim():""}a(ls,"violationRuleId");function B(e,t,n,r){if(!n||e.evidence.some(s=>s.source===t&&s.ref===n))return;let o={source:t,ref:n};r&&r.trim()&&(o.detail=r.trim().slice(0,240)),e.evidence.push(o)}a(B,"pushEvidence");function oe(e,t,n){it.has(e.id)||(e.status="residual",e.summary=t,n&&(e.nextAction=n))}a(oe,"markResidual");function Bi(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`${ss[e]} \u2014 no residual from current sensors.`}}a(Bi,"defaultOkSummary");function zi(){return _n.map(e=>it.has(e)?{id:e,status:"out-of-scope",summary:os[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:Bi(e),evidence:[]}:{id:e,status:"ok",summary:Bi(e),evidence:[]})}a(zi,"createInitialImprovementCompassLenses");function cp(e,t){for(let n of t){let r=as(n);if(!r)continue;let o=n.outcome||n.message||void 0,i=(Array.isArray(n.evidence)?n.evidence:[])[0],l=a((p,m,f)=>{let g=e.get(p);!g||it.has(p)||(B(g,"designSmells",r,o),i&&B(g,"designSmells",i,r),oe(g,m,f))},"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}}}a(cp,"mapDesignSmells");function dp(e){return e.failsStrict===!1||e.typeOnly===!0}a(dp,"isTypeOnlyPlacementDebt");function up(e,t){for(let n of t){let r=ls(n);if(!r)continue;let o=n.message,s=r.toUpperCase(),i=a((c,u,p)=>{let m=e.get(c);!m||it.has(c)||(B(m,"violations",r,o),n.file&&B(m,"violations",n.file,r),oe(m,u,p))},"attach");if(dp(n)){i("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(s==="LAYER_IMPORT_VIOLATION"||s.includes("LAYER_IMPORT")||s==="DYNAMIC_IMPORT_VIOLATION"){i("coupling","Import graph edges violate the layer contract.",l);continue}if(s.includes("CYCLE")||s==="CIRCULAR_DEPENDENCY"){i("coupling","Import cycles couple modules tightly.",l);continue}if(s.includes("PEER_ISOLATION")||s==="PEER_ISOLATION_VIOLATION"){i("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(s==="FORBIDDEN_GLOBAL"||s.startsWith("FORBIDDEN_")){i("dip","Forbidden globals / effect surfaces break dependency inversion.",{kind:"skill",ref:"/ark-autopilot",summary:"Inject a port instead of the forbidden global."}),i("testability","Forbidden ambient effects reduce pure-domain testability.",{kind:"skill",ref:"/ark-autopilot",summary:"Replace ambient effects with injectable ports."});continue}if(s==="CAPABILITY_VIOLATION"){i("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)."}),i("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(s.startsWith("ARKRULE_")||s==="INVARIANT_UNCOVERED"||s==="INVARIANT_CATALOG_EMPTY"||s==="INVARIANT_TESTS_PATH_MISSING"||s==="INVARIANT_COVERAGE_ROOTS_MISSING"){i("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."}),i("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}}}a(up,"mapViolations");function pp(e,t){let n=Number(t.cycleCount)||0;if(n>0){let g=e.get("coupling");B(g,"cycles",`count:${n}`),oe(g,"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 g=e.get("coupling");B(g,"peerIsolation",`count:${r}`),oe(g,"Peer isolation residual remains.",{kind:"skill",ref:"/ark-autopilot",summary:"Peer isolation is judgment-class residual."})}let o=Number(t.physicalCohesionFindingCount)||0;if(o>0){let g=e.get("cohesion");B(g,"physicalCohesion",`findings:${o}`),oe(g,"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 d=e.get("srp");B(d,"physicalCohesion",`findings:${o}`),oe(d,"Mirrored clusters suggest split-by-concern residual (architecture SRP).",{kind:"skill",ref:"/ark-autopilot",summary:"One reshape/extraction pilot this turn."})}let s=Number(t.pureOrCapabilityResidual)||0,i=Number(t.forbiddenGlobalResidual)||0;if(s>0||i>0){let g=e.get("dip");s>0&&B(g,"capability",`residual:${s}`),i>0&&B(g,"forbiddenGlobals",`residual:${i}`),oe(g,"Pure / capability / forbidden residual weakens dependency inversion.",{kind:"skill",ref:"/ark-autopilot",summary:"Inject ports; keep pure layers free of effects."});let d=e.get("testability");s>0&&B(d,"capability",`residual:${s}`),i>0&&B(d,"forbiddenGlobals",`residual:${i}`),oe(d,"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 g=e.get("encapsulation");B(g,"arkRules",`structureResidual:${l}`),oe(g,"ArkRules structure residual \u2014 encapsulation inside the layer.",{kind:"skill",ref:"/ark-autopilot",summary:"Fix structure sensors under [ArkRules] without inventing mechanical-safe."});let d=e.get("domain");B(d,"arkRules",`structureResidual:${l}`),oe(d,"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 g=e.get("maintainability");B(g,"designFitness","design-weak"),oe(g,"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 g=e.get("maintainability");t.dirtyBaselineRisk===!0&&B(g,"baseline","dirty-freeze-risk"),(Number(t.baselineStale)||0)>0&&B(g,"baseline",`stale:${t.baselineStale}`),oe(g,"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 g=e.get("maintainability");B(g,"baseline",`frozen:${c}`),oe(g,"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,p=Number(t.emptyLayerCount)||0;if(u>0||p>0){let g=e.get("modularity");u>0&&B(g,"coverage",`ungovernedDirs:${u}`),p>0&&B(g,"coverage",`emptyLayers:${p}`),oe(g,"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 g=e.get("modularity");B(g,"goldenPattern","absent"),oe(g,"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 m=e.get("stack");(t.stackKind??null)==="typescript"?m.status==="ok"&&(m.summary="Stack practices are partially instrumented for TypeScript / host / Ark idioms only \u2014 not a full framework checklist."):(m.status="not-instrumented",m.summary="Stack-specific best practices outside TypeScript/host/Ark idioms are not instrumented.",m.evidence=[],m.nextAction={kind:"docs",ref:"docs/use.md#improvement-compass",summary:"Ark does not score non-TS stack idioms."})}a(pp,"mapCountsAndFlags");function Wi(e,t){if(Array.isArray(t.designSmells)&&t.designSmells.length>0){let n=[...t.designSmells].sort((r,o)=>as(r).localeCompare(as(o)));cp(e,n)}if(Array.isArray(t.violations)&&t.violations.length>0){let n=[...t.violations].sort((r,o)=>{let s=ls(r).localeCompare(ls(o));return s!==0?s:String(r.file??"").localeCompare(String(o.file??""))});up(e,n)}pp(e,t)}a(Wi,"projectImprovementCompassFacts");function qi(e){for(let t of Ve){let n=e.get(t);n.status="out-of-scope",n.summary=os[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."}}}a(qi,"lockImprovementCompassOutOfScope");function Yi(e){for(let t of e)t.evidence.sort((n,r)=>{let o=n.source.localeCompare(r.source);return o!==0?o:n.ref.localeCompare(r.ref)})}a(Yi,"sortImprovementCompassEvidence");function Ji(e){return e.filter(n=>n.status==="residual"&&!it.has(n.id)).slice().sort((n,r)=>{let o=rs[n.id]??150,s=rs[r.id]??150;return o!==s?o-s:n.id.localeCompare(r.id)}).slice(0,5).map(n=>n.id)}a(Ji,"finalizeImprovementCompassTopResidual");function fp(e={}){let t=zi(),n=new Map(t.map(o=>[o.id,o]));Wi(n,e),qi(n),Yi(t);let r=Ji(t);return{schemaVersion:"1.0",notAScore:!0,lenses:t.map(o=>{let s={id:o.id,status:o.status,summary:o.summary,evidence:o.evidence.map(i=>({...i}))};return o.nextAction&&(s.nextAction={...o.nextAction}),s}),topResidual:r}}a(fp,"buildImprovementCompass");function Xi(e){return e.topResidual.map(t=>is(t))}a(Xi,"formatImprovementCompassResidualLabels");function Zi(e){for(let t of e.topResidual){let n=e.lenses.find(r=>r.id===t);if(n?.nextAction)return{...n.nextAction}}return null}a(Zi,"primaryImprovementCompassNextAction");function gp(e){let t=Xi(e),n=Ve.map(s=>is(s)),r=Zi(e),o=[];return t.length>0?o.push(`Residual: ${t.join(" \xB7 ")}`):o.push("Residual: none on instrumented lenses (not a score \u2014 green edges \u2260 finished design)."),o.push(`Out of scope (honest): ${n.join(" \xB7 ")}`),r&&o.push(`Next: ${r.ref} \u2014 ${r.summary}`),o}a(gp,"formatImprovementCompassDoctorLines");var Ke="1.0",Qi="<!-- arkgate:agent-projection:begin",xn="<!-- arkgate:agent-projection:end -->",Tn="This projection is **non-authoritative**. Enforcement is `ark-check` / host write hooks / required CI (`--strict-merge`), not AGENTS.md, skills, or this block.",jt=Object.freeze(["ark-check","host-write-hooks","ci-strict-merge"]),ea=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"]);function at(e){let t=String(e??"").replace(/\r\n/g,`
21
+ `),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")}`}a(at,"agentProjectionContentIdentity");function Vt(e){return String(e??"").replace(/\r\n/g,`
22
+ `)}a(Vt,"normalizeNewlines");function Ue(e){let t=Vt(e);return t.endsWith(`
23
23
  `)?t:`${t}
24
- `}i(He,"ensureTrailingNewline");function xt(e){return typeof e!="string"||e.trim().length===0?"unknown":e.trim().replace(/[>\s]/g,"")}i(xt,"safeVersion");function va(e){return e==="compact"?"compact":"full"}i(va,"resolveProfile");function Gr(e){let t=xt(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(Gr,"buildAgentProjectionBeginMarker");function An(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 |
24
+ `}a(Ue,"ensureTrailingNewline");function Kt(e){return typeof e!="string"||e.trim().length===0?"unknown":e.trim().replace(/[>\s]/g,"")}a(Kt,"safeVersion");function ta(e){return e==="compact"?"compact":"full"}a(ta,"resolveProfile");function cs(e){let t=Kt(e.arkgateVersion);return`<!-- arkgate:agent-projection:begin schema=${typeof e.schemaVersion=="string"&&e.schemaVersion.trim()?e.schemaVersion.trim():"1.0"} arkgateVersion=${t} nonAuthoritative=true -->`}a(cs,"buildAgentProjectionBeginMarker");function wn(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 |
25
25
  |-------|----------|-----------------|
26
- ${e.map(n=>{let r=n.name?.trim()||"Unknown",o=n.patterns??[],s=n.intentPrefixes??[],a=o.map(l=>`\`${l}\``).join(", ")||"\u2014",c=s.map(l=>`\`${l}\``).join(", ")||"\u2014";return`| ${r} | ${a} | ${c} |`}).join(`
27
- `)}`}i(An,"formatAgentProjectionLayers");function Br(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(o=>o&&typeof o.ruleId=="string"&&o.ruleId.length>0).map(o=>{let s=typeof o.title=="string"&&o.title.trim()?o.title.trim():o.ruleId;return`- \`${o.ruleId}\` \u2014 ${s}`}).join(`
26
+ ${e.map(n=>{let r=n.name?.trim()||"Unknown",o=n.patterns??[],s=n.intentPrefixes??[],i=o.map(c=>`\`${c}\``).join(", ")||"\u2014",l=s.map(c=>`\`${c}\``).join(", ")||"\u2014";return`| ${r} | ${i} | ${l} |`}).join(`
27
+ `)}`}a(wn,"formatAgentProjectionLayers");function ds(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(o=>o&&typeof o.ruleId=="string"&&o.ruleId.length>0).map(o=>{let s=typeof o.title=="string"&&o.title.trim()?o.title.trim():o.ruleId;return`- \`${o.ruleId}\` \u2014 ${s}`}).join(`
28
28
  `)}
29
29
 
30
- Full catalog: \`${n}\` (\`#RULE_ID\` anchors).`}i(Br,"formatAgentProjectionCatalogShortList");function Rn(e){let t=xt(e.arkgateVersion),n=va(e.profile),r=typeof e.checkCommand=="string"&&e.checkCommand.trim()?e.checkCommand.trim():"ark-check --strict-config",o=typeof e.diagnosticsDocsPath=="string"&&e.diagnosticsDocsPath.trim()?e.diagnosticsDocsPath.trim():"docs/diagnostics.md",s=typeof e.host=="string"?e.host.trim().toLowerCase():"",a=s&&s!=="unknown"?s:null,c=Array.isArray(e.layers)?e.layers:[],l=Array.isArray(e.catalogShortList)?e.catalogShortList:[],u=["## ArkGate agent contract projection","",hn,"","Contener \xB7 Guiar \xB7 Ordenar \u2014 contain the write, guide the next step, order leftover mess. Skills never enforce.","",`- **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)","",An(c),""):u.push("### Contract layers","",An(c),"","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)","",Br(l,o),"","### 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)","",_t.map(p=>`- \`${p}\``).join(`
30
+ Full catalog: \`${n}\` (\`#RULE_ID\` anchors).`}a(ds,"formatAgentProjectionCatalogShortList");function Nn(e){let t=Kt(e.arkgateVersion),n=ta(e.profile),r=typeof e.checkCommand=="string"&&e.checkCommand.trim()?e.checkCommand.trim():"ark-check --strict-config",o=typeof e.diagnosticsDocsPath=="string"&&e.diagnosticsDocsPath.trim()?e.diagnosticsDocsPath.trim():"docs/diagnostics.md",s=typeof e.host=="string"?e.host.trim().toLowerCase():"",i=s&&s!=="unknown"?s:null,l=Array.isArray(e.layers)?e.layers:[],c=Array.isArray(e.catalogShortList)?e.catalogShortList:[],u=["## ArkGate agent contract projection","",Tn,"","Contener \xB7 Guiar \xB7 Ordenar \u2014 contain the write, guide the next step, order leftover mess. Skills never enforce.","",`- **arkgateVersion:** \`${t}\` (must match the installed package; regenerate with \`ark agents-md --write\` after upgrade)`,`- **projectionSchema:** \`${"1.0"}\``,`- **profile:** \`${n}\`${i?` \xB7 **host:** \`${i}\``:""}`,`- **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)","",wn(l),""):u.push("### Contract layers","",wn(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)","",ds(c,o),"","### 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)","",jt.map(p=>`- \`${p}\``).join(`
31
31
  `),""),u.join(`
32
32
  `).replace(/\n{3,}/g,`
33
33
 
34
34
  `).trimEnd()+`
35
- `}i(Rn,"buildAgentProjectionBody");function Ca(e){let t=Rn(e);return`${Gr({arkgateVersion:e.arkgateVersion,schemaVersion:"1.0"})}
36
- ${t}${yn}
37
- `}i(Ca,"buildAgentProjectionBlock");function _a(e){let t=Rn(e),n=Array.isArray(e.layers)?e.layers:[],r=Array.isArray(e.catalogShortList)?e.catalogShortList:[];return{schemaVersion:"1.0",arkgateVersion:xt(e.arkgateVersion),nonAuthoritative:!0,enforcementSurfaces:[..._t],contentIdentity:Ze(t),layerCount:n.length,catalogCodeCount:r.filter(o=>o?.ruleId).length,profile:va(e.profile)}}i(_a,"buildAgentProjectionMeta");var zr=/<!--\s*arkgate:agent-projection:begin\b([^>]*)-->/i,Oa=/<!--\s*arkgate:agent-projection:end\s*-->/i,Bd=/\barkgateVersion=([A-Za-z0-9._+-]+)/i,zd=/\bschema=([A-Za-z0-9._+-]+)/i;function kn(e){let t=Ot(e??""),n=zr.exec(t);if(!n)return{block:null,body:null,before:t,after:"",beginAttrs:null};let r=n.index,o=r+n[0].length,s=t.slice(o),a=Oa.exec(s);if(!a)return{block:null,body:null,before:t,after:"",beginAttrs:null};let c=a.index,l=c+a[0].length,u=s.slice(0,c);u.startsWith(`
38
- `)&&(u=u.slice(1));let p=t.slice(r,o+l),g=s.slice(l);return{block:p,body:u,before:t.slice(0,r),after:g,beginAttrs:n[1]??""}}i(kn,"extractAgentProjectionBlock");function Wr(e){let t=String(e??""),r=zr.exec(t)?.[1]??t,o=Bd.exec(r),s=zd.exec(r),a=/\bnonAuthoritative\s*=\s*true\b/i.test(r);return{arkgateVersion:o?.[1]??null,schemaVersion:s?.[1]??null,nonAuthoritative:a}}i(Wr,"parseAgentProjectionStamp");function xa(e,t){let n=Wr(e).arkgateVersion;return n?n===xt(t):!1}i(xa,"projectionMatchesPackageVersion");function Ta(e){return String(e??"").includes("non-authoritative")}i(Ta,"projectionHasNonEnforcementLabel");function Na(e,t){let n=He(Ot(t)),o=kn(n).body??n.replace(zr,"").replace(Oa,"").trim()+`
39
- `,s=Ze(o);if(e==null||!String(e).trim())return{content:He(`# Ark Enforcement
35
+ `}a(Nn,"buildAgentProjectionBody");function na(e){let t=Nn(e);return`${cs({arkgateVersion:e.arkgateVersion,schemaVersion:"1.0"})}
36
+ ${t}${xn}
37
+ `}a(na,"buildAgentProjectionBlock");function ra(e){let t=Nn(e),n=Array.isArray(e.layers)?e.layers:[],r=Array.isArray(e.catalogShortList)?e.catalogShortList:[];return{schemaVersion:"1.0",arkgateVersion:Kt(e.arkgateVersion),nonAuthoritative:!0,enforcementSurfaces:[...jt],contentIdentity:at(t),layerCount:n.length,catalogCodeCount:r.filter(o=>o?.ruleId).length,profile:ta(e.profile)}}a(ra,"buildAgentProjectionMeta");var us=/<!--\s*arkgate:agent-projection:begin\b([^>]*)-->/i,sa=/<!--\s*arkgate:agent-projection:end\s*-->/i,mp=/\barkgateVersion=([A-Za-z0-9._+-]+)/i,hp=/\bschema=([A-Za-z0-9._+-]+)/i;function Ln(e){let t=Vt(e??""),n=us.exec(t);if(!n)return{block:null,body:null,before:t,after:"",beginAttrs:null};let r=n.index,o=r+n[0].length,s=t.slice(o),i=sa.exec(s);if(!i)return{block:null,body:null,before:t,after:"",beginAttrs:null};let l=i.index,c=l+i[0].length,u=s.slice(0,l);u.startsWith(`
38
+ `)&&(u=u.slice(1));let p=t.slice(r,o+c),m=s.slice(c);return{block:p,body:u,before:t.slice(0,r),after:m,beginAttrs:n[1]??""}}a(Ln,"extractAgentProjectionBlock");function ps(e){let t=String(e??""),r=us.exec(t)?.[1]??t,o=mp.exec(r),s=hp.exec(r),i=/\bnonAuthoritative\s*=\s*true\b/i.test(r);return{arkgateVersion:o?.[1]??null,schemaVersion:s?.[1]??null,nonAuthoritative:i}}a(ps,"parseAgentProjectionStamp");function oa(e,t){let n=ps(e).arkgateVersion;return n?n===Kt(t):!1}a(oa,"projectionMatchesPackageVersion");function ia(e){return String(e??"").includes("non-authoritative")}a(ia,"projectionHasNonEnforcementLabel");function aa(e,t){let n=Ue(Vt(t)),o=Ln(n).body??n.replace(us,"").replace(sa,"").trim()+`
39
+ `,s=at(o);if(e==null||!String(e).trim())return{content:Ue(`# Ark Enforcement
40
40
 
41
- ${n}`),action:"created",previousBlock:null,contentIdentity:s,preservedOutsideBlock:!1};let a=Ot(e),c=kn(a);if(c.block!=null){let u=c.body??"";if(Ze(u)===s)return{content:He(a),action:"unchanged",previousBlock:c.block,contentIdentity:s,preservedOutsideBlock:!0};let p=c.before.replace(/\s*$/,`
41
+ ${n}`),action:"created",previousBlock:null,contentIdentity:s,preservedOutsideBlock:!1};let i=Vt(e),l=Ln(i);if(l.block!=null){let u=l.body??"";if(at(u)===s)return{content:Ue(i),action:"unchanged",previousBlock:l.block,contentIdentity:s,preservedOutsideBlock:!0};let p=l.before.replace(/\s*$/,`
42
42
 
43
- `),g=c.after.replace(/^\s*/,`
44
- `);return{content:He(`${p}${n.trimEnd()}
45
- ${g}`),action:"block-replaced",previousBlock:c.block,contentIdentity:s,preservedOutsideBlock:!0}}let l=/^(#\s+[^\n]*\n)/m.exec(a);if(l&&l.index!=null){let u=l.index+l[1].length,p=a.slice(0,u).replace(/\s*$/,`
43
+ `),m=l.after.replace(/^\s*/,`
44
+ `);return{content:Ue(`${p}${n.trimEnd()}
45
+ ${m}`),action:"block-replaced",previousBlock:l.block,contentIdentity:s,preservedOutsideBlock:!0}}let c=/^(#\s+[^\n]*\n)/m.exec(i);if(c&&c.index!=null){let u=c.index+c[1].length,p=i.slice(0,u).replace(/\s*$/,`
46
46
 
47
- `),g=a.slice(u).replace(/^\s*/,`
48
- `);return{content:He(`${p}${n.trimEnd()}
49
- ${g}`),action:"block-inserted",previousBlock:null,contentIdentity:s,preservedOutsideBlock:!0}}return{content:He(`${n.trimEnd()}
47
+ `),m=i.slice(u).replace(/^\s*/,`
48
+ `);return{content:Ue(`${p}${n.trimEnd()}
49
+ ${m}`),action:"block-inserted",previousBlock:null,contentIdentity:s,preservedOutsideBlock:!0}}return{content:Ue(`${n.trimEnd()}
50
50
 
51
- ${a.trimStart()}`),action:"block-inserted",previousBlock:null,contentIdentity:s,preservedOutsideBlock:!0}}i(Na,"mergeAgentProjectionDocument");var Wd="1.0",Da="templates/agent-skills",Ma="templates/skills",Fa="SKILL.md",qd=Object.freeze(["Contener","Guiar","Ordenar"]),Xr=Object.freeze(["ark-adopt","ark-autopilot","ark-coverage","ark-explain","ark-explore","ark-order","ark-place","ark-runtime","ark-upgrade"]),qr=Object.freeze({"ark-architect":"ark-adopt","ark-contract":"ark-adopt","ark-fix":"ark-autopilot","ark-loop":"ark-autopilot","ark-think":"ark-explore"}),Sn=Object.freeze({Layers:["ark-adopt","ark-place","ark-explore","ark-autopilot","ark-coverage","ark-explain"],ArkRules:["ark-adopt","ark-explore","ark-autopilot"],ArkRun:["ark-adopt","ark-runtime","ark-place","ark-autopilot"],ArkOrder:["ark-adopt","ark-order","ark-place","ark-autopilot"],Contener:["ark-adopt","ark-place","ark-upgrade"],Guiar:["ark-explore","ark-autopilot","ark-explain","ark-coverage","ark-runtime"],Ordenar:["ark-order"]}),In=Object.freeze(["Layers","ArkRules","ArkRun","ArkOrder","Contener","Guiar","Ordenar"]),$a=Object.freeze({ArkRun:"ark-runtime",ArkOrder:"ark-order",Ordenar:"ark-order"}),wa="Contener \xB7 Guiar \xB7 Ordenar",Pa="Do not invent `/ark-order`",En=Object.freeze(["ark-adopt","ark-architect","ark-autopilot","ark-contract","ark-coverage","ark-explain","ark-explore","ark-fix","ark-loop","ark-order","ark-place","ark-runtime","ark-think","ark-upgrade"]),Ha=En.length,Yd=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function ja(e){return typeof e!="string"||e.length<1||e.length>64?!1:Yd.test(e)}i(ja,"isValidAgentSkillName");function Zr(e){return En.includes(e)}i(Zr,"isArkSkillName");function Yr(e){return Xr.includes(e)}i(Yr,"isFirstClassArkSkillName");function Jd(e){return e in qr?qr[e]:null}i(Jd,"arkSkillStubRedirect");function Ka(e){let t=String(e??"").replace(/^\uFEFF/,""),n=t.includes(`\r
51
+ ${i.trimStart()}`),action:"block-inserted",previousBlock:null,contentIdentity:s,preservedOutsideBlock:!0}}a(aa,"mergeAgentProjectionDocument");var yp="1.0",ua="templates/agent-skills",pa="templates/skills",fa="SKILL.md",Ap=Object.freeze(["Contener","Guiar","Ordenar"]),hs=Object.freeze(["ark-adopt","ark-autopilot","ark-coverage","ark-explain","ark-explore","ark-order","ark-place","ark-runtime","ark-upgrade"]),fs=Object.freeze({"ark-architect":"ark-adopt","ark-contract":"ark-adopt","ark-fix":"ark-autopilot","ark-loop":"ark-autopilot","ark-think":"ark-explore"}),Pn=Object.freeze({Layers:["ark-adopt","ark-place","ark-explore","ark-autopilot","ark-coverage","ark-explain"],ArkRules:["ark-adopt","ark-explore","ark-autopilot"],ArkRun:["ark-adopt","ark-runtime","ark-place","ark-autopilot"],ArkOrder:["ark-adopt","ark-order","ark-place","ark-autopilot"],Contener:["ark-adopt","ark-place","ark-upgrade"],Guiar:["ark-explore","ark-autopilot","ark-explain","ark-coverage","ark-runtime"],Ordenar:["ark-order"]}),Dn=Object.freeze(["Layers","ArkRules","ArkRun","ArkOrder","Contener","Guiar","Ordenar"]),ga=Object.freeze({ArkRun:"ark-runtime",ArkOrder:"ark-order",Ordenar:"ark-order"}),la="Contener \xB7 Guiar \xB7 Ordenar",ca="Do not invent `/ark-order`",Mn=Object.freeze(["ark-adopt","ark-architect","ark-autopilot","ark-contract","ark-coverage","ark-explain","ark-explore","ark-fix","ark-loop","ark-order","ark-place","ark-runtime","ark-think","ark-upgrade"]),ma=Mn.length,Rp=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function ha(e){return typeof e!="string"||e.length<1||e.length>64?!1:Rp.test(e)}a(ha,"isValidAgentSkillName");function ys(e){return Mn.includes(e)}a(ys,"isArkSkillName");function gs(e){return hs.includes(e)}a(gs,"isFirstClassArkSkillName");function kp(e){return e in fs?fs[e]:null}a(kp,"arkSkillStubRedirect");function ya(e){let t=String(e??"").replace(/^\uFEFF/,""),n=t.includes(`\r
52
52
  `)?`\r
53
53
  `:`
54
- `,r=t.split(/\r?\n/);if(r[0]!=="---")return{hasFrontmatter:!1,frontmatter:null,body:t};let o=r.indexOf("---",1);if(o===-1)return{hasFrontmatter:!1,frontmatter:null,body:t};let s={};for(let p=1;p<o;p+=1){let g=r[p]??"";if(g.trim()===""||g.trimStart().startsWith("#"))continue;let f=g.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);if(!f)continue;let m=f[1],d=f[2]??"";(d.startsWith('"')&&d.endsWith('"')&&d.length>=2||d.startsWith("'")&&d.endsWith("'")&&d.length>=2)&&(d=d.slice(1,-1)),s[m]=d}let a=r.slice(o+1).join(n),c=typeof s.name=="string"&&s.name.length>0?s.name:null,l=typeof s.description=="string"&&s.description.length>0?s.description:null,u=typeof s.license=="string"&&s.license.length>0?s.license:null;return{hasFrontmatter:!0,frontmatter:{fields:s,name:c,description:l,license:u},body:a}}i(Ka,"parseSkillDocument");function Va(e){let t=e.requireArkSkillName!==!1,n=e.requireBody!==!1,r=[],o=String(e.directoryName??""),s=Ka(e.content);if(!s.hasFrontmatter||!s.frontmatter)return r.push({code:"MISSING_FRONTMATTER",message:`Skill "${o}" is missing YAML frontmatter fences.`,skillName:o||void 0}),r;let{name:a,description:c}=s.frontmatter,l=a??(o||void 0);return!a||!ja(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:l}):a!==o?r.push({code:"NAME_DIRECTORY_MISMATCH",message:`Frontmatter name "${a}" must match directory name "${o}".`,skillName:a}):t&&!Zr(a)&&r.push({code:"UNKNOWN_SKILL_NAME",message:`Skill name "${a}" is not in the closed Ark skill catalog (ARK_SKILL_NAMES).`,skillName:a}),c?c.length>1024&&r.push({code:"DESCRIPTION_TOO_LONG",message:`Skill "${o}" description exceeds 1024 characters (${c.length}).`,skillName:l}):r.push({code:"MISSING_DESCRIPTION",message:`Skill "${o}" is missing a non-empty description.`,skillName:l}),n&&s.body.trim().length===0&&r.push({code:"EMPTY_BODY",message:`Skill "${o}" has an empty instruction body.`,skillName:l}),r}i(Va,"validateAgentSkillDocument");function Xd(e){let t=[],n=new Set,r=[];for(let o of e){let s=String(o.name??"");if(n.has(s)){t.push({code:"DUPLICATE_SKILL",message:`Duplicate skill entry "${s}".`,skillName:s});continue}n.add(s),r.push(s),t.push(...Va({directoryName:s,content:o.content,requireArkSkillName:!0,requireBody:!0})),o.flatTemplateContent!=null&&Jr(o.content)!==Jr(o.flatTemplateContent)&&t.push({code:"CONTENT_MISMATCH",message:`Agent Skills SKILL.md for "${s}" does not match flat template templates/skills/${s}.md.`,skillName:s})}for(let o of En)n.has(o)||t.push({code:"MISSING_SKILL",message:`Missing catalog skill "${o}" from Agent Skills package.`,skillName:o});for(let o of r)Zr(o)||(t.some(s=>s.code==="UNKNOWN_SKILL_NAME"&&s.skillName===o)?t.push({code:"EXTRA_SKILL",message:`Extra skill "${o}" is not in the closed Ark skill catalog.`,skillName:o}):t.push({code:"EXTRA_SKILL",message:`Extra skill "${o}" is not in the closed Ark skill catalog.`,skillName:o}));return r.sort(),{ok:t.length===0,issues:t,names:r,expectedCount:Ha,presentCount:r.length}}i(Xd,"validateAgentSkillsPackage");function ue(e,t){e.push(t)}i(ue,"pushCapacityIssue");function La(e,t){return e.includes(t)}i(La,"skillMentionsSurface");function Zd(e){let t=[],n=e.skills??{},r=Object.keys(Sn);for(let s of In)r.includes(s)||ue(t,{code:"CAPACITY_SURFACE_MISSING",surface:s,message:`The capacity table dropped ${s}. Skills must keep covering Layers, ArkRules, ArkRun, ArkOrder plus Contener \xB7 Guiar \xB7 Ordenar. Put ${s} back on ARK_SKILL_CAPACITY.`});for(let s of r)In.includes(s)||ue(t,{code:"CAPACITY_SURFACE_UNMAPPED",surface:s,message:`The capacity table lists ${s}, which is not a product surface. Keep the table to Layers, ArkRules, ArkRun, ArkOrder and Contener \xB7 Guiar \xB7 Ordenar.`});for(let s of In){let a=Sn[s];if(!a||a.length===0)continue;for(let l of a)Yr(l)||ue(t,{code:"CAPACITY_DOOR_NOT_FIRST_CLASS",surface:s,skillName:l,message:`/${l} is listed for ${s} but is not a first-class door. Leftover names are shortcuts. Point ${s} at a first-class skill.`});a.filter(l=>{let u=n[l];return typeof u=="string"&&La(u,s)}).length===0&&ue(t,{code:"CAPACITY_BODY_GAP",surface:s,message:`Skills no longer cover ${s}. The product has four parts (Layers, ArkRules, ArkRun, ArkOrder) plus Contener \xB7 Guiar \xB7 Ordenar. Put ${s} back in a first-class skill${s==="ArkOrder"||s==="Ordenar"?" \u2014 usually /ark-order":s==="ArkRun"?" \u2014 usually /ark-runtime":""} so agents still know when to use it.`})}for(let[s,a]of Object.entries($a)){if(!Sn[s]?.includes(a)||!Yr(a)){ue(t,{code:"CAPACITY_DEDICATED_DOOR",surface:s,skillName:a,message:`/${a} is the first-class door for ${s}. Keep it on that surface. Leftover names like /ark-think are shortcuts, not a replacement.`});continue}let l=n[a];(typeof l!="string"||!La(l,s))&&ue(t,{code:"CAPACITY_DEDICATED_DOOR",surface:s,skillName:a,message:`/${a} no longer talks about ${s}. That door is how agents reach this part of the product. Put ${s} back in the skill body.`})}for(let s of Xr){let a=n[s];if(typeof a!="string"){ue(t,{code:"CAPACITY_ROUTING_GAP",skillName:s,message:`/${s} is a first-class door but has no skill body in this check. Ship the template so agents know when to use it.`});continue}let c=a.includes(wa),l=/When \/ not when|\*\*When:\*\*/.test(a),u=/Not when|Do \*\*not\*\* use|Prefer instead/.test(a),p=/Handoff|hand off|`\/ark-/i.test(a);(!c||!l||!u||!p)&&ue(t,{code:"CAPACITY_ROUTING_GAP",skillName:s,message:`/${s} is missing when / not when / handoff or Contener \xB7 Guiar \xB7 Ordenar. First-class skills must say when to use them and which sibling to call next.`}),a.includes(Pa)&&ue(t,{code:"CAPACITY_ROUTING_GAP",skillName:s,message:`/${s} still says not to invent /ark-order. That freeze is outdated \u2014 /ark-order is a first-class door.`})}let o=e.hubs??{};for(let[s,a]of Object.entries(o)){let c=String(a??"");c.includes("/ark-order")||ue(t,{code:"CAPACITY_HUB_GAP",hub:s,message:`${s} no longer names /ark-order. Host instructions must stay at 100% of the product. Add /ark-order back, or you left the order plane behind.`}),c.includes(wa)||ue(t,{code:"CAPACITY_HUB_GAP",hub:s,message:`${s} no longer says Contener \xB7 Guiar \xB7 Ordenar. Keep that filter in the living docs so agents pick the right sibling.`}),c.includes(Pa)&&ue(t,{code:"CAPACITY_HUB_GAP",hub:s,message:`${s} still says not to invent /ark-order. That freeze is outdated \u2014 /ark-order is a first-class door.`})}return{ok:t.length===0,issues:t}}i(Zd,"validateSkillProductCapacity");var Qr=/^arkgate@(\S+)\.\s/;function Ua(e){let t=String(e??"").trim();return t?`arkgate@${t}. `:""}i(Ua,"skillDescriptionVersionPrefix");function Ga(e){return String(e??"").replace(Qr,"")}i(Ga,"stripSkillDescriptionVersion");function Qd(e){return String(e??"").match(Qr)?.[1]??null}i(Qd,"parseSkillDescriptionVersion");function eu(e,t){let n=Ga(e),r=typeof t=="string"?t.trim():"";return r?`${Ua(r)}${n}`:n}i(eu,"stampSkillDescription");function Jr(e){return String(e??"").replace(/^\uFEFF/,"").replace(/\r\n/g,`
55
- `)}i(Jr,"normalizeSkillContent");function Ba(e){return`${e}/${Fa}`}i(Ba,"agentSkillEntryRelativePath");function tu(e){return`${Da}/${Ba(e)}`}i(tu,"agentSkillPackageFileRelativePath");function nu(e){return`${Ma}/${e}.md`}i(nu,"flatSkillTemplateFileRelativePath");export{wt as ADAPTER_DIAGNOSTIC_DOCS_RELATIVE_PATH,Ea as AGENT_PROJECTION_BEGIN_MARKER,yn as AGENT_PROJECTION_END_MARKER,_t as AGENT_PROJECTION_ENFORCEMENT_SURFACES,hn as AGENT_PROJECTION_NON_ENFORCEMENT_LABEL,Da as AGENT_SKILLS_PACKAGE_RELATIVE_ROOT,Fa as AGENT_SKILL_ENTRY_FILENAME,Wn as ANALYSIS_IR_SCHEMA_VERSION,Nr as ARKORDER_RULE_IDS,ed as ARKORDER_TIER1_SENSOR_IDS,jo as ARKRUN_INTERACTION_NAME_INCOMPLETE,Mo as ARKRUN_KERNEL_FACTORY_CALLEES,bc as ARKRUN_KERNEL_INTERACTION_CALLEES,Tr as ARKRUN_RULE_IDS,Mc as ARKRUN_TIER1_SENSOR_IDS,Fo as ARKRUN_TRANSPORT_BYPASS_SPECIFIERS,$e as ARK_AGENT_PROJECTION_SCHEMA_VERSION,Wd as ARK_AGENT_SKILLS_PACKAGE_SCHEMA_VERSION,ns as ARK_ANALYSIS_RESULT_SCHEMA,Nt as ARK_ANALYSIS_RESULT_SCHEMA_VERSION,Un as ARK_CONFIG_SCHEMA,ie as ARK_CONFIG_SCHEMA_VERSION,bd as ARK_DESIGN_DELTA_SCHEMA_VERSION,Ed as ARK_ENFORCEMENT_STATE_SCHEMA_VERSION,Xr as ARK_FIRST_CLASS_SKILL_NAMES,fn as ARK_IMPROVEMENT_COMPASS_SCHEMA_VERSION,si as ARK_PROJECT_IDENTITY_SCHEMA,ss as ARK_PROJECT_IDENTITY_SCHEMA_URL,ri as ARK_PROJECT_IDENTITY_SCHEMA_VERSION,Yn as ARK_RULES_SCHEMA,sl as ARK_RULES_SCHEMA_VERSION,Ws as ARK_RULE_SENSORS,Zo as ARK_RUN_DOCTOR_SCHEMA_VERSION,Sn as ARK_SKILL_CAPACITY,$a as ARK_SKILL_CAPACITY_DEDICATED_DOORS,Qr as ARK_SKILL_DESCRIPTION_VERSION_PATTERN,En as ARK_SKILL_NAMES,Ha as ARK_SKILL_NAME_COUNT,qd as ARK_SKILL_NORTH_STAR,In as ARK_SKILL_REQUIRED_SURFACES,qr as ARK_SKILL_STUB_REDIRECTS,$d as ARK_STATUS_MANIFEST_SCHEMA,oa as ARK_STATUS_MANIFEST_SCHEMA_URL,Mr as ARK_STATUS_MANIFEST_SCHEMA_VERSION,ba as DEFAULT_AGENT_PROJECTION_RULE_IDS,dn as DIAGNOSTIC_CATALOG,vd as DIAGNOSTIC_CATALOG_SCHEMA_VERSION,Lr as DIAGNOSTIC_DOCS_RELATIVE_PATH,Cd as DIAGNOSTIC_RULE_IDS,Ic as EXTRA_MERGE_TEETH_GOVERNED_FLOOR,Jt as EffectiveContractError,Ma as FLAT_SKILL_TEMPLATES_RELATIVE_ROOT,Fe as IMPROVEMENT_COMPASS_OUT_OF_SCOPE_LENSES,gn as IMPROVEMENT_COMPASS_TOP_RESIDUAL_CAP,mn as IMPROVEMENT_LENS_IDS,Lo as MERGE_PLANES_DUAL_STAMP,ir as POLICY_DELTA_SCHEMA_VERSION,as as PROJECT_BINDING_SCHEMA,os as PROJECT_EXPECTATION_SCHEMA,zn as RESOLVED_CANDIDATE_FACTS_SCHEMA,Pe as RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,ia as STATUS_COMPASS_FACTS_SOURCES,aa as STATUS_COMPASS_MODES,pn as STATUS_COMPASS_REASON_CODES,Lt as adapterDocsCodePath,rt as adapterFindingOccurrenceTargetKeys,Pt as adapterFindingRefFromTargetKey,nt as adapterFindingTargetKey,Ze as agentProjectionContentIdentity,Ba as agentSkillEntryRelativePath,tu as agentSkillPackageFileRelativePath,qe as analyzeArchitectureConvergence,en as analyzeChange,ho as analyzePolicyDelta,Rt as analyzeProject,vt as analyzeResolvedProject,br as arkRunKernelCallKind,Jd as arkSkillStubRedirect,Gr as buildAgentProjectionBeginMarker,Ca as buildAgentProjectionBlock,Rn as buildAgentProjectionBody,_a as buildAgentProjectionMeta,Rr as buildArkRuleFileHints,Jn as buildEffectiveArkRules,Ud as buildImprovementCompass,Sd as buildRulesInventory,Ld as buildStatusManifest,nr as canPromoteInvariant,Nd as catalogFixForRuleId,wd as catalogWhyForRuleId,lr as classifyArkPolicyDelta,Sl as classifyCoverage,Sr as classifyResolvedLayerCoverage,da as classifyStatusWritePath,ln as collectAnalysisConfigWarnings,Ar as collectEmptyAppliesToFindings,Ge as collectForbiddenCapabilityUses,sn as composeMergePlanesHonesty,ro as countsAsCoverage,bs as createAICodeGate,ni as createAdapterResult,Wt as createArchitectureProfile,Hs as createArchitectureProfileFromArkConfig,js as createElevenLayerArkConfig,oi as createProjectId,ai as createProjectIdentity,Bn as createResolvedCandidateFacts,ua as defaultHonestLabel,Ec as demoteExtraPlaneTeethUnderClassificationFloor,No as deriveArkRuleFileHints,so as describeCoverage,dr as detectArchitectureCycles,Z as deterministicHash,ra as diagnosticDocsFragment,xd as diagnosticDocsPath,Zn as effectiveContractPolicyPayload,zt as elevenLayerProfile,De as emptyEffectiveArkRules,Ye as evaluateArchitectureGraph,wr as evaluateArkOrderSensors,hr as evaluateArkRuleSensors,Vo as evaluateArkRunEditorSensors,Jc as evaluateArkRunEditorSensorsFromSource,an as evaluateArkRunSensors,tr as evaluateInvariantCoverage,ca as evaluateStatusBinding,Ao as explainViolation,Ae as extraMergeTeethAllowed,kn as extractAgentProjectionBlock,Dc as extractArkRunDeclarationsFromSource,_r as extractArkRunImportedConstructorNamesFromSource,Or as extractArkRunKernelCallsFromSource,xr as extractArkRunManagedNewsFromSource,Cr as extractArkRunValueImportDependenciesFromSource,Sc as extractClassShapesFromSource,Ue as extractSemanticDependencies,nu as flatSkillTemplateFileRelativePath,Br as formatAgentProjectionCatalogShortList,An as formatAgentProjectionLayers,Ad as formatArkRunDoctorLines,Gd as formatImprovementCompassDoctorLines,Sa as formatImprovementCompassResidualLabels,un as getDiagnosticCatalogEntry,Id as inventoryToExtractionCard,wo as isArkOrderRuleId,Et as isArkRunKernelModuleSpecifier,Ir as isArkRunRuleId,vr as isArkRunTransportBypassSpecifier,Zr as isArkSkillName,Od as isCataloguedOrArkRuleFamily,Po as isExtraPlaneFinding,Yr as isFirstClassArkSkillName,_d as isKnownDiagnosticCode,ja as isValidAgentSkillName,Bt as loadArkConfigContract,Yt as loadArkRulesContract,Qt as loadContract,_e as loadResolvedCandidateFacts,Na as mergeAgentProjectionDocument,kr as normalizeExtraMergeTeethClassification,Jr as normalizeSkillContent,ma as normalizeStatusImprovementCompass,Wr as parseAgentProjectionStamp,Gn as parseArkConfigJson,dl as parseArkRulesJson,Qd as parseSkillDescriptionVersion,Ka as parseSkillDocument,cr as policyDeltaAcknowledgementMatches,Jo as preflightChange,Xo as preflightResolvedChange,Ia as primaryImprovementCompassNextAction,Pr as projectStatusArkRun,Fr as projectStatusImprovementCompass,Ta as projectionHasNonEnforcementLabel,xa as projectionMatchesPackageVersion,ul as resolveEffectiveContract,pa as resolveStatusNextAction,pt as resolvedFactsEvidenceRequirementsHash,Td as serializeDiagnosticCatalog,Ua as skillDescriptionVersionPrefix,K as stableSerialize,eu as stampSkillDescription,Fd as statusCompassResidualIsSubsetOfDoctor,Ga as stripSkillDescriptionVersion,hd as summarizeArkRunSection,bn as toAdapterDiagnostic,Md as unavailableStatusImprovementCompass,Va as validateAgentSkillDocument,Xd as validateAgentSkillsPackage,Zd as validateSkillProductCapacity,Wa as version};
54
+ `,r=t.split(/\r?\n/);if(r[0]!=="---")return{hasFrontmatter:!1,frontmatter:null,body:t};let o=r.indexOf("---",1);if(o===-1)return{hasFrontmatter:!1,frontmatter:null,body:t};let s={};for(let p=1;p<o;p+=1){let m=r[p]??"";if(m.trim()===""||m.trimStart().startsWith("#"))continue;let f=m.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);if(!f)continue;let g=f[1],d=f[2]??"";(d.startsWith('"')&&d.endsWith('"')&&d.length>=2||d.startsWith("'")&&d.endsWith("'")&&d.length>=2)&&(d=d.slice(1,-1)),s[g]=d}let i=r.slice(o+1).join(n),l=typeof s.name=="string"&&s.name.length>0?s.name:null,c=typeof s.description=="string"&&s.description.length>0?s.description:null,u=typeof s.license=="string"&&s.license.length>0?s.license:null;return{hasFrontmatter:!0,frontmatter:{fields:s,name:l,description:c,license:u},body:i}}a(ya,"parseSkillDocument");function Aa(e){let t=e.requireArkSkillName!==!1,n=e.requireBody!==!1,r=[],o=String(e.directoryName??""),s=ya(e.content);if(!s.hasFrontmatter||!s.frontmatter)return r.push({code:"MISSING_FRONTMATTER",message:`Skill "${o}" is missing YAML frontmatter fences.`,skillName:o||void 0}),r;let{name:i,description:l}=s.frontmatter,c=i??(o||void 0);return!i||!ha(i)?r.push({code:"INVALID_NAME",message:`Skill name "${i??""}" is invalid (Agent Skills: 1\u201364 chars, [a-z0-9-], no leading/trailing/consecutive hyphens).`,skillName:c}):i!==o?r.push({code:"NAME_DIRECTORY_MISMATCH",message:`Frontmatter name "${i}" must match directory name "${o}".`,skillName:i}):t&&!ys(i)&&r.push({code:"UNKNOWN_SKILL_NAME",message:`Skill name "${i}" is not in the closed Ark skill catalog (ARK_SKILL_NAMES).`,skillName:i}),l?l.length>1024&&r.push({code:"DESCRIPTION_TOO_LONG",message:`Skill "${o}" description exceeds 1024 characters (${l.length}).`,skillName:c}):r.push({code:"MISSING_DESCRIPTION",message:`Skill "${o}" is missing a non-empty description.`,skillName:c}),n&&s.body.trim().length===0&&r.push({code:"EMPTY_BODY",message:`Skill "${o}" has an empty instruction body.`,skillName:c}),r}a(Aa,"validateAgentSkillDocument");function Sp(e){let t=[],n=new Set,r=[];for(let o of e){let s=String(o.name??"");if(n.has(s)){t.push({code:"DUPLICATE_SKILL",message:`Duplicate skill entry "${s}".`,skillName:s});continue}n.add(s),r.push(s),t.push(...Aa({directoryName:s,content:o.content,requireArkSkillName:!0,requireBody:!0})),o.flatTemplateContent!=null&&ms(o.content)!==ms(o.flatTemplateContent)&&t.push({code:"CONTENT_MISMATCH",message:`Agent Skills SKILL.md for "${s}" does not match flat template templates/skills/${s}.md.`,skillName:s})}for(let o of Mn)n.has(o)||t.push({code:"MISSING_SKILL",message:`Missing catalog skill "${o}" from Agent Skills package.`,skillName:o});for(let o of r)ys(o)||(t.some(s=>s.code==="UNKNOWN_SKILL_NAME"&&s.skillName===o)?t.push({code:"EXTRA_SKILL",message:`Extra skill "${o}" is not in the closed Ark skill catalog.`,skillName:o}):t.push({code:"EXTRA_SKILL",message:`Extra skill "${o}" is not in the closed Ark skill catalog.`,skillName:o}));return r.sort(),{ok:t.length===0,issues:t,names:r,expectedCount:ma,presentCount:r.length}}a(Sp,"validateAgentSkillsPackage");function pe(e,t){e.push(t)}a(pe,"pushCapacityIssue");function da(e,t){return e.includes(t)}a(da,"skillMentionsSurface");function Ip(e){let t=[],n=e.skills??{},r=Object.keys(Pn);for(let s of Dn)r.includes(s)||pe(t,{code:"CAPACITY_SURFACE_MISSING",surface:s,message:`The capacity table dropped ${s}. Skills must keep covering Layers, ArkRules, ArkRun, ArkOrder plus Contener \xB7 Guiar \xB7 Ordenar. Put ${s} back on ARK_SKILL_CAPACITY.`});for(let s of r)Dn.includes(s)||pe(t,{code:"CAPACITY_SURFACE_UNMAPPED",surface:s,message:`The capacity table lists ${s}, which is not a product surface. Keep the table to Layers, ArkRules, ArkRun, ArkOrder and Contener \xB7 Guiar \xB7 Ordenar.`});for(let s of Dn){let i=Pn[s];if(!i||i.length===0)continue;for(let c of i)gs(c)||pe(t,{code:"CAPACITY_DOOR_NOT_FIRST_CLASS",surface:s,skillName:c,message:`/${c} is listed for ${s} but is not a first-class door. Leftover names are shortcuts. Point ${s} at a first-class skill.`});i.filter(c=>{let u=n[c];return typeof u=="string"&&da(u,s)}).length===0&&pe(t,{code:"CAPACITY_BODY_GAP",surface:s,message:`Skills no longer cover ${s}. The product has four parts (Layers, ArkRules, ArkRun, ArkOrder) plus Contener \xB7 Guiar \xB7 Ordenar. Put ${s} back in a first-class skill${s==="ArkOrder"||s==="Ordenar"?" \u2014 usually /ark-order":s==="ArkRun"?" \u2014 usually /ark-runtime":""} so agents still know when to use it.`})}for(let[s,i]of Object.entries(ga)){if(!Pn[s]?.includes(i)||!gs(i)){pe(t,{code:"CAPACITY_DEDICATED_DOOR",surface:s,skillName:i,message:`/${i} is the first-class door for ${s}. Keep it on that surface. Leftover names like /ark-think are shortcuts, not a replacement.`});continue}let c=n[i];(typeof c!="string"||!da(c,s))&&pe(t,{code:"CAPACITY_DEDICATED_DOOR",surface:s,skillName:i,message:`/${i} no longer talks about ${s}. That door is how agents reach this part of the product. Put ${s} back in the skill body.`})}for(let s of hs){let i=n[s];if(typeof i!="string"){pe(t,{code:"CAPACITY_ROUTING_GAP",skillName:s,message:`/${s} is a first-class door but has no skill body in this check. Ship the template so agents know when to use it.`});continue}let l=i.includes(la),c=/When \/ not when|\*\*When:\*\*/.test(i),u=/Not when|Do \*\*not\*\* use|Prefer instead/.test(i),p=/Handoff|hand off|`\/ark-/i.test(i);(!l||!c||!u||!p)&&pe(t,{code:"CAPACITY_ROUTING_GAP",skillName:s,message:`/${s} is missing when / not when / handoff or Contener \xB7 Guiar \xB7 Ordenar. First-class skills must say when to use them and which sibling to call next.`}),i.includes(ca)&&pe(t,{code:"CAPACITY_ROUTING_GAP",skillName:s,message:`/${s} still says not to invent /ark-order. That freeze is outdated \u2014 /ark-order is a first-class door.`})}let o=e.hubs??{};for(let[s,i]of Object.entries(o)){let l=String(i??"");l.includes("/ark-order")||pe(t,{code:"CAPACITY_HUB_GAP",hub:s,message:`${s} no longer names /ark-order. Host instructions must stay at 100% of the product. Add /ark-order back, or you left the order plane behind.`}),l.includes(la)||pe(t,{code:"CAPACITY_HUB_GAP",hub:s,message:`${s} no longer says Contener \xB7 Guiar \xB7 Ordenar. Keep that filter in the living docs so agents pick the right sibling.`}),l.includes(ca)&&pe(t,{code:"CAPACITY_HUB_GAP",hub:s,message:`${s} still says not to invent /ark-order. That freeze is outdated \u2014 /ark-order is a first-class door.`})}return{ok:t.length===0,issues:t}}a(Ip,"validateSkillProductCapacity");var As=/^arkgate@(\S+)\.\s/;function Ra(e){let t=String(e??"").trim();return t?`arkgate@${t}. `:""}a(Ra,"skillDescriptionVersionPrefix");function ka(e){return String(e??"").replace(As,"")}a(ka,"stripSkillDescriptionVersion");function Ep(e){return String(e??"").match(As)?.[1]??null}a(Ep,"parseSkillDescriptionVersion");function bp(e,t){let n=ka(e),r=typeof t=="string"?t.trim():"";return r?`${Ra(r)}${n}`:n}a(bp,"stampSkillDescription");function ms(e){return String(e??"").replace(/^\uFEFF/,"").replace(/\r\n/g,`
55
+ `)}a(ms,"normalizeSkillContent");function Sa(e){return`${e}/${fa}`}a(Sa,"agentSkillEntryRelativePath");function vp(e){return`${ua}/${Sa(e)}`}a(vp,"agentSkillPackageFileRelativePath");function Cp(e){return`${pa}/${e}.md`}a(Cp,"flatSkillTemplateFileRelativePath");export{Bt as ADAPTER_DIAGNOSTIC_DOCS_RELATIVE_PATH,Qi as AGENT_PROJECTION_BEGIN_MARKER,xn as AGENT_PROJECTION_END_MARKER,jt as AGENT_PROJECTION_ENFORCEMENT_SURFACES,Tn as AGENT_PROJECTION_NON_ENFORCEMENT_LABEL,ua as AGENT_SKILLS_PACKAGE_RELATIVE_ROOT,fa as AGENT_SKILL_ENTRY_FILENAME,lr as ANALYSIS_IR_SCHEMA_VERSION,Jr as ARKORDER_RULE_IDS,Eu as ARKORDER_TIER1_SENSOR_IDS,hi as ARKRUN_INTERACTION_NAME_INCOMPLETE,pi as ARKRUN_KERNEL_FACTORY_CALLEES,Wd as ARKRUN_KERNEL_INTERACTION_CALLEES,Yr as ARKRUN_RULE_IDS,ou as ARKRUN_TIER1_SENSOR_IDS,fi as ARKRUN_TRANSPORT_BYPASS_SPECIFIERS,Ke as ARK_AGENT_PROJECTION_SCHEMA_VERSION,yp as ARK_AGENT_SKILLS_PACKAGE_SCHEMA_VERSION,Ss as ARK_ANALYSIS_RESULT_SCHEMA,Gt as ARK_ANALYSIS_RESULT_SCHEMA_VERSION,sr as ARK_CONFIG_SCHEMA,le as ARK_CONFIG_SCHEMA_VERSION,Wu as ARK_DESIGN_DELTA_SCHEMA_VERSION,zu as ARK_ENFORCEMENT_STATE_SCHEMA_VERSION,hs as ARK_FIRST_CLASS_SKILL_NAMES,Cn as ARK_IMPROVEMENT_COMPASS_SCHEMA_VERSION,Pa as ARK_PROJECT_IDENTITY_SCHEMA,Es as ARK_PROJECT_IDENTITY_SCHEMA_URL,La as ARK_PROJECT_IDENTITY_SCHEMA_VERSION,dr as ARK_RULES_SCHEMA,gc as ARK_RULES_SCHEMA_VERSION,So as ARK_RULE_SENSORS,Oi as ARK_RUN_DOCTOR_SCHEMA_VERSION,Pn as ARK_SKILL_CAPACITY,ga as ARK_SKILL_CAPACITY_DEDICATED_DOORS,As as ARK_SKILL_DESCRIPTION_VERSION_PATTERN,Mn as ARK_SKILL_NAMES,ma as ARK_SKILL_NAME_COUNT,Ap as ARK_SKILL_NORTH_STAR,Dn as ARK_SKILL_REQUIRED_SURFACES,fs as ARK_SKILL_STUB_REDIRECTS,lp as ARK_STATUS_MANIFEST_SCHEMA,Di as ARK_STATUS_MANIFEST_SCHEMA_URL,ts as ARK_STATUS_MANIFEST_SCHEMA_VERSION,ea as DEFAULT_AGENT_PROJECTION_RULE_IDS,En as DIAGNOSTIC_CATALOG,qu as DIAGNOSTIC_CATALOG_SCHEMA_VERSION,Qr as DIAGNOSTIC_DOCS_RELATIVE_PATH,Yu as DIAGNOSTIC_RULE_IDS,Bd as EXTRA_MERGE_TEETH_GOVERNED_FLOOR,cn as EffectiveContractError,pa as FLAT_SKILL_TEMPLATES_RELATIVE_ROOT,Ve as IMPROVEMENT_COMPASS_OUT_OF_SCOPE_LENSES,On as IMPROVEMENT_COMPASS_TOP_RESIDUAL_CAP,_n as IMPROVEMENT_LENS_IDS,di as MERGE_PLANES_DUAL_STAMP,vr as POLICY_DELTA_SCHEMA_VERSION,vs as PROJECT_BINDING_SCHEMA,bs as PROJECT_EXPECTATION_SCHEMA,ar as RESOLVED_CANDIDATE_FACTS_SCHEMA,Fe as RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,Fi as STATUS_COMPASS_FACTS_SOURCES,Mi as STATUS_COMPASS_MODES,vn as STATUS_COMPASS_REASON_CODES,Wt as adapterDocsCodePath,pt as adapterFindingOccurrenceTargetKeys,zt as adapterFindingRefFromTargetKey,ut as adapterFindingTargetKey,at as agentProjectionContentIdentity,Sa as agentSkillEntryRelativePath,vp as agentSkillPackageFileRelativePath,tt as analyzeArchitectureConvergence,gn as analyzeChange,zo as analyzePolicyDelta,Nt as analyzeProject,$t as analyzeResolvedProject,Ur as arkRunKernelCallKind,kp as arkSkillStubRedirect,cs as buildAgentProjectionBeginMarker,na as buildAgentProjectionBlock,Nn as buildAgentProjectionBody,ra as buildAgentProjectionMeta,$r as buildArkRuleFileHints,ur as buildEffectiveArkRules,fp as buildImprovementCompass,Gu as buildRulesInventory,sp as buildStatusManifest,Ar as canPromoteInvariant,ep as catalogFixForRuleId,tp as catalogWhyForRuleId,Cr as classifyArkPolicyDelta,Nc as classifyCoverage,jr as classifyResolvedLayerCoverage,ji as classifyStatusWritePath,Sn as collectAnalysisConfigWarnings,Fr as collectEmptyAppliesToFindings,Ye as collectForbiddenCapabilityUses,An as composeMergePlanesHonesty,xo as countsAsCoverage,Ws as createAICodeGate,Na as createAdapterResult,on as createArchitectureProfile,fo as createArchitectureProfileFromArkConfig,go as createElevenLayerArkConfig,Da as createProjectId,Ma as createProjectIdentity,ir as createResolvedCandidateFacts,Vi as defaultHonestLabel,zd as demoteExtraPlaneTeethUnderClassificationFloor,ai as deriveArkRuleFileHints,To as describeCoverage,xr as detectArchitectureCycles,ee as deterministicHash,Li as diagnosticDocsFragment,Zu as diagnosticDocsPath,fr as effectiveContractPolicyPayload,sn as elevenLayerProfile,He as emptyEffectiveArkRules,st as evaluateArchitectureGraph,Xr as evaluateArkOrderSensors,Mr as evaluateArkRuleSensors,Ai as evaluateArkRunEditorSensors,Ru as evaluateArkRunEditorSensorsFromSource,kn as evaluateArkRunSensors,yr as evaluateInvariantCoverage,Hi as evaluateStatusBinding,Wo as explainViolation,ke as extraMergeTeethAllowed,Ln as extractAgentProjectionBlock,su as extractArkRunDeclarationsFromSource,zr as extractArkRunImportedConstructorNamesFromSource,Wr as extractArkRunKernelCallsFromSource,qr as extractArkRunManagedNewsFromSource,Br as extractArkRunValueImportDependenciesFromSource,Gd as extractClassShapesFromSource,qe as extractSemanticDependencies,Cp as flatSkillTemplateFileRelativePath,ds as formatAgentProjectionCatalogShortList,wn as formatAgentProjectionLayers,Vu as formatArkRunDoctorLines,gp as formatImprovementCompassDoctorLines,Xi as formatImprovementCompassResidualLabels,bn as getDiagnosticCatalogEntry,Bu as inventoryToExtractionCard,li as isArkOrderRuleId,Mt as isArkRunKernelModuleSpecifier,Vr as isArkRunRuleId,Gr as isArkRunTransportBypassSpecifier,ys as isArkSkillName,Xu as isCataloguedOrArkRuleFamily,ci as isExtraPlaneFinding,gs as isFirstClassArkSkillName,Ju as isKnownDiagnosticCode,ha as isValidAgentSkillName,rn as loadArkConfigContract,ln as loadArkRulesContract,fn as loadContract,xe as loadResolvedCandidateFacts,aa as mergeAgentProjectionDocument,Hr as normalizeExtraMergeTeethClassification,ms as normalizeSkillContent,Gi as normalizeStatusImprovementCompass,ps as parseAgentProjectionStamp,or as parseArkConfigJson,kc as parseArkRulesJson,Ep as parseSkillDescriptionVersion,ya as parseSkillDocument,_r as policyDeltaAcknowledgementMatches,Ci as preflightChange,_i as preflightResolvedChange,Zi as primaryImprovementCompassNextAction,Zr as projectStatusArkRun,ns as projectStatusImprovementCompass,ia as projectionHasNonEnforcementLabel,oa as projectionMatchesPackageVersion,Sc as resolveEffectiveContract,Ki as resolveStatusNextAction,vt as resolvedFactsEvidenceRequirementsHash,Qu as serializeDiagnosticCatalog,Ra as skillDescriptionVersionPrefix,K as stableSerialize,bp as stampSkillDescription,ap as statusCompassResidualIsSubsetOfDoctor,ka as stripSkillDescriptionVersion,ju as summarizeArkRunSection,Fn as toAdapterDiagnostic,ip as unavailableStatusImprovementCompass,Aa as validateAgentSkillDocument,Sp as validateAgentSkillsPackage,Ip as validateSkillProductCapacity,Ea as version};