arkgate 4.6.3 → 4.6.4
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 +26 -1
- package/README.md +6 -5
- package/bin/ark-mcp-runtime.mjs +36 -3
- package/bin/ark.mjs +1 -0
- package/bin/lib/managed-upgrade.mjs +1 -1
- package/bin/lib/upgrade-command.mjs +37 -4
- package/bin/lib/upgrade-whats-new.mjs +19 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/docs/README.md +4 -4
- package/docs/agent-guide.md +2 -1
- package/docs/ai-gates.md +5 -0
- package/docs/develop.md +1 -0
- package/docs/package-surface.md +5 -5
- package/docs/threat-model.md +1 -1
- package/package.json +1 -1
- package/server.json +2 -2
- package/templates/agent-skills/README.md +1 -1
- package/templates/agent-skills/ark-upgrade/SKILL.md +13 -2
- package/templates/skills/ark-upgrade.md +13 -2
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,30 @@ in the immutable pre-2.0 archive linked below.
|
|
|
5
5
|
|
|
6
6
|
## Unreleased
|
|
7
7
|
|
|
8
|
+
## 4.6.4 — 2026-08-18
|
|
9
|
+
|
|
10
|
+
**Patch** over **4.6.3**. `ark upgrade` now tells Codex users how to activate the local
|
|
11
|
+
`apply_patch` boundary after upgrading: refresh the project hook, restart Codex/local Desktop,
|
|
12
|
+
trust the exact hook definition, and verify `doctor.writePath` after a governed patch.
|
|
13
|
+
**No required config migration.**
|
|
14
|
+
|
|
15
|
+
**Status: prepared** (not yet on npm `latest`; see `docs/releases/4.6.4.md`).
|
|
16
|
+
|
|
17
|
+
### Changed
|
|
18
|
+
|
|
19
|
+
- **Upgrade JSON:** `whatsNew.items` includes stable id `codex-hard-write` with the exact
|
|
20
|
+
`--install-agent-gates --tools codex --force` command and evidence to inspect.
|
|
21
|
+
- **Upgrade human output:** **Suggested improvements** prints the same refresh/restart/trust/check
|
|
22
|
+
path on preview and apply, including nothing-to-apply previews.
|
|
23
|
+
- **Upgrade skill:** flat and Agent Skills guidance tells Codex to exercise a governed
|
|
24
|
+
`apply_patch` and keeps hosted/specialized/shell/direct/incomplete/human paths CI-backed.
|
|
25
|
+
- **Stale MCP fail-closed:** when process version no longer matches the project install,
|
|
26
|
+
`ark_identity` reports non-authoritative evidence and project tools return
|
|
27
|
+
`PROCESS_PACKAGE_STALE` until restart/retarget.
|
|
28
|
+
- **Global CLI handoff:** a modern stale global `ark upgrade` delegates the original invocation
|
|
29
|
+
to the project-local `node_modules/arkgate/bin/ark.mjs` instead of managing from the wrong PATH
|
|
30
|
+
version. Pre-4.6.4 globals still require one `npx arkgate upgrade` entry.
|
|
31
|
+
|
|
8
32
|
## 4.6.3 — 2026-08-18
|
|
9
33
|
|
|
10
34
|
**Patch** over **4.6.2**. Codex CLI and local ChatGPT Desktop/App Server now get a
|
|
@@ -12,7 +36,8 @@ runtime-proven pre-write block for complete `apply_patch` calls. ArkGate accepts
|
|
|
12
36
|
`tool_input.command` payload, while incomplete, hosted, specialized, shell/direct, and human
|
|
13
37
|
write paths remain CI-backed. **No required config migration.**
|
|
14
38
|
|
|
15
|
-
**Status:
|
|
39
|
+
**Status: published** (npm `latest` from signed tag `v4.6.3`; OIDC run `32167523804`;
|
|
40
|
+
see `docs/releases/4.6.3.md`).
|
|
16
41
|
|
|
17
42
|
### Changed
|
|
18
43
|
|
package/README.md
CHANGED
|
@@ -16,9 +16,9 @@ and makes sure a “green” check means something real.
|
|
|
16
16
|
|
|
17
17
|
</div>
|
|
18
18
|
|
|
19
|
-
> **ArkGate 4.6.
|
|
20
|
-
> **4.6.
|
|
21
|
-
> [4.6.
|
|
19
|
+
> **ArkGate 4.6.3** is on npm `latest` — Codex CLI/local Desktop hard-block complete trusted `apply_patch`.
|
|
20
|
+
> **4.6.4 is prepared** — `ark upgrade` tells Codex how to refresh, trust, restart, and verify it.
|
|
21
|
+
> [4.6.4 notes](docs/releases/4.6.4.md) · [4.6.3](docs/releases/4.6.3.md) · [4.6.2](docs/releases/4.6.2.md) · [4.6.1](docs/releases/4.6.1.md) · [Docs hub](docs/README.md) · [Product voice](docs/product-voice.md)
|
|
22
22
|
|
|
23
23
|
---
|
|
24
24
|
|
|
@@ -216,8 +216,9 @@ for real systems. Details: [docs/production-hardening.md](docs/production-harden
|
|
|
216
216
|
| Config · package surface · TS | [configuration](docs/configuration.md) · [package-surface](docs/package-surface.md) · [typescript-support](docs/typescript-support.md) |
|
|
217
217
|
| Brownfield | [docs/brownfield-adoption.md](docs/brownfield-adoption.md) |
|
|
218
218
|
| Security | [SECURITY.md](SECURITY.md) |
|
|
219
|
-
| Current release (4.6.
|
|
220
|
-
| Prepared patch (4.6.
|
|
219
|
+
| Current release (4.6.3 on npm `latest`) | [docs/releases/4.6.3.md](docs/releases/4.6.3.md) · [CHANGELOG](CHANGELOG.md) |
|
|
220
|
+
| Prepared patch (4.6.4) | [docs/releases/4.6.4.md](docs/releases/4.6.4.md) |
|
|
221
|
+
| Prior (4.6.2) | [docs/releases/4.6.2.md](docs/releases/4.6.2.md) |
|
|
221
222
|
| Prior (4.6.1) | [docs/releases/4.6.1.md](docs/releases/4.6.1.md) |
|
|
222
223
|
| Prior (4.6.0) | [docs/releases/4.6.0.md](docs/releases/4.6.0.md) |
|
|
223
224
|
| Prior (4.5.7) | [docs/releases/4.5.7.md](docs/releases/4.5.7.md) |
|
package/bin/ark-mcp-runtime.mjs
CHANGED
|
@@ -1960,11 +1960,14 @@ export async function runArkMcp({ hookInput } = {}) {
|
|
|
1960
1960
|
}
|
|
1961
1961
|
|
|
1962
1962
|
function contextFor(binding) {
|
|
1963
|
+
const processPackage = processPackageHonesty();
|
|
1963
1964
|
return {
|
|
1964
1965
|
projectIdentity,
|
|
1965
1966
|
binding,
|
|
1966
|
-
authoritative
|
|
1967
|
-
|
|
1967
|
+
// A correctly bound project is still non-authoritative when this long-lived
|
|
1968
|
+
// process loaded a different package version than the project now resolves.
|
|
1969
|
+
authoritative: binding.authoritative && !processPackage.processStale,
|
|
1970
|
+
processPackage,
|
|
1968
1971
|
};
|
|
1969
1972
|
}
|
|
1970
1973
|
|
|
@@ -2041,13 +2044,36 @@ export async function runArkMcp({ hookInput } = {}) {
|
|
|
2041
2044
|
);
|
|
2042
2045
|
}
|
|
2043
2046
|
|
|
2047
|
+
function staleProcessFailureResult(binding) {
|
|
2048
|
+
const processPackage = processPackageHonesty();
|
|
2049
|
+
return withProjectContext(
|
|
2050
|
+
{
|
|
2051
|
+
content: [
|
|
2052
|
+
{
|
|
2053
|
+
type: 'text',
|
|
2054
|
+
text: JSON.stringify({
|
|
2055
|
+
ok: false,
|
|
2056
|
+
error: {
|
|
2057
|
+
code: 'PROCESS_PACKAGE_STALE',
|
|
2058
|
+
message: processPackage.nextAction,
|
|
2059
|
+
},
|
|
2060
|
+
}),
|
|
2061
|
+
},
|
|
2062
|
+
],
|
|
2063
|
+
isError: true,
|
|
2064
|
+
},
|
|
2065
|
+
binding
|
|
2066
|
+
);
|
|
2067
|
+
}
|
|
2068
|
+
|
|
2044
2069
|
const TOOLS = [
|
|
2045
2070
|
{
|
|
2046
2071
|
name: 'ark_identity',
|
|
2047
2072
|
description:
|
|
2048
2073
|
'First call. Prove this MCP process is the right project: pass project.expectedRoot ' +
|
|
2049
2074
|
'(exact absolute root) and reuse the returned projectId. Do this before any other Ark tool. ' +
|
|
2050
|
-
'A missing
|
|
2075
|
+
'A missing/unmatched root or processPackage.processStale means restart/retarget the host ' +
|
|
2076
|
+
'and use the project-local CLI until identity and package versions align.',
|
|
2051
2077
|
inputSchema: { type: 'object', properties: {} },
|
|
2052
2078
|
},
|
|
2053
2079
|
{
|
|
@@ -3005,6 +3031,13 @@ export async function runArkMcp({ hookInput } = {}) {
|
|
|
3005
3031
|
reply(id, bindingFailureResult(binding));
|
|
3006
3032
|
return;
|
|
3007
3033
|
}
|
|
3034
|
+
// Keep ark_identity available so the host can diagnose the stale process,
|
|
3035
|
+
// but fail every project tool closed until the MCP server restarts on the
|
|
3036
|
+
// version installed for this root.
|
|
3037
|
+
if (params?.name !== 'ark_identity' && processPackageHonesty().processStale) {
|
|
3038
|
+
reply(id, staleProcessFailureResult(binding));
|
|
3039
|
+
return;
|
|
3040
|
+
}
|
|
3008
3041
|
try {
|
|
3009
3042
|
reply(id, withProjectContext(handler(params, binding), binding));
|
|
3010
3043
|
} catch (error) {
|
package/bin/ark.mjs
CHANGED
|
@@ -725,7 +725,7 @@ export function buildPostUpgradeChecks(root, options = {}) {
|
|
|
725
725
|
neverGateInput: true,
|
|
726
726
|
checks,
|
|
727
727
|
mcpNote:
|
|
728
|
-
'If you used Ark MCP this session: restart/retarget
|
|
728
|
+
'If you used Ark MCP this session: restart/retarget after the package bump. A stale process is non-authoritative and project tools return PROCESS_PACKAGE_STALE; always pass project.expectedRoot + expectedProjectId. Prefer project-local CLI until identity and package versions align.',
|
|
729
729
|
};
|
|
730
730
|
}
|
|
731
731
|
|
|
@@ -148,8 +148,9 @@ function staleCliRefuseMessage(detail) {
|
|
|
148
148
|
* project's installed arkgate. Legacy global 2.x mutates skills; a newer
|
|
149
149
|
* project pin must not be managed by an older outside-tree binary.
|
|
150
150
|
*
|
|
151
|
-
* Allow: no local install
|
|
152
|
-
* (realpath)
|
|
151
|
+
* Allow directly: no local install or CLI package root inside the project install tree
|
|
152
|
+
* (realpath). Any outside-tree modern CLI prefers a project-local handoff, even at the same
|
|
153
|
+
* or newer version, so one checkout never manages another through PATH state.
|
|
153
154
|
*
|
|
154
155
|
* @param {string} root project root for --root
|
|
155
156
|
* @param {{
|
|
@@ -157,7 +158,7 @@ function staleCliRefuseMessage(detail) {
|
|
|
157
158
|
* cliPackageRoot?: string|null,
|
|
158
159
|
* projectPackageJsonPath?: string|null,
|
|
159
160
|
* }} [options]
|
|
160
|
-
* @returns {{ refuse: boolean, reason: string, message?: string, cliVersion?: string|null, projectVersion?: string|null, cliPackageRoot?: string|null, projectPackageRoot?: string|null }}
|
|
161
|
+
* @returns {{ refuse: boolean, handoff?: boolean, reason: string, message?: string, cliVersion?: string|null, projectVersion?: string|null, cliPackageRoot?: string|null, projectPackageRoot?: string|null }}
|
|
161
162
|
*/
|
|
162
163
|
export function evaluateStaleUpgradeCli(root, options = {}) {
|
|
163
164
|
const projectPkgPath =
|
|
@@ -272,7 +273,8 @@ export function evaluateStaleUpgradeCli(root, options = {}) {
|
|
|
272
273
|
|
|
273
274
|
return {
|
|
274
275
|
refuse: false,
|
|
275
|
-
|
|
276
|
+
handoff: true,
|
|
277
|
+
reason: 'outside-cli-project-local-preferred',
|
|
276
278
|
cliVersion,
|
|
277
279
|
projectVersion,
|
|
278
280
|
cliPackageRoot,
|
|
@@ -325,6 +327,15 @@ function verify(root, json, arkCheck, runArkCheck) {
|
|
|
325
327
|
return { exitCode: result.status ?? 1, stderr: result.stderr?.trim() || undefined };
|
|
326
328
|
}
|
|
327
329
|
|
|
330
|
+
function runProjectLocalCli({ root, script, argv }) {
|
|
331
|
+
const result = spawnSync(process.execPath, [script, ...argv], {
|
|
332
|
+
cwd: root,
|
|
333
|
+
stdio: 'inherit',
|
|
334
|
+
env: { ...process.env, ARK_PROJECT_LOCAL_HANDOFF: '1' },
|
|
335
|
+
});
|
|
336
|
+
return result.status ?? 1;
|
|
337
|
+
}
|
|
338
|
+
|
|
328
339
|
export function runUpgradeCommand(args, dependencies) {
|
|
329
340
|
const root = args.root;
|
|
330
341
|
// Fail closed before install/plan when PATH resolves a global/stale CLI older
|
|
@@ -339,6 +350,28 @@ export function runUpgradeCommand(args, dependencies) {
|
|
|
339
350
|
cliVersion: dependencies?.cliVersion,
|
|
340
351
|
cliPackageRoot: dependencies?.cliPackageRoot,
|
|
341
352
|
});
|
|
353
|
+
if (staleGuard?.refuse || staleGuard?.handoff) {
|
|
354
|
+
const projectLocalScript =
|
|
355
|
+
typeof staleGuard.projectPackageRoot === 'string'
|
|
356
|
+
? path.join(staleGuard.projectPackageRoot, 'bin', 'ark.mjs')
|
|
357
|
+
: null;
|
|
358
|
+
if (
|
|
359
|
+
process.env.ARK_PROJECT_LOCAL_HANDOFF !== '1' &&
|
|
360
|
+
Array.isArray(dependencies?.rawArgv) &&
|
|
361
|
+
projectLocalScript &&
|
|
362
|
+
fs.existsSync(projectLocalScript)
|
|
363
|
+
) {
|
|
364
|
+
const handoff =
|
|
365
|
+
typeof dependencies.runProjectLocalCli === 'function'
|
|
366
|
+
? dependencies.runProjectLocalCli
|
|
367
|
+
: runProjectLocalCli;
|
|
368
|
+
return handoff({
|
|
369
|
+
root,
|
|
370
|
+
script: projectLocalScript,
|
|
371
|
+
argv: dependencies.rawArgv,
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
}
|
|
342
375
|
if (staleGuard?.refuse) {
|
|
343
376
|
const message = staleGuard.message || 'Refusing ark upgrade: stale CLI.';
|
|
344
377
|
if (args.json) {
|
|
@@ -65,6 +65,15 @@ export function buildUpgradeWhatsNewSuggestions() {
|
|
|
65
65
|
why:
|
|
66
66
|
'Project skills follow this pin. Shared homes stay on the newest ArkGate on the machine (additive; never downgrade). Orphan 2.x global skills stop coaching the wrong version.',
|
|
67
67
|
},
|
|
68
|
+
{
|
|
69
|
+
id: 'codex-hard-write',
|
|
70
|
+
title: 'Codex complete local apply_patch block',
|
|
71
|
+
try: 'npx arkgate-check --install-agent-gates --tools codex --force',
|
|
72
|
+
inspect:
|
|
73
|
+
'.codex/hooks.json trust + doctor.writePath after a runtime-observed apply_patch',
|
|
74
|
+
why:
|
|
75
|
+
'After upgrade, refresh the project hook, restart Codex or local Desktop, and trust the exact hook definition. Only a complete observed apply_patch is hard; hosted, specialized, shell/direct, incomplete, and human paths still rely on required CI.',
|
|
76
|
+
},
|
|
68
77
|
{
|
|
69
78
|
id: 'deep-module-coach',
|
|
70
79
|
title: 'Deep-module coach (hot paths + deepening)',
|
|
@@ -129,7 +138,16 @@ export function buildUpgradeWhatsNewSuggestions() {
|
|
|
129
138
|
try: 'ark_identity with project.expectedRoot; read processPackage on every tool',
|
|
130
139
|
inspect: 'processPackage.processPackageMismatch / processStale + nextAction',
|
|
131
140
|
why:
|
|
132
|
-
'One user, many checkouts: after package bump, restart MCP so process arkgateVersion matches install.
|
|
141
|
+
'One user, many checkouts: after package bump, restart MCP so process arkgateVersion matches install. A stale process is non-authoritative and project tools fail closed until restart.',
|
|
142
|
+
},
|
|
143
|
+
{
|
|
144
|
+
id: 'process-version-recovery',
|
|
145
|
+
title: 'Stale MCP / global CLI recovery',
|
|
146
|
+
try: 'npx arkgate upgrade --json',
|
|
147
|
+
inspect:
|
|
148
|
+
'processPackage.processStale + PROCESS_PACKAGE_STALE; project-local CLI handoff for stale global upgrade',
|
|
149
|
+
why:
|
|
150
|
+
'A long-lived MCP on an older package can no longer return authoritative project evidence. A newer global ArkGate that is older than this project automatically hands `ark upgrade` to the project-local CLI instead of staying stuck on PATH.',
|
|
133
151
|
},
|
|
134
152
|
],
|
|
135
153
|
};
|
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 Lo={};Ws(Lo,{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:()=>as,ARK_IMPROVEMENT_COMPASS_SCHEMA_VERSION:()=>ot,ARK_PROJECT_IDENTITY_SCHEMA:()=>hr,ARK_PROJECT_IDENTITY_SCHEMA_URL:()=>on,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:()=>or,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:()=>at,POLICY_DELTA_SCHEMA_VERSION:()=>wt,PROJECT_BINDING_SCHEMA:()=>ln,PROJECT_EXPECTATION_SCHEMA:()=>an,RESOLVED_CANDIDATE_FACTS_SCHEMA:()=>vt,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION:()=>oe,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:()=>os,isArkSkillName:()=>en,isCataloguedOrArkRuleFamily:()=>us,isKnownDiagnosticCode:()=>ps,isValidAgentSkillName:()=>ar,loadArkConfigContract:()=>Ue,loadArkRulesContract:()=>We,loadContract:()=>Xe,loadResolvedCandidateFacts:()=>se,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(Lo);var pr="4.6.3";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)}:{}},o=n??ft(e),a=rn(o);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:a,targetKey:o,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??[],o=e.warnings??[],a=pt(i),d=pt(o),u=[...i.map((m,c)=>ut(m,"error",a[c])),...o.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",on="https://unpkg.com/arkgate@4/schemas/ark.project-identity.schema.json",mt="^sha256:[a-f0-9]{64}$",an={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:on,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:an,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 ie(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(o=>o===s||o.startsWith(`${s}.`));if(i.length===0)n.add(s);else for(let o of i)t.add(`ambient:${o}`);for(let o of pn[s]??[])t.add(`import-exact:${o}`)}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 a=0;a<n.length;a+=1){let d=n[a];d==="\\"&&a+1<n.length?(s+=Sr(n[a+1]),a+=1):d==="*"?n[a+1]==="*"?n[a+2]==="/"?(s+="(?:.*/)?",a+=2):(s+=".*",a+=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 o=new RegExp(`^${s}$`);return br.set(e,o),o}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 o=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return s;let a=0,d=-1;for(let u of r){let g=-1;for(let m=a;m<o.length;m+=1)if(o[m]===u){g=m;break}if(g<0)return i;d=g,a=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(o=>pe(o).test(n))){for(let o of i.patterns??[])if(pe(o).test(n)){let a=mn(o,n);a>s&&(s=a,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 o=s[i];if((o==="**"||o==="*")&&i>0){let a=s[i-1];a&&!a.includes("*")&&!a.includes("{")&&!a.includes("}")&&t.add(a)}}}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,o=r?.toPath,a=ni(s,t,r?.layers),d=i&&o?Rr(i,a):void 0,u=i&&o?Rr(o,a):void 0;if(ri({fromPath:i,toPath:o,folderCount:a.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(o=>o.getSourceFile().fileName===n.fileName)}function ue(e,t){let n,r=[],s=(o,a,d,u=!1)=>r.push({specifier:d,kind:a,line:Cr(t,o),typeOnly:u,unresolved:d===void 0,node:o}),i=o=>{if(e.isImportDeclaration(o))s(o,"import",Se(e,o.moduleSpecifier),Er(e,o));else if(e.isExportDeclaration(o)&&o.moduleSpecifier)s(o,"export",Se(e,o.moduleSpecifier),Er(e,o));else if(e.isImportEqualsDeclaration(o)&&e.isExternalModuleReference(o.moduleReference))s(o,"require",Se(e,o.moduleReference.expression),o.isTypeOnly===!0);else if(e.isCallExpression(o)){let a=o.expression.kind===e.SyntaxKind.ImportKeyword,u=e.isIdentifier(o.expression)&&o.expression.text==="require"&&!yn(e,n??(n=kr(e,t)),t,o.expression);(a||u)&&s(o,u?"require":"dynamic-import",Se(e,o.arguments[0]))}e.forEachChild(o,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,o=new Set;for(let c of t.statements)if(e.isVariableStatement(c))for(let l of c.declarationList.declarations)e.isIdentifier(l.name)&&o.add(l.name.text);let a=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)||o.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=a(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=a(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=a(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 Lo={};Ws(Lo,{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:()=>as,ARK_IMPROVEMENT_COMPASS_SCHEMA_VERSION:()=>ot,ARK_PROJECT_IDENTITY_SCHEMA:()=>hr,ARK_PROJECT_IDENTITY_SCHEMA_URL:()=>on,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:()=>or,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:()=>at,POLICY_DELTA_SCHEMA_VERSION:()=>wt,PROJECT_BINDING_SCHEMA:()=>ln,PROJECT_EXPECTATION_SCHEMA:()=>an,RESOLVED_CANDIDATE_FACTS_SCHEMA:()=>vt,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION:()=>oe,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:()=>os,isArkSkillName:()=>en,isCataloguedOrArkRuleFamily:()=>us,isKnownDiagnosticCode:()=>ps,isValidAgentSkillName:()=>ar,loadArkConfigContract:()=>Ue,loadArkRulesContract:()=>We,loadContract:()=>Xe,loadResolvedCandidateFacts:()=>se,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(Lo);var pr="4.6.4";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)}:{}},o=n??ft(e),a=rn(o);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:a,targetKey:o,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??[],o=e.warnings??[],a=pt(i),d=pt(o),u=[...i.map((m,c)=>ut(m,"error",a[c])),...o.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",on="https://unpkg.com/arkgate@4/schemas/ark.project-identity.schema.json",mt="^sha256:[a-f0-9]{64}$",an={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:on,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:an,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 ie(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(o=>o===s||o.startsWith(`${s}.`));if(i.length===0)n.add(s);else for(let o of i)t.add(`ambient:${o}`);for(let o of pn[s]??[])t.add(`import-exact:${o}`)}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 a=0;a<n.length;a+=1){let d=n[a];d==="\\"&&a+1<n.length?(s+=Sr(n[a+1]),a+=1):d==="*"?n[a+1]==="*"?n[a+2]==="/"?(s+="(?:.*/)?",a+=2):(s+=".*",a+=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 o=new RegExp(`^${s}$`);return br.set(e,o),o}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 o=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return s;let a=0,d=-1;for(let u of r){let g=-1;for(let m=a;m<o.length;m+=1)if(o[m]===u){g=m;break}if(g<0)return i;d=g,a=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(o=>pe(o).test(n))){for(let o of i.patterns??[])if(pe(o).test(n)){let a=mn(o,n);a>s&&(s=a,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 o=s[i];if((o==="**"||o==="*")&&i>0){let a=s[i-1];a&&!a.includes("*")&&!a.includes("{")&&!a.includes("}")&&t.add(a)}}}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,o=r?.toPath,a=ni(s,t,r?.layers),d=i&&o?Rr(i,a):void 0,u=i&&o?Rr(o,a):void 0;if(ri({fromPath:i,toPath:o,folderCount:a.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(o=>o.getSourceFile().fileName===n.fileName)}function ue(e,t){let n,r=[],s=(o,a,d,u=!1)=>r.push({specifier:d,kind:a,line:Cr(t,o),typeOnly:u,unresolved:d===void 0,node:o}),i=o=>{if(e.isImportDeclaration(o))s(o,"import",Se(e,o.moduleSpecifier),Er(e,o));else if(e.isExportDeclaration(o)&&o.moduleSpecifier)s(o,"export",Se(e,o.moduleSpecifier),Er(e,o));else if(e.isImportEqualsDeclaration(o)&&e.isExternalModuleReference(o.moduleReference))s(o,"require",Se(e,o.moduleReference.expression),o.isTypeOnly===!0);else if(e.isCallExpression(o)){let a=o.expression.kind===e.SyntaxKind.ImportKeyword,u=e.isIdentifier(o.expression)&&o.expression.text==="require"&&!yn(e,n??(n=kr(e,t)),t,o.expression);(a||u)&&s(o,u?"require":"dynamic-import",Se(e,o.arguments[0]))}e.forEachChild(o,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,o=new Set;for(let c of t.statements)if(e.isVariableStatement(c))for(let l of c.declarationList.declarations)e.isIdentifier(l.name)&&o.add(l.name.text);let a=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)||o.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=a(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=a(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=a(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 oi(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 ai(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]),o=s[0],a=r.kind==="import"&&/\bimport\s+type\b/.test(o)||r.kind==="export"&&/\bexport\s+type\b/.test(o);t.push({value:s[1],index:i,kind:r.kind,typeOnly:a})}}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,o=i?.filePath,a=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:o}));let p=hi(e,m);if(r&&a&&p&&me(p)){let y=r.resolveLayer(p);y&&y!==a&&d.push(w("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${p}" resolves to ${y}, but the target file is classified as ${a}.`,{line:u(m),filePath:o,target:p,fromLayer:a,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,o){let a=[],d=o,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})):ai(i),y=e.typescript?li(e.typescript,i):oi(i);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(u))for(let f of l?.filter(({unresolved:h})=>h)??[]){let h=f.kind==="require";a.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&&a.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)&&a.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;a.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)||a.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:o});if(h!==!0)if(Array.isArray(h))for(let S of h)a.push(w("POLICY_VIOLATION",S.message,{filePath:u,suggestion:`Fix violation of policy "${f.name}".`}));else h===!1?a.push(w("POLICY_VIOLATION",`Policy ${f.name} failed on generated code`)):a.push(w("POLICY_VIOLATION",h.message))}if(s&&t.size>0)for(let f of y)me(f.value)&&!t.has(f.value)&&a.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&&a.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,o);a.push(...h)}catch(h){a.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];a.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=ie(h.specifier,f);S&&a.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){a.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"&&ie(S.symbol,h)||a.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){a.push(w("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${f instanceof Error?f.message:String(f)}`))}if(e.typescript)try{a.push(...Ai(e.typescript,i,o,e.architectureProfile))}catch(f){a.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:a.length===0,violations:a}}}}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"}],te={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:{...te,minItems:1,default:["src"]},exclude:{...te,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:St,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...te,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},stewards:{...te,default:[]}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...te,minItems:1},exclude:te,intentPrefixes:te,description:{type:"string",minLength:1},forbiddenGlobals:te,capabilities:{type:"object",additionalProperties:!1,properties:{deny:{type:"array",uniqueItems:!0,items:{type:"string",enum:["network","filesystem","clock","randomness","environment","process","persistence"]}}}},pure:{type:"boolean"},mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...te,minItems:1}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}}}},ne=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 o of t.required??[])e[o]===void 0&&s.push({path:At(n,o),message:"is required"});if(t.additionalProperties===!1)for(let o of Object.keys(e))o in i||s.push({path:At(n,o),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let o=t.additionalProperties;for(let a of Object.keys(e))a in i||je(e[a],o,At(n,a),r,s)}for(let[o,a]of Object.entries(i))e[o]!==void 0&&je(e[o],a,At(n,o),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(o=>JSON.stringify(o));new Set(i).size!==i.length&&s.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((i,o)=>je(i,t.items,`${n}[${o}]`,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 ne(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 ne(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.1`}]);if(r!=="unversioned"&&!n.has(r))throw new ne(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected 1.1`}]);let s=r,i={...e},o=0;for(;s!=="1.1"&&o<Rn.length+1;){o+=1;let d=Rn.find(u=>u.from===s);if(!d)throw new ne(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(s)}; expected 1.1`}]);s=d.to,i.schemaVersion=s}if(s!=="1.1")throw new ne(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected 1.1`}]);let a=r==="unversioned"?"unversioned":r==="1.0"?"1.0":null;return{candidate:Ri(i),migratedFrom:a}}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 ne(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 ne(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(o=>s.startsWith(o)))?.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 oe="1.1";var Nr=["network","filesystem","clock","randomness","environment","process","persistence"];function re(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(re),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(re),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(re),s=e.capabilityUses.map(c=>({...c})).sort(re),i=e.ambientUses.map(c=>({...c})).sort(re),o=e.publishCalls.map(c=>({...c})).sort(re),a=e.intentReferences.map(c=>({...c})).sort(re),d=e.safetyUses.map(c=>({...c})).sort(re),u=(e.classShapes??[]).map(c=>({...c,mutatingMethods:[...c.mutatingMethods??[]].map(l=>({...l}))})).sort(re),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:o,intentReferences:a,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 a of s.split("/"))if(!(!a||a==="."))if(a===".."){if(i.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);i.pop()}else i.push(a);let o=i.join("/");if(!o||o!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return o}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 ae(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=ae(e,"schemaVersion",["1.0","1.1"],"$"),r=ae(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:ae(h,"parseStatus",["parsed","invalid"],f),parseDiagnosticCount:$r(h,"parseDiagnosticCount",f),exportsOnlyTypes:$(h,"exportsOnlyTypes",f),typeOnlyExportNames:wr(h.typeOnlyExportNames,`${f}.typeOnlyExportNames`),hasTopLevelSideEffects:$(h,"hasTopLevelSideEffects",f)}}),o=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=ae(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:ae(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)}:{}}}),a=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:ae(h,"capability",Nr,f),source:ae(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=ae(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 o)if(!c.has(I.from))throw new Error(`$.dependencies references missing source file ${I.from}.`);for(let[I,R]of[["$.capabilityUses",a],["$.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:o,capabilityUses:a,ambientUses:d,publishCalls:u,intentReferences:g,safetyUses:m,classShapes:y}}function se(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])),o=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 a=new Set;for(let c of[...s.values()].sort((l,p)=>U(l).localeCompare(U(p)))){if(o.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};o.has(U(l))?(a.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[...o].sort(([p],[y])=>p.localeCompare(y)))i.has(c)||s.has(c)||a.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)))o.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
|
@@ -254,7 +254,7 @@ declare function loadArkConfigContract(input: unknown, source?: string): ArkConf
|
|
|
254
254
|
declare function parseArkConfigJson(json: string, source?: string): ArkConfigLoadResult;
|
|
255
255
|
|
|
256
256
|
/** ArkGate library version — single source of truth. */
|
|
257
|
-
declare const version = "4.6.
|
|
257
|
+
declare const version = "4.6.4";
|
|
258
258
|
|
|
259
259
|
/** Versioned public result contract shared by every ArkGate enforcement adapter. */
|
|
260
260
|
/**
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var ts="4.6.3";var ns="1.5",kn="docs/diagnostics.md";function v(e){return typeof e=="string"&&e.length>0?e:void 0}function Cn(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function Ot(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 _t(e){let t=new Map;return e.map(n=>{let r=Ot(n),s=(t.get(r)??0)+1;return t.set(r,s),s===1?r:`${r}#${s}`})}function _n(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 xn(e){return`${kn}#${e}`}function rs(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 xt(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)}:{}},o=n??Ot(e),a=_n(o);return{ruleId:r,severity:s,message:v(e.message)??r,location:{file:v(e.file)??"<unknown>",line:Cn(e.line,1),column:Cn(e.column,1)},evidence:i,nextAction:v(e.nextAction)??rs(r,i,e),findingRef:a,targetKey:o,docsCodePath:xn(r)}}function ss(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??[],o=e.warnings??[],a=_t(i),d=_t(o),u=[...i.map((m,c)=>xt(m,"error",a[c])),...o.map((m,c)=>xt(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 is={$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 os="1.0",On="https://unpkg.com/arkgate@4/schemas/ark.project-identity.schema.json",We="^sha256:[a-f0-9]{64}$",Tn={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:We,description:"Project id previously returned by ark_identity or ark_manifest."}}},Pn={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:We},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},as={$schema:"https://json-schema.org/draft/2020-12/schema",$id:On,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:We},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{type:"string",minLength:1},arkgateVersion:{type:"string",minLength:1},contractHash:{type:"string",pattern:We},contractSource:{enum:["project","default-profile","manifest"]},runtimeId:{type:"string",minLength:1},processStartedAt:{type:"string",format:"date-time"}},$defs:{expectation:Tn,binding:Pn}};function ls(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 cs(e){return{schemaVersion:"1.0",...e}}var Pt=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),Nt=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),wt=Object.freeze(Object.keys(Nt).sort()),Tt=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"}),Lt=Object.freeze({process:Object.freeze(["process","node:process"])});function Le(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=Tt[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),s=Tt[r];if(s)return s;let i=e.indexOf("/",n+1);return i<0?null:Tt[e.slice(0,i)]??null}function se(e,t){for(let n of t)if(Lt[n]?.includes(e))return n;return null}function Je(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),s=Nt[r];if(s)return s}return null}function ye(e){if(e?.pure===!0)return[...Pt].sort();let n=(e?.capabilities?.deny??[]).filter(r=>Pt.includes(r));return[...new Set(n)].sort()}function Ne(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 Ze(e){let t=new Set,n=new Set,r=Object.keys(Nt);for(let s of e?.forbiddenGlobals??[]){let i=r.filter(o=>o===s||o.startsWith(`${s}.`));if(i.length===0)n.add(s);else for(let o of i)t.add(`ambient:${o}`);for(let o of Lt[s]??[])t.add(`import-exact:${o}`)}for(let s of ye(e)){if(t.add(`import:${s}`),s==="process")for(let i of Lt.process)t.add(`import-exact:${i}`);for(let i of r)Je(i)===s&&t.add(`ambient:${i}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}var Ln=new Map;function Nn(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function Xe(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 ds(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 le(e){let t=Ln.get(e);if(t)return t;let n=Xe(e),r=ds(n),s="",i=0;for(let a=0;a<n.length;a+=1){let d=n[a];d==="\\"&&a+1<n.length?(s+=Nn(n[a+1]),a+=1):d==="*"?n[a+1]==="*"?n[a+2]==="/"?(s+="(?:.*/)?",a+=2):(s+=".*",a+=1):s+="[^/]*":d==="?"?s+="[^/]":d==="{"&&r?(s+="(?:",i+=1):d==="}"&&r&&i>0?(s+=")",i-=1):d===","&&r&&i>0?s+="|":s+=Nn(d)}let o=new RegExp(`^${s}$`);return Ln.set(e,o),o}function ps(e){return Xe(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}function Mt(e,t){let n=Xe(String(e)),r=ps(n),s=n.replace(/\*/g,"").length,i=r.length*1e4+s;if(t==null||t==="")return i;let o=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return s;let a=0,d=-1;for(let u of r){let g=-1;for(let m=a;m<o.length;m+=1)if(o[m]===u){g=m;break}if(g<0)return i;d=g,a=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(o=>le(o).test(n))){for(let o of i.patterns??[])if(le(o).test(n)){let a=Mt(o,n);a>s&&(s=a,r=i.name)}}return r}function wn(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 us(e){let t=new Set;for(let n of e??[]){let s=Xe(String(n)).split("/").filter(Boolean);for(let i=0;i<s.length;i+=1){let o=s[i];if((o==="**"||o==="*")&&i>0){let a=s[i-1];a&&!a.includes("*")&&!a.includes("{")&&!a.includes("}")&&t.add(a)}}}return[...t]}function fs(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 us(r?.patterns)}function ms(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,o=r?.toPath,a=fs(s,t,r?.layers),d=i&&o?wn(i,a):void 0,u=i&&o?wn(o,a):void 0;if(ms({fromPath:i,toPath:o,folderCount:a.length,fromSlice:d,toSlice:u}))return s;continue}if(t!==n)return s}}function he(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function Fn(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function Mn(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 Dn(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 $t(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function Ft(e,t,n,r){let s=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,i;try{i=s?t.getShorthandAssignmentValueSymbol(r.parent):$t(t,r)}catch{i=void 0}return!!i?.declarations?.some(o=>o.getSourceFile().fileName===n.fileName)}function Ae(e,t){let n,r=[],s=(o,a,d,u=!1)=>r.push({specifier:d,kind:a,line:Fn(t,o),typeOnly:u,unresolved:d===void 0,node:o}),i=o=>{if(e.isImportDeclaration(o))s(o,"import",he(e,o.moduleSpecifier),Mn(e,o));else if(e.isExportDeclaration(o)&&o.moduleSpecifier)s(o,"export",he(e,o.moduleSpecifier),Mn(e,o));else if(e.isImportEqualsDeclaration(o)&&e.isExternalModuleReference(o.moduleReference))s(o,"require",he(e,o.moduleReference.expression),o.isTypeOnly===!0);else if(e.isCallExpression(o)){let a=o.expression.kind===e.SyntaxKind.ImportKeyword,u=e.isIdentifier(o.expression)&&o.expression.text==="require"&&!Ft(e,n??(n=Dn(e,t)),t,o.expression);(a||u)&&s(o,u?"require":"dynamic-import",he(e,o.arguments[0]))}e.forEachChild(o,i)};return i(t),r}function gs(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=he(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 ys(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 $n(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 Ie(e,t,n){if(n.length===0)return[];let r=new Set(n),s=Dn(e,t),i=new Map,o=new Set;for(let c of t.statements)if(e.isVariableStatement(c))for(let l of c.declarationList.declarations)e.isIdentifier(l.name)&&o.add(l.name.text);let a=c=>{let l=gs(e,c);if(!l)return;let p=$t(s,l.root),y=p?i.get(p):void 0;return y?[...y,...l.segments.slice(1)]:Ft(e,s,t,l.root)||o.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=a(l.initializer),y=$t(s,l.name);!p||!y||i.set(y,p)}let d=[],u=new Set,g=(c,l)=>{let p=Fn(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=a(c),y=p?$n(r,p):void 0;y&&g(y,c)}else e.isIdentifier(c)&&r.has(c.text)&&ys(e,c)&&!Ft(e,s,t,c)&&g(c.text,c);if(e.isVariableDeclaration(c)&&e.isObjectBindingPattern(c.name)&&c.initializer){let p=a(c.initializer);if(p)for(let y of c.name.elements){if(!e.isIdentifier(y.name))continue;let I=y.propertyName?he(e,y.propertyName)??y.propertyName.text:y.name.text,R=$n(r,[...p,I]);R&&g(R,c.initializer)}}e.forEachChild(c,m)};return m(t),d}function Dt(e,t,n){let r=[];for(let s of n?.dependencies??Ae(e,t)){if(s.typeOnly||!s.specifier)continue;let i=Le(s.specifier);i&&r.push({capability:i,symbol:s.specifier,line:s.line,source:"import-based"})}for(let s of n?.ambientUses??Ie(e,t,wt)){let i=Je(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 Ht={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."},Vt=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 jt(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 ce(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function we(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&ce(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:Ht.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:Ht.PUBLISH_MISSING_SOURCE}),t}function w(e,t,n){return{ruleId:e,code:e,message:t,...n}}function be(e,t){return e.slice(0,t).split(`
|
|
1
|
+
var ts="4.6.4";var ns="1.5",kn="docs/diagnostics.md";function v(e){return typeof e=="string"&&e.length>0?e:void 0}function Cn(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function Ot(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 _t(e){let t=new Map;return e.map(n=>{let r=Ot(n),s=(t.get(r)??0)+1;return t.set(r,s),s===1?r:`${r}#${s}`})}function _n(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 xn(e){return`${kn}#${e}`}function rs(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 xt(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)}:{}},o=n??Ot(e),a=_n(o);return{ruleId:r,severity:s,message:v(e.message)??r,location:{file:v(e.file)??"<unknown>",line:Cn(e.line,1),column:Cn(e.column,1)},evidence:i,nextAction:v(e.nextAction)??rs(r,i,e),findingRef:a,targetKey:o,docsCodePath:xn(r)}}function ss(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??[],o=e.warnings??[],a=_t(i),d=_t(o),u=[...i.map((m,c)=>xt(m,"error",a[c])),...o.map((m,c)=>xt(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 is={$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 os="1.0",On="https://unpkg.com/arkgate@4/schemas/ark.project-identity.schema.json",We="^sha256:[a-f0-9]{64}$",Tn={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:We,description:"Project id previously returned by ark_identity or ark_manifest."}}},Pn={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:We},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},as={$schema:"https://json-schema.org/draft/2020-12/schema",$id:On,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:We},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{type:"string",minLength:1},arkgateVersion:{type:"string",minLength:1},contractHash:{type:"string",pattern:We},contractSource:{enum:["project","default-profile","manifest"]},runtimeId:{type:"string",minLength:1},processStartedAt:{type:"string",format:"date-time"}},$defs:{expectation:Tn,binding:Pn}};function ls(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 cs(e){return{schemaVersion:"1.0",...e}}var Pt=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),Nt=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),wt=Object.freeze(Object.keys(Nt).sort()),Tt=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"}),Lt=Object.freeze({process:Object.freeze(["process","node:process"])});function Le(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=Tt[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),s=Tt[r];if(s)return s;let i=e.indexOf("/",n+1);return i<0?null:Tt[e.slice(0,i)]??null}function se(e,t){for(let n of t)if(Lt[n]?.includes(e))return n;return null}function Je(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),s=Nt[r];if(s)return s}return null}function ye(e){if(e?.pure===!0)return[...Pt].sort();let n=(e?.capabilities?.deny??[]).filter(r=>Pt.includes(r));return[...new Set(n)].sort()}function Ne(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 Ze(e){let t=new Set,n=new Set,r=Object.keys(Nt);for(let s of e?.forbiddenGlobals??[]){let i=r.filter(o=>o===s||o.startsWith(`${s}.`));if(i.length===0)n.add(s);else for(let o of i)t.add(`ambient:${o}`);for(let o of Lt[s]??[])t.add(`import-exact:${o}`)}for(let s of ye(e)){if(t.add(`import:${s}`),s==="process")for(let i of Lt.process)t.add(`import-exact:${i}`);for(let i of r)Je(i)===s&&t.add(`ambient:${i}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}var Ln=new Map;function Nn(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function Xe(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 ds(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 le(e){let t=Ln.get(e);if(t)return t;let n=Xe(e),r=ds(n),s="",i=0;for(let a=0;a<n.length;a+=1){let d=n[a];d==="\\"&&a+1<n.length?(s+=Nn(n[a+1]),a+=1):d==="*"?n[a+1]==="*"?n[a+2]==="/"?(s+="(?:.*/)?",a+=2):(s+=".*",a+=1):s+="[^/]*":d==="?"?s+="[^/]":d==="{"&&r?(s+="(?:",i+=1):d==="}"&&r&&i>0?(s+=")",i-=1):d===","&&r&&i>0?s+="|":s+=Nn(d)}let o=new RegExp(`^${s}$`);return Ln.set(e,o),o}function ps(e){return Xe(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}function Mt(e,t){let n=Xe(String(e)),r=ps(n),s=n.replace(/\*/g,"").length,i=r.length*1e4+s;if(t==null||t==="")return i;let o=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return s;let a=0,d=-1;for(let u of r){let g=-1;for(let m=a;m<o.length;m+=1)if(o[m]===u){g=m;break}if(g<0)return i;d=g,a=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(o=>le(o).test(n))){for(let o of i.patterns??[])if(le(o).test(n)){let a=Mt(o,n);a>s&&(s=a,r=i.name)}}return r}function wn(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 us(e){let t=new Set;for(let n of e??[]){let s=Xe(String(n)).split("/").filter(Boolean);for(let i=0;i<s.length;i+=1){let o=s[i];if((o==="**"||o==="*")&&i>0){let a=s[i-1];a&&!a.includes("*")&&!a.includes("{")&&!a.includes("}")&&t.add(a)}}}return[...t]}function fs(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 us(r?.patterns)}function ms(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,o=r?.toPath,a=fs(s,t,r?.layers),d=i&&o?wn(i,a):void 0,u=i&&o?wn(o,a):void 0;if(ms({fromPath:i,toPath:o,folderCount:a.length,fromSlice:d,toSlice:u}))return s;continue}if(t!==n)return s}}function he(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function Fn(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function Mn(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 Dn(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 $t(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function Ft(e,t,n,r){let s=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,i;try{i=s?t.getShorthandAssignmentValueSymbol(r.parent):$t(t,r)}catch{i=void 0}return!!i?.declarations?.some(o=>o.getSourceFile().fileName===n.fileName)}function Ae(e,t){let n,r=[],s=(o,a,d,u=!1)=>r.push({specifier:d,kind:a,line:Fn(t,o),typeOnly:u,unresolved:d===void 0,node:o}),i=o=>{if(e.isImportDeclaration(o))s(o,"import",he(e,o.moduleSpecifier),Mn(e,o));else if(e.isExportDeclaration(o)&&o.moduleSpecifier)s(o,"export",he(e,o.moduleSpecifier),Mn(e,o));else if(e.isImportEqualsDeclaration(o)&&e.isExternalModuleReference(o.moduleReference))s(o,"require",he(e,o.moduleReference.expression),o.isTypeOnly===!0);else if(e.isCallExpression(o)){let a=o.expression.kind===e.SyntaxKind.ImportKeyword,u=e.isIdentifier(o.expression)&&o.expression.text==="require"&&!Ft(e,n??(n=Dn(e,t)),t,o.expression);(a||u)&&s(o,u?"require":"dynamic-import",he(e,o.arguments[0]))}e.forEachChild(o,i)};return i(t),r}function gs(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=he(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 ys(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 $n(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 Ie(e,t,n){if(n.length===0)return[];let r=new Set(n),s=Dn(e,t),i=new Map,o=new Set;for(let c of t.statements)if(e.isVariableStatement(c))for(let l of c.declarationList.declarations)e.isIdentifier(l.name)&&o.add(l.name.text);let a=c=>{let l=gs(e,c);if(!l)return;let p=$t(s,l.root),y=p?i.get(p):void 0;return y?[...y,...l.segments.slice(1)]:Ft(e,s,t,l.root)||o.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=a(l.initializer),y=$t(s,l.name);!p||!y||i.set(y,p)}let d=[],u=new Set,g=(c,l)=>{let p=Fn(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=a(c),y=p?$n(r,p):void 0;y&&g(y,c)}else e.isIdentifier(c)&&r.has(c.text)&&ys(e,c)&&!Ft(e,s,t,c)&&g(c.text,c);if(e.isVariableDeclaration(c)&&e.isObjectBindingPattern(c.name)&&c.initializer){let p=a(c.initializer);if(p)for(let y of c.name.elements){if(!e.isIdentifier(y.name))continue;let I=y.propertyName?he(e,y.propertyName)??y.propertyName.text:y.name.text,R=$n(r,[...p,I]);R&&g(R,c.initializer)}}e.forEachChild(c,m)};return m(t),d}function Dt(e,t,n){let r=[];for(let s of n?.dependencies??Ae(e,t)){if(s.typeOnly||!s.specifier)continue;let i=Le(s.specifier);i&&r.push({capability:i,symbol:s.specifier,line:s.line,source:"import-based"})}for(let s of n?.ambientUses??Ie(e,t,wt)){let i=Je(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 Ht={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."},Vt=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 jt(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 ce(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function we(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&ce(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:Ht.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:Ht.PUBLISH_MISSING_SOURCE}),t}function w(e,t,n){return{ruleId:e,code:e,message:t,...n}}function be(e,t){return e.slice(0,t).split(`
|
|
2
2
|
`).length}function hs(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 As(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]),o=s[0],a=r.kind==="import"&&/\bimport\s+type\b/.test(o)||r.kind==="export"&&/\bexport\s+type\b/.test(o);t.push({value:s[1],index:i,kind:r.kind,typeOnly:a})}}return t.sort((r,s)=>r.index-s.index)}function Is(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 bs(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 Ss(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}function Rs(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}function $e(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function Es(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}function Hn(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:Es(e,r.name)===n)}function Fe(e,t,n){return Hn(e,t,n)!==void 0}function Me(e,t,n){let r=Hn(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}function vs(e,t){let n=Me(e,t,"metadata");return Fe(e,n,"source")}function Vn(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?Vn(e,t.name):!1:!1}function Cs(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 ks(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=$e(e,n);return r!==void 0&&ce(r)||Fe(e,n,"intent")||Vn(e,n)}function _s(e,t){if(!e.isCallExpression(t))return!1;let[n,r,s]=t.arguments;return vs(e,n)||Fe(e,r,"source")||Fe(e,s,"source")}function xs(e,t){if(!e.isCallExpression(t))return;let[n,r,s]=t.arguments,i=Me(e,n,"metadata");return $e(e,Me(e,i,"source"))??$e(e,Me(e,r,"source"))??$e(e,Me(e,s,"source"))}function Os(e,t,n,r){let s=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),i=n,o=i?.filePath,a=i?.layer,d=[],u=m=>s.getLineAndCharacterOfPosition(m.getStart(s)).line+1,g=m=>{if(Cs(e,m)){let c=m.arguments[0],l=$e(e,c);for(let y of we({publishCall:!0,rawIntentName:l,objectHasIntent:Fe(e,c,"intent"),arkPublishCandidate:ks(e,m),hasSource:_s(e,m)}))d.push(w(y.ruleId,y.message,{line:u(m),filePath:o}));let p=xs(e,m);if(r&&a&&p&&ce(p)){let y=r.resolveLayer(p);y&&y!==a&&d.push(w("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${p}" resolves to ${y}, but the target file is classified as ${a}.`,{line:u(m),filePath:o,target:p,fromLayer:a,toLayer:y}))}}e.forEachChild(m,g)};return g(s),d}function jn(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,o){let a=[],d=o,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?Ae(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})):As(i),y=e.typescript?Is(e.typescript,i):hs(i);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(u))for(let f of l?.filter(({unresolved:h})=>h)??[]){let h=f.kind==="require";a.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)||Rs(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&&a.push(w("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${f}`,{line:h.index===void 0?void 0:be(i,h.index),filePath:u,suggestion:"Remove infrastructure imports from domain/application layers."+R}))}else i.includes(f)&&a.push(w("FORBIDDEN_SUBSTRING",`Forbidden substring: ${f}`,{line:be(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;a.push(w("LAYER_IMPORT_VIOLATION",N.message??(D?`Layer "${g}" must not import across slices into "${k}".`:`Layer "${g}" must not import "${k}".`),{line:be(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||!bs(f.value)&&!Ss(f.value)||a.push(w("FORBIDDEN_IMPORT",`Forbidden ${f.kind} target: "${f.value}".`,{line:be(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:o});if(h!==!0)if(Array.isArray(h))for(let S of h)a.push(w("POLICY_VIOLATION",S.message,{filePath:u,suggestion:`Fix violation of policy "${f.name}".`}));else h===!1?a.push(w("POLICY_VIOLATION",`Policy ${f.name} failed on generated code`)):a.push(w("POLICY_VIOLATION",h.message))}if(s&&t.size>0)for(let f of y)ce(f.value)&&!t.has(f.value)&&a.push(w("UNKNOWN_INTENT",`Unknown intent reference: "${f.value}"`,{line:be(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(!ce(f.value))continue;let h=e.architectureProfile.resolveLayer(f.value);if(!h)continue;let S=ee(e.architectureProfile.rules,g,h);S&&a.push(w("LAYER_REFERENCE_VIOLATION",S.message??`Layer "${g}" must not reference "${h}" through "${f.value}".`,{line:be(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,o);a.push(...h)}catch(h){a.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];a.push(...Ie(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&&a.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){a.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 Dt(e.typescript,c))f.has(S.capability)&&(S.source==="ambient-global"&&Ne(S.symbol,h)||S.source==="import-based"&&se(S.symbol,h)||a.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){a.push(w("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${f instanceof Error?f.message:String(f)}`))}if(e.typescript)try{a.push(...Os(e.typescript,i,o,e.architectureProfile))}catch(f){a.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:a.length===0,violations:a}}}}var Ts="1.1",et="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",Un=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Ps=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Ls(){let e=[];for(let t of Un)for(let n of Un)t===n||Ps.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var tt=Ls(),Ut=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"}],te={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Gt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:et,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:et,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:{...te,minItems:1,default:["src"]},exclude:{...te,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:tt,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...te,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},stewards:{...te,default:[]}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...te,minItems:1},exclude:te,intentPrefixes:te,description:{type:"string",minLength:1},forbiddenGlobals:te,capabilities:{type:"object",additionalProperties:!1,properties:{deny:{type:"array",uniqueItems:!0,items:{type:"string",enum:["network","filesystem","clock","randomness","environment","process","persistence"]}}}},pure:{type:"boolean"},mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...te,minItems:1}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}}}},ne=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 Gn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Qe(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function Se(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Ns(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function De(e,t,n,r,s){if(t.$ref){let i=Ns(t.$ref,r);if(!i){s.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}De(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(!Gn(e)){s.push({path:n,message:`must be an object; received ${Se(e)}`});return}let i=t.properties??{};for(let o of t.required??[])e[o]===void 0&&s.push({path:Qe(n,o),message:"is required"});if(t.additionalProperties===!1)for(let o of Object.keys(e))o in i||s.push({path:Qe(n,o),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let o=t.additionalProperties;for(let a of Object.keys(e))a in i||De(e[a],o,Qe(n,a),r,s)}for(let[o,a]of Object.entries(i))e[o]!==void 0&&De(e[o],a,Qe(n,o),r,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:n,message:`must be an array; received ${Se(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(o=>JSON.stringify(o));new Set(i).size!==i.length&&s.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((i,o)=>De(i,t.items,`${n}[${o}]`,r,s));return}if(t.type==="string"){if(typeof e!="string"){s.push({path:n,message:`must be a string; received ${Se(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 ${Se(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){s.push({path:n,message:`must be an integer; received ${Se(e)}`});return}t.minimum!==void 0&&e<t.minimum&&s.push({path:n,message:`must be at least ${t.minimum}`})}}function ws(e){return{...e,$schema:e.$schema===void 0?et: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?tt.map(t=>({...t})):e.rules}}function Ms(){let e=new Set(["1.1"]);for(let t of Ut)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}function $s(e,t="ark.config.json"){if(!Gn(e))throw new ne(t,[{path:"$",message:`must be an object; received ${Se(e)}`}]);let n=Ms(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new ne(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.1`}]);if(r!=="unversioned"&&!n.has(r))throw new ne(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected 1.1`}]);let s=r,i={...e},o=0;for(;s!=="1.1"&&o<Ut.length+1;){o+=1;let d=Ut.find(u=>u.from===s);if(!d)throw new ne(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(s)}; expected 1.1`}]);s=d.to,i.schemaVersion=s}if(s!=="1.1")throw new ne(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected 1.1`}]);let a=r==="unversioned"?"unversioned":r==="1.0"?"1.0":null;return{candidate:ws(i),migratedFrom:a}}function nt(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=$s(e,t),s=[];if(De(n,Gt,"$",Gt,s),s.length>0)throw new ne(t,s);return{config:n,migratedFrom:r}}function Bt(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new ne(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return nt(n,t)}function Bn(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:et,schemaVersion:"1.1"};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}function Fs(e){return e.endsWith(".")?e:`${e}.`}function Ds(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 st(e){let t=e.layers.map(s=>({...s,prefixes:s.prefixes.map(Fs)})),n=[...t].sort(Ds),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(o=>s.startsWith(o)))?.name}}}function Kn(e,t={}){return st({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 Hs=[{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}],rt=st({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:Hs,rules:tt.map(e=>({...e}))}),Vs={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 zn(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return Bn({include:e.include??[t],layers:rt.layers.map(s=>({name:s.name,patterns:(Vs[s.name]??[s.name]).map(i=>`${r}${i}/**`),intentPrefixes:s.prefixes,optional:n})),rules:[...rt.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 T(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(T).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${T(t[n])}`).join(",")}}`}var de="1.1";var qn=["network","filesystem","clock","randomness","environment","process","persistence"];function re(e,t){let n=T(e),r=T(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 He(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(re),safety:{maxTsSuppressions:e.safety?.maxTsSuppressions??0,maxAnyCasts:e.safety?.maxAnyCasts??0,allowInMemory:e.safety?.allowInMemory===!0,allowDisabledPeerIsolation:e.safety?.allowDisabledPeerIsolation===!0}};return M(T(t))}function js(e){let t=e.completenessReasons.map(c=>({code:c.code,message:c.message,...c.file?{file:c.file}:{}})).sort(re),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(re),s=e.capabilityUses.map(c=>({...c})).sort(re),i=e.ambientUses.map(c=>({...c})).sort(re),o=e.publishCalls.map(c=>({...c})).sort(re),a=e.intentReferences.map(c=>({...c})).sort(re),d=e.safetyUses.map(c=>({...c})).sort(re),u=(e.classShapes??[]).map(c=>({...c,mutatingMethods:[...c.mutatingMethods??[]].map(l=>({...l}))})).sort(re),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(T(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:o,intentReferences:a,safetyUses:d,classShapes:u}}function Wn(e){let t=js(e);return{...t,factsHash:M(T(t))}}function Kt(e){return Wn(Zn(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 Re(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 a of s.split("/"))if(!(!a||a==="."))if(a===".."){if(i.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);i.pop()}else i.push(a);let o=i.join("/");if(!o||o!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return o}function $(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}function Jn(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 Ee(e,t,n){let r=Jn(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 ie(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 Yn(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 Us(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 Zn(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=ie(e,"schemaVersion",["1.0","1.1"],"$"),r=ie(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:ie(h,"parseStatus",["parsed","invalid"],f),parseDiagnosticCount:Jn(h,"parseDiagnosticCount",f),exportsOnlyTypes:$(h,"exportsOnlyTypes",f),typeOnlyExportNames:Yn(h.typeOnlyExportNames,`${f}.typeOnlyExportNames`),hasTopLevelSideEffects:$(h,"hasTopLevelSideEffects",f)}}),o=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=Re(h,"specifier",f),k=Re(h,"target",f),N=ie(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:ie(h,"kind",["import","export","dynamic-import","require"],f),typeOnly:$(h,"typeOnly",f),line:Ee(h,"line",f),resolution:N,...k?{target:W(h,"target",f)}:{},...h.namedBindings!==void 0?{namedBindings:Yn(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)}:{}}}),a=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:Ee(h,"line",f),symbol:F(h,"symbol",f),capability:ie(h,"capability",qn,f),source:ie(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:Ee(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=Re(h,"rawIntentName",f),k=Re(h,"sourceIntent",f);return{file:W(h,"file",f),line:Ee(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:Ee(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=Re(h,"symbol",f),k=ie(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:Ee(h,"line",f),kind:k,...S?{symbol:S}:{}}});Us(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 o)if(!c.has(I.from))throw new Error(`$.dependencies references missing source file ${I.from}.`);for(let[I,R]of[["$.capabilityUses",a],["$.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=Re(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:o,capabilityUses:a,ambientUses:d,publishCalls:u,intentReferences:g,safetyUses:m,classShapes:y}}function oe(e){let t=K(e,"$"),n=F(t,"factsHash","$"),r=F(t,"candidateTreeHash","$"),s=Wn(Zn(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 Gs=["network","filesystem","clock","randomness","environment","process","persistence"],x={type:"string",minLength:1},ve={type:"integer",minimum:1},X={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},zt={$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:x,message:x,file:X}}},resolverIdentity:x,compilerIdentity:x,compilerOptionsHash:x,tsconfigHash:x,candidateTreeHash:x,evidenceRequirementsHash:x,projectPackageName:x,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:X,contentHash:x,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:x},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:x,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:ve,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:X,namedBindings:{type:"array",items:x},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:ve,symbol:x,capability:{enum:Gs},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:X,line:ve,symbol:x}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:X,line:ve,rawIntentName:x,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:x}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:X,line:ve,intent:x}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:X,line:ve,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:x},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:x,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:x,referencesGuardOrPublish:{type:"boolean"}}}}}}},factsHash:x},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 qt="1.0";function U(e){return`${e.from}->${e.to}`}function Ve(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 Ce(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])),o=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 a=new Set;for(let c of[...s.values()].sort((l,p)=>U(l).localeCompare(U(p)))){if(o.has(U(c))){t.push(Ve("satisfied",c,`${c.from} -> ${c.to} exists in the candidate architecture.`));continue}let l={from:c.to,to:c.from};o.has(U(l))?(a.add(U(l)),t.push(Ve("contradictory",c,`${c.from} -> ${c.to} was planned, but the candidate contains the reverse edge.`))):t.push(Ve("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[...o].sort(([p],[y])=>p.localeCompare(y)))i.has(c)||s.has(c)||a.has(c)||!d.has(l.from)&&!d.has(l.to)||t.push({...Ve("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)))o.has(c)||u.has(l.from)||u.has(l.to)||!d.has(l.from)&&!d.has(l.to)||t.push({...Ve("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 Bs="1.0",Yt="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",er=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","no-anemic-model","invariant-coverage"],Ks=["no-anemic-model"],Xn={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Wt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Yt,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:Yt},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:[...er]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:Xn,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:Xn}}}},pe=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkRules (${t}):
|
package/docs/README.md
CHANGED
|
@@ -58,10 +58,10 @@ These are **not** the day-to-day product path. They stay in the repo for evidenc
|
|
|
58
58
|
| Field adoption kit (scaffolding, not closed) | [field/](field/) |
|
|
59
59
|
| Runtime hardening (experimental) | [production-hardening.md](production-hardening.md) |
|
|
60
60
|
|
|
61
|
-
Current published: [releases/4.6.
|
|
62
|
-
Prepared: [releases/4.6.
|
|
63
|
-
Prior: [releases/4.6.
|
|
64
|
-
Previous: [releases/4.6.0.md](releases/4.6.0.md) · [releases/4.5.7.md](releases/4.5.7.md) · [releases/4.5.6.md](releases/4.5.6.md) · [releases/4.5.5.md](releases/4.5.5.md) · [releases/4.5.0.md](releases/4.5.0.md) · [releases/4.4.0.md](releases/4.4.0.md) · [releases/4.3.0.md](releases/4.3.0.md) · [releases/4.2.1.md](releases/4.2.1.md) · [releases/4.2.0.md](releases/4.2.0.md) · [releases/4.1.1.md](releases/4.1.1.md).
|
|
61
|
+
Current published: [releases/4.6.3.md](releases/4.6.3.md) (`arkgate@4.6.3` on npm `latest`).
|
|
62
|
+
Prepared: [releases/4.6.4.md](releases/4.6.4.md) (Codex upgrade activation guidance; not yet published).
|
|
63
|
+
Prior: [releases/4.6.2.md](releases/4.6.2.md) (`arkgate@4.6.2`).
|
|
64
|
+
Previous: [releases/4.6.1.md](releases/4.6.1.md) · [releases/4.6.0.md](releases/4.6.0.md) · [releases/4.5.7.md](releases/4.5.7.md) · [releases/4.5.6.md](releases/4.5.6.md) · [releases/4.5.5.md](releases/4.5.5.md) · [releases/4.5.0.md](releases/4.5.0.md) · [releases/4.4.0.md](releases/4.4.0.md) · [releases/4.3.0.md](releases/4.3.0.md) · [releases/4.2.1.md](releases/4.2.1.md) · [releases/4.2.0.md](releases/4.2.0.md) · [releases/4.1.1.md](releases/4.1.1.md).
|
|
65
65
|
Previous major: [releases/4.0.0.md](releases/4.0.0.md) (`arkgate@4.0.0`).
|
|
66
66
|
Config: [configuration.md](configuration.md) · Agent skills dual-plane: [agent-guide.md](agent-guide.md).
|
|
67
67
|
|
package/docs/agent-guide.md
CHANGED
|
@@ -97,7 +97,8 @@ One human often has **N checkouts** and **N package pins**. Product rules:
|
|
|
97
97
|
| One checkout = one `project.expectedRoot` | Identity (WI01) fail-closes cross-project evidence when used correctly |
|
|
98
98
|
| After `npm install arkgate@…`, restart/retarget Ark MCP | Process `arkgateVersion` is startup-loaded; long-lived MCP can lag install |
|
|
99
99
|
| Read `processPackage` on every tool response | `processPackageMismatch` / `processStale` + `nextAction` when process ≠ project install |
|
|
100
|
-
|
|
|
100
|
+
| Stale MCP in 4.6.4+ | `ark_identity` stays diagnostic; project tools return `PROCESS_PACKAGE_STALE` and top-level `authoritative:false` until restart |
|
|
101
|
+
| Prefer project-local CLI until versions align | A modern stale global `ark upgrade` hands off automatically; pre-4.6.4 globals need one `npx arkgate upgrade` entry |
|
|
101
102
|
| Upgrade each package that pins arkgate | Monorepo “done” is not one package’s pin |
|
|
102
103
|
| Registry-aware `ark upgrade --apply` | Does not false-skip when CLI == pin but registry is ahead; skip JSON has `reasonCode` + `suggestedInstallCmd` |
|
|
103
104
|
| Skills: `skillDrift` + optional `--refresh-skills` | Customized skill bodies stay preserved unless you opt in; never silent overwrite of true edits |
|
package/docs/ai-gates.md
CHANGED
|
@@ -416,6 +416,11 @@ observe a later MCP conversation from files alone. The matched `ark_identity` re
|
|
|
416
416
|
runtime observation for that caller and live process; it does not mutate the setup JSON.
|
|
417
417
|
`.codex/config.toml` by itself never upgrades `runtimeObserved` or `active`.
|
|
418
418
|
|
|
419
|
+
After a package bump, a long-lived Ark MCP whose package version no longer matches the project is
|
|
420
|
+
non-authoritative. `ark_identity` reports `processPackage.processStale`; project tools return
|
|
421
|
+
`PROCESS_PACKAGE_STALE` until Codex/local Desktop restarts or retargets the server. A modern
|
|
422
|
+
outside-tree/global `ark upgrade` hands the original invocation to the project-local CLI.
|
|
423
|
+
|
|
419
424
|
Codex uses an operation-scoped hard local patch hook plus advisory MCP for discovery/validation
|
|
420
425
|
and `ark-check` as the all-path hard merge backstop. Register all three as soon as the repo is
|
|
421
426
|
adopted.
|
package/docs/develop.md
CHANGED
|
@@ -75,6 +75,7 @@ can show `runtimeObserved: true` even when branch-protection policy is plan-unav
|
|
|
75
75
|
| Session / project status snapshot | `ark status --json` · MCP `ark_status` · [session recipe](agent-guide.md#session-recipe-agent-turn) · schema `arkgate/schema/status-manifest` |
|
|
76
76
|
| Status compass honesty | `improvementCompass.mode`: `full` \| `subset` \| `unavailable` · residual ⊆ doctor when `full` · [package-surface](package-surface.md) |
|
|
77
77
|
| Managed upgrade self-service | `ark upgrade --json` → `selfService` (activation labels + customized preserve) · [package-surface](package-surface.md) |
|
|
78
|
+
| Stale MCP/global CLI recovery | `processPackage.processStale` → non-authoritative + `PROCESS_PACKAGE_STALE`; modern outside-tree `ark upgrade` hands off to project-local CLI |
|
|
78
79
|
| Version-matched AGENTS projection | `ark agents-md` · [agent-guide](agent-guide.md) · **non-authoritative** (never enforces) |
|
|
79
80
|
| Stable finding refs (`findingRef` / `targetKey`) | analysis-result schema **1.5** · [agent-guide](agent-guide.md) · [package-surface](package-surface.md) |
|
|
80
81
|
| Agent Skills layout (same 13 names) | `templates/agent-skills/` · [agent-guide](agent-guide.md#install-skills-ark-and-ecosystem) · `npx skills add …` |
|
package/docs/package-surface.md
CHANGED
|
@@ -21,9 +21,9 @@ hardening guide remains repository-hosted rather than duplicated in the gate tar
|
|
|
21
21
|
| **Programmatic gate API** | `import { analyzeProject, loadContract, createAICodeGate, ... } from 'arkgate'` | The root export is the static gate/config/analysis contract listed below. It intentionally contains no runtime-kernel implementation. |
|
|
22
22
|
| **Improvement compass (4.4; status honesty 4.5)** | `ark-check --doctor --json` → `doctor.improvementCompass`; human doctor section **Improvement compass (not a score)**; HTML report `data-advisory="improvementCompass"`. **`ark status --json` / MCP `ark_status`** project a thin `improvementCompass` residual map with explicit honesty **`mode`**: `full` \| `subset` \| `unavailable` (always `notAScore: true`). When `mode` is `full`, status residual lens **ids** are a **subset of** doctor residual for the same facts (report snapshot stores the thin slice after `--report`). Incomplete or missing session facts → `subset` / `unavailable` + `reasonCode` / `reason` — **never invent green residual**. Residual never flips `valid` / strict-merge / `goal.met`. When status mode ≠ full, run doctor for full 15-lens detail. | Additive schema `1.0`. Closed **15** lens ids (`soc`, `cohesion`, `coupling`, `srp`, `dip`, `ocp`, `encapsulation`, `modularity`, `scalability`, `resilience`, `security`, `maintainability`, `testability`, `domain`, `stack`) with status `ok` \| `residual` \| `not-instrumented` \| `out-of-scope`, evidence refs, optional `nextAction`, capped `topResidual`, always **`notAScore: true`**. Projection from existing smells / walls / cohesion / ArkRules / design-weak only — **never** a gate input. Out-of-scope locked for scalability, resilience, and app security (no residual invent from missing SAST/APM). Root API: `buildImprovementCompass` / `IMPROVEMENT_LENS_IDS`; status: `projectStatusImprovementCompass` / `STATUS_COMPASS_MODES`. |
|
|
23
23
|
| **Deep-module coach (post-4.5 advisory)** | `ark-check --doctor --json` → `doctor.deepModuleCoach`; human doctor section **Deep-module coach (advisory — not a score)** always when doctor runs (empty candidates / hot-path `unavailable` are honesty, not omission); HTML `data-advisory="deepModuleCoach"`. | Additive schema `1.0`. Always **`notAScore: true`**. **`hotPaths`**: recent-churn heuristic from bounded git log; `available` + `status` `ok` \| `unavailable`; empty `paths` when history missing/incomplete — **never invent**. **`deepeningCandidates`**: cards projected only from existing design smells / physical cohesion / reshape pilot / pilotLoop / residual compass lenses — **empty when no evidence** (no fake candidates). Never flips `valid`, strict-merge, completeness green, or `goal.met`. Prefer deep modules / named seams / test-at-public-interface process language in skills. Domain pure + CLI gen mirror (`deepeningCoach.ts` / `bin/lib/deepening-coach.mjs`); **not** a root package export — consume via `doctor.deepModuleCoach` (or the gen mirror in Tooling). |
|
|
24
|
-
| **Upgrade what’s new (4.5.6+)** | `ark upgrade --json` → `whatsNew` (+ human **Suggested improvements** block; also on preview). | Always **`notAScore: true`**, **`neverGateInput: true`**. Closed try/inspect list: deep-module coach, improvement compass, session/status honesty, two-axis done, self-service honesty, registry-aware upgrade, skill drift/refresh, multi-project MCP. Never invents residual or flips gates. |
|
|
24
|
+
| **Upgrade what’s new (4.5.6+)** | `ark upgrade --json` → `whatsNew` (+ human **Suggested improvements** block; also on preview). | Always **`notAScore: true`**, **`neverGateInput: true`**. Closed try/inspect list: deep-module coach, improvement compass, session/status honesty, two-axis done, self-service honesty, registry-aware upgrade, skill drift/refresh, multi-project MCP, Codex hard-write refresh/trust/restart/verify, stale MCP/global CLI recovery. Never invents residual or flips gates. |
|
|
25
25
|
| **Field upgrade truth (4.5.6)** | `ark upgrade` registry-aware install; JSON `reasonCode` / `suggestedInstallCmd`; `skillDrift`; `--refresh-skills`; `postUpgradeChecks`; `hostSelection`. | No false-skip when registry ahead; offline honesty; customized skills preserved unless opt-in refresh; checks are advisory only. |
|
|
26
|
-
| **MCP process package honesty (4.5.6)** | Every MCP tool context → `processPackage` (`processPackageMismatch` / `processStale`, versions, `nextAction`). | Multi-checkout users: restart MCP after pin bump;
|
|
26
|
+
| **MCP process package honesty (4.5.6; fail-closed in 4.6.4)** | Every MCP tool context → `processPackage` (`processPackageMismatch` / `processStale`, versions, `nextAction`). | Multi-checkout users: restart MCP after pin bump. From 4.6.4, stale process context is non-authoritative; `ark_identity` remains diagnostic and project tools return `PROCESS_PACKAGE_STALE` until restart/retarget. Prefer project-local CLI until identity matched and versions align. |
|
|
27
27
|
| **Doctor design fitness** | `ark-check --doctor --json` → `doctor.designFitness`, `doctor.designSmells[]` | Additive. Stable smell `id`s: `io-under-application`, `handler-in-persistence`, `god-module`, `domain-logic-in-ui`, `facade-sql-in-routes`, `mixed-pattern-cluster`, `soft-contract`. `handler-in-persistence` covers static ES imports/re-exports of framework HTTP surfaces (`next/server`), `defineRoute` calls, and existing handler bodies inside Persistence-role layers or specific persistence paths; `require()` and dynamic `import()` are outside this narrow advisory, and a generic `Infrastructure` role alone is not Persistence. Persistence candidates are filtered and sorted before the bounded content scan so large application prefixes cannot hide the advisory. The detector inspects the first 800 sorted Persistence candidates; later candidates are uninspected, so **absence of a smell is not full-tree proof** above that envelope (incomplete/`partial` analysis also never proves “no smells”). **4.2 feedback hardening:** mode labels preserve the observed SUGGEST/ADAPT/ENFORCE state; a local permission/UI-state `canEdit` name alone is not a domain smell; real UI business rules route Domain → Application → UI; seed/fixture/demo/migration/generated files are not god-module pilots. Each smell has `evidence[]`, `fix`, technical `message`, and plain-language **`outcome`**. Does **not** fail the gate by itself. |
|
|
28
28
|
| **Post-green Shape door** | `doctor.postGreenPath`, `doctor.primaryNextAction`, `doctor.healthyFinishedForbidden` | Additive when `designFitness.designWeak`. Single Shape door (`id: clarify-for-ai`): explore shape-focus → dual-plan B → autopilot only with OK. Never empty plan A = healthy finished. |
|
|
29
29
|
| **Golden pattern (new code)** | Optional `.ark/golden-pattern.json`; doctor JSON `doctor.goldenPattern`; MCP `ark_place` / `ark_prepare_write` → `goldenPattern` | Additive, **advisory for NEW code only**. Required fields: `name`, `norm`; optional `newCodeHome`, `examplePath`, `schemaVersion`. **Absent is normal** (no claim). Never ENFORCE; never clears design-weak. Malformed → `invalid: true`, not silent guidance. |
|
|
@@ -211,9 +211,9 @@ production deployment would need to satisfy; it is not a readiness certification
|
|
|
211
211
|
## Release notes (maintainers)
|
|
212
212
|
|
|
213
213
|
Ship notes for a version live under [releases/](https://github.com/pedroknigge/arkgate/tree/main/docs/releases)
|
|
214
|
-
(prepared: [4.6.
|
|
215
|
-
current published: [4.6.
|
|
216
|
-
|
|
214
|
+
(prepared: [4.6.4.md](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/4.6.4.md);
|
|
215
|
+
current published: [4.6.3.md](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/4.6.3.md);
|
|
216
|
+
prior published: [4.6.2.md](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/4.6.2.md), [4.6.1.md](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/4.6.1.md), [4.6.0.md](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/4.6.0.md), [4.5.7.md](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/4.5.7.md), [4.5.6.md](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/4.5.6.md), [4.5.0.md](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/4.5.0.md), [4.4.0.md](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/4.4.0.md), [4.3.0.md](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/4.3.0.md),
|
|
217
217
|
[4.2.1.md](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/4.2.1.md);
|
|
218
218
|
previous: [4.2.0.md](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/4.2.0.md),
|
|
219
219
|
[4.1.1.md](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/4.1.1.md),
|
package/docs/threat-model.md
CHANGED
|
@@ -32,7 +32,7 @@ infrastructure beyond how this package is published.
|
|
|
32
32
|
| T3 | CI job missing / not required | Merge green without architecture | doctor `enforcement-ci-*` gaps; `--strict-merge`; required-status remains locally `unverified` |
|
|
33
33
|
| T4 | Config weakened (`peerIsolation: false`, empty rules) | False green | semantic policy-delta guard in strict merge; hash-bound explicit acknowledgement; present-state safety diagnostics |
|
|
34
34
|
| T5 | Baseline ratcheted open | Debt reintroduced | baseline unused/stale signals; occurrence keys |
|
|
35
|
-
| T6 |
|
|
35
|
+
| T6 | Stale MCP/global CLI or wrong root | Gate points at old package / wrong tree | project identity binding; stale process non-authoritative + `PROCESS_PACKAGE_STALE`; project-local upgrade handoff |
|
|
36
36
|
| T7 | Malicious dependency in publish | Compromised gate | signed tags, npm provenance, dependency-review, CodeQL, Semgrep, `verify-package-files` |
|
|
37
37
|
| T8 | Path traversal in hooks/check | Read/write outside project | root resolution + under-root import resolve |
|
|
38
38
|
| T9 | Runtime InMemory mistaken for durable | Data loss | durability stance docs + safety InMemory production detector |
|
package/package.json
CHANGED
package/server.json
CHANGED
|
@@ -6,12 +6,12 @@
|
|
|
6
6
|
"url": "https://github.com/pedroknigge/arkgate",
|
|
7
7
|
"source": "github"
|
|
8
8
|
},
|
|
9
|
-
"version": "4.6.
|
|
9
|
+
"version": "4.6.4",
|
|
10
10
|
"packages": [
|
|
11
11
|
{
|
|
12
12
|
"registryType": "npm",
|
|
13
13
|
"identifier": "arkgate",
|
|
14
|
-
"version": "4.6.
|
|
14
|
+
"version": "4.6.4",
|
|
15
15
|
"runtimeHint": "npx",
|
|
16
16
|
"transport": {
|
|
17
17
|
"type": "stdio"
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
This directory is the **Agent Skills–compatible** packaging of the same **13**
|
|
8
8
|
`/ark-*` skills shipped as flat templates for Ark install. **No new skill names.**
|
|
9
9
|
|
|
10
|
-
Package version when last generated context: **arkgate@4.6.
|
|
10
|
+
Package version when last generated context: **arkgate@4.6.4**
|
|
11
11
|
Schema: agent-skills package contract `1.0`
|
|
12
12
|
|
|
13
13
|
## Skills (frozen catalog)
|
|
@@ -58,6 +58,15 @@ line (advisory only — not a score):
|
|
|
58
58
|
6. **Registry-aware upgrade** — `reasonCode` / `suggestedInstallCmd` when package install is skipped or needed
|
|
59
59
|
7. **Skill drift + refresh** — `skillDrift`; opt-in `--refresh-skills` for customized skill rewrite
|
|
60
60
|
8. **Multi-project MCP** — `processPackage` mismatch/stale on every MCP tool; restart after package bump
|
|
61
|
+
9. **Codex hard write refresh** — run
|
|
62
|
+
`npx arkgate-check --install-agent-gates --tools codex --force`, restart Codex/local Desktop,
|
|
63
|
+
review and trust the exact hook, then inspect `doctor.writePath` after a governed
|
|
64
|
+
`apply_patch`. Only a complete runtime-observed local patch is hard; every other path still
|
|
65
|
+
relies on required CI.
|
|
66
|
+
10. **Stale process recovery** — a stale Ark MCP is non-authoritative and project tools return
|
|
67
|
+
`PROCESS_PACKAGE_STALE` until restart/retarget. If a modern global `ark upgrade` is older than
|
|
68
|
+
the project install, it hands the same invocation to the project-local CLI instead of managing
|
|
69
|
+
the project from the stale PATH binary.
|
|
61
70
|
|
|
62
71
|
Never invent gate verdicts from these suggestions. Missing residual is honest empty, not green.
|
|
63
72
|
|
|
@@ -95,8 +104,10 @@ restart/retargeting is required. `ark://manifest` never satisfies this preflight
|
|
|
95
104
|
|
|
96
105
|
**Process package honesty:** every tool response includes `processPackage` (`processArkgateVersion`,
|
|
97
106
|
`projectInstalledVersion`, `processPackageMismatch` / `processStale`, `nextAction`). After
|
|
98
|
-
`npm install arkgate@…`, **restart/retarget MCP** so process version matches install.
|
|
99
|
-
|
|
107
|
+
`npm install arkgate@…`, **restart/retarget MCP** so process version matches install. From 4.6.4,
|
|
108
|
+
a stale MCP is non-authoritative: `ark_identity` diagnoses it and project tools return
|
|
109
|
+
`PROCESS_PACKAGE_STALE` until restart. Prefer project-local CLI meanwhile. A modern stale global
|
|
110
|
+
`ark upgrade` hands off automatically; pre-4.6.4 globals need one `npx arkgate upgrade` entry.
|
|
100
111
|
|
|
101
112
|
## Dual plane — layers + ArkRules (mandatory, except /ark-runtime)
|
|
102
113
|
|
|
@@ -58,6 +58,15 @@ line (advisory only — not a score):
|
|
|
58
58
|
6. **Registry-aware upgrade** — `reasonCode` / `suggestedInstallCmd` when package install is skipped or needed
|
|
59
59
|
7. **Skill drift + refresh** — `skillDrift`; opt-in `--refresh-skills` for customized skill rewrite
|
|
60
60
|
8. **Multi-project MCP** — `processPackage` mismatch/stale on every MCP tool; restart after package bump
|
|
61
|
+
9. **Codex hard write refresh** — run
|
|
62
|
+
`npx arkgate-check --install-agent-gates --tools codex --force`, restart Codex/local Desktop,
|
|
63
|
+
review and trust the exact hook, then inspect `doctor.writePath` after a governed
|
|
64
|
+
`apply_patch`. Only a complete runtime-observed local patch is hard; every other path still
|
|
65
|
+
relies on required CI.
|
|
66
|
+
10. **Stale process recovery** — a stale Ark MCP is non-authoritative and project tools return
|
|
67
|
+
`PROCESS_PACKAGE_STALE` until restart/retarget. If a modern global `ark upgrade` is older than
|
|
68
|
+
the project install, it hands the same invocation to the project-local CLI instead of managing
|
|
69
|
+
the project from the stale PATH binary.
|
|
61
70
|
|
|
62
71
|
Never invent gate verdicts from these suggestions. Missing residual is honest empty, not green.
|
|
63
72
|
|
|
@@ -95,8 +104,10 @@ restart/retargeting is required. `ark://manifest` never satisfies this preflight
|
|
|
95
104
|
|
|
96
105
|
**Process package honesty:** every tool response includes `processPackage` (`processArkgateVersion`,
|
|
97
106
|
`projectInstalledVersion`, `processPackageMismatch` / `processStale`, `nextAction`). After
|
|
98
|
-
`npm install arkgate@…`, **restart/retarget MCP** so process version matches install.
|
|
99
|
-
|
|
107
|
+
`npm install arkgate@…`, **restart/retarget MCP** so process version matches install. From 4.6.4,
|
|
108
|
+
a stale MCP is non-authoritative: `ark_identity` diagnoses it and project tools return
|
|
109
|
+
`PROCESS_PACKAGE_STALE` until restart. Prefer project-local CLI meanwhile. A modern stale global
|
|
110
|
+
`ark upgrade` hands off automatically; pre-4.6.4 globals need one `npx arkgate upgrade` entry.
|
|
100
111
|
|
|
101
112
|
## Dual plane — layers + ArkRules (mandatory, except /ark-runtime)
|
|
102
113
|
|