arkgate 4.8.2 → 4.8.3

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 (51) hide show
  1. package/CHANGELOG.md +15 -3
  2. package/README.md +39 -8
  3. package/bin/lib/analysis-engine.mjs +6 -6
  4. package/bin/lib/ark-order-facts.mjs +59 -0
  5. package/bin/lib/ark-order-sensors.mjs +31 -2
  6. package/bin/lib/arkrule-file-hints.mjs +6 -2
  7. package/bin/lib/arkrules-contract.mjs +1 -0
  8. package/bin/lib/arkrules-sensors.mjs +22 -2
  9. package/bin/lib/config-extras.mjs +2 -0
  10. package/bin/lib/diagnostic-catalog.mjs +2 -1
  11. package/bin/lib/remediation.mjs +9 -1
  12. package/bin/lib/resolved-candidate-facts.mjs +31 -0
  13. package/dist/{configTypes-BdCe_gvv.d.ts → configTypes-dNJ2C0yx.d.ts} +5 -0
  14. package/dist/{diagnosticCatalog-CPzH-MLN.d.ts → diagnosticCatalog-C5GgeyEE.d.ts} +97 -7
  15. package/dist/eslint/index.cjs +6 -6
  16. package/dist/eslint/index.d.ts +1 -1
  17. package/dist/eslint/index.js +6 -6
  18. package/dist/index.cjs +34 -34
  19. package/dist/index.d.ts +24 -7
  20. package/dist/index.js +34 -34
  21. package/dist/nestjs/index.cjs +5 -5
  22. package/dist/nestjs/index.d.ts +3 -3
  23. package/dist/nestjs/index.js +5 -5
  24. package/dist/runtime/index.cjs +15 -15
  25. package/dist/runtime/index.d.ts +6 -6
  26. package/dist/runtime/index.js +15 -15
  27. package/dist/{types-C9KApBzX.d.ts → types-DeK7SYGC.d.ts} +1 -1
  28. package/dist/{types-DCSlrRnV.d.ts → types-dK24fDZa.d.ts} +1 -1
  29. package/docs/README.md +4 -4
  30. package/docs/configuration.md +12 -8
  31. package/docs/develop.md +23 -2
  32. package/docs/diagnostics.md +9 -0
  33. package/docs/enthusiast/README.md +6 -4
  34. package/docs/package-surface.md +4 -2
  35. package/docs/product-voice.md +15 -5
  36. package/docs/use.md +8 -5
  37. package/package.json +1 -1
  38. package/schemas/ark.arkrules.schema.json +1 -0
  39. package/schemas/ark.config.schema.json +9 -0
  40. package/schemas/ark.resolved-candidate-facts.schema.json +1 -1
  41. package/server.json +2 -2
  42. package/templates/agent-skills/README.md +1 -1
  43. package/templates/agent-skills/ark-adopt/SKILL.md +8 -3
  44. package/templates/agent-skills/ark-autopilot/SKILL.md +1 -1
  45. package/templates/agent-skills/ark-contract/SKILL.md +4 -0
  46. package/templates/agent-skills/ark-place/SKILL.md +6 -2
  47. package/templates/arkrules/ApplicationOrchestration.json +6 -0
  48. package/templates/skills/ark-adopt.md +8 -3
  49. package/templates/skills/ark-autopilot.md +1 -1
  50. package/templates/skills/ark-contract.md +4 -0
  51. package/templates/skills/ark-place.md +6 -2
package/dist/index.js CHANGED
@@ -1,51 +1,51 @@
1
- var fo=Object.defineProperty;var i=(e,t)=>fo(e,"name",{value:t,configurable:!0});var mo="4.8.2";var go=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,yo=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,ho=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function Ao(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),s=String(t?.toLayer??"");return go.test(n)?"pure-shared":r==="PersistenceAdapters"&&(yo.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${s} ${n}`))?"kernel-emit":ho.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&s==="PersistenceAdapters"?"use-case":"unknown"}i(Ao,"classifyLayerImportKind");function Ro(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=Ao(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(Ro,"layerImportNextAction");function ko(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}i(ko,"arkRunCallSiteName");function Eo(e){let t=ko(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(Eo,"arkRunNextAction");function pe(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return Ro(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"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";case"ARKRULE_STRUCTURE":case"ARKRULE_INVARIANT":case"INVARIANT_UNCOVERED":return`Fix the structure or invariant for ${typeof e.arkruleId=="string"&&e.arkruleId.length>0?e.arkruleId:"the ArkRule"} (declared in ${typeof e.arkruleSource=="string"&&e.arkruleSource.length>0?e.arkruleSource:"arkrules/<Layer>.json"}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`;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 Eo(e);case"ARKORDER_MISSING_PLANE":return typeof e.target=="string"&&e.target.length>0?`Import createOrderPlane from arkgate/order and call it in plane root ${e.target} listed in arkOrder.planeRoots, then preflight again.`:"Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKORDER_KERNEL_IN_DOMAIN":return"Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe.";case"ARKORDER_GENERIC_UPDATE":return"Use release() to freeze \u03BE or proposeRelease() for a pattern change with blast radius, then preflight again. Never mechanical-safe.";case"ARKORDER_TOO_MANY_PARAMS":return"Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe.";case"ARKORDER_INGEST_WRITES_XI":return"Keep ingest results as absorb/escalate only. Change \u03BE with proposeRelease + release. Never mechanical-safe.";default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(pe,"deterministicNextAction");var Qt="1.5",yr="docs/diagnostics.md";function C(e){return typeof e=="string"&&e.length>0?e:void 0}i(C,"text");function gr(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}i(gr,"positiveInteger");function en(e){let t=typeof e.ruleId=="string"?e.ruleId:typeof e.code=="string"?e.code:void 0,n=typeof e.file=="string"?e.file:void 0,r=typeof e.fromLayer=="string"?e.fromLayer:void 0,s=typeof e.toLayer=="string"?e.toLayer:void 0,o=typeof e.target=="string"?e.target:void 0;return[t,n,r??"",s??"",o??""].join("|")}i(en,"adapterFindingTargetKey");function Zt(e){let t=new Map;return e.map(n=>{let r=en(n),s=(t.get(r)??0)+1;return t.set(r,s),s===1?r:`${r}#${s}`})}i(Zt,"adapterFindingOccurrenceTargetKeys");function hr(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(hr,"adapterFindingRefFromTargetKey");function Ar(e){return`${yr}#${e}`}i(Ar,"adapterDocsCodePath");function So(e,t,n){return pe({ruleId:e,target:C(t.target)??C(n.target)??void 0,fromLayer:C(t.fromLayer)??void 0,toLayer:C(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:C(t.edgeKind)??void 0,capability:C(t.capability)??C(n.capability)??void 0,arkruleId:C(t.arkruleId)??void 0,arkruleSource:C(t.arkruleSource)??void 0})}i(So,"nextActionForDiagnostic");function Xt(e,t="error",n){let r=C(e.ruleId)??C(e.code)??"ARK_UNKNOWN",s=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,o={...C(e.target)?{target:C(e.target)}:{},...C(e.fromLayer)?{fromLayer:C(e.fromLayer)}:{},...C(e.toLayer)?{toLayer:C(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}:{},...C(e.capability)?{capability:C(e.capability)}:{},...C(e.edgeKind)?{edgeKind:C(e.edgeKind)}:{},...C(e.arkruleId)?{arkruleId:C(e.arkruleId)}:{},...C(e.arkruleSource)?{arkruleSource:C(e.arkruleSource)}:{}},a=n??en(e),l=hr(a);return{ruleId:r,severity:s,message:C(e.message)??r,location:{file:C(e.file)??"<unknown>",line:gr(e.line,1),column:gr(e.column,1)},evidence:o,nextAction:C(e.nextAction)??So(r,o,e),findingRef:l,targetKey:a,docsCodePath:Ar(r)}}i(Xt,"toAdapterDiagnostic");function Io(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:C(g.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:C(g.message)??`Analysis ${t}: required evidence is incomplete.`,...C(g.file)?{file:C(g.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],s={...C(e.policyHash)?{policyHash:C(e.policyHash)}:{},...C(e.resolverIdentity)?{resolverIdentity:C(e.resolverIdentity)}:{},...C(e.factsHash)?{factsHash:C(e.factsHash)}:{},...C(e.candidateTreeHash)?{candidateTreeHash:C(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let g of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!s[g])throw new Error(`${g} is required for resolved ${t} adapter evidence.`)}let o=e.violations??[],a=e.warnings??[],l=Zt(o),c=Zt(a),p=[...o.map((g,u)=>Xt(g,"error",l[u])),...a.map((g,u)=>Xt(g,"warning",c[u]))],m={schemaVersion:Qt,completenessReasons:r,diagnostics:p};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...m,mode:n,valid:!1,completeness:t,...s};let g={policyHash:s.policyHash,resolverIdentity:s.resolverIdentity,factsHash:s.factsHash,candidateTreeHash:s.candidateTreeHash};return t==="complete"?{...m,mode:n,valid:e.valid,completeness:t,...g}:{...m,mode:n,valid:!1,completeness:t,...g}}return t==="complete"?{...m,mode:n,valid:e.valid,completeness:t,...s}:{...m,mode:n,valid:!1,completeness:t,...s}}i(Io,"createAdapterResult");var vo={$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:Qt},mode:{enum:["lexical-compatibility","resolved-candidate-facts"]},valid:{type:"boolean"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:{type:"string",minLength:1},message:{type:"string",minLength:1},file:{type:"string",minLength:1}}}},policyHash:{type:"string",minLength:1},resolverIdentity:{type:"string",minLength:1},factsHash:{type:"string",minLength:1},candidateTreeHash:{type:"string",minLength:1},diagnostics:{type:"array",items:{type:"object",additionalProperties:!1,required:["ruleId","severity","message","location","evidence"],properties:{ruleId:{type:"string",minLength:1},severity:{enum:["error","warning"]},message:{type:"string",minLength:1},location:{type:"object",additionalProperties:!1,required:["file","line","column"],properties:{file:{type:"string",minLength:1},line:{type:"integer",minimum:1},column:{type:"integer",minimum:1}}},evidence:{type:"object",additionalProperties:!1,properties:{target:{type:"string"},fromLayer:{type:"string"},toLayer:{type:"string"},typeOnly:{type:"boolean"},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"},peerIsolation:{type:"boolean"},capability:{type:"string",minLength:1},edgeKind:{type:"string",minLength:1},arkruleId:{type:"string",minLength:1},arkruleSource:{type:"string",minLength:1}}},nextAction:{type:"string",minLength:1},findingRef:{type:"string",minLength:1,pattern:"^fnv1a-[0-9a-f]{8}$"},targetKey:{type:"string",minLength:1},docsCodePath:{type:"string",minLength:1}}}}}};var bo="1.0",Rr="https://unpkg.com/arkgate@4/schemas/ark.project-identity.schema.json",Rt="^sha256:[a-f0-9]{64}$",kr={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:Rt,description:"Project id previously returned by ark_identity or ark_manifest."}}},Er={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:Rt},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},Co={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Rr,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:Rt},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{type:"string",minLength:1},arkgateVersion:{type:"string",minLength:1},contractHash:{type:"string",pattern:Rt},contractSource:{enum:["project","default-profile","manifest"]},runtimeId:{type:"string",minLength:1},processStartedAt:{type:"string",format:"date-time"}},$defs:{expectation:kr,binding:Er}};function _o(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(_o,"createProjectId");function Oo(e){return{schemaVersion:"1.0",...e}}i(Oo,"createProjectIdentity");var nn=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),sn=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),on=Object.freeze(Object.keys(sn).sort()),tn=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"}),rn=Object.freeze({process:Object.freeze(["process","node:process"])});function Ye(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=tn[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),s=tn[r];if(s)return s;let o=e.indexOf("/",n+1);return o<0?null:tn[e.slice(0,o)]??null}i(Ye,"capabilityForModuleSpecifier");function Ie(e,t){for(let n of t)if(rn[n]?.includes(e))return n;return null}i(Ie,"forbiddenGlobalForModuleSpecifier");function kt(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),s=sn[r];if(s)return s}return null}i(kt,"capabilityForAmbientName");function Le(e){if(e?.pure===!0)return[...nn].sort();let n=(e?.capabilities?.deny??[]).filter(r=>nn.includes(r));return[...new Set(n)].sort()}i(Le,"effectiveCapabilityDeny");function We(e,t){if(t.length===0)return!1;let n=new Set(t),r=e.split(".");for(let s=r.length;s>=1;s-=1)if(n.has(r.slice(0,s).join(".")))return!0;return!1}i(We,"ambientCoveredByForbiddenGlobals");function Et(e){let t=new Set,n=new Set,r=Object.keys(sn);for(let s of e?.forbiddenGlobals??[]){let o=r.filter(a=>a===s||a.startsWith(`${s}.`));if(o.length===0)n.add(s);else for(let a of o)t.add(`ambient:${a}`);for(let a of rn[s]??[])t.add(`import-exact:${a}`)}for(let s of Le(e)){if(t.add(`import:${s}`),s==="process")for(let o of rn.process)t.add(`import-exact:${o}`);for(let o of r)kt(o)===s&&t.add(`ambient:${o}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}i(Et,"loweredLayerCoverage");var Sr=new Map;function Ir(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(Ir,"escapeLiteral");function St(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let s=e[n+1];if("*?{}[],".includes(s)||s==="\\"){t+="\\"+s,n+=1;continue}t+="/";continue}t+=r}return t}i(St,"normalizeGlobSeparators");function xo(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(xo,"bracesBalanced");function Ce(e){let t=Sr.get(e);if(t)return t;let n=St(e),r=xo(n),s="",o=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(s+=Ir(n[l+1]),l+=1):c==="*"?n[l+1]==="*"?n[l+2]==="/"?(s+="(?:.*/)?",l+=2):(s+=".*",l+=1):s+="[^/]*":c==="?"?s+="[^/]":c==="{"&&r?(s+="(?:",o+=1):c==="}"&&r&&o>0?(s+=")",o-=1):c===","&&r&&o>0?s+="|":s+=Ir(c)}let a=new RegExp(`^${s}$`);return Sr.set(e,a),a}i(Ce,"globToRegExp");function To(e){return St(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}i(To,"concreteGlobSegments");function an(e,t){let n=St(String(e)),r=To(n),s=n.replace(/\*/g,"").length,o=r.length*1e4+s;if(t==null||t==="")return o;let a=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return s;let l=0,c=-1;for(let p of r){let m=-1;for(let g=l;g<a.length;g+=1)if(a[g]===p){m=g;break}if(m<0)return o;c=m,l=m+1}return(c+1)*1e6+r.length*1e4+s}i(an,"patternSpecificity");function ie(e,t){let n=String(e).split(/[/\\]/).join("/"),r,s=-1;for(let o of t??[])if(!(o.exclude??[]).some(a=>Ce(a).test(n))){for(let a of o.patterns??[])if(Ce(a).test(n)){let l=an(a,n);l>s&&(s=l,r=o.name)}}return r}i(ie,"layerForRelativePath");function vr(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),r=new Set(t.map(s=>String(s).toLowerCase()));for(let s=0;s<n.length-1;s+=1)if(r.has(n[s].toLowerCase()))return`${n[s].toLowerCase()}/${n[s+1].toLowerCase()}`}i(vr,"sliceIdForPath");function No(e){let t=new Set;for(let n of e??[]){let s=St(String(n)).split("/").filter(Boolean);for(let o=0;o<s.length;o+=1){let a=s[o];if((a==="**"||a==="*")&&o>0){let l=s[o-1];l&&!l.includes("*")&&!l.includes("{")&&!l.includes("}")&&t.add(l)}}}return[...t]}i(No,"inferSliceFoldersFromPatterns");function Po(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(s=>typeof s=="string"&&s.length>0);let r=(n??[]).find(s=>s.name===t);return No(r?.patterns)}i(Po,"resolveSliceFolders");function Lo(e){return!e.fromPath||!e.toPath||e.folderCount<=0||!e.fromSlice||!e.toSlice?!0:e.fromSlice!==e.toSlice}i(Lo,"peerIsolationMustDeny");function me(e,t,n,r){for(let s of e??[])if(!(s.from!==t||s.to!==n)&&s.allowed===!1){if(s.peerIsolation){let o=r?.fromPath,a=r?.toPath,l=Po(s,t,r?.layers),c=o&&a?vr(o,l):void 0,p=o&&a?vr(a,l):void 0;if(Lo({fromPath:o,toPath:a,folderCount:l.length,fromSlice:c,toSlice:p}))return s;continue}if(t!==n)return s}}i(me,"findDeniedEdgeRule");function we(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(we,"literalText");function _r(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}i(_r,"lineOf");function br(e,t){if(e.isImportDeclaration(t)){let r=t.importClause;if(!r)return!1;if(r.isTypeOnly)return!0;let s=r.namedBindings;return!!(s&&e.isNamedImports(s)&&s.elements.length>0&&s.elements.every(o=>o.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(r=>r.isTypeOnly))}i(br,"isTypeOnlyReference");function Or(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=s=>s===t.fileName?t:void 0,r.fileExists=s=>s===t.fileName,r.readFile=s=>s===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}i(Or,"singleFileChecker");function ln(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}i(ln,"symbolAt");function cn(e,t,n,r){let s=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,o;try{o=s?t.getShorthandAssignmentValueSymbol(r.parent):ln(t,r)}catch{o=void 0}return!!o?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}i(cn,"localDeclaration");function De(e,t){let n,r=[],s=i((a,l,c,p=!1)=>r.push({specifier:c,kind:l,line:_r(t,a),typeOnly:p,unresolved:c===void 0,node:a}),"add"),o=i(a=>{if(e.isImportDeclaration(a))s(a,"import",we(e,a.moduleSpecifier),br(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)s(a,"export",we(e,a.moduleSpecifier),br(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))s(a,"require",we(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let l=a.expression.kind===e.SyntaxKind.ImportKeyword,p=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!cn(e,n??(n=Or(e,t)),t,a.expression);(l||p)&&s(a,p?"require":"dynamic-import",we(e,a.arguments[0]))}e.forEachChild(a,o)},"visit");return o(t),r}i(De,"extractSemanticDependencies");function wo(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let s=we(e,r.argumentExpression);if(s===void 0)return;n.unshift(s)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}i(wo,"staticAccessPath");function Do(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(Do,"runtimeIdentifierReference");function Cr(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let r=n.length;r>=1;r-=1){let s=n.slice(0,r).join(".");if(e.has(s))return s}}i(Cr,"bestForbiddenMatch");function Me(e,t,n){if(n.length===0)return[];let r=new Set(n),s=Or(e,t),o=new Map,a=new Set;for(let u of t.statements)if(e.isVariableStatement(u))for(let d of u.declarationList.declarations)e.isIdentifier(d.name)&&a.add(d.name.text);let l=i(u=>{let d=wo(e,u);if(!d)return;let f=ln(s,d.root),y=f?o.get(f):void 0;return y?[...y,...d.segments.slice(1)]:cn(e,s,t,d.root)||a.has(d.root.text)?void 0:d.segments},"resolvePath");for(let u of t.statements)if(e.isVariableStatement(u))for(let d of u.declarationList.declarations){if(!d.initializer||!e.isIdentifier(d.name))continue;let f=l(d.initializer),y=ln(s,d.name);!f||!y||o.set(y,f)}let c=[],p=new Set,m=i((u,d)=>{let f=_r(t,d),y=`${u}:${d.getStart(t)}`;p.has(y)||(p.add(y),c.push({name:u,line:f,node:d}))},"flag"),g=i(u=>{let d=u.parent&&(e.isPropertyAccessExpression(u.parent)||e.isElementAccessExpression(u.parent))&&u.parent.expression===u;if((e.isPropertyAccessExpression(u)||e.isElementAccessExpression(u))&&!d){let f=l(u),y=f?Cr(r,f):void 0;y&&m(y,u)}else e.isIdentifier(u)&&r.has(u.text)&&Do(e,u)&&!cn(e,s,t,u)&&m(u.text,u);if(e.isVariableDeclaration(u)&&e.isObjectBindingPattern(u.name)&&u.initializer){let f=l(u.initializer);if(f)for(let y of u.name.elements){if(!e.isIdentifier(y.name))continue;let I=y.propertyName?we(e,y.propertyName)??y.propertyName.text:y.name.text,N=Cr(r,[...f,I]);N&&m(N,u.initializer)}}e.forEachChild(u,g)},"visit");return g(t),c}i(Me,"collectForbiddenCapabilityUses");function dn(e,t,n){let r=[];for(let s of n?.dependencies??De(e,t)){if(s.typeOnly||!s.specifier)continue;let o=Ye(s.specifier);o&&r.push({capability:o,symbol:s.specifier,line:s.line,source:"import-based"})}for(let s of n?.ambientUses??Me(e,t,on)){let o=kt(s.name);o&&r.push({capability:o,symbol:s.name,line:s.line,source:"ambient-global"})}return r.sort((s,o)=>s.line-o.line||s.capability.localeCompare(o.capability)||s.symbol.localeCompare(o.symbol))}i(dn,"collectCapabilityUses");var un={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."},pn=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,s)=>(r.prefixes??r.intentPrefixes??[]).map(o=>({layer:r.name,layerIndex:s,prefix:o.endsWith(".")?o:`${o}.`}))).filter(({prefix:r})=>e.startsWith(r)).sort((r,s)=>s.prefix.length-r.prefix.length||r.layerIndex-s.layerIndex)[0]?.layer}i(fn,"resolveIntentLayer");function _e(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}i(_e,"looksLikeArkIntent");function Je(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&_e(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:un.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:un.PUBLISH_MISSING_SOURCE}),t}i(Je,"classifyPublishFacts");function V(e,t,n){return{ruleId:e,code:e,message:t,...n}}i(V,"violation");function Fe(e,t){return e.slice(0,t).split(`
2
- `).length}i(Fe,"lineOf");function Mo(e){let t=[],n=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,r;for(;(r=n.exec(e))!==null;)t.push({value:r[1],index:r.index});return t}i(Mo,"extractQuotedStrings");function Fo(e){let t=[],n=[{kind:"import",re:/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s*)?['"]([^'"]+)['"]/g},{kind:"export",re:/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s*['"]([^'"]+)['"]/g},{kind:"dynamic-import",re:/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g},{kind:"require",re:/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g}];for(let r of n){let s;for(;(s=r.re.exec(e))!==null;){let o=s.index+s[0].indexOf(s[1]),a=s[0],l=r.kind==="import"&&/\bimport\s+type\b/.test(a)||r.kind==="export"&&/\bexport\s+type\b/.test(a);t.push({value:s[1],index:o,kind:r.kind,typeOnly:l})}}return t.sort((r,s)=>r.index-s.index)}i(Fo,"extractModuleSpecifiers");function $o(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],s=i(o=>{e.isStringLiteralLike(o)&&r.push({value:o.text,index:o.getStart(n)}),e.forEachChild(o,s)},"visit");return s(n),r}i($o,"extractQuotedStringsAst");function Ho(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(Ho,"hasInfrastructureToken");function jo(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}i(jo,"isKnownInfrastructurePackage");function Vo(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}i(Vo,"layerHasInfrastructureRole");function Xe(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(Xe,"tsStringLiteralText");function Uo(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}i(Uo,"tsPropertyName");function xr(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:Uo(e,r.name)===n)}i(xr,"tsObjectProperty");function Qe(e,t,n){return xr(e,t,n)!==void 0}i(Qe,"tsObjectHasProperty");function Ze(e,t,n){let r=xr(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}i(Ze,"tsObjectPropertyValue");function Ko(e,t){let n=Ze(e,t,"metadata");return Qe(e,n,"source")}i(Ko,"tsObjectHasMetadataSource");function Tr(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?Tr(e,t.name):!1:!1}i(Tr,"tsLooksLikeIntentCreatorExpression");function Go(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(Go,"tsIsPublishCall");function Bo(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=Xe(e,n);return r!==void 0&&_e(r)||Qe(e,n,"intent")||Tr(e,n)}i(Bo,"tsIsArkPublishCandidate");function zo(e,t){if(!e.isCallExpression(t))return!1;let[n,r,s]=t.arguments;return Ko(e,n)||Qe(e,r,"source")||Qe(e,s,"source")}i(zo,"tsPublishHasSource");function qo(e,t){if(!e.isCallExpression(t))return;let[n,r,s]=t.arguments,o=Ze(e,n,"metadata");return Xe(e,Ze(e,o,"source"))??Xe(e,Ze(e,r,"source"))??Xe(e,Ze(e,s,"source"))}i(qo,"tsPublishSourceLiteral");function Yo(e,t,n,r){let s=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),o=n,a=o?.filePath,l=o?.layer,c=[],p=i(g=>s.getLineAndCharacterOfPosition(g.getStart(s)).line+1,"lineForNode"),m=i(g=>{if(Go(e,g)){let u=g.arguments[0],d=Xe(e,u);for(let y of Je({publishCall:!0,rawIntentName:d,objectHasIntent:Qe(e,u,"intent"),arkPublishCandidate:Bo(e,g),hasSource:zo(e,g)}))c.push(V(y.ruleId,y.message,{line:p(g),filePath:a}));let f=qo(e,g);if(r&&l&&f&&_e(f)){let y=r.resolveLayer(f);y&&y!==l&&c.push(V("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${f}" resolves to ${y}, but the target file is classified as ${l}.`,{line:p(g),filePath:a,target:f,fromLayer:l,toLayer:y}))}}e.forEachChild(g,m)},"visit");return m(s),c}i(Yo,"analyzePublishAst");function Nr(e={}){let t=new Set((e.intents||[]).map(o=>typeof o=="string"?o:o.name)),n=e.forbiddenPatterns||[],r=new Set(e.infrastructureLayers??[]),s=e.enforceIntentAllowlist??t.size>0;return{validate(o,a){let l=[],c=a,p=c?.filePath,m=c?.layer,g=e.typescript,u=g?g.createSourceFile(p??"generated.ts",o,g.ScriptTarget.Latest,!0):void 0,d=u?De(e.typescript,u):void 0,f=d?d.filter(E=>E.specifier!==void 0).map(E=>({value:E.specifier,index:E.node.getStart(u),kind:E.kind,typeOnly:E.typeOnly})):Fo(o),y=e.typescript?$o(e.typescript,o):Mo(o);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(p))for(let E of d?.filter(({unresolved:k})=>k)??[]){let k=E.kind==="require";l.push(V(k?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${k?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:E.line,filePath:p}))}let I=m!==void 0&&(r.has(m)||Vo(m)),N=m!==void 0?` If "${m}" is an infrastructure layer, mark it in ark.config.json with "mayImportInfrastructure": true (or name it with an infra token like Adapters/Persistence/Repository).`:"";for(let E of n)if(E instanceof RegExp){E.lastIndex=0;let k=E.exec(o);E.lastIndex=0,k&&l.push(V("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${E}`,{line:k.index===void 0?void 0:Fe(o,k.index),filePath:p,suggestion:"Remove infrastructure imports from domain/application layers."+N}))}else o.includes(E)&&l.push(V("FORBIDDEN_SUBSTRING",`Forbidden substring: ${E}`,{line:Fe(o,o.indexOf(E)),filePath:p}));for(let E of f){let k=e.resolveImportTarget?.(E.value,p)??(e.resolveImportLayer?{layer:e.resolveImportLayer(E.value,p)}:void 0),b=typeof p=="string"?e.resolveImportTarget?.(p)??(e.resolveImportLayer?{layer:m,relPath:void 0}:void 0):void 0,J=k?.layer;if(J&&m){let H=me(e.architectureProfile?.rules,m,J,{fromPath:b?.relPath,toPath:k?.relPath,layers:e.architectureLayers});if(H){if(E.typeOnly&&!H.peerIsolation)continue;let G=!!H.peerIsolation;l.push(V("LAYER_IMPORT_VIOLATION",H.message??(G?`Layer "${m}" must not import across slices into "${J}".`:`Layer "${m}" must not import "${J}".`),{line:Fe(o,E.index),source:E.value,target:E.value,filePath:p,fromLayer:m,toLayer:J,suggestion:G?"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:E.kind,peerIsolation:G,...E.typeOnly?{typeOnly:!0}:{}}}));continue}continue}I||E.typeOnly||!Ho(E.value)&&!jo(E.value)||l.push(V("FORBIDDEN_IMPORT",`Forbidden ${E.kind} target: "${E.value}".`,{line:Fe(o,E.index),source:E.value,target:E.value,filePath:p,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+N,details:{importKind:E.kind}}))}if(e.policies)for(let E of e.policies){let k=E.check({source:o,context:a});if(k!==!0)if(Array.isArray(k))for(let b of k)l.push(V("POLICY_VIOLATION",b.message,{filePath:p,suggestion:`Fix violation of policy "${E.name}".`}));else k===!1?l.push(V("POLICY_VIOLATION",`Policy ${E.name} failed on generated code`)):l.push(V("POLICY_VIOLATION",k.message))}if(s&&t.size>0)for(let E of y)_e(E.value)&&!t.has(E.value)&&l.push(V("UNKNOWN_INTENT",`Unknown intent reference: "${E.value}"`,{line:Fe(o,E.index),filePath:p,target:E.value,suggestion:`Register intent "${E.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&m)for(let E of y){if(!_e(E.value))continue;let k=e.architectureProfile.resolveLayer(E.value);if(!k)continue;let b=me(e.architectureProfile.rules,m,k);b&&l.push(V("LAYER_REFERENCE_VIOLATION",b.message??`Layer "${m}" must not reference "${k}" through "${E.value}".`,{line:Fe(o,E.index),filePath:p,target:E.value,fromLayer:m,toLayer:k,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:b}}))}if(e.extensions)for(let E of e.extensions)try{let k=E.analyze(o,a);l.push(...k)}catch(k){l.push(V("EXTENSION_ERROR",`Extension "${E.name}" failed: ${k instanceof Error?k.message:String(k)}`))}if(e.typescript&&u&&m&&e.forbiddenGlobals?.[m]?.length)try{let E=e.forbiddenGlobals[m];l.push(...Me(e.typescript,u,E).map(k=>V("FORBIDDEN_GLOBAL",`${m} must not use the ambient global "${k.name}".`,{line:k.line,filePath:p,target:k.name,fromLayer:m,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let k of d??[]){if(k.typeOnly||!k.specifier)continue;let b=Ie(k.specifier,E);b&&l.push(V("FORBIDDEN_GLOBAL",`${m} must not use module "${k.specifier}" because it is the import form of forbidden global "${b}".`,{line:k.line,filePath:p,source:k.specifier,target:k.specifier,fromLayer:m,details:{importKind:k.kind,forbiddenGlobal:b},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(E){l.push(V("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${E instanceof Error?E.message:String(E)}`))}if(e.typescript&&u&&m&&e.capabilityWalls?.[m]?.length)try{let E=new Set(e.capabilityWalls[m]),k=e.forbiddenGlobals?.[m]??[];for(let b of dn(e.typescript,u))E.has(b.capability)&&(b.source==="ambient-global"&&We(b.symbol,k)||b.source==="import-based"&&Ie(b.symbol,k)||l.push(V("CAPABILITY_VIOLATION",b.source==="import-based"?`${m} denies the ${b.capability} capability; found import of "${b.symbol}".`:`${m} denies the ${b.capability} capability; found ambient "${b.symbol}".`,{line:b.line,filePath:p,target:b.symbol,capability:b.capability,fromLayer:m,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(E){l.push(V("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${E instanceof Error?E.message:String(E)}`))}if(e.typescript)try{l.push(...Yo(e.typescript,o,a,e.architectureProfile))}catch(E){l.push(V("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${E instanceof Error?E.message:String(E)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:l.length===0,violations:l}}}}i(Nr,"createAICodeGate");var et={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Pr={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...et,default:[]},kernelRoots:{...et},managedLayers:{...et,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},Lr={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...et,default:[]},managedLayers:{...et,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7}}};function tt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(tt,"isObject");function wr(e){let t=new Set;if(!Array.isArray(e.layers))return t;for(let n of e.layers)tt(n)&&typeof n.name=="string"&&n.name.length>0&&t.add(n.name);return t}i(wr,"declaredLayerNames");function Dr(e){if(!tt(e))return e;let t={mode:e.mode===void 0?"advisory":e.mode,compositionRoots:e.compositionRoots===void 0?[]:e.compositionRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,requireDeclarations:e.requireDeclarations===void 0?!0:e.requireDeclarations};return e.kernelRoots!==void 0&&(t.kernelRoots=e.kernelRoots),e.ignoreDirectNewForErrors!==void 0&&(t.ignoreDirectNewForErrors=e.ignoreDirectNewForErrors),{...e,...t}}i(Dr,"defaultedArkRun");function Mr(e){if(!tt(e))return e;let t=typeof e.maxXiKeys=="number"&&e.maxXiKeys>0?e.maxXiKeys:7;return{...e,mode:e.mode===void 0?"advisory":e.mode,planeRoots:e.planeRoots===void 0?[]:e.planeRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,maxXiKeys:t}}i(Mr,"defaultedArkOrder");function Fr(e,t){let n=e.arkRun;if(n===void 0||!tt(n))return;let r=wr(e),s=n.managedLayers;if(Array.isArray(s)&&s.forEach((o,a)=>{typeof o=="string"&&o.length>0&&!r.has(o)&&t.push({path:`$.arkRun.managedLayers[${a}]`,message:`layer ${JSON.stringify(o)} is not declared in layers[]`})}),n.mode==="enforced"){let o=n.kernelRoots??n.compositionRoots;(!Array.isArray(o)||o.length===0)&&t.push({path:n.kernelRoots!==void 0?"$.arkRun.kernelRoots":"$.arkRun.compositionRoots",message:"ARKRUN_MISSING_ROOT: enforced mode requires at least one kernel root"}),(!Array.isArray(s)||s.length===0)&&t.push({path:"$.arkRun.managedLayers",message:"enforced mode requires at least one managed layer"})}}i(Fr,"validateArkRunExtra");function $r(e,t){let n=e.arkOrder;if(n===void 0||!tt(n))return;let r=wr(e),s=n.managedLayers;if(Array.isArray(s)&&s.forEach((o,a)=>{typeof o=="string"&&o.length>0&&!r.has(o)&&t.push({path:`$.arkOrder.managedLayers[${a}]`,message:`layer ${JSON.stringify(o)} is not declared in layers[]`})}),n.mode==="enforced"){let o=n.planeRoots;(!Array.isArray(o)||o.length===0)&&t.push({path:"$.arkOrder.planeRoots",message:"ARKORDER_MISSING_PLANE: enforced mode requires at least one plane root"}),(!Array.isArray(s)||s.length===0)&&t.push({path:"$.arkOrder.managedLayers",message:"enforced mode requires at least one managed layer"})}}i($r,"validateArkOrderExtra");var ne="1.3",vt="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",Hr=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Wo=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Jo(){let e=[];for(let t of Hr)for(let n of Hr)t===n||Wo.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}i(Jo,"createDefaultRules");var bt=Jo(),mn=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"},{from:"1.1",to:"1.2"},{from:"1.2",to:"1.3"}],ge={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},gn={$schema:"https://json-schema.org/draft/2020-12/schema",$id:vt,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:vt,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:ne,default:ne},name:{type:"string",minLength:1},include:{...ge,minItems:1,default:["src"]},exclude:{...ge,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:bt,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...ge,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},arkRun:{$ref:"#/$defs/arkRun"},arkOrder:{$ref:"#/$defs/arkOrder"},stewards:{...ge,default:[]}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...ge,minItems:1},exclude:ge,intentPrefixes:ge,description:{type:"string",minLength:1},forbiddenGlobals:ge,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:{...ge,minItems:1}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}},arkRun:Pr,arkOrder:Lr}},ye=class extends Error{static{i(this,"ArkConfigValidationError")}issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
1
+ var ma=Object.defineProperty;var i=(e,t)=>ma(e,"name",{value:t,configurable:!0});var ga="4.8.3";var ya=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,ha=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,Aa=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function Ra(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),s=String(t?.toLayer??"");return ya.test(n)?"pure-shared":r==="PersistenceAdapters"&&(ha.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${s} ${n}`))?"kernel-emit":Aa.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&s==="PersistenceAdapters"?"use-case":"unknown"}i(Ra,"classifyLayerImportKind");function ka(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=Ra(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(ka,"layerImportNextAction");function Ea(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}i(Ea,"arkRunCallSiteName");function Ia(e){let t=Ea(e),n=typeof e.fromLayer=="string"&&e.fromLayer.length>0?e.fromLayer:void 0;switch(e.ruleId){case"ARKRUN_MISSING_ROOT":return t?`Import createStrictArkKernel from arkgate/runtime and call it in composition root ${t} listed in arkRun.compositionRoots, then preflight again.`:"Import createStrictArkKernel from arkgate/runtime (same npm package; @arkgate/runtime is deprecated) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKRUN_KERNEL_IN_DOMAIN":return t?`Move the kernel import of ${t} out of ${n??"the Domain-role layer"} into a composition root or adapter. Import from arkgate/runtime, then preflight again.`:"Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from arkgate/runtime (same npm package; @arkgate/runtime is deprecated), then preflight again. Never mechanical-safe.";case"ARKRUN_DIRECT_NEW":return t?`Resolve ${t} from the kernel instead of constructing it with new, then preflight again.`:"Resolve the type from the kernel instead of constructing it with new, then preflight again. Never mechanical-safe \u2014 rewiring construction is a design decision.";case"ARKRUN_UNDECLARED_EMIT":return t?`Add ${t} to raises or sends on the managed component, then preflight again.`:"Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment.";case"ARKRUN_UNDECLARED_HANDLE":return t?`Add ${t} to reactsTo on the managed component, then preflight again.`:"Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment.";case"ARKRUN_UNDECLARED_DEPEND":return t?`Add ${t} to uses on the managed component, then preflight again.`:"Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment.";case"ARKRUN_TRANSPORT_BYPASS":return t?`Send through the ArkRun kernel transport instead of importing ${t}, then preflight again.`:"Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe \u2014 homemade buses stay judgment.";default:return`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(Ia,"arkRunNextAction");function pe(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return ka(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"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";case"ARKRULE_STRUCTURE":case"ARKRULE_INVARIANT":case"INVARIANT_UNCOVERED":return`Fix the structure or invariant for ${typeof e.arkruleId=="string"&&e.arkruleId.length>0?e.arkruleId:"the ArkRule"} (declared in ${typeof e.arkruleSource=="string"&&e.arkruleSource.length>0?e.arkruleSource:"arkrules/<Layer>.json"}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`;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 Ia(e);case"ARKORDER_MISSING_PLANE":return typeof e.target=="string"&&e.target.length>0?`Import createOrderPlane from arkgate/order and call it in plane root ${e.target} listed in arkOrder.planeRoots, then preflight again.`:"Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKORDER_KERNEL_IN_DOMAIN":return"Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe.";case"ARKORDER_GENERIC_UPDATE":return"Use release() to freeze \u03BE or proposeRelease() for a pattern change with blast radius, then preflight again. Never mechanical-safe.";case"ARKORDER_TOO_MANY_PARAMS":return"Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe.";case"ARKORDER_INGEST_WRITES_XI":return"Keep ingest results as absorb/escalate only. Change \u03BE with proposeRelease + release. Never mechanical-safe.";case"ARKORDER_XI_FIELD_WRITE":return typeof e.target=="string"&&e.target.length>0?`Do not persist slow key ${e.target} from a use-case. Absorb the field with ingest() or change the pattern with proposeRelease(), then preflight again.`:"Do not persist a declared slow key from a use-case. Absorb the field with ingest() or change the pattern with proposeRelease(), then preflight again. Never mechanical-safe.";default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(pe,"deterministicNextAction");var nn="1.5",Ar="docs/diagnostics.md";function O(e){return typeof e=="string"&&e.length>0?e:void 0}i(O,"text");function hr(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}i(hr,"positiveInteger");function rn(e){let t=typeof e.ruleId=="string"?e.ruleId:typeof e.code=="string"?e.code:void 0,n=typeof e.file=="string"?e.file:void 0,r=typeof e.fromLayer=="string"?e.fromLayer:void 0,s=typeof e.toLayer=="string"?e.toLayer:void 0,a=typeof e.target=="string"?e.target:void 0;return[t,n,r??"",s??"",a??""].join("|")}i(rn,"adapterFindingTargetKey");function en(e){let t=new Map;return e.map(n=>{let r=rn(n),s=(t.get(r)??0)+1;return t.set(r,s),s===1?r:`${r}#${s}`})}i(en,"adapterFindingOccurrenceTargetKeys");function Rr(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(Rr,"adapterFindingRefFromTargetKey");function kr(e){return`${Ar}#${e}`}i(kr,"adapterDocsCodePath");function Sa(e,t,n){return pe({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(Sa,"nextActionForDiagnostic");function tn(e,t="error",n){let r=O(e.ruleId)??O(e.code)??"ARK_UNKNOWN",s=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,a={...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)}:{}},o=n??rn(e),l=Rr(o);return{ruleId:r,severity:s,message:O(e.message)??r,location:{file:O(e.file)??"<unknown>",line:hr(e.line,1),column:hr(e.column,1)},evidence:a,nextAction:O(e.nextAction)??Sa(r,a,e),findingRef:l,targetKey:o,docsCodePath:kr(r)}}i(tn,"toAdapterDiagnostic");function ba(e){let t=e.completeness??"complete",n=e.mode??"lexical-compatibility";if(t==="complete"&&(e.completenessReasons?.length??0)>0)throw new Error("completenessReasons must be empty when completeness is complete.");let r=t==="complete"?[]:e.completenessReasons&&e.completenessReasons.length>0?e.completenessReasons.map(y=>({code:O(y.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:O(y.message)??`Analysis ${t}: required evidence is incomplete.`,...O(y.file)?{file:O(y.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],s={...O(e.policyHash)?{policyHash:O(e.policyHash)}:{},...O(e.resolverIdentity)?{resolverIdentity:O(e.resolverIdentity)}:{},...O(e.factsHash)?{factsHash:O(e.factsHash)}:{},...O(e.candidateTreeHash)?{candidateTreeHash:O(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let y of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!s[y])throw new Error(`${y} is required for resolved ${t} adapter evidence.`)}let a=e.violations??[],o=e.warnings??[],l=en(a),c=en(o),p=[...a.map((y,f)=>tn(y,"error",l[f])),...o.map((y,f)=>tn(y,"warning",c[f]))],g={schemaVersion:nn,completenessReasons:r,diagnostics:p};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...g,mode:n,valid:!1,completeness:t,...s};let y={policyHash:s.policyHash,resolverIdentity:s.resolverIdentity,factsHash:s.factsHash,candidateTreeHash:s.candidateTreeHash};return t==="complete"?{...g,mode:n,valid:e.valid,completeness:t,...y}:{...g,mode:n,valid:!1,completeness:t,...y}}return t==="complete"?{...g,mode:n,valid:e.valid,completeness:t,...s}:{...g,mode:n,valid:!1,completeness:t,...s}}i(ba,"createAdapterResult");var va={$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:nn},mode:{enum:["lexical-compatibility","resolved-candidate-facts"]},valid:{type:"boolean"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:{type:"string",minLength:1},message:{type:"string",minLength:1},file:{type:"string",minLength:1}}}},policyHash:{type:"string",minLength:1},resolverIdentity:{type:"string",minLength:1},factsHash:{type:"string",minLength:1},candidateTreeHash:{type:"string",minLength:1},diagnostics:{type:"array",items:{type:"object",additionalProperties:!1,required:["ruleId","severity","message","location","evidence"],properties:{ruleId:{type:"string",minLength:1},severity:{enum:["error","warning"]},message:{type:"string",minLength:1},location:{type:"object",additionalProperties:!1,required:["file","line","column"],properties:{file:{type:"string",minLength:1},line:{type:"integer",minimum:1},column:{type:"integer",minimum:1}}},evidence:{type:"object",additionalProperties:!1,properties:{target:{type:"string"},fromLayer:{type:"string"},toLayer:{type:"string"},typeOnly:{type:"boolean"},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"},peerIsolation:{type:"boolean"},capability:{type:"string",minLength:1},edgeKind:{type:"string",minLength:1},arkruleId:{type:"string",minLength:1},arkruleSource:{type:"string",minLength:1}}},nextAction:{type:"string",minLength:1},findingRef:{type:"string",minLength:1,pattern:"^fnv1a-[0-9a-f]{8}$"},targetKey:{type:"string",minLength:1},docsCodePath:{type:"string",minLength:1}}}}}};var Ca="1.0",Er="https://unpkg.com/arkgate@4/schemas/ark.project-identity.schema.json",Rt="^sha256:[a-f0-9]{64}$",Ir={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:Rt,description:"Project id previously returned by ark_identity or ark_manifest."}}},Sr={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:Rt},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},Oa={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Er,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:Rt},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{type:"string",minLength:1},arkgateVersion:{type:"string",minLength:1},contractHash:{type:"string",pattern:Rt},contractSource:{enum:["project","default-profile","manifest"]},runtimeId:{type:"string",minLength:1},processStartedAt:{type:"string",format:"date-time"}},$defs:{expectation:Ir,binding:Sr}};function _a(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(_a,"createProjectId");function xa(e){return{schemaVersion:"1.0",...e}}i(xa,"createProjectIdentity");var an=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),ln=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),cn=Object.freeze(Object.keys(ln).sort()),sn=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"}),on=Object.freeze({process:Object.freeze(["process","node:process"])});function Ye(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=sn[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),s=sn[r];if(s)return s;let a=e.indexOf("/",n+1);return a<0?null:sn[e.slice(0,a)]??null}i(Ye,"capabilityForModuleSpecifier");function Ie(e,t){for(let n of t)if(on[n]?.includes(e))return n;return null}i(Ie,"forbiddenGlobalForModuleSpecifier");function kt(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),s=ln[r];if(s)return s}return null}i(kt,"capabilityForAmbientName");function we(e){if(e?.pure===!0)return[...an].sort();let n=(e?.capabilities?.deny??[]).filter(r=>an.includes(r));return[...new Set(n)].sort()}i(we,"effectiveCapabilityDeny");function Xe(e,t){if(t.length===0)return!1;let n=new Set(t),r=e.split(".");for(let s=r.length;s>=1;s-=1)if(n.has(r.slice(0,s).join(".")))return!0;return!1}i(Xe,"ambientCoveredByForbiddenGlobals");function Et(e){let t=new Set,n=new Set,r=Object.keys(ln);for(let s of e?.forbiddenGlobals??[]){let a=r.filter(o=>o===s||o.startsWith(`${s}.`));if(a.length===0)n.add(s);else for(let o of a)t.add(`ambient:${o}`);for(let o of on[s]??[])t.add(`import-exact:${o}`)}for(let s of we(e)){if(t.add(`import:${s}`),s==="process")for(let a of on.process)t.add(`import-exact:${a}`);for(let a of r)kt(a)===s&&t.add(`ambient:${a}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}i(Et,"loweredLayerCoverage");var br=new Map;function vr(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(vr,"escapeLiteral");function It(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let s=e[n+1];if("*?{}[],".includes(s)||s==="\\"){t+="\\"+s,n+=1;continue}t+="/";continue}t+=r}return t}i(It,"normalizeGlobSeparators");function Ta(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(Ta,"bracesBalanced");function ve(e){let t=br.get(e);if(t)return t;let n=It(e),r=Ta(n),s="",a=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(s+=vr(n[l+1]),l+=1):c==="*"?n[l+1]==="*"?n[l+2]==="/"?(s+="(?:.*/)?",l+=2):(s+=".*",l+=1):s+="[^/]*":c==="?"?s+="[^/]":c==="{"&&r?(s+="(?:",a+=1):c==="}"&&r&&a>0?(s+=")",a-=1):c===","&&r&&a>0?s+="|":s+=vr(c)}let o=new RegExp(`^${s}$`);return br.set(e,o),o}i(ve,"globToRegExp");function Na(e){return It(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}i(Na,"concreteGlobSegments");function dn(e,t){let n=It(String(e)),r=Na(n),s=n.replace(/\*/g,"").length,a=r.length*1e4+s;if(t==null||t==="")return a;let o=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return s;let l=0,c=-1;for(let p of r){let g=-1;for(let y=l;y<o.length;y+=1)if(o[y]===p){g=y;break}if(g<0)return a;c=g,l=g+1}return(c+1)*1e6+r.length*1e4+s}i(dn,"patternSpecificity");function ce(e,t){let n=String(e).split(/[/\\]/).join("/"),r,s=-1;for(let a of t??[])if(!(a.exclude??[]).some(o=>ve(o).test(n))){for(let o of a.patterns??[])if(ve(o).test(n)){let l=dn(o,n);l>s&&(s=l,r=a.name)}}return r}i(ce,"layerForRelativePath");function Cr(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),r=new Set(t.map(s=>String(s).toLowerCase()));for(let s=0;s<n.length-1;s+=1)if(r.has(n[s].toLowerCase()))return`${n[s].toLowerCase()}/${n[s+1].toLowerCase()}`}i(Cr,"sliceIdForPath");function Pa(e){let t=new Set;for(let n of e??[]){let s=It(String(n)).split("/").filter(Boolean);for(let a=0;a<s.length;a+=1){let o=s[a];if((o==="**"||o==="*")&&a>0){let l=s[a-1];l&&!l.includes("*")&&!l.includes("{")&&!l.includes("}")&&t.add(l)}}}return[...t]}i(Pa,"inferSliceFoldersFromPatterns");function La(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(s=>typeof s=="string"&&s.length>0);let r=(n??[]).find(s=>s.name===t);return Pa(r?.patterns)}i(La,"resolveSliceFolders");function wa(e){return!e.fromPath||!e.toPath||e.folderCount<=0||!e.fromSlice||!e.toSlice?!0:e.fromSlice!==e.toSlice}i(wa,"peerIsolationMustDeny");function fe(e,t,n,r){for(let s of e??[])if(!(s.from!==t||s.to!==n)&&s.allowed===!1){if(s.peerIsolation){let a=r?.fromPath,o=r?.toPath,l=La(s,t,r?.layers),c=a&&o?Cr(a,l):void 0,p=a&&o?Cr(o,l):void 0;if(wa({fromPath:a,toPath:o,folderCount:l.length,fromSlice:c,toSlice:p}))return s;continue}if(t!==n)return s}}i(fe,"findDeniedEdgeRule");function De(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(De,"literalText");function xr(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}i(xr,"lineOf");function Or(e,t){if(e.isImportDeclaration(t)){let r=t.importClause;if(!r)return!1;if(r.isTypeOnly)return!0;let s=r.namedBindings;return!!(s&&e.isNamedImports(s)&&s.elements.length>0&&s.elements.every(a=>a.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(r=>r.isTypeOnly))}i(Or,"isTypeOnlyReference");function Tr(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=s=>s===t.fileName?t:void 0,r.fileExists=s=>s===t.fileName,r.readFile=s=>s===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}i(Tr,"singleFileChecker");function un(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}i(un,"symbolAt");function pn(e,t,n,r){let s=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,a;try{a=s?t.getShorthandAssignmentValueSymbol(r.parent):un(t,r)}catch{a=void 0}return!!a?.declarations?.some(o=>o.getSourceFile().fileName===n.fileName)}i(pn,"localDeclaration");function Me(e,t){let n,r=[],s=i((o,l,c,p=!1)=>r.push({specifier:c,kind:l,line:xr(t,o),typeOnly:p,unresolved:c===void 0,node:o}),"add"),a=i(o=>{if(e.isImportDeclaration(o))s(o,"import",De(e,o.moduleSpecifier),Or(e,o));else if(e.isExportDeclaration(o)&&o.moduleSpecifier)s(o,"export",De(e,o.moduleSpecifier),Or(e,o));else if(e.isImportEqualsDeclaration(o)&&e.isExternalModuleReference(o.moduleReference))s(o,"require",De(e,o.moduleReference.expression),o.isTypeOnly===!0);else if(e.isCallExpression(o)){let l=o.expression.kind===e.SyntaxKind.ImportKeyword,p=e.isIdentifier(o.expression)&&o.expression.text==="require"&&!pn(e,n??(n=Tr(e,t)),t,o.expression);(l||p)&&s(o,p?"require":"dynamic-import",De(e,o.arguments[0]))}e.forEachChild(o,a)},"visit");return a(t),r}i(Me,"extractSemanticDependencies");function Da(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let s=De(e,r.argumentExpression);if(s===void 0)return;n.unshift(s)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}i(Da,"staticAccessPath");function Ma(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(Ma,"runtimeIdentifierReference");function _r(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let r=n.length;r>=1;r-=1){let s=n.slice(0,r).join(".");if(e.has(s))return s}}i(_r,"bestForbiddenMatch");function Fe(e,t,n){if(n.length===0)return[];let r=new Set(n),s=Tr(e,t),a=new Map,o=new Set;for(let f of t.statements)if(e.isVariableStatement(f))for(let u of f.declarationList.declarations)e.isIdentifier(u.name)&&o.add(u.name.text);let l=i(f=>{let u=Da(e,f);if(!u)return;let m=un(s,u.root),A=m?a.get(m):void 0;return A?[...A,...u.segments.slice(1)]:pn(e,s,t,u.root)||o.has(u.root.text)?void 0:u.segments},"resolvePath");for(let f of t.statements)if(e.isVariableStatement(f))for(let u of f.declarationList.declarations){if(!u.initializer||!e.isIdentifier(u.name))continue;let m=l(u.initializer),A=un(s,u.name);!m||!A||a.set(A,m)}let c=[],p=new Set,g=i((f,u)=>{let m=xr(t,u),A=`${f}:${u.getStart(t)}`;p.has(A)||(p.add(A),c.push({name:f,line:m,node:u}))},"flag"),y=i(f=>{let u=f.parent&&(e.isPropertyAccessExpression(f.parent)||e.isElementAccessExpression(f.parent))&&f.parent.expression===f;if((e.isPropertyAccessExpression(f)||e.isElementAccessExpression(f))&&!u){let m=l(f),A=m?_r(r,m):void 0;A&&g(A,f)}else e.isIdentifier(f)&&r.has(f.text)&&Ma(e,f)&&!pn(e,s,t,f)&&g(f.text,f);if(e.isVariableDeclaration(f)&&e.isObjectBindingPattern(f.name)&&f.initializer){let m=l(f.initializer);if(m)for(let A of f.name.elements){if(!e.isIdentifier(A.name))continue;let b=A.propertyName?De(e,A.propertyName)??A.propertyName.text:A.name.text,N=_r(r,[...m,b]);N&&g(N,f.initializer)}}e.forEachChild(f,y)},"visit");return y(t),c}i(Fe,"collectForbiddenCapabilityUses");function fn(e,t,n){let r=[];for(let s of n?.dependencies??Me(e,t)){if(s.typeOnly||!s.specifier)continue;let a=Ye(s.specifier);a&&r.push({capability:a,symbol:s.specifier,line:s.line,source:"import-based"})}for(let s of n?.ambientUses??Fe(e,t,cn)){let a=kt(s.name);a&&r.push({capability:a,symbol:s.name,line:s.line,source:"ambient-global"})}return r.sort((s,a)=>s.line-a.line||s.capability.localeCompare(a.capability)||s.symbol.localeCompare(a.symbol))}i(fn,"collectCapabilityUses");var mn={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."},gn=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 yn(e,t){return t.flatMap((r,s)=>(r.prefixes??r.intentPrefixes??[]).map(a=>({layer:r.name,layerIndex:s,prefix:a.endsWith(".")?a:`${a}.`}))).filter(({prefix:r})=>e.startsWith(r)).sort((r,s)=>s.prefix.length-r.prefix.length||r.layerIndex-s.layerIndex)[0]?.layer}i(yn,"resolveIntentLayer");function Ce(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}i(Ce,"looksLikeArkIntent");function Je(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&Ce(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:mn.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:mn.PUBLISH_MISSING_SOURCE}),t}i(Je,"classifyPublishFacts");function q(e,t,n){return{ruleId:e,code:e,message:t,...n}}i(q,"violation");function $e(e,t){return e.slice(0,t).split(`
2
+ `).length}i($e,"lineOf");function Fa(e){let t=[],n=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,r;for(;(r=n.exec(e))!==null;)t.push({value:r[1],index:r.index});return t}i(Fa,"extractQuotedStrings");function $a(e){let t=[],n=[{kind:"import",re:/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s*)?['"]([^'"]+)['"]/g},{kind:"export",re:/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s*['"]([^'"]+)['"]/g},{kind:"dynamic-import",re:/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g},{kind:"require",re:/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g}];for(let r of n){let s;for(;(s=r.re.exec(e))!==null;){let a=s.index+s[0].indexOf(s[1]),o=s[0],l=r.kind==="import"&&/\bimport\s+type\b/.test(o)||r.kind==="export"&&/\bexport\s+type\b/.test(o);t.push({value:s[1],index:a,kind:r.kind,typeOnly:l})}}return t.sort((r,s)=>r.index-s.index)}i($a,"extractModuleSpecifiers");function Ha(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],s=i(a=>{e.isStringLiteralLike(a)&&r.push({value:a.text,index:a.getStart(n)}),e.forEachChild(a,s)},"visit");return s(n),r}i(Ha,"extractQuotedStringsAst");function ja(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(ja,"hasInfrastructureToken");function Va(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}i(Va,"isKnownInfrastructurePackage");function Ka(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}i(Ka,"layerHasInfrastructureRole");function Qe(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(Qe,"tsStringLiteralText");function Ua(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}i(Ua,"tsPropertyName");function Nr(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:Ua(e,r.name)===n)}i(Nr,"tsObjectProperty");function et(e,t,n){return Nr(e,t,n)!==void 0}i(et,"tsObjectHasProperty");function Ze(e,t,n){let r=Nr(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}i(Ze,"tsObjectPropertyValue");function Ga(e,t){let n=Ze(e,t,"metadata");return et(e,n,"source")}i(Ga,"tsObjectHasMetadataSource");function Pr(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?Pr(e,t.name):!1:!1}i(Pr,"tsLooksLikeIntentCreatorExpression");function Ba(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(Ba,"tsIsPublishCall");function za(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=Qe(e,n);return r!==void 0&&Ce(r)||et(e,n,"intent")||Pr(e,n)}i(za,"tsIsArkPublishCandidate");function qa(e,t){if(!e.isCallExpression(t))return!1;let[n,r,s]=t.arguments;return Ga(e,n)||et(e,r,"source")||et(e,s,"source")}i(qa,"tsPublishHasSource");function Wa(e,t){if(!e.isCallExpression(t))return;let[n,r,s]=t.arguments,a=Ze(e,n,"metadata");return Qe(e,Ze(e,a,"source"))??Qe(e,Ze(e,r,"source"))??Qe(e,Ze(e,s,"source"))}i(Wa,"tsPublishSourceLiteral");function Ya(e,t,n,r){let s=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),a=n,o=a?.filePath,l=a?.layer,c=[],p=i(y=>s.getLineAndCharacterOfPosition(y.getStart(s)).line+1,"lineForNode"),g=i(y=>{if(Ba(e,y)){let f=y.arguments[0],u=Qe(e,f);for(let A of Je({publishCall:!0,rawIntentName:u,objectHasIntent:et(e,f,"intent"),arkPublishCandidate:za(e,y),hasSource:qa(e,y)}))c.push(q(A.ruleId,A.message,{line:p(y),filePath:o}));let m=Wa(e,y);if(r&&l&&m&&Ce(m)){let A=r.resolveLayer(m);A&&A!==l&&c.push(q("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${m}" resolves to ${A}, but the target file is classified as ${l}.`,{line:p(y),filePath:o,target:m,fromLayer:l,toLayer:A}))}}e.forEachChild(y,g)},"visit");return g(s),c}i(Ya,"analyzePublishAst");function Lr(e={}){let t=new Set((e.intents||[]).map(a=>typeof a=="string"?a:a.name)),n=e.forbiddenPatterns||[],r=new Set(e.infrastructureLayers??[]),s=e.enforceIntentAllowlist??t.size>0;return{validate(a,o){let l=[],c=o,p=c?.filePath,g=c?.layer,y=e.typescript,f=y?y.createSourceFile(p??"generated.ts",a,y.ScriptTarget.Latest,!0):void 0,u=f?Me(e.typescript,f):void 0,m=u?u.filter(R=>R.specifier!==void 0).map(R=>({value:R.specifier,index:R.node.getStart(f),kind:R.kind,typeOnly:R.typeOnly})):$a(a),A=e.typescript?Ha(e.typescript,a):Fa(a);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(p))for(let R of u?.filter(({unresolved:I})=>I)??[]){let I=R.kind==="require";l.push(q(I?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${I?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:R.line,filePath:p}))}let b=g!==void 0&&(r.has(g)||Ka(g)),N=g!==void 0?` If "${g}" is an infrastructure layer, mark it in ark.config.json with "mayImportInfrastructure": true (or name it with an infra token like Adapters/Persistence/Repository).`:"";for(let R of n)if(R instanceof RegExp){R.lastIndex=0;let I=R.exec(a);R.lastIndex=0,I&&l.push(q("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${R}`,{line:I.index===void 0?void 0:$e(a,I.index),filePath:p,suggestion:"Remove infrastructure imports from domain/application layers."+N}))}else a.includes(R)&&l.push(q("FORBIDDEN_SUBSTRING",`Forbidden substring: ${R}`,{line:$e(a,a.indexOf(R)),filePath:p}));for(let R of m){let I=e.resolveImportTarget?.(R.value,p)??(e.resolveImportLayer?{layer:e.resolveImportLayer(R.value,p)}:void 0),C=typeof p=="string"?e.resolveImportTarget?.(p)??(e.resolveImportLayer?{layer:g,relPath:void 0}:void 0):void 0,Y=I?.layer;if(Y&&g){let k=fe(e.architectureProfile?.rules,g,Y,{fromPath:C?.relPath,toPath:I?.relPath,layers:e.architectureLayers});if(k){if(R.typeOnly&&!k.peerIsolation)continue;let L=!!k.peerIsolation;l.push(q("LAYER_IMPORT_VIOLATION",k.message??(L?`Layer "${g}" must not import across slices into "${Y}".`:`Layer "${g}" must not import "${Y}".`),{line:$e(a,R.index),source:R.value,target:R.value,filePath:p,fromLayer:g,toLayer:Y,suggestion:L?"Extract shared code to a shared layer, or coordinate slices via events/ports \u2014 do not import across feature/context slices.":"Depend on a port/interface owned by an inner layer instead, or move this code to a layer allowed to make this import.",details:{importKind:R.kind,peerIsolation:L,...R.typeOnly?{typeOnly:!0}:{}}}));continue}continue}b||R.typeOnly||!ja(R.value)&&!Va(R.value)||l.push(q("FORBIDDEN_IMPORT",`Forbidden ${R.kind} target: "${R.value}".`,{line:$e(a,R.index),source:R.value,target:R.value,filePath:p,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+N,details:{importKind:R.kind}}))}if(e.policies)for(let R of e.policies){let I=R.check({source:a,context:o});if(I!==!0)if(Array.isArray(I))for(let C of I)l.push(q("POLICY_VIOLATION",C.message,{filePath:p,suggestion:`Fix violation of policy "${R.name}".`}));else I===!1?l.push(q("POLICY_VIOLATION",`Policy ${R.name} failed on generated code`)):l.push(q("POLICY_VIOLATION",I.message))}if(s&&t.size>0)for(let R of A)Ce(R.value)&&!t.has(R.value)&&l.push(q("UNKNOWN_INTENT",`Unknown intent reference: "${R.value}"`,{line:$e(a,R.index),filePath:p,target:R.value,suggestion:`Register intent "${R.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&g)for(let R of A){if(!Ce(R.value))continue;let I=e.architectureProfile.resolveLayer(R.value);if(!I)continue;let C=fe(e.architectureProfile.rules,g,I);C&&l.push(q("LAYER_REFERENCE_VIOLATION",C.message??`Layer "${g}" must not reference "${I}" through "${R.value}".`,{line:$e(a,R.index),filePath:p,target:R.value,fromLayer:g,toLayer:I,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:C}}))}if(e.extensions)for(let R of e.extensions)try{let I=R.analyze(a,o);l.push(...I)}catch(I){l.push(q("EXTENSION_ERROR",`Extension "${R.name}" failed: ${I instanceof Error?I.message:String(I)}`))}if(e.typescript&&f&&g&&e.forbiddenGlobals?.[g]?.length)try{let R=e.forbiddenGlobals[g];l.push(...Fe(e.typescript,f,R).map(I=>q("FORBIDDEN_GLOBAL",`${g} must not use the ambient global "${I.name}".`,{line:I.line,filePath:p,target:I.name,fromLayer:g,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let I of u??[]){if(I.typeOnly||!I.specifier)continue;let C=Ie(I.specifier,R);C&&l.push(q("FORBIDDEN_GLOBAL",`${g} must not use module "${I.specifier}" because it is the import form of forbidden global "${C}".`,{line:I.line,filePath:p,source:I.specifier,target:I.specifier,fromLayer:g,details:{importKind:I.kind,forbiddenGlobal:C},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(R){l.push(q("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${R instanceof Error?R.message:String(R)}`))}if(e.typescript&&f&&g&&e.capabilityWalls?.[g]?.length)try{let R=new Set(e.capabilityWalls[g]),I=e.forbiddenGlobals?.[g]??[];for(let C of fn(e.typescript,f))R.has(C.capability)&&(C.source==="ambient-global"&&Xe(C.symbol,I)||C.source==="import-based"&&Ie(C.symbol,I)||l.push(q("CAPABILITY_VIOLATION",C.source==="import-based"?`${g} denies the ${C.capability} capability; found import of "${C.symbol}".`:`${g} denies the ${C.capability} capability; found ambient "${C.symbol}".`,{line:C.line,filePath:p,target:C.symbol,capability:C.capability,fromLayer:g,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(R){l.push(q("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${R instanceof Error?R.message:String(R)}`))}if(e.typescript)try{l.push(...Ya(e.typescript,a,o,e.architectureProfile))}catch(R){l.push(q("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${R instanceof Error?R.message:String(R)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:l.length===0,violations:l}}}}i(Lr,"createAICodeGate");var He={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},wr={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...He,default:[]},kernelRoots:{...He},managedLayers:{...He,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},Dr={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...He,default:[]},managedLayers:{...He,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...He,default:[]}}};function tt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(tt,"isObject");function Mr(e){let t=new Set;if(!Array.isArray(e.layers))return t;for(let n of e.layers)tt(n)&&typeof n.name=="string"&&n.name.length>0&&t.add(n.name);return t}i(Mr,"declaredLayerNames");function Fr(e){if(!tt(e))return e;let t={mode:e.mode===void 0?"advisory":e.mode,compositionRoots:e.compositionRoots===void 0?[]:e.compositionRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,requireDeclarations:e.requireDeclarations===void 0?!0:e.requireDeclarations};return e.kernelRoots!==void 0&&(t.kernelRoots=e.kernelRoots),e.ignoreDirectNewForErrors!==void 0&&(t.ignoreDirectNewForErrors=e.ignoreDirectNewForErrors),{...e,...t}}i(Fr,"defaultedArkRun");function $r(e){if(!tt(e))return e;let t=typeof e.maxXiKeys=="number"&&e.maxXiKeys>0?e.maxXiKeys:7;return{...e,mode:e.mode===void 0?"advisory":e.mode,planeRoots:e.planeRoots===void 0?[]:e.planeRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,maxXiKeys:t,xiKeys:e.xiKeys===void 0?[]:e.xiKeys}}i($r,"defaultedArkOrder");function Hr(e,t){let n=e.arkRun;if(n===void 0||!tt(n))return;let r=Mr(e),s=n.managedLayers;if(Array.isArray(s)&&s.forEach((a,o)=>{typeof a=="string"&&a.length>0&&!r.has(a)&&t.push({path:`$.arkRun.managedLayers[${o}]`,message:`layer ${JSON.stringify(a)} is not declared in layers[]`})}),n.mode==="enforced"){let a=n.kernelRoots??n.compositionRoots;(!Array.isArray(a)||a.length===0)&&t.push({path:n.kernelRoots!==void 0?"$.arkRun.kernelRoots":"$.arkRun.compositionRoots",message:"ARKRUN_MISSING_ROOT: enforced mode requires at least one kernel root"}),(!Array.isArray(s)||s.length===0)&&t.push({path:"$.arkRun.managedLayers",message:"enforced mode requires at least one managed layer"})}}i(Hr,"validateArkRunExtra");function jr(e,t){let n=e.arkOrder;if(n===void 0||!tt(n))return;let r=Mr(e),s=n.managedLayers;if(Array.isArray(s)&&s.forEach((a,o)=>{typeof a=="string"&&a.length>0&&!r.has(a)&&t.push({path:`$.arkOrder.managedLayers[${o}]`,message:`layer ${JSON.stringify(a)} is not declared in layers[]`})}),n.mode==="enforced"){let a=n.planeRoots;(!Array.isArray(a)||a.length===0)&&t.push({path:"$.arkOrder.planeRoots",message:"ARKORDER_MISSING_PLANE: enforced mode requires at least one plane root"}),(!Array.isArray(s)||s.length===0)&&t.push({path:"$.arkOrder.managedLayers",message:"enforced mode requires at least one managed layer"})}}i(jr,"validateArkOrderExtra");var re="1.3",bt="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",Vr=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Xa=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Ja(){let e=[];for(let t of Vr)for(let n of Vr)t===n||Xa.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}i(Ja,"createDefaultRules");var vt=Ja(),hn=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"},{from:"1.1",to:"1.2"},{from:"1.2",to:"1.3"}],me={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},An={$schema:"https://json-schema.org/draft/2020-12/schema",$id:bt,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:bt,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:re,default:re},name:{type:"string",minLength:1},include:{...me,minItems:1,default:["src"]},exclude:{...me,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:vt,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...me,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},arkRun:{$ref:"#/$defs/arkRun"},arkOrder:{$ref:"#/$defs/arkOrder"},stewards:{...me,default:[]}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...me,minItems:1},exclude:me,intentPrefixes:me,description:{type:"string",minLength:1},forbiddenGlobals:me,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:{...me,minItems:1}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}},arkRun:wr,arkOrder:Dr}},ge=class extends Error{static{i(this,"ArkConfigValidationError")}issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
3
3
  ${n.map(r=>`- ${r.path}: ${r.message}`).join(`
4
- `)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function jr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(jr,"isObject");function It(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}i(It,"propertyPath");function $e(e){return e===null?"null":Array.isArray(e)?"array":typeof e}i($e,"valueType");function Zo(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}i(Zo,"resolveSchemaRef");function nt(e,t,n,r,s){if(t.$ref){let o=Zo(t.$ref,r);if(!o){s.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}nt(e,o,n,r,s);return}if(t.const!==void 0&&!Object.is(e,t.const)){s.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(o=>Object.is(o,e))){s.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!jr(e)){s.push({path:n,message:`must be an object; received ${$e(e)}`});return}let o=t.properties??{};for(let a of t.required??[])e[a]===void 0&&s.push({path:It(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in o||s.push({path:It(n,a),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let a=t.additionalProperties;for(let l of Object.keys(e))l in o||nt(e[l],a,It(n,l),r,s)}for(let[a,l]of Object.entries(o))e[a]!==void 0&&nt(e[a],l,It(n,a),r,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:n,message:`must be an array; received ${$e(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&s.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let o=e.map(a=>JSON.stringify(a));new Set(o).size!==o.length&&s.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((o,a)=>nt(o,t.items,`${n}[${a}]`,r,s));return}if(t.type==="string"){if(typeof e!="string"){s.push({path:n,message:`must be a string; received ${$e(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&s.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&s.push({path:n,message:`must be a boolean; received ${$e(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){s.push({path:n,message:`must be an integer; received ${$e(e)}`});return}t.minimum!==void 0&&e<t.minimum&&s.push({path:n,message:`must be at least ${t.minimum}`})}}i(nt,"validateNode");function Xo(e){let t={...e,$schema:e.$schema===void 0?vt:e.$schema,schemaVersion:e.schemaVersion===void 0?ne:e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?bt.map(n=>({...n})):e.rules};return e.arkRun!==void 0&&(t.arkRun=Dr(e.arkRun)),e.arkOrder!==void 0&&(t.arkOrder=Mr(e.arkOrder)),t}i(Xo,"defaultedConfig");function Qo(e){return e===ne?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}i(Qo,"migratedFromOf");function ea(){let e=new Set([ne]);for(let t of mn)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}i(ea,"knownInputVersions");function ta(e,t="ark.config.json"){if(!jr(e))throw new ye(t,[{path:"$",message:`must be an object; received ${$e(e)}`}]);let n=ea(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new ye(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected ${ne}`}]);if(r!=="unversioned"&&!n.has(r))throw new ye(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${ne}`}]);let s=r,o={...e},a=0;for(;s!==ne&&a<mn.length+1;){a+=1;let l=mn.find(c=>c.from===s);if(!l)throw new ye(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(s)}; expected ${ne}`}]);s=l.to,o.schemaVersion=s}if(s!==ne)throw new ye(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${ne}`}]);return{candidate:Xo(o),migratedFrom:Qo(r)}}i(ta,"migrateArkConfig");function Ct(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=ta(e,t),s=[];if(nt(n,gn,"$",gn,s),Fr(n,s),$r(n,s),s.length>0)throw new ye(t,s);return{config:n,migratedFrom:r}}i(Ct,"loadArkConfigContract");function yn(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new ye(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return Ct(n,t)}i(yn,"parseArkConfigJson");function Vr(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:vt,schemaVersion:ne};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}i(Vr,"withArkConfigMetadata");function na(e){return e.endsWith(".")?e:`${e}.`}i(na,"normalizePrefix");function ra(e,t){let n=e.prefixes.length?Math.max(...e.prefixes.map(s=>s.length)):0;return(t.prefixes.length?Math.max(...t.prefixes.map(s=>s.length)):0)-n}i(ra,"byLongestPrefix");function Ot(e){let t=e.layers.map(s=>({...s,prefixes:s.prefixes.map(na)})),n=[...t].sort(ra),r=[...e.rules??[]];return{name:e.name,layers:t,rules:r,resolveLayer(s){return t.find(o=>o.match?.(s))?.name??n.find(o=>o.prefixes.some(a=>s.startsWith(a)))?.name}}}i(Ot,"createArchitectureProfile");function Ur(e,t={}){return Ot({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,r)=>({name:n.name,prefixes:n.intentPrefixes??[],description:n.description,order:r+1})),rules:e.rules??[]})}i(Ur,"createArchitectureProfileFromArkConfig");var sa=[{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}],_t=Ot({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:sa,rules:bt.map(e=>({...e}))}),oa={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 Kr(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return Vr({include:e.include??[t],layers:_t.layers.map(s=>({name:s.name,patterns:(oa[s.name]??[s.name]).map(o=>`${r}${o}/**`),intentPrefixes:s.prefixes,optional:n})),rules:[..._t.rules]})}i(Kr,"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 F(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(F).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${F(t[n])}`).join(",")}}`}i(F,"stableSerialize");var Oe="1.2";var Gr=["network","filesystem","clock","randomness","environment","process","persistence"];function Z(e,t){let n=F(e),r=F(t);return n<r?-1:n>r?1:0}i(Z,"compareCanonical");function X(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}i(X,"sortedUnique");function rt(e){let t={schemaVersion:"1.2",include:X(e.include??[]),exclude:X(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:X(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:X(n.patterns??[]),exclude:X(n.exclude??[]),forbiddenGlobals:X(n.forbiddenGlobals??[]),intentPrefixes:X(n.intentPrefixes??[]),capabilityDeny:X(n.capabilities?.deny??[]),pure:n.pure===!0})).sort(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:X(e.arkRun.compositionRoots),managedLayers:X(e.arkRun.managedLayers),requireDeclarations:e.arkRun.requireDeclarations===!0}}:{}};return z(F(t))}i(rt,"resolvedFactsEvidenceRequirementsHash");function aa(e){let t=e.completenessReasons.map(k=>({code:k.code,message:k.message,...k.file?{file:k.file}:{}})).sort(Z),n=e.files.map(k=>({...k,typeOnlyExportNames:X(k.typeOnlyExportNames)})).sort((k,b)=>k.path<b.path?-1:k.path>b.path?1:0),r=e.dependencies.map(k=>({...k,...k.namedBindings?{namedBindings:X(k.namedBindings)}:{}})).sort(Z),s=e.capabilityUses.map(k=>({...k})).sort(Z),o=e.ambientUses.map(k=>({...k})).sort(Z),a=e.publishCalls.map(k=>({...k})).sort(Z),l=e.intentReferences.map(k=>({...k})).sort(Z),c=e.safetyUses.map(k=>({...k})).sort(Z),p=(e.classShapes??[]).map(k=>({...k,mutatingMethods:[...k.mutatingMethods??[]].map(b=>({...b}))})).sort(Z),m=(e.arkRunKernelCalls??[]).map(k=>({...k})).sort(Z),g=(e.arkRunManagedNews??[]).map(k=>({...k})).sort(Z),u=(e.arkRunCompositionRootHits??[]).map(k=>({...k})).sort(Z),d=(e.arkRunDeclarations??[]).map(k=>({...k,uses:X(k.uses),reactsTo:X(k.reactsTo),raises:X(k.raises),sends:X(k.sends)})).sort(Z),f=(e.arkOrderPlaneCalls??[]).map(k=>({...k})).sort(Z),y=(e.arkOrderGenericUpdates??[]).map(k=>({...k})).sort(Z),I=(e.arkOrderRootHits??[]).map(k=>({...k})).sort(Z),N=e.files.map(({path:k,contentHash:b})=>({path:k,contentHash:b})).sort((k,b)=>k.path<b.path?-1:k.path>b.path?1:0),E=z(F(N));return{schemaVersion:"1.2",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:E,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:r,capabilityUses:s,ambientUses:o,publishCalls:a,intentReferences:l,safetyUses:c,classShapes:p,arkRunKernelCalls:m,arkRunManagedNews:g,arkRunCompositionRootHits:u,arkRunDeclarations:d,arkOrderPlaneCalls:f,arkOrderGenericUpdates:y,arkOrderRootHits:I}}i(aa,"canonicalResolvedFactsInput");function Br(e){let t=aa(e);return{...t,factsHash:z(F(t))}}i(Br,"createCanonicalResolvedCandidateFacts");function hn(e){return Br(qr(U(e,"$"),!1))}i(hn,"createResolvedCandidateFacts");function U(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}i(U,"asRecord");function K(e,t,n){let r=new Set(t),s=Object.keys(e).find(o=>!r.has(o));if(s)throw new Error(`${n}.${s} is not part of schema ${"1.2"}.`)}i(K,"assertOnlyKeys");function M(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(M,"requiredText");function he(e,t,n){if(e[t]!==void 0)return M(e,t,n)}i(he,"optionalText");function q(e,t,n){let r=M(e,t,n),s=r.replace(/\\/g,"/");if(!s||s.startsWith("/")||/^[A-Za-z]:\//.test(s)||/[\u0000-\u001f\u007f]/.test(s))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let o=[];for(let l of s.split("/"))if(!(!l||l==="."))if(l===".."){if(o.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);o.pop()}else o.push(l);let a=o.join("/");if(!a||a!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return a}i(q,"requiredProjectPath");function j(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}i(j,"requiredBoolean");function zr(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(zr,"requiredInteger");function le(e,t,n){let r=zr(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}i(le,"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}i(Y,"requiredArray");function Ae(e,t,n,r){let s=e[t];if(typeof s!="string"||!n.includes(s))throw new Error(`${r}.${t} must be one of ${n.join(", ")}.`);return s}i(Ae,"enumValue");function He(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(He,"parseStringArray");function ia(e,t,n){let r=new Set;for(let s of e){let o=t(s);if(r.has(o))throw new Error(`${n} must not contain duplicate facts (${o}).`);r.add(o)}}i(ia,"assertUnique");function qr(e,t){K(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",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=Ae(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=Ae(e,"completeness",["complete","partial","unavailable"],"$"),s=Y(e,"completenessReasons","$").map((v,_)=>{let A=`$.completenessReasons[${_}]`,R=U(v,A);K(R,["code","message","file"],A);let L=R.file===void 0?void 0:q(R,"file",A);return{code:M(R,"code",A),message:M(R,"message",A),...L?{file:L}:{}}});if(r==="complete"&&s.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(r!=="complete"&&s.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let o=Y(e,"files","$").map((v,_)=>{let A=`$.files[${_}]`,R=U(v,A);return K(R,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],A),{path:q(R,"path",A),contentHash:M(R,"contentHash",A),parseStatus:Ae(R,"parseStatus",["parsed","invalid"],A),parseDiagnosticCount:zr(R,"parseDiagnosticCount",A),exportsOnlyTypes:j(R,"exportsOnlyTypes",A),typeOnlyExportNames:He(R.typeOnlyExportNames,`${A}.typeOnlyExportNames`),hasTopLevelSideEffects:j(R,"hasTopLevelSideEffects",A)}}),a=Y(e,"dependencies","$").map((v,_)=>{let A=`$.dependencies[${_}]`,R=U(v,A);K(R,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],A);let L=he(R,"specifier",A),B=he(R,"target",A),Se=Ae(R,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],A);if(Se==="resolved-project"&&!B)throw new Error(`${A}.target is required for resolved-project dependencies.`);if(Se!=="resolved-project"&&B)throw new Error(`${A}.target is only allowed for resolved-project dependencies.`);if(Se!=="dynamic"&&!L)throw new Error(`${A}.specifier is required unless resolution is dynamic.`);return{from:q(R,"from",A),...L?{specifier:L}:{},kind:Ae(R,"kind",["import","export","dynamic-import","require"],A),typeOnly:j(R,"typeOnly",A),line:le(R,"line",A),resolution:Se,...B?{target:q(R,"target",A)}:{},...R.namedBindings!==void 0?{namedBindings:He(R.namedBindings,`${A}.namedBindings`)}:{},...R.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:j(R,"targetTypeOnlyExports",A)}:{},...R.sourcePureTypeModule!==void 0?{sourcePureTypeModule:j(R,"sourcePureTypeModule",A)}:{},...R.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:j(R,"namedBindingsTypeOnly",A)}:{},...R.portProofEligible!==void 0?{portProofEligible:j(R,"portProofEligible",A)}:{}}}),l=Y(e,"capabilityUses","$").map((v,_)=>{let A=`$.capabilityUses[${_}]`,R=U(v,A);return K(R,["file","line","symbol","capability","source"],A),{file:q(R,"file",A),line:le(R,"line",A),symbol:M(R,"symbol",A),capability:Ae(R,"capability",Gr,A),source:Ae(R,"source",["ambient-global","import-based"],A)}}),c=Y(e,"ambientUses","$").map((v,_)=>{let A=`$.ambientUses[${_}]`,R=U(v,A);return K(R,["file","line","symbol"],A),{file:q(R,"file",A),line:le(R,"line",A),symbol:M(R,"symbol",A)}}),p=Y(e,"publishCalls","$").map((v,_)=>{let A=`$.publishCalls[${_}]`,R=U(v,A);K(R,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],A);let L=he(R,"rawIntentName",A),B=he(R,"sourceIntent",A);return{file:q(R,"file",A),line:le(R,"line",A),...L?{rawIntentName:L}:{},objectHasIntent:j(R,"objectHasIntent",A),arkPublishCandidate:j(R,"arkPublishCandidate",A),hasSource:j(R,"hasSource",A),...B?{sourceIntent:B}:{}}}),m=Y(e,"intentReferences","$").map((v,_)=>{let A=`$.intentReferences[${_}]`,R=U(v,A);return K(R,["file","line","intent"],A),{file:q(R,"file",A),line:le(R,"line",A),intent:M(R,"intent",A)}}),g=Y(e,"safetyUses","$").map((v,_)=>{let A=`$.safetyUses[${_}]`,R=U(v,A);K(R,["file","line","kind","symbol"],A);let L=he(R,"symbol",A),B=Ae(R,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],A);if(B==="in-memory-store"&&!L)throw new Error(`${A}.symbol is required for in-memory-store facts.`);if(B!=="in-memory-store"&&L)throw new Error(`${A}.symbol is only allowed for in-memory-store facts.`);return{file:q(R,"file",A),line:le(R,"line",A),kind:B,...L?{symbol:L}:{}}});ia(o,v=>v.path,"$.files");let u=new Set(o.map(v=>v.path));for(let v of o){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"&&o.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(!u.has(v.from))throw new Error(`$.dependencies references missing source file ${v.from}.`);let f=(e.arkRunKernelCalls===void 0?[]:Y(e,"arkRunKernelCalls","$")).map((v,_)=>{let A=`$.arkRunKernelCalls[${_}]`,R=U(v,A);K(R,["file","line","kind","callee","viaImport","receiver","nameLiteral"],A);let L=he(R,"receiver",A),B=he(R,"nameLiteral",A);return{file:q(R,"file",A),line:le(R,"line",A),kind:Ae(R,"kind",["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"],A),callee:M(R,"callee",A),viaImport:j(R,"viaImport",A),...L?{receiver:L}:{},...B?{nameLiteral:B}:{}}}),I=(e.arkRunManagedNews===void 0?[]:Y(e,"arkRunManagedNews","$")).map((v,_)=>{let A=`$.arkRunManagedNews[${_}]`,R=U(v,A);K(R,["file","line","typeName","importedFrom"],A);let L=he(R,"importedFrom",A);return{file:q(R,"file",A),line:le(R,"line",A),typeName:M(R,"typeName",A),...L?{importedFrom:L}:{}}}),E=(e.arkRunCompositionRootHits===void 0?[]:Y(e,"arkRunCompositionRootHits","$")).map((v,_)=>{let A=`$.arkRunCompositionRootHits[${_}]`,R=U(v,A);return K(R,["file","matchedRoot","hasKernelFactory"],A),{file:q(R,"file",A),matchedRoot:M(R,"matchedRoot",A),hasKernelFactory:j(R,"hasKernelFactory",A)}}),k=e.arkRunDeclarations===void 0?[]:Y(e,"arkRunDeclarations","$"),J=(e.arkOrderPlaneCalls===void 0?[]:Y(e,"arkOrderPlaneCalls","$")).map((v,_)=>{let A=`$.arkOrderPlaneCalls[${_}]`,R=U(v,A);return K(R,["file","line","callee"],A),{file:q(R,"file",A),line:le(R,"line",A),callee:M(R,"callee",A)}}),G=(e.arkOrderGenericUpdates===void 0?[]:Y(e,"arkOrderGenericUpdates","$")).map((v,_)=>{let A=`$.arkOrderGenericUpdates[${_}]`,R=U(v,A);return K(R,["file","line","method"],A),{file:q(R,"file",A),line:le(R,"line",A),method:M(R,"method",A)}}),O=(e.arkOrderRootHits===void 0?[]:Y(e,"arkOrderRootHits","$")).map((v,_)=>{let A=`$.arkOrderRootHits[${_}]`,R=U(v,A);return K(R,["file","matchedRoot","hasPlaneFactory"],A),{file:q(R,"file",A),matchedRoot:M(R,"matchedRoot",A),hasPlaneFactory:j(R,"hasPlaneFactory",A)}}),D=k.map((v,_)=>{let A=`$.arkRunDeclarations[${_}]`,R=U(v,A);return K(R,["file","line","uses","reactsTo","raises","sends"],A),{file:q(R,"file",A),line:le(R,"line",A),uses:He(R.uses,`${A}.uses`),reactsTo:He(R.reactsTo,`${A}.reactsTo`),raises:He(R.raises,`${A}.raises`),sends:He(R.sends,`${A}.sends`)}});for(let[v,_]of[["$.capabilityUses",l],["$.ambientUses",c],["$.publishCalls",p],["$.intentReferences",m],["$.safetyUses",g],["$.arkRunKernelCalls",f],["$.arkRunManagedNews",I],["$.arkRunCompositionRootHits",E],["$.arkRunDeclarations",D],["$.arkOrderPlaneCalls",J],["$.arkOrderGenericUpdates",G],["$.arkOrderRootHits",O]])for(let A of _)if(!u.has(A.file))throw new Error(`${v} references missing file ${A.file}.`);let P=he(e,"projectPackageName","$"),fe=(e.classShapes===void 0?[]:Y(e,"classShapes","$")).map((v,_)=>{let A=`$.classShapes[${_}]`,R=U(v,A);K(R,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],A);let L=Y(R,"mutatingMethods",A).map((B,Se)=>{let be=`${A}.mutatingMethods[${Se}]`,Be=U(B,be);return K(Be,["name","referencesGuardOrPublish"],be),{name:M(Be,"name",be),referencesGuardOrPublish:j(Be,"referencesGuardOrPublish",be)}});return{file:q(R,"file",A),className:M(R,"className",A),exported:j(R,"exported",A),hasPublicMutableFields:j(R,"hasPublicMutableFields",A),hasPublicSetters:j(R,"hasPublicSetters",A),hasPublicConstructor:j(R,"hasPublicConstructor",A),hasStaticFactory:j(R,"hasStaticFactory",A),mutatingMethods:L,...R.dataOnly===void 0?{}:{dataOnly:j(R,"dataOnly",A)}}});return{schemaVersion:n,completeness:r,completenessReasons:s,resolverIdentity:M(e,"resolverIdentity","$"),compilerIdentity:M(e,"compilerIdentity","$"),compilerOptionsHash:M(e,"compilerOptionsHash","$"),tsconfigHash:M(e,"tsconfigHash","$"),evidenceRequirementsHash:M(e,"evidenceRequirementsHash","$"),...P?{projectPackageName:P}:{},files:o,dependencies:a,capabilityUses:l,ambientUses:c,publishCalls:p,intentReferences:m,safetyUses:g,classShapes:fe,arkRunKernelCalls:f,arkRunManagedNews:I,arkRunCompositionRootHits:E,arkRunDeclarations:D,arkOrderPlaneCalls:J,arkOrderGenericUpdates:G,arkOrderRootHits:O}}i(qr,"parseResolvedFactsInput");function ve(e){let t=U(e,"$"),n=M(t,"factsHash","$"),r=M(t,"candidateTreeHash","$"),s=Br(qr(t,!0));if(s.factsHash!==n)throw new Error(`$.factsHash does not match the canonical payload (${s.factsHash}).`);if(r!==s.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${s.candidateTreeHash}).`);return s}i(ve,"loadResolvedCandidateFacts");var la=["network","filesystem","clock","randomness","environment","process","persistence"],x={type:"string",minLength:1},ce={type:"integer",minimum:1},W={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},An={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.resolved-candidate-facts.schema.json",title:"ArkGate resolved candidate facts",type:"object",additionalProperties:!1,required:["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","candidateTreeHash","evidenceRequirementsHash","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","factsHash"],properties:{schemaVersion:{enum:["1.0","1.1","1.2"]},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:x,message:x,file:W}}},resolverIdentity:x,compilerIdentity:x,compilerOptionsHash:x,tsconfigHash:x,candidateTreeHash:x,evidenceRequirementsHash:x,projectPackageName:x,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:W,contentHash:x,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:x},hasTopLevelSideEffects:{type:"boolean"}},allOf:[{if:{properties:{parseStatus:{const:"parsed"}}},then:{properties:{parseDiagnosticCount:{const:0}}}},{if:{properties:{parseStatus:{const:"invalid"}}},then:{properties:{parseDiagnosticCount:{minimum:1}}}}]}},dependencies:{type:"array",items:{type:"object",additionalProperties:!1,required:["from","kind","typeOnly","line","resolution"],properties:{from:W,specifier:x,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:ce,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:W,namedBindings:{type:"array",items:x},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"}},allOf:[{if:{properties:{resolution:{const:"resolved-project"}}},then:{required:["target"]},else:{not:{required:["target"]}}},{if:{properties:{resolution:{const:"dynamic"}}},else:{required:["specifier"]}}]}},capabilityUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol","capability","source"],properties:{file:W,line:ce,symbol:x,capability:{enum:la},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:W,line:ce,symbol:x}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:W,line:ce,rawIntentName:x,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:x}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:W,line:ce,intent:x}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:W,line:ce,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:x},allOf:[{if:{properties:{kind:{const:"in-memory-store"}}},then:{required:["symbol"]},else:{not:{required:["symbol"]}}}]}},classShapes:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods"],properties:{file:W,className:x,exported:{type:"boolean"},hasPublicMutableFields:{type:"boolean"},hasPublicSetters:{type:"boolean"},hasPublicConstructor:{type:"boolean"},hasStaticFactory:{type:"boolean"},dataOnly:{type:"boolean"},mutatingMethods:{type:"array",items:{type:"object",additionalProperties:!1,required:["name","referencesGuardOrPublish"],properties:{name:x,referencesGuardOrPublish:{type:"boolean"}}}}}}},arkRunKernelCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind","callee","viaImport"],properties:{file:W,line:ce,kind:{enum:["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"]},callee:x,viaImport:{type:"boolean"},receiver:x,nameLiteral:x}}},arkRunManagedNews:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","typeName"],properties:{file:W,line:ce,typeName:x,importedFrom:x}}},arkRunCompositionRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasKernelFactory"],properties:{file:W,matchedRoot:x,hasKernelFactory:{type:"boolean"}}}},arkRunDeclarations:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","uses","reactsTo","raises","sends"],properties:{file:W,line:ce,uses:{type:"array",items:x},reactsTo:{type:"array",items:x},raises:{type:"array",items:x},sends:{type:"array",items:x}}}},arkOrderPlaneCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","callee"],properties:{file:W,line:ce,callee:x}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:W,line:ce,method:x}}},arkOrderRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasPlaneFactory"],properties:{file:W,matchedRoot:x,hasPlaneFactory:{type:"boolean"}}}},factsHash:x},allOf:[{if:{properties:{completeness:{const:"complete"}}},then:{properties:{completenessReasons:{maxItems:0},files:{items:{properties:{parseStatus:{const:"parsed"}}}}}}},{if:{properties:{completeness:{enum:["partial","unavailable"]}}},then:{properties:{completenessReasons:{minItems:1}}}}]};var Rn="1.0";function re(e){return`${e.from}->${e.to}`}i(re,"dependencyKey");function st(e,t,n,r="dependency"){return{id:`${e}:${r}:${re(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${re(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${re(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${re(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${re(t)} from the candidate, then preflight again.`}:{}}}i(st,"dependencyFinding");function je(e){let t=[],n=new Map(e.changeMap.map.files.map(u=>[u.path,u])),r=new Map(e.changes.map(u=>[u.path,u])),s=new Map(e.changeMap.map.dependencies.map(u=>[re(u),u])),o=new Map(e.baseDependencies.map(u=>[re(u),u])),a=new Map(e.candidateDependencies.map(u=>[re(u),u]));for(let u of[...n.values()].sort((d,f)=>d.path.localeCompare(f.path))){let d=r.get(u.path);d?d.operation!==u.operation?t.push({id:`contradictory:file:${u.path}`,classification:"contradictory",subject:"file",path:u.path,expectedOperation:u.operation,actualOperation:d.operation,message:`${u.path} was planned as ${u.operation} but the actual operation is ${d.operation}.`,nextAction:`Change ${u.path} to the planned ${u.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${u.path}`,classification:"satisfied",subject:"file",path:u.path,expectedOperation:u.operation,actualOperation:d.operation,message:`${u.path} matches the planned ${u.operation} operation.`}):t.push({id:`missing:file:${u.path}`,classification:"missing",subject:"file",path:u.path,expectedOperation:u.operation,message:`${u.path} was planned as ${u.operation} but is absent from the actual change.`,nextAction:`${u.operation[0].toUpperCase()}${u.operation.slice(1)} ${u.path} in the complete change set, then preflight again.`})}for(let u of[...r.values()].sort((d,f)=>d.path.localeCompare(f.path)))n.has(u.path)||t.push({id:`unplanned:file:${u.path}`,classification:"unplanned",subject:"file",path:u.path,actualOperation:u.operation,message:`${u.path} has an unplanned ${u.operation} operation.`,nextAction:`Remove ${u.path} from the change set, then preflight again.`});let l=new Set;for(let u of[...s.values()].sort((d,f)=>re(d).localeCompare(re(f)))){if(a.has(re(u))){t.push(st("satisfied",u,`${u.from} -> ${u.to} exists in the candidate architecture.`));continue}let d={from:u.to,to:u.from};a.has(re(d))?(l.add(re(d)),t.push(st("contradictory",u,`${u.from} -> ${u.to} was planned, but the candidate contains the reverse edge.`))):t.push(st("missing",u,`${u.from} -> ${u.to} is absent from the candidate architecture.`))}let c=new Set([...n.keys(),...r.keys()]);for(let[u,d]of[...a].sort(([f],[y])=>f.localeCompare(y)))o.has(u)||s.has(u)||l.has(u)||!c.has(d.from)&&!c.has(d.to)||t.push({...st("unplanned",d,`${d.from} -> ${d.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let p=new Set(e.changeMap.map.files.filter(u=>u.operation==="delete").map(u=>u.path));for(let[u,d]of[...o].sort(([f],[y])=>f.localeCompare(y)))a.has(u)||p.has(d.from)||p.has(d.to)||!c.has(d.from)&&!c.has(d.to)||t.push({...st("unplanned",d,`${d.from} -> ${d.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let m={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((u,d)=>m[u.classification]-m[d.classification]||(u.subject===d.subject?0:u.subject==="file"?-1:1)||u.id.localeCompare(d.id));let g={satisfied:t.filter(u=>u.classification==="satisfied").length,missing:t.filter(u=>u.classification==="missing").length,contradictory:t.filter(u=>u.classification==="contradictory").length,unplanned:t.filter(u=>u.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(je,"analyzeArchitectureConvergence");var ca="1.0",kn="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",Jr=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","no-anemic-model","invariant-coverage"],da=["no-anemic-model"],Yr={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},En={$schema:"https://json-schema.org/draft/2020-12/schema",$id:kn,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:kn},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:[...Jr]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:Yr,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:Yr}}}},xe=class extends Error{static{i(this,"ArkRulesValidationError")}issues;source;constructor(t,n){super(`Invalid ArkRules (${t}):
4
+ `)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function Kr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(Kr,"isObject");function St(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}i(St,"propertyPath");function je(e){return e===null?"null":Array.isArray(e)?"array":typeof e}i(je,"valueType");function Za(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}i(Za,"resolveSchemaRef");function nt(e,t,n,r,s){if(t.$ref){let a=Za(t.$ref,r);if(!a){s.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}nt(e,a,n,r,s);return}if(t.const!==void 0&&!Object.is(e,t.const)){s.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(a=>Object.is(a,e))){s.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!Kr(e)){s.push({path:n,message:`must be an object; received ${je(e)}`});return}let a=t.properties??{};for(let o of t.required??[])e[o]===void 0&&s.push({path:St(n,o),message:"is required"});if(t.additionalProperties===!1)for(let o of Object.keys(e))o in a||s.push({path:St(n,o),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let o=t.additionalProperties;for(let l of Object.keys(e))l in a||nt(e[l],o,St(n,l),r,s)}for(let[o,l]of Object.entries(a))e[o]!==void 0&&nt(e[o],l,St(n,o),r,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:n,message:`must be an array; received ${je(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&s.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let a=e.map(o=>JSON.stringify(o));new Set(a).size!==a.length&&s.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((a,o)=>nt(a,t.items,`${n}[${o}]`,r,s));return}if(t.type==="string"){if(typeof e!="string"){s.push({path:n,message:`must be a string; received ${je(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&s.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&s.push({path:n,message:`must be a boolean; received ${je(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){s.push({path:n,message:`must be an integer; received ${je(e)}`});return}t.minimum!==void 0&&e<t.minimum&&s.push({path:n,message:`must be at least ${t.minimum}`})}}i(nt,"validateNode");function Qa(e){let t={...e,$schema:e.$schema===void 0?bt:e.$schema,schemaVersion:e.schemaVersion===void 0?re:e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?vt.map(n=>({...n})):e.rules};return e.arkRun!==void 0&&(t.arkRun=Fr(e.arkRun)),e.arkOrder!==void 0&&(t.arkOrder=$r(e.arkOrder)),t}i(Qa,"defaultedConfig");function eo(e){return e===re?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}i(eo,"migratedFromOf");function to(){let e=new Set([re]);for(let t of hn)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}i(to,"knownInputVersions");function no(e,t="ark.config.json"){if(!Kr(e))throw new ge(t,[{path:"$",message:`must be an object; received ${je(e)}`}]);let n=to(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new ge(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected ${re}`}]);if(r!=="unversioned"&&!n.has(r))throw new ge(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${re}`}]);let s=r,a={...e},o=0;for(;s!==re&&o<hn.length+1;){o+=1;let l=hn.find(c=>c.from===s);if(!l)throw new ge(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(s)}; expected ${re}`}]);s=l.to,a.schemaVersion=s}if(s!==re)throw new ge(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${re}`}]);return{candidate:Qa(a),migratedFrom:eo(r)}}i(no,"migrateArkConfig");function Ct(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=no(e,t),s=[];if(nt(n,An,"$",An,s),Hr(n,s),jr(n,s),s.length>0)throw new ge(t,s);return{config:n,migratedFrom:r}}i(Ct,"loadArkConfigContract");function Rn(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new ge(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return Ct(n,t)}i(Rn,"parseArkConfigJson");function Ur(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:bt,schemaVersion:re};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}i(Ur,"withArkConfigMetadata");function ro(e){return e.endsWith(".")?e:`${e}.`}i(ro,"normalizePrefix");function so(e,t){let n=e.prefixes.length?Math.max(...e.prefixes.map(s=>s.length)):0;return(t.prefixes.length?Math.max(...t.prefixes.map(s=>s.length)):0)-n}i(so,"byLongestPrefix");function _t(e){let t=e.layers.map(s=>({...s,prefixes:s.prefixes.map(ro)})),n=[...t].sort(so),r=[...e.rules??[]];return{name:e.name,layers:t,rules:r,resolveLayer(s){return t.find(a=>a.match?.(s))?.name??n.find(a=>a.prefixes.some(o=>s.startsWith(o)))?.name}}}i(_t,"createArchitectureProfile");function Gr(e,t={}){return _t({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,r)=>({name:n.name,prefixes:n.intentPrefixes??[],description:n.description,order:r+1})),rules:e.rules??[]})}i(Gr,"createArchitectureProfileFromArkConfig");var ao=[{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}],Ot=_t({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:ao,rules:vt.map(e=>({...e}))}),oo={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 Br(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return Ur({include:e.include??[t],layers:Ot.layers.map(s=>({name:s.name,patterns:(oo[s.name]??[s.name]).map(a=>`${r}${a}/**`),intentPrefixes:s.prefixes,optional:n})),rules:[...Ot.rules]})}i(Br,"createElevenLayerArkConfig");function X(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}i(X,"deterministicHash");function j(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(j).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${j(t[n])}`).join(",")}}`}i(j,"stableSerialize");var Oe="1.2";var zr=["network","filesystem","clock","randomness","environment","process","persistence"];function W(e,t){let n=j(e),r=j(t);return n<r?-1:n>r?1:0}i(W,"compareCanonical");function J(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}i(J,"sortedUnique");function rt(e){let t={schemaVersion:"1.2",include:J(e.include??[]),exclude:J(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:J(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:J(n.patterns??[]),exclude:J(n.exclude??[]),forbiddenGlobals:J(n.forbiddenGlobals??[]),intentPrefixes:J(n.intentPrefixes??[]),capabilityDeny:J(n.capabilities?.deny??[]),pure:n.pure===!0})).sort(W),safety:{maxTsSuppressions:e.safety?.maxTsSuppressions??0,maxAnyCasts:e.safety?.maxAnyCasts??0,allowInMemory:e.safety?.allowInMemory===!0,allowDisabledPeerIsolation:e.safety?.allowDisabledPeerIsolation===!0},...e.arkRun?{arkRun:{mode:e.arkRun.mode,compositionRoots:J(e.arkRun.compositionRoots),managedLayers:J(e.arkRun.managedLayers),requireDeclarations:e.arkRun.requireDeclarations===!0}}:{}};return X(j(t))}i(rt,"resolvedFactsEvidenceRequirementsHash");function io(e){let t=e.completenessReasons.map(k=>({code:k.code,message:k.message,...k.file?{file:k.file}:{}})).sort(W),n=e.files.map(k=>({...k,typeOnlyExportNames:J(k.typeOnlyExportNames)})).sort((k,L)=>k.path<L.path?-1:k.path>L.path?1:0),r=e.dependencies.map(k=>({...k,...k.namedBindings?{namedBindings:J(k.namedBindings)}:{}})).sort(W),s=e.capabilityUses.map(k=>({...k})).sort(W),a=e.ambientUses.map(k=>({...k})).sort(W),o=e.publishCalls.map(k=>({...k})).sort(W),l=e.intentReferences.map(k=>({...k})).sort(W),c=e.safetyUses.map(k=>({...k})).sort(W),p=(e.classShapes??[]).map(k=>({...k,mutatingMethods:[...k.mutatingMethods??[]].map(L=>({...L}))})).sort(W),g=(e.arkRunKernelCalls??[]).map(k=>({...k})).sort(W),y=(e.arkRunManagedNews??[]).map(k=>({...k})).sort(W),f=(e.arkRunCompositionRootHits??[]).map(k=>({...k})).sort(W),u=(e.arkRunDeclarations??[]).map(k=>({...k,uses:J(k.uses),reactsTo:J(k.reactsTo),raises:J(k.raises),sends:J(k.sends)})).sort(W),m=(e.arkOrderPlaneCalls??[]).map(k=>({...k})).sort(W),A=(e.arkOrderGenericUpdates??[]).map(k=>({...k})).sort(W),b=(e.arkOrderRootHits??[]).map(k=>({...k})).sort(W),N=(e.arkOrderXiFieldWrites??[]).map(k=>({...k})).sort(W),R=(e.arkOrderIngestWritesXi??[]).map(k=>({...k})).sort(W),I=(e.arkOrderReleaseKeyCounts??[]).map(k=>({...k})).sort(W),C=e.files.map(({path:k,contentHash:L})=>({path:k,contentHash:L})).sort((k,L)=>k.path<L.path?-1:k.path>L.path?1:0),Y=X(j(C));return{schemaVersion:"1.2",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:Y,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:r,capabilityUses:s,ambientUses:a,publishCalls:o,intentReferences:l,safetyUses:c,classShapes:p,arkRunKernelCalls:g,arkRunManagedNews:y,arkRunCompositionRootHits:f,arkRunDeclarations:u,arkOrderPlaneCalls:m,arkOrderGenericUpdates:A,arkOrderRootHits:b,arkOrderXiFieldWrites:N,arkOrderIngestWritesXi:R,arkOrderReleaseKeyCounts:I}}i(io,"canonicalResolvedFactsInput");function qr(e){let t=io(e);return{...t,factsHash:X(j(t))}}i(qr,"createCanonicalResolvedCandidateFacts");function kn(e){return qr(Yr(F(e,"$"),!1))}i(kn,"createResolvedCandidateFacts");function F(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}i(F,"asRecord");function V(e,t,n){let r=new Set(t),s=Object.keys(e).find(a=>!r.has(a));if(s)throw new Error(`${n}.${s} is not part of schema ${"1.2"}.`)}i(V,"assertOnlyKeys");function M(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(M,"requiredText");function ye(e,t,n){if(e[t]!==void 0)return M(e,t,n)}i(ye,"optionalText");function U(e,t,n){let r=M(e,t,n),s=r.replace(/\\/g,"/");if(!s||s.startsWith("/")||/^[A-Za-z]:\//.test(s)||/[\u0000-\u001f\u007f]/.test(s))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let a=[];for(let l of s.split("/"))if(!(!l||l==="."))if(l===".."){if(a.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);a.pop()}else a.push(l);let o=a.join("/");if(!o||o!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return o}i(U,"requiredProjectPath");function G(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}i(G,"requiredBoolean");function Wr(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(Wr,"requiredInteger");function Z(e,t,n){let r=Wr(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}i(Z,"requiredPositiveInteger");function B(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}i(B,"requiredArray");function he(e,t,n,r){let s=e[t];if(typeof s!="string"||!n.includes(s))throw new Error(`${r}.${t} must be one of ${n.join(", ")}.`);return s}i(he,"enumValue");function Ve(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(Ve,"parseStringArray");function lo(e,t,n){let r=new Set;for(let s of e){let a=t(s);if(r.has(a))throw new Error(`${n} must not contain duplicate facts (${a}).`);r.add(a)}}i(lo,"assertUnique");function Yr(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=he(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=he(e,"completeness",["complete","partial","unavailable"],"$"),s=B(e,"completenessReasons","$").map((S,v)=>{let h=`$.completenessReasons[${v}]`,d=F(S,h);V(d,["code","message","file"],h);let P=d.file===void 0?void 0:U(d,"file",h);return{code:M(d,"code",h),message:M(d,"message",h),...P?{file:P}:{}}});if(r==="complete"&&s.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(r!=="complete"&&s.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let a=B(e,"files","$").map((S,v)=>{let h=`$.files[${v}]`,d=F(S,h);return V(d,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],h),{path:U(d,"path",h),contentHash:M(d,"contentHash",h),parseStatus:he(d,"parseStatus",["parsed","invalid"],h),parseDiagnosticCount:Wr(d,"parseDiagnosticCount",h),exportsOnlyTypes:G(d,"exportsOnlyTypes",h),typeOnlyExportNames:Ve(d.typeOnlyExportNames,`${h}.typeOnlyExportNames`),hasTopLevelSideEffects:G(d,"hasTopLevelSideEffects",h)}}),o=B(e,"dependencies","$").map((S,v)=>{let h=`$.dependencies[${v}]`,d=F(S,h);V(d,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],h);let P=ye(d,"specifier",h),H=ye(d,"target",h),oe=he(d,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],h);if(oe==="resolved-project"&&!H)throw new Error(`${h}.target is required for resolved-project dependencies.`);if(oe!=="resolved-project"&&H)throw new Error(`${h}.target is only allowed for resolved-project dependencies.`);if(oe!=="dynamic"&&!P)throw new Error(`${h}.specifier is required unless resolution is dynamic.`);return{from:U(d,"from",h),...P?{specifier:P}:{},kind:he(d,"kind",["import","export","dynamic-import","require"],h),typeOnly:G(d,"typeOnly",h),line:Z(d,"line",h),resolution:oe,...H?{target:U(d,"target",h)}:{},...d.namedBindings!==void 0?{namedBindings:Ve(d.namedBindings,`${h}.namedBindings`)}:{},...d.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:G(d,"targetTypeOnlyExports",h)}:{},...d.sourcePureTypeModule!==void 0?{sourcePureTypeModule:G(d,"sourcePureTypeModule",h)}:{},...d.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:G(d,"namedBindingsTypeOnly",h)}:{},...d.portProofEligible!==void 0?{portProofEligible:G(d,"portProofEligible",h)}:{}}}),l=B(e,"capabilityUses","$").map((S,v)=>{let h=`$.capabilityUses[${v}]`,d=F(S,h);return V(d,["file","line","symbol","capability","source"],h),{file:U(d,"file",h),line:Z(d,"line",h),symbol:M(d,"symbol",h),capability:he(d,"capability",zr,h),source:he(d,"source",["ambient-global","import-based"],h)}}),c=B(e,"ambientUses","$").map((S,v)=>{let h=`$.ambientUses[${v}]`,d=F(S,h);return V(d,["file","line","symbol"],h),{file:U(d,"file",h),line:Z(d,"line",h),symbol:M(d,"symbol",h)}}),p=B(e,"publishCalls","$").map((S,v)=>{let h=`$.publishCalls[${v}]`,d=F(S,h);V(d,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],h);let P=ye(d,"rawIntentName",h),H=ye(d,"sourceIntent",h);return{file:U(d,"file",h),line:Z(d,"line",h),...P?{rawIntentName:P}:{},objectHasIntent:G(d,"objectHasIntent",h),arkPublishCandidate:G(d,"arkPublishCandidate",h),hasSource:G(d,"hasSource",h),...H?{sourceIntent:H}:{}}}),g=B(e,"intentReferences","$").map((S,v)=>{let h=`$.intentReferences[${v}]`,d=F(S,h);return V(d,["file","line","intent"],h),{file:U(d,"file",h),line:Z(d,"line",h),intent:M(d,"intent",h)}}),y=B(e,"safetyUses","$").map((S,v)=>{let h=`$.safetyUses[${v}]`,d=F(S,h);V(d,["file","line","kind","symbol"],h);let P=ye(d,"symbol",h),H=he(d,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],h);if(H==="in-memory-store"&&!P)throw new Error(`${h}.symbol is required for in-memory-store facts.`);if(H!=="in-memory-store"&&P)throw new Error(`${h}.symbol is only allowed for in-memory-store facts.`);return{file:U(d,"file",h),line:Z(d,"line",h),kind:H,...P?{symbol:P}:{}}});lo(a,S=>S.path,"$.files");let f=new Set(a.map(S=>S.path));for(let S of a){if(S.parseStatus==="parsed"&&S.parseDiagnosticCount!==0)throw new Error(`$.files[${S.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(S.parseStatus==="invalid"&&S.parseDiagnosticCount===0)throw new Error(`$.files[${S.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&a.some(S=>S.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let S of o)if(!f.has(S.from))throw new Error(`$.dependencies references missing source file ${S.from}.`);let m=(e.arkRunKernelCalls===void 0?[]:B(e,"arkRunKernelCalls","$")).map((S,v)=>{let h=`$.arkRunKernelCalls[${v}]`,d=F(S,h);V(d,["file","line","kind","callee","viaImport","receiver","nameLiteral"],h);let P=ye(d,"receiver",h),H=ye(d,"nameLiteral",h);return{file:U(d,"file",h),line:Z(d,"line",h),kind:he(d,"kind",["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"],h),callee:M(d,"callee",h),viaImport:G(d,"viaImport",h),...P?{receiver:P}:{},...H?{nameLiteral:H}:{}}}),b=(e.arkRunManagedNews===void 0?[]:B(e,"arkRunManagedNews","$")).map((S,v)=>{let h=`$.arkRunManagedNews[${v}]`,d=F(S,h);V(d,["file","line","typeName","importedFrom"],h);let P=ye(d,"importedFrom",h);return{file:U(d,"file",h),line:Z(d,"line",h),typeName:M(d,"typeName",h),...P?{importedFrom:P}:{}}}),R=(e.arkRunCompositionRootHits===void 0?[]:B(e,"arkRunCompositionRootHits","$")).map((S,v)=>{let h=`$.arkRunCompositionRootHits[${v}]`,d=F(S,h);return V(d,["file","matchedRoot","hasKernelFactory"],h),{file:U(d,"file",h),matchedRoot:M(d,"matchedRoot",h),hasKernelFactory:G(d,"hasKernelFactory",h)}}),I=e.arkRunDeclarations===void 0?[]:B(e,"arkRunDeclarations","$"),Y=(e.arkOrderPlaneCalls===void 0?[]:B(e,"arkOrderPlaneCalls","$")).map((S,v)=>{let h=`$.arkOrderPlaneCalls[${v}]`,d=F(S,h);return V(d,["file","line","callee"],h),{file:U(d,"file",h),line:Z(d,"line",h),callee:M(d,"callee",h)}}),L=(e.arkOrderGenericUpdates===void 0?[]:B(e,"arkOrderGenericUpdates","$")).map((S,v)=>{let h=`$.arkOrderGenericUpdates[${v}]`,d=F(S,h);return V(d,["file","line","method"],h),{file:U(d,"file",h),line:Z(d,"line",h),method:M(d,"method",h)}}),x=(e.arkOrderRootHits===void 0?[]:B(e,"arkOrderRootHits","$")).map((S,v)=>{let h=`$.arkOrderRootHits[${v}]`,d=F(S,h);return V(d,["file","matchedRoot","hasPlaneFactory"],h),{file:U(d,"file",h),matchedRoot:M(d,"matchedRoot",h),hasPlaneFactory:G(d,"hasPlaneFactory",h)}}),w=(e.arkOrderXiFieldWrites===void 0?[]:B(e,"arkOrderXiFieldWrites","$")).map((S,v)=>{let h=`$.arkOrderXiFieldWrites[${v}]`,d=F(S,h);return V(d,["file","line","key"],h),{file:U(d,"file",h),line:Z(d,"line",h),key:M(d,"key",h)}}),ue=(e.arkOrderIngestWritesXi===void 0?[]:B(e,"arkOrderIngestWritesXi","$")).map((S,v)=>{let h=`$.arkOrderIngestWritesXi[${v}]`,d=F(S,h);return V(d,["file","line"],h),{file:U(d,"file",h),line:Z(d,"line",h)}}),qe=(e.arkOrderReleaseKeyCounts===void 0?[]:B(e,"arkOrderReleaseKeyCounts","$")).map((S,v)=>{let h=`$.arkOrderReleaseKeyCounts[${v}]`,d=F(S,h);return V(d,["file","line","keyCount"],h),{file:U(d,"file",h),line:Z(d,"line",h),keyCount:Z(d,"keyCount",h)}}),We=I.map((S,v)=>{let h=`$.arkRunDeclarations[${v}]`,d=F(S,h);return V(d,["file","line","uses","reactsTo","raises","sends"],h),{file:U(d,"file",h),line:Z(d,"line",h),uses:Ve(d.uses,`${h}.uses`),reactsTo:Ve(d.reactsTo,`${h}.reactsTo`),raises:Ve(d.raises,`${h}.raises`),sends:Ve(d.sends,`${h}.sends`)}});for(let[S,v]of[["$.capabilityUses",l],["$.ambientUses",c],["$.publishCalls",p],["$.intentReferences",g],["$.safetyUses",y],["$.arkRunKernelCalls",m],["$.arkRunManagedNews",b],["$.arkRunCompositionRootHits",R],["$.arkRunDeclarations",We],["$.arkOrderPlaneCalls",Y],["$.arkOrderGenericUpdates",L],["$.arkOrderRootHits",x],["$.arkOrderXiFieldWrites",w],["$.arkOrderIngestWritesXi",ue],["$.arkOrderReleaseKeyCounts",qe]])for(let h of v)if(!f.has(h.file))throw new Error(`${S} references missing file ${h.file}.`);let be=ye(e,"projectPackageName","$"),Zt=(e.classShapes===void 0?[]:B(e,"classShapes","$")).map((S,v)=>{let h=`$.classShapes[${v}]`,d=F(S,h);V(d,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],h);let P=B(d,"mutatingMethods",h).map((H,oe)=>{let At=`${h}.mutatingMethods[${oe}]`,Qt=F(H,At);return V(Qt,["name","referencesGuardOrPublish"],At),{name:M(Qt,"name",At),referencesGuardOrPublish:G(Qt,"referencesGuardOrPublish",At)}});return{file:U(d,"file",h),className:M(d,"className",h),exported:G(d,"exported",h),hasPublicMutableFields:G(d,"hasPublicMutableFields",h),hasPublicSetters:G(d,"hasPublicSetters",h),hasPublicConstructor:G(d,"hasPublicConstructor",h),hasStaticFactory:G(d,"hasStaticFactory",h),mutatingMethods:P,...d.dataOnly===void 0?{}:{dataOnly:G(d,"dataOnly",h)}}});return{schemaVersion:n,completeness:r,completenessReasons:s,resolverIdentity:M(e,"resolverIdentity","$"),compilerIdentity:M(e,"compilerIdentity","$"),compilerOptionsHash:M(e,"compilerOptionsHash","$"),tsconfigHash:M(e,"tsconfigHash","$"),evidenceRequirementsHash:M(e,"evidenceRequirementsHash","$"),...be?{projectPackageName:be}:{},files:a,dependencies:o,capabilityUses:l,ambientUses:c,publishCalls:p,intentReferences:g,safetyUses:y,classShapes:Zt,arkRunKernelCalls:m,arkRunManagedNews:b,arkRunCompositionRootHits:R,arkRunDeclarations:We,arkOrderPlaneCalls:Y,arkOrderGenericUpdates:L,arkOrderRootHits:x,arkOrderXiFieldWrites:w,arkOrderIngestWritesXi:ue,arkOrderReleaseKeyCounts:qe}}i(Yr,"parseResolvedFactsInput");function Se(e){let t=F(e,"$"),n=M(t,"factsHash","$"),r=M(t,"candidateTreeHash","$"),s=qr(Yr(t,!0));if(s.factsHash!==n)throw new Error(`$.factsHash does not match the canonical payload (${s.factsHash}).`);if(r!==s.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${s.candidateTreeHash}).`);return s}i(Se,"loadResolvedCandidateFacts");var co=["network","filesystem","clock","randomness","environment","process","persistence"],_={type:"string",minLength:1},te={type:"integer",minimum:1},z={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},En={$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:_,message:_,file:z}}},resolverIdentity:_,compilerIdentity:_,compilerOptionsHash:_,tsconfigHash:_,candidateTreeHash:_,evidenceRequirementsHash:_,projectPackageName:_,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:z,contentHash:_,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:_},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:z,specifier:_,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:te,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:z,namedBindings:{type:"array",items:_},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:z,line:te,symbol:_,capability:{enum:co},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:z,line:te,symbol:_}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:z,line:te,rawIntentName:_,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:_}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:z,line:te,intent:_}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:z,line:te,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:_},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:z,className:_,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:_,referencesGuardOrPublish:{type:"boolean"}}}}}}},arkRunKernelCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind","callee","viaImport"],properties:{file:z,line:te,kind:{enum:["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"]},callee:_,viaImport:{type:"boolean"},receiver:_,nameLiteral:_}}},arkRunManagedNews:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","typeName"],properties:{file:z,line:te,typeName:_,importedFrom:_}}},arkRunCompositionRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasKernelFactory"],properties:{file:z,matchedRoot:_,hasKernelFactory:{type:"boolean"}}}},arkRunDeclarations:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","uses","reactsTo","raises","sends"],properties:{file:z,line:te,uses:{type:"array",items:_},reactsTo:{type:"array",items:_},raises:{type:"array",items:_},sends:{type:"array",items:_}}}},arkOrderPlaneCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","callee"],properties:{file:z,line:te,callee:_}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:z,line:te,method:_}}},arkOrderRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasPlaneFactory"],properties:{file:z,matchedRoot:_,hasPlaneFactory:{type:"boolean"}}}},arkOrderXiFieldWrites:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:z,line:te,key:_}}},arkOrderIngestWritesXi:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line"],properties:{file:z,line:te}}},arkOrderReleaseKeyCounts:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","keyCount"],properties:{file:z,line:te,keyCount:{type:"integer",minimum:1}}}},factsHash:_},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 In="1.0";function se(e){return`${e.from}->${e.to}`}i(se,"dependencyKey");function st(e,t,n,r="dependency"){return{id:`${e}:${r}:${se(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${se(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${se(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${se(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${se(t)} from the candidate, then preflight again.`}:{}}}i(st,"dependencyFinding");function Ke(e){let t=[],n=new Map(e.changeMap.map.files.map(f=>[f.path,f])),r=new Map(e.changes.map(f=>[f.path,f])),s=new Map(e.changeMap.map.dependencies.map(f=>[se(f),f])),a=new Map(e.baseDependencies.map(f=>[se(f),f])),o=new Map(e.candidateDependencies.map(f=>[se(f),f]));for(let f of[...n.values()].sort((u,m)=>u.path.localeCompare(m.path))){let u=r.get(f.path);u?u.operation!==f.operation?t.push({id:`contradictory:file:${f.path}`,classification:"contradictory",subject:"file",path:f.path,expectedOperation:f.operation,actualOperation:u.operation,message:`${f.path} was planned as ${f.operation} but the actual operation is ${u.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:u.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((u,m)=>u.path.localeCompare(m.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[...s.values()].sort((u,m)=>se(u).localeCompare(se(m)))){if(o.has(se(f))){t.push(st("satisfied",f,`${f.from} -> ${f.to} exists in the candidate architecture.`));continue}let u={from:f.to,to:f.from};o.has(se(u))?(l.add(se(u)),t.push(st("contradictory",f,`${f.from} -> ${f.to} was planned, but the candidate contains the reverse edge.`))):t.push(st("missing",f,`${f.from} -> ${f.to} is absent from the candidate architecture.`))}let c=new Set([...n.keys(),...r.keys()]);for(let[f,u]of[...o].sort(([m],[A])=>m.localeCompare(A)))a.has(f)||s.has(f)||l.has(f)||!c.has(u.from)&&!c.has(u.to)||t.push({...st("unplanned",u,`${u.from} -> ${u.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let p=new Set(e.changeMap.map.files.filter(f=>f.operation==="delete").map(f=>f.path));for(let[f,u]of[...a].sort(([m],[A])=>m.localeCompare(A)))o.has(f)||p.has(u.from)||p.has(u.to)||!c.has(u.from)&&!c.has(u.to)||t.push({...st("unplanned",u,`${u.from} -> ${u.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let g={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((f,u)=>g[f.classification]-g[u.classification]||(f.subject===u.subject?0:f.subject==="file"?-1:1)||f.id.localeCompare(u.id));let y={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:y.missing===0&&y.contradictory===0&&y.unplanned===0,behavioralCompletion:"not-evaluated",summary:y,findings:t}}i(Ke,"analyzeArchitectureConvergence");var uo="1.0",Sn="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",Zr=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","writes-via-aggregate","no-anemic-model","invariant-coverage"],po=["no-anemic-model"],Xr={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},bn={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Sn,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:Sn},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:[...Zr]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:Xr,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:Xr}}}},_e=class extends Error{static{i(this,"ArkRulesValidationError")}issues;source;constructor(t,n){super(`Invalid ArkRules (${t}):
5
5
  ${n.map(r=>`- ${r.path}: ${r.message}`).join(`
6
- `)}`),this.name="ArkRulesValidationError",this.source=t,this.issues=n}};function it(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(it,"isObject");function xt(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}i(xt,"propertyPath");function ot(e){return e===null?"null":Array.isArray(e)?"array":typeof e}i(ot,"valueType");function ua(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}i(ua,"resolveSchemaRef");function at(e,t,n,r,s){if(t.$ref){let o=ua(t.$ref,r);if(!o){s.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}at(e,o,n,r,s);return}if(t.const!==void 0&&!Object.is(e,t.const)){s.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(o=>Object.is(o,e))){s.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!it(e)){s.push({path:n,message:`must be an object; received ${ot(e)}`});return}let o=t.properties??{};for(let a of t.required??[])e[a]===void 0&&s.push({path:xt(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in o||s.push({path:xt(n,a),message:"unknown field"});else if(it(t.additionalProperties)){let a=t.additionalProperties;for(let l of Object.keys(e))l in o||at(e[l],a,xt(n,l),r,s)}for(let[a,l]of Object.entries(o))e[a]!==void 0&&at(e[a],l,xt(n,a),r,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:n,message:`must be an array; received ${ot(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&s.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let o=e.map(a=>JSON.stringify(a));new Set(o).size!==o.length&&s.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((o,a)=>at(o,t.items,`${n}[${a}]`,r,s));return}if(t.type==="string"){if(typeof e!="string"){s.push({path:n,message:`must be a string; received ${ot(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&s.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}t.type==="boolean"&&typeof e!="boolean"&&s.push({path:n,message:`must be a boolean; received ${ot(e)}`})}i(at,"validateNode");function pa(e){return{...e,$schema:e.$schema===void 0?kn: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(pa,"defaultedArkRules");function Wr(e){return e==="enforced"?"enforced":"advisory"}i(Wr,"normalizeMode");function fa(e){return da.includes(e)}i(fa,"isTier2Sensor");function ma(e,t){let n=Array.isArray(e.structure)?e.structure:[],r=Array.isArray(e.invariants)?e.invariants:[],s=new Set;n.forEach((o,a)=>{if(!it(o))return;let l=typeof o.id=="string"?o.id:"";l&&(s.has(l)&&t.push({path:`$.structure[${a}].id`,message:`duplicate rule id ${JSON.stringify(l)}`}),s.add(l)),typeof o.sensor=="string"&&fa(o.sensor)&&o.mode==="enforced"&&t.push({path:`$.structure[${a}].mode`,message:`sensor ${JSON.stringify(o.sensor)} is Tier-2 advisory-only and cannot be enforced`}),Array.isArray(o.appliesTo)&&o.appliesTo.length===0&&t.push({path:`$.structure[${a}].appliesTo`,message:"must not be an empty array (omit the field to apply to the whole layer)"})}),r.forEach((o,a)=>{if(!it(o))return;let l=typeof o.id=="string"?o.id:"";l&&(s.has(l)&&t.push({path:`$.invariants[${a}].id`,message:`duplicate rule id ${JSON.stringify(l)}`}),s.add(l)),Array.isArray(o.appliesTo)&&o.appliesTo.length===0&&t.push({path:`$.invariants[${a}].appliesTo`,message:"must not be an empty array (omit the field to apply to the whole layer)"})})}i(ma,"validateSemantics");function Tt(e,t="arkrules.json",n){if(!it(e))throw new xe(t,[{path:"$",message:`must be an object; received ${ot(e)}`}]);let r=pa(e),s=[];if(at(r,En,"$",En,s),ma(r,s),n!==void 0&&typeof r.layer=="string"&&r.layer!==n&&s.push({path:"$.layer",message:`must match referencing key ${JSON.stringify(n)}; received ${JSON.stringify(r.layer)}`}),s.length>0)throw new xe(t,s);return{config:r}}i(Tt,"loadArkRulesContract");function ga(e,t="arkrules.json",n){let r;try{r=JSON.parse(e)}catch(s){throw new xe(t,[{path:"$",message:`invalid JSON: ${s instanceof Error?s.message:String(s)}`}])}return Tt(r,t,n)}i(ga,"parseArkRulesJson");function Sn(e){let t={},n=[],r=[],s=[...e].sort((o,a)=>o.layer.localeCompare(a.layer));for(let o of s){let a=(o.file.structure??[]).map(c=>({...c,mode:Wr(c.mode),provenance:{sourceFile:o.sourceFile,ruleId:c.id,layer:o.layer}})),l=(o.file.invariants??[]).map(c=>({...c,mode:Wr(c.mode),provenance:{sourceFile:o.sourceFile,ruleId:c.id,layer:o.layer}}));t[o.layer]={sourceFile:o.sourceFile,structure:a,invariants:l},n.push(...a),r.push(...l)}return n.sort((o,a)=>{let l=o.provenance.layer.localeCompare(a.provenance.layer);return l!==0?l:o.id.localeCompare(a.id)}),r.sort((o,a)=>{let l=o.provenance.layer.localeCompare(a.provenance.layer);return l!==0?l:o.id.localeCompare(a.id)}),{schemaVersion:"1.0",byLayer:t,structure:n,invariants:r}}i(Sn,"buildEffectiveArkRules");function Te(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}i(Te,"emptyEffectiveArkRules");var Nt=class extends Error{static{i(this,"EffectiveContractError")}issues;source;constructor(t,n){super(`Invalid Effective Contract (${t}):
6
+ `)}`),this.name="ArkRulesValidationError",this.source=t,this.issues=n}};function it(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(it,"isObject");function xt(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}i(xt,"propertyPath");function at(e){return e===null?"null":Array.isArray(e)?"array":typeof e}i(at,"valueType");function fo(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}i(fo,"resolveSchemaRef");function ot(e,t,n,r,s){if(t.$ref){let a=fo(t.$ref,r);if(!a){s.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}ot(e,a,n,r,s);return}if(t.const!==void 0&&!Object.is(e,t.const)){s.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(a=>Object.is(a,e))){s.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!it(e)){s.push({path:n,message:`must be an object; received ${at(e)}`});return}let a=t.properties??{};for(let o of t.required??[])e[o]===void 0&&s.push({path:xt(n,o),message:"is required"});if(t.additionalProperties===!1)for(let o of Object.keys(e))o in a||s.push({path:xt(n,o),message:"unknown field"});else if(it(t.additionalProperties)){let o=t.additionalProperties;for(let l of Object.keys(e))l in a||ot(e[l],o,xt(n,l),r,s)}for(let[o,l]of Object.entries(a))e[o]!==void 0&&ot(e[o],l,xt(n,o),r,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:n,message:`must be an array; received ${at(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&s.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let a=e.map(o=>JSON.stringify(o));new Set(a).size!==a.length&&s.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((a,o)=>ot(a,t.items,`${n}[${o}]`,r,s));return}if(t.type==="string"){if(typeof e!="string"){s.push({path:n,message:`must be a string; received ${at(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&s.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}t.type==="boolean"&&typeof e!="boolean"&&s.push({path:n,message:`must be a boolean; received ${at(e)}`})}i(ot,"validateNode");function mo(e){return{...e,$schema:e.$schema===void 0?Sn: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(mo,"defaultedArkRules");function Jr(e){return e==="enforced"?"enforced":"advisory"}i(Jr,"normalizeMode");function go(e){return po.includes(e)}i(go,"isTier2Sensor");function yo(e,t){let n=Array.isArray(e.structure)?e.structure:[],r=Array.isArray(e.invariants)?e.invariants:[],s=new Set;n.forEach((a,o)=>{if(!it(a))return;let l=typeof a.id=="string"?a.id:"";l&&(s.has(l)&&t.push({path:`$.structure[${o}].id`,message:`duplicate rule id ${JSON.stringify(l)}`}),s.add(l)),typeof a.sensor=="string"&&go(a.sensor)&&a.mode==="enforced"&&t.push({path:`$.structure[${o}].mode`,message:`sensor ${JSON.stringify(a.sensor)} is Tier-2 advisory-only and cannot be enforced`}),Array.isArray(a.appliesTo)&&a.appliesTo.length===0&&t.push({path:`$.structure[${o}].appliesTo`,message:"must not be an empty array (omit the field to apply to the whole layer)"})}),r.forEach((a,o)=>{if(!it(a))return;let l=typeof a.id=="string"?a.id:"";l&&(s.has(l)&&t.push({path:`$.invariants[${o}].id`,message:`duplicate rule id ${JSON.stringify(l)}`}),s.add(l)),Array.isArray(a.appliesTo)&&a.appliesTo.length===0&&t.push({path:`$.invariants[${o}].appliesTo`,message:"must not be an empty array (omit the field to apply to the whole layer)"})})}i(yo,"validateSemantics");function Tt(e,t="arkrules.json",n){if(!it(e))throw new _e(t,[{path:"$",message:`must be an object; received ${at(e)}`}]);let r=mo(e),s=[];if(ot(r,bn,"$",bn,s),yo(r,s),n!==void 0&&typeof r.layer=="string"&&r.layer!==n&&s.push({path:"$.layer",message:`must match referencing key ${JSON.stringify(n)}; received ${JSON.stringify(r.layer)}`}),s.length>0)throw new _e(t,s);return{config:r}}i(Tt,"loadArkRulesContract");function ho(e,t="arkrules.json",n){let r;try{r=JSON.parse(e)}catch(s){throw new _e(t,[{path:"$",message:`invalid JSON: ${s instanceof Error?s.message:String(s)}`}])}return Tt(r,t,n)}i(ho,"parseArkRulesJson");function vn(e){let t={},n=[],r=[],s=[...e].sort((a,o)=>a.layer.localeCompare(o.layer));for(let a of s){let o=(a.file.structure??[]).map(c=>({...c,mode:Jr(c.mode),provenance:{sourceFile:a.sourceFile,ruleId:c.id,layer:a.layer}})),l=(a.file.invariants??[]).map(c=>({...c,mode:Jr(c.mode),provenance:{sourceFile:a.sourceFile,ruleId:c.id,layer:a.layer}}));t[a.layer]={sourceFile:a.sourceFile,structure:o,invariants:l},n.push(...o),r.push(...l)}return n.sort((a,o)=>{let l=a.provenance.layer.localeCompare(o.provenance.layer);return l!==0?l:a.id.localeCompare(o.id)}),r.sort((a,o)=>{let l=a.provenance.layer.localeCompare(o.provenance.layer);return l!==0?l:a.id.localeCompare(o.id)}),{schemaVersion:"1.0",byLayer:t,structure:n,invariants:r}}i(vn,"buildEffectiveArkRules");function xe(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}i(xe,"emptyEffectiveArkRules");var Nt=class extends Error{static{i(this,"EffectiveContractError")}issues;source;constructor(t,n){super(`Invalid Effective Contract (${t}):
7
7
  ${n.map(r=>`- ${r.path}: ${r.message}`).join(`
8
- `)}`),this.name="EffectiveContractError",this.source=t,this.issues=n}};function Zr(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}i(Zr,"normalizeRel");function ya(e,t="ark.config.json"){let n=e.config.arkRules,r=[];if(!n||Object.keys(n).length===0){if(e.discoveredArkRulesFiles&&e.discoveredArkRulesFiles.length>0)for(let c of[...e.discoveredArkRulesFiles].sort())r.push({path:c,message:`ArkRules file ${JSON.stringify(c)} is not referenced by arkRules and will not be enforced`,severity:"advisory"});return{config:e.config,arkRules:Te(),warnings:r}}let s=new Set(e.config.layers.map(c=>c.name)),o=[],a=[],l=new Set;for(let c of Object.keys(n).sort()){let p=n[c],m=`$.arkRules[${JSON.stringify(c)}]`;if(typeof p!="string"||p.length===0){o.push({path:m,message:"must be a non-empty relative path string"});continue}if(p.startsWith("/")||/^[A-Za-z]:[\\/]/.test(p)){o.push({path:m,message:"must be a project-relative path (absolute paths are not allowed)"});continue}if(!s.has(c)){o.push({path:m,message:`layer ${JSON.stringify(c)} is not declared in layers[]`});continue}let g=Zr(p);l.add(g);let u=e.fileContents[g]??e.fileContents[p];if(u===void 0){o.push({path:m,message:`referenced ArkRules file ${JSON.stringify(g)} is missing`});continue}try{let d=Tt(JSON.parse(u),g,c);a.push({layer:c,sourceFile:g,file:d.config})}catch(d){if(d instanceof xe)for(let f of d.issues)o.push({path:`${m}${f.path==="$"?"":f.path.replace(/^\$/,"")}`,message:`${g}: ${f.message}`});else d instanceof SyntaxError?o.push({path:m,message:`referenced ArkRules file ${JSON.stringify(g)} is not valid JSON: ${d.message}`}):o.push({path:m,message:`referenced ArkRules file ${JSON.stringify(g)} failed to load: ${d instanceof Error?d.message:String(d)}`})}}if(e.discoveredArkRulesFiles)for(let c of[...e.discoveredArkRulesFiles].sort()){let p=Zr(c);l.has(p)||r.push({path:p,message:`ArkRules file ${JSON.stringify(p)} is not referenced by arkRules and will not be enforced`,severity:"advisory"})}if(o.length>0)throw new Nt(t,o);return{config:e.config,arkRules:Sn(a),warnings:r}}i(ya,"resolveEffectiveContract");function In(e){let{stewards:t,...n}=e.config;return{config:n,arkRules:{schemaVersion:e.arkRules.schemaVersion,structure:e.arkRules.structure.map(r=>({id:r.id,sensor:r.sensor,mode:r.mode,appliesTo:r.appliesTo??null,description:r.description??null,provenance:r.provenance})),invariants:e.arkRules.invariants.map(r=>({id:r.id,description:r.description,aggregate:r.aggregate??null,coverage:r.coverage??null,mode:r.mode,appliesTo:r.appliesTo??null,provenance:r.provenance}))}}}i(In,"effectiveContractPolicyPayload");function ha(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*['"\`][^'"\`]*${n}[^'"\`]*['"\`]`,"i").test(e)||e.includes(t)}i(ha,"titleMatchesInvariant");function Aa(e,t){if(!t)return!1;let n=t.split("."),r=n[n.length-1],s=n.length>1?n[0]:null;for(let o of Object.values(e))if(!(s&&!o.includes(s))&&(new RegExp(`(?:function\\s+|\\b)${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[(<]`).test(o)||o.includes(t)))return!0;return!1}i(Aa,"symbolPresent");function vn(e){let t=e.arkRules.invariants??[];if(t.length===0)return{coverage:[],violations:[],partial:!1};let n=e.testFiles??[],r=e.testGlobsMissing===!0||n.length===0,s=e.coverageBudgetExhausted===!0,o=[],a=[];for(let l of t){let c=[],p=l.coverage?.test!==!1,m=l.coverage?.symbol;if(!r&&p)for(let f of n){let y=e.fileContents[f];if(y&&ha(y,l.id)){c.push("test-title");break}}m&&Aa(e.fileContents,m)&&c.push("symbol");let u=(l.coverage?.test===!0||!!m||l.coverage===void 0)&&c.length>0||l.coverage?.test===!1&&!m?!0:c.length>0,d=r&&p&&c.length===0;if(o.push({invariantId:l.id,layer:l.provenance.layer,sourceFile:l.provenance.sourceFile,mode:l.mode,covered:u&&!d,evidence:c,partial:d,description:l.description}),!u||d){let f=l.mode==="enforced"&&!d,y=r||n.length===0?"never-had-tests":"tests-disappeared";a.push({ruleId:"INVARIANT_UNCOVERED",message:d?s?`Invariant ${l.id} coverage cannot be proven (coverage file budget exhausted); reporting partial, not covered.`:`Invariant ${l.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered (never-had-tests).`:y==="tests-disappeared"?`Invariant ${l.id} is not covered by a test title or declared symbol (tests-disappeared \u2014 suite exists).`:`Invariant ${l.id} is not covered by a test title or declared symbol (never-had-tests).`,file:l.provenance.sourceFile,line:1,arkruleId:l.id,arkruleSource:l.provenance.sourceFile,fromLayer:l.provenance.layer,severity:f?"error":"warning",failsStrict:f,kind:y})}}return{coverage:o,violations:a,partial:o.some(l=>l.partial)}}i(vn,"evaluateInvariantCoverage");function bn(e){return e?e.partial?{ok:!1,reason:"Coverage is partial (missing test globs); cannot promote until evidence is complete."}:e.covered?{ok:!0,reason:`Invariant ${e.invariantId} has coverage evidence.`}:{ok:!1,reason:`Invariant ${e.invariantId} is uncovered; add a test title or symbol before promoting to enforced.`}:{ok:!1,reason:"No coverage evidence supplied for this invariant; evaluate coverage before promoting to enforced."}}i(bn,"canPromoteInvariant");var On="1.0";function T(e,t){e.push({id:`${t.classification}:${t.path}:${t.kind}`,path:t.path,classification:t.classification,message:t.message,...t.classification==="weakening"||t.classification==="judgment-required"?{nextAction:`Restore the previous protection at ${t.path}, then run ArkGate again.`}:{},...t.before===void 0?{}:{before:t.before},...t.after===void 0?{}:{after:t.after}})}i(T,"addFinding");function oe(e){return[...new Set(e??[])].sort()}i(oe,"sortedUnique");function de(e,t,n,r,s){let o=oe(n),a=oe(r),l=new Set(o),c=new Set(a),p=a.filter(g=>!l.has(g)),m=o.filter(g=>!c.has(g));p.length===0&&m.length===0||(p.length>0&&T(e,{kind:"added",path:t,classification:s.added,message:s.addedMessage,before:o,after:a}),m.length>0&&T(e,{kind:"removed",path:t,classification:s.removed,message:s.removedMessage,before:o,after:a}))}i(de,"compareStringSets");function lt(e,t,n,r,s,o,a){if(n===r)return;T(e,{kind:r?"enabled":"disabled",path:t,classification:r?s:s==="strengthening"?"weakening":"strengthening",message:r?o:a,before:n,after:r})}i(lt,"compareBoolean");function Pt(e,t){let n=new Map,r=new Set;for(let s of e){let o=t(s);n.has(o)?r.add(o):n.set(o,s)}return{values:n,duplicates:[...r].sort()}}i(Pt,"keyed");function Ra(e,t,n){let r=Pt(t,o=>o.name),s=Pt(n,o=>o.name);(r.duplicates.length>0||s.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:s.duplicates});for(let o of[...new Set([...r.values.keys(),...s.values.keys()])].sort()){let a=r.values.get(o),l=s.values.get(o),c=`$.layers[${o}]`;if(!a&&l){T(e,{kind:"layer-added",path:c,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:l});continue}if(a&&!l){T(e,{kind:"layer-removed",path:c,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:a});continue}if(!a||!l)continue;de(e,`${c}.patterns`,a.patterns,l.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),de(e,`${c}.exclude`,a.exclude,l.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let p=Et(a),m=Et(l);de(e,`${c}.forbiddenGlobals`,p.rawGlobals,m.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),de(e,`${c}.capabilities`,p.atoms,m.atoms,{added:"strengthening",removed:"weakening",addedMessage:"Additional ambient/import protection is enforced in this layer (coverage atoms).",removedMessage:"An ambient/import protection was lost from this layer (coverage atoms)."}),oe(a.intentPrefixes).join("\0")!==oe(l.intentPrefixes).join("\0")&&T(e,{kind:"intent-prefixes-changed",path:`${c}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:oe(a.intentPrefixes),after:oe(l.intentPrefixes)}),lt(e,`${c}.mayImportInfrastructure`,a.mayImportInfrastructure===!0,l.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),lt(e,`${c}.optional`,a.optional===!0,l.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active.")}}i(Ra,"compareLayers");function ka(e,t,n){let r=i(a=>`${a.from}->${a.to}`,"keyOf"),s=Pt(t,r),o=Pt(n,r);(s.duplicates.length>0||o.duplicates.length>0)&&T(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:s.duplicates,after:o.duplicates});for(let a of[...new Set([...s.values.keys(),...o.values.keys()])].sort()){let l=s.values.get(a),c=o.values.get(a),p=`$.rules[${a}]`;if(!l&&c){c.allowed===!1&&T(e,{kind:"deny-added",path:p,classification:"strengthening",message:"A denied dependency edge was added.",after:c});continue}if(l&&!c){l.allowed===!1&&T(e,{kind:"deny-removed",path:p,classification:"weakening",message:"A denied dependency edge was removed.",before:l});continue}if(!l||!c)continue;l.allowed!==c.allowed&&T(e,{kind:c.allowed?"deny-disabled":"deny-enabled",path:`${p}.allowed`,classification:c.allowed?"weakening":"strengthening",message:c.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:l.allowed,after:c.allowed});let m=l.peerIsolation===!0,g=c.peerIsolation===!0;if(m!==g){let u=l.from===l.to&&c.from===c.to;T(e,{kind:g?"peer-isolation-enabled":"peer-isolation-disabled",path:`${p}.peerIsolation`,classification:u?g?"strengthening":"weakening":"judgment-required",message:u?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:m,after:g})}oe(l.sliceFolders).join("\0")!==oe(c.sliceFolders).join("\0")&&T(e,{kind:"slice-folders-changed",path:`${p}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:oe(l.sliceFolders),after:oe(c.sliceFolders)})}}i(ka,"compareRules");function Ea(e,t,n){let r=t.safety??{},s=n.safety??{};for(let o of["maxTsSuppressions","maxAnyCasts"]){let a=r[o]??0,l=s[o]??0;a!==l&&T(e,{kind:l>a?"threshold-raised":"threshold-lowered",path:`$.safety.${o}`,classification:l>a?"weakening":"strengthening",message:l>a?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:a,after:l})}for(let o of["allowInMemory","allowDisabledPeerIsolation"])lt(e,`$.safety.${o}`,r[o]===!0,s[o]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}i(Ea,"compareSafety");function Cn(e){return e.mode==="enforced"?"enforced":"advisory"}i(Cn,"arkRunMode");function _n(e){return e.mode==="enforced"?"enforced":"advisory"}i(_n,"arkOrderMode");function Sa(e,t,n){let r=t.arkOrder,s=n.arkOrder,o="$.arkOrder";if(!r&&!s)return;if(!r&&s){T(e,{kind:"arkorder-added",path:o,classification:"strengthening",message:`ArkOrder extra was added (${_n(s)}).`,after:s});return}if(r&&!s){T(e,{kind:"arkorder-removed",path:o,classification:"weakening",message:"ArkOrder extra was removed.",before:r});return}if(!r||!s)return;let a=_n(r),l=_n(s);if(a!==l){let c=a==="advisory"&&l==="enforced";T(e,{kind:c?"arkorder-promoted":"arkorder-demoted",path:`${o}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkOrder extra was promoted to enforced.":"ArkOrder extra was demoted to advisory.",before:a,after:l})}de(e,`${o}.planeRoots`,r.planeRoots,s.planeRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkOrder plane roots are governed.",removedMessage:"ArkOrder plane roots were removed and may skip the plane."}),de(e,`${o}.managedLayers`,r.managedLayers,s.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkOrder.",removedMessage:"Layers were removed from ArkOrder management."})}i(Sa,"compareArkOrder");function Ia(e,t,n){let r=t.arkRun,s=n.arkRun,o="$.arkRun";if(!r&&!s)return;if(!r&&s){T(e,{kind:"arkrun-added",path:o,classification:"strengthening",message:`ArkRun extra was added (${Cn(s)}).`,after:s});return}if(r&&!s){T(e,{kind:"arkrun-removed",path:o,classification:"weakening",message:"ArkRun extra was removed.",before:r});return}if(!r||!s)return;let a=Cn(r),l=Cn(s);if(a!==l){let c=a==="advisory"&&l==="enforced";T(e,{kind:c?"arkrun-promoted":"arkrun-demoted",path:`${o}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkRun extra was promoted to enforced.":"ArkRun extra was demoted to advisory.",before:a,after:l})}de(e,`${o}.compositionRoots`,r.compositionRoots,s.compositionRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkRun composition roots are governed.",removedMessage:"ArkRun composition roots were removed and may skip the kernel."}),de(e,`${o}.managedLayers`,r.managedLayers,s.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkRun.",removedMessage:"Layers were removed from ArkRun management."}),lt(e,`${o}.requireDeclarations`,r.requireDeclarations!==!1,s.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}i(Ia,"compareArkRun");function va(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(va,"overallClassification");function Xr(e,t){return`${e}::${t}`}i(Xr,"ruleKey");function Qr(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(Xr(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(Xr(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}i(Qr,"indexEffectiveRules");function ba(e,t,n,r,s,o){let a=new Map((o??[]).map(u=>[u.invariantId,u])),l=t.arkRules??{},c=n.arkRules??{},p=[...new Set([...Object.keys(l),...Object.keys(c)])].sort();for(let u of p){let d=l[u],f=c[u],y=`$.arkRules[${u}]`;if(d===void 0&&f!==void 0){T(e,{kind:"arkrules-ref-added",path:y,classification:"strengthening",message:`ArkRules reference for layer ${u} was added.`,after:f});continue}if(d!==void 0&&f===void 0){T(e,{kind:"arkrules-ref-removed",path:y,classification:"weakening",message:`ArkRules reference for layer ${u} was removed.`,before:d});continue}d!==f&&T(e,{kind:"arkrules-ref-path-changed",path:y,classification:"judgment-required",message:`ArkRules file path for layer ${u} changed; verify the effective rules still match intent.`,before:d,after:f})}let m=Qr(r),g=Qr(s);for(let u of[...new Set([...m.structure.keys(),...g.structure.keys()])].sort()){let d=m.structure.get(u),f=g.structure.get(u),y=`$.arkRules.structure[${u}]`;if(!d&&f){T(e,{kind:"arkrule-structure-added",path:y,classification:"strengthening",message:`Structure ArkRule ${f.id} was added (${f.mode}).`,after:f});continue}if(d&&!f){T(e,{kind:"arkrule-structure-removed",path:y,classification:"weakening",message:`Structure ArkRule ${d.id} was removed.`,before:d});continue}if(!(!d||!f)){if(d.mode!==f.mode){let I=d.mode==="advisory"&&f.mode==="enforced";T(e,{kind:I?"arkrule-promoted":"arkrule-demoted",path:`${y}.mode`,classification:I?"strengthening":"weakening",message:I?`Structure ArkRule ${f.id} was promoted to enforced.`:`Structure ArkRule ${f.id} was demoted to advisory.`,before:d.mode,after:f.mode})}d.sensor!==f.sensor&&T(e,{kind:"arkrule-sensor-changed",path:`${y}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${f.id} changed sensor identity.`,before:d.sensor,after:f.sensor})}}for(let u of[...new Set([...m.invariants.keys(),...g.invariants.keys()])].sort()){let d=m.invariants.get(u),f=g.invariants.get(u),y=`$.arkRules.invariants[${u}]`;if(!d&&f){T(e,{kind:"arkrule-invariant-added",path:y,classification:"strengthening",message:`Invariant ${f.id} was added (${f.mode}).`,after:f});continue}if(d&&!f){T(e,{kind:"arkrule-invariant-removed",path:y,classification:"weakening",message:`Invariant ${d.id} was removed.`,before:d});continue}if(!(!d||!f)&&d.mode!==f.mode)if(d.mode==="advisory"&&f.mode==="enforced"){let N=a?.get(f.id),E=bn(N);E.ok?T(e,{kind:"arkrule-invariant-promoted",path:`${y}.mode`,classification:"strengthening",message:`Invariant ${f.id} was promoted to enforced (coverage evidence present).`,before:d.mode,after:f.mode}):T(e,{kind:"arkrule-invariant-promote-refused",path:`${y}.mode`,classification:"judgment-required",message:`Invariant ${f.id} cannot be promoted to enforced: ${E.reason}`,before:d.mode,after:f.mode})}else T(e,{kind:"arkrule-invariant-demoted",path:`${y}.mode`,classification:"weakening",message:`Invariant ${f.id} was demoted to advisory.`,before:d.mode,after:f.mode})}}i(ba,"compareArkRules");function xn(e,t,n){let r=[];de(r,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),de(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."}),de(r,"$.dynamicImportAllowlist",e.dynamicImportAllowlist,t.dynamicImportAllowlist,{added:"weakening",removed:"strengthening",addedMessage:"Additional files may use non-literal dynamic imports.",removedMessage:"Fewer files may use non-literal dynamic imports."}),lt(r,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let s={off:0,soft:1,"framework-soft":1,strict:2},o=e.cyclePolicy??"strict",a=t.cyclePolicy??"strict";if(o!==a){let l=s[a]===s[o]?"judgment-required":s[a]>s[o]?"strengthening":"weakening";T(r,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:l,message:"The cycle enforcement level changed.",before:o,after:a})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&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}),Ra(r,e.layers,t.layers),ka(r,e.rules,t.rules),Ea(r,e,t),ba(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),Ia(r,e,t),Sa(r,e,t),r.sort((l,c)=>l.path.localeCompare(c.path)||l.id.localeCompare(c.id)),{schemaVersion:On,classification:va(r),findings:r}}i(xn,"classifyArkPolicyDelta");function Tn(e,t){if(!e||e.schemaVersion!==On||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(s=>typeof s!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=oe(e.findingIds),r=oe(t.findingIds);return n.length===r.length&&n.every((s,o)=>s===r[o])}i(Tn,"policyDeltaAcknowledgementMatches");function Ne(e){let t=[];for(let n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."&&t.length>0&&t.at(-1)!==".."?t.pop():t.push(n));return t.join("/")}i(Ne,"normalizePath");function es(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}i(es,"isIdentifierStart");function Lt(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}i(Lt,"isIdentifierCharacter");function se(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}i(se,"skipWhitespace");function ct(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let r=t,s="";for(t+=1;t<e.length;t+=1){let o=e[t];if(o===n)return{value:s,offset:r,excerpt:e.slice(r,t+1)};o==="\\"&&t+1<e.length?(s+=e[t+1],t+=1):s+=o}}i(ct,"readString");function ae(e,t,n){return e.startsWith(t,n)&&!Lt(e[n-1])&&!Lt(e[n+t.length])}i(ae,"isWordAt");function ts(e,t){let n=se(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=se(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!ae(e,"type",n))return!1;let s=se(e,n+4);if(s>=e.length||e[s]===","||e[s]==="}"||ae(e,"as",s)||!es(e[s]))return!1;for(n=s;n<e.length&&Lt(e[n]);)n+=1;if(n=se(e,n),ae(e,"as",n)){if(n=se(e,n+2),!es(e[n]))return!1;for(;n<e.length&&Lt(e[n]);)n+=1}r=!0}return!1}i(ts,"bracedNamedBindingsAreTypeOnly");function Ca(e,t){if(t=se(e,t+6),e[t]==="(")return ct(e,se(e,t+1));let n=!1;if(ae(e,"type",t)){let s=se(e,t+4);e[s]!==","&&!ae(e,"from",s)&&(n=!0)}else ts(e,t)&&(n=!0);let r=ns(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}i(Ca,"specifierAfterImport");function _a(e,t){t=t+6;let n=se(e,t),r=!1;if(ae(e,"type",n)){let o=se(e,n+4);(e[o]==="{"||e[o]==="*")&&(r=!0)}else ts(e,n)&&(r=!0);let s=ns(e,t,!1);return s&&r?{...s,typeOnly:!0}:s}i(_a,"specifierAfterExport");function ns(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(ae(e,"from",t))return ct(e,se(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return ct(e,t);if(t>0&&(ae(e,"import",t)||ae(e,"export",t)))return}}i(ns,"specifierInStaticStatement");function Oa(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(Oa,"skipTemplateLiteral");function xa(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=se(e,t+7);if(e[r]!=="(")return;r=se(e,r+1);let s=ct(e,r);return s?{...s,requireCall:!0}:void 0}i(xa,"specifierAfterRequire");function Ta(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="/"&&e[n+1]==="/"){if(n=e.indexOf(`
9
- `,n+2),n<0)break;continue}if(r==="/"&&e[n+1]==="*"){let o=e.indexOf("*/",n+2);if(o<0)break;n=o+1;continue}if(r==="`"){n=Oa(e,n);continue}if(r==="'"||r==='"'){let o=ct(e,n);o&&(n=o.offset+o.excerpt.length-1);continue}let s=r==="i"&&ae(e,"import",n)?Ca(e,n):r==="e"&&ae(e,"export",n)?_a(e,n):r==="r"&&ae(e,"require",n)?xa(e,n):void 0;s&&(t.push(s),n=s.offset+s.excerpt.length-1)}return t}i(Ta,"moduleSpecifiers");function rs(e,t){let n=[],r=[];for(let s of Ta(e.content)){let o=s.value;if(!o.startsWith(".")){if(s.typeOnly)continue;let p=Ye(o);if(!p)continue;let m=e.content.slice(0,s.offset).split(`
10
- `).length;r.push({file:e.path,symbol:o,capability:p,evidence:{kind:"import",file:e.path,line:m,excerpt:s.excerpt}});continue}let a=e.content.slice(0,s.offset).split(`
11
- `).length,l={kind:"import",file:e.path,line:a,excerpt:s.excerpt},c=Na(e.path,o,t);n.push({from:e.path,specifier:o,to:c?.path??null,resolution:c?"resolved":"unresolved",fromLayer:e.layer,toLayer:c?.layer??null,evidence:l})}return{edges:n,capabilityUses:r}}i(rs,"moduleFactsFor");function Na(e,t,n){let r=e.split("/");r.pop();for(let o of t.split("/"))o==="."||o===""||(o===".."?r.pop():r.push(o));let s=r.join("/");for(let o of[s,`${s}.ts`,`${s}.tsx`,`${s}.mts`,`${s}.cts`,`${s}/index.ts`,`${s}/index.tsx`]){let a=n.get(o);if(a)return a}}i(Na,"resolveSpecifier");function ss(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let s=me(t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});s&&n.push({ruleId:`layer-dependency:${s.from}->${s.to}`,message:s.message??`${s.from} must not depend on ${s.to}.`,edge:r,evidence:r.evidence})}return n}i(ss,"violationsFor");var Pa={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 La(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}i(La,"hasActiveArkRules");function wa(e,t){return La(e,t)?z(F(In({config:e,arkRules:t,warnings:[]}))):z(F(e))}i(wa,"policyHashFor");function wt(e,t,n){let r=typeof e=="string"?yn(e,t):Ct(e,t),s=n?.arkRules??Te();return{...r,arkRules:s,policyHash:wa(r.config,s)}}i(wt,"loadContract");function os(e){let t=wt(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=wt(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=xn(t.config,n.config,{baseArkRules:t.arkRules,candidateArkRules:n.arkRules,candidateInvariantCoverage:e.candidateInvariantCoverage}),s=r.findings.filter(l=>l.classification==="weakening"||l.classification==="judgment-required").map(l=>l.id).sort(),o=s.length>0,a=o&&Tn(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:s});return{schemaVersion:r.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:r.classification,findings:r.findings,blockingFindingIds:s,requiresAcknowledgement:o,acknowledged:a,valid:!o||a}}i(os,"analyzePolicyDelta");function dt(e){let t=e.files.map(g=>{let u=Ne(g.path);return{path:u,content:g.content,contentHash:z(g.content),layer:ie(u,e.contract.config.layers)??null}}).sort((g,u)=>g.path.localeCompare(u.path)),n=new Map(t.map(g=>[g.path,g])),r=[],s=[];for(let g of t){let u=rs(g,n);r.push(...u.edges),s.push(...u.capabilityUses)}let o=ss(r,e.contract.config),a=new Map(e.contract.config.layers.map(g=>[g.name,g])),l=new Map(e.contract.config.layers.map(g=>[g.name,new Set(Le(g))]));for(let g of s){let u=n.get(g.file)?.layer;if(!u)continue;let d=a.get(u),f=Ie(g.symbol,d?.forbiddenGlobals??[]);if(f){o.push({ruleId:"FORBIDDEN_GLOBAL",message:`${u} must not use module "${g.symbol}" because it is the import form of forbidden global "${f}".`,symbol:g.symbol,evidence:g.evidence});continue}l.get(u)?.has(g.capability)&&o.push({ruleId:"CAPABILITY_VIOLATION",message:`${u} denies the ${g.capability} capability; found import of "${g.symbol}".`,capability:g.capability,symbol:g.symbol,evidence:g.evidence})}let c=t.length===0?"complete":"partial",p=c==="complete"?[]:[{...Pa}],m={schemaVersion:Rn,policyHash:e.contract.policyHash,compilerOptionsHash:z(F(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(g=>g.name),edges:r,capabilityUses:s,violations:o};return{mode:"lexical-compatibility",completeness:c,completenessReasons:p,valid:c==="complete"&&o.length===0,ir:m}}i(dt,"analyzeProject");function Dt(e){let t=new Map(e.files.map(n=>[Ne(n.path),n]));for(let n of e.changes){let r=Ne(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return dt({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}i(Dt,"analyzeChange");function as(e){let t=`${e.evidence.file}:${e.evidence.line}`;if(!e.edge)return`${e.ruleId} at ${t}: ${e.message}`;let n=e.edge.to??e.edge.specifier;return`${e.ruleId} at ${t}: ${e.edge.from} imports ${n}. ${e.message}`}i(as,"explainViolation");function Nn(e){let t=0,n=new Map,r=new Map,s=new Set,o=[],a=[],l=i(c=>{n.set(c,t),r.set(c,t),t+=1,o.push(c),s.add(c);for(let g of[...e.get(c)??[]].sort())e.has(g)&&(n.has(g)?s.has(g)&&r.set(c,Math.min(r.get(c)??0,n.get(g)??0)):(l(g),r.set(c,Math.min(r.get(c)??0,r.get(g)??0))));if(r.get(c)!==n.get(c))return;let p=[],m;do{if(m=o.pop(),m===void 0)break;s.delete(m),p.push(m)}while(m!==c);p.length>1&&a.push(p.sort())},"connect");for(let c of[...e.keys()].sort())n.has(c)||l(c);return a.sort((c,p)=>c[0]<p[0]?-1:c[0]>p[0]?1:0).map(c=>({ruleId:"CIRCULAR_DEPENDENCY",file:c[0],line:1,target:c.join(" \u2192 "),message:`Circular dependency among ${c.length} files: ${c.join(" \u2192 ")} \u2192 ${c[0]}.`,cycleKind:"value"}))}i(Nn,"detectArchitectureCycles");function Ve(e){let t=e.contentViolations.map(o=>({...o})),n=(e.warnings??[]).map(o=>({...o})),r=new Map(e.files.map(o=>[o,new Set]));for(let o of e.edges){if(o.to&&o.to!==o.from&&!o.typeOnly&&r.has(o.from)&&r.get(o.from)?.add(o.to),!o.to||!o.fromLayer||!o.toLayer)continue;let a=me(e.rules,o.fromLayer,o.toLayer,{fromPath:o.from,toPath:o.to,layers:e.config.layers});if(!a)continue;let l=!!a.peerIsolation,c=!l&&!!(o.typeOnly||o.namedBindingsTypeOnly),p=a.message??(l?`${o.fromLayer} must not ${o.kind} another slice of ${o.toLayer} (${o.from} \u2192 ${o.to}). Extract shared code or use events/ports across slices.`:`${o.fromLayer} must not ${o.kind} ${o.toLayer}.`);t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:o.from,line:o.line,fromLayer:o.fromLayer,toLayer:o.toLayer,target:o.to,...o.typeOnly?{typeOnly:!0}:{},...o.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...o.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...o.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!l&&o.portProofEligible?{portProofEligible:!0}:{},...o.kind?{edgeKind:o.kind}:{},...l?{peerIsolation:!0}:{},message:c?`${p} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:p,...c?{failsStrict:!1,severity:"warning"}:{}})}let s=String(e.config.cyclePolicy??"strict").toLowerCase();if(s!=="off"){let o=Nn(r);s==="soft"||s==="framework-soft"?n.push(...o.map(a=>({...a,message:`${a.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...o)}return{violations:t,warnings:n,safety:e.safety}}i(Ve,"evaluateArchitectureGraph");var Da=["no-anemic-model"];function is(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(is,"escapeGlobLiteral");function Ma(e){let t="";for(let r=0;r<e.length;r+=1){let s=e[r];if(s==="\\"&&r+1<e.length){let o=e[r+1];if("*?{}[],".includes(o)||o==="\\"){t+="\\"+o,r+=1;continue}t+="/";continue}t+=s}let n="";for(let r=0;r<t.length;r+=1){let s=t[r];s==="\\"&&r+1<t.length?(n+=is(t[r+1]),r+=1):s==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":s==="?"?n+="[^/]":n+=is(s)}return new RegExp(`^${n}$`)}i(Ma,"globToRegExp");function ut(e,t){return!t||t.length===0?!0:t.some(n=>Ma(n).test(e))}i(ut,"matchesAppliesTo");function Fa(e){return Da.includes(e)}i(Fa,"isTier2");function ls(e){return e.mode==="enforced"&&!Fa(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}i(ls,"severityFor");function Ue(e,t,n,r=1){let{severity:s,failsStrict:o}=ls(e);return{ruleId:"ARKRULE_STRUCTURE",code:e.sensor,message:n,file:t,line:r,fromLayer:e.provenance.layer,arkruleId:e.id,arkruleSource:e.provenance.sourceFile,severity:s,sensor:e.sensor,failsStrict:o}}i(Ue,"baseViolation");function Pn(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}i(Pn,"isInRuleLayer");function Mt(e,t,n){return t.filter(r=>!(!r.exported||!ut(r.file,e.appliesTo)||!Pn(r.file,e,n)))}i(Mt,"shapesForRule");function $a(e,t,n){let r=[];for(let s of Mt(e,t,n))(s.hasPublicSetters||s.hasPublicMutableFields)&&r.push(Ue(e,s.file,`Exported class ${s.className} exposes public mutable state (sensor aggregate-private-state).`));return r}i($a,"evaluateAggregatePrivateState");function Ha(e,t,n){let r=[];for(let s of Mt(e,t,n))if(s.hasPublicConstructor&&!s.hasStaticFactory){if(!(s.hasPublicMutableFields||s.hasPublicSetters||(s.mutatingMethods?.length??0)>0))continue;r.push(Ue(e,s.file,`Exported class ${s.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}return r}i(Ha,"evaluateAlwaysValidFactory");function ja(e,t,n){let r=[];for(let s of Mt(e,t,n))for(let o of s.mutatingMethods)o.referencesGuardOrPublish||r.push(Ue(e,s.file,`Mutating method ${s.className}.${o.name} does not reference a guard or publish symbol (sensor domain-event-on-mutation).`));return r}i(ja,"evaluateDomainEventOnMutation");function Va(e,t){let n=[];for(let r of t.files)ut(r,e.appliesTo)&&Pn(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(Ue(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}i(Va,"evaluateOrchestrationOnly");function Ua(e,t){let n=[];for(let r of t.files)ut(r,e.appliesTo)&&Pn(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(Ue(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}i(Ua,"evaluateThinAdapter");function Ka(e,t,n){let r=[];for(let s of Mt(e,t,n))if(s.dataOnly===!0){let o=Ue(e,s.file,`Exported type ${s.className} looks data-only / anemic (sensor no-anemic-model; advisory only).`);r.push({...o,severity:"warning",failsStrict:!1})}return r}i(Ka,"evaluateNoAnemicModel");function Ln(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(...$a(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...Ha(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...ja(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...Va(n,e));break;case"thin-adapter":t.push(...Ua(n,e));break;case"no-anemic-model":t.push(...Ka(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(Ln,"evaluateArkRuleSensors");function wn(e,t){let n=[],r=t.map(s=>s.replace(/\\/g,"/"));for(let s of e.structure){if(!s.appliesTo||s.appliesTo.length===0||r.some(c=>ut(c,s.appliesTo)))continue;let{severity:a,failsStrict:l}=ls(s);n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule structure "${s.id}" appliesTo matched zero governed files (patterns: ${s.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:s.provenance.sourceFile,line:1,fromLayer:s.provenance.layer,arkruleId:s.id,arkruleSource:s.provenance.sourceFile,severity:a,sensor:s.sensor,failsStrict:l})}for(let s of e.invariants??[]){if(!s.appliesTo||s.appliesTo.length===0||r.some(l=>ut(l,s.appliesTo)))continue;let a=s.mode==="enforced";n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule invariant "${s.id}" appliesTo matched zero governed files (patterns: ${s.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:s.provenance.sourceFile,line:1,fromLayer:s.provenance.layer,arkruleId:s.id,arkruleSource:s.provenance.sourceFile,severity:a?"error":"warning",sensor:"invariant-coverage",failsStrict:a})}return n.sort((s,o)=>s.file.localeCompare(o.file)||s.arkruleId.localeCompare(o.arkruleId)||s.message.localeCompare(o.message))}i(wn,"collectEmptyAppliesToFindings");var Ga=/\bfrom\s+['"](?:@?prisma\/client|@supabase\/|drizzle-orm|typeorm|knex|mongodb|pg|mysql2|better-sqlite3|ioredis|redis)['"]|require\(\s*['"](?:@?prisma\/client|pg|knex|typeorm)/,Ba=/\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*=)/,za=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,qa=/\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*=/,Ya=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function cs(e,t){if(!t||t.length<40)return null;let n=t.match(new RegExp(qa.source,"g"))??[],r=t.match(new RegExp(Ya.source,"g"))??[],s=(t.match(/\bif\s*\(/g)??[]).length,o=(t.match(/\bswitch\s*\(/g)??[]).length,a=n.length>=2||n.length>=1&&r.length>=2||r.length>=3&&s+o>=6,l=Ga.test(t),c=Ba.test(t)||za.test(t),p=n.length>=1||r.length>=2,m=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),g=l&&p||c&&p||l&&m&&(s>=4||n.length>=1)||c&&l;return!a&&!g?null:{...a?{orchestrationHeavy:!0}:{},...g?{adapterThick:!0}:{}}}i(cs,"deriveArkRuleFileHints");function Dn(e){let t={};for(let[n,r]of Object.entries(e)){let s=cs(n,r);s&&(t[n.replace(/\\/g,"/")]=s)}return t}i(Dn,"buildArkRuleFileHints");function Wa(e,t){let n=[],r=/export\s+(?:abstract\s+)?class\s+([A-Za-z_][A-Za-z0-9_]*)\s*(?:extends\s+[^{]+)?(?:implements\s+[^{]+)?\{/g,s;for(;(s=r.exec(t))!==null;){let o=s[1],a=s.index+s[0].length,l=1,c=a;for(;c<t.length&&l>0;){let w=t[c];w==="{"?l+=1:w==="}"&&(l-=1),c+=1}let p=t.slice(a,c-1),m=p.split(`
12
- `).map(w=>/^\s*\/\//.test(w)||/^\s*\/\*|\*\//.test(w)?w:w.replace(/(?:public\s+|protected\s+)?readonly\s+[a-zA-Z_][a-zA-Z0-9_]*\s*(?::[^=;]+)?(?:=\s*[^;]+)?[;,]?/g,"").replace(/(?:^|[\s;{])readonly\s+[a-zA-Z_][a-zA-Z0-9_]*\s*(?::[^=;]+)?(?:=\s*[^;]+)?[;,]?/g," ")).join(`
13
- `),g=/(?:^|\n)\s*(?:public\s+)?[a-zA-Z_][a-zA-Z0-9_]*\s*[:=]/m.test(m.replace(/(?:public\s+|private\s+|protected\s+|static\s+|async\s+|get\s+|set\s+)/g,""))&&/(?:^|\n)\s*(public\s+)?(?!constructor|static|get|set|private|protected|readonly)[a-zA-Z_][a-zA-Z0-9_]*\s*[:=]/m.test(m),u=/(?:^|\n)\s*public\s+(?!static|async|get|set|constructor|readonly)[a-zA-Z_]/.test(m)||/(?:^|[\n;])\s*[a-zA-Z_][a-zA-Z0-9_]*\s*:\s*[^=;\n]+[;=]/m.test(m.split(`
14
- `).filter(w=>!/^\s*(private|protected|static|constructor|get |set |async |\/)/.test(w)).join(`
15
- `)),d=/(?:^|[\n;{])\s*(?:public\s+)?set\s+[a-zA-Z_]/.test(p),f=/(?:^|[\n;{])\s*private\s+constructor\s*\(/.test(p),y=/(?:^|[\n;{])\s*(?:public\s+)?constructor\s*\(/.test(p)&&!f,I=/(?:^|[\n;{])\s*static\s+(?:async\s+)?(?:create|of|from|parse|build|make|new)\s*[<(]/.test(p)||/(?:^|[\n;{])\s*static\s+(?:async\s+)?[A-Za-z_][A-Za-z0-9_]*\s*\([^)]*\)\s*:\s*[A-Za-z_]/.test(p),N=[],E=new Set(["if","match","when"]),k=/(?:^|\n)\s*(?:public\s+|private\s+|protected\s+|async\s+)*(?!constructor|get|set|static)([a-zA-Z_][a-zA-Z0-9_]*)\s*\([^)]*\)\s*(?::\s*[^{]+)?\{/g,b;for(;(b=k.exec(p))!==null;){let w=b[1];if(E.has(w))continue;let O=b.index+b[0].length,D=1,P=O;for(;P<p.length&&D>0;)p[P]==="{"?D+=1:p[P]==="}"&&(D-=1),P+=1;let ee=p.slice(O,P-1);if(!/this\.\w+\s*=/.test(ee))continue;let v=/\b(ensureInvariants|assertInvariants|validate|publish|emit|raise|record)\b/.test(ee);N.push({name:w,referencesGuardOrPublish:v})}let J=(p.match(/(?:^|\n)\s*(?:public\s+|private\s+|protected\s+)?(?:async\s+)?[a-zA-Z_][a-zA-Z0-9_]*\s*\(/g)??[]).length,H=(m.match(/(?:^|[\n;])\s*(?:public\s+)?(?!constructor|static|get|set|private|protected|readonly)[a-zA-Z_][a-zA-Z0-9_]*\s*[:=]/g)??[]).length,G=J<=1&&H>=2&&(u||g);n.push({file:e,className:o,exported:!0,hasPublicMutableFields:u||g,hasPublicSetters:d,hasPublicConstructor:y,hasStaticFactory:I,mutatingMethods:[...N],dataOnly:G})}return n}i(Wa,"extractClassShapesFromSource");var Ja=50;function Mn(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(Mn,"normalizeExtraMergeTeethClassification");function ke(e){let t=Mn(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(ke,"extraMergeTeethAllowed");function Fn(e){let t=e.length,n=0,r=new Set;for(let s of e){let o=typeof s.layer=="string"&&s.layer.length>0?s.layer:null;o&&(n+=1,r.add(o))}return{governedPercent:t>0?Math.round(n/t*100):0,populatedLayerCount:r.size}}i(Fn,"classifyResolvedLayerCoverage");function $n(e){return typeof e=="string"&&e.startsWith("ARKRUN_")}i($n,"isArkRunRuleId");function Za(e){return typeof e=="string"&&e.startsWith("ARKORDER_")}i(Za,"isArkOrderRuleId");function ds(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(ds,"isExtraPlaneFinding");function Xa(e,t={}){if(!Array.isArray(e)||ke(t))return e;for(let n of e)ds(n)&&n.failsStrict!==!1&&(n.failsStrict=!1,n.severity==="error"&&(n.severity="warning"));return e}i(Xa,"demoteExtraPlaneTeethUnderClassificationFloor");var us="Structure = heuristics; invariants = catalog+coverage evidence (not business runtime); ArkRun = kernel usage + declarations (not a score); ArkOrder = pattern slaving (not a score). Extra planes never merge into one architecture score. Advisory ArkRules \u2260 merge teeth. Advisory ArkRun \u2260 merge teeth. Advisory ArkOrder \u2260 merge teeth.";function Re(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):0}i(Re,"countOrZero");function Hn(e={}){let t=Mn(e.classification),n=typeof t.governedPercent=="number"?t.governedPercent:null,r=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null,s=n!=null||r!=null,o=ke(t),a=e.arkRules,l=Re(a?.structureEnforced),c=Re(a?.structureTotal),p=typeof a?.structureAdvisory=="number"?Re(a.structureAdvisory):Math.max(0,c-l),m=Re(a?.invariantEnforced),g=Re(a?.invariantTotal),u=typeof a?.invariantAdvisory=="number"?Re(a.invariantAdvisory):Math.max(0,g-m),d=l>0||m>0,f=e.arkRun?.present===!0,y=e.arkRun?.mode==="enforced"||e.arkRun?.mode==="advisory"?e.arkRun.mode:null,I=Re(e.arkRun?.residualCount),N=f&&y==="enforced",E=N&&o,k=d||N,b=k&&o,J=k&&s&&!o,H;if(b){let w=[];d&&w.push("enforced structure/invariant findings"),N&&w.push("enforced ArkRun skip findings"),H=`Layer graph failures plus ${w.join(" and ")} (advisory extras never fail merge alone).`}else J?H=`Layer graph only \u2014 enforced ${[d?"ArkRules structure/invariant":null,N?"ArkRun":null].filter(O=>!!O).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.`:H="Layer graph only \u2014 no enforced ArkRules structure/invariant teeth on this tree. Advisory packs do not arm merge teeth."+(f?y==="advisory"?" Advisory ArkRun never merge-blocks.":" ArkRun extra is present but does not arm merge teeth.":" Absence of arkRun is silent.");let G={layers:{role:"inter-layer-edges",alwaysOnGate:!0,note:"Import/export layer graph \u2014 the default merge plane. Absent arkRules or arkRun changes nothing here."},structureSensors:{role:"intra-layer-heuristics",total:c,enforced:l,advisory:p,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:m,advisory:u,covered:Re(a?.covered),uncovered:Re(a?.uncovered),note:"Invariants are catalog + coverage evidence, not a business runtime. Enforced + proven-uncovered fails merge; absence of enforced rules adds no extra teeth."},arkRun:{role:"kernel-usage-and-declarations",present:f,mode:y,residualCount:I,extraMergeTeeth:E,note:f?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."},extraMergeTeeth:b,dualPlaneStamp:us,failMergeWhen:H};return s&&(G.classificationGate={governedPercent:n,populatedLayerCount:r,floorPercent:50,allowsTeeth:o}),G}i(Hn,"composeMergePlanesHonesty");var fs=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"],Qa=["publisher","publish","raise","raiseAsync","send","sendTo","subscribe","registerHandler","resolve","resolveSingleton"],ei=new Set(fs),ti=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"]),ni=new Set(["Array","Atomics","Buffer","JSON","Math","Number","Object","Promise","Reflect","String","console","fs","path","url","util"]);function mt(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")}i(mt,"isArkRunKernelModuleSpecifier");var ms=["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"],jn=new Set(ms);function Un(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(jn.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(jn.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:jn.has(e.slice(0,r))}i(Un,"isArkRunTransportBypassSpecifier");function Vn(e){if(ei.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(Vn,"arkRunKernelCallKind");function ft(e,t){let n=1;for(let r=0;r<t;r+=1)e.charCodeAt(r)===10&&(n+=1);return n}i(ft,"lineAt");function gt(e){return e.replace(/\/\*[\s\S]*?\*\//g,t=>t.replace(/[^\n]/g," ")).replace(/(^|[^:\\])\/\/.*$/gm,t=>t.replace(/\/\/.*$/,n=>" ".repeat(n.length)))}i(gt,"stripCommentsPreservingLines");function ri(e,t){let n=e.slice(t),r=/^\s*(['"])((?:\\.|[^\\])*?)\1/.exec(n);if(!r)return;let s=r[2]??"";return s.length>0?s:void 0}i(ri,"firstStringLiteralArg");function ps(e,t,n){let r=Math.max(0,t-n.length-8),s=e.slice(r,t);return new RegExp(`\\b${n}\\s+$`).test(s)}i(ps,"keywordBefore");function Ft(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(Ft,"parseValueImportClause");function si(e,t){Ft(gt(e),t)}i(si,"forEachArkRunValueImportClause");function Kn(e,t){let n=gt(t),r=[],s=/\b(?:import|export)(\s+type)?\s+([\s\S]*?)\s+from\s*['"]([^'"]+)['"]/g,o;for(;(o=s.exec(n))!==null;){let l=o[3]??"";if(!l)continue;let c=o[0]??"";r.push({from:e,specifier:l,kind:/^\s*export/.test(c)?"export":"import",typeOnly:!!o[1],line:ft(t,o.index),resolution:"resolved-external"})}let a=/\b(?:require|import)\s*\(\s*['"]([^'"]+)['"]\s*\)/g;for(;(o=a.exec(n))!==null;){let l=o[1]??"";if(!l)continue;let c=o[0]?.startsWith("import")?"dynamic-import":"require";r.push({from:e,specifier:l,kind:c,typeOnly:!1,line:ft(t,o.index),resolution:"resolved-external"})}return r}i(Kn,"extractArkRunValueImportDependenciesFromSource");function Gn(e){let t=[];return si(e,n=>{let r=/\{([^}]*)\}/.exec(n);if(r?.[1])for(let s of r[1].split(",")){let o=s.trim();if(!o||o.startsWith("type "))continue;let a=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(o),l=a?.[2]??/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(o)?.[1],c=a?.[1]??l;l&&c&&/^[A-Z]/.test(c)&&t.push(l,c)}}),pt(t)}i(Gn,"extractArkRunImportedConstructorNamesFromSource");function oi(e){let t=new Map,n=new Set;return Ft(e,(r,s)=>{if(!mt(s))return;let o=/\*\s+as\s+([A-Za-z_][A-Za-z0-9_]*)/.exec(r);o?.[1]&&n.add(o[1]);let a=/^([A-Za-z_][A-Za-z0-9_]*)\s*(?:,|$)/.exec(r.trim());a?.[1]&&t.set(a[1],a[1]);let l=/\{([^}]*)\}/.exec(r);if(l?.[1])for(let c of l[1].split(",")){let p=c.trim();if(!p||p.startsWith("type "))continue;let m=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(p);if(m){t.set(m[2],m[1]);continue}let g=/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(p);g?.[1]&&t.set(g[1],g[1])}}),{named:t,namespaces:n}}i(oi,"collectKernelImportBindings");function ai(e,t){let n=new Set(t);return Ft(e,(r,s)=>{let o=/\{([^}]*)\}/.exec(r);if(o?.[1])for(let a of o[1].split(",")){let l=a.trim();if(!l||l.startsWith("type "))continue;let c=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(l),p=c?.[2]??/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(l)?.[1],m=c?.[1]??p;!p||!m||!/^[A-Z]/.test(m)||(mt(s)||t.has(m)||t.has(p))&&(n.add(p),n.add(m))}}),n}i(ai,"collectImportedConstructors");function ii(e,t){let n;return Ft(e,(r,s)=>{!n&&new RegExp(`\\b${t}\\b`).test(r)&&(n=s)}),n}i(ii,"importedFromForName");function Bn(e,t){let n=gt(t),r=oi(n),s=[],o=/\b([A-Za-z_][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,a;for(;(a=o.exec(n))!==null;){let l=a[1],c=a.index;if(ps(n,c,"function")||ps(n,c,"class"))continue;let m=n.slice(0,c).match(/([A-Za-z_][A-Za-z0-9_]*)\s*\.\s*$/)?.[1],g=r.named.get(l)??l,u=Vn(g)??Vn(l);if(!u)continue;let d=r.named.has(l)||m!==void 0&&r.namespaces.has(m);if(u!=="factory"&&(!d&&m===void 0||m&&ni.has(m)&&!d))continue;let f=ri(n,c+a[0].length);s.push({file:e,line:ft(t,c),kind:u,callee:l,viaImport:d,...m?{receiver:m}:{},...f?{nameLiteral:f}:{}})}return s}i(Bn,"extractArkRunKernelCallsFromSource");function zn(e,t,n){let r=gt(t),s=ai(r,n),o=[],a=/\bnew\s+(?:[A-Za-z_][A-Za-z0-9_]*\s*\.\s*)*([A-Z][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,l;for(;(l=a.exec(r))!==null;){let c=l[1];if(ti.has(c)||!s.has(c))continue;let p=ii(r,c);o.push({file:e,line:ft(t,l.index),typeName:c,...p?{importedFrom:p}:{}})}return o}i(zn,"extractArkRunManagedNewsFromSource");function li(e,t){let n=0,r;for(let s=t;s<e.length;s+=1){let o=e[s];if(r){if(o==="\\"){s+=1;continue}o===r&&(r=void 0);continue}if(o==="'"||o==='"'||o==="`"){r=o;continue}if(o==="[")n+=1;else if(o==="]"&&(n-=1,n===0))return s}return-1}i(li,"matchingBracketEnd");function ci(e,t,n){let r=e.slice(t+1,n),s=[],o=/(['"])((?:\\.|[^\\])*?)\1/g,a;for(;(a=o.exec(r))!==null;){let l=a[2]??"";l.length>0&&s.push(l)}return s}i(ci,"stringLiteralsInList");function pt(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}i(pt,"uniqueSorted");function di(e,t){let n=gt(t),r=/\b(uses|reactsTo|raises|sends)\s*:/g,s=[],o=[],a=[],l=[],c,p;for(;(p=r.exec(n))!==null;){let m=n.slice(p.index+p[0].length),g=/^\s*\[/.exec(m);if(!g)continue;let u=p.index+p[0].length+(g[0].length-1),d=li(n,u);if(d<0)continue;let f=ci(n,u,d);if(f.length===0)continue;c===void 0&&(c=p.index);let y=p[1];y==="uses"?s.push(...f):y==="reactsTo"?o.push(...f):y==="raises"?a.push(...f):l.push(...f)}return c===void 0?[]:[{file:e,line:ft(t,c),uses:pt(s),reactsTo:pt(o),raises:pt(a),sends:pt(l)}]}i(di,"extractArkRunDeclarationsFromSource");var ui=["arkrun-missing-root","arkrun-kernel-in-domain","arkrun-direct-new","arkrun-undeclared-emit","arkrun-undeclared-handle","arkrun-undeclared-depend","arkrun-transport-bypass"],pi=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],fi=new Set(pi);function mi(e){return fi.has(e)}i(mi,"isArkRunEditorSensor");var qn={"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"},hs="ARKRUN_INTERACTION_NAME_INCOMPLETE";function As(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)||/^(?:entit(?:y|ies)|aggregates?)(?:$|(?=[A-Z_\-\s]))/i.test(n)?!0:t.some(r=>{let s=r.trim().replace(/\.+$/,"");return s==="Domain"||s.startsWith("Domain.")})}i(As,"isDomainRoleLayer");function gi(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}i(gi,"compareFindings");function Ee(e,t,n,r,s,o,a){let l=e.mode==="enforced"&&a;return{ruleId:qn[t],sensor:t,message:s,file:n,line:r,...o?.fromLayer?{fromLayer:o.fromLayer}:{},...o?.target?{target:o.target}:{},severity:l?"error":"warning",failsStrict:l,nextAction:pe({ruleId:qn[t],fromLayer:o?.fromLayer,target:o?.target})}}i(Ee,"finding");function yi(e,t){let n=[],r=[],s=[],o=[];for(let a of e)a.file===t&&(n.push(...a.uses),r.push(...a.reactsTo),s.push(...a.raises),o.push(...a.sends));return{uses:new Set(n),reactsTo:new Set(r),raises:new Set(s),sends:new Set(o)}}i(yi,"bagForFile");function gs(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}i(gs,"emitKinds");function ys(e){return e==="subscribe"||e==="register-handler"}i(ys,"handleKinds");function hi(e){return e==="resolve"||e==="resolve-singleton"}i(hi,"dependKinds");function Ai(e,t,n){let r=[],s=e.kernelRoots??e.compositionRoots;if(s.length===0)return r.push(Ee(e,"arkrun-missing-root","ark.config.json",1,"ArkRun kernelRoots is empty; no createArkKernel factory site is declared.",void 0,n)),r;let o=new Map;for(let a of t){let l=o.get(a.matchedRoot)??[];l.push(a),o.set(a.matchedRoot,l)}for(let a of s){let l=[...o.get(a)??[]].sort((p,m)=>p.file.localeCompare(m.file));if(l.length===0){r.push(Ee(e,"arkrun-missing-root","ark.config.json",1,`ArkRun kernel root ${JSON.stringify(a)} matched no governed files and has no createArkKernel factory.`,{target:a},n));continue}if(l.some(p=>p.hasKernelFactory))continue;let c=l[0];r.push(Ee(e,"arkrun-missing-root",c.file,1,`ArkRun kernel root ${JSON.stringify(a)} has no createArkKernel / createStrictArkKernel factory.`,{target:a},n))}return r}i(Ai,"evaluateMissingRoot");function Ri(e,t,n,r,s){let o=new Map(t.map(l=>[l.name,l.intentPrefixes??[]])),a=[];for(let l of n){let c=l.specifier;if(!c||!mt(c))continue;let p=r(l.from);p&&As(p,o.get(p)??[])&&a.push(Ee(e,"arkrun-kernel-in-domain",l.from,l.line,`${p} must not import kernel module ${JSON.stringify(c)}.`,{fromLayer:p,target:c},s))}return a}i(Ri,"evaluateKernelInDomain");function ki(e,t,n,r,s,o){let a=new Set(e.managedLayers);if(a.size===0)return[];let l=new Map(t.map(m=>[m.name,m.intentPrefixes??[]])),c=new Set(r.filter(m=>m.hasKernelFactory).map(m=>m.file)),p=[];for(let m of n){if(c.has(m.file))continue;let g=m.typeName;if(e.ignoreDirectNewForErrors!==!1&&(g.endsWith("Error")||g==="Error")||g.endsWith("DTO")||g.endsWith("VO"))continue;let u=s(m.file);!u||!a.has(u)||As(u,l.get(u)??[])||p.push(Ee(e,"arkrun-direct-new",m.file,m.line,`${u} must not construct ${m.typeName} with new outside an ArkRun composition-root factory.`,{fromLayer:u,target:m.typeName},o))}return p}i(ki,"evaluateDirectNew");function Ei(e,t,n,r,s){let o=[],a=[];if(e.requireDeclarations!==!0)return{findings:o,completenessReasons:a};let l=new Set(e.managedLayers);if(l.size===0)return{findings:o,completenessReasons:a};for(let c of t){if(!gs(c.kind)&&!ys(c.kind)&&!hi(c.kind))continue;let p=r(c.file);if(!p||!l.has(p))continue;if(!c.nameLiteral){e.mode==="enforced"&&a.push({code:hs,file:c.file,message:`ArkRun ${c.kind} call in ${c.file} has no string-literal name; enforced extra cannot prove the declaration.`});continue}let m=yi(n,c.file);if(gs(c.kind)){if(m.raises.has(c.nameLiteral)||m.sends.has(c.nameLiteral))continue;o.push(Ee(e,"arkrun-undeclared-emit",c.file,c.line,`Emit ${JSON.stringify(c.nameLiteral)} is not declared in raises or sends.`,{fromLayer:p,target:c.nameLiteral},s));continue}if(ys(c.kind)){if(m.reactsTo.has(c.nameLiteral))continue;o.push(Ee(e,"arkrun-undeclared-handle",c.file,c.line,`Handle ${JSON.stringify(c.nameLiteral)} is not declared in reactsTo.`,{fromLayer:p,target:c.nameLiteral},s));continue}m.uses.has(c.nameLiteral)||o.push(Ee(e,"arkrun-undeclared-depend",c.file,c.line,`Depend ${JSON.stringify(c.nameLiteral)} is not declared in uses.`,{fromLayer:p,target:c.nameLiteral},s))}return{findings:o,completenessReasons:a}}i(Ei,"evaluateUndeclared");function Si(e,t,n,r){let s=new Set(e.managedLayers);if(s.size===0)return[];let o=[];for(let a of t){if(a.typeOnly)continue;let l=a.specifier;if(!l||!Un(l))continue;let c=n(a.from);!c||!s.has(c)||o.push(Ee(e,"arkrun-transport-bypass",a.from,a.line,`${c} must not import broker/queue/emitter ${JSON.stringify(l)}; use the ArkRun kernel transport.`,{fromLayer:c,target:l},r))}return o}i(Si,"evaluateTransportBypass");function $t(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=ke(e.classification),r=Ei(t,e.kernelCalls,e.declarations,e.layerForFile,n),s=[...Ai(t,e.compositionRootHits,n),...Ri(t,e.layers,e.dependencies,e.layerForFile,n),...ki(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...Si(t,e.dependencies,e.layerForFile,n)].sort(gi),o=[...r.completenessReasons].sort((a,l)=>{let c=`${a.code}\0${a.file??""}\0${a.message}`,p=`${l.code}\0${l.file??""}\0${l.message}`;return c<p?-1:c>p?1:0});return{findings:s,completenessReasons:o}}i($t,"evaluateArkRunSensors");function Rs(e){return{findings:$t(e).findings.filter(n=>mi(n.sensor)),completenessReasons:[]}}i(Rs,"evaluateArkRunEditorSensors");function Ii(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(Ii,"fileMatchesCompositionRoot");function vi(e,t,n){let r=Bn(t,n).some(a=>a.kind==="factory"),s=[],o=e.kernelRoots??e.compositionRoots;for(let a of o)Ii(a,t)&&s.push({file:t,matchedRoot:a,hasKernelFactory:r});return s}i(vi,"compositionRootHitsForSource");function bi(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=new Set(Gn(e.source));return Rs({arkRun:t,layers:e.layers,kernelCalls:[],managedNews:zn(e.file,e.source,n),compositionRootHits:vi(t,e.file,e.source),declarations:[],dependencies:Kn(e.file,e.source),layerForFile:e.layerForFile,classification:e.classification})}i(bi,"evaluateArkRunEditorSensorsFromSource");function ks(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}i(ks,"isArkOrderModuleSpecifier");var Ci=["arkorder-missing-plane","arkorder-kernel-in-domain","arkorder-generic-update","arkorder-too-many-params","arkorder-ingest-writes-xi"],Yn={"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"};function _i(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)?!0:t.some(r=>{let s=r.trim().replace(/\.+$/,"");return s==="Domain"||s.startsWith("Domain.")})}i(_i,"isDomainRoleLayer");function yt(e,t,n,r,s,o,a){let l=e.mode==="enforced"&&a;return{ruleId:Yn[t],sensor:t,message:s,file:n,line:r,...o?.fromLayer?{fromLayer:o.fromLayer}:{},...o?.target?{target:o.target}:{},severity:l?"error":"warning",failsStrict:l,nextAction:pe({ruleId:Yn[t],fromLayer:o?.fromLayer,target:o?.target})}}i(yt,"finding");function Wn(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let n=ke(e.classification),r=[],s=t.planeRoots;if(t.mode==="enforced"&&s.length===0)r.push(yt(t,"arkorder-missing-plane","ark.config.json",1,"ArkOrder planeRoots is empty; no createOrderPlane site is declared.",void 0,n));else{let a=new Map;for(let l of e.planeRootHits){let c=a.get(l.matchedRoot)??[];c.push(l),a.set(l.matchedRoot,c)}for(let l of s){let c=a.get(l)??[];if(c.length===0){r.push(yt(t,"arkorder-missing-plane","ark.config.json",1,`ArkOrder plane root ${JSON.stringify(l)} matched no governed files and has no createOrderPlane factory.`,{target:l},n));continue}c.some(p=>p.hasPlaneFactory)||r.push(yt(t,"arkorder-missing-plane",c[0].file,1,`ArkOrder plane root ${JSON.stringify(l)} has no createOrderPlane factory.`,{target:l},n))}}let o=new Map(e.layers.map(a=>[a.name,a.intentPrefixes??[]]));for(let a of e.dependencies){let l=a.specifier;if(!l||!ks(l))continue;let c=e.layerForFile(a.from);c&&_i(c,o.get(c)??[])&&r.push(yt(t,"arkorder-kernel-in-domain",a.from,a.line,"Domain-role layer imports arkgate/order; Domain stays plane-free.",{fromLayer:c,target:l},n))}for(let a of e.genericUpdates)r.push(yt(t,"arkorder-generic-update",a.file,a.line,`Generic ${a.method}() on the order plane rewrites \u03BE; Haken forbids it.`,{target:a.method},n));return r.sort((a,l)=>a.file.localeCompare(l.file)||a.ruleId.localeCompare(l.ruleId)||a.line-l.line),{findings:r,completenessReasons:[]}}i(Wn,"evaluateArkOrderSensors");function te(e,t,n={}){return{ruleId:e,message:t,...n}}i(te,"configWarning");function Ht(e){let{config:t,rules:n,files:r,manifest:s}=e,o=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(d=>typeof d!="string"))&&o.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)))o.push(te("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let d of["maxTsSuppressions","maxAnyCasts"]){let f=t.safety[d];f!==void 0&&(!Number.isInteger(f)||f<0)&&o.push(te("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${d} must be a non-negative integer.`))}let a=Array.isArray(t.layers)?t.layers:[],l=Array.isArray(s?.architecture?.layers)?s.architecture.layers:[],c=new Set([...a.map(d=>d.name).filter(Boolean),...l.map(d=>d.name).filter(d=>!!d)]);a.length===0&&o.push(te("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let p=new Set,m=new Set;for(let d of a){if(!d.name){o.push(te("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}p.has(d.name)&&m.add(d.name),p.add(d.name),d.forbiddenGlobals!==void 0&&(!Array.isArray(d.forbiddenGlobals)||d.forbiddenGlobals.some(y=>typeof y!="string"))&&o.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 f=Array.isArray(d.patterns)?d.patterns:[];if(f.length===0){o.push(te("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${d.name}" has no file patterns and will never classify files.`,{layer:d.name}));continue}for(let y of f){let I;try{I=Ce(y)}catch(E){o.push(te("CONFIG_INVALID_LAYER_PATTERN",`Layer "${d.name}" has an invalid pattern "${y}": ${E instanceof Error?E.message:String(E)}`,{layer:d.name,pattern:y}));continue}let N=d.optional===!0||d.reserved===!0||d.allowEmpty===!0;!r.some(E=>I.test(E))&&!N&&o.push(te("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${d.name}" pattern "${y}" matched no included files (possible typo). Mark the layer reserved/allowEmpty if this house is reserved for later.`,{layer:d.name,pattern:y,failsStrict:!1,reserved:!1}))}}for(let d of m)o.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)&&o.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)&&o.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 f=-1,y=[];for(let I of a)for(let N of I.patterns??[]){if(!Ce(N).test(d))continue;let E=an(N,d);E>f?(f=E,y=[I.name]):E===f&&!y.includes(I.name)&&y.push(I.name)}y.length>1&&g.add([...y].sort().join(" + "))}g.size>0&&o.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 u=r.filter(d=>!ie(d,a));return u.length>0&&o.push(te("CONFIG_UNCLASSIFIED_FILES",`${u.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:u.length,samples:u.slice(0,5)})),o}i(Ht,"collectAnalysisConfigWarnings");function Oi(e,t){return t.some(n=>{try{return Ce(n).test(e)}catch{return!1}})}i(Oi,"matchesAny");function xi(e,t){let n=e.contract.config.safety??{},r=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,s=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,o=e.contract.config.dynamicImportAllowlist??[],a=t.safetyUses.filter(y=>y.kind==="ts-suppression").map(({file:y,line:I})=>({file:y,line:I})),l=t.safetyUses.filter(y=>y.kind==="any-cast").map(({file:y,line:I})=>({file:y,line:I})),c=t.safetyUses.filter(y=>(y.kind==="dynamic-import"||y.kind==="dynamic-require")&&!Oi(y.file,o)).map(y=>({file:y.file,line:y.line,kind:y.kind==="dynamic-require"?"require":"import"})),p=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"})),m=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:l,nonLiteralDynamicImports:c,inMemoryProductionStores:p,disabledPeerIsolationRules:m,thresholds:{maxTsSuppressions:r,maxAnyCasts:s}},u=[],d=c.filter(y=>y.kind==="import");if(d.length>0){let y=d[0];u.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:y.file,line:y.line,message:`${d.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let f=c.filter(y=>y.kind==="require");if(f.length>0){let y=f[0];u.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:y.file,line:y.line,message:`${f.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(a.length>r){let y=a[0];u.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(l.length>s){let y=l[0];u.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:y.file,line:y.line,message:`${l.length} explicit any cast(s) exceed safety.maxAnyCasts (${s}).`})}if(p.length>0){let y=p[0];u.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:y.file,line:y.line,message:`${p.length} ArkGate InMemory store risk(s) appear in governed production source. Provide durable stores or set safety.allowInMemory only for an explicitly ephemeral service.`})}return m.length>0&&u.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${m.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:g,warnings:u}}i(xi,"evaluateSafety");function Ti(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}i(Ti,"ambientForbiddenGlobal");function Es(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return fn(e,n.length>0?n:pn.map(r=>({name:r.layer,prefixes:r.prefixes})))}i(Es,"intentLayer");function Ni(e,t,n){let r=[],s=new Map(e.contract.config.layers.map(o=>[o.name,o]));for(let o of t.ambientUses){let a=n.get(o.file);!a||!Ti(o.symbol,s.get(a)?.forbiddenGlobals??[])||r.push({ruleId:"FORBIDDEN_GLOBAL",file:o.file,line:o.line,fromLayer:a,target:o.symbol,message:`${a} must not use the ambient global "${o.symbol}".`})}for(let o of t.capabilityUses){let a=n.get(o.file);if(!a)continue;let l=s.get(a),c=l?.forbiddenGlobals??[],p=o.source==="import-based"?t.dependencies.find(m=>m.from===o.file&&m.line===o.line&&m.specifier===o.symbol&&!m.typeOnly)?.kind:void 0;if(!(o.source==="ambient-global"&&We(o.symbol,c))){if(o.source==="import-based"){let m=Ie(o.symbol,c);if(m){r.push({ruleId:"FORBIDDEN_GLOBAL",file:o.file,line:o.line,fromLayer:a,target:o.symbol,...p?{edgeKind:p}:{},message:`${a} must not use module "${o.symbol}" because it is the import form of forbidden global "${m}".`});continue}}Le(l).includes(o.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:o.file,line:o.line,fromLayer:a,target:o.symbol,capability:o.capability,...p?{edgeKind:p}:{},message:o.source==="import-based"?`${a} denies the ${o.capability} capability; found import of "${o.symbol}".`:`${a} denies the ${o.capability} capability; found ambient "${o.symbol}".`})}}for(let o of t.publishCalls){let a=n.get(o.file);if(!a)continue;for(let c of Je({publishCall:!0,rawIntentName:o.rawIntentName,objectHasIntent:o.objectHasIntent,arkPublishCandidate:o.arkPublishCandidate,hasSource:o.hasSource}))r.push({ruleId:c.ruleId,file:o.file,line:o.line,...c.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:a}:{},message:c.message});if(!o.sourceIntent)continue;let l=Es(o.sourceIntent,e.contract);!l||l===a||r.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:o.file,line:o.line,fromLayer:a,toLayer:l,target:o.sourceIntent,message:`Publish source "${o.sourceIntent}" resolves to ${l}, but the publishing file is classified as ${a}.`})}for(let o of t.intentReferences){let a=n.get(o.file);if(!a)continue;let l=Es(o.intent,e.contract);if(!l)continue;let c=me(e.contract.config.rules,a,l);c&&r.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:o.file,line:o.line,fromLayer:a,toLayer:l,target:o.intent,message:c.message??`${a} must not reference ${l} intent ${o.intent}.`})}return r}i(Ni,"contentViolations");function Pi(e){let{facts:t}=e,n=rt(e.contract.config),r=t.evidenceRequirementsHash===n,s=r?t.completeness:"unavailable",o=r?t.completenessReasons:[...t.completenessReasons,{code:"EVIDENCE_REQUIREMENTS_MISMATCH",message:"Resolved facts were collected for different policy-controlled evidence requirements."}].sort((h,ue)=>{let ze=`${h.code}\0${h.file??""}\0${h.message}`,qe=`${ue.code}\0${ue.file??""}\0${ue.message}`;return ze<qe?-1:ze>qe?1:0}),a=t.files.map(h=>({...h,layer:ie(h.path,e.contract.config.layers)??null})),l=new Map(a.map(h=>[h.path,h.layer])),c=t.dependencies.map(h=>{let ue=h.target?l.get(h.target)??ie(h.target,e.contract.config.layers):void 0;return{from:h.from,fromLayer:l.get(h.from)??null,...h.resolution==="resolved-project"&&h.target?{to:h.target,...ue?{toLayer:ue}:{}}:{},line:h.line,kind:h.kind,typeOnly:h.typeOnly,...h.targetTypeOnlyExports?{targetTypeOnlyExports:h.targetTypeOnlyExports}:{},...h.sourcePureTypeModule?{sourcePureTypeModule:h.sourcePureTypeModule}:{},...h.namedBindingsTypeOnly?{namedBindingsTypeOnly:h.namedBindingsTypeOnly}:{},...h.portProofEligible?{portProofEligible:h.portProofEligible}:{}}}),p=Ht({config:e.contract.config,rules:e.contract.config.rules,files:a.map(h=>h.path)}),m=xi(e,t),g=e.contract.arkRules??Te(),u=a.map(h=>h.path),f={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?Dn(e.coverageInputs.fileContents):{},...e.fileHints??{}},y=[...Ln({arkRules:g,classShapes:e.contract.classShapes??t.classShapes??[],files:u,layerForFile:i(h=>l.get(h)??ie(h,e.contract.config.layers),"layerForFile"),fileHints:f}),...wn(g,u)],I=y.filter(h=>h.failsStrict).map(h=>({ruleId:h.ruleId,file:h.file,line:h.line,message:h.message,fromLayer:h.fromLayer,arkruleId:h.arkruleId,arkruleSource:h.arkruleSource,nextAction:h.ruleId==="ARKRULE_SCOPE_EMPTY"?`Fix appliesTo globs for ${h.arkruleId} in ${h.arkruleSource} so they match governed files, or remove the rule.`:`Fix the structure or invariant for ${h.arkruleId} (declared in ${h.arkruleSource}), then preflight again.`})),N=y.filter(h=>!h.failsStrict).map(h=>({ruleId:h.ruleId,file:h.file,line:h.line,message:h.message,fromLayer:h.fromLayer,arkruleId:h.arkruleId,arkruleSource:h.arkruleSource,failsStrict:!1,nextAction:h.ruleId==="ARKRULE_SCOPE_EMPTY"?`Review appliesTo for ${h.arkruleId} in ${h.arkruleSource} (zero-match scope; advisory).`:`Review ArkRule ${h.arkruleId} in ${h.arkruleSource} (advisory).`})),k=(g.invariants?.length??0)>0?vn({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}):{coverage:[],violations:[],partial:!1},b=k.violations.filter(h=>h.failsStrict).map(h=>({ruleId:h.ruleId,file:h.file,line:h.line,message:h.message,fromLayer:h.fromLayer,arkruleId:h.arkruleId,arkruleSource:h.arkruleSource,nextAction:`Add a test title or declared symbol covering ${h.arkruleId} (declared in ${h.arkruleSource}), then preflight again.`})),J=k.violations.filter(h=>!h.failsStrict).map(h=>({ruleId:h.ruleId,file:h.file,line:h.line,message:h.message,fromLayer:h.fromLayer,arkruleId:h.arkruleId,arkruleSource:h.arkruleSource,failsStrict:!1,nextAction:`Cover invariant ${h.arkruleId} in ${h.arkruleSource} (advisory / partial).`})),H=Fn(a),G=$t({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(h=>l.get(h)??ie(h,e.contract.config.layers),"layerForFile"),classification:H}),w=e.contract.config.arkRun?.mode,O=G.findings.filter(()=>w==="enforced").map(h=>({ruleId:h.ruleId,file:h.file,line:h.line,message:h.message,fromLayer:h.fromLayer,target:h.target,nextAction:h.nextAction,sensor:h.sensor,failsStrict:h.failsStrict,...h.severity?{severity:h.severity}:{}})),D=G.findings.filter(()=>w!=="enforced").map(h=>({ruleId:h.ruleId,file:h.file,line:h.line,message:h.message,fromLayer:h.fromLayer,target:h.target,nextAction:h.nextAction,sensor:h.sensor,failsStrict:!1})),P=Wn({arkOrder:e.contract.config.arkOrder,layers:e.contract.config.layers,planeCalls:t.arkOrderPlaneCalls,genericUpdates:t.arkOrderGenericUpdates,planeRootHits:t.arkOrderRootHits,dependencies:t.dependencies,layerForFile:i(h=>l.get(h)??ie(h,e.contract.config.layers),"layerForFile"),classification:H}),ee=e.contract.config.arkOrder?.mode,fe=P.findings.filter(()=>ee==="enforced").map(h=>({ruleId:h.ruleId,file:h.file,line:h.line,message:h.message,fromLayer:h.fromLayer,target:h.target,nextAction:h.nextAction,sensor:h.sensor,failsStrict:h.failsStrict,...h.severity?{severity:h.severity}:{}})),v=P.findings.filter(()=>ee!=="enforced").map(h=>({ruleId:h.ruleId,file:h.file,line:h.line,message:h.message,fromLayer:h.fromLayer,target:h.target,nextAction:h.nextAction,sensor:h.sensor,failsStrict:!1})),A=[...k.partial&&k.coverage.some(h=>h.mode==="enforced"&&h.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."}]:[],...G.completenessReasons,...P.completenessReasons],R=Ve({config:e.contract.config,rules:e.contract.config.rules,files:a.filter(h=>h.layer).map(h=>h.path),contentViolations:[...Ni(e,t,l),...I,...b,...O,...fe],edges:c,warnings:[...p,...m.warnings,...N,...J,...D,...v],safety:m.report}),L=s==="complete"&&A.length>0?"partial":s,B=L==="complete"?o:[...o,...A].sort((h,ue)=>{let ze=`${h.code}\0${h.file??""}\0${h.message}`,qe=`${ue.code}\0${ue.file??""}\0${ue.message}`;return ze<qe?-1:ze>qe?1:0}),Se=R.violations.filter(h=>h.failsStrict!==!1),be=L==="complete"&&Se.length===0,Be=be&&R.warnings.every(h=>h.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:L,completenessReasons:B,valid:be,strictValid:Be,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:m.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:a,layers:e.contract.config.layers.map(h=>h.name),edges:c,capabilityUses:t.capabilityUses,violations:R.violations,warnings:R.warnings}}}i(Pi,"analyzeCanonicalResolvedProject");function ht(e){return Pi({contract:e.contract,facts:ve(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints})}i(ht,"analyzeResolvedProject");function Ss(e){return z(F(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}i(Ss,"analysisTreeHash");function Is(e){let t=dt(e),n=new Map(t.ir.files.map(f=>[f.path,f])),r=[],s=new Set,o=[];for(let f of e.changes){let y=f.path.replace(/\\/g,"/"),I=Ne(f.path);if(!I||I===".."||I.startsWith("../")||y.startsWith("/")||/^[A-Za-z]:\//.test(y)||y.includes("\0")){o.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(s.has(I)){o.push({ruleId:"DUPLICATE_CHANGE_PATH",file:I,line:1,message:`The atomic change set contains more than one operation for ${I}.`});continue}s.add(I),"delete"in f&&f.delete&&!n.has(I)&&o.push({ruleId:"DELETE_TARGET_MISSING",file:I,line:1,message:`Cannot delete ${I} because it is not present in the supplied base tree.`}),r.push("delete"in f&&f.delete?{path:I,delete:!0}:{path:I,content:"content"in f?f.content:""})}e.changes.length===0&&o.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let a=Dt({...e,changes:r}),l=new Map(a.ir.files.map(f=>[f.path,f])),c=a.ir.violations.filter(f=>f.ruleId==="CAPABILITY_VIOLATION"||f.ruleId==="FORBIDDEN_GLOBAL").map(f=>{let y=l.get(f.evidence.file)?.layer;return{ruleId:f.ruleId,file:f.evidence.file,line:f.evidence.line,target:f.symbol,...f.capability?{capability:f.capability}:{},...y?{fromLayer:y}:{},edgeKind:"import",message:f.message}}),p=Ve({config:e.contract.config,rules:e.contract.config.rules,files:a.ir.files.map(f=>f.path),contentViolations:c,edges:a.ir.edges.filter(f=>!!f.fromLayer).map(f=>({from:f.from,fromLayer:f.fromLayer,...f.to?{to:f.to}:{},...f.toLayer?{toLayer:f.toLayer}:{},line:f.evidence.line,kind:"import",...f.typeOnly?{typeOnly:!0}:{},...f.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),m=r.map(f=>{let y=Ne(f.path),I=n.get(y),N=l.get(y);return{path:y,operation:"delete"in f&&f.delete?"delete":I?"update":"create",...I?{beforeContentHash:I.contentHash}:{},...N?{candidateContentHash:N.contentHash}:{}}}).sort((f,y)=>f.path.localeCompare(y.path)),g=[...o,...p.violations].map(f=>({...f,nextAction:pe(f)})),u=g.filter(f=>f.failsStrict!==!1),d=e.changeMap?je({changeMap:e.changeMap,changes:m,baseDependencies:t.ir.edges.flatMap(f=>f.to?[{from:f.from,to:f.to}]:[]),candidateDependencies:a.ir.edges.flatMap(f=>f.to?[{from:f.from,to:f.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&a.valid&&u.length===0&&(d?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:a.ir.compilerOptionsHash,baseTreeHash:Ss(t.ir.files),candidateTreeHash:Ss(a.ir.files),baseCompleteness:t.completeness,candidateCompleteness:a.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:a.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...d?{convergence:d}:{},changes:m,violations:g,warnings:p.warnings}}i(Is,"preflightChange");function Li(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let s of t.split("/"))if(!(!s||s==="."))if(s===".."){if(n.length===0)return;n.pop()}else n.push(s);let r=n.join("/");return r&&r===t?r:void 0}i(Li,"canonicalChangePath");function wi(e,t){return[["resolverIdentity",e.resolverIdentity,t.resolverIdentity],["compilerIdentity",e.compilerIdentity,t.compilerIdentity],["evidenceRequirementsHash",e.evidenceRequirementsHash,t.evidenceRequirementsHash],["projectPackageName",e.projectPackageName??"",t.projectPackageName??""]].filter(([,r,s])=>r!==s).map(([r,s,o])=>({ruleId:"FACTS_IDENTITY_MISMATCH",file:"<change-set>",line:1,field:r,before:s,candidate:o,message:`Base and candidate facts must use the same ${r}.`}))}i(wi,"identityViolations");function Di(e,t,n,r){let s=n.get(t),o=r.get(t);return{path:t,operation:"delete"in e&&e.delete?"delete":s?"update":"create",...s?{beforeContentHash:s.contentHash}:{},...o?{candidateContentHash:o.contentHash}:{}}}i(Di,"preparedChange");function vs(e){let t=ve(e.baseFacts),n=ve(e.candidateFacts),r=ht({contract:e.contract,facts:t}),s=ht({contract:e.contract,facts:n}),o=new Map(t.files.map(d=>[d.path,d])),a=new Map(n.files.map(d=>[d.path,d])),l=wi(t,n),c=new Map,p=[];for(let d of e.changes){let f=Li(d.path);if(!f){l.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(c.has(f)){l.push({ruleId:"DUPLICATE_CHANGE_PATH",file:f,line:1,message:`The atomic change set contains more than one operation for ${f}.`});continue}c.set(f,d);let y=o.get(f),I=a.get(f);if("delete"in d&&d.delete)y||l.push({ruleId:"DELETE_TARGET_MISSING",file:f,line:1,message:`Cannot delete ${f} because it is not present in the supplied base facts.`}),I&&l.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:f,line:1,message:`Candidate facts still contain deleted file ${f}.`});else{let N="content"in d?d.content:"",E=z(N);I?I.contentHash!==E&&l.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:f,line:1,expectedContentHash:E,candidateContentHash:I.contentHash,message:`Candidate facts for ${f} do not match the declared content.`}):l.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:f,line:1,message:`Candidate facts do not contain changed file ${f}.`})}p.push(Di(d,f,o,a))}e.changes.length===0&&l.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});for(let d of new Set([...o.keys(),...a.keys()])){if(c.has(d))continue;let f=o.get(d),y=a.get(d);f&&y&&F(f)===F(y)||l.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:d,line:1,message:`Candidate facts change ${d}, but the atomic change set does not declare it.`})}let m=e.changeMap?je({changeMap:e.changeMap,changes:p,baseDependencies:r.ir.edges.flatMap(d=>d.to?[{from:d.from,to:d.to}]:[]),candidateDependencies:s.ir.edges.flatMap(d=>d.to?[{from:d.from,to:d.to}]:[])}):void 0,g=[...l,...s.ir.violations].map(d=>({...d,nextAction:pe(d)})),u=g.filter(d=>d.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&s.strictValid&&u.length===0&&(m?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,resolverIdentity:n.resolverIdentity,compilerIdentity:n.compilerIdentity,compilerOptionsHash:n.compilerOptionsHash,tsconfigHash:n.tsconfigHash,baseCompilerOptionsHash:t.compilerOptionsHash,candidateCompilerOptionsHash:n.compilerOptionsHash,baseTsconfigHash:t.tsconfigHash,candidateTsconfigHash:n.tsconfigHash,evidenceRequirementsHash:n.evidenceRequirementsHash,baseFactsHash:t.factsHash,candidateFactsHash:n.factsHash,baseTreeHash:t.candidateTreeHash,candidateTreeHash:n.candidateTreeHash,baseCompleteness:r.completeness,candidateCompleteness:s.completeness,baseCompletenessReasons:r.completenessReasons,candidateCompletenessReasons:s.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...m?{convergence:m}:{},changes:p.sort((d,f)=>d.path<f.path?-1:d.path>f.path?1:0),violations:g,warnings:s.ir.warnings}}i(vs,"preflightResolvedChange");var bs="1.0",Mi=12;function Cs(e){return e==="enforced"||e==="advisory"?e:null}i(Cs,"closedMode");function Fi(e){let t=new Set;if(!Array.isArray(e))return[];for(let n of e){let r=n?.ruleId;typeof r!="string"||!$n(r)||t.has(r)||t.add(r)}return[...t].sort((n,r)=>n<r?-1:n>r?1:0)}i(Fi,"uniqueArkRunRuleIds");function $i(e){return!e||typeof e!="object"?{present:!1,mode:null,roots:0,layers:0,requireDeclarations:null}:{present:!0,mode:Cs(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($i,"extraFromConfig");function Hi(e={}){let t=$i(e.arkRun),n=t.present?Fi(e.findings):[],r=n.slice(0,Mi),s=n.length,o=Hn({classification:e.classification,arkRules:{active:e.arkRules?.active===!0,structureEnforced:e.arkRules?.structureEnforced,structureTotal:e.arkRules?.structureTotal,structureAdvisory:e.arkRules?.structureAdvisory,invariantEnforced:e.arkRules?.invariantEnforced,invariantTotal:e.arkRules?.invariantTotal,invariantAdvisory:e.arkRules?.invariantAdvisory,covered:e.arkRules?.covered,uncovered:e.arkRules?.uncovered},arkRun:{present:t.present,mode:t.mode,residualCount:s}}),a=t.present&&t.mode==="enforced"&&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.":a?l="Enforced ArkRun is on the extra merge plane. Residual is a finding-id count, never a score.":l="Enforced ArkRun extra teeth stay demoted until the layer plane is honestly classified. Residual is a finding-id count, never a score.":l="Absence of arkRun is silent \u2014 Layers and ArkRules verdicts unchanged. Not a score.",{schemaVersion:bs,notAScore:!0,active:t.present,mode:t.mode,compositionRoots:t.roots,managedLayers:t.layers,requireDeclarations:t.requireDeclarations,residual:{count:s,ruleIds:r},extraMergeTeeth:a,failMergeWhen:o.failMergeWhen,note:l,mergePlanes:o}}i(Hi,"summarizeArkRunSection");function Jn(e={}){let t=e.present===!0,n=Cs(e.mode),r=e.residual,s=null;return typeof r=="number"&&Number.isFinite(r)&&r>=0&&(s=Math.floor(r)),t||(s=s??0),{notAScore:!0,present:t,mode:t?n:null,extraMergeTeeth:t&&n==="enforced"&&e.extraMergeTeeth===!0,residual:s}}i(Jn,"projectStatusArkRun");function ji(e){if(!e||e.notAScore!==!0)return[];if(e.active!==!0)return["ArkRun extra is off \u2014 silent on Layers/ArkRules (not a score)."];let t=e.mode??"unknown",n=e.extraMergeTeeth===!0?"armed":"not armed",r=[`mode: ${t} \xB7 extra merge teeth ${n} \xB7 not a score`];if(e.residual.count>0){let s=e.residual.ruleIds.join(", "),o=e.residual.count>e.residual.ruleIds.length?` (+${e.residual.count-e.residual.ruleIds.length} more)`:"";r.push(`Residual: ${s}${o}`)}else r.push("Residual: none on this scan (not a score \u2014 green extras \u2260 finished kernel wiring).");return e.failMergeWhen&&r.push(e.failMergeWhen),r}i(ji,"formatArkRunDoctorLines");function jt(e,t){return e.slice(0,t).split(`
16
- `).length}i(jt,"lineOf");function _s(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}i(_s,"normalizeInventoryPath");function xs(e,t){return e.some(n=>{let r=n.trim().replace(/\.+$/,"");return t.some(s=>r===s||r.startsWith(`${s}.`))})}i(xs,"ownsIntent");function Os(e,t=[]){return/domain|entity|aggregate|model/i.test(e)||xs(t,["Domain"])}i(Os,"isDomainLayer");function Vi(e,t=[]){return/application|orchestration|presentation|adapter|framework|interface|delivery|transport|inbound|controller/i.test(e)||xs(t,["Application","Orchestration","Presentation","Adapter","Interface","Delivery","Transport"])}i(Vi,"isControllerEligibleLayer");function Ui(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(Ui,"isNonPilotSurface");function Ki(e){let t=[],n=0,r=new Map(Object.entries(e.fileLayers??{}).map(([c,p])=>[_s(c),p])),s=new Map((e.layerContexts??[]).map(c=>[c.name,c.intentPrefixes??[]])),o=(e.layerContexts??[]).find(c=>Os(c.name,c.intentPrefixes))?.name??"DomainModel";for(let[c,p]of Object.entries(e.fileContents).sort(([m],[g])=>m.localeCompare(g))){let m=_s(c);if(Ui(m)||/GENERATED FILE\s+[—-]\s+do not edit by hand/i.test(p.slice(0,320)))continue;let g=r.has(m),u=r.get(m),d=u?s.get(u)??[]:[],f=/(?:^|\/)(?:components|ui|layouts|styles|hooks|theme|tokens|i18n|locales?)(?:\/|$)/i.test(m)||/(?:^|\/)(?:src\/)?(?:app|pages)\/.+\.(?:tsx|jsx)$/i.test(m)&&/(?:page|layout|loading|error|template|default)\.(?:tsx|jsx)$/i.test(m),y=/(?:^|\/)(?:app|pages)(?:\/[^/]+)*\/api(?:\/|$)/i.test(m),I=/(?:^|\/)actions?(?:\/|\.|$)/i.test(m)||/['"]use server['"]/.test(p),N=/controller|handler|resolver/i.test(c)||y||I||/route\.(?:ts|js|tsx|jsx)$/i.test(m)&&!f||/@(Controller|Get|Post|Put|Delete|Patch)\b/.test(p)||/\bexport\s+(?:async\s+)?function\s+(?:GET|POST|PUT|DELETE|PATCH)\b/.test(p)||/\bexport\s+const\s+(?:GET|POST|PUT|DELETE|PATCH)\s*=/.test(p),E=g?!!(u&&Vi(u,d)&&N):N,k=g?!!(u&&Os(u,d)):/domain|entity|aggregate|model/i.test(c),b=!g||k||E;if(E&&!f){let O=/\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,D;for(;(D=O.exec(p))!==null;)n+=1,t.push({id:`inv-val-${n}`,kind:"validation-in-controller",file:c,line:jt(p,D.index),message:"Business validation appears in a controller/handler \u2014 extract an invariant or Domain rule.",confidence:"direct-evidence",governedLayer:u,suggestedArkRule:{layer:o,invariantId:`INV-EXTRACT-${n}`,sensor:"invariant-coverage"},neverMechanicalSafe:!0})}let J=/\b(const|let)\s+([A-Z][A-Z0-9_]{2,})\s*=\s*(\d{2,}|['"][^'"]{8,}['"])/g,H,G=i(O=>/^(?: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(O)||/^(?: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(O)||/_(?:ROUTE|PATH|LABEL|TITLE|COLOR|THEME|CLASS|STYLE|ICON|ARIA|MSG|COPY|TIMEOUT|PORT|VERSION|RETRY|DELAY|INTERVAL|TTL|CACHE)$/i.test(O)||/_(?:TIMEOUT(?:_MS)?|MS|BYTES|BUCKET|STORAGE_KEY|WINDOW_MS)$/i.test(O)||/^(?: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(O)||/^(?:FAVORITES_STORAGE|LISTINGS_CACHE|DOCS_PATH|METRICS_INTERVAL)/i.test(O)||/^(?:DEV|DEMO|SEED|FIXTURE)_[A-Z0-9_]+$/i.test(O)||/^(?:PG|POSTGRES|OID)_[A-Z0-9_]+$/i.test(O)||/_(?:OID|OIDS)$/i.test(O)||/^(?:INT2|INT4|INT8|FLOAT4|FLOAT8|NUMERIC|DATE|TIME|TIMESTAMP|TIMESTAMPTZ|JSON|JSONB|UUID)OID$/i.test(O)||/(?:^|_)(?:SCHEMA|PROTOCOL|RESOLVER|FORMAT)_(?:URL|URI|VERSION|ID|IDENTITY)$/i.test(O),"isInfraMagicName"),w=i((O,D)=>{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(O)||/_(?:MSG|MESSAGE|TEXT|COPY|TOAST|SNACK|ALERT|BANNER|CAPTION|HINT|HELP_TEXT|ERROR_TEXT|EMPTY_TEXT|PLACEHOLDER_TEXT|USER_MESSAGE|FEEDBACK)$/i.test(O))return!0;let P=D.replace(/^['"]|['"]$/g,"");return!!(/^['"]/.test(D)&&(/\s/.test(P)||/[.!?…]$/.test(P))&&!/^(?:STATUS|STATE|PHASE|ROLE|TYPE|KIND|ORDER|PAYMENT|CART|INVOICE|POLICY)_[A-Z0-9_]+$/i.test(O))},"isUxMessageConstant");for(;(H=J.exec(p))!==null;){let O=H[2],D=H[3]??"";!b||G(O)||w(O,D)||f&&!k||/(?:^|\/)(?:integrations?|repos?|clients?|infra(?:structure)?|adapters?)(?:\/|$)/i.test(m)&&!k||(n+=1,t.push({id:`inv-magic-${n}`,kind:"magic-business-constant",file:c,line:jt(p,H.index),message:`Magic business constant ${O} may belong in a Domain policy or invariant catalog.`,confidence:"heuristic",governedLayer:u,suggestedArkRule:{layer:o,invariantId:`INV-${O}`},neverMechanicalSafe:!0}))}if(k){let O=/export\s+class\s+([A-Za-z_][A-Za-z0-9_]*)\s*\{([^}]{0,800})\}/g,D;for(;(D=O.exec(p))!==null;){let P=D[2]??"",ee=(P.match(/\b[a-zA-Z_][a-zA-Z0-9_]*\s*\(/g)??[]).length;(P.match(/:\s*[A-Za-z]/g)??[]).length>=2&&ee<=1&&(n+=1,t.push({id:`inv-anemic-${n}`,kind:"anemic-entity",file:c,line:jt(p,D.index),message:`Class ${D[1]} looks anemic (data-heavy, few behaviors).`,confidence:"heuristic",governedLayer:u,suggestedArkRule:{layer:o,structureId:"no-anemic-model",sensor:"no-anemic-model"},neverMechanicalSafe:!0}))}}if(k&&!(/\.error\.(?:ts|js|tsx|jsx)$/i.test(m)||/(?:^|\/)[^/]*(?:-access)?\.error\./i.test(m)||/(?:^|\/)errors?(?:\/|$)/i.test(m))){let D=/this\.\w+\s*=/g,P;for(;(P=D.exec(p))!==null;){let ee=p.lastIndexOf("class ",P.index),fe=ee>=0?p.indexOf("{",ee):-1,v=ee>=0&&fe>=ee&&fe<P.index?p.slice(ee,fe):"";if(/\bextends\s+(?:Error|[A-Za-z_$][A-Za-z0-9_$]*Error)\b/.test(v))continue;let _=p.slice(Math.max(0,P.index-200),P.index+200);if(!/\b(ensureInvariants|assertInvariants|validate|publish|emit)\b/.test(_)){n+=1,t.push({id:`inv-mut-${n}`,kind:"mutation-without-guard",file:c,line:jt(p,P.index),message:"Domain field mutation without nearby guard/publish call.",confidence:"heuristic",governedLayer:u,suggestedArkRule:{layer:o,structureId:"events-on-mutation",sensor:"domain-event-on-mutation"},neverMechanicalSafe:!0});break}}}}let a=new Set(e.contractedRuleIds??[]);t.sort((c,p)=>+(p.confidence==="direct-evidence")-+(c.confidence==="direct-evidence")||c.file.localeCompare(p.file)||c.line-p.line||c.kind.localeCompare(p.kind)||c.id.localeCompare(p.id));let l=t.filter(c=>c.suggestedArkRule?.invariantId&&a.has(c.suggestedArkRule.invariantId)||c.suggestedArkRule?.structureId&&a.has(c.suggestedArkRule.structureId)).length;return{candidates:t,inventoried:t.length,underContract:l,frozen:(e.frozenKeys??[]).length,notAScore:!0}}i(Ki,"buildRulesInventory");function Gi(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(Gi,"inventoryToExtractionCard");var Bi="1.1";var zi="1.0";var Zn="docs/diagnostics.md",qi="1.0";function S(e,t,n,r,s,o){return{ruleId:e,title:n,why:r,fix:s,docsAnchor:e,category:t,...o?.oftenAdvisory?{oftenAdvisory:!0}:{}}}i(S,"entry");var Vt=Object.freeze([S("LAYER_IMPORT_VIOLATION","layer","Layer import not allowed","A module import (or re-export) crosses a layer edge that ark.config.json does not allow. The architecture contract forbids that dependency direction so outer infrastructure cannot leak into pure or inner layers.","Branch by import kind: constants/types/pure \u2192 adopt into DomainModel or SharedKernel (do not invent a port); kernel/events/bootstrap from Persistence \u2192 inject a port or move the map to SharedTypes (Persistence must not emit); define a port only when the target is a real use-case. Type-only edges use `import type`. Then preflight again. Do not weaken the layer rule without a hash-bound policy acknowledgement."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("ARKRULE_STRUCTURE","arkrules","ArkRule structure sensor failed","An opt-in ArkRules structure sensor (private state, factory shape, event publish, \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."),S("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."),S("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}),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("ARKORDER_GENERIC_UPDATE","arkorder","Generic update of \u03BE","A call to update/patch/set on the order plane rewrites the slow pattern. Haken slaving forbids generic \u03BE mutation.","Use release() to freeze \u03BE or proposeRelease() for a pattern change with blast radius, then preflight again. Never mechanical-safe."),S("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."),S("ARKORDER_INGEST_WRITES_XI","arkorder","ingest assigned into \u03BE","An ingest() result is written into a Release or \u03BE store. ingest may absorb or escalate; it never mints a pattern.","Keep ingest results as absorb/escalate only. Change \u03BE with proposeRelease + release. Never mechanical-safe."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("LEXICAL_EVIDENCE_INCOMPLETE","analysis","Lexical evidence incomplete","Single-file validation cannot prove project module resolution. The write hook is already the verdict.","Re-run `npx arkgate-check --root . --config ark.config.json`, or treat the hook deny as final. Do not call ark_prepare_change from a hook deny."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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}),S("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}),S("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}),S("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}),S("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}),S("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}),S("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}),S("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}),S("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}),S("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}),S("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}),S("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}),S("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}),S("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}),S("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.")]),Xn=new Map(Vt.map(e=>[e.ruleId,e])),Yi=Object.freeze(Vt.map(e=>e.ruleId));function Wi(e){return typeof e=="string"&&e.length>0&&Xn.has(e)}i(Wi,"isKnownDiagnosticCode");function Ji(e){return typeof e!="string"||e.length===0?!1:Xn.has(e)?!0:e.startsWith("ARKRULE_")}i(Ji,"isCataloguedOrArkRuleFamily");function Ut(e){if(!(typeof e!="string"||e.length===0))return Xn.get(e)}i(Ut,"getDiagnosticCatalogEntry");function Ts(e){return`#${Ut(e)?.docsAnchor??e}`}i(Ts,"diagnosticDocsFragment");function Zi(e){return`${Zn}${Ts(e)}`}i(Zi,"diagnosticDocsPath");function Xi(){return{schemaVersion:"1.0",docsPath:Zn,codes:Vt}}i(Xi,"serializeDiagnosticCatalog");function Qi(e){return Ut(e)?.fix}i(Qi,"catalogFixForRuleId");function el(e){return Ut(e)?.why}i(el,"catalogWhyForRuleId");var Qn="1.0",Ns="https://unpkg.com/arkgate@4/schemas/ark.status-manifest.schema.json",Ps=["full","subset","unavailable"],Ls=["doctor-facts","report-snapshot","none"],Kt={FACTS_UNAVAILABLE:"FACTS_UNAVAILABLE",FACTS_PARTIAL:"FACTS_PARTIAL",NO_SESSION_SNAPSHOT:"NO_SESSION_SNAPSHOT"},ws=/^sha256:[a-f0-9]{64}$/;function Ds(e){let t=e.expectation;if(t==null||t.expectedRoot===void 0&&t.expectedProjectId===void 0)return{status:"matched",authoritative:!!e.resolvedRoot};if(t&&typeof t!="object")return{status:"mismatch",authoritative:!1,code:"INVALID_PROJECT_EXPECTATION",message:"project must be an object containing expectedRoot and/or expectedProjectId."};let n=t.expectedRoot,r=t.expectedProjectId;if(n!==void 0&&(typeof n!="string"||n.trim()===""))return{status:"mismatch",authoritative:!1,code:"INVALID_PROJECT_EXPECTATION",message:"project.expectedRoot must be a non-empty absolute path."};if(r!==void 0&&(typeof r!="string"||!ws.test(r)))return{status:"mismatch",authoritative:!1,code:"INVALID_PROJECT_EXPECTATION",message:"project.expectedProjectId must be a sha256:<64 lowercase hex> identity."};if(n===void 0&&r!==void 0)return e.projectId&&r!==e.projectId?{status:"mismatch",authoritative:!1,expectedProjectId:r,code:"PROJECT_ID_MISMATCH",message:`Expected project id ${r}, but this process is bound to ${e.projectId}.`}:{status:"unverified",authoritative:!1,expectedProjectId:r,message:"project.expectedProjectId matched or could not be compared, but expectedRoot is required for an authoritative workspace binding."};let s=e.expectedRootRelation??"unknown";return s==="outside"?{status:"mismatch",authoritative:!1,expectedRoot:n,expectedProjectId:r,code:"PROJECT_ROOT_MISMATCH",message:`Expected workspace ${n}, but this process is bound to ${e.resolvedRoot}.`}:s==="unknown"?{status:"unverified",authoritative:!1,expectedRoot:n,expectedProjectId:r,message:"Could not prove expectedRoot against the resolved project root (stale or incomplete path evidence)."}:s==="descendant"&&r===void 0?{status:"unverified",authoritative:!1,expectedRoot:n,message:`Expected workspace ${n} is inside this project, but an exact project root is required for the initial authoritative handshake.`}:r!==void 0&&e.projectId&&r!==e.projectId?{status:"mismatch",authoritative:!1,expectedRoot:n,expectedProjectId:r,code:"PROJECT_ID_MISMATCH",message:`Expected project id ${r}, but this process is bound to ${e.projectId}.`}:s==="exact"||s==="descendant"&&r&&r===e.projectId?{status:"matched",authoritative:!0,...n?{expectedRoot:n}:{},...r?{expectedProjectId:r}:{}}:{status:"unverified",authoritative:!1,expectedRoot:n,expectedProjectId:r,message:"Project expectation could not be fully verified."}}i(Ds,"evaluateStatusBinding");function Ms(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(Ms,"classifyStatusWritePath");function Fs(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(Fs,"defaultHonestLabel");function $s(e,t,n,r,s){return e.nextActionOverride?.id&&e.nextActionOverride.summary?{id:e.nextActionOverride.id,summary:e.nextActionOverride.summary}:t.status==="mismatch"?{id:"rebind-project-identity",summary:t.message||"Project expectation does not match this process \u2014 call ark_identity / ark status with the correct expectedRoot (and projectId for descendants)."}:t.status==="unverified"&&e.expectation?{id:"complete-identity-handshake",summary:t.message||"Supply project.expectedRoot at the exact project root (and expectedProjectId for descendants) for authoritative status."}:e.resolvedConfigPath?r.verdict==="fail"||(r.activeViolations??0)>0?{id:"fix-active-violations",summary:`Clear ${r.activeViolations??"active"} blocking architecture finding(s), then re-run ark-check (or ark-check --doctor).`}:r.verdict==="incomplete"?{id:"restore-complete-analysis",summary:"Last check was incomplete \u2014 restore TypeScript/analysis inputs and re-run ark-check."}:r.verdict==null&&r.at==null?{id:"run-ark-check",summary:"No last-check snapshot yet \u2014 run ark-check --report (or --doctor) to freeze session evidence."}:n.writePath==="unavailable"?{id:"install-write-path",summary:"Write path is unavailable \u2014 install agent gates for your host (ark start / --install-agent-gates) and keep required CI --strict-merge."}:n.writePath==="advisory"?{id:"keep-ci-merge-hard",summary:"Local write is advisory for this host \u2014 keep a required GitHub status on arkgate-check --strict-merge as the hard merge boundary."}:e.leftoverDesignWork===!0?{id:"map-leftover-design",summary:"Leftover design work remains. Map with /ark-explore, then apply one small refactor with /ark-autopilot. Green imports are not done."}:s.arkRulesLoaded&&(s.frozenResidual??0)>0?{id:"review-arkrules-residual",summary:"ArkRules residual remains frozen \u2014 review inventory debt without claiming a score."}:e.arkRun?.present===!0&&(e.arkRun.residual??0)>0?{id:"review-arkrun-residual",summary:"ArkRun residual remains \u2014 wire kernel usage or declarations through arkgate/runtime. Not a score."}:e.adopted==="required-merge"||e.adopted==="advisory-only-acked"?{id:"stay-enforced",summary:"Contract looks enforceable for this session \u2014 keep writing through the gate and re-check after structural edits."}:{id:"require-ci-merge-status",summary:'Make arkgate-check --strict-merge a required GitHub status, or write .ark/adoption-stance.json with stance: "advisory-only".'}:{id:"run-ark-start",summary:"No ark.config.json found \u2014 run ark start (preview) then ark start --apply."}}i($s,"resolveStatusNextAction");function tl(e){let t=typeof e.resolvedRoot=="string"&&e.resolvedRoot.length>0?e.resolvedRoot:".",n=typeof e.projectId=="string"&&ws.test(e.projectId)?e.projectId:null,r=Ds({resolvedRoot:t,projectId:n,expectation:e.expectation,expectedRootRelation:e.expectedRootRelation}),s=typeof e.activeHost=="string"?e.activeHost.trim().toLowerCase():"",o=s&&s!=="unknown"?s:s==="unknown"?"unknown":null,a=Ms({hardWriteActive:e.hardWriteActive,softWriteHost:e.softWriteHost,writePathUnavailable:e.writePathUnavailable,activeHost:o}),l=typeof e.honestLabel=="string"&&e.honestLabel.trim().length>0?e.honestLabel.trim():Fs(a,o),c={at:typeof e.lastCheckAt=="string"?e.lastCheckAt:null,verdict:e.lastCheckVerdict==="pass"||e.lastCheckVerdict==="fail"||e.lastCheckVerdict==="incomplete"?e.lastCheckVerdict:null,activeViolations:At(e.activeViolations),frozenResidual:At(e.frozenResidual)},p={arkRulesLoaded:e.arkRulesLoaded===!0,inventoried:At(e.rulesInventoried),underContract:At(e.rulesUnderContract),frozenResidual:At(e.rulesFrozenResidual)},m={writePath:a,host:o,honestLabel:l},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}:{}},u={schemaVersion:Qn,arkgateVersion:typeof e.arkgateVersion=="string"&&e.arkgateVersion.length>0?e.arkgateVersion:"unknown",projectIdentity:g,activation:m,lastCheck:c,rules:p,nextAction:$s(e,r,m,c,p)},d=js(e.improvementCompass);return d&&(u.improvementCompass=d),e.vsBase&&typeof e.vsBase.baseRef=="string"&&e.vsBase.baseRef.length>0&&(u.vsBase=e.vsBase),e.arkRun&&typeof e.arkRun=="object"&&(u.arkRun=Jn(e.arkRun)),u}i(tl,"buildStatusManifest");var Hs=new Set(Ps),nl=new Set(Ls);function er(e){let t=Hs.has(e.mode)?e.mode:"unavailable",n=e.factsSource!=null&&nl.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:Kt.FACTS_UNAVAILABLE,reason:typeof e.reason=="string"&&e.reason.length>0?e.reason:"Improvement compass facts are unavailable \u2014 run ark-check --doctor for residual lenses. Status never invents green.",factsSource:n??"none"};return r&&(a.contractHash=r),a}let s=Array.isArray(e.topResidual)?e.topResidual.filter(a=>typeof a=="string"&&a.length>0).slice(0,15):[],o={schemaVersion:"1.0",notAScore:!0,mode:t,topResidual:s};return t==="subset"?(o.reasonCode=typeof e.reasonCode=="string"&&e.reasonCode.length>0?e.reasonCode:Kt.FACTS_PARTIAL,o.reason=typeof e.reason=="string"&&e.reason.length>0?e.reason:"Status compass is a subset of doctor residual \u2014 incomplete session facts; run doctor for full."):typeof e.reasonCode=="string"&&e.reasonCode.length>0&&(o.reasonCode=e.reasonCode),typeof e.reason=="string"&&e.reason.length>0&&t==="full"&&(o.reason=e.reason),n&&(o.factsSource=n),r&&(o.contractHash=r),o}i(er,"projectStatusImprovementCompass");function rl(e={}){return er({mode:"unavailable",topResidual:[],reasonCode:e.reasonCode??Kt.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(rl,"unavailableStatusImprovementCompass");function js(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"&&Hs.has(t.mode)?n=t.mode:Array.isArray(t.topResidual)?n="subset":n="unavailable",er({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(js,"normalizeStatusImprovementCompass");function sl(e,t){let n=Array.isArray(e)?e:[],r=new Set(Array.isArray(t)?t:[]);for(let s of n)if(!(typeof s!="string"||s.length===0)&&!r.has(s))return!1;return!0}i(sl,"statusCompassResidualIsSubsetOfDoctor");function At(e){if(e==null)return null;let t=Number(e);return!Number.isFinite(t)||t<0?null:Math.floor(t)}i(At,"numberOrNull");var ol={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Ns,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:Qn},arkgateVersion:{type:"string",minLength:1},projectIdentity:{type:"object",additionalProperties:!1,required:["projectId","resolvedRoot","resolvedConfigPath","binding","authoritative"],properties:{projectId:{anyOf:[{type:"string",pattern:"^sha256:[a-f0-9]{64}$"},{type:"null"}]},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{anyOf:[{type:"string",minLength:1},{type:"null"}]},binding:{enum:["matched","unverified","mismatch"]},authoritative:{type:"boolean"},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},activation:{type:"object",additionalProperties:!1,required:["writePath","host","honestLabel"],properties:{writePath:{enum:["hard","advisory","unavailable"]},host:{anyOf:[{type:"string",minLength:1},{type:"null"}]},honestLabel:{type:"string",minLength:1}}},lastCheck:{type:"object",additionalProperties:!1,required:["at","verdict","activeViolations","frozenResidual"],properties:{at:{anyOf:[{type:"string",minLength:1},{type:"null"}]},verdict:{anyOf:[{enum:["pass","fail","incomplete"]},{type:"null"}]},activeViolations:{anyOf:[{type:"integer",minimum:0},{type:"null"}]},frozenResidual:{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}},rules:{type:"object",additionalProperties:!1,required:["arkRulesLoaded","inventoried","underContract","frozenResidual"],properties:{arkRulesLoaded:{type:"boolean"},inventoried:{anyOf:[{type:"integer",minimum:0},{type:"null"}]},underContract:{anyOf:[{type:"integer",minimum:0},{type:"null"}]},frozenResidual:{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}},nextAction:{type:"object",additionalProperties:!1,required:["id","summary"],properties:{id:{type:"string",minLength:1},summary:{type:"string",minLength:1}}},improvementCompass:{type:"object",description:"Thin improvement-compass residual ids with honesty mode (notAScore). full | subset | unavailable. Never a gate input; full lenses on doctor JSON. When full, residual ids \u2286 doctor residual for the same facts. unavailable never invents green residual.",additionalProperties:!1,required:["schemaVersion","notAScore","mode","topResidual"],properties:{schemaVersion:{const:"1.0"},notAScore:{const:!0},mode:{enum:["full","subset","unavailable"]},topResidual:{type:"array",items:{type:"string",minLength:1},maxItems:15},reasonCode:{type:"string",minLength:1},reason:{type:"string",minLength:1},factsSource:{enum:["doctor-facts","report-snapshot","none"]},contractHash:{type:"string",minLength:1}}},vsBase:{type:"object",description:"Checkout vs a git base ref: pin, contract identity, baseline grow. Advisory honesty only \u2014 never a gate input.",additionalProperties:!1,required:["baseRef","line","pinLocal","pinBase","contractEqual","baselineGrew"],properties:{baseRef:{type:"string",minLength:1},line:{type:"string",minLength:1},pinLocal:{anyOf:[{type:"string",minLength:1},{type:"null"}]},pinBase:{anyOf:[{type:"string",minLength:1},{type:"null"}]},contractEqual:{type:"boolean"},baselineGrew:{type:"boolean"}}},arkRun:{type:"object",description:"ArkRun extra residual (notAScore). present/mode from config; residual is a finding-id count (null = unknown, not green). extraMergeTeeth is honesty, never a score.",additionalProperties:!1,required:["notAScore","present","mode","extraMergeTeeth","residual"],properties:{notAScore:{const:!0},present:{type:"boolean"},mode:{anyOf:[{enum:["advisory","enforced"]},{type:"null"}]},extraMergeTeeth:{type:"boolean"},residual:{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}}}};var Gt="1.0",Bt=["soc","cohesion","coupling","srp","dip","ocp","encapsulation","modularity","scalability","resilience","security","maintainability","testability","domain","stack"],zt=5,Pe=["scalability","resilience","security"],Ke=new Set(Pe),tr={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},nr={soc:"Separation of concerns",cohesion:"High cohesion",coupling:"Low coupling",srp:"Single responsibility (architecture)",dip:"Dependency inversion",ocp:"Open/closed",encapsulation:"Encapsulation",modularity:"Modularity",scalability:"Scalability / performance",resilience:"Resilience / fault tolerance",security:"Security by design",maintainability:"Maintainability",testability:"Testability",domain:"Domain alignment",stack:"Stack-specific practices"},rr={scalability:"ArkGate does not measure performance or horizontal scale. Use load tests and APM outside Ark.",resilience:"ArkGate does not measure app resilience or chaos readiness. Structural boundaries and optional experimental runtime are not a resilience score.",security:"ArkGate does not run SAST or app-security tooling. Structural least-privilege of effects is partial only \u2014 not a security rating."};function sr(e){return nr[e]??e}i(sr,"improvementCompassHumanLabel");function or(e){let t=e.id??e.smellId??"";return typeof t=="string"?t.trim():""}i(or,"smellIdOf");function ar(e){let t=e.ruleId??e.code??"";return typeof t=="string"?t.trim():""}i(ar,"violationRuleId");function $(e,t,n,r){if(!n||e.evidence.some(o=>o.source===t&&o.ref===n))return;let s={source:t,ref:n};r&&r.trim()&&(s.detail=r.trim().slice(0,240)),e.evidence.push(s)}i($,"pushEvidence");function Q(e,t,n){Ke.has(e.id)||(e.status="residual",e.summary=t,n&&(e.nextAction=n))}i(Q,"markResidual");function Vs(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`${nr[e]} \u2014 no residual from current sensors.`}}i(Vs,"defaultOkSummary");function Us(){return Bt.map(e=>Ke.has(e)?{id:e,status:"out-of-scope",summary:rr[e],evidence:[],nextAction:{kind:"docs",ref:"docs/use.md#improvement-compass",summary:"Out of scope for ArkGate \u2014 use dedicated tooling outside the gate."}}:e==="ocp"?{id:e,status:"not-instrumented",summary:Vs(e),evidence:[]}:{id:e,status:"ok",summary:Vs(e),evidence:[]})}i(Us,"createInitialImprovementCompassLenses");function al(e,t){for(let n of t){let r=or(n);if(!r)continue;let s=n.outcome||n.message||void 0,a=(Array.isArray(n.evidence)?n.evidence:[])[0],l=i((m,g,u)=>{let d=e.get(m);!d||Ke.has(m)||($(d,"designSmells",r,s),a&&$(d,"designSmells",a,r),Q(d,g,u))},"attach"),c={kind:"skill",ref:"/ark-explore",summary:"Map Shape residual (shape-focus), then apply one extraction pilot with /ark-autopilot."},p={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.",p);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.",p),l("testability","Direct I/O under application code hurts pure unit testing.",p);break;case"handler-in-persistence":l("soc","HTTP/transport handlers live under persistence folders.",c);break;case"god-module":l("cohesion","Large multi-responsibility modules reduce cohesion.",c),l("srp","God modules own too many responsibilities \u2014 split by concern (one pilot).",{kind:"skill",ref:"/ark-autopilot",summary:"One Shape pilot this turn \u2014 never multi-pilot batch."});break;case"mixed-pattern-cluster":l("modularity","Multiple layout styles coexist \u2014 placement is unclear for the next AI turn.",{kind:"skill",ref:"/ark-explore",summary:"Pick a golden pattern and migrate one pilot cluster on touch."}),l("cohesion","Mixed layout styles scatter the same concern across patterns.",c);break;case"soft-contract":l("maintainability","Soft contract walls (layers without deny rules) hide maintainability debt.",{kind:"skill",ref:"/ark-adopt",summary:"Add real layer rules so the AI has hard walls."}),l("coupling","Layers with files but almost no deny rules allow free peer coupling.",{kind:"skill",ref:"/ark-adopt",summary:"Tighten inter-layer allows/denies without weakening enforcement."});break;default:l("maintainability","Design residual remains under an unrecognized smell id \u2014 review evidence.",c);break}}}i(al,"mapDesignSmells");function il(e){return e.failsStrict===!1||e.typeOnly===!0}i(il,"isTypeOnlyPlacementDebt");function ll(e,t){for(let n of t){let r=ar(n);if(!r)continue;let s=n.message,o=r.toUpperCase(),a=i((c,p,m)=>{let g=e.get(c);!g||Ke.has(c)||($(g,"violations",r,s),n.file&&$(g,"violations",n.file,r),Q(g,p,m))},"attach");if(il(n)){a("modularity","Type-only placement debt remains \u2014 prefer SharedTypes / owning layer (not runtime coupling).",{kind:"skill",ref:"/ark-place",summary:"Place shared types in a layer both sides may import; type-only debt is not a value edge."});continue}let l={kind:"skill",ref:"/ark-autopilot",summary:"Clear the active edge residual, then re-doctor."};if(o==="LAYER_IMPORT_VIOLATION"||o.includes("LAYER_IMPORT")||o==="DYNAMIC_IMPORT_VIOLATION"){a("coupling","Import graph edges violate the layer contract.",l);continue}if(o.includes("CYCLE")||o==="CIRCULAR_DEPENDENCY"){a("coupling","Import cycles couple modules tightly.",l);continue}if(o.includes("PEER_ISOLATION")||o==="PEER_ISOLATION_VIOLATION"){a("coupling","Peer isolation residual \u2014 slices import each other freely.",{kind:"skill",ref:"/ark-autopilot",summary:"Peer isolation fixes are judgment-class \u2014 one cluster at a time."});continue}if(o==="FORBIDDEN_GLOBAL"||o.startsWith("FORBIDDEN_")){a("dip","Forbidden globals / effect surfaces break dependency inversion.",{kind:"skill",ref:"/ark-autopilot",summary:"Inject a port instead of the forbidden global."}),a("testability","Forbidden ambient effects reduce pure-domain testability.",{kind:"skill",ref:"/ark-autopilot",summary:"Replace ambient effects with injectable ports."});continue}if(o==="CAPABILITY_VIOLATION"){a("dip","Denied capability use \u2014 invert through an allowed adapter/port.",{kind:"skill",ref:"/ark-autopilot",summary:"Capability walls require port injection (judgment, not mechanical-safe)."}),a("testability","Capability violations couple domain code to I/O \u2014 harder to unit-test.",{kind:"skill",ref:"/ark-autopilot",summary:"Keep pure layers free of denied capabilities."});continue}if(o.startsWith("ARKRULE_")||o==="INVARIANT_UNCOVERED"){a("encapsulation","ArkRules structure / invariant residual inside a layer.",{kind:"skill",ref:"/ark-autopilot",summary:"Label [ArkRules]; structure fixes are judgment \u2014 never invent mechanical-safe."}),a("domain","Intra-layer domain structure or invariant coverage residual.",{kind:"skill",ref:"/ark-explore",summary:"Inventory candidates \u2192 one ArkRules pilot with coverage evidence."});continue}}}i(ll,"mapViolations");function cl(e,t){let n=Number(t.cycleCount)||0;if(n>0){let d=e.get("coupling");$(d,"cycles",`count:${n}`),Q(d,"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 d=e.get("coupling");$(d,"peerIsolation",`count:${r}`),Q(d,"Peer isolation residual remains.",{kind:"skill",ref:"/ark-autopilot",summary:"Peer isolation is judgment-class residual."})}let s=Number(t.physicalCohesionFindingCount)||0;if(s>0){let d=e.get("cohesion");$(d,"physicalCohesion",`findings:${s}`),Q(d,"Physical cohesion residual \u2014 mirrored concept clusters across anchors.",{kind:"skill",ref:"/ark-explore",summary:"Review reshape pilot; one decision-aware pilot at a time."});let f=e.get("srp");$(f,"physicalCohesion",`findings:${s}`),Q(f,"Mirrored clusters suggest split-by-concern residual (architecture SRP).",{kind:"skill",ref:"/ark-autopilot",summary:"One reshape/extraction pilot this turn."})}let o=Number(t.pureOrCapabilityResidual)||0,a=Number(t.forbiddenGlobalResidual)||0;if(o>0||a>0){let d=e.get("dip");o>0&&$(d,"capability",`residual:${o}`),a>0&&$(d,"forbiddenGlobals",`residual:${a}`),Q(d,"Pure / capability / forbidden residual weakens dependency inversion.",{kind:"skill",ref:"/ark-autopilot",summary:"Inject ports; keep pure layers free of effects."});let f=e.get("testability");o>0&&$(f,"capability",`residual:${o}`),a>0&&$(f,"forbiddenGlobals",`residual:${a}`),Q(f,"Impure domain or capability residual reduces testability.",{kind:"skill",ref:"/ark-autopilot",summary:"Prefer ports over concrete I/O in pure/domain modules."})}let l=Number(t.arkRulesStructureResidual)||0;if(l>0){let d=e.get("encapsulation");$(d,"arkRules",`structureResidual:${l}`),Q(d,"ArkRules structure residual \u2014 encapsulation inside the layer.",{kind:"skill",ref:"/ark-autopilot",summary:"Fix structure sensors under [ArkRules] without inventing mechanical-safe."});let f=e.get("domain");$(f,"arkRules",`structureResidual:${l}`),Q(f,"ArkRules residual may mean domain shape is not yet under contract.",{kind:"skill",ref:"/ark-explore",summary:"Map inventory candidates; one pilot rule at a time."})}else t.arkRulesLoaded===!1||t.arkRulesLoaded==null;if(t.designWeak===!0){let d=e.get("maintainability");$(d,"designFitness","design-weak"),Q(d,"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 d=e.get("maintainability");t.dirtyBaselineRisk===!0&&$(d,"baseline","dirty-freeze-risk"),(Number(t.baselineStale)||0)>0&&$(d,"baseline",`stale:${t.baselineStale}`),Q(d,"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 d=e.get("maintainability");$(d,"baseline",`frozen:${c}`),Q(d,"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 p=Number(t.ungovernedDirCount)||0,m=Number(t.emptyLayerCount)||0;if(p>0||m>0){let d=e.get("modularity");p>0&&$(d,"coverage",`ungovernedDirs:${p}`),m>0&&$(d,"coverage",`emptyLayers:${m}`),Q(d,"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 d=e.get("modularity");$(d,"goldenPattern","absent"),Q(d,"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(cl,"mapCountsAndFlags");function Ks(e,t){if(Array.isArray(t.designSmells)&&t.designSmells.length>0){let n=[...t.designSmells].sort((r,s)=>or(r).localeCompare(or(s)));al(e,n)}if(Array.isArray(t.violations)&&t.violations.length>0){let n=[...t.violations].sort((r,s)=>{let o=ar(r).localeCompare(ar(s));return o!==0?o:String(r.file??"").localeCompare(String(s.file??""))});ll(e,n)}cl(e,t)}i(Ks,"projectImprovementCompassFacts");function Gs(e){for(let t of Pe){let n=e.get(t);n.status="out-of-scope",n.summary=rr[t],n.evidence=[],n.nextAction={kind:"docs",ref:"docs/use.md#improvement-compass",summary:"Out of scope for ArkGate \u2014 use dedicated tooling outside the gate."}}}i(Gs,"lockImprovementCompassOutOfScope");function Bs(e){for(let t of e)t.evidence.sort((n,r)=>{let s=n.source.localeCompare(r.source);return s!==0?s:n.ref.localeCompare(r.ref)})}i(Bs,"sortImprovementCompassEvidence");function zs(e){return e.filter(n=>n.status==="residual"&&!Ke.has(n.id)).slice().sort((n,r)=>{let s=tr[n.id]??150,o=tr[r.id]??150;return s!==o?s-o:n.id.localeCompare(r.id)}).slice(0,5).map(n=>n.id)}i(zs,"finalizeImprovementCompassTopResidual");function dl(e={}){let t=Us(),n=new Map(t.map(s=>[s.id,s]));Ks(n,e),Gs(n),Bs(t);let r=zs(t);return{schemaVersion:"1.0",notAScore:!0,lenses:t.map(s=>{let o={id:s.id,status:s.status,summary:s.summary,evidence:s.evidence.map(a=>({...a}))};return s.nextAction&&(o.nextAction={...s.nextAction}),o}),topResidual:r}}i(dl,"buildImprovementCompass");function qs(e){return e.topResidual.map(t=>sr(t))}i(qs,"formatImprovementCompassResidualLabels");function Ys(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(Ys,"primaryImprovementCompassNextAction");function ul(e){let t=qs(e),n=Pe.map(o=>sr(o)),r=Ys(e),s=[];return t.length>0?s.push(`Residual: ${t.join(" \xB7 ")}`):s.push("Residual: none on instrumented lenses (not a score \u2014 green edges \u2260 finished design)."),s.push(`Out of scope (honest): ${n.join(" \xB7 ")}`),r&&s.push(`Next: ${r.ref} \u2014 ${r.summary}`),s}i(ul,"formatImprovementCompassDoctorLines");var pl="1.0",fl="<!-- arkgate:agent-projection:begin",Ws="<!-- arkgate:agent-projection:end -->",Js="This projection is **non-authoritative**. Enforcement is `ark-check` / host write hooks / required CI (`--strict-merge`), not AGENTS.md, skills, or this block.",cr=Object.freeze(["ark-check","host-write-hooks","ci-strict-merge"]),ml=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"]),dr=/<!--\s*arkgate:agent-projection:begin\b([^>]*)-->/i,Zs=/<!--\s*arkgate:agent-projection:end\s*-->/i,gl=/\barkgateVersion=([A-Za-z0-9._+-]+)/i,yl=/\bschema=([A-Za-z0-9._+-]+)/i;function qt(e){let t=String(e??"").replace(/\r\n/g,`
17
- `),n=2166136261;for(let r=0;r<t.length;r+=1)n^=t.charCodeAt(r),n=Math.imul(n,16777619);return`fnv1a-${(n>>>0).toString(16).padStart(8,"0")}`}i(qt,"agentProjectionContentIdentity");function Yt(e){return String(e??"").replace(/\r\n/g,`
18
- `)}i(Yt,"normalizeNewlines");function Ge(e){let t=Yt(e);return t.endsWith(`
8
+ `)}`),this.name="EffectiveContractError",this.source=t,this.issues=n}};function Qr(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}i(Qr,"normalizeRel");function Ao(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:xe(),warnings:r}}let s=new Set(e.config.layers.map(c=>c.name)),a=[],o=[],l=new Set;for(let c of Object.keys(n).sort()){let p=n[c],g=`$.arkRules[${JSON.stringify(c)}]`;if(typeof p!="string"||p.length===0){a.push({path:g,message:"must be a non-empty relative path string"});continue}if(p.startsWith("/")||/^[A-Za-z]:[\\/]/.test(p)){a.push({path:g,message:"must be a project-relative path (absolute paths are not allowed)"});continue}if(!s.has(c)){a.push({path:g,message:`layer ${JSON.stringify(c)} is not declared in layers[]`});continue}let y=Qr(p);l.add(y);let f=e.fileContents[y]??e.fileContents[p];if(f===void 0){a.push({path:g,message:`referenced ArkRules file ${JSON.stringify(y)} is missing`});continue}try{let u=Tt(JSON.parse(f),y,c);o.push({layer:c,sourceFile:y,file:u.config})}catch(u){if(u instanceof _e)for(let m of u.issues)a.push({path:`${g}${m.path==="$"?"":m.path.replace(/^\$/,"")}`,message:`${y}: ${m.message}`});else u instanceof SyntaxError?a.push({path:g,message:`referenced ArkRules file ${JSON.stringify(y)} is not valid JSON: ${u.message}`}):a.push({path:g,message:`referenced ArkRules file ${JSON.stringify(y)} failed to load: ${u instanceof Error?u.message:String(u)}`})}}if(e.discoveredArkRulesFiles)for(let c of[...e.discoveredArkRulesFiles].sort()){let p=Qr(c);l.has(p)||r.push({path:p,message:`ArkRules file ${JSON.stringify(p)} is not referenced by arkRules and will not be enforced`,severity:"advisory"})}if(a.length>0)throw new Nt(t,a);return{config:e.config,arkRules:vn(o),warnings:r}}i(Ao,"resolveEffectiveContract");function Cn(e){let{stewards:t,...n}=e.config;return{config:n,arkRules:{schemaVersion:e.arkRules.schemaVersion,structure:e.arkRules.structure.map(r=>({id:r.id,sensor:r.sensor,mode:r.mode,appliesTo:r.appliesTo??null,description:r.description??null,provenance:r.provenance})),invariants:e.arkRules.invariants.map(r=>({id:r.id,description:r.description,aggregate:r.aggregate??null,coverage:r.coverage??null,mode:r.mode,appliesTo:r.appliesTo??null,provenance:r.provenance}))}}}i(Cn,"effectiveContractPolicyPayload");function Ro(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*['"\`][^'"\`]*${n}[^'"\`]*['"\`]`,"i").test(e)||e.includes(t)}i(Ro,"titleMatchesInvariant");function ko(e,t){if(!t)return!1;let n=t.split("."),r=n[n.length-1],s=n.length>1?n[0]:null;for(let a of Object.values(e))if(!(s&&!a.includes(s))&&(new RegExp(`(?:function\\s+|\\b)${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[(<]`).test(a)||a.includes(t)))return!0;return!1}i(ko,"symbolPresent");function On(e){let t=e.arkRules.invariants??[];if(t.length===0)return{coverage:[],violations:[],partial:!1};let n=e.testFiles??[],r=e.testGlobsMissing===!0||n.length===0,s=e.coverageBudgetExhausted===!0,a=[],o=[];for(let l of t){let c=[],p=l.coverage?.test!==!1,g=l.coverage?.symbol;if(!r&&p)for(let m of n){let A=e.fileContents[m];if(A&&Ro(A,l.id)){c.push("test-title");break}}g&&ko(e.fileContents,g)&&c.push("symbol");let f=(l.coverage?.test===!0||!!g||l.coverage===void 0)&&c.length>0||l.coverage?.test===!1&&!g?!0:c.length>0,u=r&&p&&c.length===0;if(a.push({invariantId:l.id,layer:l.provenance.layer,sourceFile:l.provenance.sourceFile,mode:l.mode,covered:f&&!u,evidence:c,partial:u,description:l.description}),!f||u){let m=l.mode==="enforced"&&!u,A=r||n.length===0?"never-had-tests":"tests-disappeared";o.push({ruleId:"INVARIANT_UNCOVERED",message:u?s?`Invariant ${l.id} coverage cannot be proven (coverage file budget exhausted); reporting partial, not covered.`:`Invariant ${l.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered (never-had-tests).`:A==="tests-disappeared"?`Invariant ${l.id} is not covered by a test title or declared symbol (tests-disappeared \u2014 suite exists).`:`Invariant ${l.id} is not covered by a test title or declared symbol (never-had-tests).`,file:l.provenance.sourceFile,line:1,arkruleId:l.id,arkruleSource:l.provenance.sourceFile,fromLayer:l.provenance.layer,severity:m?"error":"warning",failsStrict:m,kind:A})}}return{coverage:a,violations:o,partial:a.some(l=>l.partial)}}i(On,"evaluateInvariantCoverage");function _n(e){return e?e.partial?{ok:!1,reason:"Coverage is partial (missing test globs); cannot promote until evidence is complete."}:e.covered?{ok:!0,reason:`Invariant ${e.invariantId} has coverage evidence.`}:{ok:!1,reason:`Invariant ${e.invariantId} is uncovered; add a test title or symbol before promoting to enforced.`}:{ok:!1,reason:"No coverage evidence supplied for this invariant; evaluate coverage before promoting to enforced."}}i(_n,"canPromoteInvariant");var Nn="1.0";function T(e,t){e.push({id:`${t.classification}:${t.path}:${t.kind}`,path:t.path,classification:t.classification,message:t.message,...t.classification==="weakening"||t.classification==="judgment-required"?{nextAction:`Restore the previous protection at ${t.path}, then run ArkGate again.`}:{},...t.before===void 0?{}:{before:t.before},...t.after===void 0?{}:{after:t.after}})}i(T,"addFinding");function ie(e){return[...new Set(e??[])].sort()}i(ie,"sortedUnique");function de(e,t,n,r,s){let a=ie(n),o=ie(r),l=new Set(a),c=new Set(o),p=o.filter(y=>!l.has(y)),g=a.filter(y=>!c.has(y));p.length===0&&g.length===0||(p.length>0&&T(e,{kind:"added",path:t,classification:s.added,message:s.addedMessage,before:a,after:o}),g.length>0&&T(e,{kind:"removed",path:t,classification:s.removed,message:s.removedMessage,before:a,after:o}))}i(de,"compareStringSets");function lt(e,t,n,r,s,a,o){if(n===r)return;T(e,{kind:r?"enabled":"disabled",path:t,classification:r?s:s==="strengthening"?"weakening":"strengthening",message:r?a:o,before:n,after:r})}i(lt,"compareBoolean");function Pt(e,t){let n=new Map,r=new Set;for(let s of e){let a=t(s);n.has(a)?r.add(a):n.set(a,s)}return{values:n,duplicates:[...r].sort()}}i(Pt,"keyed");function Eo(e,t,n){let r=Pt(t,a=>a.name),s=Pt(n,a=>a.name);(r.duplicates.length>0||s.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:s.duplicates});for(let a of[...new Set([...r.values.keys(),...s.values.keys()])].sort()){let o=r.values.get(a),l=s.values.get(a),c=`$.layers[${a}]`;if(!o&&l){T(e,{kind:"layer-added",path:c,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:l});continue}if(o&&!l){T(e,{kind:"layer-removed",path:c,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:o});continue}if(!o||!l)continue;de(e,`${c}.patterns`,o.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."}),de(e,`${c}.exclude`,o.exclude,l.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let p=Et(o),g=Et(l);de(e,`${c}.forbiddenGlobals`,p.rawGlobals,g.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),de(e,`${c}.capabilities`,p.atoms,g.atoms,{added:"strengthening",removed:"weakening",addedMessage:"Additional ambient/import protection is enforced in this layer (coverage atoms).",removedMessage:"An ambient/import protection was lost from this layer (coverage atoms)."}),ie(o.intentPrefixes).join("\0")!==ie(l.intentPrefixes).join("\0")&&T(e,{kind:"intent-prefixes-changed",path:`${c}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:ie(o.intentPrefixes),after:ie(l.intentPrefixes)}),lt(e,`${c}.mayImportInfrastructure`,o.mayImportInfrastructure===!0,l.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),lt(e,`${c}.optional`,o.optional===!0,l.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active.")}}i(Eo,"compareLayers");function Io(e,t,n){let r=i(o=>`${o.from}->${o.to}`,"keyOf"),s=Pt(t,r),a=Pt(n,r);(s.duplicates.length>0||a.duplicates.length>0)&&T(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:s.duplicates,after:a.duplicates});for(let o of[...new Set([...s.values.keys(),...a.values.keys()])].sort()){let l=s.values.get(o),c=a.values.get(o),p=`$.rules[${o}]`;if(!l&&c){c.allowed===!1&&T(e,{kind:"deny-added",path:p,classification:"strengthening",message:"A denied dependency edge was added.",after:c});continue}if(l&&!c){l.allowed===!1&&T(e,{kind:"deny-removed",path:p,classification:"weakening",message:"A denied dependency edge was removed.",before:l});continue}if(!l||!c)continue;l.allowed!==c.allowed&&T(e,{kind:c.allowed?"deny-disabled":"deny-enabled",path:`${p}.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 g=l.peerIsolation===!0,y=c.peerIsolation===!0;if(g!==y){let f=l.from===l.to&&c.from===c.to;T(e,{kind:y?"peer-isolation-enabled":"peer-isolation-disabled",path:`${p}.peerIsolation`,classification:f?y?"strengthening":"weakening":"judgment-required",message:f?y?"Cross-slice dependencies inside this layer are now denied.":"Cross-slice dependencies inside this layer are no longer denied.":"Changing peer isolation on a cross-layer edge changes the denial scope.",before:g,after:y})}ie(l.sliceFolders).join("\0")!==ie(c.sliceFolders).join("\0")&&T(e,{kind:"slice-folders-changed",path:`${p}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:ie(l.sliceFolders),after:ie(c.sliceFolders)})}}i(Io,"compareRules");function So(e,t,n){let r=t.safety??{},s=n.safety??{};for(let a of["maxTsSuppressions","maxAnyCasts"]){let o=r[a]??0,l=s[a]??0;o!==l&&T(e,{kind:l>o?"threshold-raised":"threshold-lowered",path:`$.safety.${a}`,classification:l>o?"weakening":"strengthening",message:l>o?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:o,after:l})}for(let a of["allowInMemory","allowDisabledPeerIsolation"])lt(e,`$.safety.${a}`,r[a]===!0,s[a]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}i(So,"compareSafety");function xn(e){return e.mode==="enforced"?"enforced":"advisory"}i(xn,"arkRunMode");function Tn(e){return e.mode==="enforced"?"enforced":"advisory"}i(Tn,"arkOrderMode");function bo(e,t,n){let r=t.arkOrder,s=n.arkOrder,a="$.arkOrder";if(!r&&!s)return;if(!r&&s){T(e,{kind:"arkorder-added",path:a,classification:"strengthening",message:`ArkOrder extra was added (${Tn(s)}).`,after:s});return}if(r&&!s){T(e,{kind:"arkorder-removed",path:a,classification:"weakening",message:"ArkOrder extra was removed.",before:r});return}if(!r||!s)return;let o=Tn(r),l=Tn(s);if(o!==l){let c=o==="advisory"&&l==="enforced";T(e,{kind:c?"arkorder-promoted":"arkorder-demoted",path:`${a}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkOrder extra was promoted to enforced.":"ArkOrder extra was demoted to advisory.",before:o,after:l})}de(e,`${a}.planeRoots`,r.planeRoots,s.planeRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkOrder plane roots are governed.",removedMessage:"ArkOrder plane roots were removed and may skip the plane."}),de(e,`${a}.managedLayers`,r.managedLayers,s.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkOrder.",removedMessage:"Layers were removed from ArkOrder management."})}i(bo,"compareArkOrder");function vo(e,t,n){let r=t.arkRun,s=n.arkRun,a="$.arkRun";if(!r&&!s)return;if(!r&&s){T(e,{kind:"arkrun-added",path:a,classification:"strengthening",message:`ArkRun extra was added (${xn(s)}).`,after:s});return}if(r&&!s){T(e,{kind:"arkrun-removed",path:a,classification:"weakening",message:"ArkRun extra was removed.",before:r});return}if(!r||!s)return;let o=xn(r),l=xn(s);if(o!==l){let c=o==="advisory"&&l==="enforced";T(e,{kind:c?"arkrun-promoted":"arkrun-demoted",path:`${a}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkRun extra was promoted to enforced.":"ArkRun extra was demoted to advisory.",before:o,after:l})}de(e,`${a}.compositionRoots`,r.compositionRoots,s.compositionRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkRun composition roots are governed.",removedMessage:"ArkRun composition roots were removed and may skip the kernel."}),de(e,`${a}.managedLayers`,r.managedLayers,s.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkRun.",removedMessage:"Layers were removed from ArkRun management."}),lt(e,`${a}.requireDeclarations`,r.requireDeclarations!==!1,s.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}i(vo,"compareArkRun");function Co(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(Co,"overallClassification");function es(e,t){return`${e}::${t}`}i(es,"ruleKey");function ts(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(es(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(es(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}i(ts,"indexEffectiveRules");function Oo(e,t,n,r,s,a){let o=new Map((a??[]).map(f=>[f.invariantId,f])),l=t.arkRules??{},c=n.arkRules??{},p=[...new Set([...Object.keys(l),...Object.keys(c)])].sort();for(let f of p){let u=l[f],m=c[f],A=`$.arkRules[${f}]`;if(u===void 0&&m!==void 0){T(e,{kind:"arkrules-ref-added",path:A,classification:"strengthening",message:`ArkRules reference for layer ${f} was added.`,after:m});continue}if(u!==void 0&&m===void 0){T(e,{kind:"arkrules-ref-removed",path:A,classification:"weakening",message:`ArkRules reference for layer ${f} was removed.`,before:u});continue}u!==m&&T(e,{kind:"arkrules-ref-path-changed",path:A,classification:"judgment-required",message:`ArkRules file path for layer ${f} changed; verify the effective rules still match intent.`,before:u,after:m})}let g=ts(r),y=ts(s);for(let f of[...new Set([...g.structure.keys(),...y.structure.keys()])].sort()){let u=g.structure.get(f),m=y.structure.get(f),A=`$.arkRules.structure[${f}]`;if(!u&&m){T(e,{kind:"arkrule-structure-added",path:A,classification:"strengthening",message:`Structure ArkRule ${m.id} was added (${m.mode}).`,after:m});continue}if(u&&!m){T(e,{kind:"arkrule-structure-removed",path:A,classification:"weakening",message:`Structure ArkRule ${u.id} was removed.`,before:u});continue}if(!(!u||!m)){if(u.mode!==m.mode){let b=u.mode==="advisory"&&m.mode==="enforced";T(e,{kind:b?"arkrule-promoted":"arkrule-demoted",path:`${A}.mode`,classification:b?"strengthening":"weakening",message:b?`Structure ArkRule ${m.id} was promoted to enforced.`:`Structure ArkRule ${m.id} was demoted to advisory.`,before:u.mode,after:m.mode})}u.sensor!==m.sensor&&T(e,{kind:"arkrule-sensor-changed",path:`${A}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${m.id} changed sensor identity.`,before:u.sensor,after:m.sensor})}}for(let f of[...new Set([...g.invariants.keys(),...y.invariants.keys()])].sort()){let u=g.invariants.get(f),m=y.invariants.get(f),A=`$.arkRules.invariants[${f}]`;if(!u&&m){T(e,{kind:"arkrule-invariant-added",path:A,classification:"strengthening",message:`Invariant ${m.id} was added (${m.mode}).`,after:m});continue}if(u&&!m){T(e,{kind:"arkrule-invariant-removed",path:A,classification:"weakening",message:`Invariant ${u.id} was removed.`,before:u});continue}if(!(!u||!m)&&u.mode!==m.mode)if(u.mode==="advisory"&&m.mode==="enforced"){let N=o?.get(m.id),R=_n(N);R.ok?T(e,{kind:"arkrule-invariant-promoted",path:`${A}.mode`,classification:"strengthening",message:`Invariant ${m.id} was promoted to enforced (coverage evidence present).`,before:u.mode,after:m.mode}):T(e,{kind:"arkrule-invariant-promote-refused",path:`${A}.mode`,classification:"judgment-required",message:`Invariant ${m.id} cannot be promoted to enforced: ${R.reason}`,before:u.mode,after:m.mode})}else T(e,{kind:"arkrule-invariant-demoted",path:`${A}.mode`,classification:"weakening",message:`Invariant ${m.id} was demoted to advisory.`,before:u.mode,after:m.mode})}}i(Oo,"compareArkRules");function Pn(e,t,n){let r=[];de(r,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),de(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."}),de(r,"$.dynamicImportAllowlist",e.dynamicImportAllowlist,t.dynamicImportAllowlist,{added:"weakening",removed:"strengthening",addedMessage:"Additional files may use non-literal dynamic imports.",removedMessage:"Fewer files may use non-literal dynamic imports."}),lt(r,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let s={off:0,soft:1,"framework-soft":1,strict:2},a=e.cyclePolicy??"strict",o=t.cyclePolicy??"strict";if(a!==o){let l=s[o]===s[a]?"judgment-required":s[o]>s[a]?"strengthening":"weakening";T(r,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:l,message:"The cycle enforcement level changed.",before:a,after:o})}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}),Eo(r,e.layers,t.layers),Io(r,e.rules,t.rules),So(r,e,t),Oo(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),vo(r,e,t),bo(r,e,t),r.sort((l,c)=>l.path.localeCompare(c.path)||l.id.localeCompare(c.id)),{schemaVersion:Nn,classification:Co(r),findings:r}}i(Pn,"classifyArkPolicyDelta");function Ln(e,t){if(!e||e.schemaVersion!==Nn||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(s=>typeof s!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=ie(e.findingIds),r=ie(t.findingIds);return n.length===r.length&&n.every((s,a)=>s===r[a])}i(Ln,"policyDeltaAcknowledgementMatches");function Te(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(Te,"normalizePath");function ns(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}i(ns,"isIdentifierStart");function Lt(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}i(Lt,"isIdentifierCharacter");function ae(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}i(ae,"skipWhitespace");function ct(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let r=t,s="";for(t+=1;t<e.length;t+=1){let a=e[t];if(a===n)return{value:s,offset:r,excerpt:e.slice(r,t+1)};a==="\\"&&t+1<e.length?(s+=e[t+1],t+=1):s+=a}}i(ct,"readString");function le(e,t,n){return e.startsWith(t,n)&&!Lt(e[n-1])&&!Lt(e[n+t.length])}i(le,"isWordAt");function rs(e,t){let n=ae(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=ae(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!le(e,"type",n))return!1;let s=ae(e,n+4);if(s>=e.length||e[s]===","||e[s]==="}"||le(e,"as",s)||!ns(e[s]))return!1;for(n=s;n<e.length&&Lt(e[n]);)n+=1;if(n=ae(e,n),le(e,"as",n)){if(n=ae(e,n+2),!ns(e[n]))return!1;for(;n<e.length&&Lt(e[n]);)n+=1}r=!0}return!1}i(rs,"bracedNamedBindingsAreTypeOnly");function _o(e,t){if(t=ae(e,t+6),e[t]==="(")return ct(e,ae(e,t+1));let n=!1;if(le(e,"type",t)){let s=ae(e,t+4);e[s]!==","&&!le(e,"from",s)&&(n=!0)}else rs(e,t)&&(n=!0);let r=ss(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}i(_o,"specifierAfterImport");function xo(e,t){t=t+6;let n=ae(e,t),r=!1;if(le(e,"type",n)){let a=ae(e,n+4);(e[a]==="{"||e[a]==="*")&&(r=!0)}else rs(e,n)&&(r=!0);let s=ss(e,t,!1);return s&&r?{...s,typeOnly:!0}:s}i(xo,"specifierAfterExport");function ss(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(le(e,"from",t))return ct(e,ae(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return ct(e,t);if(t>0&&(le(e,"import",t)||le(e,"export",t)))return}}i(ss,"specifierInStaticStatement");function To(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(To,"skipTemplateLiteral");function No(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=ae(e,t+7);if(e[r]!=="(")return;r=ae(e,r+1);let s=ct(e,r);return s?{...s,requireCall:!0}:void 0}i(No,"specifierAfterRequire");function Po(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="/"&&e[n+1]==="/"){if(n=e.indexOf(`
9
+ `,n+2),n<0)break;continue}if(r==="/"&&e[n+1]==="*"){let a=e.indexOf("*/",n+2);if(a<0)break;n=a+1;continue}if(r==="`"){n=To(e,n);continue}if(r==="'"||r==='"'){let a=ct(e,n);a&&(n=a.offset+a.excerpt.length-1);continue}let s=r==="i"&&le(e,"import",n)?_o(e,n):r==="e"&&le(e,"export",n)?xo(e,n):r==="r"&&le(e,"require",n)?No(e,n):void 0;s&&(t.push(s),n=s.offset+s.excerpt.length-1)}return t}i(Po,"moduleSpecifiers");function as(e,t){let n=[],r=[];for(let s of Po(e.content)){let a=s.value;if(!a.startsWith(".")){if(s.typeOnly)continue;let p=Ye(a);if(!p)continue;let g=e.content.slice(0,s.offset).split(`
10
+ `).length;r.push({file:e.path,symbol:a,capability:p,evidence:{kind:"import",file:e.path,line:g,excerpt:s.excerpt}});continue}let o=e.content.slice(0,s.offset).split(`
11
+ `).length,l={kind:"import",file:e.path,line:o,excerpt:s.excerpt},c=Lo(e.path,a,t);n.push({from:e.path,specifier:a,to:c?.path??null,resolution:c?"resolved":"unresolved",fromLayer:e.layer,toLayer:c?.layer??null,evidence:l})}return{edges:n,capabilityUses:r}}i(as,"moduleFactsFor");function Lo(e,t,n){let r=e.split("/");r.pop();for(let a of t.split("/"))a==="."||a===""||(a===".."?r.pop():r.push(a));let s=r.join("/");for(let a of[s,`${s}.ts`,`${s}.tsx`,`${s}.mts`,`${s}.cts`,`${s}/index.ts`,`${s}/index.tsx`]){let o=n.get(a);if(o)return o}}i(Lo,"resolveSpecifier");function os(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let s=fe(t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});s&&n.push({ruleId:`layer-dependency:${s.from}->${s.to}`,message:s.message??`${s.from} must not depend on ${s.to}.`,edge:r,evidence:r.evidence})}return n}i(os,"violationsFor");var wo={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 Do(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}i(Do,"hasActiveArkRules");function Mo(e,t){return Do(e,t)?X(j(Cn({config:e,arkRules:t,warnings:[]}))):X(j(e))}i(Mo,"policyHashFor");function wt(e,t,n){let r=typeof e=="string"?Rn(e,t):Ct(e,t),s=n?.arkRules??xe();return{...r,arkRules:s,policyHash:Mo(r.config,s)}}i(wt,"loadContract");function is(e){let t=wt(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=wt(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=Pn(t.config,n.config,{baseArkRules:t.arkRules,candidateArkRules:n.arkRules,candidateInvariantCoverage:e.candidateInvariantCoverage}),s=r.findings.filter(l=>l.classification==="weakening"||l.classification==="judgment-required").map(l=>l.id).sort(),a=s.length>0,o=a&&Ln(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:s});return{schemaVersion:r.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:r.classification,findings:r.findings,blockingFindingIds:s,requiresAcknowledgement:a,acknowledged:o,valid:!a||o}}i(is,"analyzePolicyDelta");function dt(e){let t=e.files.map(y=>{let f=Te(y.path);return{path:f,content:y.content,contentHash:X(y.content),layer:ce(f,e.contract.config.layers)??null}}).sort((y,f)=>y.path.localeCompare(f.path)),n=new Map(t.map(y=>[y.path,y])),r=[],s=[];for(let y of t){let f=as(y,n);r.push(...f.edges),s.push(...f.capabilityUses)}let a=os(r,e.contract.config),o=new Map(e.contract.config.layers.map(y=>[y.name,y])),l=new Map(e.contract.config.layers.map(y=>[y.name,new Set(we(y))]));for(let y of s){let f=n.get(y.file)?.layer;if(!f)continue;let u=o.get(f),m=Ie(y.symbol,u?.forbiddenGlobals??[]);if(m){a.push({ruleId:"FORBIDDEN_GLOBAL",message:`${f} must not use module "${y.symbol}" because it is the import form of forbidden global "${m}".`,symbol:y.symbol,evidence:y.evidence});continue}l.get(f)?.has(y.capability)&&a.push({ruleId:"CAPABILITY_VIOLATION",message:`${f} denies the ${y.capability} capability; found import of "${y.symbol}".`,capability:y.capability,symbol:y.symbol,evidence:y.evidence})}let c=t.length===0?"complete":"partial",p=c==="complete"?[]:[{...wo}],g={schemaVersion:In,policyHash:e.contract.policyHash,compilerOptionsHash:X(j(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(y=>y.name),edges:r,capabilityUses:s,violations:a};return{mode:"lexical-compatibility",completeness:c,completenessReasons:p,valid:c==="complete"&&a.length===0,ir:g}}i(dt,"analyzeProject");function Dt(e){let t=new Map(e.files.map(n=>[Te(n.path),n]));for(let n of e.changes){let r=Te(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return dt({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}i(Dt,"analyzeChange");function ls(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(ls,"explainViolation");function wn(e){let t=0,n=new Map,r=new Map,s=new Set,a=[],o=[],l=i(c=>{n.set(c,t),r.set(c,t),t+=1,a.push(c),s.add(c);for(let y of[...e.get(c)??[]].sort())e.has(y)&&(n.has(y)?s.has(y)&&r.set(c,Math.min(r.get(c)??0,n.get(y)??0)):(l(y),r.set(c,Math.min(r.get(c)??0,r.get(y)??0))));if(r.get(c)!==n.get(c))return;let p=[],g;do{if(g=a.pop(),g===void 0)break;s.delete(g),p.push(g)}while(g!==c);p.length>1&&o.push(p.sort())},"connect");for(let c of[...e.keys()].sort())n.has(c)||l(c);return o.sort((c,p)=>c[0]<p[0]?-1:c[0]>p[0]?1:0).map(c=>({ruleId:"CIRCULAR_DEPENDENCY",file:c[0],line:1,target:c.join(" \u2192 "),message:`Circular dependency among ${c.length} files: ${c.join(" \u2192 ")} \u2192 ${c[0]}.`,cycleKind:"value"}))}i(wn,"detectArchitectureCycles");function Ue(e){let t=e.contentViolations.map(a=>({...a})),n=(e.warnings??[]).map(a=>({...a})),r=new Map(e.files.map(a=>[a,new Set]));for(let a of e.edges){if(a.to&&a.to!==a.from&&!a.typeOnly&&r.has(a.from)&&r.get(a.from)?.add(a.to),!a.to||!a.fromLayer||!a.toLayer)continue;let o=fe(e.rules,a.fromLayer,a.toLayer,{fromPath:a.from,toPath:a.to,layers:e.config.layers});if(!o)continue;let l=!!o.peerIsolation,c=!l&&!!(a.typeOnly||a.namedBindingsTypeOnly),p=o.message??(l?`${a.fromLayer} must not ${a.kind} another slice of ${a.toLayer} (${a.from} \u2192 ${a.to}). Extract shared code or use events/ports across slices.`:`${a.fromLayer} must not ${a.kind} ${a.toLayer}.`);t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:a.from,line:a.line,fromLayer:a.fromLayer,toLayer:a.toLayer,target:a.to,...a.typeOnly?{typeOnly:!0}:{},...a.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...a.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...a.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!l&&a.portProofEligible?{portProofEligible:!0}:{},...a.kind?{edgeKind:a.kind}:{},...l?{peerIsolation:!0}:{},message:c?`${p} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:p,...c?{failsStrict:!1,severity:"warning"}:{}})}let s=String(e.config.cyclePolicy??"strict").toLowerCase();if(s!=="off"){let a=wn(r);s==="soft"||s==="framework-soft"?n.push(...a.map(o=>({...o,message:`${o.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...a)}return{violations:t,warnings:n,safety:e.safety}}i(Ue,"evaluateArchitectureGraph");var Fo=["no-anemic-model"];function cs(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(cs,"escapeGlobLiteral");function $o(e){let t="";for(let r=0;r<e.length;r+=1){let s=e[r];if(s==="\\"&&r+1<e.length){let a=e[r+1];if("*?{}[],".includes(a)||a==="\\"){t+="\\"+a,r+=1;continue}t+="/";continue}t+=s}let n="";for(let r=0;r<t.length;r+=1){let s=t[r];s==="\\"&&r+1<t.length?(n+=cs(t[r+1]),r+=1):s==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":s==="?"?n+="[^/]":n+=cs(s)}return new RegExp(`^${n}$`)}i($o,"globToRegExp");function Ge(e,t){return!t||t.length===0?!0:t.some(n=>$o(n).test(e))}i(Ge,"matchesAppliesTo");function Ho(e){return Fo.includes(e)}i(Ho,"isTier2");function ds(e){return e.mode==="enforced"&&!Ho(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}i(ds,"severityFor");function Ne(e,t,n,r=1){let{severity:s,failsStrict:a}=ds(e);return{ruleId:"ARKRULE_STRUCTURE",code:e.sensor,message:n,file:t,line:r,fromLayer:e.provenance.layer,arkruleId:e.id,arkruleSource:e.provenance.sourceFile,severity:s,sensor:e.sensor,failsStrict:a}}i(Ne,"baseViolation");function Mt(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}i(Mt,"isInRuleLayer");function Ft(e,t,n){return t.filter(r=>!(!r.exported||!Ge(r.file,e.appliesTo)||!Mt(r.file,e,n)))}i(Ft,"shapesForRule");function jo(e,t,n){let r=[];for(let s of Ft(e,t,n))(s.hasPublicSetters||s.hasPublicMutableFields)&&r.push(Ne(e,s.file,`Exported class ${s.className} exposes public mutable state (sensor aggregate-private-state).`));return r}i(jo,"evaluateAggregatePrivateState");function Vo(e,t,n){let r=[];for(let s of Ft(e,t,n))if(s.hasPublicConstructor&&!s.hasStaticFactory){if(!(s.hasPublicMutableFields||s.hasPublicSetters||(s.mutatingMethods?.length??0)>0))continue;r.push(Ne(e,s.file,`Exported class ${s.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}return r}i(Vo,"evaluateAlwaysValidFactory");function Ko(e,t,n){let r=[];for(let s of Ft(e,t,n))for(let a of s.mutatingMethods)a.referencesGuardOrPublish||r.push(Ne(e,s.file,`Mutating method ${s.className}.${a.name} does not reference a guard or publish symbol (sensor domain-event-on-mutation).`));return r}i(Ko,"evaluateDomainEventOnMutation");function Uo(e,t){let n=[];for(let r of t.files)Ge(r,e.appliesTo)&&Mt(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(Ne(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}i(Uo,"evaluateOrchestrationOnly");function Go(e,t){let n=[];for(let r of t.files)Ge(r,e.appliesTo)&&Mt(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(Ne(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}i(Go,"evaluateThinAdapter");function Bo(e,t){let n=[];for(let r of t.files)Ge(r,e.appliesTo)&&Mt(r,e,t.layerForFile)&&t.fileHints?.[r]?.persistenceWrite&&n.push(Ne(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(Bo,"evaluateWritesViaAggregate");function zo(e,t,n){let r=[];for(let s of Ft(e,t,n))if(s.dataOnly===!0){let a=Ne(e,s.file,`Exported type ${s.className} looks data-only / anemic (sensor no-anemic-model; advisory only).`);r.push({...a,severity:"warning",failsStrict:!1})}return r}i(zo,"evaluateNoAnemicModel");function Dn(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(...jo(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...Vo(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...Ko(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...Uo(n,e));break;case"thin-adapter":t.push(...Go(n,e));break;case"writes-via-aggregate":t.push(...Bo(n,e));break;case"no-anemic-model":t.push(...zo(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(Dn,"evaluateArkRuleSensors");function Mn(e,t){let n=[],r=t.map(s=>s.replace(/\\/g,"/"));for(let s of e.structure){if(!s.appliesTo||s.appliesTo.length===0||r.some(c=>Ge(c,s.appliesTo)))continue;let{severity:o,failsStrict:l}=ds(s);n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule structure "${s.id}" appliesTo matched zero governed files (patterns: ${s.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:s.provenance.sourceFile,line:1,fromLayer:s.provenance.layer,arkruleId:s.id,arkruleSource:s.provenance.sourceFile,severity:o,sensor:s.sensor,failsStrict:l})}for(let s of e.invariants??[]){if(!s.appliesTo||s.appliesTo.length===0||r.some(l=>Ge(l,s.appliesTo)))continue;let o=s.mode==="enforced";n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule invariant "${s.id}" appliesTo matched zero governed files (patterns: ${s.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:s.provenance.sourceFile,line:1,fromLayer:s.provenance.layer,arkruleId:s.id,arkruleSource:s.provenance.sourceFile,severity:o?"error":"warning",sensor:"invariant-coverage",failsStrict:o})}return n.sort((s,a)=>s.file.localeCompare(a.file)||s.arkruleId.localeCompare(a.arkruleId)||s.message.localeCompare(a.message))}i(Mn,"collectEmptyAppliesToFindings");var qo=/\bfrom\s+['"](?:@?prisma\/client|@supabase\/|drizzle-orm|typeorm|knex|mongodb|pg|mysql2|mongoose|better-sqlite3|ioredis|redis|kysely|sequelize)['"]|require\(\s*['"](?:@?prisma\/client|pg|knex|typeorm|mongoose)/,Wo=/\.(?: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,Yo=/\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*=)/,Xo=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,Jo=/\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*=/,Zo=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function us(e,t){if(!t||t.length<40)return null;let n=t.match(new RegExp(Jo.source,"g"))??[],r=t.match(new RegExp(Zo.source,"g"))??[],s=(t.match(/\bif\s*\(/g)??[]).length,a=(t.match(/\bswitch\s*\(/g)??[]).length,o=n.length>=2||n.length>=1&&r.length>=2||r.length>=3&&s+a>=6,l=qo.test(t),c=Yo.test(t)||Xo.test(t),p=n.length>=1||r.length>=2,g=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),y=l&&p||c&&p||l&&g&&(s>=4||n.length>=1)||c&&l,f=l&&Wo.test(t);return!o&&!y&&!f?null:{...o?{orchestrationHeavy:!0}:{},...y?{adapterThick:!0}:{},...f?{persistenceWrite:!0}:{}}}i(us,"deriveArkRuleFileHints");function Fn(e){let t={};for(let[n,r]of Object.entries(e)){let s=us(n,r);s&&(t[n.replace(/\\/g,"/")]=s)}return t}i(Fn,"buildArkRuleFileHints");function Qo(e,t){let n=[],r=/export\s+(?:abstract\s+)?class\s+([A-Za-z_][A-Za-z0-9_]*)\s*(?:extends\s+[^{]+)?(?:implements\s+[^{]+)?\{/g,s;for(;(s=r.exec(t))!==null;){let a=s[1],o=s.index+s[0].length,l=1,c=o;for(;c<t.length&&l>0;){let D=t[c];D==="{"?l+=1:D==="}"&&(l-=1),c+=1}let p=t.slice(o,c-1),g=p.split(`
12
+ `).map(D=>/^\s*\/\//.test(D)||/^\s*\/\*|\*\//.test(D)?D:D.replace(/(?:public\s+|protected\s+)?readonly\s+[a-zA-Z_][a-zA-Z0-9_]*\s*(?::[^=;]+)?(?:=\s*[^;]+)?[;,]?/g,"").replace(/(?:^|[\s;{])readonly\s+[a-zA-Z_][a-zA-Z0-9_]*\s*(?::[^=;]+)?(?:=\s*[^;]+)?[;,]?/g," ")).join(`
13
+ `),y=/(?:^|\n)\s*(?:public\s+)?[a-zA-Z_][a-zA-Z0-9_]*\s*[:=]/m.test(g.replace(/(?:public\s+|private\s+|protected\s+|static\s+|async\s+|get\s+|set\s+)/g,""))&&/(?:^|\n)\s*(public\s+)?(?!constructor|static|get|set|private|protected|readonly)[a-zA-Z_][a-zA-Z0-9_]*\s*[:=]/m.test(g),f=/(?:^|\n)\s*public\s+(?!static|async|get|set|constructor|readonly)[a-zA-Z_]/.test(g)||/(?:^|[\n;])\s*[a-zA-Z_][a-zA-Z0-9_]*\s*:\s*[^=;\n]+[;=]/m.test(g.split(`
14
+ `).filter(D=>!/^\s*(private|protected|static|constructor|get |set |async |\/)/.test(D)).join(`
15
+ `)),u=/(?:^|[\n;{])\s*(?:public\s+)?set\s+[a-zA-Z_]/.test(p),m=/(?:^|[\n;{])\s*private\s+constructor\s*\(/.test(p),A=/(?:^|[\n;{])\s*(?:public\s+)?constructor\s*\(/.test(p)&&!m,b=/(?:^|[\n;{])\s*static\s+(?:async\s+)?(?:create|of|from|parse|build|make|new)\s*[<(]/.test(p)||/(?:^|[\n;{])\s*static\s+(?:async\s+)?[A-Za-z_][A-Za-z0-9_]*\s*\([^)]*\)\s*:\s*[A-Za-z_]/.test(p),N=[],R=new Set(["if","match","when"]),I=/(?:^|\n)\s*(?:public\s+|private\s+|protected\s+|async\s+)*(?!constructor|get|set|static)([a-zA-Z_][a-zA-Z0-9_]*)\s*\([^)]*\)\s*(?::\s*[^{]+)?\{/g,C;for(;(C=I.exec(p))!==null;){let D=C[1];if(R.has(D))continue;let x=C.index+C[0].length,$=1,w=x;for(;w<p.length&&$>0;)p[w]==="{"?$+=1:p[w]==="}"&&($-=1),w+=1;let ee=p.slice(x,w-1);if(!/this\.\w+\s*=/.test(ee))continue;let Le=/\b(ensureInvariants|assertInvariants|validate|publish|emit|raise|record)\b/.test(ee);N.push({name:D,referencesGuardOrPublish:Le})}let Y=(p.match(/(?:^|\n)\s*(?:public\s+|private\s+|protected\s+)?(?:async\s+)?[a-zA-Z_][a-zA-Z0-9_]*\s*\(/g)??[]).length,k=(g.match(/(?:^|[\n;])\s*(?:public\s+)?(?!constructor|static|get|set|private|protected|readonly)[a-zA-Z_][a-zA-Z0-9_]*\s*[:=]/g)??[]).length,L=Y<=1&&k>=2&&(f||y);n.push({file:e,className:a,exported:!0,hasPublicMutableFields:f||y,hasPublicSetters:u,hasPublicConstructor:A,hasStaticFactory:b,mutatingMethods:[...N],dataOnly:L})}return n}i(Qo,"extractClassShapesFromSource");var ei=50;function $n(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($n,"normalizeExtraMergeTeethClassification");function Re(e){let t=$n(e),n=typeof t.governedPercent=="number"?t.governedPercent:null,r=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null;return n==null&&r==null?!0:(n??0)>=50&&(r??0)>=1}i(Re,"extraMergeTeethAllowed");function Hn(e){let t=e.length,n=0,r=new Set;for(let s of e){let a=typeof s.layer=="string"&&s.layer.length>0?s.layer:null;a&&(n+=1,r.add(a))}return{governedPercent:t>0?Math.round(n/t*100):0,populatedLayerCount:r.size}}i(Hn,"classifyResolvedLayerCoverage");function jn(e){return typeof e=="string"&&e.startsWith("ARKRUN_")}i(jn,"isArkRunRuleId");function ti(e){return typeof e=="string"&&e.startsWith("ARKORDER_")}i(ti,"isArkOrderRuleId");function ps(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(ps,"isExtraPlaneFinding");function ni(e,t={}){if(!Array.isArray(e)||Re(t))return e;for(let n of e)ps(n)&&n.failsStrict!==!1&&(n.failsStrict=!1,n.severity==="error"&&(n.severity="warning"));return e}i(ni,"demoteExtraPlaneTeethUnderClassificationFloor");var fs="Structure = heuristics; invariants = catalog+coverage evidence (not business runtime); ArkRun = kernel usage + declarations (not a score); ArkOrder = pattern slaving (not a score). Extra planes never merge into one architecture score. Advisory ArkRules \u2260 merge teeth. Advisory ArkRun \u2260 merge teeth. Advisory ArkOrder \u2260 merge teeth.";function Ae(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):0}i(Ae,"countOrZero");function Vn(e={}){let t=$n(e.classification),n=typeof t.governedPercent=="number"?t.governedPercent:null,r=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null,s=n!=null||r!=null,a=Re(t),o=e.arkRules,l=Ae(o?.structureEnforced),c=Ae(o?.structureTotal),p=typeof o?.structureAdvisory=="number"?Ae(o.structureAdvisory):Math.max(0,c-l),g=Ae(o?.invariantEnforced),y=Ae(o?.invariantTotal),f=typeof o?.invariantAdvisory=="number"?Ae(o.invariantAdvisory):Math.max(0,y-g),u=l>0||g>0,m=e.arkRun?.present===!0,A=e.arkRun?.mode==="enforced"||e.arkRun?.mode==="advisory"?e.arkRun.mode:null,b=Ae(e.arkRun?.residualCount),N=m&&A==="enforced",R=N&&a,I=u||N,C=I&&a,Y=I&&s&&!a,k;if(C){let D=[];u&&D.push("enforced structure/invariant findings"),N&&D.push("enforced ArkRun skip findings"),k=`Layer graph failures plus ${D.join(" and ")} (advisory extras never fail merge alone).`}else Y?k=`Layer graph only \u2014 enforced ${[u?"ArkRules structure/invariant":null,N?"ArkRun":null].filter(x=>!!x).join(" and ")} findings are demoted under the teeth floor (need \u226550% governed and \u22651 populated layer); they do not merge-block until classification is honest.`:k="Layer graph only \u2014 no enforced ArkRules structure/invariant teeth on this tree. Advisory packs do not arm merge teeth."+(m?A==="advisory"?" Advisory ArkRun never merge-blocks.":" ArkRun extra is present but does not arm merge teeth.":" Absence of arkRun is silent.");let L={layers:{role:"inter-layer-edges",alwaysOnGate:!0,note:"Import/export layer graph \u2014 the default merge plane. Absent arkRules or arkRun changes nothing here."},structureSensors:{role:"intra-layer-heuristics",total:c,enforced:l,advisory:p,note:"Structure sensors are heuristics (prefer false negatives). Only mode:enforced fails merge; noisy sensors stay advisory by default. Advisory-only packs never add merge teeth (FG-ARKRULES-ADVISORY-ONLY)."},invariants:{role:"catalog-plus-coverage",total:y,enforced:g,advisory:f,covered:Ae(o?.covered),uncovered:Ae(o?.uncovered),note:"Invariants are catalog + coverage evidence, not a business runtime. Enforced + proven-uncovered fails merge; absence of enforced rules adds no extra teeth."},arkRun:{role:"kernel-usage-and-declarations",present:m,mode:A,residualCount:b,extraMergeTeeth:R,note:m?A==="enforced"?"Enforced ArkRun arms extra merge teeth only when the layer plane is classified. Residual is a count, never a score.":"Advisory ArkRun never adds merge teeth and never flips valid. Residual is a count, never a score.":"Absence of arkRun is silent \u2014 Layers and ArkRules verdicts unchanged. The extra never becomes a score."},extraMergeTeeth:C,dualPlaneStamp:fs,failMergeWhen:k};return s&&(L.classificationGate={governedPercent:n,populatedLayerCount:r,floorPercent:50,allowsTeeth:a}),L}i(Vn,"composeMergePlanesHonesty");var gs=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"],ri=["publisher","publish","raise","raiseAsync","send","sendTo","subscribe","registerHandler","resolve","resolveSingleton"],si=new Set(gs),ai=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"]),oi=new Set(["Array","Atomics","Buffer","JSON","Math","Number","Object","Promise","Reflect","String","console","fs","path","url","util"]);function ft(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")}i(ft,"isArkRunKernelModuleSpecifier");var ys=["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"],Kn=new Set(ys);function Gn(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(Kn.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(Kn.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:Kn.has(e.slice(0,r))}i(Gn,"isArkRunTransportBypassSpecifier");function Un(e){if(si.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(Un,"arkRunKernelCallKind");function pt(e,t){let n=1;for(let r=0;r<t;r+=1)e.charCodeAt(r)===10&&(n+=1);return n}i(pt,"lineAt");function mt(e){return e.replace(/\/\*[\s\S]*?\*\//g,t=>t.replace(/[^\n]/g," ")).replace(/(^|[^:\\])\/\/.*$/gm,t=>t.replace(/\/\/.*$/,n=>" ".repeat(n.length)))}i(mt,"stripCommentsPreservingLines");function ii(e,t){let n=e.slice(t),r=/^\s*(['"])((?:\\.|[^\\])*?)\1/.exec(n);if(!r)return;let s=r[2]??"";return s.length>0?s:void 0}i(ii,"firstStringLiteralArg");function ms(e,t,n){let r=Math.max(0,t-n.length-8),s=e.slice(r,t);return new RegExp(`\\b${n}\\s+$`).test(s)}i(ms,"keywordBefore");function $t(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($t,"parseValueImportClause");function li(e,t){$t(mt(e),t)}i(li,"forEachArkRunValueImportClause");function Bn(e,t){let n=mt(t),r=[],s=/\b(?:import|export)(\s+type)?\s+([\s\S]*?)\s+from\s*['"]([^'"]+)['"]/g,a;for(;(a=s.exec(n))!==null;){let l=a[3]??"";if(!l)continue;let c=a[0]??"";r.push({from:e,specifier:l,kind:/^\s*export/.test(c)?"export":"import",typeOnly:!!a[1],line:pt(t,a.index),resolution:"resolved-external"})}let o=/\b(?:require|import)\s*\(\s*['"]([^'"]+)['"]\s*\)/g;for(;(a=o.exec(n))!==null;){let l=a[1]??"";if(!l)continue;let c=a[0]?.startsWith("import")?"dynamic-import":"require";r.push({from:e,specifier:l,kind:c,typeOnly:!1,line:pt(t,a.index),resolution:"resolved-external"})}return r}i(Bn,"extractArkRunValueImportDependenciesFromSource");function zn(e){let t=[];return li(e,n=>{let r=/\{([^}]*)\}/.exec(n);if(r?.[1])for(let s of r[1].split(",")){let a=s.trim();if(!a||a.startsWith("type "))continue;let o=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(a),l=o?.[2]??/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(a)?.[1],c=o?.[1]??l;l&&c&&/^[A-Z]/.test(c)&&t.push(l,c)}}),ut(t)}i(zn,"extractArkRunImportedConstructorNamesFromSource");function ci(e){let t=new Map,n=new Set;return $t(e,(r,s)=>{if(!ft(s))return;let a=/\*\s+as\s+([A-Za-z_][A-Za-z0-9_]*)/.exec(r);a?.[1]&&n.add(a[1]);let o=/^([A-Za-z_][A-Za-z0-9_]*)\s*(?:,|$)/.exec(r.trim());o?.[1]&&t.set(o[1],o[1]);let l=/\{([^}]*)\}/.exec(r);if(l?.[1])for(let c of l[1].split(",")){let p=c.trim();if(!p||p.startsWith("type "))continue;let g=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(p);if(g){t.set(g[2],g[1]);continue}let y=/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(p);y?.[1]&&t.set(y[1],y[1])}}),{named:t,namespaces:n}}i(ci,"collectKernelImportBindings");function di(e,t){let n=new Set(t);return $t(e,(r,s)=>{let a=/\{([^}]*)\}/.exec(r);if(a?.[1])for(let o of a[1].split(",")){let l=o.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),p=c?.[2]??/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(l)?.[1],g=c?.[1]??p;!p||!g||!/^[A-Z]/.test(g)||(ft(s)||t.has(g)||t.has(p))&&(n.add(p),n.add(g))}}),n}i(di,"collectImportedConstructors");function ui(e,t){let n;return $t(e,(r,s)=>{!n&&new RegExp(`\\b${t}\\b`).test(r)&&(n=s)}),n}i(ui,"importedFromForName");function qn(e,t){let n=mt(t),r=ci(n),s=[],a=/\b([A-Za-z_][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,o;for(;(o=a.exec(n))!==null;){let l=o[1],c=o.index;if(ms(n,c,"function")||ms(n,c,"class"))continue;let g=n.slice(0,c).match(/([A-Za-z_][A-Za-z0-9_]*)\s*\.\s*$/)?.[1],y=r.named.get(l)??l,f=Un(y)??Un(l);if(!f)continue;let u=r.named.has(l)||g!==void 0&&r.namespaces.has(g);if(f!=="factory"&&(!u&&g===void 0||g&&oi.has(g)&&!u))continue;let m=ii(n,c+o[0].length);s.push({file:e,line:pt(t,c),kind:f,callee:l,viaImport:u,...g?{receiver:g}:{},...m?{nameLiteral:m}:{}})}return s}i(qn,"extractArkRunKernelCallsFromSource");function Wn(e,t,n){let r=mt(t),s=di(r,n),a=[],o=/\bnew\s+(?:[A-Za-z_][A-Za-z0-9_]*\s*\.\s*)*([A-Z][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,l;for(;(l=o.exec(r))!==null;){let c=l[1];if(ai.has(c)||!s.has(c))continue;let p=ui(r,c);a.push({file:e,line:pt(t,l.index),typeName:c,...p?{importedFrom:p}:{}})}return a}i(Wn,"extractArkRunManagedNewsFromSource");function pi(e,t){let n=0,r;for(let s=t;s<e.length;s+=1){let a=e[s];if(r){if(a==="\\"){s+=1;continue}a===r&&(r=void 0);continue}if(a==="'"||a==='"'||a==="`"){r=a;continue}if(a==="[")n+=1;else if(a==="]"&&(n-=1,n===0))return s}return-1}i(pi,"matchingBracketEnd");function fi(e,t,n){let r=e.slice(t+1,n),s=[],a=/(['"])((?:\\.|[^\\])*?)\1/g,o;for(;(o=a.exec(r))!==null;){let l=o[2]??"";l.length>0&&s.push(l)}return s}i(fi,"stringLiteralsInList");function ut(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}i(ut,"uniqueSorted");function mi(e,t){let n=mt(t),r=/\b(uses|reactsTo|raises|sends)\s*:/g,s=[],a=[],o=[],l=[],c,p;for(;(p=r.exec(n))!==null;){let g=n.slice(p.index+p[0].length),y=/^\s*\[/.exec(g);if(!y)continue;let f=p.index+p[0].length+(y[0].length-1),u=pi(n,f);if(u<0)continue;let m=fi(n,f,u);if(m.length===0)continue;c===void 0&&(c=p.index);let A=p[1];A==="uses"?s.push(...m):A==="reactsTo"?a.push(...m):A==="raises"?o.push(...m):l.push(...m)}return c===void 0?[]:[{file:e,line:pt(t,c),uses:ut(s),reactsTo:ut(a),raises:ut(o),sends:ut(l)}]}i(mi,"extractArkRunDeclarationsFromSource");var gi=["arkrun-missing-root","arkrun-kernel-in-domain","arkrun-direct-new","arkrun-undeclared-emit","arkrun-undeclared-handle","arkrun-undeclared-depend","arkrun-transport-bypass"],yi=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],hi=new Set(yi);function Ai(e){return hi.has(e)}i(Ai,"isArkRunEditorSensor");var Yn={"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"},Rs="ARKRUN_INTERACTION_NAME_INCOMPLETE";function ks(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)||/^(?:entit(?:y|ies)|aggregates?)(?:$|(?=[A-Z_\-\s]))/i.test(n)?!0:t.some(r=>{let s=r.trim().replace(/\.+$/,"");return s==="Domain"||s.startsWith("Domain.")})}i(ks,"isDomainRoleLayer");function Ri(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}i(Ri,"compareFindings");function ke(e,t,n,r,s,a,o){let l=e.mode==="enforced"&&o;return{ruleId:Yn[t],sensor:t,message:s,file:n,line:r,...a?.fromLayer?{fromLayer:a.fromLayer}:{},...a?.target?{target:a.target}:{},severity:l?"error":"warning",failsStrict:l,nextAction:pe({ruleId:Yn[t],fromLayer:a?.fromLayer,target:a?.target})}}i(ke,"finding");function ki(e,t){let n=[],r=[],s=[],a=[];for(let o of e)o.file===t&&(n.push(...o.uses),r.push(...o.reactsTo),s.push(...o.raises),a.push(...o.sends));return{uses:new Set(n),reactsTo:new Set(r),raises:new Set(s),sends:new Set(a)}}i(ki,"bagForFile");function hs(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}i(hs,"emitKinds");function As(e){return e==="subscribe"||e==="register-handler"}i(As,"handleKinds");function Ei(e){return e==="resolve"||e==="resolve-singleton"}i(Ei,"dependKinds");function Ii(e,t,n){let r=[],s=e.kernelRoots??e.compositionRoots;if(s.length===0)return r.push(ke(e,"arkrun-missing-root","ark.config.json",1,"ArkRun kernelRoots is empty; no createArkKernel factory site is declared.",void 0,n)),r;let a=new Map;for(let o of t){let l=a.get(o.matchedRoot)??[];l.push(o),a.set(o.matchedRoot,l)}for(let o of s){let l=[...a.get(o)??[]].sort((p,g)=>p.file.localeCompare(g.file));if(l.length===0){r.push(ke(e,"arkrun-missing-root","ark.config.json",1,`ArkRun kernel root ${JSON.stringify(o)} matched no governed files and has no createArkKernel factory.`,{target:o},n));continue}if(l.some(p=>p.hasKernelFactory))continue;let c=l[0];r.push(ke(e,"arkrun-missing-root",c.file,1,`ArkRun kernel root ${JSON.stringify(o)} has no createArkKernel / createStrictArkKernel factory.`,{target:o},n))}return r}i(Ii,"evaluateMissingRoot");function Si(e,t,n,r,s){let a=new Map(t.map(l=>[l.name,l.intentPrefixes??[]])),o=[];for(let l of n){let c=l.specifier;if(!c||!ft(c))continue;let p=r(l.from);p&&ks(p,a.get(p)??[])&&o.push(ke(e,"arkrun-kernel-in-domain",l.from,l.line,`${p} must not import kernel module ${JSON.stringify(c)}.`,{fromLayer:p,target:c},s))}return o}i(Si,"evaluateKernelInDomain");function bi(e,t,n,r,s,a){let o=new Set(e.managedLayers);if(o.size===0)return[];let l=new Map(t.map(g=>[g.name,g.intentPrefixes??[]])),c=new Set(r.filter(g=>g.hasKernelFactory).map(g=>g.file)),p=[];for(let g of n){if(c.has(g.file))continue;let y=g.typeName;if(e.ignoreDirectNewForErrors!==!1&&(y.endsWith("Error")||y==="Error")||y.endsWith("DTO")||y.endsWith("VO"))continue;let f=s(g.file);!f||!o.has(f)||ks(f,l.get(f)??[])||p.push(ke(e,"arkrun-direct-new",g.file,g.line,`${f} must not construct ${g.typeName} with new outside an ArkRun composition-root factory.`,{fromLayer:f,target:g.typeName},a))}return p}i(bi,"evaluateDirectNew");function vi(e,t,n,r,s){let a=[],o=[];if(e.requireDeclarations!==!0)return{findings:a,completenessReasons:o};let l=new Set(e.managedLayers);if(l.size===0)return{findings:a,completenessReasons:o};for(let c of t){if(!hs(c.kind)&&!As(c.kind)&&!Ei(c.kind))continue;let p=r(c.file);if(!p||!l.has(p))continue;if(!c.nameLiteral){e.mode==="enforced"&&o.push({code:Rs,file:c.file,message:`ArkRun ${c.kind} call in ${c.file} has no string-literal name; enforced extra cannot prove the declaration.`});continue}let g=ki(n,c.file);if(hs(c.kind)){if(g.raises.has(c.nameLiteral)||g.sends.has(c.nameLiteral))continue;a.push(ke(e,"arkrun-undeclared-emit",c.file,c.line,`Emit ${JSON.stringify(c.nameLiteral)} is not declared in raises or sends.`,{fromLayer:p,target:c.nameLiteral},s));continue}if(As(c.kind)){if(g.reactsTo.has(c.nameLiteral))continue;a.push(ke(e,"arkrun-undeclared-handle",c.file,c.line,`Handle ${JSON.stringify(c.nameLiteral)} is not declared in reactsTo.`,{fromLayer:p,target:c.nameLiteral},s));continue}g.uses.has(c.nameLiteral)||a.push(ke(e,"arkrun-undeclared-depend",c.file,c.line,`Depend ${JSON.stringify(c.nameLiteral)} is not declared in uses.`,{fromLayer:p,target:c.nameLiteral},s))}return{findings:a,completenessReasons:o}}i(vi,"evaluateUndeclared");function Ci(e,t,n,r){let s=new Set(e.managedLayers);if(s.size===0)return[];let a=[];for(let o of t){if(o.typeOnly)continue;let l=o.specifier;if(!l||!Gn(l))continue;let c=n(o.from);!c||!s.has(c)||a.push(ke(e,"arkrun-transport-bypass",o.from,o.line,`${c} must not import broker/queue/emitter ${JSON.stringify(l)}; use the ArkRun kernel transport.`,{fromLayer:c,target:l},r))}return a}i(Ci,"evaluateTransportBypass");function Ht(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=Re(e.classification),r=vi(t,e.kernelCalls,e.declarations,e.layerForFile,n),s=[...Ii(t,e.compositionRootHits,n),...Si(t,e.layers,e.dependencies,e.layerForFile,n),...bi(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...Ci(t,e.dependencies,e.layerForFile,n)].sort(Ri),a=[...r.completenessReasons].sort((o,l)=>{let c=`${o.code}\0${o.file??""}\0${o.message}`,p=`${l.code}\0${l.file??""}\0${l.message}`;return c<p?-1:c>p?1:0});return{findings:s,completenessReasons:a}}i(Ht,"evaluateArkRunSensors");function Es(e){return{findings:Ht(e).findings.filter(n=>Ai(n.sensor)),completenessReasons:[]}}i(Es,"evaluateArkRunEditorSensors");function Oi(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(Oi,"fileMatchesCompositionRoot");function _i(e,t,n){let r=qn(t,n).some(o=>o.kind==="factory"),s=[],a=e.kernelRoots??e.compositionRoots;for(let o of a)Oi(o,t)&&s.push({file:t,matchedRoot:o,hasKernelFactory:r});return s}i(_i,"compositionRootHitsForSource");function xi(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=new Set(zn(e.source));return Es({arkRun:t,layers:e.layers,kernelCalls:[],managedNews:Wn(e.file,e.source,n),compositionRootHits:_i(t,e.file,e.source),declarations:[],dependencies:Bn(e.file,e.source),layerForFile:e.layerForFile,classification:e.classification})}i(xi,"evaluateArkRunEditorSensorsFromSource");function Is(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}i(Is,"isArkOrderModuleSpecifier");var Ti=["arkorder-missing-plane","arkorder-kernel-in-domain","arkorder-generic-update","arkorder-too-many-params","arkorder-ingest-writes-xi","arkorder-xi-field-write"],Xn={"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"};function Ni(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)?!0:t.some(r=>{let s=r.trim().replace(/\.+$/,"");return s==="Domain"||s.startsWith("Domain.")})}i(Ni,"isDomainRoleLayer");function Ee(e,t,n,r,s,a,o){let l=e.mode==="enforced"&&o;return{ruleId:Xn[t],sensor:t,message:s,file:n,line:r,...a?.fromLayer?{fromLayer:a.fromLayer}:{},...a?.target?{target:a.target}:{},severity:l?"error":"warning",failsStrict:l,nextAction:pe({ruleId:Xn[t],fromLayer:a?.fromLayer,target:a?.target})}}i(Ee,"finding");function Jn(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let n=Re(e.classification),r=[],s=t.planeRoots;if(t.mode==="enforced"&&s.length===0)r.push(Ee(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 p of e.planeRootHits){let g=c.get(p.matchedRoot)??[];g.push(p),c.set(p.matchedRoot,g)}for(let p of s){let g=c.get(p)??[];if(g.length===0){r.push(Ee(t,"arkorder-missing-plane","ark.config.json",1,`ArkOrder plane root ${JSON.stringify(p)} matched no governed files and has no createOrderPlane factory.`,{target:p},n));continue}g.some(y=>y.hasPlaneFactory)||r.push(Ee(t,"arkorder-missing-plane",g[0].file,1,`ArkOrder plane root ${JSON.stringify(p)} has no createOrderPlane factory.`,{target:p},n))}}let a=new Map(e.layers.map(c=>[c.name,c.intentPrefixes??[]]));for(let c of e.dependencies){let p=c.specifier;if(!p||!Is(p))continue;let g=e.layerForFile(c.from);g&&Ni(g,a.get(g)??[])&&r.push(Ee(t,"arkorder-kernel-in-domain",c.from,c.line,"Domain-role layer imports arkgate/order; Domain stays plane-free.",{fromLayer:g,target:p},n))}for(let c of e.genericUpdates)r.push(Ee(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 o=t.xiKeys??[];o.length>t.maxXiKeys&&r.push(Ee(t,"arkorder-too-many-params","ark.config.json",1,`arkOrder.xiKeys has ${o.length} keys; maxXiKeys is ${t.maxXiKeys} (few slow modes).`,{target:String(o.length)},n));for(let c of e.releaseKeyCounts??[])c.keyCount<=t.maxXiKeys||r.push(Ee(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(Ee(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 o.length===0?[]:e.xiFieldWrites??[]){let p=e.layerForFile(c.file);!p||!l.has(p)||r.push(Ee(t,"arkorder-xi-field-write",c.file,c.line,`File writes slow key ${JSON.stringify(c.key)} through a persistence driver; route the field through ingest or a pattern change through proposeRelease.`,{fromLayer:p,target:c.key},n))}return r.sort((c,p)=>c.file.localeCompare(p.file)||c.ruleId.localeCompare(p.ruleId)||c.line-p.line),{findings:r,completenessReasons:[]}}i(Jn,"evaluateArkOrderSensors");function ne(e,t,n={}){return{ruleId:e,message:t,...n}}i(ne,"configWarning");function jt(e){let{config:t,rules:n,files:r,manifest:s}=e,a=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(u=>typeof u!="string"))&&a.push(ne("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","dynamicImportAllowlist must be an array of file globs.")),t.safety!==void 0&&(t.safety===null||typeof t.safety!="object"||Array.isArray(t.safety)))a.push(ne("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let u of["maxTsSuppressions","maxAnyCasts"]){let m=t.safety[u];m!==void 0&&(!Number.isInteger(m)||m<0)&&a.push(ne("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${u} must be a non-negative integer.`))}let o=Array.isArray(t.layers)?t.layers:[],l=Array.isArray(s?.architecture?.layers)?s.architecture.layers:[],c=new Set([...o.map(u=>u.name).filter(Boolean),...l.map(u=>u.name).filter(u=>!!u)]);o.length===0&&a.push(ne("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let p=new Set,g=new Set;for(let u of o){if(!u.name){a.push(ne("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}p.has(u.name)&&g.add(u.name),p.add(u.name),u.forbiddenGlobals!==void 0&&(!Array.isArray(u.forbiddenGlobals)||u.forbiddenGlobals.some(A=>typeof A!="string"))&&a.push(ne("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${u.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:u.name}));let m=Array.isArray(u.patterns)?u.patterns:[];if(m.length===0){a.push(ne("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${u.name}" has no file patterns and will never classify files.`,{layer:u.name}));continue}for(let A of m){let b;try{b=ve(A)}catch(R){a.push(ne("CONFIG_INVALID_LAYER_PATTERN",`Layer "${u.name}" has an invalid pattern "${A}": ${R instanceof Error?R.message:String(R)}`,{layer:u.name,pattern:A}));continue}let N=u.optional===!0||u.reserved===!0||u.allowEmpty===!0;!r.some(R=>b.test(R))&&!N&&a.push(ne("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${u.name}" pattern "${A}" matched no included files (possible typo). Mark the layer reserved/allowEmpty if this house is reserved for later.`,{layer:u.name,pattern:A,failsStrict:!1,reserved:!1}))}}for(let u of g)a.push(ne("CONFIG_DUPLICATE_LAYER",`Layer "${u}" is configured more than once.`,{layer:u}));if(c.size>0)for(let u of n??[])u.from&&!c.has(u.from)&&a.push(ne("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${u.from}".`,{fromLayer:u.from,toLayer:u.to})),u.to&&!c.has(u.to)&&a.push(ne("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${u.to}".`,{fromLayer:u.from,toLayer:u.to}));let y=new Set;if(o.length>1)for(let u of r){let m=-1,A=[];for(let b of o)for(let N of b.patterns??[]){if(!ve(N).test(u))continue;let R=dn(N,u);R>m?(m=R,A=[b.name]):R===m&&!A.includes(b.name)&&A.push(b.name)}A.length>1&&y.add([...A].sort().join(" + "))}y.size>0&&a.push(ne("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...y].join(", ")}.`,{pairs:[...y]}));let f=r.filter(u=>!ce(u,o));return f.length>0&&a.push(ne("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)})),a}i(jt,"collectAnalysisConfigWarnings");function Pi(e,t){return t.some(n=>{try{return ve(n).test(e)}catch{return!1}})}i(Pi,"matchesAny");function Li(e,t){let n=e.contract.config.safety??{},r=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,s=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,a=e.contract.config.dynamicImportAllowlist??[],o=t.safetyUses.filter(A=>A.kind==="ts-suppression").map(({file:A,line:b})=>({file:A,line:b})),l=t.safetyUses.filter(A=>A.kind==="any-cast").map(({file:A,line:b})=>({file:A,line:b})),c=t.safetyUses.filter(A=>(A.kind==="dynamic-import"||A.kind==="dynamic-require")&&!Pi(A.file,a)).map(A=>({file:A.file,line:A.line,kind:A.kind==="dynamic-require"?"require":"import"})),p=n.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(A=>A.kind==="in-memory-store").map(A=>({file:A.file,line:A.line,store:A.symbol??"in-memory store"})),g=n.allowDisabledPeerIsolation===!0?[]:(e.contract.config.rules??[]).filter(A=>A.peerIsolation===!1||A.allowed===!1&&!!A.from&&A.from===A.to&&A.peerIsolation!==!0).map(A=>({from:A.from,to:A.to})),y={tsSuppressions:o,anyCasts:l,nonLiteralDynamicImports:c,inMemoryProductionStores:p,disabledPeerIsolationRules:g,thresholds:{maxTsSuppressions:r,maxAnyCasts:s}},f=[],u=c.filter(A=>A.kind==="import");if(u.length>0){let A=u[0];f.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:A.file,line:A.line,message:`${u.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let m=c.filter(A=>A.kind==="require");if(m.length>0){let A=m[0];f.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:A.file,line:A.line,message:`${m.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(o.length>r){let A=o[0];f.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:A.file,line:A.line,message:`${o.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${r}).`})}if(l.length>s){let A=l[0];f.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:A.file,line:A.line,message:`${l.length} explicit any cast(s) exceed safety.maxAnyCasts (${s}).`})}if(p.length>0){let A=p[0];f.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:A.file,line:A.line,message:`${p.length} ArkGate InMemory store risk(s) appear in governed production source. Provide durable stores or set safety.allowInMemory only for an explicitly ephemeral service.`})}return g.length>0&&f.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${g.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:y,warnings:f}}i(Li,"evaluateSafety");function wi(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}i(wi,"ambientForbiddenGlobal");function Ss(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return yn(e,n.length>0?n:gn.map(r=>({name:r.layer,prefixes:r.prefixes})))}i(Ss,"intentLayer");function Di(e,t,n){let r=[],s=new Map(e.contract.config.layers.map(a=>[a.name,a]));for(let a of t.ambientUses){let o=n.get(a.file);!o||!wi(a.symbol,s.get(o)?.forbiddenGlobals??[])||r.push({ruleId:"FORBIDDEN_GLOBAL",file:a.file,line:a.line,fromLayer:o,target:a.symbol,message:`${o} must not use the ambient global "${a.symbol}".`})}for(let a of t.capabilityUses){let o=n.get(a.file);if(!o)continue;let l=s.get(o),c=l?.forbiddenGlobals??[],p=a.source==="import-based"?t.dependencies.find(g=>g.from===a.file&&g.line===a.line&&g.specifier===a.symbol&&!g.typeOnly)?.kind:void 0;if(!(a.source==="ambient-global"&&Xe(a.symbol,c))){if(a.source==="import-based"){let g=Ie(a.symbol,c);if(g){r.push({ruleId:"FORBIDDEN_GLOBAL",file:a.file,line:a.line,fromLayer:o,target:a.symbol,...p?{edgeKind:p}:{},message:`${o} must not use module "${a.symbol}" because it is the import form of forbidden global "${g}".`});continue}}we(l).includes(a.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:a.file,line:a.line,fromLayer:o,target:a.symbol,capability:a.capability,...p?{edgeKind:p}:{},message:a.source==="import-based"?`${o} denies the ${a.capability} capability; found import of "${a.symbol}".`:`${o} denies the ${a.capability} capability; found ambient "${a.symbol}".`})}}for(let a of t.publishCalls){let o=n.get(a.file);if(!o)continue;for(let c of Je({publishCall:!0,rawIntentName:a.rawIntentName,objectHasIntent:a.objectHasIntent,arkPublishCandidate:a.arkPublishCandidate,hasSource:a.hasSource}))r.push({ruleId:c.ruleId,file:a.file,line:a.line,...c.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:o}:{},message:c.message});if(!a.sourceIntent)continue;let l=Ss(a.sourceIntent,e.contract);!l||l===o||r.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:a.file,line:a.line,fromLayer:o,toLayer:l,target:a.sourceIntent,message:`Publish source "${a.sourceIntent}" resolves to ${l}, but the publishing file is classified as ${o}.`})}for(let a of t.intentReferences){let o=n.get(a.file);if(!o)continue;let l=Ss(a.intent,e.contract);if(!l)continue;let c=fe(e.contract.config.rules,o,l);c&&r.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:a.file,line:a.line,fromLayer:o,toLayer:l,target:a.intent,message:c.message??`${o} must not reference ${l} intent ${a.intent}.`})}return r}i(Di,"contentViolations");function Mi(e){let{facts:t}=e,n=rt(e.contract.config),r=t.evidenceRequirementsHash===n,s=r?t.completeness:"unavailable",a=r?t.completenessReasons:[...t.completenessReasons,{code:"EVIDENCE_REQUIREMENTS_MISMATCH",message:"Resolved facts were collected for different policy-controlled evidence requirements."}].sort((d,P)=>{let H=`${d.code}\0${d.file??""}\0${d.message}`,oe=`${P.code}\0${P.file??""}\0${P.message}`;return H<oe?-1:H>oe?1:0}),o=t.files.map(d=>({...d,layer:ce(d.path,e.contract.config.layers)??null})),l=new Map(o.map(d=>[d.path,d.layer])),c=t.dependencies.map(d=>{let P=d.target?l.get(d.target)??ce(d.target,e.contract.config.layers):void 0;return{from:d.from,fromLayer:l.get(d.from)??null,...d.resolution==="resolved-project"&&d.target?{to:d.target,...P?{toLayer:P}:{}}:{},line:d.line,kind:d.kind,typeOnly:d.typeOnly,...d.targetTypeOnlyExports?{targetTypeOnlyExports:d.targetTypeOnlyExports}:{},...d.sourcePureTypeModule?{sourcePureTypeModule:d.sourcePureTypeModule}:{},...d.namedBindingsTypeOnly?{namedBindingsTypeOnly:d.namedBindingsTypeOnly}:{},...d.portProofEligible?{portProofEligible:d.portProofEligible}:{}}}),p=jt({config:e.contract.config,rules:e.contract.config.rules,files:o.map(d=>d.path)}),g=Li(e,t),y=e.contract.arkRules??xe(),f=o.map(d=>d.path),m={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?Fn(e.coverageInputs.fileContents):{},...e.fileHints??{}},A=[...Dn({arkRules:y,classShapes:e.contract.classShapes??t.classShapes??[],files:f,layerForFile:i(d=>l.get(d)??ce(d,e.contract.config.layers),"layerForFile"),fileHints:m}),...Mn(y,f)],b=A.filter(d=>d.failsStrict).map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,arkruleId:d.arkruleId,arkruleSource:d.arkruleSource,nextAction:d.ruleId==="ARKRULE_SCOPE_EMPTY"?`Fix appliesTo globs for ${d.arkruleId} in ${d.arkruleSource} so they match governed files, or remove the rule.`:`Fix the structure or invariant for ${d.arkruleId} (declared in ${d.arkruleSource}), then preflight again.`})),N=A.filter(d=>!d.failsStrict).map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,arkruleId:d.arkruleId,arkruleSource:d.arkruleSource,failsStrict:!1,nextAction:d.ruleId==="ARKRULE_SCOPE_EMPTY"?`Review appliesTo for ${d.arkruleId} in ${d.arkruleSource} (zero-match scope; advisory).`:`Review ArkRule ${d.arkruleId} in ${d.arkruleSource} (advisory).`})),I=(y.invariants?.length??0)>0?On({arkRules:y,fileContents:e.coverageInputs?.fileContents??{},testFiles:e.coverageInputs?.testFiles??[],testGlobsMissing:e.coverageInputs?.testGlobsMissing===!0||e.coverageInputs===void 0||(e.coverageInputs.testFiles?.length??0)===0,coverageBudgetExhausted:e.coverageInputs?.coverageBudgetExhausted===!0}):{coverage:[],violations:[],partial:!1},C=I.violations.filter(d=>d.failsStrict).map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,arkruleId:d.arkruleId,arkruleSource:d.arkruleSource,nextAction:`Add a test title or declared symbol covering ${d.arkruleId} (declared in ${d.arkruleSource}), then preflight again.`})),Y=I.violations.filter(d=>!d.failsStrict).map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,arkruleId:d.arkruleId,arkruleSource:d.arkruleSource,failsStrict:!1,nextAction:`Cover invariant ${d.arkruleId} in ${d.arkruleSource} (advisory / partial).`})),k=Hn(o),L=Ht({arkRun:e.contract.config.arkRun,layers:e.contract.config.layers,kernelCalls:t.arkRunKernelCalls,managedNews:t.arkRunManagedNews,compositionRootHits:t.arkRunCompositionRootHits,declarations:t.arkRunDeclarations,dependencies:t.dependencies,layerForFile:i(d=>l.get(d)??ce(d,e.contract.config.layers),"layerForFile"),classification:k}),D=e.contract.config.arkRun?.mode,x=L.findings.filter(()=>D==="enforced").map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,target:d.target,nextAction:d.nextAction,sensor:d.sensor,failsStrict:d.failsStrict,...d.severity?{severity:d.severity}:{}})),$=L.findings.filter(()=>D!=="enforced").map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,target:d.target,nextAction:d.nextAction,sensor:d.sensor,failsStrict:!1})),w=Jn({arkOrder:e.contract.config.arkOrder,layers:e.contract.config.layers,planeCalls:t.arkOrderPlaneCalls,genericUpdates:t.arkOrderGenericUpdates,planeRootHits:t.arkOrderRootHits,xiFieldWrites:t.arkOrderXiFieldWrites,ingestWritesXi:t.arkOrderIngestWritesXi,releaseKeyCounts:t.arkOrderReleaseKeyCounts,dependencies:t.dependencies,layerForFile:i(d=>l.get(d)??ce(d,e.contract.config.layers),"layerForFile"),classification:k}),ee=e.contract.config.arkOrder?.mode,ue=w.findings.filter(()=>ee==="enforced").map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,target:d.target,nextAction:d.nextAction,sensor:d.sensor,failsStrict:d.failsStrict,...d.severity?{severity:d.severity}:{}})),Le=w.findings.filter(()=>ee!=="enforced").map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,target:d.target,nextAction:d.nextAction,sensor:d.sensor,failsStrict:!1})),We=[...I.partial&&I.coverage.some(d=>d.mode==="enforced"&&d.partial)?[{code:"INVARIANT_COVERAGE_PARTIAL",message:"Enforced ArkRules invariant coverage cannot be fully proven (missing test globs or empty test set); reporting partial, never covered."}]:[],...L.completenessReasons,...w.completenessReasons],be=Ue({config:e.contract.config,rules:e.contract.config.rules,files:o.filter(d=>d.layer).map(d=>d.path),contentViolations:[...Di(e,t,l),...b,...C,...x,...ue],edges:c,warnings:[...p,...g.warnings,...N,...Y,...$,...Le],safety:g.report}),ht=s==="complete"&&We.length>0?"partial":s,Zt=ht==="complete"?a:[...a,...We].sort((d,P)=>{let H=`${d.code}\0${d.file??""}\0${d.message}`,oe=`${P.code}\0${P.file??""}\0${P.message}`;return H<oe?-1:H>oe?1:0}),S=be.violations.filter(d=>d.failsStrict!==!1),v=ht==="complete"&&S.length===0,h=v&&be.warnings.every(d=>d.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:ht,completenessReasons:Zt,valid:v,strictValid:h,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:g.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:o,layers:e.contract.config.layers.map(d=>d.name),edges:c,capabilityUses:t.capabilityUses,violations:be.violations,warnings:be.warnings}}}i(Mi,"analyzeCanonicalResolvedProject");function gt(e){return Mi({contract:e.contract,facts:Se(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints})}i(gt,"analyzeResolvedProject");function bs(e){return X(j(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}i(bs,"analysisTreeHash");function vs(e){let t=dt(e),n=new Map(t.ir.files.map(m=>[m.path,m])),r=[],s=new Set,a=[];for(let m of e.changes){let A=m.path.replace(/\\/g,"/"),b=Te(m.path);if(!b||b===".."||b.startsWith("../")||A.startsWith("/")||/^[A-Za-z]:\//.test(A)||A.includes("\0")){a.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(s.has(b)){a.push({ruleId:"DUPLICATE_CHANGE_PATH",file:b,line:1,message:`The atomic change set contains more than one operation for ${b}.`});continue}s.add(b),"delete"in m&&m.delete&&!n.has(b)&&a.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 m&&m.delete?{path:b,delete:!0}:{path:b,content:"content"in m?m.content:""})}e.changes.length===0&&a.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let o=Dt({...e,changes:r}),l=new Map(o.ir.files.map(m=>[m.path,m])),c=o.ir.violations.filter(m=>m.ruleId==="CAPABILITY_VIOLATION"||m.ruleId==="FORBIDDEN_GLOBAL").map(m=>{let A=l.get(m.evidence.file)?.layer;return{ruleId:m.ruleId,file:m.evidence.file,line:m.evidence.line,target:m.symbol,...m.capability?{capability:m.capability}:{},...A?{fromLayer:A}:{},edgeKind:"import",message:m.message}}),p=Ue({config:e.contract.config,rules:e.contract.config.rules,files:o.ir.files.map(m=>m.path),contentViolations:c,edges:o.ir.edges.filter(m=>!!m.fromLayer).map(m=>({from:m.from,fromLayer:m.fromLayer,...m.to?{to:m.to}:{},...m.toLayer?{toLayer:m.toLayer}:{},line:m.evidence.line,kind:"import",...m.typeOnly?{typeOnly:!0}:{},...m.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),g=r.map(m=>{let A=Te(m.path),b=n.get(A),N=l.get(A);return{path:A,operation:"delete"in m&&m.delete?"delete":b?"update":"create",...b?{beforeContentHash:b.contentHash}:{},...N?{candidateContentHash:N.contentHash}:{}}}).sort((m,A)=>m.path.localeCompare(A.path)),y=[...a,...p.violations].map(m=>({...m,nextAction:pe(m)})),f=y.filter(m=>m.failsStrict!==!1),u=e.changeMap?Ke({changeMap:e.changeMap,changes:g,baseDependencies:t.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;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&o.valid&&f.length===0&&(u?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:o.ir.compilerOptionsHash,baseTreeHash:bs(t.ir.files),candidateTreeHash:bs(o.ir.files),baseCompleteness:t.completeness,candidateCompleteness:o.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:o.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...u?{convergence:u}:{},changes:g,violations:y,warnings:p.warnings}}i(vs,"preflightChange");function Fi(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let s of t.split("/"))if(!(!s||s==="."))if(s===".."){if(n.length===0)return;n.pop()}else n.push(s);let r=n.join("/");return r&&r===t?r:void 0}i(Fi,"canonicalChangePath");function $i(e,t){return[["resolverIdentity",e.resolverIdentity,t.resolverIdentity],["compilerIdentity",e.compilerIdentity,t.compilerIdentity],["evidenceRequirementsHash",e.evidenceRequirementsHash,t.evidenceRequirementsHash],["projectPackageName",e.projectPackageName??"",t.projectPackageName??""]].filter(([,r,s])=>r!==s).map(([r,s,a])=>({ruleId:"FACTS_IDENTITY_MISMATCH",file:"<change-set>",line:1,field:r,before:s,candidate:a,message:`Base and candidate facts must use the same ${r}.`}))}i($i,"identityViolations");function Hi(e,t,n,r){let s=n.get(t),a=r.get(t);return{path:t,operation:"delete"in e&&e.delete?"delete":s?"update":"create",...s?{beforeContentHash:s.contentHash}:{},...a?{candidateContentHash:a.contentHash}:{}}}i(Hi,"preparedChange");function Cs(e){let t=Se(e.baseFacts),n=Se(e.candidateFacts),r=gt({contract:e.contract,facts:t}),s=gt({contract:e.contract,facts:n}),a=new Map(t.files.map(u=>[u.path,u])),o=new Map(n.files.map(u=>[u.path,u])),l=$i(t,n),c=new Map,p=[];for(let u of e.changes){let m=Fi(u.path);if(!m){l.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(c.has(m)){l.push({ruleId:"DUPLICATE_CHANGE_PATH",file:m,line:1,message:`The atomic change set contains more than one operation for ${m}.`});continue}c.set(m,u);let A=a.get(m),b=o.get(m);if("delete"in u&&u.delete)A||l.push({ruleId:"DELETE_TARGET_MISSING",file:m,line:1,message:`Cannot delete ${m} because it is not present in the supplied base facts.`}),b&&l.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:m,line:1,message:`Candidate facts still contain deleted file ${m}.`});else{let N="content"in u?u.content:"",R=X(N);b?b.contentHash!==R&&l.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:m,line:1,expectedContentHash:R,candidateContentHash:b.contentHash,message:`Candidate facts for ${m} do not match the declared content.`}):l.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:m,line:1,message:`Candidate facts do not contain changed file ${m}.`})}p.push(Hi(u,m,a,o))}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 u of new Set([...a.keys(),...o.keys()])){if(c.has(u))continue;let m=a.get(u),A=o.get(u);m&&A&&j(m)===j(A)||l.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:u,line:1,message:`Candidate facts change ${u}, but the atomic change set does not declare it.`})}let g=e.changeMap?Ke({changeMap:e.changeMap,changes:p,baseDependencies:r.ir.edges.flatMap(u=>u.to?[{from:u.from,to:u.to}]:[]),candidateDependencies:s.ir.edges.flatMap(u=>u.to?[{from:u.from,to:u.to}]:[])}):void 0,y=[...l,...s.ir.violations].map(u=>({...u,nextAction:pe(u)})),f=y.filter(u=>u.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&s.strictValid&&f.length===0&&(g?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,resolverIdentity:n.resolverIdentity,compilerIdentity:n.compilerIdentity,compilerOptionsHash:n.compilerOptionsHash,tsconfigHash:n.tsconfigHash,baseCompilerOptionsHash:t.compilerOptionsHash,candidateCompilerOptionsHash:n.compilerOptionsHash,baseTsconfigHash:t.tsconfigHash,candidateTsconfigHash:n.tsconfigHash,evidenceRequirementsHash:n.evidenceRequirementsHash,baseFactsHash:t.factsHash,candidateFactsHash:n.factsHash,baseTreeHash:t.candidateTreeHash,candidateTreeHash:n.candidateTreeHash,baseCompleteness:r.completeness,candidateCompleteness:s.completeness,baseCompletenessReasons:r.completenessReasons,candidateCompletenessReasons:s.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...g?{convergence:g}:{},changes:p.sort((u,m)=>u.path<m.path?-1:u.path>m.path?1:0),violations:y,warnings:s.ir.warnings}}i(Cs,"preflightResolvedChange");var Os="1.0",ji=12;function _s(e){return e==="enforced"||e==="advisory"?e:null}i(_s,"closedMode");function Vi(e){let t=new Set;if(!Array.isArray(e))return[];for(let n of e){let r=n?.ruleId;typeof r!="string"||!jn(r)||t.has(r)||t.add(r)}return[...t].sort((n,r)=>n<r?-1:n>r?1:0)}i(Vi,"uniqueArkRunRuleIds");function Ki(e){return!e||typeof e!="object"?{present:!1,mode:null,roots:0,layers:0,requireDeclarations:null}:{present:!0,mode:_s(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(Ki,"extraFromConfig");function Ui(e={}){let t=Ki(e.arkRun),n=t.present?Vi(e.findings):[],r=n.slice(0,ji),s=n.length,a=Vn({classification:e.classification,arkRules:{active:e.arkRules?.active===!0,structureEnforced:e.arkRules?.structureEnforced,structureTotal:e.arkRules?.structureTotal,structureAdvisory:e.arkRules?.structureAdvisory,invariantEnforced:e.arkRules?.invariantEnforced,invariantTotal:e.arkRules?.invariantTotal,invariantAdvisory:e.arkRules?.invariantAdvisory,covered:e.arkRules?.covered,uncovered:e.arkRules?.uncovered},arkRun:{present:t.present,mode:t.mode,residualCount:s}}),o=t.present&&t.mode==="enforced"&&Re(e.classification),l;return t.present?t.mode==="advisory"?l="Advisory ArkRun residual only \u2014 never flips valid or --strict-merge. Residual is a finding-id count, never a score.":o?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:Os,notAScore:!0,active:t.present,mode:t.mode,compositionRoots:t.roots,managedLayers:t.layers,requireDeclarations:t.requireDeclarations,residual:{count:s,ruleIds:r},extraMergeTeeth:o,failMergeWhen:a.failMergeWhen,note:l,mergePlanes:a}}i(Ui,"summarizeArkRunSection");function Zn(e={}){let t=e.present===!0,n=_s(e.mode),r=e.residual,s=null;return typeof r=="number"&&Number.isFinite(r)&&r>=0&&(s=Math.floor(r)),t||(s=s??0),{notAScore:!0,present:t,mode:t?n:null,extraMergeTeeth:t&&n==="enforced"&&e.extraMergeTeeth===!0,residual:s}}i(Zn,"projectStatusArkRun");function Gi(e){if(!e||e.notAScore!==!0)return[];if(e.active!==!0)return["ArkRun extra is off \u2014 silent on Layers/ArkRules (not a score)."];let t=e.mode??"unknown",n=e.extraMergeTeeth===!0?"armed":"not armed",r=[`mode: ${t} \xB7 extra merge teeth ${n} \xB7 not a score`];if(e.residual.count>0){let s=e.residual.ruleIds.join(", "),a=e.residual.count>e.residual.ruleIds.length?` (+${e.residual.count-e.residual.ruleIds.length} more)`:"";r.push(`Residual: ${s}${a}`)}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(Gi,"formatArkRunDoctorLines");function Vt(e,t){return e.slice(0,t).split(`
16
+ `).length}i(Vt,"lineOf");function xs(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}i(xs,"normalizeInventoryPath");function Ns(e,t){return e.some(n=>{let r=n.trim().replace(/\.+$/,"");return t.some(s=>r===s||r.startsWith(`${s}.`))})}i(Ns,"ownsIntent");function Ts(e,t=[]){return/domain|entity|aggregate|model/i.test(e)||Ns(t,["Domain"])}i(Ts,"isDomainLayer");function Bi(e,t=[]){return/application|orchestration|presentation|adapter|framework|interface|delivery|transport|inbound|controller/i.test(e)||Ns(t,["Application","Orchestration","Presentation","Adapter","Interface","Delivery","Transport"])}i(Bi,"isControllerEligibleLayer");function zi(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(zi,"isNonPilotSurface");function qi(e){let t=[],n=0,r=new Map(Object.entries(e.fileLayers??{}).map(([c,p])=>[xs(c),p])),s=new Map((e.layerContexts??[]).map(c=>[c.name,c.intentPrefixes??[]])),a=(e.layerContexts??[]).find(c=>Ts(c.name,c.intentPrefixes))?.name??"DomainModel";for(let[c,p]of Object.entries(e.fileContents).sort(([g],[y])=>g.localeCompare(y))){let g=xs(c);if(zi(g)||/GENERATED FILE\s+[—-]\s+do not edit by hand/i.test(p.slice(0,320)))continue;let y=r.has(g),f=r.get(g),u=f?s.get(f)??[]:[],m=/(?:^|\/)(?:components|ui|layouts|styles|hooks|theme|tokens|i18n|locales?)(?:\/|$)/i.test(g)||/(?:^|\/)(?:src\/)?(?:app|pages)\/.+\.(?:tsx|jsx)$/i.test(g)&&/(?:page|layout|loading|error|template|default)\.(?:tsx|jsx)$/i.test(g),A=/(?:^|\/)(?:app|pages)(?:\/[^/]+)*\/api(?:\/|$)/i.test(g),b=/(?:^|\/)actions?(?:\/|\.|$)/i.test(g)||/['"]use server['"]/.test(p),N=/controller|handler|resolver/i.test(c)||A||b||/route\.(?:ts|js|tsx|jsx)$/i.test(g)&&!m||/@(Controller|Get|Post|Put|Delete|Patch)\b/.test(p)||/\bexport\s+(?:async\s+)?function\s+(?:GET|POST|PUT|DELETE|PATCH)\b/.test(p)||/\bexport\s+const\s+(?:GET|POST|PUT|DELETE|PATCH)\s*=/.test(p),R=y?!!(f&&Bi(f,u)&&N):N,I=y?!!(f&&Ts(f,u)):/domain|entity|aggregate|model/i.test(c),C=!y||I||R;if(R&&!m){let x=/\b(if\s*\([^)]{0,80}(amount|total|price|qty|quantity|balance)[^)]{0,40}\)|throw new (Error|BadRequest|ValidationError)|z\.object\(|yup\.|class-validator|@Is[A-Z])/g,$;for(;($=x.exec(p))!==null;)n+=1,t.push({id:`inv-val-${n}`,kind:"validation-in-controller",file:c,line:Vt(p,$.index),message:"Business validation appears in a controller/handler \u2014 extract an invariant or Domain rule.",confidence:"direct-evidence",governedLayer:f,suggestedArkRule:{layer:a,invariantId:`INV-EXTRACT-${n}`,sensor:"invariant-coverage"},neverMechanicalSafe:!0})}let Y=/\b(const|let)\s+([A-Z][A-Z0-9_]{2,})\s*=\s*(\d{2,}|['"][^'"]{8,}['"])/g,k,L=i(x=>/^(?:TEST|SPEC|TIMEOUT|PORT|VERSION|MAX_RETRY|MIN_RETRY|TTL|CACHE|HEADER|COOKIE|MIME|CONTENT_TYPE|HTTP_STATUS|NODE_ENV|LOG_LEVEL|FEATURE_FLAG|ID_PREFIX|Z_INDEX)(?:_|$)/i.test(x)||/^(?:ROUTE|PATH|LABEL|TITLE|HEADING|CLASS|STYLE|COLOR|THEME|BREAKPOINT|QUERY|PARAM|ICON|ARIA|MSG|COPY|I18N|LOCALE|PAGE|NAV|MENU|TAB|BTN|BUTTON|PLACEHOLDER|TOOLTIP|SHADOW|RADIUS|GAP|PADDING|MARGIN|FONT|WIDTH|HEIGHT|OPACITY|DURATION|EASE|ANIM)_/i.test(x)||/_(?:ROUTE|PATH|LABEL|TITLE|COLOR|THEME|CLASS|STYLE|ICON|ARIA|MSG|COPY|TIMEOUT|PORT|VERSION|RETRY|DELAY|INTERVAL|TTL|CACHE)$/i.test(x)||/_(?:TIMEOUT(?:_MS)?|MS|BYTES|BUCKET|STORAGE_KEY|WINDOW_MS)$/i.test(x)||/^(?:DEFAULT_(?:BASE_URL|TIMEOUT(?:_MS)?|RETRY|PORT|HOST|HEADERS?|CACHE|TTL|MS|LOCALE|LANG|TIMEZONE|TZ)|REQUEST_(?:TIMEOUT(?:_MS)?|HEADERS?|RETRY|ID_PREFIX)|STORAGE_(?:KEY|PREFIX|BUCKET)|DAY_MS$|APP_DOMAIN$|BASE_URL$)$/i.test(x)||/^(?:FAVORITES_STORAGE|LISTINGS_CACHE|DOCS_PATH|METRICS_INTERVAL)/i.test(x)||/^(?:DEV|DEMO|SEED|FIXTURE)_[A-Z0-9_]+$/i.test(x)||/^(?:PG|POSTGRES|OID)_[A-Z0-9_]+$/i.test(x)||/_(?:OID|OIDS)$/i.test(x)||/^(?:INT2|INT4|INT8|FLOAT4|FLOAT8|NUMERIC|DATE|TIME|TIMESTAMP|TIMESTAMPTZ|JSON|JSONB|UUID)OID$/i.test(x)||/(?:^|_)(?:SCHEMA|PROTOCOL|RESOLVER|FORMAT)_(?:URL|URI|VERSION|ID|IDENTITY)$/i.test(x),"isInfraMagicName"),D=i((x,$)=>{if(/^(?:ERROR|SUCCESS|WARNING|INFO|HINT|HELP|EMPTY|TOAST|SNACK|ALERT|BANNER|DIALOG|MODAL|TOOLTIP|CAPTION|SUBTITLE|HEADLINE|USER|UI|DISPLAY|FEEDBACK)_(?:MSG|MESSAGE|TEXT|COPY|LABEL|TITLE|BODY|DESC|DESCRIPTION|HINT|HELP)?/i.test(x)||/_(?:MSG|MESSAGE|TEXT|COPY|TOAST|SNACK|ALERT|BANNER|CAPTION|HINT|HELP_TEXT|ERROR_TEXT|EMPTY_TEXT|PLACEHOLDER_TEXT|USER_MESSAGE|FEEDBACK)$/i.test(x))return!0;let w=$.replace(/^['"]|['"]$/g,"");return!!(/^['"]/.test($)&&(/\s/.test(w)||/[.!?…]$/.test(w))&&!/^(?:STATUS|STATE|PHASE|ROLE|TYPE|KIND|ORDER|PAYMENT|CART|INVOICE|POLICY)_[A-Z0-9_]+$/i.test(x))},"isUxMessageConstant");for(;(k=Y.exec(p))!==null;){let x=k[2],$=k[3]??"";!C||L(x)||D(x,$)||m&&!I||/(?:^|\/)(?:integrations?|repos?|clients?|infra(?:structure)?|adapters?)(?:\/|$)/i.test(g)&&!I||(n+=1,t.push({id:`inv-magic-${n}`,kind:"magic-business-constant",file:c,line:Vt(p,k.index),message:`Magic business constant ${x} may belong in a Domain policy or invariant catalog.`,confidence:"heuristic",governedLayer:f,suggestedArkRule:{layer:a,invariantId:`INV-${x}`},neverMechanicalSafe:!0}))}if(I){let x=/export\s+class\s+([A-Za-z_][A-Za-z0-9_]*)\s*\{([^}]{0,800})\}/g,$;for(;($=x.exec(p))!==null;){let w=$[2]??"",ee=(w.match(/\b[a-zA-Z_][a-zA-Z0-9_]*\s*\(/g)??[]).length;(w.match(/:\s*[A-Za-z]/g)??[]).length>=2&&ee<=1&&(n+=1,t.push({id:`inv-anemic-${n}`,kind:"anemic-entity",file:c,line:Vt(p,$.index),message:`Class ${$[1]} looks anemic (data-heavy, few behaviors).`,confidence:"heuristic",governedLayer:f,suggestedArkRule:{layer:a,structureId:"no-anemic-model",sensor:"no-anemic-model"},neverMechanicalSafe:!0}))}}if(I&&!(/\.error\.(?:ts|js|tsx|jsx)$/i.test(g)||/(?:^|\/)[^/]*(?:-access)?\.error\./i.test(g)||/(?:^|\/)errors?(?:\/|$)/i.test(g))){let $=/this\.\w+\s*=/g,w;for(;(w=$.exec(p))!==null;){let ee=p.lastIndexOf("class ",w.index),ue=ee>=0?p.indexOf("{",ee):-1,Le=ee>=0&&ue>=ee&&ue<w.index?p.slice(ee,ue):"";if(/\bextends\s+(?:Error|[A-Za-z_$][A-Za-z0-9_$]*Error)\b/.test(Le))continue;let qe=p.slice(Math.max(0,w.index-200),w.index+200);if(!/\b(ensureInvariants|assertInvariants|validate|publish|emit)\b/.test(qe)){n+=1,t.push({id:`inv-mut-${n}`,kind:"mutation-without-guard",file:c,line:Vt(p,w.index),message:"Domain field mutation without nearby guard/publish call.",confidence:"heuristic",governedLayer:f,suggestedArkRule:{layer:a,structureId:"events-on-mutation",sensor:"domain-event-on-mutation"},neverMechanicalSafe:!0});break}}}}let o=new Set(e.contractedRuleIds??[]);t.sort((c,p)=>+(p.confidence==="direct-evidence")-+(c.confidence==="direct-evidence")||c.file.localeCompare(p.file)||c.line-p.line||c.kind.localeCompare(p.kind)||c.id.localeCompare(p.id));let l=t.filter(c=>c.suggestedArkRule?.invariantId&&o.has(c.suggestedArkRule.invariantId)||c.suggestedArkRule?.structureId&&o.has(c.suggestedArkRule.structureId)).length;return{candidates:t,inventoried:t.length,underContract:l,frozen:(e.frozenKeys??[]).length,notAScore:!0}}i(qi,"buildRulesInventory");function Wi(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(Wi,"inventoryToExtractionCard");var Yi="1.1";var Xi="1.0";var Qn="docs/diagnostics.md",Ji="1.0";function E(e,t,n,r,s,a){return{ruleId:e,title:n,why:r,fix:s,docsAnchor:e,category:t,...a?.oftenAdvisory?{oftenAdvisory:!0}:{}}}i(E,"entry");var Kt=Object.freeze([E("LAYER_IMPORT_VIOLATION","layer","Layer import not allowed","A module import (or re-export) crosses a layer edge that ark.config.json does not allow. The architecture contract forbids that dependency direction so outer infrastructure cannot leak into pure or inner layers.","Branch by import kind: constants/types/pure \u2192 adopt into DomainModel or SharedKernel (do not invent a port); kernel/events/bootstrap from Persistence \u2192 inject a port or move the map to SharedTypes (Persistence must not emit); define a port only when the target is a real use-case. Type-only edges use `import type`. Then preflight again. Do not weaken the layer rule without a hash-bound policy acknowledgement."),E("LAYER_INTENT_REFERENCE_VIOLATION","layer","Intent referenced across a blocked layer edge","A string intent (or intent-like reference) names a layer that the file\u2019s layer may not reach under the contract rules \u2014 the same plane as import edges, for event/intent coupling.","Reference that intent from a layer allowed to know about it (usually an adapter or application layer), or relocate the reference \u2014 then preflight again."),E("LAYER_REFERENCE_VIOLATION","layer","Layer reference blocked (snippet / AI gate)","Snippet analysis found an intent or string reference that would couple layers in a direction the architecture profile forbids.","Move the reference to an allowed layer or introduce a port/event boundary, then re-run the snippet gate."),E("CIRCULAR_DEPENDENCY","layer","Dependency cycle","Two or more modules import each other in a loop. Cycles make ownership unclear and break stable layer direction.","Extract the shared dependency into a third module, invert one edge behind a port, or merge units that are truly one \u2014 then preflight again."),E("FORBIDDEN_GLOBAL","capability","Forbidden ambient global or dual import","The file\u2019s layer lists this ambient (or its exact import dual, e.g. process / node:process) in forbiddenGlobals. Pure layers must not reach wall-clock, network, process, or similar effects directly.","Inject the capability through a small port (Clock, HttpPort, Config, \u2026), bind the implementation outside the walled layer, then preflight again."),E("CAPABILITY_VIOLATION","capability","Denied effect capability","The layer denies an effect capability (network, filesystem, clock, randomness, environment, process, persistence) and the candidate uses that effect via ambient or import evidence.","Define a capability port in the walled layer, bind the implementation in an adapter layer, then preflight again. Never mechanical-safe \u2014 port shape is a design decision."),E("RAW_EVENT_PUBLISH","publish","Raw event publish","Publish went through a raw string or object instead of a registered intent creator, bypassing Ark intent contracts and tooling.","Publish through a registered intent creator, then run Ark again."),E("PUBLISH_MISSING_SOURCE","publish","Publish missing metadata.source","A strict Ark publish call omitted metadata.source, so the publishing layer cannot be verified.","Add metadata.source to the publish call, then run Ark again."),E("PUBLISH_SOURCE_LAYER_MISMATCH","publish","Publish source layer mismatch","metadata.source resolves to a different layer than the file performing the publish.","Use a source intent owned by the same layer as this file, or move the publish call to the owning layer."),E("UNKNOWN_INTENT","publish","Unknown intent reference","Snippet analysis saw an intent string that is not registered in the intent registry / profile under check.","Register the intent or use a known intent name from the project registry, then re-run the gate."),E("DYNAMIC_IMPORT_NOT_ALLOWLISTED","safety","Non-literal dynamic import","A dynamic import(expr) cannot be resolved statically and the file is not on dynamicImportAllowlist. Unresolved dynamics can hide layer edges.","Rewrite to a static import when possible, or add only reviewed files to dynamicImportAllowlist after human sign-off."),E("DYNAMIC_REQUIRE_NOT_ALLOWLISTED","safety","Non-literal require","A require(expr) cannot be resolved statically and is not allowlisted \u2014 same hide-the-edge risk as dynamic import.","Prefer static import, or allowlist only reviewed files after sign-off."),E("TS_SUPPRESSION_THRESHOLD_EXCEEDED","safety","@ts-ignore / @ts-nocheck threshold","Count of TypeScript suppressions in governed production source exceeds safety.maxTsSuppressions.","Remove suppressions by fixing types, or raise the threshold only with an explicit production exception in ark.config.json."),E("ANY_CAST_THRESHOLD_EXCEEDED","safety","Explicit any cast threshold","Count of explicit any casts exceeds safety.maxAnyCasts.","Replace any with precise types, or raise the threshold only with a documented exception."),E("IN_MEMORY_STORE_IN_PRODUCTION_SOURCE","safety","In-memory store in production source","Governed production source references an Ark InMemory* store without safety.allowInMemory \u2014 durable systems should not ship ephemeral stores by accident.","Provide a durable store implementation, or set safety.allowInMemory only for an explicitly ephemeral service."),E("PEER_ISOLATION_DISABLED","safety","peerIsolation disabled on a rule","A same-layer or peer rule disables peerIsolation (or omits it where required), which allows cross-slice coupling the contract otherwise blocks.","Restore peerIsolation: true, or set safety.allowDisabledPeerIsolation only with a documented production exception."),E("ARKRULE_STRUCTURE","arkrules","ArkRule structure sensor failed","An opt-in ArkRules structure sensor (private state, factory shape, event publish, persistence write outside an aggregate, \u2026) failed on a governed file for a declared arkruleId.","Restore the declared structure for the ArkRule (see arkruleSource), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement."),E("ARKRULE_INVARIANT","arkrules","ArkRule invariant failed","Reserved / remediation-recognized code for invariant-plane failures bound to an ArkRule id (coverage path also emits INVARIANT_UNCOVERED).","Fix the invariant for the ArkRule declared in arkrules/<Layer>.json, then preflight again. Do not demote without acknowledgement."),E("ARKRULE_SCOPE_EMPTY","arkrules","ArkRule appliesTo matched zero files","An ArkRule\u2019s appliesTo globs matched no governed files \u2014 the rule cannot observe what it claims to protect.","Fix appliesTo globs so they match governed files, or remove the rule. Enforced empty scope fails; advisory empty scope warns.",{oftenAdvisory:!0}),E("INVARIANT_UNCOVERED","arkrules","Invariant without coverage evidence","An ArkRules invariant is under contract but no covering test title or declared symbol evidence was found (or coverage is partial). Kind is never-had-tests (adopt residual) vs tests-disappeared (suite exists).","Add a test title or declared symbol covering the arkruleId, then preflight again. Treat never-had-tests as adopt residual; treat tests-disappeared as a regression. Missing test globs report partial \u2014 never fake green."),E("ARKRUN_MISSING_ROOT","arkrun","No kernel factory in composition roots","The ArkRun extra is on but no createArkKernel / createStrictArkKernel / createArkKernelFromConfig / createStrictArkKernelFromConfig factory was found in arkRun.compositionRoots, so agents can skip the kernel while the write gate stays green.","Import createStrictArkKernel from arkgate/runtime (same npm package; @arkgate/runtime is deprecated) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision."),E("ARKRUN_KERNEL_IN_DOMAIN","arkrun","Domain-role layer imports the kernel","A Domain-role layer imports arkgate/runtime, @arkgate/runtime, or kernel types. Domain stays kernel-free; composition roots and adapters own the factory.","Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from arkgate/runtime (same npm package; @arkgate/runtime is deprecated), then preflight again. Never mechanical-safe."),E("ARKRUN_DIRECT_NEW","arkrun","Managed type constructed with new","A managed non-Domain file constructs an admitted type with new outside an ArkRun composition-root factory, skipping kernel resolve/registration.","Resolve the type from the kernel instead of constructing it with new, then preflight again. Never mechanical-safe \u2014 rewiring construction is a design decision."),E("ARKRUN_UNDECLARED_EMIT","arkrun","Emit name not in raises/sends","A publisher / publish / raise / send call-site literal is not listed in the file\u2019s raises or sends declaration.","Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment."),E("ARKRUN_UNDECLARED_HANDLE","arkrun","Handle name not in reactsTo","A subscribe / registerHandler call-site literal is not listed in the file\u2019s reactsTo declaration.","Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment."),E("ARKRUN_UNDECLARED_DEPEND","arkrun","Depend name not in uses","A resolve / resolveSingleton call-site literal is not listed in the file\u2019s uses declaration.","Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment."),E("ARKRUN_TRANSPORT_BYPASS","arkrun","Homemade broker or emitter import","A managed layer imports a closed broker/queue/emitter specifier (EventEmitter, queue clients, \u2026) instead of the ArkRun kernel transport.","Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe \u2014 homemade buses stay judgment."),E("ARKORDER_MISSING_PLANE","arkorder","No createOrderPlane in plane roots","The ArkOrder extra is on but no createOrderPlane factory was found in arkOrder.planeRoots, so agents can skip the pattern plane while the write gate stays green.","Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision."),E("ARKORDER_KERNEL_IN_DOMAIN","arkorder","Domain-role layer imports the order plane","A Domain-role layer imports arkgate/order. Domain stays plane-free; planeRoots own the factory.","Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe."),E("ARKORDER_GENERIC_UPDATE","arkorder","Generic update of \u03BE","A call to update/patch/set on the order plane rewrites the slow pattern. Haken slaving forbids generic \u03BE mutation.","Use release() to freeze \u03BE or proposeRelease() for a pattern change with blast radius, then preflight again. Never mechanical-safe."),E("ARKORDER_TOO_MANY_PARAMS","arkorder","Too many slow keys","\u03BE has more keys than arkOrder.maxXiKeys. Haken requires a few slow modes, not a dump of microstate.","Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe."),E("ARKORDER_INGEST_WRITES_XI","arkorder","ingest assigned into \u03BE","An ingest() result is written into a Release or \u03BE store. ingest may absorb or escalate; it never mints a pattern.","Keep ingest results as absorb/escalate only. Change \u03BE with proposeRelease + release. Never mechanical-safe."),E("ARKORDER_XI_FIELD_WRITE","arkorder","Slow key written around the order plane","A managed-layer file imports a persistence driver and writes a declared arkOrder.xiKeys name. Field events absorb or escalate; they do not PATCH the slow pattern.","Keep invoices, seats, hours, and logs on ingest. Change the slow key with proposeRelease + release, then preflight again. Never mechanical-safe."),E("INVALID_CHANGE_PATH","preflight","Unsafe change path","A change set entry is not a safe, non-empty project-relative path (absolute, escape, empty, or NUL).","Use canonical project-relative paths only in the atomic change set, then preflight again."),E("DUPLICATE_CHANGE_PATH","preflight","Duplicate path in change set","The atomic change set lists more than one operation for the same path.","Collapse to one create/update/delete per path, then preflight again."),E("DELETE_TARGET_MISSING","preflight","Delete target missing","A delete operation targets a path that is not present in the supplied base tree.","Remove the delete, or include the file in the base tree facts, then preflight again."),E("CHANGE_SET_EMPTY","preflight","Empty change set","Atomic preflight was invoked with no create, update, or delete operations.","Provide at least one change operation, then preflight again."),E("FACTS_IDENTITY_MISMATCH","preflight","Base/candidate facts identity mismatch","Base and candidate resolved facts disagree on resolver, compiler, evidence requirements, or package identity \u2014 verdicts would not be comparable.","Regenerate both fact snapshots with the same resolver/compiler/evidence requirements, then preflight again."),E("CANDIDATE_DELETE_NOT_APPLIED","preflight","Candidate still contains deleted path","Facts claim a delete, but the candidate tree still includes the path.","Ensure the candidate facts apply the delete (path absent), then preflight again."),E("CANDIDATE_CHANGE_MISSING","preflight","Declared change missing from candidate","The change set declares a create/update whose path is missing from candidate facts.","Include the new content in the candidate facts (or drop the operation), then preflight again."),E("CANDIDATE_CONTENT_HASH_MISMATCH","preflight","Candidate content hash mismatch","The candidate file content hash does not match the hash expected for the declared change.","Rebuild candidate facts from the exact proposed content, then preflight again."),E("UNDECLARED_CANDIDATE_CHANGE","preflight","Undeclared candidate change","Candidate facts differ from base for a path that was not listed in the explicit change set.","Declare every path that changes in the atomic change set, then preflight again."),E("ATOMIC_PREFLIGHT_UNAVAILABLE","preflight","Atomic preflight unavailable","The host/MCP path could not run the atomic preflight engine (missing facts, incomplete setup, or unsupported mode).","Use resolved-candidate facts / ark_prepare_change with a complete batch, or fall back to ark-check on disk. Do not treat missing preflight as green."),E("DESIGN_SMELL_REGRESSION","preflight","Design smell regression on base-relative ratchet","Compared to the base ref, the candidate introduces a created-path domain-logic-in-ui file under --strict-merge, or introduces or worsens a blocking design-smell class under --fail-on-new-smells.","Move the new UI business rule out of the created file (or revert a --fail-on-new-smells regression), then re-run with the same base ref."),E("ANALYSIS_PARSE_INCOMPLETE","analysis","Parse incomplete","Governed source could not be fully parsed; evidence includes the TypeScript diagnostic (line + message). Incremental mid-edit parse is normal for agents. Contract exclude paths skip the write hook.","Finish the source or fix the reported syntax error, then re-run `npx arkgate-check`. The write hook does not deny solely on mid-edit parse. Partial never means pass."),E("LEXICAL_EVIDENCE_INCOMPLETE","analysis","Lexical evidence incomplete","Single-file validation cannot prove project module resolution. The write hook is already the verdict.","Re-run `npx arkgate-check --root . --config ark.config.json`, or treat the hook deny as final. Do not call ark_prepare_change from a hook deny."),E("ANALYSIS_HOST_UNAVAILABLE","analysis","Analysis host unavailable","No usable TypeScript / analysis host was available for this invocation.","Install a supported TypeScript version visible to the project, then re-run. Unavailable analysis is fail-closed."),E("ADAPTER_NOT_ALLOWED_FOR_PORT","adapter","Adapter not allowed for port","Runtime/port wiring selected an adapter implementation that the architecture profile does not allow for that port.","Bind an allowed adapter for the port, or adjust the profile with an explicit policy decision \u2014 then re-run."),E("FORBIDDEN_PATTERN","snippet-policy","Forbidden regex pattern","Snippet content matched a project or profile forbiddenPatterns rule.","Remove or rewrite the matching code so the pattern no longer matches, then re-run the snippet gate."),E("FORBIDDEN_SUBSTRING","snippet-policy","Forbidden substring","Snippet content contained a forbidden substring from the AI gate options/profile.","Remove the forbidden substring, then re-run the snippet gate."),E("FORBIDDEN_IMPORT","snippet-policy","Forbidden import target","Snippet imported or required a module listed as forbidden for the active profile.","Import an allowed module or inject the dependency behind a port, then re-run."),E("POLICY_VIOLATION","snippet-policy","Policy engine violation","A registered Policy failed on the snippet or generated code under evaluation.","Adjust the code to satisfy the named policy, or change the policy only through an explicit contract decision."),E("EXTENSION_ERROR","snippet-policy","AI gate extension error","A registered AICodeGate extension threw while analyzing the snippet.","Fix or remove the failing extension; do not ignore extension failures as pass."),E("AST_ANALYZER_ERROR","snippet-policy","AST analyzer error","Built-in AST/symbol analysis failed (host error or unexpected analyzer exception).","Ensure TypeScript host and snippet are valid; re-run. If the analyzer crashes on valid input, file a bug with a minimal fixture."),E("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","config","Invalid dynamicImportAllowlist","dynamicImportAllowlist is present but not an array of file globs.","Set dynamicImportAllowlist to an array of project-relative globs (or omit it).",{oftenAdvisory:!0}),E("CONFIG_INVALID_SAFETY","config","Invalid safety object","The safety field is present but not an object.","Use a safety object with optional maxTsSuppressions, maxAnyCasts, allowInMemory, allowDisabledPeerIsolation.",{oftenAdvisory:!0}),E("CONFIG_INVALID_SAFETY_THRESHOLD","config","Invalid safety threshold","A safety threshold (maxTsSuppressions / maxAnyCasts) is not a non-negative integer.","Set each threshold to a non-negative integer.",{oftenAdvisory:!0}),E("CONFIG_NO_LAYERS","config","No layers configured","ark.config.json has no file layers, so import-boundary enforcement cannot classify files.","Declare at least one layer with name + patterns (or run ark start / a preset).",{oftenAdvisory:!0}),E("CONFIG_LAYER_WITHOUT_NAME","config","Layer missing name","A configured layer entry has no name.","Give every layer a unique non-empty name.",{oftenAdvisory:!0}),E("CONFIG_INVALID_FORBIDDEN_GLOBALS","config","Invalid forbiddenGlobals","A layer\u2019s forbiddenGlobals is not an array of strings; the entry is ignored.",'Use an array of strings (e.g. ["fetch", "Date.now"]).',{oftenAdvisory:!0}),E("CONFIG_LAYER_WITHOUT_PATTERNS","config","Layer without patterns","A named layer has no file patterns and will never classify files.","Add patterns globs that match the layer\u2019s source tree.",{oftenAdvisory:!0}),E("CONFIG_INVALID_LAYER_PATTERN","config","Invalid layer pattern","A layer pattern is not a valid glob / failed to compile.","Fix the pattern syntax for that layer.",{oftenAdvisory:!0}),E("CONFIG_LAYER_PATTERN_NO_MATCHES","config","Layer pattern matched no files","A layer pattern matched zero included files (often a typo or include mismatch). Reserved/allowEmpty houses do not emit this.","Adjust the pattern or include roots, or mark the layer reserved/allowEmpty if the glob is a future house.",{oftenAdvisory:!0}),E("CONFIG_DUPLICATE_LAYER","config","Duplicate layer name","The same layer name appears more than once in configuration.","Rename or merge duplicate layer entries.",{oftenAdvisory:!0}),E("CONFIG_RULE_UNKNOWN_FROM_LAYER","config","Rule unknown from layer","A dependency rule references a source layer name that is not declared.","Fix the rule\u2019s from field to a declared layer name.",{oftenAdvisory:!0}),E("CONFIG_RULE_UNKNOWN_TO_LAYER","config","Rule unknown to layer","A dependency rule references a target layer name that is not declared.","Fix the rule\u2019s to field to a declared layer name.",{oftenAdvisory:!0}),E("CONFIG_AMBIGUOUS_LAYERS","config","Ambiguous layer classification","Some files match multiple layers at equal specificity; classification falls back to declaration order.","Disambiguate overlapping patterns so each file has one clear layer owner.",{oftenAdvisory:!0}),E("CONFIG_UNCLASSIFIED_FILES","config","Unclassified included files","Included source files match no layer pattern; import rules will not enforce on them.","Extend layer patterns or narrow include so every governed file is classified.",{oftenAdvisory:!0}),E("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.")]),er=new Map(Kt.map(e=>[e.ruleId,e])),Zi=Object.freeze(Kt.map(e=>e.ruleId));function Qi(e){return typeof e=="string"&&e.length>0&&er.has(e)}i(Qi,"isKnownDiagnosticCode");function el(e){return typeof e!="string"||e.length===0?!1:er.has(e)?!0:e.startsWith("ARKRULE_")}i(el,"isCataloguedOrArkRuleFamily");function Ut(e){if(!(typeof e!="string"||e.length===0))return er.get(e)}i(Ut,"getDiagnosticCatalogEntry");function Ps(e){return`#${Ut(e)?.docsAnchor??e}`}i(Ps,"diagnosticDocsFragment");function tl(e){return`${Qn}${Ps(e)}`}i(tl,"diagnosticDocsPath");function nl(){return{schemaVersion:"1.0",docsPath:Qn,codes:Kt}}i(nl,"serializeDiagnosticCatalog");function rl(e){return Ut(e)?.fix}i(rl,"catalogFixForRuleId");function sl(e){return Ut(e)?.why}i(sl,"catalogWhyForRuleId");var tr="1.0",Ls="https://unpkg.com/arkgate@4/schemas/ark.status-manifest.schema.json",ws=["full","subset","unavailable"],Ds=["doctor-facts","report-snapshot","none"],Gt={FACTS_UNAVAILABLE:"FACTS_UNAVAILABLE",FACTS_PARTIAL:"FACTS_PARTIAL",NO_SESSION_SNAPSHOT:"NO_SESSION_SNAPSHOT"},Ms=/^sha256:[a-f0-9]{64}$/;function Fs(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"||!Ms.test(r)))return{status:"mismatch",authoritative:!1,code:"INVALID_PROJECT_EXPECTATION",message:"project.expectedProjectId must be a sha256:<64 lowercase hex> identity."};if(n===void 0&&r!==void 0)return e.projectId&&r!==e.projectId?{status:"mismatch",authoritative:!1,expectedProjectId:r,code:"PROJECT_ID_MISMATCH",message:`Expected project id ${r}, but this process is bound to ${e.projectId}.`}:{status:"unverified",authoritative:!1,expectedProjectId:r,message:"project.expectedProjectId matched or could not be compared, but expectedRoot is required for an authoritative workspace binding."};let s=e.expectedRootRelation??"unknown";return s==="outside"?{status:"mismatch",authoritative:!1,expectedRoot:n,expectedProjectId:r,code:"PROJECT_ROOT_MISMATCH",message:`Expected workspace ${n}, but this process is bound to ${e.resolvedRoot}.`}:s==="unknown"?{status:"unverified",authoritative:!1,expectedRoot:n,expectedProjectId:r,message:"Could not prove expectedRoot against the resolved project root (stale or incomplete path evidence)."}:s==="descendant"&&r===void 0?{status:"unverified",authoritative:!1,expectedRoot:n,message:`Expected workspace ${n} is inside this project, but an exact project root is required for the initial authoritative handshake.`}:r!==void 0&&e.projectId&&r!==e.projectId?{status:"mismatch",authoritative:!1,expectedRoot:n,expectedProjectId:r,code:"PROJECT_ID_MISMATCH",message:`Expected project id ${r}, but this process is bound to ${e.projectId}.`}:s==="exact"||s==="descendant"&&r&&r===e.projectId?{status:"matched",authoritative:!0,...n?{expectedRoot:n}:{},...r?{expectedProjectId:r}:{}}:{status:"unverified",authoritative:!1,expectedRoot:n,expectedProjectId:r,message:"Project expectation could not be fully verified."}}i(Fs,"evaluateStatusBinding");function $s(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($s,"classifyStatusWritePath");function Hs(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(Hs,"defaultHonestLabel");function js(e,t,n,r,s){return e.nextActionOverride?.id&&e.nextActionOverride.summary?{id:e.nextActionOverride.id,summary:e.nextActionOverride.summary}:t.status==="mismatch"?{id:"rebind-project-identity",summary:t.message||"Project expectation does not match this process \u2014 call ark_identity / ark status with the correct expectedRoot (and projectId for descendants)."}:t.status==="unverified"&&e.expectation?{id:"complete-identity-handshake",summary:t.message||"Supply project.expectedRoot at the exact project root (and expectedProjectId for descendants) for authoritative status."}:e.resolvedConfigPath?r.verdict==="fail"||(r.activeViolations??0)>0?{id:"fix-active-violations",summary:`Clear ${r.activeViolations??"active"} blocking architecture finding(s), then re-run ark-check (or ark-check --doctor).`}:r.verdict==="incomplete"?{id:"restore-complete-analysis",summary:"Last check was incomplete \u2014 restore TypeScript/analysis inputs and re-run ark-check."}:r.verdict==null&&r.at==null?{id:"run-ark-check",summary:"No last-check snapshot yet \u2014 run ark-check --report (or --doctor) to freeze session evidence."}:n.writePath==="unavailable"?{id:"install-write-path",summary:"Write path is unavailable \u2014 install agent gates for your host (ark start / --install-agent-gates) and keep required CI --strict-merge."}:n.writePath==="advisory"?{id:"keep-ci-merge-hard",summary:"Local write is advisory for this host \u2014 keep a required GitHub status on arkgate-check --strict-merge as the hard merge boundary."}:e.leftoverDesignWork===!0?{id:"map-leftover-design",summary:"Leftover design work remains. Map with /ark-explore, then apply one small refactor with /ark-autopilot. Green imports are not done."}:s.arkRulesLoaded&&(s.frozenResidual??0)>0?{id:"review-arkrules-residual",summary:"ArkRules residual remains frozen \u2014 review inventory debt without claiming a score."}:e.arkRun?.present===!0&&(e.arkRun.residual??0)>0?{id:"review-arkrun-residual",summary:"ArkRun residual remains \u2014 wire kernel usage or declarations through arkgate/runtime. Not a score."}:e.adopted==="required-merge"||e.adopted==="advisory-only-acked"?{id:"stay-enforced",summary:"Contract looks enforceable for this session \u2014 keep writing through the gate and re-check after structural edits."}:{id:"require-ci-merge-status",summary:'Make arkgate-check --strict-merge a required GitHub status, or write .ark/adoption-stance.json with stance: "advisory-only".'}:{id:"run-ark-start",summary:"No ark.config.json found \u2014 run ark start (preview) then ark start --apply."}}i(js,"resolveStatusNextAction");function al(e){let t=typeof e.resolvedRoot=="string"&&e.resolvedRoot.length>0?e.resolvedRoot:".",n=typeof e.projectId=="string"&&Ms.test(e.projectId)?e.projectId:null,r=Fs({resolvedRoot:t,projectId:n,expectation:e.expectation,expectedRootRelation:e.expectedRootRelation}),s=typeof e.activeHost=="string"?e.activeHost.trim().toLowerCase():"",a=s&&s!=="unknown"?s:s==="unknown"?"unknown":null,o=$s({hardWriteActive:e.hardWriteActive,softWriteHost:e.softWriteHost,writePathUnavailable:e.writePathUnavailable,activeHost:a}),l=typeof e.honestLabel=="string"&&e.honestLabel.trim().length>0?e.honestLabel.trim():Hs(o,a),c={at:typeof e.lastCheckAt=="string"?e.lastCheckAt:null,verdict:e.lastCheckVerdict==="pass"||e.lastCheckVerdict==="fail"||e.lastCheckVerdict==="incomplete"?e.lastCheckVerdict:null,activeViolations:yt(e.activeViolations),frozenResidual:yt(e.frozenResidual)},p={arkRulesLoaded:e.arkRulesLoaded===!0,inventoried:yt(e.rulesInventoried),underContract:yt(e.rulesUnderContract),frozenResidual:yt(e.rulesFrozenResidual)},g={writePath:o,host:a,honestLabel:l},y={projectId:n,resolvedRoot:t,resolvedConfigPath:typeof e.resolvedConfigPath=="string"&&e.resolvedConfigPath.length>0?e.resolvedConfigPath:null,binding:r.status,authoritative:r.authoritative,...r.code?{code:r.code}:{},...r.message?{message:r.message}:{}},f={schemaVersion:tr,arkgateVersion:typeof e.arkgateVersion=="string"&&e.arkgateVersion.length>0?e.arkgateVersion:"unknown",projectIdentity:y,activation:g,lastCheck:c,rules:p,nextAction:js(e,r,g,c,p)},u=Ks(e.improvementCompass);return u&&(f.improvementCompass=u),e.vsBase&&typeof e.vsBase.baseRef=="string"&&e.vsBase.baseRef.length>0&&(f.vsBase=e.vsBase),e.arkRun&&typeof e.arkRun=="object"&&(f.arkRun=Zn(e.arkRun)),f}i(al,"buildStatusManifest");var Vs=new Set(ws),ol=new Set(Ds);function nr(e){let t=Vs.has(e.mode)?e.mode:"unavailable",n=e.factsSource!=null&&ol.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 o={schemaVersion:"1.0",notAScore:!0,mode:"unavailable",topResidual:[],reasonCode:typeof e.reasonCode=="string"&&e.reasonCode.length>0?e.reasonCode:Gt.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&&(o.contractHash=r),o}let s=Array.isArray(e.topResidual)?e.topResidual.filter(o=>typeof o=="string"&&o.length>0).slice(0,15):[],a={schemaVersion:"1.0",notAScore:!0,mode:t,topResidual:s};return t==="subset"?(a.reasonCode=typeof e.reasonCode=="string"&&e.reasonCode.length>0?e.reasonCode:Gt.FACTS_PARTIAL,a.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&&(a.reasonCode=e.reasonCode),typeof e.reason=="string"&&e.reason.length>0&&t==="full"&&(a.reason=e.reason),n&&(a.factsSource=n),r&&(a.contractHash=r),a}i(nr,"projectStatusImprovementCompass");function il(e={}){return nr({mode:"unavailable",topResidual:[],reasonCode:e.reasonCode??Gt.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(il,"unavailableStatusImprovementCompass");function Ks(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"&&Vs.has(t.mode)?n=t.mode:Array.isArray(t.topResidual)?n="subset":n="unavailable",nr({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(Ks,"normalizeStatusImprovementCompass");function ll(e,t){let n=Array.isArray(e)?e:[],r=new Set(Array.isArray(t)?t:[]);for(let s of n)if(!(typeof s!="string"||s.length===0)&&!r.has(s))return!1;return!0}i(ll,"statusCompassResidualIsSubsetOfDoctor");function yt(e){if(e==null)return null;let t=Number(e);return!Number.isFinite(t)||t<0?null:Math.floor(t)}i(yt,"numberOrNull");var cl={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Ls,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:tr},arkgateVersion:{type:"string",minLength:1},projectIdentity:{type:"object",additionalProperties:!1,required:["projectId","resolvedRoot","resolvedConfigPath","binding","authoritative"],properties:{projectId:{anyOf:[{type:"string",pattern:"^sha256:[a-f0-9]{64}$"},{type:"null"}]},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{anyOf:[{type:"string",minLength:1},{type:"null"}]},binding:{enum:["matched","unverified","mismatch"]},authoritative:{type:"boolean"},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},activation:{type:"object",additionalProperties:!1,required:["writePath","host","honestLabel"],properties:{writePath:{enum:["hard","advisory","unavailable"]},host:{anyOf:[{type:"string",minLength:1},{type:"null"}]},honestLabel:{type:"string",minLength:1}}},lastCheck:{type:"object",additionalProperties:!1,required:["at","verdict","activeViolations","frozenResidual"],properties:{at:{anyOf:[{type:"string",minLength:1},{type:"null"}]},verdict:{anyOf:[{enum:["pass","fail","incomplete"]},{type:"null"}]},activeViolations:{anyOf:[{type:"integer",minimum:0},{type:"null"}]},frozenResidual:{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}},rules:{type:"object",additionalProperties:!1,required:["arkRulesLoaded","inventoried","underContract","frozenResidual"],properties:{arkRulesLoaded:{type:"boolean"},inventoried:{anyOf:[{type:"integer",minimum:0},{type:"null"}]},underContract:{anyOf:[{type:"integer",minimum:0},{type:"null"}]},frozenResidual:{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}},nextAction:{type:"object",additionalProperties:!1,required:["id","summary"],properties:{id:{type:"string",minLength:1},summary:{type:"string",minLength:1}}},improvementCompass:{type:"object",description:"Thin improvement-compass residual ids with honesty mode (notAScore). full | subset | unavailable. Never a gate input; full lenses on doctor JSON. When full, residual ids \u2286 doctor residual for the same facts. unavailable never invents green residual.",additionalProperties:!1,required:["schemaVersion","notAScore","mode","topResidual"],properties:{schemaVersion:{const:"1.0"},notAScore:{const:!0},mode:{enum:["full","subset","unavailable"]},topResidual:{type:"array",items:{type:"string",minLength:1},maxItems:15},reasonCode:{type:"string",minLength:1},reason:{type:"string",minLength:1},factsSource:{enum:["doctor-facts","report-snapshot","none"]},contractHash:{type:"string",minLength:1}}},vsBase:{type:"object",description:"Checkout vs a git base ref: pin, contract identity, baseline grow. Advisory honesty only \u2014 never a gate input.",additionalProperties:!1,required:["baseRef","line","pinLocal","pinBase","contractEqual","baselineGrew"],properties:{baseRef:{type:"string",minLength:1},line:{type:"string",minLength:1},pinLocal:{anyOf:[{type:"string",minLength:1},{type:"null"}]},pinBase:{anyOf:[{type:"string",minLength:1},{type:"null"}]},contractEqual:{type:"boolean"},baselineGrew:{type:"boolean"}}},arkRun:{type:"object",description:"ArkRun extra residual (notAScore). present/mode from config; residual is a finding-id count (null = unknown, not green). extraMergeTeeth is honesty, never a score.",additionalProperties:!1,required:["notAScore","present","mode","extraMergeTeeth","residual"],properties:{notAScore:{const:!0},present:{type:"boolean"},mode:{anyOf:[{enum:["advisory","enforced"]},{type:"null"}]},extraMergeTeeth:{type:"boolean"},residual:{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}}}};var Bt="1.0",zt=["soc","cohesion","coupling","srp","dip","ocp","encapsulation","modularity","scalability","resilience","security","maintainability","testability","domain","stack"],qt=5,Pe=["scalability","resilience","security"],Be=new Set(Pe),rr={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},sr={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"},ar={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 or(e){return sr[e]??e}i(or,"improvementCompassHumanLabel");function ir(e){let t=e.id??e.smellId??"";return typeof t=="string"?t.trim():""}i(ir,"smellIdOf");function lr(e){let t=e.ruleId??e.code??"";return typeof t=="string"?t.trim():""}i(lr,"violationRuleId");function K(e,t,n,r){if(!n||e.evidence.some(a=>a.source===t&&a.ref===n))return;let s={source:t,ref:n};r&&r.trim()&&(s.detail=r.trim().slice(0,240)),e.evidence.push(s)}i(K,"pushEvidence");function Q(e,t,n){Be.has(e.id)||(e.status="residual",e.summary=t,n&&(e.nextAction=n))}i(Q,"markResidual");function Us(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`${sr[e]} \u2014 no residual from current sensors.`}}i(Us,"defaultOkSummary");function Gs(){return zt.map(e=>Be.has(e)?{id:e,status:"out-of-scope",summary:ar[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:Us(e),evidence:[]}:{id:e,status:"ok",summary:Us(e),evidence:[]})}i(Gs,"createInitialImprovementCompassLenses");function dl(e,t){for(let n of t){let r=ir(n);if(!r)continue;let s=n.outcome||n.message||void 0,o=(Array.isArray(n.evidence)?n.evidence:[])[0],l=i((g,y,f)=>{let u=e.get(g);!u||Be.has(g)||(K(u,"designSmells",r,s),o&&K(u,"designSmells",o,r),Q(u,y,f))},"attach"),c={kind:"skill",ref:"/ark-explore",summary:"Map Shape residual (shape-focus), then apply one extraction pilot with /ark-autopilot."},p={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.",p);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.",p),l("testability","Direct I/O under application code hurts pure unit testing.",p);break;case"handler-in-persistence":l("soc","HTTP/transport handlers live under persistence folders.",c);break;case"god-module":l("cohesion","Large multi-responsibility modules reduce cohesion.",c),l("srp","God modules own too many responsibilities \u2014 split by concern (one pilot).",{kind:"skill",ref:"/ark-autopilot",summary:"One Shape pilot this turn \u2014 never multi-pilot batch."});break;case"mixed-pattern-cluster":l("modularity","Multiple layout styles coexist \u2014 placement is unclear for the next AI turn.",{kind:"skill",ref:"/ark-explore",summary:"Pick a golden pattern and migrate one pilot cluster on touch."}),l("cohesion","Mixed layout styles scatter the same concern across patterns.",c);break;case"soft-contract":l("maintainability","Soft contract walls (layers without deny rules) hide maintainability debt.",{kind:"skill",ref:"/ark-adopt",summary:"Add real layer rules so the AI has hard walls."}),l("coupling","Layers with files but almost no deny rules allow free peer coupling.",{kind:"skill",ref:"/ark-adopt",summary:"Tighten inter-layer allows/denies without weakening enforcement."});break;default:l("maintainability","Design residual remains under an unrecognized smell id \u2014 review evidence.",c);break}}}i(dl,"mapDesignSmells");function ul(e){return e.failsStrict===!1||e.typeOnly===!0}i(ul,"isTypeOnlyPlacementDebt");function pl(e,t){for(let n of t){let r=lr(n);if(!r)continue;let s=n.message,a=r.toUpperCase(),o=i((c,p,g)=>{let y=e.get(c);!y||Be.has(c)||(K(y,"violations",r,s),n.file&&K(y,"violations",n.file,r),Q(y,p,g))},"attach");if(ul(n)){o("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(a==="LAYER_IMPORT_VIOLATION"||a.includes("LAYER_IMPORT")||a==="DYNAMIC_IMPORT_VIOLATION"){o("coupling","Import graph edges violate the layer contract.",l);continue}if(a.includes("CYCLE")||a==="CIRCULAR_DEPENDENCY"){o("coupling","Import cycles couple modules tightly.",l);continue}if(a.includes("PEER_ISOLATION")||a==="PEER_ISOLATION_VIOLATION"){o("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(a==="FORBIDDEN_GLOBAL"||a.startsWith("FORBIDDEN_")){o("dip","Forbidden globals / effect surfaces break dependency inversion.",{kind:"skill",ref:"/ark-autopilot",summary:"Inject a port instead of the forbidden global."}),o("testability","Forbidden ambient effects reduce pure-domain testability.",{kind:"skill",ref:"/ark-autopilot",summary:"Replace ambient effects with injectable ports."});continue}if(a==="CAPABILITY_VIOLATION"){o("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)."}),o("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(a.startsWith("ARKRULE_")||a==="INVARIANT_UNCOVERED"){o("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."}),o("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(pl,"mapViolations");function fl(e,t){let n=Number(t.cycleCount)||0;if(n>0){let u=e.get("coupling");K(u,"cycles",`count:${n}`),Q(u,"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 u=e.get("coupling");K(u,"peerIsolation",`count:${r}`),Q(u,"Peer isolation residual remains.",{kind:"skill",ref:"/ark-autopilot",summary:"Peer isolation is judgment-class residual."})}let s=Number(t.physicalCohesionFindingCount)||0;if(s>0){let u=e.get("cohesion");K(u,"physicalCohesion",`findings:${s}`),Q(u,"Physical cohesion residual \u2014 mirrored concept clusters across anchors.",{kind:"skill",ref:"/ark-explore",summary:"Review reshape pilot; one decision-aware pilot at a time."});let m=e.get("srp");K(m,"physicalCohesion",`findings:${s}`),Q(m,"Mirrored clusters suggest split-by-concern residual (architecture SRP).",{kind:"skill",ref:"/ark-autopilot",summary:"One reshape/extraction pilot this turn."})}let a=Number(t.pureOrCapabilityResidual)||0,o=Number(t.forbiddenGlobalResidual)||0;if(a>0||o>0){let u=e.get("dip");a>0&&K(u,"capability",`residual:${a}`),o>0&&K(u,"forbiddenGlobals",`residual:${o}`),Q(u,"Pure / capability / forbidden residual weakens dependency inversion.",{kind:"skill",ref:"/ark-autopilot",summary:"Inject ports; keep pure layers free of effects."});let m=e.get("testability");a>0&&K(m,"capability",`residual:${a}`),o>0&&K(m,"forbiddenGlobals",`residual:${o}`),Q(m,"Impure domain or capability residual reduces testability.",{kind:"skill",ref:"/ark-autopilot",summary:"Prefer ports over concrete I/O in pure/domain modules."})}let l=Number(t.arkRulesStructureResidual)||0;if(l>0){let u=e.get("encapsulation");K(u,"arkRules",`structureResidual:${l}`),Q(u,"ArkRules structure residual \u2014 encapsulation inside the layer.",{kind:"skill",ref:"/ark-autopilot",summary:"Fix structure sensors under [ArkRules] without inventing mechanical-safe."});let m=e.get("domain");K(m,"arkRules",`structureResidual:${l}`),Q(m,"ArkRules residual may mean domain shape is not yet under contract.",{kind:"skill",ref:"/ark-explore",summary:"Map inventory candidates; one pilot rule at a time."})}else t.arkRulesLoaded===!1||t.arkRulesLoaded==null;if(t.designWeak===!0){let u=e.get("maintainability");K(u,"designFitness","design-weak"),Q(u,"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 u=e.get("maintainability");t.dirtyBaselineRisk===!0&&K(u,"baseline","dirty-freeze-risk"),(Number(t.baselineStale)||0)>0&&K(u,"baseline",`stale:${t.baselineStale}`),Q(u,"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 u=e.get("maintainability");K(u,"baseline",`frozen:${c}`),Q(u,"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 p=Number(t.ungovernedDirCount)||0,g=Number(t.emptyLayerCount)||0;if(p>0||g>0){let u=e.get("modularity");p>0&&K(u,"coverage",`ungovernedDirs:${p}`),g>0&&K(u,"coverage",`emptyLayers:${g}`),Q(u,"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 u=e.get("modularity");K(u,"goldenPattern","absent"),Q(u,"Design-weak without a golden pattern \u2014 new code lacks a placement norm for the AI.",{kind:"skill",ref:"/ark-place",summary:"Record an advisory golden pattern for new code (does not clear design-weak)."})}let y=e.get("stack");(t.stackKind??null)==="typescript"?y.status==="ok"&&(y.summary="Stack practices are partially instrumented for TypeScript / host / Ark idioms only \u2014 not a full framework checklist."):(y.status="not-instrumented",y.summary="Stack-specific best practices outside TypeScript/host/Ark idioms are not instrumented.",y.evidence=[],y.nextAction={kind:"docs",ref:"docs/use.md#improvement-compass",summary:"Ark does not score non-TS stack idioms."})}i(fl,"mapCountsAndFlags");function Bs(e,t){if(Array.isArray(t.designSmells)&&t.designSmells.length>0){let n=[...t.designSmells].sort((r,s)=>ir(r).localeCompare(ir(s)));dl(e,n)}if(Array.isArray(t.violations)&&t.violations.length>0){let n=[...t.violations].sort((r,s)=>{let a=lr(r).localeCompare(lr(s));return a!==0?a:String(r.file??"").localeCompare(String(s.file??""))});pl(e,n)}fl(e,t)}i(Bs,"projectImprovementCompassFacts");function zs(e){for(let t of Pe){let n=e.get(t);n.status="out-of-scope",n.summary=ar[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(zs,"lockImprovementCompassOutOfScope");function qs(e){for(let t of e)t.evidence.sort((n,r)=>{let s=n.source.localeCompare(r.source);return s!==0?s:n.ref.localeCompare(r.ref)})}i(qs,"sortImprovementCompassEvidence");function Ws(e){return e.filter(n=>n.status==="residual"&&!Be.has(n.id)).slice().sort((n,r)=>{let s=rr[n.id]??150,a=rr[r.id]??150;return s!==a?s-a:n.id.localeCompare(r.id)}).slice(0,5).map(n=>n.id)}i(Ws,"finalizeImprovementCompassTopResidual");function ml(e={}){let t=Gs(),n=new Map(t.map(s=>[s.id,s]));Bs(n,e),zs(n),qs(t);let r=Ws(t);return{schemaVersion:"1.0",notAScore:!0,lenses:t.map(s=>{let a={id:s.id,status:s.status,summary:s.summary,evidence:s.evidence.map(o=>({...o}))};return s.nextAction&&(a.nextAction={...s.nextAction}),a}),topResidual:r}}i(ml,"buildImprovementCompass");function Ys(e){return e.topResidual.map(t=>or(t))}i(Ys,"formatImprovementCompassResidualLabels");function Xs(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(Xs,"primaryImprovementCompassNextAction");function gl(e){let t=Ys(e),n=Pe.map(a=>or(a)),r=Xs(e),s=[];return t.length>0?s.push(`Residual: ${t.join(" \xB7 ")}`):s.push("Residual: none on instrumented lenses (not a score \u2014 green edges \u2260 finished design)."),s.push(`Out of scope (honest): ${n.join(" \xB7 ")}`),r&&s.push(`Next: ${r.ref} \u2014 ${r.summary}`),s}i(gl,"formatImprovementCompassDoctorLines");var yl="1.0",hl="<!-- arkgate:agent-projection:begin",Js="<!-- arkgate:agent-projection:end -->",Zs="This projection is **non-authoritative**. Enforcement is `ark-check` / host write hooks / required CI (`--strict-merge`), not AGENTS.md, skills, or this block.",ur=Object.freeze(["ark-check","host-write-hooks","ci-strict-merge"]),Al=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"]),pr=/<!--\s*arkgate:agent-projection:begin\b([^>]*)-->/i,Qs=/<!--\s*arkgate:agent-projection:end\s*-->/i,Rl=/\barkgateVersion=([A-Za-z0-9._+-]+)/i,kl=/\bschema=([A-Za-z0-9._+-]+)/i;function Wt(e){let t=String(e??"").replace(/\r\n/g,`
17
+ `),n=2166136261;for(let r=0;r<t.length;r+=1)n^=t.charCodeAt(r),n=Math.imul(n,16777619);return`fnv1a-${(n>>>0).toString(16).padStart(8,"0")}`}i(Wt,"agentProjectionContentIdentity");function Yt(e){return String(e??"").replace(/\r\n/g,`
18
+ `)}i(Yt,"normalizeNewlines");function ze(e){let t=Yt(e);return t.endsWith(`
19
19
  `)?t:`${t}
20
- `}i(Ge,"ensureTrailingNewline");function Wt(e){return typeof e!="string"||e.trim().length===0?"unknown":e.trim().replace(/[>\s]/g,"")}i(Wt,"safeVersion");function Xs(e){return e==="compact"?"compact":"full"}i(Xs,"resolveProfile");function Qs(e){let t=Wt(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(Qs,"buildAgentProjectionBeginMarker");function ir(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 |
20
+ `}i(ze,"ensureTrailingNewline");function Xt(e){return typeof e!="string"||e.trim().length===0?"unknown":e.trim().replace(/[>\s]/g,"")}i(Xt,"safeVersion");function ea(e){return e==="compact"?"compact":"full"}i(ea,"resolveProfile");function ta(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(ta,"buildAgentProjectionBeginMarker");function cr(e){return!Array.isArray(e)||e.length===0?"_No project layers loaded \u2014 read `ark.config.json` or run `ark start` / `ark_manifest`._":`| Layer | Patterns | Intent prefixes |
21
21
  |-------|----------|-----------------|
22
- ${e.map(n=>{let r=n.name?.trim()||"Unknown",s=n.patterns??[],o=n.intentPrefixes??[],a=s.map(c=>`\`${c}\``).join(", ")||"\u2014",l=o.map(c=>`\`${c}\``).join(", ")||"\u2014";return`| ${r} | ${a} | ${l} |`}).join(`
23
- `)}`}i(ir,"formatAgentProjectionLayers");function eo(e,t){let n=t.trim()||"docs/diagnostics.md";return!Array.isArray(e)||e.length===0?`Full public codes: \`${n}\` (and package \`DIAGNOSTIC_CATALOG\`).`:`${e.filter(s=>s&&typeof s.ruleId=="string"&&s.ruleId.length>0).map(s=>{let o=typeof s.title=="string"&&s.title.trim()?s.title.trim():s.ruleId;return`- \`${s.ruleId}\` \u2014 ${o}`}).join(`
22
+ ${e.map(n=>{let r=n.name?.trim()||"Unknown",s=n.patterns??[],a=n.intentPrefixes??[],o=s.map(c=>`\`${c}\``).join(", ")||"\u2014",l=a.map(c=>`\`${c}\``).join(", ")||"\u2014";return`| ${r} | ${o} | ${l} |`}).join(`
23
+ `)}`}i(cr,"formatAgentProjectionLayers");function na(e,t){let n=t.trim()||"docs/diagnostics.md";return!Array.isArray(e)||e.length===0?`Full public codes: \`${n}\` (and package \`DIAGNOSTIC_CATALOG\`).`:`${e.filter(s=>s&&typeof s.ruleId=="string"&&s.ruleId.length>0).map(s=>{let a=typeof s.title=="string"&&s.title.trim()?s.title.trim():s.ruleId;return`- \`${s.ruleId}\` \u2014 ${a}`}).join(`
24
24
  `)}
25
25
 
26
- Full catalog: \`${n}\` (\`#RULE_ID\` anchors).`}i(eo,"formatAgentProjectionCatalogShortList");function ur(e){let t=Wt(e.arkgateVersion),n=Xs(e.profile),r=typeof e.checkCommand=="string"&&e.checkCommand.trim()?e.checkCommand.trim():"ark-check --strict-config",s=typeof e.diagnosticsDocsPath=="string"&&e.diagnosticsDocsPath.trim()?e.diagnosticsDocsPath.trim():"docs/diagnostics.md",o=typeof e.host=="string"?e.host.trim().toLowerCase():"",a=o&&o!=="unknown"?o:null,l=Array.isArray(e.layers)?e.layers:[],c=Array.isArray(e.catalogShortList)?e.catalogShortList:[],p=["## ArkGate agent contract projection","",Js,"",`- **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"?p.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)","",ir(l),""):p.push("### Contract layers","",ir(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)","",eo(c,s),"","### Session truth","","- Machine snapshot: `ark status --json` (or MCP `ark_status`) \u2014 identity, activation honesty, last check, residual counts. **Not a score.**","- Authoritative contract: local `ark.config.json` / CLI, or `ark_manifest` after a matched `ark_identity` handshake. Identity is optional when CLI already resolved the root.","- Host docs: the same projection schema is merged into `AGENTS.md` and `CLAUDE.md` (`ark agents-md --write`).",""),p.push("### Enforcement surfaces (authoritative)","",cr.map(m=>`- \`${m}\``).join(`
26
+ Full catalog: \`${n}\` (\`#RULE_ID\` anchors).`}i(na,"formatAgentProjectionCatalogShortList");function fr(e){let t=Xt(e.arkgateVersion),n=ea(e.profile),r=typeof e.checkCommand=="string"&&e.checkCommand.trim()?e.checkCommand.trim():"ark-check --strict-config",s=typeof e.diagnosticsDocsPath=="string"&&e.diagnosticsDocsPath.trim()?e.diagnosticsDocsPath.trim():"docs/diagnostics.md",a=typeof e.host=="string"?e.host.trim().toLowerCase():"",o=a&&a!=="unknown"?a:null,l=Array.isArray(e.layers)?e.layers:[],c=Array.isArray(e.catalogShortList)?e.catalogShortList:[],p=["## ArkGate agent contract projection","",Zs,"",`- **arkgateVersion:** \`${t}\` (must match the installed package; regenerate with \`ark agents-md --write\` after upgrade)`,"- **projectionSchema:** `1.0`",`- **profile:** \`${n}\`${o?` \xB7 **host:** \`${o}\``:""}`,`- **after edits:** \`${r}\``,""];return n==="compact"?p.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)","",cr(l),""):p.push("### Contract layers","",cr(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)","",na(c,s),"","### Session truth","","- Machine snapshot: `ark status --json` (or MCP `ark_status`) \u2014 identity, activation honesty, last check, residual counts. **Not a score.**","- Authoritative contract: local `ark.config.json` / CLI, or `ark_manifest` after a matched `ark_identity` handshake. Identity is optional when CLI already resolved the root.","- Host docs: the same projection schema is merged into `AGENTS.md` and `CLAUDE.md` (`ark agents-md --write`).",""),p.push("### Enforcement surfaces (authoritative)","",ur.map(g=>`- \`${g}\``).join(`
27
27
  `),""),p.join(`
28
28
  `).replace(/\n{3,}/g,`
29
29
 
30
30
  `).trimEnd()+`
31
- `}i(ur,"buildAgentProjectionBody");function hl(e){let t=ur(e);return`${Qs({arkgateVersion:e.arkgateVersion,schemaVersion:"1.0"})}
32
- ${t}${Ws}
33
- `}i(hl,"buildAgentProjectionBlock");function Al(e){let t=ur(e),n=Array.isArray(e.layers)?e.layers:[],r=Array.isArray(e.catalogShortList)?e.catalogShortList:[];return{schemaVersion:"1.0",arkgateVersion:Wt(e.arkgateVersion),nonAuthoritative:!0,enforcementSurfaces:[...cr],contentIdentity:qt(t),layerCount:n.length,catalogCodeCount:r.filter(s=>s?.ruleId).length,profile:Xs(e.profile)}}i(Al,"buildAgentProjectionMeta");function lr(e){let t=Yt(e??""),n=dr.exec(t);if(!n)return{block:null,body:null,before:t,after:"",beginAttrs:null};let r=n.index,s=r+n[0].length,o=t.slice(s),a=Zs.exec(o);if(!a)return{block:null,body:null,before:t,after:"",beginAttrs:null};let l=a.index,c=l+a[0].length,p=o.slice(0,l);p.startsWith(`
34
- `)&&(p=p.slice(1));let m=t.slice(r,s+c),g=o.slice(c);return{block:m,body:p,before:t.slice(0,r),after:g,beginAttrs:n[1]??""}}i(lr,"extractAgentProjectionBlock");function to(e){let t=String(e??""),r=dr.exec(t)?.[1]??t,s=gl.exec(r),o=yl.exec(r),a=/\bnonAuthoritative\s*=\s*true\b/i.test(r);return{arkgateVersion:s?.[1]??null,schemaVersion:o?.[1]??null,nonAuthoritative:a}}i(to,"parseAgentProjectionStamp");function Rl(e,t){let n=to(e).arkgateVersion;return n?n===Wt(t):!1}i(Rl,"projectionMatchesPackageVersion");function kl(e){return String(e??"").includes("non-authoritative")}i(kl,"projectionHasNonEnforcementLabel");function El(e,t){let n=Ge(Yt(t)),s=lr(n).body??n.replace(dr,"").replace(Zs,"").trim()+`
35
- `,o=qt(s);if(e==null||!String(e).trim())return{content:Ge(`# Ark Enforcement
31
+ `}i(fr,"buildAgentProjectionBody");function El(e){let t=fr(e);return`${ta({arkgateVersion:e.arkgateVersion,schemaVersion:"1.0"})}
32
+ ${t}${Js}
33
+ `}i(El,"buildAgentProjectionBlock");function Il(e){let t=fr(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:[...ur],contentIdentity:Wt(t),layerCount:n.length,catalogCodeCount:r.filter(s=>s?.ruleId).length,profile:ea(e.profile)}}i(Il,"buildAgentProjectionMeta");function dr(e){let t=Yt(e??""),n=pr.exec(t);if(!n)return{block:null,body:null,before:t,after:"",beginAttrs:null};let r=n.index,s=r+n[0].length,a=t.slice(s),o=Qs.exec(a);if(!o)return{block:null,body:null,before:t,after:"",beginAttrs:null};let l=o.index,c=l+o[0].length,p=a.slice(0,l);p.startsWith(`
34
+ `)&&(p=p.slice(1));let g=t.slice(r,s+c),y=a.slice(c);return{block:g,body:p,before:t.slice(0,r),after:y,beginAttrs:n[1]??""}}i(dr,"extractAgentProjectionBlock");function ra(e){let t=String(e??""),r=pr.exec(t)?.[1]??t,s=Rl.exec(r),a=kl.exec(r),o=/\bnonAuthoritative\s*=\s*true\b/i.test(r);return{arkgateVersion:s?.[1]??null,schemaVersion:a?.[1]??null,nonAuthoritative:o}}i(ra,"parseAgentProjectionStamp");function Sl(e,t){let n=ra(e).arkgateVersion;return n?n===Xt(t):!1}i(Sl,"projectionMatchesPackageVersion");function bl(e){return String(e??"").includes("non-authoritative")}i(bl,"projectionHasNonEnforcementLabel");function vl(e,t){let n=ze(Yt(t)),s=dr(n).body??n.replace(pr,"").replace(Qs,"").trim()+`
35
+ `,a=Wt(s);if(e==null||!String(e).trim())return{content:ze(`# Ark Enforcement
36
36
 
37
- ${n}`),action:"created",previousBlock:null,contentIdentity:o,preservedOutsideBlock:!1};let a=Yt(e),l=lr(a);if(l.block!=null){let p=l.body??"";if(qt(p)===o)return{content:Ge(a),action:"unchanged",previousBlock:l.block,contentIdentity:o,preservedOutsideBlock:!0};let m=l.before.replace(/\s*$/,`
37
+ ${n}`),action:"created",previousBlock:null,contentIdentity:a,preservedOutsideBlock:!1};let o=Yt(e),l=dr(o);if(l.block!=null){let p=l.body??"";if(Wt(p)===a)return{content:ze(o),action:"unchanged",previousBlock:l.block,contentIdentity:a,preservedOutsideBlock:!0};let g=l.before.replace(/\s*$/,`
38
38
 
39
- `),g=l.after.replace(/^\s*/,`
40
- `);return{content:Ge(`${m}${n.trimEnd()}
41
- ${g}`),action:"block-replaced",previousBlock:l.block,contentIdentity:o,preservedOutsideBlock:!0}}let c=/^(#\s+[^\n]*\n)/m.exec(a);if(c&&c.index!=null){let p=c.index+c[1].length,m=a.slice(0,p).replace(/\s*$/,`
39
+ `),y=l.after.replace(/^\s*/,`
40
+ `);return{content:ze(`${g}${n.trimEnd()}
41
+ ${y}`),action:"block-replaced",previousBlock:l.block,contentIdentity:a,preservedOutsideBlock:!0}}let c=/^(#\s+[^\n]*\n)/m.exec(o);if(c&&c.index!=null){let p=c.index+c[1].length,g=o.slice(0,p).replace(/\s*$/,`
42
42
 
43
- `),g=a.slice(p).replace(/^\s*/,`
44
- `);return{content:Ge(`${m}${n.trimEnd()}
45
- ${g}`),action:"block-inserted",previousBlock:null,contentIdentity:o,preservedOutsideBlock:!0}}return{content:Ge(`${n.trimEnd()}
43
+ `),y=o.slice(p).replace(/^\s*/,`
44
+ `);return{content:ze(`${g}${n.trimEnd()}
45
+ ${y}`),action:"block-inserted",previousBlock:null,contentIdentity:a,preservedOutsideBlock:!0}}return{content:ze(`${n.trimEnd()}
46
46
 
47
- ${a.trimStart()}`),action:"block-inserted",previousBlock:null,contentIdentity:o,preservedOutsideBlock:!0}}i(El,"mergeAgentProjectionDocument");var Sl="1.0",no="templates/agent-skills",ro="templates/skills",so="SKILL.md",Jt=Object.freeze(["ark-adopt","ark-architect","ark-autopilot","ark-contract","ark-coverage","ark-explain","ark-explore","ark-fix","ark-loop","ark-place","ark-runtime","ark-think","ark-upgrade"]),oo=Jt.length,Il=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function ao(e){return typeof e!="string"||e.length<1||e.length>64?!1:Il.test(e)}i(ao,"isValidAgentSkillName");function fr(e){return Jt.includes(e)}i(fr,"isArkSkillName");function io(e){let t=String(e??"").replace(/^\uFEFF/,""),n=t.includes(`\r
47
+ ${o.trimStart()}`),action:"block-inserted",previousBlock:null,contentIdentity:a,preservedOutsideBlock:!0}}i(vl,"mergeAgentProjectionDocument");var Cl="1.0",sa="templates/agent-skills",aa="templates/skills",oa="SKILL.md",Jt=Object.freeze(["ark-adopt","ark-architect","ark-autopilot","ark-contract","ark-coverage","ark-explain","ark-explore","ark-fix","ark-loop","ark-place","ark-runtime","ark-think","ark-upgrade"]),ia=Jt.length,Ol=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function la(e){return typeof e!="string"||e.length<1||e.length>64?!1:Ol.test(e)}i(la,"isValidAgentSkillName");function gr(e){return Jt.includes(e)}i(gr,"isArkSkillName");function ca(e){let t=String(e??"").replace(/^\uFEFF/,""),n=t.includes(`\r
48
48
  `)?`\r
49
49
  `:`
50
- `,r=t.split(/\r?\n/);if(r[0]!=="---")return{hasFrontmatter:!1,frontmatter:null,body:t};let s=r.indexOf("---",1);if(s===-1)return{hasFrontmatter:!1,frontmatter:null,body:t};let o={};for(let m=1;m<s;m+=1){let g=r[m]??"";if(g.trim()===""||g.trimStart().startsWith("#"))continue;let u=g.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);if(!u)continue;let d=u[1],f=u[2]??"";(f.startsWith('"')&&f.endsWith('"')&&f.length>=2||f.startsWith("'")&&f.endsWith("'")&&f.length>=2)&&(f=f.slice(1,-1)),o[d]=f}let a=r.slice(s+1).join(n),l=typeof o.name=="string"&&o.name.length>0?o.name:null,c=typeof o.description=="string"&&o.description.length>0?o.description:null,p=typeof o.license=="string"&&o.license.length>0?o.license:null;return{hasFrontmatter:!0,frontmatter:{fields:o,name:l,description:c,license:p},body:a}}i(io,"parseSkillDocument");function lo(e){let t=e.requireArkSkillName!==!1,n=e.requireBody!==!1,r=[],s=String(e.directoryName??""),o=io(e.content);if(!o.hasFrontmatter||!o.frontmatter)return r.push({code:"MISSING_FRONTMATTER",message:`Skill "${s}" is missing YAML frontmatter fences.`,skillName:s||void 0}),r;let{name:a,description:l}=o.frontmatter,c=a??(s||void 0);return!a||!ao(a)?r.push({code:"INVALID_NAME",message:`Skill name "${a??""}" is invalid (Agent Skills: 1\u201364 chars, [a-z0-9-], no leading/trailing/consecutive hyphens).`,skillName:c}):a!==s?r.push({code:"NAME_DIRECTORY_MISMATCH",message:`Frontmatter name "${a}" must match directory name "${s}".`,skillName:a}):t&&!fr(a)&&r.push({code:"UNKNOWN_SKILL_NAME",message:`Skill name "${a}" is not in the frozen Ark 13-skill catalog (no new skill names).`,skillName:a}),l?l.length>1024&&r.push({code:"DESCRIPTION_TOO_LONG",message:`Skill "${s}" description exceeds 1024 characters (${l.length}).`,skillName:c}):r.push({code:"MISSING_DESCRIPTION",message:`Skill "${s}" is missing a non-empty description.`,skillName:c}),n&&o.body.trim().length===0&&r.push({code:"EMPTY_BODY",message:`Skill "${s}" has an empty instruction body.`,skillName:c}),r}i(lo,"validateAgentSkillDocument");function vl(e){let t=[],n=new Set,r=[];for(let s of e){let o=String(s.name??"");if(n.has(o)){t.push({code:"DUPLICATE_SKILL",message:`Duplicate skill entry "${o}".`,skillName:o});continue}n.add(o),r.push(o),t.push(...lo({directoryName:o,content:s.content,requireArkSkillName:!0,requireBody:!0})),s.flatTemplateContent!=null&&pr(s.content)!==pr(s.flatTemplateContent)&&t.push({code:"CONTENT_MISMATCH",message:`Agent Skills SKILL.md for "${o}" does not match flat template templates/skills/${o}.md.`,skillName:o})}for(let s of Jt)n.has(s)||t.push({code:"MISSING_SKILL",message:`Missing frozen skill "${s}" from Agent Skills package.`,skillName:s});for(let s of r)fr(s)||(t.some(o=>o.code==="UNKNOWN_SKILL_NAME"&&o.skillName===s)?t.push({code:"EXTRA_SKILL",message:`Extra skill "${s}" is not in the frozen Ark 13-skill catalog.`,skillName:s}):t.push({code:"EXTRA_SKILL",message:`Extra skill "${s}" is not in the frozen Ark 13-skill catalog.`,skillName:s}));return r.sort(),{ok:t.length===0,issues:t,names:r,expectedCount:oo,presentCount:r.length}}i(vl,"validateAgentSkillsPackage");var mr=/^arkgate@(\S+)\.\s/;function co(e){let t=String(e??"").trim();return t?`arkgate@${t}. `:""}i(co,"skillDescriptionVersionPrefix");function uo(e){return String(e??"").replace(mr,"")}i(uo,"stripSkillDescriptionVersion");function bl(e){return String(e??"").match(mr)?.[1]??null}i(bl,"parseSkillDescriptionVersion");function Cl(e,t){let n=uo(e),r=typeof t=="string"?t.trim():"";return r?`${co(r)}${n}`:n}i(Cl,"stampSkillDescription");function pr(e){return String(e??"").replace(/^\uFEFF/,"").replace(/\r\n/g,`
51
- `)}i(pr,"normalizeSkillContent");function po(e){return`${e}/${so}`}i(po,"agentSkillEntryRelativePath");function _l(e){return`${no}/${po(e)}`}i(_l,"agentSkillPackageFileRelativePath");function Ol(e){return`${ro}/${e}.md`}i(Ol,"flatSkillTemplateFileRelativePath");export{yr as ADAPTER_DIAGNOSTIC_DOCS_RELATIVE_PATH,fl as AGENT_PROJECTION_BEGIN_MARKER,Ws as AGENT_PROJECTION_END_MARKER,cr as AGENT_PROJECTION_ENFORCEMENT_SURFACES,Js as AGENT_PROJECTION_NON_ENFORCEMENT_LABEL,no as AGENT_SKILLS_PACKAGE_RELATIVE_ROOT,so as AGENT_SKILL_ENTRY_FILENAME,Rn as ANALYSIS_IR_SCHEMA_VERSION,Yn as ARKORDER_RULE_IDS,Ci as ARKORDER_TIER1_SENSOR_IDS,hs as ARKRUN_INTERACTION_NAME_INCOMPLETE,fs as ARKRUN_KERNEL_FACTORY_CALLEES,Qa as ARKRUN_KERNEL_INTERACTION_CALLEES,qn as ARKRUN_RULE_IDS,ui as ARKRUN_TIER1_SENSOR_IDS,ms as ARKRUN_TRANSPORT_BYPASS_SPECIFIERS,pl as ARK_AGENT_PROJECTION_SCHEMA_VERSION,Sl as ARK_AGENT_SKILLS_PACKAGE_SCHEMA_VERSION,vo as ARK_ANALYSIS_RESULT_SCHEMA,Qt as ARK_ANALYSIS_RESULT_SCHEMA_VERSION,gn as ARK_CONFIG_SCHEMA,ne as ARK_CONFIG_SCHEMA_VERSION,zi as ARK_DESIGN_DELTA_SCHEMA_VERSION,Bi as ARK_ENFORCEMENT_STATE_SCHEMA_VERSION,Gt as ARK_IMPROVEMENT_COMPASS_SCHEMA_VERSION,Co as ARK_PROJECT_IDENTITY_SCHEMA,Rr as ARK_PROJECT_IDENTITY_SCHEMA_URL,bo as ARK_PROJECT_IDENTITY_SCHEMA_VERSION,En as ARK_RULES_SCHEMA,ca as ARK_RULES_SCHEMA_VERSION,Jr as ARK_RULE_SENSORS,bs as ARK_RUN_DOCTOR_SCHEMA_VERSION,mr as ARK_SKILL_DESCRIPTION_VERSION_PATTERN,Jt as ARK_SKILL_NAMES,oo as ARK_SKILL_NAME_COUNT,ol as ARK_STATUS_MANIFEST_SCHEMA,Ns as ARK_STATUS_MANIFEST_SCHEMA_URL,Qn as ARK_STATUS_MANIFEST_SCHEMA_VERSION,ml as DEFAULT_AGENT_PROJECTION_RULE_IDS,Vt as DIAGNOSTIC_CATALOG,qi as DIAGNOSTIC_CATALOG_SCHEMA_VERSION,Zn as DIAGNOSTIC_DOCS_RELATIVE_PATH,Yi as DIAGNOSTIC_RULE_IDS,Ja as EXTRA_MERGE_TEETH_GOVERNED_FLOOR,Nt as EffectiveContractError,ro as FLAT_SKILL_TEMPLATES_RELATIVE_ROOT,Pe as IMPROVEMENT_COMPASS_OUT_OF_SCOPE_LENSES,zt as IMPROVEMENT_COMPASS_TOP_RESIDUAL_CAP,Bt as IMPROVEMENT_LENS_IDS,us as MERGE_PLANES_DUAL_STAMP,On as POLICY_DELTA_SCHEMA_VERSION,Er as PROJECT_BINDING_SCHEMA,kr as PROJECT_EXPECTATION_SCHEMA,An as RESOLVED_CANDIDATE_FACTS_SCHEMA,Oe as RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,Ls as STATUS_COMPASS_FACTS_SOURCES,Ps as STATUS_COMPASS_MODES,Kt as STATUS_COMPASS_REASON_CODES,Ar as adapterDocsCodePath,Zt as adapterFindingOccurrenceTargetKeys,hr as adapterFindingRefFromTargetKey,en as adapterFindingTargetKey,qt as agentProjectionContentIdentity,po as agentSkillEntryRelativePath,_l as agentSkillPackageFileRelativePath,je as analyzeArchitectureConvergence,Dt as analyzeChange,os as analyzePolicyDelta,dt as analyzeProject,ht as analyzeResolvedProject,Vn as arkRunKernelCallKind,Qs as buildAgentProjectionBeginMarker,hl as buildAgentProjectionBlock,ur as buildAgentProjectionBody,Al as buildAgentProjectionMeta,Dn as buildArkRuleFileHints,Sn as buildEffectiveArkRules,dl as buildImprovementCompass,Ki as buildRulesInventory,tl as buildStatusManifest,bn as canPromoteInvariant,Qi as catalogFixForRuleId,el as catalogWhyForRuleId,xn as classifyArkPolicyDelta,Fn as classifyResolvedLayerCoverage,Ms as classifyStatusWritePath,Ht as collectAnalysisConfigWarnings,wn as collectEmptyAppliesToFindings,Me as collectForbiddenCapabilityUses,Hn as composeMergePlanesHonesty,Nr as createAICodeGate,Io as createAdapterResult,Ot as createArchitectureProfile,Ur as createArchitectureProfileFromArkConfig,Kr as createElevenLayerArkConfig,_o as createProjectId,Oo as createProjectIdentity,hn as createResolvedCandidateFacts,Fs as defaultHonestLabel,Xa as demoteExtraPlaneTeethUnderClassificationFloor,cs as deriveArkRuleFileHints,Nn as detectArchitectureCycles,z as deterministicHash,Ts as diagnosticDocsFragment,Zi as diagnosticDocsPath,In as effectiveContractPolicyPayload,_t as elevenLayerProfile,Te as emptyEffectiveArkRules,Ve as evaluateArchitectureGraph,Wn as evaluateArkOrderSensors,Ln as evaluateArkRuleSensors,Rs as evaluateArkRunEditorSensors,bi as evaluateArkRunEditorSensorsFromSource,$t as evaluateArkRunSensors,vn as evaluateInvariantCoverage,Ds as evaluateStatusBinding,as as explainViolation,ke as extraMergeTeethAllowed,lr as extractAgentProjectionBlock,di as extractArkRunDeclarationsFromSource,Gn as extractArkRunImportedConstructorNamesFromSource,Bn as extractArkRunKernelCallsFromSource,zn as extractArkRunManagedNewsFromSource,Kn as extractArkRunValueImportDependenciesFromSource,Wa as extractClassShapesFromSource,De as extractSemanticDependencies,Ol as flatSkillTemplateFileRelativePath,eo as formatAgentProjectionCatalogShortList,ir as formatAgentProjectionLayers,ji as formatArkRunDoctorLines,ul as formatImprovementCompassDoctorLines,qs as formatImprovementCompassResidualLabels,Ut as getDiagnosticCatalogEntry,Gi as inventoryToExtractionCard,Za as isArkOrderRuleId,mt as isArkRunKernelModuleSpecifier,$n as isArkRunRuleId,Un as isArkRunTransportBypassSpecifier,fr as isArkSkillName,Ji as isCataloguedOrArkRuleFamily,ds as isExtraPlaneFinding,Wi as isKnownDiagnosticCode,ao as isValidAgentSkillName,Ct as loadArkConfigContract,Tt as loadArkRulesContract,wt as loadContract,ve as loadResolvedCandidateFacts,El as mergeAgentProjectionDocument,Mn as normalizeExtraMergeTeethClassification,pr as normalizeSkillContent,js as normalizeStatusImprovementCompass,to as parseAgentProjectionStamp,yn as parseArkConfigJson,ga as parseArkRulesJson,bl as parseSkillDescriptionVersion,io as parseSkillDocument,Tn as policyDeltaAcknowledgementMatches,Is as preflightChange,vs as preflightResolvedChange,Ys as primaryImprovementCompassNextAction,Jn as projectStatusArkRun,er as projectStatusImprovementCompass,kl as projectionHasNonEnforcementLabel,Rl as projectionMatchesPackageVersion,ya as resolveEffectiveContract,$s as resolveStatusNextAction,rt as resolvedFactsEvidenceRequirementsHash,Xi as serializeDiagnosticCatalog,co as skillDescriptionVersionPrefix,F as stableSerialize,Cl as stampSkillDescription,sl as statusCompassResidualIsSubsetOfDoctor,uo as stripSkillDescriptionVersion,Hi as summarizeArkRunSection,Xt as toAdapterDiagnostic,rl as unavailableStatusImprovementCompass,lo as validateAgentSkillDocument,vl as validateAgentSkillsPackage,mo as version};
50
+ `,r=t.split(/\r?\n/);if(r[0]!=="---")return{hasFrontmatter:!1,frontmatter:null,body:t};let s=r.indexOf("---",1);if(s===-1)return{hasFrontmatter:!1,frontmatter:null,body:t};let a={};for(let g=1;g<s;g+=1){let y=r[g]??"";if(y.trim()===""||y.trimStart().startsWith("#"))continue;let f=y.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);if(!f)continue;let u=f[1],m=f[2]??"";(m.startsWith('"')&&m.endsWith('"')&&m.length>=2||m.startsWith("'")&&m.endsWith("'")&&m.length>=2)&&(m=m.slice(1,-1)),a[u]=m}let o=r.slice(s+1).join(n),l=typeof a.name=="string"&&a.name.length>0?a.name:null,c=typeof a.description=="string"&&a.description.length>0?a.description:null,p=typeof a.license=="string"&&a.license.length>0?a.license:null;return{hasFrontmatter:!0,frontmatter:{fields:a,name:l,description:c,license:p},body:o}}i(ca,"parseSkillDocument");function da(e){let t=e.requireArkSkillName!==!1,n=e.requireBody!==!1,r=[],s=String(e.directoryName??""),a=ca(e.content);if(!a.hasFrontmatter||!a.frontmatter)return r.push({code:"MISSING_FRONTMATTER",message:`Skill "${s}" is missing YAML frontmatter fences.`,skillName:s||void 0}),r;let{name:o,description:l}=a.frontmatter,c=o??(s||void 0);return!o||!la(o)?r.push({code:"INVALID_NAME",message:`Skill name "${o??""}" is invalid (Agent Skills: 1\u201364 chars, [a-z0-9-], no leading/trailing/consecutive hyphens).`,skillName:c}):o!==s?r.push({code:"NAME_DIRECTORY_MISMATCH",message:`Frontmatter name "${o}" must match directory name "${s}".`,skillName:o}):t&&!gr(o)&&r.push({code:"UNKNOWN_SKILL_NAME",message:`Skill name "${o}" is not in the frozen Ark 13-skill catalog (no new skill names).`,skillName:o}),l?l.length>1024&&r.push({code:"DESCRIPTION_TOO_LONG",message:`Skill "${s}" description exceeds 1024 characters (${l.length}).`,skillName:c}):r.push({code:"MISSING_DESCRIPTION",message:`Skill "${s}" is missing a non-empty description.`,skillName:c}),n&&a.body.trim().length===0&&r.push({code:"EMPTY_BODY",message:`Skill "${s}" has an empty instruction body.`,skillName:c}),r}i(da,"validateAgentSkillDocument");function _l(e){let t=[],n=new Set,r=[];for(let s of e){let a=String(s.name??"");if(n.has(a)){t.push({code:"DUPLICATE_SKILL",message:`Duplicate skill entry "${a}".`,skillName:a});continue}n.add(a),r.push(a),t.push(...da({directoryName:a,content:s.content,requireArkSkillName:!0,requireBody:!0})),s.flatTemplateContent!=null&&mr(s.content)!==mr(s.flatTemplateContent)&&t.push({code:"CONTENT_MISMATCH",message:`Agent Skills SKILL.md for "${a}" does not match flat template templates/skills/${a}.md.`,skillName:a})}for(let s of Jt)n.has(s)||t.push({code:"MISSING_SKILL",message:`Missing frozen skill "${s}" from Agent Skills package.`,skillName:s});for(let s of r)gr(s)||(t.some(a=>a.code==="UNKNOWN_SKILL_NAME"&&a.skillName===s)?t.push({code:"EXTRA_SKILL",message:`Extra skill "${s}" is not in the frozen Ark 13-skill catalog.`,skillName:s}):t.push({code:"EXTRA_SKILL",message:`Extra skill "${s}" is not in the frozen Ark 13-skill catalog.`,skillName:s}));return r.sort(),{ok:t.length===0,issues:t,names:r,expectedCount:ia,presentCount:r.length}}i(_l,"validateAgentSkillsPackage");var yr=/^arkgate@(\S+)\.\s/;function ua(e){let t=String(e??"").trim();return t?`arkgate@${t}. `:""}i(ua,"skillDescriptionVersionPrefix");function pa(e){return String(e??"").replace(yr,"")}i(pa,"stripSkillDescriptionVersion");function xl(e){return String(e??"").match(yr)?.[1]??null}i(xl,"parseSkillDescriptionVersion");function Tl(e,t){let n=pa(e),r=typeof t=="string"?t.trim():"";return r?`${ua(r)}${n}`:n}i(Tl,"stampSkillDescription");function mr(e){return String(e??"").replace(/^\uFEFF/,"").replace(/\r\n/g,`
51
+ `)}i(mr,"normalizeSkillContent");function fa(e){return`${e}/${oa}`}i(fa,"agentSkillEntryRelativePath");function Nl(e){return`${sa}/${fa(e)}`}i(Nl,"agentSkillPackageFileRelativePath");function Pl(e){return`${aa}/${e}.md`}i(Pl,"flatSkillTemplateFileRelativePath");export{Ar as ADAPTER_DIAGNOSTIC_DOCS_RELATIVE_PATH,hl as AGENT_PROJECTION_BEGIN_MARKER,Js as AGENT_PROJECTION_END_MARKER,ur as AGENT_PROJECTION_ENFORCEMENT_SURFACES,Zs as AGENT_PROJECTION_NON_ENFORCEMENT_LABEL,sa as AGENT_SKILLS_PACKAGE_RELATIVE_ROOT,oa as AGENT_SKILL_ENTRY_FILENAME,In as ANALYSIS_IR_SCHEMA_VERSION,Xn as ARKORDER_RULE_IDS,Ti as ARKORDER_TIER1_SENSOR_IDS,Rs as ARKRUN_INTERACTION_NAME_INCOMPLETE,gs as ARKRUN_KERNEL_FACTORY_CALLEES,ri as ARKRUN_KERNEL_INTERACTION_CALLEES,Yn as ARKRUN_RULE_IDS,gi as ARKRUN_TIER1_SENSOR_IDS,ys as ARKRUN_TRANSPORT_BYPASS_SPECIFIERS,yl as ARK_AGENT_PROJECTION_SCHEMA_VERSION,Cl as ARK_AGENT_SKILLS_PACKAGE_SCHEMA_VERSION,va as ARK_ANALYSIS_RESULT_SCHEMA,nn as ARK_ANALYSIS_RESULT_SCHEMA_VERSION,An as ARK_CONFIG_SCHEMA,re as ARK_CONFIG_SCHEMA_VERSION,Xi as ARK_DESIGN_DELTA_SCHEMA_VERSION,Yi as ARK_ENFORCEMENT_STATE_SCHEMA_VERSION,Bt as ARK_IMPROVEMENT_COMPASS_SCHEMA_VERSION,Oa as ARK_PROJECT_IDENTITY_SCHEMA,Er as ARK_PROJECT_IDENTITY_SCHEMA_URL,Ca as ARK_PROJECT_IDENTITY_SCHEMA_VERSION,bn as ARK_RULES_SCHEMA,uo as ARK_RULES_SCHEMA_VERSION,Zr as ARK_RULE_SENSORS,Os as ARK_RUN_DOCTOR_SCHEMA_VERSION,yr as ARK_SKILL_DESCRIPTION_VERSION_PATTERN,Jt as ARK_SKILL_NAMES,ia as ARK_SKILL_NAME_COUNT,cl as ARK_STATUS_MANIFEST_SCHEMA,Ls as ARK_STATUS_MANIFEST_SCHEMA_URL,tr as ARK_STATUS_MANIFEST_SCHEMA_VERSION,Al as DEFAULT_AGENT_PROJECTION_RULE_IDS,Kt as DIAGNOSTIC_CATALOG,Ji as DIAGNOSTIC_CATALOG_SCHEMA_VERSION,Qn as DIAGNOSTIC_DOCS_RELATIVE_PATH,Zi as DIAGNOSTIC_RULE_IDS,ei as EXTRA_MERGE_TEETH_GOVERNED_FLOOR,Nt as EffectiveContractError,aa as FLAT_SKILL_TEMPLATES_RELATIVE_ROOT,Pe as IMPROVEMENT_COMPASS_OUT_OF_SCOPE_LENSES,qt as IMPROVEMENT_COMPASS_TOP_RESIDUAL_CAP,zt as IMPROVEMENT_LENS_IDS,fs as MERGE_PLANES_DUAL_STAMP,Nn as POLICY_DELTA_SCHEMA_VERSION,Sr as PROJECT_BINDING_SCHEMA,Ir as PROJECT_EXPECTATION_SCHEMA,En as RESOLVED_CANDIDATE_FACTS_SCHEMA,Oe as RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,Ds as STATUS_COMPASS_FACTS_SOURCES,ws as STATUS_COMPASS_MODES,Gt as STATUS_COMPASS_REASON_CODES,kr as adapterDocsCodePath,en as adapterFindingOccurrenceTargetKeys,Rr as adapterFindingRefFromTargetKey,rn as adapterFindingTargetKey,Wt as agentProjectionContentIdentity,fa as agentSkillEntryRelativePath,Nl as agentSkillPackageFileRelativePath,Ke as analyzeArchitectureConvergence,Dt as analyzeChange,is as analyzePolicyDelta,dt as analyzeProject,gt as analyzeResolvedProject,Un as arkRunKernelCallKind,ta as buildAgentProjectionBeginMarker,El as buildAgentProjectionBlock,fr as buildAgentProjectionBody,Il as buildAgentProjectionMeta,Fn as buildArkRuleFileHints,vn as buildEffectiveArkRules,ml as buildImprovementCompass,qi as buildRulesInventory,al as buildStatusManifest,_n as canPromoteInvariant,rl as catalogFixForRuleId,sl as catalogWhyForRuleId,Pn as classifyArkPolicyDelta,Hn as classifyResolvedLayerCoverage,$s as classifyStatusWritePath,jt as collectAnalysisConfigWarnings,Mn as collectEmptyAppliesToFindings,Fe as collectForbiddenCapabilityUses,Vn as composeMergePlanesHonesty,Lr as createAICodeGate,ba as createAdapterResult,_t as createArchitectureProfile,Gr as createArchitectureProfileFromArkConfig,Br as createElevenLayerArkConfig,_a as createProjectId,xa as createProjectIdentity,kn as createResolvedCandidateFacts,Hs as defaultHonestLabel,ni as demoteExtraPlaneTeethUnderClassificationFloor,us as deriveArkRuleFileHints,wn as detectArchitectureCycles,X as deterministicHash,Ps as diagnosticDocsFragment,tl as diagnosticDocsPath,Cn as effectiveContractPolicyPayload,Ot as elevenLayerProfile,xe as emptyEffectiveArkRules,Ue as evaluateArchitectureGraph,Jn as evaluateArkOrderSensors,Dn as evaluateArkRuleSensors,Es as evaluateArkRunEditorSensors,xi as evaluateArkRunEditorSensorsFromSource,Ht as evaluateArkRunSensors,On as evaluateInvariantCoverage,Fs as evaluateStatusBinding,ls as explainViolation,Re as extraMergeTeethAllowed,dr as extractAgentProjectionBlock,mi as extractArkRunDeclarationsFromSource,zn as extractArkRunImportedConstructorNamesFromSource,qn as extractArkRunKernelCallsFromSource,Wn as extractArkRunManagedNewsFromSource,Bn as extractArkRunValueImportDependenciesFromSource,Qo as extractClassShapesFromSource,Me as extractSemanticDependencies,Pl as flatSkillTemplateFileRelativePath,na as formatAgentProjectionCatalogShortList,cr as formatAgentProjectionLayers,Gi as formatArkRunDoctorLines,gl as formatImprovementCompassDoctorLines,Ys as formatImprovementCompassResidualLabels,Ut as getDiagnosticCatalogEntry,Wi as inventoryToExtractionCard,ti as isArkOrderRuleId,ft as isArkRunKernelModuleSpecifier,jn as isArkRunRuleId,Gn as isArkRunTransportBypassSpecifier,gr as isArkSkillName,el as isCataloguedOrArkRuleFamily,ps as isExtraPlaneFinding,Qi as isKnownDiagnosticCode,la as isValidAgentSkillName,Ct as loadArkConfigContract,Tt as loadArkRulesContract,wt as loadContract,Se as loadResolvedCandidateFacts,vl as mergeAgentProjectionDocument,$n as normalizeExtraMergeTeethClassification,mr as normalizeSkillContent,Ks as normalizeStatusImprovementCompass,ra as parseAgentProjectionStamp,Rn as parseArkConfigJson,ho as parseArkRulesJson,xl as parseSkillDescriptionVersion,ca as parseSkillDocument,Ln as policyDeltaAcknowledgementMatches,vs as preflightChange,Cs as preflightResolvedChange,Xs as primaryImprovementCompassNextAction,Zn as projectStatusArkRun,nr as projectStatusImprovementCompass,bl as projectionHasNonEnforcementLabel,Sl as projectionMatchesPackageVersion,Ao as resolveEffectiveContract,js as resolveStatusNextAction,rt as resolvedFactsEvidenceRequirementsHash,nl as serializeDiagnosticCatalog,ua as skillDescriptionVersionPrefix,j as stableSerialize,Tl as stampSkillDescription,ll as statusCompassResidualIsSubsetOfDoctor,pa as stripSkillDescriptionVersion,Ui as summarizeArkRunSection,tn as toAdapterDiagnostic,il as unavailableStatusImprovementCompass,da as validateAgentSkillDocument,_l as validateAgentSkillsPackage,ga as version};