arkgate 4.7.4 → 4.7.6

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/dist/index.d.ts CHANGED
@@ -704,7 +704,7 @@ declare function loadArkConfigContract(input: unknown, source?: string): ArkConf
704
704
  declare function parseArkConfigJson(json: string, source?: string): ArkConfigLoadResult;
705
705
 
706
706
  /** ArkGate library version — single source of truth. */
707
- declare const version = "4.7.4";
707
+ declare const version = "4.7.6";
708
708
 
709
709
  /**
710
710
  * Canonical, pure contract for ArkGate MCP project identity.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- var zs="4.7.4";var qs=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,Ys=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,Ws=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function Js(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),s=String(t?.toLayer??"");return qs.test(n)?"pure-shared":r==="PersistenceAdapters"&&(Ys.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${s} ${n}`))?"kernel-emit":Ws.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&s==="PersistenceAdapters"?"use-case":"unknown"}function Zs(e){if(e.typeOnly||e.targetTypeOnlyExports||e.namedBindingsTypeOnly)return"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.";if(e.peerIsolation)return"Extract the shared dependency to a shared layer, test at the public interface, then preflight again.";let t=Js(typeof e.target=="string"?e.target:"",{fromLayer:typeof e.fromLayer=="string"?e.fromLayer:void 0,toLayer:typeof e.toLayer=="string"?e.toLayer:void 0});return t==="pure-shared"?"Adopt the imported constants/types/pure module into DomainModel or SharedKernel (do not inject a port). Then preflight again.":t==="kernel-emit"?"Persistence must not emit. Inject a port or move the event map to SharedTypes; do not import kernel/events/bootstrap from a repository. Then preflight again.":t==="use-case"||e.portProofEligible?`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, test at the public interface, then preflight again.`:"Classify the import: if it is constants/types/pure, adopt into DomainModel or SharedKernel; define a port only if the target is a real use-case. Then preflight again."}function Xs(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}function Qs(e){let t=Xs(e),n=typeof e.fromLayer=="string"&&e.fromLayer.length>0?e.fromLayer:void 0;switch(e.ruleId){case"ARKRUN_MISSING_ROOT":return t?`Import createStrictArkKernel from @arkgate/runtime and call it in composition root ${t} listed in arkRun.compositionRoots, then preflight again.`:"Import createStrictArkKernel from @arkgate/runtime (never a removed arkgate/runtime shim) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKRUN_KERNEL_IN_DOMAIN":return t?`Move the kernel import of ${t} out of ${n??"the Domain-role layer"} into a composition root or adapter. Import from @arkgate/runtime, never a removed arkgate/runtime shim, then preflight again.`:"Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from @arkgate/runtime, never a removed arkgate/runtime shim, then preflight again. Never mechanical-safe.";case"ARKRUN_DIRECT_NEW":return t?`Resolve ${t} from the kernel instead of constructing it with new, then preflight again.`:"Resolve the type from the kernel instead of constructing it with new, then preflight again. Never mechanical-safe \u2014 rewiring construction is a design decision.";case"ARKRUN_UNDECLARED_EMIT":return t?`Add ${t} to raises or sends on the managed component, then preflight again.`:"Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment.";case"ARKRUN_UNDECLARED_HANDLE":return t?`Add ${t} to reactsTo on the managed component, then preflight again.`:"Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment.";case"ARKRUN_UNDECLARED_DEPEND":return t?`Add ${t} to uses on the managed component, then preflight again.`:"Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment.";case"ARKRUN_TRANSPORT_BYPASS":return t?`Send through the ArkRun kernel transport instead of importing ${t}, then preflight again.`:"Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe \u2014 homemade buses stay judgment.";default:return`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}function me(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return Zs(e);case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, test at the public interface, then preflight again.`;case"CAPABILITY_VIOLATION":return`Define a ${String(e.capability??"capability")} port in ${e.fromLayer??"the walled layer"}, bind the implementation outside it, test at the public interface, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, test at the public interface, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";case"ARKRULE_STRUCTURE":case"ARKRULE_INVARIANT":case"INVARIANT_UNCOVERED":return`Fix the structure or invariant for ${typeof e.arkruleId=="string"&&e.arkruleId.length>0?e.arkruleId:"the ArkRule"} (declared in ${typeof e.arkruleSource=="string"&&e.arkruleSource.length>0?e.arkruleSource:"arkrules/<Layer>.json"}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`;case"ARKRUN_MISSING_ROOT":case"ARKRUN_KERNEL_IN_DOMAIN":case"ARKRUN_DIRECT_NEW":case"ARKRUN_UNDECLARED_EMIT":case"ARKRUN_UNDECLARED_HANDLE":case"ARKRUN_UNDECLARED_DEPEND":case"ARKRUN_TRANSPORT_BYPASS":return Qs(e);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.`}}var Kt="1.5",sr="docs/diagnostics.md";function _(e){return typeof e=="string"&&e.length>0?e:void 0}function rr(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function Gt(e){let t=typeof e.ruleId=="string"?e.ruleId:typeof e.code=="string"?e.code:void 0,n=typeof e.file=="string"?e.file:void 0,r=typeof e.fromLayer=="string"?e.fromLayer:void 0,s=typeof e.toLayer=="string"?e.toLayer:void 0,o=typeof e.target=="string"?e.target:void 0;return[t,n,r??"",s??"",o??""].join("|")}function jt(e){let t=new Map;return e.map(n=>{let r=Gt(n),s=(t.get(r)??0)+1;return t.set(r,s),s===1?r:`${r}#${s}`})}function or(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 ar(e){return`${sr}#${e}`}function eo(e,t,n){return me({ruleId:e,target:_(t.target)??_(n.target)??void 0,fromLayer:_(t.fromLayer)??void 0,toLayer:_(t.toLayer)??void 0,typeOnly:t.typeOnly===!0,targetTypeOnlyExports:t.targetTypeOnlyExports===!0,namedBindingsTypeOnly:t.namedBindingsTypeOnly===!0,portProofEligible:t.portProofEligible===!0,peerIsolation:t.peerIsolation===!0,sourcePureTypeModule:t.sourcePureTypeModule===!0,edgeKind:_(t.edgeKind)??void 0,capability:_(t.capability)??_(n.capability)??void 0,arkruleId:_(t.arkruleId)??void 0,arkruleSource:_(t.arkruleSource)??void 0})}function Ut(e,t="error",n){let r=_(e.ruleId)??_(e.code)??"ARK_UNKNOWN",s=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,o={..._(e.target)?{target:_(e.target)}:{},..._(e.fromLayer)?{fromLayer:_(e.fromLayer)}:{},..._(e.toLayer)?{toLayer:_(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{},...typeof e.targetTypeOnlyExports=="boolean"?{targetTypeOnlyExports:e.targetTypeOnlyExports}:{},...typeof e.sourcePureTypeModule=="boolean"?{sourcePureTypeModule:e.sourcePureTypeModule}:{},...typeof e.namedBindingsTypeOnly=="boolean"?{namedBindingsTypeOnly:e.namedBindingsTypeOnly}:{},...typeof e.portProofEligible=="boolean"?{portProofEligible:e.portProofEligible}:{},...typeof e.peerIsolation=="boolean"?{peerIsolation:e.peerIsolation}:{},..._(e.capability)?{capability:_(e.capability)}:{},..._(e.edgeKind)?{edgeKind:_(e.edgeKind)}:{},..._(e.arkruleId)?{arkruleId:_(e.arkruleId)}:{},..._(e.arkruleSource)?{arkruleSource:_(e.arkruleSource)}:{}},a=n??Gt(e),i=or(a);return{ruleId:r,severity:s,message:_(e.message)??r,location:{file:_(e.file)??"<unknown>",line:rr(e.line,1),column:rr(e.column,1)},evidence:o,nextAction:_(e.nextAction)??eo(r,o,e),findingRef:i,targetKey:a,docsCodePath:ar(r)}}function to(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:_(m.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:_(m.message)??`Analysis ${t}: required evidence is incomplete.`,..._(m.file)?{file:_(m.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],s={..._(e.policyHash)?{policyHash:_(e.policyHash)}:{},..._(e.resolverIdentity)?{resolverIdentity:_(e.resolverIdentity)}:{},..._(e.factsHash)?{factsHash:_(e.factsHash)}:{},..._(e.candidateTreeHash)?{candidateTreeHash:_(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let m of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!s[m])throw new Error(`${m} is required for resolved ${t} adapter evidence.`)}let o=e.violations??[],a=e.warnings??[],i=jt(o),l=jt(a),u=[...o.map((m,d)=>Ut(m,"error",i[d])),...a.map((m,d)=>Ut(m,"warning",l[d]))],f={schemaVersion:Kt,completenessReasons:r,diagnostics:u};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...f,mode:n,valid:!1,completeness:t,...s};let m={policyHash:s.policyHash,resolverIdentity:s.resolverIdentity,factsHash:s.factsHash,candidateTreeHash:s.candidateTreeHash};return t==="complete"?{...f,mode:n,valid:e.valid,completeness:t,...m}:{...f,mode:n,valid:!1,completeness:t,...m}}return t==="complete"?{...f,mode:n,valid:e.valid,completeness:t,...s}:{...f,mode:n,valid:!1,completeness:t,...s}}var no={$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:Kt},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 ro="1.0",ir="https://unpkg.com/arkgate@4/schemas/ark.project-identity.schema.json",ct="^sha256:[a-f0-9]{64}$",lr={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:ct,description:"Project id previously returned by ark_identity or ark_manifest."}}},cr={type:"object",additionalProperties:!1,required:["status","authoritative"],properties:{status:{enum:["matched","unverified","mismatch"]},authoritative:{type:"boolean"},expectedRoot:{type:"string",minLength:1},expectedProjectId:{type:"string",pattern:ct},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},so={$schema:"https://json-schema.org/draft/2020-12/schema",$id:ir,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:ct},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{type:"string",minLength:1},arkgateVersion:{type:"string",minLength:1},contractHash:{type:"string",pattern:ct},contractSource:{enum:["project","default-profile","manifest"]},runtimeId:{type:"string",minLength:1},processStartedAt:{type:"string",format:"date-time"}},$defs:{expectation:lr,binding:cr}};function oo(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 ao(e){return{schemaVersion:"1.0",...e}}var zt=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),Yt=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Wt=Object.freeze(Object.keys(Yt).sort()),Bt=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"}),qt=Object.freeze({process:Object.freeze(["process","node:process"])});function Ve(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=Bt[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),s=Bt[r];if(s)return s;let o=e.indexOf("/",n+1);return o<0?null:Bt[e.slice(0,o)]??null}function ge(e,t){for(let n of t)if(qt[n]?.includes(e))return n;return null}function dt(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),s=Yt[r];if(s)return s}return null}function be(e){if(e?.pure===!0)return[...zt].sort();let n=(e?.capabilities?.deny??[]).filter(r=>zt.includes(r));return[...new Set(n)].sort()}function je(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 ut(e){let t=new Set,n=new Set,r=Object.keys(Yt);for(let s of e?.forbiddenGlobals??[]){let o=r.filter(a=>a===s||a.startsWith(`${s}.`));if(o.length===0)n.add(s);else for(let a of o)t.add(`ambient:${a}`);for(let a of qt[s]??[])t.add(`import-exact:${a}`)}for(let s of be(e)){if(t.add(`import:${s}`),s==="process")for(let o of qt.process)t.add(`import-exact:${o}`);for(let o of r)dt(o)===s&&t.add(`ambient:${o}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}var dr=new Map;function ur(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function pt(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 io(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 he(e){let t=dr.get(e);if(t)return t;let n=pt(e),r=io(n),s="",o=0;for(let i=0;i<n.length;i+=1){let l=n[i];l==="\\"&&i+1<n.length?(s+=ur(n[i+1]),i+=1):l==="*"?n[i+1]==="*"?n[i+2]==="/"?(s+="(?:.*/)?",i+=2):(s+=".*",i+=1):s+="[^/]*":l==="?"?s+="[^/]":l==="{"&&r?(s+="(?:",o+=1):l==="}"&&r&&o>0?(s+=")",o-=1):l===","&&r&&o>0?s+="|":s+=ur(l)}let a=new RegExp(`^${s}$`);return dr.set(e,a),a}function lo(e){return pt(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}function Jt(e,t){let n=pt(String(e)),r=lo(n),s=n.replace(/\*/g,"").length,o=r.length*1e4+s;if(t==null||t==="")return o;let a=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return s;let i=0,l=-1;for(let u of r){let f=-1;for(let m=i;m<a.length;m+=1)if(a[m]===u){f=m;break}if(f<0)return o;l=f,i=f+1}return(l+1)*1e6+r.length*1e4+s}function re(e,t){let n=String(e).split(/[/\\]/).join("/"),r,s=-1;for(let o of t??[])if(!(o.exclude??[]).some(a=>he(a).test(n))){for(let a of o.patterns??[])if(he(a).test(n)){let i=Jt(a,n);i>s&&(s=i,r=o.name)}}return r}function pr(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 co(e){let t=new Set;for(let n of e??[]){let s=pt(String(n)).split("/").filter(Boolean);for(let o=0;o<s.length;o+=1){let a=s[o];if((a==="**"||a==="*")&&o>0){let i=s[o-1];i&&!i.includes("*")&&!i.includes("{")&&!i.includes("}")&&t.add(i)}}}return[...t]}function uo(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 co(r?.patterns)}function po(e){return!e.fromPath||!e.toPath||e.folderCount<=0||!e.fromSlice||!e.toSlice?!0:e.fromSlice!==e.toSlice}function se(e,t,n,r){for(let s of e??[])if(!(s.from!==t||s.to!==n)&&s.allowed===!1){if(s.peerIsolation){let o=r?.fromPath,a=r?.toPath,i=uo(s,t,r?.layers),l=o&&a?pr(o,i):void 0,u=o&&a?pr(a,i):void 0;if(po({fromPath:o,toPath:a,folderCount:i.length,fromSlice:l,toSlice:u}))return s;continue}if(t!==n)return s}}function Ce(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function gr(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function fr(e,t){if(e.isImportDeclaration(t)){let r=t.importClause;if(!r)return!1;if(r.isTypeOnly)return!0;let s=r.namedBindings;return!!(s&&e.isNamedImports(s)&&s.elements.length>0&&s.elements.every(o=>o.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(r=>r.isTypeOnly))}function yr(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 Zt(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function Xt(e,t,n,r){let s=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,o;try{o=s?t.getShorthandAssignmentValueSymbol(r.parent):Zt(t,r)}catch{o=void 0}return!!o?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}function _e(e,t){let n,r=[],s=(a,i,l,u=!1)=>r.push({specifier:l,kind:i,line:gr(t,a),typeOnly:u,unresolved:l===void 0,node:a}),o=a=>{if(e.isImportDeclaration(a))s(a,"import",Ce(e,a.moduleSpecifier),fr(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)s(a,"export",Ce(e,a.moduleSpecifier),fr(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))s(a,"require",Ce(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let i=a.expression.kind===e.SyntaxKind.ImportKeyword,u=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!Xt(e,n??(n=yr(e,t)),t,a.expression);(i||u)&&s(a,u?"require":"dynamic-import",Ce(e,a.arguments[0]))}e.forEachChild(a,o)};return o(t),r}function fo(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=Ce(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 mo(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 mr(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 xe(e,t,n){if(n.length===0)return[];let r=new Set(n),s=yr(e,t),o=new Map,a=new Set;for(let d of t.statements)if(e.isVariableStatement(d))for(let c of d.declarationList.declarations)e.isIdentifier(c.name)&&a.add(c.name.text);let i=d=>{let c=fo(e,d);if(!c)return;let p=Zt(s,c.root),g=p?o.get(p):void 0;return g?[...g,...c.segments.slice(1)]:Xt(e,s,t,c.root)||a.has(c.root.text)?void 0:c.segments};for(let d of t.statements)if(e.isVariableStatement(d))for(let c of d.declarationList.declarations){if(!c.initializer||!e.isIdentifier(c.name))continue;let p=i(c.initializer),g=Zt(s,c.name);!p||!g||o.set(g,p)}let l=[],u=new Set,f=(d,c)=>{let p=gr(t,c),g=`${d}:${c.getStart(t)}`;u.has(g)||(u.add(g),l.push({name:d,line:p,node:c}))},m=d=>{let c=d.parent&&(e.isPropertyAccessExpression(d.parent)||e.isElementAccessExpression(d.parent))&&d.parent.expression===d;if((e.isPropertyAccessExpression(d)||e.isElementAccessExpression(d))&&!c){let p=i(d),g=p?mr(r,p):void 0;g&&f(g,d)}else e.isIdentifier(d)&&r.has(d.text)&&mo(e,d)&&!Xt(e,s,t,d)&&f(d.text,d);if(e.isVariableDeclaration(d)&&e.isObjectBindingPattern(d.name)&&d.initializer){let p=i(d.initializer);if(p)for(let g of d.name.elements){if(!e.isIdentifier(g.name))continue;let k=g.propertyName?Ce(e,g.propertyName)??g.propertyName.text:g.name.text,b=mr(r,[...p,k]);b&&f(b,d.initializer)}}e.forEachChild(d,m)};return m(t),l}function Qt(e,t,n){let r=[];for(let s of n?.dependencies??_e(e,t)){if(s.typeOnly||!s.specifier)continue;let o=Ve(s.specifier);o&&r.push({capability:o,symbol:s.specifier,line:s.line,source:"import-based"})}for(let s of n?.ambientUses??xe(e,t,Wt)){let o=dt(s.name);o&&r.push({capability:o,symbol:s.name,line:s.line,source:"ambient-global"})}return r.sort((s,o)=>s.line-o.line||s.capability.localeCompare(o.capability)||s.symbol.localeCompare(o.symbol))}var en={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."},tn=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 nn(e,t){return t.flatMap((r,s)=>(r.prefixes??r.intentPrefixes??[]).map(o=>({layer:r.name,layerIndex:s,prefix:o.endsWith(".")?o:`${o}.`}))).filter(({prefix:r})=>e.startsWith(r)).sort((r,s)=>s.prefix.length-r.prefix.length||r.layerIndex-s.layerIndex)[0]?.layer}function Ae(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function Ue(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&Ae(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:en.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:en.PUBLISH_MISSING_SOURCE}),t}function D(e,t,n){return{ruleId:e,code:e,message:t,...n}}function Te(e,t){return e.slice(0,t).split(`
1
+ var zs="4.7.6";var qs=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,Ys=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,Ws=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function Js(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),s=String(t?.toLayer??"");return qs.test(n)?"pure-shared":r==="PersistenceAdapters"&&(Ys.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${s} ${n}`))?"kernel-emit":Ws.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&s==="PersistenceAdapters"?"use-case":"unknown"}function Zs(e){if(e.typeOnly||e.targetTypeOnlyExports||e.namedBindingsTypeOnly)return"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.";if(e.peerIsolation)return"Extract the shared dependency to a shared layer, test at the public interface, then preflight again.";let t=Js(typeof e.target=="string"?e.target:"",{fromLayer:typeof e.fromLayer=="string"?e.fromLayer:void 0,toLayer:typeof e.toLayer=="string"?e.toLayer:void 0});return t==="pure-shared"?"Adopt the imported constants/types/pure module into DomainModel or SharedKernel (do not inject a port). Then preflight again.":t==="kernel-emit"?"Persistence must not emit. Inject a port or move the event map to SharedTypes; do not import kernel/events/bootstrap from a repository. Then preflight again.":t==="use-case"||e.portProofEligible?`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, test at the public interface, then preflight again.`:"Classify the import: if it is constants/types/pure, adopt into DomainModel or SharedKernel; define a port only if the target is a real use-case. Then preflight again."}function Xs(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}function Qs(e){let t=Xs(e),n=typeof e.fromLayer=="string"&&e.fromLayer.length>0?e.fromLayer:void 0;switch(e.ruleId){case"ARKRUN_MISSING_ROOT":return t?`Import createStrictArkKernel from @arkgate/runtime and call it in composition root ${t} listed in arkRun.compositionRoots, then preflight again.`:"Import createStrictArkKernel from @arkgate/runtime (never a removed arkgate/runtime shim) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKRUN_KERNEL_IN_DOMAIN":return t?`Move the kernel import of ${t} out of ${n??"the Domain-role layer"} into a composition root or adapter. Import from @arkgate/runtime, never a removed arkgate/runtime shim, then preflight again.`:"Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from @arkgate/runtime, never a removed arkgate/runtime shim, then preflight again. Never mechanical-safe.";case"ARKRUN_DIRECT_NEW":return t?`Resolve ${t} from the kernel instead of constructing it with new, then preflight again.`:"Resolve the type from the kernel instead of constructing it with new, then preflight again. Never mechanical-safe \u2014 rewiring construction is a design decision.";case"ARKRUN_UNDECLARED_EMIT":return t?`Add ${t} to raises or sends on the managed component, then preflight again.`:"Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment.";case"ARKRUN_UNDECLARED_HANDLE":return t?`Add ${t} to reactsTo on the managed component, then preflight again.`:"Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment.";case"ARKRUN_UNDECLARED_DEPEND":return t?`Add ${t} to uses on the managed component, then preflight again.`:"Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment.";case"ARKRUN_TRANSPORT_BYPASS":return t?`Send through the ArkRun kernel transport instead of importing ${t}, then preflight again.`:"Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe \u2014 homemade buses stay judgment.";default:return`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}function me(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return Zs(e);case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, test at the public interface, then preflight again.`;case"CAPABILITY_VIOLATION":return`Define a ${String(e.capability??"capability")} port in ${e.fromLayer??"the walled layer"}, bind the implementation outside it, test at the public interface, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, test at the public interface, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";case"ARKRULE_STRUCTURE":case"ARKRULE_INVARIANT":case"INVARIANT_UNCOVERED":return`Fix the structure or invariant for ${typeof e.arkruleId=="string"&&e.arkruleId.length>0?e.arkruleId:"the ArkRule"} (declared in ${typeof e.arkruleSource=="string"&&e.arkruleSource.length>0?e.arkruleSource:"arkrules/<Layer>.json"}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`;case"ARKRUN_MISSING_ROOT":case"ARKRUN_KERNEL_IN_DOMAIN":case"ARKRUN_DIRECT_NEW":case"ARKRUN_UNDECLARED_EMIT":case"ARKRUN_UNDECLARED_HANDLE":case"ARKRUN_UNDECLARED_DEPEND":case"ARKRUN_TRANSPORT_BYPASS":return Qs(e);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.`}}var Kt="1.5",sr="docs/diagnostics.md";function _(e){return typeof e=="string"&&e.length>0?e:void 0}function rr(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function Gt(e){let t=typeof e.ruleId=="string"?e.ruleId:typeof e.code=="string"?e.code:void 0,n=typeof e.file=="string"?e.file:void 0,r=typeof e.fromLayer=="string"?e.fromLayer:void 0,s=typeof e.toLayer=="string"?e.toLayer:void 0,o=typeof e.target=="string"?e.target:void 0;return[t,n,r??"",s??"",o??""].join("|")}function jt(e){let t=new Map;return e.map(n=>{let r=Gt(n),s=(t.get(r)??0)+1;return t.set(r,s),s===1?r:`${r}#${s}`})}function or(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 ar(e){return`${sr}#${e}`}function eo(e,t,n){return me({ruleId:e,target:_(t.target)??_(n.target)??void 0,fromLayer:_(t.fromLayer)??void 0,toLayer:_(t.toLayer)??void 0,typeOnly:t.typeOnly===!0,targetTypeOnlyExports:t.targetTypeOnlyExports===!0,namedBindingsTypeOnly:t.namedBindingsTypeOnly===!0,portProofEligible:t.portProofEligible===!0,peerIsolation:t.peerIsolation===!0,sourcePureTypeModule:t.sourcePureTypeModule===!0,edgeKind:_(t.edgeKind)??void 0,capability:_(t.capability)??_(n.capability)??void 0,arkruleId:_(t.arkruleId)??void 0,arkruleSource:_(t.arkruleSource)??void 0})}function Ut(e,t="error",n){let r=_(e.ruleId)??_(e.code)??"ARK_UNKNOWN",s=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,o={..._(e.target)?{target:_(e.target)}:{},..._(e.fromLayer)?{fromLayer:_(e.fromLayer)}:{},..._(e.toLayer)?{toLayer:_(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{},...typeof e.targetTypeOnlyExports=="boolean"?{targetTypeOnlyExports:e.targetTypeOnlyExports}:{},...typeof e.sourcePureTypeModule=="boolean"?{sourcePureTypeModule:e.sourcePureTypeModule}:{},...typeof e.namedBindingsTypeOnly=="boolean"?{namedBindingsTypeOnly:e.namedBindingsTypeOnly}:{},...typeof e.portProofEligible=="boolean"?{portProofEligible:e.portProofEligible}:{},...typeof e.peerIsolation=="boolean"?{peerIsolation:e.peerIsolation}:{},..._(e.capability)?{capability:_(e.capability)}:{},..._(e.edgeKind)?{edgeKind:_(e.edgeKind)}:{},..._(e.arkruleId)?{arkruleId:_(e.arkruleId)}:{},..._(e.arkruleSource)?{arkruleSource:_(e.arkruleSource)}:{}},a=n??Gt(e),i=or(a);return{ruleId:r,severity:s,message:_(e.message)??r,location:{file:_(e.file)??"<unknown>",line:rr(e.line,1),column:rr(e.column,1)},evidence:o,nextAction:_(e.nextAction)??eo(r,o,e),findingRef:i,targetKey:a,docsCodePath:ar(r)}}function to(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:_(m.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:_(m.message)??`Analysis ${t}: required evidence is incomplete.`,..._(m.file)?{file:_(m.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],s={..._(e.policyHash)?{policyHash:_(e.policyHash)}:{},..._(e.resolverIdentity)?{resolverIdentity:_(e.resolverIdentity)}:{},..._(e.factsHash)?{factsHash:_(e.factsHash)}:{},..._(e.candidateTreeHash)?{candidateTreeHash:_(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let m of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!s[m])throw new Error(`${m} is required for resolved ${t} adapter evidence.`)}let o=e.violations??[],a=e.warnings??[],i=jt(o),l=jt(a),u=[...o.map((m,d)=>Ut(m,"error",i[d])),...a.map((m,d)=>Ut(m,"warning",l[d]))],f={schemaVersion:Kt,completenessReasons:r,diagnostics:u};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...f,mode:n,valid:!1,completeness:t,...s};let m={policyHash:s.policyHash,resolverIdentity:s.resolverIdentity,factsHash:s.factsHash,candidateTreeHash:s.candidateTreeHash};return t==="complete"?{...f,mode:n,valid:e.valid,completeness:t,...m}:{...f,mode:n,valid:!1,completeness:t,...m}}return t==="complete"?{...f,mode:n,valid:e.valid,completeness:t,...s}:{...f,mode:n,valid:!1,completeness:t,...s}}var no={$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:Kt},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 ro="1.0",ir="https://unpkg.com/arkgate@4/schemas/ark.project-identity.schema.json",ct="^sha256:[a-f0-9]{64}$",lr={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:ct,description:"Project id previously returned by ark_identity or ark_manifest."}}},cr={type:"object",additionalProperties:!1,required:["status","authoritative"],properties:{status:{enum:["matched","unverified","mismatch"]},authoritative:{type:"boolean"},expectedRoot:{type:"string",minLength:1},expectedProjectId:{type:"string",pattern:ct},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},so={$schema:"https://json-schema.org/draft/2020-12/schema",$id:ir,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:ct},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{type:"string",minLength:1},arkgateVersion:{type:"string",minLength:1},contractHash:{type:"string",pattern:ct},contractSource:{enum:["project","default-profile","manifest"]},runtimeId:{type:"string",minLength:1},processStartedAt:{type:"string",format:"date-time"}},$defs:{expectation:lr,binding:cr}};function oo(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 ao(e){return{schemaVersion:"1.0",...e}}var zt=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),Yt=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Wt=Object.freeze(Object.keys(Yt).sort()),Bt=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"}),qt=Object.freeze({process:Object.freeze(["process","node:process"])});function Ve(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=Bt[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),s=Bt[r];if(s)return s;let o=e.indexOf("/",n+1);return o<0?null:Bt[e.slice(0,o)]??null}function ge(e,t){for(let n of t)if(qt[n]?.includes(e))return n;return null}function dt(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),s=Yt[r];if(s)return s}return null}function be(e){if(e?.pure===!0)return[...zt].sort();let n=(e?.capabilities?.deny??[]).filter(r=>zt.includes(r));return[...new Set(n)].sort()}function je(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 ut(e){let t=new Set,n=new Set,r=Object.keys(Yt);for(let s of e?.forbiddenGlobals??[]){let o=r.filter(a=>a===s||a.startsWith(`${s}.`));if(o.length===0)n.add(s);else for(let a of o)t.add(`ambient:${a}`);for(let a of qt[s]??[])t.add(`import-exact:${a}`)}for(let s of be(e)){if(t.add(`import:${s}`),s==="process")for(let o of qt.process)t.add(`import-exact:${o}`);for(let o of r)dt(o)===s&&t.add(`ambient:${o}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}var dr=new Map;function ur(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function pt(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 io(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 he(e){let t=dr.get(e);if(t)return t;let n=pt(e),r=io(n),s="",o=0;for(let i=0;i<n.length;i+=1){let l=n[i];l==="\\"&&i+1<n.length?(s+=ur(n[i+1]),i+=1):l==="*"?n[i+1]==="*"?n[i+2]==="/"?(s+="(?:.*/)?",i+=2):(s+=".*",i+=1):s+="[^/]*":l==="?"?s+="[^/]":l==="{"&&r?(s+="(?:",o+=1):l==="}"&&r&&o>0?(s+=")",o-=1):l===","&&r&&o>0?s+="|":s+=ur(l)}let a=new RegExp(`^${s}$`);return dr.set(e,a),a}function lo(e){return pt(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}function Jt(e,t){let n=pt(String(e)),r=lo(n),s=n.replace(/\*/g,"").length,o=r.length*1e4+s;if(t==null||t==="")return o;let a=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return s;let i=0,l=-1;for(let u of r){let f=-1;for(let m=i;m<a.length;m+=1)if(a[m]===u){f=m;break}if(f<0)return o;l=f,i=f+1}return(l+1)*1e6+r.length*1e4+s}function re(e,t){let n=String(e).split(/[/\\]/).join("/"),r,s=-1;for(let o of t??[])if(!(o.exclude??[]).some(a=>he(a).test(n))){for(let a of o.patterns??[])if(he(a).test(n)){let i=Jt(a,n);i>s&&(s=i,r=o.name)}}return r}function pr(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 co(e){let t=new Set;for(let n of e??[]){let s=pt(String(n)).split("/").filter(Boolean);for(let o=0;o<s.length;o+=1){let a=s[o];if((a==="**"||a==="*")&&o>0){let i=s[o-1];i&&!i.includes("*")&&!i.includes("{")&&!i.includes("}")&&t.add(i)}}}return[...t]}function uo(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 co(r?.patterns)}function po(e){return!e.fromPath||!e.toPath||e.folderCount<=0||!e.fromSlice||!e.toSlice?!0:e.fromSlice!==e.toSlice}function se(e,t,n,r){for(let s of e??[])if(!(s.from!==t||s.to!==n)&&s.allowed===!1){if(s.peerIsolation){let o=r?.fromPath,a=r?.toPath,i=uo(s,t,r?.layers),l=o&&a?pr(o,i):void 0,u=o&&a?pr(a,i):void 0;if(po({fromPath:o,toPath:a,folderCount:i.length,fromSlice:l,toSlice:u}))return s;continue}if(t!==n)return s}}function Ce(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function gr(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function fr(e,t){if(e.isImportDeclaration(t)){let r=t.importClause;if(!r)return!1;if(r.isTypeOnly)return!0;let s=r.namedBindings;return!!(s&&e.isNamedImports(s)&&s.elements.length>0&&s.elements.every(o=>o.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(r=>r.isTypeOnly))}function yr(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 Zt(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function Xt(e,t,n,r){let s=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,o;try{o=s?t.getShorthandAssignmentValueSymbol(r.parent):Zt(t,r)}catch{o=void 0}return!!o?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}function _e(e,t){let n,r=[],s=(a,i,l,u=!1)=>r.push({specifier:l,kind:i,line:gr(t,a),typeOnly:u,unresolved:l===void 0,node:a}),o=a=>{if(e.isImportDeclaration(a))s(a,"import",Ce(e,a.moduleSpecifier),fr(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)s(a,"export",Ce(e,a.moduleSpecifier),fr(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))s(a,"require",Ce(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let i=a.expression.kind===e.SyntaxKind.ImportKeyword,u=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!Xt(e,n??(n=yr(e,t)),t,a.expression);(i||u)&&s(a,u?"require":"dynamic-import",Ce(e,a.arguments[0]))}e.forEachChild(a,o)};return o(t),r}function fo(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=Ce(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 mo(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 mr(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 xe(e,t,n){if(n.length===0)return[];let r=new Set(n),s=yr(e,t),o=new Map,a=new Set;for(let d of t.statements)if(e.isVariableStatement(d))for(let c of d.declarationList.declarations)e.isIdentifier(c.name)&&a.add(c.name.text);let i=d=>{let c=fo(e,d);if(!c)return;let p=Zt(s,c.root),g=p?o.get(p):void 0;return g?[...g,...c.segments.slice(1)]:Xt(e,s,t,c.root)||a.has(c.root.text)?void 0:c.segments};for(let d of t.statements)if(e.isVariableStatement(d))for(let c of d.declarationList.declarations){if(!c.initializer||!e.isIdentifier(c.name))continue;let p=i(c.initializer),g=Zt(s,c.name);!p||!g||o.set(g,p)}let l=[],u=new Set,f=(d,c)=>{let p=gr(t,c),g=`${d}:${c.getStart(t)}`;u.has(g)||(u.add(g),l.push({name:d,line:p,node:c}))},m=d=>{let c=d.parent&&(e.isPropertyAccessExpression(d.parent)||e.isElementAccessExpression(d.parent))&&d.parent.expression===d;if((e.isPropertyAccessExpression(d)||e.isElementAccessExpression(d))&&!c){let p=i(d),g=p?mr(r,p):void 0;g&&f(g,d)}else e.isIdentifier(d)&&r.has(d.text)&&mo(e,d)&&!Xt(e,s,t,d)&&f(d.text,d);if(e.isVariableDeclaration(d)&&e.isObjectBindingPattern(d.name)&&d.initializer){let p=i(d.initializer);if(p)for(let g of d.name.elements){if(!e.isIdentifier(g.name))continue;let k=g.propertyName?Ce(e,g.propertyName)??g.propertyName.text:g.name.text,b=mr(r,[...p,k]);b&&f(b,d.initializer)}}e.forEachChild(d,m)};return m(t),l}function Qt(e,t,n){let r=[];for(let s of n?.dependencies??_e(e,t)){if(s.typeOnly||!s.specifier)continue;let o=Ve(s.specifier);o&&r.push({capability:o,symbol:s.specifier,line:s.line,source:"import-based"})}for(let s of n?.ambientUses??xe(e,t,Wt)){let o=dt(s.name);o&&r.push({capability:o,symbol:s.name,line:s.line,source:"ambient-global"})}return r.sort((s,o)=>s.line-o.line||s.capability.localeCompare(o.capability)||s.symbol.localeCompare(o.symbol))}var en={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."},tn=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 nn(e,t){return t.flatMap((r,s)=>(r.prefixes??r.intentPrefixes??[]).map(o=>({layer:r.name,layerIndex:s,prefix:o.endsWith(".")?o:`${o}.`}))).filter(({prefix:r})=>e.startsWith(r)).sort((r,s)=>s.prefix.length-r.prefix.length||r.layerIndex-s.layerIndex)[0]?.layer}function Ae(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function Ue(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&Ae(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:en.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:en.PUBLISH_MISSING_SOURCE}),t}function D(e,t,n){return{ruleId:e,code:e,message:t,...n}}function Te(e,t){return e.slice(0,t).split(`
2
2
  `).length}function go(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 yo(e){let t=[],n=[{kind:"import",re:/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s*)?['"]([^'"]+)['"]/g},{kind:"export",re:/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s*['"]([^'"]+)['"]/g},{kind:"dynamic-import",re:/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g},{kind:"require",re:/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g}];for(let r of n){let s;for(;(s=r.re.exec(e))!==null;){let o=s.index+s[0].indexOf(s[1]),a=s[0],i=r.kind==="import"&&/\bimport\s+type\b/.test(a)||r.kind==="export"&&/\bexport\s+type\b/.test(a);t.push({value:s[1],index:o,kind:r.kind,typeOnly:i})}}return t.sort((r,s)=>r.index-s.index)}function ho(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],s=o=>{e.isStringLiteralLike(o)&&r.push({value:o.text,index:o.getStart(n)}),e.forEachChild(o,s)};return s(n),r}function Ao(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 Ro(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}function ko(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}function Ge(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function So(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}function hr(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:So(e,r.name)===n)}function Be(e,t,n){return hr(e,t,n)!==void 0}function Ke(e,t,n){let r=hr(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}function Eo(e,t){let n=Ke(e,t,"metadata");return Be(e,n,"source")}function Ar(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?Ar(e,t.name):!1:!1}function Io(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 vo(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=Ge(e,n);return r!==void 0&&Ae(r)||Be(e,n,"intent")||Ar(e,n)}function bo(e,t){if(!e.isCallExpression(t))return!1;let[n,r,s]=t.arguments;return Eo(e,n)||Be(e,r,"source")||Be(e,s,"source")}function Co(e,t){if(!e.isCallExpression(t))return;let[n,r,s]=t.arguments,o=Ke(e,n,"metadata");return Ge(e,Ke(e,o,"source"))??Ge(e,Ke(e,r,"source"))??Ge(e,Ke(e,s,"source"))}function _o(e,t,n,r){let s=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),o=n,a=o?.filePath,i=o?.layer,l=[],u=m=>s.getLineAndCharacterOfPosition(m.getStart(s)).line+1,f=m=>{if(Io(e,m)){let d=m.arguments[0],c=Ge(e,d);for(let g of Ue({publishCall:!0,rawIntentName:c,objectHasIntent:Be(e,d,"intent"),arkPublishCandidate:vo(e,m),hasSource:bo(e,m)}))l.push(D(g.ruleId,g.message,{line:u(m),filePath:a}));let p=Co(e,m);if(r&&i&&p&&Ae(p)){let g=r.resolveLayer(p);g&&g!==i&&l.push(D("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${p}" resolves to ${g}, but the target file is classified as ${i}.`,{line:u(m),filePath:a,target:p,fromLayer:i,toLayer:g}))}}e.forEachChild(m,f)};return f(s),l}function Rr(e={}){let t=new Set((e.intents||[]).map(o=>typeof o=="string"?o:o.name)),n=e.forbiddenPatterns||[],r=new Set(e.infrastructureLayers??[]),s=e.enforceIntentAllowlist??t.size>0;return{validate(o,a){let i=[],l=a,u=l?.filePath,f=l?.layer,m=e.typescript,d=m?m.createSourceFile(u??"generated.ts",o,m.ScriptTarget.Latest,!0):void 0,c=d?_e(e.typescript,d):void 0,p=c?c.filter(R=>R.specifier!==void 0).map(R=>({value:R.specifier,index:R.node.getStart(d),kind:R.kind,typeOnly:R.typeOnly})):yo(o),g=e.typescript?ho(e.typescript,o):go(o);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(u))for(let R of c?.filter(({unresolved:I})=>I)??[]){let I=R.kind==="require";i.push(D(I?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${I?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:R.line,filePath:u}))}let k=f!==void 0&&(r.has(f)||ko(f)),b=f!==void 0?` If "${f}" is an infrastructure layer, mark it in ark.config.json with "mayImportInfrastructure": true (or name it with an infra token like Adapters/Persistence/Repository).`:"";for(let R of n)if(R instanceof RegExp){R.lastIndex=0;let I=R.exec(o);R.lastIndex=0,I&&i.push(D("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${R}`,{line:I.index===void 0?void 0:Te(o,I.index),filePath:u,suggestion:"Remove infrastructure imports from domain/application layers."+b}))}else o.includes(R)&&i.push(D("FORBIDDEN_SUBSTRING",`Forbidden substring: ${R}`,{line:Te(o,o.indexOf(R)),filePath:u}));for(let R of p){let I=e.resolveImportTarget?.(R.value,u)??(e.resolveImportLayer?{layer:e.resolveImportLayer(R.value,u)}:void 0),C=typeof u=="string"?e.resolveImportTarget?.(u)??(e.resolveImportLayer?{layer:f,relPath:void 0}:void 0):void 0,H=I?.layer;if(H&&f){let M=se(e.architectureProfile?.rules,f,H,{fromPath:C?.relPath,toPath:I?.relPath,layers:e.architectureLayers});if(M){if(R.typeOnly&&!M.peerIsolation)continue;let V=!!M.peerIsolation;i.push(D("LAYER_IMPORT_VIOLATION",M.message??(V?`Layer "${f}" must not import across slices into "${H}".`:`Layer "${f}" must not import "${H}".`),{line:Te(o,R.index),source:R.value,target:R.value,filePath:u,fromLayer:f,toLayer:H,suggestion:V?"Extract shared code to a shared layer, or coordinate slices via events/ports \u2014 do not import across feature/context slices.":"Depend on a port/interface owned by an inner layer instead, or move this code to a layer allowed to make this import.",details:{importKind:R.kind,peerIsolation:V,...R.typeOnly?{typeOnly:!0}:{}}}));continue}continue}k||R.typeOnly||!Ao(R.value)&&!Ro(R.value)||i.push(D("FORBIDDEN_IMPORT",`Forbidden ${R.kind} target: "${R.value}".`,{line:Te(o,R.index),source:R.value,target:R.value,filePath:u,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+b,details:{importKind:R.kind}}))}if(e.policies)for(let R of e.policies){let I=R.check({source:o,context:a});if(I!==!0)if(Array.isArray(I))for(let C of I)i.push(D("POLICY_VIOLATION",C.message,{filePath:u,suggestion:`Fix violation of policy "${R.name}".`}));else I===!1?i.push(D("POLICY_VIOLATION",`Policy ${R.name} failed on generated code`)):i.push(D("POLICY_VIOLATION",I.message))}if(s&&t.size>0)for(let R of g)Ae(R.value)&&!t.has(R.value)&&i.push(D("UNKNOWN_INTENT",`Unknown intent reference: "${R.value}"`,{line:Te(o,R.index),filePath:u,target:R.value,suggestion:`Register intent "${R.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&f)for(let R of g){if(!Ae(R.value))continue;let I=e.architectureProfile.resolveLayer(R.value);if(!I)continue;let C=se(e.architectureProfile.rules,f,I);C&&i.push(D("LAYER_REFERENCE_VIOLATION",C.message??`Layer "${f}" must not reference "${I}" through "${R.value}".`,{line:Te(o,R.index),filePath:u,target:R.value,fromLayer:f,toLayer:I,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:C}}))}if(e.extensions)for(let R of e.extensions)try{let I=R.analyze(o,a);i.push(...I)}catch(I){i.push(D("EXTENSION_ERROR",`Extension "${R.name}" failed: ${I instanceof Error?I.message:String(I)}`))}if(e.typescript&&d&&f&&e.forbiddenGlobals?.[f]?.length)try{let R=e.forbiddenGlobals[f];i.push(...xe(e.typescript,d,R).map(I=>D("FORBIDDEN_GLOBAL",`${f} must not use the ambient global "${I.name}".`,{line:I.line,filePath:u,target:I.name,fromLayer:f,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let I of c??[]){if(I.typeOnly||!I.specifier)continue;let C=ge(I.specifier,R);C&&i.push(D("FORBIDDEN_GLOBAL",`${f} must not use module "${I.specifier}" because it is the import form of forbidden global "${C}".`,{line:I.line,filePath:u,source:I.specifier,target:I.specifier,fromLayer:f,details:{importKind:I.kind,forbiddenGlobal:C},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(R){i.push(D("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${R instanceof Error?R.message:String(R)}`))}if(e.typescript&&d&&f&&e.capabilityWalls?.[f]?.length)try{let R=new Set(e.capabilityWalls[f]),I=e.forbiddenGlobals?.[f]??[];for(let C of Qt(e.typescript,d))R.has(C.capability)&&(C.source==="ambient-global"&&je(C.symbol,I)||C.source==="import-based"&&ge(C.symbol,I)||i.push(D("CAPABILITY_VIOLATION",C.source==="import-based"?`${f} denies the ${C.capability} capability; found import of "${C.symbol}".`:`${f} denies the ${C.capability} capability; found ambient "${C.symbol}".`,{line:C.line,filePath:u,target:C.symbol,capability:C.capability,fromLayer:f,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(R){i.push(D("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${R instanceof Error?R.message:String(R)}`))}if(e.typescript)try{i.push(..._o(e.typescript,o,a,e.architectureProfile))}catch(R){i.push(D("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${R instanceof Error?R.message:String(R)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:i.length===0,violations:i}}}}var xo="1.2",mt="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",kr=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],To=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function No(){let e=[];for(let t of kr)for(let n of kr)t===n||To.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var gt=No(),rn=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"},{from:"1.1",to:"1.2"}],te={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},sn={$schema:"https://json-schema.org/draft/2020-12/schema",$id:mt,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:mt,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:"1.2",default:"1.2"},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:gt,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:{}},arkRun:{$ref:"#/$defs/arkRun"},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"},reserved:{type:"boolean"},allowEmpty:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...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}}},arkRun:{type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...te,default:[]},managedLayers:{...te,default:[]},requireDeclarations:{type:"boolean",default:!0}}}}},oe=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
3
3
  ${n.map(r=>`- ${r.path}: ${r.message}`).join(`
4
4
  `)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function qe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ft(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function Ne(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Oo(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function ze(e,t,n,r,s){if(t.$ref){let o=Oo(t.$ref,r);if(!o){s.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}ze(e,o,n,r,s);return}if(t.const!==void 0&&!Object.is(e,t.const)){s.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(o=>Object.is(o,e))){s.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!qe(e)){s.push({path:n,message:`must be an object; received ${Ne(e)}`});return}let o=t.properties??{};for(let a of t.required??[])e[a]===void 0&&s.push({path:ft(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in o||s.push({path:ft(n,a),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let a=t.additionalProperties;for(let i of Object.keys(e))i in o||ze(e[i],a,ft(n,i),r,s)}for(let[a,i]of Object.entries(o))e[a]!==void 0&&ze(e[a],i,ft(n,a),r,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:n,message:`must be an array; received ${Ne(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&s.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let o=e.map(a=>JSON.stringify(a));new Set(o).size!==o.length&&s.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((o,a)=>ze(o,t.items,`${n}[${a}]`,r,s));return}if(t.type==="string"){if(typeof e!="string"){s.push({path:n,message:`must be a string; received ${Ne(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 ${Ne(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){s.push({path:n,message:`must be an integer; received ${Ne(e)}`});return}t.minimum!==void 0&&e<t.minimum&&s.push({path:n,message:`must be at least ${t.minimum}`})}}function Lo(e){return qe(e)?{...e,mode:e.mode===void 0?"advisory":e.mode,compositionRoots:e.compositionRoots===void 0?[]:e.compositionRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,requireDeclarations:e.requireDeclarations===void 0?!0:e.requireDeclarations}:e}function Po(e){let t={...e,$schema:e.$schema===void 0?mt:e.$schema,schemaVersion:e.schemaVersion===void 0?"1.2":e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?gt.map(n=>({...n})):e.rules};return e.arkRun!==void 0&&(t.arkRun=Lo(e.arkRun)),t}function wo(e,t){let n=e.arkRun;if(n===void 0||!qe(n))return;let r=new Set;if(Array.isArray(e.layers))for(let o of e.layers)qe(o)&&typeof o.name=="string"&&o.name.length>0&&r.add(o.name);let s=n.managedLayers;if(Array.isArray(s)&&s.forEach((o,a)=>{typeof o=="string"&&o.length>0&&!r.has(o)&&t.push({path:`$.arkRun.managedLayers[${a}]`,message:`layer ${JSON.stringify(o)} is not declared in layers[]`})}),n.mode==="enforced"){let o=n.compositionRoots;(!Array.isArray(o)||o.length===0)&&t.push({path:"$.arkRun.compositionRoots",message:"ARKRUN_MISSING_ROOT: enforced mode requires at least one composition root"}),(!Array.isArray(s)||s.length===0)&&t.push({path:"$.arkRun.managedLayers",message:"enforced mode requires at least one managed layer"})}}function Mo(e){return e==="1.2"?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"?e:null}function Do(){let e=new Set(["1.2"]);for(let t of rn)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}function Fo(e,t="ark.config.json"){if(!qe(e))throw new oe(t,[{path:"$",message:`must be an object; received ${Ne(e)}`}]);let n=Do(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new oe(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.2`}]);if(r!=="unversioned"&&!n.has(r))throw new oe(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected 1.2`}]);let s=r,o={...e},a=0;for(;s!=="1.2"&&a<rn.length+1;){a+=1;let i=rn.find(l=>l.from===s);if(!i)throw new oe(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(s)}; expected 1.2`}]);s=i.to,o.schemaVersion=s}if(s!=="1.2")throw new oe(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected 1.2`}]);return{candidate:Po(o),migratedFrom:Mo(r)}}function yt(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=Fo(e,t),s=[];if(ze(n,sn,"$",sn,s),wo(n,s),s.length>0)throw new oe(t,s);return{config:n,migratedFrom:r}}function on(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new oe(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return yt(n,t)}function Sr(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:mt,schemaVersion:"1.2"};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}function $o(e){return e.endsWith(".")?e:`${e}.`}function Ho(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 At(e){let t=e.layers.map(s=>({...s,prefixes:s.prefixes.map($o)})),n=[...t].sort(Ho),r=[...e.rules??[]];return{name:e.name,layers:t,rules:r,resolveLayer(s){return t.find(o=>o.match?.(s))?.name??n.find(o=>o.prefixes.some(a=>s.startsWith(a)))?.name}}}function Er(e,t={}){return At({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 Vo=[{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}],ht=At({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:Vo,rules:gt.map(e=>({...e}))}),jo={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 Ir(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return Sr({include:e.include??[t],layers:ht.layers.map(s=>({name:s.name,patterns:(jo[s.name]??[s.name]).map(o=>`${r}${o}/**`),intentPrefixes:s.prefixes,optional:n})),rules:[...ht.rules]})}function $(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 L(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(L).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${L(t[n])}`).join(",")}}`}var Re="1.2";var vr=["network","filesystem","clock","randomness","environment","process","persistence"];function J(e,t){let n=L(e),r=L(t);return n<r?-1:n>r?1:0}function U(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}function Ye(e){let t={schemaVersion:"1.2",include:U(e.include??[]),exclude:U(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:U(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:U(n.patterns??[]),exclude:U(n.exclude??[]),forbiddenGlobals:U(n.forbiddenGlobals??[]),intentPrefixes:U(n.intentPrefixes??[]),capabilityDeny:U(n.capabilities?.deny??[]),pure:n.pure===!0})).sort(J),safety:{maxTsSuppressions:e.safety?.maxTsSuppressions??0,maxAnyCasts:e.safety?.maxAnyCasts??0,allowInMemory:e.safety?.allowInMemory===!0,allowDisabledPeerIsolation:e.safety?.allowDisabledPeerIsolation===!0},...e.arkRun?{arkRun:{mode:e.arkRun.mode,compositionRoots:U(e.arkRun.compositionRoots),managedLayers:U(e.arkRun.managedLayers),requireDeclarations:e.arkRun.requireDeclarations===!0}}:{}};return $(L(t))}function Uo(e){let t=e.completenessReasons.map(k=>({code:k.code,message:k.message,...k.file?{file:k.file}:{}})).sort(J),n=e.files.map(k=>({...k,typeOnlyExportNames:U(k.typeOnlyExportNames)})).sort((k,b)=>k.path<b.path?-1:k.path>b.path?1:0),r=e.dependencies.map(k=>({...k,...k.namedBindings?{namedBindings:U(k.namedBindings)}:{}})).sort(J),s=e.capabilityUses.map(k=>({...k})).sort(J),o=e.ambientUses.map(k=>({...k})).sort(J),a=e.publishCalls.map(k=>({...k})).sort(J),i=e.intentReferences.map(k=>({...k})).sort(J),l=e.safetyUses.map(k=>({...k})).sort(J),u=(e.classShapes??[]).map(k=>({...k,mutatingMethods:[...k.mutatingMethods??[]].map(b=>({...b}))})).sort(J),f=(e.arkRunKernelCalls??[]).map(k=>({...k})).sort(J),m=(e.arkRunManagedNews??[]).map(k=>({...k})).sort(J),d=(e.arkRunCompositionRootHits??[]).map(k=>({...k})).sort(J),c=(e.arkRunDeclarations??[]).map(k=>({...k,uses:U(k.uses),reactsTo:U(k.reactsTo),raises:U(k.raises),sends:U(k.sends)})).sort(J),p=e.files.map(({path:k,contentHash:b})=>({path:k,contentHash:b})).sort((k,b)=>k.path<b.path?-1:k.path>b.path?1:0),g=$(L(p));return{schemaVersion:"1.2",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:g,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:r,capabilityUses:s,ambientUses:o,publishCalls:a,intentReferences:i,safetyUses:l,classShapes:u,arkRunKernelCalls:f,arkRunManagedNews:m,arkRunCompositionRootHits:d,arkRunDeclarations:c}}function br(e){let t=Uo(e);return{...t,factsHash:$(L(t))}}function an(e){return br(_r(j(e,"$"),!1))}function j(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}function K(e,t,n){let r=new Set(t),s=Object.keys(e).find(o=>!r.has(o));if(s)throw new Error(`${n}.${s} is not part of schema ${"1.2"}.`)}function w(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 ae(e,t,n){if(e[t]!==void 0)return w(e,t,n)}function z(e,t,n){let r=w(e,t,n),s=r.replace(/\\/g,"/");if(!s||s.startsWith("/")||/^[A-Za-z]:\//.test(s)||/[\u0000-\u001f\u007f]/.test(s))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let o=[];for(let i of s.split("/"))if(!(!i||i==="."))if(i===".."){if(o.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);o.pop()}else o.push(i);let a=o.join("/");if(!a||a!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return a}function F(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}function Cr(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 ie(e,t,n){let r=Cr(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}function q(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}function le(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 Oe(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 Ko(e,t,n){let r=new Set;for(let s of e){let o=t(s);if(r.has(o))throw new Error(`${n} must not contain duplicate facts (${o}).`);r.add(o)}}function _r(e,t){K(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","classShapes","arkRunKernelCalls","arkRunManagedNews","arkRunCompositionRootHits","arkRunDeclarations",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=le(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=le(e,"completeness",["complete","partial","unavailable"],"$"),s=q(e,"completenessReasons","$").map((S,v)=>{let y=`$.completenessReasons[${v}]`,A=j(S,y);K(A,["code","message","file"],y);let x=A.file===void 0?void 0:z(A,"file",y);return{code:w(A,"code",y),message:w(A,"message",y),...x?{file:x}:{}}});if(r==="complete"&&s.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(r!=="complete"&&s.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let o=q(e,"files","$").map((S,v)=>{let y=`$.files[${v}]`,A=j(S,y);return K(A,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],y),{path:z(A,"path",y),contentHash:w(A,"contentHash",y),parseStatus:le(A,"parseStatus",["parsed","invalid"],y),parseDiagnosticCount:Cr(A,"parseDiagnosticCount",y),exportsOnlyTypes:F(A,"exportsOnlyTypes",y),typeOnlyExportNames:Oe(A.typeOnlyExportNames,`${y}.typeOnlyExportNames`),hasTopLevelSideEffects:F(A,"hasTopLevelSideEffects",y)}}),a=q(e,"dependencies","$").map((S,v)=>{let y=`$.dependencies[${v}]`,A=j(S,y);K(A,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],y);let x=ae(A,"specifier",y),O=ae(A,"target",y),B=le(A,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],y);if(B==="resolved-project"&&!O)throw new Error(`${y}.target is required for resolved-project dependencies.`);if(B!=="resolved-project"&&O)throw new Error(`${y}.target is only allowed for resolved-project dependencies.`);if(B!=="dynamic"&&!x)throw new Error(`${y}.specifier is required unless resolution is dynamic.`);return{from:z(A,"from",y),...x?{specifier:x}:{},kind:le(A,"kind",["import","export","dynamic-import","require"],y),typeOnly:F(A,"typeOnly",y),line:ie(A,"line",y),resolution:B,...O?{target:z(A,"target",y)}:{},...A.namedBindings!==void 0?{namedBindings:Oe(A.namedBindings,`${y}.namedBindings`)}:{},...A.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:F(A,"targetTypeOnlyExports",y)}:{},...A.sourcePureTypeModule!==void 0?{sourcePureTypeModule:F(A,"sourcePureTypeModule",y)}:{},...A.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:F(A,"namedBindingsTypeOnly",y)}:{},...A.portProofEligible!==void 0?{portProofEligible:F(A,"portProofEligible",y)}:{}}}),i=q(e,"capabilityUses","$").map((S,v)=>{let y=`$.capabilityUses[${v}]`,A=j(S,y);return K(A,["file","line","symbol","capability","source"],y),{file:z(A,"file",y),line:ie(A,"line",y),symbol:w(A,"symbol",y),capability:le(A,"capability",vr,y),source:le(A,"source",["ambient-global","import-based"],y)}}),l=q(e,"ambientUses","$").map((S,v)=>{let y=`$.ambientUses[${v}]`,A=j(S,y);return K(A,["file","line","symbol"],y),{file:z(A,"file",y),line:ie(A,"line",y),symbol:w(A,"symbol",y)}}),u=q(e,"publishCalls","$").map((S,v)=>{let y=`$.publishCalls[${v}]`,A=j(S,y);K(A,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],y);let x=ae(A,"rawIntentName",y),O=ae(A,"sourceIntent",y);return{file:z(A,"file",y),line:ie(A,"line",y),...x?{rawIntentName:x}:{},objectHasIntent:F(A,"objectHasIntent",y),arkPublishCandidate:F(A,"arkPublishCandidate",y),hasSource:F(A,"hasSource",y),...O?{sourceIntent:O}:{}}}),f=q(e,"intentReferences","$").map((S,v)=>{let y=`$.intentReferences[${v}]`,A=j(S,y);return K(A,["file","line","intent"],y),{file:z(A,"file",y),line:ie(A,"line",y),intent:w(A,"intent",y)}}),m=q(e,"safetyUses","$").map((S,v)=>{let y=`$.safetyUses[${v}]`,A=j(S,y);K(A,["file","line","kind","symbol"],y);let x=ae(A,"symbol",y),O=le(A,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],y);if(O==="in-memory-store"&&!x)throw new Error(`${y}.symbol is required for in-memory-store facts.`);if(O!=="in-memory-store"&&x)throw new Error(`${y}.symbol is only allowed for in-memory-store facts.`);return{file:z(A,"file",y),line:ie(A,"line",y),kind:O,...x?{symbol:x}:{}}});Ko(o,S=>S.path,"$.files");let d=new Set(o.map(S=>S.path));for(let S of o){if(S.parseStatus==="parsed"&&S.parseDiagnosticCount!==0)throw new Error(`$.files[${S.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(S.parseStatus==="invalid"&&S.parseDiagnosticCount===0)throw new Error(`$.files[${S.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&o.some(S=>S.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let S of a)if(!d.has(S.from))throw new Error(`$.dependencies references missing source file ${S.from}.`);let p=(e.arkRunKernelCalls===void 0?[]:q(e,"arkRunKernelCalls","$")).map((S,v)=>{let y=`$.arkRunKernelCalls[${v}]`,A=j(S,y);K(A,["file","line","kind","callee","viaImport","receiver","nameLiteral"],y);let x=ae(A,"receiver",y),O=ae(A,"nameLiteral",y);return{file:z(A,"file",y),line:ie(A,"line",y),kind:le(A,"kind",["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"],y),callee:w(A,"callee",y),viaImport:F(A,"viaImport",y),...x?{receiver:x}:{},...O?{nameLiteral:O}:{}}}),k=(e.arkRunManagedNews===void 0?[]:q(e,"arkRunManagedNews","$")).map((S,v)=>{let y=`$.arkRunManagedNews[${v}]`,A=j(S,y);K(A,["file","line","typeName","importedFrom"],y);let x=ae(A,"importedFrom",y);return{file:z(A,"file",y),line:ie(A,"line",y),typeName:w(A,"typeName",y),...x?{importedFrom:x}:{}}}),R=(e.arkRunCompositionRootHits===void 0?[]:q(e,"arkRunCompositionRootHits","$")).map((S,v)=>{let y=`$.arkRunCompositionRootHits[${v}]`,A=j(S,y);return K(A,["file","matchedRoot","hasKernelFactory"],y),{file:z(A,"file",y),matchedRoot:w(A,"matchedRoot",y),hasKernelFactory:F(A,"hasKernelFactory",y)}}),C=(e.arkRunDeclarations===void 0?[]:q(e,"arkRunDeclarations","$")).map((S,v)=>{let y=`$.arkRunDeclarations[${v}]`,A=j(S,y);return K(A,["file","line","uses","reactsTo","raises","sends"],y),{file:z(A,"file",y),line:ie(A,"line",y),uses:Oe(A.uses,`${y}.uses`),reactsTo:Oe(A.reactsTo,`${y}.reactsTo`),raises:Oe(A.raises,`${y}.raises`),sends:Oe(A.sends,`${y}.sends`)}});for(let[S,v]of[["$.capabilityUses",i],["$.ambientUses",l],["$.publishCalls",u],["$.intentReferences",f],["$.safetyUses",m],["$.arkRunKernelCalls",p],["$.arkRunManagedNews",k],["$.arkRunCompositionRootHits",R],["$.arkRunDeclarations",C]])for(let y of v)if(!d.has(y.file))throw new Error(`${S} references missing file ${y.file}.`);let H=ae(e,"projectPackageName","$"),V=(e.classShapes===void 0?[]:q(e,"classShapes","$")).map((S,v)=>{let y=`$.classShapes[${v}]`,A=j(S,y);K(A,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],y);let x=q(A,"mutatingMethods",y).map((O,B)=>{let fe=`${y}.mutatingMethods[${B}]`,Fe=j(O,fe);return K(Fe,["name","referencesGuardOrPublish"],fe),{name:w(Fe,"name",fe),referencesGuardOrPublish:F(Fe,"referencesGuardOrPublish",fe)}});return{file:z(A,"file",y),className:w(A,"className",y),exported:F(A,"exported",y),hasPublicMutableFields:F(A,"hasPublicMutableFields",y),hasPublicSetters:F(A,"hasPublicSetters",y),hasPublicConstructor:F(A,"hasPublicConstructor",y),hasStaticFactory:F(A,"hasStaticFactory",y),mutatingMethods:x,...A.dataOnly===void 0?{}:{dataOnly:F(A,"dataOnly",y)}}});return{schemaVersion:n,completeness:r,completenessReasons:s,resolverIdentity:w(e,"resolverIdentity","$"),compilerIdentity:w(e,"compilerIdentity","$"),compilerOptionsHash:w(e,"compilerOptionsHash","$"),tsconfigHash:w(e,"tsconfigHash","$"),evidenceRequirementsHash:w(e,"evidenceRequirementsHash","$"),...H?{projectPackageName:H}:{},files:o,dependencies:a,capabilityUses:i,ambientUses:l,publishCalls:u,intentReferences:f,safetyUses:m,classShapes:V,arkRunKernelCalls:p,arkRunManagedNews:k,arkRunCompositionRootHits:R,arkRunDeclarations:C}}function ye(e){let t=j(e,"$"),n=w(t,"factsHash","$"),r=w(t,"candidateTreeHash","$"),s=br(_r(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 Go=["network","filesystem","clock","randomness","environment","process","persistence"],T={type:"string",minLength:1},ce={type:"integer",minimum:1},Y={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},ln={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.resolved-candidate-facts.schema.json",title:"ArkGate resolved candidate facts",type:"object",additionalProperties:!1,required:["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","candidateTreeHash","evidenceRequirementsHash","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","factsHash"],properties:{schemaVersion:{enum:["1.0","1.1","1.2"]},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:T,message:T,file:Y}}},resolverIdentity:T,compilerIdentity:T,compilerOptionsHash:T,tsconfigHash:T,candidateTreeHash:T,evidenceRequirementsHash:T,projectPackageName:T,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:Y,contentHash:T,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:T},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:Y,specifier:T,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:ce,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:Y,namedBindings:{type:"array",items:T},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:Y,line:ce,symbol:T,capability:{enum:Go},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:Y,line:ce,symbol:T}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:Y,line:ce,rawIntentName:T,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:T}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:Y,line:ce,intent:T}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:Y,line:ce,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:T},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:Y,className:T,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:T,referencesGuardOrPublish:{type:"boolean"}}}}}}},arkRunKernelCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind","callee","viaImport"],properties:{file:Y,line:ce,kind:{enum:["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"]},callee:T,viaImport:{type:"boolean"},receiver:T,nameLiteral:T}}},arkRunManagedNews:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","typeName"],properties:{file:Y,line:ce,typeName:T,importedFrom:T}}},arkRunCompositionRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasKernelFactory"],properties:{file:Y,matchedRoot:T,hasKernelFactory:{type:"boolean"}}}},arkRunDeclarations:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","uses","reactsTo","raises","sends"],properties:{file:Y,line:ce,uses:{type:"array",items:T},reactsTo:{type:"array",items:T},raises:{type:"array",items:T},sends:{type:"array",items:T}}}},factsHash:T},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 cn="1.0";function Z(e){return`${e.from}->${e.to}`}function We(e,t,n,r="dependency"){return{id:`${e}:${r}:${Z(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${Z(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${Z(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${Z(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${Z(t)} from the candidate, then preflight again.`}:{}}}function Le(e){let t=[],n=new Map(e.changeMap.map.files.map(d=>[d.path,d])),r=new Map(e.changes.map(d=>[d.path,d])),s=new Map(e.changeMap.map.dependencies.map(d=>[Z(d),d])),o=new Map(e.baseDependencies.map(d=>[Z(d),d])),a=new Map(e.candidateDependencies.map(d=>[Z(d),d]));for(let d of[...n.values()].sort((c,p)=>c.path.localeCompare(p.path))){let c=r.get(d.path);c?c.operation!==d.operation?t.push({id:`contradictory:file:${d.path}`,classification:"contradictory",subject:"file",path:d.path,expectedOperation:d.operation,actualOperation:c.operation,message:`${d.path} was planned as ${d.operation} but the actual operation is ${c.operation}.`,nextAction:`Change ${d.path} to the planned ${d.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${d.path}`,classification:"satisfied",subject:"file",path:d.path,expectedOperation:d.operation,actualOperation:c.operation,message:`${d.path} matches the planned ${d.operation} operation.`}):t.push({id:`missing:file:${d.path}`,classification:"missing",subject:"file",path:d.path,expectedOperation:d.operation,message:`${d.path} was planned as ${d.operation} but is absent from the actual change.`,nextAction:`${d.operation[0].toUpperCase()}${d.operation.slice(1)} ${d.path} in the complete change set, then preflight again.`})}for(let d of[...r.values()].sort((c,p)=>c.path.localeCompare(p.path)))n.has(d.path)||t.push({id:`unplanned:file:${d.path}`,classification:"unplanned",subject:"file",path:d.path,actualOperation:d.operation,message:`${d.path} has an unplanned ${d.operation} operation.`,nextAction:`Remove ${d.path} from the change set, then preflight again.`});let i=new Set;for(let d of[...s.values()].sort((c,p)=>Z(c).localeCompare(Z(p)))){if(a.has(Z(d))){t.push(We("satisfied",d,`${d.from} -> ${d.to} exists in the candidate architecture.`));continue}let c={from:d.to,to:d.from};a.has(Z(c))?(i.add(Z(c)),t.push(We("contradictory",d,`${d.from} -> ${d.to} was planned, but the candidate contains the reverse edge.`))):t.push(We("missing",d,`${d.from} -> ${d.to} is absent from the candidate architecture.`))}let l=new Set([...n.keys(),...r.keys()]);for(let[d,c]of[...a].sort(([p],[g])=>p.localeCompare(g)))o.has(d)||s.has(d)||i.has(d)||!l.has(c.from)&&!l.has(c.to)||t.push({...We("unplanned",c,`${c.from} -> ${c.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let u=new Set(e.changeMap.map.files.filter(d=>d.operation==="delete").map(d=>d.path));for(let[d,c]of[...o].sort(([p],[g])=>p.localeCompare(g)))a.has(d)||u.has(c.from)||u.has(c.to)||!l.has(c.from)&&!l.has(c.to)||t.push({...We("unplanned",c,`${c.from} -> ${c.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let f={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((d,c)=>f[d.classification]-f[c.classification]||(d.subject===c.subject?0:d.subject==="file"?-1:1)||d.id.localeCompare(c.id));let m={satisfied:t.filter(d=>d.classification==="satisfied").length,missing:t.filter(d=>d.classification==="missing").length,contradictory:t.filter(d=>d.classification==="contradictory").length,unplanned:t.filter(d=>d.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 Bo="1.0",dn="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",Nr=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","no-anemic-model","invariant-coverage"],zo=["no-anemic-model"],xr={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},un={$schema:"https://json-schema.org/draft/2020-12/schema",$id:dn,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:dn},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:[...Nr]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:xr,description:{type:"string",minLength:1}}},invariantEntry:{type:"object",additionalProperties:!1,required:["id","description"],properties:{id:{type:"string",minLength:1},description:{type:"string",minLength:1},aggregate:{type:"string",minLength:1},coverage:{type:"object",additionalProperties:!1,properties:{test:{type:"boolean"},symbol:{type:"string",minLength:1}}},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:xr}}}},ke=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkRules (${t}):
package/docs/README.md CHANGED
@@ -1,8 +1,10 @@
1
1
  # ArkGate documentation
2
2
 
3
- **If the AI writes an illegal import, the write is rejected. The same check fails the pull request.**
4
- Not an API Gateway. Not a folder linter. If the check is not required on the PR, the rules
5
- file is just documentation.
3
+ **Write. Check. Ship.**
4
+
5
+ **When the agent writes a bad import, the write doesn’t land. The same check fails the pull request.**
6
+ Not an API Gateway. Not a folder linter. If the check is not required on the PR, the config
7
+ is just documentation.
6
8
 
7
9
  Pick your path. Skip everything else.
8
10
 
@@ -24,7 +26,7 @@ Product site: [arkgate.online](https://www.arkgate.online/) · npm: [`arkgate`](
24
26
  | [use.md](use.md) | One flow: install → doctor → day-to-day |
25
27
  | [enthusiast/](enthusiast/README.md) | Tutorials and plain-language track |
26
28
  | [demos/](demos/) | Short end-to-end demos |
27
- | [product-voice.md](product-voice.md) | How ArkGate should sound in English UI (compass = lenses, not scores) |
29
+ | [product-voice.md](product-voice.md) | How ArkGate should sound (Write. Check. Ship.) |
28
30
 
29
31
  ### Develop (integrate)
30
32
  | Doc | What it is |
@@ -60,8 +62,8 @@ These are **not** the day-to-day product path. They stay in the repo for evidenc
60
62
  | Field adoption kit (scaffolding, not closed) | [field/](field/) |
61
63
  | Runtime hardening (experimental) | [production-hardening.md](production-hardening.md) |
62
64
 
63
- Current published: [releases/4.7.4.md](releases/4.7.4.md) (`arkgate@4.7.4` on npm `latest`).
64
- Prior: [releases/4.7.3.md](releases/4.7.3.md) · [4.7.2](releases/4.7.2.md) · [4.7.1](releases/4.7.1.md) · [4.7.0](releases/4.7.0.md) · [4.6.7](releases/4.6.7.md) · [4.6.6](releases/4.6.6.md) · [4.6.5](releases/4.6.5.md) · [4.6.4](releases/4.6.4.md) · [4.6.3](releases/4.6.3.md) · [4.6.2](releases/4.6.2.md) · [4.6.1](releases/4.6.1.md) · [4.6.0](releases/4.6.0.md).
65
+ Current published: [releases/4.7.5.md](releases/4.7.5.md) (`arkgate@4.7.5` on npm `latest`).
66
+ Prior: [releases/4.7.4.md](releases/4.7.4.md) · [4.7.3](releases/4.7.3.md) · [4.7.2](releases/4.7.2.md) · [4.7.1](releases/4.7.1.md) · [4.7.0](releases/4.7.0.md) · [4.6.7](releases/4.6.7.md) · [4.6.6](releases/4.6.6.md) · [4.6.5](releases/4.6.5.md) · [4.6.4](releases/4.6.4.md) · [4.6.3](releases/4.6.3.md) · [4.6.2](releases/4.6.2.md) · [4.6.1](releases/4.6.1.md) · [4.6.0](releases/4.6.0.md).
65
67
  Older notes: [releases/](releases/). Config: [configuration.md](configuration.md).
66
68
 
67
69
  ---
@@ -72,4 +74,4 @@ Older notes: [releases/](releases/). Config: [configuration.md](configuration.md
72
74
  2. **One primary flow** — `start` → doctor → optional guided work.
73
75
  3. **Honest hardness** — host write guarantees differ; a **required GitHub status context** running the merge CLI is the shared hard boundary.
74
76
  4. **History is not the product** — version archaeology lives under `releases/` and `plans/`, not the front door.
75
- 5. **Common language** — first-contact copy uses ordinary software words (import rules, rejected write, required CI). Brands are categorical. Voice: [product-voice.md](product-voice.md).
77
+ 5. **Common language** — first-contact copy uses ordinary software words (import rules, the write doesn’t land, required CI). ArkGate is import rules; ArkRules is policies; ArkRun is an experimental runtime. Voice: [product-voice.md](product-voice.md).
@@ -1,6 +1,7 @@
1
1
  # ArkGate — Agent Integration Guide
2
2
 
3
- **If the AI writes an illegal import, the write is rejected. The same check fails the pull request.**
3
+ **Write. Check. Ship.**
4
+ **When the agent writes a bad import, the write doesn’t land. The same check fails the pull request.**
4
5
  This guide is the **develop** reference for agents and codegen: write hooks, advisory MCP tools,
5
6
  CI, and `/ark-*` skills. Not an API Gateway. Not a folder linter.
6
7
 
package/docs/ai-gates.md CHANGED
@@ -1,6 +1,7 @@
1
1
  # Gating AI Agents with ArkGate
2
2
 
3
- **If the AI writes an illegal import, the write is rejected. The same check fails the pull request.**
3
+ **Write. Check. Ship.**
4
+ **When the agent writes a bad import, the write doesn’t land. The same check fails the pull request.**
4
5
  This page is host install depth (hooks / MCP / CI). Not an API Gateway. Not a folder linter.
5
6
 
6
7
  This page is **develop** depth (install hooks/MCP/CI per host). Product path: [use.md](use.md) ·
package/docs/develop.md CHANGED
@@ -1,13 +1,24 @@
1
1
  # Develop with ArkGate
2
2
 
3
+ **Write. Check. Ship.**
4
+
3
5
  For **developers** integrating ArkGate into a product repo: agents, CI, config, brownfield, and power tools.
4
6
 
5
- If the AI writes an illegal import, the write is rejected. The same check fails the pull
7
+ When the agent writes a bad import, the write doesn’t land. The same check fails the pull
6
8
  request. Not an API Gateway. Not a folder linter. Without a required CI status,
7
- `ark.config.json` is just documentation.
9
+ `ark.config.json` is just documentation. ArkGate is import rules. ArkRules and ArkRun
10
+ are optional — policies and an experimental runtime, not a second install.
8
11
 
9
12
  If you only want the happy path, start at [use.md](use.md).
10
13
 
14
+ ### Why it exists
15
+
16
+ AI coding agents generate code at unprecedented speeds, but they tend to take the shortest path. If an agent needs data in a Domain layer, it might directly import a database adapter. Left unchecked, this creates spaghetti code and technical debt at light speed.
17
+
18
+ Traditional linters catch these architectural violations in CI *after* the agent has finished its work, breaking the flow.
19
+
20
+ ArkGate solves this by shifting the check to the exact moment of writing. By intercepting file writes through IDE hooks or MCP, it ensures that if the agent writes a bad import, the write doesn't land. The agent gets immediate feedback and can self-correct before saving to disk.
21
+
11
22
  ---
12
23
 
13
24
  ## Default integration
@@ -1,6 +1,7 @@
1
1
  # ArkGate — enthusiast track
2
2
 
3
- If the AI writes an illegal import, the write is rejected. The same check fails the pull
3
+ **Write. Check. Ship.**
4
+ When the agent writes a bad import, the write doesn’t land. The same check fails the pull
4
5
  request. Not an API Gateway. Not a folder linter.
5
6
 
6
7
  Plain-language onboarding for builders who use AI agents but are not professional
@@ -18,9 +19,9 @@ aliases `ark` / `ark-check` still work).
18
19
 
19
20
  | Mode | Meaning |
20
21
  |------|---------|
21
- | **Suggest** | Propose an application shape and install a starter rules file. |
22
- | **Adapt** | Match the rules file to your real layout / raise governed coverage. |
23
- | **Enforce** | The rules cover the real code and checked edges are clean; host/CI guarantees remain separate. |
22
+ | **Setup** | Propose an application shape and install a starter config. |
23
+ | **In progress** | Match the config to your real layout / raise governed coverage. |
24
+ | **Ready** | The rules cover the real code and checked edges are clean; host/CI guarantees remain separate. |
24
25
 
25
26
  `ark start` and `ark-check --plan` will not claim "everything is guarded" while governed coverage is near zero. On Nest/Next/express starters, init also merges **framework filename conventions** into the layer globs so day-one coverage is real.
26
27
 
@@ -1,8 +1,9 @@
1
1
  # ArkGate package surface policy
2
2
 
3
- **If the AI writes an illegal import, the write is rejected. The same check fails the pull request.**
3
+ **Write. Check. Ship.**
4
+ **When the agent writes a bad import, the write doesn’t land. The same check fails the pull request.**
4
5
  That is the product wedge (host hook + required CI). Skills name the next step after that.
5
- **Not the wedge:** the optional in-process **ArkRun** kernel (`@arkgate/runtime`).
6
+ **Not the wedge:** the optional in-process **ArkRun** runtime (`@arkgate/runtime`).
6
7
 
7
8
  **Public product site:** [arkgate.online](https://www.arkgate.online/) (promise + only flow).
8
9
  In-repo `docs/` remains the package/agent reference. Source: GitHub; distribution: npm.
@@ -165,7 +166,7 @@ product claims**. Static architecture enforcement does not depend on them.
165
166
 
166
167
  | Surface | Import path | Notes |
167
168
  |---------|-------------|--------|
168
- | **ArkRun kernel** | **`@arkgate/runtime`** | Public brand **ArkRun**. Separate 0.x companion; `createStrictArkKernel` is the factory (each call is an isolated instance; no process-wide `getKernel()` singleton). Not bundled in the `arkgate` tarball (ADR 0004 / 0021). Published under the `experimental` dist-tag (never `latest`) as of 4.7.4. Install `@arkgate/runtime@experimental`. Verify with `npm view @arkgate/runtime dist-tags --json`. Root `publish-npm.yml` publishes it when that companion version is unpublished; companion-only: `publish-runtime.yml`. Event bus, intents, policies, sagas, event buffer, projections, and strict helpers. Managed components declare `uses` / `reactsTo` / `raises` / `sends` on `register()`; `getDependencyInformationPackage()` is a JSON snapshot of ids, lifetime, and declarations and never includes factories, live instances, or input DTOs (ADR 0023). `requestGraph()` slices that snapshot into **process** or **technical** graphs with optional `nodeIds`, `degreesOfSeparation`, and include/exclude query; `formatArkRunGraphMermaid()` (also `graph.mermaid`) is a helper string, never a score. `send()` is the transport port (local / localBlocking / broker); missing broker falls back to in-process local delivery, `ephemeral` defaults true, and **no cloud SDKs ship** in the package (ADR 0024). Opt-in `startInspector()` / `startArkRunInspector()` binds **`127.0.0.1` only**, refuses `NODE_ENV=production`, lazy-loads HTTP, and serves JSON snapshots, SSE, and `/graph` slices of the information package (no public / authless bind). Built-in stores are **InMemory reference only**. Branding ArkRun is not a production-durability claim. |
169
+ | **ArkRun kernel** | **`@arkgate/runtime`** | Public brand **ArkRun**. Separate 0.x companion; `createStrictArkKernel` is the factory (each call is an isolated instance; no process-wide `getKernel()` singleton). Not bundled in the `arkgate` tarball (ADR 0004 / 0021). Published under the `experimental` dist-tag as `@arkgate/runtime@0.1.0-experimental.0`. Install `@arkgate/runtime@experimental`. Verify with `npm view @arkgate/runtime dist-tags --json`. Root `publish-npm.yml` publishes it when that companion version is unpublished; companion-only: `publish-runtime.yml`. The first npm copy also received a `latest` dist-tag pointing at the same 0.x (npm default); that is not a production-durability claim. Event bus, intents, policies, sagas, event buffer, projections, and strict helpers. Managed components declare `uses` / `reactsTo` / `raises` / `sends` on `register()`; `getDependencyInformationPackage()` is a JSON snapshot of ids, lifetime, and declarations and never includes factories, live instances, or input DTOs (ADR 0023). `requestGraph()` slices that snapshot into **process** or **technical** graphs with optional `nodeIds`, `degreesOfSeparation`, and include/exclude query; `formatArkRunGraphMermaid()` (also `graph.mermaid`) is a helper string, never a score. `send()` is the transport port (local / localBlocking / broker); missing broker falls back to in-process local delivery, `ephemeral` defaults true, and **no cloud SDKs ship** in the package (ADR 0024). Opt-in `startInspector()` / `startArkRunInspector()` binds **`127.0.0.1` only**, refuses `NODE_ENV=production`, lazy-loads HTTP, and serves JSON snapshots, SSE, and `/graph` slices of the information package (no public / authless bind). Built-in stores are **InMemory reference only**. Branding ArkRun is not a production-durability claim. |
169
170
  | **NestJS adapter** | `@arkgate/runtime/nestjs` | Experimental optional peer `@nestjs/common` for the ArkRun kernel. Root `arkgate/nestjs` and `arkgate/runtime` forwarders were **removed in AR04 / ArkGate 4** — import the companion package directly. |
170
171
 
171
172
  ---
@@ -214,7 +215,8 @@ production deployment would need to satisfy; it is not a readiness certification
214
215
  ## Release notes (maintainers)
215
216
 
216
217
  Ship notes for a version live under [releases/](https://github.com/pedroknigge/arkgate/tree/main/docs/releases)
217
- (current published: [4.7.4.md](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/4.7.4.md);
218
+ (current published: [4.7.6.md](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/4.7.6.md);
219
+ prior published: [4.7.5.md](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/4.7.5.md);
218
220
  prior published: [4.7.3.md](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/4.7.3.md);
219
221
  prior published: [4.7.2.md](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/4.7.2.md);
220
222
  prior published: [4.7.0.md](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/4.7.0.md);