arkgate 3.9.1 → 3.9.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +38 -0
- package/README.md +5 -4
- package/bin/lib/ambient-state.mjs +64 -8
- package/bin/lib/doctor-advisories.mjs +8 -4
- package/bin/lib/doctor-plan.mjs +47 -13
- package/bin/lib/enforcement-honesty.mjs +225 -0
- package/bin/lib/graph-blind.mjs +235 -0
- package/bin/lib/html-report-advisories.mjs +5 -3
- package/bin/lib/pilot-loop.mjs +19 -0
- package/bin/lib/post-green-path.mjs +22 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/docs/README.md +2 -2
- package/docs/package-surface.md +3 -3
- package/package.json +1 -1
- package/server.json +3 -3
- package/templates/skills/ark-coverage.md +7 -0
- package/templates/skills/ark-explore.md +4 -1
- package/templates/skills/ark-place.md +4 -0
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var jt="3.9.1";var Gt="1.3";function I(e){return typeof e=="string"&&e.length>0?e:void 0}function ct(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function Ut(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==="CAPABILITY_VIOLATION"?`Define a ${I(n.capability)??"capability"} port in ${t.fromLayer??"the walled layer"}, bind the implementation outside it, 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 He(e,t="error"){let n=I(e.ruleId)??I(e.code)??"ARK_UNKNOWN",s=e.severity==="warning"?"warning":t,r={...I(e.target)?{target:I(e.target)}:{},...I(e.fromLayer)?{fromLayer:I(e.fromLayer)}:{},...I(e.toLayer)?{toLayer:I(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{},...typeof e.targetTypeOnlyExports=="boolean"?{targetTypeOnlyExports:e.targetTypeOnlyExports}:{},...typeof e.sourcePureTypeModule=="boolean"?{sourcePureTypeModule:e.sourcePureTypeModule}:{},...typeof e.namedBindingsTypeOnly=="boolean"?{namedBindingsTypeOnly:e.namedBindingsTypeOnly}:{},...typeof e.portProofEligible=="boolean"?{portProofEligible:e.portProofEligible}:{},...typeof e.peerIsolation=="boolean"?{peerIsolation:e.peerIsolation}:{},...I(e.capability)?{capability:I(e.capability)}:{},...I(e.edgeKind)?{edgeKind:I(e.edgeKind)}:{}};return{ruleId:n,severity:s,message:I(e.message)??n,location:{file:I(e.file)??"<unknown>",line:ct(e.line,1),column:ct(e.column,1)},evidence:r,nextAction:I(e.nextAction)??Ut(n,r,e)}}function Bt(e){let t=e.completeness??"complete",n=e.mode??"lexical-compatibility";if(t==="complete"&&(e.completenessReasons?.length??0)>0)throw new Error("completenessReasons must be empty when completeness is complete.");let s=t==="complete"?[]:e.completenessReasons&&e.completenessReasons.length>0?e.completenessReasons.map(c=>({code:I(c.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:I(c.message)??`Analysis ${t}: required evidence is incomplete.`,...I(c.file)?{file:I(c.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],r={...I(e.policyHash)?{policyHash:I(e.policyHash)}:{},...I(e.resolverIdentity)?{resolverIdentity:I(e.resolverIdentity)}:{},...I(e.factsHash)?{factsHash:I(e.factsHash)}:{},...I(e.candidateTreeHash)?{candidateTreeHash:I(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let c of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!r[c])throw new Error(`${c} is required for resolved ${t} adapter evidence.`)}let i=[...(e.violations??[]).map(c=>He(c,"error")),...(e.warnings??[]).map(c=>He(c,"warning"))],a={schemaVersion:"1.3",completenessReasons:s,diagnostics:i};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...a,mode:n,valid:!1,completeness:t,...r};let c={policyHash:r.policyHash,resolverIdentity:r.resolverIdentity,factsHash:r.factsHash,candidateTreeHash:r.candidateTreeHash};return t==="complete"?{...a,mode:n,valid:e.valid,completeness:t,...c}:{...a,mode:n,valid:!1,completeness:t,...c}}return t==="complete"?{...a,mode:n,valid:e.valid,completeness:t,...r}:{...a,mode:n,valid:!1,completeness:t,...r}}var qt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","mode","valid","completeness","completenessReasons","diagnostics"],allOf:[{if:{properties:{completeness:{enum:["partial","unavailable"]}},required:["completeness"]},then:{properties:{valid:{const:!1}}}},{if:{properties:{mode:{const:"resolved-candidate-facts"},completeness:{enum:["complete","partial"]}},required:["mode","completeness"]},then:{required:["policyHash","resolverIdentity","factsHash","candidateTreeHash"]}},{if:{properties:{completeness:{const:"complete"}},required:["completeness"]},then:{properties:{completenessReasons:{maxItems:0}}},else:{properties:{completenessReasons:{minItems:1}}}}],properties:{schemaVersion:{const:"1.3"},mode:{enum:["lexical-compatibility","resolved-candidate-facts"]},valid:{type:"boolean"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:{type:"string",minLength:1},message:{type:"string",minLength:1},file:{type:"string",minLength:1}}}},policyHash:{type:"string",minLength:1},resolverIdentity:{type:"string",minLength:1},factsHash:{type:"string",minLength:1},candidateTreeHash:{type:"string",minLength:1},diagnostics:{type:"array",items:{type:"object",additionalProperties:!1,required:["ruleId","severity","message","location","evidence"],properties:{ruleId:{type:"string",minLength:1},severity:{enum:["error","warning"]},message:{type:"string",minLength:1},location:{type:"object",additionalProperties:!1,required:["file","line","column"],properties:{file:{type:"string",minLength:1},line:{type:"integer",minimum:1},column:{type:"integer",minimum:1}}},evidence:{type:"object",additionalProperties:!1,properties:{target:{type:"string"},fromLayer:{type:"string"},toLayer:{type:"string"},typeOnly:{type:"boolean"},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"},peerIsolation:{type:"boolean"},capability:{type:"string",minLength:1},edgeKind:{type:"string",minLength:1}}},nextAction:{type:"string",minLength:1}}}}}};var je=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),Ue=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Be=Object.freeze(Object.keys(Ue).sort()),Ve=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"}),Ge=Object.freeze({process:Object.freeze(["process","node:process"])});function pe(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=Ve[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let s=e.slice(0,n),r=Ve[s];if(r)return r;let i=e.indexOf("/",n+1);return i<0?null:Ve[e.slice(0,i)]??null}function V(e,t){for(let n of t)if(Ge[n]?.includes(e))return n;return null}function Re(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let s=t.slice(0,n).join("."),r=Ue[s];if(r)return r}return null}function X(e){if(e?.pure===!0)return[...je].sort();let n=(e?.capabilities?.deny??[]).filter(s=>je.includes(s));return[...new Set(n)].sort()}function fe(e,t){if(t.length===0)return!1;let n=new Set(t),s=e.split(".");for(let r=s.length;r>=1;r-=1)if(n.has(s.slice(0,r).join(".")))return!0;return!1}function ve(e){let t=new Set,n=new Set,s=Object.keys(Ue);for(let r of e?.forbiddenGlobals??[]){let i=s.filter(a=>a===r||a.startsWith(`${r}.`));if(i.length===0)n.add(r);else for(let a of i)t.add(`ambient:${a}`);for(let a of Ge[r]??[])t.add(`import-exact:${a}`)}for(let r of X(e)){if(t.add(`import:${r}`),r==="process")for(let i of Ge.process)t.add(`import-exact:${i}`);for(let i of s)Re(i)===r&&t.add(`ambient:${i}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}var dt=new Map;function pt(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function qe(e){let t="";for(let n=0;n<e.length;n+=1){let s=e[n];if(s==="\\"&&n+1<e.length){let r=e[n+1];if("*?{}[],".includes(r)||r==="\\"){t+="\\"+r,n+=1;continue}t+="/";continue}t+=s}return t}function zt(e){let t=0;for(let n=0;n<e.length;n+=1){let s=e[n];if(s==="\\"){n+=1;continue}if(s==="{")t+=1;else if(s==="}"&&(t-=1,t<0))return!1}return t===0}function K(e){let t=dt.get(e);if(t)return t;let n=qe(e),s=zt(n),r="",i=0;for(let c=0;c<n.length;c+=1){let f=n[c];f==="\\"&&c+1<n.length?(r+=pt(n[c+1]),c+=1):f==="*"?n[c+1]==="*"?n[c+2]==="/"?(r+="(?:.*/)?",c+=2):(r+=".*",c+=1):r+="[^/]*":f==="?"?r+="[^/]":f==="{"&&s?(r+="(?:",i+=1):f==="}"&&s&&i>0?(r+=")",i-=1):f===","&&s&&i>0?r+="|":r+=pt(f)}let a=new RegExp(`^${r}$`);return dt.set(e,a),a}function ze(e){let t=qe(String(e)),s=t.split("*")[0].split("/").filter(Boolean).length,r=t.replace(/\*/g,"").length;return s*1e4+r}function j(e,t){let n=String(e).split(/[/\\]/).join("/"),s,r=-1;for(let i of t??[])if(!(i.exclude??[]).some(a=>K(a).test(n))){for(let a of i.patterns??[])if(K(a).test(n)){let c=ze(a);c>r&&(r=c,s=i.name)}}return s}function ft(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),s=new Set(t.map(r=>String(r).toLowerCase()));for(let r=0;r<n.length-1;r+=1)if(s.has(n[r].toLowerCase()))return`${n[r].toLowerCase()}/${n[r+1].toLowerCase()}`}function Kt(e){let t=new Set;for(let n of e??[]){let r=qe(String(n)).split("/").filter(Boolean);for(let i=0;i<r.length;i+=1){let a=r[i];if((a==="**"||a==="*")&&i>0){let c=r[i-1];c&&!c.includes("*")&&!c.includes("{")&&!c.includes("}")&&t.add(c)}}}return[...t]}function Yt(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(r=>typeof r=="string"&&r.length>0);let s=(n??[]).find(r=>r.name===t);return Kt(s?.patterns)}function N(e,t,n,s){for(let r of e??[])if(!(r.from!==t||r.to!==n)&&r.allowed===!1){if(r.peerIsolation){let i=s?.fromPath,a=s?.toPath;if(!i||!a)return r;let c=Yt(r,t,s?.layers);if(c.length===0)return r;let f=ft(i,c),A=ft(a,c);if(!f||!A||f!==A)return r;continue}if(t!==n)return r}}function Q(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function mt(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function ut(e,t){if(e.isImportDeclaration(t)){let s=t.importClause;if(!s)return!1;if(s.isTypeOnly)return!0;let r=s.namedBindings;return!!(r&&e.isNamedImports(r)&&r.elements.length>0&&r.elements.every(i=>i.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(s=>s.isTypeOnly))}function gt(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},s=e.createCompilerHost(n,!0);return s.getSourceFile=r=>r===t.fileName?t:void 0,s.fileExists=r=>r===t.fileName,s.readFile=r=>r===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,s).getTypeChecker()}function Ke(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function Ye(e,t,n,s){let r=s.parent&&e.isShorthandPropertyAssignment(s.parent)&&s.parent.name===s,i;try{i=r?t.getShorthandAssignmentValueSymbol(s.parent):Ke(t,s)}catch{i=void 0}return!!i?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}function ee(e,t){let n,s=[],r=(a,c,f,A=!1)=>s.push({specifier:f,kind:c,line:mt(t,a),typeOnly:A,unresolved:f===void 0,node:a}),i=a=>{if(e.isImportDeclaration(a))r(a,"import",Q(e,a.moduleSpecifier),ut(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)r(a,"export",Q(e,a.moduleSpecifier),ut(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))r(a,"require",Q(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let c=a.expression.kind===e.SyntaxKind.ImportKeyword,A=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!Ye(e,n??(n=gt(e,t)),t,a.expression);(c||A)&&r(a,A?"require":"dynamic-import",Q(e,a.arguments[0]))}e.forEachChild(a,i)};return i(t),s}function Wt(e,t){let n=[],s=t;for(;e.isPropertyAccessExpression(s)||e.isElementAccessExpression(s);){if(e.isPropertyAccessExpression(s))n.unshift(s.name.text);else{let r=Q(e,s.argumentExpression);if(r===void 0)return;n.unshift(r)}s=s.expression}if(e.isIdentifier(s))return n.unshift(s.text),{root:s,segments:n}}function Jt(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 yt(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let s=n.length;s>=1;s-=1){let r=n.slice(0,s).join(".");if(e.has(r))return r}}function te(e,t,n){if(n.length===0)return[];let s=new Set(n),r=gt(e,t),i=new Map,a=new Set;for(let o of t.statements)if(e.isVariableStatement(o))for(let l of o.declarationList.declarations)e.isIdentifier(l.name)&&a.add(l.name.text);let c=o=>{let l=Wt(e,o);if(!l)return;let p=Ke(r,l.root),d=p?i.get(p):void 0;return d?[...d,...l.segments.slice(1)]:Ye(e,r,t,l.root)||a.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 p=c(l.initializer),d=Ke(r,l.name);!p||!d||i.set(d,p)}let f=[],A=new Set,g=(o,l)=>{let p=mt(t,l),d=`${o}:${l.getStart(t)}`;A.has(d)||(A.add(d),f.push({name:o,line:p,node:l}))},u=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 p=c(o),d=p?yt(s,p):void 0;d&&g(d,o)}else e.isIdentifier(o)&&s.has(o.text)&&Jt(e,o)&&!Ye(e,r,t,o)&&g(o.text,o);if(e.isVariableDeclaration(o)&&e.isObjectBindingPattern(o.name)&&o.initializer){let p=c(o.initializer);if(p)for(let d of o.name.elements){if(!e.isIdentifier(d.name))continue;let y=d.propertyName?Q(e,d.propertyName)??d.propertyName.text:d.name.text,h=yt(s,[...p,y]);h&&g(h,o.initializer)}}e.forEachChild(o,u)};return u(t),f}function We(e,t,n){let s=[];for(let r of n?.dependencies??ee(e,t)){if(r.typeOnly||!r.specifier)continue;let i=pe(r.specifier);i&&s.push({capability:i,symbol:r.specifier,line:r.line,source:"import-based"})}for(let r of n?.ambientUses??te(e,t,Be)){let i=Re(r.name);i&&s.push({capability:i,symbol:r.name,line:r.line,source:"ambient-global"})}return s.sort((r,i)=>r.line-i.line||r.capability.localeCompare(i.capability)||r.symbol.localeCompare(i.symbol))}var Je={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."},Ze=Object.freeze([{layer:"DomainModel",prefixes:["Domain."]},{layer:"ApplicationOrchestration",prefixes:["Application."]},{layer:"PersistenceAdapters",prefixes:["Adapter.Persistence.","Adapter.Repository."]},{layer:"IntegrationAdapters",prefixes:["Adapter.Integration.","Adapter.External."]},{layer:"WorkflowSagaEngine",prefixes:["Workflow."]},{layer:"BackgroundJobsScheduling",prefixes:["Job."]},{layer:"PresentationAdapters",prefixes:["Presentation.","Adapter.Presentation.","Adapter.Api."]},{layer:"ReportingReadModels",prefixes:["Reporting."]},{layer:"ExtensibilityMetadata",prefixes:["Metadata."]},{layer:"SecurityAuditObservability",prefixes:["Security.","Audit.","Observability."]},{layer:"Kernel",prefixes:["Kernel."]}]);function Xe(e,t){return t.flatMap((s,r)=>(s.prefixes??s.intentPrefixes??[]).map(i=>({layer:s.name,layerIndex:r,prefix:i.endsWith(".")?i:`${i}.`}))).filter(({prefix:s})=>e.startsWith(s)).sort((s,r)=>r.prefix.length-s.prefix.length||s.layerIndex-r.layerIndex)[0]?.layer}function Y(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function ue(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&Y(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:Je.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:Je.PUBLISH_MISSING_SOURCE}),t}function v(e,t,n){return{ruleId:e,code:e,message:t,...n}}function ne(e,t){return e.slice(0,t).split(`
|
|
1
|
+
var jt="3.9.2";var Gt="1.3";function I(e){return typeof e=="string"&&e.length>0?e:void 0}function ct(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function Ut(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==="CAPABILITY_VIOLATION"?`Define a ${I(n.capability)??"capability"} port in ${t.fromLayer??"the walled layer"}, bind the implementation outside it, 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 He(e,t="error"){let n=I(e.ruleId)??I(e.code)??"ARK_UNKNOWN",s=e.severity==="warning"?"warning":t,r={...I(e.target)?{target:I(e.target)}:{},...I(e.fromLayer)?{fromLayer:I(e.fromLayer)}:{},...I(e.toLayer)?{toLayer:I(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{},...typeof e.targetTypeOnlyExports=="boolean"?{targetTypeOnlyExports:e.targetTypeOnlyExports}:{},...typeof e.sourcePureTypeModule=="boolean"?{sourcePureTypeModule:e.sourcePureTypeModule}:{},...typeof e.namedBindingsTypeOnly=="boolean"?{namedBindingsTypeOnly:e.namedBindingsTypeOnly}:{},...typeof e.portProofEligible=="boolean"?{portProofEligible:e.portProofEligible}:{},...typeof e.peerIsolation=="boolean"?{peerIsolation:e.peerIsolation}:{},...I(e.capability)?{capability:I(e.capability)}:{},...I(e.edgeKind)?{edgeKind:I(e.edgeKind)}:{}};return{ruleId:n,severity:s,message:I(e.message)??n,location:{file:I(e.file)??"<unknown>",line:ct(e.line,1),column:ct(e.column,1)},evidence:r,nextAction:I(e.nextAction)??Ut(n,r,e)}}function Bt(e){let t=e.completeness??"complete",n=e.mode??"lexical-compatibility";if(t==="complete"&&(e.completenessReasons?.length??0)>0)throw new Error("completenessReasons must be empty when completeness is complete.");let s=t==="complete"?[]:e.completenessReasons&&e.completenessReasons.length>0?e.completenessReasons.map(c=>({code:I(c.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:I(c.message)??`Analysis ${t}: required evidence is incomplete.`,...I(c.file)?{file:I(c.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],r={...I(e.policyHash)?{policyHash:I(e.policyHash)}:{},...I(e.resolverIdentity)?{resolverIdentity:I(e.resolverIdentity)}:{},...I(e.factsHash)?{factsHash:I(e.factsHash)}:{},...I(e.candidateTreeHash)?{candidateTreeHash:I(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let c of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!r[c])throw new Error(`${c} is required for resolved ${t} adapter evidence.`)}let i=[...(e.violations??[]).map(c=>He(c,"error")),...(e.warnings??[]).map(c=>He(c,"warning"))],a={schemaVersion:"1.3",completenessReasons:s,diagnostics:i};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...a,mode:n,valid:!1,completeness:t,...r};let c={policyHash:r.policyHash,resolverIdentity:r.resolverIdentity,factsHash:r.factsHash,candidateTreeHash:r.candidateTreeHash};return t==="complete"?{...a,mode:n,valid:e.valid,completeness:t,...c}:{...a,mode:n,valid:!1,completeness:t,...c}}return t==="complete"?{...a,mode:n,valid:e.valid,completeness:t,...r}:{...a,mode:n,valid:!1,completeness:t,...r}}var qt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","mode","valid","completeness","completenessReasons","diagnostics"],allOf:[{if:{properties:{completeness:{enum:["partial","unavailable"]}},required:["completeness"]},then:{properties:{valid:{const:!1}}}},{if:{properties:{mode:{const:"resolved-candidate-facts"},completeness:{enum:["complete","partial"]}},required:["mode","completeness"]},then:{required:["policyHash","resolverIdentity","factsHash","candidateTreeHash"]}},{if:{properties:{completeness:{const:"complete"}},required:["completeness"]},then:{properties:{completenessReasons:{maxItems:0}}},else:{properties:{completenessReasons:{minItems:1}}}}],properties:{schemaVersion:{const:"1.3"},mode:{enum:["lexical-compatibility","resolved-candidate-facts"]},valid:{type:"boolean"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:{type:"string",minLength:1},message:{type:"string",minLength:1},file:{type:"string",minLength:1}}}},policyHash:{type:"string",minLength:1},resolverIdentity:{type:"string",minLength:1},factsHash:{type:"string",minLength:1},candidateTreeHash:{type:"string",minLength:1},diagnostics:{type:"array",items:{type:"object",additionalProperties:!1,required:["ruleId","severity","message","location","evidence"],properties:{ruleId:{type:"string",minLength:1},severity:{enum:["error","warning"]},message:{type:"string",minLength:1},location:{type:"object",additionalProperties:!1,required:["file","line","column"],properties:{file:{type:"string",minLength:1},line:{type:"integer",minimum:1},column:{type:"integer",minimum:1}}},evidence:{type:"object",additionalProperties:!1,properties:{target:{type:"string"},fromLayer:{type:"string"},toLayer:{type:"string"},typeOnly:{type:"boolean"},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"},peerIsolation:{type:"boolean"},capability:{type:"string",minLength:1},edgeKind:{type:"string",minLength:1}}},nextAction:{type:"string",minLength:1}}}}}};var je=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),Ue=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Be=Object.freeze(Object.keys(Ue).sort()),Ve=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"}),Ge=Object.freeze({process:Object.freeze(["process","node:process"])});function pe(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=Ve[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let s=e.slice(0,n),r=Ve[s];if(r)return r;let i=e.indexOf("/",n+1);return i<0?null:Ve[e.slice(0,i)]??null}function V(e,t){for(let n of t)if(Ge[n]?.includes(e))return n;return null}function Re(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let s=t.slice(0,n).join("."),r=Ue[s];if(r)return r}return null}function X(e){if(e?.pure===!0)return[...je].sort();let n=(e?.capabilities?.deny??[]).filter(s=>je.includes(s));return[...new Set(n)].sort()}function fe(e,t){if(t.length===0)return!1;let n=new Set(t),s=e.split(".");for(let r=s.length;r>=1;r-=1)if(n.has(s.slice(0,r).join(".")))return!0;return!1}function ve(e){let t=new Set,n=new Set,s=Object.keys(Ue);for(let r of e?.forbiddenGlobals??[]){let i=s.filter(a=>a===r||a.startsWith(`${r}.`));if(i.length===0)n.add(r);else for(let a of i)t.add(`ambient:${a}`);for(let a of Ge[r]??[])t.add(`import-exact:${a}`)}for(let r of X(e)){if(t.add(`import:${r}`),r==="process")for(let i of Ge.process)t.add(`import-exact:${i}`);for(let i of s)Re(i)===r&&t.add(`ambient:${i}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}var dt=new Map;function pt(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function qe(e){let t="";for(let n=0;n<e.length;n+=1){let s=e[n];if(s==="\\"&&n+1<e.length){let r=e[n+1];if("*?{}[],".includes(r)||r==="\\"){t+="\\"+r,n+=1;continue}t+="/";continue}t+=s}return t}function zt(e){let t=0;for(let n=0;n<e.length;n+=1){let s=e[n];if(s==="\\"){n+=1;continue}if(s==="{")t+=1;else if(s==="}"&&(t-=1,t<0))return!1}return t===0}function K(e){let t=dt.get(e);if(t)return t;let n=qe(e),s=zt(n),r="",i=0;for(let c=0;c<n.length;c+=1){let f=n[c];f==="\\"&&c+1<n.length?(r+=pt(n[c+1]),c+=1):f==="*"?n[c+1]==="*"?n[c+2]==="/"?(r+="(?:.*/)?",c+=2):(r+=".*",c+=1):r+="[^/]*":f==="?"?r+="[^/]":f==="{"&&s?(r+="(?:",i+=1):f==="}"&&s&&i>0?(r+=")",i-=1):f===","&&s&&i>0?r+="|":r+=pt(f)}let a=new RegExp(`^${r}$`);return dt.set(e,a),a}function ze(e){let t=qe(String(e)),s=t.split("*")[0].split("/").filter(Boolean).length,r=t.replace(/\*/g,"").length;return s*1e4+r}function j(e,t){let n=String(e).split(/[/\\]/).join("/"),s,r=-1;for(let i of t??[])if(!(i.exclude??[]).some(a=>K(a).test(n))){for(let a of i.patterns??[])if(K(a).test(n)){let c=ze(a);c>r&&(r=c,s=i.name)}}return s}function ft(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),s=new Set(t.map(r=>String(r).toLowerCase()));for(let r=0;r<n.length-1;r+=1)if(s.has(n[r].toLowerCase()))return`${n[r].toLowerCase()}/${n[r+1].toLowerCase()}`}function Kt(e){let t=new Set;for(let n of e??[]){let r=qe(String(n)).split("/").filter(Boolean);for(let i=0;i<r.length;i+=1){let a=r[i];if((a==="**"||a==="*")&&i>0){let c=r[i-1];c&&!c.includes("*")&&!c.includes("{")&&!c.includes("}")&&t.add(c)}}}return[...t]}function Yt(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(r=>typeof r=="string"&&r.length>0);let s=(n??[]).find(r=>r.name===t);return Kt(s?.patterns)}function N(e,t,n,s){for(let r of e??[])if(!(r.from!==t||r.to!==n)&&r.allowed===!1){if(r.peerIsolation){let i=s?.fromPath,a=s?.toPath;if(!i||!a)return r;let c=Yt(r,t,s?.layers);if(c.length===0)return r;let f=ft(i,c),A=ft(a,c);if(!f||!A||f!==A)return r;continue}if(t!==n)return r}}function Q(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function mt(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function ut(e,t){if(e.isImportDeclaration(t)){let s=t.importClause;if(!s)return!1;if(s.isTypeOnly)return!0;let r=s.namedBindings;return!!(r&&e.isNamedImports(r)&&r.elements.length>0&&r.elements.every(i=>i.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(s=>s.isTypeOnly))}function gt(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},s=e.createCompilerHost(n,!0);return s.getSourceFile=r=>r===t.fileName?t:void 0,s.fileExists=r=>r===t.fileName,s.readFile=r=>r===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,s).getTypeChecker()}function Ke(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function Ye(e,t,n,s){let r=s.parent&&e.isShorthandPropertyAssignment(s.parent)&&s.parent.name===s,i;try{i=r?t.getShorthandAssignmentValueSymbol(s.parent):Ke(t,s)}catch{i=void 0}return!!i?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}function ee(e,t){let n,s=[],r=(a,c,f,A=!1)=>s.push({specifier:f,kind:c,line:mt(t,a),typeOnly:A,unresolved:f===void 0,node:a}),i=a=>{if(e.isImportDeclaration(a))r(a,"import",Q(e,a.moduleSpecifier),ut(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)r(a,"export",Q(e,a.moduleSpecifier),ut(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))r(a,"require",Q(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let c=a.expression.kind===e.SyntaxKind.ImportKeyword,A=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!Ye(e,n??(n=gt(e,t)),t,a.expression);(c||A)&&r(a,A?"require":"dynamic-import",Q(e,a.arguments[0]))}e.forEachChild(a,i)};return i(t),s}function Wt(e,t){let n=[],s=t;for(;e.isPropertyAccessExpression(s)||e.isElementAccessExpression(s);){if(e.isPropertyAccessExpression(s))n.unshift(s.name.text);else{let r=Q(e,s.argumentExpression);if(r===void 0)return;n.unshift(r)}s=s.expression}if(e.isIdentifier(s))return n.unshift(s.text),{root:s,segments:n}}function Jt(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 yt(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let s=n.length;s>=1;s-=1){let r=n.slice(0,s).join(".");if(e.has(r))return r}}function te(e,t,n){if(n.length===0)return[];let s=new Set(n),r=gt(e,t),i=new Map,a=new Set;for(let o of t.statements)if(e.isVariableStatement(o))for(let l of o.declarationList.declarations)e.isIdentifier(l.name)&&a.add(l.name.text);let c=o=>{let l=Wt(e,o);if(!l)return;let p=Ke(r,l.root),d=p?i.get(p):void 0;return d?[...d,...l.segments.slice(1)]:Ye(e,r,t,l.root)||a.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 p=c(l.initializer),d=Ke(r,l.name);!p||!d||i.set(d,p)}let f=[],A=new Set,g=(o,l)=>{let p=mt(t,l),d=`${o}:${l.getStart(t)}`;A.has(d)||(A.add(d),f.push({name:o,line:p,node:l}))},u=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 p=c(o),d=p?yt(s,p):void 0;d&&g(d,o)}else e.isIdentifier(o)&&s.has(o.text)&&Jt(e,o)&&!Ye(e,r,t,o)&&g(o.text,o);if(e.isVariableDeclaration(o)&&e.isObjectBindingPattern(o.name)&&o.initializer){let p=c(o.initializer);if(p)for(let d of o.name.elements){if(!e.isIdentifier(d.name))continue;let y=d.propertyName?Q(e,d.propertyName)??d.propertyName.text:d.name.text,h=yt(s,[...p,y]);h&&g(h,o.initializer)}}e.forEachChild(o,u)};return u(t),f}function We(e,t,n){let s=[];for(let r of n?.dependencies??ee(e,t)){if(r.typeOnly||!r.specifier)continue;let i=pe(r.specifier);i&&s.push({capability:i,symbol:r.specifier,line:r.line,source:"import-based"})}for(let r of n?.ambientUses??te(e,t,Be)){let i=Re(r.name);i&&s.push({capability:i,symbol:r.name,line:r.line,source:"ambient-global"})}return s.sort((r,i)=>r.line-i.line||r.capability.localeCompare(i.capability)||r.symbol.localeCompare(i.symbol))}var Je={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."},Ze=Object.freeze([{layer:"DomainModel",prefixes:["Domain."]},{layer:"ApplicationOrchestration",prefixes:["Application."]},{layer:"PersistenceAdapters",prefixes:["Adapter.Persistence.","Adapter.Repository."]},{layer:"IntegrationAdapters",prefixes:["Adapter.Integration.","Adapter.External."]},{layer:"WorkflowSagaEngine",prefixes:["Workflow."]},{layer:"BackgroundJobsScheduling",prefixes:["Job."]},{layer:"PresentationAdapters",prefixes:["Presentation.","Adapter.Presentation.","Adapter.Api."]},{layer:"ReportingReadModels",prefixes:["Reporting."]},{layer:"ExtensibilityMetadata",prefixes:["Metadata."]},{layer:"SecurityAuditObservability",prefixes:["Security.","Audit.","Observability."]},{layer:"Kernel",prefixes:["Kernel."]}]);function Xe(e,t){return t.flatMap((s,r)=>(s.prefixes??s.intentPrefixes??[]).map(i=>({layer:s.name,layerIndex:r,prefix:i.endsWith(".")?i:`${i}.`}))).filter(({prefix:s})=>e.startsWith(s)).sort((s,r)=>r.prefix.length-s.prefix.length||s.layerIndex-r.layerIndex)[0]?.layer}function Y(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function ue(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&Y(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:Je.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:Je.PUBLISH_MISSING_SOURCE}),t}function v(e,t,n){return{ruleId:e,code:e,message:t,...n}}function ne(e,t){return e.slice(0,t).split(`
|
|
2
2
|
`).length}function Zt(e){let t=[],n=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,s;for(;(s=n.exec(e))!==null;)t.push({value:s[1],index:s.index});return t}function Xt(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 s of n){let r;for(;(r=s.re.exec(e))!==null;){let i=r.index+r[0].indexOf(r[1]),a=r[0],c=s.kind==="import"&&/\bimport\s+type\b/.test(a)||s.kind==="export"&&/\bexport\s+type\b/.test(a);t.push({value:r[1],index:i,kind:s.kind,typeOnly:c})}}return t.sort((s,r)=>s.index-r.index)}function Qt(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),s=[],r=i=>{e.isStringLiteralLike(i)&&s.push({value:i.text,index:i.getStart(n)}),e.forEachChild(i,r)};return r(n),s}function en(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 tn(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}function nn(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}function me(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function rn(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}function ht(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(s=>!e.isPropertyAssignment(s)&&!e.isShorthandPropertyAssignment(s)?!1:rn(e,s.name)===n)}function ge(e,t,n){return ht(e,t,n)!==void 0}function ye(e,t,n){let s=ht(e,t,n);return s&&e.isPropertyAssignment(s)?s.initializer:void 0}function sn(e,t){let n=ye(e,t,"metadata");return ge(e,n,"source")}function At(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?At(e,t.name):!1:!1}function an(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 on(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],s=me(e,n);return s!==void 0&&Y(s)||ge(e,n,"intent")||At(e,n)}function ln(e,t){if(!e.isCallExpression(t))return!1;let[n,s,r]=t.arguments;return sn(e,n)||ge(e,s,"source")||ge(e,r,"source")}function cn(e,t){if(!e.isCallExpression(t))return;let[n,s,r]=t.arguments,i=ye(e,n,"metadata");return me(e,ye(e,i,"source"))??me(e,ye(e,s,"source"))??me(e,ye(e,r,"source"))}function dn(e,t,n,s){let r=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),i=n,a=i?.filePath,c=i?.layer,f=[],A=u=>r.getLineAndCharacterOfPosition(u.getStart(r)).line+1,g=u=>{if(an(e,u)){let o=u.arguments[0],l=me(e,o);for(let d of ue({publishCall:!0,rawIntentName:l,objectHasIntent:ge(e,o,"intent"),arkPublishCandidate:on(e,u),hasSource:ln(e,u)}))f.push(v(d.ruleId,d.message,{line:A(u),filePath:a}));let p=cn(e,u);if(s&&c&&p&&Y(p)){let d=s.resolveLayer(p);d&&d!==c&&f.push(v("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${p}" resolves to ${d}, but the target file is classified as ${c}.`,{line:A(u),filePath:a,target:p,fromLayer:c,toLayer:d}))}}e.forEachChild(u,g)};return g(r),f}function bt(e={}){let t=new Set((e.intents||[]).map(i=>typeof i=="string"?i:i.name)),n=e.forbiddenPatterns||[],s=new Set(e.infrastructureLayers??[]),r=e.enforceIntentAllowlist??t.size>0;return{validate(i,a){let c=[],f=a,A=f?.filePath,g=f?.layer,u=e.typescript,o=u?u.createSourceFile(A??"generated.ts",i,u.ScriptTarget.Latest,!0):void 0,l=o?ee(e.typescript,o):void 0,p=l?l.filter(m=>m.specifier!==void 0).map(m=>({value:m.specifier,index:m.node.getStart(o),kind:m.kind,typeOnly:m.typeOnly})):Xt(i),d=e.typescript?Qt(e.typescript,i):Zt(i);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(A))for(let m of l?.filter(({unresolved:b})=>b)??[]){let b=m.kind==="require";c.push(v(b?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${b?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:m.line,filePath:A}))}let y=g!==void 0&&(s.has(g)||nn(g)),h=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 m of n)if(m instanceof RegExp){m.lastIndex=0;let b=m.exec(i);m.lastIndex=0,b&&c.push(v("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${m}`,{line:b.index===void 0?void 0:ne(i,b.index),filePath:A,suggestion:"Remove infrastructure imports from domain/application layers."+h}))}else i.includes(m)&&c.push(v("FORBIDDEN_SUBSTRING",`Forbidden substring: ${m}`,{line:ne(i,i.indexOf(m)),filePath:A}));for(let m of p){let b=e.resolveImportTarget?.(m.value,A)??(e.resolveImportLayer?{layer:e.resolveImportLayer(m.value,A)}:void 0),C=typeof A=="string"?e.resolveImportTarget?.(A)??(e.resolveImportLayer?{layer:g,relPath:void 0}:void 0):void 0,de=b?.layer;if(de&&g){let Ee=N(e.architectureProfile?.rules,g,de,{fromPath:C?.relPath,toPath:b?.relPath,layers:e.architectureLayers});if(Ee){if(m.typeOnly&&!Ee.peerIsolation)continue;let Me=!!Ee.peerIsolation;c.push(v("LAYER_IMPORT_VIOLATION",Ee.message??(Me?`Layer "${g}" must not import across slices into "${de}".`:`Layer "${g}" must not import "${de}".`),{line:ne(i,m.index),source:m.value,target:m.value,filePath:A,fromLayer:g,toLayer:de,suggestion:Me?"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:m.kind,peerIsolation:Me,...m.typeOnly?{typeOnly:!0}:{}}}));continue}continue}y||m.typeOnly||!en(m.value)&&!tn(m.value)||c.push(v("FORBIDDEN_IMPORT",`Forbidden ${m.kind} target: "${m.value}".`,{line:ne(i,m.index),source:m.value,target:m.value,filePath:A,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+h,details:{importKind:m.kind}}))}if(e.policies)for(let m of e.policies){let b=m.check({source:i,context:a});if(b!==!0)if(Array.isArray(b))for(let C of b)c.push(v("POLICY_VIOLATION",C.message,{filePath:A,suggestion:`Fix violation of policy "${m.name}".`}));else b===!1?c.push(v("POLICY_VIOLATION",`Policy ${m.name} failed on generated code`)):c.push(v("POLICY_VIOLATION",b.message))}if(r&&t.size>0)for(let m of d)Y(m.value)&&!t.has(m.value)&&c.push(v("UNKNOWN_INTENT",`Unknown intent reference: "${m.value}"`,{line:ne(i,m.index),filePath:A,target:m.value,suggestion:`Register intent "${m.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&g)for(let m of d){if(!Y(m.value))continue;let b=e.architectureProfile.resolveLayer(m.value);if(!b)continue;let C=N(e.architectureProfile.rules,g,b);C&&c.push(v("LAYER_REFERENCE_VIOLATION",C.message??`Layer "${g}" must not reference "${b}" through "${m.value}".`,{line:ne(i,m.index),filePath:A,target:m.value,fromLayer:g,toLayer:b,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:C}}))}if(e.extensions)for(let m of e.extensions)try{let b=m.analyze(i,a);c.push(...b)}catch(b){c.push(v("EXTENSION_ERROR",`Extension "${m.name}" failed: ${b instanceof Error?b.message:String(b)}`))}if(e.typescript&&o&&g&&e.forbiddenGlobals?.[g]?.length)try{let m=e.forbiddenGlobals[g];c.push(...te(e.typescript,o,m).map(b=>v("FORBIDDEN_GLOBAL",`${g} must not use the ambient global "${b.name}".`,{line:b.line,filePath:A,target:b.name,fromLayer:g,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let b of l??[]){if(b.typeOnly||!b.specifier)continue;let C=V(b.specifier,m);C&&c.push(v("FORBIDDEN_GLOBAL",`${g} must not use module "${b.specifier}" because it is the import form of forbidden global "${C}".`,{line:b.line,filePath:A,source:b.specifier,target:b.specifier,fromLayer:g,details:{importKind:b.kind,forbiddenGlobal:C},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(m){c.push(v("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${m instanceof Error?m.message:String(m)}`))}if(e.typescript&&o&&g&&e.capabilityWalls?.[g]?.length)try{let m=new Set(e.capabilityWalls[g]),b=e.forbiddenGlobals?.[g]??[];for(let C of We(e.typescript,o))m.has(C.capability)&&(C.source==="ambient-global"&&fe(C.symbol,b)||C.source==="import-based"&&V(C.symbol,b)||c.push(v("CAPABILITY_VIOLATION",C.source==="import-based"?`${g} denies the ${C.capability} capability; found import of "${C.symbol}".`:`${g} denies the ${C.capability} capability; found ambient "${C.symbol}".`,{line:C.line,filePath:A,target:C.symbol,capability:C.capability,fromLayer:g,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(m){c.push(v("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${m instanceof Error?m.message:String(m)}`))}if(e.typescript)try{c.push(...dn(e.typescript,i,a,e.architectureProfile))}catch(m){c.push(v("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${m instanceof Error?m.message:String(m)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:c.length===0,violations:c}}}}var pn="1.0",xe="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",Ct=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],fn=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function un(){let e=[];for(let t of Ct)for(let n of Ct)t===n||fn.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var ke=un();var G={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},et={$schema:"https://json-schema.org/draft/2020-12/schema",$id:xe,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:xe,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:{...G,minItems:1,default:["src"]},exclude:{...G,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:ke,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...G,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:{...G,minItems:1},exclude:G,intentPrefixes:G,description:{type:"string",minLength:1},forbiddenGlobals:G,capabilities:{type:"object",additionalProperties:!1,properties:{deny:{type:"array",uniqueItems:!0,items:{type:"string",enum:["network","filesystem","clock","randomness","environment","process","persistence"]}}}},pure:{type:"boolean"},mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...G,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}}}}},ie=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
|
|
3
3
|
${n.map(s=>`- ${s.path}: ${s.message}`).join(`
|
|
4
4
|
`)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function It(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Qe(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function re(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function yn(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function Se(e,t,n,s,r){if(t.$ref){let i=yn(t.$ref,s);if(!i){r.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}Se(e,i,n,s,r);return}if(t.const!==void 0&&!Object.is(e,t.const)){r.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(i=>Object.is(i,e))){r.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!It(e)){r.push({path:n,message:`must be an object; received ${re(e)}`});return}let i=t.properties??{};for(let a of t.required??[])e[a]===void 0&&r.push({path:Qe(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in i||r.push({path:Qe(n,a),message:"unknown field"});for(let[a,c]of Object.entries(i))e[a]!==void 0&&Se(e[a],c,Qe(n,a),s,r);return}if(t.type==="array"){if(!Array.isArray(e)){r.push({path:n,message:`must be an array; received ${re(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&r.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let i=e.map(a=>JSON.stringify(a));new Set(i).size!==i.length&&r.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((i,a)=>Se(i,t.items,`${n}[${a}]`,s,r));return}if(t.type==="string"){if(typeof e!="string"){r.push({path:n,message:`must be a string; received ${re(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&r.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&r.push({path:n,message:`must be a boolean; received ${re(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){r.push({path:n,message:`must be an integer; received ${re(e)}`});return}t.minimum!==void 0&&e<t.minimum&&r.push({path:n,message:`must be at least ${t.minimum}`})}}function mn(e){return{...e,$schema:e.$schema===void 0?xe: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?ke.map(t=>({...t})):e.rules}}function gn(e,t="ark.config.json"){if(!It(e))throw new ie(t,[{path:"$",message:`must be an object; received ${re(e)}`}]);let n=e.schemaVersion===void 0?"unversioned":null;if(e.schemaVersion!==void 0&&e.schemaVersion!=="1.0")throw new ie(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.0`}]);return{candidate:mn(e),migratedFrom:n}}function we(e,t="ark.config.json"){let{candidate:n,migratedFrom:s}=gn(e,t),r=[];if(Se(n,et,"$",et,r),r.length>0)throw new ie(t,r);return{config:n,migratedFrom:s}}function tt(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(s){throw new ie(t,[{path:"$",message:`invalid JSON: ${s instanceof Error?s.message:String(s)}`}])}return we(n,t)}function Et(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:xe,schemaVersion:"1.0"};for(let[n,s]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=s);return t}function hn(e){return e.endsWith(".")?e:`${e}.`}function An(e,t){let n=e.prefixes.length?Math.max(...e.prefixes.map(r=>r.length)):0;return(t.prefixes.length?Math.max(...t.prefixes.map(r=>r.length)):0)-n}function Oe(e){let t=e.layers.map(r=>({...r,prefixes:r.prefixes.map(hn)})),n=[...t].sort(An),s=[...e.rules??[]];return{name:e.name,layers:t,rules:s,resolveLayer(r){return t.find(i=>i.match?.(r))?.name??n.find(i=>i.prefixes.some(a=>r.startsWith(a)))?.name}}}function Rt(e,t={}){return Oe({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,s)=>({name:n.name,prefixes:n.intentPrefixes??[],description:n.description,order:s+1})),rules:e.rules??[]})}var bn=[{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}],Pe=Oe({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:bn,rules:ke.map(e=>({...e}))}),Cn={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 vt(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,s=t==="."?"":`${t}/`;return Et({include:e.include??[t],layers:Pe.layers.map(r=>({name:r.name,patterns:(Cn[r.name]??[r.name]).map(i=>`${s}${i}/**`),intentPrefixes:r.prefixes,optional:n})),rules:[...Pe.rules]})}function S(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 E(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(E).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${E(t[n])}`).join(",")}}`}var W="1.0",St=["network","filesystem","clock","randomness","environment","process","persistence"];function q(e,t){let n=E(e),s=E(t);return n<s?-1:n>s?1:0}function T(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}function he(e){let t={schemaVersion:"1.0",include:T(e.include??[]),exclude:T(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:T(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:T(n.patterns??[]),exclude:T(n.exclude??[]),forbiddenGlobals:T(n.forbiddenGlobals??[]),intentPrefixes:T(n.intentPrefixes??[]),capabilityDeny:T(n.capabilities?.deny??[]),pure:n.pure===!0})).sort(q),safety:{maxTsSuppressions:e.safety?.maxTsSuppressions??0,maxAnyCasts:e.safety?.maxAnyCasts??0,allowInMemory:e.safety?.allowInMemory===!0,allowDisabledPeerIsolation:e.safety?.allowDisabledPeerIsolation===!0}};return S(E(t))}function In(e){let t=e.completenessReasons.map(u=>({code:u.code,message:u.message,...u.file?{file:u.file}:{}})).sort(q),n=e.files.map(u=>({...u,typeOnlyExportNames:T(u.typeOnlyExportNames)})).sort((u,o)=>u.path<o.path?-1:u.path>o.path?1:0),s=e.dependencies.map(u=>({...u,...u.namedBindings?{namedBindings:T(u.namedBindings)}:{}})).sort(q),r=e.capabilityUses.map(u=>({...u})).sort(q),i=e.ambientUses.map(u=>({...u})).sort(q),a=e.publishCalls.map(u=>({...u})).sort(q),c=e.intentReferences.map(u=>({...u})).sort(q),f=e.safetyUses.map(u=>({...u})).sort(q),A=e.files.map(({path:u,contentHash:o})=>({path:u,contentHash:o})).sort((u,o)=>u.path<o.path?-1:u.path>o.path?1:0),g=S(E(A));return{schemaVersion:"1.0",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:g,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:s,capabilityUses:r,ambientUses:i,publishCalls:a,intentReferences:c,safetyUses:f}}function kt(e){let t=In(e);return{...t,factsHash:S(E(t))}}function nt(e){return kt(Pt(D(e,"$"),!1))}function D(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}function F(e,t,n){let s=new Set(t),r=Object.keys(e).find(i=>!s.has(i));if(r)throw new Error(`${n}.${r} is not part of schema 1.0.`)}function k(e,t,n){let s=e[t];if(typeof s!="string"||s.length===0)throw new Error(`${n}.${t} must be a non-empty string.`);return s}function se(e,t,n){if(e[t]!==void 0)return k(e,t,n)}function M(e,t,n){let s=k(e,t,n),r=s.replace(/\\/g,"/");if(!r||r.startsWith("/")||/^[A-Za-z]:\//.test(r)||/[\u0000-\u001f\u007f]/.test(r))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let i=[];for(let c of r.split("/"))if(!(!c||c==="."))if(c===".."){if(i.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);i.pop()}else i.push(c);let a=i.join("/");if(!a||a!==s)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return a}function _(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}function wt(e,t,n){let s=e[t];if(!Number.isInteger(s)||Number(s)<0)throw new Error(`${n}.${t} must be a non-negative integer.`);return Number(s)}function ae(e,t,n){let s=wt(e,t,n);if(s===0)throw new Error(`${n}.${t} must be a positive integer.`);return s}function U(e,t,n){let s=e[t];if(!Array.isArray(s))throw new Error(`${n}.${t} must be an array.`);return s}function B(e,t,n,s){let r=e[t];if(typeof r!="string"||!n.includes(r))throw new Error(`${s}.${t} must be one of ${n.join(", ")}.`);return r}function xt(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!n))throw new Error(`${t} must be an array of non-empty strings.`);return[...e]}function En(e,t,n){let s=new Set;for(let r of e){let i=t(r);if(s.has(i))throw new Error(`${n} must not contain duplicate facts (${i}).`);s.add(i)}}function Pt(e,t){F(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=B(e,"schemaVersion",["1.0"],"$"),s=B(e,"completeness",["complete","partial","unavailable"],"$"),r=U(e,"completenessReasons","$").map((p,d)=>{let y=`$.completenessReasons[${d}]`,h=D(p,y);F(h,["code","message","file"],y);let m=h.file===void 0?void 0:M(h,"file",y);return{code:k(h,"code",y),message:k(h,"message",y),...m?{file:m}:{}}});if(s==="complete"&&r.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(s!=="complete"&&r.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let i=U(e,"files","$").map((p,d)=>{let y=`$.files[${d}]`,h=D(p,y);return F(h,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],y),{path:M(h,"path",y),contentHash:k(h,"contentHash",y),parseStatus:B(h,"parseStatus",["parsed","invalid"],y),parseDiagnosticCount:wt(h,"parseDiagnosticCount",y),exportsOnlyTypes:_(h,"exportsOnlyTypes",y),typeOnlyExportNames:xt(h.typeOnlyExportNames,`${y}.typeOnlyExportNames`),hasTopLevelSideEffects:_(h,"hasTopLevelSideEffects",y)}}),a=U(e,"dependencies","$").map((p,d)=>{let y=`$.dependencies[${d}]`,h=D(p,y);F(h,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],y);let m=se(h,"specifier",y),b=se(h,"target",y),C=B(h,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],y);if(C==="resolved-project"&&!b)throw new Error(`${y}.target is required for resolved-project dependencies.`);if(C!=="resolved-project"&&b)throw new Error(`${y}.target is only allowed for resolved-project dependencies.`);if(C!=="dynamic"&&!m)throw new Error(`${y}.specifier is required unless resolution is dynamic.`);return{from:M(h,"from",y),...m?{specifier:m}:{},kind:B(h,"kind",["import","export","dynamic-import","require"],y),typeOnly:_(h,"typeOnly",y),line:ae(h,"line",y),resolution:C,...b?{target:M(h,"target",y)}:{},...h.namedBindings!==void 0?{namedBindings:xt(h.namedBindings,`${y}.namedBindings`)}:{},...h.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:_(h,"targetTypeOnlyExports",y)}:{},...h.sourcePureTypeModule!==void 0?{sourcePureTypeModule:_(h,"sourcePureTypeModule",y)}:{},...h.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:_(h,"namedBindingsTypeOnly",y)}:{},...h.portProofEligible!==void 0?{portProofEligible:_(h,"portProofEligible",y)}:{}}}),c=U(e,"capabilityUses","$").map((p,d)=>{let y=`$.capabilityUses[${d}]`,h=D(p,y);return F(h,["file","line","symbol","capability","source"],y),{file:M(h,"file",y),line:ae(h,"line",y),symbol:k(h,"symbol",y),capability:B(h,"capability",St,y),source:B(h,"source",["ambient-global","import-based"],y)}}),f=U(e,"ambientUses","$").map((p,d)=>{let y=`$.ambientUses[${d}]`,h=D(p,y);return F(h,["file","line","symbol"],y),{file:M(h,"file",y),line:ae(h,"line",y),symbol:k(h,"symbol",y)}}),A=U(e,"publishCalls","$").map((p,d)=>{let y=`$.publishCalls[${d}]`,h=D(p,y);F(h,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],y);let m=se(h,"rawIntentName",y),b=se(h,"sourceIntent",y);return{file:M(h,"file",y),line:ae(h,"line",y),...m?{rawIntentName:m}:{},objectHasIntent:_(h,"objectHasIntent",y),arkPublishCandidate:_(h,"arkPublishCandidate",y),hasSource:_(h,"hasSource",y),...b?{sourceIntent:b}:{}}}),g=U(e,"intentReferences","$").map((p,d)=>{let y=`$.intentReferences[${d}]`,h=D(p,y);return F(h,["file","line","intent"],y),{file:M(h,"file",y),line:ae(h,"line",y),intent:k(h,"intent",y)}}),u=U(e,"safetyUses","$").map((p,d)=>{let y=`$.safetyUses[${d}]`,h=D(p,y);F(h,["file","line","kind","symbol"],y);let m=se(h,"symbol",y),b=B(h,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],y);if(b==="in-memory-store"&&!m)throw new Error(`${y}.symbol is required for in-memory-store facts.`);if(b!=="in-memory-store"&&m)throw new Error(`${y}.symbol is only allowed for in-memory-store facts.`);return{file:M(h,"file",y),line:ae(h,"line",y),kind:b,...m?{symbol:m}:{}}});En(i,p=>p.path,"$.files");let o=new Set(i.map(p=>p.path));for(let p of i){if(p.parseStatus==="parsed"&&p.parseDiagnosticCount!==0)throw new Error(`$.files[${p.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(p.parseStatus==="invalid"&&p.parseDiagnosticCount===0)throw new Error(`$.files[${p.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(s==="complete"&&i.some(p=>p.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let p of a)if(!o.has(p.from))throw new Error(`$.dependencies references missing source file ${p.from}.`);for(let[p,d]of[["$.capabilityUses",c],["$.ambientUses",f],["$.publishCalls",A],["$.intentReferences",g],["$.safetyUses",u]])for(let y of d)if(!o.has(y.file))throw new Error(`${p} references missing file ${y.file}.`);let l=se(e,"projectPackageName","$");return{schemaVersion:n,completeness:s,completenessReasons:r,resolverIdentity:k(e,"resolverIdentity","$"),compilerIdentity:k(e,"compilerIdentity","$"),compilerOptionsHash:k(e,"compilerOptionsHash","$"),tsconfigHash:k(e,"tsconfigHash","$"),evidenceRequirementsHash:k(e,"evidenceRequirementsHash","$"),...l?{projectPackageName:l}:{},files:i,dependencies:a,capabilityUses:c,ambientUses:f,publishCalls:A,intentReferences:g,safetyUses:u}}function z(e){let t=D(e,"$"),n=k(t,"factsHash","$"),s=k(t,"candidateTreeHash","$"),r=kt(Pt(t,!0));if(r.factsHash!==n)throw new Error(`$.factsHash does not match the canonical payload (${r.factsHash}).`);if(s!==r.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${r.candidateTreeHash}).`);return r}var Rn=["network","filesystem","clock","randomness","environment","process","persistence"],R={type:"string",minLength:1},oe={type:"integer",minimum:1},H={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},rt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.resolved-candidate-facts.schema.json",title:"ArkGate resolved candidate facts",type:"object",additionalProperties:!1,required:["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","candidateTreeHash","evidenceRequirementsHash","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","factsHash"],properties:{schemaVersion:{const:"1.0"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:R,message:R,file:H}}},resolverIdentity:R,compilerIdentity:R,compilerOptionsHash:R,tsconfigHash:R,candidateTreeHash:R,evidenceRequirementsHash:R,projectPackageName:R,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:H,contentHash:R,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:R},hasTopLevelSideEffects:{type:"boolean"}},allOf:[{if:{properties:{parseStatus:{const:"parsed"}}},then:{properties:{parseDiagnosticCount:{const:0}}}},{if:{properties:{parseStatus:{const:"invalid"}}},then:{properties:{parseDiagnosticCount:{minimum:1}}}}]}},dependencies:{type:"array",items:{type:"object",additionalProperties:!1,required:["from","kind","typeOnly","line","resolution"],properties:{from:H,specifier:R,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:oe,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:H,namedBindings:{type:"array",items:R},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"}},allOf:[{if:{properties:{resolution:{const:"resolved-project"}}},then:{required:["target"]},else:{not:{required:["target"]}}},{if:{properties:{resolution:{const:"dynamic"}}},else:{required:["specifier"]}}]}},capabilityUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol","capability","source"],properties:{file:H,line:oe,symbol:R,capability:{enum:Rn},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:H,line:oe,symbol:R}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:H,line:oe,rawIntentName:R,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:R}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:H,line:oe,intent:R}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:H,line:oe,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:R},allOf:[{if:{properties:{kind:{const:"in-memory-store"}}},then:{required:["symbol"]},else:{not:{required:["symbol"]}}}]}},factsHash:R},allOf:[{if:{properties:{completeness:{const:"complete"}}},then:{properties:{completenessReasons:{maxItems:0},files:{items:{properties:{parseStatus:{const:"parsed"}}}}}}},{if:{properties:{completeness:{enum:["partial","unavailable"]}}},then:{properties:{completenessReasons:{minItems:1}}}}]};var it="1.0";function P(e){return`${e.from}->${e.to}`}function Ae(e,t,n,s="dependency"){return{id:`${e}:${s}:${P(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${P(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${P(t)}, then preflight again.`}:e==="unplanned"?{nextAction:s==="dependency-removed"?`Restore the removed dependency ${P(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${P(t)} from the candidate, then preflight again.`}:{}}}function le(e){let t=[],n=new Map(e.changeMap.map.files.map(o=>[o.path,o])),s=new Map(e.changes.map(o=>[o.path,o])),r=new Map(e.changeMap.map.dependencies.map(o=>[P(o),o])),i=new Map(e.baseDependencies.map(o=>[P(o),o])),a=new Map(e.candidateDependencies.map(o=>[P(o),o]));for(let o of[...n.values()].sort((l,p)=>l.path.localeCompare(p.path))){let l=s.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[...s.values()].sort((l,p)=>l.path.localeCompare(p.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[...r.values()].sort((l,p)=>P(l).localeCompare(P(p)))){if(a.has(P(o))){t.push(Ae("satisfied",o,`${o.from} -> ${o.to} exists in the candidate architecture.`));continue}let l={from:o.to,to:o.from};a.has(P(l))?(c.add(P(l)),t.push(Ae("contradictory",o,`${o.from} -> ${o.to} was planned, but the candidate contains the reverse edge.`))):t.push(Ae("missing",o,`${o.from} -> ${o.to} is absent from the candidate architecture.`))}let f=new Set([...n.keys(),...s.keys()]);for(let[o,l]of[...a].sort(([p],[d])=>p.localeCompare(d)))i.has(o)||r.has(o)||c.has(o)||!f.has(l.from)&&!f.has(l.to)||t.push({...Ae("unplanned",l,`${l.from} -> ${l.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let A=new Set(e.changeMap.map.files.filter(o=>o.operation==="delete").map(o=>o.path));for(let[o,l]of[...i].sort(([p],[d])=>p.localeCompare(d)))a.has(o)||A.has(l.from)||A.has(l.to)||!f.has(l.from)&&!f.has(l.to)||t.push({...Ae("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 u={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:u.missing===0&&u.contradictory===0&&u.unplanned===0,behavioralCompletion:"not-evaluated",summary:u,findings:t}}var st="1.0";function x(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 L(e){return[...new Set(e??[])].sort()}function J(e,t,n,s,r){let i=L(n),a=L(s),c=new Set(i),f=new Set(a),A=a.filter(u=>!c.has(u)),g=i.filter(u=>!f.has(u));A.length===0&&g.length===0||(A.length>0&&x(e,{kind:"added",path:t,classification:r.added,message:r.addedMessage,before:i,after:a}),g.length>0&&x(e,{kind:"removed",path:t,classification:r.removed,message:r.removedMessage,before:i,after:a}))}function Le(e,t,n,s,r,i,a){if(n===s)return;x(e,{kind:s?"enabled":"disabled",path:t,classification:s?r:r==="strengthening"?"weakening":"strengthening",message:s?i:a,before:n,after:s})}function $e(e,t){let n=new Map,s=new Set;for(let r of e){let i=t(r);n.has(i)?s.add(i):n.set(i,r)}return{values:n,duplicates:[...s].sort()}}function vn(e,t,n){let s=$e(t,i=>i.name),r=$e(n,i=>i.name);(s.duplicates.length>0||r.duplicates.length>0)&&x(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:s.duplicates,after:r.duplicates});for(let i of[...new Set([...s.values.keys(),...r.values.keys()])].sort()){let a=s.values.get(i),c=r.values.get(i),f=`$.layers[${i}]`;if(!a&&c){x(e,{kind:"layer-added",path:f,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:c});continue}if(a&&!c){x(e,{kind:"layer-removed",path:f,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:a});continue}if(!a||!c)continue;J(e,`${f}.patterns`,a.patterns,c.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),J(e,`${f}.exclude`,a.exclude,c.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let A=ve(a),g=ve(c);J(e,`${f}.forbiddenGlobals`,A.rawGlobals,g.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),J(e,`${f}.capabilities`,A.atoms,g.atoms,{added:"strengthening",removed:"weakening",addedMessage:"Additional ambient/import protection is enforced in this layer (coverage atoms).",removedMessage:"An ambient/import protection was lost from this layer (coverage atoms)."}),L(a.intentPrefixes).join("\0")!==L(c.intentPrefixes).join("\0")&&x(e,{kind:"intent-prefixes-changed",path:`${f}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:L(a.intentPrefixes),after:L(c.intentPrefixes)}),Le(e,`${f}.mayImportInfrastructure`,a.mayImportInfrastructure===!0,c.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),Le(e,`${f}.optional`,a.optional===!0,c.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active.")}}function Sn(e,t,n){let s=a=>`${a.from}->${a.to}`,r=$e(t,s),i=$e(n,s);(r.duplicates.length>0||i.duplicates.length>0)&&x(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:r.duplicates,after:i.duplicates});for(let a of[...new Set([...r.values.keys(),...i.values.keys()])].sort()){let c=r.values.get(a),f=i.values.get(a),A=`$.rules[${a}]`;if(!c&&f){f.allowed===!1&&x(e,{kind:"deny-added",path:A,classification:"strengthening",message:"A denied dependency edge was added.",after:f});continue}if(c&&!f){c.allowed===!1&&x(e,{kind:"deny-removed",path:A,classification:"weakening",message:"A denied dependency edge was removed.",before:c});continue}if(!c||!f)continue;c.allowed!==f.allowed&&x(e,{kind:f.allowed?"deny-disabled":"deny-enabled",path:`${A}.allowed`,classification:f.allowed?"weakening":"strengthening",message:f.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:c.allowed,after:f.allowed});let g=c.peerIsolation===!0,u=f.peerIsolation===!0;if(g!==u){let o=c.from===c.to&&f.from===f.to;x(e,{kind:u?"peer-isolation-enabled":"peer-isolation-disabled",path:`${A}.peerIsolation`,classification:o?u?"strengthening":"weakening":"judgment-required",message:o?u?"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:u})}L(c.sliceFolders).join("\0")!==L(f.sliceFolders).join("\0")&&x(e,{kind:"slice-folders-changed",path:`${A}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:L(c.sliceFolders),after:L(f.sliceFolders)})}}function xn(e,t,n){let s=t.safety??{},r=n.safety??{};for(let i of["maxTsSuppressions","maxAnyCasts"]){let a=s[i]??0,c=r[i]??0;a!==c&&x(e,{kind:c>a?"threshold-raised":"threshold-lowered",path:`$.safety.${i}`,classification:c>a?"weakening":"strengthening",message:c>a?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:a,after:c})}for(let i of["allowInMemory","allowDisabledPeerIsolation"])Le(e,`$.safety.${i}`,s[i]===!0,r[i]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}function kn(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 at(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."}),Le(n,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let s={off:0,soft:1,"framework-soft":1,strict:2},r=e.cyclePolicy??"strict",i=t.cyclePolicy??"strict";if(r!==i){let a=s[i]===s[r]?"judgment-required":s[i]>s[r]?"strengthening":"weakening";x(n,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:a,message:"The cycle enforcement level changed.",before:r,after:i})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&x(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}),vn(n,e.layers,t.layers),Sn(n,e.rules,t.rules),xn(n,e,t),n.sort((a,c)=>a.path.localeCompare(c.path)||a.id.localeCompare(c.id)),{schemaVersion:st,classification:kn(n),findings:n}}function ot(e,t){if(!e||e.schemaVersion!==st||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(r=>typeof r!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=L(e.findingIds),s=L(t.findingIds);return n.length===s.length&&n.every((r,i)=>r===s[i])}function Z(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 Ot(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}function _e(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}function O(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}function be(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let s=t,r="";for(t+=1;t<e.length;t+=1){let i=e[t];if(i===n)return{value:r,offset:s,excerpt:e.slice(s,t+1)};i==="\\"&&t+1<e.length?(r+=e[t+1],t+=1):r+=i}}function $(e,t,n){return e.startsWith(t,n)&&!_e(e[n-1])&&!_e(e[n+t.length])}function Lt(e,t){let n=O(e,t);if(e[n]!=="{")return!1;n+=1;let s=!1;for(;n<e.length;){if(n=O(e,n),e[n]==="}")return s;if(e[n]===","){n+=1;continue}if(!$(e,"type",n))return!1;let r=O(e,n+4);if(r>=e.length||e[r]===","||e[r]==="}"||$(e,"as",r)||!Ot(e[r]))return!1;for(n=r;n<e.length&&_e(e[n]);)n+=1;if(n=O(e,n),$(e,"as",n)){if(n=O(e,n+2),!Ot(e[n]))return!1;for(;n<e.length&&_e(e[n]);)n+=1}s=!0}return!1}function wn(e,t){if(t=O(e,t+6),e[t]==="(")return be(e,O(e,t+1));let n=!1;if($(e,"type",t)){let r=O(e,t+4);e[r]!==","&&!$(e,"from",r)&&(n=!0)}else Lt(e,t)&&(n=!0);let s=$t(e,t,!0);return s&&n?{...s,typeOnly:!0}:s}function Pn(e,t){t=t+6;let n=O(e,t),s=!1;if($(e,"type",n)){let i=O(e,n+4);(e[i]==="{"||e[i]==="*")&&(s=!0)}else Lt(e,n)&&(s=!0);let r=$t(e,t,!1);return r&&s?{...r,typeOnly:!0}:r}function $t(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if($(e,"from",t))return be(e,O(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return be(e,t);if(t>0&&($(e,"import",t)||$(e,"export",t)))return}}function On(e,t){for(t+=1;t<e.length;t+=1){let n=e[t];if(n==="\\")t+=1;else if(n==="`")return t}return e.length}function Ln(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let s=O(e,t+7);if(e[s]!=="(")return;s=O(e,s+1);let r=be(e,s);return r?{...r,requireCall:!0}:void 0}function $n(e){let t=[];for(let n=0;n<e.length;n+=1){let s=e[n];if(s==="/"&&e[n+1]==="/"){if(n=e.indexOf(`
|
package/docs/README.md
CHANGED
|
@@ -57,8 +57,8 @@ These are **not** the day-to-day product path. They stay in the repo for evidenc
|
|
|
57
57
|
| Field adoption kit (scaffolding, not closed) | [field/](field/) |
|
|
58
58
|
| Runtime hardening (experimental) | [production-hardening.md](production-hardening.md) |
|
|
59
59
|
|
|
60
|
-
Current
|
|
61
|
-
Next prepared
|
|
60
|
+
Current release notes: [releases/3.9.1.md](releases/3.9.1.md) (`arkgate@3.9.1` on npm `latest`).
|
|
61
|
+
Next prepared: [releases/3.9.2.md](releases/3.9.2.md) (`arkgate@3.9.2` — not yet `latest`).
|
|
62
62
|
|
|
63
63
|
---
|
|
64
64
|
|
package/docs/package-surface.md
CHANGED
|
@@ -186,7 +186,7 @@ production deployment would need to satisfy; it is not a readiness certification
|
|
|
186
186
|
|
|
187
187
|
## Release notes (maintainers)
|
|
188
188
|
|
|
189
|
-
Ship notes for a version live under [releases/](https://github.com/pedroknigge/arkgate/tree/main/docs/releases) (latest
|
|
190
|
-
[3.9.
|
|
191
|
-
[3.9.
|
|
189
|
+
Ship notes for a version live under [releases/](https://github.com/pedroknigge/arkgate/tree/main/docs/releases) (latest:
|
|
190
|
+
[3.9.1.md](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/3.9.1.md); prepared:
|
|
191
|
+
[3.9.2.md](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/3.9.2.md)).
|
|
192
192
|
Publish path: signed annotated tag → GitHub Release → `publish-npm.yml` (see [CONTRIBUTING.md](https://github.com/pedroknigge/arkgate/blob/main/CONTRIBUTING.md)).
|
package/package.json
CHANGED
package/server.json
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
|
|
3
3
|
"name": "io.github.pedroknigge/arkgate",
|
|
4
|
-
"description": "ArkGate
|
|
4
|
+
"description": "ArkGate \u2014 architecture co-pilot for AI TypeScript (write gate, CI, plan/loop)",
|
|
5
5
|
"repository": {
|
|
6
6
|
"url": "https://github.com/pedroknigge/arkgate",
|
|
7
7
|
"source": "github"
|
|
8
8
|
},
|
|
9
|
-
"version": "3.9.
|
|
9
|
+
"version": "3.9.2",
|
|
10
10
|
"packages": [
|
|
11
11
|
{
|
|
12
12
|
"registryType": "npm",
|
|
13
13
|
"identifier": "arkgate",
|
|
14
|
-
"version": "3.9.
|
|
14
|
+
"version": "3.9.2",
|
|
15
15
|
"runtimeHint": "npx",
|
|
16
16
|
"transport": {
|
|
17
17
|
"type": "stdio"
|
|
@@ -71,6 +71,13 @@ Never say “your architecture is guarded” while `goal.met` is false, governed
|
|
|
71
71
|
or false-green doctor gaps are open. Never say “architecture is healthy finished” solely
|
|
72
72
|
because governed% is 100% and plan is empty.
|
|
73
73
|
|
|
74
|
+
**Honesty hard lines (doctor JSON):**
|
|
75
|
+
- `coverageHonesty.worseThanNoGate` / weak coverage (~<50%): green is **worse than no gate**.
|
|
76
|
+
- `baseline.honesty.dirtyBaselineRisk`: green-via-freeze may hide false-positive debt.
|
|
77
|
+
- `writePath.honesty.softWriteHost` (Cursor / Codex / OpenCode): write path is **advisory /
|
|
78
|
+
best-effort**, not hard PreToolUse — required CI status is the hard merge boundary.
|
|
79
|
+
- Do not invent hard write guarantees for soft hosts.
|
|
80
|
+
|
|
74
81
|
## Related onboarding
|
|
75
82
|
|
|
76
83
|
- **Greenfield:** low governed% → `/ark-architect` or `ark-check --recommend`.
|
|
@@ -247,7 +247,10 @@ Canonical productized template also in `docs/brownfield-adoption.md` §6.
|
|
|
247
247
|
|
|
248
248
|
**Q04 pilot loop:** when doctor/plan JSON is available, use **`pilotLoop.nextPilot`** as the
|
|
249
249
|
**single** next extraction card (one pilot at a time → re-doctor). Do not open five B bets
|
|
250
|
-
in parallel.
|
|
250
|
+
in parallel. When `pilotLoop.queuedBets > 0`, those bets stay **queued**, not concurrent.
|
|
251
|
+
`multiPilotBatchForbidden` / `autoApplyForbidden` (alias `autoApplyPlanBForbidden`) are hard
|
|
252
|
+
lines — never silent codemod of plan B. After the pilot lands, re-run doctor; success =
|
|
253
|
+
reduced evidence on pilot paths.
|
|
251
254
|
|
|
252
255
|
```text
|
|
253
256
|
### Extraction card
|
|
@@ -82,6 +82,10 @@ the same files or weaken the gate.
|
|
|
82
82
|
|
|
83
83
|
- If the user needs bulk adoption / wrong contract, not a single artifact: **STOP — do not continue this skill as complete.** **STOP — wrong skill: invoke /ark-adopt or /ark-contract** instead of ad-hoc multi-file grinding without a plan.
|
|
84
84
|
- If contract lacks a home for the artifact: **STOP — do not continue this skill as complete.** Adopt the layer via `/ark-contract` first.
|
|
85
|
+
- If doctor is **ENFORCE · design-weak** and the user is asking to reshape existing structure
|
|
86
|
+
(not place one new artifact): place only the new file under the golden/contract home, then
|
|
87
|
+
hand off **one** pilot via `pilotLoop.nextPilot` / `/ark-explore` shape-focus — never multi-pilot
|
|
88
|
+
batch reshape from this skill.
|
|
85
89
|
|
|
86
90
|
## Operating rules
|
|
87
91
|
|