arkgate 4.8.18 → 4.8.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/README.md +5 -6
  3. package/bin/ark-mcp-runtime.mjs +3 -3
  4. package/bin/ark-shared.mjs +187 -16
  5. package/bin/ark.mjs +18 -18
  6. package/bin/lib/ci-and-commands.mjs +2 -2
  7. package/bin/lib/doctor-human.mjs +2 -0
  8. package/bin/lib/doctor-next-actions.mjs +35 -0
  9. package/bin/lib/doctor-plan.mjs +6 -8
  10. package/bin/lib/gate-files.mjs +22 -1
  11. package/bin/lib/host-support-matrix.mjs +1 -1
  12. package/bin/lib/html-report-depth.mjs +1 -1
  13. package/bin/lib/install-migrate.mjs +3 -4
  14. package/bin/lib/managed-upgrade.mjs +30 -5
  15. package/bin/lib/mcp-adoption.mjs +4 -1
  16. package/bin/lib/presets.mjs +14 -14
  17. package/bin/lib/scan-files.mjs +3 -26
  18. package/bin/lib/skill-install.mjs +3 -2
  19. package/bin/lib/start-preview.mjs +60 -5
  20. package/bin/lib/write-path-detect.mjs +3 -2
  21. package/dist/{diagnosticCatalog-BNxKdcN4.d.ts → diagnosticCatalog-D2v0ASN2.d.ts} +1 -1
  22. package/dist/index.cjs +1 -1
  23. package/dist/index.d.ts +2 -2
  24. package/dist/index.js +1 -1
  25. package/dist/nestjs/index.cjs +1 -1
  26. package/dist/nestjs/index.js +1 -1
  27. package/dist/runtime/index.cjs +1 -1
  28. package/dist/runtime/index.d.ts +1 -1
  29. package/dist/runtime/index.js +1 -1
  30. package/docs/README.md +1 -1
  31. package/docs/agent-guide.md +3 -1
  32. package/docs/ai-gates.md +7 -3
  33. package/docs/develop.md +1 -2
  34. package/docs/use.md +1 -2
  35. package/package.json +1 -1
  36. package/server.json +2 -2
  37. package/templates/agent-skills/README.md +1 -1
  38. package/templates/agent-skills/ark-place/SKILL.md +2 -0
  39. package/templates/hooks/opencode-ark-write-gate.mjs +2 -2
  40. package/templates/skills/ark-place.md +2 -0
@@ -2,7 +2,7 @@ var Fo=Object.defineProperty;var i=(e,t)=>Fo(e,"name",{value:t,configurable:!0})
2
2
  `)}function Ud(e,t,n){let r=new Set(e.keys());if(Ro(n.include)&&(r=new Set([...r].filter(l=>{let c=e.get(l);return c!==void 0&&oa(c,n.include)}))),Ro(n.exclude))for(let l of[...r]){let c=e.get(l);c&&oa(c,n.exclude)&&r.delete(l)}let o=t.filter(l=>r.has(l.from)&&r.has(l.to));n.nodeIds.length>0&&(r=Hd(r,n.nodeIds,n.degreesOfSeparation,Kd(o)));let s=[...r].sort(Jt).map(l=>e.get(l)).filter(l=>!!l),a=o.filter(l=>r.has(l.from)&&r.has(l.to)).sort((l,c)=>Jt(l.from,c.from)||Jt(l.kind,c.kind)||Jt(l.to,c.to));return{nodes:s,edges:a}}function ar(e={},t={}){let n=Fd(e),r=sr(t),o=$d(n.components,r.slice),s=Ud(o.nodes,o.edges,r),a={schemaVersion:Ao,kernelInstanceId:n.kernelInstanceId,slice:r.slice,query:r,nodes:s.nodes,edges:s.edges,mermaid:""};return a.mermaid=bo(a),a}var Ao,ko,Io,ia,aa,la,te,Td,Nd,Dd,lr=St(()=>{"use strict";ht();Ao="1.0",ko="process",Io=["process","technical"],ia=["component","interaction"],aa=["raises","reactsTo","sends"],la=["uses"],te=class extends Error{static{i(this,"InvalidArkRunGraphQueryError")}option;constructor(t,n){super(n??(t==="slice"?'ArkRun graph slice must be "process" or "technical".':t==="degreesOfSeparation"?"ArkRun graph degreesOfSeparation must be a non-negative integer.":`ArkRun graph ${t} is not a closed query.`)),this.name="InvalidArkRunGraphQueryError",this.option=t}},Td=new Set(Io),Nd=new Set(["slice","nodeIds","degreesOfSeparation","include","exclude"]),Dd=new Set(["ids","labels","tags","groups","architectureKinds"]);i(Jt,"compare");i(ho,"uniqueSorted");i(na,"emptyMatch");i(Ro,"matchHasCriteria");i(ge,"nameList");i(ca,"globMatch");i(Xt,"anyGlob");i(da,"closedSlice");i(ua,"closedDegrees");i(ra,"closedMatch");i(sr,"closeArkRunGraphQuery");i(ir,"arkRunGraphQueryFromSearchParams");i(Ld,"nodeFields");i(oa,"nodeMatches");i(Fd,"asPackage");i(Md,"componentNode");i(rr,"interactionNode");i(Zt,"addNode");i(or,"addEdge");i($d,"buildSlice");i(Kd,"adjacency");i(Hd,"neighborhood");i(Qt,"mermaidSafeId");i(sa,"mermaidLabel");i(Gd,"uniqueMermaidIds");i(bo,"formatArkRunGraphMermaid");i(Ud,"filterGraph");i(ar,"requestArkRunGraph")});function vo(e){if(e===void 0)return"local";if(typeof e=="string"&&Vd.has(e))return e;throw new Rt("transport")}function Eo(e){if(e===void 0)return!0;if(e===!0||e===!1)return e;throw new Rt("ephemeral")}function cr(e){let t=vo(e.transport),n=Eo(e.ephemeral),r=t==="broker"&&e.brokerBound!==!0,o=t==="broker"&&!r?"broker":"local",s=t==="localBlocking";return{transport:t,ephemeral:n,deliveredVia:o,fallbackToLocal:r,notifySubscribers:o==="local",awaitHandlers:s,awaitHandoff:n||s}}var en,At,Vd,Rt,tn=St(()=>{"use strict";en=["local","localBlocking","broker"],At=!0,Vd=new Set(en),Rt=class extends Error{static{i(this,"InvalidArkRunSendOptionError")}option;constructor(t){super(t==="transport"?'ArkRun transport must be "local", "localBlocking", or "broker".':"ArkRun ephemeral must be a boolean."),this.name="InvalidArkRunSendOptionError",this.option=t}};i(vo,"closedArkRunTransportKind");i(Eo,"closedArkRunEphemeral");i(cr,"resolveArkRunSendPlan")});function ur(e){return e==="production"}function Bd(e){let t=e.split(".");if(t.length!==4)return;let n=[];for(let r of t){if(!/^\d{1,3}$/.test(r))return;let o=Number(r);if(o>255)return;n.push(o)}return n}function pa(e){if(e.startsWith("[::ffff:")&&e.endsWith("]"))return e.slice(8,-1);if(e.startsWith("::ffff:"))return e.slice(7)}function It(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();if(t==="localhost"||t==="::1"||t==="[::1]")return!0;let n=pa(t);if(n)return It(n);let r=Bd(t);return r!==void 0&&r[0]===127}function fa(e){if(e===void 0)return dr;if(typeof e!="string")throw new ce(String(e));let t=e.trim();if(jd.has(t.toLowerCase())||!It(t))throw new ce(t);let n=t.toLowerCase();if(n==="localhost")return dr;if(n==="[::1]")return"::1";let r=pa(n);return r?fa(r):n}function Wd(e){if(e===void 0)return wo;if(typeof e!="number"||!Number.isInteger(e)||e<0||e>65535)throw new ce(`port:${String(e)}`);return e}function ln(e={}){if(ur(e.nodeEnv)||ur(e.processNodeEnv))throw new kt;return{host:fa(e.host),port:Wd(e.port)}}function be(e,t,n){return`http://${e.includes(":")?`[${e}]`:e}:${t}${n}`}function zd(e){if(e!==void 0)try{return JSON.parse(JSON.stringify(e))}catch{return}}function qd(e){return{kinds:[...en],ephemeralDefault:e.ephemeralDefault===!1?!1:!0,brokerBound:e.brokerBound===!0,cloudSdksShipped:!1,fallback:xo}}function _e(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function Yd(e){let t=_e(e);if(!t||typeof t.id!="string")return;let n=t.status;if(n!=="pending"&&n!=="failed")return;let r=_e(t.event),o=r&&typeof r.intent=="string"?r.intent:typeof t.intent=="string"?t.intent:void 0,s={id:t.id,status:n,attempts:typeof t.attempts=="number"&&Number.isFinite(t.attempts)?t.attempts:0};return o&&(s.intent=o),typeof t.error=="string"&&t.error.length>0&&(s.error=t.error),typeof t.updatedAt=="string"&&(s.updatedAt=t.updatedAt),s}function pr(e){if(typeof e!="number"||!Number.isFinite(e))return se;let t=Math.trunc(e);return t<0?0:t>se?se:t}function je(e,t){let n=typeof e=="string"&&e.trim().length>0?e.trim():e&&typeof e=="object"&&"constructor"in e?String(e.constructor?.name??t):t,r=/^InMemory/i.test(n)?"memory":"durable";return{role:t,id:n,kind:r}}function cn(e={}){let t=_e(e),n=_e(t?.durability)??t,r=Array.isArray(n?.stores)?n.stores:Array.isArray(t?.stores)?t.stores:[],o=[];for(let s of r){let a=_e(s);if(!a)continue;let l=a.role;if(l!=="outbox"&&l!=="audit"&&l!=="workflow")continue;let c=typeof a.id=="string"?a.id:typeof a.name=="string"?a.name:void 0;if(!c)continue;let p=a.kind==="memory"||a.kind==="durable"?a.kind:je(c,l).kind;o.push({role:l,id:c,kind:p})}return{durability:{stores:o}}}function Be(e=[],t={}){let n=pr(t.sampleLimit),r=Array.isArray(e)?e:[],o=[],s=[];for(let a of r){let l=Yd(a);l&&(l.status==="pending"?o.push(l):s.push(l))}return{available:!0,pendingCount:o.length,failedCount:s.length,pending:o.slice(0,n),failed:s.slice(0,n),sampleLimit:n}}function Ue(){return{available:!1,pendingCount:0,failedCount:0,pending:[],failed:[],sampleLimit:se}}function Xd(e){let t=_e(e);if(!t||typeof t.id!="string")return;let n=typeof t.workflowName=="string"?t.workflowName:typeof t.name=="string"?t.name:void 0;if(!n)return;let r={id:t.id,name:n,status:typeof t.status=="string"?t.status:"unknown"};return typeof t.currentStep=="string"&&(r.currentStep=t.currentStep),typeof t.error=="string"&&t.error.length>0&&(r.error=t.error),r}function Zd(e){return e==="idle"||e==="waiting"}function We(e=[],t={}){let n=pr(t.sampleLimit),r=Array.isArray(e)?e:[],o=[],s=0,a=0,l=0,c=0;for(let p of r){let f=Xd(p);f&&(o.push(f),f.status==="running"?s+=1:f.status==="compensating"?a+=1:f.status==="failed"?l+=1:Zd(f.status)&&(c+=1))}return{available:!0,total:o.length,runningCount:s,compensatingCount:a,failedCount:l,pendingCount:c,workflows:o.slice(0,n),sampleLimit:n}}function Ve(){return{available:!1,total:0,runningCount:0,compensatingCount:0,failedCount:0,pendingCount:0,workflows:[],sampleLimit:se}}function Jd(e){if(e===void 0)return;let t=_e(e);if(!t||t.available===!1)return Ue();let n=pr(t.sampleLimit);if(Array.isArray(t.pending)||Array.isArray(t.failed)||Array.isArray(t.records)){let r=[...Array.isArray(t.pending)?t.pending:[],...Array.isArray(t.failed)?t.failed:[],...Array.isArray(t.records)?t.records:[]],o=Be(r,{sampleLimit:n}),s=typeof t.pendingCount=="number"&&Number.isFinite(t.pendingCount)?Math.max(0,Math.trunc(t.pendingCount)):o.pendingCount,a=typeof t.failedCount=="number"&&Number.isFinite(t.failedCount)?Math.max(0,Math.trunc(t.failedCount)):o.failedCount;return{...o,pendingCount:s,failedCount:a,sampleLimit:n}}return Ue()}function Qd(e){if(e===void 0)return;let t=_e(e);if(!t||t.available===!1)return Ve();let n=pr(t.sampleLimit);if(Array.isArray(t.workflows)){let r=We(t.workflows,{sampleLimit:n}),o=typeof t.total=="number"&&Number.isFinite(t.total)?Math.max(0,Math.trunc(t.total)):r.total,s=typeof t.runningCount=="number"&&Number.isFinite(t.runningCount)?Math.max(0,Math.trunc(t.runningCount)):r.runningCount,a=typeof t.compensatingCount=="number"&&Number.isFinite(t.compensatingCount)?Math.max(0,Math.trunc(t.compensatingCount)):r.compensatingCount,l=typeof t.failedCount=="number"&&Number.isFinite(t.failedCount)?Math.max(0,Math.trunc(t.failedCount)):r.failedCount,c=typeof t.pendingCount=="number"&&Number.isFinite(t.pendingCount)?Math.max(0,Math.trunc(t.pendingCount)):r.pendingCount;return{...r,total:o,runningCount:s,compensatingCount:a,failedCount:l,pendingCount:c,sampleLimit:n}}return Ve()}function fr(e={}){let t=ln({host:e.host,port:e.port}),n=Ie({kernelInstanceId:e.kernelInstanceId,components:e.package&&typeof e.package=="object"&&!Array.isArray(e.package)&&Array.isArray(e.package.components)?e.package.components:[]}),r=Jd(e.outbox),o=Qd(e.workflows),s={schemaVersion:So,kernelInstanceId:typeof e.kernelInstanceId=="string"?e.kernelInstanceId:n.kernelInstanceId,bind:{host:t.host,port:t.port,loopback:!0},package:{...n,schemaVersion:"1.0"},transport:qd(e),observability:zd(e.observability)??{},hardening:cn(e.hardening)};return r&&(s.outbox=r),o&&(s.workflows=o),s}function dn(e){return`event: ${Co}
3
3
  data: ${JSON.stringify(e)}
4
4
 
5
- `}var So,dr,wo,nn,rn,on,sn,an,Co,xo,se,kt,ce,jd,un=St(()=>{"use strict";ht();tn();So="1.0",dr="127.0.0.1",wo=0,nn="/snapshot",rn="/events",on="/graph",sn="/outbox",an="/workflows",Co="snapshot",xo="in-process-local",se=32,kt=class extends Error{static{i(this,"ArkRunInspectorProductionError")}constructor(){super("ArkRun inspector refuses to start when NODE_ENV=production."),this.name="ArkRunInspectorProductionError"}},ce=class extends Error{static{i(this,"ArkRunInspectorBindError")}constructor(t){super(`ArkRun inspector binds loopback only (default 127.0.0.1). Public host "${t}" is rejected.`),this.name="ArkRunInspectorBindError"}},jd=new Set(["","*","0","0.0.0.0","::","::0","[::]","[::0]","::ffff:0.0.0.0","[::ffff:0.0.0.0]"]);i(ur,"isArkRunInspectorProductionEnv");i(Bd,"ipv4Octets");i(pa,"unwrapIpv4Mapped");i(It,"isArkRunInspectorLoopbackHost");i(fa,"closedHost");i(Wd,"closedPort");i(ln,"resolveArkRunInspectorBind");i(be,"arkRunInspectorUrl");i(zd,"jsonClone");i(qd,"closedTransportFacts");i(_e,"asRecord");i(Yd,"closedOutboxSummary");i(pr,"closedSampleLimit");i(je,"classifyArkRunInspectorStoreDurability");i(cn,"buildArkRunInspectorHardening");i(Be,"buildArkRunInspectorOutboxMonitor");i(Ue,"unavailableArkRunInspectorOutboxMonitor");i(Xd,"closedWorkflowSummary");i(Zd,"isPendingWorkflowStatus");i(We,"buildArkRunInspectorWorkflowsMonitor");i(Ve,"unavailableArkRunInspectorWorkflowsMonitor");i(Jd,"closedOutboxMonitor");i(Qd,"closedWorkflowsMonitor");i(fr,"buildArkRunInspectorSnapshot");i(dn,"formatArkRunInspectorSseEvent")});var ga={};va(ga,{listenArkRunInspector:()=>iu});function eu(){return{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}}function tu(){return{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-store",connection:"keep-alive","x-accel-buffering":"no"}}function nu(e){let t=e&&e.length>0?e:"/";return new URL(t,"http://127.0.0.1")}function Te(e,t,n){if(!(e.writableEnded||e.destroyed))try{e.writeHead(t,eu()),e.end(JSON.stringify(n))}catch{}}function ru(e,t){let n=e.address();if(n===null||typeof n=="string")throw new ce(t.host);if(!It(n.address))throw new ce(n.address);return{host:t.host,port:n.port}}async function ou(e){if(typeof e.listInspectorOutbox=="function")return e.listInspectorOutbox();let t=e.outbox??e.eventBuffer;if(!t||typeof t.list!="function")return Ue();let[n,r]=await Promise.all([t.list("pending"),t.list("failed")]);return Be([...n??[],...r??[]],{sampleLimit:se})}async function su(e){return typeof e.listInspectorWorkflows=="function"?e.listInspectorWorkflows():!e.workflowEngine||typeof e.workflowEngine.list!="function"?Ve():We(await e.workflowEngine.list(),{sampleLimit:se})}async function iu(e,t){let n=await import("http"),r=new Set,o=new Set,s=typeof t.sseIntervalMs=="number"&&Number.isFinite(t.sseIntervalMs)?Math.max(0,t.sseIntervalMs):1e3,a=t.bind,l=i(()=>e.getInspectorSnapshot(a),"snapshot"),c=n.createServer((p,f)=>{let y=nu(p.url),u=y.pathname;if(p.method==="GET"&&(u==="/"||u===nn)){Te(f,200,l());return}if(p.method==="GET"&&u===on){try{Te(f,200,e.requestGraph(ir({slice:y.searchParams.get("slice"),nodeIds:y.searchParams.get("nodeIds"),degreesOfSeparation:y.searchParams.get("degreesOfSeparation"),include:y.searchParams.get("include"),exclude:y.searchParams.get("exclude")})))}catch(g){if(g instanceof te){Te(f,400,{error:g.message,option:g.option});return}throw g}return}if(p.method==="GET"&&u===sn){ou(e).then(g=>Te(f,200,g)).catch(g=>{Te(f,500,{error:g instanceof Error?g.message:"outbox monitor failed"})});return}if(p.method==="GET"&&u===an){su(e).then(g=>Te(f,200,g)).catch(g=>{Te(f,500,{error:g instanceof Error?g.message:"workflows monitor failed"})});return}if(p.method==="GET"&&u===rn){f.writeHead(200,tu()),f.flushHeaders(),f.write(dn(l())),r.add(f);let g=s>0?setInterval(()=>{f.write(dn(l()))},s):void 0;g&&o.add(g);let d=i(()=>{r.delete(f),g&&(clearInterval(g),o.delete(g))},"drop");p.on("close",d),f.on("close",d);return}Te(f,404,{error:"not found"})});try{await new Promise((p,f)=>{let y=i(u=>f(u),"onError");c.once("error",y),c.listen({host:t.bind.host,port:t.bind.port},()=>{c.off("error",y);try{a=ru(c,t.bind),p()}catch(u){f(u instanceof Error?u:new ce(t.bind.host))}})})}catch(p){throw await new Promise(f=>{c.close(()=>f())}),p}return{host:a.host,port:a.port,url:be(a.host,a.port,"/"),snapshotUrl:be(a.host,a.port,nn),eventsUrl:be(a.host,a.port,rn),graphUrl:be(a.host,a.port,on),outboxUrl:be(a.host,a.port,sn),workflowsUrl:be(a.host,a.port,an),close(){for(let p of o)clearInterval(p);o.clear();for(let p of r)p.end();return r.clear(),new Promise((p,f)=>{c.close(y=>{y?f(y):p()})})}}}var ma=St(()=>{"use strict";lr();un();i(eu,"jsonHeaders");i(tu,"sseHeaders");i(nu,"requestUrl");i(Te,"writeJson");i(ru,"boundAddress");i(ou,"resolveOutboxMonitor");i(su,"resolveWorkflowsMonitor");i(iu,"listenArkRunInspector")});var mr="4.8.18";var Ea=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,Sa=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,wa=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function Ca(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),o=String(t?.toLayer??"");return Ea.test(n)?"pure-shared":r==="PersistenceAdapters"&&(Sa.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${o} ${n}`))?"kernel-emit":wa.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&o==="PersistenceAdapters"?"use-case":"unknown"}i(Ca,"classifyLayerImportKind");function xa(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=Ca(typeof e.target=="string"?e.target:"",{fromLayer:typeof e.fromLayer=="string"?e.fromLayer:void 0,toLayer:typeof e.toLayer=="string"?e.toLayer:void 0});return t==="pure-shared"?"Adopt the imported constants/types/pure module into DomainModel or SharedKernel (do not inject a port). Then preflight again.":t==="kernel-emit"?"Persistence must not emit. Inject a port or move the event map to SharedTypes; do not import kernel/events/bootstrap from a repository. Then preflight again.":t==="use-case"||e.portProofEligible?`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, test at the public interface, then preflight again.`:"Classify the import: if it is constants/types/pure, adopt into DomainModel or SharedKernel; define a port only if the target is a real use-case. Then preflight again."}i(xa,"layerImportNextAction");function Oa(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}i(Oa,"arkRunCallSiteName");function Pa(e){let t=Oa(e),n=typeof e.fromLayer=="string"&&e.fromLayer.length>0?e.fromLayer:void 0;switch(e.ruleId){case"ARKRUN_MISSING_ROOT":return t?`Import createStrictArkKernel from arkgate/runtime and call it in composition root ${t} listed in arkRun.compositionRoots, then preflight again.`:"Import createStrictArkKernel from arkgate/runtime (same npm package; @arkgate/runtime is deprecated) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKRUN_KERNEL_IN_DOMAIN":return t?`Move the kernel import of ${t} out of ${n??"the Domain-role layer"} into a composition root or adapter. Import from arkgate/runtime, then preflight again.`:"Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from arkgate/runtime (same npm package; @arkgate/runtime is deprecated), then preflight again. Never mechanical-safe.";case"ARKRUN_DIRECT_NEW":return t?`Resolve ${t} from the kernel instead of constructing it with new, then preflight again.`:"Resolve the type from the kernel instead of constructing it with new, then preflight again. Never mechanical-safe \u2014 rewiring construction is a design decision.";case"ARKRUN_UNDECLARED_EMIT":return t?`Add ${t} to raises or sends on the managed component, then preflight again.`:"Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment.";case"ARKRUN_UNDECLARED_HANDLE":return t?`Add ${t} to reactsTo on the managed component, then preflight again.`:"Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment.";case"ARKRUN_UNDECLARED_DEPEND":return t?`Add ${t} to uses on the managed component, then preflight again.`:"Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment.";case"ARKRUN_TRANSPORT_BYPASS":return t?`Send through the ArkRun kernel transport instead of importing ${t}, then preflight again.`:"Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe \u2014 homemade buses stay judgment.";default:return`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(Pa,"arkRunNextAction");function fe(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return xa(e);case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, test at the public interface, then preflight again.`;case"CAPABILITY_VIOLATION":return`Define a ${String(e.capability??"capability")} port in ${e.fromLayer??"the walled layer"}, bind the implementation outside it, test at the public interface, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, test at the public interface, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"LITERAL_PATH_DRIFT":return typeof e.target=="string"&&e.target.length>0?`Rewrite the literal to ${e.target}, or run \`arkgate-check --path-drift --base-ref <ref> --write\` to apply every anchored replacement.`:"Rewrite the literal to the rename destination, or run `arkgate-check --path-drift --base-ref <ref> --write` to apply every anchored replacement.";case"LITERAL_PATH_UNRESOLVED":return"Read the candidate and decide: fix the path, or leave it. Advisory \u2014 with no rename to anchor it there is no destination to propose, so --write never touches it.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";case"INVARIANT_COVERAGE_OUTSIDE_ROOTS":return"Move the covering test under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json, then run Ark again.";case"INVARIANT_CATALOG_EMPTY":return typeof e.file=="string"&&e.file.length>0?`Add 1\u20132 short phrases to invariants[] in ${e.file}, then run ark-check --doctor. Starters show the shape.`:"Add 1\u20132 short phrases to invariants[] in arkrules/<Domain>.json, then run ark-check --doctor. Starters show the shape.";case"INVARIANT_TESTS_PATH_MISSING":return"Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present.";case"INVARIANT_COVERAGE_ROOTS_MISSING":return"Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. An enforced invariant fails closed until that path is present.";case"ARKRULE_STRUCTURE":case"ARKRULE_INVARIANT":case"INVARIANT_UNCOVERED":return`Fix the structure or invariant for ${typeof e.arkruleId=="string"&&e.arkruleId.length>0?e.arkruleId:"the ArkRule"} (declared in ${typeof e.arkruleSource=="string"&&e.arkruleSource.length>0?e.arkruleSource:"arkrules/<Layer>.json"}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`;case"ARKRUN_MISSING_ROOT":case"ARKRUN_KERNEL_IN_DOMAIN":case"ARKRUN_DIRECT_NEW":case"ARKRUN_UNDECLARED_EMIT":case"ARKRUN_UNDECLARED_HANDLE":case"ARKRUN_UNDECLARED_DEPEND":case"ARKRUN_TRANSPORT_BYPASS":return Pa(e);case"ARKORDER_MISSING_PLANE":return typeof e.target=="string"&&e.target.length>0?`Import createOrderPlane from arkgate/order and call it in plane root ${e.target} listed in arkOrder.planeRoots, then preflight again.`:"Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKORDER_KERNEL_IN_DOMAIN":return"Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe.";case"ARKORDER_GENERIC_UPDATE":return"Don't use a generic update. First freeze with release(). Later, propose the change, then apply it.";case"ARKORDER_TOO_MANY_PARAMS":return"Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe.";case"ARKORDER_INGEST_WRITES_XI":return"Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe.";case"ARKORDER_XI_FIELD_WRITE":return typeof e.target=="string"&&e.target.length>0?`Don't write ${e.target} from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.`:"Don't write a named product choice from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.";case"ARKORDER_UNVALVED_RELEASE":return"Change the choice with proposeRelease then apply. release() is only the first freeze. Never mechanical-safe.";default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(fe,"deterministicNextAction");var gn="1.5",yr="docs/diagnostics.md",Mo={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","mode","valid","completeness","completenessReasons","diagnostics"],allOf:[{if:{properties:{completeness:{enum:["partial","unavailable"]}},required:["completeness"]},then:{properties:{valid:{const:!1}}}},{if:{properties:{mode:{const:"resolved-candidate-facts"},completeness:{enum:["complete","partial"]}},required:["mode","completeness"]},then:{required:["policyHash","resolverIdentity","factsHash","candidateTreeHash"]}},{if:{properties:{completeness:{const:"complete"}},required:["completeness"]},then:{properties:{completenessReasons:{maxItems:0}}},else:{properties:{completenessReasons:{minItems:1}}}}],properties:{schemaVersion:{const:"1.5"},mode:{enum:["lexical-compatibility","resolved-candidate-facts"]},valid:{type:"boolean"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:{type:"string",minLength:1},message:{type:"string",minLength:1},file:{type:"string",minLength:1}}}},policyHash:{type:"string",minLength:1},resolverIdentity:{type:"string",minLength:1},factsHash:{type:"string",minLength:1},candidateTreeHash:{type:"string",minLength:1},diagnostics:{type:"array",items:{type:"object",additionalProperties:!1,required:["ruleId","severity","message","location","evidence"],properties:{ruleId:{type:"string",minLength:1},severity:{enum:["error","warning"]},message:{type:"string",minLength:1},location:{type:"object",additionalProperties:!1,required:["file","line","column"],properties:{file:{type:"string",minLength:1},line:{type:"integer",minimum:1},column:{type:"integer",minimum:1}}},evidence:{type:"object",additionalProperties:!1,properties:{target:{type:"string"},fromLayer:{type:"string"},toLayer:{type:"string"},typeOnly:{type:"boolean"},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"},peerIsolation:{type:"boolean"},capability:{type:"string",minLength:1},edgeKind:{type:"string",minLength:1},arkruleId:{type:"string",minLength:1},arkruleSource:{type:"string",minLength:1}}},nextAction:{type:"string",minLength:1},findingRef:{type:"string",minLength:1,pattern:"^fnv1a-[0-9a-f]{8}$"},targetKey:{type:"string",minLength:1},docsCodePath:{type:"string",minLength:1}}}}}};function mn(e){let t=typeof e.ruleId=="string"?e.ruleId:typeof e.code=="string"?e.code:void 0,n=typeof e.file=="string"?e.file:void 0,r=typeof e.fromLayer=="string"?e.fromLayer:void 0,o=typeof e.toLayer=="string"?e.toLayer:void 0,s=typeof e.target=="string"?e.target:void 0;return[t,n,r??"",o??"",s??""].join("|")}i(mn,"adapterFindingTargetKey");function yn(e){let t=new Map;return e.map(n=>{let r=mn(n),o=(t.get(r)??0)+1;return t.set(r,o),o===1?r:`${r}#${o}`})}i(yn,"adapterFindingOccurrenceTargetKeys");function hr(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}i(hr,"adapterFindingRefFromTargetKey");function Rr(e){return`${yr}#${e}`}i(Rr,"adapterDocsCodePath");function O(e){return typeof e=="string"&&e.length>0?e:void 0}i(O,"text");function $o(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}i($o,"positiveInteger");function _a(e,t,n){return fe({ruleId:e,target:O(t.target)??O(n.target)??void 0,fromLayer:O(t.fromLayer)??void 0,toLayer:O(t.toLayer)??void 0,typeOnly:t.typeOnly===!0,targetTypeOnlyExports:t.targetTypeOnlyExports===!0,namedBindingsTypeOnly:t.namedBindingsTypeOnly===!0,portProofEligible:t.portProofEligible===!0,peerIsolation:t.peerIsolation===!0,sourcePureTypeModule:t.sourcePureTypeModule===!0,edgeKind:O(t.edgeKind)??void 0,capability:O(t.capability)??O(n.capability)??void 0,arkruleId:O(t.arkruleId)??void 0,arkruleSource:O(t.arkruleSource)??void 0})}i(_a,"nextActionForDiagnostic");function Ar(e,t="error",n){let r=O(e.ruleId)??O(e.code)??"ARK_UNKNOWN",o=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,s={...O(e.target)?{target:O(e.target)}:{},...O(e.fromLayer)?{fromLayer:O(e.fromLayer)}:{},...O(e.toLayer)?{toLayer:O(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{},...typeof e.targetTypeOnlyExports=="boolean"?{targetTypeOnlyExports:e.targetTypeOnlyExports}:{},...typeof e.sourcePureTypeModule=="boolean"?{sourcePureTypeModule:e.sourcePureTypeModule}:{},...typeof e.namedBindingsTypeOnly=="boolean"?{namedBindingsTypeOnly:e.namedBindingsTypeOnly}:{},...typeof e.portProofEligible=="boolean"?{portProofEligible:e.portProofEligible}:{},...typeof e.peerIsolation=="boolean"?{peerIsolation:e.peerIsolation}:{},...O(e.capability)?{capability:O(e.capability)}:{},...O(e.edgeKind)?{edgeKind:O(e.edgeKind)}:{},...O(e.arkruleId)?{arkruleId:O(e.arkruleId)}:{},...O(e.arkruleSource)?{arkruleSource:O(e.arkruleSource)}:{}},a=n??mn(e),l=hr(a);return{ruleId:r,severity:o,message:O(e.message)??r,location:{file:O(e.file)??"<unknown>",line:$o(e.line,1),column:$o(e.column,1)},evidence:s,nextAction:O(e.nextAction)??_a(r,s,e),findingRef:l,targetKey:a,docsCodePath:Rr(r)}}i(Ar,"toAdapterDiagnostic");function Ta(e){let t=e.completeness??"complete",n=e.mode??"lexical-compatibility";if(t==="complete"&&(e.completenessReasons?.length??0)>0)throw new Error("completenessReasons must be empty when completeness is complete.");let r=t==="complete"?[]:e.completenessReasons&&e.completenessReasons.length>0?e.completenessReasons.map(y=>({code:O(y.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:O(y.message)??`Analysis ${t}: required evidence is incomplete.`,...O(y.file)?{file:O(y.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],o={...O(e.policyHash)?{policyHash:O(e.policyHash)}:{},...O(e.resolverIdentity)?{resolverIdentity:O(e.resolverIdentity)}:{},...O(e.factsHash)?{factsHash:O(e.factsHash)}:{},...O(e.candidateTreeHash)?{candidateTreeHash:O(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let y of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!o[y])throw new Error(`${y} is required for resolved ${t} adapter evidence.`)}let s=e.violations??[],a=e.warnings??[],l=yn(s),c=yn(a),p=[...s.map((y,u)=>Ar(y,"error",l[u])),...a.map((y,u)=>Ar(y,"warning",c[u]))],f={schemaVersion:"1.5",completenessReasons:r,diagnostics:p};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...f,mode:n,valid:!1,completeness:t,...o};let y={policyHash:o.policyHash,resolverIdentity:o.resolverIdentity,factsHash:o.factsHash,candidateTreeHash:o.candidateTreeHash};return t==="complete"?{...f,mode:n,valid:e.valid,completeness:t,...y}:{...f,mode:n,valid:!1,completeness:t,...y}}return t==="complete"?{...f,mode:n,valid:e.valid,completeness:t,...o}:{...f,mode:n,valid:!1,completeness:t,...o}}i(Ta,"createAdapterResult");var qe=class{static{i(this,"IntentRegistry")}intents=new Map;dependencies=new Map;productions=new Map;define(t,n){if(this.intents.has(t))throw new Error(`Intent "${t}" is already registered. Intent names must be unique within a registry.`);let r=i(s=>({intent:t,payload:s,metadata:{occurredAt:new Date().toISOString(),source:"unknown"}}),"fn");Object.defineProperty(r,"name",{value:t,enumerable:!0,configurable:!1,writable:!1});let o=r;if(this.intents.set(t,o),n?.dependsOn)for(let s of n.dependsOn)this.declareDependency(t,s);if(n?.produces)for(let s of n.produces)this.declareProduction(t,s);return o}declareDependency(t,n){this.dependencies.has(t)||this.dependencies.set(t,new Set),this.dependencies.get(t).add(n)}declareProduction(t,n){this.productions.has(t)||this.productions.set(t,new Set),this.productions.get(t).add(n)}get(t){return this.intents.get(t)}list(){return Array.from(this.intents.values())}getDependencies(t){let n=this.dependencies.get(t);return n?Array.from(n):[]}getProductions(t){let n=this.productions.get(t);return n?Array.from(n):[]}getAllRelationships(){let t=[];for(let[n,r]of this.dependencies.entries())for(let o of r)t.push({from:n,to:o,kind:"dependsOn"});for(let[n,r]of this.productions.entries())for(let o of r)t.push({from:n,to:o,kind:"produces"});return t}has(t){return this.intents.has(t)}clear(){this.intents.clear(),this.dependencies.clear(),this.productions.clear()}};var Ko=new qe;function Ho(e,t){return Ko.define(e,t)}i(Ho,"defineIntent");function hn(){return new qe}i(hn,"createIntentRegistry");var Go=Ko;var Uo=["Domain.","Application.","Adapter.","Workflow.","Job.","Presentation.","Reporting.","Metadata.","Security.","Audit.","Observability.","Kernel."];function Rn(e){if(!e||typeof e!="string")return{valid:!1,reason:"Intent name must be a non-empty string"};if(!Uo.some(n=>e.startsWith(n)))return{valid:!1,reason:`Intent "${e}" must start with one of: ${Uo.join(", ")}`};let t=e.slice(e.indexOf(".")+1);return!t||!/^[A-Za-z][A-Za-z0-9_.]*$/.test(t)?{valid:!1,reason:`Intent "${e}" has an invalid segment after the layer prefix`}:{valid:!0}}i(Rn,"validateIntentName");var Se=class extends Error{static{i(this,"PolicyViolationError")}violations;constructor(t){let n=t.map(r=>`- ${r.policyName}: ${r.message}`).join(`
5
+ `}var So,dr,wo,nn,rn,on,sn,an,Co,xo,se,kt,ce,jd,un=St(()=>{"use strict";ht();tn();So="1.0",dr="127.0.0.1",wo=0,nn="/snapshot",rn="/events",on="/graph",sn="/outbox",an="/workflows",Co="snapshot",xo="in-process-local",se=32,kt=class extends Error{static{i(this,"ArkRunInspectorProductionError")}constructor(){super("ArkRun inspector refuses to start when NODE_ENV=production."),this.name="ArkRunInspectorProductionError"}},ce=class extends Error{static{i(this,"ArkRunInspectorBindError")}constructor(t){super(`ArkRun inspector binds loopback only (default 127.0.0.1). Public host "${t}" is rejected.`),this.name="ArkRunInspectorBindError"}},jd=new Set(["","*","0","0.0.0.0","::","::0","[::]","[::0]","::ffff:0.0.0.0","[::ffff:0.0.0.0]"]);i(ur,"isArkRunInspectorProductionEnv");i(Bd,"ipv4Octets");i(pa,"unwrapIpv4Mapped");i(It,"isArkRunInspectorLoopbackHost");i(fa,"closedHost");i(Wd,"closedPort");i(ln,"resolveArkRunInspectorBind");i(be,"arkRunInspectorUrl");i(zd,"jsonClone");i(qd,"closedTransportFacts");i(_e,"asRecord");i(Yd,"closedOutboxSummary");i(pr,"closedSampleLimit");i(je,"classifyArkRunInspectorStoreDurability");i(cn,"buildArkRunInspectorHardening");i(Be,"buildArkRunInspectorOutboxMonitor");i(Ue,"unavailableArkRunInspectorOutboxMonitor");i(Xd,"closedWorkflowSummary");i(Zd,"isPendingWorkflowStatus");i(We,"buildArkRunInspectorWorkflowsMonitor");i(Ve,"unavailableArkRunInspectorWorkflowsMonitor");i(Jd,"closedOutboxMonitor");i(Qd,"closedWorkflowsMonitor");i(fr,"buildArkRunInspectorSnapshot");i(dn,"formatArkRunInspectorSseEvent")});var ga={};va(ga,{listenArkRunInspector:()=>iu});function eu(){return{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}}function tu(){return{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-store",connection:"keep-alive","x-accel-buffering":"no"}}function nu(e){let t=e&&e.length>0?e:"/";return new URL(t,"http://127.0.0.1")}function Te(e,t,n){if(!(e.writableEnded||e.destroyed))try{e.writeHead(t,eu()),e.end(JSON.stringify(n))}catch{}}function ru(e,t){let n=e.address();if(n===null||typeof n=="string")throw new ce(t.host);if(!It(n.address))throw new ce(n.address);return{host:t.host,port:n.port}}async function ou(e){if(typeof e.listInspectorOutbox=="function")return e.listInspectorOutbox();let t=e.outbox??e.eventBuffer;if(!t||typeof t.list!="function")return Ue();let[n,r]=await Promise.all([t.list("pending"),t.list("failed")]);return Be([...n??[],...r??[]],{sampleLimit:se})}async function su(e){return typeof e.listInspectorWorkflows=="function"?e.listInspectorWorkflows():!e.workflowEngine||typeof e.workflowEngine.list!="function"?Ve():We(await e.workflowEngine.list(),{sampleLimit:se})}async function iu(e,t){let n=await import("http"),r=new Set,o=new Set,s=typeof t.sseIntervalMs=="number"&&Number.isFinite(t.sseIntervalMs)?Math.max(0,t.sseIntervalMs):1e3,a=t.bind,l=i(()=>e.getInspectorSnapshot(a),"snapshot"),c=n.createServer((p,f)=>{let y=nu(p.url),u=y.pathname;if(p.method==="GET"&&(u==="/"||u===nn)){Te(f,200,l());return}if(p.method==="GET"&&u===on){try{Te(f,200,e.requestGraph(ir({slice:y.searchParams.get("slice"),nodeIds:y.searchParams.get("nodeIds"),degreesOfSeparation:y.searchParams.get("degreesOfSeparation"),include:y.searchParams.get("include"),exclude:y.searchParams.get("exclude")})))}catch(g){if(g instanceof te){Te(f,400,{error:g.message,option:g.option});return}throw g}return}if(p.method==="GET"&&u===sn){ou(e).then(g=>Te(f,200,g)).catch(g=>{Te(f,500,{error:g instanceof Error?g.message:"outbox monitor failed"})});return}if(p.method==="GET"&&u===an){su(e).then(g=>Te(f,200,g)).catch(g=>{Te(f,500,{error:g instanceof Error?g.message:"workflows monitor failed"})});return}if(p.method==="GET"&&u===rn){f.writeHead(200,tu()),f.flushHeaders(),f.write(dn(l())),r.add(f);let g=s>0?setInterval(()=>{f.write(dn(l()))},s):void 0;g&&o.add(g);let d=i(()=>{r.delete(f),g&&(clearInterval(g),o.delete(g))},"drop");p.on("close",d),f.on("close",d);return}Te(f,404,{error:"not found"})});try{await new Promise((p,f)=>{let y=i(u=>f(u),"onError");c.once("error",y),c.listen({host:t.bind.host,port:t.bind.port},()=>{c.off("error",y);try{a=ru(c,t.bind),p()}catch(u){f(u instanceof Error?u:new ce(t.bind.host))}})})}catch(p){throw await new Promise(f=>{c.close(()=>f())}),p}return{host:a.host,port:a.port,url:be(a.host,a.port,"/"),snapshotUrl:be(a.host,a.port,nn),eventsUrl:be(a.host,a.port,rn),graphUrl:be(a.host,a.port,on),outboxUrl:be(a.host,a.port,sn),workflowsUrl:be(a.host,a.port,an),close(){for(let p of o)clearInterval(p);o.clear();for(let p of r)p.end();return r.clear(),new Promise((p,f)=>{c.close(y=>{y?f(y):p()})})}}}var ma=St(()=>{"use strict";lr();un();i(eu,"jsonHeaders");i(tu,"sseHeaders");i(nu,"requestUrl");i(Te,"writeJson");i(ru,"boundAddress");i(ou,"resolveOutboxMonitor");i(su,"resolveWorkflowsMonitor");i(iu,"listenArkRunInspector")});var mr="4.8.19";var Ea=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,Sa=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,wa=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function Ca(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),o=String(t?.toLayer??"");return Ea.test(n)?"pure-shared":r==="PersistenceAdapters"&&(Sa.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${o} ${n}`))?"kernel-emit":wa.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&o==="PersistenceAdapters"?"use-case":"unknown"}i(Ca,"classifyLayerImportKind");function xa(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=Ca(typeof e.target=="string"?e.target:"",{fromLayer:typeof e.fromLayer=="string"?e.fromLayer:void 0,toLayer:typeof e.toLayer=="string"?e.toLayer:void 0});return t==="pure-shared"?"Adopt the imported constants/types/pure module into DomainModel or SharedKernel (do not inject a port). Then preflight again.":t==="kernel-emit"?"Persistence must not emit. Inject a port or move the event map to SharedTypes; do not import kernel/events/bootstrap from a repository. Then preflight again.":t==="use-case"||e.portProofEligible?`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, test at the public interface, then preflight again.`:"Classify the import: if it is constants/types/pure, adopt into DomainModel or SharedKernel; define a port only if the target is a real use-case. Then preflight again."}i(xa,"layerImportNextAction");function Oa(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}i(Oa,"arkRunCallSiteName");function Pa(e){let t=Oa(e),n=typeof e.fromLayer=="string"&&e.fromLayer.length>0?e.fromLayer:void 0;switch(e.ruleId){case"ARKRUN_MISSING_ROOT":return t?`Import createStrictArkKernel from arkgate/runtime and call it in composition root ${t} listed in arkRun.compositionRoots, then preflight again.`:"Import createStrictArkKernel from arkgate/runtime (same npm package; @arkgate/runtime is deprecated) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKRUN_KERNEL_IN_DOMAIN":return t?`Move the kernel import of ${t} out of ${n??"the Domain-role layer"} into a composition root or adapter. Import from arkgate/runtime, then preflight again.`:"Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from arkgate/runtime (same npm package; @arkgate/runtime is deprecated), then preflight again. Never mechanical-safe.";case"ARKRUN_DIRECT_NEW":return t?`Resolve ${t} from the kernel instead of constructing it with new, then preflight again.`:"Resolve the type from the kernel instead of constructing it with new, then preflight again. Never mechanical-safe \u2014 rewiring construction is a design decision.";case"ARKRUN_UNDECLARED_EMIT":return t?`Add ${t} to raises or sends on the managed component, then preflight again.`:"Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment.";case"ARKRUN_UNDECLARED_HANDLE":return t?`Add ${t} to reactsTo on the managed component, then preflight again.`:"Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment.";case"ARKRUN_UNDECLARED_DEPEND":return t?`Add ${t} to uses on the managed component, then preflight again.`:"Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment.";case"ARKRUN_TRANSPORT_BYPASS":return t?`Send through the ArkRun kernel transport instead of importing ${t}, then preflight again.`:"Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe \u2014 homemade buses stay judgment.";default:return`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(Pa,"arkRunNextAction");function fe(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return xa(e);case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, test at the public interface, then preflight again.`;case"CAPABILITY_VIOLATION":return`Define a ${String(e.capability??"capability")} port in ${e.fromLayer??"the walled layer"}, bind the implementation outside it, test at the public interface, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, test at the public interface, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"LITERAL_PATH_DRIFT":return typeof e.target=="string"&&e.target.length>0?`Rewrite the literal to ${e.target}, or run \`arkgate-check --path-drift --base-ref <ref> --write\` to apply every anchored replacement.`:"Rewrite the literal to the rename destination, or run `arkgate-check --path-drift --base-ref <ref> --write` to apply every anchored replacement.";case"LITERAL_PATH_UNRESOLVED":return"Read the candidate and decide: fix the path, or leave it. Advisory \u2014 with no rename to anchor it there is no destination to propose, so --write never touches it.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";case"INVARIANT_COVERAGE_OUTSIDE_ROOTS":return"Move the covering test under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json, then run Ark again.";case"INVARIANT_CATALOG_EMPTY":return typeof e.file=="string"&&e.file.length>0?`Add 1\u20132 short phrases to invariants[] in ${e.file}, then run ark-check --doctor. Starters show the shape.`:"Add 1\u20132 short phrases to invariants[] in arkrules/<Domain>.json, then run ark-check --doctor. Starters show the shape.";case"INVARIANT_TESTS_PATH_MISSING":return"Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present.";case"INVARIANT_COVERAGE_ROOTS_MISSING":return"Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. An enforced invariant fails closed until that path is present.";case"ARKRULE_STRUCTURE":case"ARKRULE_INVARIANT":case"INVARIANT_UNCOVERED":return`Fix the structure or invariant for ${typeof e.arkruleId=="string"&&e.arkruleId.length>0?e.arkruleId:"the ArkRule"} (declared in ${typeof e.arkruleSource=="string"&&e.arkruleSource.length>0?e.arkruleSource:"arkrules/<Layer>.json"}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`;case"ARKRUN_MISSING_ROOT":case"ARKRUN_KERNEL_IN_DOMAIN":case"ARKRUN_DIRECT_NEW":case"ARKRUN_UNDECLARED_EMIT":case"ARKRUN_UNDECLARED_HANDLE":case"ARKRUN_UNDECLARED_DEPEND":case"ARKRUN_TRANSPORT_BYPASS":return Pa(e);case"ARKORDER_MISSING_PLANE":return typeof e.target=="string"&&e.target.length>0?`Import createOrderPlane from arkgate/order and call it in plane root ${e.target} listed in arkOrder.planeRoots, then preflight again.`:"Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKORDER_KERNEL_IN_DOMAIN":return"Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe.";case"ARKORDER_GENERIC_UPDATE":return"Don't use a generic update. First freeze with release(). Later, propose the change, then apply it.";case"ARKORDER_TOO_MANY_PARAMS":return"Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe.";case"ARKORDER_INGEST_WRITES_XI":return"Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe.";case"ARKORDER_XI_FIELD_WRITE":return typeof e.target=="string"&&e.target.length>0?`Don't write ${e.target} from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.`:"Don't write a named product choice from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.";case"ARKORDER_UNVALVED_RELEASE":return"Change the choice with proposeRelease then apply. release() is only the first freeze. Never mechanical-safe.";default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(fe,"deterministicNextAction");var gn="1.5",yr="docs/diagnostics.md",Mo={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","mode","valid","completeness","completenessReasons","diagnostics"],allOf:[{if:{properties:{completeness:{enum:["partial","unavailable"]}},required:["completeness"]},then:{properties:{valid:{const:!1}}}},{if:{properties:{mode:{const:"resolved-candidate-facts"},completeness:{enum:["complete","partial"]}},required:["mode","completeness"]},then:{required:["policyHash","resolverIdentity","factsHash","candidateTreeHash"]}},{if:{properties:{completeness:{const:"complete"}},required:["completeness"]},then:{properties:{completenessReasons:{maxItems:0}}},else:{properties:{completenessReasons:{minItems:1}}}}],properties:{schemaVersion:{const:"1.5"},mode:{enum:["lexical-compatibility","resolved-candidate-facts"]},valid:{type:"boolean"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:{type:"string",minLength:1},message:{type:"string",minLength:1},file:{type:"string",minLength:1}}}},policyHash:{type:"string",minLength:1},resolverIdentity:{type:"string",minLength:1},factsHash:{type:"string",minLength:1},candidateTreeHash:{type:"string",minLength:1},diagnostics:{type:"array",items:{type:"object",additionalProperties:!1,required:["ruleId","severity","message","location","evidence"],properties:{ruleId:{type:"string",minLength:1},severity:{enum:["error","warning"]},message:{type:"string",minLength:1},location:{type:"object",additionalProperties:!1,required:["file","line","column"],properties:{file:{type:"string",minLength:1},line:{type:"integer",minimum:1},column:{type:"integer",minimum:1}}},evidence:{type:"object",additionalProperties:!1,properties:{target:{type:"string"},fromLayer:{type:"string"},toLayer:{type:"string"},typeOnly:{type:"boolean"},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"},peerIsolation:{type:"boolean"},capability:{type:"string",minLength:1},edgeKind:{type:"string",minLength:1},arkruleId:{type:"string",minLength:1},arkruleSource:{type:"string",minLength:1}}},nextAction:{type:"string",minLength:1},findingRef:{type:"string",minLength:1,pattern:"^fnv1a-[0-9a-f]{8}$"},targetKey:{type:"string",minLength:1},docsCodePath:{type:"string",minLength:1}}}}}};function mn(e){let t=typeof e.ruleId=="string"?e.ruleId:typeof e.code=="string"?e.code:void 0,n=typeof e.file=="string"?e.file:void 0,r=typeof e.fromLayer=="string"?e.fromLayer:void 0,o=typeof e.toLayer=="string"?e.toLayer:void 0,s=typeof e.target=="string"?e.target:void 0;return[t,n,r??"",o??"",s??""].join("|")}i(mn,"adapterFindingTargetKey");function yn(e){let t=new Map;return e.map(n=>{let r=mn(n),o=(t.get(r)??0)+1;return t.set(r,o),o===1?r:`${r}#${o}`})}i(yn,"adapterFindingOccurrenceTargetKeys");function hr(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}i(hr,"adapterFindingRefFromTargetKey");function Rr(e){return`${yr}#${e}`}i(Rr,"adapterDocsCodePath");function O(e){return typeof e=="string"&&e.length>0?e:void 0}i(O,"text");function $o(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}i($o,"positiveInteger");function _a(e,t,n){return fe({ruleId:e,target:O(t.target)??O(n.target)??void 0,fromLayer:O(t.fromLayer)??void 0,toLayer:O(t.toLayer)??void 0,typeOnly:t.typeOnly===!0,targetTypeOnlyExports:t.targetTypeOnlyExports===!0,namedBindingsTypeOnly:t.namedBindingsTypeOnly===!0,portProofEligible:t.portProofEligible===!0,peerIsolation:t.peerIsolation===!0,sourcePureTypeModule:t.sourcePureTypeModule===!0,edgeKind:O(t.edgeKind)??void 0,capability:O(t.capability)??O(n.capability)??void 0,arkruleId:O(t.arkruleId)??void 0,arkruleSource:O(t.arkruleSource)??void 0})}i(_a,"nextActionForDiagnostic");function Ar(e,t="error",n){let r=O(e.ruleId)??O(e.code)??"ARK_UNKNOWN",o=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,s={...O(e.target)?{target:O(e.target)}:{},...O(e.fromLayer)?{fromLayer:O(e.fromLayer)}:{},...O(e.toLayer)?{toLayer:O(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{},...typeof e.targetTypeOnlyExports=="boolean"?{targetTypeOnlyExports:e.targetTypeOnlyExports}:{},...typeof e.sourcePureTypeModule=="boolean"?{sourcePureTypeModule:e.sourcePureTypeModule}:{},...typeof e.namedBindingsTypeOnly=="boolean"?{namedBindingsTypeOnly:e.namedBindingsTypeOnly}:{},...typeof e.portProofEligible=="boolean"?{portProofEligible:e.portProofEligible}:{},...typeof e.peerIsolation=="boolean"?{peerIsolation:e.peerIsolation}:{},...O(e.capability)?{capability:O(e.capability)}:{},...O(e.edgeKind)?{edgeKind:O(e.edgeKind)}:{},...O(e.arkruleId)?{arkruleId:O(e.arkruleId)}:{},...O(e.arkruleSource)?{arkruleSource:O(e.arkruleSource)}:{}},a=n??mn(e),l=hr(a);return{ruleId:r,severity:o,message:O(e.message)??r,location:{file:O(e.file)??"<unknown>",line:$o(e.line,1),column:$o(e.column,1)},evidence:s,nextAction:O(e.nextAction)??_a(r,s,e),findingRef:l,targetKey:a,docsCodePath:Rr(r)}}i(Ar,"toAdapterDiagnostic");function Ta(e){let t=e.completeness??"complete",n=e.mode??"lexical-compatibility";if(t==="complete"&&(e.completenessReasons?.length??0)>0)throw new Error("completenessReasons must be empty when completeness is complete.");let r=t==="complete"?[]:e.completenessReasons&&e.completenessReasons.length>0?e.completenessReasons.map(y=>({code:O(y.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:O(y.message)??`Analysis ${t}: required evidence is incomplete.`,...O(y.file)?{file:O(y.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],o={...O(e.policyHash)?{policyHash:O(e.policyHash)}:{},...O(e.resolverIdentity)?{resolverIdentity:O(e.resolverIdentity)}:{},...O(e.factsHash)?{factsHash:O(e.factsHash)}:{},...O(e.candidateTreeHash)?{candidateTreeHash:O(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let y of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!o[y])throw new Error(`${y} is required for resolved ${t} adapter evidence.`)}let s=e.violations??[],a=e.warnings??[],l=yn(s),c=yn(a),p=[...s.map((y,u)=>Ar(y,"error",l[u])),...a.map((y,u)=>Ar(y,"warning",c[u]))],f={schemaVersion:"1.5",completenessReasons:r,diagnostics:p};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...f,mode:n,valid:!1,completeness:t,...o};let y={policyHash:o.policyHash,resolverIdentity:o.resolverIdentity,factsHash:o.factsHash,candidateTreeHash:o.candidateTreeHash};return t==="complete"?{...f,mode:n,valid:e.valid,completeness:t,...y}:{...f,mode:n,valid:!1,completeness:t,...y}}return t==="complete"?{...f,mode:n,valid:e.valid,completeness:t,...o}:{...f,mode:n,valid:!1,completeness:t,...o}}i(Ta,"createAdapterResult");var qe=class{static{i(this,"IntentRegistry")}intents=new Map;dependencies=new Map;productions=new Map;define(t,n){if(this.intents.has(t))throw new Error(`Intent "${t}" is already registered. Intent names must be unique within a registry.`);let r=i(s=>({intent:t,payload:s,metadata:{occurredAt:new Date().toISOString(),source:"unknown"}}),"fn");Object.defineProperty(r,"name",{value:t,enumerable:!0,configurable:!1,writable:!1});let o=r;if(this.intents.set(t,o),n?.dependsOn)for(let s of n.dependsOn)this.declareDependency(t,s);if(n?.produces)for(let s of n.produces)this.declareProduction(t,s);return o}declareDependency(t,n){this.dependencies.has(t)||this.dependencies.set(t,new Set),this.dependencies.get(t).add(n)}declareProduction(t,n){this.productions.has(t)||this.productions.set(t,new Set),this.productions.get(t).add(n)}get(t){return this.intents.get(t)}list(){return Array.from(this.intents.values())}getDependencies(t){let n=this.dependencies.get(t);return n?Array.from(n):[]}getProductions(t){let n=this.productions.get(t);return n?Array.from(n):[]}getAllRelationships(){let t=[];for(let[n,r]of this.dependencies.entries())for(let o of r)t.push({from:n,to:o,kind:"dependsOn"});for(let[n,r]of this.productions.entries())for(let o of r)t.push({from:n,to:o,kind:"produces"});return t}has(t){return this.intents.has(t)}clear(){this.intents.clear(),this.dependencies.clear(),this.productions.clear()}};var Ko=new qe;function Ho(e,t){return Ko.define(e,t)}i(Ho,"defineIntent");function hn(){return new qe}i(hn,"createIntentRegistry");var Go=Ko;var Uo=["Domain.","Application.","Adapter.","Workflow.","Job.","Presentation.","Reporting.","Metadata.","Security.","Audit.","Observability.","Kernel."];function Rn(e){if(!e||typeof e!="string")return{valid:!1,reason:"Intent name must be a non-empty string"};if(!Uo.some(n=>e.startsWith(n)))return{valid:!1,reason:`Intent "${e}" must start with one of: ${Uo.join(", ")}`};let t=e.slice(e.indexOf(".")+1);return!t||!/^[A-Za-z][A-Za-z0-9_.]*$/.test(t)?{valid:!1,reason:`Intent "${e}" has an invalid segment after the layer prefix`}:{valid:!0}}i(Rn,"validateIntentName");var Se=class extends Error{static{i(this,"PolicyViolationError")}violations;constructor(t){let n=t.map(r=>`- ${r.policyName}: ${r.message}`).join(`
6
6
  `);super(`Hard policy violation(s) detected:
7
7
  ${n}`),this.name="PolicyViolationError",this.violations=t}};var De=class{static{i(this,"PolicyEngine")}policies=[];constructor(t=[]){for(let n of t)this.add(n)}add(t){if(this.policies.some(n=>n.name===t.name))throw new Error(`Policy "${t.name}" is already registered in this engine.`);this.policies.push(t)}getPolicies(){return[...this.policies]}evaluate(t){let n=[];for(let s of this.policies){let a=s.check(t);if(a!==!0){if(a===!1){n.push({policyName:s.name,severity:s.severity,message:`Policy "${s.name}" was violated.`});continue}if(Array.isArray(a))for(let l of a)n.push({policyName:s.name,severity:s.severity,message:l.message,details:l.details});else n.push({policyName:s.name,severity:s.severity,message:a.message,details:a.details})}}let r=n.filter(s=>s.severity==="hard"),o=n.filter(s=>s.severity==="soft");return{passed:n.length===0,violations:n,hardViolations:r,softViolations:o}}enforce(t){let n=this.evaluate(t);if(n.hardViolations.length>0)throw new Se(n.hardViolations);return n}clear(){this.policies.length=0}};function Ye(e){let t=e.severity??"soft";return{name:e.name,severity:t,tags:e.tags,owner:e.owner,version:e.version,rationale:e.rationale,enforcementMode:e.enforcementMode,deprecated:e.deprecated,replacedBy:e.replacedBy,check:e.check}}i(Ye,"definePolicy");function Na(e){let t=e.indexOf(".");return t>=0?e.slice(0,t):e}i(Na,"defaultLayerOf");function Vo(e,t){return t.resolveLayer?.(e)??Na(e)}i(Vo,"resolveLayer");function Da(e,t,n){return e===n.from&&t===n.to}i(Da,"matchesRule");function An(e){let t=e.name??"Layer isolation",n=e.severity??"hard";return Ye({name:t,severity:n,tags:["layer"],check:i(r=>{let o=[...(r.edges??[]).filter(a=>a.kind==="declared"||a.kind==="produces").map(a=>({from:a.from,to:a.to})),...(r.relationships??[]).filter(a=>a.kind==="dependsOn").map(a=>({from:a.from,to:a.to}))],s=[];for(let a of o){let l=Vo(a.from,e),c=Vo(a.to,e);for(let p of e.rules)!p.allowed&&Da(l,c,p)&&s.push({policyName:t,severity:n,message:p.message??`Layer violation: ${a.from} (${l}) must not relate to ${a.to} (${c})`})}return s.length>0?s:!0},"check")})}i(An,"defineLayerPolicy");function kn(e){return e.tags?.includes("layer")??!1}i(kn,"isLayerPolicy");var kr={layerIsolation(){return kr.cleanArchitectureMatrix()},cleanArchitectureMatrix(){return An({name:"Clean architecture matrix",severity:"hard",rules:[{from:"Domain",to:"Adapter",allowed:!1},{from:"Domain",to:"Application",allowed:!1},{from:"Adapter",to:"Application",allowed:!1},{from:"Adapter",to:"Domain",allowed:!1}]})}};function In(e,t={}){return An({name:t.name??`${e.name} layer policy`,severity:t.severity??"hard",rules:e.rules,resolveLayer:e.resolveLayer})}i(In,"defineArchitectureProfilePolicy");function bn(e){return t=>({event:t,relationships:e.intentRegistry?.getAllRelationships(),edges:e.dependencyGraph?.getEdges()})}i(bn,"buildPublishPolicyContext");function jo(e){return Ye(e)}i(jo,"definePublishPolicy");var Xe=class extends Error{static{i(this,"UnregisteredIntentError")}intentName;constructor(t){super(`Intent "${t}" is not registered. Register it with IntentRegistry.define() before publish/subscribe, including metadata.source producer intents in strict mode.`),this.name="UnregisteredIntentError",this.intentName=t}},Ze=class extends Error{static{i(this,"InvalidIntentNameError")}intentName;reason;constructor(t,n){super(`Invalid intent name "${t}": ${n}`),this.name="InvalidIntentNameError",this.intentName=t,this.reason=n}},Je=class extends Error{static{i(this,"LayerPolicyContextError")}constructor(){super("Layer/architecture policies require intentRegistry, dependencyGraph, or a custom getPolicyContext. Without graph/registry context, layer policies cannot inspect relationships."),this.name="LayerPolicyContextError"}},Qe=class extends Error{static{i(this,"EventContractViolationError")}intentName;issues;constructor(t,n){super(`Event contract violation for "${t}". Register a matching event contract/version or fix the payload before publishing.`),this.name="EventContractViolationError",this.intentName=t,this.issues=n}},Le=class extends Error{static{i(this,"UnknownEventSourceError")}intentName;source;constructor(t,n){super(n?`Event "${t}" metadata.source "${n}" is not registered. Register the producer intent or publish from a known source.`:`Event "${t}" must include metadata.source. Strict Ark uses source to enforce observed layer flow.`),this.name="UnknownEventSourceError",this.intentName=t,this.source=n}},we=class extends Error{static{i(this,"SourceMetadataOverrideError")}boundSource;attemptedSource;constructor(t,n){super(`Source-bound publisher for "${t}" cannot publish with metadata.source "${n}". Create a publisher for the intended source instead.`),this.name="SourceMetadataOverrideError",this.boundSource=t,this.attemptedSource=n}},et=class extends Error{static{i(this,"ObservedLayerFlowViolationError")}source;intentName;fromLayer;toLayer;constructor(t,n,r,o,s){super(s??`Observed layer violation: "${t}" (${r}) must not produce "${n}" (${o}). Route this through an allowed layer or adjust the architecture profile rule.`),this.name="ObservedLayerFlowViolationError",this.source=t,this.intentName=n,this.fromLayer=r,this.toLayer=o}};function wt(e,t){if(!(!t.strictRegistry&&!t.validateIntentNaming)){if(t.validateIntentNaming){let n=Rn(e);if(!n.valid)throw new Ze(e,n.reason)}if(t.strictRegistry&&t.intentRegistry&&!t.intentRegistry.has(e))throw new Xe(e)}}i(wt,"assertIntentAllowed");function Bo(e,t){if(t.requireKnownSource){if(!e.metadata.source||e.metadata.source==="unknown")throw new Le(e.intent);if(t.intentRegistry&&!t.intentRegistry.has(e.metadata.source))throw new Le(e.intent,e.metadata.source)}}i(Bo,"assertSourceAllowed");function Ct(e,t){if(!t.eventContracts)return;let n=t.eventContracts.validate(e);if(!n.ok&&(t.strictEventContracts||n.contract))throw new Qe(e.intent,n.issues)}i(Ct,"assertContractAllowed");function tt(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}i(tt,"isPlainRecord");function nt(e){return Array.isArray(e)?e.map(nt):tt(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,nt(n)])):e}i(nt,"clonePatchValue");function Ir(e,t,n="payload"){let r={...e};for(let[o,s]of Object.entries(t)){let a=`${n}.${o}`;if(!(o in r)||r[o]===void 0){r[o]=nt(s);continue}if(tt(r[o])&&tt(s)){r[o]=Ir(r[o],s,a);continue}if(Array.isArray(r[o])&&Array.isArray(s)){r[o]=br(r[o],s,a);continue}throw new Error(`Interceptor patch cannot overwrite existing ${a}.`)}return r}i(Ir,"mergeRecordPatch");function br(e,t,n="payload"){let r=[...e];return t.forEach((o,s)=>{let a=`${n}[${s}]`;if(s>=r.length||r[s]===void 0){r[s]=nt(o);return}if(tt(r[s])&&tt(o)){r[s]=Ir(r[s],o,a);return}if(Array.isArray(r[s])&&Array.isArray(o)){r[s]=br(r[s],o,a);return}throw new Error(`Interceptor patch cannot overwrite existing ${a}.`)}),r}i(br,"mergeArrayPatch");function Wo(e,t){if(Array.isArray(t)){if(e===void 0)return nt(t);if(!Array.isArray(e))throw new Error("Array interceptor patch requires an array payload.");return br(e,t)}if(e===void 0)return nt(t);if(!tt(e))throw new Error("Object interceptor patch requires an object payload.");return Ir(e,t)}i(Wo,"applyPayloadPatch");async function zo(e,t){if(e.metadata.allowInterception===!1)return e;let n=[...t.interceptorsForIntent(e.intent)],r=e;for(let o of n){let s=[];try{if(await Promise.resolve(o.interceptor({event:r,intercept:i(c=>{s.push(c)},"intercept")})),s.length===0)continue;let a=new Date().toISOString(),l={...r,metadata:{...r.metadata,interceptions:[...r.metadata.interceptions??[],{interceptorId:o.interceptorId,timestamp:a}]}};for(let c of s)l={...l,payload:Wo(l.payload,c),metadata:{...l.metadata}};Ct(l,{eventContracts:t.eventContracts,strictEventContracts:t.strictEventContracts}),r=l,o.lastInterceptedAt=a,t.appendTrace({type:"event.intercepted",timestamp:a,intent:r.intent,correlationId:r.metadata.correlationId,traceId:r.metadata.traceId,spanId:r.metadata.spanId,details:{registrationId:o.registrationId,interceptorId:o.interceptorId,patchesApplied:s.length}}),await t.recordAudit("event.intercepted",r,{registrationId:o.registrationId,interceptorId:o.interceptorId,patchesApplied:s.length})}catch(a){await La(o,r,a,t)}}return r}i(zo,"applyInterceptors");async function La(e,t,n,r){let o=n instanceof Error?n.message:String(n);r.appendTrace({type:"interceptor.error",timestamp:new Date().toISOString(),intent:t.intent,correlationId:t.metadata.correlationId,traceId:t.metadata.traceId,spanId:t.metadata.spanId,details:{registrationId:e.registrationId,interceptorId:e.interceptorId,error:o}}),await r.recordAudit("interceptor.error",t,{registrationId:e.registrationId,interceptorId:e.interceptorId,error:o})}i(La,"recordInterceptorError");var qo=new Map;function Yo(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(Yo,"escapeLiteral");function vn(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let o=e[n+1];if("*?{}[],".includes(o)||o==="\\"){t+="\\"+o,n+=1;continue}t+="/";continue}t+=r}return t}i(vn,"normalizeGlobSeparators");function Fa(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="{")t+=1;else if(r==="}"&&(t-=1,t<0))return!1}return t===0}i(Fa,"bracesBalanced");function ye(e){let t=qo.get(e);if(t)return t;let n=vn(e),r=Fa(n),o="",s=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(o+=Yo(n[l+1]),l+=1):c==="*"?n[l+1]==="*"?n[l+2]==="/"?(o+="(?:.*/)?",l+=2):(o+=".*",l+=1):o+="[^/]*":c==="?"?o+="[^/]":c==="{"&&r?(o+="(?:",s+=1):c==="}"&&r&&s>0?(o+=")",s-=1):c===","&&r&&s>0?o+="|":o+=Yo(c)}let a=new RegExp(`^${o}$`);return qo.set(e,a),a}i(ye,"globToRegExp");function Ma(e){return vn(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}i(Ma,"concreteGlobSegments");function vr(e,t){let n=vn(String(e)),r=Ma(n),o=n.replace(/\*/g,"").length,s=r.length*1e4+o;if(t==null||t==="")return s;let a=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return o;let l=0,c=-1;for(let p of r){let f=-1;for(let y=l;y<a.length;y+=1)if(a[y]===p){f=y;break}if(f<0)return s;c=f,l=f+1}return(c+1)*1e6+r.length*1e4+o}i(vr,"patternSpecificity");function de(e,t){let n=String(e).split(/[/\\]/).join("/"),r,o=-1;for(let s of t??[])if(!(s.exclude??[]).some(a=>ye(a).test(n))){for(let a of s.patterns??[])if(ye(a).test(n)){let l=vr(a,n);l>o&&(o=l,r=s.name)}}return r}i(de,"layerForRelativePath");function Xo(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),r=new Set(t.map(o=>String(o).toLowerCase()));for(let o=0;o<n.length-1;o+=1)if(r.has(n[o].toLowerCase()))return`${n[o].toLowerCase()}/${n[o+1].toLowerCase()}`}i(Xo,"sliceIdForPath");function $a(e){let t=new Set;for(let n of e??[]){let o=vn(String(n)).split("/").filter(Boolean);for(let s=0;s<o.length;s+=1){let a=o[s];if((a==="**"||a==="*")&&s>0){let l=o[s-1];l&&!l.includes("*")&&!l.includes("{")&&!l.includes("}")&&t.add(l)}}}return[...t]}i($a,"inferSliceFoldersFromPatterns");function Ka(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(o=>typeof o=="string"&&o.length>0);let r=(n??[]).find(o=>o.name===t);return $a(r?.patterns)}i(Ka,"resolveSliceFolders");function Zo(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}i(Zo,"normalizeSegments");function es(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}i(es,"trimTrailingSlashes");var Ha=["src","app"];function Ga(e){let t=es(e.replace(/^[./]+/,""));return t==="*"||t==="**"}i(Ga,"isBlanketRoot");function Jo(e,t){if(!e||!t?.length)return!1;let n=String(e).split(/[/\\]/).join("/"),r=n.toLowerCase(),o=Zo(n);for(let s of t){if(typeof s!="string"||s.length===0||Ga(s))continue;if(s.includes("*")){let c=es(s.toLowerCase());if(ye(c).test(r)||ye(`${c}/**`).test(r))return!0;continue}let a=Zo(s);if(a.length===0)continue;let l=Ha.includes(o[0])&&a[0]!==o[0]?[0,1]:[0];for(let c of l){if(c+a.length>o.length)continue;let p=!0;for(let f=0;f<a.length;f+=1)if(o[c+f]!==a[f]){p=!1;break}if(p)return!0}}return!1}i(Jo,"pathUnderSharedRoot");function Qo(e,t){let n=String(e).split(/[/\\]/).filter(Boolean).join("/").toLowerCase();if(!n)return!1;let r=t.toLowerCase();return n===r?!0:!n.includes("/")&&r.endsWith(`/${n}`)}i(Qo,"sliceMatchesDeclaration");function Ua(e,t,n){return!e?.length||!t||!n?!1:e.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&Qo(r.from,t)&&Qo(r.to,n))}i(Ua,"crossSliceEdgeAllowed");function Va(e){if(!e.fromPath)return{denied:!0,reason:"missing-path"};if(e.folderCount<=0)return{denied:!0,reason:"no-slice-folders"};let t=!!e.fromSlice||e.fromShared===!0;if(!e.toPath)return t?e.fromSlice?{denied:!0,reason:"missing-path"}:{denied:!1}:{denied:!0,reason:"unclassifiable-path"};let n=!!e.toSlice||e.toShared===!0;return!t||!n?{denied:!0,reason:"unclassifiable-path"}:!e.fromSlice||!e.toSlice?{denied:!1}:e.fromSlice===e.toSlice?{denied:!1}:e.crossSliceAllowed?{denied:!1}:{denied:!0,reason:"cross-slice"}}i(Va,"peerIsolationDecision");function rt(e,t){switch(e){case"cross-slice":return`cross-slice edge ${t.fromSlice??"?"} \u2192 ${t.toSlice??"?"}. Extract the shared code, use events/ports across slices, or declare the edge in the rule's allowedCrossSlice.`;case"unclassifiable-path":{let n=[t.fromSlice?void 0:t.fromPath,t.toSlice?void 0:t.toPath].filter(o=>!!o);return`unclassifiable path${n.length>0?` (${n.join(", ")})`:""} \u2014 ArkGate cannot place it in a slice, so it cannot prove this is not a cross-slice edge. Move it into a slice, or declare its root in the rule's sharedRoots.`}case"no-slice-folders":return"no slice folders \u2014 peerIsolation is on but no slice folder resolves from the rule or the layer patterns. Set sliceFolders on the rule.";default:return"no path evidence for this edge \u2014 peerIsolation needs the importer and importee paths."}}i(rt,"peerIsolationDenyExplanation");function ot(e,t,n,r){return Fe(e,t,n,r)?.rule}i(ot,"findDeniedEdgeRule");function Fe(e,t,n,r){for(let o of e??[])if(!(o.from!==t||o.to!==n)&&o.allowed===!1){if(o.peerIsolation){let s=r?.fromPath,a=r?.toPath,l=Ka(o,t,r?.layers),c=s?Xo(s,l):void 0,p=a?Xo(a,l):void 0,f=Va({fromPath:s,toPath:a,folderCount:l.length,fromSlice:c,toSlice:p,fromShared:!c&&Jo(s,o.sharedRoots),toShared:!p&&Jo(a,o.sharedRoots),crossSliceAllowed:Ua(o.allowedCrossSlice,c,p)});if(f.denied)return{rule:o,peerIsolationReason:f.reason,fromSlice:c,toSlice:p};continue}if(t!==n)return{rule:o}}}i(Fe,"findDeniedEdgeDecision");async function ts(e,t){if(t.mode==="off"||!t.architectureProfile)return;let n=e.metadata.source;if(!n||n==="unknown")return;let r=t.architectureProfile,o=r.resolveLayer(n),s=r.resolveLayer(e.intent);if(!o||!s)return;let a=ot(r.rules,o,s);if(!a)return;let l=t.mode,c=a.message??`Observed layer violation: "${n}" (${o}) must not produce "${e.intent}" (${s}).`,p={source:n,intent:e.intent,fromLayer:o,toLayer:s,severity:l,message:c,rule:a};if(t.appendTrace({type:"layer.observedViolation",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:p}),await t.recordAudit("layer.observedViolation",e,p),l==="hard")throw new et(n,e.intent,o,s,c)}i(ts,"assertObservedLayerFlowAllowed");async function ns(e,t){let n=t.getPolicyContext(e),r;try{r=t.policyEngine.enforce(n)}catch(o){throw o instanceof Se&&(t.appendTrace({type:"policy.hardViolation",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:{violations:o.violations}}),await t.recordAudit("policy.hardViolation",e,{violations:o.violations})),o}r.softViolations.length>0&&(t.appendTrace({type:"policy.softViolation",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:{violations:r.softViolations}}),await t.recordAudit("policy.softViolation",e,{violations:r.softViolations}),t.onSoftViolation&&await t.safeHook(()=>t.onSoftViolation(r,e),"onSoftViolation",e))}i(ns,"enforcePublishPolicy");function ja(e,t){e.history.push(t),e.maxHistorySize!==void 0&&e.history.length>e.maxHistorySize&&e.history.splice(0,e.history.length-e.maxHistorySize)}i(ja,"appendHistory");function xt(e,t){e.trace.push(t),e.maxHistorySize!==void 0&&e.trace.length>e.maxHistorySize&&e.trace.splice(0,e.trace.length-e.maxHistorySize);for(let n of e.traceSinks)try{n(t)}catch{}}i(xt,"appendTrace");async function En(e,t,n,r){if(e.auditTrail)try{await e.auditTrail.record({type:t,source:n.metadata.source,intent:n.intent,correlationId:n.metadata.correlationId,causationId:n.metadata.causationId,subject:n.intent,details:r})}catch(o){xt(e,{type:"hook.error",timestamp:new Date().toISOString(),intent:n.intent,correlationId:n.metadata.correlationId,traceId:n.metadata.traceId,spanId:n.metadata.spanId,details:{hook:"auditTrail",error:o instanceof Error?o.message:String(o)}})}}i(En,"recordAudit");async function rs(e,t){let n={intent:t.intent,source:t.metadata.source,suggestion:"Publish through a registered intent creator so strict registry, contracts, and agent tooling share one source of truth."};xt(e,{type:"event.rawPublish",timestamp:new Date().toISOString(),intent:t.intent,correlationId:t.metadata.correlationId,traceId:t.metadata.traceId,spanId:t.metadata.spanId,details:n}),await En(e,"event.rawPublish",t,n)}i(rs,"recordRawPublishDiagnostic");async function os(e,t,n,r){let o={event:t,publishedAt:new Date().toISOString(),subscribersNotified:n};return ja(e,o),await e.eventBuffer?.enqueue(t,r),xt(e,{type:"event.published",timestamp:o.publishedAt,intent:t.intent,correlationId:t.metadata.correlationId,traceId:t.metadata.traceId,spanId:t.metadata.spanId,details:{subscribersNotified:n}}),await En(e,"event.published",t,{subscribersNotified:n}),o}i(os,"recordSuccessfulPublish");function Er(e,t,n){return{...e,...t,occurredAt:t.occurredAt||e.occurredAt||new Date().toISOString(),source:t.source||e.source||"unknown",kernelInstanceId:t.kernelInstanceId??e.kernelInstanceId??n,eventVersion:t.eventVersion??e.eventVersion,schemaVersion:t.schemaVersion??e.schemaVersion,allowInterception:t.allowInterception??e.allowInterception,interceptions:t.interceptions??e.interceptions,correlationId:t.correlationId??e.correlationId,causationId:t.causationId??e.causationId,traceId:t.traceId??e.traceId,spanId:t.spanId??e.spanId,parentSpanId:t.parentSpanId??e.parentSpanId}}i(Er,"enrichMetadata");var ss=0;function Ba(){return ss+=1,`interceptor-${Date.now()}-${ss}`}i(Ba,"nextInterceptorRegistrationId");var st=class{static{i(this,"EventBusImpl")}subscriptions=[];subscriptionsByIntent=new Map;interceptors=[];interceptorsByIntent=new Map;recording;onPublish;onSoftViolation;onHandlerError;eventContracts;strictEventContracts;requireKnownSource;architectureProfile;enforceObservedLayerFlowMode;rethrowHandlerErrors;policyEngine;getPolicyContext;intentRegistry;dependencyGraph;strictRegistry;validateIntentNaming;constructor(t={}){if(this.onPublish=t.onPublish,this.onSoftViolation=t.onSoftViolation,this.onHandlerError=t.onHandlerError,this.eventContracts=t.eventContracts,this.strictEventContracts=t.strictEventContracts??!1,this.requireKnownSource=t.requireKnownSource??!1,this.architectureProfile=t.architectureProfile,this.enforceObservedLayerFlowMode=t.enforceObservedLayerFlow??"off",this.rethrowHandlerErrors=t.rethrowHandlerErrors??!1,this.intentRegistry=t.intentRegistry,this.dependencyGraph=t.dependencyGraph,this.strictRegistry=t.strictRegistry??t.intentRegistry!==void 0,this.validateIntentNaming=t.validateIntentNaming??this.strictRegistry,this.recording={history:[],trace:[],maxHistorySize:t.maxHistorySize,traceSinks:[...t.traceSinks??[]],auditTrail:t.auditTrail,eventBuffer:t.eventBuffer??t.outbox,instanceId:t.instanceId},t.policyEngine?this.policyEngine=t.policyEngine:t.policies&&t.policies.length>0&&(this.policyEngine=new De(t.policies)),(this.policyEngine?.getPolicies()??t.policies??[]).some(kn)&&!t.intentRegistry&&!t.dependencyGraph&&!t.getPolicyContext)throw new Je;t.getPolicyContext?this.getPolicyContext=t.getPolicyContext:t.intentRegistry||t.dependencyGraph?this.getPolicyContext=bn({intentRegistry:t.intentRegistry,dependencyGraph:t.dependencyGraph}):this.getPolicyContext=r=>({event:r})}async publish(t,n,r,o){await this.dispatch(t,n,r,o)}async dispatch(t,n,r,o={}){let s=o.notifySubscribers!==!1,a=o.awaitHandlers!==!1,l=o.runOnPublish!==!1,c,p=typeof t!="function";if(p){let u=t,g=r??n??{};c={...u,metadata:Er(u.metadata,g,this.recording.instanceId)}}else{let u=t,g=n,d=r??{},m=u(g);c={...m,metadata:Er(m.metadata,d,this.recording.instanceId)}}p&&this.strictRegistry&&await rs(this.recording,c),wt(c.intent,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),Bo(c,{requireKnownSource:this.requireKnownSource,intentRegistry:this.intentRegistry}),Ct(c,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),c=await zo(c,{interceptorsForIntent:i(u=>this.interceptorsByIntent.get(u)??[],"interceptorsForIntent"),eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts,appendTrace:i(u=>this.appendTrace(u),"appendTrace"),recordAudit:i((u,g,d)=>this.recordAudit(u,g,d),"recordAudit")}),Ct(c,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),await ts(c,{mode:this.enforceObservedLayerFlowMode,architectureProfile:this.architectureProfile,appendTrace:i(u=>this.appendTrace(u),"appendTrace"),recordAudit:i((u,g,d)=>this.recordAudit(u,g,d),"recordAudit")}),this.dependencyGraph?.registerEventFlow(c.metadata.source,c.intent);let f=[...this.subscriptionsByIntent.get(c.intent)??[]];this.policyEngine&&await ns(c,{policyEngine:this.policyEngine,getPolicyContext:this.getPolicyContext,appendTrace:i(u=>this.appendTrace(u),"appendTrace"),recordAudit:i((u,g,d)=>this.recordAudit(u,g,d),"recordAudit"),onSoftViolation:this.onSoftViolation,safeHook:i((u,g,d)=>this.safeHook(u,g,d),"safeHook")}),await os(this.recording,c,s?f.length:0,o.tx);let y=(async()=>{s&&await Promise.all(f.map(u=>this.invokeHandler(u,c))),l&&this.onPublish&&await this.safeHook(()=>this.onPublish(c),"onPublish",c)})();return a?await y:y.then(void 0,()=>{}),c}createPublisher(t){let n=typeof t=="string"?t:t.name;return wt(n,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),{source:n,publish:i(async(r,o,s={},a)=>{if(s.source&&s.source!==n)throw new we(n,s.source);await this.publish(r,o,{...s,source:n},a)},"publish")}}subscribe(t,n){let r=typeof t=="string"?t:t.name;wt(r,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let o={intentName:r,handler:n};this.subscriptions.push(o);let s=this.subscriptionsByIntent.get(r)??[];return s.push(o),this.subscriptionsByIntent.set(r,s),()=>{let a=this.subscriptions.indexOf(o);a>=0&&this.subscriptions.splice(a,1);let l=this.subscriptionsByIntent.get(r);if(!l)return;let c=l.indexOf(o);c>=0&&l.splice(c,1),l.length===0&&this.subscriptionsByIntent.delete(r)}}registerInterceptor(t,n,r){let o=typeof t=="string"?t:t.name;wt(o,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let s={registrationId:Ba(),interceptorId:r??o,intentName:o,interceptor:n,createdAt:new Date().toISOString()};this.interceptors.push(s);let a=this.interceptorsByIntent.get(o)??[];return a.push(s),this.interceptorsByIntent.set(o,a),s.registrationId}unregisterInterceptor(t){let n=this.interceptors.find(s=>s.registrationId===t);if(!n)return!1;let r=this.interceptors.indexOf(n);r>=0&&this.interceptors.splice(r,1);let o=this.interceptorsByIntent.get(n.intentName);if(o){let s=o.indexOf(n);s>=0&&o.splice(s,1),o.length===0&&this.interceptorsByIntent.delete(n.intentName)}return!0}listInterceptors(t){return this.interceptors.filter(n=>!t||n.intentName===t).map(n=>({registrationId:n.registrationId,interceptorId:n.interceptorId,intent:n.intentName,createdAt:n.createdAt,lastInterceptedAt:n.lastInterceptedAt}))}getHistory(){return[...this.recording.history]}clearHistory(){this.recording.history.length=0}getTrace(){return[...this.recording.trace]}clearTrace(){this.recording.trace.length=0}appendTrace(t){xt(this.recording,t)}async recordAudit(t,n,r){await En(this.recording,t,n,r)}async invokeHandler(t,n){try{await Promise.resolve(t.handler(n))}catch(r){if(this.appendTrace({type:"handler.error",timestamp:new Date().toISOString(),intent:n.intent,correlationId:n.metadata.correlationId,traceId:n.metadata.traceId,spanId:n.metadata.spanId,details:{error:r instanceof Error?r.message:String(r)}}),await this.recordAudit("handler.error",n,{handlerIntent:t.intentName,error:r instanceof Error?r.message:String(r)}),this.onHandlerError&&await this.safeHook(()=>this.onHandlerError(r,n,t.intentName),"onHandlerError",n),this.rethrowHandlerErrors)throw r}}async safeHook(t,n,r){try{await Promise.resolve(t())}catch(o){this.appendTrace({type:"hook.error",timestamp:new Date().toISOString(),intent:r.intent,correlationId:r.metadata.correlationId,traceId:r.metadata.traceId,spanId:r.metadata.spanId,details:{hook:n,error:o instanceof Error?o.message:String(o)}}),await this.recordAudit("hook.error",r,{hook:n,error:o instanceof Error?o.message:String(o)})}}};function is(e){return new st(e)}i(is,"createEventBus");function Wa(e){if(!(!e||e.length===0))return e.map(t=>typeof t=="object"&&t!==null&&"key"in t?String(t.key):String(t)).join(".")}i(Wa,"formatStandardSchemaPath");function za(e){if(Array.isArray(e))return"array";if(e===null)return"object";let t=typeof e;return t==="string"||t==="number"||t==="boolean"||t==="object"?t:"unknown"}i(za,"actualType");function qa(e,t){return e?`${e}.${t}`:t}i(qa,"formatPath");function as(e,t,n,r,o){let s=za(e);if(t.type!=="unknown"&&s!==t.type){o.push({intent:r.intent,version:r.version,field:n,message:`Expected ${t.type}, received ${s}.`});return}if(t.enum&&!t.enum.some(a=>Object.is(a,e))&&o.push({intent:r.intent,version:r.version,field:n,message:"Value is not allowed by event contract enum."}),t.type==="object"&&t.fields){if(e===null||typeof e!="object"||Array.isArray(e)){o.push({intent:r.intent,version:r.version,field:n,message:"Nested object field must be a non-array object."});return}ls(e,t.fields,r,o,n)}t.type==="array"&&t.items&&Array.isArray(e)&&e.forEach((a,l)=>{as(a,t.items,`${n}[${l}]`,r,o)})}i(as,"validateSchemaField");function ls(e,t,n,r,o){for(let[s,a]of Object.entries(t)){let l=qa(o,s),c=e[s];if(c===void 0){a.required&&r.push({intent:n.intent,version:n.version,field:l,message:"Required field is missing."});continue}as(c,a,l,n,r)}}i(ls,"validateObjectSchema");var Ot=class{static{i(this,"EventContractRegistryImpl")}contracts=new Map;register(t){let n=this.key(t.intent,t.version);if(this.contracts.has(n))throw new Error(`Event contract "${n}" is already registered.`);this.contracts.set(n,{allowAdditionalFields:!0,...t})}get(t,n){return n?this.contracts.get(this.key(t,n)):this.list(t).at(-1)}list(t){return Array.from(this.contracts.values()).filter(n=>!t||n.intent===t)}validate(t){let n=t.metadata.eventVersion,r=this.get(t.intent,n),o=[];if(!r)return{ok:!1,issues:[{intent:t.intent,version:n,message:n?`No event contract registered for version "${n}".`:"No event contract registered for intent."}]};r.deprecated&&o.push({intent:t.intent,version:r.version,message:typeof r.deprecated=="string"?r.deprecated:"Event contract is deprecated."});let s=t.payload!=null&&typeof t.payload=="object"?t.payload:void 0;if(r.schema){if(!s)o.push({intent:t.intent,version:r.version,message:"Payload must be an object for schema validation."});else if(ls(s,r.schema,r,o),r.allowAdditionalFields===!1)for(let a of Object.keys(s))r.schema[a]||o.push({intent:t.intent,version:r.version,field:a,message:"Additional field is not allowed by event contract."})}if(r.standardSchema){let a=r.standardSchema["~standard"].validate(t.payload);if(a instanceof Promise)o.push({intent:t.intent,version:r.version,message:"Standard Schema validator returned a Promise; event contract validation is synchronous."});else if(a.issues)for(let l of a.issues)o.push({intent:t.intent,version:r.version,field:Wa(l.path),message:l.message})}return{ok:o.length===0,contract:r,issues:o}}clear(){this.contracts.clear()}key(t,n){return`${t}@${n}`}};function Sn(){return new Ot}i(Sn,"createEventContractRegistry");var cs=0;function Ya(){return cs+=1,`outbox-${Date.now()}-${cs}`}i(Ya,"nextOutboxId");function ds(e){return{...e,event:{...e.event,metadata:{...e.event.metadata}}}}i(ds,"cloneRecord");var Me=class{static{i(this,"InMemoryEventBuffer")}records=new Map;async enqueue(t){let n=new Date().toISOString(),r={id:Ya(),event:t,status:"pending",attempts:0,createdAt:n,updatedAt:n};return this.records.set(r.id,r),ds(r)}async markDispatched(t){let n=this.records.get(t);n&&(n.status="dispatched",n.updatedAt=new Date().toISOString())}async markFailed(t,n){let r=this.records.get(t);r&&(r.status="failed",r.attempts+=1,r.error=n instanceof Error?n.message:String(n),r.updatedAt=new Date().toISOString())}async list(t){return Array.from(this.records.values()).filter(n=>!t||n.status===t).map(ds)}async clear(){this.records.clear()}},us=Me;function Sr(e){return`${e.from}->${e.to}`}i(Sr,"flowKey");function ps(e){let t=new Set,n=[];for(let r of e){let o=Sr(r);t.has(o)||(t.add(o),n.push(r))}return n}i(ps,"uniqueFlows");function fs(e,t){let n=new Set(t.map(Sr));return e.filter(r=>!n.has(Sr(r)))}i(fs,"difference");function wn(e){let t=e.registry,n=e.eventBus,r=e.graph;return{report(){let o=t?t.getAllRelationships().filter(m=>m.kind==="produces").map(m=>({from:m.from,to:m.to})):[],s=o.length>0||!r?[]:r.getEdges().filter(m=>m.kind==="produces").map(m=>({from:m.from,to:m.to})),a=n?.getHistory().map(m=>({from:m.event.metadata.source,to:m.event.intent}))??[],l=a.length>0||!r?[]:r.getEdges().filter(m=>m.kind==="observed").map(m=>({from:m.from,to:m.to})),c=ps([...o,...s]),p=ps([...a,...l]),f=p.filter(m=>!m.from||m.from==="unknown"),y=t?Array.from(new Set(p.map(m=>m.from).filter(m=>m&&m!=="unknown"&&!t.has(m)))):[],u=t?Array.from(new Set(p.map(m=>m.to).filter(m=>!t.has(m)))):[],g=new Set(p.flatMap(m=>[m.from,m.to])),d=t?t.list().map(m=>m.name).filter(m=>!g.has(m)):[];return{generatedAt:new Date().toISOString(),declaredProductions:c,observedProductions:p,declaredButUnobserved:fs(c,p),observedButUndeclared:fs(p.filter(m=>m.from!=="unknown"),c),unknownSources:f,unregisteredObservedSources:y,unregisteredObservedIntents:u,registeredButNeverObserved:d}}}}i(wn,"createObservabilityReporter");function gs(e){return{events(t){return e.eventBus.getHistory().map(n=>n.event).filter(n=>!t||n.intent===t)},traces(t){return e.eventBus.getTrace().filter(n=>!t||n.type===t)},audit(t){return e.auditTrail.query(t)},outbox(t){return e.outbox.list(t)},observability(){return e.syncGraph(),e.observability.report()},async snapshot(){return{events:this.events(),traces:this.traces(),audit:await this.audit(),outbox:await this.outbox(),observability:this.observability()}},async clear(){e.eventBus.clearHistory(),e.eventBus.clearTrace(),await e.auditTrail.clear(),await e.outbox.clear()}}}i(gs,"createArkTestHarness");var ms=0;function Xa(){return ms+=1,`audit-${Date.now()}-${ms}`}i(Xa,"createAuditId");function Za(e,t){return!(t.type&&e.type!==t.type||t.intent&&e.intent!==t.intent||t.correlationId&&e.correlationId!==t.correlationId||t.subject&&e.subject!==t.subject||t.since&&e.timestamp<t.since||t.until&&e.timestamp>t.until)}i(Za,"matchesQuery");var Pt=class{constructor(t){this.maxRecords=t}maxRecords;static{i(this,"InMemoryAuditStore")}records=[];append(t){this.records.push(t),this.maxRecords!==void 0&&this.records.length>this.maxRecords&&this.records.splice(0,this.records.length-this.maxRecords)}query(t={}){let n=this.records.filter(r=>Za(r,t));return t.limit===void 0?[...n]:n.slice(-t.limit)}clear(){this.records.length=0}},Cn=class{constructor(t){this.store=t}store;static{i(this,"AuditTrailImpl")}async record(t){let n={id:Xa(),timestamp:t.timestamp??new Date().toISOString(),type:t.type,source:t.source,actor:t.actor,intent:t.intent,correlationId:t.correlationId,causationId:t.causationId,subject:t.subject,details:t.details};return await this.store.append(n),n}async query(t){return this.store.query(t)}async clear(){await this.store.clear()}};function xn(e={}){return new Cn(e.store??new Pt(e.maxRecords))}i(xn,"createAuditTrail");var On=class{static{i(this,"DependencyGraphImpl")}nodes=new Map;edges=[];registerDependency(t,n,r="declared"){this.ensureNode(t),this.ensureNode(n),this.addEdge({from:t,to:n,kind:r})}registerEventFlow(t,n){this.ensureNode(t),this.ensureNode(n),this.addEdge({from:t,to:n,kind:"observed"})}getNodes(){return Array.from(this.nodes.values())}getEdges(){return[...this.edges]}toJSON(){return{nodes:this.getNodes(),edges:this.getEdges()}}toMermaid(){let t=`flowchart TD
8
8
  `;for(let r of this.edges){let o=r.kind?`|${r.kind}|`:"";t+=` ${this.safeId(r.from)} -->${o} ${this.safeId(r.to)}
package/docs/README.md CHANGED
@@ -73,7 +73,7 @@ These are **not** the day-to-day product path. They stay in the repo for evidenc
73
73
  | Field adoption kit (scaffolding, not closed) | [field/](field/) |
74
74
  | Runtime hardening (experimental) | [production-hardening.md](production-hardening.md) |
75
75
 
76
- Current published: [CHANGELOG](../CHANGELOG.md) (`arkgate@4.8.18` on npm `latest`; does not close `K01`).
76
+ Current published: [CHANGELOG](../CHANGELOG.md) (`arkgate@4.8.19` on npm `latest`; does not close `K01`).
77
77
  Prior published: [releases/4.8.11.md](releases/4.8.11.md) (`arkgate@4.8.11`).
78
78
  Prior published: [releases/4.8.10.md](releases/4.8.10.md) (`arkgate@4.8.10`).
79
79
  Prior published: [releases/4.8.9.md](releases/4.8.9.md) (`arkgate@4.8.9`).
@@ -67,7 +67,9 @@ and trusted (Cursor: `Write` / `StrReplace` via `.cursor/hooks.json`). Codex CLI
67
67
  ChatGPT Desktop/App Server can hard-block a complete `apply_patch` through a trusted
68
68
  `.codex/hooks.json`; installed files stay unverified until a fresh covered invocation. Hosted
69
69
  tools, specialized opt-out paths, shell/direct writes, incomplete patch reconstruction, and
70
- OpenCode remain CI-backed or advisory. For every host, the repository-wide hard boundary is a
70
+ OpenCode remain CI-backed or advisory. Write-gate order: host pre-hook first when
71
+ the host has one; MCP `ark_prepare_write` is fallback if that hook is missing or
72
+ fail-open. For every host, the repository-wide hard boundary is a
71
73
  **required GitHub status context** that runs `arkgate-check --strict-merge` (alias
72
74
  `ark-check --strict-merge`) — the CLI name is not the status context name. Soft-write or
73
75
  unverified-hook evidence alone does not mean the project is unfinished. See
package/docs/ai-gates.md CHANGED
@@ -44,6 +44,10 @@ advisory-local / hard-CI split is a deliberate trade-off: local surfaces optimiz
44
44
  while a required merge status is the one boundary a repository can make every write path share.
45
45
  Prefer fail-closed honesty over fake hard guarantees on advisory hosts.
46
46
 
47
+ **Write-gate order:** install and trust the host pre-hook first (hard when the host
48
+ can do it). MCP `ark_prepare_write` is fallback when that path is missing or
49
+ fail-open. OpenCode is MCP-only. Required CI is always the merge line.
50
+
47
51
  Everything below uses the same `ark.config.json` as `arkgate-check` / `ark-check` (CI) — one
48
52
  rules file shared by every surface. From **4.0**, optional **ArkRules** (`arkRules` map +
49
53
  `arkrules/*.json`) ride the **same** write path, doctor, and CI adapter; absence of ArkRules
@@ -350,9 +354,9 @@ alwaysApply: true
350
354
  ---
351
355
 
352
356
  Before trusting Ark MCP evidence, call `ark_identity` with `project.expectedRoot`
353
- set to the exact project root. Then call `ark_manifest`. Before writing TypeScript,
354
- prefer MCP `ark_prepare_write` / `validate_code` when available; the project
355
- `.cursor/hooks.json` hard gate still blocks invalid Write/StrReplace.
357
+ set to the exact project root. Then call `ark_manifest`. The write gate is the project `.cursor/hooks.json` pre-hook when installed,
358
+ trusted, and `failClosed`. Call MCP `ark_prepare_write` / `validate_code` only
359
+ as fallback if that hook is missing or fail-open.
356
360
  ```
357
361
 
358
362
  Your repository backstop remains CI: `ark-check` fails its check on anything that slips
package/docs/develop.md CHANGED
@@ -35,12 +35,11 @@ ArkGate solves this by shifting the check to the exact moment of writing. By int
35
35
  ## Default integration
36
36
 
37
37
  ```bash
38
- npm install -D arkgate typescript
39
38
  npx arkgate start --apply
40
39
  npx --package=arkgate arkgate-check --doctor
41
40
  ```
42
41
 
43
- `arkgate-check` is a command in the `arkgate` package. After a local install, `npx arkgate-check --doctor` also works.
42
+ `start --apply` pins arkgate with this repo's package manager (`pnpm add -w` / `yarn add -W` at a workspace root). Do not run `npm install -D arkgate` at a `workspace:*` root — npm rejects that protocol. `arkgate-check` is a command in the `arkgate` package. After a local install, `npx arkgate-check --doctor` also works.
44
43
 
45
44
  Make the import-rules check a **required** merge **status context** (GitHub/GitLab/etc.). The CLI
46
45
  command is `arkgate-check --strict-merge` / `ark-check --strict-merge` — the hard boundary is
package/docs/use.md CHANGED
@@ -24,14 +24,13 @@ For **anyone** shipping TypeScript with an AI coding agent.
24
24
  ## In one minute
25
25
 
26
26
  ```bash
27
- npm install -D arkgate typescript
28
27
  npx arkgate start # preview what will change
29
28
  npx arkgate start --apply # install compact config + host router + CI; merge write-path gates into existing AGENTS.md / .mcp.json
30
29
  npx --package=arkgate arkgate-check --doctor # status — one next step
31
30
  npx --package=arkgate arkgate-check --doctor --all # full details
32
31
  ```
33
32
 
34
- `arkgate-check` is a command in the `arkgate` package, not its own npm package. After a local install, `npx arkgate-check --doctor` also works.
33
+ `start --apply` pins arkgate with this repo's package manager (`pnpm add -w` / `yarn add -W` at a workspace root). Do not run `npm install -D arkgate` at a `workspace:*` root — npm rejects that protocol. After a local install, `npx arkgate-check --doctor` also works. `arkgate-check` is a command in the `arkgate` package, not its own npm package.
35
34
 
36
35
  `start --apply` refuses when projected governed coverage is below 50% or
37
36
  shape confidence is weak (below 0.6 with coverage under 80%), or when the
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "arkgate",
3
- "version": "4.8.18",
3
+ "version": "4.8.19",
4
4
  "description": "When the agent writes a bad import, the write doesn’t land. The same check fails the pull request.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
package/server.json CHANGED
@@ -6,12 +6,12 @@
6
6
  "url": "https://github.com/pedroknigge/arkgate",
7
7
  "source": "github"
8
8
  },
9
- "version": "4.8.18",
9
+ "version": "4.8.19",
10
10
  "packages": [
11
11
  {
12
12
  "registryType": "npm",
13
13
  "identifier": "arkgate",
14
- "version": "4.8.18",
14
+ "version": "4.8.19",
15
15
  "runtimeHint": "npx",
16
16
  "transport": {
17
17
  "type": "stdio"
@@ -9,7 +9,7 @@ closed `/ark-*` catalog shipped as flat templates for Ark install.
9
9
  **Closed catalog** (`ARK_SKILL_NAMES`) — first-class doors plus one-release
10
10
  redirect stubs. Add a name only with a live ROADMAP item.
11
11
 
12
- Package version when last generated context: **arkgate@4.8.18**
12
+ Package version when last generated context: **arkgate@4.8.19**
13
13
  Schema: agent-skills package contract `1.0`
14
14
 
15
15
  ## Skills (closed catalog)
@@ -21,6 +21,8 @@ right house. Skills never enforce — CLI / hooks / CI do.
21
21
  ## Checklist
22
22
 
23
23
  - `filePath` is known before the call. Description alone is not a path.
24
+ - Host write gate: prefer the installed pre-hook. MCP `ark_prepare_write` is
25
+ fallback when that hook is missing or fail-open. Skills never enforce.
24
26
  - Golden pattern is load-bearing when present. Adopt generates it.
25
27
  - An included file that matches no layer is not a pass. The write gate denies it
26
28
  (`CONFIG_UNCLASSIFIED_FILES`). Place it in a layer folder, or send include/layer
@@ -8,8 +8,8 @@
8
8
  *
9
9
  * Honesty: OpenCode plugin hooks are **not** a complete hard write boundary
10
10
  * (subagent and alternate tool paths may bypass). Never treat this plugin as
11
- * Claude/Grok/Antigravity PreToolUse hard-write. Prefer MCP `ark_prepare_write`
12
- * + required merge status.
11
+ * Claude/Grok/Antigravity PreToolUse hard-write. This host has no hard pre-hook,
12
+ * so MCP `ark_prepare_write` is the local write fallback + required merge status.
13
13
  *
14
14
  * This file is a gallery template shipped with arkgate — not auto-installed.
15
15
  */
@@ -21,6 +21,8 @@ right house. Skills never enforce — CLI / hooks / CI do.
21
21
  ## Checklist
22
22
 
23
23
  - `filePath` is known before the call. Description alone is not a path.
24
+ - Host write gate: prefer the installed pre-hook. MCP `ark_prepare_write` is
25
+ fallback when that hook is missing or fail-open. Skills never enforce.
24
26
  - Golden pattern is load-bearing when present. Adopt generates it.
25
27
  - An included file that matches no layer is not a pass. The write gate denies it
26
28
  (`CONFIG_UNCLASSIFIED_FILES`). Place it in a layer folder, or send include/layer