arkgate 4.6.1 → 4.6.2
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 +30 -1
- package/README.md +5 -3
- package/bin/ark-check-runtime.mjs +23 -127
- package/bin/ark-mcp-runtime.mjs +70 -48
- package/bin/ark.mjs +19 -78
- package/bin/lib/doctor-next-actions.mjs +92 -0
- package/bin/lib/doctor-plan.mjs +59 -69
- package/bin/lib/first-run-help.mjs +221 -0
- package/bin/lib/start-preview.mjs +17 -10
- package/bin/lib/status-command.mjs +5 -0
- package/bin/lib/status-manifest.mjs +6 -0
- package/dist/index.cjs +19 -19
- package/dist/index.d.ts +6 -1
- package/dist/index.js +22 -22
- package/docs/README.md +5 -5
- package/docs/agent-guide.md +1 -1
- package/docs/enthusiast/how-to-agent-gates.md +1 -1
- package/docs/package-surface.md +3 -3
- package/docs/use.md +4 -4
- package/package.json +2 -2
- package/server.json +3 -3
- package/templates/agent-skills/README.md +1 -1
- package/templates/agent-skills/ark-adopt/SKILL.md +14 -5
- package/templates/agent-skills/ark-architect/SKILL.md +2 -2
- package/templates/agent-skills/ark-autopilot/SKILL.md +12 -5
- package/templates/agent-skills/ark-contract/SKILL.md +1 -1
- package/templates/agent-skills/ark-coverage/SKILL.md +6 -5
- package/templates/agent-skills/ark-explain/SKILL.md +3 -2
- package/templates/agent-skills/ark-explore/SKILL.md +13 -4
- package/templates/agent-skills/ark-fix/SKILL.md +1 -1
- package/templates/agent-skills/ark-loop/SKILL.md +1 -1
- package/templates/agent-skills/ark-place/SKILL.md +10 -1
- package/templates/agent-skills/ark-think/SKILL.md +3 -2
- package/templates/agent-skills/ark-upgrade/SKILL.md +10 -3
- package/templates/skills/ark-adopt.md +14 -5
- package/templates/skills/ark-architect.md +2 -2
- package/templates/skills/ark-autopilot.md +12 -5
- package/templates/skills/ark-contract.md +1 -1
- package/templates/skills/ark-coverage.md +6 -5
- package/templates/skills/ark-explain.md +3 -2
- package/templates/skills/ark-explore.md +13 -4
- package/templates/skills/ark-fix.md +1 -1
- package/templates/skills/ark-loop.md +1 -1
- package/templates/skills/ark-place.md +10 -1
- package/templates/skills/ark-think.md +3 -2
- package/templates/skills/ark-upgrade.md +10 -3
package/dist/index.cjs
CHANGED
|
@@ -1,51 +1,51 @@
|
|
|
1
|
-
"use strict";var tn=Object.defineProperty;var zs=Object.getOwnPropertyDescriptor;var qs=Object.getOwnPropertyNames;var Ys=Object.prototype.hasOwnProperty;var Ws=(e,t)=>{for(var n in t)tn(e,n,{get:t[n],enumerable:!0})},Js=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of qs(t))!Ys.call(e,s)&&s!==n&&tn(e,s,{get:()=>t[s],enumerable:!(r=zs(t,s))||r.enumerable});return e};var Zs=e=>Js(tn({},"__esModule",{value:!0}),e);var Pa={};Ws(Pa,{ADAPTER_DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>nn,AGENT_PROJECTION_BEGIN_MARKER:()=>Ns,AGENT_PROJECTION_END_MARKER:()=>Zn,AGENT_PROJECTION_ENFORCEMENT_SURFACES:()=>Jt,AGENT_PROJECTION_NON_ENFORCEMENT_LABEL:()=>Xn,AGENT_SKILLS_PACKAGE_RELATIVE_ROOT:()=>rr,AGENT_SKILL_ENTRY_FILENAME:()=>ir,ANALYSIS_IR_SCHEMA_VERSION:()=>Ct,ARK_AGENT_PROJECTION_SCHEMA_VERSION:()=>Ls,ARK_AGENT_SKILLS_PACKAGE_SCHEMA_VERSION:()=>Us,ARK_ANALYSIS_RESULT_SCHEMA:()=>gr,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>fr,ARK_CONFIG_SCHEMA:()=>bt,ARK_CONFIG_SCHEMA_VERSION:()=>Tr,ARK_DESIGN_DELTA_SCHEMA_VERSION:()=>ls,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION:()=>os,ARK_IMPROVEMENT_COMPASS_SCHEMA_VERSION:()=>at,ARK_PROJECT_IDENTITY_SCHEMA:()=>hr,ARK_PROJECT_IDENTITY_SCHEMA_URL:()=>an,ARK_PROJECT_IDENTITY_SCHEMA_VERSION:()=>yr,ARK_RULES_SCHEMA:()=>_t,ARK_RULES_SCHEMA_VERSION:()=>Vr,ARK_RULE_SENSORS:()=>kn,ARK_SKILL_NAMES:()=>dt,ARK_SKILL_NAME_COUNT:()=>ar,ARK_STATUS_MANIFEST_SCHEMA:()=>Es,ARK_STATUS_MANIFEST_SCHEMA_URL:()=>Mn,ARK_STATUS_MANIFEST_SCHEMA_VERSION:()=>hs,DEFAULT_AGENT_PROJECTION_RULE_IDS:()=>ws,DIAGNOSTIC_CATALOG:()=>nt,DIAGNOSTIC_CATALOG_SCHEMA_VERSION:()=>cs,DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>Kt,DIAGNOSTIC_RULE_IDS:()=>ds,EffectiveContractError:()=>Je,FLAT_SKILL_TEMPLATES_RELATIVE_ROOT:()=>sr,IMPROVEMENT_COMPASS_OUT_OF_SCOPE_LENSES:()=>ce,IMPROVEMENT_COMPASS_TOP_RESIDUAL_CAP:()=>lt,IMPROVEMENT_LENS_IDS:()=>ot,POLICY_DELTA_SCHEMA_VERSION:()=>wt,PROJECT_BINDING_SCHEMA:()=>ln,PROJECT_EXPECTATION_SCHEMA:()=>on,RESOLVED_CANDIDATE_FACTS_SCHEMA:()=>vt,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION:()=>ae,STATUS_COMPASS_FACTS_SOURCES:()=>Fn,STATUS_COMPASS_MODES:()=>$n,STATUS_COMPASS_REASON_CODES:()=>it,adapterDocsCodePath:()=>sn,adapterFindingOccurrenceTargetKeys:()=>pt,adapterFindingRefFromTargetKey:()=>rn,adapterFindingTargetKey:()=>ft,agentProjectionContentIdentity:()=>ct,agentSkillEntryRelativePath:()=>dr,agentSkillPackageFileRelativePath:()=>Bs,analyzeArchitectureConvergence:()=>ge,analyzeChange:()=>Qe,analyzePolicyDelta:()=>_n,analyzeProject:()=>xe,analyzeResolvedProject:()=>Te,buildAgentProjectionBeginMarker:()=>er,buildAgentProjectionBlock:()=>Fs,buildAgentProjectionBody:()=>Xt,buildAgentProjectionMeta:()=>Ds,buildArkRuleFileHints:()=>Ut,buildEffectiveArkRules:()=>xt,buildImprovementCompass:()=>Ts,buildRulesInventory:()=>is,buildStatusManifest:()=>Is,canPromoteInvariant:()=>Pt,catalogFixForRuleId:()=>gs,catalogWhyForRuleId:()=>ys,classifyArkPolicyDelta:()=>Mt,classifyStatusWritePath:()=>Hn,collectAnalysisConfigWarnings:()=>tt,collectEmptyAppliesToFindings:()=>jt,collectForbiddenCapabilityUses:()=>fe,createAICodeGate:()=>Sn,createAdapterResult:()=>mr,createArchitectureProfile:()=>Be,createArchitectureProfileFromArkConfig:()=>En,createElevenLayerArkConfig:()=>vn,createProjectId:()=>Ar,createProjectIdentity:()=>Ir,createResolvedCandidateFacts:()=>Et,defaultHonestLabel:()=>Vn,deriveArkRuleFileHints:()=>Tn,detectArchitectureCycles:()=>Dt,deterministicHash:()=>M,diagnosticDocsFragment:()=>wn,diagnosticDocsPath:()=>fs,effectiveContractPolicyPayload:()=>Ot,elevenLayerProfile:()=>Ge,emptyEffectiveArkRules:()=>le,evaluateArchitectureGraph:()=>Ie,evaluateArkRuleSensors:()=>Vt,evaluateInvariantCoverage:()=>Tt,evaluateStatusBinding:()=>Dn,explainViolation:()=>xn,extractAgentProjectionBlock:()=>Wt,extractClassShapesFromSource:()=>Qr,extractSemanticDependencies:()=>ue,flatSkillTemplateFileRelativePath:()=>Ks,formatAgentProjectionCatalogShortList:()=>tr,formatAgentProjectionLayers:()=>Yt,formatImprovementCompassDoctorLines:()=>Ps,formatImprovementCompassResidualLabels:()=>Wn,getDiagnosticCatalogEntry:()=>rt,inventoryToExtractionCard:()=>as,isArkSkillName:()=>en,isCataloguedOrArkRuleFamily:()=>us,isKnownDiagnosticCode:()=>ps,isValidAgentSkillName:()=>or,loadArkConfigContract:()=>Ue,loadArkRulesContract:()=>We,loadContract:()=>Xe,loadResolvedCandidateFacts:()=>se,mergeAgentProjectionDocument:()=>js,normalizeSkillContent:()=>Qt,normalizeStatusImprovementCompass:()=>Un,parseAgentProjectionStamp:()=>nr,parseArkConfigJson:()=>Rt,parseArkRulesJson:()=>jr,parseSkillDocument:()=>lr,policyDeltaAcknowledgementMatches:()=>$t,preflightChange:()=>Pn,preflightResolvedChange:()=>Ln,primaryImprovementCompassNextAction:()=>Jn,projectStatusImprovementCompass:()=>zt,projectionHasNonEnforcementLabel:()=>Vs,projectionMatchesPackageVersion:()=>Hs,resolveEffectiveContract:()=>Gr,resolveStatusNextAction:()=>jn,resolvedFactsEvidenceRequirementsHash:()=>ke,serializeDiagnosticCatalog:()=>ms,stableSerialize:()=>x,statusCompassResidualIsSubsetOfDoctor:()=>Rs,toAdapterDiagnostic:()=>ut,unavailableStatusImprovementCompass:()=>Ss,validateAgentSkillDocument:()=>cr,validateAgentSkillsPackage:()=>Gs,version:()=>pr});module.exports=Zs(Pa);var pr="4.6.1";var fr="1.5",nn="docs/diagnostics.md";function v(e){return typeof e=="string"&&e.length>0?e:void 0}function ur(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function ft(e){let t=typeof e.ruleId=="string"?e.ruleId:typeof e.code=="string"?e.code:void 0,n=typeof e.file=="string"?e.file:void 0,r=typeof e.fromLayer=="string"?e.fromLayer:void 0,s=typeof e.toLayer=="string"?e.toLayer:void 0,i=typeof e.target=="string"?e.target:void 0;return[t,n,r??"",s??"",i??""].join("|")}function pt(e){let t=new Map;return e.map(n=>{let r=ft(n),s=(t.get(r)??0)+1;return t.set(r,s),s===1?r:`${r}#${s}`})}function rn(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}function sn(e){return`${nn}#${e}`}function Xs(e,t,n){if(e==="LAYER_IMPORT_VIOLATION")return t.typeOnly||n.targetTypeOnlyExports===!0||n.namedBindingsTypeOnly===!0?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":n.peerIsolation===!0?"Extract the shared dependency to a shared layer, test at the public interface, then preflight again.":`Define a port in ${t.fromLayer??"the source layer"}, inject the ${t.toLayer??"outer-layer"} implementation, test at the public interface, then preflight again.`;if(e==="FORBIDDEN_GLOBAL")return`Inject ${t.target??"the capability"} through a port, test at the public interface, then preflight again.`;if(e==="CAPABILITY_VIOLATION")return`Define a ${v(n.capability)??"capability"} port in ${t.fromLayer??"the walled layer"}, bind the implementation outside it, test at the public interface, then preflight again.`;if(e==="CIRCULAR_DEPENDENCY")return"Extract the shared dependency into a third module, test at the public interface, then preflight again.";if(e==="RAW_EVENT_PUBLISH")return"Publish through a registered intent creator, then run Ark again.";if(e==="PUBLISH_MISSING_SOURCE")return"Add metadata.source to the publish call, then run Ark again.";if(e==="ARKRULE_STRUCTURE"||e==="ARKRULE_INVARIANT"||e==="INVARIANT_UNCOVERED"||e.startsWith("ARKRULE_")){let r=t.arkruleSource??"arkrules/<Layer>.json";return`Fix the structure or invariant for ${t.arkruleId??"the ArkRule"} (declared in ${r}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`}return`Resolve ${e} without weakening ark.config.json, then run Ark again.`}function ut(e,t="error",n){let r=v(e.ruleId)??v(e.code)??"ARK_UNKNOWN",s=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,i={...v(e.target)?{target:v(e.target)}:{},...v(e.fromLayer)?{fromLayer:v(e.fromLayer)}:{},...v(e.toLayer)?{toLayer:v(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}:{},...v(e.capability)?{capability:v(e.capability)}:{},...v(e.edgeKind)?{edgeKind:v(e.edgeKind)}:{},...v(e.arkruleId)?{arkruleId:v(e.arkruleId)}:{},...v(e.arkruleSource)?{arkruleSource:v(e.arkruleSource)}:{}},a=n??ft(e),o=rn(a);return{ruleId:r,severity:s,message:v(e.message)??r,location:{file:v(e.file)??"<unknown>",line:ur(e.line,1),column:ur(e.column,1)},evidence:i,nextAction:v(e.nextAction)??Xs(r,i,e),findingRef:o,targetKey:a,docsCodePath:sn(r)}}function mr(e){let t=e.completeness??"complete",n=e.mode??"lexical-compatibility";if(t==="complete"&&(e.completenessReasons?.length??0)>0)throw new Error("completenessReasons must be empty when completeness is complete.");let r=t==="complete"?[]:e.completenessReasons&&e.completenessReasons.length>0?e.completenessReasons.map(m=>({code:v(m.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:v(m.message)??`Analysis ${t}: required evidence is incomplete.`,...v(m.file)?{file:v(m.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],s={...v(e.policyHash)?{policyHash:v(e.policyHash)}:{},...v(e.resolverIdentity)?{resolverIdentity:v(e.resolverIdentity)}:{},...v(e.factsHash)?{factsHash:v(e.factsHash)}:{},...v(e.candidateTreeHash)?{candidateTreeHash:v(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let m of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!s[m])throw new Error(`${m} is required for resolved ${t} adapter evidence.`)}let i=e.violations??[],a=e.warnings??[],o=pt(i),d=pt(a),u=[...i.map((m,c)=>ut(m,"error",o[c])),...a.map((m,c)=>ut(m,"warning",d[c]))],g={schemaVersion:"1.5",completenessReasons:r,diagnostics:u};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...g,mode:n,valid:!1,completeness:t,...s};let m={policyHash:s.policyHash,resolverIdentity:s.resolverIdentity,factsHash:s.factsHash,candidateTreeHash:s.candidateTreeHash};return t==="complete"?{...g,mode:n,valid:e.valid,completeness:t,...m}:{...g,mode:n,valid:!1,completeness:t,...m}}return t==="complete"?{...g,mode:n,valid:e.valid,completeness:t,...s}:{...g,mode:n,valid:!1,completeness:t,...s}}var gr={$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}}}}}};var yr="1.0",an="https://unpkg.com/arkgate@4/schemas/ark.project-identity.schema.json",mt="^sha256:[a-f0-9]{64}$",on={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:mt,description:"Project id previously returned by ark_identity or ark_manifest."}}},ln={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:mt},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},hr={$schema:"https://json-schema.org/draft/2020-12/schema",$id:an,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:mt},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{type:"string",minLength:1},arkgateVersion:{type:"string",minLength:1},contractHash:{type:"string",pattern:mt},contractSource:{enum:["project","default-profile","manifest"]},runtimeId:{type:"string",minLength:1},processStartedAt:{type:"string",format:"date-time"}},$defs:{expectation:on,binding:ln}};function Ar(e,t,n){if(!e||!t)throw new Error("Project identity requires resolvedRoot and resolvedConfigPath.");let r=n(JSON.stringify({resolvedRoot:e,resolvedConfigPath:t})).toLowerCase();if(!/^[a-f0-9]{64}$/.test(r))throw new Error("Project identity hash adapter must return 64 hexadecimal SHA-256 characters.");return`sha256:${r}`}function Ir(e){return{schemaVersion:"1.0",...e}}var dn=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),un=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),fn=Object.freeze(Object.keys(un).sort()),cn=Object.freeze({fs:"filesystem","node:fs":"filesystem","fs/promises":"filesystem","node:fs/promises":"filesystem","fs-extra":"filesystem","graceful-fs":"filesystem",memfs:"filesystem",chokidar:"filesystem",http:"network",https:"network",http2:"network",net:"network",tls:"network",dgram:"network",dns:"network","node:http":"network","node:https":"network","node:http2":"network","node:net":"network","node:tls":"network","node:dgram":"network","node:dns":"network",axios:"network",undici:"network","node-fetch":"network",got:"network",ky:"network",superagent:"network",ws:"network",process:"process","node:process":"process",child_process:"process","node:child_process":"process","@prisma/client":"persistence",prisma:"persistence",pg:"persistence",mysql:"persistence",mysql2:"persistence",mongodb:"persistence",mongoose:"persistence",sqlite3:"persistence","better-sqlite3":"persistence",redis:"persistence",ioredis:"persistence",typeorm:"persistence",knex:"persistence","drizzle-orm":"persistence",sequelize:"persistence",kysely:"persistence","@supabase/supabase-js":"persistence"}),pn=Object.freeze({process:Object.freeze(["process","node:process"])});function Me(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=cn[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),s=cn[r];if(s)return s;let i=e.indexOf("/",n+1);return i<0?null:cn[e.slice(0,i)]??null}function ie(e,t){for(let n of t)if(pn[n]?.includes(e))return n;return null}function gt(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),s=un[r];if(s)return s}return null}function be(e){if(e?.pure===!0)return[...dn].sort();let n=(e?.capabilities?.deny??[]).filter(r=>dn.includes(r));return[...new Set(n)].sort()}function $e(e,t){if(t.length===0)return!1;let n=new Set(t),r=e.split(".");for(let s=r.length;s>=1;s-=1)if(n.has(r.slice(0,s).join(".")))return!0;return!1}function yt(e){let t=new Set,n=new Set,r=Object.keys(un);for(let s of e?.forbiddenGlobals??[]){let i=r.filter(a=>a===s||a.startsWith(`${s}.`));if(i.length===0)n.add(s);else for(let a of i)t.add(`ambient:${a}`);for(let a of pn[s]??[])t.add(`import-exact:${a}`)}for(let s of be(e)){if(t.add(`import:${s}`),s==="process")for(let i of pn.process)t.add(`import-exact:${i}`);for(let i of r)gt(i)===s&&t.add(`ambient:${i}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}var br=new Map;function Sr(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function ht(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let s=e[n+1];if("*?{}[],".includes(s)||s==="\\"){t+="\\"+s,n+=1;continue}t+="/";continue}t+=r}return t}function Qs(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="{")t+=1;else if(r==="}"&&(t-=1,t<0))return!1}return t===0}function pe(e){let t=br.get(e);if(t)return t;let n=ht(e),r=Qs(n),s="",i=0;for(let o=0;o<n.length;o+=1){let d=n[o];d==="\\"&&o+1<n.length?(s+=Sr(n[o+1]),o+=1):d==="*"?n[o+1]==="*"?n[o+2]==="/"?(s+="(?:.*/)?",o+=2):(s+=".*",o+=1):s+="[^/]*":d==="?"?s+="[^/]":d==="{"&&r?(s+="(?:",i+=1):d==="}"&&r&&i>0?(s+=")",i-=1):d===","&&r&&i>0?s+="|":s+=Sr(d)}let a=new RegExp(`^${s}$`);return br.set(e,a),a}function ei(e){return ht(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}function mn(e,t){let n=ht(String(e)),r=ei(n),s=n.replace(/\*/g,"").length,i=r.length*1e4+s;if(t==null||t==="")return i;let a=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return s;let o=0,d=-1;for(let u of r){let g=-1;for(let m=o;m<a.length;m+=1)if(a[m]===u){g=m;break}if(g<0)return i;d=g,o=g+1}return(d+1)*1e6+r.length*1e4+s}function Q(e,t){let n=String(e).split(/[/\\]/).join("/"),r,s=-1;for(let i of t??[])if(!(i.exclude??[]).some(a=>pe(a).test(n))){for(let a of i.patterns??[])if(pe(a).test(n)){let o=mn(a,n);o>s&&(s=o,r=i.name)}}return r}function Rr(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),r=new Set(t.map(s=>String(s).toLowerCase()));for(let s=0;s<n.length-1;s+=1)if(r.has(n[s].toLowerCase()))return`${n[s].toLowerCase()}/${n[s+1].toLowerCase()}`}function ti(e){let t=new Set;for(let n of e??[]){let s=ht(String(n)).split("/").filter(Boolean);for(let i=0;i<s.length;i+=1){let a=s[i];if((a==="**"||a==="*")&&i>0){let o=s[i-1];o&&!o.includes("*")&&!o.includes("{")&&!o.includes("}")&&t.add(o)}}}return[...t]}function ni(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(s=>typeof s=="string"&&s.length>0);let r=(n??[]).find(s=>s.name===t);return ti(r?.patterns)}function ri(e){return!e.fromPath||!e.toPath||e.folderCount<=0||!e.fromSlice||!e.toSlice?!0:e.fromSlice!==e.toSlice}function ee(e,t,n,r){for(let s of e??[])if(!(s.from!==t||s.to!==n)&&s.allowed===!1){if(s.peerIsolation){let i=r?.fromPath,a=r?.toPath,o=ni(s,t,r?.layers),d=i&&a?Rr(i,o):void 0,u=i&&a?Rr(a,o):void 0;if(ri({fromPath:i,toPath:a,folderCount:o.length,fromSlice:d,toSlice:u}))return s;continue}if(t!==n)return s}}function Se(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function Cr(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function Er(e,t){if(e.isImportDeclaration(t)){let r=t.importClause;if(!r)return!1;if(r.isTypeOnly)return!0;let s=r.namedBindings;return!!(s&&e.isNamedImports(s)&&s.elements.length>0&&s.elements.every(i=>i.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(r=>r.isTypeOnly))}function kr(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=s=>s===t.fileName?t:void 0,r.fileExists=s=>s===t.fileName,r.readFile=s=>s===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}function gn(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function yn(e,t,n,r){let s=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,i;try{i=s?t.getShorthandAssignmentValueSymbol(r.parent):gn(t,r)}catch{i=void 0}return!!i?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}function ue(e,t){let n,r=[],s=(a,o,d,u=!1)=>r.push({specifier:d,kind:o,line:Cr(t,a),typeOnly:u,unresolved:d===void 0,node:a}),i=a=>{if(e.isImportDeclaration(a))s(a,"import",Se(e,a.moduleSpecifier),Er(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)s(a,"export",Se(e,a.moduleSpecifier),Er(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))s(a,"require",Se(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let o=a.expression.kind===e.SyntaxKind.ImportKeyword,u=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!yn(e,n??(n=kr(e,t)),t,a.expression);(o||u)&&s(a,u?"require":"dynamic-import",Se(e,a.arguments[0]))}e.forEachChild(a,i)};return i(t),r}function si(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let s=Se(e,r.argumentExpression);if(s===void 0)return;n.unshift(s)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}function ii(e,t){let n=t.parent;return e.isPropertyAccessExpression(n)||e.isElementAccessExpression(n)?!1:e.isExpressionNode(t)&&!e.isInTypeQuery(t)||e.isShorthandPropertyAssignment(n)&&n.name===t}function vr(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let r=n.length;r>=1;r-=1){let s=n.slice(0,r).join(".");if(e.has(s))return s}}function fe(e,t,n){if(n.length===0)return[];let r=new Set(n),s=kr(e,t),i=new Map,a=new Set;for(let c of t.statements)if(e.isVariableStatement(c))for(let l of c.declarationList.declarations)e.isIdentifier(l.name)&&a.add(l.name.text);let o=c=>{let l=si(e,c);if(!l)return;let p=gn(s,l.root),y=p?i.get(p):void 0;return y?[...y,...l.segments.slice(1)]:yn(e,s,t,l.root)||a.has(l.root.text)?void 0:l.segments};for(let c of t.statements)if(e.isVariableStatement(c))for(let l of c.declarationList.declarations){if(!l.initializer||!e.isIdentifier(l.name))continue;let p=o(l.initializer),y=gn(s,l.name);!p||!y||i.set(y,p)}let d=[],u=new Set,g=(c,l)=>{let p=Cr(t,l),y=`${c}:${l.getStart(t)}`;u.has(y)||(u.add(y),d.push({name:c,line:p,node:l}))},m=c=>{let l=c.parent&&(e.isPropertyAccessExpression(c.parent)||e.isElementAccessExpression(c.parent))&&c.parent.expression===c;if((e.isPropertyAccessExpression(c)||e.isElementAccessExpression(c))&&!l){let p=o(c),y=p?vr(r,p):void 0;y&&g(y,c)}else e.isIdentifier(c)&&r.has(c.text)&&ii(e,c)&&!yn(e,s,t,c)&&g(c.text,c);if(e.isVariableDeclaration(c)&&e.isObjectBindingPattern(c.name)&&c.initializer){let p=o(c.initializer);if(p)for(let y of c.name.elements){if(!e.isIdentifier(y.name))continue;let I=y.propertyName?Se(e,y.propertyName)??y.propertyName.text:y.name.text,R=vr(r,[...p,I]);R&&g(R,c.initializer)}}e.forEachChild(c,m)};return m(t),d}function hn(e,t,n){let r=[];for(let s of n?.dependencies??ue(e,t)){if(s.typeOnly||!s.specifier)continue;let i=Me(s.specifier);i&&r.push({capability:i,symbol:s.specifier,line:s.line,source:"import-based"})}for(let s of n?.ambientUses??fe(e,t,fn)){let i=gt(s.name);i&&r.push({capability:i,symbol:s.name,line:s.line,source:"ambient-global"})}return r.sort((s,i)=>s.line-i.line||s.capability.localeCompare(i.capability)||s.symbol.localeCompare(i.symbol))}var An={RAW_EVENT_PUBLISH:"Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts and tooling.",PUBLISH_MISSING_SOURCE:"Strict Ark publish calls must include metadata.source."},In=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 bn(e,t){return t.flatMap((r,s)=>(r.prefixes??r.intentPrefixes??[]).map(i=>({layer:r.name,layerIndex:s,prefix:i.endsWith(".")?i:`${i}.`}))).filter(({prefix:r})=>e.startsWith(r)).sort((r,s)=>s.prefix.length-r.prefix.length||r.layerIndex-s.layerIndex)[0]?.layer}function me(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function Fe(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&me(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:An.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:An.PUBLISH_MISSING_SOURCE}),t}function w(e,t,n){return{ruleId:e,code:e,message:t,...n}}function Re(e,t){return e.slice(0,t).split(`
|
|
2
|
-
`).length}function ai(e){let t=[],n=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,r;for(;(r=n.exec(e))!==null;)t.push({value:r[1],index:r.index});return t}function 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 s;for(;(s=r.re.exec(e))!==null;){let i=s.index+s[0].indexOf(s[1]),a=s[0],o=r.kind==="import"&&/\bimport\s+type\b/.test(a)||r.kind==="export"&&/\bexport\s+type\b/.test(a);t.push({value:s[1],index:i,kind:r.kind,typeOnly:o})}}return t.sort((r,s)=>r.index-s.index)}function li(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],s=i=>{e.isStringLiteralLike(i)&&r.push({value:i.text,index:i.getStart(n)}),e.forEachChild(i,s)};return s(n),r}function 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))}function di(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}function pi(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}function He(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function ui(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}function _r(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:ui(e,r.name)===n)}function Ve(e,t,n){return _r(e,t,n)!==void 0}function De(e,t,n){let r=_r(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}function fi(e,t){let n=De(e,t,"metadata");return Ve(e,n,"source")}function xr(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?xr(e,t.name):!1:!1}function mi(e,t){if(!e.isCallExpression(t))return!1;let n=t.expression;return e.isPropertyAccessExpression(n)?n.name.text==="publish":e.isIdentifier(n)&&n.text==="publish"}function gi(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=He(e,n);return r!==void 0&&me(r)||Ve(e,n,"intent")||xr(e,n)}function yi(e,t){if(!e.isCallExpression(t))return!1;let[n,r,s]=t.arguments;return fi(e,n)||Ve(e,r,"source")||Ve(e,s,"source")}function hi(e,t){if(!e.isCallExpression(t))return;let[n,r,s]=t.arguments,i=De(e,n,"metadata");return He(e,De(e,i,"source"))??He(e,De(e,r,"source"))??He(e,De(e,s,"source"))}function Ai(e,t,n,r){let s=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),i=n,a=i?.filePath,o=i?.layer,d=[],u=m=>s.getLineAndCharacterOfPosition(m.getStart(s)).line+1,g=m=>{if(mi(e,m)){let c=m.arguments[0],l=He(e,c);for(let y of Fe({publishCall:!0,rawIntentName:l,objectHasIntent:Ve(e,c,"intent"),arkPublishCandidate:gi(e,m),hasSource:yi(e,m)}))d.push(w(y.ruleId,y.message,{line:u(m),filePath:a}));let p=hi(e,m);if(r&&o&&p&&me(p)){let y=r.resolveLayer(p);y&&y!==o&&d.push(w("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${p}" resolves to ${y}, but the target file is classified as ${o}.`,{line:u(m),filePath:a,target:p,fromLayer:o,toLayer:y}))}}e.forEachChild(m,g)};return g(s),d}function Sn(e={}){let t=new Set((e.intents||[]).map(i=>typeof i=="string"?i:i.name)),n=e.forbiddenPatterns||[],r=new Set(e.infrastructureLayers??[]),s=e.enforceIntentAllowlist??t.size>0;return{validate(i,a){let o=[],d=a,u=d?.filePath,g=d?.layer,m=e.typescript,c=m?m.createSourceFile(u??"generated.ts",i,m.ScriptTarget.Latest,!0):void 0,l=c?ue(e.typescript,c):void 0,p=l?l.filter(f=>f.specifier!==void 0).map(f=>({value:f.specifier,index:f.node.getStart(c),kind:f.kind,typeOnly:f.typeOnly})):oi(i),y=e.typescript?li(e.typescript,i):ai(i);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(u))for(let f of l?.filter(({unresolved:h})=>h)??[]){let h=f.kind==="require";o.push(w(h?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${h?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:f.line,filePath:u}))}let I=g!==void 0&&(r.has(g)||pi(g)),R=g!==void 0?` If "${g}" is an infrastructure layer, mark it in ark.config.json with "mayImportInfrastructure": true (or name it with an infra token like Adapters/Persistence/Repository).`:"";for(let f of n)if(f instanceof RegExp){f.lastIndex=0;let h=f.exec(i);f.lastIndex=0,h&&o.push(w("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${f}`,{line:h.index===void 0?void 0:Re(i,h.index),filePath:u,suggestion:"Remove infrastructure imports from domain/application layers."+R}))}else i.includes(f)&&o.push(w("FORBIDDEN_SUBSTRING",`Forbidden substring: ${f}`,{line:Re(i,i.indexOf(f)),filePath:u}));for(let f of p){let h=e.resolveImportTarget?.(f.value,u)??(e.resolveImportLayer?{layer:e.resolveImportLayer(f.value,u)}:void 0),S=typeof u=="string"?e.resolveImportTarget?.(u)??(e.resolveImportLayer?{layer:g,relPath:void 0}:void 0):void 0,k=h?.layer;if(k&&g){let N=ee(e.architectureProfile?.rules,g,k,{fromPath:S?.relPath,toPath:h?.relPath,layers:e.architectureLayers});if(N){if(f.typeOnly&&!N.peerIsolation)continue;let D=!!N.peerIsolation;o.push(w("LAYER_IMPORT_VIOLATION",N.message??(D?`Layer "${g}" must not import across slices into "${k}".`:`Layer "${g}" must not import "${k}".`),{line:Re(i,f.index),source:f.value,target:f.value,filePath:u,fromLayer:g,toLayer:k,suggestion:D?"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:f.kind,peerIsolation:D,...f.typeOnly?{typeOnly:!0}:{}}}));continue}continue}I||f.typeOnly||!ci(f.value)&&!di(f.value)||o.push(w("FORBIDDEN_IMPORT",`Forbidden ${f.kind} target: "${f.value}".`,{line:Re(i,f.index),source:f.value,target:f.value,filePath:u,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+R,details:{importKind:f.kind}}))}if(e.policies)for(let f of e.policies){let h=f.check({source:i,context:a});if(h!==!0)if(Array.isArray(h))for(let S of h)o.push(w("POLICY_VIOLATION",S.message,{filePath:u,suggestion:`Fix violation of policy "${f.name}".`}));else h===!1?o.push(w("POLICY_VIOLATION",`Policy ${f.name} failed on generated code`)):o.push(w("POLICY_VIOLATION",h.message))}if(s&&t.size>0)for(let f of y)me(f.value)&&!t.has(f.value)&&o.push(w("UNKNOWN_INTENT",`Unknown intent reference: "${f.value}"`,{line:Re(i,f.index),filePath:u,target:f.value,suggestion:`Register intent "${f.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&g)for(let f of y){if(!me(f.value))continue;let h=e.architectureProfile.resolveLayer(f.value);if(!h)continue;let S=ee(e.architectureProfile.rules,g,h);S&&o.push(w("LAYER_REFERENCE_VIOLATION",S.message??`Layer "${g}" must not reference "${h}" through "${f.value}".`,{line:Re(i,f.index),filePath:u,target:f.value,fromLayer:g,toLayer:h,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:S}}))}if(e.extensions)for(let f of e.extensions)try{let h=f.analyze(i,a);o.push(...h)}catch(h){o.push(w("EXTENSION_ERROR",`Extension "${f.name}" failed: ${h instanceof Error?h.message:String(h)}`))}if(e.typescript&&c&&g&&e.forbiddenGlobals?.[g]?.length)try{let f=e.forbiddenGlobals[g];o.push(...fe(e.typescript,c,f).map(h=>w("FORBIDDEN_GLOBAL",`${g} must not use the ambient global "${h.name}".`,{line:h.line,filePath:u,target:h.name,fromLayer:g,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let h of l??[]){if(h.typeOnly||!h.specifier)continue;let S=ie(h.specifier,f);S&&o.push(w("FORBIDDEN_GLOBAL",`${g} must not use module "${h.specifier}" because it is the import form of forbidden global "${S}".`,{line:h.line,filePath:u,source:h.specifier,target:h.specifier,fromLayer:g,details:{importKind:h.kind,forbiddenGlobal:S},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(f){o.push(w("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${f instanceof Error?f.message:String(f)}`))}if(e.typescript&&c&&g&&e.capabilityWalls?.[g]?.length)try{let f=new Set(e.capabilityWalls[g]),h=e.forbiddenGlobals?.[g]??[];for(let S of hn(e.typescript,c))f.has(S.capability)&&(S.source==="ambient-global"&&$e(S.symbol,h)||S.source==="import-based"&&ie(S.symbol,h)||o.push(w("CAPABILITY_VIOLATION",S.source==="import-based"?`${g} denies the ${S.capability} capability; found import of "${S.symbol}".`:`${g} denies the ${S.capability} capability; found ambient "${S.symbol}".`,{line:S.line,filePath:u,target:S.symbol,capability:S.capability,fromLayer:g,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(f){o.push(w("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${f instanceof Error?f.message:String(f)}`))}if(e.typescript)try{o.push(...Ai(e.typescript,i,a,e.architectureProfile))}catch(f){o.push(w("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${f instanceof Error?f.message:String(f)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:o.length===0,violations:o}}}}var Tr="1.1",It="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",Or=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Ii=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function bi(){let e=[];for(let t of Or)for(let n of Or)t===n||Ii.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var St=bi(),Rn=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"}],te={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},bt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:It,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:It,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:"1.1",default:"1.1"},name:{type:"string",minLength:1},include:{...te,minItems:1,default:["src"]},exclude:{...te,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:St,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...te,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},stewards:{...te,default:[]}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...te,minItems:1},exclude:te,intentPrefixes:te,description:{type:"string",minLength:1},forbiddenGlobals:te,capabilities:{type:"object",additionalProperties:!1,properties:{deny:{type:"array",uniqueItems:!0,items:{type:"string",enum:["network","filesystem","clock","randomness","environment","process","persistence"]}}}},pure:{type:"boolean"},mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...te,minItems:1}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}}}},ne=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
|
|
1
|
+
"use strict";var tn=Object.defineProperty;var zs=Object.getOwnPropertyDescriptor;var qs=Object.getOwnPropertyNames;var Ys=Object.prototype.hasOwnProperty;var Ws=(e,t)=>{for(var n in t)tn(e,n,{get:t[n],enumerable:!0})},Js=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of qs(t))!Ys.call(e,s)&&s!==n&&tn(e,s,{get:()=>t[s],enumerable:!(r=zs(t,s))||r.enumerable});return e};var Zs=e=>Js(tn({},"__esModule",{value:!0}),e);var Lo={};Ws(Lo,{ADAPTER_DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>nn,AGENT_PROJECTION_BEGIN_MARKER:()=>Ns,AGENT_PROJECTION_END_MARKER:()=>Zn,AGENT_PROJECTION_ENFORCEMENT_SURFACES:()=>Jt,AGENT_PROJECTION_NON_ENFORCEMENT_LABEL:()=>Xn,AGENT_SKILLS_PACKAGE_RELATIVE_ROOT:()=>rr,AGENT_SKILL_ENTRY_FILENAME:()=>ir,ANALYSIS_IR_SCHEMA_VERSION:()=>Ct,ARK_AGENT_PROJECTION_SCHEMA_VERSION:()=>Ls,ARK_AGENT_SKILLS_PACKAGE_SCHEMA_VERSION:()=>Us,ARK_ANALYSIS_RESULT_SCHEMA:()=>gr,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>fr,ARK_CONFIG_SCHEMA:()=>bt,ARK_CONFIG_SCHEMA_VERSION:()=>Tr,ARK_DESIGN_DELTA_SCHEMA_VERSION:()=>ls,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION:()=>as,ARK_IMPROVEMENT_COMPASS_SCHEMA_VERSION:()=>ot,ARK_PROJECT_IDENTITY_SCHEMA:()=>hr,ARK_PROJECT_IDENTITY_SCHEMA_URL:()=>on,ARK_PROJECT_IDENTITY_SCHEMA_VERSION:()=>yr,ARK_RULES_SCHEMA:()=>_t,ARK_RULES_SCHEMA_VERSION:()=>Vr,ARK_RULE_SENSORS:()=>kn,ARK_SKILL_NAMES:()=>dt,ARK_SKILL_NAME_COUNT:()=>or,ARK_STATUS_MANIFEST_SCHEMA:()=>Es,ARK_STATUS_MANIFEST_SCHEMA_URL:()=>Mn,ARK_STATUS_MANIFEST_SCHEMA_VERSION:()=>hs,DEFAULT_AGENT_PROJECTION_RULE_IDS:()=>ws,DIAGNOSTIC_CATALOG:()=>nt,DIAGNOSTIC_CATALOG_SCHEMA_VERSION:()=>cs,DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>Kt,DIAGNOSTIC_RULE_IDS:()=>ds,EffectiveContractError:()=>Je,FLAT_SKILL_TEMPLATES_RELATIVE_ROOT:()=>sr,IMPROVEMENT_COMPASS_OUT_OF_SCOPE_LENSES:()=>ce,IMPROVEMENT_COMPASS_TOP_RESIDUAL_CAP:()=>lt,IMPROVEMENT_LENS_IDS:()=>at,POLICY_DELTA_SCHEMA_VERSION:()=>wt,PROJECT_BINDING_SCHEMA:()=>ln,PROJECT_EXPECTATION_SCHEMA:()=>an,RESOLVED_CANDIDATE_FACTS_SCHEMA:()=>vt,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION:()=>oe,STATUS_COMPASS_FACTS_SOURCES:()=>Fn,STATUS_COMPASS_MODES:()=>$n,STATUS_COMPASS_REASON_CODES:()=>it,adapterDocsCodePath:()=>sn,adapterFindingOccurrenceTargetKeys:()=>pt,adapterFindingRefFromTargetKey:()=>rn,adapterFindingTargetKey:()=>ft,agentProjectionContentIdentity:()=>ct,agentSkillEntryRelativePath:()=>dr,agentSkillPackageFileRelativePath:()=>Bs,analyzeArchitectureConvergence:()=>ge,analyzeChange:()=>Qe,analyzePolicyDelta:()=>_n,analyzeProject:()=>xe,analyzeResolvedProject:()=>Te,buildAgentProjectionBeginMarker:()=>er,buildAgentProjectionBlock:()=>Fs,buildAgentProjectionBody:()=>Xt,buildAgentProjectionMeta:()=>Ds,buildArkRuleFileHints:()=>Ut,buildEffectiveArkRules:()=>xt,buildImprovementCompass:()=>Ts,buildRulesInventory:()=>is,buildStatusManifest:()=>Is,canPromoteInvariant:()=>Pt,catalogFixForRuleId:()=>gs,catalogWhyForRuleId:()=>ys,classifyArkPolicyDelta:()=>Mt,classifyStatusWritePath:()=>Hn,collectAnalysisConfigWarnings:()=>tt,collectEmptyAppliesToFindings:()=>jt,collectForbiddenCapabilityUses:()=>fe,createAICodeGate:()=>Sn,createAdapterResult:()=>mr,createArchitectureProfile:()=>Be,createArchitectureProfileFromArkConfig:()=>En,createElevenLayerArkConfig:()=>vn,createProjectId:()=>Ar,createProjectIdentity:()=>Ir,createResolvedCandidateFacts:()=>Et,defaultHonestLabel:()=>Vn,deriveArkRuleFileHints:()=>Tn,detectArchitectureCycles:()=>Dt,deterministicHash:()=>M,diagnosticDocsFragment:()=>wn,diagnosticDocsPath:()=>fs,effectiveContractPolicyPayload:()=>Ot,elevenLayerProfile:()=>Ge,emptyEffectiveArkRules:()=>le,evaluateArchitectureGraph:()=>Ie,evaluateArkRuleSensors:()=>Vt,evaluateInvariantCoverage:()=>Tt,evaluateStatusBinding:()=>Dn,explainViolation:()=>xn,extractAgentProjectionBlock:()=>Wt,extractClassShapesFromSource:()=>Qr,extractSemanticDependencies:()=>ue,flatSkillTemplateFileRelativePath:()=>Ks,formatAgentProjectionCatalogShortList:()=>tr,formatAgentProjectionLayers:()=>Yt,formatImprovementCompassDoctorLines:()=>Ps,formatImprovementCompassResidualLabels:()=>Wn,getDiagnosticCatalogEntry:()=>rt,inventoryToExtractionCard:()=>os,isArkSkillName:()=>en,isCataloguedOrArkRuleFamily:()=>us,isKnownDiagnosticCode:()=>ps,isValidAgentSkillName:()=>ar,loadArkConfigContract:()=>Ue,loadArkRulesContract:()=>We,loadContract:()=>Xe,loadResolvedCandidateFacts:()=>se,mergeAgentProjectionDocument:()=>js,normalizeSkillContent:()=>Qt,normalizeStatusImprovementCompass:()=>Un,parseAgentProjectionStamp:()=>nr,parseArkConfigJson:()=>Rt,parseArkRulesJson:()=>jr,parseSkillDocument:()=>lr,policyDeltaAcknowledgementMatches:()=>$t,preflightChange:()=>Pn,preflightResolvedChange:()=>Ln,primaryImprovementCompassNextAction:()=>Jn,projectStatusImprovementCompass:()=>zt,projectionHasNonEnforcementLabel:()=>Vs,projectionMatchesPackageVersion:()=>Hs,resolveEffectiveContract:()=>Gr,resolveStatusNextAction:()=>jn,resolvedFactsEvidenceRequirementsHash:()=>ke,serializeDiagnosticCatalog:()=>ms,stableSerialize:()=>x,statusCompassResidualIsSubsetOfDoctor:()=>Rs,toAdapterDiagnostic:()=>ut,unavailableStatusImprovementCompass:()=>Ss,validateAgentSkillDocument:()=>cr,validateAgentSkillsPackage:()=>Gs,version:()=>pr});module.exports=Zs(Lo);var pr="4.6.2";var fr="1.5",nn="docs/diagnostics.md";function v(e){return typeof e=="string"&&e.length>0?e:void 0}function ur(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function ft(e){let t=typeof e.ruleId=="string"?e.ruleId:typeof e.code=="string"?e.code:void 0,n=typeof e.file=="string"?e.file:void 0,r=typeof e.fromLayer=="string"?e.fromLayer:void 0,s=typeof e.toLayer=="string"?e.toLayer:void 0,i=typeof e.target=="string"?e.target:void 0;return[t,n,r??"",s??"",i??""].join("|")}function pt(e){let t=new Map;return e.map(n=>{let r=ft(n),s=(t.get(r)??0)+1;return t.set(r,s),s===1?r:`${r}#${s}`})}function rn(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}function sn(e){return`${nn}#${e}`}function Xs(e,t,n){if(e==="LAYER_IMPORT_VIOLATION")return t.typeOnly||n.targetTypeOnlyExports===!0||n.namedBindingsTypeOnly===!0?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":n.peerIsolation===!0?"Extract the shared dependency to a shared layer, test at the public interface, then preflight again.":`Define a port in ${t.fromLayer??"the source layer"}, inject the ${t.toLayer??"outer-layer"} implementation, test at the public interface, then preflight again.`;if(e==="FORBIDDEN_GLOBAL")return`Inject ${t.target??"the capability"} through a port, test at the public interface, then preflight again.`;if(e==="CAPABILITY_VIOLATION")return`Define a ${v(n.capability)??"capability"} port in ${t.fromLayer??"the walled layer"}, bind the implementation outside it, test at the public interface, then preflight again.`;if(e==="CIRCULAR_DEPENDENCY")return"Extract the shared dependency into a third module, test at the public interface, then preflight again.";if(e==="RAW_EVENT_PUBLISH")return"Publish through a registered intent creator, then run Ark again.";if(e==="PUBLISH_MISSING_SOURCE")return"Add metadata.source to the publish call, then run Ark again.";if(e==="ARKRULE_STRUCTURE"||e==="ARKRULE_INVARIANT"||e==="INVARIANT_UNCOVERED"||e.startsWith("ARKRULE_")){let r=t.arkruleSource??"arkrules/<Layer>.json";return`Fix the structure or invariant for ${t.arkruleId??"the ArkRule"} (declared in ${r}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`}return`Resolve ${e} without weakening ark.config.json, then run Ark again.`}function ut(e,t="error",n){let r=v(e.ruleId)??v(e.code)??"ARK_UNKNOWN",s=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,i={...v(e.target)?{target:v(e.target)}:{},...v(e.fromLayer)?{fromLayer:v(e.fromLayer)}:{},...v(e.toLayer)?{toLayer:v(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}:{},...v(e.capability)?{capability:v(e.capability)}:{},...v(e.edgeKind)?{edgeKind:v(e.edgeKind)}:{},...v(e.arkruleId)?{arkruleId:v(e.arkruleId)}:{},...v(e.arkruleSource)?{arkruleSource:v(e.arkruleSource)}:{}},o=n??ft(e),a=rn(o);return{ruleId:r,severity:s,message:v(e.message)??r,location:{file:v(e.file)??"<unknown>",line:ur(e.line,1),column:ur(e.column,1)},evidence:i,nextAction:v(e.nextAction)??Xs(r,i,e),findingRef:a,targetKey:o,docsCodePath:sn(r)}}function mr(e){let t=e.completeness??"complete",n=e.mode??"lexical-compatibility";if(t==="complete"&&(e.completenessReasons?.length??0)>0)throw new Error("completenessReasons must be empty when completeness is complete.");let r=t==="complete"?[]:e.completenessReasons&&e.completenessReasons.length>0?e.completenessReasons.map(m=>({code:v(m.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:v(m.message)??`Analysis ${t}: required evidence is incomplete.`,...v(m.file)?{file:v(m.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],s={...v(e.policyHash)?{policyHash:v(e.policyHash)}:{},...v(e.resolverIdentity)?{resolverIdentity:v(e.resolverIdentity)}:{},...v(e.factsHash)?{factsHash:v(e.factsHash)}:{},...v(e.candidateTreeHash)?{candidateTreeHash:v(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let m of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!s[m])throw new Error(`${m} is required for resolved ${t} adapter evidence.`)}let i=e.violations??[],o=e.warnings??[],a=pt(i),d=pt(o),u=[...i.map((m,c)=>ut(m,"error",a[c])),...o.map((m,c)=>ut(m,"warning",d[c]))],g={schemaVersion:"1.5",completenessReasons:r,diagnostics:u};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...g,mode:n,valid:!1,completeness:t,...s};let m={policyHash:s.policyHash,resolverIdentity:s.resolverIdentity,factsHash:s.factsHash,candidateTreeHash:s.candidateTreeHash};return t==="complete"?{...g,mode:n,valid:e.valid,completeness:t,...m}:{...g,mode:n,valid:!1,completeness:t,...m}}return t==="complete"?{...g,mode:n,valid:e.valid,completeness:t,...s}:{...g,mode:n,valid:!1,completeness:t,...s}}var gr={$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}}}}}};var yr="1.0",on="https://unpkg.com/arkgate@4/schemas/ark.project-identity.schema.json",mt="^sha256:[a-f0-9]{64}$",an={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:mt,description:"Project id previously returned by ark_identity or ark_manifest."}}},ln={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:mt},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},hr={$schema:"https://json-schema.org/draft/2020-12/schema",$id:on,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:mt},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{type:"string",minLength:1},arkgateVersion:{type:"string",minLength:1},contractHash:{type:"string",pattern:mt},contractSource:{enum:["project","default-profile","manifest"]},runtimeId:{type:"string",minLength:1},processStartedAt:{type:"string",format:"date-time"}},$defs:{expectation:an,binding:ln}};function Ar(e,t,n){if(!e||!t)throw new Error("Project identity requires resolvedRoot and resolvedConfigPath.");let r=n(JSON.stringify({resolvedRoot:e,resolvedConfigPath:t})).toLowerCase();if(!/^[a-f0-9]{64}$/.test(r))throw new Error("Project identity hash adapter must return 64 hexadecimal SHA-256 characters.");return`sha256:${r}`}function Ir(e){return{schemaVersion:"1.0",...e}}var dn=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),un=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),fn=Object.freeze(Object.keys(un).sort()),cn=Object.freeze({fs:"filesystem","node:fs":"filesystem","fs/promises":"filesystem","node:fs/promises":"filesystem","fs-extra":"filesystem","graceful-fs":"filesystem",memfs:"filesystem",chokidar:"filesystem",http:"network",https:"network",http2:"network",net:"network",tls:"network",dgram:"network",dns:"network","node:http":"network","node:https":"network","node:http2":"network","node:net":"network","node:tls":"network","node:dgram":"network","node:dns":"network",axios:"network",undici:"network","node-fetch":"network",got:"network",ky:"network",superagent:"network",ws:"network",process:"process","node:process":"process",child_process:"process","node:child_process":"process","@prisma/client":"persistence",prisma:"persistence",pg:"persistence",mysql:"persistence",mysql2:"persistence",mongodb:"persistence",mongoose:"persistence",sqlite3:"persistence","better-sqlite3":"persistence",redis:"persistence",ioredis:"persistence",typeorm:"persistence",knex:"persistence","drizzle-orm":"persistence",sequelize:"persistence",kysely:"persistence","@supabase/supabase-js":"persistence"}),pn=Object.freeze({process:Object.freeze(["process","node:process"])});function Me(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=cn[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),s=cn[r];if(s)return s;let i=e.indexOf("/",n+1);return i<0?null:cn[e.slice(0,i)]??null}function ie(e,t){for(let n of t)if(pn[n]?.includes(e))return n;return null}function gt(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),s=un[r];if(s)return s}return null}function be(e){if(e?.pure===!0)return[...dn].sort();let n=(e?.capabilities?.deny??[]).filter(r=>dn.includes(r));return[...new Set(n)].sort()}function $e(e,t){if(t.length===0)return!1;let n=new Set(t),r=e.split(".");for(let s=r.length;s>=1;s-=1)if(n.has(r.slice(0,s).join(".")))return!0;return!1}function yt(e){let t=new Set,n=new Set,r=Object.keys(un);for(let s of e?.forbiddenGlobals??[]){let i=r.filter(o=>o===s||o.startsWith(`${s}.`));if(i.length===0)n.add(s);else for(let o of i)t.add(`ambient:${o}`);for(let o of pn[s]??[])t.add(`import-exact:${o}`)}for(let s of be(e)){if(t.add(`import:${s}`),s==="process")for(let i of pn.process)t.add(`import-exact:${i}`);for(let i of r)gt(i)===s&&t.add(`ambient:${i}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}var br=new Map;function Sr(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function ht(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let s=e[n+1];if("*?{}[],".includes(s)||s==="\\"){t+="\\"+s,n+=1;continue}t+="/";continue}t+=r}return t}function Qs(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="{")t+=1;else if(r==="}"&&(t-=1,t<0))return!1}return t===0}function pe(e){let t=br.get(e);if(t)return t;let n=ht(e),r=Qs(n),s="",i=0;for(let a=0;a<n.length;a+=1){let d=n[a];d==="\\"&&a+1<n.length?(s+=Sr(n[a+1]),a+=1):d==="*"?n[a+1]==="*"?n[a+2]==="/"?(s+="(?:.*/)?",a+=2):(s+=".*",a+=1):s+="[^/]*":d==="?"?s+="[^/]":d==="{"&&r?(s+="(?:",i+=1):d==="}"&&r&&i>0?(s+=")",i-=1):d===","&&r&&i>0?s+="|":s+=Sr(d)}let o=new RegExp(`^${s}$`);return br.set(e,o),o}function ei(e){return ht(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}function mn(e,t){let n=ht(String(e)),r=ei(n),s=n.replace(/\*/g,"").length,i=r.length*1e4+s;if(t==null||t==="")return i;let o=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return s;let a=0,d=-1;for(let u of r){let g=-1;for(let m=a;m<o.length;m+=1)if(o[m]===u){g=m;break}if(g<0)return i;d=g,a=g+1}return(d+1)*1e6+r.length*1e4+s}function Q(e,t){let n=String(e).split(/[/\\]/).join("/"),r,s=-1;for(let i of t??[])if(!(i.exclude??[]).some(o=>pe(o).test(n))){for(let o of i.patterns??[])if(pe(o).test(n)){let a=mn(o,n);a>s&&(s=a,r=i.name)}}return r}function Rr(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),r=new Set(t.map(s=>String(s).toLowerCase()));for(let s=0;s<n.length-1;s+=1)if(r.has(n[s].toLowerCase()))return`${n[s].toLowerCase()}/${n[s+1].toLowerCase()}`}function ti(e){let t=new Set;for(let n of e??[]){let s=ht(String(n)).split("/").filter(Boolean);for(let i=0;i<s.length;i+=1){let o=s[i];if((o==="**"||o==="*")&&i>0){let a=s[i-1];a&&!a.includes("*")&&!a.includes("{")&&!a.includes("}")&&t.add(a)}}}return[...t]}function ni(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(s=>typeof s=="string"&&s.length>0);let r=(n??[]).find(s=>s.name===t);return ti(r?.patterns)}function ri(e){return!e.fromPath||!e.toPath||e.folderCount<=0||!e.fromSlice||!e.toSlice?!0:e.fromSlice!==e.toSlice}function ee(e,t,n,r){for(let s of e??[])if(!(s.from!==t||s.to!==n)&&s.allowed===!1){if(s.peerIsolation){let i=r?.fromPath,o=r?.toPath,a=ni(s,t,r?.layers),d=i&&o?Rr(i,a):void 0,u=i&&o?Rr(o,a):void 0;if(ri({fromPath:i,toPath:o,folderCount:a.length,fromSlice:d,toSlice:u}))return s;continue}if(t!==n)return s}}function Se(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function Cr(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function Er(e,t){if(e.isImportDeclaration(t)){let r=t.importClause;if(!r)return!1;if(r.isTypeOnly)return!0;let s=r.namedBindings;return!!(s&&e.isNamedImports(s)&&s.elements.length>0&&s.elements.every(i=>i.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(r=>r.isTypeOnly))}function kr(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=s=>s===t.fileName?t:void 0,r.fileExists=s=>s===t.fileName,r.readFile=s=>s===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}function gn(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function yn(e,t,n,r){let s=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,i;try{i=s?t.getShorthandAssignmentValueSymbol(r.parent):gn(t,r)}catch{i=void 0}return!!i?.declarations?.some(o=>o.getSourceFile().fileName===n.fileName)}function ue(e,t){let n,r=[],s=(o,a,d,u=!1)=>r.push({specifier:d,kind:a,line:Cr(t,o),typeOnly:u,unresolved:d===void 0,node:o}),i=o=>{if(e.isImportDeclaration(o))s(o,"import",Se(e,o.moduleSpecifier),Er(e,o));else if(e.isExportDeclaration(o)&&o.moduleSpecifier)s(o,"export",Se(e,o.moduleSpecifier),Er(e,o));else if(e.isImportEqualsDeclaration(o)&&e.isExternalModuleReference(o.moduleReference))s(o,"require",Se(e,o.moduleReference.expression),o.isTypeOnly===!0);else if(e.isCallExpression(o)){let a=o.expression.kind===e.SyntaxKind.ImportKeyword,u=e.isIdentifier(o.expression)&&o.expression.text==="require"&&!yn(e,n??(n=kr(e,t)),t,o.expression);(a||u)&&s(o,u?"require":"dynamic-import",Se(e,o.arguments[0]))}e.forEachChild(o,i)};return i(t),r}function si(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let s=Se(e,r.argumentExpression);if(s===void 0)return;n.unshift(s)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}function ii(e,t){let n=t.parent;return e.isPropertyAccessExpression(n)||e.isElementAccessExpression(n)?!1:e.isExpressionNode(t)&&!e.isInTypeQuery(t)||e.isShorthandPropertyAssignment(n)&&n.name===t}function vr(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let r=n.length;r>=1;r-=1){let s=n.slice(0,r).join(".");if(e.has(s))return s}}function fe(e,t,n){if(n.length===0)return[];let r=new Set(n),s=kr(e,t),i=new Map,o=new Set;for(let c of t.statements)if(e.isVariableStatement(c))for(let l of c.declarationList.declarations)e.isIdentifier(l.name)&&o.add(l.name.text);let a=c=>{let l=si(e,c);if(!l)return;let p=gn(s,l.root),y=p?i.get(p):void 0;return y?[...y,...l.segments.slice(1)]:yn(e,s,t,l.root)||o.has(l.root.text)?void 0:l.segments};for(let c of t.statements)if(e.isVariableStatement(c))for(let l of c.declarationList.declarations){if(!l.initializer||!e.isIdentifier(l.name))continue;let p=a(l.initializer),y=gn(s,l.name);!p||!y||i.set(y,p)}let d=[],u=new Set,g=(c,l)=>{let p=Cr(t,l),y=`${c}:${l.getStart(t)}`;u.has(y)||(u.add(y),d.push({name:c,line:p,node:l}))},m=c=>{let l=c.parent&&(e.isPropertyAccessExpression(c.parent)||e.isElementAccessExpression(c.parent))&&c.parent.expression===c;if((e.isPropertyAccessExpression(c)||e.isElementAccessExpression(c))&&!l){let p=a(c),y=p?vr(r,p):void 0;y&&g(y,c)}else e.isIdentifier(c)&&r.has(c.text)&&ii(e,c)&&!yn(e,s,t,c)&&g(c.text,c);if(e.isVariableDeclaration(c)&&e.isObjectBindingPattern(c.name)&&c.initializer){let p=a(c.initializer);if(p)for(let y of c.name.elements){if(!e.isIdentifier(y.name))continue;let I=y.propertyName?Se(e,y.propertyName)??y.propertyName.text:y.name.text,R=vr(r,[...p,I]);R&&g(R,c.initializer)}}e.forEachChild(c,m)};return m(t),d}function hn(e,t,n){let r=[];for(let s of n?.dependencies??ue(e,t)){if(s.typeOnly||!s.specifier)continue;let i=Me(s.specifier);i&&r.push({capability:i,symbol:s.specifier,line:s.line,source:"import-based"})}for(let s of n?.ambientUses??fe(e,t,fn)){let i=gt(s.name);i&&r.push({capability:i,symbol:s.name,line:s.line,source:"ambient-global"})}return r.sort((s,i)=>s.line-i.line||s.capability.localeCompare(i.capability)||s.symbol.localeCompare(i.symbol))}var An={RAW_EVENT_PUBLISH:"Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts and tooling.",PUBLISH_MISSING_SOURCE:"Strict Ark publish calls must include metadata.source."},In=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 bn(e,t){return t.flatMap((r,s)=>(r.prefixes??r.intentPrefixes??[]).map(i=>({layer:r.name,layerIndex:s,prefix:i.endsWith(".")?i:`${i}.`}))).filter(({prefix:r})=>e.startsWith(r)).sort((r,s)=>s.prefix.length-r.prefix.length||r.layerIndex-s.layerIndex)[0]?.layer}function me(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function Fe(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&me(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:An.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:An.PUBLISH_MISSING_SOURCE}),t}function w(e,t,n){return{ruleId:e,code:e,message:t,...n}}function Re(e,t){return e.slice(0,t).split(`
|
|
2
|
+
`).length}function oi(e){let t=[],n=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,r;for(;(r=n.exec(e))!==null;)t.push({value:r[1],index:r.index});return t}function ai(e){let t=[],n=[{kind:"import",re:/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s*)?['"]([^'"]+)['"]/g},{kind:"export",re:/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s*['"]([^'"]+)['"]/g},{kind:"dynamic-import",re:/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g},{kind:"require",re:/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g}];for(let r of n){let s;for(;(s=r.re.exec(e))!==null;){let i=s.index+s[0].indexOf(s[1]),o=s[0],a=r.kind==="import"&&/\bimport\s+type\b/.test(o)||r.kind==="export"&&/\bexport\s+type\b/.test(o);t.push({value:s[1],index:i,kind:r.kind,typeOnly:a})}}return t.sort((r,s)=>r.index-s.index)}function li(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],s=i=>{e.isStringLiteralLike(i)&&r.push({value:i.text,index:i.getStart(n)}),e.forEachChild(i,s)};return s(n),r}function 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))}function di(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}function pi(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}function He(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function ui(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}function _r(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:ui(e,r.name)===n)}function Ve(e,t,n){return _r(e,t,n)!==void 0}function De(e,t,n){let r=_r(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}function fi(e,t){let n=De(e,t,"metadata");return Ve(e,n,"source")}function xr(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?xr(e,t.name):!1:!1}function mi(e,t){if(!e.isCallExpression(t))return!1;let n=t.expression;return e.isPropertyAccessExpression(n)?n.name.text==="publish":e.isIdentifier(n)&&n.text==="publish"}function gi(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=He(e,n);return r!==void 0&&me(r)||Ve(e,n,"intent")||xr(e,n)}function yi(e,t){if(!e.isCallExpression(t))return!1;let[n,r,s]=t.arguments;return fi(e,n)||Ve(e,r,"source")||Ve(e,s,"source")}function hi(e,t){if(!e.isCallExpression(t))return;let[n,r,s]=t.arguments,i=De(e,n,"metadata");return He(e,De(e,i,"source"))??He(e,De(e,r,"source"))??He(e,De(e,s,"source"))}function Ai(e,t,n,r){let s=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),i=n,o=i?.filePath,a=i?.layer,d=[],u=m=>s.getLineAndCharacterOfPosition(m.getStart(s)).line+1,g=m=>{if(mi(e,m)){let c=m.arguments[0],l=He(e,c);for(let y of Fe({publishCall:!0,rawIntentName:l,objectHasIntent:Ve(e,c,"intent"),arkPublishCandidate:gi(e,m),hasSource:yi(e,m)}))d.push(w(y.ruleId,y.message,{line:u(m),filePath:o}));let p=hi(e,m);if(r&&a&&p&&me(p)){let y=r.resolveLayer(p);y&&y!==a&&d.push(w("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${p}" resolves to ${y}, but the target file is classified as ${a}.`,{line:u(m),filePath:o,target:p,fromLayer:a,toLayer:y}))}}e.forEachChild(m,g)};return g(s),d}function Sn(e={}){let t=new Set((e.intents||[]).map(i=>typeof i=="string"?i:i.name)),n=e.forbiddenPatterns||[],r=new Set(e.infrastructureLayers??[]),s=e.enforceIntentAllowlist??t.size>0;return{validate(i,o){let a=[],d=o,u=d?.filePath,g=d?.layer,m=e.typescript,c=m?m.createSourceFile(u??"generated.ts",i,m.ScriptTarget.Latest,!0):void 0,l=c?ue(e.typescript,c):void 0,p=l?l.filter(f=>f.specifier!==void 0).map(f=>({value:f.specifier,index:f.node.getStart(c),kind:f.kind,typeOnly:f.typeOnly})):ai(i),y=e.typescript?li(e.typescript,i):oi(i);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(u))for(let f of l?.filter(({unresolved:h})=>h)??[]){let h=f.kind==="require";a.push(w(h?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${h?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:f.line,filePath:u}))}let I=g!==void 0&&(r.has(g)||pi(g)),R=g!==void 0?` If "${g}" is an infrastructure layer, mark it in ark.config.json with "mayImportInfrastructure": true (or name it with an infra token like Adapters/Persistence/Repository).`:"";for(let f of n)if(f instanceof RegExp){f.lastIndex=0;let h=f.exec(i);f.lastIndex=0,h&&a.push(w("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${f}`,{line:h.index===void 0?void 0:Re(i,h.index),filePath:u,suggestion:"Remove infrastructure imports from domain/application layers."+R}))}else i.includes(f)&&a.push(w("FORBIDDEN_SUBSTRING",`Forbidden substring: ${f}`,{line:Re(i,i.indexOf(f)),filePath:u}));for(let f of p){let h=e.resolveImportTarget?.(f.value,u)??(e.resolveImportLayer?{layer:e.resolveImportLayer(f.value,u)}:void 0),S=typeof u=="string"?e.resolveImportTarget?.(u)??(e.resolveImportLayer?{layer:g,relPath:void 0}:void 0):void 0,k=h?.layer;if(k&&g){let N=ee(e.architectureProfile?.rules,g,k,{fromPath:S?.relPath,toPath:h?.relPath,layers:e.architectureLayers});if(N){if(f.typeOnly&&!N.peerIsolation)continue;let D=!!N.peerIsolation;a.push(w("LAYER_IMPORT_VIOLATION",N.message??(D?`Layer "${g}" must not import across slices into "${k}".`:`Layer "${g}" must not import "${k}".`),{line:Re(i,f.index),source:f.value,target:f.value,filePath:u,fromLayer:g,toLayer:k,suggestion:D?"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:f.kind,peerIsolation:D,...f.typeOnly?{typeOnly:!0}:{}}}));continue}continue}I||f.typeOnly||!ci(f.value)&&!di(f.value)||a.push(w("FORBIDDEN_IMPORT",`Forbidden ${f.kind} target: "${f.value}".`,{line:Re(i,f.index),source:f.value,target:f.value,filePath:u,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+R,details:{importKind:f.kind}}))}if(e.policies)for(let f of e.policies){let h=f.check({source:i,context:o});if(h!==!0)if(Array.isArray(h))for(let S of h)a.push(w("POLICY_VIOLATION",S.message,{filePath:u,suggestion:`Fix violation of policy "${f.name}".`}));else h===!1?a.push(w("POLICY_VIOLATION",`Policy ${f.name} failed on generated code`)):a.push(w("POLICY_VIOLATION",h.message))}if(s&&t.size>0)for(let f of y)me(f.value)&&!t.has(f.value)&&a.push(w("UNKNOWN_INTENT",`Unknown intent reference: "${f.value}"`,{line:Re(i,f.index),filePath:u,target:f.value,suggestion:`Register intent "${f.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&g)for(let f of y){if(!me(f.value))continue;let h=e.architectureProfile.resolveLayer(f.value);if(!h)continue;let S=ee(e.architectureProfile.rules,g,h);S&&a.push(w("LAYER_REFERENCE_VIOLATION",S.message??`Layer "${g}" must not reference "${h}" through "${f.value}".`,{line:Re(i,f.index),filePath:u,target:f.value,fromLayer:g,toLayer:h,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:S}}))}if(e.extensions)for(let f of e.extensions)try{let h=f.analyze(i,o);a.push(...h)}catch(h){a.push(w("EXTENSION_ERROR",`Extension "${f.name}" failed: ${h instanceof Error?h.message:String(h)}`))}if(e.typescript&&c&&g&&e.forbiddenGlobals?.[g]?.length)try{let f=e.forbiddenGlobals[g];a.push(...fe(e.typescript,c,f).map(h=>w("FORBIDDEN_GLOBAL",`${g} must not use the ambient global "${h.name}".`,{line:h.line,filePath:u,target:h.name,fromLayer:g,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let h of l??[]){if(h.typeOnly||!h.specifier)continue;let S=ie(h.specifier,f);S&&a.push(w("FORBIDDEN_GLOBAL",`${g} must not use module "${h.specifier}" because it is the import form of forbidden global "${S}".`,{line:h.line,filePath:u,source:h.specifier,target:h.specifier,fromLayer:g,details:{importKind:h.kind,forbiddenGlobal:S},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(f){a.push(w("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${f instanceof Error?f.message:String(f)}`))}if(e.typescript&&c&&g&&e.capabilityWalls?.[g]?.length)try{let f=new Set(e.capabilityWalls[g]),h=e.forbiddenGlobals?.[g]??[];for(let S of hn(e.typescript,c))f.has(S.capability)&&(S.source==="ambient-global"&&$e(S.symbol,h)||S.source==="import-based"&&ie(S.symbol,h)||a.push(w("CAPABILITY_VIOLATION",S.source==="import-based"?`${g} denies the ${S.capability} capability; found import of "${S.symbol}".`:`${g} denies the ${S.capability} capability; found ambient "${S.symbol}".`,{line:S.line,filePath:u,target:S.symbol,capability:S.capability,fromLayer:g,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(f){a.push(w("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${f instanceof Error?f.message:String(f)}`))}if(e.typescript)try{a.push(...Ai(e.typescript,i,o,e.architectureProfile))}catch(f){a.push(w("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${f instanceof Error?f.message:String(f)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:a.length===0,violations:a}}}}var Tr="1.1",It="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",Or=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Ii=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function bi(){let e=[];for(let t of Or)for(let n of Or)t===n||Ii.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var St=bi(),Rn=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"}],te={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},bt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:It,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:It,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:"1.1",default:"1.1"},name:{type:"string",minLength:1},include:{...te,minItems:1,default:["src"]},exclude:{...te,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:St,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...te,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},stewards:{...te,default:[]}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...te,minItems:1},exclude:te,intentPrefixes:te,description:{type:"string",minLength:1},forbiddenGlobals:te,capabilities:{type:"object",additionalProperties:!1,properties:{deny:{type:"array",uniqueItems:!0,items:{type:"string",enum:["network","filesystem","clock","randomness","environment","process","persistence"]}}}},pure:{type:"boolean"},mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...te,minItems:1}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}}}},ne=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
|
|
3
3
|
${n.map(r=>`- ${r.path}: ${r.message}`).join(`
|
|
4
|
-
`)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function Pr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function At(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function Ee(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Si(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function je(e,t,n,r,s){if(t.$ref){let i=Si(t.$ref,r);if(!i){s.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}je(e,i,n,r,s);return}if(t.const!==void 0&&!Object.is(e,t.const)){s.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(i=>Object.is(i,e))){s.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!Pr(e)){s.push({path:n,message:`must be an object; received ${Ee(e)}`});return}let i=t.properties??{};for(let a of t.required??[])e[a]===void 0&&s.push({path:At(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in i||s.push({path:At(n,a),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let a=t.additionalProperties;for(let o of Object.keys(e))o in i||je(e[o],a,At(n,o),r,s)}for(let[a,o]of Object.entries(i))e[a]!==void 0&&je(e[a],o,At(n,a),r,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:n,message:`must be an array; received ${Ee(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&s.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let i=e.map(a=>JSON.stringify(a));new Set(i).size!==i.length&&s.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((i,a)=>je(i,t.items,`${n}[${a}]`,r,s));return}if(t.type==="string"){if(typeof e!="string"){s.push({path:n,message:`must be a string; received ${Ee(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&s.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&s.push({path:n,message:`must be a boolean; received ${Ee(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){s.push({path:n,message:`must be an integer; received ${Ee(e)}`});return}t.minimum!==void 0&&e<t.minimum&&s.push({path:n,message:`must be at least ${t.minimum}`})}}function Ri(e){return{...e,$schema:e.$schema===void 0?It:e.$schema,schemaVersion:e.schemaVersion===void 0?"1.1":e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?St.map(t=>({...t})):e.rules}}function Ei(){let e=new Set(["1.1"]);for(let t of Rn)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}function vi(e,t="ark.config.json"){if(!Pr(e))throw new ne(t,[{path:"$",message:`must be an object; received ${Ee(e)}`}]);let n=Ei(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new ne(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.1`}]);if(r!=="unversioned"&&!n.has(r))throw new ne(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected 1.1`}]);let s=r,i={...e},a=0;for(;s!=="1.1"&&a<Rn.length+1;){a+=1;let d=Rn.find(u=>u.from===s);if(!d)throw new ne(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(s)}; expected 1.1`}]);s=d.to,i.schemaVersion=s}if(s!=="1.1")throw new ne(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected 1.1`}]);let o=r==="unversioned"?"unversioned":r==="1.0"?"1.0":null;return{candidate:Ri(i),migratedFrom:o}}function Ue(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=vi(e,t),s=[];if(je(n,bt,"$",bt,s),s.length>0)throw new ne(t,s);return{config:n,migratedFrom:r}}function Rt(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new ne(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return Ue(n,t)}function Lr(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:It,schemaVersion:"1.1"};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}function Ci(e){return e.endsWith(".")?e:`${e}.`}function ki(e,t){let n=e.prefixes.length?Math.max(...e.prefixes.map(s=>s.length)):0;return(t.prefixes.length?Math.max(...t.prefixes.map(s=>s.length)):0)-n}function Be(e){let t=e.layers.map(s=>({...s,prefixes:s.prefixes.map(Ci)})),n=[...t].sort(ki),r=[...e.rules??[]];return{name:e.name,layers:t,rules:r,resolveLayer(s){return t.find(i=>i.match?.(s))?.name??n.find(i=>i.prefixes.some(a=>s.startsWith(a)))?.name}}}function En(e,t={}){return Be({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,r)=>({name:n.name,prefixes:n.intentPrefixes??[],description:n.description,order:r+1})),rules:e.rules??[]})}var _i=[{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}],Ge=Be({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:_i,rules:St.map(e=>({...e}))}),xi={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 vn(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return Lr({include:e.include??[t],layers:Ge.layers.map(s=>({name:s.name,patterns:(xi[s.name]??[s.name]).map(i=>`${r}${i}/**`),intentPrefixes:s.prefixes,optional:n})),rules:[...Ge.rules]})}function M(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}function x(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(x).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${x(t[n])}`).join(",")}}`}var ae="1.1";var Nr=["network","filesystem","clock","randomness","environment","process","persistence"];function re(e,t){let n=x(e),r=x(t);return n<r?-1:n>r?1:0}function Z(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}function ke(e){let t={schemaVersion:"1.1",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(re),safety:{maxTsSuppressions:e.safety?.maxTsSuppressions??0,maxAnyCasts:e.safety?.maxAnyCasts??0,allowInMemory:e.safety?.allowInMemory===!0,allowDisabledPeerIsolation:e.safety?.allowDisabledPeerIsolation===!0}};return M(x(t))}function Oi(e){let t=e.completenessReasons.map(c=>({code:c.code,message:c.message,...c.file?{file:c.file}:{}})).sort(re),n=e.files.map(c=>({...c,typeOnlyExportNames:Z(c.typeOnlyExportNames)})).sort((c,l)=>c.path<l.path?-1:c.path>l.path?1:0),r=e.dependencies.map(c=>({...c,...c.namedBindings?{namedBindings:Z(c.namedBindings)}:{}})).sort(re),s=e.capabilityUses.map(c=>({...c})).sort(re),i=e.ambientUses.map(c=>({...c})).sort(re),a=e.publishCalls.map(c=>({...c})).sort(re),o=e.intentReferences.map(c=>({...c})).sort(re),d=e.safetyUses.map(c=>({...c})).sort(re),u=(e.classShapes??[]).map(c=>({...c,mutatingMethods:[...c.mutatingMethods??[]].map(l=>({...l}))})).sort(re),g=e.files.map(({path:c,contentHash:l})=>({path:c,contentHash:l})).sort((c,l)=>c.path<l.path?-1:c.path>l.path?1:0),m=M(x(g));return{schemaVersion:"1.1",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:m,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:r,capabilityUses:s,ambientUses:i,publishCalls:a,intentReferences:o,safetyUses:d,classShapes:u}}function Mr(e){let t=Oi(e);return{...t,factsHash:M(x(t))}}function Et(e){return Mr(Fr(K(e,"$"),!1))}function K(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}function Y(e,t,n){let r=new Set(t),s=Object.keys(e).find(i=>!r.has(i));if(s)throw new Error(`${n}.${s} is not part of schema ${"1.1"}.`)}function 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}function ve(e,t,n){if(e[t]!==void 0)return F(e,t,n)}function W(e,t,n){let r=F(e,t,n),s=r.replace(/\\/g,"/");if(!s||s.startsWith("/")||/^[A-Za-z]:\//.test(s)||/[\u0000-\u001f\u007f]/.test(s))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let i=[];for(let o of s.split("/"))if(!(!o||o==="."))if(o===".."){if(i.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);i.pop()}else i.push(o);let a=i.join("/");if(!a||a!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return a}function $(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}function $r(e,t,n){let r=e[t];if(!Number.isInteger(r)||Number(r)<0)throw new Error(`${n}.${t} must be a non-negative integer.`);return Number(r)}function Ce(e,t,n){let r=$r(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}function J(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}function oe(e,t,n,r){let s=e[t];if(typeof s!="string"||!n.includes(s))throw new Error(`${r}.${t} must be one of ${n.join(", ")}.`);return s}function wr(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!n))throw new Error(`${t} must be an array of non-empty strings.`);return[...e]}function Ti(e,t,n){let r=new Set;for(let s of e){let i=t(s);if(r.has(i))throw new Error(`${n} must not contain duplicate facts (${i}).`);r.add(i)}}function Fr(e,t){Y(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","classShapes",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=oe(e,"schemaVersion",["1.0","1.1"],"$"),r=oe(e,"completeness",["complete","partial","unavailable"],"$"),s=J(e,"completenessReasons","$").map((I,R)=>{let f=`$.completenessReasons[${R}]`,h=K(I,f);Y(h,["code","message","file"],f);let S=h.file===void 0?void 0:W(h,"file",f);return{code:F(h,"code",f),message:F(h,"message",f),...S?{file:S}:{}}});if(r==="complete"&&s.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(r!=="complete"&&s.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let i=J(e,"files","$").map((I,R)=>{let f=`$.files[${R}]`,h=K(I,f);return Y(h,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],f),{path:W(h,"path",f),contentHash:F(h,"contentHash",f),parseStatus:oe(h,"parseStatus",["parsed","invalid"],f),parseDiagnosticCount:$r(h,"parseDiagnosticCount",f),exportsOnlyTypes:$(h,"exportsOnlyTypes",f),typeOnlyExportNames:wr(h.typeOnlyExportNames,`${f}.typeOnlyExportNames`),hasTopLevelSideEffects:$(h,"hasTopLevelSideEffects",f)}}),a=J(e,"dependencies","$").map((I,R)=>{let f=`$.dependencies[${R}]`,h=K(I,f);Y(h,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],f);let S=ve(h,"specifier",f),k=ve(h,"target",f),N=oe(h,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],f);if(N==="resolved-project"&&!k)throw new Error(`${f}.target is required for resolved-project dependencies.`);if(N!=="resolved-project"&&k)throw new Error(`${f}.target is only allowed for resolved-project dependencies.`);if(N!=="dynamic"&&!S)throw new Error(`${f}.specifier is required unless resolution is dynamic.`);return{from:W(h,"from",f),...S?{specifier:S}:{},kind:oe(h,"kind",["import","export","dynamic-import","require"],f),typeOnly:$(h,"typeOnly",f),line:Ce(h,"line",f),resolution:N,...k?{target:W(h,"target",f)}:{},...h.namedBindings!==void 0?{namedBindings:wr(h.namedBindings,`${f}.namedBindings`)}:{},...h.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:$(h,"targetTypeOnlyExports",f)}:{},...h.sourcePureTypeModule!==void 0?{sourcePureTypeModule:$(h,"sourcePureTypeModule",f)}:{},...h.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:$(h,"namedBindingsTypeOnly",f)}:{},...h.portProofEligible!==void 0?{portProofEligible:$(h,"portProofEligible",f)}:{}}}),o=J(e,"capabilityUses","$").map((I,R)=>{let f=`$.capabilityUses[${R}]`,h=K(I,f);return Y(h,["file","line","symbol","capability","source"],f),{file:W(h,"file",f),line:Ce(h,"line",f),symbol:F(h,"symbol",f),capability:oe(h,"capability",Nr,f),source:oe(h,"source",["ambient-global","import-based"],f)}}),d=J(e,"ambientUses","$").map((I,R)=>{let f=`$.ambientUses[${R}]`,h=K(I,f);return Y(h,["file","line","symbol"],f),{file:W(h,"file",f),line:Ce(h,"line",f),symbol:F(h,"symbol",f)}}),u=J(e,"publishCalls","$").map((I,R)=>{let f=`$.publishCalls[${R}]`,h=K(I,f);Y(h,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],f);let S=ve(h,"rawIntentName",f),k=ve(h,"sourceIntent",f);return{file:W(h,"file",f),line:Ce(h,"line",f),...S?{rawIntentName:S}:{},objectHasIntent:$(h,"objectHasIntent",f),arkPublishCandidate:$(h,"arkPublishCandidate",f),hasSource:$(h,"hasSource",f),...k?{sourceIntent:k}:{}}}),g=J(e,"intentReferences","$").map((I,R)=>{let f=`$.intentReferences[${R}]`,h=K(I,f);return Y(h,["file","line","intent"],f),{file:W(h,"file",f),line:Ce(h,"line",f),intent:F(h,"intent",f)}}),m=J(e,"safetyUses","$").map((I,R)=>{let f=`$.safetyUses[${R}]`,h=K(I,f);Y(h,["file","line","kind","symbol"],f);let S=ve(h,"symbol",f),k=oe(h,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],f);if(k==="in-memory-store"&&!S)throw new Error(`${f}.symbol is required for in-memory-store facts.`);if(k!=="in-memory-store"&&S)throw new Error(`${f}.symbol is only allowed for in-memory-store facts.`);return{file:W(h,"file",f),line:Ce(h,"line",f),kind:k,...S?{symbol:S}:{}}});Ti(i,I=>I.path,"$.files");let c=new Set(i.map(I=>I.path));for(let I of i){if(I.parseStatus==="parsed"&&I.parseDiagnosticCount!==0)throw new Error(`$.files[${I.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(I.parseStatus==="invalid"&&I.parseDiagnosticCount===0)throw new Error(`$.files[${I.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&i.some(I=>I.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let I of a)if(!c.has(I.from))throw new Error(`$.dependencies references missing source file ${I.from}.`);for(let[I,R]of[["$.capabilityUses",o],["$.ambientUses",d],["$.publishCalls",u],["$.intentReferences",g],["$.safetyUses",m]])for(let f of R)if(!c.has(f.file))throw new Error(`${I} references missing file ${f.file}.`);let l=ve(e,"projectPackageName","$"),y=(e.classShapes===void 0?[]:J(e,"classShapes","$")).map((I,R)=>{let f=`$.classShapes[${R}]`,h=K(I,f);Y(h,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],f);let S=J(h,"mutatingMethods",f).map((k,N)=>{let D=`${f}.mutatingMethods[${N}]`,_=K(k,D);return Y(_,["name","referencesGuardOrPublish"],D),{name:F(_,"name",D),referencesGuardOrPublish:$(_,"referencesGuardOrPublish",D)}});return{file:W(h,"file",f),className:F(h,"className",f),exported:$(h,"exported",f),hasPublicMutableFields:$(h,"hasPublicMutableFields",f),hasPublicSetters:$(h,"hasPublicSetters",f),hasPublicConstructor:$(h,"hasPublicConstructor",f),hasStaticFactory:$(h,"hasStaticFactory",f),mutatingMethods:S,...h.dataOnly===void 0?{}:{dataOnly:$(h,"dataOnly",f)}}});return{schemaVersion:n,completeness:r,completenessReasons:s,resolverIdentity:F(e,"resolverIdentity","$"),compilerIdentity:F(e,"compilerIdentity","$"),compilerOptionsHash:F(e,"compilerOptionsHash","$"),tsconfigHash:F(e,"tsconfigHash","$"),evidenceRequirementsHash:F(e,"evidenceRequirementsHash","$"),...l?{projectPackageName:l}:{},files:i,dependencies:a,capabilityUses:o,ambientUses:d,publishCalls:u,intentReferences:g,safetyUses:m,classShapes:y}}function se(e){let t=K(e,"$"),n=F(t,"factsHash","$"),r=F(t,"candidateTreeHash","$"),s=Mr(Fr(t,!0));if(s.factsHash!==n)throw new Error(`$.factsHash does not match the canonical payload (${s.factsHash}).`);if(r!==s.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${s.candidateTreeHash}).`);return s}var Pi=["network","filesystem","clock","randomness","environment","process","persistence"],O={type:"string",minLength:1},_e={type:"integer",minimum:1},X={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},vt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.resolved-candidate-facts.schema.json",title:"ArkGate resolved candidate facts",type:"object",additionalProperties:!1,required:["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","candidateTreeHash","evidenceRequirementsHash","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","factsHash"],properties:{schemaVersion:{enum:["1.0","1.1"]},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:O,message:O,file:X}}},resolverIdentity:O,compilerIdentity:O,compilerOptionsHash:O,tsconfigHash:O,candidateTreeHash:O,evidenceRequirementsHash:O,projectPackageName:O,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:X,contentHash:O,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:O},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:X,specifier:O,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:_e,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:X,namedBindings:{type:"array",items:O},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:X,line:_e,symbol:O,capability:{enum:Pi},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:X,line:_e,symbol:O}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:X,line:_e,rawIntentName:O,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:O}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:X,line:_e,intent:O}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:X,line:_e,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:O},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:X,className:O,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:O,referencesGuardOrPublish:{type:"boolean"}}}}}}},factsHash:O},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 Ct="1.0";function U(e){return`${e.from}->${e.to}`}function Ke(e,t,n,r="dependency"){return{id:`${e}:${r}:${U(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${U(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${U(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${U(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${U(t)} from the candidate, then preflight again.`}:{}}}function ge(e){let t=[],n=new Map(e.changeMap.map.files.map(c=>[c.path,c])),r=new Map(e.changes.map(c=>[c.path,c])),s=new Map(e.changeMap.map.dependencies.map(c=>[U(c),c])),i=new Map(e.baseDependencies.map(c=>[U(c),c])),a=new Map(e.candidateDependencies.map(c=>[U(c),c]));for(let c of[...n.values()].sort((l,p)=>l.path.localeCompare(p.path))){let l=r.get(c.path);l?l.operation!==c.operation?t.push({id:`contradictory:file:${c.path}`,classification:"contradictory",subject:"file",path:c.path,expectedOperation:c.operation,actualOperation:l.operation,message:`${c.path} was planned as ${c.operation} but the actual operation is ${l.operation}.`,nextAction:`Change ${c.path} to the planned ${c.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${c.path}`,classification:"satisfied",subject:"file",path:c.path,expectedOperation:c.operation,actualOperation:l.operation,message:`${c.path} matches the planned ${c.operation} operation.`}):t.push({id:`missing:file:${c.path}`,classification:"missing",subject:"file",path:c.path,expectedOperation:c.operation,message:`${c.path} was planned as ${c.operation} but is absent from the actual change.`,nextAction:`${c.operation[0].toUpperCase()}${c.operation.slice(1)} ${c.path} in the complete change set, then preflight again.`})}for(let c of[...r.values()].sort((l,p)=>l.path.localeCompare(p.path)))n.has(c.path)||t.push({id:`unplanned:file:${c.path}`,classification:"unplanned",subject:"file",path:c.path,actualOperation:c.operation,message:`${c.path} has an unplanned ${c.operation} operation.`,nextAction:`Remove ${c.path} from the change set, then preflight again.`});let o=new Set;for(let c of[...s.values()].sort((l,p)=>U(l).localeCompare(U(p)))){if(a.has(U(c))){t.push(Ke("satisfied",c,`${c.from} -> ${c.to} exists in the candidate architecture.`));continue}let l={from:c.to,to:c.from};a.has(U(l))?(o.add(U(l)),t.push(Ke("contradictory",c,`${c.from} -> ${c.to} was planned, but the candidate contains the reverse edge.`))):t.push(Ke("missing",c,`${c.from} -> ${c.to} is absent from the candidate architecture.`))}let d=new Set([...n.keys(),...r.keys()]);for(let[c,l]of[...a].sort(([p],[y])=>p.localeCompare(y)))i.has(c)||s.has(c)||o.has(c)||!d.has(l.from)&&!d.has(l.to)||t.push({...Ke("unplanned",l,`${l.from} -> ${l.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let u=new Set(e.changeMap.map.files.filter(c=>c.operation==="delete").map(c=>c.path));for(let[c,l]of[...i].sort(([p],[y])=>p.localeCompare(y)))a.has(c)||u.has(l.from)||u.has(l.to)||!d.has(l.from)&&!d.has(l.to)||t.push({...Ke("unplanned",l,`${l.from} -> ${l.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let g={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((c,l)=>g[c.classification]-g[l.classification]||(c.subject===l.subject?0:c.subject==="file"?-1:1)||c.id.localeCompare(l.id));let m={satisfied:t.filter(c=>c.classification==="satisfied").length,missing:t.filter(c=>c.classification==="missing").length,contradictory:t.filter(c=>c.classification==="contradictory").length,unplanned:t.filter(c=>c.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:m.missing===0&&m.contradictory===0&&m.unplanned===0,behavioralCompletion:"not-evaluated",summary:m,findings:t}}var Vr="1.0",Cn="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",kn=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","no-anemic-model","invariant-coverage"],Li=["no-anemic-model"],Dr={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},_t={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Cn,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:Cn},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:[...kn]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:Dr,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:Dr}}}},ye=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkRules (${t}):
|
|
4
|
+
`)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function Pr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function At(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function Ee(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Si(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function je(e,t,n,r,s){if(t.$ref){let i=Si(t.$ref,r);if(!i){s.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}je(e,i,n,r,s);return}if(t.const!==void 0&&!Object.is(e,t.const)){s.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(i=>Object.is(i,e))){s.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!Pr(e)){s.push({path:n,message:`must be an object; received ${Ee(e)}`});return}let i=t.properties??{};for(let o of t.required??[])e[o]===void 0&&s.push({path:At(n,o),message:"is required"});if(t.additionalProperties===!1)for(let o of Object.keys(e))o in i||s.push({path:At(n,o),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let o=t.additionalProperties;for(let a of Object.keys(e))a in i||je(e[a],o,At(n,a),r,s)}for(let[o,a]of Object.entries(i))e[o]!==void 0&&je(e[o],a,At(n,o),r,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:n,message:`must be an array; received ${Ee(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&s.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let i=e.map(o=>JSON.stringify(o));new Set(i).size!==i.length&&s.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((i,o)=>je(i,t.items,`${n}[${o}]`,r,s));return}if(t.type==="string"){if(typeof e!="string"){s.push({path:n,message:`must be a string; received ${Ee(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&s.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&s.push({path:n,message:`must be a boolean; received ${Ee(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){s.push({path:n,message:`must be an integer; received ${Ee(e)}`});return}t.minimum!==void 0&&e<t.minimum&&s.push({path:n,message:`must be at least ${t.minimum}`})}}function Ri(e){return{...e,$schema:e.$schema===void 0?It:e.$schema,schemaVersion:e.schemaVersion===void 0?"1.1":e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?St.map(t=>({...t})):e.rules}}function Ei(){let e=new Set(["1.1"]);for(let t of Rn)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}function vi(e,t="ark.config.json"){if(!Pr(e))throw new ne(t,[{path:"$",message:`must be an object; received ${Ee(e)}`}]);let n=Ei(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new ne(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.1`}]);if(r!=="unversioned"&&!n.has(r))throw new ne(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected 1.1`}]);let s=r,i={...e},o=0;for(;s!=="1.1"&&o<Rn.length+1;){o+=1;let d=Rn.find(u=>u.from===s);if(!d)throw new ne(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(s)}; expected 1.1`}]);s=d.to,i.schemaVersion=s}if(s!=="1.1")throw new ne(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected 1.1`}]);let a=r==="unversioned"?"unversioned":r==="1.0"?"1.0":null;return{candidate:Ri(i),migratedFrom:a}}function Ue(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=vi(e,t),s=[];if(je(n,bt,"$",bt,s),s.length>0)throw new ne(t,s);return{config:n,migratedFrom:r}}function Rt(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new ne(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return Ue(n,t)}function Lr(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:It,schemaVersion:"1.1"};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}function Ci(e){return e.endsWith(".")?e:`${e}.`}function ki(e,t){let n=e.prefixes.length?Math.max(...e.prefixes.map(s=>s.length)):0;return(t.prefixes.length?Math.max(...t.prefixes.map(s=>s.length)):0)-n}function Be(e){let t=e.layers.map(s=>({...s,prefixes:s.prefixes.map(Ci)})),n=[...t].sort(ki),r=[...e.rules??[]];return{name:e.name,layers:t,rules:r,resolveLayer(s){return t.find(i=>i.match?.(s))?.name??n.find(i=>i.prefixes.some(o=>s.startsWith(o)))?.name}}}function En(e,t={}){return Be({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,r)=>({name:n.name,prefixes:n.intentPrefixes??[],description:n.description,order:r+1})),rules:e.rules??[]})}var _i=[{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}],Ge=Be({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:_i,rules:St.map(e=>({...e}))}),xi={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 vn(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return Lr({include:e.include??[t],layers:Ge.layers.map(s=>({name:s.name,patterns:(xi[s.name]??[s.name]).map(i=>`${r}${i}/**`),intentPrefixes:s.prefixes,optional:n})),rules:[...Ge.rules]})}function M(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}function x(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(x).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${x(t[n])}`).join(",")}}`}var oe="1.1";var Nr=["network","filesystem","clock","randomness","environment","process","persistence"];function re(e,t){let n=x(e),r=x(t);return n<r?-1:n>r?1:0}function Z(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}function ke(e){let t={schemaVersion:"1.1",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(re),safety:{maxTsSuppressions:e.safety?.maxTsSuppressions??0,maxAnyCasts:e.safety?.maxAnyCasts??0,allowInMemory:e.safety?.allowInMemory===!0,allowDisabledPeerIsolation:e.safety?.allowDisabledPeerIsolation===!0}};return M(x(t))}function Oi(e){let t=e.completenessReasons.map(c=>({code:c.code,message:c.message,...c.file?{file:c.file}:{}})).sort(re),n=e.files.map(c=>({...c,typeOnlyExportNames:Z(c.typeOnlyExportNames)})).sort((c,l)=>c.path<l.path?-1:c.path>l.path?1:0),r=e.dependencies.map(c=>({...c,...c.namedBindings?{namedBindings:Z(c.namedBindings)}:{}})).sort(re),s=e.capabilityUses.map(c=>({...c})).sort(re),i=e.ambientUses.map(c=>({...c})).sort(re),o=e.publishCalls.map(c=>({...c})).sort(re),a=e.intentReferences.map(c=>({...c})).sort(re),d=e.safetyUses.map(c=>({...c})).sort(re),u=(e.classShapes??[]).map(c=>({...c,mutatingMethods:[...c.mutatingMethods??[]].map(l=>({...l}))})).sort(re),g=e.files.map(({path:c,contentHash:l})=>({path:c,contentHash:l})).sort((c,l)=>c.path<l.path?-1:c.path>l.path?1:0),m=M(x(g));return{schemaVersion:"1.1",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:m,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:r,capabilityUses:s,ambientUses:i,publishCalls:o,intentReferences:a,safetyUses:d,classShapes:u}}function Mr(e){let t=Oi(e);return{...t,factsHash:M(x(t))}}function Et(e){return Mr(Fr(K(e,"$"),!1))}function K(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}function Y(e,t,n){let r=new Set(t),s=Object.keys(e).find(i=>!r.has(i));if(s)throw new Error(`${n}.${s} is not part of schema ${"1.1"}.`)}function 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}function ve(e,t,n){if(e[t]!==void 0)return F(e,t,n)}function W(e,t,n){let r=F(e,t,n),s=r.replace(/\\/g,"/");if(!s||s.startsWith("/")||/^[A-Za-z]:\//.test(s)||/[\u0000-\u001f\u007f]/.test(s))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let i=[];for(let a of s.split("/"))if(!(!a||a==="."))if(a===".."){if(i.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);i.pop()}else i.push(a);let o=i.join("/");if(!o||o!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return o}function $(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}function $r(e,t,n){let r=e[t];if(!Number.isInteger(r)||Number(r)<0)throw new Error(`${n}.${t} must be a non-negative integer.`);return Number(r)}function Ce(e,t,n){let r=$r(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}function J(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}function ae(e,t,n,r){let s=e[t];if(typeof s!="string"||!n.includes(s))throw new Error(`${r}.${t} must be one of ${n.join(", ")}.`);return s}function wr(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!n))throw new Error(`${t} must be an array of non-empty strings.`);return[...e]}function Ti(e,t,n){let r=new Set;for(let s of e){let i=t(s);if(r.has(i))throw new Error(`${n} must not contain duplicate facts (${i}).`);r.add(i)}}function Fr(e,t){Y(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","classShapes",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=ae(e,"schemaVersion",["1.0","1.1"],"$"),r=ae(e,"completeness",["complete","partial","unavailable"],"$"),s=J(e,"completenessReasons","$").map((I,R)=>{let f=`$.completenessReasons[${R}]`,h=K(I,f);Y(h,["code","message","file"],f);let S=h.file===void 0?void 0:W(h,"file",f);return{code:F(h,"code",f),message:F(h,"message",f),...S?{file:S}:{}}});if(r==="complete"&&s.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(r!=="complete"&&s.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let i=J(e,"files","$").map((I,R)=>{let f=`$.files[${R}]`,h=K(I,f);return Y(h,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],f),{path:W(h,"path",f),contentHash:F(h,"contentHash",f),parseStatus:ae(h,"parseStatus",["parsed","invalid"],f),parseDiagnosticCount:$r(h,"parseDiagnosticCount",f),exportsOnlyTypes:$(h,"exportsOnlyTypes",f),typeOnlyExportNames:wr(h.typeOnlyExportNames,`${f}.typeOnlyExportNames`),hasTopLevelSideEffects:$(h,"hasTopLevelSideEffects",f)}}),o=J(e,"dependencies","$").map((I,R)=>{let f=`$.dependencies[${R}]`,h=K(I,f);Y(h,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],f);let S=ve(h,"specifier",f),k=ve(h,"target",f),N=ae(h,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],f);if(N==="resolved-project"&&!k)throw new Error(`${f}.target is required for resolved-project dependencies.`);if(N!=="resolved-project"&&k)throw new Error(`${f}.target is only allowed for resolved-project dependencies.`);if(N!=="dynamic"&&!S)throw new Error(`${f}.specifier is required unless resolution is dynamic.`);return{from:W(h,"from",f),...S?{specifier:S}:{},kind:ae(h,"kind",["import","export","dynamic-import","require"],f),typeOnly:$(h,"typeOnly",f),line:Ce(h,"line",f),resolution:N,...k?{target:W(h,"target",f)}:{},...h.namedBindings!==void 0?{namedBindings:wr(h.namedBindings,`${f}.namedBindings`)}:{},...h.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:$(h,"targetTypeOnlyExports",f)}:{},...h.sourcePureTypeModule!==void 0?{sourcePureTypeModule:$(h,"sourcePureTypeModule",f)}:{},...h.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:$(h,"namedBindingsTypeOnly",f)}:{},...h.portProofEligible!==void 0?{portProofEligible:$(h,"portProofEligible",f)}:{}}}),a=J(e,"capabilityUses","$").map((I,R)=>{let f=`$.capabilityUses[${R}]`,h=K(I,f);return Y(h,["file","line","symbol","capability","source"],f),{file:W(h,"file",f),line:Ce(h,"line",f),symbol:F(h,"symbol",f),capability:ae(h,"capability",Nr,f),source:ae(h,"source",["ambient-global","import-based"],f)}}),d=J(e,"ambientUses","$").map((I,R)=>{let f=`$.ambientUses[${R}]`,h=K(I,f);return Y(h,["file","line","symbol"],f),{file:W(h,"file",f),line:Ce(h,"line",f),symbol:F(h,"symbol",f)}}),u=J(e,"publishCalls","$").map((I,R)=>{let f=`$.publishCalls[${R}]`,h=K(I,f);Y(h,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],f);let S=ve(h,"rawIntentName",f),k=ve(h,"sourceIntent",f);return{file:W(h,"file",f),line:Ce(h,"line",f),...S?{rawIntentName:S}:{},objectHasIntent:$(h,"objectHasIntent",f),arkPublishCandidate:$(h,"arkPublishCandidate",f),hasSource:$(h,"hasSource",f),...k?{sourceIntent:k}:{}}}),g=J(e,"intentReferences","$").map((I,R)=>{let f=`$.intentReferences[${R}]`,h=K(I,f);return Y(h,["file","line","intent"],f),{file:W(h,"file",f),line:Ce(h,"line",f),intent:F(h,"intent",f)}}),m=J(e,"safetyUses","$").map((I,R)=>{let f=`$.safetyUses[${R}]`,h=K(I,f);Y(h,["file","line","kind","symbol"],f);let S=ve(h,"symbol",f),k=ae(h,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],f);if(k==="in-memory-store"&&!S)throw new Error(`${f}.symbol is required for in-memory-store facts.`);if(k!=="in-memory-store"&&S)throw new Error(`${f}.symbol is only allowed for in-memory-store facts.`);return{file:W(h,"file",f),line:Ce(h,"line",f),kind:k,...S?{symbol:S}:{}}});Ti(i,I=>I.path,"$.files");let c=new Set(i.map(I=>I.path));for(let I of i){if(I.parseStatus==="parsed"&&I.parseDiagnosticCount!==0)throw new Error(`$.files[${I.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(I.parseStatus==="invalid"&&I.parseDiagnosticCount===0)throw new Error(`$.files[${I.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&i.some(I=>I.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let I of o)if(!c.has(I.from))throw new Error(`$.dependencies references missing source file ${I.from}.`);for(let[I,R]of[["$.capabilityUses",a],["$.ambientUses",d],["$.publishCalls",u],["$.intentReferences",g],["$.safetyUses",m]])for(let f of R)if(!c.has(f.file))throw new Error(`${I} references missing file ${f.file}.`);let l=ve(e,"projectPackageName","$"),y=(e.classShapes===void 0?[]:J(e,"classShapes","$")).map((I,R)=>{let f=`$.classShapes[${R}]`,h=K(I,f);Y(h,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],f);let S=J(h,"mutatingMethods",f).map((k,N)=>{let D=`${f}.mutatingMethods[${N}]`,_=K(k,D);return Y(_,["name","referencesGuardOrPublish"],D),{name:F(_,"name",D),referencesGuardOrPublish:$(_,"referencesGuardOrPublish",D)}});return{file:W(h,"file",f),className:F(h,"className",f),exported:$(h,"exported",f),hasPublicMutableFields:$(h,"hasPublicMutableFields",f),hasPublicSetters:$(h,"hasPublicSetters",f),hasPublicConstructor:$(h,"hasPublicConstructor",f),hasStaticFactory:$(h,"hasStaticFactory",f),mutatingMethods:S,...h.dataOnly===void 0?{}:{dataOnly:$(h,"dataOnly",f)}}});return{schemaVersion:n,completeness:r,completenessReasons:s,resolverIdentity:F(e,"resolverIdentity","$"),compilerIdentity:F(e,"compilerIdentity","$"),compilerOptionsHash:F(e,"compilerOptionsHash","$"),tsconfigHash:F(e,"tsconfigHash","$"),evidenceRequirementsHash:F(e,"evidenceRequirementsHash","$"),...l?{projectPackageName:l}:{},files:i,dependencies:o,capabilityUses:a,ambientUses:d,publishCalls:u,intentReferences:g,safetyUses:m,classShapes:y}}function se(e){let t=K(e,"$"),n=F(t,"factsHash","$"),r=F(t,"candidateTreeHash","$"),s=Mr(Fr(t,!0));if(s.factsHash!==n)throw new Error(`$.factsHash does not match the canonical payload (${s.factsHash}).`);if(r!==s.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${s.candidateTreeHash}).`);return s}var Pi=["network","filesystem","clock","randomness","environment","process","persistence"],O={type:"string",minLength:1},_e={type:"integer",minimum:1},X={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},vt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.resolved-candidate-facts.schema.json",title:"ArkGate resolved candidate facts",type:"object",additionalProperties:!1,required:["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","candidateTreeHash","evidenceRequirementsHash","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","factsHash"],properties:{schemaVersion:{enum:["1.0","1.1"]},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:O,message:O,file:X}}},resolverIdentity:O,compilerIdentity:O,compilerOptionsHash:O,tsconfigHash:O,candidateTreeHash:O,evidenceRequirementsHash:O,projectPackageName:O,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:X,contentHash:O,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:O},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:X,specifier:O,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:_e,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:X,namedBindings:{type:"array",items:O},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:X,line:_e,symbol:O,capability:{enum:Pi},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:X,line:_e,symbol:O}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:X,line:_e,rawIntentName:O,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:O}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:X,line:_e,intent:O}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:X,line:_e,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:O},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:X,className:O,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:O,referencesGuardOrPublish:{type:"boolean"}}}}}}},factsHash:O},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 Ct="1.0";function U(e){return`${e.from}->${e.to}`}function Ke(e,t,n,r="dependency"){return{id:`${e}:${r}:${U(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${U(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${U(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${U(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${U(t)} from the candidate, then preflight again.`}:{}}}function ge(e){let t=[],n=new Map(e.changeMap.map.files.map(c=>[c.path,c])),r=new Map(e.changes.map(c=>[c.path,c])),s=new Map(e.changeMap.map.dependencies.map(c=>[U(c),c])),i=new Map(e.baseDependencies.map(c=>[U(c),c])),o=new Map(e.candidateDependencies.map(c=>[U(c),c]));for(let c of[...n.values()].sort((l,p)=>l.path.localeCompare(p.path))){let l=r.get(c.path);l?l.operation!==c.operation?t.push({id:`contradictory:file:${c.path}`,classification:"contradictory",subject:"file",path:c.path,expectedOperation:c.operation,actualOperation:l.operation,message:`${c.path} was planned as ${c.operation} but the actual operation is ${l.operation}.`,nextAction:`Change ${c.path} to the planned ${c.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${c.path}`,classification:"satisfied",subject:"file",path:c.path,expectedOperation:c.operation,actualOperation:l.operation,message:`${c.path} matches the planned ${c.operation} operation.`}):t.push({id:`missing:file:${c.path}`,classification:"missing",subject:"file",path:c.path,expectedOperation:c.operation,message:`${c.path} was planned as ${c.operation} but is absent from the actual change.`,nextAction:`${c.operation[0].toUpperCase()}${c.operation.slice(1)} ${c.path} in the complete change set, then preflight again.`})}for(let c of[...r.values()].sort((l,p)=>l.path.localeCompare(p.path)))n.has(c.path)||t.push({id:`unplanned:file:${c.path}`,classification:"unplanned",subject:"file",path:c.path,actualOperation:c.operation,message:`${c.path} has an unplanned ${c.operation} operation.`,nextAction:`Remove ${c.path} from the change set, then preflight again.`});let a=new Set;for(let c of[...s.values()].sort((l,p)=>U(l).localeCompare(U(p)))){if(o.has(U(c))){t.push(Ke("satisfied",c,`${c.from} -> ${c.to} exists in the candidate architecture.`));continue}let l={from:c.to,to:c.from};o.has(U(l))?(a.add(U(l)),t.push(Ke("contradictory",c,`${c.from} -> ${c.to} was planned, but the candidate contains the reverse edge.`))):t.push(Ke("missing",c,`${c.from} -> ${c.to} is absent from the candidate architecture.`))}let d=new Set([...n.keys(),...r.keys()]);for(let[c,l]of[...o].sort(([p],[y])=>p.localeCompare(y)))i.has(c)||s.has(c)||a.has(c)||!d.has(l.from)&&!d.has(l.to)||t.push({...Ke("unplanned",l,`${l.from} -> ${l.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let u=new Set(e.changeMap.map.files.filter(c=>c.operation==="delete").map(c=>c.path));for(let[c,l]of[...i].sort(([p],[y])=>p.localeCompare(y)))o.has(c)||u.has(l.from)||u.has(l.to)||!d.has(l.from)&&!d.has(l.to)||t.push({...Ke("unplanned",l,`${l.from} -> ${l.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let g={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((c,l)=>g[c.classification]-g[l.classification]||(c.subject===l.subject?0:c.subject==="file"?-1:1)||c.id.localeCompare(l.id));let m={satisfied:t.filter(c=>c.classification==="satisfied").length,missing:t.filter(c=>c.classification==="missing").length,contradictory:t.filter(c=>c.classification==="contradictory").length,unplanned:t.filter(c=>c.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:m.missing===0&&m.contradictory===0&&m.unplanned===0,behavioralCompletion:"not-evaluated",summary:m,findings:t}}var Vr="1.0",Cn="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",kn=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","no-anemic-model","invariant-coverage"],Li=["no-anemic-model"],Dr={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},_t={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Cn,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:Cn},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:[...kn]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:Dr,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:Dr}}}},ye=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkRules (${t}):
|
|
5
5
|
${n.map(r=>`- ${r.path}: ${r.message}`).join(`
|
|
6
|
-
`)}`),this.name="ArkRulesValidationError",this.source=t,this.issues=n}};function Ye(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function kt(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function ze(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Ni(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function qe(e,t,n,r,s){if(t.$ref){let i=Ni(t.$ref,r);if(!i){s.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}qe(e,i,n,r,s);return}if(t.const!==void 0&&!Object.is(e,t.const)){s.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(i=>Object.is(i,e))){s.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!Ye(e)){s.push({path:n,message:`must be an object; received ${ze(e)}`});return}let i=t.properties??{};for(let
|
|
6
|
+
`)}`),this.name="ArkRulesValidationError",this.source=t,this.issues=n}};function Ye(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function kt(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function ze(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Ni(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function qe(e,t,n,r,s){if(t.$ref){let i=Ni(t.$ref,r);if(!i){s.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}qe(e,i,n,r,s);return}if(t.const!==void 0&&!Object.is(e,t.const)){s.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(i=>Object.is(i,e))){s.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!Ye(e)){s.push({path:n,message:`must be an object; received ${ze(e)}`});return}let i=t.properties??{};for(let o of t.required??[])e[o]===void 0&&s.push({path:kt(n,o),message:"is required"});if(t.additionalProperties===!1)for(let o of Object.keys(e))o in i||s.push({path:kt(n,o),message:"unknown field"});else if(Ye(t.additionalProperties)){let o=t.additionalProperties;for(let a of Object.keys(e))a in i||qe(e[a],o,kt(n,a),r,s)}for(let[o,a]of Object.entries(i))e[o]!==void 0&&qe(e[o],a,kt(n,o),r,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:n,message:`must be an array; received ${ze(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&s.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let i=e.map(o=>JSON.stringify(o));new Set(i).size!==i.length&&s.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((i,o)=>qe(i,t.items,`${n}[${o}]`,r,s));return}if(t.type==="string"){if(typeof e!="string"){s.push({path:n,message:`must be a string; received ${ze(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&s.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}t.type==="boolean"&&typeof e!="boolean"&&s.push({path:n,message:`must be a boolean; received ${ze(e)}`})}function wi(e){return{...e,$schema:e.$schema===void 0?Cn:e.$schema,schemaVersion:e.schemaVersion===void 0?"1.0":e.schemaVersion,structure:e.structure===void 0?[]:e.structure,invariants:e.invariants===void 0?[]:e.invariants}}function Hr(e){return e==="enforced"?"enforced":"advisory"}function Mi(e){return Li.includes(e)}function $i(e,t){let n=Array.isArray(e.structure)?e.structure:[],r=Array.isArray(e.invariants)?e.invariants:[],s=new Set;n.forEach((i,o)=>{if(!Ye(i))return;let a=typeof i.id=="string"?i.id:"";a&&(s.has(a)&&t.push({path:`$.structure[${o}].id`,message:`duplicate rule id ${JSON.stringify(a)}`}),s.add(a)),typeof i.sensor=="string"&&Mi(i.sensor)&&i.mode==="enforced"&&t.push({path:`$.structure[${o}].mode`,message:`sensor ${JSON.stringify(i.sensor)} is Tier-2 advisory-only and cannot be enforced`}),Array.isArray(i.appliesTo)&&i.appliesTo.length===0&&t.push({path:`$.structure[${o}].appliesTo`,message:"must not be an empty array (omit the field to apply to the whole layer)"})}),r.forEach((i,o)=>{if(!Ye(i))return;let a=typeof i.id=="string"?i.id:"";a&&(s.has(a)&&t.push({path:`$.invariants[${o}].id`,message:`duplicate rule id ${JSON.stringify(a)}`}),s.add(a)),Array.isArray(i.appliesTo)&&i.appliesTo.length===0&&t.push({path:`$.invariants[${o}].appliesTo`,message:"must not be an empty array (omit the field to apply to the whole layer)"})})}function We(e,t="arkrules.json",n){if(!Ye(e))throw new ye(t,[{path:"$",message:`must be an object; received ${ze(e)}`}]);let r=wi(e),s=[];if(qe(r,_t,"$",_t,s),$i(r,s),n!==void 0&&typeof r.layer=="string"&&r.layer!==n&&s.push({path:"$.layer",message:`must match referencing key ${JSON.stringify(n)}; received ${JSON.stringify(r.layer)}`}),s.length>0)throw new ye(t,s);return{config:r}}function jr(e,t="arkrules.json",n){let r;try{r=JSON.parse(e)}catch(s){throw new ye(t,[{path:"$",message:`invalid JSON: ${s instanceof Error?s.message:String(s)}`}])}return We(r,t,n)}function xt(e){let t={},n=[],r=[],s=[...e].sort((i,o)=>i.layer.localeCompare(o.layer));for(let i of s){let o=(i.file.structure??[]).map(d=>({...d,mode:Hr(d.mode),provenance:{sourceFile:i.sourceFile,ruleId:d.id,layer:i.layer}})),a=(i.file.invariants??[]).map(d=>({...d,mode:Hr(d.mode),provenance:{sourceFile:i.sourceFile,ruleId:d.id,layer:i.layer}}));t[i.layer]={sourceFile:i.sourceFile,structure:o,invariants:a},n.push(...o),r.push(...a)}return n.sort((i,o)=>{let a=i.provenance.layer.localeCompare(o.provenance.layer);return a!==0?a:i.id.localeCompare(o.id)}),r.sort((i,o)=>{let a=i.provenance.layer.localeCompare(o.provenance.layer);return a!==0?a:i.id.localeCompare(o.id)}),{schemaVersion:"1.0",byLayer:t,structure:n,invariants:r}}function le(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}var Je=class extends Error{issues;source;constructor(t,n){super(`Invalid Effective Contract (${t}):
|
|
7
7
|
${n.map(r=>`- ${r.path}: ${r.message}`).join(`
|
|
8
|
-
`)}`),this.name="EffectiveContractError",this.source=t,this.issues=n}};function Ur(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function Gr(e,t="ark.config.json"){let n=e.config.arkRules,r=[];if(!n||Object.keys(n).length===0){if(e.discoveredArkRulesFiles&&e.discoveredArkRulesFiles.length>0)for(let d of[...e.discoveredArkRulesFiles].sort())r.push({path:d,message:`ArkRules file ${JSON.stringify(d)} is not referenced by arkRules and will not be enforced`,severity:"advisory"});return{config:e.config,arkRules:le(),warnings:r}}let s=new Set(e.config.layers.map(d=>d.name)),i=[],a=[],o=new Set;for(let d of Object.keys(n).sort()){let u=n[d],g=`$.arkRules[${JSON.stringify(d)}]`;if(typeof u!="string"||u.length===0){i.push({path:g,message:"must be a non-empty relative path string"});continue}if(u.startsWith("/")||/^[A-Za-z]:[\\/]/.test(u)){i.push({path:g,message:"must be a project-relative path (absolute paths are not allowed)"});continue}if(!s.has(d)){i.push({path:g,message:`layer ${JSON.stringify(d)} is not declared in layers[]`});continue}let m=Ur(u);o.add(m);let c=e.fileContents[m]??e.fileContents[u];if(c===void 0){i.push({path:g,message:`referenced ArkRules file ${JSON.stringify(m)} is missing`});continue}try{let l=We(JSON.parse(c),m,d);a.push({layer:d,sourceFile:m,file:l.config})}catch(l){if(l instanceof ye)for(let p of l.issues)i.push({path:`${g}${p.path==="$"?"":p.path.replace(/^\$/,"")}`,message:`${m}: ${p.message}`});else l instanceof SyntaxError?i.push({path:g,message:`referenced ArkRules file ${JSON.stringify(m)} is not valid JSON: ${l.message}`}):i.push({path:g,message:`referenced ArkRules file ${JSON.stringify(m)} failed to load: ${l instanceof Error?l.message:String(l)}`})}}if(e.discoveredArkRulesFiles)for(let d of[...e.discoveredArkRulesFiles].sort()){let u=Ur(d);o.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(i.length>0)throw new Je(t,i);return{config:e.config,arkRules:xt(a),warnings:r}}function Ot(e){let{stewards:t,...n}=e.config;return{config:n,arkRules:{schemaVersion:e.arkRules.schemaVersion,structure:e.arkRules.structure.map(r=>({id:r.id,sensor:r.sensor,mode:r.mode,appliesTo:r.appliesTo??null,description:r.description??null,provenance:r.provenance})),invariants:e.arkRules.invariants.map(r=>({id:r.id,description:r.description,aggregate:r.aggregate??null,coverage:r.coverage??null,mode:r.mode,appliesTo:r.appliesTo??null,provenance:r.provenance}))}}}function Fi(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*['"\`][^'"\`]*${n}[^'"\`]*['"\`]`,"i").test(e)||e.includes(t)}function Di(e,t){if(!t)return!1;let n=t.split("."),r=n[n.length-1],s=n.length>1?n[0]:null;for(let i of Object.values(e))if(!(s&&!i.includes(s))&&(new RegExp(`(?:function\\s+|\\b)${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[(<]`).test(i)||i.includes(t)))return!0;return!1}function Tt(e){let t=e.arkRules.invariants??[];if(t.length===0)return{coverage:[],violations:[],partial:!1};let n=e.testFiles??[],r=e.testGlobsMissing===!0||n.length===0,s=[],i=[];for(let a of t){let o=[],d=a.coverage?.test!==!1,u=a.coverage?.symbol;if(!r&&d)for(let l of n){let p=e.fileContents[l];if(p&&Fi(p,a.id)){o.push("test-title");break}}u&&Di(e.fileContents,u)&&o.push("symbol");let m=(a.coverage?.test===!0||!!u||a.coverage===void 0)&&o.length>0||a.coverage?.test===!1&&!u?!0:o.length>0,c=r&&d&&o.length===0;if(s.push({invariantId:a.id,layer:a.provenance.layer,sourceFile:a.provenance.sourceFile,mode:a.mode,covered:m&&!c,evidence:o,partial:c,description:a.description}),!m||c){let l=a.mode==="enforced"&&!c;i.push({ruleId:"INVARIANT_UNCOVERED",message:c?`Invariant ${a.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered.`:`Invariant ${a.id} is not covered by a test title or declared symbol.`,file:a.provenance.sourceFile,line:1,arkruleId:a.id,arkruleSource:a.provenance.sourceFile,fromLayer:a.provenance.layer,severity:l?"error":"warning",failsStrict:l})}}return{coverage:s,violations:i,partial:s.some(a=>a.partial)}}function Pt(e){return e?e.partial?{ok:!1,reason:"Coverage is partial (missing test globs); cannot promote until evidence is complete."}:e.covered?{ok:!0,reason:`Invariant ${e.invariantId} has coverage evidence.`}:{ok:!1,reason:`Invariant ${e.invariantId} is uncovered; add a test title or symbol before promoting to enforced.`}:{ok:!1,reason:"No coverage evidence supplied for this invariant; evaluate coverage before promoting to enforced."}}var wt="1.0";function C(e,t){e.push({id:`${t.classification}:${t.path}:${t.kind}`,path:t.path,classification:t.classification,message:t.message,...t.classification==="weakening"||t.classification==="judgment-required"?{nextAction:`Restore the previous protection at ${t.path}, then run ArkGate again.`}:{},...t.before===void 0?{}:{before:t.before},...t.after===void 0?{}:{after:t.after}})}function z(e){return[...new Set(e??[])].sort()}function he(e,t,n,r,s){let i=z(n),a=z(r),o=new Set(i),d=new Set(a),u=a.filter(m=>!o.has(m)),g=i.filter(m=>!d.has(m));u.length===0&&g.length===0||(u.length>0&&C(e,{kind:"added",path:t,classification:s.added,message:s.addedMessage,before:i,after:a}),g.length>0&&C(e,{kind:"removed",path:t,classification:s.removed,message:s.removedMessage,before:i,after:a}))}function Lt(e,t,n,r,s,i,a){if(n===r)return;C(e,{kind:r?"enabled":"disabled",path:t,classification:r?s:s==="strengthening"?"weakening":"strengthening",message:r?i:a,before:n,after:r})}function Nt(e,t){let n=new Map,r=new Set;for(let s of e){let i=t(s);n.has(i)?r.add(i):n.set(i,s)}return{values:n,duplicates:[...r].sort()}}function Hi(e,t,n){let r=Nt(t,i=>i.name),s=Nt(n,i=>i.name);(r.duplicates.length>0||s.duplicates.length>0)&&C(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:r.duplicates,after:s.duplicates});for(let i of[...new Set([...r.values.keys(),...s.values.keys()])].sort()){let a=r.values.get(i),o=s.values.get(i),d=`$.layers[${i}]`;if(!a&&o){C(e,{kind:"layer-added",path:d,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:o});continue}if(a&&!o){C(e,{kind:"layer-removed",path:d,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:a});continue}if(!a||!o)continue;he(e,`${d}.patterns`,a.patterns,o.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),he(e,`${d}.exclude`,a.exclude,o.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let u=yt(a),g=yt(o);he(e,`${d}.forbiddenGlobals`,u.rawGlobals,g.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),he(e,`${d}.capabilities`,u.atoms,g.atoms,{added:"strengthening",removed:"weakening",addedMessage:"Additional ambient/import protection is enforced in this layer (coverage atoms).",removedMessage:"An ambient/import protection was lost from this layer (coverage atoms)."}),z(a.intentPrefixes).join("\0")!==z(o.intentPrefixes).join("\0")&&C(e,{kind:"intent-prefixes-changed",path:`${d}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:z(a.intentPrefixes),after:z(o.intentPrefixes)}),Lt(e,`${d}.mayImportInfrastructure`,a.mayImportInfrastructure===!0,o.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),Lt(e,`${d}.optional`,a.optional===!0,o.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active.")}}function Vi(e,t,n){let r=a=>`${a.from}->${a.to}`,s=Nt(t,r),i=Nt(n,r);(s.duplicates.length>0||i.duplicates.length>0)&&C(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:s.duplicates,after:i.duplicates});for(let a of[...new Set([...s.values.keys(),...i.values.keys()])].sort()){let o=s.values.get(a),d=i.values.get(a),u=`$.rules[${a}]`;if(!o&&d){d.allowed===!1&&C(e,{kind:"deny-added",path:u,classification:"strengthening",message:"A denied dependency edge was added.",after:d});continue}if(o&&!d){o.allowed===!1&&C(e,{kind:"deny-removed",path:u,classification:"weakening",message:"A denied dependency edge was removed.",before:o});continue}if(!o||!d)continue;o.allowed!==d.allowed&&C(e,{kind:d.allowed?"deny-disabled":"deny-enabled",path:`${u}.allowed`,classification:d.allowed?"weakening":"strengthening",message:d.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:o.allowed,after:d.allowed});let g=o.peerIsolation===!0,m=d.peerIsolation===!0;if(g!==m){let c=o.from===o.to&&d.from===d.to;C(e,{kind:m?"peer-isolation-enabled":"peer-isolation-disabled",path:`${u}.peerIsolation`,classification:c?m?"strengthening":"weakening":"judgment-required",message:c?m?"Cross-slice dependencies inside this layer are now denied.":"Cross-slice dependencies inside this layer are no longer denied.":"Changing peer isolation on a cross-layer edge changes the denial scope.",before:g,after:m})}z(o.sliceFolders).join("\0")!==z(d.sliceFolders).join("\0")&&C(e,{kind:"slice-folders-changed",path:`${u}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:z(o.sliceFolders),after:z(d.sliceFolders)})}}function ji(e,t,n){let r=t.safety??{},s=n.safety??{};for(let i of["maxTsSuppressions","maxAnyCasts"]){let a=r[i]??0,o=s[i]??0;a!==o&&C(e,{kind:o>a?"threshold-raised":"threshold-lowered",path:`$.safety.${i}`,classification:o>a?"weakening":"strengthening",message:o>a?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:a,after:o})}for(let i of["allowInMemory","allowDisabledPeerIsolation"])Lt(e,`$.safety.${i}`,r[i]===!0,s[i]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}function Ui(e){return e.some(t=>t.classification==="weakening")?"weakening":e.some(t=>t.classification==="judgment-required")?"judgment-required":e.some(t=>t.classification==="strengthening")?"strengthening":"neutral"}function Br(e,t){return`${e}::${t}`}function Kr(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(Br(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(Br(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}function Gi(e,t,n,r,s,i){let a=new Map((i??[]).map(c=>[c.invariantId,c])),o=t.arkRules??{},d=n.arkRules??{},u=[...new Set([...Object.keys(o),...Object.keys(d)])].sort();for(let c of u){let l=o[c],p=d[c],y=`$.arkRules[${c}]`;if(l===void 0&&p!==void 0){C(e,{kind:"arkrules-ref-added",path:y,classification:"strengthening",message:`ArkRules reference for layer ${c} was added.`,after:p});continue}if(l!==void 0&&p===void 0){C(e,{kind:"arkrules-ref-removed",path:y,classification:"weakening",message:`ArkRules reference for layer ${c} was removed.`,before:l});continue}l!==p&&C(e,{kind:"arkrules-ref-path-changed",path:y,classification:"judgment-required",message:`ArkRules file path for layer ${c} changed; verify the effective rules still match intent.`,before:l,after:p})}let g=Kr(r),m=Kr(s);for(let c of[...new Set([...g.structure.keys(),...m.structure.keys()])].sort()){let l=g.structure.get(c),p=m.structure.get(c),y=`$.arkRules.structure[${c}]`;if(!l&&p){C(e,{kind:"arkrule-structure-added",path:y,classification:"strengthening",message:`Structure ArkRule ${p.id} was added (${p.mode}).`,after:p});continue}if(l&&!p){C(e,{kind:"arkrule-structure-removed",path:y,classification:"weakening",message:`Structure ArkRule ${l.id} was removed.`,before:l});continue}if(!(!l||!p)){if(l.mode!==p.mode){let I=l.mode==="advisory"&&p.mode==="enforced";C(e,{kind:I?"arkrule-promoted":"arkrule-demoted",path:`${y}.mode`,classification:I?"strengthening":"weakening",message:I?`Structure ArkRule ${p.id} was promoted to enforced.`:`Structure ArkRule ${p.id} was demoted to advisory.`,before:l.mode,after:p.mode})}l.sensor!==p.sensor&&C(e,{kind:"arkrule-sensor-changed",path:`${y}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${p.id} changed sensor identity.`,before:l.sensor,after:p.sensor})}}for(let c of[...new Set([...g.invariants.keys(),...m.invariants.keys()])].sort()){let l=g.invariants.get(c),p=m.invariants.get(c),y=`$.arkRules.invariants[${c}]`;if(!l&&p){C(e,{kind:"arkrule-invariant-added",path:y,classification:"strengthening",message:`Invariant ${p.id} was added (${p.mode}).`,after:p});continue}if(l&&!p){C(e,{kind:"arkrule-invariant-removed",path:y,classification:"weakening",message:`Invariant ${l.id} was removed.`,before:l});continue}if(!(!l||!p)&&l.mode!==p.mode)if(l.mode==="advisory"&&p.mode==="enforced"){let R=a?.get(p.id),f=Pt(R);f.ok?C(e,{kind:"arkrule-invariant-promoted",path:`${y}.mode`,classification:"strengthening",message:`Invariant ${p.id} was promoted to enforced (coverage evidence present).`,before:l.mode,after:p.mode}):C(e,{kind:"arkrule-invariant-promote-refused",path:`${y}.mode`,classification:"judgment-required",message:`Invariant ${p.id} cannot be promoted to enforced: ${f.reason}`,before:l.mode,after:p.mode})}else C(e,{kind:"arkrule-invariant-demoted",path:`${y}.mode`,classification:"weakening",message:`Invariant ${p.id} was demoted to advisory.`,before:l.mode,after:p.mode})}}function Mt(e,t,n){let r=[];he(r,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),he(r,"$.exclude",e.exclude,t.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional project paths are excluded from governance.",removedMessage:"Fewer project paths are excluded from governance."}),he(r,"$.dynamicImportAllowlist",e.dynamicImportAllowlist,t.dynamicImportAllowlist,{added:"weakening",removed:"strengthening",addedMessage:"Additional files may use non-literal dynamic imports.",removedMessage:"Fewer files may use non-literal dynamic imports."}),Lt(r,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let s={off:0,soft:1,"framework-soft":1,strict:2},i=e.cyclePolicy??"strict",a=t.cyclePolicy??"strict";if(i!==a){let o=s[a]===s[i]?"judgment-required":s[a]>s[i]?"strengthening":"weakening";C(r,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:o,message:"The cycle enforcement level changed.",before:i,after:a})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&C(r,{kind:"framework-overlay-changed",path:"$.frameworkOverlay",classification:"judgment-required",message:"The framework overlay changed and may alter effective layer matching.",before:e.frameworkOverlay??null,after:t.frameworkOverlay??null}),Hi(r,e.layers,t.layers),Vi(r,e.rules,t.rules),ji(r,e,t),Gi(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),r.sort((o,d)=>o.path.localeCompare(d.path)||o.id.localeCompare(d.id)),{schemaVersion:wt,classification:Ui(r),findings:r}}function $t(e,t){if(!e||e.schemaVersion!==wt||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(s=>typeof s!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=z(e.findingIds),r=z(t.findingIds);return n.length===r.length&&n.every((s,i)=>s===r[i])}function Ae(e){let t=[];for(let n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."&&t.length>0&&t.at(-1)!==".."?t.pop():t.push(n));return t.join("/")}function zr(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}function Ft(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}function G(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}function Ze(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let r=t,s="";for(t+=1;t<e.length;t+=1){let i=e[t];if(i===n)return{value:s,offset:r,excerpt:e.slice(r,t+1)};i==="\\"&&t+1<e.length?(s+=e[t+1],t+=1):s+=i}}function q(e,t,n){return e.startsWith(t,n)&&!Ft(e[n-1])&&!Ft(e[n+t.length])}function qr(e,t){let n=G(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=G(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!q(e,"type",n))return!1;let s=G(e,n+4);if(s>=e.length||e[s]===","||e[s]==="}"||q(e,"as",s)||!zr(e[s]))return!1;for(n=s;n<e.length&&Ft(e[n]);)n+=1;if(n=G(e,n),q(e,"as",n)){if(n=G(e,n+2),!zr(e[n]))return!1;for(;n<e.length&&Ft(e[n]);)n+=1}r=!0}return!1}function Bi(e,t){if(t=G(e,t+6),e[t]==="(")return Ze(e,G(e,t+1));let n=!1;if(q(e,"type",t)){let s=G(e,t+4);e[s]!==","&&!q(e,"from",s)&&(n=!0)}else qr(e,t)&&(n=!0);let r=Yr(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}function Ki(e,t){t=t+6;let n=G(e,t),r=!1;if(q(e,"type",n)){let i=G(e,n+4);(e[i]==="{"||e[i]==="*")&&(r=!0)}else qr(e,n)&&(r=!0);let s=Yr(e,t,!1);return s&&r?{...s,typeOnly:!0}:s}function Yr(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(q(e,"from",t))return Ze(e,G(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return Ze(e,t);if(t>0&&(q(e,"import",t)||q(e,"export",t)))return}}function zi(e,t){for(t+=1;t<e.length;t+=1){let n=e[t];if(n==="\\")t+=1;else if(n==="`")return t}return e.length}function qi(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=G(e,t+7);if(e[r]!=="(")return;r=G(e,r+1);let s=Ze(e,r);return s?{...s,requireCall:!0}:void 0}function Yi(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(`
|
|
8
|
+
`)}`),this.name="EffectiveContractError",this.source=t,this.issues=n}};function Ur(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function Gr(e,t="ark.config.json"){let n=e.config.arkRules,r=[];if(!n||Object.keys(n).length===0){if(e.discoveredArkRulesFiles&&e.discoveredArkRulesFiles.length>0)for(let d of[...e.discoveredArkRulesFiles].sort())r.push({path:d,message:`ArkRules file ${JSON.stringify(d)} is not referenced by arkRules and will not be enforced`,severity:"advisory"});return{config:e.config,arkRules:le(),warnings:r}}let s=new Set(e.config.layers.map(d=>d.name)),i=[],o=[],a=new Set;for(let d of Object.keys(n).sort()){let u=n[d],g=`$.arkRules[${JSON.stringify(d)}]`;if(typeof u!="string"||u.length===0){i.push({path:g,message:"must be a non-empty relative path string"});continue}if(u.startsWith("/")||/^[A-Za-z]:[\\/]/.test(u)){i.push({path:g,message:"must be a project-relative path (absolute paths are not allowed)"});continue}if(!s.has(d)){i.push({path:g,message:`layer ${JSON.stringify(d)} is not declared in layers[]`});continue}let m=Ur(u);a.add(m);let c=e.fileContents[m]??e.fileContents[u];if(c===void 0){i.push({path:g,message:`referenced ArkRules file ${JSON.stringify(m)} is missing`});continue}try{let l=We(JSON.parse(c),m,d);o.push({layer:d,sourceFile:m,file:l.config})}catch(l){if(l instanceof ye)for(let p of l.issues)i.push({path:`${g}${p.path==="$"?"":p.path.replace(/^\$/,"")}`,message:`${m}: ${p.message}`});else l instanceof SyntaxError?i.push({path:g,message:`referenced ArkRules file ${JSON.stringify(m)} is not valid JSON: ${l.message}`}):i.push({path:g,message:`referenced ArkRules file ${JSON.stringify(m)} failed to load: ${l instanceof Error?l.message:String(l)}`})}}if(e.discoveredArkRulesFiles)for(let d of[...e.discoveredArkRulesFiles].sort()){let u=Ur(d);a.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(i.length>0)throw new Je(t,i);return{config:e.config,arkRules:xt(o),warnings:r}}function Ot(e){let{stewards:t,...n}=e.config;return{config:n,arkRules:{schemaVersion:e.arkRules.schemaVersion,structure:e.arkRules.structure.map(r=>({id:r.id,sensor:r.sensor,mode:r.mode,appliesTo:r.appliesTo??null,description:r.description??null,provenance:r.provenance})),invariants:e.arkRules.invariants.map(r=>({id:r.id,description:r.description,aggregate:r.aggregate??null,coverage:r.coverage??null,mode:r.mode,appliesTo:r.appliesTo??null,provenance:r.provenance}))}}}function Fi(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*['"\`][^'"\`]*${n}[^'"\`]*['"\`]`,"i").test(e)||e.includes(t)}function Di(e,t){if(!t)return!1;let n=t.split("."),r=n[n.length-1],s=n.length>1?n[0]:null;for(let i of Object.values(e))if(!(s&&!i.includes(s))&&(new RegExp(`(?:function\\s+|\\b)${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[(<]`).test(i)||i.includes(t)))return!0;return!1}function Tt(e){let t=e.arkRules.invariants??[];if(t.length===0)return{coverage:[],violations:[],partial:!1};let n=e.testFiles??[],r=e.testGlobsMissing===!0||n.length===0,s=[],i=[];for(let o of t){let a=[],d=o.coverage?.test!==!1,u=o.coverage?.symbol;if(!r&&d)for(let l of n){let p=e.fileContents[l];if(p&&Fi(p,o.id)){a.push("test-title");break}}u&&Di(e.fileContents,u)&&a.push("symbol");let m=(o.coverage?.test===!0||!!u||o.coverage===void 0)&&a.length>0||o.coverage?.test===!1&&!u?!0:a.length>0,c=r&&d&&a.length===0;if(s.push({invariantId:o.id,layer:o.provenance.layer,sourceFile:o.provenance.sourceFile,mode:o.mode,covered:m&&!c,evidence:a,partial:c,description:o.description}),!m||c){let l=o.mode==="enforced"&&!c;i.push({ruleId:"INVARIANT_UNCOVERED",message:c?`Invariant ${o.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered.`:`Invariant ${o.id} is not covered by a test title or declared symbol.`,file:o.provenance.sourceFile,line:1,arkruleId:o.id,arkruleSource:o.provenance.sourceFile,fromLayer:o.provenance.layer,severity:l?"error":"warning",failsStrict:l})}}return{coverage:s,violations:i,partial:s.some(o=>o.partial)}}function Pt(e){return e?e.partial?{ok:!1,reason:"Coverage is partial (missing test globs); cannot promote until evidence is complete."}:e.covered?{ok:!0,reason:`Invariant ${e.invariantId} has coverage evidence.`}:{ok:!1,reason:`Invariant ${e.invariantId} is uncovered; add a test title or symbol before promoting to enforced.`}:{ok:!1,reason:"No coverage evidence supplied for this invariant; evaluate coverage before promoting to enforced."}}var wt="1.0";function C(e,t){e.push({id:`${t.classification}:${t.path}:${t.kind}`,path:t.path,classification:t.classification,message:t.message,...t.classification==="weakening"||t.classification==="judgment-required"?{nextAction:`Restore the previous protection at ${t.path}, then run ArkGate again.`}:{},...t.before===void 0?{}:{before:t.before},...t.after===void 0?{}:{after:t.after}})}function z(e){return[...new Set(e??[])].sort()}function he(e,t,n,r,s){let i=z(n),o=z(r),a=new Set(i),d=new Set(o),u=o.filter(m=>!a.has(m)),g=i.filter(m=>!d.has(m));u.length===0&&g.length===0||(u.length>0&&C(e,{kind:"added",path:t,classification:s.added,message:s.addedMessage,before:i,after:o}),g.length>0&&C(e,{kind:"removed",path:t,classification:s.removed,message:s.removedMessage,before:i,after:o}))}function Lt(e,t,n,r,s,i,o){if(n===r)return;C(e,{kind:r?"enabled":"disabled",path:t,classification:r?s:s==="strengthening"?"weakening":"strengthening",message:r?i:o,before:n,after:r})}function Nt(e,t){let n=new Map,r=new Set;for(let s of e){let i=t(s);n.has(i)?r.add(i):n.set(i,s)}return{values:n,duplicates:[...r].sort()}}function Hi(e,t,n){let r=Nt(t,i=>i.name),s=Nt(n,i=>i.name);(r.duplicates.length>0||s.duplicates.length>0)&&C(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:r.duplicates,after:s.duplicates});for(let i of[...new Set([...r.values.keys(),...s.values.keys()])].sort()){let o=r.values.get(i),a=s.values.get(i),d=`$.layers[${i}]`;if(!o&&a){C(e,{kind:"layer-added",path:d,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:a});continue}if(o&&!a){C(e,{kind:"layer-removed",path:d,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:o});continue}if(!o||!a)continue;he(e,`${d}.patterns`,o.patterns,a.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),he(e,`${d}.exclude`,o.exclude,a.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let u=yt(o),g=yt(a);he(e,`${d}.forbiddenGlobals`,u.rawGlobals,g.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),he(e,`${d}.capabilities`,u.atoms,g.atoms,{added:"strengthening",removed:"weakening",addedMessage:"Additional ambient/import protection is enforced in this layer (coverage atoms).",removedMessage:"An ambient/import protection was lost from this layer (coverage atoms)."}),z(o.intentPrefixes).join("\0")!==z(a.intentPrefixes).join("\0")&&C(e,{kind:"intent-prefixes-changed",path:`${d}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:z(o.intentPrefixes),after:z(a.intentPrefixes)}),Lt(e,`${d}.mayImportInfrastructure`,o.mayImportInfrastructure===!0,a.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),Lt(e,`${d}.optional`,o.optional===!0,a.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active.")}}function Vi(e,t,n){let r=o=>`${o.from}->${o.to}`,s=Nt(t,r),i=Nt(n,r);(s.duplicates.length>0||i.duplicates.length>0)&&C(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:s.duplicates,after:i.duplicates});for(let o of[...new Set([...s.values.keys(),...i.values.keys()])].sort()){let a=s.values.get(o),d=i.values.get(o),u=`$.rules[${o}]`;if(!a&&d){d.allowed===!1&&C(e,{kind:"deny-added",path:u,classification:"strengthening",message:"A denied dependency edge was added.",after:d});continue}if(a&&!d){a.allowed===!1&&C(e,{kind:"deny-removed",path:u,classification:"weakening",message:"A denied dependency edge was removed.",before:a});continue}if(!a||!d)continue;a.allowed!==d.allowed&&C(e,{kind:d.allowed?"deny-disabled":"deny-enabled",path:`${u}.allowed`,classification:d.allowed?"weakening":"strengthening",message:d.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:a.allowed,after:d.allowed});let g=a.peerIsolation===!0,m=d.peerIsolation===!0;if(g!==m){let c=a.from===a.to&&d.from===d.to;C(e,{kind:m?"peer-isolation-enabled":"peer-isolation-disabled",path:`${u}.peerIsolation`,classification:c?m?"strengthening":"weakening":"judgment-required",message:c?m?"Cross-slice dependencies inside this layer are now denied.":"Cross-slice dependencies inside this layer are no longer denied.":"Changing peer isolation on a cross-layer edge changes the denial scope.",before:g,after:m})}z(a.sliceFolders).join("\0")!==z(d.sliceFolders).join("\0")&&C(e,{kind:"slice-folders-changed",path:`${u}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:z(a.sliceFolders),after:z(d.sliceFolders)})}}function ji(e,t,n){let r=t.safety??{},s=n.safety??{};for(let i of["maxTsSuppressions","maxAnyCasts"]){let o=r[i]??0,a=s[i]??0;o!==a&&C(e,{kind:a>o?"threshold-raised":"threshold-lowered",path:`$.safety.${i}`,classification:a>o?"weakening":"strengthening",message:a>o?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:o,after:a})}for(let i of["allowInMemory","allowDisabledPeerIsolation"])Lt(e,`$.safety.${i}`,r[i]===!0,s[i]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}function Ui(e){return e.some(t=>t.classification==="weakening")?"weakening":e.some(t=>t.classification==="judgment-required")?"judgment-required":e.some(t=>t.classification==="strengthening")?"strengthening":"neutral"}function Br(e,t){return`${e}::${t}`}function Kr(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(Br(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(Br(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}function Gi(e,t,n,r,s,i){let o=new Map((i??[]).map(c=>[c.invariantId,c])),a=t.arkRules??{},d=n.arkRules??{},u=[...new Set([...Object.keys(a),...Object.keys(d)])].sort();for(let c of u){let l=a[c],p=d[c],y=`$.arkRules[${c}]`;if(l===void 0&&p!==void 0){C(e,{kind:"arkrules-ref-added",path:y,classification:"strengthening",message:`ArkRules reference for layer ${c} was added.`,after:p});continue}if(l!==void 0&&p===void 0){C(e,{kind:"arkrules-ref-removed",path:y,classification:"weakening",message:`ArkRules reference for layer ${c} was removed.`,before:l});continue}l!==p&&C(e,{kind:"arkrules-ref-path-changed",path:y,classification:"judgment-required",message:`ArkRules file path for layer ${c} changed; verify the effective rules still match intent.`,before:l,after:p})}let g=Kr(r),m=Kr(s);for(let c of[...new Set([...g.structure.keys(),...m.structure.keys()])].sort()){let l=g.structure.get(c),p=m.structure.get(c),y=`$.arkRules.structure[${c}]`;if(!l&&p){C(e,{kind:"arkrule-structure-added",path:y,classification:"strengthening",message:`Structure ArkRule ${p.id} was added (${p.mode}).`,after:p});continue}if(l&&!p){C(e,{kind:"arkrule-structure-removed",path:y,classification:"weakening",message:`Structure ArkRule ${l.id} was removed.`,before:l});continue}if(!(!l||!p)){if(l.mode!==p.mode){let I=l.mode==="advisory"&&p.mode==="enforced";C(e,{kind:I?"arkrule-promoted":"arkrule-demoted",path:`${y}.mode`,classification:I?"strengthening":"weakening",message:I?`Structure ArkRule ${p.id} was promoted to enforced.`:`Structure ArkRule ${p.id} was demoted to advisory.`,before:l.mode,after:p.mode})}l.sensor!==p.sensor&&C(e,{kind:"arkrule-sensor-changed",path:`${y}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${p.id} changed sensor identity.`,before:l.sensor,after:p.sensor})}}for(let c of[...new Set([...g.invariants.keys(),...m.invariants.keys()])].sort()){let l=g.invariants.get(c),p=m.invariants.get(c),y=`$.arkRules.invariants[${c}]`;if(!l&&p){C(e,{kind:"arkrule-invariant-added",path:y,classification:"strengthening",message:`Invariant ${p.id} was added (${p.mode}).`,after:p});continue}if(l&&!p){C(e,{kind:"arkrule-invariant-removed",path:y,classification:"weakening",message:`Invariant ${l.id} was removed.`,before:l});continue}if(!(!l||!p)&&l.mode!==p.mode)if(l.mode==="advisory"&&p.mode==="enforced"){let R=o?.get(p.id),f=Pt(R);f.ok?C(e,{kind:"arkrule-invariant-promoted",path:`${y}.mode`,classification:"strengthening",message:`Invariant ${p.id} was promoted to enforced (coverage evidence present).`,before:l.mode,after:p.mode}):C(e,{kind:"arkrule-invariant-promote-refused",path:`${y}.mode`,classification:"judgment-required",message:`Invariant ${p.id} cannot be promoted to enforced: ${f.reason}`,before:l.mode,after:p.mode})}else C(e,{kind:"arkrule-invariant-demoted",path:`${y}.mode`,classification:"weakening",message:`Invariant ${p.id} was demoted to advisory.`,before:l.mode,after:p.mode})}}function Mt(e,t,n){let r=[];he(r,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),he(r,"$.exclude",e.exclude,t.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional project paths are excluded from governance.",removedMessage:"Fewer project paths are excluded from governance."}),he(r,"$.dynamicImportAllowlist",e.dynamicImportAllowlist,t.dynamicImportAllowlist,{added:"weakening",removed:"strengthening",addedMessage:"Additional files may use non-literal dynamic imports.",removedMessage:"Fewer files may use non-literal dynamic imports."}),Lt(r,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let s={off:0,soft:1,"framework-soft":1,strict:2},i=e.cyclePolicy??"strict",o=t.cyclePolicy??"strict";if(i!==o){let a=s[o]===s[i]?"judgment-required":s[o]>s[i]?"strengthening":"weakening";C(r,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:a,message:"The cycle enforcement level changed.",before:i,after:o})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&C(r,{kind:"framework-overlay-changed",path:"$.frameworkOverlay",classification:"judgment-required",message:"The framework overlay changed and may alter effective layer matching.",before:e.frameworkOverlay??null,after:t.frameworkOverlay??null}),Hi(r,e.layers,t.layers),Vi(r,e.rules,t.rules),ji(r,e,t),Gi(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),r.sort((a,d)=>a.path.localeCompare(d.path)||a.id.localeCompare(d.id)),{schemaVersion:wt,classification:Ui(r),findings:r}}function $t(e,t){if(!e||e.schemaVersion!==wt||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(s=>typeof s!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=z(e.findingIds),r=z(t.findingIds);return n.length===r.length&&n.every((s,i)=>s===r[i])}function Ae(e){let t=[];for(let n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."&&t.length>0&&t.at(-1)!==".."?t.pop():t.push(n));return t.join("/")}function zr(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}function Ft(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}function G(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}function Ze(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let r=t,s="";for(t+=1;t<e.length;t+=1){let i=e[t];if(i===n)return{value:s,offset:r,excerpt:e.slice(r,t+1)};i==="\\"&&t+1<e.length?(s+=e[t+1],t+=1):s+=i}}function q(e,t,n){return e.startsWith(t,n)&&!Ft(e[n-1])&&!Ft(e[n+t.length])}function qr(e,t){let n=G(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=G(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!q(e,"type",n))return!1;let s=G(e,n+4);if(s>=e.length||e[s]===","||e[s]==="}"||q(e,"as",s)||!zr(e[s]))return!1;for(n=s;n<e.length&&Ft(e[n]);)n+=1;if(n=G(e,n),q(e,"as",n)){if(n=G(e,n+2),!zr(e[n]))return!1;for(;n<e.length&&Ft(e[n]);)n+=1}r=!0}return!1}function Bi(e,t){if(t=G(e,t+6),e[t]==="(")return Ze(e,G(e,t+1));let n=!1;if(q(e,"type",t)){let s=G(e,t+4);e[s]!==","&&!q(e,"from",s)&&(n=!0)}else qr(e,t)&&(n=!0);let r=Yr(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}function Ki(e,t){t=t+6;let n=G(e,t),r=!1;if(q(e,"type",n)){let i=G(e,n+4);(e[i]==="{"||e[i]==="*")&&(r=!0)}else qr(e,n)&&(r=!0);let s=Yr(e,t,!1);return s&&r?{...s,typeOnly:!0}:s}function Yr(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(q(e,"from",t))return Ze(e,G(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return Ze(e,t);if(t>0&&(q(e,"import",t)||q(e,"export",t)))return}}function zi(e,t){for(t+=1;t<e.length;t+=1){let n=e[t];if(n==="\\")t+=1;else if(n==="`")return t}return e.length}function qi(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=G(e,t+7);if(e[r]!=="(")return;r=G(e,r+1);let s=Ze(e,r);return s?{...s,requireCall:!0}:void 0}function Yi(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
9
|
`,n+2),n<0)break;continue}if(r==="/"&&e[n+1]==="*"){let i=e.indexOf("*/",n+2);if(i<0)break;n=i+1;continue}if(r==="`"){n=zi(e,n);continue}if(r==="'"||r==='"'){let i=Ze(e,n);i&&(n=i.offset+i.excerpt.length-1);continue}let s=r==="i"&&q(e,"import",n)?Bi(e,n):r==="e"&&q(e,"export",n)?Ki(e,n):r==="r"&&q(e,"require",n)?qi(e,n):void 0;s&&(t.push(s),n=s.offset+s.excerpt.length-1)}return t}function Wr(e,t){let n=[],r=[];for(let s of Yi(e.content)){let i=s.value;if(!i.startsWith(".")){if(s.typeOnly)continue;let u=Me(i);if(!u)continue;let g=e.content.slice(0,s.offset).split(`
|
|
10
|
-
`).length;r.push({file:e.path,symbol:i,capability:u,evidence:{kind:"import",file:e.path,line:g,excerpt:s.excerpt}});continue}let
|
|
11
|
-
`).length,o={kind:"import",file:e.path,line:a,excerpt:s.excerpt},d=Wi(e.path,i,t);n.push({from:e.path,specifier:i,to:d?.path??null,resolution:d?"resolved":"unresolved",fromLayer:e.layer,toLayer:d?.layer??null,evidence:o})}return{edges:n,capabilityUses:r}}function Wi(e,t,n){let r=e.split("/");r.pop();for(let i of t.split("/"))i==="."||i===""||(i===".."?r.pop():r.push(i));let s=r.join("/");for(let i of[s,`${s}.ts`,`${s}.tsx`,`${s}.mts`,`${s}.cts`,`${s}/index.ts`,`${s}/index.tsx`]){let a=n.get(i);if(a)return a}}function Jr(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let s=ee(t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});s&&n.push({ruleId:`layer-dependency:${s.from}->${s.to}`,message:s.message??`${s.from} must not depend on ${s.to}.`,edge:r,evidence:r.evidence})}return n}var Ji={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 Zi(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}function Xi(e,t){return Zi(e,t)?M(x(Ot({config:e,arkRules:t,warnings:[]}))):M(x(e))}function Xe(e,t,n){let r=typeof e=="string"?Rt(e,t):Ue(e,t),s=n?.arkRules??le();return{...r,arkRules:s,policyHash:Xi(r.config,s)}}function _n(e){let t=Xe(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=Xe(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=Mt(t.config,n.config,{baseArkRules:t.arkRules,candidateArkRules:n.arkRules,candidateInvariantCoverage:e.candidateInvariantCoverage}),s=r.findings.filter(o=>o.classification==="weakening"||o.classification==="judgment-required").map(o=>o.id).sort(),i=s.length>0,a=i&&$t(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:s});return{schemaVersion:r.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:r.classification,findings:r.findings,blockingFindingIds:s,requiresAcknowledgement:i,acknowledged:a,valid:!i||a}}function xe(e){let t=e.files.map(m=>{let c=Ae(m.path);return{path:c,content:m.content,contentHash:M(m.content),layer:Q(c,e.contract.config.layers)??null}}).sort((m,c)=>m.path.localeCompare(c.path)),n=new Map(t.map(m=>[m.path,m])),r=[],s=[];for(let m of t){let c=Wr(m,n);r.push(...c.edges),s.push(...c.capabilityUses)}let i=Jr(r,e.contract.config),a=new Map(e.contract.config.layers.map(m=>[m.name,m])),o=new Map(e.contract.config.layers.map(m=>[m.name,new Set(be(m))]));for(let m of s){let c=n.get(m.file)?.layer;if(!c)continue;let l=a.get(c),p=ie(m.symbol,l?.forbiddenGlobals??[]);if(p){i.push({ruleId:"FORBIDDEN_GLOBAL",message:`${c} must not use module "${m.symbol}" because it is the import form of forbidden global "${p}".`,symbol:m.symbol,evidence:m.evidence});continue}o.get(c)?.has(m.capability)&&i.push({ruleId:"CAPABILITY_VIOLATION",message:`${c} denies the ${m.capability} capability; found import of "${m.symbol}".`,capability:m.capability,symbol:m.symbol,evidence:m.evidence})}let d=t.length===0?"complete":"partial",u=d==="complete"?[]:[{...Ji}],g={schemaVersion:Ct,policyHash:e.contract.policyHash,compilerOptionsHash:M(x(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(m=>m.name),edges:r,capabilityUses:s,violations:i};return{mode:"lexical-compatibility",completeness:d,completenessReasons:u,valid:d==="complete"&&i.length===0,ir:g}}function Qe(e){let t=new Map(e.files.map(n=>[Ae(n.path),n]));for(let n of e.changes){let r=Ae(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return xe({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}function xn(e){let t=`${e.evidence.file}:${e.evidence.line}`;if(!e.edge)return`${e.ruleId} at ${t}: ${e.message}`;let n=e.edge.to??e.edge.specifier;return`${e.ruleId} at ${t}: ${e.edge.from} imports ${n}. ${e.message}`}function Dt(e){let t=0,n=new Map,r=new Map,s=new Set,i=[],a=[],o=d=>{n.set(d,t),r.set(d,t),t+=1,i.push(d),s.add(d);for(let m of[...e.get(d)??[]].sort())e.has(m)&&(n.has(m)?s.has(m)&&r.set(d,Math.min(r.get(d)??0,n.get(m)??0)):(o(m),r.set(d,Math.min(r.get(d)??0,r.get(m)??0))));if(r.get(d)!==n.get(d))return;let u=[],g;do{if(g=i.pop(),g===void 0)break;s.delete(g),u.push(g)}while(g!==d);u.length>1&&a.push(u.sort())};for(let d of[...e.keys()].sort())n.has(d)||o(d);return a.sort((d,u)=>d[0]<u[0]?-1:d[0]>u[0]?1:0).map(d=>({ruleId:"CIRCULAR_DEPENDENCY",file:d[0],line:1,target:d.join(" \u2192 "),message:`Circular dependency among ${d.length} files: ${d.join(" \u2192 ")} \u2192 ${d[0]}.`,cycleKind:"value"}))}function Ie(e){let t=e.contentViolations.map(i=>({...i})),n=(e.warnings??[]).map(i=>({...i})),r=new Map(e.files.map(i=>[i,new Set]));for(let i of e.edges){if(i.to&&i.to!==i.from&&!i.typeOnly&&r.has(i.from)&&r.get(i.from)?.add(i.to),!i.to||!i.fromLayer||!i.toLayer)continue;let a=ee(e.rules,i.fromLayer,i.toLayer,{fromPath:i.from,toPath:i.to,layers:e.config.layers});if(!a)continue;let o=!!a.peerIsolation,d=!o&&!!(i.typeOnly||i.namedBindingsTypeOnly),u=a.message??(o?`${i.fromLayer} must not ${i.kind} another slice of ${i.toLayer} (${i.from} \u2192 ${i.to}). Extract shared code or use events/ports across slices.`:`${i.fromLayer} must not ${i.kind} ${i.toLayer}.`);t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:i.from,line:i.line,fromLayer:i.fromLayer,toLayer:i.toLayer,target:i.to,...i.typeOnly?{typeOnly:!0}:{},...i.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...i.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...i.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!o&&i.portProofEligible?{portProofEligible:!0}:{},...i.kind?{edgeKind:i.kind}:{},...o?{peerIsolation:!0}:{},message:d?`${u} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:u,...d?{failsStrict:!1,severity:"warning"}:{}})}let s=String(e.config.cyclePolicy??"strict").toLowerCase();if(s!=="off"){let i=Dt(r);s==="soft"||s==="framework-soft"?n.push(...i.map(a=>({...a,message:`${a.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...i)}return{violations:t,warnings:n,safety:e.safety}}var Qi=["no-anemic-model"];function Zr(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function ea(e){let t="";for(let r=0;r<e.length;r+=1){let s=e[r];if(s==="\\"&&r+1<e.length){let i=e[r+1];if("*?{}[],".includes(i)||i==="\\"){t+="\\"+i,r+=1;continue}t+="/";continue}t+=s}let n="";for(let r=0;r<t.length;r+=1){let s=t[r];s==="\\"&&r+1<t.length?(n+=Zr(t[r+1]),r+=1):s==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":s==="?"?n+="[^/]":n+=Zr(s)}return new RegExp(`^${n}$`)}function et(e,t){return!t||t.length===0?!0:t.some(n=>ea(n).test(e))}function ta(e){return Qi.includes(e)}function Xr(e){return e.mode==="enforced"&&!ta(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}function Oe(e,t,n,r=1){let{severity:s,failsStrict:i}=Xr(e);return{ruleId:"ARKRULE_STRUCTURE",code:e.sensor,message:n,file:t,line:r,fromLayer:e.provenance.layer,arkruleId:e.id,arkruleSource:e.provenance.sourceFile,severity:s,sensor:e.sensor,failsStrict:i}}function On(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}function Ht(e,t,n){return t.filter(r=>!(!r.exported||!et(r.file,e.appliesTo)||!On(r.file,e,n)))}function na(e,t,n){let r=[];for(let s of Ht(e,t,n))(s.hasPublicSetters||s.hasPublicMutableFields)&&r.push(Oe(e,s.file,`Exported class ${s.className} exposes public mutable state (sensor aggregate-private-state).`));return r}function ra(e,t,n){let r=[];for(let s of Ht(e,t,n))if(s.hasPublicConstructor&&!s.hasStaticFactory){if(!(s.hasPublicMutableFields||s.hasPublicSetters||(s.mutatingMethods?.length??0)>0))continue;r.push(Oe(e,s.file,`Exported class ${s.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}return r}function sa(e,t,n){let r=[];for(let s of Ht(e,t,n))for(let i of s.mutatingMethods)i.referencesGuardOrPublish||r.push(Oe(e,s.file,`Mutating method ${s.className}.${i.name} does not reference a guard or publish symbol (sensor domain-event-on-mutation).`));return r}function ia(e,t){let n=[];for(let r of t.files)et(r,e.appliesTo)&&On(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}function aa(e,t){let n=[];for(let r of t.files)et(r,e.appliesTo)&&On(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}function oa(e,t,n){let r=[];for(let s of Ht(e,t,n))if(s.dataOnly===!0){let i=Oe(e,s.file,`Exported type ${s.className} looks data-only / anemic (sensor no-anemic-model; advisory only).`);r.push({...i,severity:"warning",failsStrict:!1})}return r}function Vt(e){if(!e.arkRules.structure.length)return[];let t=[];for(let n of e.arkRules.structure)switch(n.sensor){case"aggregate-private-state":t.push(...na(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...ra(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...sa(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...ia(n,e));break;case"thin-adapter":t.push(...aa(n,e));break;case"no-anemic-model":t.push(...oa(n,e.classShapes,e.layerForFile));break;case"invariant-coverage":break;default:break}return t.sort((n,r)=>n.file.localeCompare(r.file)||n.arkruleId.localeCompare(r.arkruleId)||n.message.localeCompare(r.message))}function jt(e,t){let n=[],r=t.map(s=>s.replace(/\\/g,"/"));for(let s of e.structure){if(!s.appliesTo||s.appliesTo.length===0||r.some(d=>et(d,s.appliesTo)))continue;let{severity:a,failsStrict:o}=Xr(s);n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule structure "${s.id}" appliesTo matched zero governed files (patterns: ${s.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:s.provenance.sourceFile,line:1,fromLayer:s.provenance.layer,arkruleId:s.id,arkruleSource:s.provenance.sourceFile,severity:a,sensor:s.sensor,failsStrict:o})}for(let s of e.invariants??[]){if(!s.appliesTo||s.appliesTo.length===0||r.some(o=>et(o,s.appliesTo)))continue;let a=s.mode==="enforced";n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule invariant "${s.id}" appliesTo matched zero governed files (patterns: ${s.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:s.provenance.sourceFile,line:1,fromLayer:s.provenance.layer,arkruleId:s.id,arkruleSource:s.provenance.sourceFile,severity:a?"error":"warning",sensor:"invariant-coverage",failsStrict:a})}return n.sort((s,i)=>s.file.localeCompare(i.file)||s.arkruleId.localeCompare(i.arkruleId)||s.message.localeCompare(i.message))}var la=/\bfrom\s+['"](?:@?prisma\/client|@supabase\/|drizzle-orm|typeorm|knex|mongodb|pg|mysql2|better-sqlite3|ioredis|redis)['"]|require\(\s*['"](?:@?prisma\/client|pg|knex|typeorm)/,ca=/\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*=)/,da=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,pa=/\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*=/,ua=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function Tn(e,t){if(!t||t.length<40)return null;let n=t.match(new RegExp(pa.source,"g"))??[],r=t.match(new RegExp(ua.source,"g"))??[],s=(t.match(/\bif\s*\(/g)??[]).length,i=(t.match(/\bswitch\s*\(/g)??[]).length,a=n.length>=2||n.length>=1&&r.length>=2||r.length>=3&&s+i>=6,o=la.test(t),d=ca.test(t)||da.test(t),u=n.length>=1||r.length>=2,g=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),m=o&&u||d&&u||o&&g&&(s>=4||n.length>=1)||d&&o;return!a&&!m?null:{...a?{orchestrationHeavy:!0}:{},...m?{adapterThick:!0}:{}}}function Ut(e){let t={};for(let[n,r]of Object.entries(e)){let s=Tn(n,r);s&&(t[n.replace(/\\/g,"/")]=s)}return t}function Qr(e,t){let n=[],r=/export\s+(?:abstract\s+)?class\s+([A-Za-z_][A-Za-z0-9_]*)\s*(?:extends\s+[^{]+)?(?:implements\s+[^{]+)?\{/g,s;for(;(s=r.exec(t))!==null;){let i=s[1],a=s.index+s[0].length,o=1,d=a;for(;d<t.length&&o>0;){let _=t[d];_==="{"?o+=1:_==="}"&&(o-=1),d+=1}let u=t.slice(a,d-1),g=u.split(`
|
|
10
|
+
`).length;r.push({file:e.path,symbol:i,capability:u,evidence:{kind:"import",file:e.path,line:g,excerpt:s.excerpt}});continue}let o=e.content.slice(0,s.offset).split(`
|
|
11
|
+
`).length,a={kind:"import",file:e.path,line:o,excerpt:s.excerpt},d=Wi(e.path,i,t);n.push({from:e.path,specifier:i,to:d?.path??null,resolution:d?"resolved":"unresolved",fromLayer:e.layer,toLayer:d?.layer??null,evidence:a})}return{edges:n,capabilityUses:r}}function Wi(e,t,n){let r=e.split("/");r.pop();for(let i of t.split("/"))i==="."||i===""||(i===".."?r.pop():r.push(i));let s=r.join("/");for(let i of[s,`${s}.ts`,`${s}.tsx`,`${s}.mts`,`${s}.cts`,`${s}/index.ts`,`${s}/index.tsx`]){let o=n.get(i);if(o)return o}}function Jr(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let s=ee(t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});s&&n.push({ruleId:`layer-dependency:${s.from}->${s.to}`,message:s.message??`${s.from} must not depend on ${s.to}.`,edge:r,evidence:r.evidence})}return n}var Ji={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 Zi(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}function Xi(e,t){return Zi(e,t)?M(x(Ot({config:e,arkRules:t,warnings:[]}))):M(x(e))}function Xe(e,t,n){let r=typeof e=="string"?Rt(e,t):Ue(e,t),s=n?.arkRules??le();return{...r,arkRules:s,policyHash:Xi(r.config,s)}}function _n(e){let t=Xe(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=Xe(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=Mt(t.config,n.config,{baseArkRules:t.arkRules,candidateArkRules:n.arkRules,candidateInvariantCoverage:e.candidateInvariantCoverage}),s=r.findings.filter(a=>a.classification==="weakening"||a.classification==="judgment-required").map(a=>a.id).sort(),i=s.length>0,o=i&&$t(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:s});return{schemaVersion:r.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:r.classification,findings:r.findings,blockingFindingIds:s,requiresAcknowledgement:i,acknowledged:o,valid:!i||o}}function xe(e){let t=e.files.map(m=>{let c=Ae(m.path);return{path:c,content:m.content,contentHash:M(m.content),layer:Q(c,e.contract.config.layers)??null}}).sort((m,c)=>m.path.localeCompare(c.path)),n=new Map(t.map(m=>[m.path,m])),r=[],s=[];for(let m of t){let c=Wr(m,n);r.push(...c.edges),s.push(...c.capabilityUses)}let i=Jr(r,e.contract.config),o=new Map(e.contract.config.layers.map(m=>[m.name,m])),a=new Map(e.contract.config.layers.map(m=>[m.name,new Set(be(m))]));for(let m of s){let c=n.get(m.file)?.layer;if(!c)continue;let l=o.get(c),p=ie(m.symbol,l?.forbiddenGlobals??[]);if(p){i.push({ruleId:"FORBIDDEN_GLOBAL",message:`${c} must not use module "${m.symbol}" because it is the import form of forbidden global "${p}".`,symbol:m.symbol,evidence:m.evidence});continue}a.get(c)?.has(m.capability)&&i.push({ruleId:"CAPABILITY_VIOLATION",message:`${c} denies the ${m.capability} capability; found import of "${m.symbol}".`,capability:m.capability,symbol:m.symbol,evidence:m.evidence})}let d=t.length===0?"complete":"partial",u=d==="complete"?[]:[{...Ji}],g={schemaVersion:Ct,policyHash:e.contract.policyHash,compilerOptionsHash:M(x(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(m=>m.name),edges:r,capabilityUses:s,violations:i};return{mode:"lexical-compatibility",completeness:d,completenessReasons:u,valid:d==="complete"&&i.length===0,ir:g}}function Qe(e){let t=new Map(e.files.map(n=>[Ae(n.path),n]));for(let n of e.changes){let r=Ae(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return xe({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}function xn(e){let t=`${e.evidence.file}:${e.evidence.line}`;if(!e.edge)return`${e.ruleId} at ${t}: ${e.message}`;let n=e.edge.to??e.edge.specifier;return`${e.ruleId} at ${t}: ${e.edge.from} imports ${n}. ${e.message}`}function Dt(e){let t=0,n=new Map,r=new Map,s=new Set,i=[],o=[],a=d=>{n.set(d,t),r.set(d,t),t+=1,i.push(d),s.add(d);for(let m of[...e.get(d)??[]].sort())e.has(m)&&(n.has(m)?s.has(m)&&r.set(d,Math.min(r.get(d)??0,n.get(m)??0)):(a(m),r.set(d,Math.min(r.get(d)??0,r.get(m)??0))));if(r.get(d)!==n.get(d))return;let u=[],g;do{if(g=i.pop(),g===void 0)break;s.delete(g),u.push(g)}while(g!==d);u.length>1&&o.push(u.sort())};for(let d of[...e.keys()].sort())n.has(d)||a(d);return o.sort((d,u)=>d[0]<u[0]?-1:d[0]>u[0]?1:0).map(d=>({ruleId:"CIRCULAR_DEPENDENCY",file:d[0],line:1,target:d.join(" \u2192 "),message:`Circular dependency among ${d.length} files: ${d.join(" \u2192 ")} \u2192 ${d[0]}.`,cycleKind:"value"}))}function Ie(e){let t=e.contentViolations.map(i=>({...i})),n=(e.warnings??[]).map(i=>({...i})),r=new Map(e.files.map(i=>[i,new Set]));for(let i of e.edges){if(i.to&&i.to!==i.from&&!i.typeOnly&&r.has(i.from)&&r.get(i.from)?.add(i.to),!i.to||!i.fromLayer||!i.toLayer)continue;let o=ee(e.rules,i.fromLayer,i.toLayer,{fromPath:i.from,toPath:i.to,layers:e.config.layers});if(!o)continue;let a=!!o.peerIsolation,d=!a&&!!(i.typeOnly||i.namedBindingsTypeOnly),u=o.message??(a?`${i.fromLayer} must not ${i.kind} another slice of ${i.toLayer} (${i.from} \u2192 ${i.to}). Extract shared code or use events/ports across slices.`:`${i.fromLayer} must not ${i.kind} ${i.toLayer}.`);t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:i.from,line:i.line,fromLayer:i.fromLayer,toLayer:i.toLayer,target:i.to,...i.typeOnly?{typeOnly:!0}:{},...i.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...i.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...i.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!a&&i.portProofEligible?{portProofEligible:!0}:{},...i.kind?{edgeKind:i.kind}:{},...a?{peerIsolation:!0}:{},message:d?`${u} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:u,...d?{failsStrict:!1,severity:"warning"}:{}})}let s=String(e.config.cyclePolicy??"strict").toLowerCase();if(s!=="off"){let i=Dt(r);s==="soft"||s==="framework-soft"?n.push(...i.map(o=>({...o,message:`${o.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...i)}return{violations:t,warnings:n,safety:e.safety}}var Qi=["no-anemic-model"];function Zr(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function eo(e){let t="";for(let r=0;r<e.length;r+=1){let s=e[r];if(s==="\\"&&r+1<e.length){let i=e[r+1];if("*?{}[],".includes(i)||i==="\\"){t+="\\"+i,r+=1;continue}t+="/";continue}t+=s}let n="";for(let r=0;r<t.length;r+=1){let s=t[r];s==="\\"&&r+1<t.length?(n+=Zr(t[r+1]),r+=1):s==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":s==="?"?n+="[^/]":n+=Zr(s)}return new RegExp(`^${n}$`)}function et(e,t){return!t||t.length===0?!0:t.some(n=>eo(n).test(e))}function to(e){return Qi.includes(e)}function Xr(e){return e.mode==="enforced"&&!to(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}function Oe(e,t,n,r=1){let{severity:s,failsStrict:i}=Xr(e);return{ruleId:"ARKRULE_STRUCTURE",code:e.sensor,message:n,file:t,line:r,fromLayer:e.provenance.layer,arkruleId:e.id,arkruleSource:e.provenance.sourceFile,severity:s,sensor:e.sensor,failsStrict:i}}function On(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}function Ht(e,t,n){return t.filter(r=>!(!r.exported||!et(r.file,e.appliesTo)||!On(r.file,e,n)))}function no(e,t,n){let r=[];for(let s of Ht(e,t,n))(s.hasPublicSetters||s.hasPublicMutableFields)&&r.push(Oe(e,s.file,`Exported class ${s.className} exposes public mutable state (sensor aggregate-private-state).`));return r}function ro(e,t,n){let r=[];for(let s of Ht(e,t,n))if(s.hasPublicConstructor&&!s.hasStaticFactory){if(!(s.hasPublicMutableFields||s.hasPublicSetters||(s.mutatingMethods?.length??0)>0))continue;r.push(Oe(e,s.file,`Exported class ${s.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}return r}function so(e,t,n){let r=[];for(let s of Ht(e,t,n))for(let i of s.mutatingMethods)i.referencesGuardOrPublish||r.push(Oe(e,s.file,`Mutating method ${s.className}.${i.name} does not reference a guard or publish symbol (sensor domain-event-on-mutation).`));return r}function io(e,t){let n=[];for(let r of t.files)et(r,e.appliesTo)&&On(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}function oo(e,t){let n=[];for(let r of t.files)et(r,e.appliesTo)&&On(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}function ao(e,t,n){let r=[];for(let s of Ht(e,t,n))if(s.dataOnly===!0){let i=Oe(e,s.file,`Exported type ${s.className} looks data-only / anemic (sensor no-anemic-model; advisory only).`);r.push({...i,severity:"warning",failsStrict:!1})}return r}function Vt(e){if(!e.arkRules.structure.length)return[];let t=[];for(let n of e.arkRules.structure)switch(n.sensor){case"aggregate-private-state":t.push(...no(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...ro(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...so(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...io(n,e));break;case"thin-adapter":t.push(...oo(n,e));break;case"no-anemic-model":t.push(...ao(n,e.classShapes,e.layerForFile));break;case"invariant-coverage":break;default:break}return t.sort((n,r)=>n.file.localeCompare(r.file)||n.arkruleId.localeCompare(r.arkruleId)||n.message.localeCompare(r.message))}function jt(e,t){let n=[],r=t.map(s=>s.replace(/\\/g,"/"));for(let s of e.structure){if(!s.appliesTo||s.appliesTo.length===0||r.some(d=>et(d,s.appliesTo)))continue;let{severity:o,failsStrict:a}=Xr(s);n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule structure "${s.id}" appliesTo matched zero governed files (patterns: ${s.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:s.provenance.sourceFile,line:1,fromLayer:s.provenance.layer,arkruleId:s.id,arkruleSource:s.provenance.sourceFile,severity:o,sensor:s.sensor,failsStrict:a})}for(let s of e.invariants??[]){if(!s.appliesTo||s.appliesTo.length===0||r.some(a=>et(a,s.appliesTo)))continue;let o=s.mode==="enforced";n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule invariant "${s.id}" appliesTo matched zero governed files (patterns: ${s.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:s.provenance.sourceFile,line:1,fromLayer:s.provenance.layer,arkruleId:s.id,arkruleSource:s.provenance.sourceFile,severity:o?"error":"warning",sensor:"invariant-coverage",failsStrict:o})}return n.sort((s,i)=>s.file.localeCompare(i.file)||s.arkruleId.localeCompare(i.arkruleId)||s.message.localeCompare(i.message))}var lo=/\bfrom\s+['"](?:@?prisma\/client|@supabase\/|drizzle-orm|typeorm|knex|mongodb|pg|mysql2|better-sqlite3|ioredis|redis)['"]|require\(\s*['"](?:@?prisma\/client|pg|knex|typeorm)/,co=/\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*=)/,po=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,uo=/\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*=/,fo=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function Tn(e,t){if(!t||t.length<40)return null;let n=t.match(new RegExp(uo.source,"g"))??[],r=t.match(new RegExp(fo.source,"g"))??[],s=(t.match(/\bif\s*\(/g)??[]).length,i=(t.match(/\bswitch\s*\(/g)??[]).length,o=n.length>=2||n.length>=1&&r.length>=2||r.length>=3&&s+i>=6,a=lo.test(t),d=co.test(t)||po.test(t),u=n.length>=1||r.length>=2,g=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),m=a&&u||d&&u||a&&g&&(s>=4||n.length>=1)||d&&a;return!o&&!m?null:{...o?{orchestrationHeavy:!0}:{},...m?{adapterThick:!0}:{}}}function Ut(e){let t={};for(let[n,r]of Object.entries(e)){let s=Tn(n,r);s&&(t[n.replace(/\\/g,"/")]=s)}return t}function Qr(e,t){let n=[],r=/export\s+(?:abstract\s+)?class\s+([A-Za-z_][A-Za-z0-9_]*)\s*(?:extends\s+[^{]+)?(?:implements\s+[^{]+)?\{/g,s;for(;(s=r.exec(t))!==null;){let i=s[1],o=s.index+s[0].length,a=1,d=o;for(;d<t.length&&a>0;){let _=t[d];_==="{"?a+=1:_==="}"&&(a-=1),d+=1}let u=t.slice(o,d-1),g=u.split(`
|
|
12
12
|
`).map(_=>/^\s*\/\//.test(_)||/^\s*\/\*|\*\//.test(_)?_:_.replace(/(?:public\s+|protected\s+)?readonly\s+[a-zA-Z_][a-zA-Z0-9_]*\s*(?::[^=;]+)?(?:=\s*[^;]+)?[;,]?/g,"").replace(/(?:^|[\s;{])readonly\s+[a-zA-Z_][a-zA-Z0-9_]*\s*(?::[^=;]+)?(?:=\s*[^;]+)?[;,]?/g," ")).join(`
|
|
13
13
|
`),m=/(?:^|\n)\s*(?:public\s+)?[a-zA-Z_][a-zA-Z0-9_]*\s*[:=]/m.test(g.replace(/(?:public\s+|private\s+|protected\s+|static\s+|async\s+|get\s+|set\s+)/g,""))&&/(?:^|\n)\s*(public\s+)?(?!constructor|static|get|set|private|protected|readonly)[a-zA-Z_][a-zA-Z0-9_]*\s*[:=]/m.test(g),c=/(?:^|\n)\s*public\s+(?!static|async|get|set|constructor|readonly)[a-zA-Z_]/.test(g)||/(?:^|[\n;])\s*[a-zA-Z_][a-zA-Z0-9_]*\s*:\s*[^=;\n]+[;=]/m.test(g.split(`
|
|
14
14
|
`).filter(_=>!/^\s*(private|protected|static|constructor|get |set |async |\/)/.test(_)).join(`
|
|
15
|
-
`)),l=/(?:^|[\n;{])\s*(?:public\s+)?set\s+[a-zA-Z_]/.test(u),p=/(?:^|[\n;{])\s*private\s+constructor\s*\(/.test(u),y=/(?:^|[\n;{])\s*(?:public\s+)?constructor\s*\(/.test(u)&&!p,I=/(?:^|[\n;{])\s*static\s+(?:async\s+)?(?:create|of|from|parse|build|make|new)\s*[<(]/.test(u)||/(?:^|[\n;{])\s*static\s+(?:async\s+)?[A-Za-z_][A-Za-z0-9_]*\s*\([^)]*\)\s*:\s*[A-Za-z_]/.test(u),R=[],f=new Set(["if","match","when"]),h=/(?:^|\n)\s*(?:public\s+|private\s+|protected\s+|async\s+)*(?!constructor|get|set|static)([a-zA-Z_][a-zA-Z0-9_]*)\s*\([^)]*\)\s*(?::\s*[^{]+)?\{/g,S;for(;(S=h.exec(u))!==null;){let _=S[1];if(f.has(_))continue;let E=S.index+S[0].length,L=1,T=E;for(;T<u.length&&L>0;)u[T]==="{"?L+=1:u[T]==="}"&&(L-=1),T+=1;let j=u.slice(E,T-1);if(!/this\.\w+\s*=/.test(j))continue;let A=/\b(ensureInvariants|assertInvariants|validate|publish|emit|raise|record)\b/.test(j);R.push({name:_,referencesGuardOrPublish:A})}let k=(u.match(/(?:^|\n)\s*(?:public\s+|private\s+|protected\s+)?(?:async\s+)?[a-zA-Z_][a-zA-Z0-9_]*\s*\(/g)??[]).length,N=(g.match(/(?:^|[\n;])\s*(?:public\s+)?(?!constructor|static|get|set|private|protected|readonly)[a-zA-Z_][a-zA-Z0-9_]*\s*[:=]/g)??[]).length,D=k<=1&&N>=2&&(c||m);n.push({file:e,className:i,exported:!0,hasPublicMutableFields:c||m,hasPublicSetters:l,hasPublicConstructor:y,hasStaticFactory:I,mutatingMethods:[...R],dataOnly:D})}return n}function V(e,t,n={}){return{ruleId:e,message:t,...n}}function tt(e){let{config:t,rules:n,files:r,manifest:s}=e,i=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(l=>typeof l!="string"))&&i.push(V("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","dynamicImportAllowlist must be an array of file globs.")),t.safety!==void 0&&(t.safety===null||typeof t.safety!="object"||Array.isArray(t.safety)))i.push(V("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let l of["maxTsSuppressions","maxAnyCasts"]){let p=t.safety[l];p!==void 0&&(!Number.isInteger(p)||p<0)&&i.push(V("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${l} must be a non-negative integer.`))}let a=Array.isArray(t.layers)?t.layers:[],o=Array.isArray(s?.architecture?.layers)?s.architecture.layers:[],d=new Set([...a.map(l=>l.name).filter(Boolean),...o.map(l=>l.name).filter(l=>!!l)]);a.length===0&&i.push(V("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let u=new Set,g=new Set;for(let l of a){if(!l.name){i.push(V("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}u.has(l.name)&&g.add(l.name),u.add(l.name),l.forbiddenGlobals!==void 0&&(!Array.isArray(l.forbiddenGlobals)||l.forbiddenGlobals.some(y=>typeof y!="string"))&&i.push(V("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${l.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:l.name}));let p=Array.isArray(l.patterns)?l.patterns:[];if(p.length===0){i.push(V("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${l.name}" has no file patterns and will never classify files.`,{layer:l.name}));continue}for(let y of p){let I;try{I=pe(y)}catch(R){i.push(V("CONFIG_INVALID_LAYER_PATTERN",`Layer "${l.name}" has an invalid pattern "${y}": ${R instanceof Error?R.message:String(R)}`,{layer:l.name,pattern:y}));continue}!r.some(R=>I.test(R))&&!l.optional&&i.push(V("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${l.name}" pattern "${y}" matched no included files.`,{layer:l.name,pattern:y,failsStrict:!1}))}}for(let l of g)i.push(V("CONFIG_DUPLICATE_LAYER",`Layer "${l}" is configured more than once.`,{layer:l}));if(d.size>0)for(let l of n??[])l.from&&!d.has(l.from)&&i.push(V("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${l.from}".`,{fromLayer:l.from,toLayer:l.to})),l.to&&!d.has(l.to)&&i.push(V("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${l.to}".`,{fromLayer:l.from,toLayer:l.to}));let m=new Set;if(a.length>1)for(let l of r){let p=-1,y=[];for(let I of a)for(let R of I.patterns??[]){if(!pe(R).test(l))continue;let f=mn(R,l);f>p?(p=f,y=[I.name]):f===p&&!y.includes(I.name)&&y.push(I.name)}y.length>1&&m.add([...y].sort().join(" + "))}m.size>0&&i.push(V("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...m].join(", ")}.`,{pairs:[...m]}));let c=r.filter(l=>!Q(l,a));return c.length>0&&i.push(V("CONFIG_UNCLASSIFIED_FILES",`${c.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:c.length,samples:c.slice(0,5)})),i}function fa(e,t){return t.some(n=>{try{return pe(n).test(e)}catch{return!1}})}function ma(e,t){let n=e.contract.config.safety??{},r=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,s=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,i=e.contract.config.dynamicImportAllowlist??[],a=t.safetyUses.filter(y=>y.kind==="ts-suppression").map(({file:y,line:I})=>({file:y,line:I})),o=t.safetyUses.filter(y=>y.kind==="any-cast").map(({file:y,line:I})=>({file:y,line:I})),d=t.safetyUses.filter(y=>(y.kind==="dynamic-import"||y.kind==="dynamic-require")&&!fa(y.file,i)).map(y=>({file:y.file,line:y.line,kind:y.kind==="dynamic-require"?"require":"import"})),u=n.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(y=>y.kind==="in-memory-store").map(y=>({file:y.file,line:y.line,store:y.symbol??"in-memory store"})),g=n.allowDisabledPeerIsolation===!0?[]:(e.contract.config.rules??[]).filter(y=>y.peerIsolation===!1||y.allowed===!1&&!!y.from&&y.from===y.to&&y.peerIsolation!==!0).map(y=>({from:y.from,to:y.to})),m={tsSuppressions:a,anyCasts:o,nonLiteralDynamicImports:d,inMemoryProductionStores:u,disabledPeerIsolationRules:g,thresholds:{maxTsSuppressions:r,maxAnyCasts:s}},c=[],l=d.filter(y=>y.kind==="import");if(l.length>0){let y=l[0];c.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:y.file,line:y.line,message:`${l.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let p=d.filter(y=>y.kind==="require");if(p.length>0){let y=p[0];c.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:y.file,line:y.line,message:`${p.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(a.length>r){let y=a[0];c.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:y.file,line:y.line,message:`${a.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${r}).`})}if(o.length>s){let y=o[0];c.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:y.file,line:y.line,message:`${o.length} explicit any cast(s) exceed safety.maxAnyCasts (${s}).`})}if(u.length>0){let y=u[0];c.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:y.file,line:y.line,message:`${u.length} ArkGate InMemory store risk(s) appear in governed production source. Provide durable stores or set safety.allowInMemory only for an explicitly ephemeral service.`})}return g.length>0&&c.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${g.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:m,warnings:c}}function ga(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}function es(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return bn(e,n.length>0?n:In.map(r=>({name:r.layer,prefixes:r.prefixes})))}function ya(e,t,n){let r=[],s=new Map(e.contract.config.layers.map(i=>[i.name,i]));for(let i of t.ambientUses){let a=n.get(i.file);!a||!ga(i.symbol,s.get(a)?.forbiddenGlobals??[])||r.push({ruleId:"FORBIDDEN_GLOBAL",file:i.file,line:i.line,fromLayer:a,target:i.symbol,message:`${a} must not use the ambient global "${i.symbol}".`})}for(let i of t.capabilityUses){let a=n.get(i.file);if(!a)continue;let o=s.get(a),d=o?.forbiddenGlobals??[],u=i.source==="import-based"?t.dependencies.find(g=>g.from===i.file&&g.line===i.line&&g.specifier===i.symbol&&!g.typeOnly)?.kind:void 0;if(!(i.source==="ambient-global"&&$e(i.symbol,d))){if(i.source==="import-based"){let g=ie(i.symbol,d);if(g){r.push({ruleId:"FORBIDDEN_GLOBAL",file:i.file,line:i.line,fromLayer:a,target:i.symbol,...u?{edgeKind:u}:{},message:`${a} must not use module "${i.symbol}" because it is the import form of forbidden global "${g}".`});continue}}be(o).includes(i.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:i.file,line:i.line,fromLayer:a,target:i.symbol,capability:i.capability,...u?{edgeKind:u}:{},message:i.source==="import-based"?`${a} denies the ${i.capability} capability; found import of "${i.symbol}".`:`${a} denies the ${i.capability} capability; found ambient "${i.symbol}".`})}}for(let i of t.publishCalls){let a=n.get(i.file);if(!a)continue;for(let d of Fe({publishCall:!0,rawIntentName:i.rawIntentName,objectHasIntent:i.objectHasIntent,arkPublishCandidate:i.arkPublishCandidate,hasSource:i.hasSource}))r.push({ruleId:d.ruleId,file:i.file,line:i.line,...d.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:a}:{},message:d.message});if(!i.sourceIntent)continue;let o=es(i.sourceIntent,e.contract);!o||o===a||r.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:i.file,line:i.line,fromLayer:a,toLayer:o,target:i.sourceIntent,message:`Publish source "${i.sourceIntent}" resolves to ${o}, but the publishing file is classified as ${a}.`})}for(let i of t.intentReferences){let a=n.get(i.file);if(!a)continue;let o=es(i.intent,e.contract);if(!o)continue;let d=ee(e.contract.config.rules,a,o);d&&r.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:i.file,line:i.line,fromLayer:a,toLayer:o,target:i.intent,message:d.message??`${a} must not reference ${o} intent ${i.intent}.`})}return r}function ha(e){let{facts:t}=e,n=ke(e.contract.config),r=t.evidenceRequirementsHash===n,s=r?t.completeness:"unavailable",i=r?t.completenessReasons:[...t.completenessReasons,{code:"EVIDENCE_REQUIREMENTS_MISMATCH",message:"Resolved facts were collected for different policy-controlled evidence requirements."}].sort((A,B)=>{let Ne=`${A.code}\0${A.file??""}\0${A.message}`,we=`${B.code}\0${B.file??""}\0${B.message}`;return Ne<we?-1:Ne>we?1:0}),a=t.files.map(A=>({...A,layer:Q(A.path,e.contract.config.layers)??null})),o=new Map(a.map(A=>[A.path,A.layer])),d=t.dependencies.map(A=>{let B=A.target?o.get(A.target)??Q(A.target,e.contract.config.layers):void 0;return{from:A.from,fromLayer:o.get(A.from)??null,...A.resolution==="resolved-project"&&A.target?{to:A.target,...B?{toLayer:B}:{}}:{},line:A.line,kind:A.kind,typeOnly:A.typeOnly,...A.targetTypeOnlyExports?{targetTypeOnlyExports:A.targetTypeOnlyExports}:{},...A.sourcePureTypeModule?{sourcePureTypeModule:A.sourcePureTypeModule}:{},...A.namedBindingsTypeOnly?{namedBindingsTypeOnly:A.namedBindingsTypeOnly}:{},...A.portProofEligible?{portProofEligible:A.portProofEligible}:{}}}),u=tt({config:e.contract.config,rules:e.contract.config.rules,files:a.map(A=>A.path)}),g=ma(e,t),m=e.contract.arkRules??le(),c=a.map(A=>A.path),p={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?Ut(e.coverageInputs.fileContents):{},...e.fileHints??{}},y=[...Vt({arkRules:m,classShapes:e.contract.classShapes??t.classShapes??[],files:c,layerForFile:A=>o.get(A)??Q(A,e.contract.config.layers),fileHints:p}),...jt(m,c)],I=y.filter(A=>A.failsStrict).map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,arkruleId:A.arkruleId,arkruleSource:A.arkruleSource,nextAction:A.ruleId==="ARKRULE_SCOPE_EMPTY"?`Fix appliesTo globs for ${A.arkruleId} in ${A.arkruleSource} so they match governed files, or remove the rule.`:`Fix the structure or invariant for ${A.arkruleId} (declared in ${A.arkruleSource}), then preflight again.`})),R=y.filter(A=>!A.failsStrict).map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,arkruleId:A.arkruleId,arkruleSource:A.arkruleSource,failsStrict:!1,nextAction:A.ruleId==="ARKRULE_SCOPE_EMPTY"?`Review appliesTo for ${A.arkruleId} in ${A.arkruleSource} (zero-match scope; advisory).`:`Review ArkRule ${A.arkruleId} in ${A.arkruleSource} (advisory).`})),h=(m.invariants?.length??0)>0?Tt({arkRules:m,fileContents:e.coverageInputs?.fileContents??{},testFiles:e.coverageInputs?.testFiles??[],testGlobsMissing:e.coverageInputs?.testGlobsMissing===!0||e.coverageInputs===void 0||(e.coverageInputs.testFiles?.length??0)===0}):{coverage:[],violations:[],partial:!1},S=h.violations.filter(A=>A.failsStrict).map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,arkruleId:A.arkruleId,arkruleSource:A.arkruleSource,nextAction:`Add a test title or declared symbol covering ${A.arkruleId} (declared in ${A.arkruleSource}), then preflight again.`})),k=h.violations.filter(A=>!A.failsStrict).map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,arkruleId:A.arkruleId,arkruleSource:A.arkruleSource,failsStrict:!1,nextAction:`Cover invariant ${A.arkruleId} in ${A.arkruleSource} (advisory / partial).`})),D=h.partial&&h.coverage.some(A=>A.mode==="enforced"&&A.partial)?[{code:"INVARIANT_COVERAGE_PARTIAL",message:"Enforced ArkRules invariant coverage cannot be fully proven (missing test globs or empty test set); reporting partial, never covered."}]:[],_=Ie({config:e.contract.config,rules:e.contract.config.rules,files:a.filter(A=>A.layer).map(A=>A.path),contentViolations:[...ya(e,t,o),...I,...S],edges:d,warnings:[...u,...g.warnings,...R,...k],safety:g.report}),E=s==="complete"&&D.length>0?"partial":s,L=E==="complete"?i:[...i,...D].sort((A,B)=>{let Ne=`${A.code}\0${A.file??""}\0${A.message}`,we=`${B.code}\0${B.file??""}\0${B.message}`;return Ne<we?-1:Ne>we?1:0}),T=_.violations.filter(A=>A.failsStrict!==!1),j=E==="complete"&&T.length===0,de=j&&_.warnings.every(A=>A.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:E,completenessReasons:L,valid:j,strictValid:de,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:g.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:a,layers:e.contract.config.layers.map(A=>A.name),edges:d,capabilityUses:t.capabilityUses,violations:_.violations,warnings:_.warnings}}}function Te(e){return ha({contract:e.contract,facts:se(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints})}function Gt(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return e.typeOnly||e.targetTypeOnlyExports||e.namedBindingsTypeOnly?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":e.peerIsolation?"Extract the shared dependency to a shared layer, test at the public interface, then preflight again.":`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, test at the public interface, then preflight again.`;case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, test at the public interface, then preflight again.`;case"CAPABILITY_VIOLATION":return`Define a ${String(e.capability??"capability")} port in ${e.fromLayer??"the walled layer"}, bind the implementation outside it, test at the public interface, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, test at the public interface, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";case"ARKRULE_STRUCTURE":case"ARKRULE_INVARIANT":case"INVARIANT_UNCOVERED":return`Fix the structure or invariant for ${typeof e.arkruleId=="string"&&e.arkruleId.length>0?e.arkruleId:"the ArkRule"} (declared in ${typeof e.arkruleSource=="string"&&e.arkruleSource.length>0?e.arkruleSource:"arkrules/<Layer>.json"}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`;default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}function ts(e){return M(x(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}function Pn(e){let t=xe(e),n=new Map(t.ir.files.map(p=>[p.path,p])),r=[],s=new Set,i=[];for(let p of e.changes){let y=p.path.replace(/\\/g,"/"),I=Ae(p.path);if(!I||I===".."||I.startsWith("../")||y.startsWith("/")||/^[A-Za-z]:\//.test(y)||y.includes("\0")){i.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(s.has(I)){i.push({ruleId:"DUPLICATE_CHANGE_PATH",file:I,line:1,message:`The atomic change set contains more than one operation for ${I}.`});continue}s.add(I),"delete"in p&&p.delete&&!n.has(I)&&i.push({ruleId:"DELETE_TARGET_MISSING",file:I,line:1,message:`Cannot delete ${I} because it is not present in the supplied base tree.`}),r.push("delete"in p&&p.delete?{path:I,delete:!0}:{path:I,content:"content"in p?p.content:""})}e.changes.length===0&&i.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let a=Qe({...e,changes:r}),o=new Map(a.ir.files.map(p=>[p.path,p])),d=a.ir.violations.filter(p=>p.ruleId==="CAPABILITY_VIOLATION"||p.ruleId==="FORBIDDEN_GLOBAL").map(p=>{let y=o.get(p.evidence.file)?.layer;return{ruleId:p.ruleId,file:p.evidence.file,line:p.evidence.line,target:p.symbol,...p.capability?{capability:p.capability}:{},...y?{fromLayer:y}:{},edgeKind:"import",message:p.message}}),u=Ie({config:e.contract.config,rules:e.contract.config.rules,files:a.ir.files.map(p=>p.path),contentViolations:d,edges:a.ir.edges.filter(p=>!!p.fromLayer).map(p=>({from:p.from,fromLayer:p.fromLayer,...p.to?{to:p.to}:{},...p.toLayer?{toLayer:p.toLayer}:{},line:p.evidence.line,kind:"import",...p.typeOnly?{typeOnly:!0}:{},...p.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),g=r.map(p=>{let y=Ae(p.path),I=n.get(y),R=o.get(y);return{path:y,operation:"delete"in p&&p.delete?"delete":I?"update":"create",...I?{beforeContentHash:I.contentHash}:{},...R?{candidateContentHash:R.contentHash}:{}}}).sort((p,y)=>p.path.localeCompare(y.path)),m=[...i,...u.violations].map(p=>({...p,nextAction:Gt(p)})),c=m.filter(p=>p.failsStrict!==!1),l=e.changeMap?ge({changeMap:e.changeMap,changes:g,baseDependencies:t.ir.edges.flatMap(p=>p.to?[{from:p.from,to:p.to}]:[]),candidateDependencies:a.ir.edges.flatMap(p=>p.to?[{from:p.from,to:p.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&a.valid&&c.length===0&&(l?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:a.ir.compilerOptionsHash,baseTreeHash:ts(t.ir.files),candidateTreeHash:ts(a.ir.files),baseCompleteness:t.completeness,candidateCompleteness:a.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:a.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...l?{convergence:l}:{},changes:g,violations:m,warnings:u.warnings}}function Aa(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let s of t.split("/"))if(!(!s||s==="."))if(s===".."){if(n.length===0)return;n.pop()}else n.push(s);let r=n.join("/");return r&&r===t?r:void 0}function Ia(e,t){return[["resolverIdentity",e.resolverIdentity,t.resolverIdentity],["compilerIdentity",e.compilerIdentity,t.compilerIdentity],["evidenceRequirementsHash",e.evidenceRequirementsHash,t.evidenceRequirementsHash],["projectPackageName",e.projectPackageName??"",t.projectPackageName??""]].filter(([,r,s])=>r!==s).map(([r,s,i])=>({ruleId:"FACTS_IDENTITY_MISMATCH",file:"<change-set>",line:1,field:r,before:s,candidate:i,message:`Base and candidate facts must use the same ${r}.`}))}function ba(e,t,n,r){let s=n.get(t),i=r.get(t);return{path:t,operation:"delete"in e&&e.delete?"delete":s?"update":"create",...s?{beforeContentHash:s.contentHash}:{},...i?{candidateContentHash:i.contentHash}:{}}}function Ln(e){let t=se(e.baseFacts),n=se(e.candidateFacts),r=Te({contract:e.contract,facts:t}),s=Te({contract:e.contract,facts:n}),i=new Map(t.files.map(l=>[l.path,l])),a=new Map(n.files.map(l=>[l.path,l])),o=Ia(t,n),d=new Map,u=[];for(let l of e.changes){let p=Aa(l.path);if(!p){o.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(d.has(p)){o.push({ruleId:"DUPLICATE_CHANGE_PATH",file:p,line:1,message:`The atomic change set contains more than one operation for ${p}.`});continue}d.set(p,l);let y=i.get(p),I=a.get(p);if("delete"in l&&l.delete)y||o.push({ruleId:"DELETE_TARGET_MISSING",file:p,line:1,message:`Cannot delete ${p} because it is not present in the supplied base facts.`}),I&&o.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:p,line:1,message:`Candidate facts still contain deleted file ${p}.`});else{let R="content"in l?l.content:"",f=M(R);I?I.contentHash!==f&&o.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:p,line:1,expectedContentHash:f,candidateContentHash:I.contentHash,message:`Candidate facts for ${p} do not match the declared content.`}):o.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:p,line:1,message:`Candidate facts do not contain changed file ${p}.`})}u.push(ba(l,p,i,a))}e.changes.length===0&&o.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});for(let l of new Set([...i.keys(),...a.keys()])){if(d.has(l))continue;let p=i.get(l),y=a.get(l);p&&y&&x(p)===x(y)||o.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:l,line:1,message:`Candidate facts change ${l}, but the atomic change set does not declare it.`})}let g=e.changeMap?ge({changeMap:e.changeMap,changes:u,baseDependencies:r.ir.edges.flatMap(l=>l.to?[{from:l.from,to:l.to}]:[]),candidateDependencies:s.ir.edges.flatMap(l=>l.to?[{from:l.from,to:l.to}]:[])}):void 0,m=[...o,...s.ir.violations].map(l=>({...l,nextAction:Gt(l)})),c=m.filter(l=>l.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&s.strictValid&&c.length===0&&(g?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,resolverIdentity:n.resolverIdentity,compilerIdentity:n.compilerIdentity,compilerOptionsHash:n.compilerOptionsHash,tsconfigHash:n.tsconfigHash,baseCompilerOptionsHash:t.compilerOptionsHash,candidateCompilerOptionsHash:n.compilerOptionsHash,baseTsconfigHash:t.tsconfigHash,candidateTsconfigHash:n.tsconfigHash,evidenceRequirementsHash:n.evidenceRequirementsHash,baseFactsHash:t.factsHash,candidateFactsHash:n.factsHash,baseTreeHash:t.candidateTreeHash,candidateTreeHash:n.candidateTreeHash,baseCompleteness:r.completeness,candidateCompleteness:s.completeness,baseCompletenessReasons:r.completenessReasons,candidateCompletenessReasons:s.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...g?{convergence:g}:{},changes:u.sort((l,p)=>l.path<p.path?-1:l.path>p.path?1:0),violations:m,warnings:s.ir.warnings}}function Bt(e,t){return e.slice(0,t).split(`
|
|
16
|
-
`).length}function ns(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function ss(e,t){return e.some(n=>{let r=n.trim().replace(/\.+$/,"");return t.some(s=>r===s||r.startsWith(`${s}.`))})}function rs(e,t=[]){return/domain|entity|aggregate|model/i.test(e)||ss(t,["Domain"])}function Sa(e,t=[]){return/application|orchestration|presentation|adapter|framework|interface|delivery|transport|inbound|controller/i.test(e)||ss(t,["Application","Orchestration","Presentation","Adapter","Interface","Delivery","Transport"])}function Ra(e){return/(?:^|\/)(?:tests?|__tests__|fixtures?|testdata|mocks?|stubs?|examples?|samples?|seeds?|seeders?|migrations?|excluded|exclusions?)(?:\/|$)/i.test(e)||/(?:^|\/)[^/]*\.(?:test|spec|fixture|mock|stub|seed|seeder)\.[^/]+$/i.test(e)||/(?:^|\/)(?:seed|seeder|fixture|mock|stub)\.[^/]+$/i.test(e)}function is(e){let t=[],n=0,r=new Map(Object.entries(e.fileLayers??{}).map(([d,u])=>[ns(d),u])),s=new Map((e.layerContexts??[]).map(d=>[d.name,d.intentPrefixes??[]])),i=(e.layerContexts??[]).find(d=>rs(d.name,d.intentPrefixes))?.name??"DomainModel";for(let[d,u]of Object.entries(e.fileContents).sort(([g],[m])=>g.localeCompare(m))){let g=ns(d);if(Ra(g)||/GENERATED FILE\s+[—-]\s+do not edit by hand/i.test(u.slice(0,320)))continue;let m=r.has(g),c=r.get(g),l=c?s.get(c)??[]:[],p=/(?:^|\/)(?:components|ui|layouts|styles|hooks|theme|tokens|i18n|locales?)(?:\/|$)/i.test(g)||/(?:^|\/)(?:src\/)?(?:app|pages)\/.+\.(?:tsx|jsx)$/i.test(g)&&/(?:page|layout|loading|error|template|default)\.(?:tsx|jsx)$/i.test(g),y=/(?:^|\/)(?:app|pages)(?:\/[^/]+)*\/api(?:\/|$)/i.test(g),I=/(?:^|\/)actions?(?:\/|\.|$)/i.test(g)||/['"]use server['"]/.test(u),R=/controller|handler|resolver/i.test(d)||y||I||/route\.(?:ts|js|tsx|jsx)$/i.test(g)&&!p||/@(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),f=m?!!(c&&Sa(c,l)&&R):R,h=m?!!(c&&rs(c,l)):/domain|entity|aggregate|model/i.test(d),S=!m||h||f;if(f&&!p){let E=/\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,L;for(;(L=E.exec(u))!==null;)n+=1,t.push({id:`inv-val-${n}`,kind:"validation-in-controller",file:d,line:Bt(u,L.index),message:"Business validation appears in a controller/handler \u2014 extract an invariant or Domain rule.",confidence:"direct-evidence",governedLayer:c,suggestedArkRule:{layer:i,invariantId:`INV-EXTRACT-${n}`,sensor:"invariant-coverage"},neverMechanicalSafe:!0})}let k=/\b(const|let)\s+([A-Z][A-Z0-9_]{2,})\s*=\s*(\d{2,}|['"][^'"]{8,}['"])/g,N,D=E=>/^(?: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(E)||/^(?: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(E)||/_(?:ROUTE|PATH|LABEL|TITLE|COLOR|THEME|CLASS|STYLE|ICON|ARIA|MSG|COPY|TIMEOUT|PORT|VERSION|RETRY|DELAY|INTERVAL|TTL|CACHE)$/i.test(E)||/_(?:TIMEOUT(?:_MS)?|MS|BYTES|BUCKET|STORAGE_KEY|WINDOW_MS)$/i.test(E)||/^(?: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(E)||/^(?:FAVORITES_STORAGE|LISTINGS_CACHE|DOCS_PATH|METRICS_INTERVAL)/i.test(E)||/^(?:DEV|DEMO|SEED|FIXTURE)_[A-Z0-9_]+$/i.test(E)||/^(?:PG|POSTGRES|OID)_[A-Z0-9_]+$/i.test(E)||/_(?:OID|OIDS)$/i.test(E)||/^(?:INT2|INT4|INT8|FLOAT4|FLOAT8|NUMERIC|DATE|TIME|TIMESTAMP|TIMESTAMPTZ|JSON|JSONB|UUID)OID$/i.test(E)||/(?:^|_)(?:SCHEMA|PROTOCOL|RESOLVER|FORMAT)_(?:URL|URI|VERSION|ID|IDENTITY)$/i.test(E),_=(E,L)=>{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(E)||/_(?:MSG|MESSAGE|TEXT|COPY|TOAST|SNACK|ALERT|BANNER|CAPTION|HINT|HELP_TEXT|ERROR_TEXT|EMPTY_TEXT|PLACEHOLDER_TEXT|USER_MESSAGE|FEEDBACK)$/i.test(E))return!0;let T=L.replace(/^['"]|['"]$/g,"");return!!(/^['"]/.test(L)&&(/\s/.test(T)||/[.!?…]$/.test(T))&&!/^(?:STATUS|STATE|PHASE|ROLE|TYPE|KIND|ORDER|PAYMENT|CART|INVOICE|POLICY)_[A-Z0-9_]+$/i.test(E))};for(;(N=k.exec(u))!==null;){let E=N[2],L=N[3]??"";!S||D(E)||_(E,L)||p&&!h||/(?:^|\/)(?:integrations?|repos?|clients?|infra(?:structure)?|adapters?)(?:\/|$)/i.test(g)&&!h||(n+=1,t.push({id:`inv-magic-${n}`,kind:"magic-business-constant",file:d,line:Bt(u,N.index),message:`Magic business constant ${E} may belong in a Domain policy or invariant catalog.`,confidence:"heuristic",governedLayer:c,suggestedArkRule:{layer:i,invariantId:`INV-${E}`},neverMechanicalSafe:!0}))}if(h){let E=/export\s+class\s+([A-Za-z_][A-Za-z0-9_]*)\s*\{([^}]{0,800})\}/g,L;for(;(L=E.exec(u))!==null;){let T=L[2]??"",j=(T.match(/\b[a-zA-Z_][a-zA-Z0-9_]*\s*\(/g)??[]).length;(T.match(/:\s*[A-Za-z]/g)??[]).length>=2&&j<=1&&(n+=1,t.push({id:`inv-anemic-${n}`,kind:"anemic-entity",file:d,line:Bt(u,L.index),message:`Class ${L[1]} looks anemic (data-heavy, few behaviors).`,confidence:"heuristic",governedLayer:c,suggestedArkRule:{layer:i,structureId:"no-anemic-model",sensor:"no-anemic-model"},neverMechanicalSafe:!0}))}}if(h&&!(/\.error\.(?:ts|js|tsx|jsx)$/i.test(g)||/(?:^|\/)[^/]*(?:-access)?\.error\./i.test(g)||/(?:^|\/)errors?(?:\/|$)/i.test(g))){let L=/this\.\w+\s*=/g,T;for(;(T=L.exec(u))!==null;){let j=u.lastIndexOf("class ",T.index),de=j>=0?u.indexOf("{",j):-1,A=j>=0&&de>=j&&de<T.index?u.slice(j,de):"";if(/\bextends\s+(?:Error|[A-Za-z_$][A-Za-z0-9_$]*Error)\b/.test(A))continue;let B=u.slice(Math.max(0,T.index-200),T.index+200);if(!/\b(ensureInvariants|assertInvariants|validate|publish|emit)\b/.test(B)){n+=1,t.push({id:`inv-mut-${n}`,kind:"mutation-without-guard",file:d,line:Bt(u,T.index),message:"Domain field mutation without nearby guard/publish call.",confidence:"heuristic",governedLayer:c,suggestedArkRule:{layer:i,structureId:"events-on-mutation",sensor:"domain-event-on-mutation"},neverMechanicalSafe:!0});break}}}}let a=new Set(e.contractedRuleIds??[]);t.sort((d,u)=>+(u.confidence==="direct-evidence")-+(d.confidence==="direct-evidence")||d.file.localeCompare(u.file)||d.line-u.line||d.kind.localeCompare(u.kind)||d.id.localeCompare(u.id));let o=t.filter(d=>d.suggestedArkRule?.invariantId&&a.has(d.suggestedArkRule.invariantId)||d.suggestedArkRule?.structureId&&a.has(d.suggestedArkRule.structureId)).length;return{candidates:t,inventoried:t.length,underContract:o,frozen:(e.frozenKeys??[]).length,notAScore:!0}}function as(e){return{pilot:`Extract rule candidate ${e.id} (${e.kind})`,pilotTarget:e.file,smellId:e.kind,move:`Declare in arkrules/${e.suggestedArkRule?.layer??"DomainModel"}.json, implement pure Domain logic, add covering test.`,doNot:["Do not auto-apply codemods","Do not promote to enforced without coverage evidence","Do not batch multiple extractions"],successSignal:"Doctor reports candidate under contract; gate green with residual honest.",killSwitch:"Stop if extraction requires multi-module redesign without a clear aggregate owner.",neverMechanicalSafe:!0,class:"judgment",next:"Run ark_prepare_change / preflight, then re-doctor."}}var os="1.1";var ls="1.0";var Kt="docs/diagnostics.md",cs="1.0";function b(e,t,n,r,s,i){return{ruleId:e,title:n,why:r,fix:s,docsAnchor:e,category:t,...i?.oftenAdvisory?{oftenAdvisory:!0}:{}}}var nt=Object.freeze([b("LAYER_IMPORT_VIOLATION","layer","Layer import not allowed","A module import (or re-export) crosses a layer edge that ark.config.json does not allow. The architecture contract forbids that dependency direction so outer infrastructure cannot leak into pure or inner layers.","Define a port in the source layer, inject the outer-layer implementation, or move/share the type with `import type` when the edge is type-only \u2014 then preflight again. Do not weaken the layer rule without a hash-bound policy acknowledgement."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("ARKRULE_STRUCTURE","arkrules","ArkRule structure sensor failed","An opt-in ArkRules structure sensor (private state, factory shape, event publish, \u2026) failed on a governed file for a declared arkruleId.","Restore the declared structure for the ArkRule (see arkruleSource), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement."),b("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."),b("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}),b("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).","Add a test title or declared symbol covering the arkruleId, then preflight again. Missing test globs report partial \u2014 never fake green."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("DESIGN_SMELL_REGRESSION","preflight","Design smell regression on base-relative ratchet","Compared to the base ref, the candidate introduces or worsens a blocking design-smell class (e.g. domain-logic-in-ui) under --fail-on-new-smells.","Revert the regression or redesign so the smell does not worsen versus base, then re-run with the same base ref."),b("ANALYSIS_PARSE_INCOMPLETE","analysis","Parse incomplete","Governed source could not be fully parsed; analysis is partial and must not paint green.","Fix syntax/parse errors in governed files (or restore a usable TypeScript host), then re-run. Partial never means pass."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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}),b("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}),b("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}),b("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}),b("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}),b("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}),b("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}),b("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}),b("CONFIG_LAYER_PATTERN_NO_MATCHES","config","Layer pattern matched no files","A layer pattern matched zero included files (often a typo or include mismatch).","Adjust the pattern or include roots so governed files match.",{oftenAdvisory:!0}),b("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}),b("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}),b("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}),b("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}),b("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}),b("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.")]),Nn=new Map(nt.map(e=>[e.ruleId,e])),ds=Object.freeze(nt.map(e=>e.ruleId));function ps(e){return typeof e=="string"&&e.length>0&&Nn.has(e)}function us(e){return typeof e!="string"||e.length===0?!1:Nn.has(e)?!0:e.startsWith("ARKRULE_")}function rt(e){if(!(typeof e!="string"||e.length===0))return Nn.get(e)}function wn(e){return`#${rt(e)?.docsAnchor??e}`}function fs(e){return`${Kt}${wn(e)}`}function ms(){return{schemaVersion:"1.0",docsPath:Kt,codes:nt}}function gs(e){return rt(e)?.fix}function ys(e){return rt(e)?.why}var hs="1.0",Mn="https://unpkg.com/arkgate@4/schemas/ark.status-manifest.schema.json",$n=["full","subset","unavailable"],Fn=["doctor-facts","report-snapshot","none"],it={FACTS_UNAVAILABLE:"FACTS_UNAVAILABLE",FACTS_PARTIAL:"FACTS_PARTIAL",NO_SESSION_SNAPSHOT:"NO_SESSION_SNAPSHOT"},As=/^sha256:[a-f0-9]{64}$/;function Dn(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"||!As.test(r)))return{status:"mismatch",authoritative:!1,code:"INVALID_PROJECT_EXPECTATION",message:"project.expectedProjectId must be a sha256:<64 lowercase hex> identity."};if(n===void 0&&r!==void 0)return e.projectId&&r!==e.projectId?{status:"mismatch",authoritative:!1,expectedProjectId:r,code:"PROJECT_ID_MISMATCH",message:`Expected project id ${r}, but this process is bound to ${e.projectId}.`}:{status:"unverified",authoritative:!1,expectedProjectId:r,message:"project.expectedProjectId matched or could not be compared, but expectedRoot is required for an authoritative workspace binding."};let s=e.expectedRootRelation??"unknown";return s==="outside"?{status:"mismatch",authoritative:!1,expectedRoot:n,expectedProjectId:r,code:"PROJECT_ROOT_MISMATCH",message:`Expected workspace ${n}, but this process is bound to ${e.resolvedRoot}.`}:s==="unknown"?{status:"unverified",authoritative:!1,expectedRoot:n,expectedProjectId:r,message:"Could not prove expectedRoot against the resolved project root (stale or incomplete path evidence)."}:s==="descendant"&&r===void 0?{status:"unverified",authoritative:!1,expectedRoot:n,message:`Expected workspace ${n} is inside this project, but an exact project root is required for the initial authoritative handshake.`}:r!==void 0&&e.projectId&&r!==e.projectId?{status:"mismatch",authoritative:!1,expectedRoot:n,expectedProjectId:r,code:"PROJECT_ID_MISMATCH",message:`Expected project id ${r}, but this process is bound to ${e.projectId}.`}:s==="exact"||s==="descendant"&&r&&r===e.projectId?{status:"matched",authoritative:!0,...n?{expectedRoot:n}:{},...r?{expectedProjectId:r}:{}}:{status:"unverified",authoritative:!1,expectedRoot:n,expectedProjectId:r,message:"Project expectation could not be fully verified."}}function Hn(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"}function Vn(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)."}function jn(e,t,n,r,s){return e.nextActionOverride?.id&&e.nextActionOverride.summary?{id:e.nextActionOverride.id,summary:e.nextActionOverride.summary}:t.status==="mismatch"?{id:"rebind-project-identity",summary:t.message||"Project expectation does not match this process \u2014 call ark_identity / ark status with the correct expectedRoot (and projectId for descendants)."}:t.status==="unverified"&&e.expectation?{id:"complete-identity-handshake",summary:t.message||"Supply project.expectedRoot at the exact project root (and expectedProjectId for descendants) for authoritative status."}:e.resolvedConfigPath?r.verdict==="fail"||(r.activeViolations??0)>0?{id:"fix-active-violations",summary:`Clear ${r.activeViolations??"active"} blocking architecture finding(s), then re-run ark-check (or ark-check --doctor).`}:r.verdict==="incomplete"?{id:"restore-complete-analysis",summary:"Last check was incomplete \u2014 restore TypeScript/analysis inputs and re-run ark-check."}:r.verdict==null&&r.at==null?{id:"run-ark-check",summary:"No last-check snapshot yet \u2014 run ark-check --report (or --doctor) to freeze session evidence."}:n.writePath==="unavailable"?{id:"install-write-path",summary:"Write path is unavailable \u2014 install agent gates for your host (ark start / --install-agent-gates) and keep required CI --strict-merge."}:n.writePath==="advisory"?{id:"keep-ci-merge-hard",summary:"Local write is advisory for this host \u2014 keep a required GitHub status on arkgate-check --strict-merge as the hard merge boundary."}:s.arkRulesLoaded&&(s.frozenResidual??0)>0?{id:"review-arkrules-residual",summary:"ArkRules residual remains frozen \u2014 review inventory debt without claiming a score."}:{id:"stay-enforced",summary:"Contract looks enforceable for this session \u2014 keep writing through the gate and re-check after structural edits."}:{id:"run-ark-start",summary:"No ark.config.json found \u2014 run ark start (preview) then ark start --apply."}}function Is(e){let t=typeof e.resolvedRoot=="string"&&e.resolvedRoot.length>0?e.resolvedRoot:".",n=typeof e.projectId=="string"&&As.test(e.projectId)?e.projectId:null,r=Dn({resolvedRoot:t,projectId:n,expectation:e.expectation,expectedRootRelation:e.expectedRootRelation}),s=typeof e.activeHost=="string"?e.activeHost.trim().toLowerCase():"",i=s&&s!=="unknown"?s:s==="unknown"?"unknown":null,a=Hn({hardWriteActive:e.hardWriteActive,softWriteHost:e.softWriteHost,writePathUnavailable:e.writePathUnavailable,activeHost:i}),o=typeof e.honestLabel=="string"&&e.honestLabel.trim().length>0?e.honestLabel.trim():Vn(a,i),d={at:typeof e.lastCheckAt=="string"?e.lastCheckAt:null,verdict:e.lastCheckVerdict==="pass"||e.lastCheckVerdict==="fail"||e.lastCheckVerdict==="incomplete"?e.lastCheckVerdict:null,activeViolations:st(e.activeViolations),frozenResidual:st(e.frozenResidual)},u={arkRulesLoaded:e.arkRulesLoaded===!0,inventoried:st(e.rulesInventoried),underContract:st(e.rulesUnderContract),frozenResidual:st(e.rulesFrozenResidual)},g={writePath:a,host:i,honestLabel:o},m={projectId:n,resolvedRoot:t,resolvedConfigPath:typeof e.resolvedConfigPath=="string"&&e.resolvedConfigPath.length>0?e.resolvedConfigPath:null,binding:r.status,authoritative:r.authoritative,...r.code?{code:r.code}:{},...r.message?{message:r.message}:{}},c={schemaVersion:"1.0",arkgateVersion:typeof e.arkgateVersion=="string"&&e.arkgateVersion.length>0?e.arkgateVersion:"unknown",projectIdentity:m,activation:g,lastCheck:d,rules:u,nextAction:jn(e,r,g,d,u)},l=Un(e.improvementCompass);return l&&(c.improvementCompass=l),e.vsBase&&typeof e.vsBase.baseRef=="string"&&e.vsBase.baseRef.length>0&&(c.vsBase=e.vsBase),c}var bs=new Set($n),Ea=new Set(Fn);function zt(e){let t=bs.has(e.mode)?e.mode:"unavailable",n=e.factsSource!=null&&Ea.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:it.FACTS_UNAVAILABLE,reason:typeof e.reason=="string"&&e.reason.length>0?e.reason:"Improvement compass facts are unavailable \u2014 run ark-check --doctor for residual lenses. Status never invents green.",factsSource:n??"none"};return r&&(a.contractHash=r),a}let s=Array.isArray(e.topResidual)?e.topResidual.filter(a=>typeof a=="string"&&a.length>0).slice(0,15):[],i={schemaVersion:"1.0",notAScore:!0,mode:t,topResidual:s};return t==="subset"?(i.reasonCode=typeof e.reasonCode=="string"&&e.reasonCode.length>0?e.reasonCode:it.FACTS_PARTIAL,i.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&&(i.reasonCode=e.reasonCode),typeof e.reason=="string"&&e.reason.length>0&&t==="full"&&(i.reason=e.reason),n&&(i.factsSource=n),r&&(i.contractHash=r),i}function Ss(e={}){return zt({mode:"unavailable",topResidual:[],reasonCode:e.reasonCode??it.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})}function Un(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"&&bs.has(t.mode)?n=t.mode:Array.isArray(t.topResidual)?n="subset":n="unavailable",zt({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})}function Rs(e,t){let n=Array.isArray(e)?e:[],r=new Set(Array.isArray(t)?t:[]);for(let s of n)if(!(typeof s!="string"||s.length===0)&&!r.has(s))return!1;return!0}function st(e){if(e==null)return null;let t=Number(e);return!Number.isFinite(t)||t<0?null:Math.floor(t)}var Es={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Mn,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:"1.0"},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"}}}}};var at="1.0",ot=["soc","cohesion","coupling","srp","dip","ocp","encapsulation","modularity","scalability","resilience","security","maintainability","testability","domain","stack"],lt=5,ce=["scalability","resilience","security"],Pe=new Set(ce),Gn={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},Bn={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"},Kn={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 zn(e){return Bn[e]??e}function qn(e){let t=e.id??e.smellId??"";return typeof t=="string"?t.trim():""}function Yn(e){let t=e.ruleId??e.code??"";return typeof t=="string"?t.trim():""}function P(e,t,n,r){if(!n||e.evidence.some(i=>i.source===t&&i.ref===n))return;let s={source:t,ref:n};r&&r.trim()&&(s.detail=r.trim().slice(0,240)),e.evidence.push(s)}function H(e,t,n){Pe.has(e.id)||(e.status="residual",e.summary=t,n&&(e.nextAction=n))}function vs(e){switch(e){case"soc":return"No separation-of-concerns residual detected from current sensors.";case"cohesion":return"No cohesion residual (god-module / physical cohesion) from current sensors.";case"coupling":return"No coupling residual (import edges, cycles, peer isolation) from current sensors.";case"srp":return"No single-responsibility residual from current sensors.";case"dip":return"No dependency-inversion residual (pure / capability / forbidden walls) from current sensors.";case"ocp":return"Open/closed is not strongly instrumented \u2014 no switch-chain sensor.";case"encapsulation":return"No encapsulation residual from ArkRules structure sensors.";case"modularity":return"No modularity / placement residual from current sensors.";case"maintainability":return"No maintainability residual (design-weak / baseline honesty) from current sensors.";case"testability":return"No testability residual (impure domain / capability walls) from current sensors.";case"domain":return"No domain-alignment residual from current sensors.";case"stack":return"Stack practices are only partially instrumented (TypeScript / host / Ark idioms).";default:return`${Bn[e]} \u2014 no residual from current sensors.`}}function Cs(){return ot.map(e=>Pe.has(e)?{id:e,status:"out-of-scope",summary:Kn[e],evidence:[],nextAction:{kind:"docs",ref:"docs/use.md#improvement-compass",summary:"Out of scope for ArkGate \u2014 use dedicated tooling outside the gate."}}:e==="ocp"?{id:e,status:"not-instrumented",summary:vs(e),evidence:[]}:{id:e,status:"ok",summary:vs(e),evidence:[]})}function va(e,t){for(let n of t){let r=qn(n);if(!r)continue;let s=n.outcome||n.message||void 0,a=(Array.isArray(n.evidence)?n.evidence:[])[0],o=(g,m,c)=>{let l=e.get(g);!l||Pe.has(g)||(P(l,"designSmells",r,s),a&&P(l,"designSmells",a,r),H(l,m,c))},d={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":o("soc","Business rules still mix with UI or presentation surfaces.",d),o("domain","Domain logic lives outside Domain \u2014 align rules with Domain ownership.",d);break;case"facade-sql-in-routes":o("soc","Routes/controllers own SQL or ORM access \u2014 concerns are mixed.",d),o("dip","Transport depends on concrete persistence instead of a port.",u);break;case"io-under-application":o("soc","Application/business code reaches I/O directly \u2014 separation is weak.",d),o("dip","I/O is not inverted behind ports/adapters.",u),o("testability","Direct I/O under application code hurts pure unit testing.",u);break;case"handler-in-persistence":o("soc","HTTP/transport handlers live under persistence folders.",d);break;case"god-module":o("cohesion","Large multi-responsibility modules reduce cohesion.",d),o("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":o("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."}),o("cohesion","Mixed layout styles scatter the same concern across patterns.",d);break;case"soft-contract":o("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."}),o("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:o("maintainability","Design residual remains under an unrecognized smell id \u2014 review evidence.",d);break}}}function Ca(e){return e.failsStrict===!1||e.typeOnly===!0}function ka(e,t){for(let n of t){let r=Yn(n);if(!r)continue;let s=n.message,i=r.toUpperCase(),a=(d,u,g)=>{let m=e.get(d);!m||Pe.has(d)||(P(m,"violations",r,s),n.file&&P(m,"violations",n.file,r),H(m,u,g))};if(Ca(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 o={kind:"skill",ref:"/ark-autopilot",summary:"Clear the active edge residual, then re-doctor."};if(i==="LAYER_IMPORT_VIOLATION"||i.includes("LAYER_IMPORT")||i==="DYNAMIC_IMPORT_VIOLATION"){a("coupling","Import graph edges violate the layer contract.",o);continue}if(i.includes("CYCLE")||i==="CIRCULAR_DEPENDENCY"){a("coupling","Import cycles couple modules tightly.",o);continue}if(i.includes("PEER_ISOLATION")||i==="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(i==="FORBIDDEN_GLOBAL"||i.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(i==="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(i.startsWith("ARKRULE_")||i==="INVARIANT_UNCOVERED"){a("encapsulation","ArkRules structure / invariant residual inside a layer.",{kind:"skill",ref:"/ark-autopilot",summary:"Label [ArkRules]; structure fixes are judgment \u2014 never invent mechanical-safe."}),a("domain","Intra-layer domain structure or invariant coverage residual.",{kind:"skill",ref:"/ark-explore",summary:"Inventory candidates \u2192 one ArkRules pilot with coverage evidence."});continue}}}function _a(e,t){let n=Number(t.cycleCount)||0;if(n>0){let l=e.get("coupling");P(l,"cycles",`count:${n}`),H(l,"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 l=e.get("coupling");P(l,"peerIsolation",`count:${r}`),H(l,"Peer isolation residual remains.",{kind:"skill",ref:"/ark-autopilot",summary:"Peer isolation is judgment-class residual."})}let s=Number(t.physicalCohesionFindingCount)||0;if(s>0){let l=e.get("cohesion");P(l,"physicalCohesion",`findings:${s}`),H(l,"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 p=e.get("srp");P(p,"physicalCohesion",`findings:${s}`),H(p,"Mirrored clusters suggest split-by-concern residual (architecture SRP).",{kind:"skill",ref:"/ark-autopilot",summary:"One reshape/extraction pilot this turn."})}let i=Number(t.pureOrCapabilityResidual)||0,a=Number(t.forbiddenGlobalResidual)||0;if(i>0||a>0){let l=e.get("dip");i>0&&P(l,"capability",`residual:${i}`),a>0&&P(l,"forbiddenGlobals",`residual:${a}`),H(l,"Pure / capability / forbidden residual weakens dependency inversion.",{kind:"skill",ref:"/ark-autopilot",summary:"Inject ports; keep pure layers free of effects."});let p=e.get("testability");i>0&&P(p,"capability",`residual:${i}`),a>0&&P(p,"forbiddenGlobals",`residual:${a}`),H(p,"Impure domain or capability residual reduces testability.",{kind:"skill",ref:"/ark-autopilot",summary:"Prefer ports over concrete I/O in pure/domain modules."})}let o=Number(t.arkRulesStructureResidual)||0;if(o>0){let l=e.get("encapsulation");P(l,"arkRules",`structureResidual:${o}`),H(l,"ArkRules structure residual \u2014 encapsulation inside the layer.",{kind:"skill",ref:"/ark-autopilot",summary:"Fix structure sensors under [ArkRules] without inventing mechanical-safe."});let p=e.get("domain");P(p,"arkRules",`structureResidual:${o}`),H(p,"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 l=e.get("maintainability");P(l,"designFitness","design-weak"),H(l,"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 l=e.get("maintainability");t.dirtyBaselineRisk===!0&&P(l,"baseline","dirty-freeze-risk"),(Number(t.baselineStale)||0)>0&&P(l,"baseline",`stale:${t.baselineStale}`),H(l,"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 d=Number(t.frozenResidual)||0;if(t.baselineExists===!0&&d>=10&&e.get("maintainability").status!=="residual"){let l=e.get("maintainability");P(l,"baseline",`frozen:${d}`),H(l,"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,g=Number(t.emptyLayerCount)||0;if(u>0||g>0){let l=e.get("modularity");u>0&&P(l,"coverage",`ungovernedDirs:${u}`),g>0&&P(l,"coverage",`emptyLayers:${g}`),H(l,"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 l=e.get("modularity");P(l,"goldenPattern","absent"),H(l,"Design-weak without a golden pattern \u2014 new code lacks a placement norm for the AI.",{kind:"skill",ref:"/ark-place",summary:"Record an advisory golden pattern for new code (does not clear design-weak)."})}let m=e.get("stack");(t.stackKind??null)==="typescript"?m.status==="ok"&&(m.summary="Stack practices are partially instrumented for TypeScript / host / Ark idioms only \u2014 not a full framework checklist."):(m.status="not-instrumented",m.summary="Stack-specific best practices outside TypeScript/host/Ark idioms are not instrumented.",m.evidence=[],m.nextAction={kind:"docs",ref:"docs/use.md#improvement-compass",summary:"Ark does not score non-TS stack idioms."})}function ks(e,t){if(Array.isArray(t.designSmells)&&t.designSmells.length>0){let n=[...t.designSmells].sort((r,s)=>qn(r).localeCompare(qn(s)));va(e,n)}if(Array.isArray(t.violations)&&t.violations.length>0){let n=[...t.violations].sort((r,s)=>{let i=Yn(r).localeCompare(Yn(s));return i!==0?i:String(r.file??"").localeCompare(String(s.file??""))});ka(e,n)}_a(e,t)}function _s(e){for(let t of ce){let n=e.get(t);n.status="out-of-scope",n.summary=Kn[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."}}}function xs(e){for(let t of e)t.evidence.sort((n,r)=>{let s=n.source.localeCompare(r.source);return s!==0?s:n.ref.localeCompare(r.ref)})}function Os(e){return e.filter(n=>n.status==="residual"&&!Pe.has(n.id)).slice().sort((n,r)=>{let s=Gn[n.id]??150,i=Gn[r.id]??150;return s!==i?s-i:n.id.localeCompare(r.id)}).slice(0,5).map(n=>n.id)}function Ts(e={}){let t=Cs(),n=new Map(t.map(s=>[s.id,s]));ks(n,e),_s(n),xs(t);let r=Os(t);return{schemaVersion:"1.0",notAScore:!0,lenses:t.map(s=>{let i={id:s.id,status:s.status,summary:s.summary,evidence:s.evidence.map(a=>({...a}))};return s.nextAction&&(i.nextAction={...s.nextAction}),i}),topResidual:r}}function Wn(e){return e.topResidual.map(t=>zn(t))}function Jn(e){for(let t of e.topResidual){let n=e.lenses.find(r=>r.id===t);if(n?.nextAction)return{...n.nextAction}}return null}function Ps(e){let t=Wn(e),n=ce.map(i=>zn(i)),r=Jn(e),s=[];return t.length>0?s.push(`Residual: ${t.join(" \xB7 ")}`):s.push("Residual: none on instrumented lenses (not a score \u2014 green edges \u2260 finished design)."),s.push(`Out of scope (honest): ${n.join(" \xB7 ")}`),r&&s.push(`Next: ${r.ref} \u2014 ${r.summary}`),s}var Ls="1.0",Ns="<!-- arkgate:agent-projection:begin",Zn="<!-- arkgate:agent-projection:end -->",Xn="This projection is **non-authoritative**. Enforcement is `ark-check` / host write hooks / required CI (`--strict-merge`), not AGENTS.md, skills, or this block.",Jt=Object.freeze(["ark-check","host-write-hooks","ci-strict-merge"]),ws=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"]),Qn=/<!--\s*arkgate:agent-projection:begin\b([^>]*)-->/i,Ms=/<!--\s*arkgate:agent-projection:end\s*-->/i,xa=/\barkgateVersion=([A-Za-z0-9._+-]+)/i,Oa=/\bschema=([A-Za-z0-9._+-]+)/i;function ct(e){let t=String(e??"").replace(/\r\n/g,`
|
|
15
|
+
`)),l=/(?:^|[\n;{])\s*(?:public\s+)?set\s+[a-zA-Z_]/.test(u),p=/(?:^|[\n;{])\s*private\s+constructor\s*\(/.test(u),y=/(?:^|[\n;{])\s*(?:public\s+)?constructor\s*\(/.test(u)&&!p,I=/(?:^|[\n;{])\s*static\s+(?:async\s+)?(?:create|of|from|parse|build|make|new)\s*[<(]/.test(u)||/(?:^|[\n;{])\s*static\s+(?:async\s+)?[A-Za-z_][A-Za-z0-9_]*\s*\([^)]*\)\s*:\s*[A-Za-z_]/.test(u),R=[],f=new Set(["if","match","when"]),h=/(?:^|\n)\s*(?:public\s+|private\s+|protected\s+|async\s+)*(?!constructor|get|set|static)([a-zA-Z_][a-zA-Z0-9_]*)\s*\([^)]*\)\s*(?::\s*[^{]+)?\{/g,S;for(;(S=h.exec(u))!==null;){let _=S[1];if(f.has(_))continue;let E=S.index+S[0].length,L=1,T=E;for(;T<u.length&&L>0;)u[T]==="{"?L+=1:u[T]==="}"&&(L-=1),T+=1;let j=u.slice(E,T-1);if(!/this\.\w+\s*=/.test(j))continue;let A=/\b(ensureInvariants|assertInvariants|validate|publish|emit|raise|record)\b/.test(j);R.push({name:_,referencesGuardOrPublish:A})}let k=(u.match(/(?:^|\n)\s*(?:public\s+|private\s+|protected\s+)?(?:async\s+)?[a-zA-Z_][a-zA-Z0-9_]*\s*\(/g)??[]).length,N=(g.match(/(?:^|[\n;])\s*(?:public\s+)?(?!constructor|static|get|set|private|protected|readonly)[a-zA-Z_][a-zA-Z0-9_]*\s*[:=]/g)??[]).length,D=k<=1&&N>=2&&(c||m);n.push({file:e,className:i,exported:!0,hasPublicMutableFields:c||m,hasPublicSetters:l,hasPublicConstructor:y,hasStaticFactory:I,mutatingMethods:[...R],dataOnly:D})}return n}function V(e,t,n={}){return{ruleId:e,message:t,...n}}function tt(e){let{config:t,rules:n,files:r,manifest:s}=e,i=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(l=>typeof l!="string"))&&i.push(V("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","dynamicImportAllowlist must be an array of file globs.")),t.safety!==void 0&&(t.safety===null||typeof t.safety!="object"||Array.isArray(t.safety)))i.push(V("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let l of["maxTsSuppressions","maxAnyCasts"]){let p=t.safety[l];p!==void 0&&(!Number.isInteger(p)||p<0)&&i.push(V("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${l} must be a non-negative integer.`))}let o=Array.isArray(t.layers)?t.layers:[],a=Array.isArray(s?.architecture?.layers)?s.architecture.layers:[],d=new Set([...o.map(l=>l.name).filter(Boolean),...a.map(l=>l.name).filter(l=>!!l)]);o.length===0&&i.push(V("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let u=new Set,g=new Set;for(let l of o){if(!l.name){i.push(V("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}u.has(l.name)&&g.add(l.name),u.add(l.name),l.forbiddenGlobals!==void 0&&(!Array.isArray(l.forbiddenGlobals)||l.forbiddenGlobals.some(y=>typeof y!="string"))&&i.push(V("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${l.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:l.name}));let p=Array.isArray(l.patterns)?l.patterns:[];if(p.length===0){i.push(V("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${l.name}" has no file patterns and will never classify files.`,{layer:l.name}));continue}for(let y of p){let I;try{I=pe(y)}catch(R){i.push(V("CONFIG_INVALID_LAYER_PATTERN",`Layer "${l.name}" has an invalid pattern "${y}": ${R instanceof Error?R.message:String(R)}`,{layer:l.name,pattern:y}));continue}!r.some(R=>I.test(R))&&!l.optional&&i.push(V("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${l.name}" pattern "${y}" matched no included files.`,{layer:l.name,pattern:y,failsStrict:!1}))}}for(let l of g)i.push(V("CONFIG_DUPLICATE_LAYER",`Layer "${l}" is configured more than once.`,{layer:l}));if(d.size>0)for(let l of n??[])l.from&&!d.has(l.from)&&i.push(V("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${l.from}".`,{fromLayer:l.from,toLayer:l.to})),l.to&&!d.has(l.to)&&i.push(V("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${l.to}".`,{fromLayer:l.from,toLayer:l.to}));let m=new Set;if(o.length>1)for(let l of r){let p=-1,y=[];for(let I of o)for(let R of I.patterns??[]){if(!pe(R).test(l))continue;let f=mn(R,l);f>p?(p=f,y=[I.name]):f===p&&!y.includes(I.name)&&y.push(I.name)}y.length>1&&m.add([...y].sort().join(" + "))}m.size>0&&i.push(V("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...m].join(", ")}.`,{pairs:[...m]}));let c=r.filter(l=>!Q(l,o));return c.length>0&&i.push(V("CONFIG_UNCLASSIFIED_FILES",`${c.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:c.length,samples:c.slice(0,5)})),i}function mo(e,t){return t.some(n=>{try{return pe(n).test(e)}catch{return!1}})}function go(e,t){let n=e.contract.config.safety??{},r=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,s=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,i=e.contract.config.dynamicImportAllowlist??[],o=t.safetyUses.filter(y=>y.kind==="ts-suppression").map(({file:y,line:I})=>({file:y,line:I})),a=t.safetyUses.filter(y=>y.kind==="any-cast").map(({file:y,line:I})=>({file:y,line:I})),d=t.safetyUses.filter(y=>(y.kind==="dynamic-import"||y.kind==="dynamic-require")&&!mo(y.file,i)).map(y=>({file:y.file,line:y.line,kind:y.kind==="dynamic-require"?"require":"import"})),u=n.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(y=>y.kind==="in-memory-store").map(y=>({file:y.file,line:y.line,store:y.symbol??"in-memory store"})),g=n.allowDisabledPeerIsolation===!0?[]:(e.contract.config.rules??[]).filter(y=>y.peerIsolation===!1||y.allowed===!1&&!!y.from&&y.from===y.to&&y.peerIsolation!==!0).map(y=>({from:y.from,to:y.to})),m={tsSuppressions:o,anyCasts:a,nonLiteralDynamicImports:d,inMemoryProductionStores:u,disabledPeerIsolationRules:g,thresholds:{maxTsSuppressions:r,maxAnyCasts:s}},c=[],l=d.filter(y=>y.kind==="import");if(l.length>0){let y=l[0];c.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:y.file,line:y.line,message:`${l.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let p=d.filter(y=>y.kind==="require");if(p.length>0){let y=p[0];c.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:y.file,line:y.line,message:`${p.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(o.length>r){let y=o[0];c.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:y.file,line:y.line,message:`${o.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${r}).`})}if(a.length>s){let y=a[0];c.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:y.file,line:y.line,message:`${a.length} explicit any cast(s) exceed safety.maxAnyCasts (${s}).`})}if(u.length>0){let y=u[0];c.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:y.file,line:y.line,message:`${u.length} ArkGate InMemory store risk(s) appear in governed production source. Provide durable stores or set safety.allowInMemory only for an explicitly ephemeral service.`})}return g.length>0&&c.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${g.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:m,warnings:c}}function yo(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}function es(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return bn(e,n.length>0?n:In.map(r=>({name:r.layer,prefixes:r.prefixes})))}function ho(e,t,n){let r=[],s=new Map(e.contract.config.layers.map(i=>[i.name,i]));for(let i of t.ambientUses){let o=n.get(i.file);!o||!yo(i.symbol,s.get(o)?.forbiddenGlobals??[])||r.push({ruleId:"FORBIDDEN_GLOBAL",file:i.file,line:i.line,fromLayer:o,target:i.symbol,message:`${o} must not use the ambient global "${i.symbol}".`})}for(let i of t.capabilityUses){let o=n.get(i.file);if(!o)continue;let a=s.get(o),d=a?.forbiddenGlobals??[],u=i.source==="import-based"?t.dependencies.find(g=>g.from===i.file&&g.line===i.line&&g.specifier===i.symbol&&!g.typeOnly)?.kind:void 0;if(!(i.source==="ambient-global"&&$e(i.symbol,d))){if(i.source==="import-based"){let g=ie(i.symbol,d);if(g){r.push({ruleId:"FORBIDDEN_GLOBAL",file:i.file,line:i.line,fromLayer:o,target:i.symbol,...u?{edgeKind:u}:{},message:`${o} must not use module "${i.symbol}" because it is the import form of forbidden global "${g}".`});continue}}be(a).includes(i.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:i.file,line:i.line,fromLayer:o,target:i.symbol,capability:i.capability,...u?{edgeKind:u}:{},message:i.source==="import-based"?`${o} denies the ${i.capability} capability; found import of "${i.symbol}".`:`${o} denies the ${i.capability} capability; found ambient "${i.symbol}".`})}}for(let i of t.publishCalls){let o=n.get(i.file);if(!o)continue;for(let d of Fe({publishCall:!0,rawIntentName:i.rawIntentName,objectHasIntent:i.objectHasIntent,arkPublishCandidate:i.arkPublishCandidate,hasSource:i.hasSource}))r.push({ruleId:d.ruleId,file:i.file,line:i.line,...d.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:o}:{},message:d.message});if(!i.sourceIntent)continue;let a=es(i.sourceIntent,e.contract);!a||a===o||r.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:i.file,line:i.line,fromLayer:o,toLayer:a,target:i.sourceIntent,message:`Publish source "${i.sourceIntent}" resolves to ${a}, but the publishing file is classified as ${o}.`})}for(let i of t.intentReferences){let o=n.get(i.file);if(!o)continue;let a=es(i.intent,e.contract);if(!a)continue;let d=ee(e.contract.config.rules,o,a);d&&r.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:i.file,line:i.line,fromLayer:o,toLayer:a,target:i.intent,message:d.message??`${o} must not reference ${a} intent ${i.intent}.`})}return r}function Ao(e){let{facts:t}=e,n=ke(e.contract.config),r=t.evidenceRequirementsHash===n,s=r?t.completeness:"unavailable",i=r?t.completenessReasons:[...t.completenessReasons,{code:"EVIDENCE_REQUIREMENTS_MISMATCH",message:"Resolved facts were collected for different policy-controlled evidence requirements."}].sort((A,B)=>{let Ne=`${A.code}\0${A.file??""}\0${A.message}`,we=`${B.code}\0${B.file??""}\0${B.message}`;return Ne<we?-1:Ne>we?1:0}),o=t.files.map(A=>({...A,layer:Q(A.path,e.contract.config.layers)??null})),a=new Map(o.map(A=>[A.path,A.layer])),d=t.dependencies.map(A=>{let B=A.target?a.get(A.target)??Q(A.target,e.contract.config.layers):void 0;return{from:A.from,fromLayer:a.get(A.from)??null,...A.resolution==="resolved-project"&&A.target?{to:A.target,...B?{toLayer:B}:{}}:{},line:A.line,kind:A.kind,typeOnly:A.typeOnly,...A.targetTypeOnlyExports?{targetTypeOnlyExports:A.targetTypeOnlyExports}:{},...A.sourcePureTypeModule?{sourcePureTypeModule:A.sourcePureTypeModule}:{},...A.namedBindingsTypeOnly?{namedBindingsTypeOnly:A.namedBindingsTypeOnly}:{},...A.portProofEligible?{portProofEligible:A.portProofEligible}:{}}}),u=tt({config:e.contract.config,rules:e.contract.config.rules,files:o.map(A=>A.path)}),g=go(e,t),m=e.contract.arkRules??le(),c=o.map(A=>A.path),p={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?Ut(e.coverageInputs.fileContents):{},...e.fileHints??{}},y=[...Vt({arkRules:m,classShapes:e.contract.classShapes??t.classShapes??[],files:c,layerForFile:A=>a.get(A)??Q(A,e.contract.config.layers),fileHints:p}),...jt(m,c)],I=y.filter(A=>A.failsStrict).map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,arkruleId:A.arkruleId,arkruleSource:A.arkruleSource,nextAction:A.ruleId==="ARKRULE_SCOPE_EMPTY"?`Fix appliesTo globs for ${A.arkruleId} in ${A.arkruleSource} so they match governed files, or remove the rule.`:`Fix the structure or invariant for ${A.arkruleId} (declared in ${A.arkruleSource}), then preflight again.`})),R=y.filter(A=>!A.failsStrict).map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,arkruleId:A.arkruleId,arkruleSource:A.arkruleSource,failsStrict:!1,nextAction:A.ruleId==="ARKRULE_SCOPE_EMPTY"?`Review appliesTo for ${A.arkruleId} in ${A.arkruleSource} (zero-match scope; advisory).`:`Review ArkRule ${A.arkruleId} in ${A.arkruleSource} (advisory).`})),h=(m.invariants?.length??0)>0?Tt({arkRules:m,fileContents:e.coverageInputs?.fileContents??{},testFiles:e.coverageInputs?.testFiles??[],testGlobsMissing:e.coverageInputs?.testGlobsMissing===!0||e.coverageInputs===void 0||(e.coverageInputs.testFiles?.length??0)===0}):{coverage:[],violations:[],partial:!1},S=h.violations.filter(A=>A.failsStrict).map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,arkruleId:A.arkruleId,arkruleSource:A.arkruleSource,nextAction:`Add a test title or declared symbol covering ${A.arkruleId} (declared in ${A.arkruleSource}), then preflight again.`})),k=h.violations.filter(A=>!A.failsStrict).map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,arkruleId:A.arkruleId,arkruleSource:A.arkruleSource,failsStrict:!1,nextAction:`Cover invariant ${A.arkruleId} in ${A.arkruleSource} (advisory / partial).`})),D=h.partial&&h.coverage.some(A=>A.mode==="enforced"&&A.partial)?[{code:"INVARIANT_COVERAGE_PARTIAL",message:"Enforced ArkRules invariant coverage cannot be fully proven (missing test globs or empty test set); reporting partial, never covered."}]:[],_=Ie({config:e.contract.config,rules:e.contract.config.rules,files:o.filter(A=>A.layer).map(A=>A.path),contentViolations:[...ho(e,t,a),...I,...S],edges:d,warnings:[...u,...g.warnings,...R,...k],safety:g.report}),E=s==="complete"&&D.length>0?"partial":s,L=E==="complete"?i:[...i,...D].sort((A,B)=>{let Ne=`${A.code}\0${A.file??""}\0${A.message}`,we=`${B.code}\0${B.file??""}\0${B.message}`;return Ne<we?-1:Ne>we?1:0}),T=_.violations.filter(A=>A.failsStrict!==!1),j=E==="complete"&&T.length===0,de=j&&_.warnings.every(A=>A.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:E,completenessReasons:L,valid:j,strictValid:de,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:g.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:o,layers:e.contract.config.layers.map(A=>A.name),edges:d,capabilityUses:t.capabilityUses,violations:_.violations,warnings:_.warnings}}}function Te(e){return Ao({contract:e.contract,facts:se(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints})}function Gt(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return e.typeOnly||e.targetTypeOnlyExports||e.namedBindingsTypeOnly?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":e.peerIsolation?"Extract the shared dependency to a shared layer, test at the public interface, then preflight again.":`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, test at the public interface, then preflight again.`;case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, test at the public interface, then preflight again.`;case"CAPABILITY_VIOLATION":return`Define a ${String(e.capability??"capability")} port in ${e.fromLayer??"the walled layer"}, bind the implementation outside it, test at the public interface, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, test at the public interface, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";case"ARKRULE_STRUCTURE":case"ARKRULE_INVARIANT":case"INVARIANT_UNCOVERED":return`Fix the structure or invariant for ${typeof e.arkruleId=="string"&&e.arkruleId.length>0?e.arkruleId:"the ArkRule"} (declared in ${typeof e.arkruleSource=="string"&&e.arkruleSource.length>0?e.arkruleSource:"arkrules/<Layer>.json"}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`;default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}function ts(e){return M(x(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}function Pn(e){let t=xe(e),n=new Map(t.ir.files.map(p=>[p.path,p])),r=[],s=new Set,i=[];for(let p of e.changes){let y=p.path.replace(/\\/g,"/"),I=Ae(p.path);if(!I||I===".."||I.startsWith("../")||y.startsWith("/")||/^[A-Za-z]:\//.test(y)||y.includes("\0")){i.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(s.has(I)){i.push({ruleId:"DUPLICATE_CHANGE_PATH",file:I,line:1,message:`The atomic change set contains more than one operation for ${I}.`});continue}s.add(I),"delete"in p&&p.delete&&!n.has(I)&&i.push({ruleId:"DELETE_TARGET_MISSING",file:I,line:1,message:`Cannot delete ${I} because it is not present in the supplied base tree.`}),r.push("delete"in p&&p.delete?{path:I,delete:!0}:{path:I,content:"content"in p?p.content:""})}e.changes.length===0&&i.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let o=Qe({...e,changes:r}),a=new Map(o.ir.files.map(p=>[p.path,p])),d=o.ir.violations.filter(p=>p.ruleId==="CAPABILITY_VIOLATION"||p.ruleId==="FORBIDDEN_GLOBAL").map(p=>{let y=a.get(p.evidence.file)?.layer;return{ruleId:p.ruleId,file:p.evidence.file,line:p.evidence.line,target:p.symbol,...p.capability?{capability:p.capability}:{},...y?{fromLayer:y}:{},edgeKind:"import",message:p.message}}),u=Ie({config:e.contract.config,rules:e.contract.config.rules,files:o.ir.files.map(p=>p.path),contentViolations:d,edges:o.ir.edges.filter(p=>!!p.fromLayer).map(p=>({from:p.from,fromLayer:p.fromLayer,...p.to?{to:p.to}:{},...p.toLayer?{toLayer:p.toLayer}:{},line:p.evidence.line,kind:"import",...p.typeOnly?{typeOnly:!0}:{},...p.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),g=r.map(p=>{let y=Ae(p.path),I=n.get(y),R=a.get(y);return{path:y,operation:"delete"in p&&p.delete?"delete":I?"update":"create",...I?{beforeContentHash:I.contentHash}:{},...R?{candidateContentHash:R.contentHash}:{}}}).sort((p,y)=>p.path.localeCompare(y.path)),m=[...i,...u.violations].map(p=>({...p,nextAction:Gt(p)})),c=m.filter(p=>p.failsStrict!==!1),l=e.changeMap?ge({changeMap:e.changeMap,changes:g,baseDependencies:t.ir.edges.flatMap(p=>p.to?[{from:p.from,to:p.to}]:[]),candidateDependencies:o.ir.edges.flatMap(p=>p.to?[{from:p.from,to:p.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&o.valid&&c.length===0&&(l?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:o.ir.compilerOptionsHash,baseTreeHash:ts(t.ir.files),candidateTreeHash:ts(o.ir.files),baseCompleteness:t.completeness,candidateCompleteness:o.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:o.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...l?{convergence:l}:{},changes:g,violations:m,warnings:u.warnings}}function Io(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let s of t.split("/"))if(!(!s||s==="."))if(s===".."){if(n.length===0)return;n.pop()}else n.push(s);let r=n.join("/");return r&&r===t?r:void 0}function bo(e,t){return[["resolverIdentity",e.resolverIdentity,t.resolverIdentity],["compilerIdentity",e.compilerIdentity,t.compilerIdentity],["evidenceRequirementsHash",e.evidenceRequirementsHash,t.evidenceRequirementsHash],["projectPackageName",e.projectPackageName??"",t.projectPackageName??""]].filter(([,r,s])=>r!==s).map(([r,s,i])=>({ruleId:"FACTS_IDENTITY_MISMATCH",file:"<change-set>",line:1,field:r,before:s,candidate:i,message:`Base and candidate facts must use the same ${r}.`}))}function So(e,t,n,r){let s=n.get(t),i=r.get(t);return{path:t,operation:"delete"in e&&e.delete?"delete":s?"update":"create",...s?{beforeContentHash:s.contentHash}:{},...i?{candidateContentHash:i.contentHash}:{}}}function Ln(e){let t=se(e.baseFacts),n=se(e.candidateFacts),r=Te({contract:e.contract,facts:t}),s=Te({contract:e.contract,facts:n}),i=new Map(t.files.map(l=>[l.path,l])),o=new Map(n.files.map(l=>[l.path,l])),a=bo(t,n),d=new Map,u=[];for(let l of e.changes){let p=Io(l.path);if(!p){a.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(d.has(p)){a.push({ruleId:"DUPLICATE_CHANGE_PATH",file:p,line:1,message:`The atomic change set contains more than one operation for ${p}.`});continue}d.set(p,l);let y=i.get(p),I=o.get(p);if("delete"in l&&l.delete)y||a.push({ruleId:"DELETE_TARGET_MISSING",file:p,line:1,message:`Cannot delete ${p} because it is not present in the supplied base facts.`}),I&&a.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:p,line:1,message:`Candidate facts still contain deleted file ${p}.`});else{let R="content"in l?l.content:"",f=M(R);I?I.contentHash!==f&&a.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:p,line:1,expectedContentHash:f,candidateContentHash:I.contentHash,message:`Candidate facts for ${p} do not match the declared content.`}):a.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:p,line:1,message:`Candidate facts do not contain changed file ${p}.`})}u.push(So(l,p,i,o))}e.changes.length===0&&a.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});for(let l of new Set([...i.keys(),...o.keys()])){if(d.has(l))continue;let p=i.get(l),y=o.get(l);p&&y&&x(p)===x(y)||a.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:l,line:1,message:`Candidate facts change ${l}, but the atomic change set does not declare it.`})}let g=e.changeMap?ge({changeMap:e.changeMap,changes:u,baseDependencies:r.ir.edges.flatMap(l=>l.to?[{from:l.from,to:l.to}]:[]),candidateDependencies:s.ir.edges.flatMap(l=>l.to?[{from:l.from,to:l.to}]:[])}):void 0,m=[...a,...s.ir.violations].map(l=>({...l,nextAction:Gt(l)})),c=m.filter(l=>l.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&s.strictValid&&c.length===0&&(g?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,resolverIdentity:n.resolverIdentity,compilerIdentity:n.compilerIdentity,compilerOptionsHash:n.compilerOptionsHash,tsconfigHash:n.tsconfigHash,baseCompilerOptionsHash:t.compilerOptionsHash,candidateCompilerOptionsHash:n.compilerOptionsHash,baseTsconfigHash:t.tsconfigHash,candidateTsconfigHash:n.tsconfigHash,evidenceRequirementsHash:n.evidenceRequirementsHash,baseFactsHash:t.factsHash,candidateFactsHash:n.factsHash,baseTreeHash:t.candidateTreeHash,candidateTreeHash:n.candidateTreeHash,baseCompleteness:r.completeness,candidateCompleteness:s.completeness,baseCompletenessReasons:r.completenessReasons,candidateCompletenessReasons:s.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...g?{convergence:g}:{},changes:u.sort((l,p)=>l.path<p.path?-1:l.path>p.path?1:0),violations:m,warnings:s.ir.warnings}}function Bt(e,t){return e.slice(0,t).split(`
|
|
16
|
+
`).length}function ns(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function ss(e,t){return e.some(n=>{let r=n.trim().replace(/\.+$/,"");return t.some(s=>r===s||r.startsWith(`${s}.`))})}function rs(e,t=[]){return/domain|entity|aggregate|model/i.test(e)||ss(t,["Domain"])}function Ro(e,t=[]){return/application|orchestration|presentation|adapter|framework|interface|delivery|transport|inbound|controller/i.test(e)||ss(t,["Application","Orchestration","Presentation","Adapter","Interface","Delivery","Transport"])}function Eo(e){return/(?:^|\/)(?:tests?|__tests__|fixtures?|testdata|mocks?|stubs?|examples?|samples?|seeds?|seeders?|migrations?|excluded|exclusions?)(?:\/|$)/i.test(e)||/(?:^|\/)[^/]*\.(?:test|spec|fixture|mock|stub|seed|seeder)\.[^/]+$/i.test(e)||/(?:^|\/)(?:seed|seeder|fixture|mock|stub)\.[^/]+$/i.test(e)}function is(e){let t=[],n=0,r=new Map(Object.entries(e.fileLayers??{}).map(([d,u])=>[ns(d),u])),s=new Map((e.layerContexts??[]).map(d=>[d.name,d.intentPrefixes??[]])),i=(e.layerContexts??[]).find(d=>rs(d.name,d.intentPrefixes))?.name??"DomainModel";for(let[d,u]of Object.entries(e.fileContents).sort(([g],[m])=>g.localeCompare(m))){let g=ns(d);if(Eo(g)||/GENERATED FILE\s+[—-]\s+do not edit by hand/i.test(u.slice(0,320)))continue;let m=r.has(g),c=r.get(g),l=c?s.get(c)??[]:[],p=/(?:^|\/)(?:components|ui|layouts|styles|hooks|theme|tokens|i18n|locales?)(?:\/|$)/i.test(g)||/(?:^|\/)(?:src\/)?(?:app|pages)\/.+\.(?:tsx|jsx)$/i.test(g)&&/(?:page|layout|loading|error|template|default)\.(?:tsx|jsx)$/i.test(g),y=/(?:^|\/)(?:app|pages)(?:\/[^/]+)*\/api(?:\/|$)/i.test(g),I=/(?:^|\/)actions?(?:\/|\.|$)/i.test(g)||/['"]use server['"]/.test(u),R=/controller|handler|resolver/i.test(d)||y||I||/route\.(?:ts|js|tsx|jsx)$/i.test(g)&&!p||/@(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),f=m?!!(c&&Ro(c,l)&&R):R,h=m?!!(c&&rs(c,l)):/domain|entity|aggregate|model/i.test(d),S=!m||h||f;if(f&&!p){let E=/\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,L;for(;(L=E.exec(u))!==null;)n+=1,t.push({id:`inv-val-${n}`,kind:"validation-in-controller",file:d,line:Bt(u,L.index),message:"Business validation appears in a controller/handler \u2014 extract an invariant or Domain rule.",confidence:"direct-evidence",governedLayer:c,suggestedArkRule:{layer:i,invariantId:`INV-EXTRACT-${n}`,sensor:"invariant-coverage"},neverMechanicalSafe:!0})}let k=/\b(const|let)\s+([A-Z][A-Z0-9_]{2,})\s*=\s*(\d{2,}|['"][^'"]{8,}['"])/g,N,D=E=>/^(?: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(E)||/^(?: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(E)||/_(?:ROUTE|PATH|LABEL|TITLE|COLOR|THEME|CLASS|STYLE|ICON|ARIA|MSG|COPY|TIMEOUT|PORT|VERSION|RETRY|DELAY|INTERVAL|TTL|CACHE)$/i.test(E)||/_(?:TIMEOUT(?:_MS)?|MS|BYTES|BUCKET|STORAGE_KEY|WINDOW_MS)$/i.test(E)||/^(?: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(E)||/^(?:FAVORITES_STORAGE|LISTINGS_CACHE|DOCS_PATH|METRICS_INTERVAL)/i.test(E)||/^(?:DEV|DEMO|SEED|FIXTURE)_[A-Z0-9_]+$/i.test(E)||/^(?:PG|POSTGRES|OID)_[A-Z0-9_]+$/i.test(E)||/_(?:OID|OIDS)$/i.test(E)||/^(?:INT2|INT4|INT8|FLOAT4|FLOAT8|NUMERIC|DATE|TIME|TIMESTAMP|TIMESTAMPTZ|JSON|JSONB|UUID)OID$/i.test(E)||/(?:^|_)(?:SCHEMA|PROTOCOL|RESOLVER|FORMAT)_(?:URL|URI|VERSION|ID|IDENTITY)$/i.test(E),_=(E,L)=>{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(E)||/_(?:MSG|MESSAGE|TEXT|COPY|TOAST|SNACK|ALERT|BANNER|CAPTION|HINT|HELP_TEXT|ERROR_TEXT|EMPTY_TEXT|PLACEHOLDER_TEXT|USER_MESSAGE|FEEDBACK)$/i.test(E))return!0;let T=L.replace(/^['"]|['"]$/g,"");return!!(/^['"]/.test(L)&&(/\s/.test(T)||/[.!?…]$/.test(T))&&!/^(?:STATUS|STATE|PHASE|ROLE|TYPE|KIND|ORDER|PAYMENT|CART|INVOICE|POLICY)_[A-Z0-9_]+$/i.test(E))};for(;(N=k.exec(u))!==null;){let E=N[2],L=N[3]??"";!S||D(E)||_(E,L)||p&&!h||/(?:^|\/)(?:integrations?|repos?|clients?|infra(?:structure)?|adapters?)(?:\/|$)/i.test(g)&&!h||(n+=1,t.push({id:`inv-magic-${n}`,kind:"magic-business-constant",file:d,line:Bt(u,N.index),message:`Magic business constant ${E} may belong in a Domain policy or invariant catalog.`,confidence:"heuristic",governedLayer:c,suggestedArkRule:{layer:i,invariantId:`INV-${E}`},neverMechanicalSafe:!0}))}if(h){let E=/export\s+class\s+([A-Za-z_][A-Za-z0-9_]*)\s*\{([^}]{0,800})\}/g,L;for(;(L=E.exec(u))!==null;){let T=L[2]??"",j=(T.match(/\b[a-zA-Z_][a-zA-Z0-9_]*\s*\(/g)??[]).length;(T.match(/:\s*[A-Za-z]/g)??[]).length>=2&&j<=1&&(n+=1,t.push({id:`inv-anemic-${n}`,kind:"anemic-entity",file:d,line:Bt(u,L.index),message:`Class ${L[1]} looks anemic (data-heavy, few behaviors).`,confidence:"heuristic",governedLayer:c,suggestedArkRule:{layer:i,structureId:"no-anemic-model",sensor:"no-anemic-model"},neverMechanicalSafe:!0}))}}if(h&&!(/\.error\.(?:ts|js|tsx|jsx)$/i.test(g)||/(?:^|\/)[^/]*(?:-access)?\.error\./i.test(g)||/(?:^|\/)errors?(?:\/|$)/i.test(g))){let L=/this\.\w+\s*=/g,T;for(;(T=L.exec(u))!==null;){let j=u.lastIndexOf("class ",T.index),de=j>=0?u.indexOf("{",j):-1,A=j>=0&&de>=j&&de<T.index?u.slice(j,de):"";if(/\bextends\s+(?:Error|[A-Za-z_$][A-Za-z0-9_$]*Error)\b/.test(A))continue;let B=u.slice(Math.max(0,T.index-200),T.index+200);if(!/\b(ensureInvariants|assertInvariants|validate|publish|emit)\b/.test(B)){n+=1,t.push({id:`inv-mut-${n}`,kind:"mutation-without-guard",file:d,line:Bt(u,T.index),message:"Domain field mutation without nearby guard/publish call.",confidence:"heuristic",governedLayer:c,suggestedArkRule:{layer:i,structureId:"events-on-mutation",sensor:"domain-event-on-mutation"},neverMechanicalSafe:!0});break}}}}let o=new Set(e.contractedRuleIds??[]);t.sort((d,u)=>+(u.confidence==="direct-evidence")-+(d.confidence==="direct-evidence")||d.file.localeCompare(u.file)||d.line-u.line||d.kind.localeCompare(u.kind)||d.id.localeCompare(u.id));let a=t.filter(d=>d.suggestedArkRule?.invariantId&&o.has(d.suggestedArkRule.invariantId)||d.suggestedArkRule?.structureId&&o.has(d.suggestedArkRule.structureId)).length;return{candidates:t,inventoried:t.length,underContract:a,frozen:(e.frozenKeys??[]).length,notAScore:!0}}function os(e){return{pilot:`Extract rule candidate ${e.id} (${e.kind})`,pilotTarget:e.file,smellId:e.kind,move:`Declare in arkrules/${e.suggestedArkRule?.layer??"DomainModel"}.json, implement pure Domain logic, add covering test.`,doNot:["Do not auto-apply codemods","Do not promote to enforced without coverage evidence","Do not batch multiple extractions"],successSignal:"Doctor reports candidate under contract; gate green with residual honest.",killSwitch:"Stop if extraction requires multi-module redesign without a clear aggregate owner.",neverMechanicalSafe:!0,class:"judgment",next:"Run ark_prepare_change / preflight, then re-doctor."}}var as="1.1";var ls="1.0";var Kt="docs/diagnostics.md",cs="1.0";function b(e,t,n,r,s,i){return{ruleId:e,title:n,why:r,fix:s,docsAnchor:e,category:t,...i?.oftenAdvisory?{oftenAdvisory:!0}:{}}}var nt=Object.freeze([b("LAYER_IMPORT_VIOLATION","layer","Layer import not allowed","A module import (or re-export) crosses a layer edge that ark.config.json does not allow. The architecture contract forbids that dependency direction so outer infrastructure cannot leak into pure or inner layers.","Define a port in the source layer, inject the outer-layer implementation, or move/share the type with `import type` when the edge is type-only \u2014 then preflight again. Do not weaken the layer rule without a hash-bound policy acknowledgement."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("ARKRULE_STRUCTURE","arkrules","ArkRule structure sensor failed","An opt-in ArkRules structure sensor (private state, factory shape, event publish, \u2026) failed on a governed file for a declared arkruleId.","Restore the declared structure for the ArkRule (see arkruleSource), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement."),b("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."),b("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}),b("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).","Add a test title or declared symbol covering the arkruleId, then preflight again. Missing test globs report partial \u2014 never fake green."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("DESIGN_SMELL_REGRESSION","preflight","Design smell regression on base-relative ratchet","Compared to the base ref, the candidate introduces or worsens a blocking design-smell class (e.g. domain-logic-in-ui) under --fail-on-new-smells.","Revert the regression or redesign so the smell does not worsen versus base, then re-run with the same base ref."),b("ANALYSIS_PARSE_INCOMPLETE","analysis","Parse incomplete","Governed source could not be fully parsed; analysis is partial and must not paint green.","Fix syntax/parse errors in governed files (or restore a usable TypeScript host), then re-run. Partial never means pass."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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}),b("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}),b("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}),b("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}),b("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}),b("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}),b("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}),b("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}),b("CONFIG_LAYER_PATTERN_NO_MATCHES","config","Layer pattern matched no files","A layer pattern matched zero included files (often a typo or include mismatch).","Adjust the pattern or include roots so governed files match.",{oftenAdvisory:!0}),b("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}),b("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}),b("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}),b("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}),b("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}),b("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.")]),Nn=new Map(nt.map(e=>[e.ruleId,e])),ds=Object.freeze(nt.map(e=>e.ruleId));function ps(e){return typeof e=="string"&&e.length>0&&Nn.has(e)}function us(e){return typeof e!="string"||e.length===0?!1:Nn.has(e)?!0:e.startsWith("ARKRULE_")}function rt(e){if(!(typeof e!="string"||e.length===0))return Nn.get(e)}function wn(e){return`#${rt(e)?.docsAnchor??e}`}function fs(e){return`${Kt}${wn(e)}`}function ms(){return{schemaVersion:"1.0",docsPath:Kt,codes:nt}}function gs(e){return rt(e)?.fix}function ys(e){return rt(e)?.why}var hs="1.0",Mn="https://unpkg.com/arkgate@4/schemas/ark.status-manifest.schema.json",$n=["full","subset","unavailable"],Fn=["doctor-facts","report-snapshot","none"],it={FACTS_UNAVAILABLE:"FACTS_UNAVAILABLE",FACTS_PARTIAL:"FACTS_PARTIAL",NO_SESSION_SNAPSHOT:"NO_SESSION_SNAPSHOT"},As=/^sha256:[a-f0-9]{64}$/;function Dn(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"||!As.test(r)))return{status:"mismatch",authoritative:!1,code:"INVALID_PROJECT_EXPECTATION",message:"project.expectedProjectId must be a sha256:<64 lowercase hex> identity."};if(n===void 0&&r!==void 0)return e.projectId&&r!==e.projectId?{status:"mismatch",authoritative:!1,expectedProjectId:r,code:"PROJECT_ID_MISMATCH",message:`Expected project id ${r}, but this process is bound to ${e.projectId}.`}:{status:"unverified",authoritative:!1,expectedProjectId:r,message:"project.expectedProjectId matched or could not be compared, but expectedRoot is required for an authoritative workspace binding."};let s=e.expectedRootRelation??"unknown";return s==="outside"?{status:"mismatch",authoritative:!1,expectedRoot:n,expectedProjectId:r,code:"PROJECT_ROOT_MISMATCH",message:`Expected workspace ${n}, but this process is bound to ${e.resolvedRoot}.`}:s==="unknown"?{status:"unverified",authoritative:!1,expectedRoot:n,expectedProjectId:r,message:"Could not prove expectedRoot against the resolved project root (stale or incomplete path evidence)."}:s==="descendant"&&r===void 0?{status:"unverified",authoritative:!1,expectedRoot:n,message:`Expected workspace ${n} is inside this project, but an exact project root is required for the initial authoritative handshake.`}:r!==void 0&&e.projectId&&r!==e.projectId?{status:"mismatch",authoritative:!1,expectedRoot:n,expectedProjectId:r,code:"PROJECT_ID_MISMATCH",message:`Expected project id ${r}, but this process is bound to ${e.projectId}.`}:s==="exact"||s==="descendant"&&r&&r===e.projectId?{status:"matched",authoritative:!0,...n?{expectedRoot:n}:{},...r?{expectedProjectId:r}:{}}:{status:"unverified",authoritative:!1,expectedRoot:n,expectedProjectId:r,message:"Project expectation could not be fully verified."}}function Hn(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"}function Vn(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)."}function jn(e,t,n,r,s){return e.nextActionOverride?.id&&e.nextActionOverride.summary?{id:e.nextActionOverride.id,summary:e.nextActionOverride.summary}:t.status==="mismatch"?{id:"rebind-project-identity",summary:t.message||"Project expectation does not match this process \u2014 call ark_identity / ark status with the correct expectedRoot (and projectId for descendants)."}:t.status==="unverified"&&e.expectation?{id:"complete-identity-handshake",summary:t.message||"Supply project.expectedRoot at the exact project root (and expectedProjectId for descendants) for authoritative status."}:e.resolvedConfigPath?r.verdict==="fail"||(r.activeViolations??0)>0?{id:"fix-active-violations",summary:`Clear ${r.activeViolations??"active"} blocking architecture finding(s), then re-run ark-check (or ark-check --doctor).`}:r.verdict==="incomplete"?{id:"restore-complete-analysis",summary:"Last check was incomplete \u2014 restore TypeScript/analysis inputs and re-run ark-check."}:r.verdict==null&&r.at==null?{id:"run-ark-check",summary:"No last-check snapshot yet \u2014 run ark-check --report (or --doctor) to freeze session evidence."}:n.writePath==="unavailable"?{id:"install-write-path",summary:"Write path is unavailable \u2014 install agent gates for your host (ark start / --install-agent-gates) and keep required CI --strict-merge."}:n.writePath==="advisory"?{id:"keep-ci-merge-hard",summary:"Local write is advisory for this host \u2014 keep a required GitHub status on arkgate-check --strict-merge as the hard merge boundary."}:e.leftoverDesignWork===!0?{id:"map-leftover-design",summary:"Leftover design work remains. Map with /ark-explore, then apply one small refactor with /ark-autopilot. Green imports are not done."}:s.arkRulesLoaded&&(s.frozenResidual??0)>0?{id:"review-arkrules-residual",summary:"ArkRules residual remains frozen \u2014 review inventory debt without claiming a score."}:{id:"stay-enforced",summary:"Contract looks enforceable for this session \u2014 keep writing through the gate and re-check after structural edits."}:{id:"run-ark-start",summary:"No ark.config.json found \u2014 run ark start (preview) then ark start --apply."}}function Is(e){let t=typeof e.resolvedRoot=="string"&&e.resolvedRoot.length>0?e.resolvedRoot:".",n=typeof e.projectId=="string"&&As.test(e.projectId)?e.projectId:null,r=Dn({resolvedRoot:t,projectId:n,expectation:e.expectation,expectedRootRelation:e.expectedRootRelation}),s=typeof e.activeHost=="string"?e.activeHost.trim().toLowerCase():"",i=s&&s!=="unknown"?s:s==="unknown"?"unknown":null,o=Hn({hardWriteActive:e.hardWriteActive,softWriteHost:e.softWriteHost,writePathUnavailable:e.writePathUnavailable,activeHost:i}),a=typeof e.honestLabel=="string"&&e.honestLabel.trim().length>0?e.honestLabel.trim():Vn(o,i),d={at:typeof e.lastCheckAt=="string"?e.lastCheckAt:null,verdict:e.lastCheckVerdict==="pass"||e.lastCheckVerdict==="fail"||e.lastCheckVerdict==="incomplete"?e.lastCheckVerdict:null,activeViolations:st(e.activeViolations),frozenResidual:st(e.frozenResidual)},u={arkRulesLoaded:e.arkRulesLoaded===!0,inventoried:st(e.rulesInventoried),underContract:st(e.rulesUnderContract),frozenResidual:st(e.rulesFrozenResidual)},g={writePath:o,host:i,honestLabel:a},m={projectId:n,resolvedRoot:t,resolvedConfigPath:typeof e.resolvedConfigPath=="string"&&e.resolvedConfigPath.length>0?e.resolvedConfigPath:null,binding:r.status,authoritative:r.authoritative,...r.code?{code:r.code}:{},...r.message?{message:r.message}:{}},c={schemaVersion:"1.0",arkgateVersion:typeof e.arkgateVersion=="string"&&e.arkgateVersion.length>0?e.arkgateVersion:"unknown",projectIdentity:m,activation:g,lastCheck:d,rules:u,nextAction:jn(e,r,g,d,u)},l=Un(e.improvementCompass);return l&&(c.improvementCompass=l),e.vsBase&&typeof e.vsBase.baseRef=="string"&&e.vsBase.baseRef.length>0&&(c.vsBase=e.vsBase),c}var bs=new Set($n),vo=new Set(Fn);function zt(e){let t=bs.has(e.mode)?e.mode:"unavailable",n=e.factsSource!=null&&vo.has(e.factsSource)?e.factsSource:t==="unavailable"?"none":void 0,r=typeof e.contractHash=="string"&&e.contractHash.length>0?e.contractHash:void 0;if(t==="unavailable"){let o={schemaVersion:"1.0",notAScore:!0,mode:"unavailable",topResidual:[],reasonCode:typeof e.reasonCode=="string"&&e.reasonCode.length>0?e.reasonCode:it.FACTS_UNAVAILABLE,reason:typeof e.reason=="string"&&e.reason.length>0?e.reason:"Improvement compass facts are unavailable \u2014 run ark-check --doctor for residual lenses. Status never invents green.",factsSource:n??"none"};return r&&(o.contractHash=r),o}let s=Array.isArray(e.topResidual)?e.topResidual.filter(o=>typeof o=="string"&&o.length>0).slice(0,15):[],i={schemaVersion:"1.0",notAScore:!0,mode:t,topResidual:s};return t==="subset"?(i.reasonCode=typeof e.reasonCode=="string"&&e.reasonCode.length>0?e.reasonCode:it.FACTS_PARTIAL,i.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&&(i.reasonCode=e.reasonCode),typeof e.reason=="string"&&e.reason.length>0&&t==="full"&&(i.reason=e.reason),n&&(i.factsSource=n),r&&(i.contractHash=r),i}function Ss(e={}){return zt({mode:"unavailable",topResidual:[],reasonCode:e.reasonCode??it.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})}function Un(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"&&bs.has(t.mode)?n=t.mode:Array.isArray(t.topResidual)?n="subset":n="unavailable",zt({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})}function Rs(e,t){let n=Array.isArray(e)?e:[],r=new Set(Array.isArray(t)?t:[]);for(let s of n)if(!(typeof s!="string"||s.length===0)&&!r.has(s))return!1;return!0}function st(e){if(e==null)return null;let t=Number(e);return!Number.isFinite(t)||t<0?null:Math.floor(t)}var Es={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Mn,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:"1.0"},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"}}}}};var ot="1.0",at=["soc","cohesion","coupling","srp","dip","ocp","encapsulation","modularity","scalability","resilience","security","maintainability","testability","domain","stack"],lt=5,ce=["scalability","resilience","security"],Pe=new Set(ce),Gn={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},Bn={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"},Kn={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 zn(e){return Bn[e]??e}function qn(e){let t=e.id??e.smellId??"";return typeof t=="string"?t.trim():""}function Yn(e){let t=e.ruleId??e.code??"";return typeof t=="string"?t.trim():""}function P(e,t,n,r){if(!n||e.evidence.some(i=>i.source===t&&i.ref===n))return;let s={source:t,ref:n};r&&r.trim()&&(s.detail=r.trim().slice(0,240)),e.evidence.push(s)}function H(e,t,n){Pe.has(e.id)||(e.status="residual",e.summary=t,n&&(e.nextAction=n))}function vs(e){switch(e){case"soc":return"No separation-of-concerns residual detected from current sensors.";case"cohesion":return"No cohesion residual (god-module / physical cohesion) from current sensors.";case"coupling":return"No coupling residual (import edges, cycles, peer isolation) from current sensors.";case"srp":return"No single-responsibility residual from current sensors.";case"dip":return"No dependency-inversion residual (pure / capability / forbidden walls) from current sensors.";case"ocp":return"Open/closed is not strongly instrumented \u2014 no switch-chain sensor.";case"encapsulation":return"No encapsulation residual from ArkRules structure sensors.";case"modularity":return"No modularity / placement residual from current sensors.";case"maintainability":return"No maintainability residual (design-weak / baseline honesty) from current sensors.";case"testability":return"No testability residual (impure domain / capability walls) from current sensors.";case"domain":return"No domain-alignment residual from current sensors.";case"stack":return"Stack practices are only partially instrumented (TypeScript / host / Ark idioms).";default:return`${Bn[e]} \u2014 no residual from current sensors.`}}function Cs(){return at.map(e=>Pe.has(e)?{id:e,status:"out-of-scope",summary:Kn[e],evidence:[],nextAction:{kind:"docs",ref:"docs/use.md#improvement-compass",summary:"Out of scope for ArkGate \u2014 use dedicated tooling outside the gate."}}:e==="ocp"?{id:e,status:"not-instrumented",summary:vs(e),evidence:[]}:{id:e,status:"ok",summary:vs(e),evidence:[]})}function Co(e,t){for(let n of t){let r=qn(n);if(!r)continue;let s=n.outcome||n.message||void 0,o=(Array.isArray(n.evidence)?n.evidence:[])[0],a=(g,m,c)=>{let l=e.get(g);!l||Pe.has(g)||(P(l,"designSmells",r,s),o&&P(l,"designSmells",o,r),H(l,m,c))},d={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":a("soc","Business rules still mix with UI or presentation surfaces.",d),a("domain","Domain logic lives outside Domain \u2014 align rules with Domain ownership.",d);break;case"facade-sql-in-routes":a("soc","Routes/controllers own SQL or ORM access \u2014 concerns are mixed.",d),a("dip","Transport depends on concrete persistence instead of a port.",u);break;case"io-under-application":a("soc","Application/business code reaches I/O directly \u2014 separation is weak.",d),a("dip","I/O is not inverted behind ports/adapters.",u),a("testability","Direct I/O under application code hurts pure unit testing.",u);break;case"handler-in-persistence":a("soc","HTTP/transport handlers live under persistence folders.",d);break;case"god-module":a("cohesion","Large multi-responsibility modules reduce cohesion.",d),a("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":a("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."}),a("cohesion","Mixed layout styles scatter the same concern across patterns.",d);break;case"soft-contract":a("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."}),a("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:a("maintainability","Design residual remains under an unrecognized smell id \u2014 review evidence.",d);break}}}function ko(e){return e.failsStrict===!1||e.typeOnly===!0}function _o(e,t){for(let n of t){let r=Yn(n);if(!r)continue;let s=n.message,i=r.toUpperCase(),o=(d,u,g)=>{let m=e.get(d);!m||Pe.has(d)||(P(m,"violations",r,s),n.file&&P(m,"violations",n.file,r),H(m,u,g))};if(ko(n)){o("modularity","Type-only placement debt remains \u2014 prefer SharedTypes / owning layer (not runtime coupling).",{kind:"skill",ref:"/ark-place",summary:"Place shared types in a layer both sides may import; type-only debt is not a value edge."});continue}let a={kind:"skill",ref:"/ark-autopilot",summary:"Clear the active edge residual, then re-doctor."};if(i==="LAYER_IMPORT_VIOLATION"||i.includes("LAYER_IMPORT")||i==="DYNAMIC_IMPORT_VIOLATION"){o("coupling","Import graph edges violate the layer contract.",a);continue}if(i.includes("CYCLE")||i==="CIRCULAR_DEPENDENCY"){o("coupling","Import cycles couple modules tightly.",a);continue}if(i.includes("PEER_ISOLATION")||i==="PEER_ISOLATION_VIOLATION"){o("coupling","Peer isolation residual \u2014 slices import each other freely.",{kind:"skill",ref:"/ark-autopilot",summary:"Peer isolation fixes are judgment-class \u2014 one cluster at a time."});continue}if(i==="FORBIDDEN_GLOBAL"||i.startsWith("FORBIDDEN_")){o("dip","Forbidden globals / effect surfaces break dependency inversion.",{kind:"skill",ref:"/ark-autopilot",summary:"Inject a port instead of the forbidden global."}),o("testability","Forbidden ambient effects reduce pure-domain testability.",{kind:"skill",ref:"/ark-autopilot",summary:"Replace ambient effects with injectable ports."});continue}if(i==="CAPABILITY_VIOLATION"){o("dip","Denied capability use \u2014 invert through an allowed adapter/port.",{kind:"skill",ref:"/ark-autopilot",summary:"Capability walls require port injection (judgment, not mechanical-safe)."}),o("testability","Capability violations couple domain code to I/O \u2014 harder to unit-test.",{kind:"skill",ref:"/ark-autopilot",summary:"Keep pure layers free of denied capabilities."});continue}if(i.startsWith("ARKRULE_")||i==="INVARIANT_UNCOVERED"){o("encapsulation","ArkRules structure / invariant residual inside a layer.",{kind:"skill",ref:"/ark-autopilot",summary:"Label [ArkRules]; structure fixes are judgment \u2014 never invent mechanical-safe."}),o("domain","Intra-layer domain structure or invariant coverage residual.",{kind:"skill",ref:"/ark-explore",summary:"Inventory candidates \u2192 one ArkRules pilot with coverage evidence."});continue}}}function xo(e,t){let n=Number(t.cycleCount)||0;if(n>0){let l=e.get("coupling");P(l,"cycles",`count:${n}`),H(l,"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 l=e.get("coupling");P(l,"peerIsolation",`count:${r}`),H(l,"Peer isolation residual remains.",{kind:"skill",ref:"/ark-autopilot",summary:"Peer isolation is judgment-class residual."})}let s=Number(t.physicalCohesionFindingCount)||0;if(s>0){let l=e.get("cohesion");P(l,"physicalCohesion",`findings:${s}`),H(l,"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 p=e.get("srp");P(p,"physicalCohesion",`findings:${s}`),H(p,"Mirrored clusters suggest split-by-concern residual (architecture SRP).",{kind:"skill",ref:"/ark-autopilot",summary:"One reshape/extraction pilot this turn."})}let i=Number(t.pureOrCapabilityResidual)||0,o=Number(t.forbiddenGlobalResidual)||0;if(i>0||o>0){let l=e.get("dip");i>0&&P(l,"capability",`residual:${i}`),o>0&&P(l,"forbiddenGlobals",`residual:${o}`),H(l,"Pure / capability / forbidden residual weakens dependency inversion.",{kind:"skill",ref:"/ark-autopilot",summary:"Inject ports; keep pure layers free of effects."});let p=e.get("testability");i>0&&P(p,"capability",`residual:${i}`),o>0&&P(p,"forbiddenGlobals",`residual:${o}`),H(p,"Impure domain or capability residual reduces testability.",{kind:"skill",ref:"/ark-autopilot",summary:"Prefer ports over concrete I/O in pure/domain modules."})}let a=Number(t.arkRulesStructureResidual)||0;if(a>0){let l=e.get("encapsulation");P(l,"arkRules",`structureResidual:${a}`),H(l,"ArkRules structure residual \u2014 encapsulation inside the layer.",{kind:"skill",ref:"/ark-autopilot",summary:"Fix structure sensors under [ArkRules] without inventing mechanical-safe."});let p=e.get("domain");P(p,"arkRules",`structureResidual:${a}`),H(p,"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 l=e.get("maintainability");P(l,"designFitness","design-weak"),H(l,"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 l=e.get("maintainability");t.dirtyBaselineRisk===!0&&P(l,"baseline","dirty-freeze-risk"),(Number(t.baselineStale)||0)>0&&P(l,"baseline",`stale:${t.baselineStale}`),H(l,"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 d=Number(t.frozenResidual)||0;if(t.baselineExists===!0&&d>=10&&e.get("maintainability").status!=="residual"){let l=e.get("maintainability");P(l,"baseline",`frozen:${d}`),H(l,"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,g=Number(t.emptyLayerCount)||0;if(u>0||g>0){let l=e.get("modularity");u>0&&P(l,"coverage",`ungovernedDirs:${u}`),g>0&&P(l,"coverage",`emptyLayers:${g}`),H(l,"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 l=e.get("modularity");P(l,"goldenPattern","absent"),H(l,"Design-weak without a golden pattern \u2014 new code lacks a placement norm for the AI.",{kind:"skill",ref:"/ark-place",summary:"Record an advisory golden pattern for new code (does not clear design-weak)."})}let m=e.get("stack");(t.stackKind??null)==="typescript"?m.status==="ok"&&(m.summary="Stack practices are partially instrumented for TypeScript / host / Ark idioms only \u2014 not a full framework checklist."):(m.status="not-instrumented",m.summary="Stack-specific best practices outside TypeScript/host/Ark idioms are not instrumented.",m.evidence=[],m.nextAction={kind:"docs",ref:"docs/use.md#improvement-compass",summary:"Ark does not score non-TS stack idioms."})}function ks(e,t){if(Array.isArray(t.designSmells)&&t.designSmells.length>0){let n=[...t.designSmells].sort((r,s)=>qn(r).localeCompare(qn(s)));Co(e,n)}if(Array.isArray(t.violations)&&t.violations.length>0){let n=[...t.violations].sort((r,s)=>{let i=Yn(r).localeCompare(Yn(s));return i!==0?i:String(r.file??"").localeCompare(String(s.file??""))});_o(e,n)}xo(e,t)}function _s(e){for(let t of ce){let n=e.get(t);n.status="out-of-scope",n.summary=Kn[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."}}}function xs(e){for(let t of e)t.evidence.sort((n,r)=>{let s=n.source.localeCompare(r.source);return s!==0?s:n.ref.localeCompare(r.ref)})}function Os(e){return e.filter(n=>n.status==="residual"&&!Pe.has(n.id)).slice().sort((n,r)=>{let s=Gn[n.id]??150,i=Gn[r.id]??150;return s!==i?s-i:n.id.localeCompare(r.id)}).slice(0,5).map(n=>n.id)}function Ts(e={}){let t=Cs(),n=new Map(t.map(s=>[s.id,s]));ks(n,e),_s(n),xs(t);let r=Os(t);return{schemaVersion:"1.0",notAScore:!0,lenses:t.map(s=>{let i={id:s.id,status:s.status,summary:s.summary,evidence:s.evidence.map(o=>({...o}))};return s.nextAction&&(i.nextAction={...s.nextAction}),i}),topResidual:r}}function Wn(e){return e.topResidual.map(t=>zn(t))}function Jn(e){for(let t of e.topResidual){let n=e.lenses.find(r=>r.id===t);if(n?.nextAction)return{...n.nextAction}}return null}function Ps(e){let t=Wn(e),n=ce.map(i=>zn(i)),r=Jn(e),s=[];return t.length>0?s.push(`Residual: ${t.join(" \xB7 ")}`):s.push("Residual: none on instrumented lenses (not a score \u2014 green edges \u2260 finished design)."),s.push(`Out of scope (honest): ${n.join(" \xB7 ")}`),r&&s.push(`Next: ${r.ref} \u2014 ${r.summary}`),s}var Ls="1.0",Ns="<!-- arkgate:agent-projection:begin",Zn="<!-- arkgate:agent-projection:end -->",Xn="This projection is **non-authoritative**. Enforcement is `ark-check` / host write hooks / required CI (`--strict-merge`), not AGENTS.md, skills, or this block.",Jt=Object.freeze(["ark-check","host-write-hooks","ci-strict-merge"]),ws=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"]),Qn=/<!--\s*arkgate:agent-projection:begin\b([^>]*)-->/i,Ms=/<!--\s*arkgate:agent-projection:end\s*-->/i,Oo=/\barkgateVersion=([A-Za-z0-9._+-]+)/i,To=/\bschema=([A-Za-z0-9._+-]+)/i;function ct(e){let t=String(e??"").replace(/\r\n/g,`
|
|
17
17
|
`),n=2166136261;for(let r=0;r<t.length;r+=1)n^=t.charCodeAt(r),n=Math.imul(n,16777619);return`fnv1a-${(n>>>0).toString(16).padStart(8,"0")}`}function qt(e){return String(e??"").replace(/\r\n/g,`
|
|
18
18
|
`)}function Le(e){let t=qt(e);return t.endsWith(`
|
|
19
19
|
`)?t:`${t}
|
|
20
20
|
`}function Zt(e){return typeof e!="string"||e.trim().length===0?"unknown":e.trim().replace(/[>\s]/g,"")}function $s(e){return e==="compact"?"compact":"full"}function er(e){let t=Zt(e.arkgateVersion);return`<!-- arkgate:agent-projection:begin schema=${typeof e.schemaVersion=="string"&&e.schemaVersion.trim()?e.schemaVersion.trim():"1.0"} arkgateVersion=${t} nonAuthoritative=true -->`}function Yt(e){return!Array.isArray(e)||e.length===0?"_No project layers loaded \u2014 read `ark.config.json` or run `ark start` / `ark_manifest`._":`| Layer | Patterns | Intent prefixes |
|
|
21
21
|
|-------|----------|-----------------|
|
|
22
|
-
${e.map(n=>{let r=n.name?.trim()||"Unknown",s=n.patterns??[],i=n.intentPrefixes??[],
|
|
22
|
+
${e.map(n=>{let r=n.name?.trim()||"Unknown",s=n.patterns??[],i=n.intentPrefixes??[],o=s.map(d=>`\`${d}\``).join(", ")||"\u2014",a=i.map(d=>`\`${d}\``).join(", ")||"\u2014";return`| ${r} | ${o} | ${a} |`}).join(`
|
|
23
23
|
`)}`}function tr(e,t){let n=t.trim()||"docs/diagnostics.md";return!Array.isArray(e)||e.length===0?`Full public codes: \`${n}\` (and package \`DIAGNOSTIC_CATALOG\`).`:`${e.filter(s=>s&&typeof s.ruleId=="string"&&s.ruleId.length>0).map(s=>{let i=typeof s.title=="string"&&s.title.trim()?s.title.trim():s.ruleId;return`- \`${s.ruleId}\` \u2014 ${i}`}).join(`
|
|
24
24
|
`)}
|
|
25
25
|
|
|
26
|
-
Full catalog: \`${n}\` (\`#RULE_ID\` anchors).`}function Xt(e){let t=Zt(e.arkgateVersion),n=$s(e.profile),r=typeof e.checkCommand=="string"&&e.checkCommand.trim()?e.checkCommand.trim():"ark-check --strict-config",s=typeof e.diagnosticsDocsPath=="string"&&e.diagnosticsDocsPath.trim()?e.diagnosticsDocsPath.trim():"docs/diagnostics.md",i=typeof e.host=="string"?e.host.trim().toLowerCase():"",
|
|
26
|
+
Full catalog: \`${n}\` (\`#RULE_ID\` anchors).`}function Xt(e){let t=Zt(e.arkgateVersion),n=$s(e.profile),r=typeof e.checkCommand=="string"&&e.checkCommand.trim()?e.checkCommand.trim():"ark-check --strict-config",s=typeof e.diagnosticsDocsPath=="string"&&e.diagnosticsDocsPath.trim()?e.diagnosticsDocsPath.trim():"docs/diagnostics.md",i=typeof e.host=="string"?e.host.trim().toLowerCase():"",o=i&&i!=="unknown"?i:null,a=Array.isArray(e.layers)?e.layers:[],d=Array.isArray(e.catalogShortList)?e.catalogShortList:[],u=["## ArkGate agent contract projection","",Xn,"",`- **arkgateVersion:** \`${t}\` (must match the installed package; regenerate with \`ark agents-md --write\` after upgrade)`,"- **projectionSchema:** `1.0`",`- **profile:** \`${n}\`${o?` \xB7 **host:** \`${o}\``:""}`,`- **after edits:** \`${r}\``,""];return n==="compact"?u.push("### Primary path","","1. Run doctor (`ark-check --doctor`) \u2014 status light + primary next action.","2. Read the improvement compass (not a score). Name leftover work in plain language; never \u201Cdone\u201D on green imports alone while leftover design work remains.","3. Call `ark_identity` with `project.expectedRoot` at the exact project root; reuse root + `projectId` on Ark MCP calls.","4. Read architecture config with `ark_manifest` (same expectation). `ark://manifest` is compatibility-only / unverified.","5. Place files inside configured layers; validate; run the check command above on violations \u2014 fix architecture, do not weaken the gate.","6. Single door: import-rule debt \u2192 fix; leftover design work / residual shape lenses \u2192 map then guided apply with user OK.","","### Contract layers (summary)","",Yt(a),""):u.push("### Contract layers","",Yt(a),"","When creating a **new** kind of code that no layer covers, update `ark.config.json` first (`/ark-adopt`), then place the file.","","### Diagnostic codes (short list)","",tr(d,s),"","### Session truth","","- Machine snapshot: `ark status --json` (or MCP `ark_status`) \u2014 identity, activation honesty, last check, residual counts. **Not a score.**","- Authoritative contract: `ark_manifest` after a matched `ark_identity` handshake.",""),u.push("### Enforcement surfaces (authoritative)","",Jt.map(g=>`- \`${g}\``).join(`
|
|
27
27
|
`),""),u.join(`
|
|
28
28
|
`).replace(/\n{3,}/g,`
|
|
29
29
|
|
|
30
30
|
`).trimEnd()+`
|
|
31
31
|
`}function Fs(e){let t=Xt(e);return`${er({arkgateVersion:e.arkgateVersion,schemaVersion:"1.0"})}
|
|
32
32
|
${t}${Zn}
|
|
33
|
-
`}function Ds(e){let t=Xt(e),n=Array.isArray(e.layers)?e.layers:[],r=Array.isArray(e.catalogShortList)?e.catalogShortList:[];return{schemaVersion:"1.0",arkgateVersion:Zt(e.arkgateVersion),nonAuthoritative:!0,enforcementSurfaces:[...Jt],contentIdentity:ct(t),layerCount:n.length,catalogCodeCount:r.filter(s=>s?.ruleId).length,profile:$s(e.profile)}}function Wt(e){let t=qt(e??""),n=Qn.exec(t);if(!n)return{block:null,body:null,before:t,after:"",beginAttrs:null};let r=n.index,s=r+n[0].length,i=t.slice(s),
|
|
34
|
-
`)&&(u=u.slice(1));let g=t.slice(r,s+d),m=i.slice(d);return{block:g,body:u,before:t.slice(0,r),after:m,beginAttrs:n[1]??""}}function nr(e){let t=String(e??""),r=Qn.exec(t)?.[1]??t,s=
|
|
33
|
+
`}function Ds(e){let t=Xt(e),n=Array.isArray(e.layers)?e.layers:[],r=Array.isArray(e.catalogShortList)?e.catalogShortList:[];return{schemaVersion:"1.0",arkgateVersion:Zt(e.arkgateVersion),nonAuthoritative:!0,enforcementSurfaces:[...Jt],contentIdentity:ct(t),layerCount:n.length,catalogCodeCount:r.filter(s=>s?.ruleId).length,profile:$s(e.profile)}}function Wt(e){let t=qt(e??""),n=Qn.exec(t);if(!n)return{block:null,body:null,before:t,after:"",beginAttrs:null};let r=n.index,s=r+n[0].length,i=t.slice(s),o=Ms.exec(i);if(!o)return{block:null,body:null,before:t,after:"",beginAttrs:null};let a=o.index,d=a+o[0].length,u=i.slice(0,a);u.startsWith(`
|
|
34
|
+
`)&&(u=u.slice(1));let g=t.slice(r,s+d),m=i.slice(d);return{block:g,body:u,before:t.slice(0,r),after:m,beginAttrs:n[1]??""}}function nr(e){let t=String(e??""),r=Qn.exec(t)?.[1]??t,s=Oo.exec(r),i=To.exec(r),o=/\bnonAuthoritative\s*=\s*true\b/i.test(r);return{arkgateVersion:s?.[1]??null,schemaVersion:i?.[1]??null,nonAuthoritative:o}}function Hs(e,t){let n=nr(e).arkgateVersion;return n?n===Zt(t):!1}function Vs(e){return String(e??"").includes("non-authoritative")}function js(e,t){let n=Le(qt(t)),s=Wt(n).body??n.replace(Qn,"").replace(Ms,"").trim()+`
|
|
35
35
|
`,i=ct(s);if(e==null||!String(e).trim())return{content:Le(`# Ark Enforcement
|
|
36
36
|
|
|
37
|
-
${n}`),action:"created",previousBlock:null,contentIdentity:i,preservedOutsideBlock:!1};let
|
|
37
|
+
${n}`),action:"created",previousBlock:null,contentIdentity:i,preservedOutsideBlock:!1};let o=qt(e),a=Wt(o);if(a.block!=null){let u=a.body??"";if(ct(u)===i)return{content:Le(o),action:"unchanged",previousBlock:a.block,contentIdentity:i,preservedOutsideBlock:!0};let g=a.before.replace(/\s*$/,`
|
|
38
38
|
|
|
39
|
-
`),m=
|
|
39
|
+
`),m=a.after.replace(/^\s*/,`
|
|
40
40
|
`);return{content:Le(`${g}${n.trimEnd()}
|
|
41
|
-
${m}`),action:"block-replaced",previousBlock:
|
|
41
|
+
${m}`),action:"block-replaced",previousBlock:a.block,contentIdentity:i,preservedOutsideBlock:!0}}let d=/^(#\s+[^\n]*\n)/m.exec(o);if(d&&d.index!=null){let u=d.index+d[1].length,g=o.slice(0,u).replace(/\s*$/,`
|
|
42
42
|
|
|
43
|
-
`),m=
|
|
43
|
+
`),m=o.slice(u).replace(/^\s*/,`
|
|
44
44
|
`);return{content:Le(`${g}${n.trimEnd()}
|
|
45
45
|
${m}`),action:"block-inserted",previousBlock:null,contentIdentity:i,preservedOutsideBlock:!0}}return{content:Le(`${n.trimEnd()}
|
|
46
46
|
|
|
47
|
-
${
|
|
47
|
+
${o.trimStart()}`),action:"block-inserted",previousBlock:null,contentIdentity:i,preservedOutsideBlock:!0}}var Us="1.0",rr="templates/agent-skills",sr="templates/skills",ir="SKILL.md",dt=Object.freeze(["ark-adopt","ark-architect","ark-autopilot","ark-contract","ark-coverage","ark-explain","ark-explore","ark-fix","ark-loop","ark-place","ark-runtime","ark-think","ark-upgrade"]),or=dt.length,Po=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function ar(e){return typeof e!="string"||e.length<1||e.length>64?!1:Po.test(e)}function en(e){return dt.includes(e)}function lr(e){let t=String(e??"").replace(/^\uFEFF/,""),n=t.includes(`\r
|
|
48
48
|
`)?`\r
|
|
49
49
|
`:`
|
|
50
|
-
`,r=t.split(/\r?\n/);if(r[0]!=="---")return{hasFrontmatter:!1,frontmatter:null,body:t};let s=r.indexOf("---",1);if(s===-1)return{hasFrontmatter:!1,frontmatter:null,body:t};let i={};for(let g=1;g<s;g+=1){let m=r[g]??"";if(m.trim()===""||m.trimStart().startsWith("#"))continue;let c=m.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);if(!c)continue;let l=c[1],p=c[2]??"";(p.startsWith('"')&&p.endsWith('"')&&p.length>=2||p.startsWith("'")&&p.endsWith("'")&&p.length>=2)&&(p=p.slice(1,-1)),i[l]=p}let
|
|
50
|
+
`,r=t.split(/\r?\n/);if(r[0]!=="---")return{hasFrontmatter:!1,frontmatter:null,body:t};let s=r.indexOf("---",1);if(s===-1)return{hasFrontmatter:!1,frontmatter:null,body:t};let i={};for(let g=1;g<s;g+=1){let m=r[g]??"";if(m.trim()===""||m.trimStart().startsWith("#"))continue;let c=m.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);if(!c)continue;let l=c[1],p=c[2]??"";(p.startsWith('"')&&p.endsWith('"')&&p.length>=2||p.startsWith("'")&&p.endsWith("'")&&p.length>=2)&&(p=p.slice(1,-1)),i[l]=p}let o=r.slice(s+1).join(n),a=typeof i.name=="string"&&i.name.length>0?i.name:null,d=typeof i.description=="string"&&i.description.length>0?i.description:null,u=typeof i.license=="string"&&i.license.length>0?i.license:null;return{hasFrontmatter:!0,frontmatter:{fields:i,name:a,description:d,license:u},body:o}}function cr(e){let t=e.requireArkSkillName!==!1,n=e.requireBody!==!1,r=[],s=String(e.directoryName??""),i=lr(e.content);if(!i.hasFrontmatter||!i.frontmatter)return r.push({code:"MISSING_FRONTMATTER",message:`Skill "${s}" is missing YAML frontmatter fences.`,skillName:s||void 0}),r;let{name:o,description:a}=i.frontmatter,d=o??(s||void 0);return!o||!ar(o)?r.push({code:"INVALID_NAME",message:`Skill name "${o??""}" is invalid (Agent Skills: 1\u201364 chars, [a-z0-9-], no leading/trailing/consecutive hyphens).`,skillName:d}):o!==s?r.push({code:"NAME_DIRECTORY_MISMATCH",message:`Frontmatter name "${o}" must match directory name "${s}".`,skillName:o}):t&&!en(o)&&r.push({code:"UNKNOWN_SKILL_NAME",message:`Skill name "${o}" is not in the frozen Ark 13-skill catalog (no new skill names).`,skillName:o}),a?a.length>1024&&r.push({code:"DESCRIPTION_TOO_LONG",message:`Skill "${s}" description exceeds 1024 characters (${a.length}).`,skillName:d}):r.push({code:"MISSING_DESCRIPTION",message:`Skill "${s}" is missing a non-empty description.`,skillName:d}),n&&i.body.trim().length===0&&r.push({code:"EMPTY_BODY",message:`Skill "${s}" has an empty instruction body.`,skillName:d}),r}function Gs(e){let t=[],n=new Set,r=[];for(let s of e){let i=String(s.name??"");if(n.has(i)){t.push({code:"DUPLICATE_SKILL",message:`Duplicate skill entry "${i}".`,skillName:i});continue}n.add(i),r.push(i),t.push(...cr({directoryName:i,content:s.content,requireArkSkillName:!0,requireBody:!0})),s.flatTemplateContent!=null&&Qt(s.content)!==Qt(s.flatTemplateContent)&&t.push({code:"CONTENT_MISMATCH",message:`Agent Skills SKILL.md for "${i}" does not match flat template templates/skills/${i}.md.`,skillName:i})}for(let s of dt)n.has(s)||t.push({code:"MISSING_SKILL",message:`Missing frozen skill "${s}" from Agent Skills package.`,skillName:s});for(let s of r)en(s)||(t.some(i=>i.code==="UNKNOWN_SKILL_NAME"&&i.skillName===s)?t.push({code:"EXTRA_SKILL",message:`Extra skill "${s}" is not in the frozen Ark 13-skill catalog.`,skillName:s}):t.push({code:"EXTRA_SKILL",message:`Extra skill "${s}" is not in the frozen Ark 13-skill catalog.`,skillName:s}));return r.sort(),{ok:t.length===0,issues:t,names:r,expectedCount:or,presentCount:r.length}}function Qt(e){return String(e??"").replace(/^\uFEFF/,"").replace(/\r\n/g,`
|
|
51
51
|
`)}function dr(e){return`${e}/${ir}`}function Bs(e){return`${rr}/${dr(e)}`}function Ks(e){return`${sr}/${e}.md`}0&&(module.exports={ADAPTER_DIAGNOSTIC_DOCS_RELATIVE_PATH,AGENT_PROJECTION_BEGIN_MARKER,AGENT_PROJECTION_END_MARKER,AGENT_PROJECTION_ENFORCEMENT_SURFACES,AGENT_PROJECTION_NON_ENFORCEMENT_LABEL,AGENT_SKILLS_PACKAGE_RELATIVE_ROOT,AGENT_SKILL_ENTRY_FILENAME,ANALYSIS_IR_SCHEMA_VERSION,ARK_AGENT_PROJECTION_SCHEMA_VERSION,ARK_AGENT_SKILLS_PACKAGE_SCHEMA_VERSION,ARK_ANALYSIS_RESULT_SCHEMA,ARK_ANALYSIS_RESULT_SCHEMA_VERSION,ARK_CONFIG_SCHEMA,ARK_CONFIG_SCHEMA_VERSION,ARK_DESIGN_DELTA_SCHEMA_VERSION,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION,ARK_IMPROVEMENT_COMPASS_SCHEMA_VERSION,ARK_PROJECT_IDENTITY_SCHEMA,ARK_PROJECT_IDENTITY_SCHEMA_URL,ARK_PROJECT_IDENTITY_SCHEMA_VERSION,ARK_RULES_SCHEMA,ARK_RULES_SCHEMA_VERSION,ARK_RULE_SENSORS,ARK_SKILL_NAMES,ARK_SKILL_NAME_COUNT,ARK_STATUS_MANIFEST_SCHEMA,ARK_STATUS_MANIFEST_SCHEMA_URL,ARK_STATUS_MANIFEST_SCHEMA_VERSION,DEFAULT_AGENT_PROJECTION_RULE_IDS,DIAGNOSTIC_CATALOG,DIAGNOSTIC_CATALOG_SCHEMA_VERSION,DIAGNOSTIC_DOCS_RELATIVE_PATH,DIAGNOSTIC_RULE_IDS,EffectiveContractError,FLAT_SKILL_TEMPLATES_RELATIVE_ROOT,IMPROVEMENT_COMPASS_OUT_OF_SCOPE_LENSES,IMPROVEMENT_COMPASS_TOP_RESIDUAL_CAP,IMPROVEMENT_LENS_IDS,POLICY_DELTA_SCHEMA_VERSION,PROJECT_BINDING_SCHEMA,PROJECT_EXPECTATION_SCHEMA,RESOLVED_CANDIDATE_FACTS_SCHEMA,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,STATUS_COMPASS_FACTS_SOURCES,STATUS_COMPASS_MODES,STATUS_COMPASS_REASON_CODES,adapterDocsCodePath,adapterFindingOccurrenceTargetKeys,adapterFindingRefFromTargetKey,adapterFindingTargetKey,agentProjectionContentIdentity,agentSkillEntryRelativePath,agentSkillPackageFileRelativePath,analyzeArchitectureConvergence,analyzeChange,analyzePolicyDelta,analyzeProject,analyzeResolvedProject,buildAgentProjectionBeginMarker,buildAgentProjectionBlock,buildAgentProjectionBody,buildAgentProjectionMeta,buildArkRuleFileHints,buildEffectiveArkRules,buildImprovementCompass,buildRulesInventory,buildStatusManifest,canPromoteInvariant,catalogFixForRuleId,catalogWhyForRuleId,classifyArkPolicyDelta,classifyStatusWritePath,collectAnalysisConfigWarnings,collectEmptyAppliesToFindings,collectForbiddenCapabilityUses,createAICodeGate,createAdapterResult,createArchitectureProfile,createArchitectureProfileFromArkConfig,createElevenLayerArkConfig,createProjectId,createProjectIdentity,createResolvedCandidateFacts,defaultHonestLabel,deriveArkRuleFileHints,detectArchitectureCycles,deterministicHash,diagnosticDocsFragment,diagnosticDocsPath,effectiveContractPolicyPayload,elevenLayerProfile,emptyEffectiveArkRules,evaluateArchitectureGraph,evaluateArkRuleSensors,evaluateInvariantCoverage,evaluateStatusBinding,explainViolation,extractAgentProjectionBlock,extractClassShapesFromSource,extractSemanticDependencies,flatSkillTemplateFileRelativePath,formatAgentProjectionCatalogShortList,formatAgentProjectionLayers,formatImprovementCompassDoctorLines,formatImprovementCompassResidualLabels,getDiagnosticCatalogEntry,inventoryToExtractionCard,isArkSkillName,isCataloguedOrArkRuleFamily,isKnownDiagnosticCode,isValidAgentSkillName,loadArkConfigContract,loadArkRulesContract,loadContract,loadResolvedCandidateFacts,mergeAgentProjectionDocument,normalizeSkillContent,normalizeStatusImprovementCompass,parseAgentProjectionStamp,parseArkConfigJson,parseArkRulesJson,parseSkillDocument,policyDeltaAcknowledgementMatches,preflightChange,preflightResolvedChange,primaryImprovementCompassNextAction,projectStatusImprovementCompass,projectionHasNonEnforcementLabel,projectionMatchesPackageVersion,resolveEffectiveContract,resolveStatusNextAction,resolvedFactsEvidenceRequirementsHash,serializeDiagnosticCatalog,stableSerialize,statusCompassResidualIsSubsetOfDoctor,toAdapterDiagnostic,unavailableStatusImprovementCompass,validateAgentSkillDocument,validateAgentSkillsPackage,version});
|