arkgate 4.8.16 → 4.8.18
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.
- package/CHANGELOG.md +81 -0
- package/README.md +10 -7
- package/bin/ark-check-runtime.mjs +5 -1
- package/bin/ark-mcp-runtime.mjs +14 -7
- package/bin/ark-shared.mjs +10 -4
- package/bin/ark.mjs +6 -0
- package/bin/lib/adr-path.mjs +116 -0
- package/bin/lib/adr-presence.mjs +3 -2
- package/bin/lib/agent-gates.mjs +2 -0
- package/bin/lib/analysis-engine.mjs +6 -6
- package/bin/lib/doctor-human.mjs +2 -2
- package/bin/lib/doctor-next-actions.mjs +117 -17
- package/bin/lib/first-run-help.mjs +6 -2
- package/bin/lib/html-report.mjs +1 -1
- package/bin/lib/policy-delta-io.mjs +19 -10
- package/bin/lib/presets.mjs +15 -21
- package/bin/lib/skill-install.mjs +42 -4
- package/bin/lib/start-preview.mjs +75 -3
- package/dist/{diagnosticCatalog-KWvGLI1U.d.ts → diagnosticCatalog-BNxKdcN4.d.ts} +7 -1
- package/dist/index.cjs +9 -9
- package/dist/index.d.ts +2 -2
- package/dist/index.js +11 -11
- package/dist/nestjs/index.cjs +1 -1
- package/dist/nestjs/index.js +1 -1
- package/dist/runtime/index.cjs +6 -6
- package/dist/runtime/index.d.ts +1 -1
- package/dist/runtime/index.js +6 -6
- package/docs/README.md +2 -2
- package/docs/agent-guide.md +9 -2
- package/docs/ai-gates.md +4 -0
- package/docs/configuration.md +6 -3
- package/docs/enthusiast/how-to-agent-gates.md +3 -1
- package/docs/enthusiast/how-to-pick-shape.md +1 -1
- package/docs/package-surface.md +1 -1
- package/docs/use.md +9 -4
- package/package.json +1 -1
- package/server.json +2 -2
- package/templates/agent-skills/README.md +1 -1
- package/templates/agent-skills/ark-adopt/SKILL.md +8 -5
- package/templates/agent-skills/ark-explain/SKILL.md +3 -0
- package/templates/agent-skills/ark-explore/SKILL.md +3 -1
- package/templates/agent-skills/ark-upgrade/SKILL.md +1 -0
- package/templates/skills/ark-adopt.md +8 -5
- package/templates/skills/ark-explain.md +3 -0
- package/templates/skills/ark-explore.md +3 -1
- package/templates/skills/ark-upgrade.md +1 -0
package/dist/index.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
var Na=Object.defineProperty;var i=(e,t)=>Na(e,"name",{value:t,configurable:!0});var wa="4.8.16";var Pa=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,La=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,Da=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function Ma(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),o=String(t?.toLayer??"");return Pa.test(n)?"pure-shared":r==="PersistenceAdapters"&&(La.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${o} ${n}`))?"kernel-emit":Da.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&o==="PersistenceAdapters"?"use-case":"unknown"}i(Ma,"classifyLayerImportKind");function Fa(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=Ma(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(Fa,"layerImportNextAction");function $a(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}i($a,"arkRunCallSiteName");function Ha(e){let t=$a(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(Ha,"arkRunNextAction");function ge(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return Fa(e);case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, test at the public interface, then preflight again.`;case"CAPABILITY_VIOLATION":return`Define a ${String(e.capability??"capability")} port in ${e.fromLayer??"the walled layer"}, bind the implementation outside it, test at the public interface, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, test at the public interface, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"LITERAL_PATH_DRIFT":return typeof e.target=="string"&&e.target.length>0?`Rewrite the literal to ${e.target}, or run \`arkgate-check --path-drift --base-ref <ref> --write\` to apply every anchored replacement.`:"Rewrite the literal to the rename destination, or run `arkgate-check --path-drift --base-ref <ref> --write` to apply every anchored replacement.";case"LITERAL_PATH_UNRESOLVED":return"Read the candidate and decide: fix the path, or leave it. Advisory \u2014 with no rename to anchor it there is no destination to propose, so --write never touches it.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";case"INVARIANT_COVERAGE_OUTSIDE_ROOTS":return"Move the covering test under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json, then run Ark again.";case"INVARIANT_CATALOG_EMPTY":return typeof e.file=="string"&&e.file.length>0?`Add 1\u20132 short phrases to invariants[] in ${e.file}, then run ark-check --doctor. Starters show the shape.`:"Add 1\u20132 short phrases to invariants[] in arkrules/<Domain>.json, then run ark-check --doctor. Starters show the shape.";case"INVARIANT_TESTS_PATH_MISSING":return"Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present.";case"INVARIANT_COVERAGE_ROOTS_MISSING":return"Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. An enforced invariant fails closed until that path is present.";case"ARKRULE_STRUCTURE":case"ARKRULE_INVARIANT":case"INVARIANT_UNCOVERED":return`Fix the structure or invariant for ${typeof e.arkruleId=="string"&&e.arkruleId.length>0?e.arkruleId:"the ArkRule"} (declared in ${typeof e.arkruleSource=="string"&&e.arkruleSource.length>0?e.arkruleSource:"arkrules/<Layer>.json"}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`;case"ARKRUN_MISSING_ROOT":case"ARKRUN_KERNEL_IN_DOMAIN":case"ARKRUN_DIRECT_NEW":case"ARKRUN_UNDECLARED_EMIT":case"ARKRUN_UNDECLARED_HANDLE":case"ARKRUN_UNDECLARED_DEPEND":case"ARKRUN_TRANSPORT_BYPASS":return Ha(e);case"ARKORDER_MISSING_PLANE":return typeof e.target=="string"&&e.target.length>0?`Import createOrderPlane from arkgate/order and call it in plane root ${e.target} listed in arkOrder.planeRoots, then preflight again.`:"Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKORDER_KERNEL_IN_DOMAIN":return"Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe.";case"ARKORDER_GENERIC_UPDATE":return"Don't use a generic update. First freeze with release(). Later, propose the change, then apply it.";case"ARKORDER_TOO_MANY_PARAMS":return"Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe.";case"ARKORDER_INGEST_WRITES_XI":return"Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe.";case"ARKORDER_XI_FIELD_WRITE":return typeof e.target=="string"&&e.target.length>0?`Don't write ${e.target} from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.`:"Don't write a named product choice from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.";case"ARKORDER_UNVALVED_RELEASE":return"Change the choice with proposeRelease then apply. release() is only the first freeze. Never mechanical-safe.";default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(ge,"deterministicNextAction");var Nt="1.5",wt="docs/diagnostics.md",Qr={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","mode","valid","completeness","completenessReasons","diagnostics"],allOf:[{if:{properties:{completeness:{enum:["partial","unavailable"]}},required:["completeness"]},then:{properties:{valid:{const:!1}}}},{if:{properties:{mode:{const:"resolved-candidate-facts"},completeness:{enum:["complete","partial"]}},required:["mode","completeness"]},then:{required:["policyHash","resolverIdentity","factsHash","candidateTreeHash"]}},{if:{properties:{completeness:{const:"complete"}},required:["completeness"]},then:{properties:{completenessReasons:{maxItems:0}}},else:{properties:{completenessReasons:{minItems:1}}}}],properties:{schemaVersion:{const:"1.5"},mode:{enum:["lexical-compatibility","resolved-candidate-facts"]},valid:{type:"boolean"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:{type:"string",minLength:1},message:{type:"string",minLength:1},file:{type:"string",minLength:1}}}},policyHash:{type:"string",minLength:1},resolverIdentity:{type:"string",minLength:1},factsHash:{type:"string",minLength:1},candidateTreeHash:{type:"string",minLength:1},diagnostics:{type:"array",items:{type:"object",additionalProperties:!1,required:["ruleId","severity","message","location","evidence"],properties:{ruleId:{type:"string",minLength:1},severity:{enum:["error","warning"]},message:{type:"string",minLength:1},location:{type:"object",additionalProperties:!1,required:["file","line","column"],properties:{file:{type:"string",minLength:1},line:{type:"integer",minimum:1},column:{type:"integer",minimum:1}}},evidence:{type:"object",additionalProperties:!1,properties:{target:{type:"string"},fromLayer:{type:"string"},toLayer:{type:"string"},typeOnly:{type:"boolean"},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"},peerIsolation:{type:"boolean"},capability:{type:"string",minLength:1},edgeKind:{type:"string",minLength:1},arkruleId:{type:"string",minLength:1},arkruleSource:{type:"string",minLength:1}}},nextAction:{type:"string",minLength:1},findingRef:{type:"string",minLength:1,pattern:"^fnv1a-[0-9a-f]{8}$"},targetKey:{type:"string",minLength:1},docsCodePath:{type:"string",minLength:1}}}}}};function nt(e){let t=typeof e.ruleId=="string"?e.ruleId:typeof e.code=="string"?e.code:void 0,n=typeof e.file=="string"?e.file:void 0,r=typeof e.fromLayer=="string"?e.fromLayer:void 0,o=typeof e.toLayer=="string"?e.toLayer:void 0,s=typeof e.target=="string"?e.target:void 0;return[t,n,r??"",o??"",s??""].join("|")}i(nt,"adapterFindingTargetKey");function rt(e){let t=new Map;return e.map(n=>{let r=nt(n),o=(t.get(r)??0)+1;return t.set(r,o),o===1?r:`${r}#${o}`})}i(rt,"adapterFindingOccurrenceTargetKeys");function Pt(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}i(Pt,"adapterFindingRefFromTargetKey");function Lt(e){return`${wt}#${e}`}i(Lt,"adapterDocsCodePath");function x(e){return typeof e=="string"&&e.length>0?e:void 0}i(x,"text");function es(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}i(es,"positiveInteger");function ja(e,t,n){return ge({ruleId:e,target:x(t.target)??x(n.target)??void 0,fromLayer:x(t.fromLayer)??void 0,toLayer:x(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:x(t.edgeKind)??void 0,capability:x(t.capability)??x(n.capability)??void 0,arkruleId:x(t.arkruleId)??void 0,arkruleSource:x(t.arkruleSource)??void 0})}i(ja,"nextActionForDiagnostic");function In(e,t="error",n){let r=x(e.ruleId)??x(e.code)??"ARK_UNKNOWN",o=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,s={...x(e.target)?{target:x(e.target)}:{},...x(e.fromLayer)?{fromLayer:x(e.fromLayer)}:{},...x(e.toLayer)?{toLayer:x(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}:{},...x(e.capability)?{capability:x(e.capability)}:{},...x(e.edgeKind)?{edgeKind:x(e.edgeKind)}:{},...x(e.arkruleId)?{arkruleId:x(e.arkruleId)}:{},...x(e.arkruleSource)?{arkruleSource:x(e.arkruleSource)}:{}},a=n??nt(e),c=Pt(a);return{ruleId:r,severity:o,message:x(e.message)??r,location:{file:x(e.file)??"<unknown>",line:es(e.line,1),column:es(e.column,1)},evidence:s,nextAction:x(e.nextAction)??ja(r,s,e),findingRef:c,targetKey:a,docsCodePath:Lt(r)}}i(In,"toAdapterDiagnostic");function Ka(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:x(g.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:x(g.message)??`Analysis ${t}: required evidence is incomplete.`,...x(g.file)?{file:x(g.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],o={...x(e.policyHash)?{policyHash:x(e.policyHash)}:{},...x(e.resolverIdentity)?{resolverIdentity:x(e.resolverIdentity)}:{},...x(e.factsHash)?{factsHash:x(e.factsHash)}:{},...x(e.candidateTreeHash)?{candidateTreeHash:x(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let g of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!o[g])throw new Error(`${g} is required for resolved ${t} adapter evidence.`)}let s=e.violations??[],a=e.warnings??[],c=rt(s),l=rt(a),u=[...s.map((g,f)=>In(g,"error",c[f])),...a.map((g,f)=>In(g,"warning",l[f]))],p={schemaVersion:"1.5",completenessReasons:r,diagnostics:u};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...p,mode:n,valid:!1,completeness:t,...o};let g={policyHash:o.policyHash,resolverIdentity:o.resolverIdentity,factsHash:o.factsHash,candidateTreeHash:o.candidateTreeHash};return t==="complete"?{...p,mode:n,valid:e.valid,completeness:t,...g}:{...p,mode:n,valid:!1,completeness:t,...g}}return t==="complete"?{...p,mode:n,valid:e.valid,completeness:t,...o}:{...p,mode:n,valid:!1,completeness:t,...o}}i(Ka,"createAdapterResult");var Va="1.0",ts="https://unpkg.com/arkgate@4/schemas/ark.project-identity.schema.json",Dt="^sha256:[a-f0-9]{64}$",ns={type:"object",additionalProperties:!1,properties:{expectedRoot:{type:"string",minLength:1,description:"Absolute expected workspace/project directory. The initial authoritative handshake requires the exact project root; descendant calls also require expectedProjectId."},expectedProjectId:{type:"string",pattern:Dt,description:"Project id previously returned by ark_identity or ark_manifest."}}},rs={type:"object",additionalProperties:!1,required:["status","authoritative"],properties:{status:{enum:["matched","unverified","mismatch"]},authoritative:{type:"boolean"},expectedRoot:{type:"string",minLength:1},expectedProjectId:{type:"string",pattern:Dt},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},Ua={$schema:"https://json-schema.org/draft/2020-12/schema",$id:ts,title:"ArkGate MCP project identity",description:"Stable project binding plus separate runtime and architecture-contract evidence.",type:"object",additionalProperties:!1,required:["schemaVersion","projectId","resolvedRoot","resolvedConfigPath","arkgateVersion","contractHash","contractSource","runtimeId","processStartedAt"],properties:{schemaVersion:{const:"1.0"},projectId:{type:"string",pattern:Dt},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{type:"string",minLength:1},arkgateVersion:{type:"string",minLength:1},contractHash:{type:"string",pattern:Dt},contractSource:{enum:["project","default-profile","manifest"]},runtimeId:{type:"string",minLength:1},processStartedAt:{type:"string",format:"date-time"}},$defs:{expectation:ns,binding:rs}};function Ga(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(Ga,"createProjectId");function Ba(e){return{schemaVersion:"1.0",...e}}i(Ba,"createProjectIdentity");var vn=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),_n=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),On=Object.freeze(Object.keys(_n).sort()),bn=Object.freeze({fs:"filesystem","node:fs":"filesystem","fs/promises":"filesystem","node:fs/promises":"filesystem","fs-extra":"filesystem","graceful-fs":"filesystem",memfs:"filesystem",chokidar:"filesystem",http:"network",https:"network",http2:"network",net:"network",tls:"network",dgram:"network",dns:"network","node:http":"network","node:https":"network","node:http2":"network","node:net":"network","node:tls":"network","node:dgram":"network","node:dns":"network",axios:"network",undici:"network","node-fetch":"network",got:"network",ky:"network",superagent:"network",ws:"network",process:"process","node:process":"process",child_process:"process","node:child_process":"process","@prisma/client":"persistence",prisma:"persistence",pg:"persistence",mysql:"persistence",mysql2:"persistence",mongodb:"persistence",mongoose:"persistence",sqlite3:"persistence","better-sqlite3":"persistence",redis:"persistence",ioredis:"persistence",typeorm:"persistence",knex:"persistence","drizzle-orm":"persistence",sequelize:"persistence",kysely:"persistence","@supabase/supabase-js":"persistence"}),Cn=Object.freeze({process:Object.freeze(["process","node:process"])});function st(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=bn[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),o=bn[r];if(o)return o;let s=e.indexOf("/",n+1);return s<0?null:bn[e.slice(0,s)]??null}i(st,"capabilityForModuleSpecifier");function Ce(e,t){for(let n of t)if(Cn[n]?.includes(e))return n;return null}i(Ce,"forbiddenGlobalForModuleSpecifier");function Mt(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),o=_n[r];if(o)return o}return null}i(Mt,"capabilityForAmbientName");function je(e){if(e?.pure===!0)return[...vn].sort();let n=(e?.capabilities?.deny??[]).filter(r=>vn.includes(r));return[...new Set(n)].sort()}i(je,"effectiveCapabilityDeny");function ot(e,t){if(t.length===0)return!1;let n=new Set(t),r=e.split(".");for(let o=r.length;o>=1;o-=1)if(n.has(r.slice(0,o).join(".")))return!0;return!1}i(ot,"ambientCoveredByForbiddenGlobals");function Ft(e){let t=new Set,n=new Set,r=Object.keys(_n);for(let o of e?.forbiddenGlobals??[]){let s=r.filter(a=>a===o||a.startsWith(`${o}.`));if(s.length===0)n.add(o);else for(let a of s)t.add(`ambient:${a}`);for(let a of Cn[o]??[])t.add(`import-exact:${a}`)}for(let o of je(e)){if(t.add(`import:${o}`),o==="process")for(let s of Cn.process)t.add(`import-exact:${s}`);for(let s of r)Mt(s)===o&&t.add(`ambient:${s}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}i(Ft,"loweredLayerCoverage");var ss=new Map;function os(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(os,"escapeLiteral");function $t(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let o=e[n+1];if("*?{}[],".includes(o)||o==="\\"){t+="\\"+o,n+=1;continue}t+="/";continue}t+=r}return t}i($t,"normalizeGlobSeparators");function za(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(za,"bracesBalanced");function Re(e){let t=ss.get(e);if(t)return t;let n=$t(e),r=za(n),o="",s=0;for(let c=0;c<n.length;c+=1){let l=n[c];l==="\\"&&c+1<n.length?(o+=os(n[c+1]),c+=1):l==="*"?n[c+1]==="*"?n[c+2]==="/"?(o+="(?:.*/)?",c+=2):(o+=".*",c+=1):o+="[^/]*":l==="?"?o+="[^/]":l==="{"&&r?(o+="(?:",s+=1):l==="}"&&r&&s>0?(o+=")",s-=1):l===","&&r&&s>0?o+="|":o+=os(l)}let a=new RegExp(`^${o}$`);return ss.set(e,a),a}i(Re,"globToRegExp");function Wa(e){return $t(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}i(Wa,"concreteGlobSegments");function xn(e,t){let n=$t(String(e)),r=Wa(n),o=n.replace(/\*/g,"").length,s=r.length*1e4+o;if(t==null||t==="")return s;let a=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return o;let c=0,l=-1;for(let u of r){let p=-1;for(let g=c;g<a.length;g+=1)if(a[g]===u){p=g;break}if(p<0)return s;l=p,c=p+1}return(l+1)*1e6+r.length*1e4+o}i(xn,"patternSpecificity");function fe(e,t){let n=String(e).split(/[/\\]/).join("/"),r,o=-1;for(let s of t??[])if(!(s.exclude??[]).some(a=>Re(a).test(n))){for(let a of s.patterns??[])if(Re(a).test(n)){let c=xn(a,n);c>o&&(o=c,r=s.name)}}return r}i(fe,"layerForRelativePath");function as(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),r=new Set(t.map(o=>String(o).toLowerCase()));for(let o=0;o<n.length-1;o+=1)if(r.has(n[o].toLowerCase()))return`${n[o].toLowerCase()}/${n[o+1].toLowerCase()}`}i(as,"sliceIdForPath");function qa(e){let t=new Set;for(let n of e??[]){let o=$t(String(n)).split("/").filter(Boolean);for(let s=0;s<o.length;s+=1){let a=o[s];if((a==="**"||a==="*")&&s>0){let c=o[s-1];c&&!c.includes("*")&&!c.includes("{")&&!c.includes("}")&&t.add(c)}}}return[...t]}i(qa,"inferSliceFoldersFromPatterns");function Ya(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(o=>typeof o=="string"&&o.length>0);let r=(n??[]).find(o=>o.name===t);return qa(r?.patterns)}i(Ya,"resolveSliceFolders");function is(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}i(is,"normalizeSegments");function ds(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}i(ds,"trimTrailingSlashes");var Ja=["src","app"];function Xa(e){let t=ds(e.replace(/^[./]+/,""));return t==="*"||t==="**"}i(Xa,"isBlanketRoot");function ls(e,t){if(!e||!t?.length)return!1;let n=String(e).split(/[/\\]/).join("/"),r=n.toLowerCase(),o=is(n);for(let s of t){if(typeof s!="string"||s.length===0||Xa(s))continue;if(s.includes("*")){let l=ds(s.toLowerCase());if(Re(l).test(r)||Re(`${l}/**`).test(r))return!0;continue}let a=is(s);if(a.length===0)continue;let c=Ja.includes(o[0])&&a[0]!==o[0]?[0,1]:[0];for(let l of c){if(l+a.length>o.length)continue;let u=!0;for(let p=0;p<a.length;p+=1)if(o[l+p]!==a[p]){u=!1;break}if(u)return!0}}return!1}i(ls,"pathUnderSharedRoot");function cs(e,t){let n=String(e).split(/[/\\]/).filter(Boolean).join("/").toLowerCase();if(!n)return!1;let r=t.toLowerCase();return n===r?!0:!n.includes("/")&&r.endsWith(`/${n}`)}i(cs,"sliceMatchesDeclaration");function Za(e,t,n){return!e?.length||!t||!n?!1:e.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&cs(r.from,t)&&cs(r.to,n))}i(Za,"crossSliceEdgeAllowed");function Qa(e){if(!e.fromPath)return{denied:!0,reason:"missing-path"};if(e.folderCount<=0)return{denied:!0,reason:"no-slice-folders"};let t=!!e.fromSlice||e.fromShared===!0;if(!e.toPath)return t?e.fromSlice?{denied:!0,reason:"missing-path"}:{denied:!1}:{denied:!0,reason:"unclassifiable-path"};let n=!!e.toSlice||e.toShared===!0;return!t||!n?{denied:!0,reason:"unclassifiable-path"}:!e.fromSlice||!e.toSlice?{denied:!1}:e.fromSlice===e.toSlice?{denied:!1}:e.crossSliceAllowed?{denied:!1}:{denied:!0,reason:"cross-slice"}}i(Qa,"peerIsolationDecision");function Ke(e,t){switch(e){case"cross-slice":return`cross-slice edge ${t.fromSlice??"?"} \u2192 ${t.toSlice??"?"}. Extract the shared code, use events/ports across slices, or declare the edge in the rule's allowedCrossSlice.`;case"unclassifiable-path":{let n=[t.fromSlice?void 0:t.fromPath,t.toSlice?void 0:t.toPath].filter(o=>!!o);return`unclassifiable path${n.length>0?` (${n.join(", ")})`:""} \u2014 ArkGate cannot place it in a slice, so it cannot prove this is not a cross-slice edge. Move it into a slice, or declare its root in the rule's sharedRoots.`}case"no-slice-folders":return"no slice folders \u2014 peerIsolation is on but no slice folder resolves from the rule or the layer patterns. Set sliceFolders on the rule.";default:return"no path evidence for this edge \u2014 peerIsolation needs the importer and importee paths."}}i(Ke,"peerIsolationDenyExplanation");function Ht(e,t,n,r){return Te(e,t,n,r)?.rule}i(Ht,"findDeniedEdgeRule");function Te(e,t,n,r){for(let o of e??[])if(!(o.from!==t||o.to!==n)&&o.allowed===!1){if(o.peerIsolation){let s=r?.fromPath,a=r?.toPath,c=Ya(o,t,r?.layers),l=s?as(s,c):void 0,u=a?as(a,c):void 0,p=Qa({fromPath:s,toPath:a,folderCount:c.length,fromSlice:l,toSlice:u,fromShared:!l&&ls(s,o.sharedRoots),toShared:!u&&ls(a,o.sharedRoots),crossSliceAllowed:Za(o.allowedCrossSlice,l,u)});if(p.denied)return{rule:o,peerIsolationReason:p.reason,fromSlice:l,toSlice:u};continue}if(t!==n)return{rule:o}}}i(Te,"findDeniedEdgeDecision");function Ve(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(Ve,"literalText");function fs(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}i(fs,"lineOf");function us(e,t){if(e.isImportDeclaration(t)){let r=t.importClause;if(!r)return!1;if(r.isTypeOnly)return!0;let o=r.namedBindings;return!!(o&&e.isNamedImports(o)&&o.elements.length>0&&o.elements.every(s=>s.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(r=>r.isTypeOnly))}i(us,"isTypeOnlyReference");function ms(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=o=>o===t.fileName?t:void 0,r.fileExists=o=>o===t.fileName,r.readFile=o=>o===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}i(ms,"singleFileChecker");function Tn(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}i(Tn,"symbolAt");function Nn(e,t,n,r){let o=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,s;try{s=o?t.getShorthandAssignmentValueSymbol(r.parent):Tn(t,r)}catch{s=void 0}return!!s?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}i(Nn,"localDeclaration");function Ue(e,t){let n,r=[],o=i((a,c,l,u=!1)=>r.push({specifier:l,kind:c,line:fs(t,a),typeOnly:u,unresolved:l===void 0,node:a}),"add"),s=i(a=>{if(e.isImportDeclaration(a))o(a,"import",Ve(e,a.moduleSpecifier),us(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)o(a,"export",Ve(e,a.moduleSpecifier),us(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))o(a,"require",Ve(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let c=a.expression.kind===e.SyntaxKind.ImportKeyword,u=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!Nn(e,n??(n=ms(e,t)),t,a.expression);(c||u)&&o(a,u?"require":"dynamic-import",Ve(e,a.arguments[0]))}e.forEachChild(a,s)},"visit");return s(t),r}i(Ue,"extractSemanticDependencies");function ei(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let o=Ve(e,r.argumentExpression);if(o===void 0)return;n.unshift(o)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}i(ei,"staticAccessPath");function ti(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(ti,"runtimeIdentifierReference");function ps(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let r=n.length;r>=1;r-=1){let o=n.slice(0,r).join(".");if(e.has(o))return o}}i(ps,"bestForbiddenMatch");function Ge(e,t,n){if(n.length===0)return[];let r=new Set(n),o=ms(e,t),s=new Map,a=new Set;for(let f of t.statements)if(e.isVariableStatement(f))for(let m of f.declarationList.declarations)e.isIdentifier(m.name)&&a.add(m.name.text);let c=i(f=>{let m=ei(e,f);if(!m)return;let d=Tn(o,m.root),A=d?s.get(d):void 0;return A?[...A,...m.segments.slice(1)]:Nn(e,o,t,m.root)||a.has(m.root.text)?void 0:m.segments},"resolvePath");for(let f of t.statements)if(e.isVariableStatement(f))for(let m of f.declarationList.declarations){if(!m.initializer||!e.isIdentifier(m.name))continue;let d=c(m.initializer),A=Tn(o,m.name);!d||!A||s.set(A,d)}let l=[],u=new Set,p=i((f,m)=>{let d=fs(t,m),A=`${f}:${m.getStart(t)}`;u.has(A)||(u.add(A),l.push({name:f,line:d,node:m}))},"flag"),g=i(f=>{let m=f.parent&&(e.isPropertyAccessExpression(f.parent)||e.isElementAccessExpression(f.parent))&&f.parent.expression===f;if((e.isPropertyAccessExpression(f)||e.isElementAccessExpression(f))&&!m){let d=c(f),A=d?ps(r,d):void 0;A&&p(A,f)}else e.isIdentifier(f)&&r.has(f.text)&&ti(e,f)&&!Nn(e,o,t,f)&&p(f.text,f);if(e.isVariableDeclaration(f)&&e.isObjectBindingPattern(f.name)&&f.initializer){let d=c(f.initializer);if(d)for(let A of f.name.elements){if(!e.isIdentifier(A.name))continue;let b=A.propertyName?Ve(e,A.propertyName)??A.propertyName.text:A.name.text,O=ps(r,[...d,b]);O&&p(O,f.initializer)}}e.forEachChild(f,g)},"visit");return g(t),l}i(Ge,"collectForbiddenCapabilityUses");function wn(e,t,n){let r=[];for(let o of n?.dependencies??Ue(e,t)){if(o.typeOnly||!o.specifier)continue;let s=st(o.specifier);s&&r.push({capability:s,symbol:o.specifier,line:o.line,source:"import-based"})}for(let o of n?.ambientUses??Ge(e,t,On)){let s=Mt(o.name);s&&r.push({capability:s,symbol:o.name,line:o.line,source:"ambient-global"})}return r.sort((o,s)=>o.line-s.line||o.capability.localeCompare(s.capability)||o.symbol.localeCompare(s.symbol))}i(wn,"collectCapabilityUses");var Pn={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."},Ln=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 Dn(e,t){return t.flatMap((r,o)=>(r.prefixes??r.intentPrefixes??[]).map(s=>({layer:r.name,layerIndex:o,prefix:s.endsWith(".")?s:`${s}.`}))).filter(({prefix:r})=>e.startsWith(r)).sort((r,o)=>o.prefix.length-r.prefix.length||r.layerIndex-o.layerIndex)[0]?.layer}i(Dn,"resolveIntentLayer");function Ne(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}i(Ne,"looksLikeArkIntent");function at(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&Ne(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:Pn.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:Pn.PUBLISH_MISSING_SOURCE}),t}i(at,"classifyPublishFacts");function W(e,t,n){return{ruleId:e,code:e,message:t,...n}}i(W,"violation");function Be(e,t){return e.slice(0,t).split(`
|
|
1
|
+
var Na=Object.defineProperty;var i=(e,t)=>Na(e,"name",{value:t,configurable:!0});var wa="4.8.18";var Pa=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,La=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,Da=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function Ma(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),o=String(t?.toLayer??"");return Pa.test(n)?"pure-shared":r==="PersistenceAdapters"&&(La.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${o} ${n}`))?"kernel-emit":Da.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&o==="PersistenceAdapters"?"use-case":"unknown"}i(Ma,"classifyLayerImportKind");function Fa(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=Ma(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(Fa,"layerImportNextAction");function $a(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}i($a,"arkRunCallSiteName");function Ha(e){let t=$a(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(Ha,"arkRunNextAction");function ge(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return Fa(e);case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, test at the public interface, then preflight again.`;case"CAPABILITY_VIOLATION":return`Define a ${String(e.capability??"capability")} port in ${e.fromLayer??"the walled layer"}, bind the implementation outside it, test at the public interface, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, test at the public interface, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"LITERAL_PATH_DRIFT":return typeof e.target=="string"&&e.target.length>0?`Rewrite the literal to ${e.target}, or run \`arkgate-check --path-drift --base-ref <ref> --write\` to apply every anchored replacement.`:"Rewrite the literal to the rename destination, or run `arkgate-check --path-drift --base-ref <ref> --write` to apply every anchored replacement.";case"LITERAL_PATH_UNRESOLVED":return"Read the candidate and decide: fix the path, or leave it. Advisory \u2014 with no rename to anchor it there is no destination to propose, so --write never touches it.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";case"INVARIANT_COVERAGE_OUTSIDE_ROOTS":return"Move the covering test under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json, then run Ark again.";case"INVARIANT_CATALOG_EMPTY":return typeof e.file=="string"&&e.file.length>0?`Add 1\u20132 short phrases to invariants[] in ${e.file}, then run ark-check --doctor. Starters show the shape.`:"Add 1\u20132 short phrases to invariants[] in arkrules/<Domain>.json, then run ark-check --doctor. Starters show the shape.";case"INVARIANT_TESTS_PATH_MISSING":return"Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present.";case"INVARIANT_COVERAGE_ROOTS_MISSING":return"Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. An enforced invariant fails closed until that path is present.";case"ARKRULE_STRUCTURE":case"ARKRULE_INVARIANT":case"INVARIANT_UNCOVERED":return`Fix the structure or invariant for ${typeof e.arkruleId=="string"&&e.arkruleId.length>0?e.arkruleId:"the ArkRule"} (declared in ${typeof e.arkruleSource=="string"&&e.arkruleSource.length>0?e.arkruleSource:"arkrules/<Layer>.json"}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`;case"ARKRUN_MISSING_ROOT":case"ARKRUN_KERNEL_IN_DOMAIN":case"ARKRUN_DIRECT_NEW":case"ARKRUN_UNDECLARED_EMIT":case"ARKRUN_UNDECLARED_HANDLE":case"ARKRUN_UNDECLARED_DEPEND":case"ARKRUN_TRANSPORT_BYPASS":return Ha(e);case"ARKORDER_MISSING_PLANE":return typeof e.target=="string"&&e.target.length>0?`Import createOrderPlane from arkgate/order and call it in plane root ${e.target} listed in arkOrder.planeRoots, then preflight again.`:"Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKORDER_KERNEL_IN_DOMAIN":return"Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe.";case"ARKORDER_GENERIC_UPDATE":return"Don't use a generic update. First freeze with release(). Later, propose the change, then apply it.";case"ARKORDER_TOO_MANY_PARAMS":return"Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe.";case"ARKORDER_INGEST_WRITES_XI":return"Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe.";case"ARKORDER_XI_FIELD_WRITE":return typeof e.target=="string"&&e.target.length>0?`Don't write ${e.target} from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.`:"Don't write a named product choice from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.";case"ARKORDER_UNVALVED_RELEASE":return"Change the choice with proposeRelease then apply. release() is only the first freeze. Never mechanical-safe.";default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(ge,"deterministicNextAction");var Nt="1.5",wt="docs/diagnostics.md",Qr={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","mode","valid","completeness","completenessReasons","diagnostics"],allOf:[{if:{properties:{completeness:{enum:["partial","unavailable"]}},required:["completeness"]},then:{properties:{valid:{const:!1}}}},{if:{properties:{mode:{const:"resolved-candidate-facts"},completeness:{enum:["complete","partial"]}},required:["mode","completeness"]},then:{required:["policyHash","resolverIdentity","factsHash","candidateTreeHash"]}},{if:{properties:{completeness:{const:"complete"}},required:["completeness"]},then:{properties:{completenessReasons:{maxItems:0}}},else:{properties:{completenessReasons:{minItems:1}}}}],properties:{schemaVersion:{const:"1.5"},mode:{enum:["lexical-compatibility","resolved-candidate-facts"]},valid:{type:"boolean"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:{type:"string",minLength:1},message:{type:"string",minLength:1},file:{type:"string",minLength:1}}}},policyHash:{type:"string",minLength:1},resolverIdentity:{type:"string",minLength:1},factsHash:{type:"string",minLength:1},candidateTreeHash:{type:"string",minLength:1},diagnostics:{type:"array",items:{type:"object",additionalProperties:!1,required:["ruleId","severity","message","location","evidence"],properties:{ruleId:{type:"string",minLength:1},severity:{enum:["error","warning"]},message:{type:"string",minLength:1},location:{type:"object",additionalProperties:!1,required:["file","line","column"],properties:{file:{type:"string",minLength:1},line:{type:"integer",minimum:1},column:{type:"integer",minimum:1}}},evidence:{type:"object",additionalProperties:!1,properties:{target:{type:"string"},fromLayer:{type:"string"},toLayer:{type:"string"},typeOnly:{type:"boolean"},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"},peerIsolation:{type:"boolean"},capability:{type:"string",minLength:1},edgeKind:{type:"string",minLength:1},arkruleId:{type:"string",minLength:1},arkruleSource:{type:"string",minLength:1}}},nextAction:{type:"string",minLength:1},findingRef:{type:"string",minLength:1,pattern:"^fnv1a-[0-9a-f]{8}$"},targetKey:{type:"string",minLength:1},docsCodePath:{type:"string",minLength:1}}}}}};function nt(e){let t=typeof e.ruleId=="string"?e.ruleId:typeof e.code=="string"?e.code:void 0,n=typeof e.file=="string"?e.file:void 0,r=typeof e.fromLayer=="string"?e.fromLayer:void 0,o=typeof e.toLayer=="string"?e.toLayer:void 0,s=typeof e.target=="string"?e.target:void 0;return[t,n,r??"",o??"",s??""].join("|")}i(nt,"adapterFindingTargetKey");function rt(e){let t=new Map;return e.map(n=>{let r=nt(n),o=(t.get(r)??0)+1;return t.set(r,o),o===1?r:`${r}#${o}`})}i(rt,"adapterFindingOccurrenceTargetKeys");function Pt(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}i(Pt,"adapterFindingRefFromTargetKey");function Lt(e){return`${wt}#${e}`}i(Lt,"adapterDocsCodePath");function x(e){return typeof e=="string"&&e.length>0?e:void 0}i(x,"text");function es(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}i(es,"positiveInteger");function ja(e,t,n){return ge({ruleId:e,target:x(t.target)??x(n.target)??void 0,fromLayer:x(t.fromLayer)??void 0,toLayer:x(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:x(t.edgeKind)??void 0,capability:x(t.capability)??x(n.capability)??void 0,arkruleId:x(t.arkruleId)??void 0,arkruleSource:x(t.arkruleSource)??void 0})}i(ja,"nextActionForDiagnostic");function In(e,t="error",n){let r=x(e.ruleId)??x(e.code)??"ARK_UNKNOWN",o=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,s={...x(e.target)?{target:x(e.target)}:{},...x(e.fromLayer)?{fromLayer:x(e.fromLayer)}:{},...x(e.toLayer)?{toLayer:x(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}:{},...x(e.capability)?{capability:x(e.capability)}:{},...x(e.edgeKind)?{edgeKind:x(e.edgeKind)}:{},...x(e.arkruleId)?{arkruleId:x(e.arkruleId)}:{},...x(e.arkruleSource)?{arkruleSource:x(e.arkruleSource)}:{}},a=n??nt(e),c=Pt(a);return{ruleId:r,severity:o,message:x(e.message)??r,location:{file:x(e.file)??"<unknown>",line:es(e.line,1),column:es(e.column,1)},evidence:s,nextAction:x(e.nextAction)??ja(r,s,e),findingRef:c,targetKey:a,docsCodePath:Lt(r)}}i(In,"toAdapterDiagnostic");function Ka(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:x(g.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:x(g.message)??`Analysis ${t}: required evidence is incomplete.`,...x(g.file)?{file:x(g.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],o={...x(e.policyHash)?{policyHash:x(e.policyHash)}:{},...x(e.resolverIdentity)?{resolverIdentity:x(e.resolverIdentity)}:{},...x(e.factsHash)?{factsHash:x(e.factsHash)}:{},...x(e.candidateTreeHash)?{candidateTreeHash:x(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let g of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!o[g])throw new Error(`${g} is required for resolved ${t} adapter evidence.`)}let s=e.violations??[],a=e.warnings??[],c=rt(s),l=rt(a),u=[...s.map((g,f)=>In(g,"error",c[f])),...a.map((g,f)=>In(g,"warning",l[f]))],p={schemaVersion:"1.5",completenessReasons:r,diagnostics:u};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...p,mode:n,valid:!1,completeness:t,...o};let g={policyHash:o.policyHash,resolverIdentity:o.resolverIdentity,factsHash:o.factsHash,candidateTreeHash:o.candidateTreeHash};return t==="complete"?{...p,mode:n,valid:e.valid,completeness:t,...g}:{...p,mode:n,valid:!1,completeness:t,...g}}return t==="complete"?{...p,mode:n,valid:e.valid,completeness:t,...o}:{...p,mode:n,valid:!1,completeness:t,...o}}i(Ka,"createAdapterResult");var Va="1.0",ts="https://unpkg.com/arkgate@4/schemas/ark.project-identity.schema.json",Dt="^sha256:[a-f0-9]{64}$",ns={type:"object",additionalProperties:!1,properties:{expectedRoot:{type:"string",minLength:1,description:"Absolute expected workspace/project directory. The initial authoritative handshake requires the exact project root; descendant calls also require expectedProjectId."},expectedProjectId:{type:"string",pattern:Dt,description:"Project id previously returned by ark_identity or ark_manifest."}}},rs={type:"object",additionalProperties:!1,required:["status","authoritative"],properties:{status:{enum:["matched","unverified","mismatch"]},authoritative:{type:"boolean"},expectedRoot:{type:"string",minLength:1},expectedProjectId:{type:"string",pattern:Dt},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},Ua={$schema:"https://json-schema.org/draft/2020-12/schema",$id:ts,title:"ArkGate MCP project identity",description:"Stable project binding plus separate runtime and architecture-contract evidence.",type:"object",additionalProperties:!1,required:["schemaVersion","projectId","resolvedRoot","resolvedConfigPath","arkgateVersion","contractHash","contractSource","runtimeId","processStartedAt"],properties:{schemaVersion:{const:"1.0"},projectId:{type:"string",pattern:Dt},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{type:"string",minLength:1},arkgateVersion:{type:"string",minLength:1},contractHash:{type:"string",pattern:Dt},contractSource:{enum:["project","default-profile","manifest"]},runtimeId:{type:"string",minLength:1},processStartedAt:{type:"string",format:"date-time"}},$defs:{expectation:ns,binding:rs}};function Ga(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(Ga,"createProjectId");function Ba(e){return{schemaVersion:"1.0",...e}}i(Ba,"createProjectIdentity");var vn=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),_n=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),On=Object.freeze(Object.keys(_n).sort()),bn=Object.freeze({fs:"filesystem","node:fs":"filesystem","fs/promises":"filesystem","node:fs/promises":"filesystem","fs-extra":"filesystem","graceful-fs":"filesystem",memfs:"filesystem",chokidar:"filesystem",http:"network",https:"network",http2:"network",net:"network",tls:"network",dgram:"network",dns:"network","node:http":"network","node:https":"network","node:http2":"network","node:net":"network","node:tls":"network","node:dgram":"network","node:dns":"network",axios:"network",undici:"network","node-fetch":"network",got:"network",ky:"network",superagent:"network",ws:"network",process:"process","node:process":"process",child_process:"process","node:child_process":"process","@prisma/client":"persistence",prisma:"persistence",pg:"persistence",mysql:"persistence",mysql2:"persistence",mongodb:"persistence",mongoose:"persistence",sqlite3:"persistence","better-sqlite3":"persistence",redis:"persistence",ioredis:"persistence",typeorm:"persistence",knex:"persistence","drizzle-orm":"persistence",sequelize:"persistence",kysely:"persistence","@supabase/supabase-js":"persistence"}),Cn=Object.freeze({process:Object.freeze(["process","node:process"])});function st(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=bn[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),o=bn[r];if(o)return o;let s=e.indexOf("/",n+1);return s<0?null:bn[e.slice(0,s)]??null}i(st,"capabilityForModuleSpecifier");function Ce(e,t){for(let n of t)if(Cn[n]?.includes(e))return n;return null}i(Ce,"forbiddenGlobalForModuleSpecifier");function Mt(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),o=_n[r];if(o)return o}return null}i(Mt,"capabilityForAmbientName");function je(e){if(e?.pure===!0)return[...vn].sort();let n=(e?.capabilities?.deny??[]).filter(r=>vn.includes(r));return[...new Set(n)].sort()}i(je,"effectiveCapabilityDeny");function ot(e,t){if(t.length===0)return!1;let n=new Set(t),r=e.split(".");for(let o=r.length;o>=1;o-=1)if(n.has(r.slice(0,o).join(".")))return!0;return!1}i(ot,"ambientCoveredByForbiddenGlobals");function Ft(e){let t=new Set,n=new Set,r=Object.keys(_n);for(let o of e?.forbiddenGlobals??[]){let s=r.filter(a=>a===o||a.startsWith(`${o}.`));if(s.length===0)n.add(o);else for(let a of s)t.add(`ambient:${a}`);for(let a of Cn[o]??[])t.add(`import-exact:${a}`)}for(let o of je(e)){if(t.add(`import:${o}`),o==="process")for(let s of Cn.process)t.add(`import-exact:${s}`);for(let s of r)Mt(s)===o&&t.add(`ambient:${s}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}i(Ft,"loweredLayerCoverage");var ss=new Map;function os(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(os,"escapeLiteral");function $t(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let o=e[n+1];if("*?{}[],".includes(o)||o==="\\"){t+="\\"+o,n+=1;continue}t+="/";continue}t+=r}return t}i($t,"normalizeGlobSeparators");function za(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(za,"bracesBalanced");function Re(e){let t=ss.get(e);if(t)return t;let n=$t(e),r=za(n),o="",s=0;for(let c=0;c<n.length;c+=1){let l=n[c];l==="\\"&&c+1<n.length?(o+=os(n[c+1]),c+=1):l==="*"?n[c+1]==="*"?n[c+2]==="/"?(o+="(?:.*/)?",c+=2):(o+=".*",c+=1):o+="[^/]*":l==="?"?o+="[^/]":l==="{"&&r?(o+="(?:",s+=1):l==="}"&&r&&s>0?(o+=")",s-=1):l===","&&r&&s>0?o+="|":o+=os(l)}let a=new RegExp(`^${o}$`);return ss.set(e,a),a}i(Re,"globToRegExp");function Wa(e){return $t(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}i(Wa,"concreteGlobSegments");function xn(e,t){let n=$t(String(e)),r=Wa(n),o=n.replace(/\*/g,"").length,s=r.length*1e4+o;if(t==null||t==="")return s;let a=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return o;let c=0,l=-1;for(let u of r){let p=-1;for(let g=c;g<a.length;g+=1)if(a[g]===u){p=g;break}if(p<0)return s;l=p,c=p+1}return(l+1)*1e6+r.length*1e4+o}i(xn,"patternSpecificity");function fe(e,t){let n=String(e).split(/[/\\]/).join("/"),r,o=-1;for(let s of t??[])if(!(s.exclude??[]).some(a=>Re(a).test(n))){for(let a of s.patterns??[])if(Re(a).test(n)){let c=xn(a,n);c>o&&(o=c,r=s.name)}}return r}i(fe,"layerForRelativePath");function as(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),r=new Set(t.map(o=>String(o).toLowerCase()));for(let o=0;o<n.length-1;o+=1)if(r.has(n[o].toLowerCase()))return`${n[o].toLowerCase()}/${n[o+1].toLowerCase()}`}i(as,"sliceIdForPath");function qa(e){let t=new Set;for(let n of e??[]){let o=$t(String(n)).split("/").filter(Boolean);for(let s=0;s<o.length;s+=1){let a=o[s];if((a==="**"||a==="*")&&s>0){let c=o[s-1];c&&!c.includes("*")&&!c.includes("{")&&!c.includes("}")&&t.add(c)}}}return[...t]}i(qa,"inferSliceFoldersFromPatterns");function Ya(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(o=>typeof o=="string"&&o.length>0);let r=(n??[]).find(o=>o.name===t);return qa(r?.patterns)}i(Ya,"resolveSliceFolders");function is(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}i(is,"normalizeSegments");function ds(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}i(ds,"trimTrailingSlashes");var Ja=["src","app"];function Xa(e){let t=ds(e.replace(/^[./]+/,""));return t==="*"||t==="**"}i(Xa,"isBlanketRoot");function ls(e,t){if(!e||!t?.length)return!1;let n=String(e).split(/[/\\]/).join("/"),r=n.toLowerCase(),o=is(n);for(let s of t){if(typeof s!="string"||s.length===0||Xa(s))continue;if(s.includes("*")){let l=ds(s.toLowerCase());if(Re(l).test(r)||Re(`${l}/**`).test(r))return!0;continue}let a=is(s);if(a.length===0)continue;let c=Ja.includes(o[0])&&a[0]!==o[0]?[0,1]:[0];for(let l of c){if(l+a.length>o.length)continue;let u=!0;for(let p=0;p<a.length;p+=1)if(o[l+p]!==a[p]){u=!1;break}if(u)return!0}}return!1}i(ls,"pathUnderSharedRoot");function cs(e,t){let n=String(e).split(/[/\\]/).filter(Boolean).join("/").toLowerCase();if(!n)return!1;let r=t.toLowerCase();return n===r?!0:!n.includes("/")&&r.endsWith(`/${n}`)}i(cs,"sliceMatchesDeclaration");function Za(e,t,n){return!e?.length||!t||!n?!1:e.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&cs(r.from,t)&&cs(r.to,n))}i(Za,"crossSliceEdgeAllowed");function Qa(e){if(!e.fromPath)return{denied:!0,reason:"missing-path"};if(e.folderCount<=0)return{denied:!0,reason:"no-slice-folders"};let t=!!e.fromSlice||e.fromShared===!0;if(!e.toPath)return t?e.fromSlice?{denied:!0,reason:"missing-path"}:{denied:!1}:{denied:!0,reason:"unclassifiable-path"};let n=!!e.toSlice||e.toShared===!0;return!t||!n?{denied:!0,reason:"unclassifiable-path"}:!e.fromSlice||!e.toSlice?{denied:!1}:e.fromSlice===e.toSlice?{denied:!1}:e.crossSliceAllowed?{denied:!1}:{denied:!0,reason:"cross-slice"}}i(Qa,"peerIsolationDecision");function Ke(e,t){switch(e){case"cross-slice":return`cross-slice edge ${t.fromSlice??"?"} \u2192 ${t.toSlice??"?"}. Extract the shared code, use events/ports across slices, or declare the edge in the rule's allowedCrossSlice.`;case"unclassifiable-path":{let n=[t.fromSlice?void 0:t.fromPath,t.toSlice?void 0:t.toPath].filter(o=>!!o);return`unclassifiable path${n.length>0?` (${n.join(", ")})`:""} \u2014 ArkGate cannot place it in a slice, so it cannot prove this is not a cross-slice edge. Move it into a slice, or declare its root in the rule's sharedRoots.`}case"no-slice-folders":return"no slice folders \u2014 peerIsolation is on but no slice folder resolves from the rule or the layer patterns. Set sliceFolders on the rule.";default:return"no path evidence for this edge \u2014 peerIsolation needs the importer and importee paths."}}i(Ke,"peerIsolationDenyExplanation");function Ht(e,t,n,r){return Te(e,t,n,r)?.rule}i(Ht,"findDeniedEdgeRule");function Te(e,t,n,r){for(let o of e??[])if(!(o.from!==t||o.to!==n)&&o.allowed===!1){if(o.peerIsolation){let s=r?.fromPath,a=r?.toPath,c=Ya(o,t,r?.layers),l=s?as(s,c):void 0,u=a?as(a,c):void 0,p=Qa({fromPath:s,toPath:a,folderCount:c.length,fromSlice:l,toSlice:u,fromShared:!l&&ls(s,o.sharedRoots),toShared:!u&&ls(a,o.sharedRoots),crossSliceAllowed:Za(o.allowedCrossSlice,l,u)});if(p.denied)return{rule:o,peerIsolationReason:p.reason,fromSlice:l,toSlice:u};continue}if(t!==n)return{rule:o}}}i(Te,"findDeniedEdgeDecision");function Ve(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(Ve,"literalText");function fs(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}i(fs,"lineOf");function us(e,t){if(e.isImportDeclaration(t)){let r=t.importClause;if(!r)return!1;if(r.isTypeOnly)return!0;let o=r.namedBindings;return!!(o&&e.isNamedImports(o)&&o.elements.length>0&&o.elements.every(s=>s.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(r=>r.isTypeOnly))}i(us,"isTypeOnlyReference");function ms(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=o=>o===t.fileName?t:void 0,r.fileExists=o=>o===t.fileName,r.readFile=o=>o===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}i(ms,"singleFileChecker");function Tn(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}i(Tn,"symbolAt");function Nn(e,t,n,r){let o=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,s;try{s=o?t.getShorthandAssignmentValueSymbol(r.parent):Tn(t,r)}catch{s=void 0}return!!s?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}i(Nn,"localDeclaration");function Ue(e,t){let n,r=[],o=i((a,c,l,u=!1)=>r.push({specifier:l,kind:c,line:fs(t,a),typeOnly:u,unresolved:l===void 0,node:a}),"add"),s=i(a=>{if(e.isImportDeclaration(a))o(a,"import",Ve(e,a.moduleSpecifier),us(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)o(a,"export",Ve(e,a.moduleSpecifier),us(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))o(a,"require",Ve(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let c=a.expression.kind===e.SyntaxKind.ImportKeyword,u=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!Nn(e,n??(n=ms(e,t)),t,a.expression);(c||u)&&o(a,u?"require":"dynamic-import",Ve(e,a.arguments[0]))}e.forEachChild(a,s)},"visit");return s(t),r}i(Ue,"extractSemanticDependencies");function ei(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let o=Ve(e,r.argumentExpression);if(o===void 0)return;n.unshift(o)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}i(ei,"staticAccessPath");function ti(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(ti,"runtimeIdentifierReference");function ps(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let r=n.length;r>=1;r-=1){let o=n.slice(0,r).join(".");if(e.has(o))return o}}i(ps,"bestForbiddenMatch");function Ge(e,t,n){if(n.length===0)return[];let r=new Set(n),o=ms(e,t),s=new Map,a=new Set;for(let f of t.statements)if(e.isVariableStatement(f))for(let m of f.declarationList.declarations)e.isIdentifier(m.name)&&a.add(m.name.text);let c=i(f=>{let m=ei(e,f);if(!m)return;let d=Tn(o,m.root),A=d?s.get(d):void 0;return A?[...A,...m.segments.slice(1)]:Nn(e,o,t,m.root)||a.has(m.root.text)?void 0:m.segments},"resolvePath");for(let f of t.statements)if(e.isVariableStatement(f))for(let m of f.declarationList.declarations){if(!m.initializer||!e.isIdentifier(m.name))continue;let d=c(m.initializer),A=Tn(o,m.name);!d||!A||s.set(A,d)}let l=[],u=new Set,p=i((f,m)=>{let d=fs(t,m),A=`${f}:${m.getStart(t)}`;u.has(A)||(u.add(A),l.push({name:f,line:d,node:m}))},"flag"),g=i(f=>{let m=f.parent&&(e.isPropertyAccessExpression(f.parent)||e.isElementAccessExpression(f.parent))&&f.parent.expression===f;if((e.isPropertyAccessExpression(f)||e.isElementAccessExpression(f))&&!m){let d=c(f),A=d?ps(r,d):void 0;A&&p(A,f)}else e.isIdentifier(f)&&r.has(f.text)&&ti(e,f)&&!Nn(e,o,t,f)&&p(f.text,f);if(e.isVariableDeclaration(f)&&e.isObjectBindingPattern(f.name)&&f.initializer){let d=c(f.initializer);if(d)for(let A of f.name.elements){if(!e.isIdentifier(A.name))continue;let b=A.propertyName?Ve(e,A.propertyName)??A.propertyName.text:A.name.text,O=ps(r,[...d,b]);O&&p(O,f.initializer)}}e.forEachChild(f,g)},"visit");return g(t),l}i(Ge,"collectForbiddenCapabilityUses");function wn(e,t,n){let r=[];for(let o of n?.dependencies??Ue(e,t)){if(o.typeOnly||!o.specifier)continue;let s=st(o.specifier);s&&r.push({capability:s,symbol:o.specifier,line:o.line,source:"import-based"})}for(let o of n?.ambientUses??Ge(e,t,On)){let s=Mt(o.name);s&&r.push({capability:s,symbol:o.name,line:o.line,source:"ambient-global"})}return r.sort((o,s)=>o.line-s.line||o.capability.localeCompare(s.capability)||o.symbol.localeCompare(s.symbol))}i(wn,"collectCapabilityUses");var Pn={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."},Ln=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 Dn(e,t){return t.flatMap((r,o)=>(r.prefixes??r.intentPrefixes??[]).map(s=>({layer:r.name,layerIndex:o,prefix:s.endsWith(".")?s:`${s}.`}))).filter(({prefix:r})=>e.startsWith(r)).sort((r,o)=>o.prefix.length-r.prefix.length||r.layerIndex-o.layerIndex)[0]?.layer}i(Dn,"resolveIntentLayer");function Ne(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}i(Ne,"looksLikeArkIntent");function at(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&Ne(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:Pn.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:Pn.PUBLISH_MISSING_SOURCE}),t}i(at,"classifyPublishFacts");function W(e,t,n){return{ruleId:e,code:e,message:t,...n}}i(W,"violation");function Be(e,t){return e.slice(0,t).split(`
|
|
2
2
|
`).length}i(Be,"lineOf");var ni=new Set(["publish","subscribe","defineIntent","registerHandler"]);function ri(e,t){return e.index+e[0].indexOf(t)}i(ri,"captureIndex");function si(e){let t=[],n=new Set,r=i((c,l)=>{!c||n.has(l)||(n.add(l),t.push({value:c,index:l}))},"push"),o=i(c=>{c.lastIndex=0;let l;for(;(l=c.exec(e))!==null;){let u=l[1];u&&r(u,ri(l,u))}},"pushFrom");o(/\b(?:publish|subscribe|defineIntent|registerHandler)\s{0,8}(?:<[^>]{0,120}>)?\s{0,8}\(\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),o(/\b(?:intent|onEvent)\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g);let s=/\breactsTo\s{0,8}:\s{0,8}\[([^\]]{0,2000})\]/g,a;for(;(a=s.exec(e))!==null;){let c=a[1]??"",l=a.index+a[0].indexOf(c),u=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,p;for(;(p=u.exec(c))!==null;){let g=p[1];g&&r(g,l+p.index+p[0].indexOf(g))}}return o(/\bmetadata\s{0,8}:\s{0,8}\{[^}]{0,400}\bsource\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),o(/\bpublish\s{0,8}(?:<[^>]{0,120}>)?\s{0,8}\([^;]{0,400}?\bsource\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),t.sort((c,l)=>c.index-l.index)}i(si,"extractQuotedStrings");function oi(e){let t=[],n=[{kind:"import",re:/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s*)?['"]([^'"]+)['"]/g},{kind:"export",re:/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s*['"]([^'"]+)['"]/g},{kind:"dynamic-import",re:/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g},{kind:"require",re:/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g}];for(let r of n){let o;for(;(o=r.re.exec(e))!==null;){let s=o.index+o[0].indexOf(o[1]),a=o[0],c=r.kind==="import"&&/\bimport\s+type\b/.test(a)||r.kind==="export"&&/\bexport\s+type\b/.test(a);t.push({value:o[1],index:s,kind:r.kind,typeOnly:c})}}return t.sort((r,o)=>r.index-o.index)}i(oi,"extractModuleSpecifiers");function ai(e,t){return!!(t&&(e.isParenthesizedExpression(t)||e.isAsExpression(t)||typeof e.isTypeAssertionExpression=="function"&&e.isTypeAssertionExpression(t)||typeof e.isSatisfiesExpression=="function"&&e.isSatisfiesExpression(t)))}i(ai,"isSyntaxWrapper");function Mn(e,t){let n=t;for(;n?.parent&&ai(e,n.parent);)n=n.parent;return n}i(Mn,"unwrapWrappers");function Fn(e,t){if(!t||!e.isCallExpression(t))return;let n=t.expression;if(e.isIdentifier(n))return n.text;if(e.isPropertyAccessExpression(n))return n.name.text}i(Fn,"callCalleeName");function ii(e,t){let n=t.parent;if(!n||!e.isObjectLiteralExpression(n))return!1;let r=Mn(e,n),o=r.parent;if(!o)return!1;if(e.isCallExpression(o)&&Fn(e,o)==="publish"){let s=o.arguments;return s[1]===r||s[2]===r}if(e.isPropertyAssignment(o)&&$n(e,o.name)==="metadata"){let s=o.parent;if(!s)return!1;let c=Mn(e,s).parent;return!!(c&&e.isCallExpression(c)&&Fn(e,c)==="publish")}return!1}i(ii,"isPublishMetadataSource");function gs(e,t){let n=Mn(e,t),r=n.parent;if(!r)return!1;if(e.isCallExpression(r)){let o=Fn(e,r);if(o&&ni.has(o)&&r.arguments.some(s=>s===n))return!0}if(e.isArrayLiteralExpression(r))return gs(e,r);if(e.isPropertyAssignment(r)){let o=$n(e,r.name);if(o==="intent"||o==="onEvent"||o==="reactsTo"||o==="source"&&ii(e,r))return!0}return!1}i(gs,"isDeclaredIntentSite");function li(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],o=i(s=>{e.isStringLiteralLike(s)&&gs(e,s)&&r.push({value:s.text,index:s.getStart(n)}),e.forEachChild(s,o)},"visit");return o(n),r}i(li,"extractQuotedStringsAst");function ci(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(ci,"hasInfrastructureToken");function di(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}i(di,"isKnownInfrastructurePackage");function ui(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}i(ui,"layerHasInfrastructureRole");function lt(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(lt,"tsStringLiteralText");function $n(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}i($n,"tsPropertyName");function ys(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:$n(e,r.name)===n)}i(ys,"tsObjectProperty");function ct(e,t,n){return ys(e,t,n)!==void 0}i(ct,"tsObjectHasProperty");function it(e,t,n){let r=ys(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}i(it,"tsObjectPropertyValue");function pi(e,t){let n=it(e,t,"metadata");return ct(e,n,"source")}i(pi,"tsObjectHasMetadataSource");function hs(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?hs(e,t.name):!1:!1}i(hs,"tsLooksLikeIntentCreatorExpression");function fi(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(fi,"tsIsPublishCall");function mi(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=lt(e,n);return r!==void 0&&Ne(r)||ct(e,n,"intent")||hs(e,n)}i(mi,"tsIsArkPublishCandidate");function gi(e,t){if(!e.isCallExpression(t))return!1;let[n,r,o]=t.arguments;return pi(e,n)||ct(e,r,"source")||ct(e,o,"source")}i(gi,"tsPublishHasSource");function yi(e,t){if(!e.isCallExpression(t))return;let[n,r,o]=t.arguments,s=it(e,n,"metadata");return lt(e,it(e,s,"source"))??lt(e,it(e,r,"source"))??lt(e,it(e,o,"source"))}i(yi,"tsPublishSourceLiteral");function hi(e,t,n,r){let o=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),s=n,a=s?.filePath,c=s?.layer,l=[],u=i(g=>o.getLineAndCharacterOfPosition(g.getStart(o)).line+1,"lineForNode"),p=i(g=>{if(fi(e,g)){let f=g.arguments[0],m=lt(e,f);for(let A of at({publishCall:!0,rawIntentName:m,objectHasIntent:ct(e,f,"intent"),arkPublishCandidate:mi(e,g),hasSource:gi(e,g)}))l.push(W(A.ruleId,A.message,{line:u(g),filePath:a}));let d=yi(e,g);if(r&&c&&d&&Ne(d)){let A=r.resolveLayer(d);A&&A!==c&&l.push(W("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${d}" resolves to ${A}, but the target file is classified as ${c}.`,{line:u(g),filePath:a,target:d,fromLayer:c,toLayer:A}))}}e.forEachChild(g,p)},"visit");return p(o),l}i(hi,"analyzePublishAst");function As(e={}){let t=new Set((e.intents||[]).map(s=>typeof s=="string"?s:s.name)),n=e.forbiddenPatterns||[],r=new Set(e.infrastructureLayers??[]),o=e.enforceIntentAllowlist??t.size>0;return{validate(s,a){let c=[],l=a,u=l?.filePath,p=l?.layer,g=e.typescript,f=g?g.createSourceFile(u??"generated.ts",s,g.ScriptTarget.Latest,!0):void 0,m=f?Ue(e.typescript,f):void 0,d=m?m.filter(k=>k.specifier!==void 0).map(k=>({value:k.specifier,index:k.node.getStart(f),kind:k.kind,typeOnly:k.typeOnly})):oi(s),A=e.typescript?li(e.typescript,s):si(s);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(u))for(let k of m?.filter(({unresolved:I})=>I)??[]){let I=k.kind==="require";c.push(W(I?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${I?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:k.line,filePath:u}))}let b=p!==void 0&&(r.has(p)||ui(p)),O=p!==void 0?` If "${p}" is an infrastructure layer, mark it in ark.config.json with "mayImportInfrastructure": true (or name it with an infra token like Adapters/Persistence/Repository).`:"";for(let k of n)if(k instanceof RegExp){k.lastIndex=0;let I=k.exec(s);k.lastIndex=0,I&&c.push(W("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${k}`,{line:I.index===void 0?void 0:Be(s,I.index),filePath:u,suggestion:"Remove infrastructure imports from domain/application layers."+O}))}else s.includes(k)&&c.push(W("FORBIDDEN_SUBSTRING",`Forbidden substring: ${k}`,{line:Be(s,s.indexOf(k)),filePath:u}));for(let k of d){let I=e.resolveImportTarget?.(k.value,u)??(e.resolveImportLayer?{layer:e.resolveImportLayer(k.value,u)}:void 0),C=typeof u=="string"?e.resolveImportTarget?.(u)??(e.resolveImportLayer?{layer:p,relPath:void 0}:void 0):void 0,L=I?.layer;if(L&&p){let E=Ht(e.architectureProfile?.rules,p,L,{fromPath:C?.relPath,toPath:I?.relPath,layers:e.architectureLayers});if(E){if(k.typeOnly&&!E.peerIsolation)continue;let P=!!E.peerIsolation;c.push(W("LAYER_IMPORT_VIOLATION",E.message??(P?`Layer "${p}" must not import across slices into "${L}".`:`Layer "${p}" must not import "${L}".`),{line:Be(s,k.index),source:k.value,target:k.value,filePath:u,fromLayer:p,toLayer:L,suggestion:P?"Extract shared code to a shared layer, or coordinate slices via events/ports \u2014 do not import across feature/context slices.":"Depend on a port/interface owned by an inner layer instead, or move this code to a layer allowed to make this import.",details:{importKind:k.kind,peerIsolation:P,...k.typeOnly?{typeOnly:!0}:{}}}));continue}continue}b||k.typeOnly||!ci(k.value)&&!di(k.value)||c.push(W("FORBIDDEN_IMPORT",`Forbidden ${k.kind} target: "${k.value}".`,{line:Be(s,k.index),source:k.value,target:k.value,filePath:u,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+O,details:{importKind:k.kind}}))}if(e.policies)for(let k of e.policies){let I=k.check({source:s,context:a});if(I!==!0)if(Array.isArray(I))for(let C of I)c.push(W("POLICY_VIOLATION",C.message,{filePath:u,suggestion:`Fix violation of policy "${k.name}".`}));else I===!1?c.push(W("POLICY_VIOLATION",`Policy ${k.name} failed on generated code`)):c.push(W("POLICY_VIOLATION",I.message))}if(o&&t.size>0)for(let k of A)Ne(k.value)&&!t.has(k.value)&&c.push(W("UNKNOWN_INTENT",`Unknown intent reference: "${k.value}"`,{line:Be(s,k.index),filePath:u,target:k.value,suggestion:`Register intent "${k.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&p)for(let k of A){if(!Ne(k.value))continue;let I=e.architectureProfile.resolveLayer(k.value);if(!I)continue;let C=Te(e.architectureProfile.rules,p,I,{fromPath:typeof u=="string"?u:void 0,layers:e.architectureLayers});if(C){let L=C.rule.peerIsolation?Ke(C.peerIsolationReason??"cross-slice",{fromPath:typeof u=="string"?u:void 0,fromSlice:C.fromSlice,toSlice:C.toSlice}):void 0,E=`Layer "${p}" must not reference "${I}" through "${k.value}".`,P=L&&C.peerIsolationReason!=="cross-slice"?`${E} ${L}`:C.rule.message?L?`${C.rule.message} (${L})`:C.rule.message:E;c.push(W("LAYER_REFERENCE_VIOLATION",P,{line:Be(s,k.index),filePath:u,target:k.value,fromLayer:p,toLayer:I,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:C.rule,peerIsolationReason:C.peerIsolationReason}}))}}if(e.extensions)for(let k of e.extensions)try{let I=k.analyze(s,a);c.push(...I)}catch(I){c.push(W("EXTENSION_ERROR",`Extension "${k.name}" failed: ${I instanceof Error?I.message:String(I)}`))}if(e.typescript&&f&&p&&e.forbiddenGlobals?.[p]?.length)try{let k=e.forbiddenGlobals[p];c.push(...Ge(e.typescript,f,k).map(I=>W("FORBIDDEN_GLOBAL",`${p} must not use the ambient global "${I.name}".`,{line:I.line,filePath:u,target:I.name,fromLayer:p,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let I of m??[]){if(I.typeOnly||!I.specifier)continue;let C=Ce(I.specifier,k);C&&c.push(W("FORBIDDEN_GLOBAL",`${p} must not use module "${I.specifier}" because it is the import form of forbidden global "${C}".`,{line:I.line,filePath:u,source:I.specifier,target:I.specifier,fromLayer:p,details:{importKind:I.kind,forbiddenGlobal:C},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(k){c.push(W("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${k instanceof Error?k.message:String(k)}`))}if(e.typescript&&f&&p&&e.capabilityWalls?.[p]?.length)try{let k=new Set(e.capabilityWalls[p]),I=e.forbiddenGlobals?.[p]??[];for(let C of wn(e.typescript,f))k.has(C.capability)&&(C.source==="ambient-global"&&ot(C.symbol,I)||C.source==="import-based"&&Ce(C.symbol,I)||c.push(W("CAPABILITY_VIOLATION",C.source==="import-based"?`${p} denies the ${C.capability} capability; found import of "${C.symbol}".`:`${p} denies the ${C.capability} capability; found ambient "${C.symbol}".`,{line:C.line,filePath:u,target:C.symbol,capability:C.capability,fromLayer:p,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(k){c.push(W("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${k instanceof Error?k.message:String(k)}`))}if(e.typescript)try{c.push(...hi(e.typescript,s,a,e.architectureProfile))}catch(k){c.push(W("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${k instanceof Error?k.message:String(k)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:c.length===0,violations:c}}}}i(As,"createAICodeGate");var we={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Rs={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...we,default:[]},kernelRoots:{...we},managedLayers:{...we,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},ks={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...we,default:[]},managedLayers:{...we,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...we,default:[]},appliesTo:{...we,default:[]}}};function dt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(dt,"isObject");function Es(e){let t=new Set;if(!Array.isArray(e.layers))return t;for(let n of e.layers)dt(n)&&typeof n.name=="string"&&n.name.length>0&&t.add(n.name);return t}i(Es,"declaredLayerNames");function Ss(e){if(!dt(e))return e;let t={mode:e.mode===void 0?"advisory":e.mode,compositionRoots:e.compositionRoots===void 0?[]:e.compositionRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,requireDeclarations:e.requireDeclarations===void 0?!0:e.requireDeclarations};return e.kernelRoots!==void 0&&(t.kernelRoots=e.kernelRoots),e.ignoreDirectNewForErrors!==void 0&&(t.ignoreDirectNewForErrors=e.ignoreDirectNewForErrors),{...e,...t}}i(Ss,"defaultedArkRun");function Is(e){if(!dt(e))return e;let t=typeof e.maxXiKeys=="number"&&e.maxXiKeys>0?e.maxXiKeys:7;return{...e,mode:e.mode===void 0?"advisory":e.mode,planeRoots:e.planeRoots===void 0?[]:e.planeRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,maxXiKeys:t,xiKeys:e.xiKeys===void 0?[]:e.xiKeys}}i(Is,"defaultedArkOrder");function bs(e,t){let n=e.arkRun;if(n===void 0||!dt(n))return;let r=Es(e),o=n.managedLayers;if(Array.isArray(o)&&o.forEach((s,a)=>{typeof s=="string"&&s.length>0&&!r.has(s)&&t.push({path:`$.arkRun.managedLayers[${a}]`,message:`layer ${JSON.stringify(s)} is not declared in layers[]`})}),n.mode==="enforced"){let s=n.kernelRoots??n.compositionRoots;(!Array.isArray(s)||s.length===0)&&t.push({path:n.kernelRoots!==void 0?"$.arkRun.kernelRoots":"$.arkRun.compositionRoots",message:"ARKRUN_MISSING_ROOT: enforced mode requires at least one kernel root"}),(!Array.isArray(o)||o.length===0)&&t.push({path:"$.arkRun.managedLayers",message:"enforced mode requires at least one managed layer"})}}i(bs,"validateArkRunExtra");function vs(e,t){let n=e.arkOrder;if(n===void 0||!dt(n))return;let r=Es(e),o=n.managedLayers;if(Array.isArray(o)&&o.forEach((s,a)=>{typeof s=="string"&&s.length>0&&!r.has(s)&&t.push({path:`$.arkOrder.managedLayers[${a}]`,message:`layer ${JSON.stringify(s)} is not declared in layers[]`})}),n.mode==="enforced"){let s=n.planeRoots;(!Array.isArray(s)||s.length===0)&&t.push({path:"$.arkOrder.planeRoots",message:"ARKORDER_MISSING_PLANE: enforced mode requires at least one plane root"}),(!Array.isArray(o)||o.length===0)&&t.push({path:"$.arkOrder.managedLayers",message:"enforced mode requires at least one managed layer"})}}i(vs,"validateArkOrderExtra");function jt(e){if(typeof e!="string")return null;let t=e.trim().replace(/^@/,"").toLowerCase();return t.length>0?t:null}i(jt,"normalizeStewardId");function Cs(e){let t=jt(e);return!t||Hn(t)||t.includes(" ")||t.includes("@")?!1:/^(?!-)[a-z0-9-]{1,39}(?<!-)$/.test(t)}i(Cs,"isGitHubHandle");function Ai(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();return!t.includes("@")||t.includes(" ")||Hn(t)?!1:/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}i(Ai,"isGitHubEmail");function Ri(e){if(typeof e!="string")return null;let t=e.trim().match(/^(?:\d+\+)?([^@]+)@users\.noreply\.github\.com$/i);return t&&Cs(t[1])?jt(t[1]):null}i(Ri,"githubHandleFromEmail");function _s(e){let t=Ri(e);if(t)return t;let n=jt(e);return!n||Hn(n)?null:Cs(n)||Ai(n)?n:null}i(_s,"canonicalStewardId");var ki=/bot\b|\[bot\]|dependabot|renovate|github-actions|imgbot|codecov/i;function Hn(e){let t=jt(e);return!t||ki.test(t)}i(Hn,"isAutomationAuthor");var le="1.3",Ei=["public","auth","admin","internal"];function Si(e){return e?.optional===!0||e?.reserved===!0||e?.allowEmpty===!0}i(Si,"isFutureHouseLayer");function Ii(e){let t=e&&typeof e=="object"?e.owners:void 0;if(!Array.isArray(t)||t.length===0)return;let n=t.filter(r=>typeof r=="string"&&r.length>0);return n.length>0?n:void 0}i(Ii,"layerOwnersList");function xs(e){return e?.requireLayerOwners!==!0||!Array.isArray(e.layers)?[]:e.layers.filter(t=>!Si(t)&&!Ii(t)).map(t=>t.name)}i(xs,"layersMissingRequiredOwners");function Ts(e){return`Add a GitHub handle or email to ${e}'s owners in ark.config.json (/ark-adopt).`}i(Ts,"missingLayerOwnersNextAction");var Vt="https://unpkg.com/arkgate@4/schemas/ark.config.schema.json",Os=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],bi=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function vi(){let e=[];for(let t of Os)for(let n of Os)t===n||bi.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}i(vi,"createDefaultRules");var Ut=vi(),jn=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"},{from:"1.1",to:"1.2"},{from:"1.2",to:"1.3"}],ie={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Kn={$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:le,default:le},name:{type:"string",minLength:1},include:{...ie,minItems:1,default:["src"]},exclude:{...ie,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:Ut,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...ie,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},coverage:{$ref:"#/$defs/coverage"},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},arkRun:{$ref:"#/$defs/arkRun"},arkOrder:{$ref:"#/$defs/arkOrder"},stewards:{...ie,default:[]},requireLayerOwners:{type:"boolean"}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...ie,minItems:1},exclude:ie,intentPrefixes:ie,description:{type:"string",minLength:1},trustBoundary:{type:"string",enum:[...Ei]},owners:{...ie,minItems:1},forbiddenGlobals:ie,capabilities:{type:"object",additionalProperties:!1,properties:{deny:{type:"array",uniqueItems:!0,items:{type:"string",enum:["network","filesystem","clock","randomness","environment","process","persistence"]}}}},pure:{type:"boolean"},mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"},reserved:{type:"boolean"},allowEmpty:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...ie,minItems:1},sharedRoots:{...ie,minItems:1},allowedCrossSlice:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}},coverage:{type:"object",additionalProperties:!1,description:"Invariant coverage scan controls. testGlobs replaces the built-in test-name heuristic; maxFiles raises or lowers the evidence file budget and also bounds structural-hint preload for orchestration-only, thin-adapter, and writes-via-aggregate (default 400; there is no arkrules.hintBudget); coverageRoots declares where the project runs its tests, so a covering test found outside them is reported instead of silently certifying an invariant. When any invariant is enforced, missing coverageRoots fails closed.",properties:{testGlobs:{...ie,minItems:1},maxFiles:{type:"integer",minimum:1,description:"Evidence file budget (default 400) and structural-hint preload cap for orchestration-only, thin-adapter, and writes-via-aggregate. Raise this when hinted/governed counts show truncated sensors. There is no separate arkrules.hintBudget."},coverageRoots:{...ie,minItems:1}}},arkRun:Rs,arkOrder:ks}},ke=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
4
|
`)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function Ns(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(Ns,"isObject");function Kt(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}i(Kt,"propertyPath");function ze(e){return e===null?"null":Array.isArray(e)?"array":typeof e}i(ze,"valueType");function Ci(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}i(Ci,"resolveSchemaRef");function ut(e,t,n,r,o){if(t.$ref){let s=Ci(t.$ref,r);if(!s){o.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}ut(e,s,n,r,o);return}if(t.const!==void 0&&!Object.is(e,t.const)){o.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(s=>Object.is(s,e))){o.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!Ns(e)){o.push({path:n,message:`must be an object; received ${ze(e)}`});return}let s=t.properties??{};for(let a of t.required??[])e[a]===void 0&&o.push({path:Kt(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in s||o.push({path:Kt(n,a),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let a=t.additionalProperties;for(let c of Object.keys(e))c in s||ut(e[c],a,Kt(n,c),r,o)}for(let[a,c]of Object.entries(s))e[a]!==void 0&&ut(e[a],c,Kt(n,a),r,o);return}if(t.type==="array"){if(!Array.isArray(e)){o.push({path:n,message:`must be an array; received ${ze(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&o.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let s=e.map(a=>JSON.stringify(a));new Set(s).size!==s.length&&o.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((s,a)=>ut(s,t.items,`${n}[${a}]`,r,o));return}if(t.type==="string"){if(typeof e!="string"){o.push({path:n,message:`must be a string; received ${ze(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&o.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&o.push({path:n,message:`must be a boolean; received ${ze(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){o.push({path:n,message:`must be an integer; received ${ze(e)}`});return}t.minimum!==void 0&&e<t.minimum&&o.push({path:n,message:`must be at least ${t.minimum}`})}}i(ut,"validateNode");function _i(e,t){let n=e.layers;Array.isArray(n)&&n.forEach((r,o)=>{if(!r||typeof r!="object"||Array.isArray(r)||!("owners"in r))return;let s=r.owners;Array.isArray(s)&&s.forEach((a,c)=>{typeof a=="string"&&(_s(a)||t.push({path:`$.layers[${o}].owners[${c}]`,message:"must be a GitHub handle or email (not a display name)"}))})})}i(_i,"validateLayerOwners");function Oi(e){let t={...e,$schema:e.$schema===void 0?Vt:e.$schema,schemaVersion:e.schemaVersion===void 0?le:e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?Ut.map(n=>({...n})):e.rules};return e.arkRun!==void 0&&(t.arkRun=Ss(e.arkRun)),e.arkOrder!==void 0&&(t.arkOrder=Is(e.arkOrder)),t}i(Oi,"defaultedConfig");function xi(e){return e===le?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}i(xi,"migratedFromOf");function Ti(){let e=new Set([le]);for(let t of jn)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}i(Ti,"knownInputVersions");function Ni(e,t="ark.config.json"){if(!Ns(e))throw new ke(t,[{path:"$",message:`must be an object; received ${ze(e)}`}]);let n=Ti(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new ke(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected ${le}`}]);if(r!=="unversioned"&&!n.has(r))throw new ke(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${le}`}]);let o=r,s={...e},a=0;for(;o!==le&&a<jn.length+1;){a+=1;let c=jn.find(l=>l.from===o);if(!c)throw new ke(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(o)}; expected ${le}`}]);o=c.to,s.schemaVersion=o}if(o!==le)throw new ke(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${le}`}]);return{candidate:Oi(s),migratedFrom:xi(r)}}i(Ni,"migrateArkConfig");function Gt(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=Ni(e,t),o=[];if(ut(n,Kn,"$",Kn,o),bs(n,o),vs(n,o),_i(n,o),o.length>0)throw new ke(t,o);return{config:n,migratedFrom:r}}i(Gt,"loadArkConfigContract");function Vn(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new ke(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return Gt(n,t)}i(Vn,"parseArkConfigJson");function ws(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:Vt,schemaVersion:le};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}i(ws,"withArkConfigMetadata");function wi(e){return e.endsWith(".")?e:`${e}.`}i(wi,"normalizePrefix");function Pi(e,t){let n=e.prefixes.length?Math.max(...e.prefixes.map(o=>o.length)):0;return(t.prefixes.length?Math.max(...t.prefixes.map(o=>o.length)):0)-n}i(Pi,"byLongestPrefix");function zt(e){let t=e.layers.map(o=>({...o,prefixes:o.prefixes.map(wi)})),n=[...t].sort(Pi),r=[...e.rules??[]];return{name:e.name,layers:t,rules:r,resolveLayer(o){return t.find(s=>s.match?.(o))?.name??n.find(s=>s.prefixes.some(a=>o.startsWith(a)))?.name}}}i(zt,"createArchitectureProfile");function Ps(e,t={}){return zt({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,r)=>({name:n.name,prefixes:n.intentPrefixes??[],description:n.description,trustBoundary:n.trustBoundary,owners:n.owners,order:r+1})),rules:e.rules??[]})}i(Ps,"createArchitectureProfileFromArkConfig");var Li=[{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}],Bt=zt({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:Li,rules:Ut.map(e=>({...e}))}),Di={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 Ls(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return ws({include:e.include??[t],layers:Bt.layers.map(o=>({name:o.name,patterns:(Di[o.name]??[o.name]).map(s=>`${r}${s}/**`),intentPrefixes:o.prefixes,optional:n})),rules:[...Bt.rules]})}i(Ls,"createElevenLayerArkConfig");function X(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}i(X,"deterministicHash");function H(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(H).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${H(t[n])}`).join(",")}}`}i(H,"stableSerialize");var Pe="1.2";var Ds=["network","filesystem","clock","randomness","environment","process","persistence"];function q(e,t){let n=H(e),r=H(t);return n<r?-1:n>r?1:0}i(q,"compareCanonical");function Z(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}i(Z,"sortedUnique");function pt(e){let t={schemaVersion:"1.2",include:Z(e.include??[]),exclude:Z(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:Z(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:Z(n.patterns??[]),exclude:Z(n.exclude??[]),forbiddenGlobals:Z(n.forbiddenGlobals??[]),intentPrefixes:Z(n.intentPrefixes??[]),capabilityDeny:Z(n.capabilities?.deny??[]),pure:n.pure===!0})).sort(q),safety:{maxTsSuppressions:e.safety?.maxTsSuppressions??0,maxAnyCasts:e.safety?.maxAnyCasts??0,allowInMemory:e.safety?.allowInMemory===!0,allowDisabledPeerIsolation:e.safety?.allowDisabledPeerIsolation===!0},...e.arkRun?{arkRun:{mode:e.arkRun.mode,compositionRoots:Z(e.arkRun.compositionRoots),managedLayers:Z(e.arkRun.managedLayers),requireDeclarations:e.arkRun.requireDeclarations===!0}}:{}};return X(H(t))}i(pt,"resolvedFactsEvidenceRequirementsHash");function Mi(e){let t=e.completenessReasons.map(E=>({code:E.code,message:E.message,...E.file?{file:E.file}:{}})).sort(q),n=e.files.map(E=>({...E,typeOnlyExportNames:Z(E.typeOnlyExportNames)})).sort((E,P)=>E.path<P.path?-1:E.path>P.path?1:0),r=e.dependencies.map(E=>({...E,...E.namedBindings?{namedBindings:Z(E.namedBindings)}:{}})).sort(q),o=e.capabilityUses.map(E=>({...E})).sort(q),s=e.ambientUses.map(E=>({...E})).sort(q),a=e.publishCalls.map(E=>({...E})).sort(q),c=e.intentReferences.map(E=>({...E})).sort(q),l=e.safetyUses.map(E=>({...E})).sort(q),u=(e.classShapes??[]).map(E=>({...E,mutatingMethods:[...E.mutatingMethods??[]].map(P=>({...P}))})).sort(q),p=(e.arkRunKernelCalls??[]).map(E=>({...E})).sort(q),g=(e.arkRunManagedNews??[]).map(E=>({...E})).sort(q),f=(e.arkRunCompositionRootHits??[]).map(E=>({...E})).sort(q),m=(e.arkRunDeclarations??[]).map(E=>({...E,uses:Z(E.uses),reactsTo:Z(E.reactsTo),raises:Z(E.raises),sends:Z(E.sends)})).sort(q),d=(e.arkOrderPlaneCalls??[]).map(E=>({...E})).sort(q),A=(e.arkOrderGenericUpdates??[]).map(E=>({...E})).sort(q),b=(e.arkOrderRootHits??[]).map(E=>({...E})).sort(q),O=(e.arkOrderXiFieldWrites??[]).map(E=>({...E})).sort(q),k=(e.arkOrderIngestWritesXi??[]).map(E=>({...E})).sort(q),I=(e.arkOrderReleaseKeyCounts??[]).map(E=>({...E})).sort(q),C=e.files.map(({path:E,contentHash:P})=>({path:E,contentHash:P})).sort((E,P)=>E.path<P.path?-1:E.path>P.path?1:0),L=X(H(C));return{schemaVersion:"1.2",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:L,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:r,capabilityUses:o,ambientUses:s,publishCalls:a,intentReferences:c,safetyUses:l,classShapes:u,arkRunKernelCalls:p,arkRunManagedNews:g,arkRunCompositionRootHits:f,arkRunDeclarations:m,arkOrderPlaneCalls:d,arkOrderGenericUpdates:A,arkOrderRootHits:b,arkOrderXiFieldWrites:O,arkOrderIngestWritesXi:k,arkOrderReleaseKeyCounts:I}}i(Mi,"canonicalResolvedFactsInput");function Ms(e){let t=Mi(e);return{...t,factsHash:X(H(t))}}i(Ms,"createCanonicalResolvedCandidateFacts");function Un(e){return Ms($s($(e,"$"),!1))}i(Un,"createResolvedCandidateFacts");function $(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}i($,"asRecord");function j(e,t,n){let r=new Set(t),o=Object.keys(e).find(s=>!r.has(s));if(o)throw new Error(`${n}.${o} is not part of schema ${"1.2"}.`)}i(j,"assertOnlyKeys");function F(e,t,n){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`${n}.${t} must be a non-empty string.`);return r}i(F,"requiredText");function Ee(e,t,n){if(e[t]!==void 0)return F(e,t,n)}i(Ee,"optionalText");function U(e,t,n){let r=F(e,t,n),o=r.replace(/\\/g,"/");if(!o||o.startsWith("/")||/^[A-Za-z]:\//.test(o)||/[\u0000-\u001f\u007f]/.test(o))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let s=[];for(let c of o.split("/"))if(!(!c||c==="."))if(c===".."){if(s.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);s.pop()}else s.push(c);let a=s.join("/");if(!a||a!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return a}i(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 Fs(e,t,n){let r=e[t];if(!Number.isInteger(r)||Number(r)<0)throw new Error(`${n}.${t} must be a non-negative integer.`);return Number(r)}i(Fs,"requiredInteger");function te(e,t,n){let r=Fs(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}i(te,"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 Se(e,t,n,r){let o=e[t];if(typeof o!="string"||!n.includes(o))throw new Error(`${r}.${t} must be one of ${n.join(", ")}.`);return o}i(Se,"enumValue");function We(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!n))throw new Error(`${t} must be an array of non-empty strings.`);return[...e]}i(We,"parseStringArray");function Fi(e,t,n){let r=new Set;for(let o of e){let s=t(o);if(r.has(s))throw new Error(`${n} must not contain duplicate facts (${s}).`);r.add(s)}}i(Fi,"assertUnique");function $s(e,t){j(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","classShapes","arkRunKernelCalls","arkRunManagedNews","arkRunCompositionRootHits","arkRunDeclarations","arkOrderPlaneCalls","arkOrderGenericUpdates","arkOrderRootHits","arkOrderXiFieldWrites","arkOrderIngestWritesXi","arkOrderReleaseKeyCounts",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=Se(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=Se(e,"completeness",["complete","partial","unavailable"],"$"),o=B(e,"completenessReasons","$").map((v,_)=>{let y=`$.completenessReasons[${_}]`,R=$(v,y);j(R,["code","message","file"],y);let M=R.file===void 0?void 0:U(R,"file",y);return{code:F(R,"code",y),message:F(R,"message",y),...M?{file:M}:{}}});if(r==="complete"&&o.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(r!=="complete"&&o.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let s=B(e,"files","$").map((v,_)=>{let y=`$.files[${_}]`,R=$(v,y);return j(R,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],y),{path:U(R,"path",y),contentHash:F(R,"contentHash",y),parseStatus:Se(R,"parseStatus",["parsed","invalid"],y),parseDiagnosticCount:Fs(R,"parseDiagnosticCount",y),exportsOnlyTypes:G(R,"exportsOnlyTypes",y),typeOnlyExportNames:We(R.typeOnlyExportNames,`${y}.typeOnlyExportNames`),hasTopLevelSideEffects:G(R,"hasTopLevelSideEffects",y)}}),a=B(e,"dependencies","$").map((v,_)=>{let y=`$.dependencies[${_}]`,R=$(v,y);j(R,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],y);let M=Ee(R,"specifier",y),Y=Ee(R,"target",y),ve=Se(R,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],y);if(ve==="resolved-project"&&!Y)throw new Error(`${y}.target is required for resolved-project dependencies.`);if(ve!=="resolved-project"&&Y)throw new Error(`${y}.target is only allowed for resolved-project dependencies.`);if(ve!=="dynamic"&&!M)throw new Error(`${y}.specifier is required unless resolution is dynamic.`);return{from:U(R,"from",y),...M?{specifier:M}:{},kind:Se(R,"kind",["import","export","dynamic-import","require"],y),typeOnly:G(R,"typeOnly",y),line:te(R,"line",y),resolution:ve,...Y?{target:U(R,"target",y)}:{},...R.namedBindings!==void 0?{namedBindings:We(R.namedBindings,`${y}.namedBindings`)}:{},...R.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:G(R,"targetTypeOnlyExports",y)}:{},...R.sourcePureTypeModule!==void 0?{sourcePureTypeModule:G(R,"sourcePureTypeModule",y)}:{},...R.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:G(R,"namedBindingsTypeOnly",y)}:{},...R.portProofEligible!==void 0?{portProofEligible:G(R,"portProofEligible",y)}:{}}}),c=B(e,"capabilityUses","$").map((v,_)=>{let y=`$.capabilityUses[${_}]`,R=$(v,y);return j(R,["file","line","symbol","capability","source"],y),{file:U(R,"file",y),line:te(R,"line",y),symbol:F(R,"symbol",y),capability:Se(R,"capability",Ds,y),source:Se(R,"source",["ambient-global","import-based"],y)}}),l=B(e,"ambientUses","$").map((v,_)=>{let y=`$.ambientUses[${_}]`,R=$(v,y);return j(R,["file","line","symbol"],y),{file:U(R,"file",y),line:te(R,"line",y),symbol:F(R,"symbol",y)}}),u=B(e,"publishCalls","$").map((v,_)=>{let y=`$.publishCalls[${_}]`,R=$(v,y);j(R,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],y);let M=Ee(R,"rawIntentName",y),Y=Ee(R,"sourceIntent",y);return{file:U(R,"file",y),line:te(R,"line",y),...M?{rawIntentName:M}:{},objectHasIntent:G(R,"objectHasIntent",y),arkPublishCandidate:G(R,"arkPublishCandidate",y),hasSource:G(R,"hasSource",y),...Y?{sourceIntent:Y}:{}}}),p=B(e,"intentReferences","$").map((v,_)=>{let y=`$.intentReferences[${_}]`,R=$(v,y);return j(R,["file","line","intent"],y),{file:U(R,"file",y),line:te(R,"line",y),intent:F(R,"intent",y)}}),g=B(e,"safetyUses","$").map((v,_)=>{let y=`$.safetyUses[${_}]`,R=$(v,y);j(R,["file","line","kind","symbol"],y);let M=Ee(R,"symbol",y),Y=Se(R,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],y);if(Y==="in-memory-store"&&!M)throw new Error(`${y}.symbol is required for in-memory-store facts.`);if(Y!=="in-memory-store"&&M)throw new Error(`${y}.symbol is only allowed for in-memory-store facts.`);return{file:U(R,"file",y),line:te(R,"line",y),kind:Y,...M?{symbol:M}:{}}});Fi(s,v=>v.path,"$.files");let f=new Set(s.map(v=>v.path));for(let v of s){if(v.parseStatus==="parsed"&&v.parseDiagnosticCount!==0)throw new Error(`$.files[${v.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(v.parseStatus==="invalid"&&v.parseDiagnosticCount===0)throw new Error(`$.files[${v.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&s.some(v=>v.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let v of a)if(!f.has(v.from))throw new Error(`$.dependencies references missing source file ${v.from}.`);let d=(e.arkRunKernelCalls===void 0?[]:B(e,"arkRunKernelCalls","$")).map((v,_)=>{let y=`$.arkRunKernelCalls[${_}]`,R=$(v,y);j(R,["file","line","kind","callee","viaImport","receiver","nameLiteral"],y);let M=Ee(R,"receiver",y),Y=Ee(R,"nameLiteral",y);return{file:U(R,"file",y),line:te(R,"line",y),kind:Se(R,"kind",["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"],y),callee:F(R,"callee",y),viaImport:G(R,"viaImport",y),...M?{receiver:M}:{},...Y?{nameLiteral:Y}:{}}}),b=(e.arkRunManagedNews===void 0?[]:B(e,"arkRunManagedNews","$")).map((v,_)=>{let y=`$.arkRunManagedNews[${_}]`,R=$(v,y);j(R,["file","line","typeName","importedFrom"],y);let M=Ee(R,"importedFrom",y);return{file:U(R,"file",y),line:te(R,"line",y),typeName:F(R,"typeName",y),...M?{importedFrom:M}:{}}}),k=(e.arkRunCompositionRootHits===void 0?[]:B(e,"arkRunCompositionRootHits","$")).map((v,_)=>{let y=`$.arkRunCompositionRootHits[${_}]`,R=$(v,y);return j(R,["file","matchedRoot","hasKernelFactory"],y),{file:U(R,"file",y),matchedRoot:F(R,"matchedRoot",y),hasKernelFactory:G(R,"hasKernelFactory",y)}}),I=e.arkRunDeclarations===void 0?[]:B(e,"arkRunDeclarations","$"),L=(e.arkOrderPlaneCalls===void 0?[]:B(e,"arkOrderPlaneCalls","$")).map((v,_)=>{let y=`$.arkOrderPlaneCalls[${_}]`,R=$(v,y);return j(R,["file","line","callee"],y),{file:U(R,"file",y),line:te(R,"line",y),callee:F(R,"callee",y)}}),P=(e.arkOrderGenericUpdates===void 0?[]:B(e,"arkOrderGenericUpdates","$")).map((v,_)=>{let y=`$.arkOrderGenericUpdates[${_}]`,R=$(v,y);return j(R,["file","line","method"],y),{file:U(R,"file",y),line:te(R,"line",y),method:F(R,"method",y)}}),T=(e.arkOrderRootHits===void 0?[]:B(e,"arkOrderRootHits","$")).map((v,_)=>{let y=`$.arkOrderRootHits[${_}]`,R=$(v,y);return j(R,["file","matchedRoot","hasPlaneFactory"],y),{file:U(R,"file",y),matchedRoot:F(R,"matchedRoot",y),hasPlaneFactory:G(R,"hasPlaneFactory",y)}}),D=(e.arkOrderXiFieldWrites===void 0?[]:B(e,"arkOrderXiFieldWrites","$")).map((v,_)=>{let y=`$.arkOrderXiFieldWrites[${_}]`,R=$(v,y);return j(R,["file","line","key"],y),{file:U(R,"file",y),line:te(R,"line",y),key:F(R,"key",y)}}),J=(e.arkOrderIngestWritesXi===void 0?[]:B(e,"arkOrderIngestWritesXi","$")).map((v,_)=>{let y=`$.arkOrderIngestWritesXi[${_}]`,R=$(v,y);return j(R,["file","line"],y),{file:U(R,"file",y),line:te(R,"line",y)}}),Ae=(e.arkOrderReleaseKeyCounts===void 0?[]:B(e,"arkOrderReleaseKeyCounts","$")).map((v,_)=>{let y=`$.arkOrderReleaseKeyCounts[${_}]`,R=$(v,y);return j(R,["file","line","keyCount"],y),{file:U(R,"file",y),line:te(R,"line",y),keyCount:te(R,"keyCount",y)}}),Qe=I.map((v,_)=>{let y=`$.arkRunDeclarations[${_}]`,R=$(v,y);return j(R,["file","line","uses","reactsTo","raises","sends"],y),{file:U(R,"file",y),line:te(R,"line",y),uses:We(R.uses,`${y}.uses`),reactsTo:We(R.reactsTo,`${y}.reactsTo`),raises:We(R.raises,`${y}.raises`),sends:We(R.sends,`${y}.sends`)}});for(let[v,_]of[["$.capabilityUses",c],["$.ambientUses",l],["$.publishCalls",u],["$.intentReferences",p],["$.safetyUses",g],["$.arkRunKernelCalls",d],["$.arkRunManagedNews",b],["$.arkRunCompositionRootHits",k],["$.arkRunDeclarations",Qe],["$.arkOrderPlaneCalls",L],["$.arkOrderGenericUpdates",P],["$.arkOrderRootHits",T],["$.arkOrderXiFieldWrites",D],["$.arkOrderIngestWritesXi",J],["$.arkOrderReleaseKeyCounts",Ae]])for(let y of _)if(!f.has(y.file))throw new Error(`${v} references missing file ${y.file}.`);let Tt=Ee(e,"projectPackageName","$"),Zr=(e.classShapes===void 0?[]:B(e,"classShapes","$")).map((v,_)=>{let y=`$.classShapes[${_}]`,R=$(v,y);j(R,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],y);let M=B(R,"mutatingMethods",y).map((Y,ve)=>{let h=`${y}.mutatingMethods[${ve}]`,oe=$(Y,h);return j(oe,["name","referencesGuardOrPublish"],h),{name:F(oe,"name",h),referencesGuardOrPublish:G(oe,"referencesGuardOrPublish",h)}});return{file:U(R,"file",y),className:F(R,"className",y),exported:G(R,"exported",y),hasPublicMutableFields:G(R,"hasPublicMutableFields",y),hasPublicSetters:G(R,"hasPublicSetters",y),hasPublicConstructor:G(R,"hasPublicConstructor",y),hasStaticFactory:G(R,"hasStaticFactory",y),mutatingMethods:M,...R.dataOnly===void 0?{}:{dataOnly:G(R,"dataOnly",y)}}});return{schemaVersion:n,completeness:r,completenessReasons:o,resolverIdentity:F(e,"resolverIdentity","$"),compilerIdentity:F(e,"compilerIdentity","$"),compilerOptionsHash:F(e,"compilerOptionsHash","$"),tsconfigHash:F(e,"tsconfigHash","$"),evidenceRequirementsHash:F(e,"evidenceRequirementsHash","$"),...Tt?{projectPackageName:Tt}:{},files:s,dependencies:a,capabilityUses:c,ambientUses:l,publishCalls:u,intentReferences:p,safetyUses:g,classShapes:Zr,arkRunKernelCalls:d,arkRunManagedNews:b,arkRunCompositionRootHits:k,arkRunDeclarations:Qe,arkOrderPlaneCalls:L,arkOrderGenericUpdates:P,arkOrderRootHits:T,arkOrderXiFieldWrites:D,arkOrderIngestWritesXi:J,arkOrderReleaseKeyCounts:Ae}}i($s,"parseResolvedFactsInput");function _e(e){let t=$(e,"$"),n=F(t,"factsHash","$"),r=F(t,"candidateTreeHash","$"),o=Ms($s(t,!0));if(o.factsHash!==n)throw new Error(`$.factsHash does not match the canonical payload (${o.factsHash}).`);if(r!==o.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${o.candidateTreeHash}).`);return o}i(_e,"loadResolvedCandidateFacts");var $i=["network","filesystem","clock","randomness","environment","process","persistence"],N={type:"string",minLength:1},ae={type:"integer",minimum:1},z={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},Gn={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.resolved-candidate-facts.schema.json",title:"ArkGate resolved candidate facts",type:"object",additionalProperties:!1,required:["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","candidateTreeHash","evidenceRequirementsHash","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","factsHash"],properties:{schemaVersion:{enum:["1.0","1.1","1.2"]},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:N,message:N,file:z}}},resolverIdentity:N,compilerIdentity:N,compilerOptionsHash:N,tsconfigHash:N,candidateTreeHash:N,evidenceRequirementsHash:N,projectPackageName:N,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:z,contentHash:N,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:N},hasTopLevelSideEffects:{type:"boolean"}},allOf:[{if:{properties:{parseStatus:{const:"parsed"}}},then:{properties:{parseDiagnosticCount:{const:0}}}},{if:{properties:{parseStatus:{const:"invalid"}}},then:{properties:{parseDiagnosticCount:{minimum:1}}}}]}},dependencies:{type:"array",items:{type:"object",additionalProperties:!1,required:["from","kind","typeOnly","line","resolution"],properties:{from:z,specifier:N,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:ae,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:z,namedBindings:{type:"array",items:N},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"}},allOf:[{if:{properties:{resolution:{const:"resolved-project"}}},then:{required:["target"]},else:{not:{required:["target"]}}},{if:{properties:{resolution:{const:"dynamic"}}},else:{required:["specifier"]}}]}},capabilityUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol","capability","source"],properties:{file:z,line:ae,symbol:N,capability:{enum:$i},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:z,line:ae,symbol:N}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:z,line:ae,rawIntentName:N,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:N}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:z,line:ae,intent:N}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:z,line:ae,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:N},allOf:[{if:{properties:{kind:{const:"in-memory-store"}}},then:{required:["symbol"]},else:{not:{required:["symbol"]}}}]}},classShapes:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods"],properties:{file:z,className:N,exported:{type:"boolean"},hasPublicMutableFields:{type:"boolean"},hasPublicSetters:{type:"boolean"},hasPublicConstructor:{type:"boolean"},hasStaticFactory:{type:"boolean"},dataOnly:{type:"boolean"},mutatingMethods:{type:"array",items:{type:"object",additionalProperties:!1,required:["name","referencesGuardOrPublish"],properties:{name:N,referencesGuardOrPublish:{type:"boolean"}}}}}}},arkRunKernelCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind","callee","viaImport"],properties:{file:z,line:ae,kind:{enum:["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"]},callee:N,viaImport:{type:"boolean"},receiver:N,nameLiteral:N}}},arkRunManagedNews:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","typeName"],properties:{file:z,line:ae,typeName:N,importedFrom:N}}},arkRunCompositionRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasKernelFactory"],properties:{file:z,matchedRoot:N,hasKernelFactory:{type:"boolean"}}}},arkRunDeclarations:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","uses","reactsTo","raises","sends"],properties:{file:z,line:ae,uses:{type:"array",items:N},reactsTo:{type:"array",items:N},raises:{type:"array",items:N},sends:{type:"array",items:N}}}},arkOrderPlaneCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","callee"],properties:{file:z,line:ae,callee:N}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:z,line:ae,method:N}}},arkOrderRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasPlaneFactory"],properties:{file:z,matchedRoot:N,hasPlaneFactory:{type:"boolean"}}}},arkOrderXiFieldWrites:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:z,line:ae,key:N}}},arkOrderIngestWritesXi:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line"],properties:{file:z,line:ae}}},arkOrderReleaseKeyCounts:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","keyCount"],properties:{file:z,line:ae,keyCount:{type:"integer",minimum:1}}}},factsHash:N},allOf:[{if:{properties:{completeness:{const:"complete"}}},then:{properties:{completenessReasons:{maxItems:0},files:{items:{properties:{parseStatus:{const:"parsed"}}}}}}},{if:{properties:{completeness:{enum:["partial","unavailable"]}}},then:{properties:{completenessReasons:{minItems:1}}}}]};var Bn="1.0";function ce(e){return`${e.from}->${e.to}`}i(ce,"dependencyKey");function ft(e,t,n,r="dependency"){return{id:`${e}:${r}:${ce(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${ce(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${ce(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${ce(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${ce(t)} from the candidate, then preflight again.`}:{}}}i(ft,"dependencyFinding");function qe(e){let t=[],n=new Map(e.changeMap.map.files.map(f=>[f.path,f])),r=new Map(e.changes.map(f=>[f.path,f])),o=new Map(e.changeMap.map.dependencies.map(f=>[ce(f),f])),s=new Map(e.baseDependencies.map(f=>[ce(f),f])),a=new Map(e.candidateDependencies.map(f=>[ce(f),f]));for(let f of[...n.values()].sort((m,d)=>m.path.localeCompare(d.path))){let m=r.get(f.path);m?m.operation!==f.operation?t.push({id:`contradictory:file:${f.path}`,classification:"contradictory",subject:"file",path:f.path,expectedOperation:f.operation,actualOperation:m.operation,message:`${f.path} was planned as ${f.operation} but the actual operation is ${m.operation}.`,nextAction:`Change ${f.path} to the planned ${f.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${f.path}`,classification:"satisfied",subject:"file",path:f.path,expectedOperation:f.operation,actualOperation:m.operation,message:`${f.path} matches the planned ${f.operation} operation.`}):t.push({id:`missing:file:${f.path}`,classification:"missing",subject:"file",path:f.path,expectedOperation:f.operation,message:`${f.path} was planned as ${f.operation} but is absent from the actual change.`,nextAction:`${f.operation[0].toUpperCase()}${f.operation.slice(1)} ${f.path} in the complete change set, then preflight again.`})}for(let f of[...r.values()].sort((m,d)=>m.path.localeCompare(d.path)))n.has(f.path)||t.push({id:`unplanned:file:${f.path}`,classification:"unplanned",subject:"file",path:f.path,actualOperation:f.operation,message:`${f.path} has an unplanned ${f.operation} operation.`,nextAction:`Remove ${f.path} from the change set, then preflight again.`});let c=new Set;for(let f of[...o.values()].sort((m,d)=>ce(m).localeCompare(ce(d)))){if(a.has(ce(f))){t.push(ft("satisfied",f,`${f.from} -> ${f.to} exists in the candidate architecture.`));continue}let m={from:f.to,to:f.from};a.has(ce(m))?(c.add(ce(m)),t.push(ft("contradictory",f,`${f.from} -> ${f.to} was planned, but the candidate contains the reverse edge.`))):t.push(ft("missing",f,`${f.from} -> ${f.to} is absent from the candidate architecture.`))}let l=new Set([...n.keys(),...r.keys()]);for(let[f,m]of[...a].sort(([d],[A])=>d.localeCompare(A)))s.has(f)||o.has(f)||c.has(f)||!l.has(m.from)&&!l.has(m.to)||t.push({...ft("unplanned",m,`${m.from} -> ${m.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let u=new Set(e.changeMap.map.files.filter(f=>f.operation==="delete").map(f=>f.path));for(let[f,m]of[...s].sort(([d],[A])=>d.localeCompare(A)))a.has(f)||u.has(m.from)||u.has(m.to)||!l.has(m.from)&&!l.has(m.to)||t.push({...ft("unplanned",m,`${m.from} -> ${m.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let p={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((f,m)=>p[f.classification]-p[m.classification]||(f.subject===m.subject?0:f.subject==="file"?-1:1)||f.id.localeCompare(m.id));let g={satisfied:t.filter(f=>f.classification==="satisfied").length,missing:t.filter(f=>f.classification==="missing").length,contradictory:t.filter(f=>f.classification==="contradictory").length,unplanned:t.filter(f=>f.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:g.missing===0&&g.contradictory===0&&g.unplanned===0,behavioralCompletion:"not-evaluated",summary:g,findings:t}}i(qe,"analyzeArchitectureConvergence");var Hi="1.0",zn="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",Ks=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","writes-via-aggregate","no-anemic-model","invariant-coverage"],ji=["no-anemic-model"],Hs={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Wn={$schema:"https://json-schema.org/draft/2020-12/schema",$id:zn,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:zn},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:[...Ks]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:Hs,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:Hs}}}},Le=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
6
|
`)}`),this.name="ArkRulesValidationError",this.source=t,this.issues=n}};function yt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(yt,"isObject");function Wt(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}i(Wt,"propertyPath");function mt(e){return e===null?"null":Array.isArray(e)?"array":typeof e}i(mt,"valueType");function Ki(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}i(Ki,"resolveSchemaRef");function gt(e,t,n,r,o){if(t.$ref){let s=Ki(t.$ref,r);if(!s){o.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}gt(e,s,n,r,o);return}if(t.const!==void 0&&!Object.is(e,t.const)){o.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(s=>Object.is(s,e))){o.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!yt(e)){o.push({path:n,message:`must be an object; received ${mt(e)}`});return}let s=t.properties??{};for(let a of t.required??[])e[a]===void 0&&o.push({path:Wt(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in s||o.push({path:Wt(n,a),message:"unknown field"});else if(yt(t.additionalProperties)){let a=t.additionalProperties;for(let c of Object.keys(e))c in s||gt(e[c],a,Wt(n,c),r,o)}for(let[a,c]of Object.entries(s))e[a]!==void 0&>(e[a],c,Wt(n,a),r,o);return}if(t.type==="array"){if(!Array.isArray(e)){o.push({path:n,message:`must be an array; received ${mt(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&o.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let s=e.map(a=>JSON.stringify(a));new Set(s).size!==s.length&&o.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((s,a)=>gt(s,t.items,`${n}[${a}]`,r,o));return}if(t.type==="string"){if(typeof e!="string"){o.push({path:n,message:`must be a string; received ${mt(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&o.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}t.type==="boolean"&&typeof e!="boolean"&&o.push({path:n,message:`must be a boolean; received ${mt(e)}`})}i(gt,"validateNode");function Vi(e){return{...e,$schema:e.$schema===void 0?zn: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(Vi,"defaultedArkRules");function js(e){return e==="enforced"?"enforced":"advisory"}i(js,"normalizeMode");function Ui(e){return ji.includes(e)}i(Ui,"isTier2Sensor");function Gi(e,t){let n=Array.isArray(e.structure)?e.structure:[],r=Array.isArray(e.invariants)?e.invariants:[],o=new Set;n.forEach((s,a)=>{if(!yt(s))return;let c=typeof s.id=="string"?s.id:"";c&&(o.has(c)&&t.push({path:`$.structure[${a}].id`,message:`duplicate rule id ${JSON.stringify(c)}`}),o.add(c)),typeof s.sensor=="string"&&Ui(s.sensor)&&s.mode==="enforced"&&t.push({path:`$.structure[${a}].mode`,message:`${c?`rule ${JSON.stringify(c)} uses sensor `:"sensor "}${JSON.stringify(s.sensor)}, which is Tier-2 advisory-only and cannot be enforced${c?" (arkgate-check --sensors lists which sensors can)":""}`}),Array.isArray(s.appliesTo)&&s.appliesTo.length===0&&t.push({path:`$.structure[${a}].appliesTo`,message:"must not be an empty array (omit the field to apply to the whole layer)"})}),r.forEach((s,a)=>{if(!yt(s))return;let c=typeof s.id=="string"?s.id:"";c&&(o.has(c)&&t.push({path:`$.invariants[${a}].id`,message:`duplicate rule id ${JSON.stringify(c)}`}),o.add(c)),Array.isArray(s.appliesTo)&&s.appliesTo.length===0&&t.push({path:`$.invariants[${a}].appliesTo`,message:"must not be an empty array (omit the field to apply to the whole layer)"})})}i(Gi,"validateSemantics");function qt(e,t="arkrules.json",n){if(!yt(e))throw new Le(t,[{path:"$",message:`must be an object; received ${mt(e)}`}]);let r=Vi(e),o=[];if(gt(r,Wn,"$",Wn,o),Gi(r,o),n!==void 0&&typeof r.layer=="string"&&r.layer!==n&&o.push({path:"$.layer",message:`must match referencing key ${JSON.stringify(n)}; received ${JSON.stringify(r.layer)}`}),o.length>0)throw new Le(t,o);return{config:r}}i(qt,"loadArkRulesContract");function Bi(e,t="arkrules.json",n){let r;try{r=JSON.parse(e)}catch(o){throw new Le(t,[{path:"$",message:`invalid JSON: ${o instanceof Error?o.message:String(o)}`}])}return qt(r,t,n)}i(Bi,"parseArkRulesJson");function qn(e){let t={},n=[],r=[],o=[...e].sort((s,a)=>s.layer.localeCompare(a.layer));for(let s of o){let a=(s.file.structure??[]).map(l=>({...l,mode:js(l.mode),provenance:{sourceFile:s.sourceFile,ruleId:l.id,layer:s.layer}})),c=(s.file.invariants??[]).map(l=>({...l,mode:js(l.mode),provenance:{sourceFile:s.sourceFile,ruleId:l.id,layer:s.layer}}));t[s.layer]={sourceFile:s.sourceFile,structure:a,invariants:c},n.push(...a),r.push(...c)}return n.sort((s,a)=>{let c=s.provenance.layer.localeCompare(a.provenance.layer);return c!==0?c:s.id.localeCompare(a.id)}),r.sort((s,a)=>{let c=s.provenance.layer.localeCompare(a.provenance.layer);return c!==0?c:s.id.localeCompare(a.id)}),{schemaVersion:"1.0",byLayer:t,structure:n,invariants:r}}i(qn,"buildEffectiveArkRules");function De(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}i(De,"emptyEffectiveArkRules");var Yt=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 Vs(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}i(Vs,"normalizeRel");function zi(e,t="ark.config.json"){let n=e.config.arkRules,r=[];if(!n||Object.keys(n).length===0){if(e.discoveredArkRulesFiles&&e.discoveredArkRulesFiles.length>0)for(let l of[...e.discoveredArkRulesFiles].sort())r.push({path:l,message:`ArkRules file ${JSON.stringify(l)} is not referenced by arkRules and will not be enforced`,severity:"advisory"});return{config:e.config,arkRules:De(),warnings:r}}let o=new Set(e.config.layers.map(l=>l.name)),s=[],a=[],c=new Set;for(let l of Object.keys(n).sort()){let u=n[l],p=`$.arkRules[${JSON.stringify(l)}]`;if(typeof u!="string"||u.length===0){s.push({path:p,message:"must be a non-empty relative path string"});continue}if(u.startsWith("/")||/^[A-Za-z]:[\\/]/.test(u)){s.push({path:p,message:"must be a project-relative path (absolute paths are not allowed)"});continue}if(!o.has(l)){s.push({path:p,message:`layer ${JSON.stringify(l)} is not declared in layers[]`});continue}let g=Vs(u);c.add(g);let f=e.fileContents[g]??e.fileContents[u];if(f===void 0){s.push({path:p,message:`referenced ArkRules file ${JSON.stringify(g)} is missing`});continue}try{let m=qt(JSON.parse(f),g,l);a.push({layer:l,sourceFile:g,file:m.config})}catch(m){if(m instanceof Le)for(let d of m.issues)s.push({path:`${p}${d.path==="$"?"":d.path.replace(/^\$/,"")}`,message:`${g}: ${d.message}`});else m instanceof SyntaxError?s.push({path:p,message:`referenced ArkRules file ${JSON.stringify(g)} is not valid JSON: ${m.message}`}):s.push({path:p,message:`referenced ArkRules file ${JSON.stringify(g)} failed to load: ${m instanceof Error?m.message:String(m)}`})}}if(e.discoveredArkRulesFiles)for(let l of[...e.discoveredArkRulesFiles].sort()){let u=Vs(l);c.has(u)||r.push({path:u,message:`ArkRules file ${JSON.stringify(u)} is not referenced by arkRules and will not be enforced`,severity:"advisory"})}if(s.length>0)throw new Yt(t,s);return{config:e.config,arkRules:qn(a),warnings:r}}i(zi,"resolveEffectiveContract");function Yn(e){return{...e,layers:e.layers.map(t=>{let{description:n,trustBoundary:r,owners:o,...s}=t;return s})}}i(Yn,"omitLayerDescriptions");function Jn(e){let{stewards:t,...n}=Yn(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(Jn,"effectiveContractPolicyPayload");var Wi="INVARIANT_TESTS_PATH_MISSING",qi="This project is adopted and has domain invariants, but ark.config.json does not name a real tests path. Add coverage.testGlobs or coverage.coverageRoots pointing at the folder where those tests live, then re-run. Without that path, coverage is an empty checkbox.",Yi="INVARIANT_COVERAGE_ROOTS_MISSING",Ji="A domain invariant is enforced, but ark.config.json does not name coverage.coverageRoots \u2014 the folders where this project's test runner actually goes. Add coverage.coverageRoots pointing at that folder, then re-run. Without it, coverage can certify a test no runner runs.";function Us(e,t=!1){if(!e)return"";let n=e.discarded,r=[];if(n.budget>0&&!t&&r.push(`${n.budget} past the ${e.maxFiles}-file budget`),n.noInvariantMention>0&&r.push(`${n.noInvariantMention} naming no catalogued invariant`),n.oversize>0&&r.push(`${n.oversize} over the per-file byte cap`),n.unreadable>0&&r.push(`${n.unreadable} unreadable (files or directories)`),n.depthLimited>0&&r.push(`${n.depthLimited} directories past the walk depth limit`),n.outOfRoot>0&&r.push(`${n.outOfRoot} symlinked outside the project root`),r.length===0)return"";let o=t?"":` (loaded ${e.filesLoaded} files, kept ${e.testFilesRetained} tests)`;return` Scan discarded ${r.join(", ")}${o}.`}i(Us,"formatCoverageDiscards");function Xi(e,t){let n=e.replace(/\\/g,"/").replace(/^\.\//,"");return t.some(r=>{let o=r.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"");return o===""||o==="."?!0:n===o||n.startsWith(`${o}/`)})}i(Xi,"isUnderCoverageRoot");function Zi(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*['"\`][^'"\`]*${n}[^'"\`]*['"\`]`,"i").test(e)||e.includes(t)}i(Zi,"titleMatchesInvariant");function Qi(e,t){if(!t)return!1;let n=t.split("."),r=n[n.length-1],o=n.length>1?n[0]:null;for(let s of Object.values(e))if(!(o&&!s.includes(o))&&(new RegExp(`(?:function\\s+|\\b)${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[(<]`).test(s)||s.includes(t)))return!0;return!1}i(Qi,"symbolPresent");function Zn(e){let t=e.arkRules.invariants??[];if(t.length===0)return{coverage:[],violations:[],partial:!1};let n=e.testFiles??[],r=e.testGlobsMissing===!0||n.length===0,o=e.coverageBudgetExhausted===!0,s=e.coverageStats,a=Us(s),c=Us(s,!0),l=s?`coverage file budget exhausted: ${s.filesLoaded} files loaded at the ${s.maxFiles}-file cap, ${s.testFilesRetained} tests retained, ${s.discarded.budget} files discarded at the cap; raise "coverage.maxFiles" in ark.config.json (the cap bounds files RETAINED as evidence${typeof s.filesRead=="number"?`; ${s.filesRead} were read`:""})`:"coverage file budget exhausted",u=(e.coverageRoots??[]).filter(d=>typeof d=="string"&&d.length>0),p=u.length>0,g=u.join(", "),f=[],m=[];for(let d of t){let A=[],b=d.coverage?.test!==!1,O=d.coverage?.symbol,k,I;if(!r&&b){let P;for(let ee of n){let T=e.fileContents[ee];if(!(!T||!Zi(T,d.id))){if(!p||Xi(ee,u)){k=ee,I=p?!1:void 0;break}P??=ee}}k===void 0&&P!==void 0&&(k=P,I=!0),k!==void 0&&A.push("test-title")}O&&Qi(e.fileContents,O)&&A.push("symbol");let L=(d.coverage?.test===!0||!!O||d.coverage===void 0)&&A.length>0||d.coverage?.test===!1&&!O?!0:A.length>0,E=r&&b&&A.length===0;if(f.push({invariantId:d.id,layer:d.provenance.layer,sourceFile:d.provenance.sourceFile,mode:d.mode,covered:L&&!E,evidence:A,partial:E,description:d.description,...k!==void 0?{testEvidenceFile:k}:{},...I!==void 0?{outsideDeclaredRoots:I}:{},coverageRootsDeclared:p}),I===!0&&k!==void 0&&m.push({ruleId:"INVARIANT_COVERAGE_OUTSIDE_ROOTS",message:`Invariant ${d.id} is covered only by ${k}, which is outside the declared coverage roots (${g}). ArkGate matches declared text and never executes tests, so it cannot tell whether that file is run: move the test under a declared root, or add its root to "coverage.coverageRoots" in ark.config.json.`,file:k,line:1,arkruleId:d.id,arkruleSource:d.provenance.sourceFile,fromLayer:d.provenance.layer,severity:"warning",failsStrict:!1}),!L||E){let P=d.mode==="enforced"&&!E,ee=r||n.length===0?"never-had-tests":"tests-disappeared";m.push({ruleId:"INVARIANT_UNCOVERED",message:(E?o?`Invariant ${d.id} coverage cannot be proven (${l}); reporting partial, not covered.`:`Invariant ${d.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered (never-had-tests).`:ee==="tests-disappeared"?`Invariant ${d.id}: no scanned test names it in a describe/it title and no declared symbol was found (tests-disappeared \u2014 a suite exists). ArkGate matches declared text; it never executes tests.`:`Invariant ${d.id}: no scanned test names it in a describe/it title and no declared symbol was found (never-had-tests \u2014 the scan found no tests at all). ArkGate matches declared text; it never executes tests.`)+(E&&o?c:a),file:d.provenance.sourceFile,line:1,arkruleId:d.id,arkruleSource:d.provenance.sourceFile,fromLayer:d.provenance.layer,severity:P?"error":"warning",failsStrict:P,kind:ee})}}return{coverage:f,violations:m,partial:f.some(d=>d.partial)}}i(Zn,"evaluateInvariantCoverage");function Qn(e){return e?e.partial?{ok:!1,reason:"Coverage is partial (missing test globs); cannot promote until evidence is complete."}:e.covered?e.outsideDeclaredRoots===!0?{ok:!1,reason:`Invariant ${e.invariantId} is covered only by ${e.testEvidenceFile??"a test"}, outside the declared coverage roots; ArkGate cannot tell whether that test runs, so it will not promote on it.`}:e.coverageRootsDeclared===!1?{ok:!1,reason:`Declare coverage.coverageRoots in ark.config.json before promoting ${e.invariantId} to enforced. Without that, ArkGate cannot tell whether a covering test is one the runner executes.`}:{ok:!0,reason:`Invariant ${e.invariantId} has coverage evidence.`}:{ok:!1,reason:`Invariant ${e.invariantId} is uncovered; add a test title or symbol before promoting to enforced.`}:{ok:!1,reason:"No coverage evidence supplied for this invariant; evaluate coverage before promoting to enforced."}}i(Qn,"canPromoteInvariant");function Xn(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!="string")continue;let r=n.trim();r.length>0&&t.push(r)}return t}i(Xn,"nonEmptyPathStrings");function el(e){return!e||typeof e!="object"?[]:[...Xn(e.testGlobs),...Xn(e.coverageRoots)]}i(el,"configuredInvariantTestsPaths");function tl(e){return el(e).length>0}i(tl,"hasConfiguredInvariantTestsPath");function er(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.coverage?.test!==!1)}i(er,"catalogDemandsInvariantTestsPath");function Gs(e){let t=e.hasDomainInvariants===!0||e.hasDomainInvariants!==!1&&er(e.invariants);return e.adopted!==!0||!t?[]:tl(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:Wi,message:qi,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]}i(Gs,"collectMissingInvariantTestsPathFindings");function nl(e){return!e||typeof e!="object"?[]:Xn(e.coverageRoots)}i(nl,"configuredCoverageRoots");function rl(e){return nl(e).length>0}i(rl,"hasConfiguredCoverageRoots");function tr(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.mode==="enforced")}i(tr,"catalogHasEnforcedInvariant");function Bs(e){return e.hasEnforcedInvariant===!0||e.hasEnforcedInvariant!==!1&&tr(e.invariants)?rl(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:Yi,message:Ji,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]:[]}i(Bs,"collectMissingCoverageRootsFindings");var sr="1.0";function w(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(w,"addFinding");function Q(e){return[...new Set(e??[])].sort()}i(Q,"sortedUnique");function me(e,t,n,r,o){let s=Q(n),a=Q(r),c=new Set(s),l=new Set(a),u=a.filter(g=>!c.has(g)),p=s.filter(g=>!l.has(g));u.length===0&&p.length===0||(u.length>0&&w(e,{kind:"added",path:t,classification:o.added,message:o.addedMessage,before:s,after:a}),p.length>0&&w(e,{kind:"removed",path:t,classification:o.removed,message:o.removedMessage,before:s,after:a}))}i(me,"compareStringSets");function ht(e,t,n,r,o,s,a){if(n===r)return;w(e,{kind:r?"enabled":"disabled",path:t,classification:r?o:o==="strengthening"?"weakening":"strengthening",message:r?s:a,before:n,after:r})}i(ht,"compareBoolean");function Jt(e,t){let n=new Map,r=new Set;for(let o of e){let s=t(o);n.has(s)?r.add(s):n.set(s,o)}return{values:n,duplicates:[...r].sort()}}i(Jt,"keyed");function sl(e,t,n){let r=Jt(t,s=>s.name),o=Jt(n,s=>s.name);(r.duplicates.length>0||o.duplicates.length>0)&&w(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:r.duplicates,after:o.duplicates});for(let s of[...new Set([...r.values.keys(),...o.values.keys()])].sort()){let a=r.values.get(s),c=o.values.get(s),l=`$.layers[${s}]`;if(!a&&c){w(e,{kind:"layer-added",path:l,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:c});continue}if(a&&!c){w(e,{kind:"layer-removed",path:l,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:a});continue}if(!a||!c)continue;me(e,`${l}.patterns`,a.patterns,c.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),me(e,`${l}.exclude`,a.exclude,c.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let u=Ft(a),p=Ft(c);me(e,`${l}.forbiddenGlobals`,u.rawGlobals,p.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),me(e,`${l}.capabilities`,u.atoms,p.atoms,{added:"strengthening",removed:"weakening",addedMessage:"Additional ambient/import protection is enforced in this layer (coverage atoms).",removedMessage:"An ambient/import protection was lost from this layer (coverage atoms)."}),Q(a.intentPrefixes).join("\0")!==Q(c.intentPrefixes).join("\0")&&w(e,{kind:"intent-prefixes-changed",path:`${l}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:Q(a.intentPrefixes),after:Q(c.intentPrefixes)}),ht(e,`${l}.mayImportInfrastructure`,a.mayImportInfrastructure===!0,c.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),ht(e,`${l}.optional`,a.optional===!0,c.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active.")}}i(sl,"compareLayers");function ol(e,t,n){let r=i(a=>`${a.from}->${a.to}`,"keyOf"),o=Jt(t,r),s=Jt(n,r);(o.duplicates.length>0||s.duplicates.length>0)&&w(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:o.duplicates,after:s.duplicates});for(let a of[...new Set([...o.values.keys(),...s.values.keys()])].sort()){let c=o.values.get(a),l=s.values.get(a),u=`$.rules[${a}]`;if(!c&&l){l.allowed===!1&&w(e,{kind:"deny-added",path:u,classification:"strengthening",message:"A denied dependency edge was added.",after:l});continue}if(c&&!l){c.allowed===!1&&w(e,{kind:"deny-removed",path:u,classification:"weakening",message:"A denied dependency edge was removed.",before:c});continue}if(!c||!l)continue;c.allowed!==l.allowed&&w(e,{kind:l.allowed?"deny-disabled":"deny-enabled",path:`${u}.allowed`,classification:l.allowed?"weakening":"strengthening",message:l.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:c.allowed,after:l.allowed});let p=c.peerIsolation===!0,g=l.peerIsolation===!0;if(p!==g){let f=c.from===c.to&&l.from===l.to;w(e,{kind:g?"peer-isolation-enabled":"peer-isolation-disabled",path:`${u}.peerIsolation`,classification:f?g?"strengthening":"weakening":"judgment-required",message:f?g?"Cross-slice dependencies inside this layer are now denied.":"Cross-slice dependencies inside this layer are no longer denied.":"Changing peer isolation on a cross-layer edge changes the denial scope.",before:p,after:g})}Q(c.sliceFolders).join("\0")!==Q(l.sliceFolders).join("\0")&&w(e,{kind:"slice-folders-changed",path:`${u}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:Q(c.sliceFolders),after:Q(l.sliceFolders)}),!(!p&&!g)&&(Ws(e,`${u}.sharedRoots`,"shared-roots",Q(c.sharedRoots),Q(l.sharedRoots),"Roots declared shared are exempt from the peerIsolation unclassifiable denial.","Roots are no longer declared shared and fall back to the peerIsolation denial."),Ws(e,`${u}.allowedCrossSlice`,"cross-slice-allowance",Q((c.allowedCrossSlice??[]).map(zs)),Q((l.allowedCrossSlice??[]).map(zs)),"Directed cross-slice edges are now allowed by declaration.","Directed cross-slice edges are no longer declared and deny again."))}}i(ol,"compareRules");function zs(e){return JSON.stringify([e.from,e.to])}i(zs,"crossSliceKey");function Ws(e,t,n,r,o,s,a){if(JSON.stringify(r)===JSON.stringify(o))return;let c=o.filter(p=>!r.includes(p)),l=r.filter(p=>!o.includes(p)),u=c.length>0&&l.length>0;w(e,{kind:u?`${n}-changed`:c.length>0?`${n}-added`:`${n}-removed`,path:t,classification:u?"judgment-required":c.length>0?"weakening":"strengthening",message:u?`${s} Entries were added and removed in the same change.`:c.length>0?s:a,before:r,after:o})}i(Ws,"compareDeclaredExceptions");function al(e,t,n){let r=t.safety??{},o=n.safety??{};for(let s of["maxTsSuppressions","maxAnyCasts"]){let a=r[s]??0,c=o[s]??0;a!==c&&w(e,{kind:c>a?"threshold-raised":"threshold-lowered",path:`$.safety.${s}`,classification:c>a?"weakening":"strengthening",message:c>a?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:a,after:c})}for(let s of["allowInMemory","allowDisabledPeerIsolation"])ht(e,`$.safety.${s}`,r[s]===!0,o[s]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}i(al,"compareSafety");function nr(e){return e.mode==="enforced"?"enforced":"advisory"}i(nr,"arkRunMode");function rr(e){return e.mode==="enforced"?"enforced":"advisory"}i(rr,"arkOrderMode");function il(e,t,n){let r=t.arkOrder,o=n.arkOrder,s="$.arkOrder";if(!r&&!o)return;if(!r&&o){w(e,{kind:"arkorder-added",path:s,classification:"strengthening",message:`ArkOrder extra was added (${rr(o)}).`,after:o});return}if(r&&!o){w(e,{kind:"arkorder-removed",path:s,classification:"weakening",message:"ArkOrder extra was removed.",before:r});return}if(!r||!o)return;let a=rr(r),c=rr(o);if(a!==c){let l=a==="advisory"&&c==="enforced";w(e,{kind:l?"arkorder-promoted":"arkorder-demoted",path:`${s}.mode`,classification:l?"strengthening":"weakening",message:l?"ArkOrder extra was promoted to enforced.":"ArkOrder extra was demoted to advisory.",before:a,after:c})}me(e,`${s}.planeRoots`,r.planeRoots,o.planeRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkOrder plane roots are governed.",removedMessage:"ArkOrder plane roots were removed and may skip the plane."}),me(e,`${s}.managedLayers`,r.managedLayers,o.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkOrder.",removedMessage:"Layers were removed from ArkOrder management."})}i(il,"compareArkOrder");function ll(e,t,n){let r=t.arkRun,o=n.arkRun,s="$.arkRun";if(!r&&!o)return;if(!r&&o){w(e,{kind:"arkrun-added",path:s,classification:"strengthening",message:`ArkRun extra was added (${nr(o)}).`,after:o});return}if(r&&!o){w(e,{kind:"arkrun-removed",path:s,classification:"weakening",message:"ArkRun extra was removed.",before:r});return}if(!r||!o)return;let a=nr(r),c=nr(o);if(a!==c){let l=a==="advisory"&&c==="enforced";w(e,{kind:l?"arkrun-promoted":"arkrun-demoted",path:`${s}.mode`,classification:l?"strengthening":"weakening",message:l?"ArkRun extra was promoted to enforced.":"ArkRun extra was demoted to advisory.",before:a,after:c})}me(e,`${s}.compositionRoots`,r.compositionRoots,o.compositionRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkRun composition roots are governed.",removedMessage:"ArkRun composition roots were removed and may skip the kernel."}),me(e,`${s}.managedLayers`,r.managedLayers,o.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkRun.",removedMessage:"Layers were removed from ArkRun management."}),ht(e,`${s}.requireDeclarations`,r.requireDeclarations!==!1,o.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}i(ll,"compareArkRun");function cl(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(cl,"overallClassification");function qs(e,t){return`${e}::${t}`}i(qs,"ruleKey");function Ys(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(qs(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(qs(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}i(Ys,"indexEffectiveRules");function dl(e,t,n,r,o,s){let a=new Map((s??[]).map(f=>[f.invariantId,f])),c=t.arkRules??{},l=n.arkRules??{},u=[...new Set([...Object.keys(c),...Object.keys(l)])].sort();for(let f of u){let m=c[f],d=l[f],A=`$.arkRules[${f}]`;if(m===void 0&&d!==void 0){w(e,{kind:"arkrules-ref-added",path:A,classification:"strengthening",message:`ArkRules reference for layer ${f} was added.`,after:d});continue}if(m!==void 0&&d===void 0){w(e,{kind:"arkrules-ref-removed",path:A,classification:"weakening",message:`ArkRules reference for layer ${f} was removed.`,before:m});continue}m!==d&&w(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:m,after:d})}let p=Ys(r),g=Ys(o);for(let f of[...new Set([...p.structure.keys(),...g.structure.keys()])].sort()){let m=p.structure.get(f),d=g.structure.get(f),A=`$.arkRules.structure[${f}]`;if(!m&&d){w(e,{kind:"arkrule-structure-added",path:A,classification:"strengthening",message:`Structure ArkRule ${d.id} was added (${d.mode}).`,after:d});continue}if(m&&!d){w(e,{kind:"arkrule-structure-removed",path:A,classification:"weakening",message:`Structure ArkRule ${m.id} was removed.`,before:m});continue}if(!(!m||!d)){if(m.mode!==d.mode){let b=m.mode==="advisory"&&d.mode==="enforced";w(e,{kind:b?"arkrule-promoted":"arkrule-demoted",path:`${A}.mode`,classification:b?"strengthening":"weakening",message:b?`Structure ArkRule ${d.id} was promoted to enforced.`:`Structure ArkRule ${d.id} was demoted to advisory.`,before:m.mode,after:d.mode})}m.sensor!==d.sensor&&w(e,{kind:"arkrule-sensor-changed",path:`${A}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${d.id} changed sensor identity.`,before:m.sensor,after:d.sensor})}}for(let f of[...new Set([...p.invariants.keys(),...g.invariants.keys()])].sort()){let m=p.invariants.get(f),d=g.invariants.get(f),A=`$.arkRules.invariants[${f}]`;if(!m&&d){w(e,{kind:"arkrule-invariant-added",path:A,classification:"strengthening",message:`Invariant ${d.id} was added (${d.mode}).`,after:d});continue}if(m&&!d){w(e,{kind:"arkrule-invariant-removed",path:A,classification:"weakening",message:`Invariant ${m.id} was removed.`,before:m});continue}if(!(!m||!d)&&m.mode!==d.mode)if(m.mode==="advisory"&&d.mode==="enforced"){let O=a?.get(d.id),k=Qn(O);k.ok?w(e,{kind:"arkrule-invariant-promoted",path:`${A}.mode`,classification:"strengthening",message:`Invariant ${d.id} was promoted to enforced (coverage evidence present).`,before:m.mode,after:d.mode}):w(e,{kind:"arkrule-invariant-promote-refused",path:`${A}.mode`,classification:"judgment-required",message:`Invariant ${d.id} cannot be promoted to enforced: ${k.reason}`,before:m.mode,after:d.mode})}else w(e,{kind:"arkrule-invariant-demoted",path:`${A}.mode`,classification:"weakening",message:`Invariant ${d.id} was demoted to advisory.`,before:m.mode,after:d.mode})}}i(dl,"compareArkRules");function or(e,t,n){let r=[];me(r,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),me(r,"$.exclude",e.exclude,t.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional project paths are excluded from governance.",removedMessage:"Fewer project paths are excluded from governance."}),me(r,"$.dynamicImportAllowlist",e.dynamicImportAllowlist,t.dynamicImportAllowlist,{added:"weakening",removed:"strengthening",addedMessage:"Additional files may use non-literal dynamic imports.",removedMessage:"Fewer files may use non-literal dynamic imports."}),ht(r,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let o={off:0,soft:1,"framework-soft":1,strict:2},s=e.cyclePolicy??"strict",a=t.cyclePolicy??"strict";if(s!==a){let c=o[a]===o[s]?"judgment-required":o[a]>o[s]?"strengthening":"weakening";w(r,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:c,message:"The cycle enforcement level changed.",before:s,after:a})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&w(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}),sl(r,e.layers,t.layers),ol(r,e.rules,t.rules),al(r,e,t),dl(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),ll(r,e,t),il(r,e,t),r.sort((c,l)=>c.path.localeCompare(l.path)||c.id.localeCompare(l.id)),{schemaVersion:sr,classification:cl(r),findings:r}}i(or,"classifyArkPolicyDelta");function ar(e,t){if(!e||e.schemaVersion!==sr||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(o=>typeof o!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=Q(e.findingIds),r=Q(t.findingIds);return n.length===r.length&&n.every((o,s)=>o===r[s])}i(ar,"policyDeltaAcknowledgementMatches");function Me(e){let t=[];for(let n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."&&t.length>0&&t.at(-1)!==".."?t.pop():t.push(n));return t.join("/")}i(Me,"normalizePath");function Js(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}i(Js,"isIdentifierStart");function Xt(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}i(Xt,"isIdentifierCharacter");function de(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}i(de,"skipWhitespace");function At(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let r=t,o="";for(t+=1;t<e.length;t+=1){let s=e[t];if(s===n)return{value:o,offset:r,excerpt:e.slice(r,t+1)};s==="\\"&&t+1<e.length?(o+=e[t+1],t+=1):o+=s}}i(At,"readString");function ue(e,t,n){return e.startsWith(t,n)&&!Xt(e[n-1])&&!Xt(e[n+t.length])}i(ue,"isWordAt");function Xs(e,t){let n=de(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=de(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!ue(e,"type",n))return!1;let o=de(e,n+4);if(o>=e.length||e[o]===","||e[o]==="}"||ue(e,"as",o)||!Js(e[o]))return!1;for(n=o;n<e.length&&Xt(e[n]);)n+=1;if(n=de(e,n),ue(e,"as",n)){if(n=de(e,n+2),!Js(e[n]))return!1;for(;n<e.length&&Xt(e[n]);)n+=1}r=!0}return!1}i(Xs,"bracedNamedBindingsAreTypeOnly");function ul(e,t){if(t=de(e,t+6),e[t]==="(")return At(e,de(e,t+1));let n=!1;if(ue(e,"type",t)){let o=de(e,t+4);e[o]!==","&&!ue(e,"from",o)&&(n=!0)}else Xs(e,t)&&(n=!0);let r=Zs(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}i(ul,"specifierAfterImport");function pl(e,t){t=t+6;let n=de(e,t),r=!1;if(ue(e,"type",n)){let s=de(e,n+4);(e[s]==="{"||e[s]==="*")&&(r=!0)}else Xs(e,n)&&(r=!0);let o=Zs(e,t,!1);return o&&r?{...o,typeOnly:!0}:o}i(pl,"specifierAfterExport");function Zs(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(ue(e,"from",t))return At(e,de(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return At(e,t);if(t>0&&(ue(e,"import",t)||ue(e,"export",t)))return}}i(Zs,"specifierInStaticStatement");function fl(e,t){for(t+=1;t<e.length;t+=1){let n=e[t];if(n==="\\")t+=1;else if(n==="`")return t}return e.length}i(fl,"skipTemplateLiteral");function ml(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=de(e,t+7);if(e[r]!=="(")return;r=de(e,r+1);let o=At(e,r);return o?{...o,requireCall:!0}:void 0}i(ml,"specifierAfterRequire");function gl(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 s=e.indexOf("*/",n+2);if(s<0)break;n=s+1;continue}if(r==="`"){n=
|
|
8
|
+
`)}`),this.name="EffectiveContractError",this.source=t,this.issues=n}};function Vs(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}i(Vs,"normalizeRel");function zi(e,t="ark.config.json"){let n=e.config.arkRules,r=[];if(!n||Object.keys(n).length===0){if(e.discoveredArkRulesFiles&&e.discoveredArkRulesFiles.length>0)for(let l of[...e.discoveredArkRulesFiles].sort())r.push({path:l,message:`ArkRules file ${JSON.stringify(l)} is not referenced by arkRules and will not be enforced`,severity:"advisory"});return{config:e.config,arkRules:De(),warnings:r}}let o=new Set(e.config.layers.map(l=>l.name)),s=[],a=[],c=new Set;for(let l of Object.keys(n).sort()){let u=n[l],p=`$.arkRules[${JSON.stringify(l)}]`;if(typeof u!="string"||u.length===0){s.push({path:p,message:"must be a non-empty relative path string"});continue}if(u.startsWith("/")||/^[A-Za-z]:[\\/]/.test(u)){s.push({path:p,message:"must be a project-relative path (absolute paths are not allowed)"});continue}if(!o.has(l)){s.push({path:p,message:`layer ${JSON.stringify(l)} is not declared in layers[]`});continue}let g=Vs(u);c.add(g);let f=e.fileContents[g]??e.fileContents[u];if(f===void 0){s.push({path:p,message:`referenced ArkRules file ${JSON.stringify(g)} is missing`});continue}try{let m=qt(JSON.parse(f),g,l);a.push({layer:l,sourceFile:g,file:m.config})}catch(m){if(m instanceof Le)for(let d of m.issues)s.push({path:`${p}${d.path==="$"?"":d.path.replace(/^\$/,"")}`,message:`${g}: ${d.message}`});else m instanceof SyntaxError?s.push({path:p,message:`referenced ArkRules file ${JSON.stringify(g)} is not valid JSON: ${m.message}`}):s.push({path:p,message:`referenced ArkRules file ${JSON.stringify(g)} failed to load: ${m instanceof Error?m.message:String(m)}`})}}if(e.discoveredArkRulesFiles)for(let l of[...e.discoveredArkRulesFiles].sort()){let u=Vs(l);c.has(u)||r.push({path:u,message:`ArkRules file ${JSON.stringify(u)} is not referenced by arkRules and will not be enforced`,severity:"advisory"})}if(s.length>0)throw new Yt(t,s);return{config:e.config,arkRules:qn(a),warnings:r}}i(zi,"resolveEffectiveContract");function Yn(e){return{...e,layers:e.layers.map(t=>{let{description:n,trustBoundary:r,owners:o,...s}=t;return s})}}i(Yn,"omitLayerDescriptions");function Jn(e){let{stewards:t,...n}=Yn(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(Jn,"effectiveContractPolicyPayload");var Wi="INVARIANT_TESTS_PATH_MISSING",qi="This project is adopted and has domain invariants, but ark.config.json does not name a real tests path. Add coverage.testGlobs or coverage.coverageRoots pointing at the folder where those tests live, then re-run. Without that path, coverage is an empty checkbox.",Yi="INVARIANT_COVERAGE_ROOTS_MISSING",Ji="A domain invariant is enforced, but ark.config.json does not name coverage.coverageRoots \u2014 the folders where this project's test runner actually goes. Add coverage.coverageRoots pointing at that folder, then re-run. Without it, coverage can certify a test no runner runs.";function Us(e,t=!1){if(!e)return"";let n=e.discarded,r=[];if(n.budget>0&&!t&&r.push(`${n.budget} past the ${e.maxFiles}-file budget`),n.noInvariantMention>0&&r.push(`${n.noInvariantMention} naming no catalogued invariant`),n.oversize>0&&r.push(`${n.oversize} over the per-file byte cap`),n.unreadable>0&&r.push(`${n.unreadable} unreadable (files or directories)`),n.depthLimited>0&&r.push(`${n.depthLimited} directories past the walk depth limit`),n.outOfRoot>0&&r.push(`${n.outOfRoot} symlinked outside the project root`),r.length===0)return"";let o=t?"":` (loaded ${e.filesLoaded} files, kept ${e.testFilesRetained} tests)`;return` Scan discarded ${r.join(", ")}${o}.`}i(Us,"formatCoverageDiscards");function Xi(e,t){let n=e.replace(/\\/g,"/").replace(/^\.\//,"");return t.some(r=>{let o=r.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"");return o===""||o==="."?!0:n===o||n.startsWith(`${o}/`)})}i(Xi,"isUnderCoverageRoot");function Zi(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*['"\`][^'"\`]*${n}[^'"\`]*['"\`]`,"i").test(e)||e.includes(t)}i(Zi,"titleMatchesInvariant");function Qi(e,t){if(!t)return!1;let n=t.split("."),r=n[n.length-1],o=n.length>1?n[0]:null;for(let s of Object.values(e))if(!(o&&!s.includes(o))&&(new RegExp(`(?:function\\s+|\\b)${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[(<]`).test(s)||s.includes(t)))return!0;return!1}i(Qi,"symbolPresent");function Zn(e){let t=e.arkRules.invariants??[];if(t.length===0)return{coverage:[],violations:[],partial:!1};let n=e.testFiles??[],r=e.testGlobsMissing===!0||n.length===0,o=e.coverageBudgetExhausted===!0,s=e.coverageStats,a=Us(s),c=Us(s,!0),l=s?`coverage file budget exhausted: ${s.filesLoaded} files loaded at the ${s.maxFiles}-file cap, ${s.testFilesRetained} tests retained, ${s.discarded.budget} files discarded at the cap; raise "coverage.maxFiles" in ark.config.json (the cap bounds files RETAINED as evidence${typeof s.filesRead=="number"?`; ${s.filesRead} were read`:""})`:"coverage file budget exhausted",u=(e.coverageRoots??[]).filter(d=>typeof d=="string"&&d.length>0),p=u.length>0,g=u.join(", "),f=[],m=[];for(let d of t){let A=[],b=d.coverage?.test!==!1,O=d.coverage?.symbol,k,I;if(!r&&b){let P;for(let ee of n){let T=e.fileContents[ee];if(!(!T||!Zi(T,d.id))){if(!p||Xi(ee,u)){k=ee,I=p?!1:void 0;break}P??=ee}}k===void 0&&P!==void 0&&(k=P,I=!0),k!==void 0&&A.push("test-title")}O&&Qi(e.fileContents,O)&&A.push("symbol");let L=(d.coverage?.test===!0||!!O||d.coverage===void 0)&&A.length>0||d.coverage?.test===!1&&!O?!0:A.length>0,E=r&&b&&A.length===0;if(f.push({invariantId:d.id,layer:d.provenance.layer,sourceFile:d.provenance.sourceFile,mode:d.mode,covered:L&&!E,evidence:A,partial:E,description:d.description,...k!==void 0?{testEvidenceFile:k}:{},...I!==void 0?{outsideDeclaredRoots:I}:{},coverageRootsDeclared:p}),I===!0&&k!==void 0&&m.push({ruleId:"INVARIANT_COVERAGE_OUTSIDE_ROOTS",message:`Invariant ${d.id} is covered only by ${k}, which is outside the declared coverage roots (${g}). ArkGate matches declared text and never executes tests, so it cannot tell whether that file is run: move the test under a declared root, or add its root to "coverage.coverageRoots" in ark.config.json.`,file:k,line:1,arkruleId:d.id,arkruleSource:d.provenance.sourceFile,fromLayer:d.provenance.layer,severity:"warning",failsStrict:!1}),!L||E){let P=d.mode==="enforced"&&!E,ee=r||n.length===0?"never-had-tests":"tests-disappeared";m.push({ruleId:"INVARIANT_UNCOVERED",message:(E?o?`Invariant ${d.id} coverage cannot be proven (${l}); reporting partial, not covered.`:`Invariant ${d.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered (never-had-tests).`:ee==="tests-disappeared"?`Invariant ${d.id}: no scanned test names it in a describe/it title and no declared symbol was found (tests-disappeared \u2014 a suite exists). ArkGate matches declared text; it never executes tests.`:`Invariant ${d.id}: no scanned test names it in a describe/it title and no declared symbol was found (never-had-tests \u2014 the scan found no tests at all). ArkGate matches declared text; it never executes tests.`)+(E&&o?c:a),file:d.provenance.sourceFile,line:1,arkruleId:d.id,arkruleSource:d.provenance.sourceFile,fromLayer:d.provenance.layer,severity:P?"error":"warning",failsStrict:P,kind:ee})}}return{coverage:f,violations:m,partial:f.some(d=>d.partial)}}i(Zn,"evaluateInvariantCoverage");function Qn(e){return e?e.partial?{ok:!1,reason:"Coverage is partial (missing test globs); cannot promote until evidence is complete."}:e.covered?e.outsideDeclaredRoots===!0?{ok:!1,reason:`Invariant ${e.invariantId} is covered only by ${e.testEvidenceFile??"a test"}, outside the declared coverage roots; ArkGate cannot tell whether that test runs, so it will not promote on it.`}:e.coverageRootsDeclared===!1?{ok:!1,reason:`Declare coverage.coverageRoots in ark.config.json before promoting ${e.invariantId} to enforced. Without that, ArkGate cannot tell whether a covering test is one the runner executes.`}:{ok:!0,reason:`Invariant ${e.invariantId} has coverage evidence.`}:{ok:!1,reason:`Invariant ${e.invariantId} is uncovered; add a test title or symbol before promoting to enforced.`}:{ok:!1,reason:"No coverage evidence supplied for this invariant; evaluate coverage before promoting to enforced."}}i(Qn,"canPromoteInvariant");function Xn(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!="string")continue;let r=n.trim();r.length>0&&t.push(r)}return t}i(Xn,"nonEmptyPathStrings");function el(e){return!e||typeof e!="object"?[]:[...Xn(e.testGlobs),...Xn(e.coverageRoots)]}i(el,"configuredInvariantTestsPaths");function tl(e){return el(e).length>0}i(tl,"hasConfiguredInvariantTestsPath");function er(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.coverage?.test!==!1)}i(er,"catalogDemandsInvariantTestsPath");function Gs(e){let t=e.hasDomainInvariants===!0||e.hasDomainInvariants!==!1&&er(e.invariants);return e.adopted!==!0||!t?[]:tl(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:Wi,message:qi,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]}i(Gs,"collectMissingInvariantTestsPathFindings");function nl(e){return!e||typeof e!="object"?[]:Xn(e.coverageRoots)}i(nl,"configuredCoverageRoots");function rl(e){return nl(e).length>0}i(rl,"hasConfiguredCoverageRoots");function tr(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.mode==="enforced")}i(tr,"catalogHasEnforcedInvariant");function Bs(e){return e.hasEnforcedInvariant===!0||e.hasEnforcedInvariant!==!1&&tr(e.invariants)?rl(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:Yi,message:Ji,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]:[]}i(Bs,"collectMissingCoverageRootsFindings");var sr="1.0",sl="add a short note under docs/adr/ (or docs/decisions/) and put that file path in --policy-ack as adrPath.";function w(e,t){let n=t.classification==="weakening"||t.classification==="judgment-required"?`Restore the previous protection at ${t.path}, or ${sl}`:void 0,r=t.nextAction??n;e.push({id:`${t.classification}:${t.path}:${t.kind}`,path:t.path,classification:t.classification,message:t.message,...r?{nextAction:r}:{},...t.before===void 0?{}:{before:t.before},...t.after===void 0?{}:{after:t.after}})}i(w,"addFinding");function Q(e){return[...new Set(e??[])].sort()}i(Q,"sortedUnique");function me(e,t,n,r,o){let s=Q(n),a=Q(r),c=new Set(s),l=new Set(a),u=a.filter(g=>!c.has(g)),p=s.filter(g=>!l.has(g));u.length===0&&p.length===0||(u.length>0&&w(e,{kind:"added",path:t,classification:o.added,message:o.addedMessage,before:s,after:a}),p.length>0&&w(e,{kind:"removed",path:t,classification:o.removed,message:o.removedMessage,before:s,after:a}))}i(me,"compareStringSets");function ht(e,t,n,r,o,s,a){if(n===r)return;w(e,{kind:r?"enabled":"disabled",path:t,classification:r?o:o==="strengthening"?"weakening":"strengthening",message:r?s:a,before:n,after:r})}i(ht,"compareBoolean");function Jt(e,t){let n=new Map,r=new Set;for(let o of e){let s=t(o);n.has(s)?r.add(s):n.set(s,o)}return{values:n,duplicates:[...r].sort()}}i(Jt,"keyed");function ol(e,t,n){let r=Jt(t,s=>s.name),o=Jt(n,s=>s.name);(r.duplicates.length>0||o.duplicates.length>0)&&w(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:r.duplicates,after:o.duplicates});for(let s of[...new Set([...r.values.keys(),...o.values.keys()])].sort()){let a=r.values.get(s),c=o.values.get(s),l=`$.layers[${s}]`;if(!a&&c){w(e,{kind:"layer-added",path:l,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",nextAction:"Write a short note under docs/adr/ (or docs/decisions/) for this new layer and put that file path in --policy-ack as adrPath.",after:c});continue}if(a&&!c){w(e,{kind:"layer-removed",path:l,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:a});continue}if(!a||!c)continue;me(e,`${l}.patterns`,a.patterns,c.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),me(e,`${l}.exclude`,a.exclude,c.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let u=Ft(a),p=Ft(c);me(e,`${l}.forbiddenGlobals`,u.rawGlobals,p.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),me(e,`${l}.capabilities`,u.atoms,p.atoms,{added:"strengthening",removed:"weakening",addedMessage:"Additional ambient/import protection is enforced in this layer (coverage atoms).",removedMessage:"An ambient/import protection was lost from this layer (coverage atoms)."}),Q(a.intentPrefixes).join("\0")!==Q(c.intentPrefixes).join("\0")&&w(e,{kind:"intent-prefixes-changed",path:`${l}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:Q(a.intentPrefixes),after:Q(c.intentPrefixes)}),ht(e,`${l}.mayImportInfrastructure`,a.mayImportInfrastructure===!0,c.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),ht(e,`${l}.optional`,a.optional===!0,c.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active.")}}i(ol,"compareLayers");function al(e,t,n){let r=i(a=>`${a.from}->${a.to}`,"keyOf"),o=Jt(t,r),s=Jt(n,r);(o.duplicates.length>0||s.duplicates.length>0)&&w(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:o.duplicates,after:s.duplicates});for(let a of[...new Set([...o.values.keys(),...s.values.keys()])].sort()){let c=o.values.get(a),l=s.values.get(a),u=`$.rules[${a}]`;if(!c&&l){l.allowed===!1?w(e,{kind:"deny-added",path:u,classification:"strengthening",message:"A denied dependency edge was added.",after:l}):w(e,{kind:"allow-added",path:u,classification:"judgment-required",message:"A new import edge was added; confirm this house should import that one.",nextAction:"Write a short note under docs/adr/ (or docs/decisions/) for this new import edge and put that file path in --policy-ack as adrPath.",after:l});continue}if(c&&!l){c.allowed===!1&&w(e,{kind:"deny-removed",path:u,classification:"weakening",message:"A denied dependency edge was removed.",before:c});continue}if(!c||!l)continue;c.allowed!==l.allowed&&w(e,{kind:l.allowed?"deny-disabled":"deny-enabled",path:`${u}.allowed`,classification:l.allowed?"weakening":"strengthening",message:l.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:c.allowed,after:l.allowed});let p=c.peerIsolation===!0,g=l.peerIsolation===!0;if(p!==g){let f=c.from===c.to&&l.from===l.to;w(e,{kind:g?"peer-isolation-enabled":"peer-isolation-disabled",path:`${u}.peerIsolation`,classification:f?g?"strengthening":"weakening":"judgment-required",message:f?g?"Cross-slice dependencies inside this layer are now denied.":"Cross-slice dependencies inside this layer are no longer denied.":"Changing peer isolation on a cross-layer edge changes the denial scope.",before:p,after:g})}Q(c.sliceFolders).join("\0")!==Q(l.sliceFolders).join("\0")&&w(e,{kind:"slice-folders-changed",path:`${u}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:Q(c.sliceFolders),after:Q(l.sliceFolders)}),!(!p&&!g)&&(Ws(e,`${u}.sharedRoots`,"shared-roots",Q(c.sharedRoots),Q(l.sharedRoots),"Roots declared shared are exempt from the peerIsolation unclassifiable denial.","Roots are no longer declared shared and fall back to the peerIsolation denial."),Ws(e,`${u}.allowedCrossSlice`,"cross-slice-allowance",Q((c.allowedCrossSlice??[]).map(zs)),Q((l.allowedCrossSlice??[]).map(zs)),"Directed cross-slice edges are now allowed by declaration.","Directed cross-slice edges are no longer declared and deny again."))}}i(al,"compareRules");function zs(e){return JSON.stringify([e.from,e.to])}i(zs,"crossSliceKey");function Ws(e,t,n,r,o,s,a){if(JSON.stringify(r)===JSON.stringify(o))return;let c=o.filter(p=>!r.includes(p)),l=r.filter(p=>!o.includes(p)),u=c.length>0&&l.length>0;w(e,{kind:u?`${n}-changed`:c.length>0?`${n}-added`:`${n}-removed`,path:t,classification:u?"judgment-required":c.length>0?"weakening":"strengthening",message:u?`${s} Entries were added and removed in the same change.`:c.length>0?s:a,before:r,after:o})}i(Ws,"compareDeclaredExceptions");function il(e,t,n){let r=t.safety??{},o=n.safety??{};for(let s of["maxTsSuppressions","maxAnyCasts"]){let a=r[s]??0,c=o[s]??0;a!==c&&w(e,{kind:c>a?"threshold-raised":"threshold-lowered",path:`$.safety.${s}`,classification:c>a?"weakening":"strengthening",message:c>a?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:a,after:c})}for(let s of["allowInMemory","allowDisabledPeerIsolation"])ht(e,`$.safety.${s}`,r[s]===!0,o[s]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}i(il,"compareSafety");function nr(e){return e.mode==="enforced"?"enforced":"advisory"}i(nr,"arkRunMode");function rr(e){return e.mode==="enforced"?"enforced":"advisory"}i(rr,"arkOrderMode");function ll(e,t,n){let r=t.arkOrder,o=n.arkOrder,s="$.arkOrder";if(!r&&!o)return;if(!r&&o){w(e,{kind:"arkorder-added",path:s,classification:"strengthening",message:`ArkOrder extra was added (${rr(o)}).`,after:o});return}if(r&&!o){w(e,{kind:"arkorder-removed",path:s,classification:"weakening",message:"ArkOrder extra was removed.",before:r});return}if(!r||!o)return;let a=rr(r),c=rr(o);if(a!==c){let l=a==="advisory"&&c==="enforced";w(e,{kind:l?"arkorder-promoted":"arkorder-demoted",path:`${s}.mode`,classification:l?"strengthening":"weakening",message:l?"ArkOrder extra was promoted to enforced.":"ArkOrder extra was demoted to advisory.",before:a,after:c})}me(e,`${s}.planeRoots`,r.planeRoots,o.planeRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkOrder plane roots are governed.",removedMessage:"ArkOrder plane roots were removed and may skip the plane."}),me(e,`${s}.managedLayers`,r.managedLayers,o.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkOrder.",removedMessage:"Layers were removed from ArkOrder management."})}i(ll,"compareArkOrder");function cl(e,t,n){let r=t.arkRun,o=n.arkRun,s="$.arkRun";if(!r&&!o)return;if(!r&&o){w(e,{kind:"arkrun-added",path:s,classification:"strengthening",message:`ArkRun extra was added (${nr(o)}).`,after:o});return}if(r&&!o){w(e,{kind:"arkrun-removed",path:s,classification:"weakening",message:"ArkRun extra was removed.",before:r});return}if(!r||!o)return;let a=nr(r),c=nr(o);if(a!==c){let l=a==="advisory"&&c==="enforced";w(e,{kind:l?"arkrun-promoted":"arkrun-demoted",path:`${s}.mode`,classification:l?"strengthening":"weakening",message:l?"ArkRun extra was promoted to enforced.":"ArkRun extra was demoted to advisory.",before:a,after:c})}me(e,`${s}.compositionRoots`,r.compositionRoots,o.compositionRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkRun composition roots are governed.",removedMessage:"ArkRun composition roots were removed and may skip the kernel."}),me(e,`${s}.managedLayers`,r.managedLayers,o.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkRun.",removedMessage:"Layers were removed from ArkRun management."}),ht(e,`${s}.requireDeclarations`,r.requireDeclarations!==!1,o.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}i(cl,"compareArkRun");function dl(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(dl,"overallClassification");function qs(e,t){return`${e}::${t}`}i(qs,"ruleKey");function Ys(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(qs(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(qs(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}i(Ys,"indexEffectiveRules");function ul(e,t,n,r,o,s){let a=new Map((s??[]).map(f=>[f.invariantId,f])),c=t.arkRules??{},l=n.arkRules??{},u=[...new Set([...Object.keys(c),...Object.keys(l)])].sort();for(let f of u){let m=c[f],d=l[f],A=`$.arkRules[${f}]`;if(m===void 0&&d!==void 0){w(e,{kind:"arkrules-ref-added",path:A,classification:"strengthening",message:`ArkRules reference for layer ${f} was added.`,after:d});continue}if(m!==void 0&&d===void 0){w(e,{kind:"arkrules-ref-removed",path:A,classification:"weakening",message:`ArkRules reference for layer ${f} was removed.`,before:m});continue}m!==d&&w(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:m,after:d})}let p=Ys(r),g=Ys(o);for(let f of[...new Set([...p.structure.keys(),...g.structure.keys()])].sort()){let m=p.structure.get(f),d=g.structure.get(f),A=`$.arkRules.structure[${f}]`;if(!m&&d){w(e,{kind:"arkrule-structure-added",path:A,classification:"strengthening",message:`Structure ArkRule ${d.id} was added (${d.mode}).`,after:d});continue}if(m&&!d){w(e,{kind:"arkrule-structure-removed",path:A,classification:"weakening",message:`Structure ArkRule ${m.id} was removed.`,before:m});continue}if(!(!m||!d)){if(m.mode!==d.mode){let b=m.mode==="advisory"&&d.mode==="enforced";w(e,{kind:b?"arkrule-promoted":"arkrule-demoted",path:`${A}.mode`,classification:b?"strengthening":"weakening",message:b?`Structure ArkRule ${d.id} was promoted to enforced.`:`Structure ArkRule ${d.id} was demoted to advisory.`,before:m.mode,after:d.mode})}m.sensor!==d.sensor&&w(e,{kind:"arkrule-sensor-changed",path:`${A}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${d.id} changed sensor identity.`,before:m.sensor,after:d.sensor})}}for(let f of[...new Set([...p.invariants.keys(),...g.invariants.keys()])].sort()){let m=p.invariants.get(f),d=g.invariants.get(f),A=`$.arkRules.invariants[${f}]`;if(!m&&d){w(e,{kind:"arkrule-invariant-added",path:A,classification:"strengthening",message:`Invariant ${d.id} was added (${d.mode}).`,after:d});continue}if(m&&!d){w(e,{kind:"arkrule-invariant-removed",path:A,classification:"weakening",message:`Invariant ${m.id} was removed.`,before:m});continue}if(!(!m||!d)&&m.mode!==d.mode)if(m.mode==="advisory"&&d.mode==="enforced"){let O=a?.get(d.id),k=Qn(O);k.ok?w(e,{kind:"arkrule-invariant-promoted",path:`${A}.mode`,classification:"strengthening",message:`Invariant ${d.id} was promoted to enforced (coverage evidence present).`,before:m.mode,after:d.mode}):w(e,{kind:"arkrule-invariant-promote-refused",path:`${A}.mode`,classification:"judgment-required",message:`Invariant ${d.id} cannot be promoted to enforced: ${k.reason}`,before:m.mode,after:d.mode})}else w(e,{kind:"arkrule-invariant-demoted",path:`${A}.mode`,classification:"weakening",message:`Invariant ${d.id} was demoted to advisory.`,before:m.mode,after:d.mode})}}i(ul,"compareArkRules");function or(e,t,n){let r=[];me(r,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),me(r,"$.exclude",e.exclude,t.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional project paths are excluded from governance.",removedMessage:"Fewer project paths are excluded from governance."}),me(r,"$.dynamicImportAllowlist",e.dynamicImportAllowlist,t.dynamicImportAllowlist,{added:"weakening",removed:"strengthening",addedMessage:"Additional files may use non-literal dynamic imports.",removedMessage:"Fewer files may use non-literal dynamic imports."}),ht(r,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let o={off:0,soft:1,"framework-soft":1,strict:2},s=e.cyclePolicy??"strict",a=t.cyclePolicy??"strict";if(s!==a){let c=o[a]===o[s]?"judgment-required":o[a]>o[s]?"strengthening":"weakening";w(r,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:c,message:"The cycle enforcement level changed.",before:s,after:a})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&w(r,{kind:"framework-overlay-changed",path:"$.frameworkOverlay",classification:"judgment-required",message:"The framework overlay changed and may alter effective layer matching.",before:e.frameworkOverlay??null,after:t.frameworkOverlay??null}),ol(r,e.layers,t.layers),al(r,e.rules,t.rules),il(r,e,t),ul(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),cl(r,e,t),ll(r,e,t),r.sort((c,l)=>c.path.localeCompare(l.path)||c.id.localeCompare(l.id)),{schemaVersion:sr,classification:dl(r),findings:r}}i(or,"classifyArkPolicyDelta");function ar(e,t){if(!e||e.schemaVersion!==sr||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(o=>typeof o!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=Q(e.findingIds),r=Q(t.findingIds);return n.length===r.length&&n.every((o,s)=>o===r[s])}i(ar,"policyDeltaAcknowledgementMatches");function Me(e){let t=[];for(let n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."&&t.length>0&&t.at(-1)!==".."?t.pop():t.push(n));return t.join("/")}i(Me,"normalizePath");function Js(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}i(Js,"isIdentifierStart");function Xt(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}i(Xt,"isIdentifierCharacter");function de(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}i(de,"skipWhitespace");function At(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let r=t,o="";for(t+=1;t<e.length;t+=1){let s=e[t];if(s===n)return{value:o,offset:r,excerpt:e.slice(r,t+1)};s==="\\"&&t+1<e.length?(o+=e[t+1],t+=1):o+=s}}i(At,"readString");function ue(e,t,n){return e.startsWith(t,n)&&!Xt(e[n-1])&&!Xt(e[n+t.length])}i(ue,"isWordAt");function Xs(e,t){let n=de(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=de(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!ue(e,"type",n))return!1;let o=de(e,n+4);if(o>=e.length||e[o]===","||e[o]==="}"||ue(e,"as",o)||!Js(e[o]))return!1;for(n=o;n<e.length&&Xt(e[n]);)n+=1;if(n=de(e,n),ue(e,"as",n)){if(n=de(e,n+2),!Js(e[n]))return!1;for(;n<e.length&&Xt(e[n]);)n+=1}r=!0}return!1}i(Xs,"bracedNamedBindingsAreTypeOnly");function pl(e,t){if(t=de(e,t+6),e[t]==="(")return At(e,de(e,t+1));let n=!1;if(ue(e,"type",t)){let o=de(e,t+4);e[o]!==","&&!ue(e,"from",o)&&(n=!0)}else Xs(e,t)&&(n=!0);let r=Zs(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}i(pl,"specifierAfterImport");function fl(e,t){t=t+6;let n=de(e,t),r=!1;if(ue(e,"type",n)){let s=de(e,n+4);(e[s]==="{"||e[s]==="*")&&(r=!0)}else Xs(e,n)&&(r=!0);let o=Zs(e,t,!1);return o&&r?{...o,typeOnly:!0}:o}i(fl,"specifierAfterExport");function Zs(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(ue(e,"from",t))return At(e,de(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return At(e,t);if(t>0&&(ue(e,"import",t)||ue(e,"export",t)))return}}i(Zs,"specifierInStaticStatement");function ml(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(ml,"skipTemplateLiteral");function gl(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=de(e,t+7);if(e[r]!=="(")return;r=de(e,r+1);let o=At(e,r);return o?{...o,requireCall:!0}:void 0}i(gl,"specifierAfterRequire");function yl(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 s=e.indexOf("*/",n+2);if(s<0)break;n=s+1;continue}if(r==="`"){n=ml(e,n);continue}if(r==="'"||r==='"'){let s=At(e,n);s&&(n=s.offset+s.excerpt.length-1);continue}let o=r==="i"&&ue(e,"import",n)?pl(e,n):r==="e"&&ue(e,"export",n)?fl(e,n):r==="r"&&ue(e,"require",n)?gl(e,n):void 0;o&&(t.push(o),n=o.offset+o.excerpt.length-1)}return t}i(yl,"moduleSpecifiers");function Qs(e,t){let n=[],r=[];for(let o of yl(e.content)){let s=o.value;if(!s.startsWith(".")){if(o.typeOnly)continue;let u=st(s);if(!u)continue;let p=e.content.slice(0,o.offset).split(`
|
|
10
10
|
`).length;r.push({file:e.path,symbol:s,capability:u,evidence:{kind:"import",file:e.path,line:p,excerpt:o.excerpt}});continue}let a=e.content.slice(0,o.offset).split(`
|
|
11
|
-
`).length,c={kind:"import",file:e.path,line:a,excerpt:o.excerpt},l=yl(e.path,s,t);n.push({from:e.path,specifier:s,to:l?.path??null,resolution:l?"resolved":"unresolved",fromLayer:e.layer,toLayer:l?.layer??null,evidence:c})}return{edges:n,capabilityUses:r}}i(Qs,"moduleFactsFor");function yl(e,t,n){let r=e.split("/");r.pop();for(let s of t.split("/"))s==="."||s===""||(s===".."?r.pop():r.push(s));let o=r.join("/");for(let s of[o,`${o}.ts`,`${o}.tsx`,`${o}.mts`,`${o}.cts`,`${o}/index.ts`,`${o}/index.tsx`]){let a=n.get(s);if(a)return a}}i(yl,"resolveSpecifier");function eo(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let o=Ht(t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});o&&n.push({ruleId:`layer-dependency:${o.from}->${o.to}`,message:o.message??`${o.from} must not depend on ${o.to}.`,edge:r,evidence:r.evidence})}return n}i(eo,"violationsFor");var hl={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 Al(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}i(Al,"hasActiveArkRules");function Rl(e,t){return Al(e,t)?X(H(Jn({config:e,arkRules:t,warnings:[]}))):X(H(Yn(e)))}i(Rl,"policyHashFor");function Zt(e,t,n){let r=typeof e=="string"?Vn(e,t):Gt(e,t),o=n?.arkRules??De();return{...r,arkRules:o,policyHash:Rl(r.config,o)}}i(Zt,"loadContract");function to(e){let t=Zt(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=Zt(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=or(t.config,n.config,{baseArkRules:t.arkRules,candidateArkRules:n.arkRules,candidateInvariantCoverage:e.candidateInvariantCoverage}),o=r.findings.filter(c=>c.classification==="weakening"||c.classification==="judgment-required").map(c=>c.id).sort(),s=o.length>0,a=s&&ar(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:o});return{schemaVersion:r.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:r.classification,findings:r.findings,blockingFindingIds:o,requiresAcknowledgement:s,acknowledged:a,valid:!s||a}}i(to,"analyzePolicyDelta");function Rt(e){let t=e.files.map(g=>{let f=Me(g.path);return{path:f,content:g.content,contentHash:X(g.content),layer:fe(f,e.contract.config.layers)??null}}).sort((g,f)=>g.path.localeCompare(f.path)),n=new Map(t.map(g=>[g.path,g])),r=[],o=[];for(let g of t){let f=Qs(g,n);r.push(...f.edges),o.push(...f.capabilityUses)}let s=eo(r,e.contract.config),a=new Map(e.contract.config.layers.map(g=>[g.name,g])),c=new Map(e.contract.config.layers.map(g=>[g.name,new Set(je(g))]));for(let g of o){let f=n.get(g.file)?.layer;if(!f)continue;let m=a.get(f),d=Ce(g.symbol,m?.forbiddenGlobals??[]);if(d){s.push({ruleId:"FORBIDDEN_GLOBAL",message:`${f} must not use module "${g.symbol}" because it is the import form of forbidden global "${d}".`,symbol:g.symbol,evidence:g.evidence});continue}c.get(f)?.has(g.capability)&&s.push({ruleId:"CAPABILITY_VIOLATION",message:`${f} denies the ${g.capability} capability; found import of "${g.symbol}".`,capability:g.capability,symbol:g.symbol,evidence:g.evidence})}let l=t.length===0?"complete":"partial",u=l==="complete"?[]:[{...hl}],p={schemaVersion:Bn,policyHash:e.contract.policyHash,compilerOptionsHash:X(H(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(g=>g.name),edges:r,capabilityUses:o,violations:s};return{mode:"lexical-compatibility",completeness:l,completenessReasons:u,valid:l==="complete"&&s.length===0,ir:p}}i(Rt,"analyzeProject");function Qt(e){let t=new Map(e.files.map(n=>[Me(n.path),n]));for(let n of e.changes){let r=Me(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return Rt({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}i(Qt,"analyzeChange");function no(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(no,"explainViolation");function ir(e){let t=0,n=new Map,r=new Map,o=new Set,s=[],a=[],c=i(l=>{n.set(l,t),r.set(l,t),t+=1,s.push(l),o.add(l);for(let g of[...e.get(l)??[]].sort())e.has(g)&&(n.has(g)?o.has(g)&&r.set(l,Math.min(r.get(l)??0,n.get(g)??0)):(c(g),r.set(l,Math.min(r.get(l)??0,r.get(g)??0))));if(r.get(l)!==n.get(l))return;let u=[],p;do{if(p=s.pop(),p===void 0)break;o.delete(p),u.push(p)}while(p!==l);u.length>1&&a.push(u.sort())},"connect");for(let l of[...e.keys()].sort())n.has(l)||c(l);return a.sort((l,u)=>l[0]<u[0]?-1:l[0]>u[0]?1:0).map(l=>({ruleId:"CIRCULAR_DEPENDENCY",file:l[0],line:1,target:l.join(" \u2192 "),message:`Circular dependency among ${l.length} files: ${l.join(" \u2192 ")} \u2192 ${l[0]}.`,cycleKind:"value"}))}i(ir,"detectArchitectureCycles");function Ye(e){let t=e.contentViolations.map(s=>({...s})),n=(e.warnings??[]).map(s=>({...s})),r=new Map(e.files.map(s=>[s,new Set]));for(let s of e.edges){if(s.to&&s.to!==s.from&&!s.typeOnly&&r.has(s.from)&&r.get(s.from)?.add(s.to),!s.to||!s.fromLayer||!s.toLayer)continue;let a=Te(e.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:e.config.layers});if(!a)continue;let c=a.rule,l=!!c.peerIsolation,u=!l&&!!(s.typeOnly||s.namedBindingsTypeOnly),p=l?Ke(a.peerIsolationReason??"cross-slice",{fromPath:s.from,toPath:s.to,fromSlice:a.fromSlice,toSlice:a.toSlice}):void 0,g=c.message?p?`${c.message} (${p})`:c.message:p?`${s.fromLayer} must not ${s.kind} another slice of ${s.toLayer} (${s.from} \u2192 ${s.to}): ${p}`:`${s.fromLayer} must not ${s.kind} ${s.toLayer}.`;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:s.from,line:s.line,fromLayer:s.fromLayer,toLayer:s.toLayer,target:s.to,...s.typeOnly?{typeOnly:!0}:{},...s.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...s.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...s.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!l&&s.portProofEligible?{portProofEligible:!0}:{},...s.kind?{edgeKind:s.kind}:{},...l?{peerIsolation:!0}:{},message:u?`${g} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:g,...u?{failsStrict:!1,severity:"warning"}:{}})}let o=String(e.config.cyclePolicy??"strict").toLowerCase();if(o!=="off"){let s=ir(r);o==="soft"||o==="framework-soft"?n.push(...s.map(a=>({...a,message:`${a.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...s)}return{violations:t,warnings:n,safety:e.safety}}i(Ye,"evaluateArchitectureGraph");function ro(e){if(typeof e.target=="string"&&e.target.length>0)return e.target;let t=String(e.sensor||e.code||"").trim();if(!t&&typeof e.message=="string"){let r=e.message.match(/\(sensor ([a-z0-9-]+)\)/i);r?.[1]&&(t=r[1])}let n=String(e.symbol||"").trim();return t?n?`${t}:${n}`:t:n}i(ro,"structureFreezeTarget");var kl=["no-anemic-model"],co=["ensureInvariants","assertInvariants","validate","publish","emit","raise","record"],dr=new RegExp(`\\b(${co.join("|")})\\b`),uo="(?:_?pendingEvents|domainEvents|uncommittedEvents|recordedEvents)",ur=new RegExp(`\\bthis\\.${uo}\\.push\\s*\\(`),El=new RegExp(`^this\\.${uo}\\s*=\\s*\\[\\s*\\]`),Sl=/^this\.[A-Za-z_][A-Za-z0-9_]*\s*=\s*\[\s*\]/,Il=/\bthis\.[A-Za-z_][A-Za-z0-9_]*\s*=(?!=)/g,po="truncatedUntil";function pr(){return`${co.join(", ")}, or events-array .push(`}i(pr,"expectedDomainInvariantWordsPhrase");function bl(e){return dr.test(e)||ur.test(e)}i(bl,"referencesGuardOrPublish");function fr(e,t,n){let r=e.slice(t);if(El.test(r))return!0;if(!Sl.test(r))return!1;if(n&&/^pullEvents$/i.test(n))return!0;let o=t>200?t-200:0;return/\bpullEvents\b/.test(e.slice(o,t+200))}i(fr,"isIdiomaticEventsReset");function vl(e,t){let n=new RegExp(Il.source,"g"),r;for(;(r=n.exec(t))!==null;)if(!fr(t,r.index,e))return!0;return!1}i(vl,"methodAssignsThis");function Cl(e,t){return t==null||Object.defineProperty(e,po,{value:t,enumerable:!1,configurable:!0}),e}i(Cl,"attachShapeTruncation");function cr(e){let t=Object.getOwnPropertyDescriptor(e,po)?.value;return typeof t=="number"?t:void 0}i(cr,"shapeTruncatedUntil");function _l(e){let t=cr(e);return t==null?"":` shape analysed until character ${t}`}i(_l,"shapeTruncationSuffix");function so(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(so,"escapeGlobLiteral");function Ol(e){let t="";for(let r=0;r<e.length;r+=1){let o=e[r];if(o==="\\"&&r+1<e.length){let s=e[r+1];if("*?{}[],".includes(s)||s==="\\"){t+="\\"+s,r+=1;continue}t+="/";continue}t+=o}let n="";for(let r=0;r<t.length;r+=1){let o=t[r];o==="\\"&&r+1<t.length?(n+=so(t[r+1]),r+=1):o==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":o==="?"?n+="[^/]":n+=so(o)}return new RegExp(`^${n}$`)}i(Ol,"globToRegExp");function Je(e,t){return!t||t.length===0?!0:t.some(n=>Ol(n).test(e))}i(Je,"matchesAppliesTo");function fo(e){return kl.includes(e)}i(fo,"isTier2");function mo(e){return e.mode==="enforced"&&!fo(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}i(mo,"severityFor");function Oe(e,t,n,r=1){let{severity:o,failsStrict:s}=mo(e);return{ruleId:"ARKRULE_STRUCTURE",code:e.sensor,message:n,file:t,line:r,fromLayer:e.provenance.layer,arkruleId:e.id,arkruleSource:e.provenance.sourceFile,severity:o,sensor:e.sensor,failsStrict:s}}i(Oe,"baseViolation");function tn(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}i(tn,"isInRuleLayer");function nn(e,t,n){return t.filter(r=>!(!r.exported||!Je(r.file,e.appliesTo)||!tn(r.file,e,n)))}i(nn,"shapesForRule");function xl(e,t,n){let r=[];for(let o of nn(e,t,n))(o.hasPublicSetters||o.hasPublicMutableFields)&&r.push(Oe(e,o.file,`Exported class ${o.className} exposes public mutable state (sensor aggregate-private-state).`));return r}i(xl,"evaluateAggregatePrivateState");function Tl(e,t,n){let r=[];for(let o of nn(e,t,n))if(o.hasPublicConstructor&&!o.hasStaticFactory){if(!(o.hasPublicMutableFields||o.hasPublicSetters||(o.mutatingMethods?.length??0)>0))continue;r.push(Oe(e,o.file,`Exported class ${o.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}return r}i(Tl,"evaluateAlwaysValidFactory");function Nl(e,t,n){let r=[],o=pr();for(let s of nn(e,t,n)){let a=_l(s);cr(s)!=null&&r.push(Oe(e,s.file,`Exported class ${s.className} shape analysed until character ${cr(s)}; later methods may be invisible (sensor domain-event-on-mutation).`));for(let c of s.mutatingMethods)c.referencesGuardOrPublish||r.push(Oe(e,s.file,`Mutating method ${s.className}.${c.name} does not reference ${o} (sensor domain-event-on-mutation).${a}`))}return r}i(Nl,"evaluateDomainEventOnMutation");function wl(e,t){let n=[];for(let r of t.files)Je(r,e.appliesTo)&&tn(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(Oe(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}i(wl,"evaluateOrchestrationOnly");function Pl(e,t){let n=[];for(let r of t.files)Je(r,e.appliesTo)&&tn(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(Oe(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}i(Pl,"evaluateThinAdapter");function Ll(e,t){let n=[];for(let r of t.files)Je(r,e.appliesTo)&&tn(r,e,t.layerForFile)&&t.fileHints?.[r]?.persistenceWrite&&n.push(Oe(e,r,"File imports a persistence driver and issues a write; route the write through a Domain aggregate and a persistence adapter (sensor writes-via-aggregate)."));return n}i(Ll,"evaluateWritesViaAggregate");function Dl(e,t,n){let r=[];for(let o of nn(e,t,n))if(o.dataOnly===!0){let s=Oe(e,o.file,`Exported type ${o.className} looks data-only / anemic (sensor no-anemic-model; advisory only).`);r.push({...s,severity:"warning",failsStrict:!1})}return r}i(Dl,"evaluateNoAnemicModel");function mr(e){if(!e.arkRules.structure.length)return[];let t=[];for(let n of e.arkRules.structure)switch(n.sensor){case"aggregate-private-state":t.push(...xl(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...Tl(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...Nl(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...wl(n,e));break;case"thin-adapter":t.push(...Pl(n,e));break;case"writes-via-aggregate":t.push(...Ll(n,e));break;case"no-anemic-model":t.push(...Dl(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(mr,"evaluateArkRuleSensors");function gr(e,t){let n=[],r=t.map(o=>o.replace(/\\/g,"/"));for(let o of e.structure){if(!o.appliesTo||o.appliesTo.length===0||r.some(l=>Je(l,o.appliesTo)))continue;let{severity:a,failsStrict:c}=mo(o);n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule structure "${o.id}" appliesTo matched zero governed files (patterns: ${o.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:o.provenance.sourceFile,line:1,fromLayer:o.provenance.layer,arkruleId:o.id,arkruleSource:o.provenance.sourceFile,severity:a,sensor:o.sensor,failsStrict:c})}for(let o of e.invariants??[]){if(!o.appliesTo||o.appliesTo.length===0||r.some(c=>Je(c,o.appliesTo)))continue;let a=o.mode==="enforced";n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule invariant "${o.id}" appliesTo matched zero governed files (patterns: ${o.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:o.provenance.sourceFile,line:1,fromLayer:o.provenance.layer,arkruleId:o.id,arkruleSource:o.provenance.sourceFile,severity:a?"error":"warning",sensor:"invariant-coverage",failsStrict:a})}return n.sort((o,s)=>o.file.localeCompare(s.file)||o.arkruleId.localeCompare(s.arkruleId)||o.message.localeCompare(s.message))}i(gr,"collectEmptyAppliesToFindings");var oo=64;function Ml(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===46;)t-=1;return t===e.length?e:e.slice(0,t)}i(Ml,"stripTrailingDots");function Fl(e){let t=e.trim(),n=t.length>oo?t.slice(0,oo):t;return Ml(n)}i(Fl,"normalizeIntentPrefix");function $l(e){let t=e.toLowerCase();return t.includes("domain")||t.includes("entity")||t.includes("aggregate")||t.includes("model")}i($l,"layerNameLooksDomain");function Hl(e){return e.some(t=>{let n=Fl(t);return n==="Domain"||n.startsWith("Domain.")})}i(Hl,"ownsDomainIntent");function jl(e,t=[]){return $l(e)||Hl(t)}i(jl,"isDomainRoleLayerName");function go(e){if(e.arkRulesActive!==!0)return[];let t=(e.layers??[]).filter(l=>jl(l.name,l.intentPrefixes??[])).map(l=>l.name);if(t.length===0)return[];let n=new Set(t);if(!(e.files??[]).some(l=>{let u=typeof l.layer=="string"?l.layer:"";return u.length>0&&n.has(u)}))return[];if((e.arkRules.invariants??[]).filter(l=>n.has(l.provenance.layer)).length>0)return[];let s=t.find(l=>e.arkRules.byLayer?.[l])??t[0],a=e.arkRules.byLayer?.[s]?.sourceFile??`arkrules/${s}.json`,c=(e.arkRules.structure??[]).some(l=>l.mode==="enforced"&&n.has(l.provenance.layer)&&!fo(l.sensor));return[{ruleId:"INVARIANT_CATALOG_EMPTY",code:"invariant-catalog-empty",message:`ArkRules is on and ${s} has code, but invariants[] is empty \u2014 there are no phrases the code must preserve. Add 1\u20132 short phrases in ${a}.`,file:a,line:1,fromLayer:s,arkruleId:"invariant-catalog",arkruleSource:a,severity:c?"error":"warning",sensor:"invariant-coverage",failsStrict:c}]}i(go,"collectEmptyInvariantCatalogFindings");var ao=/\bfrom\s+['"](?:@?prisma\/client|@supabase\/|drizzle-orm(?:\/[^'"]+)?|postgres(?:\/[^'"]+)?|typeorm|knex|mongodb|pg|mysql2|mongoose|better-sqlite3|ioredis|redis|kysely|sequelize)['"]|require\(\s*['"](?:@?prisma\/client|pg|postgres(?:\/[^'"]+)?|drizzle-orm(?:\/[^'"]+)?|knex|typeorm|mongoose)/,io=/\bfrom\s+['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)(?:\.[cm]?[jt]sx?)?['"]|require\(\s*['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)/,Kl=/\b(?:db|tx|client|prisma(?:Client)?|drizzle)\b(?:\s*\.\s*[A-Za-z_]\w*)*\s*\.\s*(?:insert(?:One|Many)?|update(?:One|Many)?|upsert|delete(?:One|Many)?|createMany|create|replaceOne|findOneAnd(?:Update|Delete|Replace))\s*\(|\bINSERT\s+INTO\b|\bUPDATE\s+[A-Za-z_][\w.]*\s+SET\b|\bDELETE\s+FROM\b/i;function Vl(e){return e==="PersistenceAdapters"}i(Vl,"isPersistenceDriverLayer");function Ul(e,t){if(ao.test(e)||io.test(e))return!0;if(!t)return!1;for(let n of t){if(Vl(n.layer))return!0;let r=n.specifier;if(!r)continue;let o=`from '${r}'`;if(ao.test(o)||io.test(o))return!0}return!1}i(Ul,"sourceImportsPersistenceDriver");var Gl=/\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*=)/,Bl=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,zl=/\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*=/,Wl=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function yo(e,t,n){if(!t)return null;let r=Ul(t,n),o=r&&Kl.test(t);if(t.length<40)return o?{persistenceWrite:!0}:null;let s=t.match(new RegExp(zl.source,"g"))??[],a=t.match(new RegExp(Wl.source,"g"))??[],c=(t.match(/\bif\s*\(/g)??[]).length,l=(t.match(/\bswitch\s*\(/g)??[]).length,u=s.length>=2||s.length>=1&&a.length>=2||a.length>=3&&c+l>=6,p=Gl.test(t)||Bl.test(t),g=s.length>=1||a.length>=2,f=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),m=r&&g||p&&g||r&&f&&(c>=4||s.length>=1)||p&&r;return!u&&!m&&!o?null:{...u?{orchestrationHeavy:!0}:{},...m?{adapterThick:!0}:{},...o?{persistenceWrite:!0}:{}}}i(yo,"deriveArkRuleFileHints");function yr(e,t){let n={};for(let[r,o]of Object.entries(e)){let s=r.replace(/\\/g,"/"),a=yo(r,o,t?.[s]);a&&(n[s]=a)}return n}i(yr,"buildArkRuleFileHints");var ql=new Set(["public","private","protected","static","async","readonly","abstract","override","declare","get","set"]),Yl=new Set(["if","match","when"]);function en(e,t){let n=e[t];if(n==="/"&&e[t+1]==="/"){let r=e.indexOf(`
|
|
12
|
-
`,t);return r===-1?e.length:r}if(n==="/"&&e[t+1]==="*"){let r=e.indexOf("*/",t+2);return r===-1?e.length:r+2}if(n==="'"||n==='"'||n==="`"){let r=t+1;for(;r<e.length;){if(e[r]==="\\"){r+=2;continue}if(e[r]===n)return r+1;r+=1}return e.length}return t}i(en,"skipStringOrComment");function kt(e,t){let n=t;for(;n<e.length;){if(/\s/.test(e[n])){n+=1;continue}if(e[n]==="/"&&(e[n+1]==="/"||e[n+1]==="*")){n=en(e,n);continue}break}return n}i(kt,"skipWsAndComments");function lo(e,t){let n=e[t];if(!n||!/[A-Za-z_]/.test(n))return null;let r=t+1;for(;r<e.length&&/[A-Za-z0-9_]/.test(e[r]);)r+=1;return{ident:e.slice(t,r),end:r}}i(lo,"readIdent");function lr(e,t,n,r){if(e[t]!==n)return null;let o=1,s=t+1;for(;s<e.length&&o>0;){let a=en(e,s);if(a!==s){s=a;continue}let c=e[s];c===n?o+=1:c===r&&(o-=1),s+=1}return o===0?s:null}i(lr,"skipBalanced");function Jl(e){let t=[],n=0,r;for(;n<e.length&&(n=kt(e,n),!(n>=e.length));){if(e[n]===";"){n+=1;continue}let o=[],s=n;for(;;){let p=lo(e,s);if(!p||!ql.has(p.ident))break;o.push(p.ident),s=kt(e,p.end)}let a=lo(e,s);if(!a){n+=1;continue}if(s=kt(e,a.end),e[s]==="<"){let p=lr(e,s,"<",">");if(p==null){r=e.length;break}s=kt(e,p)}if(e[s]==="("){let p=lr(e,s,"(",")");if(p==null){r=e.length;break}if(s=kt(e,p),e[s]===":")for(s+=1;s<e.length&&e[s]!=="{"&&e[s]!==";";){let g=en(e,s);if(g!==s){s=g;continue}s+=1}if(e[s]==="{"){let g=lr(e,s,"{","}");if(g==null){r=e.length;break}t.push({name:a.ident,modifiers:o,kind:"method",body:e.slice(s+1,g-1)}),n=g;continue}if(e[s]===";"){n=s+1;continue}n=s+1;continue}let c=0,l=0,u=0;for(;s<e.length;){let p=en(e,s);if(p!==s){s=p;continue}let g=e[s];if(g==="{")c+=1;else if(g==="}"){if(c===0)break;c-=1}else if(g==="(")l+=1;else if(g===")")l-=1;else if(g==="[")u+=1;else if(g==="]")u-=1;else if(g===";"&&c===0&&l===0&&u===0){s+=1;break}s+=1}t.push({name:a.ident,modifiers:o,kind:"field",body:""}),n=s}return{members:t,truncatedAt:r}}i(Jl,"scanClassMembers");function Xl(e,t){let n=[],r=/export\s+(?:abstract\s+)?class\s+([A-Za-z_][A-Za-z0-9_]*)\s*(?:extends\s+[^{]+)?(?:implements\s+[^{]+)?\{/g,o;for(;(o=r.exec(t))!==null;){let s=o[1],a=o.index+o[0].length,c=1,l=a;for(;l<t.length&&c>0;){let E=t[l];E==="{"?c+=1:E==="}"&&(c-=1),l+=1}let u=t.slice(a,l-1),p=c>0,g=Jl(u),f=p?t.length:g.truncatedAt==null?void 0:a+g.truncatedAt,m=g.members.filter(E=>!(E.kind!=="field"||E.name==="constructor"||E.modifiers.includes("private")||E.modifiers.includes("protected")||E.modifiers.includes("readonly")||E.modifiers.includes("static")||E.modifiers.includes("get")||E.modifiers.includes("set"))),d=m.length>0,A=/(?:^|[\n;{])\s*(?:public\s+)?set\s+[a-zA-Z_]/.test(u),b=/(?:^|[\n;{])\s*private\s+constructor\s*\(/.test(u),O=/(?:^|[\n;{])\s*(?:public\s+)?constructor\s*\(/.test(u)&&!b,k=/(?:^|[\n;{])\s*static\s+(?:async\s+)?(?:create|of|from|parse|build|make|new)\s*[<(]/.test(u)||/(?:^|[\n;{])\s*static\s+(?:async\s+)?[A-Za-z_][A-Za-z0-9_]*\s*\([^)]*\)\s*:\s*[A-Za-z_]/.test(u),I=[];for(let E of g.members)E.kind==="method"&&E.name!=="constructor"&&(E.modifiers.includes("static")||E.modifiers.includes("get")||E.modifiers.includes("set")||Yl.has(E.name)||vl(E.name,E.body)&&I.push({name:E.name,referencesGuardOrPublish:bl(E.body)}));let L=g.members.filter(E=>E.kind==="method").length<=1&&m.length>=2&&d;n.push(Cl({file:e,className:s,exported:!0,hasPublicMutableFields:d,hasPublicSetters:A,hasPublicConstructor:O,hasStaticFactory:k,mutatingMethods:[...I],dataOnly:L},f))}return n}i(Xl,"extractClassShapesFromSource");var Zl=50;function hr(e){if(!e)return{};let t=typeof e.governedPercent=="number"?e.governedPercent:null,n=typeof e.populatedLayerCount=="number"?e.populatedLayerCount:null;return n==null&&typeof e.classifiedFiles=="number"&&(n=e.classifiedFiles>0?1:0),{governedPercent:t,populatedLayerCount:n}}i(hr,"normalizeExtraMergeTeethClassification");function he(e){let t=hr(e),n=typeof t.governedPercent=="number"?t.governedPercent:null,r=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null;return n==null&&r==null?!0:(n??0)>=50&&(r??0)>=1}i(he,"extraMergeTeethAllowed");function Ar(e){let t=e.length,n=0,r=new Set;for(let o of e){let s=typeof o.layer=="string"&&o.layer.length>0?o.layer:null;s&&(n+=1,r.add(s))}return{governedPercent:t>0?Math.round(n/t*100):0,populatedLayerCount:r.size}}i(Ar,"classifyResolvedLayerCoverage");function Rr(e){return typeof e=="string"&&e.startsWith("ARKRUN_")}i(Rr,"isArkRunRuleId");function ho(e){return typeof e=="string"&&e.startsWith("ARKORDER_")}i(ho,"isArkOrderRuleId");function Ao(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(Ao,"isExtraPlaneFinding");function Ql(e,t={}){if(!Array.isArray(e)||he(t))return e;for(let n of e)Ao(n)&&n.failsStrict!==!1&&(n.failsStrict=!1,n.severity==="error"&&(n.severity="warning"));return e}i(Ql,"demoteExtraPlaneTeethUnderClassificationFloor");var Ro="Structure = heuristics; invariants = catalog+coverage evidence (not business runtime); ArkRun = kernel usage + declarations (not a score); ArkOrder = the few big product choices (not a score). Extra planes never merge into one architecture score. Advisory ArkRules \u2260 merge teeth. Advisory ArkRun \u2260 merge teeth. Advisory ArkOrder \u2260 merge teeth.";function ye(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):0}i(ye,"countOrZero");function rn(e={}){let t=hr(e.classification),n=typeof t.governedPercent=="number"?t.governedPercent:null,r=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null,o=n!=null||r!=null,s=he(t),a=e.arkRules,c=ye(a?.structureEnforced),l=ye(a?.structureTotal),u=typeof a?.structureAdvisory=="number"?ye(a.structureAdvisory):Math.max(0,l-c),p=ye(a?.invariantEnforced),g=ye(a?.invariantTotal),f=typeof a?.invariantAdvisory=="number"?ye(a.invariantAdvisory):Math.max(0,g-p),m=c>0||p>0,d=e.arkRun?.present===!0,A=e.arkRun?.mode==="enforced"||e.arkRun?.mode==="advisory"?e.arkRun.mode:null,b=ye(e.arkRun?.residualCount),O=d&&A==="enforced",k=O&&s,I=e.arkOrder?.present===!0,C=e.arkOrder?.mode==="enforced"||e.arkOrder?.mode==="advisory"?e.arkOrder.mode:null,L=ye(e.arkOrder?.residualCount),E=I&&C==="enforced",P=E&&s,ee=m||O||E,T=ee&&s,V=ee&&o&&!s,D;if(T){let J=[];m&&J.push("enforced structure/invariant findings"),O&&J.push("enforced ArkRun skip findings"),E&&J.push("enforced ArkOrder skip findings"),D=`Layer graph failures plus ${J.join(" and ")} (advisory extras never fail merge alone).`}else if(V)D=`Layer graph only \u2014 enforced ${[m?"ArkRules structure/invariant":null,O?"ArkRun":null,E?"ArkOrder":null].filter(be=>!!be).join(" and ")} findings are demoted under the teeth floor (need \u226550% governed and \u22651 populated layer); they do not merge-block until classification is honest.`;else{let J=d?A==="advisory"?" Advisory ArkRun never merge-blocks.":" ArkRun extra is present but does not arm merge teeth.":" Absence of arkRun is silent.",be=I?C==="advisory"?" Advisory ArkOrder never merge-blocks.":" ArkOrder extra is present but does not arm merge teeth.":" Absence of arkOrder is silent.";D="Layer graph only \u2014 no enforced ArkRules structure/invariant teeth on this tree. Advisory packs do not arm merge teeth."+J+be}let se={layers:{role:"inter-layer-edges",alwaysOnGate:!0,note:"Import/export layer graph \u2014 the default merge plane. Absent extras change nothing here."},structureSensors:{role:"intra-layer-heuristics",total:l,enforced:c,advisory:u,note:"Structure sensors are heuristics (prefer false negatives). Only mode:enforced fails merge; noisy sensors stay advisory by default. Advisory-only packs never add merge teeth (FG-ARKRULES-ADVISORY-ONLY)."},invariants:{role:"catalog-plus-coverage",total:g,enforced:p,advisory:f,covered:ye(a?.covered),uncovered:ye(a?.uncovered),note:"Invariants are catalog + coverage evidence, not a business runtime. Enforced + proven-uncovered fails merge; absence of enforced rules adds no extra teeth."},arkRun:{role:"kernel-usage-and-declarations",present:d,mode:A,residualCount:b,extraMergeTeeth:k,note:d?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."},arkOrder:{role:"pattern-slaving",present:I,mode:C,residualCount:L,extraMergeTeeth:P,note:I?C==="enforced"?"Enforced ArkOrder arms extra merge teeth only when the layer plane is classified. Residual is a count, never a score.":"Advisory ArkOrder never adds merge teeth and never flips valid. Residual is a count, never a score.":"Absence of arkOrder is silent \u2014 Layers verdicts unchanged. The extra never becomes a score."},extraMergeTeeth:T,dualPlaneStamp:Ro,failMergeWhen:D};return o&&(se.classificationGate={governedPercent:n,populatedLayerCount:r,floorPercent:50,allowsTeeth:s}),se}i(rn,"composeMergePlanesHonesty");var Eo=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"],ec=["publisher","publish","raise","raiseAsync","send","sendTo","subscribe","registerHandler","resolve","resolveSingleton"],tc=new Set(Eo),nc=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"]),rc=new Set(["Array","Atomics","Buffer","JSON","Math","Number","Object","Promise","Reflect","String","console","fs","path","url","util"]);function It(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")}i(It,"isArkRunKernelModuleSpecifier");var So=["events","node:events","eventemitter2","eventemitter3","emittery","kafkajs","kafka-node","amqplib","amqp","bull","bullmq","mqtt","nats","@aws-sdk/client-sqs","@aws-sdk/client-sns","@aws-sdk/client-eventbridge","@google-cloud/pubsub","@azure/service-bus"],kr=new Set(So);function Sr(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(kr.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(kr.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:kr.has(e.slice(0,r))}i(Sr,"isArkRunTransportBypassSpecifier");function Er(e){if(tc.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(Er,"arkRunKernelCallKind");function St(e,t){let n=1;for(let r=0;r<t;r+=1)e.charCodeAt(r)===10&&(n+=1);return n}i(St,"lineAt");function bt(e){return e.replace(/\/\*[\s\S]*?\*\//g,t=>t.replace(/[^\n]/g," ")).replace(/(^|[^:\\])\/\/.*$/gm,t=>t.replace(/\/\/.*$/,n=>" ".repeat(n.length)))}i(bt,"stripCommentsPreservingLines");function sc(e,t){let n=e.slice(t),r=/^\s*(['"])((?:\\.|[^\\])*?)\1/.exec(n);if(!r)return;let o=r[2]??"";return o.length>0?o:void 0}i(sc,"firstStringLiteralArg");function ko(e,t,n){let r=Math.max(0,t-n.length-8),o=e.slice(r,t);return new RegExp(`\\b${n}\\s+$`).test(o)}i(ko,"keywordBefore");function sn(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(sn,"parseValueImportClause");function oc(e,t){sn(bt(e),t)}i(oc,"forEachArkRunValueImportClause");function Ir(e,t){let n=bt(t),r=[],o=/\b(?:import|export)(\s+type)?\s+([\s\S]*?)\s+from\s*['"]([^'"]+)['"]/g,s;for(;(s=o.exec(n))!==null;){let c=s[3]??"";if(!c)continue;let l=s[0]??"";r.push({from:e,specifier:c,kind:/^\s*export/.test(l)?"export":"import",typeOnly:!!s[1],line:St(t,s.index),resolution:"resolved-external"})}let a=/\b(?:require|import)\s*\(\s*['"]([^'"]+)['"]\s*\)/g;for(;(s=a.exec(n))!==null;){let c=s[1]??"";if(!c)continue;let l=s[0]?.startsWith("import")?"dynamic-import":"require";r.push({from:e,specifier:c,kind:l,typeOnly:!1,line:St(t,s.index),resolution:"resolved-external"})}return r}i(Ir,"extractArkRunValueImportDependenciesFromSource");function br(e){let t=[];return oc(e,n=>{let r=/\{([^}]*)\}/.exec(n);if(r?.[1])for(let o of r[1].split(",")){let s=o.trim();if(!s||s.startsWith("type "))continue;let a=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(s),c=a?.[2]??/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(s)?.[1],l=a?.[1]??c;c&&l&&/^[A-Z]/.test(l)&&t.push(c,l)}}),Et(t)}i(br,"extractArkRunImportedConstructorNamesFromSource");function ac(e){let t=new Map,n=new Set;return sn(e,(r,o)=>{if(!It(o))return;let s=/\*\s+as\s+([A-Za-z_][A-Za-z0-9_]*)/.exec(r);s?.[1]&&n.add(s[1]);let a=/^([A-Za-z_][A-Za-z0-9_]*)\s*(?:,|$)/.exec(r.trim());a?.[1]&&t.set(a[1],a[1]);let c=/\{([^}]*)\}/.exec(r);if(c?.[1])for(let l of c[1].split(",")){let u=l.trim();if(!u||u.startsWith("type "))continue;let p=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(u);if(p){t.set(p[2],p[1]);continue}let g=/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(u);g?.[1]&&t.set(g[1],g[1])}}),{named:t,namespaces:n}}i(ac,"collectKernelImportBindings");function ic(e,t){let n=new Set(t);return sn(e,(r,o)=>{let s=/\{([^}]*)\}/.exec(r);if(s?.[1])for(let a of s[1].split(",")){let c=a.trim();if(!c||c.startsWith("type "))continue;let l=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(c),u=l?.[2]??/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(c)?.[1],p=l?.[1]??u;!u||!p||!/^[A-Z]/.test(p)||(It(o)||t.has(p)||t.has(u))&&(n.add(u),n.add(p))}}),n}i(ic,"collectImportedConstructors");function lc(e,t){let n;return sn(e,(r,o)=>{!n&&new RegExp(`\\b${t}\\b`).test(r)&&(n=o)}),n}i(lc,"importedFromForName");function vr(e,t){let n=bt(t),r=ac(n),o=[],s=/\b([A-Za-z_][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,a;for(;(a=s.exec(n))!==null;){let c=a[1],l=a.index;if(ko(n,l,"function")||ko(n,l,"class"))continue;let p=n.slice(0,l).match(/([A-Za-z_][A-Za-z0-9_]*)\s*\.\s*$/)?.[1],g=r.named.get(c)??c,f=Er(g)??Er(c);if(!f)continue;let m=r.named.has(c)||p!==void 0&&r.namespaces.has(p);if(f!=="factory"&&(!m&&p===void 0||p&&rc.has(p)&&!m))continue;let d=sc(n,l+a[0].length);o.push({file:e,line:St(t,l),kind:f,callee:c,viaImport:m,...p?{receiver:p}:{},...d?{nameLiteral:d}:{}})}return o}i(vr,"extractArkRunKernelCallsFromSource");function Cr(e,t,n){let r=bt(t),o=ic(r,n),s=[],a=/\bnew\s+(?:[A-Za-z_][A-Za-z0-9_]*\s*\.\s*)*([A-Z][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,c;for(;(c=a.exec(r))!==null;){let l=c[1];if(nc.has(l)||!o.has(l))continue;let u=lc(r,l);s.push({file:e,line:St(t,c.index),typeName:l,...u?{importedFrom:u}:{}})}return s}i(Cr,"extractArkRunManagedNewsFromSource");function cc(e,t){let n=0,r;for(let o=t;o<e.length;o+=1){let s=e[o];if(r){if(s==="\\"){o+=1;continue}s===r&&(r=void 0);continue}if(s==="'"||s==='"'||s==="`"){r=s;continue}if(s==="[")n+=1;else if(s==="]"&&(n-=1,n===0))return o}return-1}i(cc,"matchingBracketEnd");function dc(e,t,n){let r=e.slice(t+1,n),o=[],s=/(['"])((?:\\.|[^\\])*?)\1/g,a;for(;(a=s.exec(r))!==null;){let c=a[2]??"";c.length>0&&o.push(c)}return o}i(dc,"stringLiteralsInList");function Et(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}i(Et,"uniqueSorted");function uc(e,t){let n=bt(t),r=/\b(uses|reactsTo|raises|sends)\s*:/g,o=[],s=[],a=[],c=[],l,u;for(;(u=r.exec(n))!==null;){let p=n.slice(u.index+u[0].length),g=/^\s*\[/.exec(p);if(!g)continue;let f=u.index+u[0].length+(g[0].length-1),m=cc(n,f);if(m<0)continue;let d=dc(n,f,m);if(d.length===0)continue;l===void 0&&(l=u.index);let A=u[1];A==="uses"?o.push(...d):A==="reactsTo"?s.push(...d):A==="raises"?a.push(...d):c.push(...d)}return l===void 0?[]:[{file:e,line:St(t,l),uses:Et(o),reactsTo:Et(s),raises:Et(a),sends:Et(c)}]}i(uc,"extractArkRunDeclarationsFromSource");var pc=["arkrun-missing-root","arkrun-kernel-in-domain","arkrun-direct-new","arkrun-undeclared-emit","arkrun-undeclared-handle","arkrun-undeclared-depend","arkrun-transport-bypass"],fc=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],mc=new Set(fc);function gc(e){return mc.has(e)}i(gc,"isArkRunEditorSensor");var _r={"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"},vo="ARKRUN_INTERACTION_NAME_INCOMPLETE";function Co(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)||/^(?:entit(?:y|ies)|aggregates?)(?:$|(?=[A-Z_\-\s]))/i.test(n)?!0:t.some(r=>{let o=r.trim().replace(/\.+$/,"");return o==="Domain"||o.startsWith("Domain.")})}i(Co,"isDomainRoleLayer");function yc(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}i(yc,"compareFindings");function Ie(e,t,n,r,o,s,a){let c=e.mode==="enforced"&&a;return{ruleId:_r[t],sensor:t,message:o,file:n,line:r,...s?.fromLayer?{fromLayer:s.fromLayer}:{},...s?.target?{target:s.target}:{},severity:c?"error":"warning",failsStrict:c,nextAction:ge({ruleId:_r[t],fromLayer:s?.fromLayer,target:s?.target})}}i(Ie,"finding");function hc(e,t){let n=[],r=[],o=[],s=[];for(let a of e)a.file===t&&(n.push(...a.uses),r.push(...a.reactsTo),o.push(...a.raises),s.push(...a.sends));return{uses:new Set(n),reactsTo:new Set(r),raises:new Set(o),sends:new Set(s)}}i(hc,"bagForFile");function Io(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}i(Io,"emitKinds");function bo(e){return e==="subscribe"||e==="register-handler"}i(bo,"handleKinds");function Ac(e){return e==="resolve"||e==="resolve-singleton"}i(Ac,"dependKinds");function Rc(e,t,n){let r=[],o=e.kernelRoots??e.compositionRoots;if(o.length===0)return r.push(Ie(e,"arkrun-missing-root","ark.config.json",1,"ArkRun kernelRoots is empty; no createArkKernel factory site is declared.",void 0,n)),r;let s=new Map;for(let a of t){let c=s.get(a.matchedRoot)??[];c.push(a),s.set(a.matchedRoot,c)}for(let a of o){let c=[...s.get(a)??[]].sort((u,p)=>u.file.localeCompare(p.file));if(c.length===0){r.push(Ie(e,"arkrun-missing-root","ark.config.json",1,`ArkRun kernel root ${JSON.stringify(a)} matched no governed files and has no createArkKernel factory.`,{target:a},n));continue}if(c.some(u=>u.hasKernelFactory))continue;let l=c[0];r.push(Ie(e,"arkrun-missing-root",l.file,1,`ArkRun kernel root ${JSON.stringify(a)} has no createArkKernel / createStrictArkKernel factory.`,{target:a},n))}return r}i(Rc,"evaluateMissingRoot");function kc(e,t,n,r,o){let s=new Map(t.map(c=>[c.name,c.intentPrefixes??[]])),a=[];for(let c of n){let l=c.specifier;if(!l||!It(l))continue;let u=r(c.from);u&&Co(u,s.get(u)??[])&&a.push(Ie(e,"arkrun-kernel-in-domain",c.from,c.line,`${u} must not import kernel module ${JSON.stringify(l)}.`,{fromLayer:u,target:l},o))}return a}i(kc,"evaluateKernelInDomain");function Ec(e,t,n,r,o,s){let a=new Set(e.managedLayers);if(a.size===0)return[];let c=new Map(t.map(p=>[p.name,p.intentPrefixes??[]])),l=new Set(r.filter(p=>p.hasKernelFactory).map(p=>p.file)),u=[];for(let p of n){if(l.has(p.file))continue;let g=p.typeName;if(e.ignoreDirectNewForErrors!==!1&&(g.endsWith("Error")||g==="Error")||g.endsWith("DTO")||g.endsWith("VO"))continue;let f=o(p.file);!f||!a.has(f)||Co(f,c.get(f)??[])||u.push(Ie(e,"arkrun-direct-new",p.file,p.line,`${f} must not construct ${p.typeName} with new outside an ArkRun composition-root factory.`,{fromLayer:f,target:p.typeName},s))}return u}i(Ec,"evaluateDirectNew");function Sc(e,t,n,r,o){let s=[],a=[];if(e.requireDeclarations!==!0)return{findings:s,completenessReasons:a};let c=new Set(e.managedLayers);if(c.size===0)return{findings:s,completenessReasons:a};for(let l of t){if(!Io(l.kind)&&!bo(l.kind)&&!Ac(l.kind))continue;let u=r(l.file);if(!u||!c.has(u))continue;if(!l.nameLiteral){e.mode==="enforced"&&a.push({code:vo,file:l.file,message:`ArkRun ${l.kind} call in ${l.file} has no string-literal name; enforced extra cannot prove the declaration.`});continue}let p=hc(n,l.file);if(Io(l.kind)){if(p.raises.has(l.nameLiteral)||p.sends.has(l.nameLiteral))continue;s.push(Ie(e,"arkrun-undeclared-emit",l.file,l.line,`Emit ${JSON.stringify(l.nameLiteral)} is not declared in raises or sends.`,{fromLayer:u,target:l.nameLiteral},o));continue}if(bo(l.kind)){if(p.reactsTo.has(l.nameLiteral))continue;s.push(Ie(e,"arkrun-undeclared-handle",l.file,l.line,`Handle ${JSON.stringify(l.nameLiteral)} is not declared in reactsTo.`,{fromLayer:u,target:l.nameLiteral},o));continue}p.uses.has(l.nameLiteral)||s.push(Ie(e,"arkrun-undeclared-depend",l.file,l.line,`Depend ${JSON.stringify(l.nameLiteral)} is not declared in uses.`,{fromLayer:u,target:l.nameLiteral},o))}return{findings:s,completenessReasons:a}}i(Sc,"evaluateUndeclared");function Ic(e,t,n,r){let o=new Set(e.managedLayers);if(o.size===0)return[];let s=[];for(let a of t){if(a.typeOnly)continue;let c=a.specifier;if(!c||!Sr(c))continue;let l=n(a.from);!l||!o.has(l)||s.push(Ie(e,"arkrun-transport-bypass",a.from,a.line,`${l} must not import broker/queue/emitter ${JSON.stringify(c)}; use the ArkRun kernel transport.`,{fromLayer:l,target:c},r))}return s}i(Ic,"evaluateTransportBypass");function on(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=he(e.classification),r=Sc(t,e.kernelCalls,e.declarations,e.layerForFile,n),o=[...Rc(t,e.compositionRootHits,n),...kc(t,e.layers,e.dependencies,e.layerForFile,n),...Ec(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...Ic(t,e.dependencies,e.layerForFile,n)].sort(yc),s=[...r.completenessReasons].sort((a,c)=>{let l=`${a.code}\0${a.file??""}\0${a.message}`,u=`${c.code}\0${c.file??""}\0${c.message}`;return l<u?-1:l>u?1:0});return{findings:o,completenessReasons:s}}i(on,"evaluateArkRunSensors");function _o(e){return{findings:on(e).findings.filter(n=>gc(n.sensor)),completenessReasons:[]}}i(_o,"evaluateArkRunEditorSensors");function bc(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(bc,"fileMatchesCompositionRoot");function vc(e,t,n){let r=vr(t,n).some(a=>a.kind==="factory"),o=[],s=e.kernelRoots??e.compositionRoots;for(let a of s)bc(a,t)&&o.push({file:t,matchedRoot:a,hasKernelFactory:r});return o}i(vc,"compositionRootHitsForSource");function Cc(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=new Set(br(e.source));return _o({arkRun:t,layers:e.layers,kernelCalls:[],managedNews:Cr(e.file,e.source,n),compositionRootHits:vc(t,e.file,e.source),declarations:[],dependencies:Ir(e.file,e.source),layerForFile:e.layerForFile,classification:e.classification})}i(Cc,"evaluateArkRunEditorSensorsFromSource");function Oo(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}i(Oo,"isArkOrderModuleSpecifier");var xo=new Map;function To(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(To,"escapeAppliesToLiteral");function _c(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let o=e[n+1];if("*?{}[],".includes(o)||o==="\\"){t+="\\"+o,n+=1;continue}t+="/";continue}t+=r}return t}i(_c,"normalizeAppliesToGlob");function Oc(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(Oc,"appliesToBracesBalanced");function xc(e){let t=xo.get(e);if(t)return t;let n=_c(e),r=Oc(n),o="",s=0;for(let c=0;c<n.length;c+=1){let l=n[c];l==="\\"&&c+1<n.length?(o+=To(n[c+1]),c+=1):l==="*"?n[c+1]==="*"?n[c+2]==="/"?(o+="(?:.*/)?",c+=2):(o+=".*",c+=1):o+="[^/]*":l==="?"?o+="[^/]":l==="{"&&r?(o+="(?:",s+=1):l==="}"&&r&&s>0?(o+=")",s-=1):l===","&&r&&s>0?o+="|":o+=To(l)}let a=new RegExp(`^${o}$`);return xo.set(e,a),a}i(xc,"globToRegExp");var Tc=["arkorder-missing-plane","arkorder-kernel-in-domain","arkorder-generic-update","arkorder-too-many-params","arkorder-ingest-writes-xi","arkorder-xi-field-write","arkorder-information-budget","arkorder-xi-ttl"],Or={"arkorder-missing-plane":"ARKORDER_MISSING_PLANE","arkorder-kernel-in-domain":"ARKORDER_KERNEL_IN_DOMAIN","arkorder-generic-update":"ARKORDER_GENERIC_UPDATE","arkorder-too-many-params":"ARKORDER_TOO_MANY_PARAMS","arkorder-ingest-writes-xi":"ARKORDER_INGEST_WRITES_XI","arkorder-xi-field-write":"ARKORDER_XI_FIELD_WRITE","arkorder-information-budget":"ARKORDER_INFORMATION_BUDGET","arkorder-xi-ttl":"ARKORDER_XI_TTL"};function Nc(e,t){return!t||t.length===0?!0:t.some(n=>xc(n).test(e))}i(Nc,"matchesArkOrderAppliesTo");function wc(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)?!0:t.some(r=>{let o=r.trim().replace(/\.+$/,"");return o==="Domain"||o.startsWith("Domain.")})}i(wc,"isDomainRoleLayer");function xe(e,t,n,r,o,s,a){let c=e.mode==="enforced"&&a;return{ruleId:Or[t],sensor:t,message:o,file:n,line:r,...s?.fromLayer?{fromLayer:s.fromLayer}:{},...s?.target?{target:s.target}:{},severity:c?"error":"warning",failsStrict:c,nextAction:ge({ruleId:Or[t],fromLayer:s?.fromLayer,target:s?.target})}}i(xe,"finding");function xr(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let n=he(e.classification),r=[],o=t.planeRoots;if(t.mode==="enforced"&&o.length===0)r.push(xe(t,"arkorder-missing-plane","ark.config.json",1,"ArkOrder planeRoots is empty; no createOrderPlane site is declared.",void 0,n));else{let l=new Map;for(let u of e.planeRootHits){let p=l.get(u.matchedRoot)??[];p.push(u),l.set(u.matchedRoot,p)}for(let u of o){let p=l.get(u)??[];if(p.length===0){r.push(xe(t,"arkorder-missing-plane","ark.config.json",1,`ArkOrder plane root ${JSON.stringify(u)} matched no governed files and has no createOrderPlane factory.`,{target:u},n));continue}p.some(g=>g.hasPlaneFactory)||r.push(xe(t,"arkorder-missing-plane",p[0].file,1,`ArkOrder plane root ${JSON.stringify(u)} has no createOrderPlane factory.`,{target:u},n))}}let s=new Map(e.layers.map(l=>[l.name,l.intentPrefixes??[]]));for(let l of e.dependencies){let u=l.specifier;if(!u||!Oo(u))continue;let p=e.layerForFile(l.from);p&&wc(p,s.get(p)??[])&&r.push(xe(t,"arkorder-kernel-in-domain",l.from,l.line,"Domain-role layer imports arkgate/order; Domain stays plane-free.",{fromLayer:p,target:u},n))}for(let l of e.genericUpdates)r.push(xe(t,"arkorder-generic-update",l.file,l.line,`Generic ${l.method}() on the order plane rewrites \u03BE; Haken forbids it.`,{target:l.method},n));let a=t.xiKeys??[];for(let l of e.releaseKeyCounts??[])l.keyCount<=t.maxXiKeys||r.push(xe(t,"arkorder-too-many-params",l.file,l.line,`release() freezes ${l.keyCount} keys; maxXiKeys is ${t.maxXiKeys} (few slow modes).`,{target:String(l.keyCount)},n));for(let l of e.ingestWritesXi??[])r.push(xe(t,"arkorder-ingest-writes-xi",l.file,l.line,"ingest() result is assigned into a Release or \u03BE store; ingest may absorb or escalate, never mint a pattern.",void 0,n));let c=new Set(t.managedLayers);for(let l of a.length===0?[]:e.xiFieldWrites??[]){let u=e.layerForFile(l.file);!u||!c.has(u)||Nc(l.file,t.appliesTo)&&r.push(xe(t,"arkorder-xi-field-write",l.file,l.line,`This file writes ${JSON.stringify(l.key)} the same way it would write a seat count. Take the event in, or change that choice through the valve (propose, then apply).`,{fromLayer:u,target:l.key},n))}return r.sort((l,u)=>l.file.localeCompare(u.file)||l.ruleId.localeCompare(u.ruleId)||l.line-u.line),{findings:r,completenessReasons:[]}}i(xr,"evaluateArkOrderSensors");function ne(e,t,n={}){return{ruleId:e,message:t,...n}}i(ne,"configWarning");function an(e){let{config:t,rules:n,files:r,manifest:o}=e,s=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(d=>typeof d!="string"))&&s.push(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)))s.push(ne("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let d of["maxTsSuppressions","maxAnyCasts"]){let A=t.safety[d];A!==void 0&&(!Number.isInteger(A)||A<0)&&s.push(ne("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${d} must be a non-negative integer.`))}let a=Array.isArray(t.layers)?t.layers:[],c=Array.isArray(o?.architecture?.layers)?o.architecture.layers:[],l=new Set([...a.map(d=>d.name).filter(Boolean),...c.map(d=>d.name).filter(d=>!!d)]);a.length===0&&s.push(ne("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let u=new Set,p=new Set;for(let d of a){if(!d.name){s.push(ne("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}u.has(d.name)&&p.add(d.name),u.add(d.name),d.forbiddenGlobals!==void 0&&(!Array.isArray(d.forbiddenGlobals)||d.forbiddenGlobals.some(b=>typeof b!="string"))&&s.push(ne("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 A=Array.isArray(d.patterns)?d.patterns:[];if(A.length===0){s.push(ne("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${d.name}" has no file patterns and will never classify files.`,{layer:d.name}));continue}for(let b of A){let O;try{O=Re(b)}catch(I){s.push(ne("CONFIG_INVALID_LAYER_PATTERN",`Layer "${d.name}" has an invalid pattern "${b}": ${I instanceof Error?I.message:String(I)}`,{layer:d.name,pattern:b}));continue}let k=d.optional===!0||d.reserved===!0||d.allowEmpty===!0;!r.some(I=>O.test(I))&&!k&&s.push(ne("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${d.name}" pattern "${b}" matched no included files (possible typo). Mark the layer reserved/allowEmpty if this house is reserved for later.`,{layer:d.name,pattern:b,failsStrict:!1,reserved:!1}))}}for(let d of p)s.push(ne("CONFIG_DUPLICATE_LAYER",`Layer "${d}" is configured more than once.`,{layer:d}));if(l.size>0)for(let d of n??[])d.from&&!l.has(d.from)&&s.push(ne("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${d.from}".`,{fromLayer:d.from,toLayer:d.to})),d.to&&!l.has(d.to)&&s.push(ne("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 A=-1,b=[];for(let O of a)for(let k of O.patterns??[]){if(!Re(k).test(d))continue;let I=xn(k,d);I>A?(A=I,b=[O.name]):I===A&&!b.includes(O.name)&&b.push(O.name)}b.length>1&&g.add([...b].sort().join(" + "))}g.size>0&&s.push(ne("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...g].join(", ")}.`,{pairs:[...g]}));let f=r.filter(d=>!fe(d,a));f.length>0&&s.push(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)}));let m=xs(t);if(m.length>0){let d=m[0]??"this layer";s.push(ne("CONFIG_LAYER_MISSING_OWNER",`${d} has no owner. Add a GitHub handle or email to layers[].owners so this house has a name on the door.`,{layers:m,nextAction:Ts(d)}))}return s}i(an,"collectAnalysisConfigWarnings");function No(e,t){let n=e.ruleId==="ARKRULE_STRUCTURE",r=e.ruleId==="ARKRULE_SCOPE_EMPTY",o=e.ruleId==="INVARIANT_CATALOG_EMPTY";return{ruleId:e.ruleId,file:e.file,line:e.line,message:e.message,fromLayer:e.fromLayer,arkruleId:e.arkruleId,arkruleSource:e.arkruleSource,...n?{sensor:e.sensor,code:e.code,target:ro({sensor:e.sensor,code:e.code})}:{},...r||o?{freezable:!1}:{},nextAction:t}}i(No,"toArkRuleEngineViolation");function Pc(e){let t=e.arkRules;return!!(t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0)}i(Pc,"arkRulesMapIsOn");function wo(e,t){return e.ruleId==="INVARIANT_CATALOG_EMPTY"?t?`Add 1\u20132 short phrases to invariants[] in ${e.arkruleSource} so Domain has policies the code must preserve (advisory \u2014 does not fail the merge until a domain structure rule is enforced).`:`Add 1\u20132 short phrases to invariants[] in ${e.arkruleSource} so Domain has policies the code must preserve. Empty catalog fails --strict-merge because a domain structure rule is already enforced.`:e.ruleId==="ARKRULE_SCOPE_EMPTY"?t?`Review appliesTo for ${e.arkruleId} in ${e.arkruleSource} (zero-match scope; advisory). Empty scope is not freezable; promote only after the folder exists.`:`Fix appliesTo globs for ${e.arkruleId} in ${e.arkruleSource} so they match governed files, or remove the rule. ARKRULE_SCOPE_EMPTY is a config diagnostic and is not freezable (even with --force). Land the rule as advisory until the folder exists, then promote.`:t?`Review ArkRule ${e.arkruleId} in ${e.arkruleSource} (advisory).`:`Fix the structure or invariant for ${e.arkruleId} (declared in ${e.arkruleSource}), then preflight again.`}i(wo,"arkRuleFindingNextAction");function Lc(e,t){return t.some(n=>{try{return Re(n).test(e)}catch{return!1}})}i(Lc,"matchesAny");function Dc(e,t){let n=e.contract.config.safety??{},r=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,o=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,s=e.contract.config.dynamicImportAllowlist??[],a=t.safetyUses.filter(A=>A.kind==="ts-suppression").map(({file:A,line:b})=>({file:A,line:b})),c=t.safetyUses.filter(A=>A.kind==="any-cast").map(({file:A,line:b})=>({file:A,line:b})),l=t.safetyUses.filter(A=>(A.kind==="dynamic-import"||A.kind==="dynamic-require")&&!Lc(A.file,s)).map(A=>({file:A.file,line:A.line,kind:A.kind==="dynamic-require"?"require":"import"})),u=n.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(A=>A.kind==="in-memory-store").map(A=>({file:A.file,line:A.line,store:A.symbol??"in-memory store"})),p=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})),g={tsSuppressions:a,anyCasts:c,nonLiteralDynamicImports:l,inMemoryProductionStores:u,disabledPeerIsolationRules:p,thresholds:{maxTsSuppressions:r,maxAnyCasts:o}},f=[],m=l.filter(A=>A.kind==="import");if(m.length>0){let A=m[0];f.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:A.file,line:A.line,message:`${m.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let d=l.filter(A=>A.kind==="require");if(d.length>0){let A=d[0];f.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:A.file,line:A.line,message:`${d.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(a.length>r){let A=a[0];f.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:A.file,line:A.line,message:`${a.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${r}).`})}if(c.length>o){let A=c[0];f.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:A.file,line:A.line,message:`${c.length} explicit any cast(s) exceed safety.maxAnyCasts (${o}).`})}if(u.length>0){let A=u[0];f.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:A.file,line:A.line,message:`${u.length} ArkGate InMemory store risk(s) appear in governed production source. Provide durable stores or set safety.allowInMemory only for an explicitly ephemeral service.`})}return p.length>0&&f.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${p.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:g,warnings:f}}i(Dc,"evaluateSafety");function Mc(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}i(Mc,"ambientForbiddenGlobal");function Po(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return Dn(e,n.length>0?n:Ln.map(r=>({name:r.layer,prefixes:r.prefixes})))}i(Po,"intentLayer");function Fc(e,t,n){let r=[],o=new Map(e.contract.config.layers.map(s=>[s.name,s]));for(let s of t.ambientUses){let a=n.get(s.file);!a||!Mc(s.symbol,o.get(a)?.forbiddenGlobals??[])||r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:a,target:s.symbol,message:`${a} must not use the ambient global "${s.symbol}".`})}for(let s of t.capabilityUses){let a=n.get(s.file);if(!a)continue;let c=o.get(a),l=c?.forbiddenGlobals??[],u=s.source==="import-based"?t.dependencies.find(p=>p.from===s.file&&p.line===s.line&&p.specifier===s.symbol&&!p.typeOnly)?.kind:void 0;if(!(s.source==="ambient-global"&&ot(s.symbol,l))){if(s.source==="import-based"){let p=Ce(s.symbol,l);if(p){r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:a,target:s.symbol,...u?{edgeKind:u}:{},message:`${a} must not use module "${s.symbol}" because it is the import form of forbidden global "${p}".`});continue}}je(c).includes(s.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:s.file,line:s.line,fromLayer:a,target:s.symbol,capability:s.capability,...u?{edgeKind:u}:{},message:s.source==="import-based"?`${a} denies the ${s.capability} capability; found import of "${s.symbol}".`:`${a} denies the ${s.capability} capability; found ambient "${s.symbol}".`})}}for(let s of t.publishCalls){let a=n.get(s.file);if(!a)continue;for(let l of at({publishCall:!0,rawIntentName:s.rawIntentName,objectHasIntent:s.objectHasIntent,arkPublishCandidate:s.arkPublishCandidate,hasSource:s.hasSource}))r.push({ruleId:l.ruleId,file:s.file,line:s.line,...l.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:a}:{},message:l.message});if(!s.sourceIntent)continue;let c=Po(s.sourceIntent,e.contract);!c||c===a||r.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:s.file,line:s.line,fromLayer:a,toLayer:c,target:s.sourceIntent,message:`Publish source "${s.sourceIntent}" resolves to ${c}, but the publishing file is classified as ${a}.`})}for(let s of t.intentReferences){let a=n.get(s.file);if(!a)continue;let c=Po(s.intent,e.contract);if(!c)continue;let l=Te(e.contract.config.rules,a,c,{fromPath:s.file,layers:e.contract.config.layers});if(!l)continue;let u=l.rule.peerIsolation?Ke(l.peerIsolationReason??"cross-slice",{fromPath:s.file,fromSlice:l.fromSlice,toSlice:l.toSlice}):void 0,p=`${a} must not reference ${c} intent ${s.intent}.`,g=u&&l.peerIsolationReason!=="cross-slice"?`${p} ${u}`:l.rule.message?u?`${l.rule.message} (${u})`:l.rule.message:p;r.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:s.file,line:s.line,fromLayer:a,toLayer:c,target:s.intent,...l.rule.peerIsolation?{peerIsolation:!0}:{},message:g})}return r}i(Fc,"contentViolations");function $c(e){let{facts:t}=e,n=pt(e.contract.config),r=t.evidenceRequirementsHash===n,o=r?t.completeness:"unavailable",s=r?t.completenessReasons:[...t.completenessReasons,{code:"EVIDENCE_REQUIREMENTS_MISMATCH",message:"Resolved facts were collected for different policy-controlled evidence requirements."}].sort((h,oe)=>{let et=`${h.code}\0${h.file??""}\0${h.message}`,tt=`${oe.code}\0${oe.file??""}\0${oe.message}`;return et<tt?-1:et>tt?1:0}),a=t.files.map(h=>({...h,layer:fe(h.path,e.contract.config.layers)??null})),c=new Map(a.map(h=>[h.path,h.layer])),l=t.dependencies.map(h=>{let oe=h.target?c.get(h.target)??fe(h.target,e.contract.config.layers):void 0;return{from:h.from,fromLayer:c.get(h.from)??null,...h.resolution==="resolved-project"&&h.target?{to:h.target,...oe?{toLayer:oe}:{}}:{},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}:{}}}),u=an({config:e.contract.config,rules:e.contract.config.rules,files:a.map(h=>h.path)}),p=Dc(e,t),g=e.contract.arkRules??De(),f=a.map(h=>h.path),d={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?yr(e.coverageInputs.fileContents):{},...e.fileHints??{}},A=i(h=>c.get(h)??fe(h,e.contract.config.layers),"resolveLayer"),b=[...mr({arkRules:g,classShapes:e.contract.classShapes??t.classShapes??[],files:f,layerForFile:A,fileHints:d}),...gr(g,f),...go({arkRulesActive:Pc(e.contract.config),arkRules:g,layers:e.contract.config.layers??[],files:f.map(h=>({path:h,layer:A(h)}))})],O=(g.invariants?.length??0)>0,k=Bs({hasEnforcedInvariant:tr(g.invariants),coverage:e.contract.config.coverage,...e.coverageRootsPresent===!1?{declaredPathPresent:!1}:{}}),I=k.length>0?[]:Gs({adopted:e.adopted===!0,hasDomainInvariants:er(g.invariants),coverage:e.contract.config.coverage,...e.invariantTestsPathPresent===!1?{declaredPathPresent:!1}:{}}),C=[...k.map(h=>({ruleId:h.ruleId,file:h.file,line:h.line,message:h.message,nextAction:"Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. An enforced invariant fails closed until that path is present.",failsStrict:!0,freezable:!1})),...I.map(h=>({ruleId:h.ruleId,file:h.file,line:h.line,message:h.message,nextAction:"Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present.",failsStrict:!0,freezable:!1}))],L=b.filter(h=>h.failsStrict).map(h=>No(h,wo(h,!1))),E=b.filter(h=>!h.failsStrict).map(h=>({...No(h,wo(h,!0)),failsStrict:!1})),P=O?Zn({arkRules:g,fileContents:e.coverageInputs?.fileContents??{},testFiles:e.coverageInputs?.testFiles??[],testGlobsMissing:e.coverageInputs?.testGlobsMissing===!0||e.coverageInputs===void 0||(e.coverageInputs.testFiles?.length??0)===0,coverageBudgetExhausted:e.coverageInputs?.coverageBudgetExhausted===!0,...e.coverageInputs?.stats?{coverageStats:e.coverageInputs.stats}:{},...e.coverageInputs?.coverageRoots?{coverageRoots:e.coverageInputs.coverageRoots}:{}}):{coverage:[],violations:[],partial:!1},ee=P.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.`})),T=P.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:h.ruleId==="INVARIANT_COVERAGE_OUTSIDE_ROOTS"?`Move ${h.file} under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json.`:`Cover invariant ${h.arkruleId} in ${h.arkruleSource} (advisory / partial).`})),V=Ar(a),D=on({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=>c.get(h)??fe(h,e.contract.config.layers),"layerForFile"),classification:V}),se=e.contract.config.arkRun?.mode,J=D.findings.filter(()=>se==="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}:{}})),be=D.findings.filter(()=>se!=="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})),Ae=xr({arkOrder:e.contract.config.arkOrder,layers:e.contract.config.layers,planeCalls:t.arkOrderPlaneCalls,genericUpdates:t.arkOrderGenericUpdates,planeRootHits:t.arkOrderRootHits,xiFieldWrites:t.arkOrderXiFieldWrites,ingestWritesXi:t.arkOrderIngestWritesXi,releaseKeyCounts:t.arkOrderReleaseKeyCounts,dependencies:t.dependencies,layerForFile:i(h=>c.get(h)??fe(h,e.contract.config.layers),"layerForFile"),classification:V}),Qe=e.contract.config.arkOrder?.mode,Tt=Ae.findings.filter(()=>Qe==="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}:{}})),Xr=Ae.findings.filter(()=>Qe!=="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})),v=[...P.partial&&P.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."}]:[],...D.completenessReasons,...Ae.completenessReasons],_=Ye({config:e.contract.config,rules:e.contract.config.rules,files:a.filter(h=>h.layer).map(h=>h.path),contentViolations:[...Fc(e,t,c),...L,...C,...ee,...J,...Tt],edges:l,warnings:[...u,...p.warnings,...E,...T,...be,...Xr],safety:p.report}),y=o==="complete"&&v.length>0?"partial":o,R=y==="complete"?s:[...s,...v].sort((h,oe)=>{let et=`${h.code}\0${h.file??""}\0${h.message}`,tt=`${oe.code}\0${oe.file??""}\0${oe.message}`;return et<tt?-1:et>tt?1:0}),M=_.violations.filter(h=>h.failsStrict!==!1),Y=y==="complete"&&M.length===0,ve=Y&&_.warnings.every(h=>h.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:y,completenessReasons:R,valid:Y,strictValid:ve,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:p.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:a,layers:e.contract.config.layers.map(h=>h.name),edges:l,capabilityUses:t.capabilityUses,violations:_.violations,warnings:_.warnings}}}i($c,"analyzeCanonicalResolvedProject");function vt(e){return $c({contract:e.contract,facts:_e(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints,adopted:e.adopted,invariantTestsPathPresent:e.invariantTestsPathPresent,coverageRootsPresent:e.coverageRootsPresent})}i(vt,"analyzeResolvedProject");function Lo(e){return X(H(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}i(Lo,"analysisTreeHash");function Do(e){let t=Rt(e),n=new Map(t.ir.files.map(d=>[d.path,d])),r=[],o=new Set,s=[];for(let d of e.changes){let A=d.path.replace(/\\/g,"/"),b=Me(d.path);if(!b||b===".."||b.startsWith("../")||A.startsWith("/")||/^[A-Za-z]:\//.test(A)||A.includes("\0")){s.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(o.has(b)){s.push({ruleId:"DUPLICATE_CHANGE_PATH",file:b,line:1,message:`The atomic change set contains more than one operation for ${b}.`});continue}o.add(b),"delete"in d&&d.delete&&!n.has(b)&&s.push({ruleId:"DELETE_TARGET_MISSING",file:b,line:1,message:`Cannot delete ${b} because it is not present in the supplied base tree.`}),r.push("delete"in d&&d.delete?{path:b,delete:!0}:{path:b,content:"content"in d?d.content:""})}e.changes.length===0&&s.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let a=Qt({...e,changes:r}),c=new Map(a.ir.files.map(d=>[d.path,d])),l=a.ir.violations.filter(d=>d.ruleId==="CAPABILITY_VIOLATION"||d.ruleId==="FORBIDDEN_GLOBAL").map(d=>{let A=c.get(d.evidence.file)?.layer;return{ruleId:d.ruleId,file:d.evidence.file,line:d.evidence.line,target:d.symbol,...d.capability?{capability:d.capability}:{},...A?{fromLayer:A}:{},edgeKind:"import",message:d.message}}),u=Ye({config:e.contract.config,rules:e.contract.config.rules,files:a.ir.files.map(d=>d.path),contentViolations:l,edges:a.ir.edges.filter(d=>!!d.fromLayer).map(d=>({from:d.from,fromLayer:d.fromLayer,...d.to?{to:d.to}:{},...d.toLayer?{toLayer:d.toLayer}:{},line:d.evidence.line,kind:"import",...d.typeOnly?{typeOnly:!0}:{},...d.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),p=r.map(d=>{let A=Me(d.path),b=n.get(A),O=c.get(A);return{path:A,operation:"delete"in d&&d.delete?"delete":b?"update":"create",...b?{beforeContentHash:b.contentHash}:{},...O?{candidateContentHash:O.contentHash}:{}}}).sort((d,A)=>d.path.localeCompare(A.path)),g=[...s,...u.violations].map(d=>({...d,nextAction:ge(d)})),f=g.filter(d=>d.failsStrict!==!1),m=e.changeMap?qe({changeMap:e.changeMap,changes:p,baseDependencies:t.ir.edges.flatMap(d=>d.to?[{from:d.from,to:d.to}]:[]),candidateDependencies:a.ir.edges.flatMap(d=>d.to?[{from:d.from,to:d.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&a.valid&&f.length===0&&(m?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:a.ir.compilerOptionsHash,baseTreeHash:Lo(t.ir.files),candidateTreeHash:Lo(a.ir.files),baseCompleteness:t.completeness,candidateCompleteness:a.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:a.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...m?{convergence:m}:{},changes:p,violations:g,warnings:u.warnings}}i(Do,"preflightChange");function Hc(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let o of t.split("/"))if(!(!o||o==="."))if(o===".."){if(n.length===0)return;n.pop()}else n.push(o);let r=n.join("/");return r&&r===t?r:void 0}i(Hc,"canonicalChangePath");function jc(e,t){return[["resolverIdentity",e.resolverIdentity,t.resolverIdentity],["compilerIdentity",e.compilerIdentity,t.compilerIdentity],["evidenceRequirementsHash",e.evidenceRequirementsHash,t.evidenceRequirementsHash],["projectPackageName",e.projectPackageName??"",t.projectPackageName??""]].filter(([,r,o])=>r!==o).map(([r,o,s])=>({ruleId:"FACTS_IDENTITY_MISMATCH",file:"<change-set>",line:1,field:r,before:o,candidate:s,message:`Base and candidate facts must use the same ${r}.`}))}i(jc,"identityViolations");function Kc(e,t,n,r){let o=n.get(t),s=r.get(t);return{path:t,operation:"delete"in e&&e.delete?"delete":o?"update":"create",...o?{beforeContentHash:o.contentHash}:{},...s?{candidateContentHash:s.contentHash}:{}}}i(Kc,"preparedChange");function Mo(e){let t=_e(e.baseFacts),n=_e(e.candidateFacts),r=vt({contract:e.contract,facts:t}),o=vt({contract:e.contract,facts:n}),s=new Map(t.files.map(m=>[m.path,m])),a=new Map(n.files.map(m=>[m.path,m])),c=jc(t,n),l=new Map,u=[];for(let m of e.changes){let d=Hc(m.path);if(!d){c.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(l.has(d)){c.push({ruleId:"DUPLICATE_CHANGE_PATH",file:d,line:1,message:`The atomic change set contains more than one operation for ${d}.`});continue}l.set(d,m);let A=s.get(d),b=a.get(d);if("delete"in m&&m.delete)A||c.push({ruleId:"DELETE_TARGET_MISSING",file:d,line:1,message:`Cannot delete ${d} because it is not present in the supplied base facts.`}),b&&c.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:d,line:1,message:`Candidate facts still contain deleted file ${d}.`});else{let O="content"in m?m.content:"",k=X(O);b?b.contentHash!==k&&c.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:d,line:1,expectedContentHash:k,candidateContentHash:b.contentHash,message:`Candidate facts for ${d} do not match the declared content.`}):c.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:d,line:1,message:`Candidate facts do not contain changed file ${d}.`})}u.push(Kc(m,d,s,a))}e.changes.length===0&&c.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});for(let m of new Set([...s.keys(),...a.keys()])){if(l.has(m))continue;let d=s.get(m),A=a.get(m);d&&A&&H(d)===H(A)||c.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:m,line:1,message:`Candidate facts change ${m}, but the atomic change set does not declare it.`})}let p=e.changeMap?qe({changeMap:e.changeMap,changes:u,baseDependencies:r.ir.edges.flatMap(m=>m.to?[{from:m.from,to:m.to}]:[]),candidateDependencies:o.ir.edges.flatMap(m=>m.to?[{from:m.from,to:m.to}]:[])}):void 0,g=[...c,...o.ir.violations].map(m=>({...m,nextAction:ge(m)})),f=g.filter(m=>m.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&o.strictValid&&f.length===0&&(p?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,resolverIdentity:n.resolverIdentity,compilerIdentity:n.compilerIdentity,compilerOptionsHash:n.compilerOptionsHash,tsconfigHash:n.tsconfigHash,baseCompilerOptionsHash:t.compilerOptionsHash,candidateCompilerOptionsHash:n.compilerOptionsHash,baseTsconfigHash:t.tsconfigHash,candidateTsconfigHash:n.tsconfigHash,evidenceRequirementsHash:n.evidenceRequirementsHash,baseFactsHash:t.factsHash,candidateFactsHash:n.factsHash,baseTreeHash:t.candidateTreeHash,candidateTreeHash:n.candidateTreeHash,baseCompleteness:r.completeness,candidateCompleteness:o.completeness,baseCompletenessReasons:r.completenessReasons,candidateCompletenessReasons:o.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...p?{convergence:p}:{},changes:u.sort((m,d)=>m.path<d.path?-1:m.path>d.path?1:0),violations:g,warnings:o.ir.warnings}}i(Mo,"preflightResolvedChange");var Fo="1.0",Vc=12,Uc="Layers stop a bad import. ArkRun is an optional experimental runtime \u2014 in-memory, not Postgres. Data is gone on restart.",Gc="Next: /ark-runtime to wire one candidate.";function $o(e){return e==="enforced"||e==="advisory"?e:null}i($o,"closedMode");function Bc(e){let t=new Set;if(!Array.isArray(e))return[];for(let n of e){let r=n?.ruleId;typeof r!="string"||!Rr(r)||t.has(r)||t.add(r)}return[...t].sort((n,r)=>n<r?-1:n>r?1:0)}i(Bc,"uniqueArkRunRuleIds");function zc(e){return!e||typeof e!="object"?{present:!1,mode:null,roots:0,layers:0,requireDeclarations:null}:{present:!0,mode:$o(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(zc,"extraFromConfig");function Wc(e={}){let t=zc(e.arkRun),n=t.present?Bc(e.findings):[],r=n.slice(0,Vc),o=n.length,s=rn({classification:e.classification,arkRules:{active:e.arkRules?.active===!0,structureEnforced:e.arkRules?.structureEnforced,structureTotal:e.arkRules?.structureTotal,structureAdvisory:e.arkRules?.structureAdvisory,invariantEnforced:e.arkRules?.invariantEnforced,invariantTotal:e.arkRules?.invariantTotal,invariantAdvisory:e.arkRules?.invariantAdvisory,covered:e.arkRules?.covered,uncovered:e.arkRules?.uncovered},arkRun:{present:t.present,mode:t.mode,residualCount:o}}),a=t.present&&t.mode==="enforced"&&he(e.classification),c;return t.present?t.mode==="advisory"?c="Advisory ArkRun residual only \u2014 never flips valid or --strict-merge. Residual is a finding-id count, never a score.":a?c="Enforced ArkRun is on the extra merge plane. Residual is a finding-id count, never a score.":c="Enforced ArkRun extra teeth stay demoted until the layer plane is honestly classified. Residual is a finding-id count, never a score.":c="Absence of arkRun is silent \u2014 Layers and ArkRules verdicts unchanged. Not a score.",{schemaVersion:Fo,notAScore:!0,active:t.present,mode:t.mode,compositionRoots:t.roots,managedLayers:t.layers,requireDeclarations:t.requireDeclarations,residual:{count:o,ruleIds:r},extraMergeTeeth:a,failMergeWhen:s.failMergeWhen,note:c,mergePlanes:s}}i(Wc,"summarizeArkRunSection");function Tr(e={}){let t=e.present===!0,n=$o(e.mode),r=e.residual,o=null;return typeof r=="number"&&Number.isFinite(r)&&r>=0&&(o=Math.floor(r)),t||(o=o??0),{notAScore:!0,present:t,mode:t?n:null,extraMergeTeeth:t&&n==="enforced"&&e.extraMergeTeeth===!0,residual:o}}i(Tr,"projectStatusArkRun");function qc(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=[Uc,`mode: ${t} \xB7 extra merge teeth ${n} \xB7 not a score`];if(e.residual.count>0){let o=e.residual.ruleIds.join(", "),s=e.residual.count>e.residual.ruleIds.length?` (+${e.residual.count-e.residual.ruleIds.length} more)`:"";r.push(`Residual: ${o}${s}`),r.push(Gc)}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(qc,"formatArkRunDoctorLines");function ln(e,t){return e.slice(0,t).split(`
|
|
13
|
-
`).length}i(ln,"lineOf");function Ho(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}i(Ho,"normalizeInventoryPath");function Ko(e,t){return e.some(n=>{let r=n.trim().replace(/\.+$/,"");return t.some(o=>r===o||r.startsWith(`${o}.`))})}i(Ko,"ownsIntent");function jo(e,t=[]){return/domain|entity|aggregate|model/i.test(e)||Ko(t,["Domain"])}i(jo,"isDomainLayer");function Yc(e,t=[]){return/application|orchestration|presentation|adapter|framework|interface|delivery|transport|inbound|controller/i.test(e)||Ko(t,["Application","Orchestration","Presentation","Adapter","Interface","Delivery","Transport"])}i(Yc,"isControllerEligibleLayer");function Jc(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(Jc,"isNonPilotSurface");function Xc(e){let t=[],n=0,r=new Map(Object.entries(e.fileLayers??{}).map(([l,u])=>[Ho(l),u])),o=new Map((e.layerContexts??[]).map(l=>[l.name,l.intentPrefixes??[]])),s=(e.layerContexts??[]).find(l=>jo(l.name,l.intentPrefixes))?.name??"DomainModel";for(let[l,u]of Object.entries(e.fileContents).sort(([p],[g])=>p.localeCompare(g))){let p=Ho(l);if(Jc(p)||/GENERATED FILE\s+[—-]\s+do not edit by hand/i.test(u.slice(0,320)))continue;let g=r.has(p),f=r.get(p),m=f?o.get(f)??[]:[],d=/(?:^|\/)(?:components|ui|layouts|styles|hooks|theme|tokens|i18n|locales?)(?:\/|$)/i.test(p)||/(?:^|\/)(?:src\/)?(?:app|pages)\/.+\.(?:tsx|jsx)$/i.test(p)&&/(?:page|layout|loading|error|template|default)\.(?:tsx|jsx)$/i.test(p),A=/(?:^|\/)(?:app|pages)(?:\/[^/]+)*\/api(?:\/|$)/i.test(p),b=/(?:^|\/)actions?(?:\/|\.|$)/i.test(p)||/['"]use server['"]/.test(u),O=/controller|handler|resolver/i.test(l)||A||b||/route\.(?:ts|js|tsx|jsx)$/i.test(p)&&!d||/@(Controller|Get|Post|Put|Delete|Patch)\b/.test(u)||/\bexport\s+(?:async\s+)?function\s+(?:GET|POST|PUT|DELETE|PATCH)\b/.test(u)||/\bexport\s+const\s+(?:GET|POST|PUT|DELETE|PATCH)\s*=/.test(u),k=g?!!(f&&Yc(f,m)&&O):O,I=g?!!(f&&jo(f,m)):/domain|entity|aggregate|model/i.test(l),C=!g||I||k;if(k&&!d){let T=/\b(if\s*\([^)]{0,80}(amount|total|price|qty|quantity|balance)[^)]{0,40}\)|throw new (Error|BadRequest|ValidationError)|z\.object\(|yup\.|class-validator|@Is[A-Z])/g,V;for(;(V=T.exec(u))!==null;)n+=1,t.push({id:`inv-val-${n}`,kind:"validation-in-controller",file:l,line:ln(u,V.index),message:"Business validation appears in a controller/handler \u2014 extract an invariant or Domain rule.",confidence:"direct-evidence",governedLayer:f,suggestedArkRule:{layer:s,invariantId:`INV-EXTRACT-${n}`,sensor:"invariant-coverage"},neverMechanicalSafe:!0})}let L=/\b(const|let)\s+([A-Z][A-Z0-9_]{2,})\s*=\s*(\d{2,}|['"][^'"]{8,}['"])/g,E,P=i(T=>/^(?:TEST|SPEC|TIMEOUT|PORT|VERSION|MAX_RETRY|MIN_RETRY|TTL|CACHE|HEADER|COOKIE|MIME|CONTENT_TYPE|HTTP_STATUS|NODE_ENV|LOG_LEVEL|FEATURE_FLAG|ID_PREFIX|Z_INDEX)(?:_|$)/i.test(T)||/^(?:ROUTE|PATH|LABEL|TITLE|HEADING|CLASS|STYLE|COLOR|THEME|BREAKPOINT|QUERY|PARAM|ICON|ARIA|MSG|COPY|I18N|LOCALE|PAGE|NAV|MENU|TAB|BTN|BUTTON|PLACEHOLDER|TOOLTIP|SHADOW|RADIUS|GAP|PADDING|MARGIN|FONT|WIDTH|HEIGHT|OPACITY|DURATION|EASE|ANIM)_/i.test(T)||/_(?:ROUTE|PATH|LABEL|TITLE|COLOR|THEME|CLASS|STYLE|ICON|ARIA|MSG|COPY|TIMEOUT|PORT|VERSION|RETRY|DELAY|INTERVAL|TTL|CACHE)$/i.test(T)||/_(?:TIMEOUT(?:_MS)?|MS|BYTES|BUCKET|STORAGE_KEY|WINDOW_MS)$/i.test(T)||/^(?:DEFAULT_(?:BASE_URL|TIMEOUT(?:_MS)?|RETRY|PORT|HOST|HEADERS?|CACHE|TTL|MS|LOCALE|LANG|TIMEZONE|TZ)|REQUEST_(?:TIMEOUT(?:_MS)?|HEADERS?|RETRY|ID_PREFIX)|STORAGE_(?:KEY|PREFIX|BUCKET)|DAY_MS$|APP_DOMAIN$|BASE_URL$)$/i.test(T)||/^(?:FAVORITES_STORAGE|LISTINGS_CACHE|DOCS_PATH|METRICS_INTERVAL)/i.test(T)||/^(?:DEV|DEMO|SEED|FIXTURE)_[A-Z0-9_]+$/i.test(T)||/^(?:PG|POSTGRES|OID)_[A-Z0-9_]+$/i.test(T)||/_(?:OID|OIDS)$/i.test(T)||/^(?:INT2|INT4|INT8|FLOAT4|FLOAT8|NUMERIC|DATE|TIME|TIMESTAMP|TIMESTAMPTZ|JSON|JSONB|UUID)OID$/i.test(T)||/(?:^|_)(?:SCHEMA|PROTOCOL|RESOLVER|FORMAT)_(?:URL|URI|VERSION|ID|IDENTITY)$/i.test(T),"isInfraMagicName"),ee=i((T,V)=>{if(/^(?:ERROR|SUCCESS|WARNING|INFO|HINT|HELP|EMPTY|TOAST|SNACK|ALERT|BANNER|DIALOG|MODAL|TOOLTIP|CAPTION|SUBTITLE|HEADLINE|USER|UI|DISPLAY|FEEDBACK)_(?:MSG|MESSAGE|TEXT|COPY|LABEL|TITLE|BODY|DESC|DESCRIPTION|HINT|HELP)?/i.test(T)||/_(?:MSG|MESSAGE|TEXT|COPY|TOAST|SNACK|ALERT|BANNER|CAPTION|HINT|HELP_TEXT|ERROR_TEXT|EMPTY_TEXT|PLACEHOLDER_TEXT|USER_MESSAGE|FEEDBACK)$/i.test(T))return!0;let D=V.replace(/^['"]|['"]$/g,"");return!!(/^['"]/.test(V)&&(/\s/.test(D)||/[.!?…]$/.test(D))&&!/^(?:STATUS|STATE|PHASE|ROLE|TYPE|KIND|ORDER|PAYMENT|CART|INVOICE|POLICY)_[A-Z0-9_]+$/i.test(T))},"isUxMessageConstant");for(;(E=L.exec(u))!==null;){let T=E[2],V=E[3]??"";!C||P(T)||ee(T,V)||d&&!I||/(?:^|\/)(?:integrations?|repos?|clients?|infra(?:structure)?|adapters?)(?:\/|$)/i.test(p)&&!I||(n+=1,t.push({id:`inv-magic-${n}`,kind:"magic-business-constant",file:l,line:ln(u,E.index),message:`Magic business constant ${T} may belong in a Domain policy or invariant catalog.`,confidence:"heuristic",governedLayer:f,suggestedArkRule:{layer:s,invariantId:`INV-${T}`},neverMechanicalSafe:!0}))}if(I){let T=/export\s+class\s+([A-Za-z_][A-Za-z0-9_]*)\s*\{([^}]{0,800})\}/g,V;for(;(V=T.exec(u))!==null;){let D=V[2]??"",se=(D.match(/\b[a-zA-Z_][a-zA-Z0-9_]*\s*\(/g)??[]).length;(D.match(/:\s*[A-Za-z]/g)??[]).length>=2&&se<=1&&(n+=1,t.push({id:`inv-anemic-${n}`,kind:"anemic-entity",file:l,line:ln(u,V.index),message:`Class ${V[1]} looks anemic (data-heavy, few behaviors).`,confidence:"heuristic",governedLayer:f,suggestedArkRule:{layer:s,structureId:"no-anemic-model",sensor:"no-anemic-model"},neverMechanicalSafe:!0}))}}if(I&&!(/\.error\.(?:ts|js|tsx|jsx)$/i.test(p)||/(?:^|\/)[^/]*(?:-access)?\.error\./i.test(p)||/(?:^|\/)errors?(?:\/|$)/i.test(p))){let V=/\bthis\.[A-Za-z_][A-Za-z0-9_]*\s*=(?!=)/g,D;for(;(D=V.exec(u))!==null;){let se=u.lastIndexOf("class ",D.index),J=se>=0?u.indexOf("{",se):-1,be=se>=0&&J>=se&&J<D.index?u.slice(se,J):"";if(/\bextends\s+(?:Error|[A-Za-z_$][A-Za-z0-9_$]*Error)\b/.test(be)||fr(u,D.index))continue;let Ae=u.slice(Math.max(0,D.index-200),D.index+200);if(!dr.test(Ae)&&!ur.test(Ae)){n+=1,t.push({id:`inv-mut-${n}`,kind:"mutation-without-guard",file:l,line:ln(u,D.index),message:`Domain field mutation without nearby ${pr()}.`,confidence:"heuristic",governedLayer:f,suggestedArkRule:{layer:s,structureId:"events-on-mutation",sensor:"domain-event-on-mutation"},neverMechanicalSafe:!0});break}}}}let a=new Set(e.contractedRuleIds??[]);t.sort((l,u)=>+(u.confidence==="direct-evidence")-+(l.confidence==="direct-evidence")||l.file.localeCompare(u.file)||l.line-u.line||l.kind.localeCompare(u.kind)||l.id.localeCompare(u.id));let c=t.filter(l=>l.suggestedArkRule?.invariantId&&a.has(l.suggestedArkRule.invariantId)||l.suggestedArkRule?.structureId&&a.has(l.suggestedArkRule.structureId)).length;return{candidates:t,inventoried:t.length,underContract:c,frozen:(e.frozenKeys??[]).length,notAScore:!0}}i(Xc,"buildRulesInventory");function Zc(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(Zc,"inventoryToExtractionCard");var Qc="1.1";var ed="1.0";var Nr="docs/diagnostics.md",td="1.0";function S(e,t,n,r,o,s){return{ruleId:e,title:n,why:r,fix:o,docsAnchor:e,category:t,...s?.oftenAdvisory?{oftenAdvisory:!0}:{}}}i(S,"entry");var cn=Object.freeze([S("LAYER_IMPORT_VIOLATION","layer","This import is not allowed","This file imported a folder it may not reach. The write doesn\u2019t land. The same check fails the pull request.","Branch by import kind: constants/types/pure \u2192 adopt into DomainModel or SharedKernel (do not invent a port); kernel/events/bootstrap from Persistence \u2192 inject a port or move the map to SharedTypes (Persistence must not emit); define a port only when the target is a real use-case. Type-only edges use `import type`. Then preflight again. Do not weaken the layer rule without a hash-bound policy acknowledgement."),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, 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."),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("ARKRULE_HINT_BUDGET_EXHAUSTED","arkrules","Structural-hint budget exhausted","orchestration-only, thin-adapter, and writes-via-aggregate only evaluate files the hint loader preloaded. When eligible governed files exceed that budget (coverage.maxFiles, default 400 \u2014 there is no arkrules.hintBudget), those sensors never saw the rest of their scope. Enforced + unreviewed is not green. The finding names exact hinted/governed counts and per-sensor reviewed N/M of scope.","Raise coverage.maxFiles in ark.config.json (this cap also bounds structural-hint preload; --doctor names the coupling) so hinted/governed counts match, then re-run with --strict-config. An enforced hint sensor that cannot see its scope fails strict."),S("INVARIANT_CATALOG_EMPTY","arkrules","Domain invariant catalog is empty","ArkRules is on and a Domain-role layer has code, but invariants[] has no phrases the code must preserve. Empty looks like \u201Cdone\u201D until someone fills the catalog.","Add 1\u20132 short phrases to invariants[] in arkrules/<Domain>.json (or the mapped file). Starters show the shape. Advisory unless a domain structure rule is already enforced \u2014 then --strict-merge can refuse. Do not freeze this finding.",{oftenAdvisory:!0}),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. When the message reports an exhausted file budget, raise coverage.maxFiles (or narrow coverage.testGlobs) in ark.config.json."),S("INVARIANT_COVERAGE_OUTSIDE_ROOTS","arkrules","Covering test outside the declared coverage roots","The only test naming this invariant sits outside coverage.coverageRoots \u2014 the places the project declares its runner executes. ArkGate matches declared text and never executes tests, so it cannot tell whether that file is ever run: coverage there is a test that exists, not a test that runs.","Move the test under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json. Advisory: it never fails strict, but promotion to enforced refuses on it.",{oftenAdvisory:!0}),S("INVARIANT_TESTS_PATH_MISSING","arkrules","Domain-invariant tests path missing under adopted","The project is adopted (required CI or explicit advisory) and has domain invariants that want test evidence, but ark.config.json does not name where those tests live. Green coverage without a real tests path is an empty checkbox.","Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present. Not freezable."),S("INVARIANT_COVERAGE_ROOTS_MISSING","arkrules","Coverage roots missing while an invariant is enforced","A catalogued domain invariant is enforced, but ark.config.json does not name coverage.coverageRoots \u2014 the folders where the project says its test runner actually goes. Without that declaration, INVARIANT_COVERAGE_OUTSIDE_ROOTS cannot fire and coverage can certify a test no runner runs.","Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. testGlobs alone is not enough. Fail-closed until that path is present. Not freezable."),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 a big product choice","A call to update/patch/set rewrites a named product choice (like billing plan) as if it were a seat count.","Don't use a generic update. First freeze with release(). Later, propose the change, then apply it."),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, escalate_up, or hold; it never mints a pattern.","Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe."),S("ARKORDER_XI_FIELD_WRITE","arkorder","Big product choice written like a seat count","A use-case writes a named product choice (like billing plan) through a database update. Invoices and seats can flow. That choice cannot.","Keep invoices and seats as events. Change the choice through the valve (proposeRelease then apply), not a generic update."),S("ARKORDER_INFORMATION_BUDGET","arkorder","Projection observes a forbidden kind","h(\u03BE) allowedKinds includes a kind listed in informationBudget.cannotObserve. A scale may not look at what it was told not to see.","Cut that kind from the projector or from cannotObserve, then preflight again. Never mechanical-safe."),S("ARKORDER_XI_TTL","arkorder","Slow key carries a freshness field","\u03BE named ttl/freshUntil/maxAge. Freshness belongs on \u03C3. A slow parameter that expires per transaction is not slow.","Move freshness onto \u03C3 (freshUntil) and keep \u03BE stable, then preflight again. Never mechanical-safe."),S("ARKORDER_STALE_SIGMA","arkorder","\u03C3 is stale","ingest ran after \u03C3.freshUntil (or sigmaMaxAgeMs). \u03BE does not TTL.","Call refreshSigma and ingest again, or proposeRelease then apply(ProposeResult) if the pattern changed. Never mechanical-safe."),S("ARKORDER_UNVALVED_RELEASE","arkorder","Second freeze without the valve","release() already froze the big choice. A later release() with a different value does not land. First freeze is release(); later change is proposeRelease then apply.","Change the choice with proposeRelease then apply. release() is only the first freeze. Never mechanical-safe."),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","This check only saw one file, so it cannot fully prove how the import resolves. The result is provisional \u2014 `ark-check` on the project is the authority.","Run `npx arkgate-check --root . --config ark.config.json` to confirm. Do not call ark_prepare_change from a hook deny."),S("ANALYSIS_COVERS_NO_FILES","analysis","Analysis covered no files","No file matched the contract include and layer patterns under the analyzed root, so the run had nothing to check. Every rule is vacuously satisfied on an empty set: a green here would read exactly like a green over a governed tree while certifying nothing. Usual causes are a --root that is not the tree the contract describes (including a contract found outside the requested root, whose directory is then adopted as the project root), include / exclude patterns that match nothing, or layer patterns written for a different layout.","Point --root at the tree the contract describes, or keep the contract inside that tree, or fix the include / exclude / layer patterns so they match real files \u2014 then re-run `npx arkgate-check --root . --config ark.config.json`. This is a refusal about ArkGate\u2019s own inputs, not a finding about your code; no baseline or policy acknowledgement can suppress it."),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("CONFIG_LAYER_MISSING_OWNER","config","Layer missing owner","requireLayerOwners is on and this layer has no owners. Writes to that house fail closed, like a folder with no name on the door.","Add a GitHub handle or email to that layer\u2019s owners in ark.config.json (/ark-adopt), then re-run. Reserved/allowEmpty houses may stay unnamed. Turn the flag off only if you no longer want owners required."),S("LITERAL_PATH_DRIFT","drift","Literal path moved by a rename","A repo path written inside a string, a comment or a docstring no longer resolves, and the rename set says where it went. Nothing in the gate sees this class: `tsc` resolves imports, not strings, and ESLint does not either, so the rename compiles green and the reference lies afterwards. It appears in four forms \u2014 the tsconfig alias, a relative literal, a path written without the include-root prefix, and prose \u2014 and a hand sweep reliably covers one of them.","Apply the suggested replacement, or re-run `npx arkgate-check --path-drift --base-ref <ref> --write` to apply every writable anchored replacement at once. The rewrite is mechanical and one-directional: the destination comes from the rename, it must itself resolve and be path-shaped, and the token is rewritten in the form the author wrote it in. A destination that leaves the alias root of the literal is reported with the target only and must be rewritten by hand."),S("LITERAL_PATH_UNRESOLVED","drift","Literal path does not resolve","A literal that looks like a repo path does not resolve under this root, and no rename explains where it went. Unlike LITERAL_PATH_DRIFT this is a candidate, not a verdict: with nothing to anchor it, ArkGate cannot tell a dead reference from an illustrative path in a comment, an example in documentation, or a path belonging to another tree.","Read the candidate and decide: fix the path, or leave it. Advisory only \u2014 it never fails a run and is never rewritten by --write, because there is no destination to propose. Run `--path-drift --all` to list the sweep.",{oftenAdvisory:!0}),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.")]),wr=new Map(cn.map(e=>[e.ruleId,e])),nd=Object.freeze(cn.map(e=>e.ruleId));function rd(e){return typeof e=="string"&&e.length>0&&wr.has(e)}i(rd,"isKnownDiagnosticCode");function sd(e){return typeof e!="string"||e.length===0?!1:wr.has(e)?!0:e.startsWith("ARKRULE_")}i(sd,"isCataloguedOrArkRuleFamily");function dn(e){if(!(typeof e!="string"||e.length===0))return wr.get(e)}i(dn,"getDiagnosticCatalogEntry");function Vo(e){return`#${dn(e)?.docsAnchor??e}`}i(Vo,"diagnosticDocsFragment");function od(e){return`${Nr}${Vo(e)}`}i(od,"diagnosticDocsPath");function ad(){return{schemaVersion:"1.0",docsPath:Nr,codes:cn}}i(ad,"serializeDiagnosticCatalog");function id(e){return dn(e)?.fix}i(id,"catalogFixForRuleId");function ld(e){return dn(e)?.why}i(ld,"catalogWhyForRuleId");function cd(e){return e==="enforced"||e==="advisory"?e:null}i(cd,"closedMode");function Uo(e={}){let t=e.present===!0,n=cd(e.mode),r=e.residual,o=null;return typeof r=="number"&&Number.isFinite(r)&&r>=0&&(o=Math.floor(r)),t||(o=o??0),{notAScore:!0,present:t,mode:t?n:null,extraMergeTeeth:t&&n==="enforced"&&e.extraMergeTeeth===!0,residual:o}}i(Uo,"projectStatusArkOrder");var Pr="1.0",Go="https://unpkg.com/arkgate@4/schemas/ark.status-manifest.schema.json",Bo=["full","subset","unavailable"],zo=["doctor-facts","report-snapshot","none"],un={FACTS_UNAVAILABLE:"FACTS_UNAVAILABLE",FACTS_PARTIAL:"FACTS_PARTIAL",NO_SESSION_SNAPSHOT:"NO_SESSION_SNAPSHOT"},Wo=/^sha256:[a-f0-9]{64}$/;function qo(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"||!Wo.test(r)))return{status:"mismatch",authoritative:!1,code:"INVALID_PROJECT_EXPECTATION",message:"project.expectedProjectId must be a sha256:<64 lowercase hex> identity."};if(n===void 0&&r!==void 0)return e.projectId&&r!==e.projectId?{status:"mismatch",authoritative:!1,expectedProjectId:r,code:"PROJECT_ID_MISMATCH",message:`Expected project id ${r}, but this process is bound to ${e.projectId}.`}:{status:"unverified",authoritative:!1,expectedProjectId:r,message:"project.expectedProjectId matched or could not be compared, but expectedRoot is required for an authoritative workspace binding."};let o=e.expectedRootRelation??"unknown";return o==="outside"?{status:"mismatch",authoritative:!1,expectedRoot:n,expectedProjectId:r,code:"PROJECT_ROOT_MISMATCH",message:`Expected workspace ${n}, but this process is bound to ${e.resolvedRoot}.`}:o==="unknown"?{status:"unverified",authoritative:!1,expectedRoot:n,expectedProjectId:r,message:"Could not prove expectedRoot against the resolved project root (stale or incomplete path evidence)."}:o==="descendant"&&r===void 0?{status:"unverified",authoritative:!1,expectedRoot:n,message:`Expected workspace ${n} is inside this project, but an exact project root is required for the initial authoritative handshake.`}:r!==void 0&&e.projectId&&r!==e.projectId?{status:"mismatch",authoritative:!1,expectedRoot:n,expectedProjectId:r,code:"PROJECT_ID_MISMATCH",message:`Expected project id ${r}, but this process is bound to ${e.projectId}.`}:o==="exact"||o==="descendant"&&r&&r===e.projectId?{status:"matched",authoritative:!0,...n?{expectedRoot:n}:{},...r?{expectedProjectId:r}:{}}:{status:"unverified",authoritative:!1,expectedRoot:n,expectedProjectId:r,message:"Project expectation could not be fully verified."}}i(qo,"evaluateStatusBinding");function Yo(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(Yo,"classifyStatusWritePath");function Jo(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(Jo,"defaultHonestLabel");function Xo(e,t,n,r,o){return e.nextActionOverride?.id&&e.nextActionOverride.summary?{id:e.nextActionOverride.id,summary:e.nextActionOverride.summary}:t.status==="mismatch"?{id:"rebind-project-identity",summary:t.message||"Project expectation does not match this process \u2014 call ark_identity / ark status with the correct expectedRoot (and projectId for descendants)."}:t.status==="unverified"&&e.expectation?{id:"complete-identity-handshake",summary:t.message||"Supply project.expectedRoot at the exact project root (and expectedProjectId for descendants) for authoritative status."}:e.resolvedConfigPath?r.verdict==="fail"||(r.activeViolations??0)>0?{id:"fix-active-violations",summary:`Clear ${r.activeViolations??"active"} blocking architecture finding(s), then re-run ark-check (or ark-check --doctor).`}:r.verdict==="incomplete"?{id:"restore-complete-analysis",summary:"Last check was incomplete \u2014 restore TypeScript/analysis inputs and re-run ark-check."}:r.verdict==null&&r.at==null?{id:"run-ark-check",summary:"No last-check snapshot yet \u2014 run ark-check --report (or --doctor) to freeze session evidence."}:n.writePath==="unavailable"?{id:"install-write-path",summary:"Write path is unavailable \u2014 install agent gates for your host (ark start / --install-agent-gates) and keep required CI --strict-merge."}:n.writePath==="advisory"?{id:"keep-ci-merge-hard",summary:"Local write is advisory for this host \u2014 keep a required GitHub status on arkgate-check --strict-merge as the hard merge boundary."}:e.leftoverDesignWork===!0?{id:"map-leftover-design",summary:"Leftover design work remains. Map with /ark-explore, then apply one small refactor with /ark-autopilot. Green imports are not done."}:o.arkRulesLoaded&&(o.frozenResidual??0)>0?{id:"review-arkrules-residual",summary:"ArkRules residual remains frozen \u2014 review inventory debt without claiming a score."}:e.arkRun?.present===!0&&(e.arkRun.residual??0)>0?{id:"review-arkrun-residual",summary:"ArkRun residual remains \u2014 wire kernel usage or declarations through arkgate/runtime. Not a score."}:e.arkOrder?.present===!0&&(e.arkOrder.residual??0)>0?{id:"review-arkorder-residual",summary:"ArkOrder leftover remains \u2014 change that product choice through the valve (proposeRelease then apply), not a generic update. Not a score."}:e.adopted==="required-merge"||e.adopted==="advisory-only-acked"?{id:"stay-enforced",summary:"Contract looks enforceable for this session \u2014 keep writing through the gate and re-check after structural edits."}:{id:"require-ci-merge-status",summary:'Make arkgate-check --strict-merge a required GitHub status, or write .ark/adoption-stance.json with stance: "advisory-only".'}:{id:"run-ark-start",summary:"No ark.config.json found \u2014 run ark start (preview) then ark start --apply."}}i(Xo,"resolveStatusNextAction");function dd(e){let t=typeof e.resolvedRoot=="string"&&e.resolvedRoot.length>0?e.resolvedRoot:".",n=typeof e.projectId=="string"&&Wo.test(e.projectId)?e.projectId:null,r=qo({resolvedRoot:t,projectId:n,expectation:e.expectation,expectedRootRelation:e.expectedRootRelation}),o=typeof e.activeHost=="string"?e.activeHost.trim().toLowerCase():"",s=o&&o!=="unknown"?o:o==="unknown"?"unknown":null,a=Yo({hardWriteActive:e.hardWriteActive,softWriteHost:e.softWriteHost,writePathUnavailable:e.writePathUnavailable,activeHost:s}),c=typeof e.honestLabel=="string"&&e.honestLabel.trim().length>0?e.honestLabel.trim():Jo(a,s),l={at:typeof e.lastCheckAt=="string"?e.lastCheckAt:null,verdict:e.lastCheckVerdict==="pass"||e.lastCheckVerdict==="fail"||e.lastCheckVerdict==="incomplete"?e.lastCheckVerdict:null,activeViolations:Ct(e.activeViolations),frozenResidual:Ct(e.frozenResidual)},u={arkRulesLoaded:e.arkRulesLoaded===!0,inventoried:Ct(e.rulesInventoried),underContract:Ct(e.rulesUnderContract),frozenResidual:Ct(e.rulesFrozenResidual)},p={writePath:a,host:s,honestLabel:c},g={projectId:n,resolvedRoot:t,resolvedConfigPath:typeof e.resolvedConfigPath=="string"&&e.resolvedConfigPath.length>0?e.resolvedConfigPath:null,binding:r.status,authoritative:r.authoritative,...r.code?{code:r.code}:{},...r.message?{message:r.message}:{}},f={schemaVersion:Pr,arkgateVersion:typeof e.arkgateVersion=="string"&&e.arkgateVersion.length>0?e.arkgateVersion:"unknown",projectIdentity:g,activation:p,lastCheck:l,rules:u,nextAction:Xo(e,r,p,l,u)},m=Qo(e.improvementCompass);return m&&(f.improvementCompass=m),e.vsBase&&typeof e.vsBase.baseRef=="string"&&e.vsBase.baseRef.length>0&&(f.vsBase=e.vsBase),e.arkRun&&typeof e.arkRun=="object"&&(f.arkRun=Tr(e.arkRun)),e.arkOrder&&typeof e.arkOrder=="object"&&(f.arkOrder=Uo(e.arkOrder)),f}i(dd,"buildStatusManifest");var Zo=new Set(Bo),ud=new Set(zo);function Lr(e){let t=Zo.has(e.mode)?e.mode:"unavailable",n=e.factsSource!=null&&ud.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:un.FACTS_UNAVAILABLE,reason:typeof e.reason=="string"&&e.reason.length>0?e.reason:"Improvement compass facts are unavailable \u2014 run ark-check --doctor for residual lenses. Status never invents green.",factsSource:n??"none"};return r&&(a.contractHash=r),a}let o=Array.isArray(e.topResidual)?e.topResidual.filter(a=>typeof a=="string"&&a.length>0).slice(0,15):[],s={schemaVersion:"1.0",notAScore:!0,mode:t,topResidual:o};return t==="subset"?(s.reasonCode=typeof e.reasonCode=="string"&&e.reasonCode.length>0?e.reasonCode:un.FACTS_PARTIAL,s.reason=typeof e.reason=="string"&&e.reason.length>0?e.reason:"Status compass is a subset of doctor residual \u2014 incomplete session facts; run doctor for full."):typeof e.reasonCode=="string"&&e.reasonCode.length>0&&(s.reasonCode=e.reasonCode),typeof e.reason=="string"&&e.reason.length>0&&t==="full"&&(s.reason=e.reason),n&&(s.factsSource=n),r&&(s.contractHash=r),s}i(Lr,"projectStatusImprovementCompass");function pd(e={}){return Lr({mode:"unavailable",topResidual:[],reasonCode:e.reasonCode??un.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(pd,"unavailableStatusImprovementCompass");function Qo(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"&&Zo.has(t.mode)?n=t.mode:Array.isArray(t.topResidual)?n="subset":n="unavailable",Lr({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(Qo,"normalizeStatusImprovementCompass");function fd(e,t){let n=Array.isArray(e)?e:[],r=new Set(Array.isArray(t)?t:[]);for(let o of n)if(!(typeof o!="string"||o.length===0)&&!r.has(o))return!1;return!0}i(fd,"statusCompassResidualIsSubsetOfDoctor");function Ct(e){if(e==null)return null;let t=Number(e);return!Number.isFinite(t)||t<0?null:Math.floor(t)}i(Ct,"numberOrNull");var md={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Go,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:Pr},arkgateVersion:{type:"string",minLength:1},projectIdentity:{type:"object",additionalProperties:!1,required:["projectId","resolvedRoot","resolvedConfigPath","binding","authoritative"],properties:{projectId:{anyOf:[{type:"string",pattern:"^sha256:[a-f0-9]{64}$"},{type:"null"}]},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{anyOf:[{type:"string",minLength:1},{type:"null"}]},binding:{enum:["matched","unverified","mismatch"]},authoritative:{type:"boolean"},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},activation:{type:"object",additionalProperties:!1,required:["writePath","host","honestLabel"],properties:{writePath:{enum:["hard","advisory","unavailable"]},host:{anyOf:[{type:"string",minLength:1},{type:"null"}]},honestLabel:{type:"string",minLength:1}}},lastCheck:{type:"object",additionalProperties:!1,required:["at","verdict","activeViolations","frozenResidual"],properties:{at:{anyOf:[{type:"string",minLength:1},{type:"null"}]},verdict:{anyOf:[{enum:["pass","fail","incomplete"]},{type:"null"}]},activeViolations:{anyOf:[{type:"integer",minimum:0},{type:"null"}]},frozenResidual:{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}},rules:{type:"object",additionalProperties:!1,required:["arkRulesLoaded","inventoried","underContract","frozenResidual"],properties:{arkRulesLoaded:{type:"boolean"},inventoried:{anyOf:[{type:"integer",minimum:0},{type:"null"}]},underContract:{anyOf:[{type:"integer",minimum:0},{type:"null"}]},frozenResidual:{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}},nextAction:{type:"object",additionalProperties:!1,required:["id","summary"],properties:{id:{type:"string",minLength:1},summary:{type:"string",minLength:1}}},improvementCompass:{type:"object",description:"Thin improvement-compass residual ids with honesty mode (notAScore). full | subset | unavailable. Never a gate input; full lenses on doctor JSON. When full, residual ids \u2286 doctor residual for the same facts. unavailable never invents green residual.",additionalProperties:!1,required:["schemaVersion","notAScore","mode","topResidual"],properties:{schemaVersion:{const:"1.0"},notAScore:{const:!0},mode:{enum:["full","subset","unavailable"]},topResidual:{type:"array",items:{type:"string",minLength:1},maxItems:15},reasonCode:{type:"string",minLength:1},reason:{type:"string",minLength:1},factsSource:{enum:["doctor-facts","report-snapshot","none"]},contractHash:{type:"string",minLength:1}}},vsBase:{type:"object",description:"Checkout vs a git base ref: pin, contract identity, baseline grow. Advisory honesty only \u2014 never a gate input.",additionalProperties:!1,required:["baseRef","line","pinLocal","pinBase","contractEqual","baselineGrew"],properties:{baseRef:{type:"string",minLength:1},line:{type:"string",minLength:1},pinLocal:{anyOf:[{type:"string",minLength:1},{type:"null"}]},pinBase:{anyOf:[{type:"string",minLength:1},{type:"null"}]},contractEqual:{type:"boolean"},baselineGrew:{type:"boolean"}}},arkRun:{type:"object",description:"ArkRun extra residual (notAScore). present/mode from config; residual is a finding-id count (null = unknown, not green). extraMergeTeeth is honesty, never a score.",additionalProperties:!1,required:["notAScore","present","mode","extraMergeTeeth","residual"],properties:{notAScore:{const:!0},present:{type:"boolean"},mode:{anyOf:[{enum:["advisory","enforced"]},{type:"null"}]},extraMergeTeeth:{type:"boolean"},residual:{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}},arkOrder:{type:"object",description:"ArkOrder extra residual (notAScore). present/mode from config; residual is a finding-id count (null = unknown, not green). extraMergeTeeth is honesty, never a score.",additionalProperties:!1,required:["notAScore","present","mode","extraMergeTeeth","residual"],properties:{notAScore:{const:!0},present:{type:"boolean"},mode:{anyOf:[{enum:["advisory","enforced"]},{type:"null"}]},extraMergeTeeth:{type:"boolean"},residual:{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}}}};var pn="1.0",fn=["soc","cohesion","coupling","srp","dip","ocp","encapsulation","modularity","scalability","resilience","security","maintainability","testability","domain","stack"],mn=5,Fe=["scalability","resilience","security"],Xe=new Set(Fe),Dr={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},Mr={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"},Fr={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 $r(e){return Mr[e]??e}i($r,"improvementCompassHumanLabel");function Hr(e){let t=e.id??e.smellId??"";return typeof t=="string"?t.trim():""}i(Hr,"smellIdOf");function jr(e){let t=e.ruleId??e.code??"";return typeof t=="string"?t.trim():""}i(jr,"violationRuleId");function K(e,t,n,r){if(!n||e.evidence.some(s=>s.source===t&&s.ref===n))return;let o={source:t,ref:n};r&&r.trim()&&(o.detail=r.trim().slice(0,240)),e.evidence.push(o)}i(K,"pushEvidence");function re(e,t,n){Xe.has(e.id)||(e.status="residual",e.summary=t,n&&(e.nextAction=n))}i(re,"markResidual");function ea(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`${Mr[e]} \u2014 no residual from current sensors.`}}i(ea,"defaultOkSummary");function ta(){return fn.map(e=>Xe.has(e)?{id:e,status:"out-of-scope",summary:Fr[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:ea(e),evidence:[]}:{id:e,status:"ok",summary:ea(e),evidence:[]})}i(ta,"createInitialImprovementCompassLenses");function gd(e,t){for(let n of t){let r=Hr(n);if(!r)continue;let o=n.outcome||n.message||void 0,a=(Array.isArray(n.evidence)?n.evidence:[])[0],c=i((p,g,f)=>{let m=e.get(p);!m||Xe.has(p)||(K(m,"designSmells",r,o),a&&K(m,"designSmells",a,r),re(m,g,f))},"attach"),l={kind:"skill",ref:"/ark-explore",summary:"Map Shape residual (shape-focus), then apply one extraction pilot with /ark-autopilot."},u={kind:"skill",ref:"/ark-autopilot",summary:"Inject a port/adapter for I/O; keep domain pure."};switch(r){case"domain-logic-in-ui":c("soc","Business rules still mix with UI or presentation surfaces.",l),c("domain","Domain logic lives outside Domain \u2014 align rules with Domain ownership.",l);break;case"facade-sql-in-routes":c("soc","Routes/controllers own SQL or ORM access \u2014 concerns are mixed.",l),c("dip","Transport depends on concrete persistence instead of a port.",u);break;case"io-under-application":c("soc","Application/business code reaches I/O directly \u2014 separation is weak.",l),c("dip","I/O is not inverted behind ports/adapters.",u),c("testability","Direct I/O under application code hurts pure unit testing.",u);break;case"handler-in-persistence":c("soc","HTTP/transport handlers live under persistence folders.",l);break;case"god-module":c("cohesion","Large multi-responsibility modules reduce cohesion.",l),c("srp","God modules own too many responsibilities \u2014 split by concern (one pilot).",{kind:"skill",ref:"/ark-autopilot",summary:"One Shape pilot this turn \u2014 never multi-pilot batch."});break;case"mixed-pattern-cluster":c("modularity","Multiple layout styles coexist \u2014 placement is unclear for the next AI turn.",{kind:"skill",ref:"/ark-explore",summary:"Pick a golden pattern and migrate one pilot cluster on touch."}),c("cohesion","Mixed layout styles scatter the same concern across patterns.",l);break;case"soft-contract":c("maintainability","Soft contract walls (layers without deny rules) hide maintainability debt.",{kind:"skill",ref:"/ark-adopt",summary:"Add real layer rules so the AI has hard walls."}),c("coupling","Layers with files but almost no deny rules allow free peer coupling.",{kind:"skill",ref:"/ark-adopt",summary:"Tighten inter-layer allows/denies without weakening enforcement."});break;default:c("maintainability","Design residual remains under an unrecognized smell id \u2014 review evidence.",l);break}}}i(gd,"mapDesignSmells");function yd(e){return e.failsStrict===!1||e.typeOnly===!0}i(yd,"isTypeOnlyPlacementDebt");function hd(e,t){for(let n of t){let r=jr(n);if(!r)continue;let o=n.message,s=r.toUpperCase(),a=i((l,u,p)=>{let g=e.get(l);!g||Xe.has(l)||(K(g,"violations",r,o),n.file&&K(g,"violations",n.file,r),re(g,u,p))},"attach");if(yd(n)){a("modularity","Type-only placement debt remains \u2014 prefer SharedTypes / owning layer (not runtime coupling).",{kind:"skill",ref:"/ark-place",summary:"Place shared types in a layer both sides may import; type-only debt is not a value edge."});continue}let c={kind:"skill",ref:"/ark-autopilot",summary:"Clear the active edge residual, then re-doctor."};if(s==="LAYER_IMPORT_VIOLATION"||s.includes("LAYER_IMPORT")||s==="DYNAMIC_IMPORT_VIOLATION"){a("coupling","Import graph edges violate the layer contract.",c);continue}if(s.includes("CYCLE")||s==="CIRCULAR_DEPENDENCY"){a("coupling","Import cycles couple modules tightly.",c);continue}if(s.includes("PEER_ISOLATION")||s==="PEER_ISOLATION_VIOLATION"){a("coupling","Peer isolation residual \u2014 slices import each other freely.",{kind:"skill",ref:"/ark-autopilot",summary:"Peer isolation fixes are judgment-class \u2014 one cluster at a time."});continue}if(s==="FORBIDDEN_GLOBAL"||s.startsWith("FORBIDDEN_")){a("dip","Forbidden globals / effect surfaces break dependency inversion.",{kind:"skill",ref:"/ark-autopilot",summary:"Inject a port instead of the forbidden global."}),a("testability","Forbidden ambient effects reduce pure-domain testability.",{kind:"skill",ref:"/ark-autopilot",summary:"Replace ambient effects with injectable ports."});continue}if(s==="CAPABILITY_VIOLATION"){a("dip","Denied capability use \u2014 invert through an allowed adapter/port.",{kind:"skill",ref:"/ark-autopilot",summary:"Capability walls require port injection (judgment, not mechanical-safe)."}),a("testability","Capability violations couple domain code to I/O \u2014 harder to unit-test.",{kind:"skill",ref:"/ark-autopilot",summary:"Keep pure layers free of denied capabilities."});continue}if(s.startsWith("ARKRULE_")||s==="INVARIANT_UNCOVERED"||s==="INVARIANT_CATALOG_EMPTY"||s==="INVARIANT_TESTS_PATH_MISSING"||s==="INVARIANT_COVERAGE_ROOTS_MISSING"){a("encapsulation","ArkRules structure / invariant residual inside a layer.",{kind:"skill",ref:"/ark-autopilot",summary:"Label [ArkRules]; structure fixes are judgment \u2014 never invent mechanical-safe."}),a("domain","Intra-layer domain structure or invariant coverage residual.",{kind:"skill",ref:"/ark-explore",summary:"Inventory candidates \u2192 one ArkRules pilot with coverage evidence."});continue}}}i(hd,"mapViolations");function Ad(e,t){let n=Number(t.cycleCount)||0;if(n>0){let m=e.get("coupling");K(m,"cycles",`count:${n}`),re(m,"Import cycles couple modules tightly.",{kind:"skill",ref:"/ark-autopilot",summary:"Break cycles with a judgment extraction \u2014 one pilot."})}let r=typeof t.peerIsolationCount=="boolean"?t.peerIsolationCount?1:0:Number(t.peerIsolationCount)||0;if(r>0){let m=e.get("coupling");K(m,"peerIsolation",`count:${r}`),re(m,"Peer isolation residual remains.",{kind:"skill",ref:"/ark-autopilot",summary:"Peer isolation is judgment-class residual."})}let o=Number(t.physicalCohesionFindingCount)||0;if(o>0){let m=e.get("cohesion");K(m,"physicalCohesion",`findings:${o}`),re(m,"Physical cohesion residual \u2014 mirrored concept clusters across anchors.",{kind:"skill",ref:"/ark-explore",summary:"Review reshape pilot; one decision-aware pilot at a time."});let d=e.get("srp");K(d,"physicalCohesion",`findings:${o}`),re(d,"Mirrored clusters suggest split-by-concern residual (architecture SRP).",{kind:"skill",ref:"/ark-autopilot",summary:"One reshape/extraction pilot this turn."})}let s=Number(t.pureOrCapabilityResidual)||0,a=Number(t.forbiddenGlobalResidual)||0;if(s>0||a>0){let m=e.get("dip");s>0&&K(m,"capability",`residual:${s}`),a>0&&K(m,"forbiddenGlobals",`residual:${a}`),re(m,"Pure / capability / forbidden residual weakens dependency inversion.",{kind:"skill",ref:"/ark-autopilot",summary:"Inject ports; keep pure layers free of effects."});let d=e.get("testability");s>0&&K(d,"capability",`residual:${s}`),a>0&&K(d,"forbiddenGlobals",`residual:${a}`),re(d,"Impure domain or capability residual reduces testability.",{kind:"skill",ref:"/ark-autopilot",summary:"Prefer ports over concrete I/O in pure/domain modules."})}let c=Number(t.arkRulesStructureResidual)||0;if(c>0){let m=e.get("encapsulation");K(m,"arkRules",`structureResidual:${c}`),re(m,"ArkRules structure residual \u2014 encapsulation inside the layer.",{kind:"skill",ref:"/ark-autopilot",summary:"Fix structure sensors under [ArkRules] without inventing mechanical-safe."});let d=e.get("domain");K(d,"arkRules",`structureResidual:${c}`),re(d,"ArkRules residual may mean domain shape is not yet under contract.",{kind:"skill",ref:"/ark-explore",summary:"Map inventory candidates; one pilot rule at a time."})}else t.arkRulesLoaded===!1||t.arkRulesLoaded==null;if(t.designWeak===!0){let m=e.get("maintainability");K(m,"designFitness","design-weak"),re(m,"Design-weak: checked edges may be clean, but design residual remains \u2014 not finished.",{kind:"skill",ref:"/ark-explore",summary:"Shape door: explore shape-focus \u2192 dual-plan B \u2192 one /ark-autopilot pilot."})}if(t.dirtyBaselineRisk===!0||(Number(t.baselineStale)||0)>0){let m=e.get("maintainability");t.dirtyBaselineRisk===!0&&K(m,"baseline","dirty-freeze-risk"),(Number(t.baselineStale)||0)>0&&K(m,"baseline",`stale:${t.baselineStale}`),re(m,"Baseline honesty residual \u2014 frozen debt or stale keys need review.",{kind:"command",ref:"ark-check --doctor",summary:"Review baseline freeze honesty; do not freeze new wrong debt."})}let l=Number(t.frozenResidual)||0;if(t.baselineExists===!0&&l>=10&&e.get("maintainability").status!=="residual"){let m=e.get("maintainability");K(m,"baseline",`frozen:${l}`),re(m,"Substantial frozen residual remains under the baseline \u2014 review debt honestly.",{kind:"command",ref:"ark-check --doctor",summary:"Review freezes; do not freeze new wrong debt to clear residual."})}let u=Number(t.ungovernedDirCount)||0,p=Number(t.emptyLayerCount)||0;if(u>0||p>0){let m=e.get("modularity");u>0&&K(m,"coverage",`ungovernedDirs:${u}`),p>0&&K(m,"coverage",`emptyLayers:${p}`),re(m,"Placement / modularity residual \u2014 ungoverned dirs or empty layer globs.",{kind:"skill",ref:"/ark-adopt",summary:"Classify ungoverned paths; fix empty layer patterns."})}if(t.designWeak===!0&&t.goldenPatternPresent===!1){let m=e.get("modularity");K(m,"goldenPattern","absent"),re(m,"Design-weak without a golden pattern \u2014 new code lacks a placement norm for the AI.",{kind:"skill",ref:"/ark-place",summary:"Record an advisory golden pattern for new code (does not clear design-weak)."})}let g=e.get("stack");(t.stackKind??null)==="typescript"?g.status==="ok"&&(g.summary="Stack practices are partially instrumented for TypeScript / host / Ark idioms only \u2014 not a full framework checklist."):(g.status="not-instrumented",g.summary="Stack-specific best practices outside TypeScript/host/Ark idioms are not instrumented.",g.evidence=[],g.nextAction={kind:"docs",ref:"docs/use.md#improvement-compass",summary:"Ark does not score non-TS stack idioms."})}i(Ad,"mapCountsAndFlags");function na(e,t){if(Array.isArray(t.designSmells)&&t.designSmells.length>0){let n=[...t.designSmells].sort((r,o)=>Hr(r).localeCompare(Hr(o)));gd(e,n)}if(Array.isArray(t.violations)&&t.violations.length>0){let n=[...t.violations].sort((r,o)=>{let s=jr(r).localeCompare(jr(o));return s!==0?s:String(r.file??"").localeCompare(String(o.file??""))});hd(e,n)}Ad(e,t)}i(na,"projectImprovementCompassFacts");function ra(e){for(let t of Fe){let n=e.get(t);n.status="out-of-scope",n.summary=Fr[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(ra,"lockImprovementCompassOutOfScope");function sa(e){for(let t of e)t.evidence.sort((n,r)=>{let o=n.source.localeCompare(r.source);return o!==0?o:n.ref.localeCompare(r.ref)})}i(sa,"sortImprovementCompassEvidence");function oa(e){return e.filter(n=>n.status==="residual"&&!Xe.has(n.id)).slice().sort((n,r)=>{let o=Dr[n.id]??150,s=Dr[r.id]??150;return o!==s?o-s:n.id.localeCompare(r.id)}).slice(0,5).map(n=>n.id)}i(oa,"finalizeImprovementCompassTopResidual");function Rd(e={}){let t=ta(),n=new Map(t.map(o=>[o.id,o]));na(n,e),ra(n),sa(t);let r=oa(t);return{schemaVersion:"1.0",notAScore:!0,lenses:t.map(o=>{let s={id:o.id,status:o.status,summary:o.summary,evidence:o.evidence.map(a=>({...a}))};return o.nextAction&&(s.nextAction={...o.nextAction}),s}),topResidual:r}}i(Rd,"buildImprovementCompass");function aa(e){return e.topResidual.map(t=>$r(t))}i(aa,"formatImprovementCompassResidualLabels");function ia(e){for(let t of e.topResidual){let n=e.lenses.find(r=>r.id===t);if(n?.nextAction)return{...n.nextAction}}return null}i(ia,"primaryImprovementCompassNextAction");function kd(e){let t=aa(e),n=Fe.map(s=>$r(s)),r=ia(e),o=[];return t.length>0?o.push(`Residual: ${t.join(" \xB7 ")}`):o.push("Residual: none on instrumented lenses (not a score \u2014 green edges \u2260 finished design)."),o.push(`Out of scope (honest): ${n.join(" \xB7 ")}`),r&&o.push(`Next: ${r.ref} \u2014 ${r.summary}`),o}i(kd,"formatImprovementCompassDoctorLines");var $e="1.0",la="<!-- arkgate:agent-projection:begin",gn="<!-- arkgate:agent-projection:end -->",yn="This projection is **non-authoritative**. Enforcement is `ark-check` / host write hooks / required CI (`--strict-merge`), not AGENTS.md, skills, or this block.",_t=Object.freeze(["ark-check","host-write-hooks","ci-strict-merge"]),ca=Object.freeze(["LAYER_IMPORT_VIOLATION","LAYER_INTENT_REFERENCE_VIOLATION","CIRCULAR_DEPENDENCY","CAPABILITY_VIOLATION","RAW_EVENT_PUBLISH","ARKRULE_STRUCTURE","ATOMIC_PREFLIGHT_UNAVAILABLE","ANALYSIS_PARSE_INCOMPLETE","ARK_UNKNOWN"]);function Ze(e){let t=String(e??"").replace(/\r\n/g,`
|
|
11
|
+
`).length,c={kind:"import",file:e.path,line:a,excerpt:o.excerpt},l=hl(e.path,s,t);n.push({from:e.path,specifier:s,to:l?.path??null,resolution:l?"resolved":"unresolved",fromLayer:e.layer,toLayer:l?.layer??null,evidence:c})}return{edges:n,capabilityUses:r}}i(Qs,"moduleFactsFor");function hl(e,t,n){let r=e.split("/");r.pop();for(let s of t.split("/"))s==="."||s===""||(s===".."?r.pop():r.push(s));let o=r.join("/");for(let s of[o,`${o}.ts`,`${o}.tsx`,`${o}.mts`,`${o}.cts`,`${o}/index.ts`,`${o}/index.tsx`]){let a=n.get(s);if(a)return a}}i(hl,"resolveSpecifier");function eo(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let o=Ht(t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});o&&n.push({ruleId:`layer-dependency:${o.from}->${o.to}`,message:o.message??`${o.from} must not depend on ${o.to}.`,edge:r,evidence:r.evidence})}return n}i(eo,"violationsFor");var Al={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 Rl(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}i(Rl,"hasActiveArkRules");function kl(e,t){return Rl(e,t)?X(H(Jn({config:e,arkRules:t,warnings:[]}))):X(H(Yn(e)))}i(kl,"policyHashFor");function Zt(e,t,n){let r=typeof e=="string"?Vn(e,t):Gt(e,t),o=n?.arkRules??De();return{...r,arkRules:o,policyHash:kl(r.config,o)}}i(Zt,"loadContract");function to(e){let t=Zt(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=Zt(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=or(t.config,n.config,{baseArkRules:t.arkRules,candidateArkRules:n.arkRules,candidateInvariantCoverage:e.candidateInvariantCoverage}),o=r.findings.filter(c=>c.classification==="weakening"||c.classification==="judgment-required").map(c=>c.id).sort(),s=o.length>0,a=s&&ar(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:o});return{schemaVersion:r.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:r.classification,findings:r.findings,blockingFindingIds:o,requiresAcknowledgement:s,acknowledged:a,valid:!s||a}}i(to,"analyzePolicyDelta");function Rt(e){let t=e.files.map(g=>{let f=Me(g.path);return{path:f,content:g.content,contentHash:X(g.content),layer:fe(f,e.contract.config.layers)??null}}).sort((g,f)=>g.path.localeCompare(f.path)),n=new Map(t.map(g=>[g.path,g])),r=[],o=[];for(let g of t){let f=Qs(g,n);r.push(...f.edges),o.push(...f.capabilityUses)}let s=eo(r,e.contract.config),a=new Map(e.contract.config.layers.map(g=>[g.name,g])),c=new Map(e.contract.config.layers.map(g=>[g.name,new Set(je(g))]));for(let g of o){let f=n.get(g.file)?.layer;if(!f)continue;let m=a.get(f),d=Ce(g.symbol,m?.forbiddenGlobals??[]);if(d){s.push({ruleId:"FORBIDDEN_GLOBAL",message:`${f} must not use module "${g.symbol}" because it is the import form of forbidden global "${d}".`,symbol:g.symbol,evidence:g.evidence});continue}c.get(f)?.has(g.capability)&&s.push({ruleId:"CAPABILITY_VIOLATION",message:`${f} denies the ${g.capability} capability; found import of "${g.symbol}".`,capability:g.capability,symbol:g.symbol,evidence:g.evidence})}let l=t.length===0?"complete":"partial",u=l==="complete"?[]:[{...Al}],p={schemaVersion:Bn,policyHash:e.contract.policyHash,compilerOptionsHash:X(H(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(g=>g.name),edges:r,capabilityUses:o,violations:s};return{mode:"lexical-compatibility",completeness:l,completenessReasons:u,valid:l==="complete"&&s.length===0,ir:p}}i(Rt,"analyzeProject");function Qt(e){let t=new Map(e.files.map(n=>[Me(n.path),n]));for(let n of e.changes){let r=Me(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return Rt({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}i(Qt,"analyzeChange");function no(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(no,"explainViolation");function ir(e){let t=0,n=new Map,r=new Map,o=new Set,s=[],a=[],c=i(l=>{n.set(l,t),r.set(l,t),t+=1,s.push(l),o.add(l);for(let g of[...e.get(l)??[]].sort())e.has(g)&&(n.has(g)?o.has(g)&&r.set(l,Math.min(r.get(l)??0,n.get(g)??0)):(c(g),r.set(l,Math.min(r.get(l)??0,r.get(g)??0))));if(r.get(l)!==n.get(l))return;let u=[],p;do{if(p=s.pop(),p===void 0)break;o.delete(p),u.push(p)}while(p!==l);u.length>1&&a.push(u.sort())},"connect");for(let l of[...e.keys()].sort())n.has(l)||c(l);return a.sort((l,u)=>l[0]<u[0]?-1:l[0]>u[0]?1:0).map(l=>({ruleId:"CIRCULAR_DEPENDENCY",file:l[0],line:1,target:l.join(" \u2192 "),message:`Circular dependency among ${l.length} files: ${l.join(" \u2192 ")} \u2192 ${l[0]}.`,cycleKind:"value"}))}i(ir,"detectArchitectureCycles");function Ye(e){let t=e.contentViolations.map(s=>({...s})),n=(e.warnings??[]).map(s=>({...s})),r=new Map(e.files.map(s=>[s,new Set]));for(let s of e.edges){if(s.to&&s.to!==s.from&&!s.typeOnly&&r.has(s.from)&&r.get(s.from)?.add(s.to),!s.to||!s.fromLayer||!s.toLayer)continue;let a=Te(e.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:e.config.layers});if(!a)continue;let c=a.rule,l=!!c.peerIsolation,u=!l&&!!(s.typeOnly||s.namedBindingsTypeOnly),p=l?Ke(a.peerIsolationReason??"cross-slice",{fromPath:s.from,toPath:s.to,fromSlice:a.fromSlice,toSlice:a.toSlice}):void 0,g=c.message?p?`${c.message} (${p})`:c.message:p?`${s.fromLayer} must not ${s.kind} another slice of ${s.toLayer} (${s.from} \u2192 ${s.to}): ${p}`:`${s.fromLayer} must not ${s.kind} ${s.toLayer}.`;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:s.from,line:s.line,fromLayer:s.fromLayer,toLayer:s.toLayer,target:s.to,...s.typeOnly?{typeOnly:!0}:{},...s.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...s.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...s.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!l&&s.portProofEligible?{portProofEligible:!0}:{},...s.kind?{edgeKind:s.kind}:{},...l?{peerIsolation:!0}:{},message:u?`${g} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:g,...u?{failsStrict:!1,severity:"warning"}:{}})}let o=String(e.config.cyclePolicy??"strict").toLowerCase();if(o!=="off"){let s=ir(r);o==="soft"||o==="framework-soft"?n.push(...s.map(a=>({...a,message:`${a.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...s)}return{violations:t,warnings:n,safety:e.safety}}i(Ye,"evaluateArchitectureGraph");function ro(e){if(typeof e.target=="string"&&e.target.length>0)return e.target;let t=String(e.sensor||e.code||"").trim();if(!t&&typeof e.message=="string"){let r=e.message.match(/\(sensor ([a-z0-9-]+)\)/i);r?.[1]&&(t=r[1])}let n=String(e.symbol||"").trim();return t?n?`${t}:${n}`:t:n}i(ro,"structureFreezeTarget");var El=["no-anemic-model"],co=["ensureInvariants","assertInvariants","validate","publish","emit","raise","record"],dr=new RegExp(`\\b(${co.join("|")})\\b`),uo="(?:_?pendingEvents|domainEvents|uncommittedEvents|recordedEvents)",ur=new RegExp(`\\bthis\\.${uo}\\.push\\s*\\(`),Sl=new RegExp(`^this\\.${uo}\\s*=\\s*\\[\\s*\\]`),Il=/^this\.[A-Za-z_][A-Za-z0-9_]*\s*=\s*\[\s*\]/,bl=/\bthis\.[A-Za-z_][A-Za-z0-9_]*\s*=(?!=)/g,po="truncatedUntil";function pr(){return`${co.join(", ")}, or events-array .push(`}i(pr,"expectedDomainInvariantWordsPhrase");function vl(e){return dr.test(e)||ur.test(e)}i(vl,"referencesGuardOrPublish");function fr(e,t,n){let r=e.slice(t);if(Sl.test(r))return!0;if(!Il.test(r))return!1;if(n&&/^pullEvents$/i.test(n))return!0;let o=t>200?t-200:0;return/\bpullEvents\b/.test(e.slice(o,t+200))}i(fr,"isIdiomaticEventsReset");function Cl(e,t){let n=new RegExp(bl.source,"g"),r;for(;(r=n.exec(t))!==null;)if(!fr(t,r.index,e))return!0;return!1}i(Cl,"methodAssignsThis");function _l(e,t){return t==null||Object.defineProperty(e,po,{value:t,enumerable:!1,configurable:!0}),e}i(_l,"attachShapeTruncation");function cr(e){let t=Object.getOwnPropertyDescriptor(e,po)?.value;return typeof t=="number"?t:void 0}i(cr,"shapeTruncatedUntil");function Ol(e){let t=cr(e);return t==null?"":` shape analysed until character ${t}`}i(Ol,"shapeTruncationSuffix");function so(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(so,"escapeGlobLiteral");function xl(e){let t="";for(let r=0;r<e.length;r+=1){let o=e[r];if(o==="\\"&&r+1<e.length){let s=e[r+1];if("*?{}[],".includes(s)||s==="\\"){t+="\\"+s,r+=1;continue}t+="/";continue}t+=o}let n="";for(let r=0;r<t.length;r+=1){let o=t[r];o==="\\"&&r+1<t.length?(n+=so(t[r+1]),r+=1):o==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":o==="?"?n+="[^/]":n+=so(o)}return new RegExp(`^${n}$`)}i(xl,"globToRegExp");function Je(e,t){return!t||t.length===0?!0:t.some(n=>xl(n).test(e))}i(Je,"matchesAppliesTo");function fo(e){return El.includes(e)}i(fo,"isTier2");function mo(e){return e.mode==="enforced"&&!fo(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}i(mo,"severityFor");function Oe(e,t,n,r=1){let{severity:o,failsStrict:s}=mo(e);return{ruleId:"ARKRULE_STRUCTURE",code:e.sensor,message:n,file:t,line:r,fromLayer:e.provenance.layer,arkruleId:e.id,arkruleSource:e.provenance.sourceFile,severity:o,sensor:e.sensor,failsStrict:s}}i(Oe,"baseViolation");function tn(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}i(tn,"isInRuleLayer");function nn(e,t,n){return t.filter(r=>!(!r.exported||!Je(r.file,e.appliesTo)||!tn(r.file,e,n)))}i(nn,"shapesForRule");function Tl(e,t,n){let r=[];for(let o of nn(e,t,n))(o.hasPublicSetters||o.hasPublicMutableFields)&&r.push(Oe(e,o.file,`Exported class ${o.className} exposes public mutable state (sensor aggregate-private-state).`));return r}i(Tl,"evaluateAggregatePrivateState");function Nl(e,t,n){let r=[];for(let o of nn(e,t,n))if(o.hasPublicConstructor&&!o.hasStaticFactory){if(!(o.hasPublicMutableFields||o.hasPublicSetters||(o.mutatingMethods?.length??0)>0))continue;r.push(Oe(e,o.file,`Exported class ${o.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}return r}i(Nl,"evaluateAlwaysValidFactory");function wl(e,t,n){let r=[],o=pr();for(let s of nn(e,t,n)){let a=Ol(s);cr(s)!=null&&r.push(Oe(e,s.file,`Exported class ${s.className} shape analysed until character ${cr(s)}; later methods may be invisible (sensor domain-event-on-mutation).`));for(let c of s.mutatingMethods)c.referencesGuardOrPublish||r.push(Oe(e,s.file,`Mutating method ${s.className}.${c.name} does not reference ${o} (sensor domain-event-on-mutation).${a}`))}return r}i(wl,"evaluateDomainEventOnMutation");function Pl(e,t){let n=[];for(let r of t.files)Je(r,e.appliesTo)&&tn(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(Oe(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}i(Pl,"evaluateOrchestrationOnly");function Ll(e,t){let n=[];for(let r of t.files)Je(r,e.appliesTo)&&tn(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(Oe(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}i(Ll,"evaluateThinAdapter");function Dl(e,t){let n=[];for(let r of t.files)Je(r,e.appliesTo)&&tn(r,e,t.layerForFile)&&t.fileHints?.[r]?.persistenceWrite&&n.push(Oe(e,r,"File imports a persistence driver and issues a write; route the write through a Domain aggregate and a persistence adapter (sensor writes-via-aggregate)."));return n}i(Dl,"evaluateWritesViaAggregate");function Ml(e,t,n){let r=[];for(let o of nn(e,t,n))if(o.dataOnly===!0){let s=Oe(e,o.file,`Exported type ${o.className} looks data-only / anemic (sensor no-anemic-model; advisory only).`);r.push({...s,severity:"warning",failsStrict:!1})}return r}i(Ml,"evaluateNoAnemicModel");function mr(e){if(!e.arkRules.structure.length)return[];let t=[];for(let n of e.arkRules.structure)switch(n.sensor){case"aggregate-private-state":t.push(...Tl(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...Nl(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...wl(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...Pl(n,e));break;case"thin-adapter":t.push(...Ll(n,e));break;case"writes-via-aggregate":t.push(...Dl(n,e));break;case"no-anemic-model":t.push(...Ml(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(mr,"evaluateArkRuleSensors");function gr(e,t){let n=[],r=t.map(o=>o.replace(/\\/g,"/"));for(let o of e.structure){if(!o.appliesTo||o.appliesTo.length===0||r.some(l=>Je(l,o.appliesTo)))continue;let{severity:a,failsStrict:c}=mo(o);n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule structure "${o.id}" appliesTo matched zero governed files (patterns: ${o.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:o.provenance.sourceFile,line:1,fromLayer:o.provenance.layer,arkruleId:o.id,arkruleSource:o.provenance.sourceFile,severity:a,sensor:o.sensor,failsStrict:c})}for(let o of e.invariants??[]){if(!o.appliesTo||o.appliesTo.length===0||r.some(c=>Je(c,o.appliesTo)))continue;let a=o.mode==="enforced";n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule invariant "${o.id}" appliesTo matched zero governed files (patterns: ${o.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:o.provenance.sourceFile,line:1,fromLayer:o.provenance.layer,arkruleId:o.id,arkruleSource:o.provenance.sourceFile,severity:a?"error":"warning",sensor:"invariant-coverage",failsStrict:a})}return n.sort((o,s)=>o.file.localeCompare(s.file)||o.arkruleId.localeCompare(s.arkruleId)||o.message.localeCompare(s.message))}i(gr,"collectEmptyAppliesToFindings");var oo=64;function Fl(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===46;)t-=1;return t===e.length?e:e.slice(0,t)}i(Fl,"stripTrailingDots");function $l(e){let t=e.trim(),n=t.length>oo?t.slice(0,oo):t;return Fl(n)}i($l,"normalizeIntentPrefix");function Hl(e){let t=e.toLowerCase();return t.includes("domain")||t.includes("entity")||t.includes("aggregate")||t.includes("model")}i(Hl,"layerNameLooksDomain");function jl(e){return e.some(t=>{let n=$l(t);return n==="Domain"||n.startsWith("Domain.")})}i(jl,"ownsDomainIntent");function Kl(e,t=[]){return Hl(e)||jl(t)}i(Kl,"isDomainRoleLayerName");function go(e){if(e.arkRulesActive!==!0)return[];let t=(e.layers??[]).filter(l=>Kl(l.name,l.intentPrefixes??[])).map(l=>l.name);if(t.length===0)return[];let n=new Set(t);if(!(e.files??[]).some(l=>{let u=typeof l.layer=="string"?l.layer:"";return u.length>0&&n.has(u)}))return[];if((e.arkRules.invariants??[]).filter(l=>n.has(l.provenance.layer)).length>0)return[];let s=t.find(l=>e.arkRules.byLayer?.[l])??t[0],a=e.arkRules.byLayer?.[s]?.sourceFile??`arkrules/${s}.json`,c=(e.arkRules.structure??[]).some(l=>l.mode==="enforced"&&n.has(l.provenance.layer)&&!fo(l.sensor));return[{ruleId:"INVARIANT_CATALOG_EMPTY",code:"invariant-catalog-empty",message:`ArkRules is on and ${s} has code, but invariants[] is empty \u2014 there are no phrases the code must preserve. Add 1\u20132 short phrases in ${a}.`,file:a,line:1,fromLayer:s,arkruleId:"invariant-catalog",arkruleSource:a,severity:c?"error":"warning",sensor:"invariant-coverage",failsStrict:c}]}i(go,"collectEmptyInvariantCatalogFindings");var ao=/\bfrom\s+['"](?:@?prisma\/client|@supabase\/|drizzle-orm(?:\/[^'"]+)?|postgres(?:\/[^'"]+)?|typeorm|knex|mongodb|pg|mysql2|mongoose|better-sqlite3|ioredis|redis|kysely|sequelize)['"]|require\(\s*['"](?:@?prisma\/client|pg|postgres(?:\/[^'"]+)?|drizzle-orm(?:\/[^'"]+)?|knex|typeorm|mongoose)/,io=/\bfrom\s+['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)(?:\.[cm]?[jt]sx?)?['"]|require\(\s*['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)/,Vl=/\b(?:db|tx|client|prisma(?:Client)?|drizzle)\b(?:\s*\.\s*[A-Za-z_]\w*)*\s*\.\s*(?:insert(?:One|Many)?|update(?:One|Many)?|upsert|delete(?:One|Many)?|createMany|create|replaceOne|findOneAnd(?:Update|Delete|Replace))\s*\(|\bINSERT\s+INTO\b|\bUPDATE\s+[A-Za-z_][\w.]*\s+SET\b|\bDELETE\s+FROM\b/i;function Ul(e){return e==="PersistenceAdapters"}i(Ul,"isPersistenceDriverLayer");function Gl(e,t){if(ao.test(e)||io.test(e))return!0;if(!t)return!1;for(let n of t){if(Ul(n.layer))return!0;let r=n.specifier;if(!r)continue;let o=`from '${r}'`;if(ao.test(o)||io.test(o))return!0}return!1}i(Gl,"sourceImportsPersistenceDriver");var Bl=/\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*=)/,zl=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,Wl=/\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*=/,ql=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function yo(e,t,n){if(!t)return null;let r=Gl(t,n),o=r&&Vl.test(t);if(t.length<40)return o?{persistenceWrite:!0}:null;let s=t.match(new RegExp(Wl.source,"g"))??[],a=t.match(new RegExp(ql.source,"g"))??[],c=(t.match(/\bif\s*\(/g)??[]).length,l=(t.match(/\bswitch\s*\(/g)??[]).length,u=s.length>=2||s.length>=1&&a.length>=2||a.length>=3&&c+l>=6,p=Bl.test(t)||zl.test(t),g=s.length>=1||a.length>=2,f=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),m=r&&g||p&&g||r&&f&&(c>=4||s.length>=1)||p&&r;return!u&&!m&&!o?null:{...u?{orchestrationHeavy:!0}:{},...m?{adapterThick:!0}:{},...o?{persistenceWrite:!0}:{}}}i(yo,"deriveArkRuleFileHints");function yr(e,t){let n={};for(let[r,o]of Object.entries(e)){let s=r.replace(/\\/g,"/"),a=yo(r,o,t?.[s]);a&&(n[s]=a)}return n}i(yr,"buildArkRuleFileHints");var Yl=new Set(["public","private","protected","static","async","readonly","abstract","override","declare","get","set"]),Jl=new Set(["if","match","when"]);function en(e,t){let n=e[t];if(n==="/"&&e[t+1]==="/"){let r=e.indexOf(`
|
|
12
|
+
`,t);return r===-1?e.length:r}if(n==="/"&&e[t+1]==="*"){let r=e.indexOf("*/",t+2);return r===-1?e.length:r+2}if(n==="'"||n==='"'||n==="`"){let r=t+1;for(;r<e.length;){if(e[r]==="\\"){r+=2;continue}if(e[r]===n)return r+1;r+=1}return e.length}return t}i(en,"skipStringOrComment");function kt(e,t){let n=t;for(;n<e.length;){if(/\s/.test(e[n])){n+=1;continue}if(e[n]==="/"&&(e[n+1]==="/"||e[n+1]==="*")){n=en(e,n);continue}break}return n}i(kt,"skipWsAndComments");function lo(e,t){let n=e[t];if(!n||!/[A-Za-z_]/.test(n))return null;let r=t+1;for(;r<e.length&&/[A-Za-z0-9_]/.test(e[r]);)r+=1;return{ident:e.slice(t,r),end:r}}i(lo,"readIdent");function lr(e,t,n,r){if(e[t]!==n)return null;let o=1,s=t+1;for(;s<e.length&&o>0;){let a=en(e,s);if(a!==s){s=a;continue}let c=e[s];c===n?o+=1:c===r&&(o-=1),s+=1}return o===0?s:null}i(lr,"skipBalanced");function Xl(e){let t=[],n=0,r;for(;n<e.length&&(n=kt(e,n),!(n>=e.length));){if(e[n]===";"){n+=1;continue}let o=[],s=n;for(;;){let p=lo(e,s);if(!p||!Yl.has(p.ident))break;o.push(p.ident),s=kt(e,p.end)}let a=lo(e,s);if(!a){n+=1;continue}if(s=kt(e,a.end),e[s]==="<"){let p=lr(e,s,"<",">");if(p==null){r=e.length;break}s=kt(e,p)}if(e[s]==="("){let p=lr(e,s,"(",")");if(p==null){r=e.length;break}if(s=kt(e,p),e[s]===":")for(s+=1;s<e.length&&e[s]!=="{"&&e[s]!==";";){let g=en(e,s);if(g!==s){s=g;continue}s+=1}if(e[s]==="{"){let g=lr(e,s,"{","}");if(g==null){r=e.length;break}t.push({name:a.ident,modifiers:o,kind:"method",body:e.slice(s+1,g-1)}),n=g;continue}if(e[s]===";"){n=s+1;continue}n=s+1;continue}let c=0,l=0,u=0;for(;s<e.length;){let p=en(e,s);if(p!==s){s=p;continue}let g=e[s];if(g==="{")c+=1;else if(g==="}"){if(c===0)break;c-=1}else if(g==="(")l+=1;else if(g===")")l-=1;else if(g==="[")u+=1;else if(g==="]")u-=1;else if(g===";"&&c===0&&l===0&&u===0){s+=1;break}s+=1}t.push({name:a.ident,modifiers:o,kind:"field",body:""}),n=s}return{members:t,truncatedAt:r}}i(Xl,"scanClassMembers");function Zl(e,t){let n=[],r=/export\s+(?:abstract\s+)?class\s+([A-Za-z_][A-Za-z0-9_]*)\s*(?:extends\s+[^{]+)?(?:implements\s+[^{]+)?\{/g,o;for(;(o=r.exec(t))!==null;){let s=o[1],a=o.index+o[0].length,c=1,l=a;for(;l<t.length&&c>0;){let E=t[l];E==="{"?c+=1:E==="}"&&(c-=1),l+=1}let u=t.slice(a,l-1),p=c>0,g=Xl(u),f=p?t.length:g.truncatedAt==null?void 0:a+g.truncatedAt,m=g.members.filter(E=>!(E.kind!=="field"||E.name==="constructor"||E.modifiers.includes("private")||E.modifiers.includes("protected")||E.modifiers.includes("readonly")||E.modifiers.includes("static")||E.modifiers.includes("get")||E.modifiers.includes("set"))),d=m.length>0,A=/(?:^|[\n;{])\s*(?:public\s+)?set\s+[a-zA-Z_]/.test(u),b=/(?:^|[\n;{])\s*private\s+constructor\s*\(/.test(u),O=/(?:^|[\n;{])\s*(?:public\s+)?constructor\s*\(/.test(u)&&!b,k=/(?:^|[\n;{])\s*static\s+(?:async\s+)?(?:create|of|from|parse|build|make|new)\s*[<(]/.test(u)||/(?:^|[\n;{])\s*static\s+(?:async\s+)?[A-Za-z_][A-Za-z0-9_]*\s*\([^)]*\)\s*:\s*[A-Za-z_]/.test(u),I=[];for(let E of g.members)E.kind==="method"&&E.name!=="constructor"&&(E.modifiers.includes("static")||E.modifiers.includes("get")||E.modifiers.includes("set")||Jl.has(E.name)||Cl(E.name,E.body)&&I.push({name:E.name,referencesGuardOrPublish:vl(E.body)}));let L=g.members.filter(E=>E.kind==="method").length<=1&&m.length>=2&&d;n.push(_l({file:e,className:s,exported:!0,hasPublicMutableFields:d,hasPublicSetters:A,hasPublicConstructor:O,hasStaticFactory:k,mutatingMethods:[...I],dataOnly:L},f))}return n}i(Zl,"extractClassShapesFromSource");var Ql=50;function hr(e){if(!e)return{};let t=typeof e.governedPercent=="number"?e.governedPercent:null,n=typeof e.populatedLayerCount=="number"?e.populatedLayerCount:null;return n==null&&typeof e.classifiedFiles=="number"&&(n=e.classifiedFiles>0?1:0),{governedPercent:t,populatedLayerCount:n}}i(hr,"normalizeExtraMergeTeethClassification");function he(e){let t=hr(e),n=typeof t.governedPercent=="number"?t.governedPercent:null,r=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null;return n==null&&r==null?!0:(n??0)>=50&&(r??0)>=1}i(he,"extraMergeTeethAllowed");function Ar(e){let t=e.length,n=0,r=new Set;for(let o of e){let s=typeof o.layer=="string"&&o.layer.length>0?o.layer:null;s&&(n+=1,r.add(s))}return{governedPercent:t>0?Math.round(n/t*100):0,populatedLayerCount:r.size}}i(Ar,"classifyResolvedLayerCoverage");function Rr(e){return typeof e=="string"&&e.startsWith("ARKRUN_")}i(Rr,"isArkRunRuleId");function ho(e){return typeof e=="string"&&e.startsWith("ARKORDER_")}i(ho,"isArkOrderRuleId");function Ao(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(Ao,"isExtraPlaneFinding");function ec(e,t={}){if(!Array.isArray(e)||he(t))return e;for(let n of e)Ao(n)&&n.failsStrict!==!1&&(n.failsStrict=!1,n.severity==="error"&&(n.severity="warning"));return e}i(ec,"demoteExtraPlaneTeethUnderClassificationFloor");var Ro="Structure = heuristics; invariants = catalog+coverage evidence (not business runtime); ArkRun = kernel usage + declarations (not a score); ArkOrder = the few big product choices (not a score). Extra planes never merge into one architecture score. Advisory ArkRules \u2260 merge teeth. Advisory ArkRun \u2260 merge teeth. Advisory ArkOrder \u2260 merge teeth.";function ye(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):0}i(ye,"countOrZero");function rn(e={}){let t=hr(e.classification),n=typeof t.governedPercent=="number"?t.governedPercent:null,r=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null,o=n!=null||r!=null,s=he(t),a=e.arkRules,c=ye(a?.structureEnforced),l=ye(a?.structureTotal),u=typeof a?.structureAdvisory=="number"?ye(a.structureAdvisory):Math.max(0,l-c),p=ye(a?.invariantEnforced),g=ye(a?.invariantTotal),f=typeof a?.invariantAdvisory=="number"?ye(a.invariantAdvisory):Math.max(0,g-p),m=c>0||p>0,d=e.arkRun?.present===!0,A=e.arkRun?.mode==="enforced"||e.arkRun?.mode==="advisory"?e.arkRun.mode:null,b=ye(e.arkRun?.residualCount),O=d&&A==="enforced",k=O&&s,I=e.arkOrder?.present===!0,C=e.arkOrder?.mode==="enforced"||e.arkOrder?.mode==="advisory"?e.arkOrder.mode:null,L=ye(e.arkOrder?.residualCount),E=I&&C==="enforced",P=E&&s,ee=m||O||E,T=ee&&s,V=ee&&o&&!s,D;if(T){let J=[];m&&J.push("enforced structure/invariant findings"),O&&J.push("enforced ArkRun skip findings"),E&&J.push("enforced ArkOrder skip findings"),D=`Layer graph failures plus ${J.join(" and ")} (advisory extras never fail merge alone).`}else if(V)D=`Layer graph only \u2014 enforced ${[m?"ArkRules structure/invariant":null,O?"ArkRun":null,E?"ArkOrder":null].filter(be=>!!be).join(" and ")} findings are demoted under the teeth floor (need \u226550% governed and \u22651 populated layer); they do not merge-block until classification is honest.`;else{let J=d?A==="advisory"?" Advisory ArkRun never merge-blocks.":" ArkRun extra is present but does not arm merge teeth.":" Absence of arkRun is silent.",be=I?C==="advisory"?" Advisory ArkOrder never merge-blocks.":" ArkOrder extra is present but does not arm merge teeth.":" Absence of arkOrder is silent.";D="Layer graph only \u2014 no enforced ArkRules structure/invariant teeth on this tree. Advisory packs do not arm merge teeth."+J+be}let se={layers:{role:"inter-layer-edges",alwaysOnGate:!0,note:"Import/export layer graph \u2014 the default merge plane. Absent extras change nothing here."},structureSensors:{role:"intra-layer-heuristics",total:l,enforced:c,advisory:u,note:"Structure sensors are heuristics (prefer false negatives). Only mode:enforced fails merge; noisy sensors stay advisory by default. Advisory-only packs never add merge teeth (FG-ARKRULES-ADVISORY-ONLY)."},invariants:{role:"catalog-plus-coverage",total:g,enforced:p,advisory:f,covered:ye(a?.covered),uncovered:ye(a?.uncovered),note:"Invariants are catalog + coverage evidence, not a business runtime. Enforced + proven-uncovered fails merge; absence of enforced rules adds no extra teeth."},arkRun:{role:"kernel-usage-and-declarations",present:d,mode:A,residualCount:b,extraMergeTeeth:k,note:d?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."},arkOrder:{role:"pattern-slaving",present:I,mode:C,residualCount:L,extraMergeTeeth:P,note:I?C==="enforced"?"Enforced ArkOrder arms extra merge teeth only when the layer plane is classified. Residual is a count, never a score.":"Advisory ArkOrder never adds merge teeth and never flips valid. Residual is a count, never a score.":"Absence of arkOrder is silent \u2014 Layers verdicts unchanged. The extra never becomes a score."},extraMergeTeeth:T,dualPlaneStamp:Ro,failMergeWhen:D};return o&&(se.classificationGate={governedPercent:n,populatedLayerCount:r,floorPercent:50,allowsTeeth:s}),se}i(rn,"composeMergePlanesHonesty");var Eo=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"],tc=["publisher","publish","raise","raiseAsync","send","sendTo","subscribe","registerHandler","resolve","resolveSingleton"],nc=new Set(Eo),rc=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"]),sc=new Set(["Array","Atomics","Buffer","JSON","Math","Number","Object","Promise","Reflect","String","console","fs","path","url","util"]);function It(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")}i(It,"isArkRunKernelModuleSpecifier");var So=["events","node:events","eventemitter2","eventemitter3","emittery","kafkajs","kafka-node","amqplib","amqp","bull","bullmq","mqtt","nats","@aws-sdk/client-sqs","@aws-sdk/client-sns","@aws-sdk/client-eventbridge","@google-cloud/pubsub","@azure/service-bus"],kr=new Set(So);function Sr(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(kr.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(kr.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:kr.has(e.slice(0,r))}i(Sr,"isArkRunTransportBypassSpecifier");function Er(e){if(nc.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(Er,"arkRunKernelCallKind");function St(e,t){let n=1;for(let r=0;r<t;r+=1)e.charCodeAt(r)===10&&(n+=1);return n}i(St,"lineAt");function bt(e){return e.replace(/\/\*[\s\S]*?\*\//g,t=>t.replace(/[^\n]/g," ")).replace(/(^|[^:\\])\/\/.*$/gm,t=>t.replace(/\/\/.*$/,n=>" ".repeat(n.length)))}i(bt,"stripCommentsPreservingLines");function oc(e,t){let n=e.slice(t),r=/^\s*(['"])((?:\\.|[^\\])*?)\1/.exec(n);if(!r)return;let o=r[2]??"";return o.length>0?o:void 0}i(oc,"firstStringLiteralArg");function ko(e,t,n){let r=Math.max(0,t-n.length-8),o=e.slice(r,t);return new RegExp(`\\b${n}\\s+$`).test(o)}i(ko,"keywordBefore");function sn(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(sn,"parseValueImportClause");function ac(e,t){sn(bt(e),t)}i(ac,"forEachArkRunValueImportClause");function Ir(e,t){let n=bt(t),r=[],o=/\b(?:import|export)(\s+type)?\s+([\s\S]*?)\s+from\s*['"]([^'"]+)['"]/g,s;for(;(s=o.exec(n))!==null;){let c=s[3]??"";if(!c)continue;let l=s[0]??"";r.push({from:e,specifier:c,kind:/^\s*export/.test(l)?"export":"import",typeOnly:!!s[1],line:St(t,s.index),resolution:"resolved-external"})}let a=/\b(?:require|import)\s*\(\s*['"]([^'"]+)['"]\s*\)/g;for(;(s=a.exec(n))!==null;){let c=s[1]??"";if(!c)continue;let l=s[0]?.startsWith("import")?"dynamic-import":"require";r.push({from:e,specifier:c,kind:l,typeOnly:!1,line:St(t,s.index),resolution:"resolved-external"})}return r}i(Ir,"extractArkRunValueImportDependenciesFromSource");function br(e){let t=[];return ac(e,n=>{let r=/\{([^}]*)\}/.exec(n);if(r?.[1])for(let o of r[1].split(",")){let s=o.trim();if(!s||s.startsWith("type "))continue;let a=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(s),c=a?.[2]??/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(s)?.[1],l=a?.[1]??c;c&&l&&/^[A-Z]/.test(l)&&t.push(c,l)}}),Et(t)}i(br,"extractArkRunImportedConstructorNamesFromSource");function ic(e){let t=new Map,n=new Set;return sn(e,(r,o)=>{if(!It(o))return;let s=/\*\s+as\s+([A-Za-z_][A-Za-z0-9_]*)/.exec(r);s?.[1]&&n.add(s[1]);let a=/^([A-Za-z_][A-Za-z0-9_]*)\s*(?:,|$)/.exec(r.trim());a?.[1]&&t.set(a[1],a[1]);let c=/\{([^}]*)\}/.exec(r);if(c?.[1])for(let l of c[1].split(",")){let u=l.trim();if(!u||u.startsWith("type "))continue;let p=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(u);if(p){t.set(p[2],p[1]);continue}let g=/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(u);g?.[1]&&t.set(g[1],g[1])}}),{named:t,namespaces:n}}i(ic,"collectKernelImportBindings");function lc(e,t){let n=new Set(t);return sn(e,(r,o)=>{let s=/\{([^}]*)\}/.exec(r);if(s?.[1])for(let a of s[1].split(",")){let c=a.trim();if(!c||c.startsWith("type "))continue;let l=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(c),u=l?.[2]??/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(c)?.[1],p=l?.[1]??u;!u||!p||!/^[A-Z]/.test(p)||(It(o)||t.has(p)||t.has(u))&&(n.add(u),n.add(p))}}),n}i(lc,"collectImportedConstructors");function cc(e,t){let n;return sn(e,(r,o)=>{!n&&new RegExp(`\\b${t}\\b`).test(r)&&(n=o)}),n}i(cc,"importedFromForName");function vr(e,t){let n=bt(t),r=ic(n),o=[],s=/\b([A-Za-z_][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,a;for(;(a=s.exec(n))!==null;){let c=a[1],l=a.index;if(ko(n,l,"function")||ko(n,l,"class"))continue;let p=n.slice(0,l).match(/([A-Za-z_][A-Za-z0-9_]*)\s*\.\s*$/)?.[1],g=r.named.get(c)??c,f=Er(g)??Er(c);if(!f)continue;let m=r.named.has(c)||p!==void 0&&r.namespaces.has(p);if(f!=="factory"&&(!m&&p===void 0||p&&sc.has(p)&&!m))continue;let d=oc(n,l+a[0].length);o.push({file:e,line:St(t,l),kind:f,callee:c,viaImport:m,...p?{receiver:p}:{},...d?{nameLiteral:d}:{}})}return o}i(vr,"extractArkRunKernelCallsFromSource");function Cr(e,t,n){let r=bt(t),o=lc(r,n),s=[],a=/\bnew\s+(?:[A-Za-z_][A-Za-z0-9_]*\s*\.\s*)*([A-Z][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,c;for(;(c=a.exec(r))!==null;){let l=c[1];if(rc.has(l)||!o.has(l))continue;let u=cc(r,l);s.push({file:e,line:St(t,c.index),typeName:l,...u?{importedFrom:u}:{}})}return s}i(Cr,"extractArkRunManagedNewsFromSource");function dc(e,t){let n=0,r;for(let o=t;o<e.length;o+=1){let s=e[o];if(r){if(s==="\\"){o+=1;continue}s===r&&(r=void 0);continue}if(s==="'"||s==='"'||s==="`"){r=s;continue}if(s==="[")n+=1;else if(s==="]"&&(n-=1,n===0))return o}return-1}i(dc,"matchingBracketEnd");function uc(e,t,n){let r=e.slice(t+1,n),o=[],s=/(['"])((?:\\.|[^\\])*?)\1/g,a;for(;(a=s.exec(r))!==null;){let c=a[2]??"";c.length>0&&o.push(c)}return o}i(uc,"stringLiteralsInList");function Et(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}i(Et,"uniqueSorted");function pc(e,t){let n=bt(t),r=/\b(uses|reactsTo|raises|sends)\s*:/g,o=[],s=[],a=[],c=[],l,u;for(;(u=r.exec(n))!==null;){let p=n.slice(u.index+u[0].length),g=/^\s*\[/.exec(p);if(!g)continue;let f=u.index+u[0].length+(g[0].length-1),m=dc(n,f);if(m<0)continue;let d=uc(n,f,m);if(d.length===0)continue;l===void 0&&(l=u.index);let A=u[1];A==="uses"?o.push(...d):A==="reactsTo"?s.push(...d):A==="raises"?a.push(...d):c.push(...d)}return l===void 0?[]:[{file:e,line:St(t,l),uses:Et(o),reactsTo:Et(s),raises:Et(a),sends:Et(c)}]}i(pc,"extractArkRunDeclarationsFromSource");var fc=["arkrun-missing-root","arkrun-kernel-in-domain","arkrun-direct-new","arkrun-undeclared-emit","arkrun-undeclared-handle","arkrun-undeclared-depend","arkrun-transport-bypass"],mc=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],gc=new Set(mc);function yc(e){return gc.has(e)}i(yc,"isArkRunEditorSensor");var _r={"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"},vo="ARKRUN_INTERACTION_NAME_INCOMPLETE";function Co(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)||/^(?:entit(?:y|ies)|aggregates?)(?:$|(?=[A-Z_\-\s]))/i.test(n)?!0:t.some(r=>{let o=r.trim().replace(/\.+$/,"");return o==="Domain"||o.startsWith("Domain.")})}i(Co,"isDomainRoleLayer");function hc(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}i(hc,"compareFindings");function Ie(e,t,n,r,o,s,a){let c=e.mode==="enforced"&&a;return{ruleId:_r[t],sensor:t,message:o,file:n,line:r,...s?.fromLayer?{fromLayer:s.fromLayer}:{},...s?.target?{target:s.target}:{},severity:c?"error":"warning",failsStrict:c,nextAction:ge({ruleId:_r[t],fromLayer:s?.fromLayer,target:s?.target})}}i(Ie,"finding");function Ac(e,t){let n=[],r=[],o=[],s=[];for(let a of e)a.file===t&&(n.push(...a.uses),r.push(...a.reactsTo),o.push(...a.raises),s.push(...a.sends));return{uses:new Set(n),reactsTo:new Set(r),raises:new Set(o),sends:new Set(s)}}i(Ac,"bagForFile");function Io(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}i(Io,"emitKinds");function bo(e){return e==="subscribe"||e==="register-handler"}i(bo,"handleKinds");function Rc(e){return e==="resolve"||e==="resolve-singleton"}i(Rc,"dependKinds");function kc(e,t,n){let r=[],o=e.kernelRoots??e.compositionRoots;if(o.length===0)return r.push(Ie(e,"arkrun-missing-root","ark.config.json",1,"ArkRun kernelRoots is empty; no createArkKernel factory site is declared.",void 0,n)),r;let s=new Map;for(let a of t){let c=s.get(a.matchedRoot)??[];c.push(a),s.set(a.matchedRoot,c)}for(let a of o){let c=[...s.get(a)??[]].sort((u,p)=>u.file.localeCompare(p.file));if(c.length===0){r.push(Ie(e,"arkrun-missing-root","ark.config.json",1,`ArkRun kernel root ${JSON.stringify(a)} matched no governed files and has no createArkKernel factory.`,{target:a},n));continue}if(c.some(u=>u.hasKernelFactory))continue;let l=c[0];r.push(Ie(e,"arkrun-missing-root",l.file,1,`ArkRun kernel root ${JSON.stringify(a)} has no createArkKernel / createStrictArkKernel factory.`,{target:a},n))}return r}i(kc,"evaluateMissingRoot");function Ec(e,t,n,r,o){let s=new Map(t.map(c=>[c.name,c.intentPrefixes??[]])),a=[];for(let c of n){let l=c.specifier;if(!l||!It(l))continue;let u=r(c.from);u&&Co(u,s.get(u)??[])&&a.push(Ie(e,"arkrun-kernel-in-domain",c.from,c.line,`${u} must not import kernel module ${JSON.stringify(l)}.`,{fromLayer:u,target:l},o))}return a}i(Ec,"evaluateKernelInDomain");function Sc(e,t,n,r,o,s){let a=new Set(e.managedLayers);if(a.size===0)return[];let c=new Map(t.map(p=>[p.name,p.intentPrefixes??[]])),l=new Set(r.filter(p=>p.hasKernelFactory).map(p=>p.file)),u=[];for(let p of n){if(l.has(p.file))continue;let g=p.typeName;if(e.ignoreDirectNewForErrors!==!1&&(g.endsWith("Error")||g==="Error")||g.endsWith("DTO")||g.endsWith("VO"))continue;let f=o(p.file);!f||!a.has(f)||Co(f,c.get(f)??[])||u.push(Ie(e,"arkrun-direct-new",p.file,p.line,`${f} must not construct ${p.typeName} with new outside an ArkRun composition-root factory.`,{fromLayer:f,target:p.typeName},s))}return u}i(Sc,"evaluateDirectNew");function Ic(e,t,n,r,o){let s=[],a=[];if(e.requireDeclarations!==!0)return{findings:s,completenessReasons:a};let c=new Set(e.managedLayers);if(c.size===0)return{findings:s,completenessReasons:a};for(let l of t){if(!Io(l.kind)&&!bo(l.kind)&&!Rc(l.kind))continue;let u=r(l.file);if(!u||!c.has(u))continue;if(!l.nameLiteral){e.mode==="enforced"&&a.push({code:vo,file:l.file,message:`ArkRun ${l.kind} call in ${l.file} has no string-literal name; enforced extra cannot prove the declaration.`});continue}let p=Ac(n,l.file);if(Io(l.kind)){if(p.raises.has(l.nameLiteral)||p.sends.has(l.nameLiteral))continue;s.push(Ie(e,"arkrun-undeclared-emit",l.file,l.line,`Emit ${JSON.stringify(l.nameLiteral)} is not declared in raises or sends.`,{fromLayer:u,target:l.nameLiteral},o));continue}if(bo(l.kind)){if(p.reactsTo.has(l.nameLiteral))continue;s.push(Ie(e,"arkrun-undeclared-handle",l.file,l.line,`Handle ${JSON.stringify(l.nameLiteral)} is not declared in reactsTo.`,{fromLayer:u,target:l.nameLiteral},o));continue}p.uses.has(l.nameLiteral)||s.push(Ie(e,"arkrun-undeclared-depend",l.file,l.line,`Depend ${JSON.stringify(l.nameLiteral)} is not declared in uses.`,{fromLayer:u,target:l.nameLiteral},o))}return{findings:s,completenessReasons:a}}i(Ic,"evaluateUndeclared");function bc(e,t,n,r){let o=new Set(e.managedLayers);if(o.size===0)return[];let s=[];for(let a of t){if(a.typeOnly)continue;let c=a.specifier;if(!c||!Sr(c))continue;let l=n(a.from);!l||!o.has(l)||s.push(Ie(e,"arkrun-transport-bypass",a.from,a.line,`${l} must not import broker/queue/emitter ${JSON.stringify(c)}; use the ArkRun kernel transport.`,{fromLayer:l,target:c},r))}return s}i(bc,"evaluateTransportBypass");function on(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=he(e.classification),r=Ic(t,e.kernelCalls,e.declarations,e.layerForFile,n),o=[...kc(t,e.compositionRootHits,n),...Ec(t,e.layers,e.dependencies,e.layerForFile,n),...Sc(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...bc(t,e.dependencies,e.layerForFile,n)].sort(hc),s=[...r.completenessReasons].sort((a,c)=>{let l=`${a.code}\0${a.file??""}\0${a.message}`,u=`${c.code}\0${c.file??""}\0${c.message}`;return l<u?-1:l>u?1:0});return{findings:o,completenessReasons:s}}i(on,"evaluateArkRunSensors");function _o(e){return{findings:on(e).findings.filter(n=>yc(n.sensor)),completenessReasons:[]}}i(_o,"evaluateArkRunEditorSensors");function vc(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(vc,"fileMatchesCompositionRoot");function Cc(e,t,n){let r=vr(t,n).some(a=>a.kind==="factory"),o=[],s=e.kernelRoots??e.compositionRoots;for(let a of s)vc(a,t)&&o.push({file:t,matchedRoot:a,hasKernelFactory:r});return o}i(Cc,"compositionRootHitsForSource");function _c(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=new Set(br(e.source));return _o({arkRun:t,layers:e.layers,kernelCalls:[],managedNews:Cr(e.file,e.source,n),compositionRootHits:Cc(t,e.file,e.source),declarations:[],dependencies:Ir(e.file,e.source),layerForFile:e.layerForFile,classification:e.classification})}i(_c,"evaluateArkRunEditorSensorsFromSource");function Oo(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}i(Oo,"isArkOrderModuleSpecifier");var xo=new Map;function To(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(To,"escapeAppliesToLiteral");function Oc(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let o=e[n+1];if("*?{}[],".includes(o)||o==="\\"){t+="\\"+o,n+=1;continue}t+="/";continue}t+=r}return t}i(Oc,"normalizeAppliesToGlob");function xc(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(xc,"appliesToBracesBalanced");function Tc(e){let t=xo.get(e);if(t)return t;let n=Oc(e),r=xc(n),o="",s=0;for(let c=0;c<n.length;c+=1){let l=n[c];l==="\\"&&c+1<n.length?(o+=To(n[c+1]),c+=1):l==="*"?n[c+1]==="*"?n[c+2]==="/"?(o+="(?:.*/)?",c+=2):(o+=".*",c+=1):o+="[^/]*":l==="?"?o+="[^/]":l==="{"&&r?(o+="(?:",s+=1):l==="}"&&r&&s>0?(o+=")",s-=1):l===","&&r&&s>0?o+="|":o+=To(l)}let a=new RegExp(`^${o}$`);return xo.set(e,a),a}i(Tc,"globToRegExp");var Nc=["arkorder-missing-plane","arkorder-kernel-in-domain","arkorder-generic-update","arkorder-too-many-params","arkorder-ingest-writes-xi","arkorder-xi-field-write","arkorder-information-budget","arkorder-xi-ttl"],Or={"arkorder-missing-plane":"ARKORDER_MISSING_PLANE","arkorder-kernel-in-domain":"ARKORDER_KERNEL_IN_DOMAIN","arkorder-generic-update":"ARKORDER_GENERIC_UPDATE","arkorder-too-many-params":"ARKORDER_TOO_MANY_PARAMS","arkorder-ingest-writes-xi":"ARKORDER_INGEST_WRITES_XI","arkorder-xi-field-write":"ARKORDER_XI_FIELD_WRITE","arkorder-information-budget":"ARKORDER_INFORMATION_BUDGET","arkorder-xi-ttl":"ARKORDER_XI_TTL"};function wc(e,t){return!t||t.length===0?!0:t.some(n=>Tc(n).test(e))}i(wc,"matchesArkOrderAppliesTo");function Pc(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)?!0:t.some(r=>{let o=r.trim().replace(/\.+$/,"");return o==="Domain"||o.startsWith("Domain.")})}i(Pc,"isDomainRoleLayer");function xe(e,t,n,r,o,s,a){let c=e.mode==="enforced"&&a;return{ruleId:Or[t],sensor:t,message:o,file:n,line:r,...s?.fromLayer?{fromLayer:s.fromLayer}:{},...s?.target?{target:s.target}:{},severity:c?"error":"warning",failsStrict:c,nextAction:ge({ruleId:Or[t],fromLayer:s?.fromLayer,target:s?.target})}}i(xe,"finding");function xr(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let n=he(e.classification),r=[],o=t.planeRoots;if(t.mode==="enforced"&&o.length===0)r.push(xe(t,"arkorder-missing-plane","ark.config.json",1,"ArkOrder planeRoots is empty; no createOrderPlane site is declared.",void 0,n));else{let l=new Map;for(let u of e.planeRootHits){let p=l.get(u.matchedRoot)??[];p.push(u),l.set(u.matchedRoot,p)}for(let u of o){let p=l.get(u)??[];if(p.length===0){r.push(xe(t,"arkorder-missing-plane","ark.config.json",1,`ArkOrder plane root ${JSON.stringify(u)} matched no governed files and has no createOrderPlane factory.`,{target:u},n));continue}p.some(g=>g.hasPlaneFactory)||r.push(xe(t,"arkorder-missing-plane",p[0].file,1,`ArkOrder plane root ${JSON.stringify(u)} has no createOrderPlane factory.`,{target:u},n))}}let s=new Map(e.layers.map(l=>[l.name,l.intentPrefixes??[]]));for(let l of e.dependencies){let u=l.specifier;if(!u||!Oo(u))continue;let p=e.layerForFile(l.from);p&&Pc(p,s.get(p)??[])&&r.push(xe(t,"arkorder-kernel-in-domain",l.from,l.line,"Domain-role layer imports arkgate/order; Domain stays plane-free.",{fromLayer:p,target:u},n))}for(let l of e.genericUpdates)r.push(xe(t,"arkorder-generic-update",l.file,l.line,`Generic ${l.method}() on the order plane rewrites \u03BE; Haken forbids it.`,{target:l.method},n));let a=t.xiKeys??[];for(let l of e.releaseKeyCounts??[])l.keyCount<=t.maxXiKeys||r.push(xe(t,"arkorder-too-many-params",l.file,l.line,`release() freezes ${l.keyCount} keys; maxXiKeys is ${t.maxXiKeys} (few slow modes).`,{target:String(l.keyCount)},n));for(let l of e.ingestWritesXi??[])r.push(xe(t,"arkorder-ingest-writes-xi",l.file,l.line,"ingest() result is assigned into a Release or \u03BE store; ingest may absorb or escalate, never mint a pattern.",void 0,n));let c=new Set(t.managedLayers);for(let l of a.length===0?[]:e.xiFieldWrites??[]){let u=e.layerForFile(l.file);!u||!c.has(u)||wc(l.file,t.appliesTo)&&r.push(xe(t,"arkorder-xi-field-write",l.file,l.line,`This file writes ${JSON.stringify(l.key)} the same way it would write a seat count. Take the event in, or change that choice through the valve (propose, then apply).`,{fromLayer:u,target:l.key},n))}return r.sort((l,u)=>l.file.localeCompare(u.file)||l.ruleId.localeCompare(u.ruleId)||l.line-u.line),{findings:r,completenessReasons:[]}}i(xr,"evaluateArkOrderSensors");function ne(e,t,n={}){return{ruleId:e,message:t,...n}}i(ne,"configWarning");function an(e){let{config:t,rules:n,files:r,manifest:o}=e,s=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(d=>typeof d!="string"))&&s.push(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)))s.push(ne("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let d of["maxTsSuppressions","maxAnyCasts"]){let A=t.safety[d];A!==void 0&&(!Number.isInteger(A)||A<0)&&s.push(ne("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${d} must be a non-negative integer.`))}let a=Array.isArray(t.layers)?t.layers:[],c=Array.isArray(o?.architecture?.layers)?o.architecture.layers:[],l=new Set([...a.map(d=>d.name).filter(Boolean),...c.map(d=>d.name).filter(d=>!!d)]);a.length===0&&s.push(ne("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let u=new Set,p=new Set;for(let d of a){if(!d.name){s.push(ne("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}u.has(d.name)&&p.add(d.name),u.add(d.name),d.forbiddenGlobals!==void 0&&(!Array.isArray(d.forbiddenGlobals)||d.forbiddenGlobals.some(b=>typeof b!="string"))&&s.push(ne("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 A=Array.isArray(d.patterns)?d.patterns:[];if(A.length===0){s.push(ne("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${d.name}" has no file patterns and will never classify files.`,{layer:d.name}));continue}for(let b of A){let O;try{O=Re(b)}catch(I){s.push(ne("CONFIG_INVALID_LAYER_PATTERN",`Layer "${d.name}" has an invalid pattern "${b}": ${I instanceof Error?I.message:String(I)}`,{layer:d.name,pattern:b}));continue}let k=d.optional===!0||d.reserved===!0||d.allowEmpty===!0;!r.some(I=>O.test(I))&&!k&&s.push(ne("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${d.name}" pattern "${b}" matched no included files (possible typo). Mark the layer reserved/allowEmpty if this house is reserved for later.`,{layer:d.name,pattern:b,failsStrict:!1,reserved:!1}))}}for(let d of p)s.push(ne("CONFIG_DUPLICATE_LAYER",`Layer "${d}" is configured more than once.`,{layer:d}));if(l.size>0)for(let d of n??[])d.from&&!l.has(d.from)&&s.push(ne("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${d.from}".`,{fromLayer:d.from,toLayer:d.to})),d.to&&!l.has(d.to)&&s.push(ne("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 A=-1,b=[];for(let O of a)for(let k of O.patterns??[]){if(!Re(k).test(d))continue;let I=xn(k,d);I>A?(A=I,b=[O.name]):I===A&&!b.includes(O.name)&&b.push(O.name)}b.length>1&&g.add([...b].sort().join(" + "))}g.size>0&&s.push(ne("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...g].join(", ")}.`,{pairs:[...g]}));let f=r.filter(d=>!fe(d,a));f.length>0&&s.push(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)}));let m=xs(t);if(m.length>0){let d=m[0]??"this layer";s.push(ne("CONFIG_LAYER_MISSING_OWNER",`${d} has no owner. Add a GitHub handle or email to layers[].owners so this house has a name on the door.`,{layers:m,nextAction:Ts(d)}))}return s}i(an,"collectAnalysisConfigWarnings");function No(e,t){let n=e.ruleId==="ARKRULE_STRUCTURE",r=e.ruleId==="ARKRULE_SCOPE_EMPTY",o=e.ruleId==="INVARIANT_CATALOG_EMPTY";return{ruleId:e.ruleId,file:e.file,line:e.line,message:e.message,fromLayer:e.fromLayer,arkruleId:e.arkruleId,arkruleSource:e.arkruleSource,...n?{sensor:e.sensor,code:e.code,target:ro({sensor:e.sensor,code:e.code})}:{},...r||o?{freezable:!1}:{},nextAction:t}}i(No,"toArkRuleEngineViolation");function Lc(e){let t=e.arkRules;return!!(t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0)}i(Lc,"arkRulesMapIsOn");function wo(e,t){return e.ruleId==="INVARIANT_CATALOG_EMPTY"?t?`Add 1\u20132 short phrases to invariants[] in ${e.arkruleSource} so Domain has policies the code must preserve (advisory \u2014 does not fail the merge until a domain structure rule is enforced).`:`Add 1\u20132 short phrases to invariants[] in ${e.arkruleSource} so Domain has policies the code must preserve. Empty catalog fails --strict-merge because a domain structure rule is already enforced.`:e.ruleId==="ARKRULE_SCOPE_EMPTY"?t?`Review appliesTo for ${e.arkruleId} in ${e.arkruleSource} (zero-match scope; advisory). Empty scope is not freezable; promote only after the folder exists.`:`Fix appliesTo globs for ${e.arkruleId} in ${e.arkruleSource} so they match governed files, or remove the rule. ARKRULE_SCOPE_EMPTY is a config diagnostic and is not freezable (even with --force). Land the rule as advisory until the folder exists, then promote.`:t?`Review ArkRule ${e.arkruleId} in ${e.arkruleSource} (advisory).`:`Fix the structure or invariant for ${e.arkruleId} (declared in ${e.arkruleSource}), then preflight again.`}i(wo,"arkRuleFindingNextAction");function Dc(e,t){return t.some(n=>{try{return Re(n).test(e)}catch{return!1}})}i(Dc,"matchesAny");function Mc(e,t){let n=e.contract.config.safety??{},r=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,o=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,s=e.contract.config.dynamicImportAllowlist??[],a=t.safetyUses.filter(A=>A.kind==="ts-suppression").map(({file:A,line:b})=>({file:A,line:b})),c=t.safetyUses.filter(A=>A.kind==="any-cast").map(({file:A,line:b})=>({file:A,line:b})),l=t.safetyUses.filter(A=>(A.kind==="dynamic-import"||A.kind==="dynamic-require")&&!Dc(A.file,s)).map(A=>({file:A.file,line:A.line,kind:A.kind==="dynamic-require"?"require":"import"})),u=n.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(A=>A.kind==="in-memory-store").map(A=>({file:A.file,line:A.line,store:A.symbol??"in-memory store"})),p=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})),g={tsSuppressions:a,anyCasts:c,nonLiteralDynamicImports:l,inMemoryProductionStores:u,disabledPeerIsolationRules:p,thresholds:{maxTsSuppressions:r,maxAnyCasts:o}},f=[],m=l.filter(A=>A.kind==="import");if(m.length>0){let A=m[0];f.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:A.file,line:A.line,message:`${m.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let d=l.filter(A=>A.kind==="require");if(d.length>0){let A=d[0];f.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:A.file,line:A.line,message:`${d.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(a.length>r){let A=a[0];f.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:A.file,line:A.line,message:`${a.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${r}).`})}if(c.length>o){let A=c[0];f.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:A.file,line:A.line,message:`${c.length} explicit any cast(s) exceed safety.maxAnyCasts (${o}).`})}if(u.length>0){let A=u[0];f.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:A.file,line:A.line,message:`${u.length} ArkGate InMemory store risk(s) appear in governed production source. Provide durable stores or set safety.allowInMemory only for an explicitly ephemeral service.`})}return p.length>0&&f.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${p.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:g,warnings:f}}i(Mc,"evaluateSafety");function Fc(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}i(Fc,"ambientForbiddenGlobal");function Po(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return Dn(e,n.length>0?n:Ln.map(r=>({name:r.layer,prefixes:r.prefixes})))}i(Po,"intentLayer");function $c(e,t,n){let r=[],o=new Map(e.contract.config.layers.map(s=>[s.name,s]));for(let s of t.ambientUses){let a=n.get(s.file);!a||!Fc(s.symbol,o.get(a)?.forbiddenGlobals??[])||r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:a,target:s.symbol,message:`${a} must not use the ambient global "${s.symbol}".`})}for(let s of t.capabilityUses){let a=n.get(s.file);if(!a)continue;let c=o.get(a),l=c?.forbiddenGlobals??[],u=s.source==="import-based"?t.dependencies.find(p=>p.from===s.file&&p.line===s.line&&p.specifier===s.symbol&&!p.typeOnly)?.kind:void 0;if(!(s.source==="ambient-global"&&ot(s.symbol,l))){if(s.source==="import-based"){let p=Ce(s.symbol,l);if(p){r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:a,target:s.symbol,...u?{edgeKind:u}:{},message:`${a} must not use module "${s.symbol}" because it is the import form of forbidden global "${p}".`});continue}}je(c).includes(s.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:s.file,line:s.line,fromLayer:a,target:s.symbol,capability:s.capability,...u?{edgeKind:u}:{},message:s.source==="import-based"?`${a} denies the ${s.capability} capability; found import of "${s.symbol}".`:`${a} denies the ${s.capability} capability; found ambient "${s.symbol}".`})}}for(let s of t.publishCalls){let a=n.get(s.file);if(!a)continue;for(let l of at({publishCall:!0,rawIntentName:s.rawIntentName,objectHasIntent:s.objectHasIntent,arkPublishCandidate:s.arkPublishCandidate,hasSource:s.hasSource}))r.push({ruleId:l.ruleId,file:s.file,line:s.line,...l.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:a}:{},message:l.message});if(!s.sourceIntent)continue;let c=Po(s.sourceIntent,e.contract);!c||c===a||r.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:s.file,line:s.line,fromLayer:a,toLayer:c,target:s.sourceIntent,message:`Publish source "${s.sourceIntent}" resolves to ${c}, but the publishing file is classified as ${a}.`})}for(let s of t.intentReferences){let a=n.get(s.file);if(!a)continue;let c=Po(s.intent,e.contract);if(!c)continue;let l=Te(e.contract.config.rules,a,c,{fromPath:s.file,layers:e.contract.config.layers});if(!l)continue;let u=l.rule.peerIsolation?Ke(l.peerIsolationReason??"cross-slice",{fromPath:s.file,fromSlice:l.fromSlice,toSlice:l.toSlice}):void 0,p=`${a} must not reference ${c} intent ${s.intent}.`,g=u&&l.peerIsolationReason!=="cross-slice"?`${p} ${u}`:l.rule.message?u?`${l.rule.message} (${u})`:l.rule.message:p;r.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:s.file,line:s.line,fromLayer:a,toLayer:c,target:s.intent,...l.rule.peerIsolation?{peerIsolation:!0}:{},message:g})}return r}i($c,"contentViolations");function Hc(e){let{facts:t}=e,n=pt(e.contract.config),r=t.evidenceRequirementsHash===n,o=r?t.completeness:"unavailable",s=r?t.completenessReasons:[...t.completenessReasons,{code:"EVIDENCE_REQUIREMENTS_MISMATCH",message:"Resolved facts were collected for different policy-controlled evidence requirements."}].sort((h,oe)=>{let et=`${h.code}\0${h.file??""}\0${h.message}`,tt=`${oe.code}\0${oe.file??""}\0${oe.message}`;return et<tt?-1:et>tt?1:0}),a=t.files.map(h=>({...h,layer:fe(h.path,e.contract.config.layers)??null})),c=new Map(a.map(h=>[h.path,h.layer])),l=t.dependencies.map(h=>{let oe=h.target?c.get(h.target)??fe(h.target,e.contract.config.layers):void 0;return{from:h.from,fromLayer:c.get(h.from)??null,...h.resolution==="resolved-project"&&h.target?{to:h.target,...oe?{toLayer:oe}:{}}:{},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}:{}}}),u=an({config:e.contract.config,rules:e.contract.config.rules,files:a.map(h=>h.path)}),p=Mc(e,t),g=e.contract.arkRules??De(),f=a.map(h=>h.path),d={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?yr(e.coverageInputs.fileContents):{},...e.fileHints??{}},A=i(h=>c.get(h)??fe(h,e.contract.config.layers),"resolveLayer"),b=[...mr({arkRules:g,classShapes:e.contract.classShapes??t.classShapes??[],files:f,layerForFile:A,fileHints:d}),...gr(g,f),...go({arkRulesActive:Lc(e.contract.config),arkRules:g,layers:e.contract.config.layers??[],files:f.map(h=>({path:h,layer:A(h)}))})],O=(g.invariants?.length??0)>0,k=Bs({hasEnforcedInvariant:tr(g.invariants),coverage:e.contract.config.coverage,...e.coverageRootsPresent===!1?{declaredPathPresent:!1}:{}}),I=k.length>0?[]:Gs({adopted:e.adopted===!0,hasDomainInvariants:er(g.invariants),coverage:e.contract.config.coverage,...e.invariantTestsPathPresent===!1?{declaredPathPresent:!1}:{}}),C=[...k.map(h=>({ruleId:h.ruleId,file:h.file,line:h.line,message:h.message,nextAction:"Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. An enforced invariant fails closed until that path is present.",failsStrict:!0,freezable:!1})),...I.map(h=>({ruleId:h.ruleId,file:h.file,line:h.line,message:h.message,nextAction:"Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present.",failsStrict:!0,freezable:!1}))],L=b.filter(h=>h.failsStrict).map(h=>No(h,wo(h,!1))),E=b.filter(h=>!h.failsStrict).map(h=>({...No(h,wo(h,!0)),failsStrict:!1})),P=O?Zn({arkRules:g,fileContents:e.coverageInputs?.fileContents??{},testFiles:e.coverageInputs?.testFiles??[],testGlobsMissing:e.coverageInputs?.testGlobsMissing===!0||e.coverageInputs===void 0||(e.coverageInputs.testFiles?.length??0)===0,coverageBudgetExhausted:e.coverageInputs?.coverageBudgetExhausted===!0,...e.coverageInputs?.stats?{coverageStats:e.coverageInputs.stats}:{},...e.coverageInputs?.coverageRoots?{coverageRoots:e.coverageInputs.coverageRoots}:{}}):{coverage:[],violations:[],partial:!1},ee=P.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.`})),T=P.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:h.ruleId==="INVARIANT_COVERAGE_OUTSIDE_ROOTS"?`Move ${h.file} under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json.`:`Cover invariant ${h.arkruleId} in ${h.arkruleSource} (advisory / partial).`})),V=Ar(a),D=on({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=>c.get(h)??fe(h,e.contract.config.layers),"layerForFile"),classification:V}),se=e.contract.config.arkRun?.mode,J=D.findings.filter(()=>se==="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}:{}})),be=D.findings.filter(()=>se!=="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})),Ae=xr({arkOrder:e.contract.config.arkOrder,layers:e.contract.config.layers,planeCalls:t.arkOrderPlaneCalls,genericUpdates:t.arkOrderGenericUpdates,planeRootHits:t.arkOrderRootHits,xiFieldWrites:t.arkOrderXiFieldWrites,ingestWritesXi:t.arkOrderIngestWritesXi,releaseKeyCounts:t.arkOrderReleaseKeyCounts,dependencies:t.dependencies,layerForFile:i(h=>c.get(h)??fe(h,e.contract.config.layers),"layerForFile"),classification:V}),Qe=e.contract.config.arkOrder?.mode,Tt=Ae.findings.filter(()=>Qe==="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}:{}})),Xr=Ae.findings.filter(()=>Qe!=="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})),v=[...P.partial&&P.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."}]:[],...D.completenessReasons,...Ae.completenessReasons],_=Ye({config:e.contract.config,rules:e.contract.config.rules,files:a.filter(h=>h.layer).map(h=>h.path),contentViolations:[...$c(e,t,c),...L,...C,...ee,...J,...Tt],edges:l,warnings:[...u,...p.warnings,...E,...T,...be,...Xr],safety:p.report}),y=o==="complete"&&v.length>0?"partial":o,R=y==="complete"?s:[...s,...v].sort((h,oe)=>{let et=`${h.code}\0${h.file??""}\0${h.message}`,tt=`${oe.code}\0${oe.file??""}\0${oe.message}`;return et<tt?-1:et>tt?1:0}),M=_.violations.filter(h=>h.failsStrict!==!1),Y=y==="complete"&&M.length===0,ve=Y&&_.warnings.every(h=>h.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:y,completenessReasons:R,valid:Y,strictValid:ve,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:p.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:a,layers:e.contract.config.layers.map(h=>h.name),edges:l,capabilityUses:t.capabilityUses,violations:_.violations,warnings:_.warnings}}}i(Hc,"analyzeCanonicalResolvedProject");function vt(e){return Hc({contract:e.contract,facts:_e(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints,adopted:e.adopted,invariantTestsPathPresent:e.invariantTestsPathPresent,coverageRootsPresent:e.coverageRootsPresent})}i(vt,"analyzeResolvedProject");function Lo(e){return X(H(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}i(Lo,"analysisTreeHash");function Do(e){let t=Rt(e),n=new Map(t.ir.files.map(d=>[d.path,d])),r=[],o=new Set,s=[];for(let d of e.changes){let A=d.path.replace(/\\/g,"/"),b=Me(d.path);if(!b||b===".."||b.startsWith("../")||A.startsWith("/")||/^[A-Za-z]:\//.test(A)||A.includes("\0")){s.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(o.has(b)){s.push({ruleId:"DUPLICATE_CHANGE_PATH",file:b,line:1,message:`The atomic change set contains more than one operation for ${b}.`});continue}o.add(b),"delete"in d&&d.delete&&!n.has(b)&&s.push({ruleId:"DELETE_TARGET_MISSING",file:b,line:1,message:`Cannot delete ${b} because it is not present in the supplied base tree.`}),r.push("delete"in d&&d.delete?{path:b,delete:!0}:{path:b,content:"content"in d?d.content:""})}e.changes.length===0&&s.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let a=Qt({...e,changes:r}),c=new Map(a.ir.files.map(d=>[d.path,d])),l=a.ir.violations.filter(d=>d.ruleId==="CAPABILITY_VIOLATION"||d.ruleId==="FORBIDDEN_GLOBAL").map(d=>{let A=c.get(d.evidence.file)?.layer;return{ruleId:d.ruleId,file:d.evidence.file,line:d.evidence.line,target:d.symbol,...d.capability?{capability:d.capability}:{},...A?{fromLayer:A}:{},edgeKind:"import",message:d.message}}),u=Ye({config:e.contract.config,rules:e.contract.config.rules,files:a.ir.files.map(d=>d.path),contentViolations:l,edges:a.ir.edges.filter(d=>!!d.fromLayer).map(d=>({from:d.from,fromLayer:d.fromLayer,...d.to?{to:d.to}:{},...d.toLayer?{toLayer:d.toLayer}:{},line:d.evidence.line,kind:"import",...d.typeOnly?{typeOnly:!0}:{},...d.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),p=r.map(d=>{let A=Me(d.path),b=n.get(A),O=c.get(A);return{path:A,operation:"delete"in d&&d.delete?"delete":b?"update":"create",...b?{beforeContentHash:b.contentHash}:{},...O?{candidateContentHash:O.contentHash}:{}}}).sort((d,A)=>d.path.localeCompare(A.path)),g=[...s,...u.violations].map(d=>({...d,nextAction:ge(d)})),f=g.filter(d=>d.failsStrict!==!1),m=e.changeMap?qe({changeMap:e.changeMap,changes:p,baseDependencies:t.ir.edges.flatMap(d=>d.to?[{from:d.from,to:d.to}]:[]),candidateDependencies:a.ir.edges.flatMap(d=>d.to?[{from:d.from,to:d.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&a.valid&&f.length===0&&(m?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:a.ir.compilerOptionsHash,baseTreeHash:Lo(t.ir.files),candidateTreeHash:Lo(a.ir.files),baseCompleteness:t.completeness,candidateCompleteness:a.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:a.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...m?{convergence:m}:{},changes:p,violations:g,warnings:u.warnings}}i(Do,"preflightChange");function jc(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let o of t.split("/"))if(!(!o||o==="."))if(o===".."){if(n.length===0)return;n.pop()}else n.push(o);let r=n.join("/");return r&&r===t?r:void 0}i(jc,"canonicalChangePath");function Kc(e,t){return[["resolverIdentity",e.resolverIdentity,t.resolverIdentity],["compilerIdentity",e.compilerIdentity,t.compilerIdentity],["evidenceRequirementsHash",e.evidenceRequirementsHash,t.evidenceRequirementsHash],["projectPackageName",e.projectPackageName??"",t.projectPackageName??""]].filter(([,r,o])=>r!==o).map(([r,o,s])=>({ruleId:"FACTS_IDENTITY_MISMATCH",file:"<change-set>",line:1,field:r,before:o,candidate:s,message:`Base and candidate facts must use the same ${r}.`}))}i(Kc,"identityViolations");function Vc(e,t,n,r){let o=n.get(t),s=r.get(t);return{path:t,operation:"delete"in e&&e.delete?"delete":o?"update":"create",...o?{beforeContentHash:o.contentHash}:{},...s?{candidateContentHash:s.contentHash}:{}}}i(Vc,"preparedChange");function Mo(e){let t=_e(e.baseFacts),n=_e(e.candidateFacts),r=vt({contract:e.contract,facts:t}),o=vt({contract:e.contract,facts:n}),s=new Map(t.files.map(m=>[m.path,m])),a=new Map(n.files.map(m=>[m.path,m])),c=Kc(t,n),l=new Map,u=[];for(let m of e.changes){let d=jc(m.path);if(!d){c.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(l.has(d)){c.push({ruleId:"DUPLICATE_CHANGE_PATH",file:d,line:1,message:`The atomic change set contains more than one operation for ${d}.`});continue}l.set(d,m);let A=s.get(d),b=a.get(d);if("delete"in m&&m.delete)A||c.push({ruleId:"DELETE_TARGET_MISSING",file:d,line:1,message:`Cannot delete ${d} because it is not present in the supplied base facts.`}),b&&c.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:d,line:1,message:`Candidate facts still contain deleted file ${d}.`});else{let O="content"in m?m.content:"",k=X(O);b?b.contentHash!==k&&c.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:d,line:1,expectedContentHash:k,candidateContentHash:b.contentHash,message:`Candidate facts for ${d} do not match the declared content.`}):c.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:d,line:1,message:`Candidate facts do not contain changed file ${d}.`})}u.push(Vc(m,d,s,a))}e.changes.length===0&&c.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});for(let m of new Set([...s.keys(),...a.keys()])){if(l.has(m))continue;let d=s.get(m),A=a.get(m);d&&A&&H(d)===H(A)||c.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:m,line:1,message:`Candidate facts change ${m}, but the atomic change set does not declare it.`})}let p=e.changeMap?qe({changeMap:e.changeMap,changes:u,baseDependencies:r.ir.edges.flatMap(m=>m.to?[{from:m.from,to:m.to}]:[]),candidateDependencies:o.ir.edges.flatMap(m=>m.to?[{from:m.from,to:m.to}]:[])}):void 0,g=[...c,...o.ir.violations].map(m=>({...m,nextAction:ge(m)})),f=g.filter(m=>m.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&o.strictValid&&f.length===0&&(p?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,resolverIdentity:n.resolverIdentity,compilerIdentity:n.compilerIdentity,compilerOptionsHash:n.compilerOptionsHash,tsconfigHash:n.tsconfigHash,baseCompilerOptionsHash:t.compilerOptionsHash,candidateCompilerOptionsHash:n.compilerOptionsHash,baseTsconfigHash:t.tsconfigHash,candidateTsconfigHash:n.tsconfigHash,evidenceRequirementsHash:n.evidenceRequirementsHash,baseFactsHash:t.factsHash,candidateFactsHash:n.factsHash,baseTreeHash:t.candidateTreeHash,candidateTreeHash:n.candidateTreeHash,baseCompleteness:r.completeness,candidateCompleteness:o.completeness,baseCompletenessReasons:r.completenessReasons,candidateCompletenessReasons:o.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...p?{convergence:p}:{},changes:u.sort((m,d)=>m.path<d.path?-1:m.path>d.path?1:0),violations:g,warnings:o.ir.warnings}}i(Mo,"preflightResolvedChange");var Fo="1.0",Uc=12,Gc="Layers stop a bad import. ArkRun is an optional experimental runtime \u2014 in-memory, not Postgres. Data is gone on restart.",Bc="Next: /ark-runtime to wire one candidate.";function $o(e){return e==="enforced"||e==="advisory"?e:null}i($o,"closedMode");function zc(e){let t=new Set;if(!Array.isArray(e))return[];for(let n of e){let r=n?.ruleId;typeof r!="string"||!Rr(r)||t.has(r)||t.add(r)}return[...t].sort((n,r)=>n<r?-1:n>r?1:0)}i(zc,"uniqueArkRunRuleIds");function Wc(e){return!e||typeof e!="object"?{present:!1,mode:null,roots:0,layers:0,requireDeclarations:null}:{present:!0,mode:$o(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(Wc,"extraFromConfig");function qc(e={}){let t=Wc(e.arkRun),n=t.present?zc(e.findings):[],r=n.slice(0,Uc),o=n.length,s=rn({classification:e.classification,arkRules:{active:e.arkRules?.active===!0,structureEnforced:e.arkRules?.structureEnforced,structureTotal:e.arkRules?.structureTotal,structureAdvisory:e.arkRules?.structureAdvisory,invariantEnforced:e.arkRules?.invariantEnforced,invariantTotal:e.arkRules?.invariantTotal,invariantAdvisory:e.arkRules?.invariantAdvisory,covered:e.arkRules?.covered,uncovered:e.arkRules?.uncovered},arkRun:{present:t.present,mode:t.mode,residualCount:o}}),a=t.present&&t.mode==="enforced"&&he(e.classification),c;return t.present?t.mode==="advisory"?c="Advisory ArkRun residual only \u2014 never flips valid or --strict-merge. Residual is a finding-id count, never a score.":a?c="Enforced ArkRun is on the extra merge plane. Residual is a finding-id count, never a score.":c="Enforced ArkRun extra teeth stay demoted until the layer plane is honestly classified. Residual is a finding-id count, never a score.":c="Absence of arkRun is silent \u2014 Layers and ArkRules verdicts unchanged. Not a score.",{schemaVersion:Fo,notAScore:!0,active:t.present,mode:t.mode,compositionRoots:t.roots,managedLayers:t.layers,requireDeclarations:t.requireDeclarations,residual:{count:o,ruleIds:r},extraMergeTeeth:a,failMergeWhen:s.failMergeWhen,note:c,mergePlanes:s}}i(qc,"summarizeArkRunSection");function Tr(e={}){let t=e.present===!0,n=$o(e.mode),r=e.residual,o=null;return typeof r=="number"&&Number.isFinite(r)&&r>=0&&(o=Math.floor(r)),t||(o=o??0),{notAScore:!0,present:t,mode:t?n:null,extraMergeTeeth:t&&n==="enforced"&&e.extraMergeTeeth===!0,residual:o}}i(Tr,"projectStatusArkRun");function Yc(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=[Gc,`mode: ${t} \xB7 extra merge teeth ${n} \xB7 not a score`];if(e.residual.count>0){let o=e.residual.ruleIds.join(", "),s=e.residual.count>e.residual.ruleIds.length?` (+${e.residual.count-e.residual.ruleIds.length} more)`:"";r.push(`Residual: ${o}${s}`),r.push(Bc)}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(Yc,"formatArkRunDoctorLines");function ln(e,t){return e.slice(0,t).split(`
|
|
13
|
+
`).length}i(ln,"lineOf");function Ho(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}i(Ho,"normalizeInventoryPath");function Ko(e,t){return e.some(n=>{let r=n.trim().replace(/\.+$/,"");return t.some(o=>r===o||r.startsWith(`${o}.`))})}i(Ko,"ownsIntent");function jo(e,t=[]){return/domain|entity|aggregate|model/i.test(e)||Ko(t,["Domain"])}i(jo,"isDomainLayer");function Jc(e,t=[]){return/application|orchestration|presentation|adapter|framework|interface|delivery|transport|inbound|controller/i.test(e)||Ko(t,["Application","Orchestration","Presentation","Adapter","Interface","Delivery","Transport"])}i(Jc,"isControllerEligibleLayer");function Xc(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(Xc,"isNonPilotSurface");function Zc(e){let t=[],n=0,r=new Map(Object.entries(e.fileLayers??{}).map(([l,u])=>[Ho(l),u])),o=new Map((e.layerContexts??[]).map(l=>[l.name,l.intentPrefixes??[]])),s=(e.layerContexts??[]).find(l=>jo(l.name,l.intentPrefixes))?.name??"DomainModel";for(let[l,u]of Object.entries(e.fileContents).sort(([p],[g])=>p.localeCompare(g))){let p=Ho(l);if(Xc(p)||/GENERATED FILE\s+[—-]\s+do not edit by hand/i.test(u.slice(0,320)))continue;let g=r.has(p),f=r.get(p),m=f?o.get(f)??[]:[],d=/(?:^|\/)(?:components|ui|layouts|styles|hooks|theme|tokens|i18n|locales?)(?:\/|$)/i.test(p)||/(?:^|\/)(?:src\/)?(?:app|pages)\/.+\.(?:tsx|jsx)$/i.test(p)&&/(?:page|layout|loading|error|template|default)\.(?:tsx|jsx)$/i.test(p),A=/(?:^|\/)(?:app|pages)(?:\/[^/]+)*\/api(?:\/|$)/i.test(p),b=/(?:^|\/)actions?(?:\/|\.|$)/i.test(p)||/['"]use server['"]/.test(u),O=/controller|handler|resolver/i.test(l)||A||b||/route\.(?:ts|js|tsx|jsx)$/i.test(p)&&!d||/@(Controller|Get|Post|Put|Delete|Patch)\b/.test(u)||/\bexport\s+(?:async\s+)?function\s+(?:GET|POST|PUT|DELETE|PATCH)\b/.test(u)||/\bexport\s+const\s+(?:GET|POST|PUT|DELETE|PATCH)\s*=/.test(u),k=g?!!(f&&Jc(f,m)&&O):O,I=g?!!(f&&jo(f,m)):/domain|entity|aggregate|model/i.test(l),C=!g||I||k;if(k&&!d){let T=/\b(if\s*\([^)]{0,80}(amount|total|price|qty|quantity|balance)[^)]{0,40}\)|throw new (Error|BadRequest|ValidationError)|z\.object\(|yup\.|class-validator|@Is[A-Z])/g,V;for(;(V=T.exec(u))!==null;)n+=1,t.push({id:`inv-val-${n}`,kind:"validation-in-controller",file:l,line:ln(u,V.index),message:"Business validation appears in a controller/handler \u2014 extract an invariant or Domain rule.",confidence:"direct-evidence",governedLayer:f,suggestedArkRule:{layer:s,invariantId:`INV-EXTRACT-${n}`,sensor:"invariant-coverage"},neverMechanicalSafe:!0})}let L=/\b(const|let)\s+([A-Z][A-Z0-9_]{2,})\s*=\s*(\d{2,}|['"][^'"]{8,}['"])/g,E,P=i(T=>/^(?:TEST|SPEC|TIMEOUT|PORT|VERSION|MAX_RETRY|MIN_RETRY|TTL|CACHE|HEADER|COOKIE|MIME|CONTENT_TYPE|HTTP_STATUS|NODE_ENV|LOG_LEVEL|FEATURE_FLAG|ID_PREFIX|Z_INDEX)(?:_|$)/i.test(T)||/^(?:ROUTE|PATH|LABEL|TITLE|HEADING|CLASS|STYLE|COLOR|THEME|BREAKPOINT|QUERY|PARAM|ICON|ARIA|MSG|COPY|I18N|LOCALE|PAGE|NAV|MENU|TAB|BTN|BUTTON|PLACEHOLDER|TOOLTIP|SHADOW|RADIUS|GAP|PADDING|MARGIN|FONT|WIDTH|HEIGHT|OPACITY|DURATION|EASE|ANIM)_/i.test(T)||/_(?:ROUTE|PATH|LABEL|TITLE|COLOR|THEME|CLASS|STYLE|ICON|ARIA|MSG|COPY|TIMEOUT|PORT|VERSION|RETRY|DELAY|INTERVAL|TTL|CACHE)$/i.test(T)||/_(?:TIMEOUT(?:_MS)?|MS|BYTES|BUCKET|STORAGE_KEY|WINDOW_MS)$/i.test(T)||/^(?:DEFAULT_(?:BASE_URL|TIMEOUT(?:_MS)?|RETRY|PORT|HOST|HEADERS?|CACHE|TTL|MS|LOCALE|LANG|TIMEZONE|TZ)|REQUEST_(?:TIMEOUT(?:_MS)?|HEADERS?|RETRY|ID_PREFIX)|STORAGE_(?:KEY|PREFIX|BUCKET)|DAY_MS$|APP_DOMAIN$|BASE_URL$)$/i.test(T)||/^(?:FAVORITES_STORAGE|LISTINGS_CACHE|DOCS_PATH|METRICS_INTERVAL)/i.test(T)||/^(?:DEV|DEMO|SEED|FIXTURE)_[A-Z0-9_]+$/i.test(T)||/^(?:PG|POSTGRES|OID)_[A-Z0-9_]+$/i.test(T)||/_(?:OID|OIDS)$/i.test(T)||/^(?:INT2|INT4|INT8|FLOAT4|FLOAT8|NUMERIC|DATE|TIME|TIMESTAMP|TIMESTAMPTZ|JSON|JSONB|UUID)OID$/i.test(T)||/(?:^|_)(?:SCHEMA|PROTOCOL|RESOLVER|FORMAT)_(?:URL|URI|VERSION|ID|IDENTITY)$/i.test(T),"isInfraMagicName"),ee=i((T,V)=>{if(/^(?:ERROR|SUCCESS|WARNING|INFO|HINT|HELP|EMPTY|TOAST|SNACK|ALERT|BANNER|DIALOG|MODAL|TOOLTIP|CAPTION|SUBTITLE|HEADLINE|USER|UI|DISPLAY|FEEDBACK)_(?:MSG|MESSAGE|TEXT|COPY|LABEL|TITLE|BODY|DESC|DESCRIPTION|HINT|HELP)?/i.test(T)||/_(?:MSG|MESSAGE|TEXT|COPY|TOAST|SNACK|ALERT|BANNER|CAPTION|HINT|HELP_TEXT|ERROR_TEXT|EMPTY_TEXT|PLACEHOLDER_TEXT|USER_MESSAGE|FEEDBACK)$/i.test(T))return!0;let D=V.replace(/^['"]|['"]$/g,"");return!!(/^['"]/.test(V)&&(/\s/.test(D)||/[.!?…]$/.test(D))&&!/^(?:STATUS|STATE|PHASE|ROLE|TYPE|KIND|ORDER|PAYMENT|CART|INVOICE|POLICY)_[A-Z0-9_]+$/i.test(T))},"isUxMessageConstant");for(;(E=L.exec(u))!==null;){let T=E[2],V=E[3]??"";!C||P(T)||ee(T,V)||d&&!I||/(?:^|\/)(?:integrations?|repos?|clients?|infra(?:structure)?|adapters?)(?:\/|$)/i.test(p)&&!I||(n+=1,t.push({id:`inv-magic-${n}`,kind:"magic-business-constant",file:l,line:ln(u,E.index),message:`Magic business constant ${T} may belong in a Domain policy or invariant catalog.`,confidence:"heuristic",governedLayer:f,suggestedArkRule:{layer:s,invariantId:`INV-${T}`},neverMechanicalSafe:!0}))}if(I){let T=/export\s+class\s+([A-Za-z_][A-Za-z0-9_]*)\s*\{([^}]{0,800})\}/g,V;for(;(V=T.exec(u))!==null;){let D=V[2]??"",se=(D.match(/\b[a-zA-Z_][a-zA-Z0-9_]*\s*\(/g)??[]).length;(D.match(/:\s*[A-Za-z]/g)??[]).length>=2&&se<=1&&(n+=1,t.push({id:`inv-anemic-${n}`,kind:"anemic-entity",file:l,line:ln(u,V.index),message:`Class ${V[1]} looks anemic (data-heavy, few behaviors).`,confidence:"heuristic",governedLayer:f,suggestedArkRule:{layer:s,structureId:"no-anemic-model",sensor:"no-anemic-model"},neverMechanicalSafe:!0}))}}if(I&&!(/\.error\.(?:ts|js|tsx|jsx)$/i.test(p)||/(?:^|\/)[^/]*(?:-access)?\.error\./i.test(p)||/(?:^|\/)errors?(?:\/|$)/i.test(p))){let V=/\bthis\.[A-Za-z_][A-Za-z0-9_]*\s*=(?!=)/g,D;for(;(D=V.exec(u))!==null;){let se=u.lastIndexOf("class ",D.index),J=se>=0?u.indexOf("{",se):-1,be=se>=0&&J>=se&&J<D.index?u.slice(se,J):"";if(/\bextends\s+(?:Error|[A-Za-z_$][A-Za-z0-9_$]*Error)\b/.test(be)||fr(u,D.index))continue;let Ae=u.slice(Math.max(0,D.index-200),D.index+200);if(!dr.test(Ae)&&!ur.test(Ae)){n+=1,t.push({id:`inv-mut-${n}`,kind:"mutation-without-guard",file:l,line:ln(u,D.index),message:`Domain field mutation without nearby ${pr()}.`,confidence:"heuristic",governedLayer:f,suggestedArkRule:{layer:s,structureId:"events-on-mutation",sensor:"domain-event-on-mutation"},neverMechanicalSafe:!0});break}}}}let a=new Set(e.contractedRuleIds??[]);t.sort((l,u)=>+(u.confidence==="direct-evidence")-+(l.confidence==="direct-evidence")||l.file.localeCompare(u.file)||l.line-u.line||l.kind.localeCompare(u.kind)||l.id.localeCompare(u.id));let c=t.filter(l=>l.suggestedArkRule?.invariantId&&a.has(l.suggestedArkRule.invariantId)||l.suggestedArkRule?.structureId&&a.has(l.suggestedArkRule.structureId)).length;return{candidates:t,inventoried:t.length,underContract:c,frozen:(e.frozenKeys??[]).length,notAScore:!0}}i(Zc,"buildRulesInventory");function Qc(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(Qc,"inventoryToExtractionCard");var ed="1.1";var td="1.0";var Nr="docs/diagnostics.md",nd="1.0";function S(e,t,n,r,o,s){return{ruleId:e,title:n,why:r,fix:o,docsAnchor:e,category:t,...s?.oftenAdvisory?{oftenAdvisory:!0}:{}}}i(S,"entry");var cn=Object.freeze([S("LAYER_IMPORT_VIOLATION","layer","This import is not allowed","This file imported a folder it may not reach. The write doesn\u2019t land. The same check fails the pull request.","Branch by import kind: constants/types/pure \u2192 adopt into DomainModel or SharedKernel (do not invent a port); kernel/events/bootstrap from Persistence \u2192 inject a port or move the map to SharedTypes (Persistence must not emit); define a port only when the target is a real use-case. Type-only edges use `import type`. Then preflight again. Do not weaken the layer rule without a hash-bound policy acknowledgement."),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, 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."),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("ARKRULE_HINT_BUDGET_EXHAUSTED","arkrules","Structural-hint budget exhausted","orchestration-only, thin-adapter, and writes-via-aggregate only evaluate files the hint loader preloaded. When eligible governed files exceed that budget (coverage.maxFiles, default 400 \u2014 there is no arkrules.hintBudget), those sensors never saw the rest of their scope. Enforced + unreviewed is not green. The finding names exact hinted/governed counts and per-sensor reviewed N/M of scope.","Raise coverage.maxFiles in ark.config.json (this cap also bounds structural-hint preload; --doctor names the coupling) so hinted/governed counts match, then re-run with --strict-config. An enforced hint sensor that cannot see its scope fails strict."),S("INVARIANT_CATALOG_EMPTY","arkrules","Domain invariant catalog is empty","ArkRules is on and a Domain-role layer has code, but invariants[] has no phrases the code must preserve. Empty looks like \u201Cdone\u201D until someone fills the catalog.","Add 1\u20132 short phrases to invariants[] in arkrules/<Domain>.json (or the mapped file). Starters show the shape. Advisory unless a domain structure rule is already enforced \u2014 then --strict-merge can refuse. Do not freeze this finding.",{oftenAdvisory:!0}),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. When the message reports an exhausted file budget, raise coverage.maxFiles (or narrow coverage.testGlobs) in ark.config.json."),S("INVARIANT_COVERAGE_OUTSIDE_ROOTS","arkrules","Covering test outside the declared coverage roots","The only test naming this invariant sits outside coverage.coverageRoots \u2014 the places the project declares its runner executes. ArkGate matches declared text and never executes tests, so it cannot tell whether that file is ever run: coverage there is a test that exists, not a test that runs.","Move the test under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json. Advisory: it never fails strict, but promotion to enforced refuses on it.",{oftenAdvisory:!0}),S("INVARIANT_TESTS_PATH_MISSING","arkrules","Domain-invariant tests path missing under adopted","The project is adopted (required CI or explicit advisory) and has domain invariants that want test evidence, but ark.config.json does not name where those tests live. Green coverage without a real tests path is an empty checkbox.","Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present. Not freezable."),S("INVARIANT_COVERAGE_ROOTS_MISSING","arkrules","Coverage roots missing while an invariant is enforced","A catalogued domain invariant is enforced, but ark.config.json does not name coverage.coverageRoots \u2014 the folders where the project says its test runner actually goes. Without that declaration, INVARIANT_COVERAGE_OUTSIDE_ROOTS cannot fire and coverage can certify a test no runner runs.","Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. testGlobs alone is not enough. Fail-closed until that path is present. Not freezable."),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 a big product choice","A call to update/patch/set rewrites a named product choice (like billing plan) as if it were a seat count.","Don't use a generic update. First freeze with release(). Later, propose the change, then apply it."),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, escalate_up, or hold; it never mints a pattern.","Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe."),S("ARKORDER_XI_FIELD_WRITE","arkorder","Big product choice written like a seat count","A use-case writes a named product choice (like billing plan) through a database update. Invoices and seats can flow. That choice cannot.","Keep invoices and seats as events. Change the choice through the valve (proposeRelease then apply), not a generic update."),S("ARKORDER_INFORMATION_BUDGET","arkorder","Projection observes a forbidden kind","h(\u03BE) allowedKinds includes a kind listed in informationBudget.cannotObserve. A scale may not look at what it was told not to see.","Cut that kind from the projector or from cannotObserve, then preflight again. Never mechanical-safe."),S("ARKORDER_XI_TTL","arkorder","Slow key carries a freshness field","\u03BE named ttl/freshUntil/maxAge. Freshness belongs on \u03C3. A slow parameter that expires per transaction is not slow.","Move freshness onto \u03C3 (freshUntil) and keep \u03BE stable, then preflight again. Never mechanical-safe."),S("ARKORDER_STALE_SIGMA","arkorder","\u03C3 is stale","ingest ran after \u03C3.freshUntil (or sigmaMaxAgeMs). \u03BE does not TTL.","Call refreshSigma and ingest again, or proposeRelease then apply(ProposeResult) if the pattern changed. Never mechanical-safe."),S("ARKORDER_UNVALVED_RELEASE","arkorder","Second freeze without the valve","release() already froze the big choice. A later release() with a different value does not land. First freeze is release(); later change is proposeRelease then apply.","Change the choice with proposeRelease then apply. release() is only the first freeze. Never mechanical-safe."),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","This check only saw one file, so it cannot fully prove how the import resolves. The result is provisional \u2014 `ark-check` on the project is the authority.","Run `npx arkgate-check --root . --config ark.config.json` to confirm. Do not call ark_prepare_change from a hook deny."),S("ANALYSIS_COVERS_NO_FILES","analysis","Analysis covered no files","No file matched the contract include and layer patterns under the analyzed root, so the run had nothing to check. Every rule is vacuously satisfied on an empty set: a green here would read exactly like a green over a governed tree while certifying nothing. Usual causes are a --root that is not the tree the contract describes (including a contract found outside the requested root, whose directory is then adopted as the project root), include / exclude patterns that match nothing, or layer patterns written for a different layout.","Point --root at the tree the contract describes, or keep the contract inside that tree, or fix the include / exclude / layer patterns so they match real files \u2014 then re-run `npx arkgate-check --root . --config ark.config.json`. This is a refusal about ArkGate\u2019s own inputs, not a finding about your code; no baseline or policy acknowledgement can suppress it."),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("CONFIG_LAYER_MISSING_OWNER","config","Layer missing owner","requireLayerOwners is on and this layer has no owners. Writes to that house fail closed, like a folder with no name on the door.","Add a GitHub handle or email to that layer\u2019s owners in ark.config.json (/ark-adopt), then re-run. Reserved/allowEmpty houses may stay unnamed. Turn the flag off only if you no longer want owners required."),S("LITERAL_PATH_DRIFT","drift","Literal path moved by a rename","A repo path written inside a string, a comment or a docstring no longer resolves, and the rename set says where it went. Nothing in the gate sees this class: `tsc` resolves imports, not strings, and ESLint does not either, so the rename compiles green and the reference lies afterwards. It appears in four forms \u2014 the tsconfig alias, a relative literal, a path written without the include-root prefix, and prose \u2014 and a hand sweep reliably covers one of them.","Apply the suggested replacement, or re-run `npx arkgate-check --path-drift --base-ref <ref> --write` to apply every writable anchored replacement at once. The rewrite is mechanical and one-directional: the destination comes from the rename, it must itself resolve and be path-shaped, and the token is rewritten in the form the author wrote it in. A destination that leaves the alias root of the literal is reported with the target only and must be rewritten by hand."),S("LITERAL_PATH_UNRESOLVED","drift","Literal path does not resolve","A literal that looks like a repo path does not resolve under this root, and no rename explains where it went. Unlike LITERAL_PATH_DRIFT this is a candidate, not a verdict: with nothing to anchor it, ArkGate cannot tell a dead reference from an illustrative path in a comment, an example in documentation, or a path belonging to another tree.","Read the candidate and decide: fix the path, or leave it. Advisory only \u2014 it never fails a run and is never rewritten by --write, because there is no destination to propose. Run `--path-drift --all` to list the sweep.",{oftenAdvisory:!0}),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.")]),wr=new Map(cn.map(e=>[e.ruleId,e])),rd=Object.freeze(cn.map(e=>e.ruleId));function sd(e){return typeof e=="string"&&e.length>0&&wr.has(e)}i(sd,"isKnownDiagnosticCode");function od(e){return typeof e!="string"||e.length===0?!1:wr.has(e)?!0:e.startsWith("ARKRULE_")}i(od,"isCataloguedOrArkRuleFamily");function dn(e){if(!(typeof e!="string"||e.length===0))return wr.get(e)}i(dn,"getDiagnosticCatalogEntry");function Vo(e){return`#${dn(e)?.docsAnchor??e}`}i(Vo,"diagnosticDocsFragment");function ad(e){return`${Nr}${Vo(e)}`}i(ad,"diagnosticDocsPath");function id(){return{schemaVersion:"1.0",docsPath:Nr,codes:cn}}i(id,"serializeDiagnosticCatalog");function ld(e){return dn(e)?.fix}i(ld,"catalogFixForRuleId");function cd(e){return dn(e)?.why}i(cd,"catalogWhyForRuleId");function dd(e){return e==="enforced"||e==="advisory"?e:null}i(dd,"closedMode");function Uo(e={}){let t=e.present===!0,n=dd(e.mode),r=e.residual,o=null;return typeof r=="number"&&Number.isFinite(r)&&r>=0&&(o=Math.floor(r)),t||(o=o??0),{notAScore:!0,present:t,mode:t?n:null,extraMergeTeeth:t&&n==="enforced"&&e.extraMergeTeeth===!0,residual:o}}i(Uo,"projectStatusArkOrder");var Pr="1.0",Go="https://unpkg.com/arkgate@4/schemas/ark.status-manifest.schema.json",Bo=["full","subset","unavailable"],zo=["doctor-facts","report-snapshot","none"],un={FACTS_UNAVAILABLE:"FACTS_UNAVAILABLE",FACTS_PARTIAL:"FACTS_PARTIAL",NO_SESSION_SNAPSHOT:"NO_SESSION_SNAPSHOT"},Wo=/^sha256:[a-f0-9]{64}$/;function qo(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"||!Wo.test(r)))return{status:"mismatch",authoritative:!1,code:"INVALID_PROJECT_EXPECTATION",message:"project.expectedProjectId must be a sha256:<64 lowercase hex> identity."};if(n===void 0&&r!==void 0)return e.projectId&&r!==e.projectId?{status:"mismatch",authoritative:!1,expectedProjectId:r,code:"PROJECT_ID_MISMATCH",message:`Expected project id ${r}, but this process is bound to ${e.projectId}.`}:{status:"unverified",authoritative:!1,expectedProjectId:r,message:"project.expectedProjectId matched or could not be compared, but expectedRoot is required for an authoritative workspace binding."};let o=e.expectedRootRelation??"unknown";return o==="outside"?{status:"mismatch",authoritative:!1,expectedRoot:n,expectedProjectId:r,code:"PROJECT_ROOT_MISMATCH",message:`Expected workspace ${n}, but this process is bound to ${e.resolvedRoot}.`}:o==="unknown"?{status:"unverified",authoritative:!1,expectedRoot:n,expectedProjectId:r,message:"Could not prove expectedRoot against the resolved project root (stale or incomplete path evidence)."}:o==="descendant"&&r===void 0?{status:"unverified",authoritative:!1,expectedRoot:n,message:`Expected workspace ${n} is inside this project, but an exact project root is required for the initial authoritative handshake.`}:r!==void 0&&e.projectId&&r!==e.projectId?{status:"mismatch",authoritative:!1,expectedRoot:n,expectedProjectId:r,code:"PROJECT_ID_MISMATCH",message:`Expected project id ${r}, but this process is bound to ${e.projectId}.`}:o==="exact"||o==="descendant"&&r&&r===e.projectId?{status:"matched",authoritative:!0,...n?{expectedRoot:n}:{},...r?{expectedProjectId:r}:{}}:{status:"unverified",authoritative:!1,expectedRoot:n,expectedProjectId:r,message:"Project expectation could not be fully verified."}}i(qo,"evaluateStatusBinding");function Yo(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(Yo,"classifyStatusWritePath");function Jo(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(Jo,"defaultHonestLabel");function Xo(e,t,n,r,o){return e.nextActionOverride?.id&&e.nextActionOverride.summary?{id:e.nextActionOverride.id,summary:e.nextActionOverride.summary}:t.status==="mismatch"?{id:"rebind-project-identity",summary:t.message||"Project expectation does not match this process \u2014 call ark_identity / ark status with the correct expectedRoot (and projectId for descendants)."}:t.status==="unverified"&&e.expectation?{id:"complete-identity-handshake",summary:t.message||"Supply project.expectedRoot at the exact project root (and expectedProjectId for descendants) for authoritative status."}:e.resolvedConfigPath?r.verdict==="fail"||(r.activeViolations??0)>0?{id:"fix-active-violations",summary:`Clear ${r.activeViolations??"active"} blocking architecture finding(s), then re-run ark-check (or ark-check --doctor).`}:r.verdict==="incomplete"?{id:"restore-complete-analysis",summary:"Last check was incomplete \u2014 restore TypeScript/analysis inputs and re-run ark-check."}:r.verdict==null&&r.at==null?{id:"run-ark-check",summary:"No last-check snapshot yet \u2014 run ark-check --report (or --doctor) to freeze session evidence."}:n.writePath==="unavailable"?{id:"install-write-path",summary:"Write path is unavailable \u2014 install agent gates for your host (ark start / --install-agent-gates) and keep required CI --strict-merge."}:n.writePath==="advisory"?{id:"keep-ci-merge-hard",summary:"Local write is advisory for this host \u2014 keep a required GitHub status on arkgate-check --strict-merge as the hard merge boundary."}:e.leftoverDesignWork===!0?{id:"map-leftover-design",summary:"Leftover design work remains. Map with /ark-explore, then apply one small refactor with /ark-autopilot. Green imports are not done."}:o.arkRulesLoaded&&(o.frozenResidual??0)>0?{id:"review-arkrules-residual",summary:"ArkRules residual remains frozen \u2014 review inventory debt without claiming a score."}:e.arkRun?.present===!0&&(e.arkRun.residual??0)>0?{id:"review-arkrun-residual",summary:"ArkRun residual remains \u2014 wire kernel usage or declarations through arkgate/runtime. Not a score."}:e.arkOrder?.present===!0&&(e.arkOrder.residual??0)>0?{id:"review-arkorder-residual",summary:"ArkOrder leftover remains \u2014 change that product choice through the valve (proposeRelease then apply), not a generic update. Not a score."}:e.adopted==="required-merge"||e.adopted==="advisory-only-acked"?{id:"stay-enforced",summary:"Contract looks enforceable for this session \u2014 keep writing through the gate and re-check after structural edits."}:{id:"require-ci-merge-status",summary:'Make arkgate-check --strict-merge a required GitHub status, or write .ark/adoption-stance.json with stance: "advisory-only".'}:{id:"run-ark-start",summary:"No ark.config.json found \u2014 run ark start (preview) then ark start --apply."}}i(Xo,"resolveStatusNextAction");function ud(e){let t=typeof e.resolvedRoot=="string"&&e.resolvedRoot.length>0?e.resolvedRoot:".",n=typeof e.projectId=="string"&&Wo.test(e.projectId)?e.projectId:null,r=qo({resolvedRoot:t,projectId:n,expectation:e.expectation,expectedRootRelation:e.expectedRootRelation}),o=typeof e.activeHost=="string"?e.activeHost.trim().toLowerCase():"",s=o&&o!=="unknown"?o:o==="unknown"?"unknown":null,a=Yo({hardWriteActive:e.hardWriteActive,softWriteHost:e.softWriteHost,writePathUnavailable:e.writePathUnavailable,activeHost:s}),c=typeof e.honestLabel=="string"&&e.honestLabel.trim().length>0?e.honestLabel.trim():Jo(a,s),l={at:typeof e.lastCheckAt=="string"?e.lastCheckAt:null,verdict:e.lastCheckVerdict==="pass"||e.lastCheckVerdict==="fail"||e.lastCheckVerdict==="incomplete"?e.lastCheckVerdict:null,activeViolations:Ct(e.activeViolations),frozenResidual:Ct(e.frozenResidual)},u={arkRulesLoaded:e.arkRulesLoaded===!0,inventoried:Ct(e.rulesInventoried),underContract:Ct(e.rulesUnderContract),frozenResidual:Ct(e.rulesFrozenResidual)},p={writePath:a,host:s,honestLabel:c},g={projectId:n,resolvedRoot:t,resolvedConfigPath:typeof e.resolvedConfigPath=="string"&&e.resolvedConfigPath.length>0?e.resolvedConfigPath:null,binding:r.status,authoritative:r.authoritative,...r.code?{code:r.code}:{},...r.message?{message:r.message}:{}},f={schemaVersion:Pr,arkgateVersion:typeof e.arkgateVersion=="string"&&e.arkgateVersion.length>0?e.arkgateVersion:"unknown",projectIdentity:g,activation:p,lastCheck:l,rules:u,nextAction:Xo(e,r,p,l,u)},m=Qo(e.improvementCompass);return m&&(f.improvementCompass=m),e.vsBase&&typeof e.vsBase.baseRef=="string"&&e.vsBase.baseRef.length>0&&(f.vsBase=e.vsBase),e.arkRun&&typeof e.arkRun=="object"&&(f.arkRun=Tr(e.arkRun)),e.arkOrder&&typeof e.arkOrder=="object"&&(f.arkOrder=Uo(e.arkOrder)),f}i(ud,"buildStatusManifest");var Zo=new Set(Bo),pd=new Set(zo);function Lr(e){let t=Zo.has(e.mode)?e.mode:"unavailable",n=e.factsSource!=null&&pd.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:un.FACTS_UNAVAILABLE,reason:typeof e.reason=="string"&&e.reason.length>0?e.reason:"Improvement compass facts are unavailable \u2014 run ark-check --doctor for residual lenses. Status never invents green.",factsSource:n??"none"};return r&&(a.contractHash=r),a}let o=Array.isArray(e.topResidual)?e.topResidual.filter(a=>typeof a=="string"&&a.length>0).slice(0,15):[],s={schemaVersion:"1.0",notAScore:!0,mode:t,topResidual:o};return t==="subset"?(s.reasonCode=typeof e.reasonCode=="string"&&e.reasonCode.length>0?e.reasonCode:un.FACTS_PARTIAL,s.reason=typeof e.reason=="string"&&e.reason.length>0?e.reason:"Status compass is a subset of doctor residual \u2014 incomplete session facts; run doctor for full."):typeof e.reasonCode=="string"&&e.reasonCode.length>0&&(s.reasonCode=e.reasonCode),typeof e.reason=="string"&&e.reason.length>0&&t==="full"&&(s.reason=e.reason),n&&(s.factsSource=n),r&&(s.contractHash=r),s}i(Lr,"projectStatusImprovementCompass");function fd(e={}){return Lr({mode:"unavailable",topResidual:[],reasonCode:e.reasonCode??un.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(fd,"unavailableStatusImprovementCompass");function Qo(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"&&Zo.has(t.mode)?n=t.mode:Array.isArray(t.topResidual)?n="subset":n="unavailable",Lr({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(Qo,"normalizeStatusImprovementCompass");function md(e,t){let n=Array.isArray(e)?e:[],r=new Set(Array.isArray(t)?t:[]);for(let o of n)if(!(typeof o!="string"||o.length===0)&&!r.has(o))return!1;return!0}i(md,"statusCompassResidualIsSubsetOfDoctor");function Ct(e){if(e==null)return null;let t=Number(e);return!Number.isFinite(t)||t<0?null:Math.floor(t)}i(Ct,"numberOrNull");var gd={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Go,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:Pr},arkgateVersion:{type:"string",minLength:1},projectIdentity:{type:"object",additionalProperties:!1,required:["projectId","resolvedRoot","resolvedConfigPath","binding","authoritative"],properties:{projectId:{anyOf:[{type:"string",pattern:"^sha256:[a-f0-9]{64}$"},{type:"null"}]},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{anyOf:[{type:"string",minLength:1},{type:"null"}]},binding:{enum:["matched","unverified","mismatch"]},authoritative:{type:"boolean"},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},activation:{type:"object",additionalProperties:!1,required:["writePath","host","honestLabel"],properties:{writePath:{enum:["hard","advisory","unavailable"]},host:{anyOf:[{type:"string",minLength:1},{type:"null"}]},honestLabel:{type:"string",minLength:1}}},lastCheck:{type:"object",additionalProperties:!1,required:["at","verdict","activeViolations","frozenResidual"],properties:{at:{anyOf:[{type:"string",minLength:1},{type:"null"}]},verdict:{anyOf:[{enum:["pass","fail","incomplete"]},{type:"null"}]},activeViolations:{anyOf:[{type:"integer",minimum:0},{type:"null"}]},frozenResidual:{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}},rules:{type:"object",additionalProperties:!1,required:["arkRulesLoaded","inventoried","underContract","frozenResidual"],properties:{arkRulesLoaded:{type:"boolean"},inventoried:{anyOf:[{type:"integer",minimum:0},{type:"null"}]},underContract:{anyOf:[{type:"integer",minimum:0},{type:"null"}]},frozenResidual:{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}},nextAction:{type:"object",additionalProperties:!1,required:["id","summary"],properties:{id:{type:"string",minLength:1},summary:{type:"string",minLength:1}}},improvementCompass:{type:"object",description:"Thin improvement-compass residual ids with honesty mode (notAScore). full | subset | unavailable. Never a gate input; full lenses on doctor JSON. When full, residual ids \u2286 doctor residual for the same facts. unavailable never invents green residual.",additionalProperties:!1,required:["schemaVersion","notAScore","mode","topResidual"],properties:{schemaVersion:{const:"1.0"},notAScore:{const:!0},mode:{enum:["full","subset","unavailable"]},topResidual:{type:"array",items:{type:"string",minLength:1},maxItems:15},reasonCode:{type:"string",minLength:1},reason:{type:"string",minLength:1},factsSource:{enum:["doctor-facts","report-snapshot","none"]},contractHash:{type:"string",minLength:1}}},vsBase:{type:"object",description:"Checkout vs a git base ref: pin, contract identity, baseline grow. Advisory honesty only \u2014 never a gate input.",additionalProperties:!1,required:["baseRef","line","pinLocal","pinBase","contractEqual","baselineGrew"],properties:{baseRef:{type:"string",minLength:1},line:{type:"string",minLength:1},pinLocal:{anyOf:[{type:"string",minLength:1},{type:"null"}]},pinBase:{anyOf:[{type:"string",minLength:1},{type:"null"}]},contractEqual:{type:"boolean"},baselineGrew:{type:"boolean"}}},arkRun:{type:"object",description:"ArkRun extra residual (notAScore). present/mode from config; residual is a finding-id count (null = unknown, not green). extraMergeTeeth is honesty, never a score.",additionalProperties:!1,required:["notAScore","present","mode","extraMergeTeeth","residual"],properties:{notAScore:{const:!0},present:{type:"boolean"},mode:{anyOf:[{enum:["advisory","enforced"]},{type:"null"}]},extraMergeTeeth:{type:"boolean"},residual:{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}},arkOrder:{type:"object",description:"ArkOrder extra residual (notAScore). present/mode from config; residual is a finding-id count (null = unknown, not green). extraMergeTeeth is honesty, never a score.",additionalProperties:!1,required:["notAScore","present","mode","extraMergeTeeth","residual"],properties:{notAScore:{const:!0},present:{type:"boolean"},mode:{anyOf:[{enum:["advisory","enforced"]},{type:"null"}]},extraMergeTeeth:{type:"boolean"},residual:{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}}}};var pn="1.0",fn=["soc","cohesion","coupling","srp","dip","ocp","encapsulation","modularity","scalability","resilience","security","maintainability","testability","domain","stack"],mn=5,Fe=["scalability","resilience","security"],Xe=new Set(Fe),Dr={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},Mr={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"},Fr={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 $r(e){return Mr[e]??e}i($r,"improvementCompassHumanLabel");function Hr(e){let t=e.id??e.smellId??"";return typeof t=="string"?t.trim():""}i(Hr,"smellIdOf");function jr(e){let t=e.ruleId??e.code??"";return typeof t=="string"?t.trim():""}i(jr,"violationRuleId");function K(e,t,n,r){if(!n||e.evidence.some(s=>s.source===t&&s.ref===n))return;let o={source:t,ref:n};r&&r.trim()&&(o.detail=r.trim().slice(0,240)),e.evidence.push(o)}i(K,"pushEvidence");function re(e,t,n){Xe.has(e.id)||(e.status="residual",e.summary=t,n&&(e.nextAction=n))}i(re,"markResidual");function ea(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`${Mr[e]} \u2014 no residual from current sensors.`}}i(ea,"defaultOkSummary");function ta(){return fn.map(e=>Xe.has(e)?{id:e,status:"out-of-scope",summary:Fr[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:ea(e),evidence:[]}:{id:e,status:"ok",summary:ea(e),evidence:[]})}i(ta,"createInitialImprovementCompassLenses");function yd(e,t){for(let n of t){let r=Hr(n);if(!r)continue;let o=n.outcome||n.message||void 0,a=(Array.isArray(n.evidence)?n.evidence:[])[0],c=i((p,g,f)=>{let m=e.get(p);!m||Xe.has(p)||(K(m,"designSmells",r,o),a&&K(m,"designSmells",a,r),re(m,g,f))},"attach"),l={kind:"skill",ref:"/ark-explore",summary:"Map Shape residual (shape-focus), then apply one extraction pilot with /ark-autopilot."},u={kind:"skill",ref:"/ark-autopilot",summary:"Inject a port/adapter for I/O; keep domain pure."};switch(r){case"domain-logic-in-ui":c("soc","Business rules still mix with UI or presentation surfaces.",l),c("domain","Domain logic lives outside Domain \u2014 align rules with Domain ownership.",l);break;case"facade-sql-in-routes":c("soc","Routes/controllers own SQL or ORM access \u2014 concerns are mixed.",l),c("dip","Transport depends on concrete persistence instead of a port.",u);break;case"io-under-application":c("soc","Application/business code reaches I/O directly \u2014 separation is weak.",l),c("dip","I/O is not inverted behind ports/adapters.",u),c("testability","Direct I/O under application code hurts pure unit testing.",u);break;case"handler-in-persistence":c("soc","HTTP/transport handlers live under persistence folders.",l);break;case"god-module":c("cohesion","Large multi-responsibility modules reduce cohesion.",l),c("srp","God modules own too many responsibilities \u2014 split by concern (one pilot).",{kind:"skill",ref:"/ark-autopilot",summary:"One Shape pilot this turn \u2014 never multi-pilot batch."});break;case"mixed-pattern-cluster":c("modularity","Multiple layout styles coexist \u2014 placement is unclear for the next AI turn.",{kind:"skill",ref:"/ark-explore",summary:"Pick a golden pattern and migrate one pilot cluster on touch."}),c("cohesion","Mixed layout styles scatter the same concern across patterns.",l);break;case"soft-contract":c("maintainability","Soft contract walls (layers without deny rules) hide maintainability debt.",{kind:"skill",ref:"/ark-adopt",summary:"Add real layer rules so the AI has hard walls."}),c("coupling","Layers with files but almost no deny rules allow free peer coupling.",{kind:"skill",ref:"/ark-adopt",summary:"Tighten inter-layer allows/denies without weakening enforcement."});break;default:c("maintainability","Design residual remains under an unrecognized smell id \u2014 review evidence.",l);break}}}i(yd,"mapDesignSmells");function hd(e){return e.failsStrict===!1||e.typeOnly===!0}i(hd,"isTypeOnlyPlacementDebt");function Ad(e,t){for(let n of t){let r=jr(n);if(!r)continue;let o=n.message,s=r.toUpperCase(),a=i((l,u,p)=>{let g=e.get(l);!g||Xe.has(l)||(K(g,"violations",r,o),n.file&&K(g,"violations",n.file,r),re(g,u,p))},"attach");if(hd(n)){a("modularity","Type-only placement debt remains \u2014 prefer SharedTypes / owning layer (not runtime coupling).",{kind:"skill",ref:"/ark-place",summary:"Place shared types in a layer both sides may import; type-only debt is not a value edge."});continue}let c={kind:"skill",ref:"/ark-autopilot",summary:"Clear the active edge residual, then re-doctor."};if(s==="LAYER_IMPORT_VIOLATION"||s.includes("LAYER_IMPORT")||s==="DYNAMIC_IMPORT_VIOLATION"){a("coupling","Import graph edges violate the layer contract.",c);continue}if(s.includes("CYCLE")||s==="CIRCULAR_DEPENDENCY"){a("coupling","Import cycles couple modules tightly.",c);continue}if(s.includes("PEER_ISOLATION")||s==="PEER_ISOLATION_VIOLATION"){a("coupling","Peer isolation residual \u2014 slices import each other freely.",{kind:"skill",ref:"/ark-autopilot",summary:"Peer isolation fixes are judgment-class \u2014 one cluster at a time."});continue}if(s==="FORBIDDEN_GLOBAL"||s.startsWith("FORBIDDEN_")){a("dip","Forbidden globals / effect surfaces break dependency inversion.",{kind:"skill",ref:"/ark-autopilot",summary:"Inject a port instead of the forbidden global."}),a("testability","Forbidden ambient effects reduce pure-domain testability.",{kind:"skill",ref:"/ark-autopilot",summary:"Replace ambient effects with injectable ports."});continue}if(s==="CAPABILITY_VIOLATION"){a("dip","Denied capability use \u2014 invert through an allowed adapter/port.",{kind:"skill",ref:"/ark-autopilot",summary:"Capability walls require port injection (judgment, not mechanical-safe)."}),a("testability","Capability violations couple domain code to I/O \u2014 harder to unit-test.",{kind:"skill",ref:"/ark-autopilot",summary:"Keep pure layers free of denied capabilities."});continue}if(s.startsWith("ARKRULE_")||s==="INVARIANT_UNCOVERED"||s==="INVARIANT_CATALOG_EMPTY"||s==="INVARIANT_TESTS_PATH_MISSING"||s==="INVARIANT_COVERAGE_ROOTS_MISSING"){a("encapsulation","ArkRules structure / invariant residual inside a layer.",{kind:"skill",ref:"/ark-autopilot",summary:"Label [ArkRules]; structure fixes are judgment \u2014 never invent mechanical-safe."}),a("domain","Intra-layer domain structure or invariant coverage residual.",{kind:"skill",ref:"/ark-explore",summary:"Inventory candidates \u2192 one ArkRules pilot with coverage evidence."});continue}}}i(Ad,"mapViolations");function Rd(e,t){let n=Number(t.cycleCount)||0;if(n>0){let m=e.get("coupling");K(m,"cycles",`count:${n}`),re(m,"Import cycles couple modules tightly.",{kind:"skill",ref:"/ark-autopilot",summary:"Break cycles with a judgment extraction \u2014 one pilot."})}let r=typeof t.peerIsolationCount=="boolean"?t.peerIsolationCount?1:0:Number(t.peerIsolationCount)||0;if(r>0){let m=e.get("coupling");K(m,"peerIsolation",`count:${r}`),re(m,"Peer isolation residual remains.",{kind:"skill",ref:"/ark-autopilot",summary:"Peer isolation is judgment-class residual."})}let o=Number(t.physicalCohesionFindingCount)||0;if(o>0){let m=e.get("cohesion");K(m,"physicalCohesion",`findings:${o}`),re(m,"Physical cohesion residual \u2014 mirrored concept clusters across anchors.",{kind:"skill",ref:"/ark-explore",summary:"Review reshape pilot; one decision-aware pilot at a time."});let d=e.get("srp");K(d,"physicalCohesion",`findings:${o}`),re(d,"Mirrored clusters suggest split-by-concern residual (architecture SRP).",{kind:"skill",ref:"/ark-autopilot",summary:"One reshape/extraction pilot this turn."})}let s=Number(t.pureOrCapabilityResidual)||0,a=Number(t.forbiddenGlobalResidual)||0;if(s>0||a>0){let m=e.get("dip");s>0&&K(m,"capability",`residual:${s}`),a>0&&K(m,"forbiddenGlobals",`residual:${a}`),re(m,"Pure / capability / forbidden residual weakens dependency inversion.",{kind:"skill",ref:"/ark-autopilot",summary:"Inject ports; keep pure layers free of effects."});let d=e.get("testability");s>0&&K(d,"capability",`residual:${s}`),a>0&&K(d,"forbiddenGlobals",`residual:${a}`),re(d,"Impure domain or capability residual reduces testability.",{kind:"skill",ref:"/ark-autopilot",summary:"Prefer ports over concrete I/O in pure/domain modules."})}let c=Number(t.arkRulesStructureResidual)||0;if(c>0){let m=e.get("encapsulation");K(m,"arkRules",`structureResidual:${c}`),re(m,"ArkRules structure residual \u2014 encapsulation inside the layer.",{kind:"skill",ref:"/ark-autopilot",summary:"Fix structure sensors under [ArkRules] without inventing mechanical-safe."});let d=e.get("domain");K(d,"arkRules",`structureResidual:${c}`),re(d,"ArkRules residual may mean domain shape is not yet under contract.",{kind:"skill",ref:"/ark-explore",summary:"Map inventory candidates; one pilot rule at a time."})}else t.arkRulesLoaded===!1||t.arkRulesLoaded==null;if(t.designWeak===!0){let m=e.get("maintainability");K(m,"designFitness","design-weak"),re(m,"Design-weak: checked edges may be clean, but design residual remains \u2014 not finished.",{kind:"skill",ref:"/ark-explore",summary:"Shape door: explore shape-focus \u2192 dual-plan B \u2192 one /ark-autopilot pilot."})}if(t.dirtyBaselineRisk===!0||(Number(t.baselineStale)||0)>0){let m=e.get("maintainability");t.dirtyBaselineRisk===!0&&K(m,"baseline","dirty-freeze-risk"),(Number(t.baselineStale)||0)>0&&K(m,"baseline",`stale:${t.baselineStale}`),re(m,"Baseline honesty residual \u2014 frozen debt or stale keys need review.",{kind:"command",ref:"ark-check --doctor",summary:"Review baseline freeze honesty; do not freeze new wrong debt."})}let l=Number(t.frozenResidual)||0;if(t.baselineExists===!0&&l>=10&&e.get("maintainability").status!=="residual"){let m=e.get("maintainability");K(m,"baseline",`frozen:${l}`),re(m,"Substantial frozen residual remains under the baseline \u2014 review debt honestly.",{kind:"command",ref:"ark-check --doctor",summary:"Review freezes; do not freeze new wrong debt to clear residual."})}let u=Number(t.ungovernedDirCount)||0,p=Number(t.emptyLayerCount)||0;if(u>0||p>0){let m=e.get("modularity");u>0&&K(m,"coverage",`ungovernedDirs:${u}`),p>0&&K(m,"coverage",`emptyLayers:${p}`),re(m,"Placement / modularity residual \u2014 ungoverned dirs or empty layer globs.",{kind:"skill",ref:"/ark-adopt",summary:"Classify ungoverned paths; fix empty layer patterns."})}if(t.designWeak===!0&&t.goldenPatternPresent===!1){let m=e.get("modularity");K(m,"goldenPattern","absent"),re(m,"Design-weak without a golden pattern \u2014 new code lacks a placement norm for the AI.",{kind:"skill",ref:"/ark-place",summary:"Record an advisory golden pattern for new code (does not clear design-weak)."})}let g=e.get("stack");(t.stackKind??null)==="typescript"?g.status==="ok"&&(g.summary="Stack practices are partially instrumented for TypeScript / host / Ark idioms only \u2014 not a full framework checklist."):(g.status="not-instrumented",g.summary="Stack-specific best practices outside TypeScript/host/Ark idioms are not instrumented.",g.evidence=[],g.nextAction={kind:"docs",ref:"docs/use.md#improvement-compass",summary:"Ark does not score non-TS stack idioms."})}i(Rd,"mapCountsAndFlags");function na(e,t){if(Array.isArray(t.designSmells)&&t.designSmells.length>0){let n=[...t.designSmells].sort((r,o)=>Hr(r).localeCompare(Hr(o)));yd(e,n)}if(Array.isArray(t.violations)&&t.violations.length>0){let n=[...t.violations].sort((r,o)=>{let s=jr(r).localeCompare(jr(o));return s!==0?s:String(r.file??"").localeCompare(String(o.file??""))});Ad(e,n)}Rd(e,t)}i(na,"projectImprovementCompassFacts");function ra(e){for(let t of Fe){let n=e.get(t);n.status="out-of-scope",n.summary=Fr[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(ra,"lockImprovementCompassOutOfScope");function sa(e){for(let t of e)t.evidence.sort((n,r)=>{let o=n.source.localeCompare(r.source);return o!==0?o:n.ref.localeCompare(r.ref)})}i(sa,"sortImprovementCompassEvidence");function oa(e){return e.filter(n=>n.status==="residual"&&!Xe.has(n.id)).slice().sort((n,r)=>{let o=Dr[n.id]??150,s=Dr[r.id]??150;return o!==s?o-s:n.id.localeCompare(r.id)}).slice(0,5).map(n=>n.id)}i(oa,"finalizeImprovementCompassTopResidual");function kd(e={}){let t=ta(),n=new Map(t.map(o=>[o.id,o]));na(n,e),ra(n),sa(t);let r=oa(t);return{schemaVersion:"1.0",notAScore:!0,lenses:t.map(o=>{let s={id:o.id,status:o.status,summary:o.summary,evidence:o.evidence.map(a=>({...a}))};return o.nextAction&&(s.nextAction={...o.nextAction}),s}),topResidual:r}}i(kd,"buildImprovementCompass");function aa(e){return e.topResidual.map(t=>$r(t))}i(aa,"formatImprovementCompassResidualLabels");function ia(e){for(let t of e.topResidual){let n=e.lenses.find(r=>r.id===t);if(n?.nextAction)return{...n.nextAction}}return null}i(ia,"primaryImprovementCompassNextAction");function Ed(e){let t=aa(e),n=Fe.map(s=>$r(s)),r=ia(e),o=[];return t.length>0?o.push(`Residual: ${t.join(" \xB7 ")}`):o.push("Residual: none on instrumented lenses (not a score \u2014 green edges \u2260 finished design)."),o.push(`Out of scope (honest): ${n.join(" \xB7 ")}`),r&&o.push(`Next: ${r.ref} \u2014 ${r.summary}`),o}i(Ed,"formatImprovementCompassDoctorLines");var $e="1.0",la="<!-- arkgate:agent-projection:begin",gn="<!-- arkgate:agent-projection:end -->",yn="This projection is **non-authoritative**. Enforcement is `ark-check` / host write hooks / required CI (`--strict-merge`), not AGENTS.md, skills, or this block.",_t=Object.freeze(["ark-check","host-write-hooks","ci-strict-merge"]),ca=Object.freeze(["LAYER_IMPORT_VIOLATION","LAYER_INTENT_REFERENCE_VIOLATION","CIRCULAR_DEPENDENCY","CAPABILITY_VIOLATION","RAW_EVENT_PUBLISH","ARKRULE_STRUCTURE","ATOMIC_PREFLIGHT_UNAVAILABLE","ANALYSIS_PARSE_INCOMPLETE","ARK_UNKNOWN"]);function Ze(e){let t=String(e??"").replace(/\r\n/g,`
|
|
14
14
|
`),n=2166136261;for(let r=0;r<t.length;r+=1)n^=t.charCodeAt(r),n=Math.imul(n,16777619);return`fnv1a-${(n>>>0).toString(16).padStart(8,"0")}`}i(Ze,"agentProjectionContentIdentity");function Ot(e){return String(e??"").replace(/\r\n/g,`
|
|
15
15
|
`)}i(Ot,"normalizeNewlines");function He(e){let t=Ot(e);return t.endsWith(`
|
|
16
16
|
`)?t:`${t}
|
|
@@ -27,8 +27,8 @@ Full catalog: \`${n}\` (\`#RULE_ID\` anchors).`}i(Vr,"formatAgentProjectionCatal
|
|
|
27
27
|
`).trimEnd()+`
|
|
28
28
|
`}i(An,"buildAgentProjectionBody");function ua(e){let t=An(e);return`${Kr({arkgateVersion:e.arkgateVersion,schemaVersion:"1.0"})}
|
|
29
29
|
${t}${gn}
|
|
30
|
-
`}i(ua,"buildAgentProjectionBlock");function pa(e){let t=An(e),n=Array.isArray(e.layers)?e.layers:[],r=Array.isArray(e.catalogShortList)?e.catalogShortList:[];return{schemaVersion:"1.0",arkgateVersion:xt(e.arkgateVersion),nonAuthoritative:!0,enforcementSurfaces:[..._t],contentIdentity:Ze(t),layerCount:n.length,catalogCodeCount:r.filter(o=>o?.ruleId).length,profile:da(e.profile)}}i(pa,"buildAgentProjectionMeta");var Ur=/<!--\s*arkgate:agent-projection:begin\b([^>]*)-->/i,fa=/<!--\s*arkgate:agent-projection:end\s*-->/i,
|
|
31
|
-
`)&&(u=u.slice(1));let p=t.slice(r,o+l),g=s.slice(l);return{block:p,body:u,before:t.slice(0,r),after:g,beginAttrs:n[1]??""}}i(Rn,"extractAgentProjectionBlock");function Gr(e){let t=String(e??""),r=Ur.exec(t)?.[1]??t,o=
|
|
30
|
+
`}i(ua,"buildAgentProjectionBlock");function pa(e){let t=An(e),n=Array.isArray(e.layers)?e.layers:[],r=Array.isArray(e.catalogShortList)?e.catalogShortList:[];return{schemaVersion:"1.0",arkgateVersion:xt(e.arkgateVersion),nonAuthoritative:!0,enforcementSurfaces:[..._t],contentIdentity:Ze(t),layerCount:n.length,catalogCodeCount:r.filter(o=>o?.ruleId).length,profile:da(e.profile)}}i(pa,"buildAgentProjectionMeta");var Ur=/<!--\s*arkgate:agent-projection:begin\b([^>]*)-->/i,fa=/<!--\s*arkgate:agent-projection:end\s*-->/i,Sd=/\barkgateVersion=([A-Za-z0-9._+-]+)/i,Id=/\bschema=([A-Za-z0-9._+-]+)/i;function Rn(e){let t=Ot(e??""),n=Ur.exec(t);if(!n)return{block:null,body:null,before:t,after:"",beginAttrs:null};let r=n.index,o=r+n[0].length,s=t.slice(o),a=fa.exec(s);if(!a)return{block:null,body:null,before:t,after:"",beginAttrs:null};let c=a.index,l=c+a[0].length,u=s.slice(0,c);u.startsWith(`
|
|
31
|
+
`)&&(u=u.slice(1));let p=t.slice(r,o+l),g=s.slice(l);return{block:p,body:u,before:t.slice(0,r),after:g,beginAttrs:n[1]??""}}i(Rn,"extractAgentProjectionBlock");function Gr(e){let t=String(e??""),r=Ur.exec(t)?.[1]??t,o=Sd.exec(r),s=Id.exec(r),a=/\bnonAuthoritative\s*=\s*true\b/i.test(r);return{arkgateVersion:o?.[1]??null,schemaVersion:s?.[1]??null,nonAuthoritative:a}}i(Gr,"parseAgentProjectionStamp");function ma(e,t){let n=Gr(e).arkgateVersion;return n?n===xt(t):!1}i(ma,"projectionMatchesPackageVersion");function ga(e){return String(e??"").includes("non-authoritative")}i(ga,"projectionHasNonEnforcementLabel");function ya(e,t){let n=He(Ot(t)),o=Rn(n).body??n.replace(Ur,"").replace(fa,"").trim()+`
|
|
32
32
|
`,s=Ze(o);if(e==null||!String(e).trim())return{content:He(`# Ark Enforcement
|
|
33
33
|
|
|
34
34
|
${n}`),action:"created",previousBlock:null,contentIdentity:s,preservedOutsideBlock:!1};let a=Ot(e),c=Rn(a);if(c.block!=null){let u=c.body??"";if(Ze(u)===s)return{content:He(a),action:"unchanged",previousBlock:c.block,contentIdentity:s,preservedOutsideBlock:!0};let p=c.before.replace(/\s*$/,`
|
|
@@ -41,8 +41,8 @@ ${g}`),action:"block-replaced",previousBlock:c.block,contentIdentity:s,preserved
|
|
|
41
41
|
`);return{content:He(`${p}${n.trimEnd()}
|
|
42
42
|
${g}`),action:"block-inserted",previousBlock:null,contentIdentity:s,preservedOutsideBlock:!0}}return{content:He(`${n.trimEnd()}
|
|
43
43
|
|
|
44
|
-
${a.trimStart()}`),action:"block-inserted",previousBlock:null,contentIdentity:s,preservedOutsideBlock:!0}}i(ya,"mergeAgentProjectionDocument");var
|
|
44
|
+
${a.trimStart()}`),action:"block-inserted",previousBlock:null,contentIdentity:s,preservedOutsideBlock:!0}}i(ya,"mergeAgentProjectionDocument");var bd="1.0",ka="templates/agent-skills",Ea="templates/skills",Sa="SKILL.md",vd=Object.freeze(["Contener","Guiar","Ordenar"]),qr=Object.freeze(["ark-adopt","ark-autopilot","ark-coverage","ark-explain","ark-explore","ark-order","ark-place","ark-runtime","ark-upgrade"]),Br=Object.freeze({"ark-architect":"ark-adopt","ark-contract":"ark-adopt","ark-fix":"ark-autopilot","ark-loop":"ark-autopilot","ark-think":"ark-explore"}),kn=Object.freeze({Layers:["ark-adopt","ark-place","ark-explore","ark-autopilot","ark-coverage","ark-explain"],ArkRules:["ark-adopt","ark-explore","ark-autopilot"],ArkRun:["ark-adopt","ark-runtime","ark-place","ark-autopilot"],ArkOrder:["ark-adopt","ark-order","ark-place","ark-autopilot"],Contener:["ark-adopt","ark-place","ark-upgrade"],Guiar:["ark-explore","ark-autopilot","ark-explain","ark-coverage","ark-runtime"],Ordenar:["ark-order"]}),En=Object.freeze(["Layers","ArkRules","ArkRun","ArkOrder","Contener","Guiar","Ordenar"]),Ia=Object.freeze({ArkRun:"ark-runtime",ArkOrder:"ark-order",Ordenar:"ark-order"}),ha="Contener \xB7 Guiar \xB7 Ordenar",Aa="Do not invent `/ark-order`",Sn=Object.freeze(["ark-adopt","ark-architect","ark-autopilot","ark-contract","ark-coverage","ark-explain","ark-explore","ark-fix","ark-loop","ark-order","ark-place","ark-runtime","ark-think","ark-upgrade"]),ba=Sn.length,Cd=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function va(e){return typeof e!="string"||e.length<1||e.length>64?!1:Cd.test(e)}i(va,"isValidAgentSkillName");function Yr(e){return Sn.includes(e)}i(Yr,"isArkSkillName");function zr(e){return qr.includes(e)}i(zr,"isFirstClassArkSkillName");function _d(e){return e in Br?Br[e]:null}i(_d,"arkSkillStubRedirect");function Ca(e){let t=String(e??"").replace(/^\uFEFF/,""),n=t.includes(`\r
|
|
45
45
|
`)?`\r
|
|
46
46
|
`:`
|
|
47
|
-
`,r=t.split(/\r?\n/);if(r[0]!=="---")return{hasFrontmatter:!1,frontmatter:null,body:t};let o=r.indexOf("---",1);if(o===-1)return{hasFrontmatter:!1,frontmatter:null,body:t};let s={};for(let p=1;p<o;p+=1){let g=r[p]??"";if(g.trim()===""||g.trimStart().startsWith("#"))continue;let f=g.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);if(!f)continue;let m=f[1],d=f[2]??"";(d.startsWith('"')&&d.endsWith('"')&&d.length>=2||d.startsWith("'")&&d.endsWith("'")&&d.length>=2)&&(d=d.slice(1,-1)),s[m]=d}let a=r.slice(o+1).join(n),c=typeof s.name=="string"&&s.name.length>0?s.name:null,l=typeof s.description=="string"&&s.description.length>0?s.description:null,u=typeof s.license=="string"&&s.license.length>0?s.license:null;return{hasFrontmatter:!0,frontmatter:{fields:s,name:c,description:l,license:u},body:a}}i(Ca,"parseSkillDocument");function _a(e){let t=e.requireArkSkillName!==!1,n=e.requireBody!==!1,r=[],o=String(e.directoryName??""),s=Ca(e.content);if(!s.hasFrontmatter||!s.frontmatter)return r.push({code:"MISSING_FRONTMATTER",message:`Skill "${o}" is missing YAML frontmatter fences.`,skillName:o||void 0}),r;let{name:a,description:c}=s.frontmatter,l=a??(o||void 0);return!a||!va(a)?r.push({code:"INVALID_NAME",message:`Skill name "${a??""}" is invalid (Agent Skills: 1\u201364 chars, [a-z0-9-], no leading/trailing/consecutive hyphens).`,skillName:l}):a!==o?r.push({code:"NAME_DIRECTORY_MISMATCH",message:`Frontmatter name "${a}" must match directory name "${o}".`,skillName:a}):t&&!Yr(a)&&r.push({code:"UNKNOWN_SKILL_NAME",message:`Skill name "${a}" is not in the closed Ark skill catalog (ARK_SKILL_NAMES).`,skillName:a}),c?c.length>1024&&r.push({code:"DESCRIPTION_TOO_LONG",message:`Skill "${o}" description exceeds 1024 characters (${c.length}).`,skillName:l}):r.push({code:"MISSING_DESCRIPTION",message:`Skill "${o}" is missing a non-empty description.`,skillName:l}),n&&s.body.trim().length===0&&r.push({code:"EMPTY_BODY",message:`Skill "${o}" has an empty instruction body.`,skillName:l}),r}i(_a,"validateAgentSkillDocument");function
|
|
48
|
-
`)}i(Wr,"normalizeSkillContent");function Ta(e){return`${e}/${Sa}`}i(Ta,"agentSkillEntryRelativePath");function
|
|
47
|
+
`,r=t.split(/\r?\n/);if(r[0]!=="---")return{hasFrontmatter:!1,frontmatter:null,body:t};let o=r.indexOf("---",1);if(o===-1)return{hasFrontmatter:!1,frontmatter:null,body:t};let s={};for(let p=1;p<o;p+=1){let g=r[p]??"";if(g.trim()===""||g.trimStart().startsWith("#"))continue;let f=g.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);if(!f)continue;let m=f[1],d=f[2]??"";(d.startsWith('"')&&d.endsWith('"')&&d.length>=2||d.startsWith("'")&&d.endsWith("'")&&d.length>=2)&&(d=d.slice(1,-1)),s[m]=d}let a=r.slice(o+1).join(n),c=typeof s.name=="string"&&s.name.length>0?s.name:null,l=typeof s.description=="string"&&s.description.length>0?s.description:null,u=typeof s.license=="string"&&s.license.length>0?s.license:null;return{hasFrontmatter:!0,frontmatter:{fields:s,name:c,description:l,license:u},body:a}}i(Ca,"parseSkillDocument");function _a(e){let t=e.requireArkSkillName!==!1,n=e.requireBody!==!1,r=[],o=String(e.directoryName??""),s=Ca(e.content);if(!s.hasFrontmatter||!s.frontmatter)return r.push({code:"MISSING_FRONTMATTER",message:`Skill "${o}" is missing YAML frontmatter fences.`,skillName:o||void 0}),r;let{name:a,description:c}=s.frontmatter,l=a??(o||void 0);return!a||!va(a)?r.push({code:"INVALID_NAME",message:`Skill name "${a??""}" is invalid (Agent Skills: 1\u201364 chars, [a-z0-9-], no leading/trailing/consecutive hyphens).`,skillName:l}):a!==o?r.push({code:"NAME_DIRECTORY_MISMATCH",message:`Frontmatter name "${a}" must match directory name "${o}".`,skillName:a}):t&&!Yr(a)&&r.push({code:"UNKNOWN_SKILL_NAME",message:`Skill name "${a}" is not in the closed Ark skill catalog (ARK_SKILL_NAMES).`,skillName:a}),c?c.length>1024&&r.push({code:"DESCRIPTION_TOO_LONG",message:`Skill "${o}" description exceeds 1024 characters (${c.length}).`,skillName:l}):r.push({code:"MISSING_DESCRIPTION",message:`Skill "${o}" is missing a non-empty description.`,skillName:l}),n&&s.body.trim().length===0&&r.push({code:"EMPTY_BODY",message:`Skill "${o}" has an empty instruction body.`,skillName:l}),r}i(_a,"validateAgentSkillDocument");function Od(e){let t=[],n=new Set,r=[];for(let o of e){let s=String(o.name??"");if(n.has(s)){t.push({code:"DUPLICATE_SKILL",message:`Duplicate skill entry "${s}".`,skillName:s});continue}n.add(s),r.push(s),t.push(..._a({directoryName:s,content:o.content,requireArkSkillName:!0,requireBody:!0})),o.flatTemplateContent!=null&&Wr(o.content)!==Wr(o.flatTemplateContent)&&t.push({code:"CONTENT_MISMATCH",message:`Agent Skills SKILL.md for "${s}" does not match flat template templates/skills/${s}.md.`,skillName:s})}for(let o of Sn)n.has(o)||t.push({code:"MISSING_SKILL",message:`Missing catalog skill "${o}" from Agent Skills package.`,skillName:o});for(let o of r)Yr(o)||(t.some(s=>s.code==="UNKNOWN_SKILL_NAME"&&s.skillName===o)?t.push({code:"EXTRA_SKILL",message:`Extra skill "${o}" is not in the closed Ark skill catalog.`,skillName:o}):t.push({code:"EXTRA_SKILL",message:`Extra skill "${o}" is not in the closed Ark skill catalog.`,skillName:o}));return r.sort(),{ok:t.length===0,issues:t,names:r,expectedCount:ba,presentCount:r.length}}i(Od,"validateAgentSkillsPackage");function pe(e,t){e.push(t)}i(pe,"pushCapacityIssue");function Ra(e,t){return e.includes(t)}i(Ra,"skillMentionsSurface");function xd(e){let t=[],n=e.skills??{},r=Object.keys(kn);for(let s of En)r.includes(s)||pe(t,{code:"CAPACITY_SURFACE_MISSING",surface:s,message:`The capacity table dropped ${s}. Skills must keep covering Layers, ArkRules, ArkRun, ArkOrder plus Contener \xB7 Guiar \xB7 Ordenar. Put ${s} back on ARK_SKILL_CAPACITY.`});for(let s of r)En.includes(s)||pe(t,{code:"CAPACITY_SURFACE_UNMAPPED",surface:s,message:`The capacity table lists ${s}, which is not a product surface. Keep the table to Layers, ArkRules, ArkRun, ArkOrder and Contener \xB7 Guiar \xB7 Ordenar.`});for(let s of En){let a=kn[s];if(!a||a.length===0)continue;for(let l of a)zr(l)||pe(t,{code:"CAPACITY_DOOR_NOT_FIRST_CLASS",surface:s,skillName:l,message:`/${l} is listed for ${s} but is not a first-class door. Leftover names are shortcuts. Point ${s} at a first-class skill.`});a.filter(l=>{let u=n[l];return typeof u=="string"&&Ra(u,s)}).length===0&&pe(t,{code:"CAPACITY_BODY_GAP",surface:s,message:`Skills no longer cover ${s}. The product has four parts (Layers, ArkRules, ArkRun, ArkOrder) plus Contener \xB7 Guiar \xB7 Ordenar. Put ${s} back in a first-class skill${s==="ArkOrder"||s==="Ordenar"?" \u2014 usually /ark-order":s==="ArkRun"?" \u2014 usually /ark-runtime":""} so agents still know when to use it.`})}for(let[s,a]of Object.entries(Ia)){if(!kn[s]?.includes(a)||!zr(a)){pe(t,{code:"CAPACITY_DEDICATED_DOOR",surface:s,skillName:a,message:`/${a} is the first-class door for ${s}. Keep it on that surface. Leftover names like /ark-think are shortcuts, not a replacement.`});continue}let l=n[a];(typeof l!="string"||!Ra(l,s))&&pe(t,{code:"CAPACITY_DEDICATED_DOOR",surface:s,skillName:a,message:`/${a} no longer talks about ${s}. That door is how agents reach this part of the product. Put ${s} back in the skill body.`})}for(let s of qr){let a=n[s];if(typeof a!="string"){pe(t,{code:"CAPACITY_ROUTING_GAP",skillName:s,message:`/${s} is a first-class door but has no skill body in this check. Ship the template so agents know when to use it.`});continue}let c=a.includes(ha),l=/When \/ not when|\*\*When:\*\*/.test(a),u=/Not when|Do \*\*not\*\* use|Prefer instead/.test(a),p=/Handoff|hand off|`\/ark-/i.test(a);(!c||!l||!u||!p)&&pe(t,{code:"CAPACITY_ROUTING_GAP",skillName:s,message:`/${s} is missing when / not when / handoff or Contener \xB7 Guiar \xB7 Ordenar. First-class skills must say when to use them and which sibling to call next.`}),a.includes(Aa)&&pe(t,{code:"CAPACITY_ROUTING_GAP",skillName:s,message:`/${s} still says not to invent /ark-order. That freeze is outdated \u2014 /ark-order is a first-class door.`})}let o=e.hubs??{};for(let[s,a]of Object.entries(o)){let c=String(a??"");c.includes("/ark-order")||pe(t,{code:"CAPACITY_HUB_GAP",hub:s,message:`${s} no longer names /ark-order. Host instructions must stay at 100% of the product. Add /ark-order back, or you left the order plane behind.`}),c.includes(ha)||pe(t,{code:"CAPACITY_HUB_GAP",hub:s,message:`${s} no longer says Contener \xB7 Guiar \xB7 Ordenar. Keep that filter in the living docs so agents pick the right sibling.`}),c.includes(Aa)&&pe(t,{code:"CAPACITY_HUB_GAP",hub:s,message:`${s} still says not to invent /ark-order. That freeze is outdated \u2014 /ark-order is a first-class door.`})}return{ok:t.length===0,issues:t}}i(xd,"validateSkillProductCapacity");var Jr=/^arkgate@(\S+)\.\s/;function Oa(e){let t=String(e??"").trim();return t?`arkgate@${t}. `:""}i(Oa,"skillDescriptionVersionPrefix");function xa(e){return String(e??"").replace(Jr,"")}i(xa,"stripSkillDescriptionVersion");function Td(e){return String(e??"").match(Jr)?.[1]??null}i(Td,"parseSkillDescriptionVersion");function Nd(e,t){let n=xa(e),r=typeof t=="string"?t.trim():"";return r?`${Oa(r)}${n}`:n}i(Nd,"stampSkillDescription");function Wr(e){return String(e??"").replace(/^\uFEFF/,"").replace(/\r\n/g,`
|
|
48
|
+
`)}i(Wr,"normalizeSkillContent");function Ta(e){return`${e}/${Sa}`}i(Ta,"agentSkillEntryRelativePath");function wd(e){return`${ka}/${Ta(e)}`}i(wd,"agentSkillPackageFileRelativePath");function Pd(e){return`${Ea}/${e}.md`}i(Pd,"flatSkillTemplateFileRelativePath");export{wt as ADAPTER_DIAGNOSTIC_DOCS_RELATIVE_PATH,la as AGENT_PROJECTION_BEGIN_MARKER,gn as AGENT_PROJECTION_END_MARKER,_t as AGENT_PROJECTION_ENFORCEMENT_SURFACES,yn as AGENT_PROJECTION_NON_ENFORCEMENT_LABEL,ka as AGENT_SKILLS_PACKAGE_RELATIVE_ROOT,Sa as AGENT_SKILL_ENTRY_FILENAME,Bn as ANALYSIS_IR_SCHEMA_VERSION,Or as ARKORDER_RULE_IDS,Nc as ARKORDER_TIER1_SENSOR_IDS,vo as ARKRUN_INTERACTION_NAME_INCOMPLETE,Eo as ARKRUN_KERNEL_FACTORY_CALLEES,tc as ARKRUN_KERNEL_INTERACTION_CALLEES,_r as ARKRUN_RULE_IDS,fc as ARKRUN_TIER1_SENSOR_IDS,So as ARKRUN_TRANSPORT_BYPASS_SPECIFIERS,$e as ARK_AGENT_PROJECTION_SCHEMA_VERSION,bd as ARK_AGENT_SKILLS_PACKAGE_SCHEMA_VERSION,Qr as ARK_ANALYSIS_RESULT_SCHEMA,Nt as ARK_ANALYSIS_RESULT_SCHEMA_VERSION,Kn as ARK_CONFIG_SCHEMA,le as ARK_CONFIG_SCHEMA_VERSION,td as ARK_DESIGN_DELTA_SCHEMA_VERSION,ed as ARK_ENFORCEMENT_STATE_SCHEMA_VERSION,qr as ARK_FIRST_CLASS_SKILL_NAMES,pn as ARK_IMPROVEMENT_COMPASS_SCHEMA_VERSION,Ua as ARK_PROJECT_IDENTITY_SCHEMA,ts as ARK_PROJECT_IDENTITY_SCHEMA_URL,Va as ARK_PROJECT_IDENTITY_SCHEMA_VERSION,Wn as ARK_RULES_SCHEMA,Hi as ARK_RULES_SCHEMA_VERSION,Ks as ARK_RULE_SENSORS,Fo as ARK_RUN_DOCTOR_SCHEMA_VERSION,kn as ARK_SKILL_CAPACITY,Ia as ARK_SKILL_CAPACITY_DEDICATED_DOORS,Jr as ARK_SKILL_DESCRIPTION_VERSION_PATTERN,Sn as ARK_SKILL_NAMES,ba as ARK_SKILL_NAME_COUNT,vd as ARK_SKILL_NORTH_STAR,En as ARK_SKILL_REQUIRED_SURFACES,Br as ARK_SKILL_STUB_REDIRECTS,gd as ARK_STATUS_MANIFEST_SCHEMA,Go as ARK_STATUS_MANIFEST_SCHEMA_URL,Pr as ARK_STATUS_MANIFEST_SCHEMA_VERSION,ca as DEFAULT_AGENT_PROJECTION_RULE_IDS,cn as DIAGNOSTIC_CATALOG,nd as DIAGNOSTIC_CATALOG_SCHEMA_VERSION,Nr as DIAGNOSTIC_DOCS_RELATIVE_PATH,rd as DIAGNOSTIC_RULE_IDS,Ql as EXTRA_MERGE_TEETH_GOVERNED_FLOOR,Yt as EffectiveContractError,Ea as FLAT_SKILL_TEMPLATES_RELATIVE_ROOT,Fe as IMPROVEMENT_COMPASS_OUT_OF_SCOPE_LENSES,mn as IMPROVEMENT_COMPASS_TOP_RESIDUAL_CAP,fn as IMPROVEMENT_LENS_IDS,Ro as MERGE_PLANES_DUAL_STAMP,sr as POLICY_DELTA_SCHEMA_VERSION,rs as PROJECT_BINDING_SCHEMA,ns as PROJECT_EXPECTATION_SCHEMA,Gn as RESOLVED_CANDIDATE_FACTS_SCHEMA,Pe as RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,zo as STATUS_COMPASS_FACTS_SOURCES,Bo as STATUS_COMPASS_MODES,un as STATUS_COMPASS_REASON_CODES,Lt as adapterDocsCodePath,rt as adapterFindingOccurrenceTargetKeys,Pt as adapterFindingRefFromTargetKey,nt as adapterFindingTargetKey,Ze as agentProjectionContentIdentity,Ta as agentSkillEntryRelativePath,wd as agentSkillPackageFileRelativePath,qe as analyzeArchitectureConvergence,Qt as analyzeChange,to as analyzePolicyDelta,Rt as analyzeProject,vt as analyzeResolvedProject,Er as arkRunKernelCallKind,_d as arkSkillStubRedirect,Kr as buildAgentProjectionBeginMarker,ua as buildAgentProjectionBlock,An as buildAgentProjectionBody,pa as buildAgentProjectionMeta,yr as buildArkRuleFileHints,qn as buildEffectiveArkRules,kd as buildImprovementCompass,Zc as buildRulesInventory,ud as buildStatusManifest,Qn as canPromoteInvariant,ld as catalogFixForRuleId,cd as catalogWhyForRuleId,or as classifyArkPolicyDelta,Ar as classifyResolvedLayerCoverage,Yo as classifyStatusWritePath,an as collectAnalysisConfigWarnings,gr as collectEmptyAppliesToFindings,Ge as collectForbiddenCapabilityUses,rn as composeMergePlanesHonesty,As as createAICodeGate,Ka as createAdapterResult,zt as createArchitectureProfile,Ps as createArchitectureProfileFromArkConfig,Ls as createElevenLayerArkConfig,Ga as createProjectId,Ba as createProjectIdentity,Un as createResolvedCandidateFacts,Jo as defaultHonestLabel,ec as demoteExtraPlaneTeethUnderClassificationFloor,yo as deriveArkRuleFileHints,ir as detectArchitectureCycles,X as deterministicHash,Vo as diagnosticDocsFragment,ad as diagnosticDocsPath,Jn as effectiveContractPolicyPayload,Bt as elevenLayerProfile,De as emptyEffectiveArkRules,Ye as evaluateArchitectureGraph,xr as evaluateArkOrderSensors,mr as evaluateArkRuleSensors,_o as evaluateArkRunEditorSensors,_c as evaluateArkRunEditorSensorsFromSource,on as evaluateArkRunSensors,Zn as evaluateInvariantCoverage,qo as evaluateStatusBinding,no as explainViolation,he as extraMergeTeethAllowed,Rn as extractAgentProjectionBlock,pc as extractArkRunDeclarationsFromSource,br as extractArkRunImportedConstructorNamesFromSource,vr as extractArkRunKernelCallsFromSource,Cr as extractArkRunManagedNewsFromSource,Ir as extractArkRunValueImportDependenciesFromSource,Zl as extractClassShapesFromSource,Ue as extractSemanticDependencies,Pd as flatSkillTemplateFileRelativePath,Vr as formatAgentProjectionCatalogShortList,hn as formatAgentProjectionLayers,Yc as formatArkRunDoctorLines,Ed as formatImprovementCompassDoctorLines,aa as formatImprovementCompassResidualLabels,dn as getDiagnosticCatalogEntry,Qc as inventoryToExtractionCard,ho as isArkOrderRuleId,It as isArkRunKernelModuleSpecifier,Rr as isArkRunRuleId,Sr as isArkRunTransportBypassSpecifier,Yr as isArkSkillName,od as isCataloguedOrArkRuleFamily,Ao as isExtraPlaneFinding,zr as isFirstClassArkSkillName,sd as isKnownDiagnosticCode,va as isValidAgentSkillName,Gt as loadArkConfigContract,qt as loadArkRulesContract,Zt as loadContract,_e as loadResolvedCandidateFacts,ya as mergeAgentProjectionDocument,hr as normalizeExtraMergeTeethClassification,Wr as normalizeSkillContent,Qo as normalizeStatusImprovementCompass,Gr as parseAgentProjectionStamp,Vn as parseArkConfigJson,Bi as parseArkRulesJson,Td as parseSkillDescriptionVersion,Ca as parseSkillDocument,ar as policyDeltaAcknowledgementMatches,Do as preflightChange,Mo as preflightResolvedChange,ia as primaryImprovementCompassNextAction,Tr as projectStatusArkRun,Lr as projectStatusImprovementCompass,ga as projectionHasNonEnforcementLabel,ma as projectionMatchesPackageVersion,zi as resolveEffectiveContract,Xo as resolveStatusNextAction,pt as resolvedFactsEvidenceRequirementsHash,id as serializeDiagnosticCatalog,Oa as skillDescriptionVersionPrefix,H as stableSerialize,Nd as stampSkillDescription,md as statusCompassResidualIsSubsetOfDoctor,xa as stripSkillDescriptionVersion,qc as summarizeArkRunSection,In as toAdapterDiagnostic,fd as unavailableStatusImprovementCompass,_a as validateAgentSkillDocument,Od as validateAgentSkillsPackage,xd as validateSkillProductCapacity,wa as version};
|