arkgate 3.1.0 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
- var Ke="3.1.0";var ze="1.1";function E(e){return typeof e=="string"&&e.length>0?e:void 0}function Ie(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function qe(e,t,n){return e==="LAYER_IMPORT_VIOLATION"?t.typeOnly||n.targetTypeOnlyExports===!0||n.namedBindingsTypeOnly===!0?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":n.peerIsolation===!0?"Extract the shared dependency to a shared layer, then preflight again.":`Define a port in ${t.fromLayer??"the source layer"}, inject the ${t.toLayer??"outer-layer"} implementation, then preflight again.`:e==="FORBIDDEN_GLOBAL"?`Inject ${t.target??"the capability"} through a port, then preflight again.`:e==="CIRCULAR_DEPENDENCY"?"Extract the shared dependency into a third module, then preflight again.":e==="RAW_EVENT_PUBLISH"?"Publish through a registered intent creator, then run Ark again.":e==="PUBLISH_MISSING_SOURCE"?"Add metadata.source to the publish call, then run Ark again.":`Resolve ${e} without weakening ark.config.json, then run Ark again.`}function oe(e,t="error"){let n=E(e.ruleId)??E(e.code)??"ARK_UNKNOWN",r=e.severity==="warning"?"warning":t,a={...E(e.target)?{target:E(e.target)}:{},...E(e.fromLayer)?{fromLayer:E(e.fromLayer)}:{},...E(e.toLayer)?{toLayer:E(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{}};return{ruleId:n,severity:r,message:E(e.message)??n,location:{file:E(e.file)??"<unknown>",line:Ie(e.line,1),column:Ie(e.column,1)},evidence:a,nextAction:E(e.nextAction)??qe(n,a,e)}}function Ye(e){return{schemaVersion:"1.1",valid:e.valid,diagnostics:[...(e.violations??[]).map(t=>oe(t,"error")),...(e.warnings??[]).map(t=>oe(t,"warning"))]}}var We={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@2/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","valid","diagnostics"],properties:{schemaVersion:{const:"1.1"},valid:{type:"boolean"},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"}}},nextAction:{type:"string",minLength:1}}}}}};var Se=new Map;function ke(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function se(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let a=e[n+1];if("*?{}[],".includes(a)||a==="\\"){t+="\\"+a,n+=1;continue}t+="/";continue}t+=r}return t}function Je(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="{")t+=1;else if(r==="}"&&(t-=1,t<0))return!1}return t===0}function F(e){let t=Se.get(e);if(t)return t;let n=se(e),r=Je(n),a="",i=0;for(let c=0;c<n.length;c+=1){let d=n[c];d==="\\"&&c+1<n.length?(a+=ke(n[c+1]),c+=1):d==="*"?n[c+1]==="*"?n[c+2]==="/"?(a+="(?:.*/)?",c+=2):(a+=".*",c+=1):a+="[^/]*":d==="?"?a+="[^/]":d==="{"&&r?(a+="(?:",i+=1):d==="}"&&r&&i>0?(a+=")",i-=1):d===","&&r&&i>0?a+="|":a+=ke(d)}let s=new RegExp(`^${a}$`);return Se.set(e,s),s}function ce(e){let t=se(String(e)),r=t.split("*")[0].split("/").filter(Boolean).length,a=t.replace(/\*/g,"").length;return r*1e4+a}function z(e,t){let n=String(e).split(/[/\\]/).join("/"),r,a=-1;for(let i of t??[])if(!(i.exclude??[]).some(s=>F(s).test(n))){for(let s of i.patterns??[])if(F(s).test(n)){let c=ce(s);c>a&&(a=c,r=i.name)}}return r}function Ee(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),r=new Set(t.map(a=>String(a).toLowerCase()));for(let a=0;a<n.length-1;a+=1)if(r.has(n[a].toLowerCase()))return`${n[a]}/${n[a+1]}`}function Ze(e){let t=new Set;for(let n of e??[]){let a=se(String(n)).split("/").filter(Boolean);for(let i=0;i<a.length;i+=1){let s=a[i];if((s==="**"||s==="*")&&i>0){let c=a[i-1];c&&!c.includes("*")&&!c.includes("{")&&!c.includes("}")&&t.add(c)}}}return[...t]}function Qe(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(a=>typeof a=="string"&&a.length>0);let r=(n??[]).find(a=>a.name===t);return Ze(r?.patterns)}function v(e,t,n,r){for(let a of e??[])if(!(a.from!==t||a.to!==n)&&a.allowed===!1){if(a.peerIsolation){let i=r?.fromPath,s=r?.toPath;if(!i||!s)continue;let c=Qe(a,t,r?.layers);if(c.length===0)continue;let d=Ee(i,c),u=Ee(s,c);if(!d||!u)continue;if(d!==u)return a;continue}if(t!==n)return a}}var le={RAW_EVENT_PUBLISH:"Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts and tooling.",PUBLISH_MISSING_SOURCE:"Strict Ark publish calls must include metadata.source."};function R(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function de(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&R(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:le.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:le.PUBLISH_MISSING_SOURCE}),t}function _(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function Pe(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function Le(e,t){if(e.isImportDeclaration(t)){let n=t.importClause;if(!n)return!1;if(n.isTypeOnly)return!0;let r=n.namedBindings;return!!(r&&e.isNamedImports(r)&&r.elements.length>0&&r.elements.every(a=>a.isTypeOnly))}if(e.isExportDeclaration(t)){if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(r=>r.isTypeOnly))}return!1}function Re(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=a=>a===t.fileName?t:void 0,r.fileExists=a=>a===t.fileName,r.readFile=a=>a===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}function pe(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function fe(e,t,n,r){let a=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,i;try{i=a?t.getShorthandAssignmentValueSymbol(r.parent):pe(t,r)}catch{i=void 0}return!!i?.declarations?.some(s=>s.getSourceFile().fileName===n.fileName)}function q(e,t){let n,r=[],a=(s,c,d,u=!1)=>r.push({specifier:d,kind:c,line:Pe(t,s),typeOnly:u,unresolved:d===void 0,node:s}),i=s=>{if(e.isImportDeclaration(s))a(s,"import",_(e,s.moduleSpecifier),Le(e,s));else if(e.isExportDeclaration(s)&&s.moduleSpecifier)a(s,"export",_(e,s.moduleSpecifier),Le(e,s));else if(e.isImportEqualsDeclaration(s)&&e.isExternalModuleReference(s.moduleReference))a(s,"require",_(e,s.moduleReference.expression));else if(e.isCallExpression(s)){let c=s.expression.kind===e.SyntaxKind.ImportKeyword,u=e.isIdentifier(s.expression)&&s.expression.text==="require"&&!fe(e,n??(n=Re(e,t)),t,s.expression);(c||u)&&a(s,u?"require":"dynamic-import",_(e,s.arguments[0]))}e.forEachChild(s,i)};return i(t),r}function Xe(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let a=_(e,r.argumentExpression);if(a===void 0)return;n.unshift(a)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}function et(e,t){let n=t.parent;return e.isPropertyAccessExpression(n)||e.isElementAccessExpression(n)?!1:e.isExpressionNode(t)&&!e.isInTypeQuery(t)||e.isShorthandPropertyAssignment(n)&&n.name===t}function we(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let r=n.length;r>=1;r-=1){let a=n.slice(0,r).join(".");if(e.has(a))return a}}function Y(e,t,n){if(n.length===0)return[];let r=new Set(n),a=Re(e,t),i=new Map,s=new Set;for(let o of t.statements)if(e.isVariableStatement(o))for(let l of o.declarationList.declarations)e.isIdentifier(l.name)&&s.add(l.name.text);let c=o=>{let l=Xe(e,o);if(!l)return;let f=pe(a,l.root),y=f?i.get(f):void 0;return y?[...y,...l.segments.slice(1)]:fe(e,a,t,l.root)||s.has(l.root.text)?void 0:l.segments};for(let o of t.statements)if(e.isVariableStatement(o))for(let l of o.declarationList.declarations){if(!l.initializer||!e.isIdentifier(l.name))continue;let f=c(l.initializer),y=pe(a,l.name);!f||!y||i.set(y,f)}let d=[],u=new Set,g=(o,l)=>{let f=Pe(t,l),y=`${o}:${l.getStart(t)}`;u.has(y)||(u.add(y),d.push({name:o,line:f,node:l}))},h=o=>{let l=o.parent&&(e.isPropertyAccessExpression(o.parent)||e.isElementAccessExpression(o.parent))&&o.parent.expression===o;if((e.isPropertyAccessExpression(o)||e.isElementAccessExpression(o))&&!l){let f=c(o),y=f?we(r,f):void 0;y&&g(y,o)}else e.isIdentifier(o)&&r.has(o.text)&&et(e,o)&&!fe(e,a,t,o)&&g(o.text,o);if(e.isVariableDeclaration(o)&&e.isObjectBindingPattern(o.name)&&o.initializer){let f=c(o.initializer);if(f)for(let y of o.name.elements){if(!e.isIdentifier(y.name))continue;let k=y.propertyName?_(e,y.propertyName)??y.propertyName.text:y.name.text,b=we(r,[...f,k]);b&&g(b,o.initializer)}}e.forEachChild(o,h)};return h(t),d}function A(e,t,n){return{ruleId:e,code:e,message:t,...n}}function N(e,t){return e.slice(0,t).split(`
2
- `).length}function tt(e){let t=[],n=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,r;for(;(r=n.exec(e))!==null;)t.push({value:r[1],index:r.index});return t}function nt(e){let t=[],n=[{kind:"import",re:/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s*)?['"]([^'"]+)['"]/g},{kind:"export",re:/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s*['"]([^'"]+)['"]/g},{kind:"dynamic-import",re:/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g},{kind:"require",re:/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g}];for(let r of n){let a;for(;(a=r.re.exec(e))!==null;){let i=a.index+a[0].indexOf(a[1]),s=a[0],c=r.kind==="import"&&/\bimport\s+type\b/.test(s)||r.kind==="export"&&/\bexport\s+type\b/.test(s);t.push({value:a[1],index:i,kind:r.kind,typeOnly:c})}}return t.sort((r,a)=>r.index-a.index)}function rt(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],a=i=>{e.isStringLiteralLike(i)&&r.push({value:i.text,index:i.getStart(n)}),e.forEachChild(i,a)};return a(n),r}function it(e){let t=e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);return["adapter","adapters","infra","infrastructure","persistence","repository","repositories","integration","database","db"].some(n=>t.includes(n))}function at(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}function ot(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}function V(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function st(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}function Oe(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:st(e,r.name)===n)}function j(e,t,n){return Oe(e,t,n)!==void 0}function H(e,t,n){let r=Oe(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}function ct(e,t){let n=H(e,t,"metadata");return j(e,n,"source")}function $e(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?$e(e,t.name):!1:!1}function lt(e,t){if(!e.isCallExpression(t))return!1;let n=t.expression;return e.isPropertyAccessExpression(n)?n.name.text==="publish":e.isIdentifier(n)&&n.text==="publish"}function dt(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=V(e,n);return r!==void 0&&R(r)||j(e,n,"intent")||$e(e,n)}function pt(e,t){if(!e.isCallExpression(t))return!1;let[n,r,a]=t.arguments;return ct(e,n)||j(e,r,"source")||j(e,a,"source")}function ft(e,t){if(!e.isCallExpression(t))return;let[n,r,a]=t.arguments,i=H(e,n,"metadata");return V(e,H(e,i,"source"))??V(e,H(e,r,"source"))??V(e,H(e,a,"source"))}function ut(e,t,n,r){let a=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),i=n,s=i?.filePath,c=i?.layer,d=[],u=h=>a.getLineAndCharacterOfPosition(h.getStart(a)).line+1,g=h=>{if(lt(e,h)){let o=h.arguments[0],l=V(e,o);for(let y of de({publishCall:!0,rawIntentName:l,objectHasIntent:j(e,o,"intent"),arkPublishCandidate:dt(e,h),hasSource:pt(e,h)}))d.push(A(y.ruleId,y.message,{line:u(h),filePath:s}));let f=ft(e,h);if(r&&c&&f&&R(f)){let y=r.resolveLayer(f);y&&y!==c&&d.push(A("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${f}" resolves to ${y}, but the target file is classified as ${c}.`,{line:u(h),filePath:s,target:f,fromLayer:c,toLayer:y}))}}e.forEachChild(h,g)};return g(a),d}function ve(e={}){let t=new Set((e.intents||[]).map(i=>typeof i=="string"?i:i.name)),n=e.forbiddenPatterns||[],r=new Set(e.infrastructureLayers??[]),a=e.enforceIntentAllowlist??t.size>0;return{validate(i,s){let c=[],d=s,u=d?.filePath,g=d?.layer,h=e.typescript,o=h?h.createSourceFile(u??"generated.ts",i,h.ScriptTarget.Latest,!0):void 0,l=o?q(e.typescript,o):void 0,f=l?l.filter(p=>p.specifier!==void 0).map(p=>({value:p.specifier,index:p.node.getStart(o),kind:p.kind,typeOnly:p.typeOnly})):nt(i),y=e.typescript?rt(e.typescript,i):tt(i);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(u))for(let p of l?.filter(({unresolved:m})=>m)??[]){let m=p.kind==="require";c.push(A(m?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${m?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:p.line,filePath:u}))}let k=g!==void 0&&(r.has(g)||ot(g)),b=g!==void 0?` If "${g}" is an infrastructure layer, mark it in ark.config.json with "mayImportInfrastructure": true (or name it with an infra token like Adapters/Persistence/Repository).`:"";for(let p of n)if(p instanceof RegExp){p.lastIndex=0;let m=p.exec(i);p.lastIndex=0,m&&c.push(A("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${p}`,{line:m.index===void 0?void 0:N(i,m.index),filePath:u,suggestion:"Remove infrastructure imports from domain/application layers."+b}))}else i.includes(p)&&c.push(A("FORBIDDEN_SUBSTRING",`Forbidden substring: ${p}`,{line:N(i,i.indexOf(p)),filePath:u}));for(let p of f){let m=e.resolveImportTarget?.(p.value,u)??(e.resolveImportLayer?{layer:e.resolveImportLayer(p.value,u)}:void 0),P=typeof u=="string"?e.resolveImportTarget?.(u)??(e.resolveImportLayer?{layer:g,relPath:void 0}:void 0):void 0,$=m?.layer;if($&&g){let K=v(e.architectureProfile?.rules,g,$,{fromPath:P?.relPath,toPath:m?.relPath,layers:e.architectureLayers});if(K){if(p.typeOnly&&!K.peerIsolation)continue;let ae=!!K.peerIsolation;c.push(A("LAYER_IMPORT_VIOLATION",K.message??(ae?`Layer "${g}" must not import across slices into "${$}".`:`Layer "${g}" must not import "${$}".`),{line:N(i,p.index),source:p.value,target:p.value,filePath:u,fromLayer:g,toLayer:$,suggestion:ae?"Extract shared code to a shared layer, or coordinate slices via events/ports \u2014 do not import across feature/context slices.":"Depend on a port/interface owned by an inner layer instead, or move this code to a layer allowed to make this import.",details:{importKind:p.kind,peerIsolation:ae,...p.typeOnly?{typeOnly:!0}:{}}}));continue}if($!==g)continue}k||p.typeOnly||!it(p.value)&&!at(p.value)||c.push(A("FORBIDDEN_IMPORT",`Forbidden ${p.kind} target: "${p.value}".`,{line:N(i,p.index),source:p.value,target:p.value,filePath:u,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+b,details:{importKind:p.kind}}))}if(e.policies)for(let p of e.policies){let m=p.check({source:i,context:s});if(m!==!0)if(Array.isArray(m))for(let P of m)c.push(A("POLICY_VIOLATION",P.message,{filePath:u,suggestion:`Fix violation of policy "${p.name}".`}));else m===!1?c.push(A("POLICY_VIOLATION",`Policy ${p.name} failed on generated code`)):c.push(A("POLICY_VIOLATION",m.message))}if(a&&t.size>0)for(let p of y)R(p.value)&&!t.has(p.value)&&c.push(A("UNKNOWN_INTENT",`Unknown intent reference: "${p.value}"`,{line:N(i,p.index),filePath:u,target:p.value,suggestion:`Register intent "${p.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&g)for(let p of y){if(!R(p.value))continue;let m=e.architectureProfile.resolveLayer(p.value);if(!m)continue;let P=v(e.architectureProfile.rules,g,m);P&&c.push(A("LAYER_REFERENCE_VIOLATION",P.message??`Layer "${g}" must not reference "${m}" through "${p.value}".`,{line:N(i,p.index),filePath:u,target:p.value,fromLayer:g,toLayer:m,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:P}}))}if(e.extensions)for(let p of e.extensions)try{let m=p.analyze(i,s);c.push(...m)}catch(m){c.push(A("EXTENSION_ERROR",`Extension "${p.name}" failed: ${m instanceof Error?m.message:String(m)}`))}if(e.typescript&&o&&g&&e.forbiddenGlobals?.[g]?.length)try{c.push(...Y(e.typescript,o,e.forbiddenGlobals[g]).map(p=>A("FORBIDDEN_GLOBAL",`${g} must not use the ambient global "${p.name}".`,{line:p.line,filePath:u,target:p.name,fromLayer:g,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})))}catch(p){c.push(A("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${p instanceof Error?p.message:String(p)}`))}if(e.typescript)try{c.push(...ut(e.typescript,i,s,e.architectureProfile))}catch(p){c.push(A("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${p instanceof Error?p.message:String(p)}`))}return{valid:c.length===0,violations:c}}}}var gt="1.0",J="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",_e=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],yt=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function ht(){let e=[];for(let t of _e)for(let n of _e)t===n||yt.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var Z=ht();var L={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},ge={$schema:"https://json-schema.org/draft/2020-12/schema",$id:J,title:"ArkGate architecture contract",description:"Versioned contract consumed identically by ArkGate CLI, MCP, and ESLint surfaces.",type:"object",additionalProperties:!1,required:["$schema","schemaVersion","include","layers","rules"],properties:{$schema:{type:"string",minLength:1,default:J,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:"1.0",default:"1.0"},name:{type:"string",minLength:1},include:{...L,minItems:1,default:["src"]},exclude:{...L,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:Z,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...L,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...L,minItems:1},exclude:L,intentPrefixes:L,description:{type:"string",minLength:1},forbiddenGlobals:L,mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...L,minItems:1}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}}}},D=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
1
+ var et="3.3.0";var tt="1.1";function E(e){return typeof e=="string"&&e.length>0?e:void 0}function Le(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function nt(e,t,n){return e==="LAYER_IMPORT_VIOLATION"?t.typeOnly||n.targetTypeOnlyExports===!0||n.namedBindingsTypeOnly===!0?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":n.peerIsolation===!0?"Extract the shared dependency to a shared layer, then preflight again.":`Define a port in ${t.fromLayer??"the source layer"}, inject the ${t.toLayer??"outer-layer"} implementation, then preflight again.`:e==="FORBIDDEN_GLOBAL"?`Inject ${t.target??"the capability"} through a port, then preflight again.`:e==="CIRCULAR_DEPENDENCY"?"Extract the shared dependency into a third module, then preflight again.":e==="RAW_EVENT_PUBLISH"?"Publish through a registered intent creator, then run Ark again.":e==="PUBLISH_MISSING_SOURCE"?"Add metadata.source to the publish call, then run Ark again.":`Resolve ${e} without weakening ark.config.json, then run Ark again.`}function fe(e,t="error"){let n=E(e.ruleId)??E(e.code)??"ARK_UNKNOWN",r=e.severity==="warning"?"warning":t,i={...E(e.target)?{target:E(e.target)}:{},...E(e.fromLayer)?{fromLayer:E(e.fromLayer)}:{},...E(e.toLayer)?{toLayer:E(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{}};return{ruleId:n,severity:r,message:E(e.message)??n,location:{file:E(e.file)??"<unknown>",line:Le(e.line,1),column:Le(e.column,1)},evidence:i,nextAction:E(e.nextAction)??nt(n,i,e)}}function rt(e){return{schemaVersion:"1.1",valid:e.valid,diagnostics:[...(e.violations??[]).map(t=>fe(t,"error")),...(e.warnings??[]).map(t=>fe(t,"warning"))]}}var it={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@2/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","valid","diagnostics"],properties:{schemaVersion:{const:"1.1"},valid:{type:"boolean"},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"}}},nextAction:{type:"string",minLength:1}}}}}};var Pe=new Map;function Re(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function ue(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let i=e[n+1];if("*?{}[],".includes(i)||i==="\\"){t+="\\"+i,n+=1;continue}t+="/";continue}t+=r}return t}function at(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="{")t+=1;else if(r==="}"&&(t-=1,t<0))return!1}return t===0}function H(e){let t=Pe.get(e);if(t)return t;let n=ue(e),r=at(n),i="",a=0;for(let c=0;c<n.length;c+=1){let p=n[c];p==="\\"&&c+1<n.length?(i+=Re(n[c+1]),c+=1):p==="*"?n[c+1]==="*"?n[c+2]==="/"?(i+="(?:.*/)?",c+=2):(i+=".*",c+=1):i+="[^/]*":p==="?"?i+="[^/]":p==="{"&&r?(i+="(?:",a+=1):p==="}"&&r&&a>0?(i+=")",a-=1):p===","&&r&&a>0?i+="|":i+=Re(p)}let s=new RegExp(`^${i}$`);return Pe.set(e,s),s}function ye(e){let t=ue(String(e)),r=t.split("*")[0].split("/").filter(Boolean).length,i=t.replace(/\*/g,"").length;return r*1e4+i}function G(e,t){let n=String(e).split(/[/\\]/).join("/"),r,i=-1;for(let a of t??[])if(!(a.exclude??[]).some(s=>H(s).test(n))){for(let s of a.patterns??[])if(H(s).test(n)){let c=ye(s);c>i&&(i=c,r=a.name)}}return r}function Oe(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),r=new Set(t.map(i=>String(i).toLowerCase()));for(let i=0;i<n.length-1;i+=1)if(r.has(n[i].toLowerCase()))return`${n[i]}/${n[i+1]}`}function ot(e){let t=new Set;for(let n of e??[]){let i=ue(String(n)).split("/").filter(Boolean);for(let a=0;a<i.length;a+=1){let s=i[a];if((s==="**"||s==="*")&&a>0){let c=i[a-1];c&&!c.includes("*")&&!c.includes("{")&&!c.includes("}")&&t.add(c)}}}return[...t]}function st(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(i=>typeof i=="string"&&i.length>0);let r=(n??[]).find(i=>i.name===t);return ot(r?.patterns)}function $(e,t,n,r){for(let i of e??[])if(!(i.from!==t||i.to!==n)&&i.allowed===!1){if(i.peerIsolation){let a=r?.fromPath,s=r?.toPath;if(!a||!s)continue;let c=st(i,t,r?.layers);if(c.length===0)continue;let p=Oe(a,c),u=Oe(s,c);if(!p||!u)continue;if(p!==u)return i;continue}if(t!==n)return i}}var ge={RAW_EVENT_PUBLISH:"Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts and tooling.",PUBLISH_MISSING_SOURCE:"Strict Ark publish calls must include metadata.source."};function v(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function me(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&v(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:ge.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:ge.PUBLISH_MISSING_SOURCE}),t}function M(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function _e(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function $e(e,t){if(e.isImportDeclaration(t)){let n=t.importClause;if(!n)return!1;if(n.isTypeOnly)return!0;let r=n.namedBindings;return!!(r&&e.isNamedImports(r)&&r.elements.length>0&&r.elements.every(i=>i.isTypeOnly))}if(e.isExportDeclaration(t)){if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(r=>r.isTypeOnly))}return!1}function Ne(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=i=>i===t.fileName?t:void 0,r.fileExists=i=>i===t.fileName,r.readFile=i=>i===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}function he(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function Ae(e,t,n,r){let i=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,a;try{a=i?t.getShorthandAssignmentValueSymbol(r.parent):he(t,r)}catch{a=void 0}return!!a?.declarations?.some(s=>s.getSourceFile().fileName===n.fileName)}function U(e,t){let n,r=[],i=(s,c,p,u=!1)=>r.push({specifier:p,kind:c,line:_e(t,s),typeOnly:u,unresolved:p===void 0,node:s}),a=s=>{if(e.isImportDeclaration(s))i(s,"import",M(e,s.moduleSpecifier),$e(e,s));else if(e.isExportDeclaration(s)&&s.moduleSpecifier)i(s,"export",M(e,s.moduleSpecifier),$e(e,s));else if(e.isImportEqualsDeclaration(s)&&e.isExternalModuleReference(s.moduleReference))i(s,"require",M(e,s.moduleReference.expression));else if(e.isCallExpression(s)){let c=s.expression.kind===e.SyntaxKind.ImportKeyword,u=e.isIdentifier(s.expression)&&s.expression.text==="require"&&!Ae(e,n??(n=Ne(e,t)),t,s.expression);(c||u)&&i(s,u?"require":"dynamic-import",M(e,s.arguments[0]))}e.forEachChild(s,a)};return a(t),r}function ct(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let i=M(e,r.argumentExpression);if(i===void 0)return;n.unshift(i)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}function lt(e,t){let n=t.parent;return e.isPropertyAccessExpression(n)||e.isElementAccessExpression(n)?!1:e.isExpressionNode(t)&&!e.isInTypeQuery(t)||e.isShorthandPropertyAssignment(n)&&n.name===t}function ve(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let r=n.length;r>=1;r-=1){let i=n.slice(0,r).join(".");if(e.has(i))return i}}function z(e,t,n){if(n.length===0)return[];let r=new Set(n),i=Ne(e,t),a=new Map,s=new Set;for(let o of t.statements)if(e.isVariableStatement(o))for(let l of o.declarationList.declarations)e.isIdentifier(l.name)&&s.add(l.name.text);let c=o=>{let l=ct(e,o);if(!l)return;let f=he(i,l.root),g=f?a.get(f):void 0;return g?[...g,...l.segments.slice(1)]:Ae(e,i,t,l.root)||s.has(l.root.text)?void 0:l.segments};for(let o of t.statements)if(e.isVariableStatement(o))for(let l of o.declarationList.declarations){if(!l.initializer||!e.isIdentifier(l.name))continue;let f=c(l.initializer),g=he(i,l.name);!f||!g||a.set(g,f)}let p=[],u=new Set,y=(o,l)=>{let f=_e(t,l),g=`${o}:${l.getStart(t)}`;u.has(g)||(u.add(g),p.push({name:o,line:f,node:l}))},m=o=>{let l=o.parent&&(e.isPropertyAccessExpression(o.parent)||e.isElementAccessExpression(o.parent))&&o.parent.expression===o;if((e.isPropertyAccessExpression(o)||e.isElementAccessExpression(o))&&!l){let f=c(o),g=f?ve(r,f):void 0;g&&y(g,o)}else e.isIdentifier(o)&&r.has(o.text)&&lt(e,o)&&!Ae(e,i,t,o)&&y(o.text,o);if(e.isVariableDeclaration(o)&&e.isObjectBindingPattern(o.name)&&o.initializer){let f=c(o.initializer);if(f)for(let g of o.name.elements){if(!e.isIdentifier(g.name))continue;let k=g.propertyName?M(e,g.propertyName)??g.propertyName.text:g.name.text,b=ve(r,[...f,k]);b&&y(b,o.initializer)}}e.forEachChild(o,m)};return m(t),p}function A(e,t,n){return{ruleId:e,code:e,message:t,...n}}function T(e,t){return e.slice(0,t).split(`
2
+ `).length}function pt(e){let t=[],n=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,r;for(;(r=n.exec(e))!==null;)t.push({value:r[1],index:r.index});return t}function dt(e){let t=[],n=[{kind:"import",re:/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s*)?['"]([^'"]+)['"]/g},{kind:"export",re:/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s*['"]([^'"]+)['"]/g},{kind:"dynamic-import",re:/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g},{kind:"require",re:/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g}];for(let r of n){let i;for(;(i=r.re.exec(e))!==null;){let a=i.index+i[0].indexOf(i[1]),s=i[0],c=r.kind==="import"&&/\bimport\s+type\b/.test(s)||r.kind==="export"&&/\bexport\s+type\b/.test(s);t.push({value:i[1],index:a,kind:r.kind,typeOnly:c})}}return t.sort((r,i)=>r.index-i.index)}function ft(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],i=a=>{e.isStringLiteralLike(a)&&r.push({value:a.text,index:a.getStart(n)}),e.forEachChild(a,i)};return i(n),r}function ut(e){let t=e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);return["adapter","adapters","infra","infrastructure","persistence","repository","repositories","integration","database","db"].some(n=>t.includes(n))}function yt(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}function gt(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}function K(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function mt(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}function Me(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:mt(e,r.name)===n)}function Y(e,t,n){return Me(e,t,n)!==void 0}function B(e,t,n){let r=Me(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}function ht(e,t){let n=B(e,t,"metadata");return Y(e,n,"source")}function Te(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?Te(e,t.name):!1:!1}function At(e,t){if(!e.isCallExpression(t))return!1;let n=t.expression;return e.isPropertyAccessExpression(n)?n.name.text==="publish":e.isIdentifier(n)&&n.text==="publish"}function Ct(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=K(e,n);return r!==void 0&&v(r)||Y(e,n,"intent")||Te(e,n)}function bt(e,t){if(!e.isCallExpression(t))return!1;let[n,r,i]=t.arguments;return ht(e,n)||Y(e,r,"source")||Y(e,i,"source")}function It(e,t){if(!e.isCallExpression(t))return;let[n,r,i]=t.arguments,a=B(e,n,"metadata");return K(e,B(e,a,"source"))??K(e,B(e,r,"source"))??K(e,B(e,i,"source"))}function xt(e,t,n,r){let i=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),a=n,s=a?.filePath,c=a?.layer,p=[],u=m=>i.getLineAndCharacterOfPosition(m.getStart(i)).line+1,y=m=>{if(At(e,m)){let o=m.arguments[0],l=K(e,o);for(let g of me({publishCall:!0,rawIntentName:l,objectHasIntent:Y(e,o,"intent"),arkPublishCandidate:Ct(e,m),hasSource:bt(e,m)}))p.push(A(g.ruleId,g.message,{line:u(m),filePath:s}));let f=It(e,m);if(r&&c&&f&&v(f)){let g=r.resolveLayer(f);g&&g!==c&&p.push(A("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${f}" resolves to ${g}, but the target file is classified as ${c}.`,{line:u(m),filePath:s,target:f,fromLayer:c,toLayer:g}))}}e.forEachChild(m,y)};return y(i),p}function De(e={}){let t=new Set((e.intents||[]).map(a=>typeof a=="string"?a:a.name)),n=e.forbiddenPatterns||[],r=new Set(e.infrastructureLayers??[]),i=e.enforceIntentAllowlist??t.size>0;return{validate(a,s){let c=[],p=s,u=p?.filePath,y=p?.layer,m=e.typescript,o=m?m.createSourceFile(u??"generated.ts",a,m.ScriptTarget.Latest,!0):void 0,l=o?U(e.typescript,o):void 0,f=l?l.filter(d=>d.specifier!==void 0).map(d=>({value:d.specifier,index:d.node.getStart(o),kind:d.kind,typeOnly:d.typeOnly})):dt(a),g=e.typescript?ft(e.typescript,a):pt(a);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(u))for(let d of l?.filter(({unresolved:h})=>h)??[]){let h=d.kind==="require";c.push(A(h?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${h?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:d.line,filePath:u}))}let k=y!==void 0&&(r.has(y)||gt(y)),b=y!==void 0?` If "${y}" is an infrastructure layer, mark it in ark.config.json with "mayImportInfrastructure": true (or name it with an infra token like Adapters/Persistence/Repository).`:"";for(let d of n)if(d instanceof RegExp){d.lastIndex=0;let h=d.exec(a);d.lastIndex=0,h&&c.push(A("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${d}`,{line:h.index===void 0?void 0:T(a,h.index),filePath:u,suggestion:"Remove infrastructure imports from domain/application layers."+b}))}else a.includes(d)&&c.push(A("FORBIDDEN_SUBSTRING",`Forbidden substring: ${d}`,{line:T(a,a.indexOf(d)),filePath:u}));for(let d of f){let h=e.resolveImportTarget?.(d.value,u)??(e.resolveImportLayer?{layer:e.resolveImportLayer(d.value,u)}:void 0),O=typeof u=="string"?e.resolveImportTarget?.(u)??(e.resolveImportLayer?{layer:y,relPath:void 0}:void 0):void 0,N=h?.layer;if(N&&y){let J=$(e.architectureProfile?.rules,y,N,{fromPath:O?.relPath,toPath:h?.relPath,layers:e.architectureLayers});if(J){if(d.typeOnly&&!J.peerIsolation)continue;let de=!!J.peerIsolation;c.push(A("LAYER_IMPORT_VIOLATION",J.message??(de?`Layer "${y}" must not import across slices into "${N}".`:`Layer "${y}" must not import "${N}".`),{line:T(a,d.index),source:d.value,target:d.value,filePath:u,fromLayer:y,toLayer:N,suggestion:de?"Extract shared code to a shared layer, or coordinate slices via events/ports \u2014 do not import across feature/context slices.":"Depend on a port/interface owned by an inner layer instead, or move this code to a layer allowed to make this import.",details:{importKind:d.kind,peerIsolation:de,...d.typeOnly?{typeOnly:!0}:{}}}));continue}if(N!==y)continue}k||d.typeOnly||!ut(d.value)&&!yt(d.value)||c.push(A("FORBIDDEN_IMPORT",`Forbidden ${d.kind} target: "${d.value}".`,{line:T(a,d.index),source:d.value,target:d.value,filePath:u,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+b,details:{importKind:d.kind}}))}if(e.policies)for(let d of e.policies){let h=d.check({source:a,context:s});if(h!==!0)if(Array.isArray(h))for(let O of h)c.push(A("POLICY_VIOLATION",O.message,{filePath:u,suggestion:`Fix violation of policy "${d.name}".`}));else h===!1?c.push(A("POLICY_VIOLATION",`Policy ${d.name} failed on generated code`)):c.push(A("POLICY_VIOLATION",h.message))}if(i&&t.size>0)for(let d of g)v(d.value)&&!t.has(d.value)&&c.push(A("UNKNOWN_INTENT",`Unknown intent reference: "${d.value}"`,{line:T(a,d.index),filePath:u,target:d.value,suggestion:`Register intent "${d.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&y)for(let d of g){if(!v(d.value))continue;let h=e.architectureProfile.resolveLayer(d.value);if(!h)continue;let O=$(e.architectureProfile.rules,y,h);O&&c.push(A("LAYER_REFERENCE_VIOLATION",O.message??`Layer "${y}" must not reference "${h}" through "${d.value}".`,{line:T(a,d.index),filePath:u,target:d.value,fromLayer:y,toLayer:h,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:O}}))}if(e.extensions)for(let d of e.extensions)try{let h=d.analyze(a,s);c.push(...h)}catch(h){c.push(A("EXTENSION_ERROR",`Extension "${d.name}" failed: ${h instanceof Error?h.message:String(h)}`))}if(e.typescript&&o&&y&&e.forbiddenGlobals?.[y]?.length)try{c.push(...z(e.typescript,o,e.forbiddenGlobals[y]).map(d=>A("FORBIDDEN_GLOBAL",`${y} must not use the ambient global "${d.name}".`,{line:d.line,filePath:u,target:d.name,fromLayer:y,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})))}catch(d){c.push(A("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${d instanceof Error?d.message:String(d)}`))}if(e.typescript)try{c.push(...xt(e.typescript,a,s,e.architectureProfile))}catch(d){c.push(A("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${d instanceof Error?d.message:String(d)}`))}return{valid:c.length===0,violations:c}}}}var St="1.0",Q="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",Fe=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],kt=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Et(){let e=[];for(let t of Fe)for(let n of Fe)t===n||kt.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var X=Et();var L={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},be={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Q,title:"ArkGate architecture contract",description:"Versioned contract consumed identically by ArkGate CLI, MCP, and ESLint surfaces.",type:"object",additionalProperties:!1,required:["$schema","schemaVersion","include","layers","rules"],properties:{$schema:{type:"string",minLength:1,default:Q,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:"1.0",default:"1.0"},name:{type:"string",minLength:1},include:{...L,minItems:1,default:["src"]},exclude:{...L,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:X,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...L,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...L,minItems:1},exclude:L,intentPrefixes:L,description:{type:"string",minLength:1},forbiddenGlobals:L,mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...L,minItems:1}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}}}},F=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
3
3
  ${n.map(r=>`- ${r.path}: ${r.message}`).join(`
4
- `)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function Ne(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ue(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function M(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function mt(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function W(e,t,n,r,a){if(t.$ref){let i=mt(t.$ref,r);if(!i){a.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}W(e,i,n,r,a);return}if(t.const!==void 0&&!Object.is(e,t.const)){a.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(i=>Object.is(i,e))){a.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!Ne(e)){a.push({path:n,message:`must be an object; received ${M(e)}`});return}let i=t.properties??{};for(let s of t.required??[])e[s]===void 0&&a.push({path:ue(n,s),message:"is required"});if(t.additionalProperties===!1)for(let s of Object.keys(e))s in i||a.push({path:ue(n,s),message:"unknown field"});for(let[s,c]of Object.entries(i))e[s]!==void 0&&W(e[s],c,ue(n,s),r,a);return}if(t.type==="array"){if(!Array.isArray(e)){a.push({path:n,message:`must be an array; received ${M(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&a.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let i=e.map(s=>JSON.stringify(s));new Set(i).size!==i.length&&a.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((i,s)=>W(i,t.items,`${n}[${s}]`,r,a));return}if(t.type==="string"){if(typeof e!="string"){a.push({path:n,message:`must be a string; received ${M(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&a.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&a.push({path:n,message:`must be a boolean; received ${M(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){a.push({path:n,message:`must be an integer; received ${M(e)}`});return}t.minimum!==void 0&&e<t.minimum&&a.push({path:n,message:`must be at least ${t.minimum}`})}}function At(e){return{...e,$schema:e.$schema===void 0?J:e.$schema,schemaVersion:e.schemaVersion===void 0?"1.0":e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?Z.map(t=>({...t})):e.rules}}function Ct(e,t="ark.config.json"){if(!Ne(e))throw new D(t,[{path:"$",message:`must be an object; received ${M(e)}`}]);let n=e.schemaVersion===void 0?"unversioned":null;if(e.schemaVersion!==void 0&&e.schemaVersion!=="1.0")throw new D(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.0`}]);return{candidate:At(e),migratedFrom:n}}function Q(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=Ct(e,t),a=[];if(W(n,ge,"$",ge,a),a.length>0)throw new D(t,a);return{config:n,migratedFrom:r}}function ye(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new D(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return Q(n,t)}function Me(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:J,schemaVersion:"1.0"};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}function bt(e){return e.endsWith(".")?e:`${e}.`}function xt(e,t){let n=e.prefixes.length?Math.max(...e.prefixes.map(a=>a.length)):0;return(t.prefixes.length?Math.max(...t.prefixes.map(a=>a.length)):0)-n}function ee(e){let t=e.layers.map(a=>({...a,prefixes:a.prefixes.map(bt)})),n=[...t].sort(xt),r=[...e.rules??[]];return{name:e.name,layers:t,rules:r,resolveLayer(a){return t.find(i=>i.match?.(a))?.name??n.find(i=>i.prefixes.some(s=>a.startsWith(s)))?.name}}}function De(e,t={}){return ee({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,r)=>({name:n.name,prefixes:n.intentPrefixes??[],description:n.description,order:r+1})),rules:e.rules??[]})}var It=[{name:"DomainModel",prefixes:["Domain"],description:"Rich domain model, business rules, and domain events.",order:1},{name:"ApplicationOrchestration",prefixes:["Application"],description:"Use cases and command orchestration.",order:2},{name:"PersistenceAdapters",prefixes:["Adapter.Persistence","Adapter.Repository"],description:"Database, repository, and storage adapters.",order:3},{name:"IntegrationAdapters",prefixes:["Adapter.Integration","Adapter.External"],description:"External systems, APIs, and integration adapters.",order:4},{name:"WorkflowSagaEngine",prefixes:["Workflow"],description:"Sagas, workflows, and long-running processes.",order:5},{name:"BackgroundJobsScheduling",prefixes:["Job"],description:"Background jobs, scheduled work, and async processors.",order:6},{name:"PresentationAdapters",prefixes:["Presentation","Adapter.Presentation","Adapter.Api"],description:"API, UI, controller, and presentation adapters.",order:7},{name:"ReportingReadModels",prefixes:["Reporting"],description:"Read models, projections, and reporting surfaces.",order:8},{name:"ExtensibilityMetadata",prefixes:["Metadata"],description:"Metadata, extensions, and schema contracts.",order:9},{name:"SecurityAuditObservability",prefixes:["Security","Audit","Observability"],description:"Security, audit, and observability concerns.",order:10},{name:"Kernel",prefixes:["Kernel"],description:"Ark-owned governance and kernel signals.",order:11}],X=ee({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:It,rules:Z.map(e=>({...e}))}),St={DomainModel:["domain"],ApplicationOrchestration:["application","app"],PersistenceAdapters:["adapters/persistence","adapters/repository","repositories","infra/persistence"],IntegrationAdapters:["adapters/integration","adapters/external","integrations"],WorkflowSagaEngine:["workflows","sagas"],BackgroundJobsScheduling:["jobs","schedules"],PresentationAdapters:["presentation","adapters/presentation","adapters/api"],ReportingReadModels:["reporting","read-models","projections"],ExtensibilityMetadata:["metadata","extensions"],SecurityAuditObservability:["security","audit","observability"],Kernel:["kernel"]};function Te(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return Me({include:e.include??[t],layers:X.layers.map(a=>({name:a.name,patterns:(St[a.name]??[a.name]).map(i=>`${r}${i}/**`),intentPrefixes:a.prefixes,optional:n})),rules:[...X.rules]})}var he="1.0";function O(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}function w(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(w).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${w(t[n])}`).join(",")}}`}var kt="1.0";function C(e,t){e.push({id:`${t.classification}:${t.path}:${t.kind}`,path:t.path,classification:t.classification,message:t.message,...t.classification==="weakening"||t.classification==="judgment-required"?{nextAction:`Restore the previous protection at ${t.path}, then run ArkGate again.`}:{},...t.before===void 0?{}:{before:t.before},...t.after===void 0?{}:{after:t.after}})}function I(e){return[...new Set(e??[])].sort()}function T(e,t,n,r,a){let i=I(n),s=I(r),c=new Set(i),d=new Set(s),u=s.filter(h=>!c.has(h)),g=i.filter(h=>!d.has(h));u.length===0&&g.length===0||(u.length>0&&C(e,{kind:"added",path:t,classification:a.added,message:a.addedMessage,before:i,after:s}),g.length>0&&C(e,{kind:"removed",path:t,classification:a.removed,message:a.removedMessage,before:i,after:s}))}function te(e,t,n,r,a,i,s){if(n===r)return;C(e,{kind:r?"enabled":"disabled",path:t,classification:r?a:a==="strengthening"?"weakening":"strengthening",message:r?i:s,before:n,after:r})}function ne(e,t){let n=new Map,r=new Set;for(let a of e){let i=t(a);n.has(i)?r.add(i):n.set(i,a)}return{values:n,duplicates:[...r].sort()}}function Et(e,t,n){let r=ne(t,i=>i.name),a=ne(n,i=>i.name);(r.duplicates.length>0||a.duplicates.length>0)&&C(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:r.duplicates,after:a.duplicates});for(let i of[...new Set([...r.values.keys(),...a.values.keys()])].sort()){let s=r.values.get(i),c=a.values.get(i),d=`$.layers[${i}]`;if(!s&&c){C(e,{kind:"layer-added",path:d,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:c});continue}if(s&&!c){C(e,{kind:"layer-removed",path:d,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:s});continue}!s||!c||(T(e,`${d}.patterns`,s.patterns,c.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),T(e,`${d}.exclude`,s.exclude,c.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."}),T(e,`${d}.forbiddenGlobals`,s.forbiddenGlobals,c.forbiddenGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),I(s.intentPrefixes).join("\0")!==I(c.intentPrefixes).join("\0")&&C(e,{kind:"intent-prefixes-changed",path:`${d}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:I(s.intentPrefixes),after:I(c.intentPrefixes)}),te(e,`${d}.mayImportInfrastructure`,s.mayImportInfrastructure===!0,c.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),te(e,`${d}.optional`,s.optional===!0,c.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active."))}}function Lt(e,t,n){let r=s=>`${s.from}->${s.to}`,a=ne(t,r),i=ne(n,r);(a.duplicates.length>0||i.duplicates.length>0)&&C(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:a.duplicates,after:i.duplicates});for(let s of[...new Set([...a.values.keys(),...i.values.keys()])].sort()){let c=a.values.get(s),d=i.values.get(s),u=`$.rules[${s}]`;if(!c&&d){d.allowed===!1&&C(e,{kind:"deny-added",path:u,classification:"strengthening",message:"A denied dependency edge was added.",after:d});continue}if(c&&!d){c.allowed===!1&&C(e,{kind:"deny-removed",path:u,classification:"weakening",message:"A denied dependency edge was removed.",before:c});continue}if(!c||!d)continue;c.allowed!==d.allowed&&C(e,{kind:d.allowed?"deny-disabled":"deny-enabled",path:`${u}.allowed`,classification:d.allowed?"weakening":"strengthening",message:d.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:c.allowed,after:d.allowed});let g=c.peerIsolation===!0,h=d.peerIsolation===!0;if(g!==h){let o=c.from===c.to&&d.from===d.to;C(e,{kind:h?"peer-isolation-enabled":"peer-isolation-disabled",path:`${u}.peerIsolation`,classification:o?h?"strengthening":"weakening":"judgment-required",message:o?h?"Cross-slice dependencies inside this layer are now denied.":"Cross-slice dependencies inside this layer are no longer denied.":"Changing peer isolation on a cross-layer edge changes the denial scope.",before:g,after:h})}I(c.sliceFolders).join("\0")!==I(d.sliceFolders).join("\0")&&C(e,{kind:"slice-folders-changed",path:`${u}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:I(c.sliceFolders),after:I(d.sliceFolders)})}}function wt(e,t,n){let r=t.safety??{},a=n.safety??{};for(let i of["maxTsSuppressions","maxAnyCasts"]){let s=r[i]??0,c=a[i]??0;s!==c&&C(e,{kind:c>s?"threshold-raised":"threshold-lowered",path:`$.safety.${i}`,classification:c>s?"weakening":"strengthening",message:c>s?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:s,after:c})}for(let i of["allowInMemory","allowDisabledPeerIsolation"])te(e,`$.safety.${i}`,r[i]===!0,a[i]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}function Pt(e){return e.some(t=>t.classification==="weakening")?"weakening":e.some(t=>t.classification==="judgment-required")?"judgment-required":e.some(t=>t.classification==="strengthening")?"strengthening":"neutral"}function me(e,t){let n=[];T(n,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),T(n,"$.exclude",e.exclude,t.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional project paths are excluded from governance.",removedMessage:"Fewer project paths are excluded from governance."}),T(n,"$.dynamicImportAllowlist",e.dynamicImportAllowlist,t.dynamicImportAllowlist,{added:"weakening",removed:"strengthening",addedMessage:"Additional files may use non-literal dynamic imports.",removedMessage:"Fewer files may use non-literal dynamic imports."}),te(n,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let r={off:0,soft:1,"framework-soft":1,strict:2},a=e.cyclePolicy??"strict",i=t.cyclePolicy??"strict";if(a!==i){let s=r[i]===r[a]?"judgment-required":r[i]>r[a]?"strengthening":"weakening";C(n,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:s,message:"The cycle enforcement level changed.",before:a,after:i})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&C(n,{kind:"framework-overlay-changed",path:"$.frameworkOverlay",classification:"judgment-required",message:"The framework overlay changed and may alter effective layer matching.",before:e.frameworkOverlay??null,after:t.frameworkOverlay??null}),Et(n,e.layers,t.layers),Lt(n,e.rules,t.rules),wt(n,e,t),n.sort((s,c)=>s.path.localeCompare(c.path)||s.id.localeCompare(c.id)),{schemaVersion:"1.0",classification:Pt(n),findings:n}}function Ae(e,t){if(!e||e.schemaVersion!=="1.0"||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(a=>typeof a!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=I(e.findingIds),r=I(t.findingIds);return n.length===r.length&&n.every((a,i)=>a===r[i])}function S(e){return`${e.from}->${e.to}`}function G(e,t,n,r="dependency"){return{id:`${e}:${r}:${S(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${S(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${S(t)}, then preflight again.`}:e==="unplanned"?{nextAction:`Remove the unplanned dependency ${S(t)} from the candidate, then preflight again.`}:{}}}function re(e){let t=[],n=new Map(e.changeMap.map.files.map(o=>[o.path,o])),r=new Map(e.changes.map(o=>[o.path,o])),a=new Map(e.changeMap.map.dependencies.map(o=>[S(o),o])),i=new Map(e.baseDependencies.map(o=>[S(o),o])),s=new Map(e.candidateDependencies.map(o=>[S(o),o]));for(let o of[...n.values()].sort((l,f)=>l.path.localeCompare(f.path))){let l=r.get(o.path);l?l.operation!==o.operation?t.push({id:`contradictory:file:${o.path}`,classification:"contradictory",subject:"file",path:o.path,expectedOperation:o.operation,actualOperation:l.operation,message:`${o.path} was planned as ${o.operation} but the actual operation is ${l.operation}.`,nextAction:`Change ${o.path} to the planned ${o.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${o.path}`,classification:"satisfied",subject:"file",path:o.path,expectedOperation:o.operation,actualOperation:l.operation,message:`${o.path} matches the planned ${o.operation} operation.`}):t.push({id:`missing:file:${o.path}`,classification:"missing",subject:"file",path:o.path,expectedOperation:o.operation,message:`${o.path} was planned as ${o.operation} but is absent from the actual change.`,nextAction:`${o.operation[0].toUpperCase()}${o.operation.slice(1)} ${o.path} in the complete change set, then preflight again.`})}for(let o of[...r.values()].sort((l,f)=>l.path.localeCompare(f.path)))n.has(o.path)||t.push({id:`unplanned:file:${o.path}`,classification:"unplanned",subject:"file",path:o.path,actualOperation:o.operation,message:`${o.path} has an unplanned ${o.operation} operation.`,nextAction:`Remove ${o.path} from the change set, then preflight again.`});let c=new Set;for(let o of[...a.values()].sort((l,f)=>S(l).localeCompare(S(f)))){if(s.has(S(o))){t.push(G("satisfied",o,`${o.from} -> ${o.to} exists in the candidate architecture.`));continue}let l={from:o.to,to:o.from};s.has(S(l))?(c.add(S(l)),t.push(G("contradictory",o,`${o.from} -> ${o.to} was planned, but the candidate contains the reverse edge.`))):t.push(G("missing",o,`${o.from} -> ${o.to} is absent from the candidate architecture.`))}let d=new Set([...n.keys(),...r.keys()]);for(let[o,l]of[...s].sort(([f],[y])=>f.localeCompare(y)))i.has(o)||a.has(o)||c.has(o)||!d.has(l.from)&&!d.has(l.to)||t.push({...G("unplanned",l,`${l.from} -> ${l.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let u=new Set(e.changeMap.map.files.filter(o=>o.operation==="delete").map(o=>o.path));for(let[o,l]of[...i].sort(([f],[y])=>f.localeCompare(y)))s.has(o)||u.has(l.from)||u.has(l.to)||!d.has(l.from)&&!d.has(l.to)||t.push({...G("unplanned",l,`${l.from} -> ${l.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let g={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((o,l)=>g[o.classification]-g[l.classification]||(o.subject===l.subject?0:o.subject==="file"?-1:1)||o.id.localeCompare(l.id));let h={satisfied:t.filter(o=>o.classification==="satisfied").length,missing:t.filter(o=>o.classification==="missing").length,contradictory:t.filter(o=>o.classification==="contradictory").length,unplanned:t.filter(o=>o.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:h.missing===0&&h.contradictory===0&&h.unplanned===0,behavioralCompletion:"not-evaluated",summary:h,findings:t}}function Fe(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return e.typeOnly||e.targetTypeOnlyExports||e.namedBindingsTypeOnly?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":e.peerIsolation?"Extract the shared dependency to a shared layer, then preflight again.":`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, then preflight again.`;case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";default:return`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}function Ce(e,t){let n=typeof e=="string"?ye(e,t):Q(e,t);return{...n,policyHash:O(w(n.config))}}function Rt(e){let t=Ce(e.baseConfig,e.baseSource??"base ark.config.json"),n=Ce(e.candidateConfig,e.candidateSource??"candidate ark.config.json"),r=me(t.config,n.config),a=r.findings.filter(c=>c.classification==="weakening"||c.classification==="judgment-required").map(c=>c.id).sort(),i=a.length>0,s=i&&Ae(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:a});return{schemaVersion:r.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:r.classification,findings:r.findings,blockingFindingIds:a,requiresAcknowledgement:i,acknowledged:s,valid:!i||s}}function B(e){let t=[];for(let n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."&&t.length>0&&t.at(-1)!==".."?t.pop():t.push(n));return t.join("/")}function He(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}function be(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}function ie(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let r=t,a="";for(t+=1;t<e.length;t+=1){let i=e[t];if(i===n)return{value:a,offset:r,excerpt:e.slice(r,t+1)};i==="\\"&&t+1<e.length?(a+=e[t+1],t+=1):a+=i}}function U(e,t,n){return e.startsWith(t,n)&&!He(e[n-1])&&!He(e[n+t.length])}function Ot(e,t){return t=be(e,t+6),e[t]==="("?ie(e,be(e,t+1)):je(e,t,!0)}function $t(e,t){return je(e,t+6,!1)}function je(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(U(e,"from",t))return ie(e,be(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return ie(e,t);if(t>0&&(U(e,"import",t)||U(e,"export",t)))return}}function vt(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="/"&&e[n+1]==="/"){if(n=e.indexOf(`
5
- `,n+2),n<0)break;continue}if(r==="/"&&e[n+1]==="*"){let i=e.indexOf("*/",n+2);if(i<0)break;n=i+1;continue}if(r==="'"||r==='"'||r==="`"){let i=ie(e,n);i&&(n=i.offset+i.excerpt.length-1);continue}let a=U(e,"import",n)?Ot(e,n):U(e,"export",n)?$t(e,n):void 0;a&&t.push(a)}return t}function _t(e,t){let n=[];for(let r of vt(e.content)){let a=r.value;if(!a.startsWith("."))continue;let i=e.content.slice(0,r.offset).split(`
6
- `).length,s={kind:"import",file:e.path,line:i,excerpt:r.excerpt},c=Nt(e.path,a,t);n.push({from:e.path,specifier:a,to:c?.path??null,resolution:c?"resolved":"unresolved",fromLayer:e.layer,toLayer:c?.layer??null,evidence:s})}return n}function Nt(e,t,n){let r=e.split("/");r.pop();for(let i of t.split("/"))i==="."||i===""||(i===".."?r.pop():r.push(i));let a=r.join("/");for(let i of[a,`${a}.ts`,`${a}.tsx`,`${a}.mts`,`${a}.cts`,`${a}/index.ts`,`${a}/index.tsx`]){let s=n.get(i);if(s)return s}}function Mt(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let a=v(t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});a&&n.push({ruleId:`layer-dependency:${a.from}->${a.to}`,message:a.message??`${a.from} must not depend on ${a.to}.`,edge:r,evidence:r.evidence})}return n}function xe(e){let t=e.files.map(s=>{let c=B(s.path);return{path:c,content:s.content,contentHash:O(s.content),layer:z(c,e.contract.config.layers)??null}}).sort((s,c)=>s.path.localeCompare(c.path)),n=new Map(t.map(s=>[s.path,s])),r=t.flatMap(s=>_t(s,n)),a=[],i=Mt(r,e.contract.config);return{ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:O(w(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(s=>s.name),edges:r,capabilityUses:a,violations:i}}}function Ge(e){let t=new Map(e.files.map(n=>[B(n.path),n]));for(let n of e.changes){let r=B(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return xe({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}function Dt(e){let t=`${e.evidence.file}:${e.evidence.line}`;if(!e.edge)return`${e.ruleId} at ${t}: ${e.message}`;let n=e.edge.to??e.edge.specifier;return`${e.ruleId} at ${t}: ${e.edge.from} imports ${n}. ${e.message}`}function Ue(e){let t=0,n=new Map,r=new Map,a=new Set,i=[],s=[],c=d=>{n.set(d,t),r.set(d,t),t+=1,i.push(d),a.add(d);for(let h of[...e.get(d)??[]].sort())e.has(h)&&(n.has(h)?a.has(h)&&r.set(d,Math.min(r.get(d)??0,n.get(h)??0)):(c(h),r.set(d,Math.min(r.get(d)??0,r.get(h)??0))));if(r.get(d)!==n.get(d))return;let u=[],g;do{if(g=i.pop(),g===void 0)break;a.delete(g),u.push(g)}while(g!==d);u.length>1&&s.push(u.sort())};for(let d of[...e.keys()].sort())n.has(d)||c(d);return s.sort((d,u)=>d[0].localeCompare(u[0])).map(d=>({ruleId:"CIRCULAR_DEPENDENCY",file:d[0],line:1,target:d.join(" \u2192 "),message:`Circular dependency among ${d.length} files: ${d.join(" \u2192 ")} \u2192 ${d[0]}.`,cycleKind:"value"}))}function Be(e){let t=e.contentViolations.map(i=>({...i})),n=(e.warnings??[]).map(i=>({...i})),r=new Map(e.files.map(i=>[i,new Set]));for(let i of e.edges){if(i.to&&i.to!==i.from&&!i.typeOnly&&r.has(i.from)&&r.get(i.from)?.add(i.to),!i.to||!i.toLayer)continue;let s=v(e.rules,i.fromLayer,i.toLayer,{fromPath:i.from,toPath:i.to,layers:e.config.layers});if(!s)continue;let c=!!s.peerIsolation;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:i.from,line:i.line,fromLayer:i.fromLayer,toLayer:i.toLayer,target:i.to,...i.typeOnly?{typeOnly:!0}:{},...i.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...i.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...i.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!c&&i.portProofEligible?{portProofEligible:!0}:{},...i.kind?{edgeKind:i.kind}:{},...c?{peerIsolation:!0}:{},message:s.message??(c?`${i.fromLayer} must not ${i.kind} another slice of ${i.toLayer} (${i.from} \u2192 ${i.to}). Extract shared code or use events/ports across slices.`:`${i.fromLayer} must not ${i.kind} ${i.toLayer}.`)})}let a=String(e.config.cyclePolicy??"strict").toLowerCase();if(a!=="off"){let i=Ue(r);a==="soft"||a==="framework-soft"?n.push(...i.map(s=>({...s,message:`${s.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...i)}return{violations:t,warnings:n,safety:e.safety}}function Ve(e){return O(w(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}function Tt(e){let t=xe(e),n=new Map(t.ir.files.map(o=>[o.path,o])),r=[],a=new Set,i=[];for(let o of e.changes){let l=o.path.replace(/\\/g,"/"),f=B(o.path);if(!f||f===".."||f.startsWith("../")||l.startsWith("/")||/^[A-Za-z]:\//.test(l)||l.includes("\0")){i.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(a.has(f)){i.push({ruleId:"DUPLICATE_CHANGE_PATH",file:f,line:1,message:`The atomic change set contains more than one operation for ${f}.`});continue}a.add(f),"delete"in o&&o.delete&&!n.has(f)&&i.push({ruleId:"DELETE_TARGET_MISSING",file:f,line:1,message:`Cannot delete ${f} because it is not present in the supplied base tree.`}),r.push("delete"in o&&o.delete?{path:f,delete:!0}:{path:f,content:"content"in o?o.content:""})}e.changes.length===0&&i.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let s=Ge({...e,changes:r}),c=new Map(s.ir.files.map(o=>[o.path,o])),d=Be({config:e.contract.config,rules:e.contract.config.rules,files:s.ir.files.map(o=>o.path),contentViolations:[],edges:s.ir.edges.filter(o=>!!o.fromLayer).map(o=>({from:o.from,fromLayer:o.fromLayer,...o.to?{to:o.to}:{},...o.toLayer?{toLayer:o.toLayer}:{},line:o.evidence.line,kind:"import"}))}),u=r.map(o=>{let l=B(o.path),f=n.get(l),y=c.get(l);return{path:l,operation:"delete"in o&&o.delete?"delete":f?"update":"create",...f?{beforeContentHash:f.contentHash}:{},...y?{candidateContentHash:y.contentHash}:{}}}).sort((o,l)=>o.path.localeCompare(l.path)),g=[...i,...d.violations].map(o=>({...o,nextAction:Fe(o)})),h=e.changeMap?re({changeMap:e.changeMap,changes:u,baseDependencies:t.ir.edges.flatMap(o=>o.to?[{from:o.from,to:o.to}]:[]),candidateDependencies:s.ir.edges.flatMap(o=>o.to?[{from:o.from,to:o.to}]:[])}):void 0;return{schemaVersion:"1.0",valid:g.length===0&&(h?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:s.ir.compilerOptionsHash,baseTreeHash:Ve(t.ir.files),candidateTreeHash:Ve(s.ir.files),...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...h?{convergence:h}:{},changes:u,violations:g,warnings:d.warnings}}function x(e,t,n={}){return{ruleId:e,message:t,...n}}function Ft(e){let{config:t,rules:n,files:r,manifest:a}=e,i=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(l=>typeof l!="string"))&&i.push(x("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","dynamicImportAllowlist must be an array of file globs.")),t.safety!==void 0&&(t.safety===null||typeof t.safety!="object"||Array.isArray(t.safety)))i.push(x("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let l of["maxTsSuppressions","maxAnyCasts"]){let f=t.safety[l];f!==void 0&&(!Number.isInteger(f)||f<0)&&i.push(x("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${l} must be a non-negative integer.`))}let s=Array.isArray(t.layers)?t.layers:[],c=Array.isArray(a?.architecture?.layers)?a.architecture.layers:[],d=new Set([...s.map(l=>l.name).filter(Boolean),...c.map(l=>l.name).filter(l=>!!l)]);s.length===0&&i.push(x("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let u=new Set,g=new Set;for(let l of s){if(!l.name){i.push(x("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}u.has(l.name)&&g.add(l.name),u.add(l.name),l.forbiddenGlobals!==void 0&&(!Array.isArray(l.forbiddenGlobals)||l.forbiddenGlobals.some(y=>typeof y!="string"))&&i.push(x("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${l.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:l.name}));let f=Array.isArray(l.patterns)?l.patterns:[];if(f.length===0){i.push(x("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${l.name}" has no file patterns and will never classify files.`,{layer:l.name}));continue}for(let y of f){let k;try{k=F(y)}catch(b){i.push(x("CONFIG_INVALID_LAYER_PATTERN",`Layer "${l.name}" has an invalid pattern "${y}": ${b instanceof Error?b.message:String(b)}`,{layer:l.name,pattern:y}));continue}!r.some(b=>k.test(b))&&!l.optional&&i.push(x("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${l.name}" pattern "${y}" matched no included files.`,{layer:l.name,pattern:y,failsStrict:!1}))}}for(let l of g)i.push(x("CONFIG_DUPLICATE_LAYER",`Layer "${l}" is configured more than once.`,{layer:l}));if(d.size>0)for(let l of n??[])l.from&&!d.has(l.from)&&i.push(x("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${l.from}".`,{fromLayer:l.from,toLayer:l.to})),l.to&&!d.has(l.to)&&i.push(x("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${l.to}".`,{fromLayer:l.from,toLayer:l.to}));let h=new Set;if(s.length>1)for(let l of r){let f=-1,y=[];for(let k of s)for(let b of k.patterns??[]){if(!F(b).test(l))continue;let p=ce(b);p>f?(f=p,y=[k.name]):p===f&&!y.includes(k.name)&&y.push(k.name)}y.length>1&&h.add([...y].sort().join(" + "))}h.size>0&&i.push(x("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...h].join(", ")}.`,{pairs:[...h]}));let o=r.filter(l=>!z(l,s));return o.length>0&&i.push(x("CONFIG_UNCLASSIFIED_FILES",`${o.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:o.length,samples:o.slice(0,5)})),i}export{he as ANALYSIS_IR_SCHEMA_VERSION,We as ARK_ANALYSIS_RESULT_SCHEMA,ze as ARK_ANALYSIS_RESULT_SCHEMA_VERSION,ge as ARK_CONFIG_SCHEMA,gt as ARK_CONFIG_SCHEMA_VERSION,kt as POLICY_DELTA_SCHEMA_VERSION,re as analyzeArchitectureConvergence,Ge as analyzeChange,Rt as analyzePolicyDelta,xe as analyzeProject,me as classifyArkPolicyDelta,Ft as collectAnalysisConfigWarnings,Y as collectForbiddenCapabilityUses,ve as createAICodeGate,Ye as createAdapterResult,ee as createArchitectureProfile,De as createArchitectureProfileFromArkConfig,Te as createElevenLayerArkConfig,Ue as detectArchitectureCycles,O as deterministicHash,X as elevenLayerProfile,Be as evaluateArchitectureGraph,Dt as explainViolation,q as extractSemanticDependencies,Q as loadArkConfigContract,Ce as loadContract,ye as parseArkConfigJson,Ae as policyDeltaAcknowledgementMatches,Tt as preflightChange,w as stableSerialize,oe as toAdapterDiagnostic,Ke as version};
4
+ `)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function je(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ce(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function D(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function wt(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function Z(e,t,n,r,i){if(t.$ref){let a=wt(t.$ref,r);if(!a){i.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}Z(e,a,n,r,i);return}if(t.const!==void 0&&!Object.is(e,t.const)){i.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(a=>Object.is(a,e))){i.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!je(e)){i.push({path:n,message:`must be an object; received ${D(e)}`});return}let a=t.properties??{};for(let s of t.required??[])e[s]===void 0&&i.push({path:Ce(n,s),message:"is required"});if(t.additionalProperties===!1)for(let s of Object.keys(e))s in a||i.push({path:Ce(n,s),message:"unknown field"});for(let[s,c]of Object.entries(a))e[s]!==void 0&&Z(e[s],c,Ce(n,s),r,i);return}if(t.type==="array"){if(!Array.isArray(e)){i.push({path:n,message:`must be an array; received ${D(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&i.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let a=e.map(s=>JSON.stringify(s));new Set(a).size!==a.length&&i.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((a,s)=>Z(a,t.items,`${n}[${s}]`,r,i));return}if(t.type==="string"){if(typeof e!="string"){i.push({path:n,message:`must be a string; received ${D(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&i.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&i.push({path:n,message:`must be a boolean; received ${D(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){i.push({path:n,message:`must be an integer; received ${D(e)}`});return}t.minimum!==void 0&&e<t.minimum&&i.push({path:n,message:`must be at least ${t.minimum}`})}}function Lt(e){return{...e,$schema:e.$schema===void 0?Q:e.$schema,schemaVersion:e.schemaVersion===void 0?"1.0":e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?X.map(t=>({...t})):e.rules}}function Pt(e,t="ark.config.json"){if(!je(e))throw new F(t,[{path:"$",message:`must be an object; received ${D(e)}`}]);let n=e.schemaVersion===void 0?"unversioned":null;if(e.schemaVersion!==void 0&&e.schemaVersion!=="1.0")throw new F(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.0`}]);return{candidate:Lt(e),migratedFrom:n}}function ee(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=Pt(e,t),i=[];if(Z(n,be,"$",be,i),i.length>0)throw new F(t,i);return{config:n,migratedFrom:r}}function Ie(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new F(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return ee(n,t)}function Ve(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:Q,schemaVersion:"1.0"};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}function Rt(e){return e.endsWith(".")?e:`${e}.`}function Ot(e,t){let n=e.prefixes.length?Math.max(...e.prefixes.map(i=>i.length)):0;return(t.prefixes.length?Math.max(...t.prefixes.map(i=>i.length)):0)-n}function ne(e){let t=e.layers.map(i=>({...i,prefixes:i.prefixes.map(Rt)})),n=[...t].sort(Ot),r=[...e.rules??[]];return{name:e.name,layers:t,rules:r,resolveLayer(i){return t.find(a=>a.match?.(i))?.name??n.find(a=>a.prefixes.some(s=>i.startsWith(s)))?.name}}}function He(e,t={}){return ne({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,r)=>({name:n.name,prefixes:n.intentPrefixes??[],description:n.description,order:r+1})),rules:e.rules??[]})}var $t=[{name:"DomainModel",prefixes:["Domain"],description:"Rich domain model, business rules, and domain events.",order:1},{name:"ApplicationOrchestration",prefixes:["Application"],description:"Use cases and command orchestration.",order:2},{name:"PersistenceAdapters",prefixes:["Adapter.Persistence","Adapter.Repository"],description:"Database, repository, and storage adapters.",order:3},{name:"IntegrationAdapters",prefixes:["Adapter.Integration","Adapter.External"],description:"External systems, APIs, and integration adapters.",order:4},{name:"WorkflowSagaEngine",prefixes:["Workflow"],description:"Sagas, workflows, and long-running processes.",order:5},{name:"BackgroundJobsScheduling",prefixes:["Job"],description:"Background jobs, scheduled work, and async processors.",order:6},{name:"PresentationAdapters",prefixes:["Presentation","Adapter.Presentation","Adapter.Api"],description:"API, UI, controller, and presentation adapters.",order:7},{name:"ReportingReadModels",prefixes:["Reporting"],description:"Read models, projections, and reporting surfaces.",order:8},{name:"ExtensibilityMetadata",prefixes:["Metadata"],description:"Metadata, extensions, and schema contracts.",order:9},{name:"SecurityAuditObservability",prefixes:["Security","Audit","Observability"],description:"Security, audit, and observability concerns.",order:10},{name:"Kernel",prefixes:["Kernel"],description:"Ark-owned governance and kernel signals.",order:11}],te=ne({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:$t,rules:X.map(e=>({...e}))}),vt={DomainModel:["domain"],ApplicationOrchestration:["application","app"],PersistenceAdapters:["adapters/persistence","adapters/repository","repositories","infra/persistence"],IntegrationAdapters:["adapters/integration","adapters/external","integrations"],WorkflowSagaEngine:["workflows","sagas"],BackgroundJobsScheduling:["jobs","schedules"],PresentationAdapters:["presentation","adapters/presentation","adapters/api"],ReportingReadModels:["reporting","read-models","projections"],ExtensibilityMetadata:["metadata","extensions"],SecurityAuditObservability:["security","audit","observability"],Kernel:["kernel"]};function Ge(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return Ve({include:e.include??[t],layers:te.layers.map(i=>({name:i.name,patterns:(vt[i.name]??[i.name]).map(a=>`${r}${a}/**`),intentPrefixes:i.prefixes,optional:n})),rules:[...te.rules]})}var xe="1.0";function P(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}function w(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(w).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${w(t[n])}`).join(",")}}`}function x(e){return`${e.from}->${e.to}`}function q(e,t,n,r="dependency"){return{id:`${e}:${r}:${x(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${x(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${x(t)}, then preflight again.`}:e==="unplanned"?{nextAction:`Remove the unplanned dependency ${x(t)} from the candidate, then preflight again.`}:{}}}function re(e){let t=[],n=new Map(e.changeMap.map.files.map(o=>[o.path,o])),r=new Map(e.changes.map(o=>[o.path,o])),i=new Map(e.changeMap.map.dependencies.map(o=>[x(o),o])),a=new Map(e.baseDependencies.map(o=>[x(o),o])),s=new Map(e.candidateDependencies.map(o=>[x(o),o]));for(let o of[...n.values()].sort((l,f)=>l.path.localeCompare(f.path))){let l=r.get(o.path);l?l.operation!==o.operation?t.push({id:`contradictory:file:${o.path}`,classification:"contradictory",subject:"file",path:o.path,expectedOperation:o.operation,actualOperation:l.operation,message:`${o.path} was planned as ${o.operation} but the actual operation is ${l.operation}.`,nextAction:`Change ${o.path} to the planned ${o.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${o.path}`,classification:"satisfied",subject:"file",path:o.path,expectedOperation:o.operation,actualOperation:l.operation,message:`${o.path} matches the planned ${o.operation} operation.`}):t.push({id:`missing:file:${o.path}`,classification:"missing",subject:"file",path:o.path,expectedOperation:o.operation,message:`${o.path} was planned as ${o.operation} but is absent from the actual change.`,nextAction:`${o.operation[0].toUpperCase()}${o.operation.slice(1)} ${o.path} in the complete change set, then preflight again.`})}for(let o of[...r.values()].sort((l,f)=>l.path.localeCompare(f.path)))n.has(o.path)||t.push({id:`unplanned:file:${o.path}`,classification:"unplanned",subject:"file",path:o.path,actualOperation:o.operation,message:`${o.path} has an unplanned ${o.operation} operation.`,nextAction:`Remove ${o.path} from the change set, then preflight again.`});let c=new Set;for(let o of[...i.values()].sort((l,f)=>x(l).localeCompare(x(f)))){if(s.has(x(o))){t.push(q("satisfied",o,`${o.from} -> ${o.to} exists in the candidate architecture.`));continue}let l={from:o.to,to:o.from};s.has(x(l))?(c.add(x(l)),t.push(q("contradictory",o,`${o.from} -> ${o.to} was planned, but the candidate contains the reverse edge.`))):t.push(q("missing",o,`${o.from} -> ${o.to} is absent from the candidate architecture.`))}let p=new Set([...n.keys(),...r.keys()]);for(let[o,l]of[...s].sort(([f],[g])=>f.localeCompare(g)))a.has(o)||i.has(o)||c.has(o)||!p.has(l.from)&&!p.has(l.to)||t.push({...q("unplanned",l,`${l.from} -> ${l.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let u=new Set(e.changeMap.map.files.filter(o=>o.operation==="delete").map(o=>o.path));for(let[o,l]of[...a].sort(([f],[g])=>f.localeCompare(g)))s.has(o)||u.has(l.from)||u.has(l.to)||!p.has(l.from)&&!p.has(l.to)||t.push({...q("unplanned",l,`${l.from} -> ${l.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let y={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((o,l)=>y[o.classification]-y[l.classification]||(o.subject===l.subject?0:o.subject==="file"?-1:1)||o.id.localeCompare(l.id));let m={satisfied:t.filter(o=>o.classification==="satisfied").length,missing:t.filter(o=>o.classification==="missing").length,contradictory:t.filter(o=>o.classification==="contradictory").length,unplanned:t.filter(o=>o.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:m.missing===0&&m.contradictory===0&&m.unplanned===0,behavioralCompletion:"not-evaluated",summary:m,findings:t}}var _t=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),Nt=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Ue=Object.freeze(Object.keys(Nt).sort()),Se=Object.freeze({fs:"filesystem","node:fs":"filesystem","fs/promises":"filesystem","node:fs/promises":"filesystem","fs-extra":"filesystem","graceful-fs":"filesystem",memfs:"filesystem",chokidar:"filesystem",http:"network",https:"network",http2:"network",net:"network",tls:"network",dgram:"network",dns:"network","node:http":"network","node:https":"network","node:http2":"network","node:net":"network","node:tls":"network","node:dgram":"network","node:dns":"network",axios:"network",undici:"network","node-fetch":"network",got:"network",ky:"network",superagent:"network",ws:"network",process:"process","node:process":"process",child_process:"process","node:child_process":"process","@prisma/client":"persistence",prisma:"persistence",pg:"persistence",mysql:"persistence",mysql2:"persistence",mongodb:"persistence",mongoose:"persistence",sqlite3:"persistence","better-sqlite3":"persistence",redis:"persistence",ioredis:"persistence",typeorm:"persistence",knex:"persistence","drizzle-orm":"persistence",sequelize:"persistence",kysely:"persistence","@supabase/supabase-js":"persistence"});function ie(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=Se[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),i=Se[r];if(i)return i;let a=e.indexOf("/",n+1);return a<0?null:Se[e.slice(0,a)]??null}var Tt="1.0";function C(e,t){e.push({id:`${t.classification}:${t.path}:${t.kind}`,path:t.path,classification:t.classification,message:t.message,...t.classification==="weakening"||t.classification==="judgment-required"?{nextAction:`Restore the previous protection at ${t.path}, then run ArkGate again.`}:{},...t.before===void 0?{}:{before:t.before},...t.after===void 0?{}:{after:t.after}})}function S(e){return[...new Set(e??[])].sort()}function j(e,t,n,r,i){let a=S(n),s=S(r),c=new Set(a),p=new Set(s),u=s.filter(m=>!c.has(m)),y=a.filter(m=>!p.has(m));u.length===0&&y.length===0||(u.length>0&&C(e,{kind:"added",path:t,classification:i.added,message:i.addedMessage,before:a,after:s}),y.length>0&&C(e,{kind:"removed",path:t,classification:i.removed,message:i.removedMessage,before:a,after:s}))}function ae(e,t,n,r,i,a,s){if(n===r)return;C(e,{kind:r?"enabled":"disabled",path:t,classification:r?i:i==="strengthening"?"weakening":"strengthening",message:r?a:s,before:n,after:r})}function oe(e,t){let n=new Map,r=new Set;for(let i of e){let a=t(i);n.has(a)?r.add(a):n.set(a,i)}return{values:n,duplicates:[...r].sort()}}function Dt(e,t,n){let r=oe(t,a=>a.name),i=oe(n,a=>a.name);(r.duplicates.length>0||i.duplicates.length>0)&&C(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:r.duplicates,after:i.duplicates});for(let a of[...new Set([...r.values.keys(),...i.values.keys()])].sort()){let s=r.values.get(a),c=i.values.get(a),p=`$.layers[${a}]`;if(!s&&c){C(e,{kind:"layer-added",path:p,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:c});continue}if(s&&!c){C(e,{kind:"layer-removed",path:p,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:s});continue}!s||!c||(j(e,`${p}.patterns`,s.patterns,c.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),j(e,`${p}.exclude`,s.exclude,c.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."}),j(e,`${p}.forbiddenGlobals`,s.forbiddenGlobals,c.forbiddenGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),S(s.intentPrefixes).join("\0")!==S(c.intentPrefixes).join("\0")&&C(e,{kind:"intent-prefixes-changed",path:`${p}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:S(s.intentPrefixes),after:S(c.intentPrefixes)}),ae(e,`${p}.mayImportInfrastructure`,s.mayImportInfrastructure===!0,c.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),ae(e,`${p}.optional`,s.optional===!0,c.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active."))}}function Ft(e,t,n){let r=s=>`${s.from}->${s.to}`,i=oe(t,r),a=oe(n,r);(i.duplicates.length>0||a.duplicates.length>0)&&C(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:i.duplicates,after:a.duplicates});for(let s of[...new Set([...i.values.keys(),...a.values.keys()])].sort()){let c=i.values.get(s),p=a.values.get(s),u=`$.rules[${s}]`;if(!c&&p){p.allowed===!1&&C(e,{kind:"deny-added",path:u,classification:"strengthening",message:"A denied dependency edge was added.",after:p});continue}if(c&&!p){c.allowed===!1&&C(e,{kind:"deny-removed",path:u,classification:"weakening",message:"A denied dependency edge was removed.",before:c});continue}if(!c||!p)continue;c.allowed!==p.allowed&&C(e,{kind:p.allowed?"deny-disabled":"deny-enabled",path:`${u}.allowed`,classification:p.allowed?"weakening":"strengthening",message:p.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:c.allowed,after:p.allowed});let y=c.peerIsolation===!0,m=p.peerIsolation===!0;if(y!==m){let o=c.from===c.to&&p.from===p.to;C(e,{kind:m?"peer-isolation-enabled":"peer-isolation-disabled",path:`${u}.peerIsolation`,classification:o?m?"strengthening":"weakening":"judgment-required",message:o?m?"Cross-slice dependencies inside this layer are now denied.":"Cross-slice dependencies inside this layer are no longer denied.":"Changing peer isolation on a cross-layer edge changes the denial scope.",before:y,after:m})}S(c.sliceFolders).join("\0")!==S(p.sliceFolders).join("\0")&&C(e,{kind:"slice-folders-changed",path:`${u}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:S(c.sliceFolders),after:S(p.sliceFolders)})}}function jt(e,t,n){let r=t.safety??{},i=n.safety??{};for(let a of["maxTsSuppressions","maxAnyCasts"]){let s=r[a]??0,c=i[a]??0;s!==c&&C(e,{kind:c>s?"threshold-raised":"threshold-lowered",path:`$.safety.${a}`,classification:c>s?"weakening":"strengthening",message:c>s?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:s,after:c})}for(let a of["allowInMemory","allowDisabledPeerIsolation"])ae(e,`$.safety.${a}`,r[a]===!0,i[a]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}function Vt(e){return e.some(t=>t.classification==="weakening")?"weakening":e.some(t=>t.classification==="judgment-required")?"judgment-required":e.some(t=>t.classification==="strengthening")?"strengthening":"neutral"}function ke(e,t){let n=[];j(n,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),j(n,"$.exclude",e.exclude,t.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional project paths are excluded from governance.",removedMessage:"Fewer project paths are excluded from governance."}),j(n,"$.dynamicImportAllowlist",e.dynamicImportAllowlist,t.dynamicImportAllowlist,{added:"weakening",removed:"strengthening",addedMessage:"Additional files may use non-literal dynamic imports.",removedMessage:"Fewer files may use non-literal dynamic imports."}),ae(n,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let r={off:0,soft:1,"framework-soft":1,strict:2},i=e.cyclePolicy??"strict",a=t.cyclePolicy??"strict";if(i!==a){let s=r[a]===r[i]?"judgment-required":r[a]>r[i]?"strengthening":"weakening";C(n,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:s,message:"The cycle enforcement level changed.",before:i,after:a})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&C(n,{kind:"framework-overlay-changed",path:"$.frameworkOverlay",classification:"judgment-required",message:"The framework overlay changed and may alter effective layer matching.",before:e.frameworkOverlay??null,after:t.frameworkOverlay??null}),Dt(n,e.layers,t.layers),Ft(n,e.rules,t.rules),jt(n,e,t),n.sort((s,c)=>s.path.localeCompare(c.path)||s.id.localeCompare(c.id)),{schemaVersion:"1.0",classification:Vt(n),findings:n}}function Ee(e,t){if(!e||e.schemaVersion!=="1.0"||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(i=>typeof i!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=S(e.findingIds),r=S(t.findingIds);return n.length===r.length&&n.every((i,a)=>i===r[a])}function _(e){let t=[];for(let n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."&&t.length>0&&t.at(-1)!==".."?t.pop():t.push(n));return t.join("/")}function ze(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}function V(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}function se(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let r=t,i="";for(t+=1;t<e.length;t+=1){let a=e[t];if(a===n)return{value:i,offset:r,excerpt:e.slice(r,t+1)};a==="\\"&&t+1<e.length?(i+=e[t+1],t+=1):i+=a}}function R(e,t,n){return e.startsWith(t,n)&&!ze(e[n-1])&&!ze(e[n+t.length])}function Ht(e,t){if(t=V(e,t+6),e[t]==="(")return se(e,V(e,t+1));let n=!1;if(R(e,"type",t)){let i=V(e,t+4);e[i]!==","&&!R(e,"from",i)&&(n=!0)}let r=Be(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}function Gt(e,t){t=t+6;let n=V(e,t),r=!1;if(R(e,"type",n)){let a=V(e,n+4);(e[a]==="{"||e[a]==="*")&&(r=!0)}let i=Be(e,t,!1);return i&&r?{...i,typeOnly:!0}:i}function Be(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(R(e,"from",t))return se(e,V(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return se(e,t);if(t>0&&(R(e,"import",t)||R(e,"export",t)))return}}function Ut(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="/"&&e[n+1]==="/"){if(n=e.indexOf(`
5
+ `,n+2),n<0)break;continue}if(r==="/"&&e[n+1]==="*"){let a=e.indexOf("*/",n+2);if(a<0)break;n=a+1;continue}if(r==="'"||r==='"'||r==="`"){let a=se(e,n);a&&(n=a.offset+a.excerpt.length-1);continue}let i=R(e,"import",n)?Ht(e,n):R(e,"export",n)?Gt(e,n):void 0;i&&t.push(i)}return t}function Ke(e,t){let n=[],r=[];for(let i of Ut(e.content)){let a=i.value;if(!a.startsWith(".")){if(i.typeOnly)continue;let u=ie(a);if(!u)continue;let y=e.content.slice(0,i.offset).split(`
6
+ `).length;r.push({file:e.path,symbol:a,capability:u,evidence:{kind:"import",file:e.path,line:y,excerpt:i.excerpt}});continue}let s=e.content.slice(0,i.offset).split(`
7
+ `).length,c={kind:"import",file:e.path,line:s,excerpt:i.excerpt},p=zt(e.path,a,t);n.push({from:e.path,specifier:a,to:p?.path??null,resolution:p?"resolved":"unresolved",fromLayer:e.layer,toLayer:p?.layer??null,evidence:c})}return{edges:n,capabilityUses:r}}function zt(e,t,n){let r=e.split("/");r.pop();for(let a of t.split("/"))a==="."||a===""||(a===".."?r.pop():r.push(a));let i=r.join("/");for(let a of[i,`${i}.ts`,`${i}.tsx`,`${i}.mts`,`${i}.cts`,`${i}/index.ts`,`${i}/index.tsx`]){let s=n.get(a);if(s)return s}}function Ye(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let i=$(t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});i&&n.push({ruleId:`layer-dependency:${i.from}->${i.to}`,message:i.message??`${i.from} must not depend on ${i.to}.`,edge:r,evidence:r.evidence})}return n}function ce(e,t){let n=typeof e=="string"?Ie(e,t):ee(e,t);return{...n,policyHash:P(w(n.config))}}function qe(e){let t=ce(e.baseConfig,e.baseSource??"base ark.config.json"),n=ce(e.candidateConfig,e.candidateSource??"candidate ark.config.json"),r=ke(t.config,n.config),i=r.findings.filter(c=>c.classification==="weakening"||c.classification==="judgment-required").map(c=>c.id).sort(),a=i.length>0,s=a&&Ee(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:i});return{schemaVersion:r.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:r.classification,findings:r.findings,blockingFindingIds:i,requiresAcknowledgement:a,acknowledged:s,valid:!a||s}}function W(e){let t=e.files.map(s=>{let c=_(s.path);return{path:c,content:s.content,contentHash:P(s.content),layer:G(c,e.contract.config.layers)??null}}).sort((s,c)=>s.path.localeCompare(c.path)),n=new Map(t.map(s=>[s.path,s])),r=[],i=[];for(let s of t){let c=Ke(s,n);r.push(...c.edges),i.push(...c.capabilityUses)}let a=Ye(r,e.contract.config);return{ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:P(w(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(s=>s.name),edges:r,capabilityUses:i,violations:a}}}function le(e){let t=new Map(e.files.map(n=>[_(n.path),n]));for(let n of e.changes){let r=_(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return W({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}function We(e){let t=`${e.evidence.file}:${e.evidence.line}`;if(!e.edge)return`${e.ruleId} at ${t}: ${e.message}`;let n=e.edge.to??e.edge.specifier;return`${e.ruleId} at ${t}: ${e.edge.from} imports ${n}. ${e.message}`}function we(e){let t=0,n=new Map,r=new Map,i=new Set,a=[],s=[],c=p=>{n.set(p,t),r.set(p,t),t+=1,a.push(p),i.add(p);for(let m of[...e.get(p)??[]].sort())e.has(m)&&(n.has(m)?i.has(m)&&r.set(p,Math.min(r.get(p)??0,n.get(m)??0)):(c(m),r.set(p,Math.min(r.get(p)??0,r.get(m)??0))));if(r.get(p)!==n.get(p))return;let u=[],y;do{if(y=a.pop(),y===void 0)break;i.delete(y),u.push(y)}while(y!==p);u.length>1&&s.push(u.sort())};for(let p of[...e.keys()].sort())n.has(p)||c(p);return s.sort((p,u)=>p[0].localeCompare(u[0])).map(p=>({ruleId:"CIRCULAR_DEPENDENCY",file:p[0],line:1,target:p.join(" \u2192 "),message:`Circular dependency among ${p.length} files: ${p.join(" \u2192 ")} \u2192 ${p[0]}.`,cycleKind:"value"}))}function pe(e){let t=e.contentViolations.map(a=>({...a})),n=(e.warnings??[]).map(a=>({...a})),r=new Map(e.files.map(a=>[a,new Set]));for(let a of e.edges){if(a.to&&a.to!==a.from&&!a.typeOnly&&r.has(a.from)&&r.get(a.from)?.add(a.to),!a.to||!a.toLayer)continue;let s=$(e.rules,a.fromLayer,a.toLayer,{fromPath:a.from,toPath:a.to,layers:e.config.layers});if(!s)continue;let c=!!s.peerIsolation;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:a.from,line:a.line,fromLayer:a.fromLayer,toLayer:a.toLayer,target:a.to,...a.typeOnly?{typeOnly:!0}:{},...a.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...a.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...a.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!c&&a.portProofEligible?{portProofEligible:!0}:{},...a.kind?{edgeKind:a.kind}:{},...c?{peerIsolation:!0}:{},message:s.message??(c?`${a.fromLayer} must not ${a.kind} another slice of ${a.toLayer} (${a.from} \u2192 ${a.to}). Extract shared code or use events/ports across slices.`:`${a.fromLayer} must not ${a.kind} ${a.toLayer}.`)})}let i=String(e.config.cyclePolicy??"strict").toLowerCase();if(i!=="off"){let a=we(r);i==="soft"||i==="framework-soft"?n.push(...a.map(s=>({...s,message:`${s.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...a)}return{violations:t,warnings:n,safety:e.safety}}function Je(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return e.typeOnly||e.targetTypeOnlyExports||e.namedBindingsTypeOnly?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":e.peerIsolation?"Extract the shared dependency to a shared layer, then preflight again.":`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, then preflight again.`;case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";default:return`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}function Ze(e){return P(w(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}function Qe(e){let t=W(e),n=new Map(t.ir.files.map(o=>[o.path,o])),r=[],i=new Set,a=[];for(let o of e.changes){let l=o.path.replace(/\\/g,"/"),f=_(o.path);if(!f||f===".."||f.startsWith("../")||l.startsWith("/")||/^[A-Za-z]:\//.test(l)||l.includes("\0")){a.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(i.has(f)){a.push({ruleId:"DUPLICATE_CHANGE_PATH",file:f,line:1,message:`The atomic change set contains more than one operation for ${f}.`});continue}i.add(f),"delete"in o&&o.delete&&!n.has(f)&&a.push({ruleId:"DELETE_TARGET_MISSING",file:f,line:1,message:`Cannot delete ${f} because it is not present in the supplied base tree.`}),r.push("delete"in o&&o.delete?{path:f,delete:!0}:{path:f,content:"content"in o?o.content:""})}e.changes.length===0&&a.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let s=le({...e,changes:r}),c=new Map(s.ir.files.map(o=>[o.path,o])),p=pe({config:e.contract.config,rules:e.contract.config.rules,files:s.ir.files.map(o=>o.path),contentViolations:[],edges:s.ir.edges.filter(o=>!!o.fromLayer).map(o=>({from:o.from,fromLayer:o.fromLayer,...o.to?{to:o.to}:{},...o.toLayer?{toLayer:o.toLayer}:{},line:o.evidence.line,kind:"import"}))}),u=r.map(o=>{let l=_(o.path),f=n.get(l),g=c.get(l);return{path:l,operation:"delete"in o&&o.delete?"delete":f?"update":"create",...f?{beforeContentHash:f.contentHash}:{},...g?{candidateContentHash:g.contentHash}:{}}}).sort((o,l)=>o.path.localeCompare(l.path)),y=[...a,...p.violations].map(o=>({...o,nextAction:Je(o)})),m=e.changeMap?re({changeMap:e.changeMap,changes:u,baseDependencies:t.ir.edges.flatMap(o=>o.to?[{from:o.from,to:o.to}]:[]),candidateDependencies:s.ir.edges.flatMap(o=>o.to?[{from:o.from,to:o.to}]:[])}):void 0;return{schemaVersion:"1.0",valid:y.length===0&&(m?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:s.ir.compilerOptionsHash,baseTreeHash:Ze(t.ir.files),candidateTreeHash:Ze(s.ir.files),...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...m?{convergence:m}:{},changes:u,violations:y,warnings:p.warnings}}function I(e,t,n={}){return{ruleId:e,message:t,...n}}function Xe(e){let{config:t,rules:n,files:r,manifest:i}=e,a=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(l=>typeof l!="string"))&&a.push(I("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","dynamicImportAllowlist must be an array of file globs.")),t.safety!==void 0&&(t.safety===null||typeof t.safety!="object"||Array.isArray(t.safety)))a.push(I("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let l of["maxTsSuppressions","maxAnyCasts"]){let f=t.safety[l];f!==void 0&&(!Number.isInteger(f)||f<0)&&a.push(I("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${l} must be a non-negative integer.`))}let s=Array.isArray(t.layers)?t.layers:[],c=Array.isArray(i?.architecture?.layers)?i.architecture.layers:[],p=new Set([...s.map(l=>l.name).filter(Boolean),...c.map(l=>l.name).filter(l=>!!l)]);s.length===0&&a.push(I("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let u=new Set,y=new Set;for(let l of s){if(!l.name){a.push(I("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}u.has(l.name)&&y.add(l.name),u.add(l.name),l.forbiddenGlobals!==void 0&&(!Array.isArray(l.forbiddenGlobals)||l.forbiddenGlobals.some(g=>typeof g!="string"))&&a.push(I("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${l.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:l.name}));let f=Array.isArray(l.patterns)?l.patterns:[];if(f.length===0){a.push(I("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${l.name}" has no file patterns and will never classify files.`,{layer:l.name}));continue}for(let g of f){let k;try{k=H(g)}catch(b){a.push(I("CONFIG_INVALID_LAYER_PATTERN",`Layer "${l.name}" has an invalid pattern "${g}": ${b instanceof Error?b.message:String(b)}`,{layer:l.name,pattern:g}));continue}!r.some(b=>k.test(b))&&!l.optional&&a.push(I("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${l.name}" pattern "${g}" matched no included files.`,{layer:l.name,pattern:g,failsStrict:!1}))}}for(let l of y)a.push(I("CONFIG_DUPLICATE_LAYER",`Layer "${l}" is configured more than once.`,{layer:l}));if(p.size>0)for(let l of n??[])l.from&&!p.has(l.from)&&a.push(I("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${l.from}".`,{fromLayer:l.from,toLayer:l.to})),l.to&&!p.has(l.to)&&a.push(I("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${l.to}".`,{fromLayer:l.from,toLayer:l.to}));let m=new Set;if(s.length>1)for(let l of r){let f=-1,g=[];for(let k of s)for(let b of k.patterns??[]){if(!H(b).test(l))continue;let d=ye(b);d>f?(f=d,g=[k.name]):d===f&&!g.includes(k.name)&&g.push(k.name)}g.length>1&&m.add([...g].sort().join(" + "))}m.size>0&&a.push(I("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...m].join(", ")}.`,{pairs:[...m]}));let o=r.filter(l=>!G(l,s));return o.length>0&&a.push(I("CONFIG_UNCLASSIFIED_FILES",`${o.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:o.length,samples:o.slice(0,5)})),a}export{xe as ANALYSIS_IR_SCHEMA_VERSION,it as ARK_ANALYSIS_RESULT_SCHEMA,tt as ARK_ANALYSIS_RESULT_SCHEMA_VERSION,be as ARK_CONFIG_SCHEMA,St as ARK_CONFIG_SCHEMA_VERSION,Tt as POLICY_DELTA_SCHEMA_VERSION,re as analyzeArchitectureConvergence,le as analyzeChange,qe as analyzePolicyDelta,W as analyzeProject,ke as classifyArkPolicyDelta,Xe as collectAnalysisConfigWarnings,z as collectForbiddenCapabilityUses,De as createAICodeGate,rt as createAdapterResult,ne as createArchitectureProfile,He as createArchitectureProfileFromArkConfig,Ge as createElevenLayerArkConfig,we as detectArchitectureCycles,P as deterministicHash,te as elevenLayerProfile,pe as evaluateArchitectureGraph,We as explainViolation,U as extractSemanticDependencies,ee as loadArkConfigContract,ce as loadContract,Ie as parseArkConfigJson,Ee as policyDeltaAcknowledgementMatches,Qe as preflightChange,w as stableSerialize,fe as toAdapterDiagnostic,et as version};
@@ -3,7 +3,9 @@
3
3
  **ArkGate** (`arkgate`) — architecture co-pilot for AI TypeScript. This guide describes how AI
4
4
  agents and codegen tools safely interact with write hooks, advisory MCP tools, CI, and `/ark-*`
5
5
  skills. Guarantees differ by host; start with the
6
- [canonical host support matrix](../README.md#host-enforcement-support).
6
+ [canonical host support matrix](../README.md#host-enforcement-support). The advisory-local /
7
+ hard-CI split is a deliberate trade-off, not a gap: local hooks and MCP coach at write time,
8
+ while a required merge status is the one boundary a repository can make every write path share.
7
9
 
8
10
  CLI names: prefer **`arkgate` / `arkgate-check` / `arkgate-mcp`**; aliases `ark` / `ark-check` /
9
11
  `ark-mcp` still work for one major. TypeScript **5.x / 6.x / 7.x** as the project compiler:
@@ -57,7 +59,8 @@ MCP `ark_recommend` and the `/ark-architect` skill.
57
59
  ### Terminal onboarding (Phase B)
58
60
 
59
61
  ```bash
60
- npx ark start --yes # preferred: shape → compact contract → active host → CI → plan
62
+ npx ark start --yes # preferred read-only preview: shape → contract → host → CI
63
+ npx ark start --yes --apply # apply exactly the previewed compact setup
61
64
  npx ark init --archetype crud-product --yes # non-interactive: shape → preset → origin → gates
62
65
  npx ark init # TTY wizard: pick application shape (1–8), not a framework
63
66
  npx ark-check --doctor # includes "New here?" when coverage is low or config is fresh
@@ -66,8 +69,8 @@ npx ark-check --watch # debounced re-check when govern
66
69
  ```
67
70
 
68
71
  **Day-zero origin (2.12+):** `ark init` freezes `.ark/reports/origin.*` before writing agent
69
- docs or CI templates. Compact `ark start` keeps first-run setup under five project files and
70
- 25 KB;
72
+ docs or CI templates. Compact `ark start` previews first and keeps the applied setup under five
73
+ project files and 25 KB;
71
74
  run `ark-check --report ark-report.html` explicitly when you want to establish an origin/evolution
72
75
  baseline. Do not `--reset-origin` unless the user explicitly wants a new baseline.
73
76
 
@@ -116,6 +119,31 @@ Smell **ids** (stable JSON) plus **outcome** lines (plain language, Q02) on each
116
119
  | `mixed-pattern-cluster` | Several layout styles — pick one golden pattern + pilot |
117
120
  | `soft-contract` | Layers without deny rules — add real walls, not soft green |
118
121
 
122
+ **Contract health (W01):** doctor JSON also carries `contractHealth` — a meta-lint of the
123
+ contract itself (never of the code): `contract-bidirectional-allow` (both directions explicitly
124
+ allowed between two layers), `contract-peripheral-depends-core` (audit/observability layer allowed
125
+ into orchestration/persistence), `contract-lateral-adapter-allow` (adapter layer allowed into a
126
+ sibling adapter layer), `contract-dead-rule` (rule references an empty or unknown layer, or is a
127
+ same-layer no-op; `optional: true` layers are exempt). Advisory only: it never changes the
128
+ verdict, `designFitness`, or `patternBets` — layer roles come from name heuristics, so treat a
129
+ miss as a warning to read, not a defect to silence. A deliberate edge is acknowledged in
130
+ `.ark/contract-smell-acks.json` (`{ acks: [{ id, edge, reason }] }`); `acknowledged` counts
131
+ applied acks only, and a malformed sidecar or edge string suppresses nothing.
132
+
133
+ **Effect capabilities (U03, evidence-only):** the analysis IR reports typed capability uses for
134
+ seven closed ids (`network`, `filesystem`, `clock`, `randomness`, `environment`, `process`,
135
+ `persistence`). `collectCapabilityUses(ts, sourceFile)` is the symbol-aware collector (ambient
136
+ globals + imports, one scanner — shadowing/type-only/`globalThis` handled); `ir.capabilityUses`
137
+ carries the import-based subset the pure engine can prove from content alone. Direct evidence
138
+ only; nothing blocks on capabilities until a layer opts into a wall (U04). Vocabulary and
139
+ lowering: `src/domain/capabilities.ts` / ADR 0009.
140
+
141
+ **Governance weight (W02):** `contractHealth.governanceWeight` reports raw facts (layers, rules,
142
+ governed files, files/layer, rules/layer) plus a fixed band (`heavy` / `typical` / `light` /
143
+ `unknown`) with fixed wording. It is explicitly `notAScore` — never a gate input. Read `heavy` as
144
+ "justify the next layer/rule with demonstrated pressure", never as "delete layers"; read `light`
145
+ as "a boundary may be missing where violations concentrate".
146
+
119
147
  Each smell also has `evidence[]` paths and `message` (technical detail). Plan **B** bets include
120
148
  `pilot`, `successSignal`, `killSwitch`, and **`neverMechanicalSafe: true`** — loop/autoPatch must
121
149
  ignore them. For judgment I/O moves use **extraction cards**
package/docs/ai-gates.md CHANGED
@@ -5,34 +5,29 @@ On Claude Code and Grok Build, an installed and trusted PreToolUse hook can bloc
5
5
  before they land on disk. Cursor and OpenAI Codex use advisory MCP validation at write time; CI is
6
6
  their hard repository check. Codex 0.123+ dispatches hooks for its native `apply_patch` handler,
7
7
  but Code Mode hosts can execute deferred nested writes without that project hook event. See the
8
- [canonical host support matrix](../README.md#host-enforcement-support) before installing.
8
+ [canonical host support matrix](../README.md#host-enforcement-support) before installing. The
9
+ advisory-local / hard-CI split is a deliberate trade-off: local surfaces optimize feedback speed,
10
+ while a required merge status is the one boundary a repository can make every write path share.
9
11
 
10
12
  Everything below uses the same `ark.config.json` as `arkgate-check` / `ark-check` (CI) — one
11
13
  contract shared by every surface. Generate it once:
12
14
 
13
15
  ```bash
14
16
  npx arkgate-check --init
15
- # aliases: ark-check, ark init, arkgate start
17
+ # aliases: ark-check --init, ark init
16
18
  ```
17
19
 
18
20
  For guided setup with prompts, use:
19
21
 
20
22
  ```bash
21
- npx arkgate start
23
+ npx arkgate start # read-only preview
24
+ npx arkgate start --apply # apply exactly the previewed setup
22
25
  # or: npx ark init
23
26
  ```
24
27
 
25
- `ark start` asks for the active agent on a TTY (or detects it otherwise) and applies a compact
26
- router setup: at most five project files and no `package.json` change unless you pass `--install`.
27
- Use `--tools <host>` to select the host explicitly. The broader command below remains the explicit
28
- way to install the full per-host `/ark-*` skill inventory.
29
-
30
- For non-interactive defaults, use:
31
-
32
- ```bash
33
- npx arkgate start --yes
34
- # or: npx ark init --yes
35
- ```
28
+ `ark start` detects one active host and previews a compact setup (≤5 files / 25 KB). Nothing is
29
+ written until `--apply`, which rejects stale inputs. Select a host with `--tools <host>`; use the
30
+ broader installer below only for the full `/ark-*` inventory.
36
31
 
37
32
  You can also generate only the starter gate files for common agent runtimes and CI:
38
33
 
@@ -32,7 +32,7 @@ Add to the top of `src/domain/order.ts`:
32
32
  import { createInMemoryOrderRepository } from '../adapters/persistence/in-memory-order-repository.js';
33
33
  ```
34
34
 
35
- ### 3. Run the CI gate (same stimulus as the write-gate hook)
35
+ ### 3. Run the CI gate (same architecture contract as the write-gate hook)
36
36
 
37
37
  ```bash
38
38
  npm run check
@@ -71,4 +71,4 @@ Expected:
71
71
  - The fix is a file move or port inversion — not editing `ark.config.json`.
72
72
 
73
73
  See also: [Break it on purpose](../../examples/hexagonal-order-api/README.md#break-it-on-purpose)
74
- for two more exercises.
74
+ for two more exercises.
@@ -32,12 +32,14 @@ aliases `ark` / `ark-check` still work).
32
32
  | **Reference** | [Commands and artifacts](reference-commands.md) | `--recommend`, `--write-plan`, `ark-adoption-plan.json`, fix-class JSON |
33
33
  | **Explanation** | [Why application shape matters](explanation-application-shape.md) | Understand shapes vs frameworks and progressive phases |
34
34
 
35
- ## Public demos (Phase D)
35
+ ## Public demos
36
36
 
37
37
  Reproducible scripts — no video required:
38
38
 
39
39
  - [Write-gate self-correction](../demos/01-write-gate-self-correction.md)
40
40
  - [Brownfield baseline adoption](../demos/02-brownfield-baseline-adoption.md)
41
+ - [Co-pilot autopilot, end to end](../demos/03-copilot-autopilot.md)
42
+
41
43
  ## Gallery starters
42
44
 
43
45
  | Archetype | Directory |
@@ -46,6 +48,8 @@ Reproducible scripts — no video required:
46
48
  | `api-backend` | [examples/api-backend-starter](../../examples/api-backend-starter/) |
47
49
  | `worker-pipeline` | [examples/worker-pipeline-starter](../../examples/worker-pipeline-starter/) |
48
50
  | `multi-app-workspace` | [examples/multi-app-workspace-starter](../../examples/multi-app-workspace-starter/) |
51
+ | `vertical-slice-product` | [examples/vertical-slice-starter](../../examples/vertical-slice-starter/) |
52
+ | `ddd-bounded-contexts` | [examples/ddd-context-starter](../../examples/ddd-context-starter/) |
49
53
 
50
54
  Deep teaching example (runnable API + break exercises): [hexagonal-order-api](../../examples/hexagonal-order-api/).
51
55
 
@@ -21,7 +21,7 @@ Installs:
21
21
  |------|-------------|
22
22
  | Claude Code | `.claude/settings.json`, `.claude/skills/` |
23
23
  | Cursor | `.cursor/mcp.json`, `.cursor/rules/ark.mdc`, `.cursor/commands/` |
24
- | Codex | `docs/ark-codex-config.toml` + home MCP/prompts |
24
+ | Codex | `.codex/hooks.json`, `.agents/skills/`; MCP in `$CODEX_HOME/config.toml` |
25
25
  | **Grok Build** | `.grok/config.toml`, `.grok/hooks/`, `.grok/skills/` |
26
26
 
27
27
  See the [canonical host support matrix](../../README.md#host-enforcement-support) for the exact
@@ -42,10 +42,8 @@ npx arkgate-check --doctor
42
42
  npx arkgate-check --require-gates
43
43
  ```
44
44
 
45
- Doctor JSON (`--doctor --json`) includes **`writePath`**: the active host's supported profile,
46
- installed evidence, and whether PreToolUse is
47
- `repair` (machine-readable autoPatch on deny), `reject-only`, `mcp-only`, or
48
- `none` — plus `prepareWrite` / `autoPatch` booleans for leads.
45
+ Doctor JSON includes `writePath.mode` plus `enforcementLadder`: support, installation, observed
46
+ evidence, covered operations, bypassability, and CI honesty. MCP registration stays advisory.
49
47
 
50
48
  After upgrading the package, refresh skills so agents see the latest plan kinds:
51
49
 
@@ -15,6 +15,9 @@ Available packs:
15
15
  - `enthusiast-layered`
16
16
  - `enthusiast-feature-sliced`
17
17
  - `enthusiast-monorepo`
18
+ - `enthusiast-ui-surface`
19
+ - `enthusiast-vertical-slice`
20
+ - `enthusiast-ddd-bounded-contexts`
18
21
 
19
22
  ## Apply
20
23
 
@@ -34,4 +37,4 @@ Monorepo packs detect workspace roots from `package.json` / `pnpm-workspace.yaml
34
37
  | Application shape (todo app, API, …) | `ark-check --recommend` → `ark init --archetype` |
35
38
  | Preset name only | `--apply-policy-pack enthusiast-<preset>` |
36
39
 
37
- `ark-adoption-plan.json` from `--write-plan` includes a suggested `policyPack` id matching the recommended preset.
40
+ `ark-adoption-plan.json` from `--write-plan` includes a suggested `policyPack` id matching the recommended preset.
@@ -16,6 +16,8 @@ Authoritative source: `templates/architecture-playbook.json` (shipped in the npm
16
16
  | `integration-bridge` | System glue | `hexagonal` |
17
17
  | `multi-app-workspace` | Monorepo | `monorepo` |
18
18
  | `prototype-spike` | Quick experiment | `layered` |
19
+ | `vertical-slice-product` | Feature-first product | `vertical-slice` |
20
+ | `ddd-bounded-contexts` | Multiple business domains | `ddd-bounded-contexts` |
19
21
 
20
22
  ## Named presets
21
23
 
@@ -25,6 +27,9 @@ Authoritative source: `templates/architecture-playbook.json` (shipped in the npm
25
27
  | `layered` | `enthusiast-layered` |
26
28
  | `feature-sliced` | `enthusiast-feature-sliced` |
27
29
  | `monorepo` | `enthusiast-monorepo` |
30
+ | `ui-surface` | `enthusiast-ui-surface` |
31
+ | `vertical-slice` | `enthusiast-vertical-slice` |
32
+ | `ddd-bounded-contexts` | `enthusiast-ddd-bounded-contexts` |
28
33
 
29
34
  ## Gallery mapping
30
35
 
@@ -33,4 +38,6 @@ Authoritative source: `templates/architecture-playbook.json` (shipped in the npm
33
38
  | `crud-product` | `examples/crud-product-starter/` |
34
39
  | `api-backend` | `examples/api-backend-starter/` |
35
40
  | `worker-pipeline` | `examples/worker-pipeline-starter/` |
36
- | `multi-app-workspace` | `examples/multi-app-workspace-starter/` |
41
+ | `multi-app-workspace` | `examples/multi-app-workspace-starter/` |
42
+ | `vertical-slice-product` | `examples/vertical-slice-starter/` |
43
+ | `ddd-bounded-contexts` | `examples/ddd-context-starter/` |
@@ -37,16 +37,22 @@ Pack metadata: `templates/policy-packs/enthusiast-*.json`.
37
37
  ## Init and verify
38
38
 
39
39
  ```bash
40
- arkgate start --yes # guided setup + plan
40
+ arkgate start --yes # read-only setup preview with non-interactive defaults
41
+ arkgate start --yes --apply # apply exactly that preview
41
42
  ark init --archetype <id> --yes # alias path
42
43
  arkgate-check --doctor [--json]
43
44
  arkgate-check --coverage [--json]
44
45
  arkgate-check --plan [--json] # mechanical-safe vs judgment vs deferred
45
46
  arkgate-check --strict-config
47
+ arkgate-check --strict-merge
48
+ arkgate preflight --changes changes.json [--change-map map.json] --json
46
49
  arkgate-check --report out.html --beginner
47
50
  arkgate-check --watch
48
51
  ```
49
52
 
53
+ In 3.1+, strict merge protects policy changes; preflight checks one complete batch without writing
54
+ (`--change-map` adds structural convergence). MCP: `ark_policy_delta`, `ark_prepare_change`.
55
+
50
56
  ## Plan classes (`--plan --json`)
51
57
 
52
58
  | `class` | Agent may auto-apply? | Examples (`remediationKind`) |
@@ -62,4 +68,4 @@ When present on violations:
62
68
  - `fixClass` — e.g. `port-inversion`, `file-move`
63
69
  - `effort` — `small` | `medium`
64
70
  - `enthusiastHint` — plain English fix guidance
65
- - plan enrichment: `class`, `remediationKind`, `typeOnly`, `sourcePureTypeModule`, `targetTypeOnlyExports`, `namedBindingsTypeOnly`
71
+ - plan enrichment: `class`, `remediationKind`, `typeOnly`, `sourcePureTypeModule`, `targetTypeOnlyExports`, `namedBindingsTypeOnly`
@@ -23,6 +23,9 @@ hardening guide remains repository-hosted rather than duplicated in the gate tar
23
23
  | **Plan pattern B (P03+)** | `ark-check --plan --json` → `plan.patternBets[]`, `plan.goal.designWeak` | Additive. Each bet: `id`, `smellId`, `pilot`, `evidence`, `successSignal`, `killSwitch`, **`neverMechanicalSafe: true`**, `class: "judgment"`. **Never** auto-applied by loop/autoPatch; not a `remediationKind` mechanical-safe. `goal.met` remains edge honesty only. |
24
24
  | **Pilot loop (Q04)** | `plan.pilotLoop` / `doctor.pilotLoop` | Additive. When design-weak: `active`, `oneAtATime`, `neverMechanicalSafe`, **`nextPilot`** extraction-card fields (`pilotTarget`, `smellId`, `move`, `successSignal`, `killSwitch`, `doNot[]`). **One pilot → re-doctor**; never multi-pilot batch; never mechanical-safe. |
25
25
  | **AI-velocity eval (Q05)** | `npm run eval:ai-velocity` → `eval/ai-velocity-report.json` | Fixture-measured (no live LLM). Same feature scenario on design-weak vs golden-path arms; metric **`placementTurns`** (agent-equivalent). Golden must be strictly better. Method string lives next to the number. Does not weaken the gate. |
26
+ | **Contract health (W01)** | `ark-check --doctor --json` → `doctor.contractHealth`; optional `.ark/contract-smell-acks.json` | Additive, **advisory only** — meta-lint of the contract itself (layer-name heuristics; imprecision costs a warning line, never a verdict); never changes the verdict, `designFitness`, or `patternBets`. Stable smell ids: `contract-bidirectional-allow`, `contract-peripheral-depends-core`, `contract-lateral-adapter-allow`, `contract-dead-rule`; each smell has `severity`, `evidence[]` (sorted, honest `…(+N more)` truncation), `fix`, `message`, plain-language `outcome`, and `acknowledgedEdges` (acks applied to that id). Acknowledgments live in the bounded sidecar (`{ acks: [{ id, edge, reason }] }`, ≤64 KB / ≤200 entries; bidirectional edges order-insensitive, exact two segments); `contractHealth.acknowledged` counts **applied** acks only (stale acks count 0). **Absent is normal**; malformed file or edge grammar → ignored + `ackFile.invalid` where applicable, never silent suppression. |
27
+ | **Effect capabilities (U03)** | Analysis API `collectCapabilityUses(ts, sourceFile)` + Domain vocabulary (`CAPABILITY_IDS`, `capabilityForModuleSpecifier`, `capabilityForAmbientName`, `lowerForbiddenGlobal`); pure-engine `ir.capabilityUses` | Additive within IR `1.0`. Seven **closed** ids: `network`, `filesystem`, `clock`, `randomness`, `environment`, `process`, `persistence` (ADR 0009). Direct evidence only — transitive inference never detects. The symbol-aware collector covers ambient globals (shadowing/type-only/globalThis-alias precision from the S05/C04 machinery) plus imports; the compiler-free IR engine carries **import-based** uses only (exact module or subpath match, never substring; textual `import type`/`export type` erasure — ANY braced named-binding list stays a value import there, and template-literal bodies are scanned like the rest of the file; the symbol path owns that precision). **Evidence only in U03: no verdict, wall, or gate reads these until U04's opt-in policy.** |
28
+ | **Governance weight (W02)** | `ark-check --doctor --json` → `doctor.contractHealth.governanceWeight` | Additive, **advisory only** — raw facts (`declaredLayers`, `populatedLayers`, `governedFiles`, `rules`, `deniedEdges`, `allowedEdges`, `filesPerLayer`, `rulesPerLayer`) plus a fixed comparative band `weight: heavy | typical | light | unknown` and its fixed `note`. Fixed deterministic thresholds: **heavy** = fewer than 25 governed files per declared layer AND (6+ layers OR 4+ well-formed rules per layer); **light** = at most 2 layers over 150+ governed files; **unknown** = no layers or no governed files; everything else is **typical** (banding uses raw ratios; the reported ratios are rounded for display). `notAScore: true` is explicit: never a composite score, ranking, or gate input; the heavy note asks to justify NEW layers/rules and never suggests deleting working ones. Human doctor prints a line only for `heavy`/`light`. |
26
29
  | **MCP tools** | `arkgate-mcp` / `ark://…` resources | Tool names and primary argument shapes are stable within a major. |
27
30
  | **`ark.config.json`** | Layer globs, rules, include/exclude, forbiddenGlobals, intent prefixes, `peerIsolation`, `dynamicImportAllowlist`, `safety` thresholds | Versioned by `schemaVersion`; unknown fields fail closed and migrations preserve the previous supported major. |
28
31
  | **Policy transition analysis (T01, 3.1.0)** | `analyzePolicyDelta(...)`; MCP `ark_policy_delta`; CLI `--policy-base` / `--policy-base-ref` / `--policy-ack`; check JSON `policyDelta` | Additive schema `1.0`. Classifications and finding ids are deterministic. Weakening/judgment requires an acknowledgement bound to both policy hashes and the exact blocking finding set. |
@@ -91,5 +94,6 @@ production deployment would need to satisfy; it is not a readiness certification
91
94
 
92
95
  ## Release notes (maintainers)
93
96
 
94
- Ship notes for a version live under [releases/](./releases/) (e.g. [2.12.0.md](./releases/2.12.0.md)).
97
+ Ship notes for a version live under [releases/](./releases/) (latest:
98
+ [3.3.0.md](./releases/3.3.0.md)).
95
99
  Publish path: signed annotated tag → GitHub Release → `publish-npm.yml` (see [CONTRIBUTING.md](../CONTRIBUTING.md)).
@@ -1,4 +1,4 @@
1
- # Threat model — ArkGate (Q9)
1
+ # Threat model — ArkGate
2
2
 
3
3
  **Scope:** architecture write/CI gates, agent hooks/MCP, and the experimental optional runtime.
4
4
  **Not in scope:** full org identity platforms, browser XSS in consumer apps, or npm registry
@@ -54,7 +54,8 @@ npm publish <-- signed tag --- GitHub Release + provenance
54
54
  ## Residual risk (accepted)
55
55
 
56
56
  - Branch protection is **external GitHub state** — doctor reports honestly when unavailable.
57
- - Full external adoption matrix (Q4) and independent ≥95 audit (Q10) are separate exit gates.
57
+ - External adoption and independent-audit evidence are release snapshots bound to pinned commits;
58
+ they do not prove every repository layout or future host version.
58
59
  - Live multi-agent loop-cost remains optional (`ARK_EVAL_LOOP_LIVE`).
59
60
 
60
61
  ## Verification hooks