arkgate 3.0.5 → 3.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +47 -1
- package/README.md +29 -9
- package/bin/ark-check.mjs +46 -4
- package/bin/ark-mcp.mjs +267 -26
- package/bin/ark.mjs +47 -0
- package/bin/lib/adapter-contract.mjs +27 -1
- package/bin/lib/analysis-engine.mjs +7 -1169
- package/bin/lib/ci-and-commands.mjs +4 -0
- package/bin/lib/doctor-plan.mjs +7 -4
- package/bin/lib/host-support-matrix.mjs +6 -2
- package/bin/lib/policy-delta-io.mjs +161 -0
- package/bin/lib/prepare-change.mjs +186 -0
- package/bin/lib/remediation.mjs +24 -0
- package/bin/lib/violations.mjs +2 -2
- package/bin/lib/write-path-capabilities.mjs +67 -1
- package/bin/lib/write-path-detect.mjs +4 -3
- package/dist/eslint/index.cjs +3 -977
- package/dist/eslint/index.js +3 -931
- package/dist/index.cjs +6 -1960
- package/dist/index.d.cts +152 -5
- package/dist/index.d.ts +152 -5
- package/dist/index.js +6 -1908
- package/docs/agent-guide.md +15 -1
- package/docs/ai-gates.md +8 -1
- package/docs/configuration.md +44 -0
- package/docs/package-surface.md +8 -1
- package/docs/threat-model.md +7 -4
- package/package.json +6 -5
- package/schemas/ark.analysis-result.schema.json +5 -1
- package/schemas/ark.change-map.schema.json +77 -0
- package/server.json +2 -2
- package/docs/ark-check-example.json +0 -87
- package/docs/demos/03-copilot-autopilot.md +0 -93
- package/docs/migrate-from-ark-runtime-kernel.md +0 -174
- package/docs/production-hardening.md +0 -100
|
@@ -1,1171 +1,9 @@
|
|
|
1
1
|
// GENERATED from src/kernel/analysis.ts by scripts/generate-analysis-engine.mjs.
|
|
2
2
|
// Do not edit this file directly.
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
function deterministicHash(value) {
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
}
|
|
11
|
-
return `fnv1a-${(hash >>> 0).toString(16).padStart(8, "0")}`;
|
|
12
|
-
}
|
|
13
|
-
function stableSerialize(value) {
|
|
14
|
-
if (value === null || typeof value !== "object") return JSON.stringify(value);
|
|
15
|
-
if (Array.isArray(value)) return `[${value.map(stableSerialize).join(",")}]`;
|
|
16
|
-
const object = value;
|
|
17
|
-
return `{${Object.keys(object).sort().map((key) => `${JSON.stringify(key)}:${stableSerialize(object[key])}`).join(",")}}`;
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
// src/domain/configContract.ts
|
|
21
|
-
var ARK_CONFIG_SCHEMA_VERSION = "1.0";
|
|
22
|
-
var ARK_CONFIG_SCHEMA_URL = "https://unpkg.com/arkgate@2/schemas/ark.config.schema.json";
|
|
23
|
-
var DEFAULT_LAYER_NAMES = [
|
|
24
|
-
"DomainModel",
|
|
25
|
-
"ApplicationOrchestration",
|
|
26
|
-
"PersistenceAdapters",
|
|
27
|
-
"IntegrationAdapters",
|
|
28
|
-
"WorkflowSagaEngine",
|
|
29
|
-
"BackgroundJobsScheduling",
|
|
30
|
-
"PresentationAdapters",
|
|
31
|
-
"ReportingReadModels",
|
|
32
|
-
"ExtensibilityMetadata",
|
|
33
|
-
"SecurityAuditObservability",
|
|
34
|
-
"Kernel"
|
|
35
|
-
];
|
|
36
|
-
var DEFAULT_ALLOWED_FLOWS = /* @__PURE__ */ new Set([
|
|
37
|
-
"PresentationAdapters->ApplicationOrchestration",
|
|
38
|
-
"ApplicationOrchestration->DomainModel",
|
|
39
|
-
"WorkflowSagaEngine->ApplicationOrchestration",
|
|
40
|
-
"WorkflowSagaEngine->DomainModel",
|
|
41
|
-
"BackgroundJobsScheduling->ApplicationOrchestration"
|
|
42
|
-
]);
|
|
43
|
-
function createDefaultRules() {
|
|
44
|
-
const rules = [];
|
|
45
|
-
for (const from of DEFAULT_LAYER_NAMES) {
|
|
46
|
-
for (const to of DEFAULT_LAYER_NAMES) {
|
|
47
|
-
if (from === to || DEFAULT_ALLOWED_FLOWS.has(`${from}->${to}`)) continue;
|
|
48
|
-
rules.push({ from, to, allowed: false });
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
return rules;
|
|
52
|
-
}
|
|
53
|
-
var DEFAULT_ARK_CONFIG_RULES = createDefaultRules();
|
|
54
|
-
var stringArraySchema = {
|
|
55
|
-
type: "array",
|
|
56
|
-
items: { type: "string", minLength: 1 },
|
|
57
|
-
uniqueItems: true
|
|
58
|
-
};
|
|
59
|
-
var ARK_CONFIG_SCHEMA = {
|
|
60
|
-
$schema: "https://json-schema.org/draft/2020-12/schema",
|
|
61
|
-
$id: ARK_CONFIG_SCHEMA_URL,
|
|
62
|
-
title: "ArkGate architecture contract",
|
|
63
|
-
description: "Versioned contract consumed identically by ArkGate CLI, MCP, and ESLint surfaces.",
|
|
64
|
-
type: "object",
|
|
65
|
-
additionalProperties: false,
|
|
66
|
-
required: ["$schema", "schemaVersion", "include", "layers", "rules"],
|
|
67
|
-
properties: {
|
|
68
|
-
$schema: {
|
|
69
|
-
type: "string",
|
|
70
|
-
minLength: 1,
|
|
71
|
-
default: ARK_CONFIG_SCHEMA_URL,
|
|
72
|
-
description: "Editor-facing URL or local path for this JSON Schema."
|
|
73
|
-
},
|
|
74
|
-
schemaVersion: {
|
|
75
|
-
type: "string",
|
|
76
|
-
const: ARK_CONFIG_SCHEMA_VERSION,
|
|
77
|
-
default: ARK_CONFIG_SCHEMA_VERSION
|
|
78
|
-
},
|
|
79
|
-
name: { type: "string", minLength: 1 },
|
|
80
|
-
include: { ...stringArraySchema, minItems: 1, default: ["src"] },
|
|
81
|
-
exclude: { ...stringArraySchema, default: [] },
|
|
82
|
-
excludeGenerated: { type: "boolean", default: true },
|
|
83
|
-
frameworkOverlay: { type: "string", minLength: 1 },
|
|
84
|
-
layers: {
|
|
85
|
-
type: "array",
|
|
86
|
-
default: [],
|
|
87
|
-
items: { $ref: "#/$defs/layer" }
|
|
88
|
-
},
|
|
89
|
-
rules: {
|
|
90
|
-
type: "array",
|
|
91
|
-
default: DEFAULT_ARK_CONFIG_RULES,
|
|
92
|
-
items: { $ref: "#/$defs/rule" }
|
|
93
|
-
},
|
|
94
|
-
cyclePolicy: {
|
|
95
|
-
type: "string",
|
|
96
|
-
enum: ["strict", "soft", "framework-soft", "off"],
|
|
97
|
-
default: "strict"
|
|
98
|
-
},
|
|
99
|
-
dynamicImportAllowlist: { ...stringArraySchema, default: [] },
|
|
100
|
-
safety: {
|
|
101
|
-
$ref: "#/$defs/safety",
|
|
102
|
-
default: {
|
|
103
|
-
maxTsSuppressions: 0,
|
|
104
|
-
maxAnyCasts: 0,
|
|
105
|
-
allowInMemory: false,
|
|
106
|
-
allowDisabledPeerIsolation: false
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
},
|
|
110
|
-
$defs: {
|
|
111
|
-
layer: {
|
|
112
|
-
type: "object",
|
|
113
|
-
additionalProperties: false,
|
|
114
|
-
required: ["name", "patterns"],
|
|
115
|
-
properties: {
|
|
116
|
-
name: { type: "string", minLength: 1 },
|
|
117
|
-
patterns: { ...stringArraySchema, minItems: 1 },
|
|
118
|
-
exclude: stringArraySchema,
|
|
119
|
-
intentPrefixes: stringArraySchema,
|
|
120
|
-
description: { type: "string", minLength: 1 },
|
|
121
|
-
forbiddenGlobals: stringArraySchema,
|
|
122
|
-
mayImportInfrastructure: { type: "boolean" },
|
|
123
|
-
optional: { type: "boolean" }
|
|
124
|
-
}
|
|
125
|
-
},
|
|
126
|
-
rule: {
|
|
127
|
-
type: "object",
|
|
128
|
-
additionalProperties: false,
|
|
129
|
-
required: ["from", "to", "allowed"],
|
|
130
|
-
properties: {
|
|
131
|
-
from: { type: "string", minLength: 1 },
|
|
132
|
-
to: { type: "string", minLength: 1 },
|
|
133
|
-
allowed: { type: "boolean" },
|
|
134
|
-
message: { type: "string", minLength: 1 },
|
|
135
|
-
peerIsolation: { type: "boolean" },
|
|
136
|
-
sliceFolders: { ...stringArraySchema, minItems: 1 }
|
|
137
|
-
}
|
|
138
|
-
},
|
|
139
|
-
safety: {
|
|
140
|
-
type: "object",
|
|
141
|
-
additionalProperties: false,
|
|
142
|
-
properties: {
|
|
143
|
-
maxTsSuppressions: { type: "integer", minimum: 0, default: 0 },
|
|
144
|
-
maxAnyCasts: { type: "integer", minimum: 0, default: 0 },
|
|
145
|
-
allowInMemory: { type: "boolean", default: false },
|
|
146
|
-
allowDisabledPeerIsolation: { type: "boolean", default: false }
|
|
147
|
-
}
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
};
|
|
151
|
-
var ArkConfigValidationError = class extends Error {
|
|
152
|
-
issues;
|
|
153
|
-
source;
|
|
154
|
-
constructor(source, issues) {
|
|
155
|
-
super(
|
|
156
|
-
`Invalid ArkGate config (${source}):
|
|
157
|
-
${issues.map((issue) => `- ${issue.path}: ${issue.message}`).join("\n")}`
|
|
158
|
-
);
|
|
159
|
-
this.name = "ArkConfigValidationError";
|
|
160
|
-
this.source = source;
|
|
161
|
-
this.issues = issues;
|
|
162
|
-
}
|
|
163
|
-
};
|
|
164
|
-
function isObject(value) {
|
|
165
|
-
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
166
|
-
}
|
|
167
|
-
function propertyPath(parent, key) {
|
|
168
|
-
return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? `${parent}.${key}` : `${parent}[${JSON.stringify(key)}]`;
|
|
169
|
-
}
|
|
170
|
-
function valueType(value) {
|
|
171
|
-
if (value === null) return "null";
|
|
172
|
-
if (Array.isArray(value)) return "array";
|
|
173
|
-
return typeof value;
|
|
174
|
-
}
|
|
175
|
-
function resolveSchemaRef(ref, root) {
|
|
176
|
-
const prefix = "#/$defs/";
|
|
177
|
-
if (!ref.startsWith(prefix)) return void 0;
|
|
178
|
-
return root.$defs[ref.slice(prefix.length)];
|
|
179
|
-
}
|
|
180
|
-
function validateNode(value, schema, path, root, issues) {
|
|
181
|
-
if (schema.$ref) {
|
|
182
|
-
const referenced = resolveSchemaRef(schema.$ref, root);
|
|
183
|
-
if (!referenced) {
|
|
184
|
-
issues.push({ path, message: `schema reference ${schema.$ref} cannot be resolved` });
|
|
185
|
-
return;
|
|
186
|
-
}
|
|
187
|
-
validateNode(value, referenced, path, root, issues);
|
|
188
|
-
return;
|
|
189
|
-
}
|
|
190
|
-
if (schema.const !== void 0 && !Object.is(value, schema.const)) {
|
|
191
|
-
issues.push({ path, message: `must equal ${JSON.stringify(schema.const)}` });
|
|
192
|
-
return;
|
|
193
|
-
}
|
|
194
|
-
if (schema.enum && !schema.enum.some((candidate) => Object.is(candidate, value))) {
|
|
195
|
-
issues.push({ path, message: `must be one of ${schema.enum.map(String).join(", ")}` });
|
|
196
|
-
return;
|
|
197
|
-
}
|
|
198
|
-
if (schema.type === "object") {
|
|
199
|
-
if (!isObject(value)) {
|
|
200
|
-
issues.push({ path, message: `must be an object; received ${valueType(value)}` });
|
|
201
|
-
return;
|
|
202
|
-
}
|
|
203
|
-
const properties = schema.properties ?? {};
|
|
204
|
-
for (const key of schema.required ?? []) {
|
|
205
|
-
if (value[key] === void 0) {
|
|
206
|
-
issues.push({ path: propertyPath(path, key), message: "is required" });
|
|
207
|
-
}
|
|
208
|
-
}
|
|
209
|
-
if (schema.additionalProperties === false) {
|
|
210
|
-
for (const key of Object.keys(value)) {
|
|
211
|
-
if (!(key in properties)) {
|
|
212
|
-
issues.push({ path: propertyPath(path, key), message: "unknown field" });
|
|
213
|
-
}
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
for (const [key, childSchema] of Object.entries(properties)) {
|
|
217
|
-
if (value[key] !== void 0) {
|
|
218
|
-
validateNode(value[key], childSchema, propertyPath(path, key), root, issues);
|
|
219
|
-
}
|
|
220
|
-
}
|
|
221
|
-
return;
|
|
222
|
-
}
|
|
223
|
-
if (schema.type === "array") {
|
|
224
|
-
if (!Array.isArray(value)) {
|
|
225
|
-
issues.push({ path, message: `must be an array; received ${valueType(value)}` });
|
|
226
|
-
return;
|
|
227
|
-
}
|
|
228
|
-
if (schema.minItems !== void 0 && value.length < schema.minItems) {
|
|
229
|
-
issues.push({ path, message: `must contain at least ${schema.minItems} item(s)` });
|
|
230
|
-
}
|
|
231
|
-
if (schema.uniqueItems) {
|
|
232
|
-
const serialized = value.map((entry) => JSON.stringify(entry));
|
|
233
|
-
if (new Set(serialized).size !== serialized.length) {
|
|
234
|
-
issues.push({ path, message: "must not contain duplicate items" });
|
|
235
|
-
}
|
|
236
|
-
}
|
|
237
|
-
if (schema.items) {
|
|
238
|
-
value.forEach(
|
|
239
|
-
(entry, index) => validateNode(entry, schema.items, `${path}[${index}]`, root, issues)
|
|
240
|
-
);
|
|
241
|
-
}
|
|
242
|
-
return;
|
|
243
|
-
}
|
|
244
|
-
if (schema.type === "string") {
|
|
245
|
-
if (typeof value !== "string") {
|
|
246
|
-
issues.push({ path, message: `must be a string; received ${valueType(value)}` });
|
|
247
|
-
return;
|
|
248
|
-
}
|
|
249
|
-
if (schema.minLength !== void 0 && value.length < schema.minLength) {
|
|
250
|
-
issues.push({ path, message: `must contain at least ${schema.minLength} character(s)` });
|
|
251
|
-
}
|
|
252
|
-
return;
|
|
253
|
-
}
|
|
254
|
-
if (schema.type === "boolean") {
|
|
255
|
-
if (typeof value !== "boolean") {
|
|
256
|
-
issues.push({ path, message: `must be a boolean; received ${valueType(value)}` });
|
|
257
|
-
}
|
|
258
|
-
return;
|
|
259
|
-
}
|
|
260
|
-
if (schema.type === "integer") {
|
|
261
|
-
if (!Number.isInteger(value)) {
|
|
262
|
-
issues.push({ path, message: `must be an integer; received ${valueType(value)}` });
|
|
263
|
-
return;
|
|
264
|
-
}
|
|
265
|
-
if (schema.minimum !== void 0 && value < schema.minimum) {
|
|
266
|
-
issues.push({ path, message: `must be at least ${schema.minimum}` });
|
|
267
|
-
}
|
|
268
|
-
}
|
|
269
|
-
}
|
|
270
|
-
function defaultedConfig(input) {
|
|
271
|
-
return {
|
|
272
|
-
...input,
|
|
273
|
-
$schema: input.$schema === void 0 ? ARK_CONFIG_SCHEMA_URL : input.$schema,
|
|
274
|
-
schemaVersion: input.schemaVersion === void 0 ? ARK_CONFIG_SCHEMA_VERSION : input.schemaVersion,
|
|
275
|
-
include: input.include === void 0 ? ["src"] : input.include,
|
|
276
|
-
layers: input.layers === void 0 ? [] : input.layers,
|
|
277
|
-
rules: input.rules === void 0 ? DEFAULT_ARK_CONFIG_RULES.map((rule) => ({ ...rule })) : input.rules
|
|
278
|
-
};
|
|
279
|
-
}
|
|
280
|
-
function migrateArkConfig(input, source = "ark.config.json") {
|
|
281
|
-
if (!isObject(input)) {
|
|
282
|
-
throw new ArkConfigValidationError(source, [
|
|
283
|
-
{ path: "$", message: `must be an object; received ${valueType(input)}` }
|
|
284
|
-
]);
|
|
285
|
-
}
|
|
286
|
-
const migratedFrom = input.schemaVersion === void 0 ? "unversioned" : null;
|
|
287
|
-
if (input.schemaVersion !== void 0 && input.schemaVersion !== ARK_CONFIG_SCHEMA_VERSION) {
|
|
288
|
-
throw new ArkConfigValidationError(source, [
|
|
289
|
-
{
|
|
290
|
-
path: "$.schemaVersion",
|
|
291
|
-
message: `unsupported version ${JSON.stringify(input.schemaVersion)}; expected ${ARK_CONFIG_SCHEMA_VERSION}`
|
|
292
|
-
}
|
|
293
|
-
]);
|
|
294
|
-
}
|
|
295
|
-
return { candidate: defaultedConfig(input), migratedFrom };
|
|
296
|
-
}
|
|
297
|
-
function loadArkConfigContract(input, source = "ark.config.json") {
|
|
298
|
-
const { candidate, migratedFrom } = migrateArkConfig(input, source);
|
|
299
|
-
const issues = [];
|
|
300
|
-
validateNode(
|
|
301
|
-
candidate,
|
|
302
|
-
ARK_CONFIG_SCHEMA,
|
|
303
|
-
"$",
|
|
304
|
-
ARK_CONFIG_SCHEMA,
|
|
305
|
-
issues
|
|
306
|
-
);
|
|
307
|
-
if (issues.length > 0) throw new ArkConfigValidationError(source, issues);
|
|
308
|
-
return { config: candidate, migratedFrom };
|
|
309
|
-
}
|
|
310
|
-
function parseArkConfigJson(json, source = "ark.config.json") {
|
|
311
|
-
let input;
|
|
312
|
-
try {
|
|
313
|
-
input = JSON.parse(json);
|
|
314
|
-
} catch (error) {
|
|
315
|
-
throw new ArkConfigValidationError(source, [
|
|
316
|
-
{
|
|
317
|
-
path: "$",
|
|
318
|
-
message: `invalid JSON: ${error instanceof Error ? error.message : String(error)}`
|
|
319
|
-
}
|
|
320
|
-
]);
|
|
321
|
-
}
|
|
322
|
-
return loadArkConfigContract(input, source);
|
|
323
|
-
}
|
|
324
|
-
|
|
325
|
-
// src/domain/layerMatch.ts
|
|
326
|
-
var regexpCache = /* @__PURE__ */ new Map();
|
|
327
|
-
function escapeLiteral(ch) {
|
|
328
|
-
return /[.*+?^${}()|[\]\\]/.test(ch) ? `\\${ch}` : ch;
|
|
329
|
-
}
|
|
330
|
-
function normalizeGlobSeparators(pattern) {
|
|
331
|
-
let out = "";
|
|
332
|
-
for (let i = 0; i < pattern.length; i += 1) {
|
|
333
|
-
const c = pattern[i];
|
|
334
|
-
if (c === "\\" && i + 1 < pattern.length) {
|
|
335
|
-
const next = pattern[i + 1];
|
|
336
|
-
if ("*?{}[],".includes(next) || next === "\\") {
|
|
337
|
-
out += "\\" + next;
|
|
338
|
-
i += 1;
|
|
339
|
-
continue;
|
|
340
|
-
}
|
|
341
|
-
out += "/";
|
|
342
|
-
continue;
|
|
343
|
-
}
|
|
344
|
-
out += c;
|
|
345
|
-
}
|
|
346
|
-
return out;
|
|
347
|
-
}
|
|
348
|
-
function bracesBalanced(glob) {
|
|
349
|
-
let depth = 0;
|
|
350
|
-
for (let i = 0; i < glob.length; i += 1) {
|
|
351
|
-
const c = glob[i];
|
|
352
|
-
if (c === "\\") {
|
|
353
|
-
i += 1;
|
|
354
|
-
continue;
|
|
355
|
-
}
|
|
356
|
-
if (c === "{") depth += 1;
|
|
357
|
-
else if (c === "}") {
|
|
358
|
-
depth -= 1;
|
|
359
|
-
if (depth < 0) return false;
|
|
360
|
-
}
|
|
361
|
-
}
|
|
362
|
-
return depth === 0;
|
|
363
|
-
}
|
|
364
|
-
function globToRegExp(pattern) {
|
|
365
|
-
const cached = regexpCache.get(pattern);
|
|
366
|
-
if (cached) return cached;
|
|
367
|
-
const glob = normalizeGlobSeparators(pattern);
|
|
368
|
-
const useBraces = bracesBalanced(glob);
|
|
369
|
-
let out = "";
|
|
370
|
-
let braceDepth = 0;
|
|
371
|
-
for (let i = 0; i < glob.length; i += 1) {
|
|
372
|
-
const c = glob[i];
|
|
373
|
-
if (c === "\\" && i + 1 < glob.length) {
|
|
374
|
-
out += escapeLiteral(glob[i + 1]);
|
|
375
|
-
i += 1;
|
|
376
|
-
} else if (c === "*") {
|
|
377
|
-
if (glob[i + 1] === "*") {
|
|
378
|
-
if (glob[i + 2] === "/") {
|
|
379
|
-
out += "(?:.*/)?";
|
|
380
|
-
i += 2;
|
|
381
|
-
} else {
|
|
382
|
-
out += ".*";
|
|
383
|
-
i += 1;
|
|
384
|
-
}
|
|
385
|
-
} else {
|
|
386
|
-
out += "[^/]*";
|
|
387
|
-
}
|
|
388
|
-
} else if (c === "?") {
|
|
389
|
-
out += "[^/]";
|
|
390
|
-
} else if (c === "{" && useBraces) {
|
|
391
|
-
out += "(?:";
|
|
392
|
-
braceDepth += 1;
|
|
393
|
-
} else if (c === "}" && useBraces && braceDepth > 0) {
|
|
394
|
-
out += ")";
|
|
395
|
-
braceDepth -= 1;
|
|
396
|
-
} else if (c === "," && useBraces && braceDepth > 0) {
|
|
397
|
-
out += "|";
|
|
398
|
-
} else {
|
|
399
|
-
out += escapeLiteral(c);
|
|
400
|
-
}
|
|
401
|
-
}
|
|
402
|
-
const re = new RegExp(`^${out}$`);
|
|
403
|
-
regexpCache.set(pattern, re);
|
|
404
|
-
return re;
|
|
405
|
-
}
|
|
406
|
-
function patternSpecificity(pattern) {
|
|
407
|
-
const glob = normalizeGlobSeparators(String(pattern));
|
|
408
|
-
const beforeWildcard = glob.split("*")[0];
|
|
409
|
-
const literalSegments = beforeWildcard.split("/").filter(Boolean).length;
|
|
410
|
-
const literalLength = glob.replace(/\*/g, "").length;
|
|
411
|
-
return literalSegments * 1e4 + literalLength;
|
|
412
|
-
}
|
|
413
|
-
function layerForRelativePath(relPath, layers) {
|
|
414
|
-
const rel = String(relPath).split(/[/\\]/).join("/");
|
|
415
|
-
let bestName;
|
|
416
|
-
let bestScore = -1;
|
|
417
|
-
for (const layer of layers ?? []) {
|
|
418
|
-
if ((layer.exclude ?? []).some((pattern) => globToRegExp(pattern).test(rel))) {
|
|
419
|
-
continue;
|
|
420
|
-
}
|
|
421
|
-
for (const pattern of layer.patterns ?? []) {
|
|
422
|
-
if (globToRegExp(pattern).test(rel)) {
|
|
423
|
-
const score = patternSpecificity(pattern);
|
|
424
|
-
if (score > bestScore) {
|
|
425
|
-
bestScore = score;
|
|
426
|
-
bestName = layer.name;
|
|
427
|
-
}
|
|
428
|
-
}
|
|
429
|
-
}
|
|
430
|
-
}
|
|
431
|
-
return bestName;
|
|
432
|
-
}
|
|
433
|
-
function sliceIdForPath(relPath, sliceFolders) {
|
|
434
|
-
if (!sliceFolders?.length) return void 0;
|
|
435
|
-
const parts = String(relPath).split(/[/\\]/).filter(Boolean);
|
|
436
|
-
const folders = new Set(sliceFolders.map((s) => String(s).toLowerCase()));
|
|
437
|
-
for (let i = 0; i < parts.length - 1; i += 1) {
|
|
438
|
-
if (folders.has(parts[i].toLowerCase())) {
|
|
439
|
-
return `${parts[i]}/${parts[i + 1]}`;
|
|
440
|
-
}
|
|
441
|
-
}
|
|
442
|
-
return void 0;
|
|
443
|
-
}
|
|
444
|
-
function inferSliceFoldersFromPatterns(patterns) {
|
|
445
|
-
const out = /* @__PURE__ */ new Set();
|
|
446
|
-
for (const pattern of patterns ?? []) {
|
|
447
|
-
const glob = normalizeGlobSeparators(String(pattern));
|
|
448
|
-
const parts = glob.split("/").filter(Boolean);
|
|
449
|
-
for (let i = 0; i < parts.length; i += 1) {
|
|
450
|
-
const part = parts[i];
|
|
451
|
-
if ((part === "**" || part === "*") && i > 0) {
|
|
452
|
-
const prev = parts[i - 1];
|
|
453
|
-
if (prev && !prev.includes("*") && !prev.includes("{") && !prev.includes("}")) {
|
|
454
|
-
out.add(prev);
|
|
455
|
-
}
|
|
456
|
-
}
|
|
457
|
-
}
|
|
458
|
-
}
|
|
459
|
-
return [...out];
|
|
460
|
-
}
|
|
461
|
-
function resolveSliceFolders(rule, layerName, layers) {
|
|
462
|
-
if (Array.isArray(rule.sliceFolders) && rule.sliceFolders.length > 0) {
|
|
463
|
-
return rule.sliceFolders.filter((s) => typeof s === "string" && s.length > 0);
|
|
464
|
-
}
|
|
465
|
-
const layer = (layers ?? []).find((l) => l.name === layerName);
|
|
466
|
-
return inferSliceFoldersFromPatterns(layer?.patterns);
|
|
467
|
-
}
|
|
468
|
-
function findDeniedEdgeRule(rules, from, to, options) {
|
|
469
|
-
for (const rule of rules ?? []) {
|
|
470
|
-
if (rule.from !== from || rule.to !== to) continue;
|
|
471
|
-
if (rule.allowed !== false) continue;
|
|
472
|
-
if (rule.peerIsolation) {
|
|
473
|
-
const fromPath = options?.fromPath;
|
|
474
|
-
const toPath = options?.toPath;
|
|
475
|
-
if (!fromPath || !toPath) continue;
|
|
476
|
-
const folders = resolveSliceFolders(rule, from, options?.layers);
|
|
477
|
-
if (folders.length === 0) continue;
|
|
478
|
-
const fromSlice = sliceIdForPath(fromPath, folders);
|
|
479
|
-
const toSlice = sliceIdForPath(toPath, folders);
|
|
480
|
-
if (!fromSlice || !toSlice) continue;
|
|
481
|
-
if (fromSlice !== toSlice) return rule;
|
|
482
|
-
continue;
|
|
483
|
-
}
|
|
484
|
-
if (from === to) continue;
|
|
485
|
-
return rule;
|
|
486
|
-
}
|
|
487
|
-
return void 0;
|
|
488
|
-
}
|
|
489
|
-
|
|
490
|
-
// src/kernel/semanticAnalysis.ts
|
|
491
|
-
function literalText(ts, node) {
|
|
492
|
-
return node && ts.isStringLiteralLike(node) ? node.text : void 0;
|
|
493
|
-
}
|
|
494
|
-
function lineOf(sourceFile, node) {
|
|
495
|
-
return sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;
|
|
496
|
-
}
|
|
497
|
-
function isTypeOnlyReference(ts, node) {
|
|
498
|
-
if (ts.isImportDeclaration(node)) {
|
|
499
|
-
const clause = node.importClause;
|
|
500
|
-
if (!clause) return false;
|
|
501
|
-
if (clause.isTypeOnly) return true;
|
|
502
|
-
const named = clause.namedBindings;
|
|
503
|
-
return Boolean(
|
|
504
|
-
named && ts.isNamedImports(named) && named.elements.length > 0 && named.elements.every((element) => element.isTypeOnly)
|
|
505
|
-
);
|
|
506
|
-
}
|
|
507
|
-
if (ts.isExportDeclaration(node)) {
|
|
508
|
-
if (node.isTypeOnly) return true;
|
|
509
|
-
const clause = node.exportClause;
|
|
510
|
-
return Boolean(
|
|
511
|
-
clause && ts.isNamedExports(clause) && clause.elements.length > 0 && clause.elements.every((element) => element.isTypeOnly)
|
|
512
|
-
);
|
|
513
|
-
}
|
|
514
|
-
return false;
|
|
515
|
-
}
|
|
516
|
-
function singleFileChecker(ts, sourceFile) {
|
|
517
|
-
const options = { noLib: true, noResolve: true, target: ts.ScriptTarget.Latest };
|
|
518
|
-
const host = ts.createCompilerHost(options, true);
|
|
519
|
-
host.getSourceFile = (fileName) => fileName === sourceFile.fileName ? sourceFile : void 0;
|
|
520
|
-
host.fileExists = (fileName) => fileName === sourceFile.fileName;
|
|
521
|
-
host.readFile = (fileName) => fileName === sourceFile.fileName ? sourceFile.text : void 0;
|
|
522
|
-
return ts.createProgram([sourceFile.fileName], options, host).getTypeChecker();
|
|
523
|
-
}
|
|
524
|
-
function symbolAt(checker, node) {
|
|
525
|
-
try {
|
|
526
|
-
return checker.getSymbolAtLocation(node);
|
|
527
|
-
} catch {
|
|
528
|
-
return void 0;
|
|
529
|
-
}
|
|
530
|
-
}
|
|
531
|
-
function localDeclaration(ts, checker, sourceFile, node) {
|
|
532
|
-
const shorthand = node.parent && ts.isShorthandPropertyAssignment(node.parent) && node.parent.name === node;
|
|
533
|
-
let symbol;
|
|
534
|
-
try {
|
|
535
|
-
symbol = shorthand ? checker.getShorthandAssignmentValueSymbol(node.parent) : symbolAt(checker, node);
|
|
536
|
-
} catch {
|
|
537
|
-
symbol = void 0;
|
|
538
|
-
}
|
|
539
|
-
return Boolean(
|
|
540
|
-
symbol?.declarations?.some(
|
|
541
|
-
(declaration) => declaration.getSourceFile().fileName === sourceFile.fileName
|
|
542
|
-
)
|
|
543
|
-
);
|
|
544
|
-
}
|
|
545
|
-
function extractSemanticDependencies(ts, sourceFile) {
|
|
546
|
-
let checker;
|
|
547
|
-
const dependencies = [];
|
|
548
|
-
const add = (node, kind, specifier, typeOnly = false) => dependencies.push({
|
|
549
|
-
specifier,
|
|
550
|
-
kind,
|
|
551
|
-
line: lineOf(sourceFile, node),
|
|
552
|
-
typeOnly,
|
|
553
|
-
unresolved: specifier === void 0,
|
|
554
|
-
node
|
|
555
|
-
});
|
|
556
|
-
const visit = (node) => {
|
|
557
|
-
if (ts.isImportDeclaration(node)) {
|
|
558
|
-
add(node, "import", literalText(ts, node.moduleSpecifier), isTypeOnlyReference(ts, node));
|
|
559
|
-
} else if (ts.isExportDeclaration(node) && node.moduleSpecifier) {
|
|
560
|
-
add(node, "export", literalText(ts, node.moduleSpecifier), isTypeOnlyReference(ts, node));
|
|
561
|
-
} else if (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference)) {
|
|
562
|
-
add(node, "require", literalText(ts, node.moduleReference.expression));
|
|
563
|
-
} else if (ts.isCallExpression(node)) {
|
|
564
|
-
const dynamicImport = node.expression.kind === ts.SyntaxKind.ImportKeyword;
|
|
565
|
-
const requireCall = ts.isIdentifier(node.expression) && node.expression.text === "require";
|
|
566
|
-
const directRequire = requireCall && !localDeclaration(
|
|
567
|
-
ts,
|
|
568
|
-
checker ?? (checker = singleFileChecker(ts, sourceFile)),
|
|
569
|
-
sourceFile,
|
|
570
|
-
node.expression
|
|
571
|
-
);
|
|
572
|
-
if (dynamicImport || directRequire) {
|
|
573
|
-
add(node, directRequire ? "require" : "dynamic-import", literalText(ts, node.arguments[0]));
|
|
574
|
-
}
|
|
575
|
-
}
|
|
576
|
-
ts.forEachChild(node, visit);
|
|
577
|
-
};
|
|
578
|
-
visit(sourceFile);
|
|
579
|
-
return dependencies;
|
|
580
|
-
}
|
|
581
|
-
function staticAccessPath(ts, node) {
|
|
582
|
-
const segments = [];
|
|
583
|
-
let current = node;
|
|
584
|
-
while (ts.isPropertyAccessExpression(current) || ts.isElementAccessExpression(current)) {
|
|
585
|
-
if (ts.isPropertyAccessExpression(current)) segments.unshift(current.name.text);
|
|
586
|
-
else {
|
|
587
|
-
const property = literalText(ts, current.argumentExpression);
|
|
588
|
-
if (property === void 0) return void 0;
|
|
589
|
-
segments.unshift(property);
|
|
590
|
-
}
|
|
591
|
-
current = current.expression;
|
|
592
|
-
}
|
|
593
|
-
if (!ts.isIdentifier(current)) return void 0;
|
|
594
|
-
segments.unshift(current.text);
|
|
595
|
-
return { root: current, segments };
|
|
596
|
-
}
|
|
597
|
-
function runtimeIdentifierReference(ts, node) {
|
|
598
|
-
const parent = node.parent;
|
|
599
|
-
if (ts.isPropertyAccessExpression(parent) || ts.isElementAccessExpression(parent)) return false;
|
|
600
|
-
return ts.isExpressionNode(node) && !ts.isInTypeQuery(node) || ts.isShorthandPropertyAssignment(parent) && parent.name === node;
|
|
601
|
-
}
|
|
602
|
-
function bestForbiddenMatch(entries, segments) {
|
|
603
|
-
const normalized = segments[0] === "globalThis" ? segments.slice(1) : segments;
|
|
604
|
-
for (let length = normalized.length; length >= 1; length -= 1) {
|
|
605
|
-
const candidate = normalized.slice(0, length).join(".");
|
|
606
|
-
if (entries.has(candidate)) return candidate;
|
|
607
|
-
}
|
|
608
|
-
return void 0;
|
|
609
|
-
}
|
|
610
|
-
function collectForbiddenCapabilityUses(ts, sourceFile, forbidden) {
|
|
611
|
-
if (forbidden.length === 0) return [];
|
|
612
|
-
const entries = new Set(forbidden);
|
|
613
|
-
const checker = singleFileChecker(ts, sourceFile);
|
|
614
|
-
const aliases = /* @__PURE__ */ new Map();
|
|
615
|
-
const topLevelNames = /* @__PURE__ */ new Set();
|
|
616
|
-
for (const statement of sourceFile.statements) {
|
|
617
|
-
if (ts.isVariableStatement(statement)) {
|
|
618
|
-
for (const declaration of statement.declarationList.declarations) {
|
|
619
|
-
if (ts.isIdentifier(declaration.name)) topLevelNames.add(declaration.name.text);
|
|
620
|
-
}
|
|
621
|
-
}
|
|
622
|
-
}
|
|
623
|
-
const resolvePath = (node) => {
|
|
624
|
-
const path = staticAccessPath(ts, node);
|
|
625
|
-
if (!path) return void 0;
|
|
626
|
-
const symbol = symbolAt(checker, path.root);
|
|
627
|
-
const alias = symbol ? aliases.get(symbol) : void 0;
|
|
628
|
-
if (alias) return [...alias, ...path.segments.slice(1)];
|
|
629
|
-
return localDeclaration(ts, checker, sourceFile, path.root) || topLevelNames.has(path.root.text) ? void 0 : path.segments;
|
|
630
|
-
};
|
|
631
|
-
for (const statement of sourceFile.statements) {
|
|
632
|
-
if (!ts.isVariableStatement(statement)) continue;
|
|
633
|
-
for (const declaration of statement.declarationList.declarations) {
|
|
634
|
-
if (!declaration.initializer || !ts.isIdentifier(declaration.name)) continue;
|
|
635
|
-
const path = resolvePath(declaration.initializer);
|
|
636
|
-
const symbol = symbolAt(checker, declaration.name);
|
|
637
|
-
if (!path || !symbol) continue;
|
|
638
|
-
aliases.set(symbol, path);
|
|
639
|
-
}
|
|
640
|
-
}
|
|
641
|
-
const uses = [];
|
|
642
|
-
const seen = /* @__PURE__ */ new Set();
|
|
643
|
-
const flag = (name, node) => {
|
|
644
|
-
const line = lineOf(sourceFile, node);
|
|
645
|
-
const key = `${name}:${node.getStart(sourceFile)}`;
|
|
646
|
-
if (seen.has(key)) return;
|
|
647
|
-
seen.add(key);
|
|
648
|
-
uses.push({ name, line, node });
|
|
649
|
-
};
|
|
650
|
-
const visit = (node) => {
|
|
651
|
-
const parentContinuesPath = node.parent && (ts.isPropertyAccessExpression(node.parent) || ts.isElementAccessExpression(node.parent)) && node.parent.expression === node;
|
|
652
|
-
if ((ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) && !parentContinuesPath) {
|
|
653
|
-
const path = resolvePath(node);
|
|
654
|
-
const match = path ? bestForbiddenMatch(entries, path) : void 0;
|
|
655
|
-
if (match) flag(match, node);
|
|
656
|
-
} else if (ts.isIdentifier(node) && entries.has(node.text) && runtimeIdentifierReference(ts, node) && !localDeclaration(ts, checker, sourceFile, node)) {
|
|
657
|
-
flag(node.text, node);
|
|
658
|
-
}
|
|
659
|
-
if (ts.isVariableDeclaration(node) && ts.isObjectBindingPattern(node.name) && node.initializer) {
|
|
660
|
-
const base = resolvePath(node.initializer);
|
|
661
|
-
if (base) {
|
|
662
|
-
for (const element of node.name.elements) {
|
|
663
|
-
if (!ts.isIdentifier(element.name)) continue;
|
|
664
|
-
const property = element.propertyName ? literalText(ts, element.propertyName) ?? element.propertyName.text : element.name.text;
|
|
665
|
-
const match = bestForbiddenMatch(entries, [...base, property]);
|
|
666
|
-
if (match) flag(match, node.initializer);
|
|
667
|
-
}
|
|
668
|
-
}
|
|
669
|
-
}
|
|
670
|
-
ts.forEachChild(node, visit);
|
|
671
|
-
};
|
|
672
|
-
visit(sourceFile);
|
|
673
|
-
return uses;
|
|
674
|
-
}
|
|
675
|
-
|
|
676
|
-
// src/domain/sourcePolicy.ts
|
|
677
|
-
var SOURCE_POLICY_MESSAGES = {
|
|
678
|
-
RAW_EVENT_PUBLISH: "Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts and tooling.",
|
|
679
|
-
PUBLISH_MISSING_SOURCE: "Strict Ark publish calls must include metadata.source."
|
|
680
|
-
};
|
|
681
|
-
function looksLikeArkIntent(value) {
|
|
682
|
-
return /^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(
|
|
683
|
-
value
|
|
684
|
-
);
|
|
685
|
-
}
|
|
686
|
-
function classifyPublishFacts(facts) {
|
|
687
|
-
if (!facts.publishCall) return [];
|
|
688
|
-
const findings = [];
|
|
689
|
-
if (facts.rawIntentName !== void 0 && looksLikeArkIntent(facts.rawIntentName) || facts.objectHasIntent) {
|
|
690
|
-
findings.push({
|
|
691
|
-
ruleId: "RAW_EVENT_PUBLISH",
|
|
692
|
-
message: SOURCE_POLICY_MESSAGES.RAW_EVENT_PUBLISH
|
|
693
|
-
});
|
|
694
|
-
}
|
|
695
|
-
if (facts.arkPublishCandidate && !facts.hasSource) {
|
|
696
|
-
findings.push({
|
|
697
|
-
ruleId: "PUBLISH_MISSING_SOURCE",
|
|
698
|
-
message: SOURCE_POLICY_MESSAGES.PUBLISH_MISSING_SOURCE
|
|
699
|
-
});
|
|
700
|
-
}
|
|
701
|
-
return findings;
|
|
702
|
-
}
|
|
703
|
-
|
|
704
|
-
// src/kernel/analysis.ts
|
|
705
|
-
function loadContract(input, source) {
|
|
706
|
-
const loaded = typeof input === "string" ? parseArkConfigJson(input, source) : loadArkConfigContract(input, source);
|
|
707
|
-
return { ...loaded, policyHash: deterministicHash(stableSerialize(loaded.config)) };
|
|
708
|
-
}
|
|
709
|
-
function normalizePath(value) {
|
|
710
|
-
return value.replace(/\\/g, "/").replace(/^\.\//, "");
|
|
711
|
-
}
|
|
712
|
-
function isIdentifierCharacter(value) {
|
|
713
|
-
return value !== void 0 && /[A-Za-z0-9_$]/.test(value);
|
|
714
|
-
}
|
|
715
|
-
function skipWhitespace(source, index) {
|
|
716
|
-
while (index < source.length && /\s/.test(source[index])) index += 1;
|
|
717
|
-
return index;
|
|
718
|
-
}
|
|
719
|
-
function readString(source, index) {
|
|
720
|
-
const quote = source[index];
|
|
721
|
-
if (quote !== "'" && quote !== '"') return void 0;
|
|
722
|
-
const start = index;
|
|
723
|
-
let value = "";
|
|
724
|
-
for (index += 1; index < source.length; index += 1) {
|
|
725
|
-
const current = source[index];
|
|
726
|
-
if (current === quote) {
|
|
727
|
-
return { value, offset: start, excerpt: source.slice(start, index + 1) };
|
|
728
|
-
}
|
|
729
|
-
if (current === "\\" && index + 1 < source.length) {
|
|
730
|
-
value += source[index + 1];
|
|
731
|
-
index += 1;
|
|
732
|
-
} else {
|
|
733
|
-
value += current;
|
|
734
|
-
}
|
|
735
|
-
}
|
|
736
|
-
return void 0;
|
|
737
|
-
}
|
|
738
|
-
function isWordAt(source, word, index) {
|
|
739
|
-
return source.startsWith(word, index) && !isIdentifierCharacter(source[index - 1]) && !isIdentifierCharacter(source[index + word.length]);
|
|
740
|
-
}
|
|
741
|
-
function specifierAfterImport(source, index) {
|
|
742
|
-
index = skipWhitespace(source, index + "import".length);
|
|
743
|
-
if (source[index] === "(") return readString(source, skipWhitespace(source, index + 1));
|
|
744
|
-
return specifierInStaticStatement(source, index, true);
|
|
745
|
-
}
|
|
746
|
-
function specifierAfterExport(source, index) {
|
|
747
|
-
return specifierInStaticStatement(source, index + "export".length, false);
|
|
748
|
-
}
|
|
749
|
-
function specifierInStaticStatement(source, index, allowDirectSpecifier) {
|
|
750
|
-
for (; index < source.length; index += 1) {
|
|
751
|
-
if (source[index] === ";") return void 0;
|
|
752
|
-
if (isWordAt(source, "from", index)) {
|
|
753
|
-
return readString(source, skipWhitespace(source, index + "from".length));
|
|
754
|
-
}
|
|
755
|
-
if (allowDirectSpecifier && (source[index] === "'" || source[index] === '"')) {
|
|
756
|
-
return readString(source, index);
|
|
757
|
-
}
|
|
758
|
-
if (index > 0 && (isWordAt(source, "import", index) || isWordAt(source, "export", index))) {
|
|
759
|
-
return void 0;
|
|
760
|
-
}
|
|
761
|
-
}
|
|
762
|
-
return void 0;
|
|
763
|
-
}
|
|
764
|
-
function moduleSpecifiers(source) {
|
|
765
|
-
const result = [];
|
|
766
|
-
for (let index = 0; index < source.length; index += 1) {
|
|
767
|
-
const current = source[index];
|
|
768
|
-
if (current === "/" && source[index + 1] === "/") {
|
|
769
|
-
index = source.indexOf("\n", index + 2);
|
|
770
|
-
if (index < 0) break;
|
|
771
|
-
continue;
|
|
772
|
-
}
|
|
773
|
-
if (current === "/" && source[index + 1] === "*") {
|
|
774
|
-
const end = source.indexOf("*/", index + 2);
|
|
775
|
-
if (end < 0) break;
|
|
776
|
-
index = end + 1;
|
|
777
|
-
continue;
|
|
778
|
-
}
|
|
779
|
-
if (current === "'" || current === '"' || current === "`") {
|
|
780
|
-
const string = readString(source, index);
|
|
781
|
-
if (string) index = string.offset + string.excerpt.length - 1;
|
|
782
|
-
continue;
|
|
783
|
-
}
|
|
784
|
-
const specifier = isWordAt(source, "import", index) ? specifierAfterImport(source, index) : isWordAt(source, "export", index) ? specifierAfterExport(source, index) : void 0;
|
|
785
|
-
if (specifier) result.push(specifier);
|
|
786
|
-
}
|
|
787
|
-
return result;
|
|
788
|
-
}
|
|
789
|
-
function importEdges(file, files) {
|
|
790
|
-
const edges = [];
|
|
791
|
-
for (const moduleSpecifier of moduleSpecifiers(file.content)) {
|
|
792
|
-
const specifier = moduleSpecifier.value;
|
|
793
|
-
if (!specifier.startsWith(".")) continue;
|
|
794
|
-
const line = file.content.slice(0, moduleSpecifier.offset).split("\n").length;
|
|
795
|
-
const evidence = {
|
|
796
|
-
kind: "import",
|
|
797
|
-
file: file.path,
|
|
798
|
-
line,
|
|
799
|
-
excerpt: moduleSpecifier.excerpt
|
|
800
|
-
};
|
|
801
|
-
const target = resolveSpecifier(file.path, specifier, files);
|
|
802
|
-
edges.push({
|
|
803
|
-
from: file.path,
|
|
804
|
-
specifier,
|
|
805
|
-
to: target?.path ?? null,
|
|
806
|
-
resolution: target ? "resolved" : "unresolved",
|
|
807
|
-
fromLayer: file.layer,
|
|
808
|
-
toLayer: target?.layer ?? null,
|
|
809
|
-
evidence
|
|
810
|
-
});
|
|
811
|
-
}
|
|
812
|
-
return edges;
|
|
813
|
-
}
|
|
814
|
-
function resolveSpecifier(from, specifier, files) {
|
|
815
|
-
const segments = from.split("/");
|
|
816
|
-
segments.pop();
|
|
817
|
-
for (const segment of specifier.split("/")) {
|
|
818
|
-
if (segment === "." || segment === "") continue;
|
|
819
|
-
if (segment === "..") segments.pop();
|
|
820
|
-
else segments.push(segment);
|
|
821
|
-
}
|
|
822
|
-
const base = segments.join("/");
|
|
823
|
-
for (const candidate of [base, `${base}.ts`, `${base}.tsx`, `${base}.mts`, `${base}.cts`, `${base}/index.ts`, `${base}/index.tsx`]) {
|
|
824
|
-
const found = files.get(candidate);
|
|
825
|
-
if (found) return found;
|
|
826
|
-
}
|
|
827
|
-
return void 0;
|
|
828
|
-
}
|
|
829
|
-
function violationsFor(edges, config) {
|
|
830
|
-
const violations = [];
|
|
831
|
-
for (const edge of edges) {
|
|
832
|
-
if (!edge.to || !edge.fromLayer || !edge.toLayer) continue;
|
|
833
|
-
const rule = findDeniedEdgeRule(config.rules, edge.fromLayer, edge.toLayer, {
|
|
834
|
-
fromPath: edge.from,
|
|
835
|
-
toPath: edge.to,
|
|
836
|
-
layers: config.layers
|
|
837
|
-
});
|
|
838
|
-
if (!rule) continue;
|
|
839
|
-
violations.push({
|
|
840
|
-
ruleId: `layer-dependency:${rule.from}->${rule.to}`,
|
|
841
|
-
message: rule.message ?? `${rule.from} must not depend on ${rule.to}.`,
|
|
842
|
-
edge,
|
|
843
|
-
evidence: edge.evidence
|
|
844
|
-
});
|
|
845
|
-
}
|
|
846
|
-
return violations;
|
|
847
|
-
}
|
|
848
|
-
function analyzeProject(input) {
|
|
849
|
-
const files = input.files.map((inputFile) => {
|
|
850
|
-
const path = normalizePath(inputFile.path);
|
|
851
|
-
return {
|
|
852
|
-
path,
|
|
853
|
-
content: inputFile.content,
|
|
854
|
-
contentHash: deterministicHash(inputFile.content),
|
|
855
|
-
layer: layerForRelativePath(path, input.contract.config.layers) ?? null
|
|
856
|
-
};
|
|
857
|
-
}).sort((left, right) => left.path.localeCompare(right.path));
|
|
858
|
-
const fileByPath = new Map(files.map((file) => [file.path, file]));
|
|
859
|
-
const edges = files.flatMap((file) => importEdges(file, fileByPath));
|
|
860
|
-
const capabilityUses = [];
|
|
861
|
-
const violations = violationsFor(edges, input.contract.config);
|
|
862
|
-
return {
|
|
863
|
-
ir: {
|
|
864
|
-
schemaVersion: ANALYSIS_IR_SCHEMA_VERSION,
|
|
865
|
-
policyHash: input.contract.policyHash,
|
|
866
|
-
compilerOptionsHash: deterministicHash(stableSerialize(input.compilerOptions ?? {})),
|
|
867
|
-
files,
|
|
868
|
-
layers: input.contract.config.layers.map((layer) => layer.name),
|
|
869
|
-
edges,
|
|
870
|
-
capabilityUses,
|
|
871
|
-
violations
|
|
872
|
-
}
|
|
873
|
-
};
|
|
874
|
-
}
|
|
875
|
-
function analyzeChange(input) {
|
|
876
|
-
const files = new Map(input.files.map((file) => [normalizePath(file.path), file]));
|
|
877
|
-
for (const change of input.changes) {
|
|
878
|
-
const path = normalizePath(change.path);
|
|
879
|
-
if ("delete" in change && change.delete) files.delete(path);
|
|
880
|
-
else if ("content" in change) files.set(path, { path, content: change.content });
|
|
881
|
-
}
|
|
882
|
-
return analyzeProject({
|
|
883
|
-
contract: input.contract,
|
|
884
|
-
files: [...files.values()],
|
|
885
|
-
compilerOptions: input.compilerOptions
|
|
886
|
-
});
|
|
887
|
-
}
|
|
888
|
-
function explainViolation(violation) {
|
|
889
|
-
const location = `${violation.evidence.file}:${violation.evidence.line}`;
|
|
890
|
-
if (!violation.edge) return `${violation.ruleId} at ${location}: ${violation.message}`;
|
|
891
|
-
const target = violation.edge.to ?? violation.edge.specifier;
|
|
892
|
-
return `${violation.ruleId} at ${location}: ${violation.edge.from} imports ${target}. ${violation.message}`;
|
|
893
|
-
}
|
|
894
|
-
function detectArchitectureCycles(graph) {
|
|
895
|
-
let index = 0;
|
|
896
|
-
const indices = /* @__PURE__ */ new Map();
|
|
897
|
-
const low = /* @__PURE__ */ new Map();
|
|
898
|
-
const onStack = /* @__PURE__ */ new Set();
|
|
899
|
-
const stack = [];
|
|
900
|
-
const components = [];
|
|
901
|
-
const connect = (file) => {
|
|
902
|
-
indices.set(file, index);
|
|
903
|
-
low.set(file, index);
|
|
904
|
-
index += 1;
|
|
905
|
-
stack.push(file);
|
|
906
|
-
onStack.add(file);
|
|
907
|
-
for (const target of [...graph.get(file) ?? []].sort()) {
|
|
908
|
-
if (!graph.has(target)) continue;
|
|
909
|
-
if (!indices.has(target)) {
|
|
910
|
-
connect(target);
|
|
911
|
-
low.set(file, Math.min(low.get(file) ?? 0, low.get(target) ?? 0));
|
|
912
|
-
} else if (onStack.has(target)) {
|
|
913
|
-
low.set(file, Math.min(low.get(file) ?? 0, indices.get(target) ?? 0));
|
|
914
|
-
}
|
|
915
|
-
}
|
|
916
|
-
if (low.get(file) !== indices.get(file)) return;
|
|
917
|
-
const component = [];
|
|
918
|
-
let member;
|
|
919
|
-
do {
|
|
920
|
-
member = stack.pop();
|
|
921
|
-
if (member === void 0) break;
|
|
922
|
-
onStack.delete(member);
|
|
923
|
-
component.push(member);
|
|
924
|
-
} while (member !== file);
|
|
925
|
-
if (component.length > 1) components.push(component.sort());
|
|
926
|
-
};
|
|
927
|
-
for (const file of [...graph.keys()].sort()) {
|
|
928
|
-
if (!indices.has(file)) connect(file);
|
|
929
|
-
}
|
|
930
|
-
return components.sort((left, right) => left[0].localeCompare(right[0])).map((members) => ({
|
|
931
|
-
ruleId: "CIRCULAR_DEPENDENCY",
|
|
932
|
-
file: members[0],
|
|
933
|
-
line: 1,
|
|
934
|
-
target: members.join(" \u2192 "),
|
|
935
|
-
message: `Circular dependency among ${members.length} files: ${members.join(" \u2192 ")} \u2192 ${members[0]}.`,
|
|
936
|
-
cycleKind: "value"
|
|
937
|
-
}));
|
|
938
|
-
}
|
|
939
|
-
function evaluateArchitectureGraph(input) {
|
|
940
|
-
const violations = input.contentViolations.map((violation) => ({ ...violation }));
|
|
941
|
-
const warnings = (input.warnings ?? []).map((warning) => ({ ...warning }));
|
|
942
|
-
const graph = new Map(
|
|
943
|
-
input.files.map((file) => [file, /* @__PURE__ */ new Set()])
|
|
944
|
-
);
|
|
945
|
-
for (const edge of input.edges) {
|
|
946
|
-
if (edge.to && edge.to !== edge.from && !edge.typeOnly && graph.has(edge.from)) {
|
|
947
|
-
graph.get(edge.from)?.add(edge.to);
|
|
948
|
-
}
|
|
949
|
-
if (!edge.to || !edge.toLayer) continue;
|
|
950
|
-
const rule = findDeniedEdgeRule(input.rules, edge.fromLayer, edge.toLayer, {
|
|
951
|
-
fromPath: edge.from,
|
|
952
|
-
toPath: edge.to,
|
|
953
|
-
layers: input.config.layers
|
|
954
|
-
});
|
|
955
|
-
if (!rule) continue;
|
|
956
|
-
const peerIsolation = Boolean(rule.peerIsolation);
|
|
957
|
-
violations.push({
|
|
958
|
-
ruleId: "LAYER_IMPORT_VIOLATION",
|
|
959
|
-
file: edge.from,
|
|
960
|
-
line: edge.line,
|
|
961
|
-
fromLayer: edge.fromLayer,
|
|
962
|
-
toLayer: edge.toLayer,
|
|
963
|
-
target: edge.to,
|
|
964
|
-
...edge.typeOnly ? { typeOnly: true } : {},
|
|
965
|
-
...edge.targetTypeOnlyExports ? { targetTypeOnlyExports: true } : {},
|
|
966
|
-
...edge.sourcePureTypeModule ? { sourcePureTypeModule: true } : {},
|
|
967
|
-
...edge.namedBindingsTypeOnly ? { namedBindingsTypeOnly: true } : {},
|
|
968
|
-
...!peerIsolation && edge.portProofEligible ? { portProofEligible: true } : {},
|
|
969
|
-
...edge.kind ? { edgeKind: edge.kind } : {},
|
|
970
|
-
...peerIsolation ? { peerIsolation: true } : {},
|
|
971
|
-
message: rule.message ?? (peerIsolation ? `${edge.fromLayer} must not ${edge.kind} another slice of ${edge.toLayer} (${edge.from} \u2192 ${edge.to}). Extract shared code or use events/ports across slices.` : `${edge.fromLayer} must not ${edge.kind} ${edge.toLayer}.`)
|
|
972
|
-
});
|
|
973
|
-
}
|
|
974
|
-
const cyclePolicy = String(input.config.cyclePolicy ?? "strict").toLowerCase();
|
|
975
|
-
if (cyclePolicy !== "off") {
|
|
976
|
-
const cycles = detectArchitectureCycles(graph);
|
|
977
|
-
if (cyclePolicy === "soft" || cyclePolicy === "framework-soft") {
|
|
978
|
-
warnings.push(
|
|
979
|
-
...cycles.map((cycle) => ({
|
|
980
|
-
...cycle,
|
|
981
|
-
message: `${cycle.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,
|
|
982
|
-
failsStrict: false
|
|
983
|
-
}))
|
|
984
|
-
);
|
|
985
|
-
} else {
|
|
986
|
-
violations.push(...cycles);
|
|
987
|
-
}
|
|
988
|
-
}
|
|
989
|
-
return { violations, warnings, safety: input.safety };
|
|
990
|
-
}
|
|
991
|
-
function configWarning(ruleId, message, extra = {}) {
|
|
992
|
-
return { ruleId, message, ...extra };
|
|
993
|
-
}
|
|
994
|
-
function collectAnalysisConfigWarnings(input) {
|
|
995
|
-
const { config, rules, files, manifest } = input;
|
|
996
|
-
const warnings = [];
|
|
997
|
-
if (config.dynamicImportAllowlist !== void 0 && (!Array.isArray(config.dynamicImportAllowlist) || config.dynamicImportAllowlist.some((entry) => typeof entry !== "string"))) {
|
|
998
|
-
warnings.push(
|
|
999
|
-
configWarning(
|
|
1000
|
-
"CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST",
|
|
1001
|
-
"dynamicImportAllowlist must be an array of file globs."
|
|
1002
|
-
)
|
|
1003
|
-
);
|
|
1004
|
-
}
|
|
1005
|
-
if (config.safety !== void 0 && (config.safety === null || typeof config.safety !== "object" || Array.isArray(config.safety))) {
|
|
1006
|
-
warnings.push(configWarning("CONFIG_INVALID_SAFETY", "safety must be an object."));
|
|
1007
|
-
} else if (config.safety) {
|
|
1008
|
-
for (const key of ["maxTsSuppressions", "maxAnyCasts"]) {
|
|
1009
|
-
const value = config.safety[key];
|
|
1010
|
-
if (value !== void 0 && (!Number.isInteger(value) || value < 0)) {
|
|
1011
|
-
warnings.push(
|
|
1012
|
-
configWarning(
|
|
1013
|
-
"CONFIG_INVALID_SAFETY_THRESHOLD",
|
|
1014
|
-
`safety.${key} must be a non-negative integer.`
|
|
1015
|
-
)
|
|
1016
|
-
);
|
|
1017
|
-
}
|
|
1018
|
-
}
|
|
1019
|
-
}
|
|
1020
|
-
const layers = Array.isArray(config.layers) ? config.layers : [];
|
|
1021
|
-
const manifestLayers = Array.isArray(manifest?.architecture?.layers) ? manifest.architecture.layers : [];
|
|
1022
|
-
const knownLayers = /* @__PURE__ */ new Set([
|
|
1023
|
-
...layers.map((layer) => layer.name).filter(Boolean),
|
|
1024
|
-
...manifestLayers.map((layer) => layer.name).filter((name) => Boolean(name))
|
|
1025
|
-
]);
|
|
1026
|
-
if (layers.length === 0) {
|
|
1027
|
-
warnings.push(
|
|
1028
|
-
configWarning(
|
|
1029
|
-
"CONFIG_NO_LAYERS",
|
|
1030
|
-
"No file layers are configured; ark-check cannot classify files for import-boundary enforcement."
|
|
1031
|
-
)
|
|
1032
|
-
);
|
|
1033
|
-
}
|
|
1034
|
-
const seenLayers = /* @__PURE__ */ new Set();
|
|
1035
|
-
const duplicateLayers = /* @__PURE__ */ new Set();
|
|
1036
|
-
for (const layer of layers) {
|
|
1037
|
-
if (!layer.name) {
|
|
1038
|
-
warnings.push(configWarning("CONFIG_LAYER_WITHOUT_NAME", "A configured layer is missing a name."));
|
|
1039
|
-
continue;
|
|
1040
|
-
}
|
|
1041
|
-
if (seenLayers.has(layer.name)) duplicateLayers.add(layer.name);
|
|
1042
|
-
seenLayers.add(layer.name);
|
|
1043
|
-
if (layer.forbiddenGlobals !== void 0 && (!Array.isArray(layer.forbiddenGlobals) || layer.forbiddenGlobals.some((entry) => typeof entry !== "string"))) {
|
|
1044
|
-
warnings.push(
|
|
1045
|
-
configWarning(
|
|
1046
|
-
"CONFIG_INVALID_FORBIDDEN_GLOBALS",
|
|
1047
|
-
`Layer "${layer.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,
|
|
1048
|
-
{ layer: layer.name }
|
|
1049
|
-
)
|
|
1050
|
-
);
|
|
1051
|
-
}
|
|
1052
|
-
const patterns = Array.isArray(layer.patterns) ? layer.patterns : [];
|
|
1053
|
-
if (patterns.length === 0) {
|
|
1054
|
-
warnings.push(
|
|
1055
|
-
configWarning(
|
|
1056
|
-
"CONFIG_LAYER_WITHOUT_PATTERNS",
|
|
1057
|
-
`Layer "${layer.name}" has no file patterns and will never classify files.`,
|
|
1058
|
-
{ layer: layer.name }
|
|
1059
|
-
)
|
|
1060
|
-
);
|
|
1061
|
-
continue;
|
|
1062
|
-
}
|
|
1063
|
-
for (const pattern of patterns) {
|
|
1064
|
-
let expression;
|
|
1065
|
-
try {
|
|
1066
|
-
expression = globToRegExp(pattern);
|
|
1067
|
-
} catch (error) {
|
|
1068
|
-
warnings.push(
|
|
1069
|
-
configWarning(
|
|
1070
|
-
"CONFIG_INVALID_LAYER_PATTERN",
|
|
1071
|
-
`Layer "${layer.name}" has an invalid pattern "${pattern}": ${error instanceof Error ? error.message : String(error)}`,
|
|
1072
|
-
{ layer: layer.name, pattern }
|
|
1073
|
-
)
|
|
1074
|
-
);
|
|
1075
|
-
continue;
|
|
1076
|
-
}
|
|
1077
|
-
if (!files.some((file) => expression.test(file)) && !layer.optional) {
|
|
1078
|
-
warnings.push(
|
|
1079
|
-
configWarning(
|
|
1080
|
-
"CONFIG_LAYER_PATTERN_NO_MATCHES",
|
|
1081
|
-
`Layer "${layer.name}" pattern "${pattern}" matched no included files.`,
|
|
1082
|
-
{ layer: layer.name, pattern, failsStrict: false }
|
|
1083
|
-
)
|
|
1084
|
-
);
|
|
1085
|
-
}
|
|
1086
|
-
}
|
|
1087
|
-
}
|
|
1088
|
-
for (const name of duplicateLayers) {
|
|
1089
|
-
warnings.push(
|
|
1090
|
-
configWarning("CONFIG_DUPLICATE_LAYER", `Layer "${name}" is configured more than once.`, {
|
|
1091
|
-
layer: name
|
|
1092
|
-
})
|
|
1093
|
-
);
|
|
1094
|
-
}
|
|
1095
|
-
if (knownLayers.size > 0) {
|
|
1096
|
-
for (const rule of rules ?? []) {
|
|
1097
|
-
if (rule.from && !knownLayers.has(rule.from)) {
|
|
1098
|
-
warnings.push(
|
|
1099
|
-
configWarning(
|
|
1100
|
-
"CONFIG_RULE_UNKNOWN_FROM_LAYER",
|
|
1101
|
-
`Rule references unknown source layer "${rule.from}".`,
|
|
1102
|
-
{ fromLayer: rule.from, toLayer: rule.to }
|
|
1103
|
-
)
|
|
1104
|
-
);
|
|
1105
|
-
}
|
|
1106
|
-
if (rule.to && !knownLayers.has(rule.to)) {
|
|
1107
|
-
warnings.push(
|
|
1108
|
-
configWarning(
|
|
1109
|
-
"CONFIG_RULE_UNKNOWN_TO_LAYER",
|
|
1110
|
-
`Rule references unknown target layer "${rule.to}".`,
|
|
1111
|
-
{ fromLayer: rule.from, toLayer: rule.to }
|
|
1112
|
-
)
|
|
1113
|
-
);
|
|
1114
|
-
}
|
|
1115
|
-
}
|
|
1116
|
-
}
|
|
1117
|
-
const ambiguousPairs = /* @__PURE__ */ new Set();
|
|
1118
|
-
if (layers.length > 1) {
|
|
1119
|
-
for (const file of files) {
|
|
1120
|
-
let topScore = -1;
|
|
1121
|
-
let topLayers = [];
|
|
1122
|
-
for (const layer of layers) {
|
|
1123
|
-
for (const pattern of layer.patterns ?? []) {
|
|
1124
|
-
if (!globToRegExp(pattern).test(file)) continue;
|
|
1125
|
-
const score = patternSpecificity(pattern);
|
|
1126
|
-
if (score > topScore) {
|
|
1127
|
-
topScore = score;
|
|
1128
|
-
topLayers = [layer.name];
|
|
1129
|
-
} else if (score === topScore && !topLayers.includes(layer.name)) {
|
|
1130
|
-
topLayers.push(layer.name);
|
|
1131
|
-
}
|
|
1132
|
-
}
|
|
1133
|
-
}
|
|
1134
|
-
if (topLayers.length > 1) ambiguousPairs.add([...topLayers].sort().join(" + "));
|
|
1135
|
-
}
|
|
1136
|
-
}
|
|
1137
|
-
if (ambiguousPairs.size > 0) {
|
|
1138
|
-
warnings.push(
|
|
1139
|
-
configWarning(
|
|
1140
|
-
"CONFIG_AMBIGUOUS_LAYERS",
|
|
1141
|
-
`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...ambiguousPairs].join(", ")}.`,
|
|
1142
|
-
{ pairs: [...ambiguousPairs] }
|
|
1143
|
-
)
|
|
1144
|
-
);
|
|
1145
|
-
}
|
|
1146
|
-
const unclassified = files.filter((file) => !layerForRelativePath(file, layers));
|
|
1147
|
-
if (unclassified.length > 0) {
|
|
1148
|
-
warnings.push(
|
|
1149
|
-
configWarning(
|
|
1150
|
-
"CONFIG_UNCLASSIFIED_FILES",
|
|
1151
|
-
`${unclassified.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,
|
|
1152
|
-
{ count: unclassified.length, samples: unclassified.slice(0, 5) }
|
|
1153
|
-
)
|
|
1154
|
-
);
|
|
1155
|
-
}
|
|
1156
|
-
return warnings;
|
|
1157
|
-
}
|
|
1158
|
-
export {
|
|
1159
|
-
SOURCE_POLICY_MESSAGES,
|
|
1160
|
-
analyzeChange,
|
|
1161
|
-
analyzeProject,
|
|
1162
|
-
classifyPublishFacts,
|
|
1163
|
-
collectAnalysisConfigWarnings,
|
|
1164
|
-
collectForbiddenCapabilityUses,
|
|
1165
|
-
detectArchitectureCycles,
|
|
1166
|
-
evaluateArchitectureGraph,
|
|
1167
|
-
explainViolation,
|
|
1168
|
-
extractSemanticDependencies,
|
|
1169
|
-
loadContract,
|
|
1170
|
-
looksLikeArkIntent
|
|
1171
|
-
};
|
|
3
|
+
function $(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}function E(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(E).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${E(t[n])}`).join(",")}}`}var K="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",ie=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Ee=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function we(){let e=[];for(let t of ie)for(let n of ie)t===n||Ee.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var se=we();var w={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},ae={$schema:"https://json-schema.org/draft/2020-12/schema",$id:K,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:K,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:"1.0",default:"1.0"},name:{type:"string",minLength:1},include:{...w,minItems:1,default:["src"]},exclude:{...w,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:se,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...w,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...w,minItems:1},exclude:w,intentPrefixes:w,description:{type:"string",minLength:1},forbiddenGlobals:w,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:{...w,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}}}}},P=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
|
|
4
|
+
${n.map(r=>`- ${r.path}: ${r.message}`).join(`
|
|
5
|
+
`)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function oe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function B(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function R(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function $e(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function F(e,t,n,r,i){if(t.$ref){let a=$e(t.$ref,r);if(!a){i.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}F(e,a,n,r,i);return}if(t.const!==void 0&&!Object.is(e,t.const)){i.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(a=>Object.is(a,e))){i.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!oe(e)){i.push({path:n,message:`must be an object; received ${R(e)}`});return}let a=t.properties??{};for(let o of t.required??[])e[o]===void 0&&i.push({path:B(n,o),message:"is required"});if(t.additionalProperties===!1)for(let o of Object.keys(e))o in a||i.push({path:B(n,o),message:"unknown field"});for(let[o,l]of Object.entries(a))e[o]!==void 0&&F(e[o],l,B(n,o),r,i);return}if(t.type==="array"){if(!Array.isArray(e)){i.push({path:n,message:`must be an array; received ${R(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&i.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let a=e.map(o=>JSON.stringify(o));new Set(a).size!==a.length&&i.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((a,o)=>F(a,t.items,`${n}[${o}]`,r,i));return}if(t.type==="string"){if(typeof e!="string"){i.push({path:n,message:`must be a string; received ${R(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&i.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&i.push({path:n,message:`must be a boolean; received ${R(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){i.push({path:n,message:`must be an integer; received ${R(e)}`});return}t.minimum!==void 0&&e<t.minimum&&i.push({path:n,message:`must be at least ${t.minimum}`})}}function Oe(e){return{...e,$schema:e.$schema===void 0?K:e.$schema,schemaVersion:e.schemaVersion===void 0?"1.0":e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?se.map(t=>({...t})):e.rules}}function Re(e,t="ark.config.json"){if(!oe(e))throw new P(t,[{path:"$",message:`must be an object; received ${R(e)}`}]);let n=e.schemaVersion===void 0?"unversioned":null;if(e.schemaVersion!==void 0&&e.schemaVersion!=="1.0")throw new P(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.0`}]);return{candidate:Oe(e),migratedFrom:n}}function q(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=Re(e,t),i=[];if(F(n,ae,"$",ae,i),i.length>0)throw new P(t,i);return{config:n,migratedFrom:r}}function ce(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new P(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return q(n,t)}var le=new Map;function de(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function z(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let i=e[n+1];if("*?{}[],".includes(i)||i==="\\"){t+="\\"+i,n+=1;continue}t+="/";continue}t+=r}return t}function Pe(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 _(e){let t=le.get(e);if(t)return t;let n=z(e),r=Pe(n),i="",a=0;for(let l=0;l<n.length;l+=1){let d=n[l];d==="\\"&&l+1<n.length?(i+=de(n[l+1]),l+=1):d==="*"?n[l+1]==="*"?n[l+2]==="/"?(i+="(?:.*/)?",l+=2):(i+=".*",l+=1):i+="[^/]*":d==="?"?i+="[^/]":d==="{"&&r?(i+="(?:",a+=1):d==="}"&&r&&a>0?(i+=")",a-=1):d===","&&r&&a>0?i+="|":i+=de(d)}let o=new RegExp(`^${i}$`);return le.set(e,o),o}function Y(e){let t=z(String(e)),r=t.split("*")[0].split("/").filter(Boolean).length,i=t.replace(/\*/g,"").length;return r*1e4+i}function M(e,t){let n=String(e).split(/[/\\]/).join("/"),r,i=-1;for(let a of t??[])if(!(a.exclude??[]).some(o=>_(o).test(n))){for(let o of a.patterns??[])if(_(o).test(n)){let l=Y(o);l>i&&(i=l,r=a.name)}}return r}function pe(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),r=new Set(t.map(i=>String(i).toLowerCase()));for(let i=0;i<n.length-1;i+=1)if(r.has(n[i].toLowerCase()))return`${n[i]}/${n[i+1]}`}function Le(e){let t=new Set;for(let n of e??[]){let i=z(String(n)).split("/").filter(Boolean);for(let a=0;a<i.length;a+=1){let o=i[a];if((o==="**"||o==="*")&&a>0){let l=i[a-1];l&&!l.includes("*")&&!l.includes("{")&&!l.includes("}")&&t.add(l)}}}return[...t]}function ve(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(i=>typeof i=="string"&&i.length>0);let r=(n??[]).find(i=>i.name===t);return Le(r?.patterns)}function W(e,t,n,r){for(let i of e??[])if(!(i.from!==t||i.to!==n)&&i.allowed===!1){if(i.peerIsolation){let a=r?.fromPath,o=r?.toPath;if(!a||!o)continue;let l=ve(i,t,r?.layers);if(l.length===0)continue;let d=pe(a,l),u=pe(o,l);if(!d||!u)continue;if(d!==u)return i;continue}if(t!==n)return i}}function C(e,t){e.push({id:`${t.classification}:${t.path}:${t.kind}`,path:t.path,classification:t.classification,message:t.message,...t.classification==="weakening"||t.classification==="judgment-required"?{nextAction:`Restore the previous protection at ${t.path}, then run ArkGate again.`}:{},...t.before===void 0?{}:{before:t.before},...t.after===void 0?{}:{after:t.after}})}function S(e){return[...new Set(e??[])].sort()}function L(e,t,n,r,i){let a=S(n),o=S(r),l=new Set(a),d=new Set(o),u=o.filter(g=>!l.has(g)),m=a.filter(g=>!d.has(g));u.length===0&&m.length===0||(u.length>0&&C(e,{kind:"added",path:t,classification:i.added,message:i.addedMessage,before:a,after:o}),m.length>0&&C(e,{kind:"removed",path:t,classification:i.removed,message:i.removedMessage,before:a,after:o}))}function j(e,t,n,r,i,a,o){if(n===r)return;C(e,{kind:r?"enabled":"disabled",path:t,classification:r?i:i==="strengthening"?"weakening":"strengthening",message:r?a:o,before:n,after:r})}function H(e,t){let n=new Map,r=new Set;for(let i of e){let a=t(i);n.has(a)?r.add(a):n.set(a,i)}return{values:n,duplicates:[...r].sort()}}function _e(e,t,n){let r=H(t,a=>a.name),i=H(n,a=>a.name);(r.duplicates.length>0||i.duplicates.length>0)&&C(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:r.duplicates,after:i.duplicates});for(let a of[...new Set([...r.values.keys(),...i.values.keys()])].sort()){let o=r.values.get(a),l=i.values.get(a),d=`$.layers[${a}]`;if(!o&&l){C(e,{kind:"layer-added",path:d,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:l});continue}if(o&&!l){C(e,{kind:"layer-removed",path:d,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:o});continue}!o||!l||(L(e,`${d}.patterns`,o.patterns,l.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),L(e,`${d}.exclude`,o.exclude,l.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."}),L(e,`${d}.forbiddenGlobals`,o.forbiddenGlobals,l.forbiddenGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),S(o.intentPrefixes).join("\0")!==S(l.intentPrefixes).join("\0")&&C(e,{kind:"intent-prefixes-changed",path:`${d}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:S(o.intentPrefixes),after:S(l.intentPrefixes)}),j(e,`${d}.mayImportInfrastructure`,o.mayImportInfrastructure===!0,l.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),j(e,`${d}.optional`,o.optional===!0,l.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active."))}}function Me(e,t,n){let r=o=>`${o.from}->${o.to}`,i=H(t,r),a=H(n,r);(i.duplicates.length>0||a.duplicates.length>0)&&C(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:i.duplicates,after:a.duplicates});for(let o of[...new Set([...i.values.keys(),...a.values.keys()])].sort()){let l=i.values.get(o),d=a.values.get(o),u=`$.rules[${o}]`;if(!l&&d){d.allowed===!1&&C(e,{kind:"deny-added",path:u,classification:"strengthening",message:"A denied dependency edge was added.",after:d});continue}if(l&&!d){l.allowed===!1&&C(e,{kind:"deny-removed",path:u,classification:"weakening",message:"A denied dependency edge was removed.",before:l});continue}if(!l||!d)continue;l.allowed!==d.allowed&&C(e,{kind:d.allowed?"deny-disabled":"deny-enabled",path:`${u}.allowed`,classification:d.allowed?"weakening":"strengthening",message:d.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:l.allowed,after:d.allowed});let m=l.peerIsolation===!0,g=d.peerIsolation===!0;if(m!==g){let s=l.from===l.to&&d.from===d.to;C(e,{kind:g?"peer-isolation-enabled":"peer-isolation-disabled",path:`${u}.peerIsolation`,classification:s?g?"strengthening":"weakening":"judgment-required",message:s?g?"Cross-slice dependencies inside this layer are now denied.":"Cross-slice dependencies inside this layer are no longer denied.":"Changing peer isolation on a cross-layer edge changes the denial scope.",before:m,after:g})}S(l.sliceFolders).join("\0")!==S(d.sliceFolders).join("\0")&&C(e,{kind:"slice-folders-changed",path:`${u}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:S(l.sliceFolders),after:S(d.sliceFolders)})}}function Ne(e,t,n){let r=t.safety??{},i=n.safety??{};for(let a of["maxTsSuppressions","maxAnyCasts"]){let o=r[a]??0,l=i[a]??0;o!==l&&C(e,{kind:l>o?"threshold-raised":"threshold-lowered",path:`$.safety.${a}`,classification:l>o?"weakening":"strengthening",message:l>o?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:o,after:l})}for(let a of["allowInMemory","allowDisabledPeerIsolation"])j(e,`$.safety.${a}`,r[a]===!0,i[a]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}function De(e){return e.some(t=>t.classification==="weakening")?"weakening":e.some(t=>t.classification==="judgment-required")?"judgment-required":e.some(t=>t.classification==="strengthening")?"strengthening":"neutral"}function fe(e,t){let n=[];L(n,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),L(n,"$.exclude",e.exclude,t.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional project paths are excluded from governance.",removedMessage:"Fewer project paths are excluded from governance."}),L(n,"$.dynamicImportAllowlist",e.dynamicImportAllowlist,t.dynamicImportAllowlist,{added:"weakening",removed:"strengthening",addedMessage:"Additional files may use non-literal dynamic imports.",removedMessage:"Fewer files may use non-literal dynamic imports."}),j(n,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let r={off:0,soft:1,"framework-soft":1,strict:2},i=e.cyclePolicy??"strict",a=t.cyclePolicy??"strict";if(i!==a){let o=r[a]===r[i]?"judgment-required":r[a]>r[i]?"strengthening":"weakening";C(n,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:o,message:"The cycle enforcement level changed.",before:i,after:a})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&C(n,{kind:"framework-overlay-changed",path:"$.frameworkOverlay",classification:"judgment-required",message:"The framework overlay changed and may alter effective layer matching.",before:e.frameworkOverlay??null,after:t.frameworkOverlay??null}),_e(n,e.layers,t.layers),Me(n,e.rules,t.rules),Ne(n,e,t),n.sort((o,l)=>o.path.localeCompare(l.path)||o.id.localeCompare(l.id)),{schemaVersion:"1.0",classification:De(n),findings:n}}function ue(e,t){if(!e||e.schemaVersion!=="1.0"||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(i=>typeof i!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=S(e.findingIds),r=S(t.findingIds);return n.length===r.length&&n.every((i,a)=>i===r[a])}function k(e){return`${e.from}->${e.to}`}function N(e,t,n,r="dependency"){return{id:`${e}:${r}:${k(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${k(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${k(t)}, then preflight again.`}:e==="unplanned"?{nextAction:`Remove the unplanned dependency ${k(t)} from the candidate, then preflight again.`}:{}}}function J(e){let t=[],n=new Map(e.changeMap.map.files.map(s=>[s.path,s])),r=new Map(e.changes.map(s=>[s.path,s])),i=new Map(e.changeMap.map.dependencies.map(s=>[k(s),s])),a=new Map(e.baseDependencies.map(s=>[k(s),s])),o=new Map(e.candidateDependencies.map(s=>[k(s),s]));for(let s of[...n.values()].sort((c,p)=>c.path.localeCompare(p.path))){let c=r.get(s.path);c?c.operation!==s.operation?t.push({id:`contradictory:file:${s.path}`,classification:"contradictory",subject:"file",path:s.path,expectedOperation:s.operation,actualOperation:c.operation,message:`${s.path} was planned as ${s.operation} but the actual operation is ${c.operation}.`,nextAction:`Change ${s.path} to the planned ${s.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${s.path}`,classification:"satisfied",subject:"file",path:s.path,expectedOperation:s.operation,actualOperation:c.operation,message:`${s.path} matches the planned ${s.operation} operation.`}):t.push({id:`missing:file:${s.path}`,classification:"missing",subject:"file",path:s.path,expectedOperation:s.operation,message:`${s.path} was planned as ${s.operation} but is absent from the actual change.`,nextAction:`${s.operation[0].toUpperCase()}${s.operation.slice(1)} ${s.path} in the complete change set, then preflight again.`})}for(let s of[...r.values()].sort((c,p)=>c.path.localeCompare(p.path)))n.has(s.path)||t.push({id:`unplanned:file:${s.path}`,classification:"unplanned",subject:"file",path:s.path,actualOperation:s.operation,message:`${s.path} has an unplanned ${s.operation} operation.`,nextAction:`Remove ${s.path} from the change set, then preflight again.`});let l=new Set;for(let s of[...i.values()].sort((c,p)=>k(c).localeCompare(k(p)))){if(o.has(k(s))){t.push(N("satisfied",s,`${s.from} -> ${s.to} exists in the candidate architecture.`));continue}let c={from:s.to,to:s.from};o.has(k(c))?(l.add(k(c)),t.push(N("contradictory",s,`${s.from} -> ${s.to} was planned, but the candidate contains the reverse edge.`))):t.push(N("missing",s,`${s.from} -> ${s.to} is absent from the candidate architecture.`))}let d=new Set([...n.keys(),...r.keys()]);for(let[s,c]of[...o].sort(([p],[f])=>p.localeCompare(f)))a.has(s)||i.has(s)||l.has(s)||!d.has(c.from)&&!d.has(c.to)||t.push({...N("unplanned",c,`${c.from} -> ${c.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let u=new Set(e.changeMap.map.files.filter(s=>s.operation==="delete").map(s=>s.path));for(let[s,c]of[...a].sort(([p],[f])=>p.localeCompare(f)))o.has(s)||u.has(c.from)||u.has(c.to)||!d.has(c.from)&&!d.has(c.to)||t.push({...N("unplanned",c,`${c.from} -> ${c.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let m={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((s,c)=>m[s.classification]-m[c.classification]||(s.subject===c.subject?0:s.subject==="file"?-1:1)||s.id.localeCompare(c.id));let g={satisfied:t.filter(s=>s.classification==="satisfied").length,missing:t.filter(s=>s.classification==="missing").length,contradictory:t.filter(s=>s.classification==="contradictory").length,unplanned:t.filter(s=>s.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:g.missing===0&&g.contradictory===0&&g.unplanned===0,behavioralCompletion:"not-evaluated",summary:g,findings:t}}function ge(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return e.typeOnly||e.targetTypeOnlyExports||e.namedBindingsTypeOnly?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":e.peerIsolation?"Extract the shared dependency to a shared layer, then preflight again.":`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, then preflight again.`;case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";default:return`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}var Z="1.0";var V=class extends Error{issues;source;constructor(t,n){super(`Invalid architecture change map (${t}):
|
|
6
|
+
${n.map(r=>`- ${r.path}: ${r.message}`).join(`
|
|
7
|
+
`)}`),this.name="ArchitectureChangeMapValidationError",this.source=t,this.issues=n}};function Q(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function X(e,t,n,r){for(let i of Object.keys(e))t.includes(i)||r.push({path:`${n}.${i}`,message:"unknown field"})}function O(e,t,n,r){let i=e[t];if(typeof i=="string"&&i.length>0)return i;r.push({path:`${n}.${t}`,message:"must be a non-empty string"})}function Te(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let i of t.split("/"))if(!(!i||i==="."))if(i===".."){if(n.length===0)return;n.pop()}else n.push(i);let r=n.join("/");return r&&r===t?r:void 0}function Fe(e,t,n="architecture change map"){let r=[];if(!Q(e))throw new V(n,[{path:"$",message:"must be an object"}]);X(e,["$schema","schemaVersion","files","dependencies"],"$",r);let i=O(e,"$schema","$",r),a=O(e,"schemaVersion","$",r);a&&a!==Z&&r.push({path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(a)}; expected ${Z}`});let o=new Set(t.layers.map(p=>p.name)),l=[],d=new Set;!Array.isArray(e.files)||e.files.length===0?r.push({path:"$.files",message:"must be a non-empty array"}):e.files.forEach((p,f)=>{let h=`$.files[${f}]`;if(!Q(p)){r.push({path:h,message:"must be an object"});return}X(p,["path","operation","layer"],h,r);let y=O(p,"path",h,r),A=O(p,"operation",h,r),b=O(p,"layer",h,r),x=y?Te(y):void 0;y&&!x&&r.push({path:`${h}.path`,message:"must be a canonical project-relative path"}),A&&!["create","update","delete"].includes(A)&&r.push({path:`${h}.operation`,message:"must be create, update, or delete"}),b&&!o.has(b)&&r.push({path:`${h}.layer`,message:`references unknown layer ${JSON.stringify(b)}`}),x&&d.has(x)&&r.push({path:`${h}.path`,message:`duplicates planned path ${x}`}),x&&d.add(x);let U=x?M(x,t.layers):void 0;x&&b&&o.has(b)&&U!==b&&r.push({path:`${h}.layer`,message:U?`${x} resolves to ${U}, not ${b}`:`${x} is not assigned to an architecture layer`}),x&&A&&["create","update","delete"].includes(A)&&b&&l.push({path:x,operation:A,layer:b})});let u=[],m=new Map(l.map(p=>[p.path,p.operation])),g=new Set,s=e.dependencies??[];if(Array.isArray(s)?s.forEach((p,f)=>{let h=`$.dependencies[${f}]`;if(!Q(p)){r.push({path:h,message:"must be an object"});return}X(p,["from","to"],h,r);let y=O(p,"from",h,r),A=O(p,"to",h,r);y&&!d.has(y)&&r.push({path:`${h}.from`,message:`must reference a planned file path: ${y}`}),A&&!d.has(A)&&r.push({path:`${h}.to`,message:`must reference a planned file path: ${A}`}),y&&m.get(y)==="delete"&&r.push({path:`${h}.from`,message:`cannot depend from deleted file ${y}`}),A&&m.get(A)==="delete"&&r.push({path:`${h}.to`,message:`cannot depend on deleted file ${A}`}),y&&A&&y===A&&r.push({path:h,message:"must not declare a self dependency"});let b=y&&A?`${y}\0${A}`:void 0;b&&g.has(b)&&r.push({path:h,message:`duplicates dependency ${y} -> ${A}`}),b&&g.add(b),y&&A&&u.push({from:y,to:A})}):r.push({path:"$.dependencies",message:"must be an array"}),r.length>0)throw new V(n,r);let c={$schema:i,schemaVersion:Z,files:l.sort((p,f)=>p.path.localeCompare(f.path)),dependencies:u.sort((p,f)=>p.from.localeCompare(f.from)||p.to.localeCompare(f.to))};return{map:c,hash:$(E(c))}}function v(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function me(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function he(e,t){if(e.isImportDeclaration(t)){let n=t.importClause;if(!n)return!1;if(n.isTypeOnly)return!0;let r=n.namedBindings;return!!(r&&e.isNamedImports(r)&&r.elements.length>0&&r.elements.every(i=>i.isTypeOnly))}if(e.isExportDeclaration(t)){if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(r=>r.isTypeOnly))}return!1}function Ae(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=i=>i===t.fileName?t:void 0,r.fileExists=i=>i===t.fileName,r.readFile=i=>i===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}function ee(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function te(e,t,n,r){let i=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,a;try{a=i?t.getShorthandAssignmentValueSymbol(r.parent):ee(t,r)}catch{a=void 0}return!!a?.declarations?.some(o=>o.getSourceFile().fileName===n.fileName)}function je(e,t){let n,r=[],i=(o,l,d,u=!1)=>r.push({specifier:d,kind:l,line:me(t,o),typeOnly:u,unresolved:d===void 0,node:o}),a=o=>{if(e.isImportDeclaration(o))i(o,"import",v(e,o.moduleSpecifier),he(e,o));else if(e.isExportDeclaration(o)&&o.moduleSpecifier)i(o,"export",v(e,o.moduleSpecifier),he(e,o));else if(e.isImportEqualsDeclaration(o)&&e.isExternalModuleReference(o.moduleReference))i(o,"require",v(e,o.moduleReference.expression));else if(e.isCallExpression(o)){let l=o.expression.kind===e.SyntaxKind.ImportKeyword,u=e.isIdentifier(o.expression)&&o.expression.text==="require"&&!te(e,n??(n=Ae(e,t)),t,o.expression);(l||u)&&i(o,u?"require":"dynamic-import",v(e,o.arguments[0]))}e.forEachChild(o,a)};return a(t),r}function He(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let i=v(e,r.argumentExpression);if(i===void 0)return;n.unshift(i)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}function Ve(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 ye(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let r=n.length;r>=1;r-=1){let i=n.slice(0,r).join(".");if(e.has(i))return i}}function Ge(e,t,n){if(n.length===0)return[];let r=new Set(n),i=Ae(e,t),a=new Map,o=new Set;for(let s of t.statements)if(e.isVariableStatement(s))for(let c of s.declarationList.declarations)e.isIdentifier(c.name)&&o.add(c.name.text);let l=s=>{let c=He(e,s);if(!c)return;let p=ee(i,c.root),f=p?a.get(p):void 0;return f?[...f,...c.segments.slice(1)]:te(e,i,t,c.root)||o.has(c.root.text)?void 0:c.segments};for(let s of t.statements)if(e.isVariableStatement(s))for(let c of s.declarationList.declarations){if(!c.initializer||!e.isIdentifier(c.name))continue;let p=l(c.initializer),f=ee(i,c.name);!p||!f||a.set(f,p)}let d=[],u=new Set,m=(s,c)=>{let p=me(t,c),f=`${s}:${c.getStart(t)}`;u.has(f)||(u.add(f),d.push({name:s,line:p,node:c}))},g=s=>{let c=s.parent&&(e.isPropertyAccessExpression(s.parent)||e.isElementAccessExpression(s.parent))&&s.parent.expression===s;if((e.isPropertyAccessExpression(s)||e.isElementAccessExpression(s))&&!c){let p=l(s),f=p?ye(r,p):void 0;f&&m(f,s)}else e.isIdentifier(s)&&r.has(s.text)&&Ve(e,s)&&!te(e,i,t,s)&&m(s.text,s);if(e.isVariableDeclaration(s)&&e.isObjectBindingPattern(s.name)&&s.initializer){let p=l(s.initializer);if(p)for(let f of s.name.elements){if(!e.isIdentifier(f.name))continue;let h=f.propertyName?v(e,f.propertyName)??f.propertyName.text:f.name.text,y=ye(r,[...p,h]);y&&m(y,s.initializer)}}e.forEachChild(s,g)};return g(t),d}var ne={RAW_EVENT_PUBLISH:"Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts and tooling.",PUBLISH_MISSING_SOURCE:"Strict Ark publish calls must include metadata.source."};function Ce(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function Ue(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&Ce(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:ne.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:ne.PUBLISH_MISSING_SOURCE}),t}function be(e,t){let n=typeof e=="string"?ce(e,t):q(e,t);return{...n,policyHash:$(E(n.config))}}function mt(e){let t=be(e.baseConfig,e.baseSource??"base ark.config.json"),n=be(e.candidateConfig,e.candidateSource??"candidate ark.config.json"),r=fe(t.config,n.config),i=r.findings.filter(l=>l.classification==="weakening"||l.classification==="judgment-required").map(l=>l.id).sort(),a=i.length>0,o=a&&ue(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:i});return{schemaVersion:r.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:r.classification,findings:r.findings,blockingFindingIds:i,requiresAcknowledgement:a,acknowledged:o,valid:!a||o}}function T(e){let t=[];for(let n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."&&t.length>0&&t.at(-1)!==".."?t.pop():t.push(n));return t.join("/")}function Ie(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}function re(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}function G(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let r=t,i="";for(t+=1;t<e.length;t+=1){let a=e[t];if(a===n)return{value:i,offset:r,excerpt:e.slice(r,t+1)};a==="\\"&&t+1<e.length?(i+=e[t+1],t+=1):i+=a}}function D(e,t,n){return e.startsWith(t,n)&&!Ie(e[n-1])&&!Ie(e[n+t.length])}function Ke(e,t){return t=re(e,t+6),e[t]==="("?G(e,re(e,t+1)):Se(e,t,!0)}function qe(e,t){return Se(e,t+6,!1)}function Se(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(D(e,"from",t))return G(e,re(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return G(e,t);if(t>0&&(D(e,"import",t)||D(e,"export",t)))return}}function ze(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="/"&&e[n+1]==="/"){if(n=e.indexOf(`
|
|
8
|
+
`,n+2),n<0)break;continue}if(r==="/"&&e[n+1]==="*"){let a=e.indexOf("*/",n+2);if(a<0)break;n=a+1;continue}if(r==="'"||r==='"'||r==="`"){let a=G(e,n);a&&(n=a.offset+a.excerpt.length-1);continue}let i=D(e,"import",n)?Ke(e,n):D(e,"export",n)?qe(e,n):void 0;i&&t.push(i)}return t}function Ye(e,t){let n=[];for(let r of ze(e.content)){let i=r.value;if(!i.startsWith("."))continue;let a=e.content.slice(0,r.offset).split(`
|
|
9
|
+
`).length,o={kind:"import",file:e.path,line:a,excerpt:r.excerpt},l=We(e.path,i,t);n.push({from:e.path,specifier:i,to:l?.path??null,resolution:l?"resolved":"unresolved",fromLayer:e.layer,toLayer:l?.layer??null,evidence:o})}return n}function We(e,t,n){let r=e.split("/");r.pop();for(let a of t.split("/"))a==="."||a===""||(a===".."?r.pop():r.push(a));let i=r.join("/");for(let a of[i,`${i}.ts`,`${i}.tsx`,`${i}.mts`,`${i}.cts`,`${i}/index.ts`,`${i}/index.tsx`]){let o=n.get(a);if(o)return o}}function Je(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let i=W(t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});i&&n.push({ruleId:`layer-dependency:${i.from}->${i.to}`,message:i.message??`${i.from} must not depend on ${i.to}.`,edge:r,evidence:r.evidence})}return n}function ke(e){let t=e.files.map(o=>{let l=T(o.path);return{path:l,content:o.content,contentHash:$(o.content),layer:M(l,e.contract.config.layers)??null}}).sort((o,l)=>o.path.localeCompare(l.path)),n=new Map(t.map(o=>[o.path,o])),r=t.flatMap(o=>Ye(o,n)),i=[],a=Je(r,e.contract.config);return{ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:$(E(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(o=>o.name),edges:r,capabilityUses:i,violations:a}}}function Ze(e){let t=new Map(e.files.map(n=>[T(n.path),n]));for(let n of e.changes){let r=T(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return ke({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}function At(e){let t=`${e.evidence.file}:${e.evidence.line}`;if(!e.edge)return`${e.ruleId} at ${t}: ${e.message}`;let n=e.edge.to??e.edge.specifier;return`${e.ruleId} at ${t}: ${e.edge.from} imports ${n}. ${e.message}`}function Qe(e){let t=0,n=new Map,r=new Map,i=new Set,a=[],o=[],l=d=>{n.set(d,t),r.set(d,t),t+=1,a.push(d),i.add(d);for(let g of[...e.get(d)??[]].sort())e.has(g)&&(n.has(g)?i.has(g)&&r.set(d,Math.min(r.get(d)??0,n.get(g)??0)):(l(g),r.set(d,Math.min(r.get(d)??0,r.get(g)??0))));if(r.get(d)!==n.get(d))return;let u=[],m;do{if(m=a.pop(),m===void 0)break;i.delete(m),u.push(m)}while(m!==d);u.length>1&&o.push(u.sort())};for(let d of[...e.keys()].sort())n.has(d)||l(d);return o.sort((d,u)=>d[0].localeCompare(u[0])).map(d=>({ruleId:"CIRCULAR_DEPENDENCY",file:d[0],line:1,target:d.join(" \u2192 "),message:`Circular dependency among ${d.length} files: ${d.join(" \u2192 ")} \u2192 ${d[0]}.`,cycleKind:"value"}))}function Xe(e){let t=e.contentViolations.map(a=>({...a})),n=(e.warnings??[]).map(a=>({...a})),r=new Map(e.files.map(a=>[a,new Set]));for(let a of e.edges){if(a.to&&a.to!==a.from&&!a.typeOnly&&r.has(a.from)&&r.get(a.from)?.add(a.to),!a.to||!a.toLayer)continue;let o=W(e.rules,a.fromLayer,a.toLayer,{fromPath:a.from,toPath:a.to,layers:e.config.layers});if(!o)continue;let l=!!o.peerIsolation;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:a.from,line:a.line,fromLayer:a.fromLayer,toLayer:a.toLayer,target:a.to,...a.typeOnly?{typeOnly:!0}:{},...a.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...a.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...a.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!l&&a.portProofEligible?{portProofEligible:!0}:{},...a.kind?{edgeKind:a.kind}:{},...l?{peerIsolation:!0}:{},message:o.message??(l?`${a.fromLayer} must not ${a.kind} another slice of ${a.toLayer} (${a.from} \u2192 ${a.to}). Extract shared code or use events/ports across slices.`:`${a.fromLayer} must not ${a.kind} ${a.toLayer}.`)})}let i=String(e.config.cyclePolicy??"strict").toLowerCase();if(i!=="off"){let a=Qe(r);i==="soft"||i==="framework-soft"?n.push(...a.map(o=>({...o,message:`${o.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...a)}return{violations:t,warnings:n,safety:e.safety}}function xe(e){return $(E(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}function Ct(e){let t=ke(e),n=new Map(t.ir.files.map(s=>[s.path,s])),r=[],i=new Set,a=[];for(let s of e.changes){let c=s.path.replace(/\\/g,"/"),p=T(s.path);if(!p||p===".."||p.startsWith("../")||c.startsWith("/")||/^[A-Za-z]:\//.test(c)||c.includes("\0")){a.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(i.has(p)){a.push({ruleId:"DUPLICATE_CHANGE_PATH",file:p,line:1,message:`The atomic change set contains more than one operation for ${p}.`});continue}i.add(p),"delete"in s&&s.delete&&!n.has(p)&&a.push({ruleId:"DELETE_TARGET_MISSING",file:p,line:1,message:`Cannot delete ${p} because it is not present in the supplied base tree.`}),r.push("delete"in s&&s.delete?{path:p,delete:!0}:{path:p,content:"content"in s?s.content:""})}e.changes.length===0&&a.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let o=Ze({...e,changes:r}),l=new Map(o.ir.files.map(s=>[s.path,s])),d=Xe({config:e.contract.config,rules:e.contract.config.rules,files:o.ir.files.map(s=>s.path),contentViolations:[],edges:o.ir.edges.filter(s=>!!s.fromLayer).map(s=>({from:s.from,fromLayer:s.fromLayer,...s.to?{to:s.to}:{},...s.toLayer?{toLayer:s.toLayer}:{},line:s.evidence.line,kind:"import"}))}),u=r.map(s=>{let c=T(s.path),p=n.get(c),f=l.get(c);return{path:c,operation:"delete"in s&&s.delete?"delete":p?"update":"create",...p?{beforeContentHash:p.contentHash}:{},...f?{candidateContentHash:f.contentHash}:{}}}).sort((s,c)=>s.path.localeCompare(c.path)),m=[...a,...d.violations].map(s=>({...s,nextAction:ge(s)})),g=e.changeMap?J({changeMap:e.changeMap,changes:u,baseDependencies:t.ir.edges.flatMap(s=>s.to?[{from:s.from,to:s.to}]:[]),candidateDependencies:o.ir.edges.flatMap(s=>s.to?[{from:s.from,to:s.to}]:[])}):void 0;return{schemaVersion:"1.0",valid:m.length===0&&(g?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:o.ir.compilerOptionsHash,baseTreeHash:xe(t.ir.files),candidateTreeHash:xe(o.ir.files),...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...g?{convergence:g}:{},changes:u,violations:m,warnings:d.warnings}}function I(e,t,n={}){return{ruleId:e,message:t,...n}}function bt(e){let{config:t,rules:n,files:r,manifest:i}=e,a=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(c=>typeof c!="string"))&&a.push(I("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","dynamicImportAllowlist must be an array of file globs.")),t.safety!==void 0&&(t.safety===null||typeof t.safety!="object"||Array.isArray(t.safety)))a.push(I("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let c of["maxTsSuppressions","maxAnyCasts"]){let p=t.safety[c];p!==void 0&&(!Number.isInteger(p)||p<0)&&a.push(I("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${c} must be a non-negative integer.`))}let o=Array.isArray(t.layers)?t.layers:[],l=Array.isArray(i?.architecture?.layers)?i.architecture.layers:[],d=new Set([...o.map(c=>c.name).filter(Boolean),...l.map(c=>c.name).filter(c=>!!c)]);o.length===0&&a.push(I("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let u=new Set,m=new Set;for(let c of o){if(!c.name){a.push(I("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}u.has(c.name)&&m.add(c.name),u.add(c.name),c.forbiddenGlobals!==void 0&&(!Array.isArray(c.forbiddenGlobals)||c.forbiddenGlobals.some(f=>typeof f!="string"))&&a.push(I("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${c.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:c.name}));let p=Array.isArray(c.patterns)?c.patterns:[];if(p.length===0){a.push(I("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${c.name}" has no file patterns and will never classify files.`,{layer:c.name}));continue}for(let f of p){let h;try{h=_(f)}catch(y){a.push(I("CONFIG_INVALID_LAYER_PATTERN",`Layer "${c.name}" has an invalid pattern "${f}": ${y instanceof Error?y.message:String(y)}`,{layer:c.name,pattern:f}));continue}!r.some(y=>h.test(y))&&!c.optional&&a.push(I("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${c.name}" pattern "${f}" matched no included files.`,{layer:c.name,pattern:f,failsStrict:!1}))}}for(let c of m)a.push(I("CONFIG_DUPLICATE_LAYER",`Layer "${c}" is configured more than once.`,{layer:c}));if(d.size>0)for(let c of n??[])c.from&&!d.has(c.from)&&a.push(I("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${c.from}".`,{fromLayer:c.from,toLayer:c.to})),c.to&&!d.has(c.to)&&a.push(I("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${c.to}".`,{fromLayer:c.from,toLayer:c.to}));let g=new Set;if(o.length>1)for(let c of r){let p=-1,f=[];for(let h of o)for(let y of h.patterns??[]){if(!_(y).test(c))continue;let A=Y(y);A>p?(p=A,f=[h.name]):A===p&&!f.includes(h.name)&&f.push(h.name)}f.length>1&&g.add([...f].sort().join(" + "))}g.size>0&&a.push(I("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...g].join(", ")}.`,{pairs:[...g]}));let s=r.filter(c=>!M(c,o));return s.length>0&&a.push(I("CONFIG_UNCLASSIFIED_FILES",`${s.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:s.length,samples:s.slice(0,5)})),a}export{ne as SOURCE_POLICY_MESSAGES,J as analyzeArchitectureConvergence,Ze as analyzeChange,mt as analyzePolicyDelta,ke as analyzeProject,Ue as classifyPublishFacts,bt as collectAnalysisConfigWarnings,Ge as collectForbiddenCapabilityUses,Qe as detectArchitectureCycles,Xe as evaluateArchitectureGraph,At as explainViolation,je as extractSemanticDependencies,Fe as loadArchitectureChangeMap,be as loadContract,Ce as looksLikeArkIntent,Ct as preflightChange};
|