arkgate 4.5.6 → 4.5.7
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 +24 -1
- package/README.md +7 -7
- package/bin/ark-check-runtime.mjs +6 -4
- package/bin/ark-mcp-runtime.mjs +82 -61
- package/bin/ark.mjs +2 -2
- package/bin/lib/agent-gates.mjs +2 -0
- package/bin/lib/ci-and-commands.mjs +2 -1
- package/bin/lib/gate-files.mjs +1 -1
- package/bin/lib/hook-templates.mjs +13 -11
- package/bin/lib/host-support-matrix.mjs +31 -11
- package/bin/lib/install-migrate.mjs +24 -0
- package/bin/lib/managed-upgrade.mjs +6 -1
- package/bin/lib/mcp-adoption.mjs +6 -1
- package/bin/lib/mcp-process-package.mjs +95 -0
- package/bin/lib/start-preview.mjs +5 -1
- package/bin/lib/write-path-capabilities.mjs +62 -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/agent-guide.md +8 -6
- package/docs/ai-gates.md +24 -14
- package/docs/enthusiast/how-to-agent-gates.md +4 -3
- package/docs/package-surface.md +2 -2
- package/package.json +1 -1
- package/server.json +2 -2
package/bin/lib/mcp-adoption.mjs
CHANGED
|
@@ -27,7 +27,12 @@ export const COMMAND_GATE_TEXT_FILES = [
|
|
|
27
27
|
'.grok/hooks/ark-write-gate.json', '.grok/config.toml', '.codex/config.toml',
|
|
28
28
|
'.agents/hooks.json',
|
|
29
29
|
];
|
|
30
|
-
export const COMMAND_GATE_JSON_FILES = [
|
|
30
|
+
export const COMMAND_GATE_JSON_FILES = [
|
|
31
|
+
'.mcp.json',
|
|
32
|
+
'.cursor/mcp.json',
|
|
33
|
+
'.cursor/hooks.json',
|
|
34
|
+
'opencode.json',
|
|
35
|
+
];
|
|
31
36
|
// Primary CLI names (product) + one-major aliases. migrate-commands must strip ALL of these
|
|
32
37
|
// before re-emitting a single preferred bin — otherwise a partial rename leaves
|
|
33
38
|
// args: ["ark-mcp", "arkgate-mcp", ...] which breaks stdio MCP hosts.
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* FX06 — MCP process package vs project install honesty.
|
|
3
|
+
*
|
|
4
|
+
* Pure-ish helpers so unit tests need no MCP server. Production MCP runtime
|
|
5
|
+
* calls buildProcessPackageHonesty with the process version + project root.
|
|
6
|
+
*/
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { createRequire } from 'node:module';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Resolve installed arkgate version for a project root (shallow node_modules,
|
|
13
|
+
* then Node module resolution for hoisted monorepos).
|
|
14
|
+
* @param {string} root
|
|
15
|
+
* @returns {string|null}
|
|
16
|
+
*/
|
|
17
|
+
export function readProjectInstalledArkgateVersion(root) {
|
|
18
|
+
const resolvedRoot = path.resolve(root);
|
|
19
|
+
try {
|
|
20
|
+
const shallow = path.join(resolvedRoot, 'node_modules', 'arkgate', 'package.json');
|
|
21
|
+
if (fs.existsSync(shallow)) {
|
|
22
|
+
const v = JSON.parse(fs.readFileSync(shallow, 'utf8')).version;
|
|
23
|
+
return typeof v === 'string' && v.trim() ? v.trim() : null;
|
|
24
|
+
}
|
|
25
|
+
} catch {
|
|
26
|
+
/* fall through */
|
|
27
|
+
}
|
|
28
|
+
try {
|
|
29
|
+
const requireFromProject = createRequire(path.join(resolvedRoot, 'package.json'));
|
|
30
|
+
const pkgJson = requireFromProject.resolve('arkgate/package.json');
|
|
31
|
+
const v = JSON.parse(fs.readFileSync(pkgJson, 'utf8')).version;
|
|
32
|
+
return typeof v === 'string' && v.trim() ? v.trim() : null;
|
|
33
|
+
} catch {
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* @param {{
|
|
40
|
+
* processVersion?: string|null,
|
|
41
|
+
* projectInstalledVersion?: string|null,
|
|
42
|
+
* root?: string,
|
|
43
|
+
* }} input
|
|
44
|
+
* @returns {{
|
|
45
|
+
* schemaVersion: '1.0',
|
|
46
|
+
* notAScore: true,
|
|
47
|
+
* processArkgateVersion: string|null,
|
|
48
|
+
* projectInstalledVersion: string|null,
|
|
49
|
+
* processPackageMismatch: boolean,
|
|
50
|
+
* processStale: boolean,
|
|
51
|
+
* nextAction: string,
|
|
52
|
+
* }}
|
|
53
|
+
*/
|
|
54
|
+
export function buildProcessPackageHonesty(input = {}) {
|
|
55
|
+
const processVersion =
|
|
56
|
+
typeof input.processVersion === 'string' && input.processVersion.trim()
|
|
57
|
+
? input.processVersion.trim()
|
|
58
|
+
: null;
|
|
59
|
+
let projectInstalledVersion =
|
|
60
|
+
input.projectInstalledVersion !== undefined
|
|
61
|
+
? input.projectInstalledVersion
|
|
62
|
+
: null;
|
|
63
|
+
if (
|
|
64
|
+
projectInstalledVersion === null &&
|
|
65
|
+
input.projectInstalledVersion === undefined &&
|
|
66
|
+
typeof input.root === 'string' &&
|
|
67
|
+
input.root
|
|
68
|
+
) {
|
|
69
|
+
projectInstalledVersion = readProjectInstalledArkgateVersion(input.root);
|
|
70
|
+
}
|
|
71
|
+
if (typeof projectInstalledVersion === 'string') {
|
|
72
|
+
projectInstalledVersion = projectInstalledVersion.trim() || null;
|
|
73
|
+
} else if (projectInstalledVersion !== null) {
|
|
74
|
+
projectInstalledVersion = null;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const mismatch =
|
|
78
|
+
processVersion != null &&
|
|
79
|
+
projectInstalledVersion != null &&
|
|
80
|
+
processVersion !== projectInstalledVersion;
|
|
81
|
+
|
|
82
|
+
return {
|
|
83
|
+
schemaVersion: '1.0',
|
|
84
|
+
notAScore: true,
|
|
85
|
+
processArkgateVersion: processVersion,
|
|
86
|
+
projectInstalledVersion,
|
|
87
|
+
processPackageMismatch: mismatch,
|
|
88
|
+
processStale: mismatch,
|
|
89
|
+
nextAction: mismatch
|
|
90
|
+
? 'Restart or retarget the Ark MCP server so process arkgateVersion matches the project install. Prefer project-local CLI (`npx arkgate` / `npx arkgate-check`) until identity is matched and versions align. Multi-checkout users: one expectedRoot per project; never reuse another checkout’s projectId.'
|
|
91
|
+
: projectInstalledVersion == null
|
|
92
|
+
? 'Project has no resolvable node_modules/arkgate; install the package or use CLI from a project that pins arkgate.'
|
|
93
|
+
: 'Process package version matches project install for this MCP root.',
|
|
94
|
+
};
|
|
95
|
+
}
|
|
@@ -10,6 +10,7 @@ import {
|
|
|
10
10
|
claudeSettings,
|
|
11
11
|
codexHooks,
|
|
12
12
|
codexProjectConfig,
|
|
13
|
+
cursorHooks,
|
|
13
14
|
grokHooks,
|
|
14
15
|
grokProjectConfig,
|
|
15
16
|
opencodeProjectConfig,
|
|
@@ -30,7 +31,10 @@ const COMPACT_HOST_TEMPLATES = {
|
|
|
30
31
|
['.agents/hooks.json', antigravityHooks(root)],
|
|
31
32
|
['.mcp.json', mcpJson(root)],
|
|
32
33
|
],
|
|
33
|
-
cursor: (root) => [
|
|
34
|
+
cursor: (root) => [
|
|
35
|
+
['.cursor/mcp.json', mcpJson(root)],
|
|
36
|
+
['.cursor/hooks.json', cursorHooks(root)],
|
|
37
|
+
],
|
|
34
38
|
codex: (root) => [
|
|
35
39
|
['.codex/hooks.json', codexHooks(root)],
|
|
36
40
|
['.codex/config.toml', codexProjectConfig(root)],
|
|
@@ -216,6 +216,9 @@ function requiredWriteOperations(relativePath) {
|
|
|
216
216
|
if (relativePath === '.agents/hooks.json' || relativePath.startsWith('.agents/')) {
|
|
217
217
|
return ['write_to_file', 'replace_file_content', 'multi_replace_file_content'];
|
|
218
218
|
}
|
|
219
|
+
if (relativePath === '.cursor/hooks.json' || relativePath.startsWith('.cursor/hooks')) {
|
|
220
|
+
return ['Write', 'StrReplace'];
|
|
221
|
+
}
|
|
219
222
|
return ['Write', 'Edit', 'MultiEdit'];
|
|
220
223
|
}
|
|
221
224
|
|
|
@@ -284,6 +287,51 @@ function collectPreToolUseGroups(parsed) {
|
|
|
284
287
|
return [];
|
|
285
288
|
}
|
|
286
289
|
|
|
290
|
+
/**
|
|
291
|
+
* Cursor hooks.json (version 1): { hooks: { preToolUse: [{ command, matcher, failClosed }] } }
|
|
292
|
+
* Flat command entries — not Claude's nested `{ hooks: [{ type, command }] }` groups.
|
|
293
|
+
*/
|
|
294
|
+
function cursorHookEvidence(root) {
|
|
295
|
+
const relativePath = '.cursor/hooks.json';
|
|
296
|
+
const text = readText(path.join(root, relativePath));
|
|
297
|
+
let hooks = [];
|
|
298
|
+
try {
|
|
299
|
+
const parsed = JSON.parse(text);
|
|
300
|
+
const entries = Array.isArray(parsed?.hooks?.preToolUse) ? parsed.hooks.preToolUse : [];
|
|
301
|
+
hooks = entries
|
|
302
|
+
.filter((entry) => entry && typeof entry === 'object' && (!entry.type || entry.type === 'command'))
|
|
303
|
+
.map((entry) => ({
|
|
304
|
+
hook: entry,
|
|
305
|
+
invocation: commandArkMcpInvocation(entry?.command),
|
|
306
|
+
operations: matcherOperations(relativePath, entry?.matcher),
|
|
307
|
+
}))
|
|
308
|
+
.filter((entry) => entry.invocation);
|
|
309
|
+
} catch {
|
|
310
|
+
hooks = [];
|
|
311
|
+
}
|
|
312
|
+
const hardHooks = hooks.filter((entry) => entry.invocation.binArgs.includes('--hook'));
|
|
313
|
+
const required = requiredWriteOperations(relativePath);
|
|
314
|
+
const hard = required.every((operation) =>
|
|
315
|
+
hardHooks.some((entry) => entry.operations.includes(operation))
|
|
316
|
+
);
|
|
317
|
+
const repair =
|
|
318
|
+
hard &&
|
|
319
|
+
required.every((operation) =>
|
|
320
|
+
hardHooks.some(
|
|
321
|
+
({ hook, invocation, operations }) =>
|
|
322
|
+
operations.includes(operation) &&
|
|
323
|
+
(invocation.binArgs.includes('--hook-repair') ||
|
|
324
|
+
/^(?:1|true|yes|on)$/i.test(
|
|
325
|
+
String(hook.env?.ARK_HOOK_REPAIR ?? invocation.environment.ARK_HOOK_REPAIR ?? '')
|
|
326
|
+
))
|
|
327
|
+
)
|
|
328
|
+
);
|
|
329
|
+
return {
|
|
330
|
+
hard: hard ? [relativePath] : [],
|
|
331
|
+
repair: repair ? [relativePath] : [],
|
|
332
|
+
};
|
|
333
|
+
}
|
|
334
|
+
|
|
287
335
|
function hookEvidence(root, relativePath) {
|
|
288
336
|
const text = readText(path.join(root, relativePath));
|
|
289
337
|
let hooks = [];
|
|
@@ -396,6 +444,7 @@ export function detectWritePathInventory(root) {
|
|
|
396
444
|
const claudeHook = hookEvidence(root, '.claude/settings.json');
|
|
397
445
|
const grokHook = hookEvidence(root, '.grok/hooks/ark-write-gate.json');
|
|
398
446
|
const antigravityHook = hookEvidence(root, '.agents/hooks.json');
|
|
447
|
+
const cursorHook = cursorHookEvidence(root);
|
|
399
448
|
const hosts = {
|
|
400
449
|
claude: hostRecord(
|
|
401
450
|
claudeHook.hard,
|
|
@@ -416,7 +465,19 @@ export function detectWritePathInventory(root) {
|
|
|
416
465
|
antigravityHook.repair,
|
|
417
466
|
merge
|
|
418
467
|
),
|
|
419
|
-
cursor: hostRecord(
|
|
468
|
+
cursor: hostRecord(
|
|
469
|
+
cursorHook.hard,
|
|
470
|
+
[
|
|
471
|
+
...mcpEvidence(root, '.cursor/mcp.json'),
|
|
472
|
+
// Shared project MCP is also a valid advisory surface for Cursor sessions.
|
|
473
|
+
...mcpEvidence(root, '.mcp.json'),
|
|
474
|
+
],
|
|
475
|
+
// EH07: hooks may emit --hook-repair envelopes, but Cursor Write updated_input
|
|
476
|
+
// reinjection is not package-guaranteed — keep inventory repair-payload false
|
|
477
|
+
// (envelope honesty lives on support.repair-envelope-emitted).
|
|
478
|
+
[],
|
|
479
|
+
merge
|
|
480
|
+
),
|
|
420
481
|
// Codex 0.123+ emits PreToolUse for the native apply_patch handler, but some
|
|
421
482
|
// Code Mode hosts execute deferred nested writes without dispatching that
|
|
422
483
|
// project hook. Keep the installed hook as best-effort protection; do not
|
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var tn=Object.defineProperty;var zs=Object.getOwnPropertyDescriptor;var qs=Object.getOwnPropertyNames;var Ys=Object.prototype.hasOwnProperty;var Ws=(e,t)=>{for(var n in t)tn(e,n,{get:t[n],enumerable:!0})},Js=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of qs(t))!Ys.call(e,s)&&s!==n&&tn(e,s,{get:()=>t[s],enumerable:!(r=zs(t,s))||r.enumerable});return e};var Zs=e=>Js(tn({},"__esModule",{value:!0}),e);var Pa={};Ws(Pa,{ADAPTER_DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>nn,AGENT_PROJECTION_BEGIN_MARKER:()=>Ns,AGENT_PROJECTION_END_MARKER:()=>Zn,AGENT_PROJECTION_ENFORCEMENT_SURFACES:()=>Jt,AGENT_PROJECTION_NON_ENFORCEMENT_LABEL:()=>Xn,AGENT_SKILLS_PACKAGE_RELATIVE_ROOT:()=>rr,AGENT_SKILL_ENTRY_FILENAME:()=>ir,ANALYSIS_IR_SCHEMA_VERSION:()=>Ct,ARK_AGENT_PROJECTION_SCHEMA_VERSION:()=>Ls,ARK_AGENT_SKILLS_PACKAGE_SCHEMA_VERSION:()=>Us,ARK_ANALYSIS_RESULT_SCHEMA:()=>gr,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>fr,ARK_CONFIG_SCHEMA:()=>bt,ARK_CONFIG_SCHEMA_VERSION:()=>Tr,ARK_DESIGN_DELTA_SCHEMA_VERSION:()=>ls,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION:()=>os,ARK_IMPROVEMENT_COMPASS_SCHEMA_VERSION:()=>at,ARK_PROJECT_IDENTITY_SCHEMA:()=>hr,ARK_PROJECT_IDENTITY_SCHEMA_URL:()=>an,ARK_PROJECT_IDENTITY_SCHEMA_VERSION:()=>yr,ARK_RULES_SCHEMA:()=>_t,ARK_RULES_SCHEMA_VERSION:()=>Vr,ARK_RULE_SENSORS:()=>kn,ARK_SKILL_NAMES:()=>dt,ARK_SKILL_NAME_COUNT:()=>ar,ARK_STATUS_MANIFEST_SCHEMA:()=>Es,ARK_STATUS_MANIFEST_SCHEMA_URL:()=>Mn,ARK_STATUS_MANIFEST_SCHEMA_VERSION:()=>hs,DEFAULT_AGENT_PROJECTION_RULE_IDS:()=>ws,DIAGNOSTIC_CATALOG:()=>nt,DIAGNOSTIC_CATALOG_SCHEMA_VERSION:()=>cs,DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>Kt,DIAGNOSTIC_RULE_IDS:()=>ds,EffectiveContractError:()=>Je,FLAT_SKILL_TEMPLATES_RELATIVE_ROOT:()=>sr,IMPROVEMENT_COMPASS_OUT_OF_SCOPE_LENSES:()=>ce,IMPROVEMENT_COMPASS_TOP_RESIDUAL_CAP:()=>lt,IMPROVEMENT_LENS_IDS:()=>ot,POLICY_DELTA_SCHEMA_VERSION:()=>wt,PROJECT_BINDING_SCHEMA:()=>ln,PROJECT_EXPECTATION_SCHEMA:()=>on,RESOLVED_CANDIDATE_FACTS_SCHEMA:()=>vt,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION:()=>ae,STATUS_COMPASS_FACTS_SOURCES:()=>Fn,STATUS_COMPASS_MODES:()=>$n,STATUS_COMPASS_REASON_CODES:()=>it,adapterDocsCodePath:()=>sn,adapterFindingOccurrenceTargetKeys:()=>pt,adapterFindingRefFromTargetKey:()=>rn,adapterFindingTargetKey:()=>ft,agentProjectionContentIdentity:()=>ct,agentSkillEntryRelativePath:()=>dr,agentSkillPackageFileRelativePath:()=>Bs,analyzeArchitectureConvergence:()=>ge,analyzeChange:()=>Qe,analyzePolicyDelta:()=>_n,analyzeProject:()=>xe,analyzeResolvedProject:()=>Te,buildAgentProjectionBeginMarker:()=>er,buildAgentProjectionBlock:()=>Fs,buildAgentProjectionBody:()=>Xt,buildAgentProjectionMeta:()=>Ds,buildArkRuleFileHints:()=>Ut,buildEffectiveArkRules:()=>xt,buildImprovementCompass:()=>Ts,buildRulesInventory:()=>is,buildStatusManifest:()=>Is,canPromoteInvariant:()=>Pt,catalogFixForRuleId:()=>gs,catalogWhyForRuleId:()=>ys,classifyArkPolicyDelta:()=>Mt,classifyStatusWritePath:()=>Hn,collectAnalysisConfigWarnings:()=>tt,collectEmptyAppliesToFindings:()=>jt,collectForbiddenCapabilityUses:()=>fe,createAICodeGate:()=>Sn,createAdapterResult:()=>mr,createArchitectureProfile:()=>Be,createArchitectureProfileFromArkConfig:()=>En,createElevenLayerArkConfig:()=>vn,createProjectId:()=>Ar,createProjectIdentity:()=>Ir,createResolvedCandidateFacts:()=>Et,defaultHonestLabel:()=>Vn,deriveArkRuleFileHints:()=>Tn,detectArchitectureCycles:()=>Dt,deterministicHash:()=>M,diagnosticDocsFragment:()=>wn,diagnosticDocsPath:()=>fs,effectiveContractPolicyPayload:()=>Ot,elevenLayerProfile:()=>Ge,emptyEffectiveArkRules:()=>le,evaluateArchitectureGraph:()=>Ie,evaluateArkRuleSensors:()=>Vt,evaluateInvariantCoverage:()=>Tt,evaluateStatusBinding:()=>Dn,explainViolation:()=>xn,extractAgentProjectionBlock:()=>Wt,extractClassShapesFromSource:()=>Qr,extractSemanticDependencies:()=>ue,flatSkillTemplateFileRelativePath:()=>Ks,formatAgentProjectionCatalogShortList:()=>tr,formatAgentProjectionLayers:()=>Yt,formatImprovementCompassDoctorLines:()=>Ps,formatImprovementCompassResidualLabels:()=>Wn,getDiagnosticCatalogEntry:()=>rt,inventoryToExtractionCard:()=>as,isArkSkillName:()=>en,isCataloguedOrArkRuleFamily:()=>us,isKnownDiagnosticCode:()=>ps,isValidAgentSkillName:()=>or,loadArkConfigContract:()=>Ue,loadArkRulesContract:()=>We,loadContract:()=>Xe,loadResolvedCandidateFacts:()=>re,mergeAgentProjectionDocument:()=>js,normalizeSkillContent:()=>Qt,normalizeStatusImprovementCompass:()=>Un,parseAgentProjectionStamp:()=>nr,parseArkConfigJson:()=>Rt,parseArkRulesJson:()=>jr,parseSkillDocument:()=>lr,policyDeltaAcknowledgementMatches:()=>$t,preflightChange:()=>Pn,preflightResolvedChange:()=>Ln,primaryImprovementCompassNextAction:()=>Jn,projectStatusImprovementCompass:()=>zt,projectionHasNonEnforcementLabel:()=>Vs,projectionMatchesPackageVersion:()=>Hs,resolveEffectiveContract:()=>Gr,resolveStatusNextAction:()=>jn,resolvedFactsEvidenceRequirementsHash:()=>ke,serializeDiagnosticCatalog:()=>ms,stableSerialize:()=>x,statusCompassResidualIsSubsetOfDoctor:()=>Rs,toAdapterDiagnostic:()=>ut,unavailableStatusImprovementCompass:()=>Ss,validateAgentSkillDocument:()=>cr,validateAgentSkillsPackage:()=>Gs,version:()=>pr});module.exports=Zs(Pa);var pr="4.5.6";var fr="1.5",nn="docs/diagnostics.md";function v(e){return typeof e=="string"&&e.length>0?e:void 0}function ur(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function ft(e){let t=typeof e.ruleId=="string"?e.ruleId:typeof e.code=="string"?e.code:void 0,n=typeof e.file=="string"?e.file:void 0,r=typeof e.fromLayer=="string"?e.fromLayer:void 0,s=typeof e.toLayer=="string"?e.toLayer:void 0,i=typeof e.target=="string"?e.target:void 0;return[t,n,r??"",s??"",i??""].join("|")}function pt(e){let t=new Map;return e.map(n=>{let r=ft(n),s=(t.get(r)??0)+1;return t.set(r,s),s===1?r:`${r}#${s}`})}function rn(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}function sn(e){return`${nn}#${e}`}function Xs(e,t,n){if(e==="LAYER_IMPORT_VIOLATION")return t.typeOnly||n.targetTypeOnlyExports===!0||n.namedBindingsTypeOnly===!0?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":n.peerIsolation===!0?"Extract the shared dependency to a shared layer, test at the public interface, then preflight again.":`Define a port in ${t.fromLayer??"the source layer"}, inject the ${t.toLayer??"outer-layer"} implementation, test at the public interface, then preflight again.`;if(e==="FORBIDDEN_GLOBAL")return`Inject ${t.target??"the capability"} through a port, test at the public interface, then preflight again.`;if(e==="CAPABILITY_VIOLATION")return`Define a ${v(n.capability)??"capability"} port in ${t.fromLayer??"the walled layer"}, bind the implementation outside it, test at the public interface, then preflight again.`;if(e==="CIRCULAR_DEPENDENCY")return"Extract the shared dependency into a third module, test at the public interface, then preflight again.";if(e==="RAW_EVENT_PUBLISH")return"Publish through a registered intent creator, then run Ark again.";if(e==="PUBLISH_MISSING_SOURCE")return"Add metadata.source to the publish call, then run Ark again.";if(e==="ARKRULE_STRUCTURE"||e==="ARKRULE_INVARIANT"||e==="INVARIANT_UNCOVERED"||e.startsWith("ARKRULE_")){let r=t.arkruleSource??"arkrules/<Layer>.json";return`Fix the structure or invariant for ${t.arkruleId??"the ArkRule"} (declared in ${r}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`}return`Resolve ${e} without weakening ark.config.json, then run Ark again.`}function ut(e,t="error",n){let r=v(e.ruleId)??v(e.code)??"ARK_UNKNOWN",s=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,i={...v(e.target)?{target:v(e.target)}:{},...v(e.fromLayer)?{fromLayer:v(e.fromLayer)}:{},...v(e.toLayer)?{toLayer:v(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{},...typeof e.targetTypeOnlyExports=="boolean"?{targetTypeOnlyExports:e.targetTypeOnlyExports}:{},...typeof e.sourcePureTypeModule=="boolean"?{sourcePureTypeModule:e.sourcePureTypeModule}:{},...typeof e.namedBindingsTypeOnly=="boolean"?{namedBindingsTypeOnly:e.namedBindingsTypeOnly}:{},...typeof e.portProofEligible=="boolean"?{portProofEligible:e.portProofEligible}:{},...typeof e.peerIsolation=="boolean"?{peerIsolation:e.peerIsolation}:{},...v(e.capability)?{capability:v(e.capability)}:{},...v(e.edgeKind)?{edgeKind:v(e.edgeKind)}:{},...v(e.arkruleId)?{arkruleId:v(e.arkruleId)}:{},...v(e.arkruleSource)?{arkruleSource:v(e.arkruleSource)}:{}},a=n??ft(e),o=rn(a);return{ruleId:r,severity:s,message:v(e.message)??r,location:{file:v(e.file)??"<unknown>",line:ur(e.line,1),column:ur(e.column,1)},evidence:i,nextAction:v(e.nextAction)??Xs(r,i,e),findingRef:o,targetKey:a,docsCodePath:sn(r)}}function mr(e){let t=e.completeness??"complete",n=e.mode??"lexical-compatibility";if(t==="complete"&&(e.completenessReasons?.length??0)>0)throw new Error("completenessReasons must be empty when completeness is complete.");let r=t==="complete"?[]:e.completenessReasons&&e.completenessReasons.length>0?e.completenessReasons.map(m=>({code:v(m.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:v(m.message)??`Analysis ${t}: required evidence is incomplete.`,...v(m.file)?{file:v(m.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],s={...v(e.policyHash)?{policyHash:v(e.policyHash)}:{},...v(e.resolverIdentity)?{resolverIdentity:v(e.resolverIdentity)}:{},...v(e.factsHash)?{factsHash:v(e.factsHash)}:{},...v(e.candidateTreeHash)?{candidateTreeHash:v(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let m of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!s[m])throw new Error(`${m} is required for resolved ${t} adapter evidence.`)}let i=e.violations??[],a=e.warnings??[],o=pt(i),d=pt(a),u=[...i.map((m,c)=>ut(m,"error",o[c])),...a.map((m,c)=>ut(m,"warning",d[c]))],g={schemaVersion:"1.5",completenessReasons:r,diagnostics:u};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...g,mode:n,valid:!1,completeness:t,...s};let m={policyHash:s.policyHash,resolverIdentity:s.resolverIdentity,factsHash:s.factsHash,candidateTreeHash:s.candidateTreeHash};return t==="complete"?{...g,mode:n,valid:e.valid,completeness:t,...m}:{...g,mode:n,valid:!1,completeness:t,...m}}return t==="complete"?{...g,mode:n,valid:e.valid,completeness:t,...s}:{...g,mode:n,valid:!1,completeness:t,...s}}var gr={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","mode","valid","completeness","completenessReasons","diagnostics"],allOf:[{if:{properties:{completeness:{enum:["partial","unavailable"]}},required:["completeness"]},then:{properties:{valid:{const:!1}}}},{if:{properties:{mode:{const:"resolved-candidate-facts"},completeness:{enum:["complete","partial"]}},required:["mode","completeness"]},then:{required:["policyHash","resolverIdentity","factsHash","candidateTreeHash"]}},{if:{properties:{completeness:{const:"complete"}},required:["completeness"]},then:{properties:{completenessReasons:{maxItems:0}}},else:{properties:{completenessReasons:{minItems:1}}}}],properties:{schemaVersion:{const:"1.5"},mode:{enum:["lexical-compatibility","resolved-candidate-facts"]},valid:{type:"boolean"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:{type:"string",minLength:1},message:{type:"string",minLength:1},file:{type:"string",minLength:1}}}},policyHash:{type:"string",minLength:1},resolverIdentity:{type:"string",minLength:1},factsHash:{type:"string",minLength:1},candidateTreeHash:{type:"string",minLength:1},diagnostics:{type:"array",items:{type:"object",additionalProperties:!1,required:["ruleId","severity","message","location","evidence"],properties:{ruleId:{type:"string",minLength:1},severity:{enum:["error","warning"]},message:{type:"string",minLength:1},location:{type:"object",additionalProperties:!1,required:["file","line","column"],properties:{file:{type:"string",minLength:1},line:{type:"integer",minimum:1},column:{type:"integer",minimum:1}}},evidence:{type:"object",additionalProperties:!1,properties:{target:{type:"string"},fromLayer:{type:"string"},toLayer:{type:"string"},typeOnly:{type:"boolean"},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"},peerIsolation:{type:"boolean"},capability:{type:"string",minLength:1},edgeKind:{type:"string",minLength:1},arkruleId:{type:"string",minLength:1},arkruleSource:{type:"string",minLength:1}}},nextAction:{type:"string",minLength:1},findingRef:{type:"string",minLength:1,pattern:"^fnv1a-[0-9a-f]{8}$"},targetKey:{type:"string",minLength:1},docsCodePath:{type:"string",minLength:1}}}}}};var yr="1.0",an="https://unpkg.com/arkgate@4/schemas/ark.project-identity.schema.json",mt="^sha256:[a-f0-9]{64}$",on={type:"object",additionalProperties:!1,properties:{expectedRoot:{type:"string",minLength:1,description:"Absolute expected workspace/project directory. The initial authoritative handshake requires the exact project root; descendant calls also require expectedProjectId."},expectedProjectId:{type:"string",pattern:mt,description:"Project id previously returned by ark_identity or ark_manifest."}}},ln={type:"object",additionalProperties:!1,required:["status","authoritative"],properties:{status:{enum:["matched","unverified","mismatch"]},authoritative:{type:"boolean"},expectedRoot:{type:"string",minLength:1},expectedProjectId:{type:"string",pattern:mt},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},hr={$schema:"https://json-schema.org/draft/2020-12/schema",$id:an,title:"ArkGate MCP project identity",description:"Stable project binding plus separate runtime and architecture-contract evidence.",type:"object",additionalProperties:!1,required:["schemaVersion","projectId","resolvedRoot","resolvedConfigPath","arkgateVersion","contractHash","contractSource","runtimeId","processStartedAt"],properties:{schemaVersion:{const:"1.0"},projectId:{type:"string",pattern:mt},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{type:"string",minLength:1},arkgateVersion:{type:"string",minLength:1},contractHash:{type:"string",pattern:mt},contractSource:{enum:["project","default-profile","manifest"]},runtimeId:{type:"string",minLength:1},processStartedAt:{type:"string",format:"date-time"}},$defs:{expectation:on,binding:ln}};function Ar(e,t,n){if(!e||!t)throw new Error("Project identity requires resolvedRoot and resolvedConfigPath.");let r=n(JSON.stringify({resolvedRoot:e,resolvedConfigPath:t})).toLowerCase();if(!/^[a-f0-9]{64}$/.test(r))throw new Error("Project identity hash adapter must return 64 hexadecimal SHA-256 characters.");return`sha256:${r}`}function Ir(e){return{schemaVersion:"1.0",...e}}var dn=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),un=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),fn=Object.freeze(Object.keys(un).sort()),cn=Object.freeze({fs:"filesystem","node:fs":"filesystem","fs/promises":"filesystem","node:fs/promises":"filesystem","fs-extra":"filesystem","graceful-fs":"filesystem",memfs:"filesystem",chokidar:"filesystem",http:"network",https:"network",http2:"network",net:"network",tls:"network",dgram:"network",dns:"network","node:http":"network","node:https":"network","node:http2":"network","node:net":"network","node:tls":"network","node:dgram":"network","node:dns":"network",axios:"network",undici:"network","node-fetch":"network",got:"network",ky:"network",superagent:"network",ws:"network",process:"process","node:process":"process",child_process:"process","node:child_process":"process","@prisma/client":"persistence",prisma:"persistence",pg:"persistence",mysql:"persistence",mysql2:"persistence",mongodb:"persistence",mongoose:"persistence",sqlite3:"persistence","better-sqlite3":"persistence",redis:"persistence",ioredis:"persistence",typeorm:"persistence",knex:"persistence","drizzle-orm":"persistence",sequelize:"persistence",kysely:"persistence","@supabase/supabase-js":"persistence"}),pn=Object.freeze({process:Object.freeze(["process","node:process"])});function Me(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=cn[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),s=cn[r];if(s)return s;let i=e.indexOf("/",n+1);return i<0?null:cn[e.slice(0,i)]??null}function se(e,t){for(let n of t)if(pn[n]?.includes(e))return n;return null}function gt(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),s=un[r];if(s)return s}return null}function be(e){if(e?.pure===!0)return[...dn].sort();let n=(e?.capabilities?.deny??[]).filter(r=>dn.includes(r));return[...new Set(n)].sort()}function $e(e,t){if(t.length===0)return!1;let n=new Set(t),r=e.split(".");for(let s=r.length;s>=1;s-=1)if(n.has(r.slice(0,s).join(".")))return!0;return!1}function yt(e){let t=new Set,n=new Set,r=Object.keys(un);for(let s of e?.forbiddenGlobals??[]){let i=r.filter(a=>a===s||a.startsWith(`${s}.`));if(i.length===0)n.add(s);else for(let a of i)t.add(`ambient:${a}`);for(let a of pn[s]??[])t.add(`import-exact:${a}`)}for(let s of be(e)){if(t.add(`import:${s}`),s==="process")for(let i of pn.process)t.add(`import-exact:${i}`);for(let i of r)gt(i)===s&&t.add(`ambient:${i}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}var br=new Map;function Sr(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function ht(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let s=e[n+1];if("*?{}[],".includes(s)||s==="\\"){t+="\\"+s,n+=1;continue}t+="/";continue}t+=r}return t}function Qs(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="{")t+=1;else if(r==="}"&&(t-=1,t<0))return!1}return t===0}function pe(e){let t=br.get(e);if(t)return t;let n=ht(e),r=Qs(n),s="",i=0;for(let o=0;o<n.length;o+=1){let d=n[o];d==="\\"&&o+1<n.length?(s+=Sr(n[o+1]),o+=1):d==="*"?n[o+1]==="*"?n[o+2]==="/"?(s+="(?:.*/)?",o+=2):(s+=".*",o+=1):s+="[^/]*":d==="?"?s+="[^/]":d==="{"&&r?(s+="(?:",i+=1):d==="}"&&r&&i>0?(s+=")",i-=1):d===","&&r&&i>0?s+="|":s+=Sr(d)}let a=new RegExp(`^${s}$`);return br.set(e,a),a}function ei(e){return ht(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}function mn(e,t){let n=ht(String(e)),r=ei(n),s=n.replace(/\*/g,"").length,i=r.length*1e4+s;if(t==null||t==="")return i;let a=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return s;let o=0,d=-1;for(let u of r){let g=-1;for(let m=o;m<a.length;m+=1)if(a[m]===u){g=m;break}if(g<0)return i;d=g,o=g+1}return(d+1)*1e6+r.length*1e4+s}function Q(e,t){let n=String(e).split(/[/\\]/).join("/"),r,s=-1;for(let i of t??[])if(!(i.exclude??[]).some(a=>pe(a).test(n))){for(let a of i.patterns??[])if(pe(a).test(n)){let o=mn(a,n);o>s&&(s=o,r=i.name)}}return r}function Rr(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),r=new Set(t.map(s=>String(s).toLowerCase()));for(let s=0;s<n.length-1;s+=1)if(r.has(n[s].toLowerCase()))return`${n[s].toLowerCase()}/${n[s+1].toLowerCase()}`}function ti(e){let t=new Set;for(let n of e??[]){let s=ht(String(n)).split("/").filter(Boolean);for(let i=0;i<s.length;i+=1){let a=s[i];if((a==="**"||a==="*")&&i>0){let o=s[i-1];o&&!o.includes("*")&&!o.includes("{")&&!o.includes("}")&&t.add(o)}}}return[...t]}function ni(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(s=>typeof s=="string"&&s.length>0);let r=(n??[]).find(s=>s.name===t);return ti(r?.patterns)}function ri(e){return!e.fromPath||!e.toPath||e.folderCount<=0||!e.fromSlice||!e.toSlice?!0:e.fromSlice!==e.toSlice}function ee(e,t,n,r){for(let s of e??[])if(!(s.from!==t||s.to!==n)&&s.allowed===!1){if(s.peerIsolation){let i=r?.fromPath,a=r?.toPath,o=ni(s,t,r?.layers),d=i&&a?Rr(i,o):void 0,u=i&&a?Rr(a,o):void 0;if(ri({fromPath:i,toPath:a,folderCount:o.length,fromSlice:d,toSlice:u}))return s;continue}if(t!==n)return s}}function Se(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function Cr(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function Er(e,t){if(e.isImportDeclaration(t)){let r=t.importClause;if(!r)return!1;if(r.isTypeOnly)return!0;let s=r.namedBindings;return!!(s&&e.isNamedImports(s)&&s.elements.length>0&&s.elements.every(i=>i.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(r=>r.isTypeOnly))}function kr(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=s=>s===t.fileName?t:void 0,r.fileExists=s=>s===t.fileName,r.readFile=s=>s===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}function gn(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function yn(e,t,n,r){let s=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,i;try{i=s?t.getShorthandAssignmentValueSymbol(r.parent):gn(t,r)}catch{i=void 0}return!!i?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}function ue(e,t){let n,r=[],s=(a,o,d,u=!1)=>r.push({specifier:d,kind:o,line:Cr(t,a),typeOnly:u,unresolved:d===void 0,node:a}),i=a=>{if(e.isImportDeclaration(a))s(a,"import",Se(e,a.moduleSpecifier),Er(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)s(a,"export",Se(e,a.moduleSpecifier),Er(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))s(a,"require",Se(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let o=a.expression.kind===e.SyntaxKind.ImportKeyword,u=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!yn(e,n??(n=kr(e,t)),t,a.expression);(o||u)&&s(a,u?"require":"dynamic-import",Se(e,a.arguments[0]))}e.forEachChild(a,i)};return i(t),r}function si(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let s=Se(e,r.argumentExpression);if(s===void 0)return;n.unshift(s)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}function ii(e,t){let n=t.parent;return e.isPropertyAccessExpression(n)||e.isElementAccessExpression(n)?!1:e.isExpressionNode(t)&&!e.isInTypeQuery(t)||e.isShorthandPropertyAssignment(n)&&n.name===t}function vr(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let r=n.length;r>=1;r-=1){let s=n.slice(0,r).join(".");if(e.has(s))return s}}function fe(e,t,n){if(n.length===0)return[];let r=new Set(n),s=kr(e,t),i=new Map,a=new Set;for(let c of t.statements)if(e.isVariableStatement(c))for(let l of c.declarationList.declarations)e.isIdentifier(l.name)&&a.add(l.name.text);let o=c=>{let l=si(e,c);if(!l)return;let p=gn(s,l.root),y=p?i.get(p):void 0;return y?[...y,...l.segments.slice(1)]:yn(e,s,t,l.root)||a.has(l.root.text)?void 0:l.segments};for(let c of t.statements)if(e.isVariableStatement(c))for(let l of c.declarationList.declarations){if(!l.initializer||!e.isIdentifier(l.name))continue;let p=o(l.initializer),y=gn(s,l.name);!p||!y||i.set(y,p)}let d=[],u=new Set,g=(c,l)=>{let p=Cr(t,l),y=`${c}:${l.getStart(t)}`;u.has(y)||(u.add(y),d.push({name:c,line:p,node:l}))},m=c=>{let l=c.parent&&(e.isPropertyAccessExpression(c.parent)||e.isElementAccessExpression(c.parent))&&c.parent.expression===c;if((e.isPropertyAccessExpression(c)||e.isElementAccessExpression(c))&&!l){let p=o(c),y=p?vr(r,p):void 0;y&&g(y,c)}else e.isIdentifier(c)&&r.has(c.text)&&ii(e,c)&&!yn(e,s,t,c)&&g(c.text,c);if(e.isVariableDeclaration(c)&&e.isObjectBindingPattern(c.name)&&c.initializer){let p=o(c.initializer);if(p)for(let y of c.name.elements){if(!e.isIdentifier(y.name))continue;let I=y.propertyName?Se(e,y.propertyName)??y.propertyName.text:y.name.text,R=vr(r,[...p,I]);R&&g(R,c.initializer)}}e.forEachChild(c,m)};return m(t),d}function hn(e,t,n){let r=[];for(let s of n?.dependencies??ue(e,t)){if(s.typeOnly||!s.specifier)continue;let i=Me(s.specifier);i&&r.push({capability:i,symbol:s.specifier,line:s.line,source:"import-based"})}for(let s of n?.ambientUses??fe(e,t,fn)){let i=gt(s.name);i&&r.push({capability:i,symbol:s.name,line:s.line,source:"ambient-global"})}return r.sort((s,i)=>s.line-i.line||s.capability.localeCompare(i.capability)||s.symbol.localeCompare(i.symbol))}var An={RAW_EVENT_PUBLISH:"Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts and tooling.",PUBLISH_MISSING_SOURCE:"Strict Ark publish calls must include metadata.source."},In=Object.freeze([{layer:"DomainModel",prefixes:["Domain."]},{layer:"ApplicationOrchestration",prefixes:["Application."]},{layer:"PersistenceAdapters",prefixes:["Adapter.Persistence.","Adapter.Repository."]},{layer:"IntegrationAdapters",prefixes:["Adapter.Integration.","Adapter.External."]},{layer:"WorkflowSagaEngine",prefixes:["Workflow."]},{layer:"BackgroundJobsScheduling",prefixes:["Job."]},{layer:"PresentationAdapters",prefixes:["Presentation.","Adapter.Presentation.","Adapter.Api."]},{layer:"ReportingReadModels",prefixes:["Reporting."]},{layer:"ExtensibilityMetadata",prefixes:["Metadata."]},{layer:"SecurityAuditObservability",prefixes:["Security.","Audit.","Observability."]},{layer:"Kernel",prefixes:["Kernel."]}]);function bn(e,t){return t.flatMap((r,s)=>(r.prefixes??r.intentPrefixes??[]).map(i=>({layer:r.name,layerIndex:s,prefix:i.endsWith(".")?i:`${i}.`}))).filter(({prefix:r})=>e.startsWith(r)).sort((r,s)=>s.prefix.length-r.prefix.length||r.layerIndex-s.layerIndex)[0]?.layer}function me(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function Fe(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&me(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:An.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:An.PUBLISH_MISSING_SOURCE}),t}function w(e,t,n){return{ruleId:e,code:e,message:t,...n}}function Re(e,t){return e.slice(0,t).split(`
|
|
1
|
+
"use strict";var tn=Object.defineProperty;var zs=Object.getOwnPropertyDescriptor;var qs=Object.getOwnPropertyNames;var Ys=Object.prototype.hasOwnProperty;var Ws=(e,t)=>{for(var n in t)tn(e,n,{get:t[n],enumerable:!0})},Js=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of qs(t))!Ys.call(e,s)&&s!==n&&tn(e,s,{get:()=>t[s],enumerable:!(r=zs(t,s))||r.enumerable});return e};var Zs=e=>Js(tn({},"__esModule",{value:!0}),e);var Pa={};Ws(Pa,{ADAPTER_DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>nn,AGENT_PROJECTION_BEGIN_MARKER:()=>Ns,AGENT_PROJECTION_END_MARKER:()=>Zn,AGENT_PROJECTION_ENFORCEMENT_SURFACES:()=>Jt,AGENT_PROJECTION_NON_ENFORCEMENT_LABEL:()=>Xn,AGENT_SKILLS_PACKAGE_RELATIVE_ROOT:()=>rr,AGENT_SKILL_ENTRY_FILENAME:()=>ir,ANALYSIS_IR_SCHEMA_VERSION:()=>Ct,ARK_AGENT_PROJECTION_SCHEMA_VERSION:()=>Ls,ARK_AGENT_SKILLS_PACKAGE_SCHEMA_VERSION:()=>Us,ARK_ANALYSIS_RESULT_SCHEMA:()=>gr,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>fr,ARK_CONFIG_SCHEMA:()=>bt,ARK_CONFIG_SCHEMA_VERSION:()=>Tr,ARK_DESIGN_DELTA_SCHEMA_VERSION:()=>ls,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION:()=>os,ARK_IMPROVEMENT_COMPASS_SCHEMA_VERSION:()=>at,ARK_PROJECT_IDENTITY_SCHEMA:()=>hr,ARK_PROJECT_IDENTITY_SCHEMA_URL:()=>an,ARK_PROJECT_IDENTITY_SCHEMA_VERSION:()=>yr,ARK_RULES_SCHEMA:()=>_t,ARK_RULES_SCHEMA_VERSION:()=>Vr,ARK_RULE_SENSORS:()=>kn,ARK_SKILL_NAMES:()=>dt,ARK_SKILL_NAME_COUNT:()=>ar,ARK_STATUS_MANIFEST_SCHEMA:()=>Es,ARK_STATUS_MANIFEST_SCHEMA_URL:()=>Mn,ARK_STATUS_MANIFEST_SCHEMA_VERSION:()=>hs,DEFAULT_AGENT_PROJECTION_RULE_IDS:()=>ws,DIAGNOSTIC_CATALOG:()=>nt,DIAGNOSTIC_CATALOG_SCHEMA_VERSION:()=>cs,DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>Kt,DIAGNOSTIC_RULE_IDS:()=>ds,EffectiveContractError:()=>Je,FLAT_SKILL_TEMPLATES_RELATIVE_ROOT:()=>sr,IMPROVEMENT_COMPASS_OUT_OF_SCOPE_LENSES:()=>ce,IMPROVEMENT_COMPASS_TOP_RESIDUAL_CAP:()=>lt,IMPROVEMENT_LENS_IDS:()=>ot,POLICY_DELTA_SCHEMA_VERSION:()=>wt,PROJECT_BINDING_SCHEMA:()=>ln,PROJECT_EXPECTATION_SCHEMA:()=>on,RESOLVED_CANDIDATE_FACTS_SCHEMA:()=>vt,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION:()=>ae,STATUS_COMPASS_FACTS_SOURCES:()=>Fn,STATUS_COMPASS_MODES:()=>$n,STATUS_COMPASS_REASON_CODES:()=>it,adapterDocsCodePath:()=>sn,adapterFindingOccurrenceTargetKeys:()=>pt,adapterFindingRefFromTargetKey:()=>rn,adapterFindingTargetKey:()=>ft,agentProjectionContentIdentity:()=>ct,agentSkillEntryRelativePath:()=>dr,agentSkillPackageFileRelativePath:()=>Bs,analyzeArchitectureConvergence:()=>ge,analyzeChange:()=>Qe,analyzePolicyDelta:()=>_n,analyzeProject:()=>xe,analyzeResolvedProject:()=>Te,buildAgentProjectionBeginMarker:()=>er,buildAgentProjectionBlock:()=>Fs,buildAgentProjectionBody:()=>Xt,buildAgentProjectionMeta:()=>Ds,buildArkRuleFileHints:()=>Ut,buildEffectiveArkRules:()=>xt,buildImprovementCompass:()=>Ts,buildRulesInventory:()=>is,buildStatusManifest:()=>Is,canPromoteInvariant:()=>Pt,catalogFixForRuleId:()=>gs,catalogWhyForRuleId:()=>ys,classifyArkPolicyDelta:()=>Mt,classifyStatusWritePath:()=>Hn,collectAnalysisConfigWarnings:()=>tt,collectEmptyAppliesToFindings:()=>jt,collectForbiddenCapabilityUses:()=>fe,createAICodeGate:()=>Sn,createAdapterResult:()=>mr,createArchitectureProfile:()=>Be,createArchitectureProfileFromArkConfig:()=>En,createElevenLayerArkConfig:()=>vn,createProjectId:()=>Ar,createProjectIdentity:()=>Ir,createResolvedCandidateFacts:()=>Et,defaultHonestLabel:()=>Vn,deriveArkRuleFileHints:()=>Tn,detectArchitectureCycles:()=>Dt,deterministicHash:()=>M,diagnosticDocsFragment:()=>wn,diagnosticDocsPath:()=>fs,effectiveContractPolicyPayload:()=>Ot,elevenLayerProfile:()=>Ge,emptyEffectiveArkRules:()=>le,evaluateArchitectureGraph:()=>Ie,evaluateArkRuleSensors:()=>Vt,evaluateInvariantCoverage:()=>Tt,evaluateStatusBinding:()=>Dn,explainViolation:()=>xn,extractAgentProjectionBlock:()=>Wt,extractClassShapesFromSource:()=>Qr,extractSemanticDependencies:()=>ue,flatSkillTemplateFileRelativePath:()=>Ks,formatAgentProjectionCatalogShortList:()=>tr,formatAgentProjectionLayers:()=>Yt,formatImprovementCompassDoctorLines:()=>Ps,formatImprovementCompassResidualLabels:()=>Wn,getDiagnosticCatalogEntry:()=>rt,inventoryToExtractionCard:()=>as,isArkSkillName:()=>en,isCataloguedOrArkRuleFamily:()=>us,isKnownDiagnosticCode:()=>ps,isValidAgentSkillName:()=>or,loadArkConfigContract:()=>Ue,loadArkRulesContract:()=>We,loadContract:()=>Xe,loadResolvedCandidateFacts:()=>re,mergeAgentProjectionDocument:()=>js,normalizeSkillContent:()=>Qt,normalizeStatusImprovementCompass:()=>Un,parseAgentProjectionStamp:()=>nr,parseArkConfigJson:()=>Rt,parseArkRulesJson:()=>jr,parseSkillDocument:()=>lr,policyDeltaAcknowledgementMatches:()=>$t,preflightChange:()=>Pn,preflightResolvedChange:()=>Ln,primaryImprovementCompassNextAction:()=>Jn,projectStatusImprovementCompass:()=>zt,projectionHasNonEnforcementLabel:()=>Vs,projectionMatchesPackageVersion:()=>Hs,resolveEffectiveContract:()=>Gr,resolveStatusNextAction:()=>jn,resolvedFactsEvidenceRequirementsHash:()=>ke,serializeDiagnosticCatalog:()=>ms,stableSerialize:()=>x,statusCompassResidualIsSubsetOfDoctor:()=>Rs,toAdapterDiagnostic:()=>ut,unavailableStatusImprovementCompass:()=>Ss,validateAgentSkillDocument:()=>cr,validateAgentSkillsPackage:()=>Gs,version:()=>pr});module.exports=Zs(Pa);var pr="4.5.7";var fr="1.5",nn="docs/diagnostics.md";function v(e){return typeof e=="string"&&e.length>0?e:void 0}function ur(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function ft(e){let t=typeof e.ruleId=="string"?e.ruleId:typeof e.code=="string"?e.code:void 0,n=typeof e.file=="string"?e.file:void 0,r=typeof e.fromLayer=="string"?e.fromLayer:void 0,s=typeof e.toLayer=="string"?e.toLayer:void 0,i=typeof e.target=="string"?e.target:void 0;return[t,n,r??"",s??"",i??""].join("|")}function pt(e){let t=new Map;return e.map(n=>{let r=ft(n),s=(t.get(r)??0)+1;return t.set(r,s),s===1?r:`${r}#${s}`})}function rn(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}function sn(e){return`${nn}#${e}`}function Xs(e,t,n){if(e==="LAYER_IMPORT_VIOLATION")return t.typeOnly||n.targetTypeOnlyExports===!0||n.namedBindingsTypeOnly===!0?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":n.peerIsolation===!0?"Extract the shared dependency to a shared layer, test at the public interface, then preflight again.":`Define a port in ${t.fromLayer??"the source layer"}, inject the ${t.toLayer??"outer-layer"} implementation, test at the public interface, then preflight again.`;if(e==="FORBIDDEN_GLOBAL")return`Inject ${t.target??"the capability"} through a port, test at the public interface, then preflight again.`;if(e==="CAPABILITY_VIOLATION")return`Define a ${v(n.capability)??"capability"} port in ${t.fromLayer??"the walled layer"}, bind the implementation outside it, test at the public interface, then preflight again.`;if(e==="CIRCULAR_DEPENDENCY")return"Extract the shared dependency into a third module, test at the public interface, then preflight again.";if(e==="RAW_EVENT_PUBLISH")return"Publish through a registered intent creator, then run Ark again.";if(e==="PUBLISH_MISSING_SOURCE")return"Add metadata.source to the publish call, then run Ark again.";if(e==="ARKRULE_STRUCTURE"||e==="ARKRULE_INVARIANT"||e==="INVARIANT_UNCOVERED"||e.startsWith("ARKRULE_")){let r=t.arkruleSource??"arkrules/<Layer>.json";return`Fix the structure or invariant for ${t.arkruleId??"the ArkRule"} (declared in ${r}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`}return`Resolve ${e} without weakening ark.config.json, then run Ark again.`}function ut(e,t="error",n){let r=v(e.ruleId)??v(e.code)??"ARK_UNKNOWN",s=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,i={...v(e.target)?{target:v(e.target)}:{},...v(e.fromLayer)?{fromLayer:v(e.fromLayer)}:{},...v(e.toLayer)?{toLayer:v(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{},...typeof e.targetTypeOnlyExports=="boolean"?{targetTypeOnlyExports:e.targetTypeOnlyExports}:{},...typeof e.sourcePureTypeModule=="boolean"?{sourcePureTypeModule:e.sourcePureTypeModule}:{},...typeof e.namedBindingsTypeOnly=="boolean"?{namedBindingsTypeOnly:e.namedBindingsTypeOnly}:{},...typeof e.portProofEligible=="boolean"?{portProofEligible:e.portProofEligible}:{},...typeof e.peerIsolation=="boolean"?{peerIsolation:e.peerIsolation}:{},...v(e.capability)?{capability:v(e.capability)}:{},...v(e.edgeKind)?{edgeKind:v(e.edgeKind)}:{},...v(e.arkruleId)?{arkruleId:v(e.arkruleId)}:{},...v(e.arkruleSource)?{arkruleSource:v(e.arkruleSource)}:{}},a=n??ft(e),o=rn(a);return{ruleId:r,severity:s,message:v(e.message)??r,location:{file:v(e.file)??"<unknown>",line:ur(e.line,1),column:ur(e.column,1)},evidence:i,nextAction:v(e.nextAction)??Xs(r,i,e),findingRef:o,targetKey:a,docsCodePath:sn(r)}}function mr(e){let t=e.completeness??"complete",n=e.mode??"lexical-compatibility";if(t==="complete"&&(e.completenessReasons?.length??0)>0)throw new Error("completenessReasons must be empty when completeness is complete.");let r=t==="complete"?[]:e.completenessReasons&&e.completenessReasons.length>0?e.completenessReasons.map(m=>({code:v(m.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:v(m.message)??`Analysis ${t}: required evidence is incomplete.`,...v(m.file)?{file:v(m.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],s={...v(e.policyHash)?{policyHash:v(e.policyHash)}:{},...v(e.resolverIdentity)?{resolverIdentity:v(e.resolverIdentity)}:{},...v(e.factsHash)?{factsHash:v(e.factsHash)}:{},...v(e.candidateTreeHash)?{candidateTreeHash:v(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let m of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!s[m])throw new Error(`${m} is required for resolved ${t} adapter evidence.`)}let i=e.violations??[],a=e.warnings??[],o=pt(i),d=pt(a),u=[...i.map((m,c)=>ut(m,"error",o[c])),...a.map((m,c)=>ut(m,"warning",d[c]))],g={schemaVersion:"1.5",completenessReasons:r,diagnostics:u};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...g,mode:n,valid:!1,completeness:t,...s};let m={policyHash:s.policyHash,resolverIdentity:s.resolverIdentity,factsHash:s.factsHash,candidateTreeHash:s.candidateTreeHash};return t==="complete"?{...g,mode:n,valid:e.valid,completeness:t,...m}:{...g,mode:n,valid:!1,completeness:t,...m}}return t==="complete"?{...g,mode:n,valid:e.valid,completeness:t,...s}:{...g,mode:n,valid:!1,completeness:t,...s}}var gr={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","mode","valid","completeness","completenessReasons","diagnostics"],allOf:[{if:{properties:{completeness:{enum:["partial","unavailable"]}},required:["completeness"]},then:{properties:{valid:{const:!1}}}},{if:{properties:{mode:{const:"resolved-candidate-facts"},completeness:{enum:["complete","partial"]}},required:["mode","completeness"]},then:{required:["policyHash","resolverIdentity","factsHash","candidateTreeHash"]}},{if:{properties:{completeness:{const:"complete"}},required:["completeness"]},then:{properties:{completenessReasons:{maxItems:0}}},else:{properties:{completenessReasons:{minItems:1}}}}],properties:{schemaVersion:{const:"1.5"},mode:{enum:["lexical-compatibility","resolved-candidate-facts"]},valid:{type:"boolean"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:{type:"string",minLength:1},message:{type:"string",minLength:1},file:{type:"string",minLength:1}}}},policyHash:{type:"string",minLength:1},resolverIdentity:{type:"string",minLength:1},factsHash:{type:"string",minLength:1},candidateTreeHash:{type:"string",minLength:1},diagnostics:{type:"array",items:{type:"object",additionalProperties:!1,required:["ruleId","severity","message","location","evidence"],properties:{ruleId:{type:"string",minLength:1},severity:{enum:["error","warning"]},message:{type:"string",minLength:1},location:{type:"object",additionalProperties:!1,required:["file","line","column"],properties:{file:{type:"string",minLength:1},line:{type:"integer",minimum:1},column:{type:"integer",minimum:1}}},evidence:{type:"object",additionalProperties:!1,properties:{target:{type:"string"},fromLayer:{type:"string"},toLayer:{type:"string"},typeOnly:{type:"boolean"},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"},peerIsolation:{type:"boolean"},capability:{type:"string",minLength:1},edgeKind:{type:"string",minLength:1},arkruleId:{type:"string",minLength:1},arkruleSource:{type:"string",minLength:1}}},nextAction:{type:"string",minLength:1},findingRef:{type:"string",minLength:1,pattern:"^fnv1a-[0-9a-f]{8}$"},targetKey:{type:"string",minLength:1},docsCodePath:{type:"string",minLength:1}}}}}};var yr="1.0",an="https://unpkg.com/arkgate@4/schemas/ark.project-identity.schema.json",mt="^sha256:[a-f0-9]{64}$",on={type:"object",additionalProperties:!1,properties:{expectedRoot:{type:"string",minLength:1,description:"Absolute expected workspace/project directory. The initial authoritative handshake requires the exact project root; descendant calls also require expectedProjectId."},expectedProjectId:{type:"string",pattern:mt,description:"Project id previously returned by ark_identity or ark_manifest."}}},ln={type:"object",additionalProperties:!1,required:["status","authoritative"],properties:{status:{enum:["matched","unverified","mismatch"]},authoritative:{type:"boolean"},expectedRoot:{type:"string",minLength:1},expectedProjectId:{type:"string",pattern:mt},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},hr={$schema:"https://json-schema.org/draft/2020-12/schema",$id:an,title:"ArkGate MCP project identity",description:"Stable project binding plus separate runtime and architecture-contract evidence.",type:"object",additionalProperties:!1,required:["schemaVersion","projectId","resolvedRoot","resolvedConfigPath","arkgateVersion","contractHash","contractSource","runtimeId","processStartedAt"],properties:{schemaVersion:{const:"1.0"},projectId:{type:"string",pattern:mt},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{type:"string",minLength:1},arkgateVersion:{type:"string",minLength:1},contractHash:{type:"string",pattern:mt},contractSource:{enum:["project","default-profile","manifest"]},runtimeId:{type:"string",minLength:1},processStartedAt:{type:"string",format:"date-time"}},$defs:{expectation:on,binding:ln}};function Ar(e,t,n){if(!e||!t)throw new Error("Project identity requires resolvedRoot and resolvedConfigPath.");let r=n(JSON.stringify({resolvedRoot:e,resolvedConfigPath:t})).toLowerCase();if(!/^[a-f0-9]{64}$/.test(r))throw new Error("Project identity hash adapter must return 64 hexadecimal SHA-256 characters.");return`sha256:${r}`}function Ir(e){return{schemaVersion:"1.0",...e}}var dn=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),un=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),fn=Object.freeze(Object.keys(un).sort()),cn=Object.freeze({fs:"filesystem","node:fs":"filesystem","fs/promises":"filesystem","node:fs/promises":"filesystem","fs-extra":"filesystem","graceful-fs":"filesystem",memfs:"filesystem",chokidar:"filesystem",http:"network",https:"network",http2:"network",net:"network",tls:"network",dgram:"network",dns:"network","node:http":"network","node:https":"network","node:http2":"network","node:net":"network","node:tls":"network","node:dgram":"network","node:dns":"network",axios:"network",undici:"network","node-fetch":"network",got:"network",ky:"network",superagent:"network",ws:"network",process:"process","node:process":"process",child_process:"process","node:child_process":"process","@prisma/client":"persistence",prisma:"persistence",pg:"persistence",mysql:"persistence",mysql2:"persistence",mongodb:"persistence",mongoose:"persistence",sqlite3:"persistence","better-sqlite3":"persistence",redis:"persistence",ioredis:"persistence",typeorm:"persistence",knex:"persistence","drizzle-orm":"persistence",sequelize:"persistence",kysely:"persistence","@supabase/supabase-js":"persistence"}),pn=Object.freeze({process:Object.freeze(["process","node:process"])});function Me(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=cn[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),s=cn[r];if(s)return s;let i=e.indexOf("/",n+1);return i<0?null:cn[e.slice(0,i)]??null}function se(e,t){for(let n of t)if(pn[n]?.includes(e))return n;return null}function gt(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),s=un[r];if(s)return s}return null}function be(e){if(e?.pure===!0)return[...dn].sort();let n=(e?.capabilities?.deny??[]).filter(r=>dn.includes(r));return[...new Set(n)].sort()}function $e(e,t){if(t.length===0)return!1;let n=new Set(t),r=e.split(".");for(let s=r.length;s>=1;s-=1)if(n.has(r.slice(0,s).join(".")))return!0;return!1}function yt(e){let t=new Set,n=new Set,r=Object.keys(un);for(let s of e?.forbiddenGlobals??[]){let i=r.filter(a=>a===s||a.startsWith(`${s}.`));if(i.length===0)n.add(s);else for(let a of i)t.add(`ambient:${a}`);for(let a of pn[s]??[])t.add(`import-exact:${a}`)}for(let s of be(e)){if(t.add(`import:${s}`),s==="process")for(let i of pn.process)t.add(`import-exact:${i}`);for(let i of r)gt(i)===s&&t.add(`ambient:${i}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}var br=new Map;function Sr(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function ht(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let s=e[n+1];if("*?{}[],".includes(s)||s==="\\"){t+="\\"+s,n+=1;continue}t+="/";continue}t+=r}return t}function Qs(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="{")t+=1;else if(r==="}"&&(t-=1,t<0))return!1}return t===0}function pe(e){let t=br.get(e);if(t)return t;let n=ht(e),r=Qs(n),s="",i=0;for(let o=0;o<n.length;o+=1){let d=n[o];d==="\\"&&o+1<n.length?(s+=Sr(n[o+1]),o+=1):d==="*"?n[o+1]==="*"?n[o+2]==="/"?(s+="(?:.*/)?",o+=2):(s+=".*",o+=1):s+="[^/]*":d==="?"?s+="[^/]":d==="{"&&r?(s+="(?:",i+=1):d==="}"&&r&&i>0?(s+=")",i-=1):d===","&&r&&i>0?s+="|":s+=Sr(d)}let a=new RegExp(`^${s}$`);return br.set(e,a),a}function ei(e){return ht(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}function mn(e,t){let n=ht(String(e)),r=ei(n),s=n.replace(/\*/g,"").length,i=r.length*1e4+s;if(t==null||t==="")return i;let a=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return s;let o=0,d=-1;for(let u of r){let g=-1;for(let m=o;m<a.length;m+=1)if(a[m]===u){g=m;break}if(g<0)return i;d=g,o=g+1}return(d+1)*1e6+r.length*1e4+s}function Q(e,t){let n=String(e).split(/[/\\]/).join("/"),r,s=-1;for(let i of t??[])if(!(i.exclude??[]).some(a=>pe(a).test(n))){for(let a of i.patterns??[])if(pe(a).test(n)){let o=mn(a,n);o>s&&(s=o,r=i.name)}}return r}function Rr(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),r=new Set(t.map(s=>String(s).toLowerCase()));for(let s=0;s<n.length-1;s+=1)if(r.has(n[s].toLowerCase()))return`${n[s].toLowerCase()}/${n[s+1].toLowerCase()}`}function ti(e){let t=new Set;for(let n of e??[]){let s=ht(String(n)).split("/").filter(Boolean);for(let i=0;i<s.length;i+=1){let a=s[i];if((a==="**"||a==="*")&&i>0){let o=s[i-1];o&&!o.includes("*")&&!o.includes("{")&&!o.includes("}")&&t.add(o)}}}return[...t]}function ni(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(s=>typeof s=="string"&&s.length>0);let r=(n??[]).find(s=>s.name===t);return ti(r?.patterns)}function ri(e){return!e.fromPath||!e.toPath||e.folderCount<=0||!e.fromSlice||!e.toSlice?!0:e.fromSlice!==e.toSlice}function ee(e,t,n,r){for(let s of e??[])if(!(s.from!==t||s.to!==n)&&s.allowed===!1){if(s.peerIsolation){let i=r?.fromPath,a=r?.toPath,o=ni(s,t,r?.layers),d=i&&a?Rr(i,o):void 0,u=i&&a?Rr(a,o):void 0;if(ri({fromPath:i,toPath:a,folderCount:o.length,fromSlice:d,toSlice:u}))return s;continue}if(t!==n)return s}}function Se(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function Cr(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function Er(e,t){if(e.isImportDeclaration(t)){let r=t.importClause;if(!r)return!1;if(r.isTypeOnly)return!0;let s=r.namedBindings;return!!(s&&e.isNamedImports(s)&&s.elements.length>0&&s.elements.every(i=>i.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(r=>r.isTypeOnly))}function kr(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=s=>s===t.fileName?t:void 0,r.fileExists=s=>s===t.fileName,r.readFile=s=>s===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}function gn(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function yn(e,t,n,r){let s=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,i;try{i=s?t.getShorthandAssignmentValueSymbol(r.parent):gn(t,r)}catch{i=void 0}return!!i?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}function ue(e,t){let n,r=[],s=(a,o,d,u=!1)=>r.push({specifier:d,kind:o,line:Cr(t,a),typeOnly:u,unresolved:d===void 0,node:a}),i=a=>{if(e.isImportDeclaration(a))s(a,"import",Se(e,a.moduleSpecifier),Er(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)s(a,"export",Se(e,a.moduleSpecifier),Er(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))s(a,"require",Se(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let o=a.expression.kind===e.SyntaxKind.ImportKeyword,u=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!yn(e,n??(n=kr(e,t)),t,a.expression);(o||u)&&s(a,u?"require":"dynamic-import",Se(e,a.arguments[0]))}e.forEachChild(a,i)};return i(t),r}function si(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let s=Se(e,r.argumentExpression);if(s===void 0)return;n.unshift(s)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}function ii(e,t){let n=t.parent;return e.isPropertyAccessExpression(n)||e.isElementAccessExpression(n)?!1:e.isExpressionNode(t)&&!e.isInTypeQuery(t)||e.isShorthandPropertyAssignment(n)&&n.name===t}function vr(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let r=n.length;r>=1;r-=1){let s=n.slice(0,r).join(".");if(e.has(s))return s}}function fe(e,t,n){if(n.length===0)return[];let r=new Set(n),s=kr(e,t),i=new Map,a=new Set;for(let c of t.statements)if(e.isVariableStatement(c))for(let l of c.declarationList.declarations)e.isIdentifier(l.name)&&a.add(l.name.text);let o=c=>{let l=si(e,c);if(!l)return;let p=gn(s,l.root),y=p?i.get(p):void 0;return y?[...y,...l.segments.slice(1)]:yn(e,s,t,l.root)||a.has(l.root.text)?void 0:l.segments};for(let c of t.statements)if(e.isVariableStatement(c))for(let l of c.declarationList.declarations){if(!l.initializer||!e.isIdentifier(l.name))continue;let p=o(l.initializer),y=gn(s,l.name);!p||!y||i.set(y,p)}let d=[],u=new Set,g=(c,l)=>{let p=Cr(t,l),y=`${c}:${l.getStart(t)}`;u.has(y)||(u.add(y),d.push({name:c,line:p,node:l}))},m=c=>{let l=c.parent&&(e.isPropertyAccessExpression(c.parent)||e.isElementAccessExpression(c.parent))&&c.parent.expression===c;if((e.isPropertyAccessExpression(c)||e.isElementAccessExpression(c))&&!l){let p=o(c),y=p?vr(r,p):void 0;y&&g(y,c)}else e.isIdentifier(c)&&r.has(c.text)&&ii(e,c)&&!yn(e,s,t,c)&&g(c.text,c);if(e.isVariableDeclaration(c)&&e.isObjectBindingPattern(c.name)&&c.initializer){let p=o(c.initializer);if(p)for(let y of c.name.elements){if(!e.isIdentifier(y.name))continue;let I=y.propertyName?Se(e,y.propertyName)??y.propertyName.text:y.name.text,R=vr(r,[...p,I]);R&&g(R,c.initializer)}}e.forEachChild(c,m)};return m(t),d}function hn(e,t,n){let r=[];for(let s of n?.dependencies??ue(e,t)){if(s.typeOnly||!s.specifier)continue;let i=Me(s.specifier);i&&r.push({capability:i,symbol:s.specifier,line:s.line,source:"import-based"})}for(let s of n?.ambientUses??fe(e,t,fn)){let i=gt(s.name);i&&r.push({capability:i,symbol:s.name,line:s.line,source:"ambient-global"})}return r.sort((s,i)=>s.line-i.line||s.capability.localeCompare(i.capability)||s.symbol.localeCompare(i.symbol))}var An={RAW_EVENT_PUBLISH:"Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts and tooling.",PUBLISH_MISSING_SOURCE:"Strict Ark publish calls must include metadata.source."},In=Object.freeze([{layer:"DomainModel",prefixes:["Domain."]},{layer:"ApplicationOrchestration",prefixes:["Application."]},{layer:"PersistenceAdapters",prefixes:["Adapter.Persistence.","Adapter.Repository."]},{layer:"IntegrationAdapters",prefixes:["Adapter.Integration.","Adapter.External."]},{layer:"WorkflowSagaEngine",prefixes:["Workflow."]},{layer:"BackgroundJobsScheduling",prefixes:["Job."]},{layer:"PresentationAdapters",prefixes:["Presentation.","Adapter.Presentation.","Adapter.Api."]},{layer:"ReportingReadModels",prefixes:["Reporting."]},{layer:"ExtensibilityMetadata",prefixes:["Metadata."]},{layer:"SecurityAuditObservability",prefixes:["Security.","Audit.","Observability."]},{layer:"Kernel",prefixes:["Kernel."]}]);function bn(e,t){return t.flatMap((r,s)=>(r.prefixes??r.intentPrefixes??[]).map(i=>({layer:r.name,layerIndex:s,prefix:i.endsWith(".")?i:`${i}.`}))).filter(({prefix:r})=>e.startsWith(r)).sort((r,s)=>s.prefix.length-r.prefix.length||r.layerIndex-s.layerIndex)[0]?.layer}function me(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function Fe(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&me(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:An.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:An.PUBLISH_MISSING_SOURCE}),t}function w(e,t,n){return{ruleId:e,code:e,message:t,...n}}function Re(e,t){return e.slice(0,t).split(`
|
|
2
2
|
`).length}function ai(e){let t=[],n=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,r;for(;(r=n.exec(e))!==null;)t.push({value:r[1],index:r.index});return t}function oi(e){let t=[],n=[{kind:"import",re:/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s*)?['"]([^'"]+)['"]/g},{kind:"export",re:/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s*['"]([^'"]+)['"]/g},{kind:"dynamic-import",re:/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g},{kind:"require",re:/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g}];for(let r of n){let s;for(;(s=r.re.exec(e))!==null;){let i=s.index+s[0].indexOf(s[1]),a=s[0],o=r.kind==="import"&&/\bimport\s+type\b/.test(a)||r.kind==="export"&&/\bexport\s+type\b/.test(a);t.push({value:s[1],index:i,kind:r.kind,typeOnly:o})}}return t.sort((r,s)=>r.index-s.index)}function li(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],s=i=>{e.isStringLiteralLike(i)&&r.push({value:i.text,index:i.getStart(n)}),e.forEachChild(i,s)};return s(n),r}function ci(e){let t=e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);return["adapter","adapters","infra","infrastructure","persistence","repository","repositories","integration","database","db"].some(n=>t.includes(n))}function di(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}function pi(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}function He(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function ui(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}function _r(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:ui(e,r.name)===n)}function Ve(e,t,n){return _r(e,t,n)!==void 0}function De(e,t,n){let r=_r(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}function fi(e,t){let n=De(e,t,"metadata");return Ve(e,n,"source")}function xr(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?xr(e,t.name):!1:!1}function mi(e,t){if(!e.isCallExpression(t))return!1;let n=t.expression;return e.isPropertyAccessExpression(n)?n.name.text==="publish":e.isIdentifier(n)&&n.text==="publish"}function gi(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=He(e,n);return r!==void 0&&me(r)||Ve(e,n,"intent")||xr(e,n)}function yi(e,t){if(!e.isCallExpression(t))return!1;let[n,r,s]=t.arguments;return fi(e,n)||Ve(e,r,"source")||Ve(e,s,"source")}function hi(e,t){if(!e.isCallExpression(t))return;let[n,r,s]=t.arguments,i=De(e,n,"metadata");return He(e,De(e,i,"source"))??He(e,De(e,r,"source"))??He(e,De(e,s,"source"))}function Ai(e,t,n,r){let s=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),i=n,a=i?.filePath,o=i?.layer,d=[],u=m=>s.getLineAndCharacterOfPosition(m.getStart(s)).line+1,g=m=>{if(mi(e,m)){let c=m.arguments[0],l=He(e,c);for(let y of Fe({publishCall:!0,rawIntentName:l,objectHasIntent:Ve(e,c,"intent"),arkPublishCandidate:gi(e,m),hasSource:yi(e,m)}))d.push(w(y.ruleId,y.message,{line:u(m),filePath:a}));let p=hi(e,m);if(r&&o&&p&&me(p)){let y=r.resolveLayer(p);y&&y!==o&&d.push(w("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${p}" resolves to ${y}, but the target file is classified as ${o}.`,{line:u(m),filePath:a,target:p,fromLayer:o,toLayer:y}))}}e.forEachChild(m,g)};return g(s),d}function Sn(e={}){let t=new Set((e.intents||[]).map(i=>typeof i=="string"?i:i.name)),n=e.forbiddenPatterns||[],r=new Set(e.infrastructureLayers??[]),s=e.enforceIntentAllowlist??t.size>0;return{validate(i,a){let o=[],d=a,u=d?.filePath,g=d?.layer,m=e.typescript,c=m?m.createSourceFile(u??"generated.ts",i,m.ScriptTarget.Latest,!0):void 0,l=c?ue(e.typescript,c):void 0,p=l?l.filter(f=>f.specifier!==void 0).map(f=>({value:f.specifier,index:f.node.getStart(c),kind:f.kind,typeOnly:f.typeOnly})):oi(i),y=e.typescript?li(e.typescript,i):ai(i);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(u))for(let f of l?.filter(({unresolved:h})=>h)??[]){let h=f.kind==="require";o.push(w(h?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${h?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:f.line,filePath:u}))}let I=g!==void 0&&(r.has(g)||pi(g)),R=g!==void 0?` If "${g}" is an infrastructure layer, mark it in ark.config.json with "mayImportInfrastructure": true (or name it with an infra token like Adapters/Persistence/Repository).`:"";for(let f of n)if(f instanceof RegExp){f.lastIndex=0;let h=f.exec(i);f.lastIndex=0,h&&o.push(w("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${f}`,{line:h.index===void 0?void 0:Re(i,h.index),filePath:u,suggestion:"Remove infrastructure imports from domain/application layers."+R}))}else i.includes(f)&&o.push(w("FORBIDDEN_SUBSTRING",`Forbidden substring: ${f}`,{line:Re(i,i.indexOf(f)),filePath:u}));for(let f of p){let h=e.resolveImportTarget?.(f.value,u)??(e.resolveImportLayer?{layer:e.resolveImportLayer(f.value,u)}:void 0),S=typeof u=="string"?e.resolveImportTarget?.(u)??(e.resolveImportLayer?{layer:g,relPath:void 0}:void 0):void 0,k=h?.layer;if(k&&g){let N=ee(e.architectureProfile?.rules,g,k,{fromPath:S?.relPath,toPath:h?.relPath,layers:e.architectureLayers});if(N){if(f.typeOnly&&!N.peerIsolation)continue;let D=!!N.peerIsolation;o.push(w("LAYER_IMPORT_VIOLATION",N.message??(D?`Layer "${g}" must not import across slices into "${k}".`:`Layer "${g}" must not import "${k}".`),{line:Re(i,f.index),source:f.value,target:f.value,filePath:u,fromLayer:g,toLayer:k,suggestion:D?"Extract shared code to a shared layer, or coordinate slices via events/ports \u2014 do not import across feature/context slices.":"Depend on a port/interface owned by an inner layer instead, or move this code to a layer allowed to make this import.",details:{importKind:f.kind,peerIsolation:D,...f.typeOnly?{typeOnly:!0}:{}}}));continue}continue}I||f.typeOnly||!ci(f.value)&&!di(f.value)||o.push(w("FORBIDDEN_IMPORT",`Forbidden ${f.kind} target: "${f.value}".`,{line:Re(i,f.index),source:f.value,target:f.value,filePath:u,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+R,details:{importKind:f.kind}}))}if(e.policies)for(let f of e.policies){let h=f.check({source:i,context:a});if(h!==!0)if(Array.isArray(h))for(let S of h)o.push(w("POLICY_VIOLATION",S.message,{filePath:u,suggestion:`Fix violation of policy "${f.name}".`}));else h===!1?o.push(w("POLICY_VIOLATION",`Policy ${f.name} failed on generated code`)):o.push(w("POLICY_VIOLATION",h.message))}if(s&&t.size>0)for(let f of y)me(f.value)&&!t.has(f.value)&&o.push(w("UNKNOWN_INTENT",`Unknown intent reference: "${f.value}"`,{line:Re(i,f.index),filePath:u,target:f.value,suggestion:`Register intent "${f.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&g)for(let f of y){if(!me(f.value))continue;let h=e.architectureProfile.resolveLayer(f.value);if(!h)continue;let S=ee(e.architectureProfile.rules,g,h);S&&o.push(w("LAYER_REFERENCE_VIOLATION",S.message??`Layer "${g}" must not reference "${h}" through "${f.value}".`,{line:Re(i,f.index),filePath:u,target:f.value,fromLayer:g,toLayer:h,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:S}}))}if(e.extensions)for(let f of e.extensions)try{let h=f.analyze(i,a);o.push(...h)}catch(h){o.push(w("EXTENSION_ERROR",`Extension "${f.name}" failed: ${h instanceof Error?h.message:String(h)}`))}if(e.typescript&&c&&g&&e.forbiddenGlobals?.[g]?.length)try{let f=e.forbiddenGlobals[g];o.push(...fe(e.typescript,c,f).map(h=>w("FORBIDDEN_GLOBAL",`${g} must not use the ambient global "${h.name}".`,{line:h.line,filePath:u,target:h.name,fromLayer:g,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let h of l??[]){if(h.typeOnly||!h.specifier)continue;let S=se(h.specifier,f);S&&o.push(w("FORBIDDEN_GLOBAL",`${g} must not use module "${h.specifier}" because it is the import form of forbidden global "${S}".`,{line:h.line,filePath:u,source:h.specifier,target:h.specifier,fromLayer:g,details:{importKind:h.kind,forbiddenGlobal:S},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(f){o.push(w("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${f instanceof Error?f.message:String(f)}`))}if(e.typescript&&c&&g&&e.capabilityWalls?.[g]?.length)try{let f=new Set(e.capabilityWalls[g]),h=e.forbiddenGlobals?.[g]??[];for(let S of hn(e.typescript,c))f.has(S.capability)&&(S.source==="ambient-global"&&$e(S.symbol,h)||S.source==="import-based"&&se(S.symbol,h)||o.push(w("CAPABILITY_VIOLATION",S.source==="import-based"?`${g} denies the ${S.capability} capability; found import of "${S.symbol}".`:`${g} denies the ${S.capability} capability; found ambient "${S.symbol}".`,{line:S.line,filePath:u,target:S.symbol,capability:S.capability,fromLayer:g,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(f){o.push(w("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${f instanceof Error?f.message:String(f)}`))}if(e.typescript)try{o.push(...Ai(e.typescript,i,a,e.architectureProfile))}catch(f){o.push(w("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${f instanceof Error?f.message:String(f)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:o.length===0,violations:o}}}}var Tr="1.1",It="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",Or=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Ii=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function bi(){let e=[];for(let t of Or)for(let n of Or)t===n||Ii.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var St=bi(),Rn=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"}],ie={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},bt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:It,title:"ArkGate architecture contract",description:"Versioned contract consumed identically by ArkGate CLI, MCP, and ESLint surfaces.",type:"object",additionalProperties:!1,required:["$schema","schemaVersion","include","layers","rules"],properties:{$schema:{type:"string",minLength:1,default:It,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:"1.1",default:"1.1"},name:{type:"string",minLength:1},include:{...ie,minItems:1,default:["src"]},exclude:{...ie,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:St,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...ie,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...ie,minItems:1},exclude:ie,intentPrefixes:ie,description:{type:"string",minLength:1},forbiddenGlobals:ie,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:{...ie,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}}}}},te=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
|
|
3
3
|
${n.map(r=>`- ${r.path}: ${r.message}`).join(`
|
|
4
4
|
`)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function Pr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function At(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function Ee(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Si(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function je(e,t,n,r,s){if(t.$ref){let i=Si(t.$ref,r);if(!i){s.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}je(e,i,n,r,s);return}if(t.const!==void 0&&!Object.is(e,t.const)){s.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(i=>Object.is(i,e))){s.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!Pr(e)){s.push({path:n,message:`must be an object; received ${Ee(e)}`});return}let i=t.properties??{};for(let a of t.required??[])e[a]===void 0&&s.push({path:At(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in i||s.push({path:At(n,a),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let a=t.additionalProperties;for(let o of Object.keys(e))o in i||je(e[o],a,At(n,o),r,s)}for(let[a,o]of Object.entries(i))e[a]!==void 0&&je(e[a],o,At(n,a),r,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:n,message:`must be an array; received ${Ee(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&s.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let i=e.map(a=>JSON.stringify(a));new Set(i).size!==i.length&&s.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((i,a)=>je(i,t.items,`${n}[${a}]`,r,s));return}if(t.type==="string"){if(typeof e!="string"){s.push({path:n,message:`must be a string; received ${Ee(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&s.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&s.push({path:n,message:`must be a boolean; received ${Ee(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){s.push({path:n,message:`must be an integer; received ${Ee(e)}`});return}t.minimum!==void 0&&e<t.minimum&&s.push({path:n,message:`must be at least ${t.minimum}`})}}function Ri(e){return{...e,$schema:e.$schema===void 0?It:e.$schema,schemaVersion:e.schemaVersion===void 0?"1.1":e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?St.map(t=>({...t})):e.rules}}function Ei(){let e=new Set(["1.1"]);for(let t of Rn)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}function vi(e,t="ark.config.json"){if(!Pr(e))throw new te(t,[{path:"$",message:`must be an object; received ${Ee(e)}`}]);let n=Ei(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new te(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.1`}]);if(r!=="unversioned"&&!n.has(r))throw new te(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected 1.1`}]);let s=r,i={...e},a=0;for(;s!=="1.1"&&a<Rn.length+1;){a+=1;let d=Rn.find(u=>u.from===s);if(!d)throw new te(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(s)}; expected 1.1`}]);s=d.to,i.schemaVersion=s}if(s!=="1.1")throw new te(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected 1.1`}]);let o=r==="unversioned"?"unversioned":r==="1.0"?"1.0":null;return{candidate:Ri(i),migratedFrom:o}}function Ue(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=vi(e,t),s=[];if(je(n,bt,"$",bt,s),s.length>0)throw new te(t,s);return{config:n,migratedFrom:r}}function Rt(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new te(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return Ue(n,t)}function Lr(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:It,schemaVersion:"1.1"};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}function Ci(e){return e.endsWith(".")?e:`${e}.`}function ki(e,t){let n=e.prefixes.length?Math.max(...e.prefixes.map(s=>s.length)):0;return(t.prefixes.length?Math.max(...t.prefixes.map(s=>s.length)):0)-n}function Be(e){let t=e.layers.map(s=>({...s,prefixes:s.prefixes.map(Ci)})),n=[...t].sort(ki),r=[...e.rules??[]];return{name:e.name,layers:t,rules:r,resolveLayer(s){return t.find(i=>i.match?.(s))?.name??n.find(i=>i.prefixes.some(a=>s.startsWith(a)))?.name}}}function En(e,t={}){return Be({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,r)=>({name:n.name,prefixes:n.intentPrefixes??[],description:n.description,order:r+1})),rules:e.rules??[]})}var _i=[{name:"DomainModel",prefixes:["Domain"],description:"Rich domain model, business rules, and domain events.",order:1},{name:"ApplicationOrchestration",prefixes:["Application"],description:"Use cases and command orchestration.",order:2},{name:"PersistenceAdapters",prefixes:["Adapter.Persistence","Adapter.Repository"],description:"Database, repository, and storage adapters.",order:3},{name:"IntegrationAdapters",prefixes:["Adapter.Integration","Adapter.External"],description:"External systems, APIs, and integration adapters.",order:4},{name:"WorkflowSagaEngine",prefixes:["Workflow"],description:"Sagas, workflows, and long-running processes.",order:5},{name:"BackgroundJobsScheduling",prefixes:["Job"],description:"Background jobs, scheduled work, and async processors.",order:6},{name:"PresentationAdapters",prefixes:["Presentation","Adapter.Presentation","Adapter.Api"],description:"API, UI, controller, and presentation adapters.",order:7},{name:"ReportingReadModels",prefixes:["Reporting"],description:"Read models, projections, and reporting surfaces.",order:8},{name:"ExtensibilityMetadata",prefixes:["Metadata"],description:"Metadata, extensions, and schema contracts.",order:9},{name:"SecurityAuditObservability",prefixes:["Security","Audit","Observability"],description:"Security, audit, and observability concerns.",order:10},{name:"Kernel",prefixes:["Kernel"],description:"Ark-owned governance and kernel signals.",order:11}],Ge=Be({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:_i,rules:St.map(e=>({...e}))}),xi={DomainModel:["domain"],ApplicationOrchestration:["application","app"],PersistenceAdapters:["adapters/persistence","adapters/repository","repositories","infra/persistence"],IntegrationAdapters:["adapters/integration","adapters/external","integrations"],WorkflowSagaEngine:["workflows","sagas"],BackgroundJobsScheduling:["jobs","schedules"],PresentationAdapters:["presentation","adapters/presentation","adapters/api"],ReportingReadModels:["reporting","read-models","projections"],ExtensibilityMetadata:["metadata","extensions"],SecurityAuditObservability:["security","audit","observability"],Kernel:["kernel"]};function vn(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return Lr({include:e.include??[t],layers:Ge.layers.map(s=>({name:s.name,patterns:(xi[s.name]??[s.name]).map(i=>`${r}${i}/**`),intentPrefixes:s.prefixes,optional:n})),rules:[...Ge.rules]})}function M(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}function x(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(x).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${x(t[n])}`).join(",")}}`}var ae="1.1";var Nr=["network","filesystem","clock","randomness","environment","process","persistence"];function ne(e,t){let n=x(e),r=x(t);return n<r?-1:n>r?1:0}function Z(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}function ke(e){let t={schemaVersion:"1.1",include:Z(e.include??[]),exclude:Z(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:Z(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:Z(n.patterns??[]),exclude:Z(n.exclude??[]),forbiddenGlobals:Z(n.forbiddenGlobals??[]),intentPrefixes:Z(n.intentPrefixes??[]),capabilityDeny:Z(n.capabilities?.deny??[]),pure:n.pure===!0})).sort(ne),safety:{maxTsSuppressions:e.safety?.maxTsSuppressions??0,maxAnyCasts:e.safety?.maxAnyCasts??0,allowInMemory:e.safety?.allowInMemory===!0,allowDisabledPeerIsolation:e.safety?.allowDisabledPeerIsolation===!0}};return M(x(t))}function Oi(e){let t=e.completenessReasons.map(c=>({code:c.code,message:c.message,...c.file?{file:c.file}:{}})).sort(ne),n=e.files.map(c=>({...c,typeOnlyExportNames:Z(c.typeOnlyExportNames)})).sort((c,l)=>c.path<l.path?-1:c.path>l.path?1:0),r=e.dependencies.map(c=>({...c,...c.namedBindings?{namedBindings:Z(c.namedBindings)}:{}})).sort(ne),s=e.capabilityUses.map(c=>({...c})).sort(ne),i=e.ambientUses.map(c=>({...c})).sort(ne),a=e.publishCalls.map(c=>({...c})).sort(ne),o=e.intentReferences.map(c=>({...c})).sort(ne),d=e.safetyUses.map(c=>({...c})).sort(ne),u=(e.classShapes??[]).map(c=>({...c,mutatingMethods:[...c.mutatingMethods??[]].map(l=>({...l}))})).sort(ne),g=e.files.map(({path:c,contentHash:l})=>({path:c,contentHash:l})).sort((c,l)=>c.path<l.path?-1:c.path>l.path?1:0),m=M(x(g));return{schemaVersion:"1.1",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:m,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:r,capabilityUses:s,ambientUses:i,publishCalls:a,intentReferences:o,safetyUses:d,classShapes:u}}function Mr(e){let t=Oi(e);return{...t,factsHash:M(x(t))}}function Et(e){return Mr(Fr(K(e,"$"),!1))}function K(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}function Y(e,t,n){let r=new Set(t),s=Object.keys(e).find(i=>!r.has(i));if(s)throw new Error(`${n}.${s} is not part of schema ${"1.1"}.`)}function F(e,t,n){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`${n}.${t} must be a non-empty string.`);return r}function ve(e,t,n){if(e[t]!==void 0)return F(e,t,n)}function W(e,t,n){let r=F(e,t,n),s=r.replace(/\\/g,"/");if(!s||s.startsWith("/")||/^[A-Za-z]:\//.test(s)||/[\u0000-\u001f\u007f]/.test(s))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let i=[];for(let o of s.split("/"))if(!(!o||o==="."))if(o===".."){if(i.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);i.pop()}else i.push(o);let a=i.join("/");if(!a||a!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return a}function $(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}function $r(e,t,n){let r=e[t];if(!Number.isInteger(r)||Number(r)<0)throw new Error(`${n}.${t} must be a non-negative integer.`);return Number(r)}function Ce(e,t,n){let r=$r(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}function J(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}function oe(e,t,n,r){let s=e[t];if(typeof s!="string"||!n.includes(s))throw new Error(`${r}.${t} must be one of ${n.join(", ")}.`);return s}function wr(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!n))throw new Error(`${t} must be an array of non-empty strings.`);return[...e]}function Ti(e,t,n){let r=new Set;for(let s of e){let i=t(s);if(r.has(i))throw new Error(`${n} must not contain duplicate facts (${i}).`);r.add(i)}}function Fr(e,t){Y(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","classShapes",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=oe(e,"schemaVersion",["1.0","1.1"],"$"),r=oe(e,"completeness",["complete","partial","unavailable"],"$"),s=J(e,"completenessReasons","$").map((I,R)=>{let f=`$.completenessReasons[${R}]`,h=K(I,f);Y(h,["code","message","file"],f);let S=h.file===void 0?void 0:W(h,"file",f);return{code:F(h,"code",f),message:F(h,"message",f),...S?{file:S}:{}}});if(r==="complete"&&s.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(r!=="complete"&&s.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let i=J(e,"files","$").map((I,R)=>{let f=`$.files[${R}]`,h=K(I,f);return Y(h,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],f),{path:W(h,"path",f),contentHash:F(h,"contentHash",f),parseStatus:oe(h,"parseStatus",["parsed","invalid"],f),parseDiagnosticCount:$r(h,"parseDiagnosticCount",f),exportsOnlyTypes:$(h,"exportsOnlyTypes",f),typeOnlyExportNames:wr(h.typeOnlyExportNames,`${f}.typeOnlyExportNames`),hasTopLevelSideEffects:$(h,"hasTopLevelSideEffects",f)}}),a=J(e,"dependencies","$").map((I,R)=>{let f=`$.dependencies[${R}]`,h=K(I,f);Y(h,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],f);let S=ve(h,"specifier",f),k=ve(h,"target",f),N=oe(h,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],f);if(N==="resolved-project"&&!k)throw new Error(`${f}.target is required for resolved-project dependencies.`);if(N!=="resolved-project"&&k)throw new Error(`${f}.target is only allowed for resolved-project dependencies.`);if(N!=="dynamic"&&!S)throw new Error(`${f}.specifier is required unless resolution is dynamic.`);return{from:W(h,"from",f),...S?{specifier:S}:{},kind:oe(h,"kind",["import","export","dynamic-import","require"],f),typeOnly:$(h,"typeOnly",f),line:Ce(h,"line",f),resolution:N,...k?{target:W(h,"target",f)}:{},...h.namedBindings!==void 0?{namedBindings:wr(h.namedBindings,`${f}.namedBindings`)}:{},...h.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:$(h,"targetTypeOnlyExports",f)}:{},...h.sourcePureTypeModule!==void 0?{sourcePureTypeModule:$(h,"sourcePureTypeModule",f)}:{},...h.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:$(h,"namedBindingsTypeOnly",f)}:{},...h.portProofEligible!==void 0?{portProofEligible:$(h,"portProofEligible",f)}:{}}}),o=J(e,"capabilityUses","$").map((I,R)=>{let f=`$.capabilityUses[${R}]`,h=K(I,f);return Y(h,["file","line","symbol","capability","source"],f),{file:W(h,"file",f),line:Ce(h,"line",f),symbol:F(h,"symbol",f),capability:oe(h,"capability",Nr,f),source:oe(h,"source",["ambient-global","import-based"],f)}}),d=J(e,"ambientUses","$").map((I,R)=>{let f=`$.ambientUses[${R}]`,h=K(I,f);return Y(h,["file","line","symbol"],f),{file:W(h,"file",f),line:Ce(h,"line",f),symbol:F(h,"symbol",f)}}),u=J(e,"publishCalls","$").map((I,R)=>{let f=`$.publishCalls[${R}]`,h=K(I,f);Y(h,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],f);let S=ve(h,"rawIntentName",f),k=ve(h,"sourceIntent",f);return{file:W(h,"file",f),line:Ce(h,"line",f),...S?{rawIntentName:S}:{},objectHasIntent:$(h,"objectHasIntent",f),arkPublishCandidate:$(h,"arkPublishCandidate",f),hasSource:$(h,"hasSource",f),...k?{sourceIntent:k}:{}}}),g=J(e,"intentReferences","$").map((I,R)=>{let f=`$.intentReferences[${R}]`,h=K(I,f);return Y(h,["file","line","intent"],f),{file:W(h,"file",f),line:Ce(h,"line",f),intent:F(h,"intent",f)}}),m=J(e,"safetyUses","$").map((I,R)=>{let f=`$.safetyUses[${R}]`,h=K(I,f);Y(h,["file","line","kind","symbol"],f);let S=ve(h,"symbol",f),k=oe(h,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],f);if(k==="in-memory-store"&&!S)throw new Error(`${f}.symbol is required for in-memory-store facts.`);if(k!=="in-memory-store"&&S)throw new Error(`${f}.symbol is only allowed for in-memory-store facts.`);return{file:W(h,"file",f),line:Ce(h,"line",f),kind:k,...S?{symbol:S}:{}}});Ti(i,I=>I.path,"$.files");let c=new Set(i.map(I=>I.path));for(let I of i){if(I.parseStatus==="parsed"&&I.parseDiagnosticCount!==0)throw new Error(`$.files[${I.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(I.parseStatus==="invalid"&&I.parseDiagnosticCount===0)throw new Error(`$.files[${I.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&i.some(I=>I.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let I of a)if(!c.has(I.from))throw new Error(`$.dependencies references missing source file ${I.from}.`);for(let[I,R]of[["$.capabilityUses",o],["$.ambientUses",d],["$.publishCalls",u],["$.intentReferences",g],["$.safetyUses",m]])for(let f of R)if(!c.has(f.file))throw new Error(`${I} references missing file ${f.file}.`);let l=ve(e,"projectPackageName","$"),y=(e.classShapes===void 0?[]:J(e,"classShapes","$")).map((I,R)=>{let f=`$.classShapes[${R}]`,h=K(I,f);Y(h,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],f);let S=J(h,"mutatingMethods",f).map((k,N)=>{let D=`${f}.mutatingMethods[${N}]`,_=K(k,D);return Y(_,["name","referencesGuardOrPublish"],D),{name:F(_,"name",D),referencesGuardOrPublish:$(_,"referencesGuardOrPublish",D)}});return{file:W(h,"file",f),className:F(h,"className",f),exported:$(h,"exported",f),hasPublicMutableFields:$(h,"hasPublicMutableFields",f),hasPublicSetters:$(h,"hasPublicSetters",f),hasPublicConstructor:$(h,"hasPublicConstructor",f),hasStaticFactory:$(h,"hasStaticFactory",f),mutatingMethods:S,...h.dataOnly===void 0?{}:{dataOnly:$(h,"dataOnly",f)}}});return{schemaVersion:n,completeness:r,completenessReasons:s,resolverIdentity:F(e,"resolverIdentity","$"),compilerIdentity:F(e,"compilerIdentity","$"),compilerOptionsHash:F(e,"compilerOptionsHash","$"),tsconfigHash:F(e,"tsconfigHash","$"),evidenceRequirementsHash:F(e,"evidenceRequirementsHash","$"),...l?{projectPackageName:l}:{},files:i,dependencies:a,capabilityUses:o,ambientUses:d,publishCalls:u,intentReferences:g,safetyUses:m,classShapes:y}}function re(e){let t=K(e,"$"),n=F(t,"factsHash","$"),r=F(t,"candidateTreeHash","$"),s=Mr(Fr(t,!0));if(s.factsHash!==n)throw new Error(`$.factsHash does not match the canonical payload (${s.factsHash}).`);if(r!==s.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${s.candidateTreeHash}).`);return s}var Pi=["network","filesystem","clock","randomness","environment","process","persistence"],O={type:"string",minLength:1},_e={type:"integer",minimum:1},X={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},vt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.resolved-candidate-facts.schema.json",title:"ArkGate resolved candidate facts",type:"object",additionalProperties:!1,required:["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","candidateTreeHash","evidenceRequirementsHash","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","factsHash"],properties:{schemaVersion:{enum:["1.0","1.1"]},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:O,message:O,file:X}}},resolverIdentity:O,compilerIdentity:O,compilerOptionsHash:O,tsconfigHash:O,candidateTreeHash:O,evidenceRequirementsHash:O,projectPackageName:O,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:X,contentHash:O,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:O},hasTopLevelSideEffects:{type:"boolean"}},allOf:[{if:{properties:{parseStatus:{const:"parsed"}}},then:{properties:{parseDiagnosticCount:{const:0}}}},{if:{properties:{parseStatus:{const:"invalid"}}},then:{properties:{parseDiagnosticCount:{minimum:1}}}}]}},dependencies:{type:"array",items:{type:"object",additionalProperties:!1,required:["from","kind","typeOnly","line","resolution"],properties:{from:X,specifier:O,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:_e,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:X,namedBindings:{type:"array",items:O},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"}},allOf:[{if:{properties:{resolution:{const:"resolved-project"}}},then:{required:["target"]},else:{not:{required:["target"]}}},{if:{properties:{resolution:{const:"dynamic"}}},else:{required:["specifier"]}}]}},capabilityUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol","capability","source"],properties:{file:X,line:_e,symbol:O,capability:{enum:Pi},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:X,line:_e,symbol:O}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:X,line:_e,rawIntentName:O,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:O}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:X,line:_e,intent:O}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:X,line:_e,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:O},allOf:[{if:{properties:{kind:{const:"in-memory-store"}}},then:{required:["symbol"]},else:{not:{required:["symbol"]}}}]}},classShapes:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods"],properties:{file:X,className:O,exported:{type:"boolean"},hasPublicMutableFields:{type:"boolean"},hasPublicSetters:{type:"boolean"},hasPublicConstructor:{type:"boolean"},hasStaticFactory:{type:"boolean"},dataOnly:{type:"boolean"},mutatingMethods:{type:"array",items:{type:"object",additionalProperties:!1,required:["name","referencesGuardOrPublish"],properties:{name:O,referencesGuardOrPublish:{type:"boolean"}}}}}}},factsHash:O},allOf:[{if:{properties:{completeness:{const:"complete"}}},then:{properties:{completenessReasons:{maxItems:0},files:{items:{properties:{parseStatus:{const:"parsed"}}}}}}},{if:{properties:{completeness:{enum:["partial","unavailable"]}}},then:{properties:{completenessReasons:{minItems:1}}}}]};var Ct="1.0";function U(e){return`${e.from}->${e.to}`}function Ke(e,t,n,r="dependency"){return{id:`${e}:${r}:${U(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${U(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${U(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${U(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${U(t)} from the candidate, then preflight again.`}:{}}}function ge(e){let t=[],n=new Map(e.changeMap.map.files.map(c=>[c.path,c])),r=new Map(e.changes.map(c=>[c.path,c])),s=new Map(e.changeMap.map.dependencies.map(c=>[U(c),c])),i=new Map(e.baseDependencies.map(c=>[U(c),c])),a=new Map(e.candidateDependencies.map(c=>[U(c),c]));for(let c of[...n.values()].sort((l,p)=>l.path.localeCompare(p.path))){let l=r.get(c.path);l?l.operation!==c.operation?t.push({id:`contradictory:file:${c.path}`,classification:"contradictory",subject:"file",path:c.path,expectedOperation:c.operation,actualOperation:l.operation,message:`${c.path} was planned as ${c.operation} but the actual operation is ${l.operation}.`,nextAction:`Change ${c.path} to the planned ${c.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${c.path}`,classification:"satisfied",subject:"file",path:c.path,expectedOperation:c.operation,actualOperation:l.operation,message:`${c.path} matches the planned ${c.operation} operation.`}):t.push({id:`missing:file:${c.path}`,classification:"missing",subject:"file",path:c.path,expectedOperation:c.operation,message:`${c.path} was planned as ${c.operation} but is absent from the actual change.`,nextAction:`${c.operation[0].toUpperCase()}${c.operation.slice(1)} ${c.path} in the complete change set, then preflight again.`})}for(let c of[...r.values()].sort((l,p)=>l.path.localeCompare(p.path)))n.has(c.path)||t.push({id:`unplanned:file:${c.path}`,classification:"unplanned",subject:"file",path:c.path,actualOperation:c.operation,message:`${c.path} has an unplanned ${c.operation} operation.`,nextAction:`Remove ${c.path} from the change set, then preflight again.`});let o=new Set;for(let c of[...s.values()].sort((l,p)=>U(l).localeCompare(U(p)))){if(a.has(U(c))){t.push(Ke("satisfied",c,`${c.from} -> ${c.to} exists in the candidate architecture.`));continue}let l={from:c.to,to:c.from};a.has(U(l))?(o.add(U(l)),t.push(Ke("contradictory",c,`${c.from} -> ${c.to} was planned, but the candidate contains the reverse edge.`))):t.push(Ke("missing",c,`${c.from} -> ${c.to} is absent from the candidate architecture.`))}let d=new Set([...n.keys(),...r.keys()]);for(let[c,l]of[...a].sort(([p],[y])=>p.localeCompare(y)))i.has(c)||s.has(c)||o.has(c)||!d.has(l.from)&&!d.has(l.to)||t.push({...Ke("unplanned",l,`${l.from} -> ${l.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let u=new Set(e.changeMap.map.files.filter(c=>c.operation==="delete").map(c=>c.path));for(let[c,l]of[...i].sort(([p],[y])=>p.localeCompare(y)))a.has(c)||u.has(l.from)||u.has(l.to)||!d.has(l.from)&&!d.has(l.to)||t.push({...Ke("unplanned",l,`${l.from} -> ${l.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let g={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((c,l)=>g[c.classification]-g[l.classification]||(c.subject===l.subject?0:c.subject==="file"?-1:1)||c.id.localeCompare(l.id));let m={satisfied:t.filter(c=>c.classification==="satisfied").length,missing:t.filter(c=>c.classification==="missing").length,contradictory:t.filter(c=>c.classification==="contradictory").length,unplanned:t.filter(c=>c.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:m.missing===0&&m.contradictory===0&&m.unplanned===0,behavioralCompletion:"not-evaluated",summary:m,findings:t}}var Vr="1.0",Cn="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",kn=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","no-anemic-model","invariant-coverage"],Li=["no-anemic-model"],Dr={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},_t={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Cn,title:"ArkGate ArkRules (intra-layer contract)",description:"Per-layer structure sensors and invariant catalog consumed by the ArkGate Effective Contract.",type:"object",additionalProperties:!1,required:["schemaVersion","layer"],properties:{$schema:{type:"string",minLength:1,default:Cn},schemaVersion:{type:"string",const:"1.0",default:"1.0"},layer:{type:"string",minLength:1},structure:{type:"array",default:[],items:{$ref:"#/$defs/structureEntry"}},invariants:{type:"array",default:[],items:{$ref:"#/$defs/invariantEntry"}}},$defs:{structureEntry:{type:"object",additionalProperties:!1,required:["id","sensor"],properties:{id:{type:"string",minLength:1},sensor:{type:"string",enum:[...kn]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:Dr,description:{type:"string",minLength:1}}},invariantEntry:{type:"object",additionalProperties:!1,required:["id","description"],properties:{id:{type:"string",minLength:1},description:{type:"string",minLength:1},aggregate:{type:"string",minLength:1},coverage:{type:"object",additionalProperties:!1,properties:{test:{type:"boolean"},symbol:{type:"string",minLength:1}}},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:Dr}}}},ye=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkRules (${t}):
|
package/dist/index.d.ts
CHANGED
|
@@ -244,7 +244,7 @@ declare function loadArkConfigContract(input: unknown, source?: string): ArkConf
|
|
|
244
244
|
declare function parseArkConfigJson(json: string, source?: string): ArkConfigLoadResult;
|
|
245
245
|
|
|
246
246
|
/** ArkGate library version — single source of truth. */
|
|
247
|
-
declare const version = "4.5.
|
|
247
|
+
declare const version = "4.5.7";
|
|
248
248
|
|
|
249
249
|
/** Versioned public result contract shared by every ArkGate enforcement adapter. */
|
|
250
250
|
/**
|