arkgate 4.2.0 → 4.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +86 -4
  2. package/README.md +20 -6
  3. package/bin/ark-mcp-runtime.mjs +64 -0
  4. package/bin/ark-shared.mjs +16 -4
  5. package/bin/ark.mjs +55 -1
  6. package/bin/lib/adapter-contract.mjs +88 -5
  7. package/bin/lib/agent-projection-command.mjs +396 -0
  8. package/bin/lib/agent-projection.mjs +319 -0
  9. package/bin/lib/agent-skills-package.mjs +266 -0
  10. package/bin/lib/baseline-key.mjs +32 -0
  11. package/bin/lib/ci-and-commands.mjs +44 -0
  12. package/bin/lib/diagnostic-catalog.mjs +155 -0
  13. package/bin/lib/physical-cohesion.mjs +2 -1
  14. package/bin/lib/status-command.mjs +369 -0
  15. package/bin/lib/status-manifest.mjs +394 -0
  16. package/dist/eslint/index.cjs +3 -3
  17. package/dist/eslint/index.js +3 -3
  18. package/dist/index.cjs +46 -11
  19. package/dist/index.d.ts +729 -6
  20. package/dist/index.js +46 -11
  21. package/docs/README.md +6 -6
  22. package/docs/agent-guide.md +112 -14
  23. package/docs/configuration.md +7 -0
  24. package/docs/develop.md +8 -0
  25. package/docs/diagnostics.md +606 -0
  26. package/docs/package-surface.md +19 -8
  27. package/docs/product-voice.md +45 -0
  28. package/docs/use.md +23 -0
  29. package/package.json +11 -1
  30. package/schemas/ark.analysis-result.schema.json +14 -1
  31. package/schemas/ark.status-manifest.schema.json +244 -0
  32. package/server.json +2 -2
  33. package/templates/agent-skills/README.md +59 -0
  34. package/templates/agent-skills/ark-adopt/SKILL.md +171 -0
  35. package/templates/agent-skills/ark-architect/SKILL.md +175 -0
  36. package/templates/agent-skills/ark-autopilot/SKILL.md +242 -0
  37. package/templates/agent-skills/ark-contract/SKILL.md +136 -0
  38. package/templates/agent-skills/ark-coverage/SKILL.md +167 -0
  39. package/templates/agent-skills/ark-explain/SKILL.md +210 -0
  40. package/templates/agent-skills/ark-explore/SKILL.md +377 -0
  41. package/templates/agent-skills/ark-fix/SKILL.md +185 -0
  42. package/templates/agent-skills/ark-loop/SKILL.md +180 -0
  43. package/templates/agent-skills/ark-place/SKILL.md +162 -0
  44. package/templates/agent-skills/ark-runtime/SKILL.md +120 -0
  45. package/templates/agent-skills/ark-think/SKILL.md +133 -0
  46. package/templates/agent-skills/ark-upgrade/SKILL.md +218 -0
@@ -0,0 +1,394 @@
1
+ /**
2
+ * GENERATED FILE — do not edit by hand.
3
+ *
4
+ * Canonical algorithm: src/domain/statusManifest.ts
5
+ * Regenerate: node scripts/generate-cli-pure.mjs
6
+ * Drift check: node scripts/generate-cli-pure.mjs --check
7
+ *
8
+ * Pure CLI helper (bin/lib/status-manifest.mjs). Zero Node I/O.
9
+ */
10
+
11
+ export const ARK_STATUS_MANIFEST_SCHEMA_VERSION = '1.0';
12
+ export const ARK_STATUS_MANIFEST_SCHEMA_URL = 'https://unpkg.com/arkgate@4/schemas/ark.status-manifest.schema.json';
13
+ const PROJECT_ID_PATTERN = /^sha256:[a-f0-9]{64}$/;
14
+ /**
15
+ * Evaluate project binding for status without filesystem.
16
+ * Paths must already be canonical absolute strings when compared.
17
+ */
18
+ export function evaluateStatusBinding(input) {
19
+ const expectation = input.expectation;
20
+ if (expectation == null ||
21
+ (expectation.expectedRoot === undefined && expectation.expectedProjectId === undefined)) {
22
+ // Local CLI / unbound MCP: this process is bound to resolvedRoot when known.
23
+ return {
24
+ status: 'matched',
25
+ authoritative: Boolean(input.resolvedRoot),
26
+ };
27
+ }
28
+ if (expectation && typeof expectation !== 'object') {
29
+ return {
30
+ status: 'mismatch',
31
+ authoritative: false,
32
+ code: 'INVALID_PROJECT_EXPECTATION',
33
+ message: 'project must be an object containing expectedRoot and/or expectedProjectId.',
34
+ };
35
+ }
36
+ const rawRoot = expectation.expectedRoot;
37
+ const rawId = expectation.expectedProjectId;
38
+ if (rawRoot !== undefined &&
39
+ (typeof rawRoot !== 'string' || rawRoot.trim() === '')) {
40
+ return {
41
+ status: 'mismatch',
42
+ authoritative: false,
43
+ code: 'INVALID_PROJECT_EXPECTATION',
44
+ message: 'project.expectedRoot must be a non-empty absolute path.',
45
+ };
46
+ }
47
+ if (rawId !== undefined && (typeof rawId !== 'string' || !PROJECT_ID_PATTERN.test(rawId))) {
48
+ return {
49
+ status: 'mismatch',
50
+ authoritative: false,
51
+ code: 'INVALID_PROJECT_EXPECTATION',
52
+ message: 'project.expectedProjectId must be a sha256:<64 lowercase hex> identity.',
53
+ };
54
+ }
55
+ if (rawRoot === undefined && rawId !== undefined) {
56
+ if (input.projectId && rawId !== input.projectId) {
57
+ return {
58
+ status: 'mismatch',
59
+ authoritative: false,
60
+ expectedProjectId: rawId,
61
+ code: 'PROJECT_ID_MISMATCH',
62
+ message: `Expected project id ${rawId}, but this process is bound to ${input.projectId}.`,
63
+ };
64
+ }
65
+ return {
66
+ status: 'unverified',
67
+ authoritative: false,
68
+ expectedProjectId: rawId,
69
+ message: 'project.expectedProjectId matched or could not be compared, but expectedRoot is required for an authoritative workspace binding.',
70
+ };
71
+ }
72
+ const relation = input.expectedRootRelation ?? 'unknown';
73
+ if (relation === 'outside') {
74
+ return {
75
+ status: 'mismatch',
76
+ authoritative: false,
77
+ expectedRoot: rawRoot,
78
+ expectedProjectId: rawId,
79
+ code: 'PROJECT_ROOT_MISMATCH',
80
+ message: `Expected workspace ${rawRoot}, but this process is bound to ${input.resolvedRoot}.`,
81
+ };
82
+ }
83
+ if (relation === 'unknown') {
84
+ return {
85
+ status: 'unverified',
86
+ authoritative: false,
87
+ expectedRoot: rawRoot,
88
+ expectedProjectId: rawId,
89
+ message: 'Could not prove expectedRoot against the resolved project root (stale or incomplete path evidence).',
90
+ };
91
+ }
92
+ if (relation === 'descendant' && rawId === undefined) {
93
+ return {
94
+ status: 'unverified',
95
+ authoritative: false,
96
+ expectedRoot: rawRoot,
97
+ message: `Expected workspace ${rawRoot} is inside this project, but an exact project root is required for the initial authoritative handshake.`,
98
+ };
99
+ }
100
+ if (rawId !== undefined && input.projectId && rawId !== input.projectId) {
101
+ return {
102
+ status: 'mismatch',
103
+ authoritative: false,
104
+ expectedRoot: rawRoot,
105
+ expectedProjectId: rawId,
106
+ code: 'PROJECT_ID_MISMATCH',
107
+ message: `Expected project id ${rawId}, but this process is bound to ${input.projectId}.`,
108
+ };
109
+ }
110
+ if (relation === 'exact' || (relation === 'descendant' && rawId && rawId === input.projectId)) {
111
+ return {
112
+ status: 'matched',
113
+ authoritative: true,
114
+ ...(rawRoot ? { expectedRoot: rawRoot } : {}),
115
+ ...(rawId ? { expectedProjectId: rawId } : {}),
116
+ };
117
+ }
118
+ return {
119
+ status: 'unverified',
120
+ authoritative: false,
121
+ expectedRoot: rawRoot,
122
+ expectedProjectId: rawId,
123
+ message: 'Project expectation could not be fully verified.',
124
+ };
125
+ }
126
+ /**
127
+ * Map write-path evidence to the closed activation writePath vocabulary.
128
+ * Soft hosts never become hard; missing analysis → unavailable.
129
+ */
130
+ export function classifyStatusWritePath(input) {
131
+ if (input.writePathUnavailable === true)
132
+ return 'unavailable';
133
+ if (input.softWriteHost === true)
134
+ return 'advisory';
135
+ if (input.hardWriteActive === true)
136
+ return 'hard';
137
+ // Hard-capable host without proven hard → advisory (honest, not hard).
138
+ const host = typeof input.activeHost === 'string' ? input.activeHost.trim().toLowerCase() : '';
139
+ if (!host || host === 'unknown')
140
+ return 'unavailable';
141
+ return 'advisory';
142
+ }
143
+ export function defaultHonestLabel(writePath, host) {
144
+ const hostLabel = host && host !== 'unknown' ? host : 'unknown-host';
145
+ if (writePath === 'hard') {
146
+ return `Local write is hard for ${hostLabel} when the covered PreToolUse path is active; CI --strict-merge remains the merge backstop.`;
147
+ }
148
+ if (writePath === 'advisory') {
149
+ return `Local write is advisory for ${hostLabel}; hard merge boundary is a required status running arkgate-check --strict-merge (alias ark-check).`;
150
+ }
151
+ return 'Write-path activation is unavailable or unverified for this invocation (no active host / incomplete evidence).';
152
+ }
153
+ /**
154
+ * Deterministic next action from residual facts (no LLM).
155
+ * Prefer explicit override from productHonesty when provided.
156
+ */
157
+ export function resolveStatusNextAction(facts, binding, activation, lastCheck, rules) {
158
+ if (facts.nextActionOverride?.id && facts.nextActionOverride.summary) {
159
+ return {
160
+ id: facts.nextActionOverride.id,
161
+ summary: facts.nextActionOverride.summary,
162
+ };
163
+ }
164
+ if (binding.status === 'mismatch') {
165
+ return {
166
+ id: 'rebind-project-identity',
167
+ summary: binding.message ||
168
+ 'Project expectation does not match this process — call ark_identity / ark status with the correct expectedRoot (and projectId for descendants).',
169
+ };
170
+ }
171
+ if (binding.status === 'unverified' && facts.expectation) {
172
+ return {
173
+ id: 'complete-identity-handshake',
174
+ summary: binding.message ||
175
+ 'Supply project.expectedRoot at the exact project root (and expectedProjectId for descendants) for authoritative status.',
176
+ };
177
+ }
178
+ if (!facts.resolvedConfigPath) {
179
+ return {
180
+ id: 'run-ark-start',
181
+ summary: 'No ark.config.json found — run ark start (preview) then ark start --apply.',
182
+ };
183
+ }
184
+ if (lastCheck.verdict === 'fail' || (lastCheck.activeViolations ?? 0) > 0) {
185
+ return {
186
+ id: 'fix-active-violations',
187
+ summary: `Clear ${lastCheck.activeViolations ?? 'active'} blocking architecture finding(s), then re-run ark-check (or ark-check --doctor).`,
188
+ };
189
+ }
190
+ if (lastCheck.verdict === 'incomplete') {
191
+ return {
192
+ id: 'restore-complete-analysis',
193
+ summary: 'Last check was incomplete — restore TypeScript/analysis inputs and re-run ark-check.',
194
+ };
195
+ }
196
+ if (lastCheck.verdict == null && lastCheck.at == null) {
197
+ return {
198
+ id: 'run-ark-check',
199
+ summary: 'No last-check snapshot yet — run ark-check --report (or --doctor) to freeze session evidence.',
200
+ };
201
+ }
202
+ if (activation.writePath === 'unavailable') {
203
+ return {
204
+ id: 'install-write-path',
205
+ summary: 'Write path is unavailable — install agent gates for your host (ark start / --install-agent-gates) and keep required CI --strict-merge.',
206
+ };
207
+ }
208
+ if (activation.writePath === 'advisory') {
209
+ return {
210
+ id: 'keep-ci-merge-hard',
211
+ summary: 'Local write is advisory for this host — keep a required GitHub status on arkgate-check --strict-merge as the hard merge boundary.',
212
+ };
213
+ }
214
+ if (rules.arkRulesLoaded && (rules.frozenResidual ?? 0) > 0) {
215
+ return {
216
+ id: 'review-arkrules-residual',
217
+ summary: 'ArkRules residual remains frozen — review inventory debt without claiming a score.',
218
+ };
219
+ }
220
+ return {
221
+ id: 'stay-enforced',
222
+ summary: 'Contract looks enforceable for this session — keep writing through the gate and re-check after structural edits.',
223
+ };
224
+ }
225
+ export function buildStatusManifest(facts) {
226
+ const resolvedRoot = typeof facts.resolvedRoot === 'string' && facts.resolvedRoot.length > 0
227
+ ? facts.resolvedRoot
228
+ : '.';
229
+ const projectId = typeof facts.projectId === 'string' && PROJECT_ID_PATTERN.test(facts.projectId)
230
+ ? facts.projectId
231
+ : null;
232
+ const binding = evaluateStatusBinding({
233
+ resolvedRoot,
234
+ projectId,
235
+ expectation: facts.expectation,
236
+ expectedRootRelation: facts.expectedRootRelation,
237
+ });
238
+ const hostRaw = typeof facts.activeHost === 'string' ? facts.activeHost.trim().toLowerCase() : '';
239
+ const host = hostRaw && hostRaw !== 'unknown' ? hostRaw : hostRaw === 'unknown' ? 'unknown' : null;
240
+ const writePath = classifyStatusWritePath({
241
+ hardWriteActive: facts.hardWriteActive,
242
+ softWriteHost: facts.softWriteHost,
243
+ writePathUnavailable: facts.writePathUnavailable,
244
+ activeHost: host,
245
+ });
246
+ const honestLabel = typeof facts.honestLabel === 'string' && facts.honestLabel.trim().length > 0
247
+ ? facts.honestLabel.trim()
248
+ : defaultHonestLabel(writePath, host);
249
+ const lastCheck = {
250
+ at: typeof facts.lastCheckAt === 'string' ? facts.lastCheckAt : null,
251
+ verdict: facts.lastCheckVerdict === 'pass' ||
252
+ facts.lastCheckVerdict === 'fail' ||
253
+ facts.lastCheckVerdict === 'incomplete'
254
+ ? facts.lastCheckVerdict
255
+ : null,
256
+ activeViolations: numberOrNull(facts.activeViolations),
257
+ frozenResidual: numberOrNull(facts.frozenResidual),
258
+ };
259
+ const rules = {
260
+ arkRulesLoaded: facts.arkRulesLoaded === true,
261
+ inventoried: numberOrNull(facts.rulesInventoried),
262
+ underContract: numberOrNull(facts.rulesUnderContract),
263
+ frozenResidual: numberOrNull(facts.rulesFrozenResidual),
264
+ };
265
+ const activation = {
266
+ writePath,
267
+ host,
268
+ honestLabel,
269
+ };
270
+ const projectIdentity = {
271
+ projectId,
272
+ resolvedRoot,
273
+ resolvedConfigPath: typeof facts.resolvedConfigPath === 'string' && facts.resolvedConfigPath.length > 0
274
+ ? facts.resolvedConfigPath
275
+ : null,
276
+ binding: binding.status,
277
+ authoritative: binding.authoritative,
278
+ ...(binding.code ? { code: binding.code } : {}),
279
+ ...(binding.message ? { message: binding.message } : {}),
280
+ };
281
+ return {
282
+ schemaVersion: ARK_STATUS_MANIFEST_SCHEMA_VERSION,
283
+ arkgateVersion: typeof facts.arkgateVersion === 'string' && facts.arkgateVersion.length > 0
284
+ ? facts.arkgateVersion
285
+ : 'unknown',
286
+ projectIdentity,
287
+ activation,
288
+ lastCheck,
289
+ rules,
290
+ nextAction: resolveStatusNextAction(facts, binding, activation, lastCheck, rules),
291
+ };
292
+ }
293
+ function numberOrNull(value) {
294
+ if (value == null)
295
+ return null;
296
+ const n = Number(value);
297
+ if (!Number.isFinite(n) || n < 0)
298
+ return null;
299
+ return Math.floor(n);
300
+ }
301
+ /** JSON Schema for the public status manifest (package export + agents). */
302
+ export const ARK_STATUS_MANIFEST_SCHEMA = {
303
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
304
+ $id: ARK_STATUS_MANIFEST_SCHEMA_URL,
305
+ title: 'ArkGate status manifest',
306
+ description: 'Unified session/project status snapshot for agents (identity, activation honesty, last check, rules counts, next action). Not a score.',
307
+ type: 'object',
308
+ additionalProperties: false,
309
+ required: [
310
+ 'schemaVersion',
311
+ 'arkgateVersion',
312
+ 'projectIdentity',
313
+ 'activation',
314
+ 'lastCheck',
315
+ 'rules',
316
+ 'nextAction',
317
+ ],
318
+ properties: {
319
+ schemaVersion: { const: ARK_STATUS_MANIFEST_SCHEMA_VERSION },
320
+ arkgateVersion: { type: 'string', minLength: 1 },
321
+ projectIdentity: {
322
+ type: 'object',
323
+ additionalProperties: false,
324
+ required: [
325
+ 'projectId',
326
+ 'resolvedRoot',
327
+ 'resolvedConfigPath',
328
+ 'binding',
329
+ 'authoritative',
330
+ ],
331
+ properties: {
332
+ projectId: {
333
+ anyOf: [
334
+ { type: 'string', pattern: '^sha256:[a-f0-9]{64}$' },
335
+ { type: 'null' },
336
+ ],
337
+ },
338
+ resolvedRoot: { type: 'string', minLength: 1 },
339
+ resolvedConfigPath: { anyOf: [{ type: 'string', minLength: 1 }, { type: 'null' }] },
340
+ binding: { enum: ['matched', 'unverified', 'mismatch'] },
341
+ authoritative: { type: 'boolean' },
342
+ code: {
343
+ enum: [
344
+ 'PROJECT_ROOT_MISMATCH',
345
+ 'PROJECT_ID_MISMATCH',
346
+ 'INVALID_PROJECT_EXPECTATION',
347
+ ],
348
+ },
349
+ message: { type: 'string', minLength: 1 },
350
+ },
351
+ },
352
+ activation: {
353
+ type: 'object',
354
+ additionalProperties: false,
355
+ required: ['writePath', 'host', 'honestLabel'],
356
+ properties: {
357
+ writePath: { enum: ['hard', 'advisory', 'unavailable'] },
358
+ host: { anyOf: [{ type: 'string', minLength: 1 }, { type: 'null' }] },
359
+ honestLabel: { type: 'string', minLength: 1 },
360
+ },
361
+ },
362
+ lastCheck: {
363
+ type: 'object',
364
+ additionalProperties: false,
365
+ required: ['at', 'verdict', 'activeViolations', 'frozenResidual'],
366
+ properties: {
367
+ at: { anyOf: [{ type: 'string', minLength: 1 }, { type: 'null' }] },
368
+ verdict: { anyOf: [{ enum: ['pass', 'fail', 'incomplete'] }, { type: 'null' }] },
369
+ activeViolations: { anyOf: [{ type: 'integer', minimum: 0 }, { type: 'null' }] },
370
+ frozenResidual: { anyOf: [{ type: 'integer', minimum: 0 }, { type: 'null' }] },
371
+ },
372
+ },
373
+ rules: {
374
+ type: 'object',
375
+ additionalProperties: false,
376
+ required: ['arkRulesLoaded', 'inventoried', 'underContract', 'frozenResidual'],
377
+ properties: {
378
+ arkRulesLoaded: { type: 'boolean' },
379
+ inventoried: { anyOf: [{ type: 'integer', minimum: 0 }, { type: 'null' }] },
380
+ underContract: { anyOf: [{ type: 'integer', minimum: 0 }, { type: 'null' }] },
381
+ frozenResidual: { anyOf: [{ type: 'integer', minimum: 0 }, { type: 'null' }] },
382
+ },
383
+ },
384
+ nextAction: {
385
+ type: 'object',
386
+ additionalProperties: false,
387
+ required: ['id', 'summary'],
388
+ properties: {
389
+ id: { type: 'string', minLength: 1 },
390
+ summary: { type: 'string', minLength: 1 },
391
+ },
392
+ },
393
+ },
394
+ };
@@ -1,3 +1,3 @@
1
- "use strict";var Oe=Object.create;var L=Object.defineProperty;var _e=Object.getOwnPropertyDescriptor;var ve=Object.getOwnPropertyNames;var Pe=Object.getPrototypeOf,$e=Object.prototype.hasOwnProperty;var Te=(e,t)=>{for(var n in t)L(e,n,{get:t[n],enumerable:!0})},Q=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of ve(t))!$e.call(e,r)&&r!==n&&L(e,r,{get:()=>t[r],enumerable:!(s=_e(t,r))||s.enumerable});return e};var ee=(e,t,n)=>(n=e!=null?Oe(Pe(e)):{},Q(t||!e||!e.__esModule?L(n,"default",{value:e,enumerable:!0}):n,e)),je=e=>Q(L({},"__esModule",{value:!0}),e);var at={};Te(at,{default:()=>it,findConfigPath:()=>T,globToRegExp:()=>E,isEdgeDenied:()=>F,layerForRelativePath:()=>R,loadArkConfig:()=>j,noDeniedCapabilities:()=>Le,noDomainInfraImports:()=>we,noForbiddenGlobals:()=>Ne,noRawEventPublish:()=>Ee,patternSpecificity:()=>D,plugin:()=>$,readTsconfigPathAliases:()=>he,requirePublishSource:()=>Ce,resolveImportSpecifier:()=>ke,resolveRelativeImport:()=>Ae});module.exports=je(at);var S=ee(require("fs"),1),d=ee(require("path"),1);var te=new Map;function ne(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function O(e){let t="";for(let n=0;n<e.length;n+=1){let s=e[n];if(s==="\\"&&n+1<e.length){let r=e[n+1];if("*?{}[],".includes(r)||r==="\\"){t+="\\"+r,n+=1;continue}t+="/";continue}t+=s}return t}function Me(e){let t=0;for(let n=0;n<e.length;n+=1){let s=e[n];if(s==="\\"){n+=1;continue}if(s==="{")t+=1;else if(s==="}"&&(t-=1,t<0))return!1}return t===0}function E(e){let t=te.get(e);if(t)return t;let n=O(e),s=Me(n),r="",i=0;for(let c=0;c<n.length;c+=1){let g=n[c];g==="\\"&&c+1<n.length?(r+=ne(n[c+1]),c+=1):g==="*"?n[c+1]==="*"?n[c+2]==="/"?(r+="(?:.*/)?",c+=2):(r+=".*",c+=1):r+="[^/]*":g==="?"?r+="[^/]":g==="{"&&s?(r+="(?:",i+=1):g==="}"&&s&&i>0?(r+=")",i-=1):g===","&&s&&i>0?r+="|":r+=ne(g)}let l=new RegExp(`^${r}$`);return te.set(e,l),l}function De(e){return O(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}function D(e,t){let n=O(String(e)),s=De(n),r=n.replace(/\*/g,"").length,i=s.length*1e4+r;if(t==null||t==="")return i;let l=String(t).split(/[/\\]/).filter(Boolean);if(s.length===0)return r;let c=0,g=-1;for(let f of s){let p=-1;for(let o=c;o<l.length;o+=1)if(l[o]===f){p=o;break}if(p<0)return i;g=p,c=p+1}return(g+1)*1e6+s.length*1e4+r}function R(e,t){let n=String(e).split(/[/\\]/).join("/"),s,r=-1;for(let i of t??[])if(!(i.exclude??[]).some(l=>E(l).test(n))){for(let l of i.patterns??[])if(E(l).test(n)){let c=D(l,n);c>r&&(r=c,s=i.name)}}return s}function re(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),s=new Set(t.map(r=>String(r).toLowerCase()));for(let r=0;r<n.length-1;r+=1)if(s.has(n[r].toLowerCase()))return`${n[r].toLowerCase()}/${n[r+1].toLowerCase()}`}function Ve(e){let t=new Set;for(let n of e??[]){let r=O(String(n)).split("/").filter(Boolean);for(let i=0;i<r.length;i+=1){let l=r[i];if((l==="**"||l==="*")&&i>0){let c=r[i-1];c&&!c.includes("*")&&!c.includes("{")&&!c.includes("}")&&t.add(c)}}}return[...t]}function Fe(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(r=>typeof r=="string"&&r.length>0);let s=(n??[]).find(r=>r.name===t);return Ve(s?.patterns)}function V(e,t,n,s){for(let r of e??[])if(!(r.from!==t||r.to!==n)&&r.allowed===!1){if(r.peerIsolation){let i=s?.fromPath,l=s?.toPath;if(!i||!l)return r;let c=Fe(r,t,s?.layers);if(c.length===0)return r;let g=re(i,c),f=re(l,c);if(!g||!f||g!==f)return r;continue}if(t!==n)return r}}function F(e,t,n,s){return V(e,t,n,s)!==void 0}var He=["**/*.gen.ts","**/*.gen.tsx","**/*.generated.ts","**/*.generated.tsx"];function Ke(e){let t=Array.isArray(e?.exclude)?e.exclude.filter(s=>typeof s=="string"):[];return[...e?.excludeGenerated===!1?[]:He,...t]}function se(e,t){let n=String(e).split(/[/\\]/).join("/");return Ke(t).some(s=>E(s).test(n))}var oe=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),Ge=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),pt=Object.freeze(Object.keys(Ge).sort()),H=Object.freeze({fs:"filesystem","node:fs":"filesystem","fs/promises":"filesystem","node:fs/promises":"filesystem","fs-extra":"filesystem","graceful-fs":"filesystem",memfs:"filesystem",chokidar:"filesystem",http:"network",https:"network",http2:"network",net:"network",tls:"network",dgram:"network",dns:"network","node:http":"network","node:https":"network","node:http2":"network","node:net":"network","node:tls":"network","node:dgram":"network","node:dns":"network",axios:"network",undici:"network","node-fetch":"network",got:"network",ky:"network",superagent:"network",ws:"network",process:"process","node:process":"process",child_process:"process","node:child_process":"process","@prisma/client":"persistence",prisma:"persistence",pg:"persistence",mysql:"persistence",mysql2:"persistence",mongodb:"persistence",mongoose:"persistence",sqlite3:"persistence","better-sqlite3":"persistence",redis:"persistence",ioredis:"persistence",typeorm:"persistence",knex:"persistence","drizzle-orm":"persistence",sequelize:"persistence",kysely:"persistence","@supabase/supabase-js":"persistence"}),Be=Object.freeze({process:Object.freeze(["process","node:process"])});function ie(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=H[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let s=e.slice(0,n),r=H[s];if(r)return r;let i=e.indexOf("/",n+1);return i<0?null:H[e.slice(0,i)]??null}function K(e,t){for(let n of t)if(Be[n]?.includes(e))return n;return null}function ae(e){if(e?.pure===!0)return[...oe].sort();let n=(e?.capabilities?.deny??[]).filter(s=>oe.includes(s));return[...new Set(n)].sort()}var G="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",le=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Ue=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function qe(){let e=[];for(let t of le)for(let n of le)t===n||Ue.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var pe=qe(),B=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"}],I={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},ce={$schema:"https://json-schema.org/draft/2020-12/schema",$id:G,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:G,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:"1.1",default:"1.1"},name:{type:"string",minLength:1},include:{...I,minItems:1,default:["src"]},exclude:{...I,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:pe,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...I,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...I,minItems:1},exclude:I,intentPrefixes:I,description:{type:"string",minLength:1},forbiddenGlobals:I,capabilities:{type:"object",additionalProperties:!1,properties:{deny:{type:"array",uniqueItems:!0,items:{type:"string",enum:["network","filesystem","clock","randomness","environment","process","persistence"]}}}},pure:{type:"boolean"},mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...I,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}}}}},k=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
2
- ${n.map(s=>`- ${s.path}: ${s.message}`).join(`
3
- `)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function de(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function _(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function x(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function We(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function C(e,t,n,s,r){if(t.$ref){let i=We(t.$ref,s);if(!i){r.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}C(e,i,n,s,r);return}if(t.const!==void 0&&!Object.is(e,t.const)){r.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(i=>Object.is(i,e))){r.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!de(e)){r.push({path:n,message:`must be an object; received ${x(e)}`});return}let i=t.properties??{};for(let l of t.required??[])e[l]===void 0&&r.push({path:_(n,l),message:"is required"});if(t.additionalProperties===!1)for(let l of Object.keys(e))l in i||r.push({path:_(n,l),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let l=t.additionalProperties;for(let c of Object.keys(e))c in i||C(e[c],l,_(n,c),s,r)}for(let[l,c]of Object.entries(i))e[l]!==void 0&&C(e[l],c,_(n,l),s,r);return}if(t.type==="array"){if(!Array.isArray(e)){r.push({path:n,message:`must be an array; received ${x(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&r.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let i=e.map(l=>JSON.stringify(l));new Set(i).size!==i.length&&r.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((i,l)=>C(i,t.items,`${n}[${l}]`,s,r));return}if(t.type==="string"){if(typeof e!="string"){r.push({path:n,message:`must be a string; received ${x(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&r.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&r.push({path:n,message:`must be a boolean; received ${x(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){r.push({path:n,message:`must be an integer; received ${x(e)}`});return}t.minimum!==void 0&&e<t.minimum&&r.push({path:n,message:`must be at least ${t.minimum}`})}}function Ye(e){return{...e,$schema:e.$schema===void 0?G:e.$schema,schemaVersion:e.schemaVersion===void 0?"1.1":e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?pe.map(t=>({...t})):e.rules}}function Je(){let e=new Set(["1.1"]);for(let t of B)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}function ze(e,t="ark.config.json"){if(!de(e))throw new k(t,[{path:"$",message:`must be an object; received ${x(e)}`}]);let n=Je(),s=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(s===null)throw new k(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.1`}]);if(s!=="unversioned"&&!n.has(s))throw new k(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(s)}; expected 1.1`}]);let r=s,i={...e},l=0;for(;r!=="1.1"&&l<B.length+1;){l+=1;let g=B.find(f=>f.from===r);if(!g)throw new k(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected 1.1`}]);r=g.to,i.schemaVersion=r}if(r!=="1.1")throw new k(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(s)}; expected 1.1`}]);let c=s==="unversioned"?"unversioned":s==="1.0"?"1.0":null;return{candidate:Ye(i),migratedFrom:c}}function Ze(e,t="ark.config.json"){let{candidate:n,migratedFrom:s}=ze(e,t),r=[];if(C(n,ce,"$",ce,r),r.length>0)throw new k(t,r);return{config:n,migratedFrom:s}}function ue(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(s){throw new k(t,[{path:"$",message:`invalid JSON: ${s instanceof Error?s.message:String(s)}`}])}return Ze(n,t)}function b(e){return typeof e=="string"&&e.length>0?e:void 0}function fe(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function Xe(e,t,n){if(e==="LAYER_IMPORT_VIOLATION")return t.typeOnly||n.targetTypeOnlyExports===!0||n.namedBindingsTypeOnly===!0?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":n.peerIsolation===!0?"Extract the shared dependency to a shared layer, then preflight again.":`Define a port in ${t.fromLayer??"the source layer"}, inject the ${t.toLayer??"outer-layer"} implementation, then preflight again.`;if(e==="FORBIDDEN_GLOBAL")return`Inject ${t.target??"the capability"} through a port, then preflight again.`;if(e==="CAPABILITY_VIOLATION")return`Define a ${b(n.capability)??"capability"} port in ${t.fromLayer??"the walled layer"}, bind the implementation outside it, then preflight again.`;if(e==="CIRCULAR_DEPENDENCY")return"Extract the shared dependency into a third module, then preflight again.";if(e==="RAW_EVENT_PUBLISH")return"Publish through a registered intent creator, then run Ark again.";if(e==="PUBLISH_MISSING_SOURCE")return"Add metadata.source to the publish call, then run Ark again.";if(e==="ARKRULE_STRUCTURE"||e==="ARKRULE_INVARIANT"||e==="INVARIANT_UNCOVERED"||e.startsWith("ARKRULE_")){let s=t.arkruleSource??"arkrules/<Layer>.json";return`Fix the structure or invariant for ${t.arkruleId??"the ArkRule"} (declared in ${s}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`}return`Resolve ${e} without weakening ark.config.json, then run Ark again.`}function ge(e,t="error"){let n=b(e.ruleId)??b(e.code)??"ARK_UNKNOWN",s=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,r={...b(e.target)?{target:b(e.target)}:{},...b(e.fromLayer)?{fromLayer:b(e.fromLayer)}:{},...b(e.toLayer)?{toLayer:b(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{},...typeof e.targetTypeOnlyExports=="boolean"?{targetTypeOnlyExports:e.targetTypeOnlyExports}:{},...typeof e.sourcePureTypeModule=="boolean"?{sourcePureTypeModule:e.sourcePureTypeModule}:{},...typeof e.namedBindingsTypeOnly=="boolean"?{namedBindingsTypeOnly:e.namedBindingsTypeOnly}:{},...typeof e.portProofEligible=="boolean"?{portProofEligible:e.portProofEligible}:{},...typeof e.peerIsolation=="boolean"?{peerIsolation:e.peerIsolation}:{},...b(e.capability)?{capability:b(e.capability)}:{},...b(e.edgeKind)?{edgeKind:b(e.edgeKind)}:{},...b(e.arkruleId)?{arkruleId:b(e.arkruleId)}:{},...b(e.arkruleSource)?{arkruleSource:b(e.arkruleSource)}:{}};return{ruleId:n,severity:s,message:b(e.message)??n,location:{file:b(e.file)??"<unknown>",line:fe(e.line,1),column:fe(e.column,1)},evidence:r,nextAction:b(e.nextAction)??Xe(n,r,e)}}var me={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."},gt=Object.freeze([{layer:"DomainModel",prefixes:["Domain."]},{layer:"ApplicationOrchestration",prefixes:["Application."]},{layer:"PersistenceAdapters",prefixes:["Adapter.Persistence.","Adapter.Repository."]},{layer:"IntegrationAdapters",prefixes:["Adapter.Integration.","Adapter.External."]},{layer:"WorkflowSagaEngine",prefixes:["Workflow."]},{layer:"BackgroundJobsScheduling",prefixes:["Job."]},{layer:"PresentationAdapters",prefixes:["Presentation.","Adapter.Presentation.","Adapter.Api."]},{layer:"ReportingReadModels",prefixes:["Reporting."]},{layer:"ExtensibilityMetadata",prefixes:["Metadata."]},{layer:"SecurityAuditObservability",prefixes:["Security.","Audit.","Observability."]},{layer:"Kernel",prefixes:["Kernel."]}]);function Qe(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function U(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&Qe(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:me.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:me.PUBLISH_MISSING_SOURCE}),t}function N(e){if(typeof e.physicalFilename=="string"&&e.physicalFilename.length>0)return e.physicalFilename;if(typeof e.filename=="string"&&e.filename.length>0)return e.filename;if(typeof e.getFilename=="function")try{let t=e.getFilename();if(typeof t=="string"&&t.length>0)return t}catch{}return""}function w(e,t,n,s,r){let i=ge({...s,line:s.line??t.loc?.start?.line,column:s.column??(typeof t.loc?.start?.column=="number"?t.loc.start.column+1:void 0)});return e.report({node:t,messageId:n,...r?{data:r}:{},diagnostic:i}),i}function T(e){if(!e||e==="<input>"||e.startsWith("stdin"))return null;let t=d.default.dirname(d.default.resolve(e));for(;;){let n=d.default.join(t,"ark.config.json");if(S.default.existsSync(n))return n;let s=d.default.dirname(t);if(s===t)return null;t=s}}var ye=new Map;function j(e){if(!S.default.existsSync(e))return null;let t=S.default.readFileSync(e,"utf8"),n=ye.get(e);if(n?.source===t)return n.config;let s=ue(t,e).config;return ye.set(e,{source:t,config:s}),s}function W(e,t){return(e.include??[]).some(s=>{let r=String(s).replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/$/,"");return r==="."||t===r||t.startsWith(`${r}/`)})&&!se(t,e)}function be(e){let t=[e,`${e}.ts`,`${e}.tsx`,`${e}.mts`,`${e}.cts`,`${e}.js`,`${e}.jsx`,d.default.join(e,"index.ts"),d.default.join(e,"index.tsx"),d.default.join(e,"index.js")];for(let n of t)try{if(S.default.existsSync(n)&&S.default.statSync(n).isFile())return n}catch{}return null}function he(e){let t=d.default.resolve(e),n=null;for(;;){let f=d.default.join(t,"tsconfig.json");if(S.default.existsSync(f)){n=f;break}let p=d.default.dirname(t);if(p===t)break;t=p}if(!n)return{baseUrl:e,aliases:[]};let s=f=>{try{let p=S.default.readFileSync(f,"utf8");return p=p.replace(/\/\*[\s\S]*?\*\//g,"").replace(/(^|[^:])\/\/.*$/gm,"$1"),JSON.parse(p)}catch{return null}},r=(f,p)=>{if(p>4)return{};let o=s(f);if(!o)return{};let a=o.compilerOptions??{},u=a.baseUrl,m=a.paths,y=o.extends;if(typeof y=="string"&&!y.startsWith("@")){let h=d.default.resolve(d.default.dirname(f),y.endsWith(".json")?y:`${y}.json`);if(S.default.existsSync(h)){let A=r(h,p+1);u=u??A.baseUrl,m={...A.paths??{},...m??{}}}}return{baseUrl:u,paths:m}},i=r(n,0),l=d.default.dirname(n),c=d.default.resolve(l,i.baseUrl||"."),g=[];for(let[f,p]of Object.entries(i.paths||{})){if(!Array.isArray(p)||p.length===0)continue;let o=f.replace(/\*$/,"");o&&g.push({from:o,to:String(p[0]).replace(/\*$/,"")})}return g.sort((f,p)=>p.from.length-f.from.length),{baseUrl:c,aliases:g}}function Ae(e,t){if(!t.startsWith("."))return null;let n=d.default.resolve(d.default.dirname(e),t);return be(n)}function ke(e,t,n){if(!t)return null;if(t.startsWith("."))return Ae(e,t);let s=n||d.default.dirname(e),{baseUrl:r,aliases:i}=he(s),l=i.find(g=>t.startsWith(g.from));if(!l)return null;let c=d.default.resolve(r,`${l.to}${t.slice(l.from.length)}`);return be(c)}function M(e){return typeof e?.value=="string"?e.value:void 0}function Y(e){return e?.name??M(e)}function J(e){return e.sourceCode??e.getSourceCode?.()}function Se(e,t){let n=J(e)?.getScope?.(t);for(;n;){let s=n.references?.find(r=>r.identifier===t);if(s)return s;n=n.upper??void 0}}function v(e,t,n){let s=Se(e,t);if(s?.resolved)return(s.resolved.defs?.length??0)>0;let r=J(e)?.getScope?.(t);for(;r;){let i=r.set?.get(n);if(i)return(i.defs?.length??0)>0;r=r.upper??void 0}return!1}function et(e,t){let n=Se(e,t);return n?n.isValueReference!==!1:t.parent?.type==="VariableDeclarator"&&t.parent.init===t}function Ie(e){if(e?.type==="Identifier"&&e.name)return{root:e,segments:[e.name]};if(!e||!(e.type==="MemberExpression"||!!(e.object&&e.property))||e.computed===!0)return;let n=Ie(e.object),s=Y(e.property);if(!(!n||!s))return{root:n.root,segments:[...n.segments,s]}}function tt(e){return Y(e.callee?.property)}function Re(e,t){return e?.properties?.find(n=>Y(n.key)===t)}function P(e,t){return Re(e,t)!==void 0}function nt(e){let t=Re(e,"metadata")?.value;return P(t,"source")}function xe(e){return tt(e)==="publish"}function q(e){if(e.importKind==="type"||e.exportKind==="type")return!0;let t=e.specifiers??[];return t.length===0?!1:t.every(n=>n.type==="ImportSpecifier")?t.every(n=>n.importKind==="type"):t.every(n=>n.exportKind==="type")}function rt(e){let t=e;for(;t?.parent;)t=t.parent;return t?.type==="Program"?t:void 0}function st(e){let t=rt(e)?.body;if(!t)return!1;let n=!1;for(let s of t){if(s.type==="ImportDeclaration"){if(!q(s))return!1;continue}if(!(s.type==="TSInterfaceDeclaration"||s.type==="TSTypeAliasDeclaration")){if(s.type==="ExportNamedDeclaration"){if(s.declaration){if(s.declaration.type!=="TSInterfaceDeclaration"&&s.declaration.type!=="TSTypeAliasDeclaration")return!1}else if(!q(s))return!1;n=!0;continue}return!1}}return n}var we={meta:{type:"problem",docs:{description:"Disallow imports that violate ark.config.json layer rules (same contract as arkgate-check)."},messages:{forbiddenImport:"Architecture: {{fromLayer}} must not import {{toLayer}} (ark.config.json). Specifier: {{specifier}}",forbiddenImportHeuristic:"Domain code must not import infrastructure, adapters, repositories, or database modules."},schema:[]},create(e){let t=N(e),n=T(t),s=n?j(n):null,r=n?d.default.dirname(n):null,i=l=>{let c=M(l.source);if(c&&s&&r&&t){let g=d.default.isAbsolute(t)?t:d.default.resolve(t),f=d.default.relative(r,g).split(d.default.sep).join("/");if(!W(s,f))return;let p=R(f,s.layers);if(!p)return;let o=ke(g,c,r);if(!o)return;let a=d.default.relative(r,o).split(d.default.sep).join("/");if(a.startsWith(".."))return;let u=R(a,s.layers);if(!u)return;let m={fromPath:f,toPath:a,layers:s.layers},y=V(s.rules,p,u,m);if(y||F(s.rules,p,u,m)){let h=l.type?.startsWith("Export")?"export":"import",A=q(l),z=!!y?.peerIsolation,Z=A&&!z,X=y?.message??`${p} must not ${h} ${u}.`;w(e,l,"forbiddenImport",{ruleId:"LAYER_IMPORT_VIOLATION",file:f,fromLayer:p,toLayer:u,target:a,edgeKind:h,...z?{peerIsolation:!0}:{},...A?{typeOnly:!0}:{},...Z?{severity:"warning"}:{},...st(l)?{sourcePureTypeModule:!0}:{},message:Z?`${X} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:X},{fromLayer:p,toLayer:u,specifier:c})}return}};return{ImportDeclaration:i,ExportNamedDeclaration:i,ExportAllDeclaration:i}}},Ee={meta:{type:"problem",docs:{description:"Require event bus publish calls to use registered intent creators instead of raw event objects or intent strings."},messages:{rawPublish:"Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts."},schema:[]},create(e){return{CallExpression(t){let n=t.arguments?.[0],s=M(n),r=U({publishCall:xe(t),rawIntentName:s,objectHasIntent:P(n,"intent"),arkPublishCandidate:!1,hasSource:!0});if(r.some(i=>i.ruleId==="RAW_EVENT_PUBLISH")){let i=r.find(l=>l.ruleId==="RAW_EVENT_PUBLISH");w(e,t,"rawPublish",{...i,file:N(e)})}}}}},Ce={meta:{type:"problem",docs:{description:"Require event bus publish calls to include source metadata."},messages:{missingSource:"Strict Ark publish calls must include metadata.source."},schema:[]},create(e){return{CallExpression(t){let n=t.arguments?.[0],s=t.arguments?.[2],i=U({publishCall:xe(t),rawIntentName:M(n),objectHasIntent:P(n,"intent"),arkPublishCandidate:!0,hasSource:nt(n)||P(s,"source")}).find(l=>l.ruleId==="PUBLISH_MISSING_SOURCE");i&&w(e,t,"missingSource",{...i,file:N(e)})}}}},Ne={meta:{type:"problem",docs:{description:"Disallow ambient globals from the layer\u2019s forbiddenGlobals in ark.config.json (same purity surface as ark-check). Option `globals` is a standalone fallback when no project config applies."},messages:{forbiddenGlobal:'Ambient global "{{name}}" is forbidden in {{layer}} (ark.config.json); inject the capability through a port instead.',forbiddenGlobalDefault:'Ambient global "{{name}}" is forbidden here; inject the capability through a port instead.',forbiddenModule:'{{layer}} must not use module "{{specifier}}" because it is the import form of forbidden global "{{name}}".'},schema:[{type:"object",properties:{globals:{type:"array",items:{type:"string"}}},additionalProperties:!1}]},create(e){let t=N(e),n=e.options?.[0],s=T(t),r=s?j(s):null,i=s?d.default.dirname(s):null,l=null,c="this layer";if(r&&i&&t){let o=d.default.isAbsolute(t)?t:d.default.resolve(t),a=d.default.relative(i,o).split(d.default.sep).join("/");if(!W(r,a))return{};let u=r.layers?.find(m=>m.name===R(a,r.layers));u?.forbiddenGlobals?.length?(l=new Set(u.forbiddenGlobals),c=u.name):l=null}else n?.globals&&(l=new Set(n.globals));if(!l)return{};let g=typeof J(e)?.getScope=="function",f=(o,a)=>{let u=d.default.isAbsolute(t)?t:d.default.resolve(t),m=i?d.default.relative(i,u).split(d.default.sep).join("/"):t;w(e,o,r?"forbiddenGlobal":"forbiddenGlobalDefault",{ruleId:"FORBIDDEN_GLOBAL",file:m,fromLayer:c,target:a,message:`${c} must not use the ambient global "${a}".`},{name:a,layer:c})},p=(o,a,u,m)=>{if(u||typeof a!="string")return;let y=K(a,l);if(!y)return;let h=d.default.isAbsolute(t)?t:d.default.resolve(t),A=i?d.default.relative(i,h).split(d.default.sep).join("/"):t;w(e,o,"forbiddenModule",{ruleId:"FORBIDDEN_GLOBAL",file:A,fromLayer:c,target:a,edgeKind:m,message:`${c} must not use module "${a}" because it is the import form of forbidden global "${y}".`},{layer:c,name:y,specifier:a,importKind:m})};return{MemberExpression(o){if(o.parent?.type==="MemberExpression"&&o.parent.object===o)return;let a=Ie(o);if(!a||v(e,a.root,a.segments[0]))return;let u=a.segments[0]==="globalThis",m=u?a.segments.slice(1):a.segments,y;for(let h=m.length;h>=(u?1:2);h-=1){let A=m.slice(0,h).join(".");if(l.has(A)){y=A;break}}y?f(o,y):!g&&l.has(a.segments[0])&&f(o,a.segments[0])},CallExpression(o){let a=o;if(a.callee?.type==="Identifier"&&a.callee.name==="require"&&a.arguments?.[0]?.type==="Literal"&&!v(e,o,"require")&&p(o,a.arguments[0].value,!1,"require"),g)return;let u=a.callee?.type==="Identifier"?a.callee.name:void 0;u&&l.has(u)&&f(o,u)},ImportDeclaration(o){let a=o,u=(a.specifiers??[]).filter(y=>y.type==="ImportSpecifier"),m=u.length>0&&u.length===(a.specifiers??[]).length&&u.every(y=>y.importKind==="type");p(o,a.source?.value,a.importKind==="type"||m,"import")},ImportExpression(o){let a=o;a.source?.type==="Literal"&&p(o,a.source.value,!1,"dynamic-import")},TSImportEqualsDeclaration(o){let a=o;p(o,a.moduleReference?.expression?.value,a.importKind==="type"||a.isTypeOnly===!0,"require")},ExportNamedDeclaration(o){let a=o;if(!a.source)return;let u=a.specifiers??[],m=u.length>0&&u.every(y=>y.exportKind==="type");p(o,a.source.value,a.exportKind==="type"||m,"export")},ExportAllDeclaration(o){let a=o;p(o,a.source?.value,a.exportKind==="type","export")},NewExpression(o){if(g)return;let a=o.callee?.type==="Identifier"?o.callee.name:void 0;a&&l.has(a)&&f(o,a)},Identifier(o){!g||!o.name||!l.has(o.name)||!et(e,o)||v(e,o,o.name)||f(o,o.name)}}}},Le={meta:{type:"problem",docs:{description:"Disallow importing modules whose effect capability the layer denies (ark.config.json capabilities.deny / pure \u2014 same wall surface as ark-check). Import dimension only: ambient globals stay with no-forbidden-globals and the CLI/hook symbol path."},messages:{deniedCapability:'{{layer}} denies the {{capability}} capability (ark.config.json); "{{specifier}}" imports it. Define a port and bind the implementation in an adapter layer.'},schema:[]},create(e){let t=N(e),n=T(t),s=n?j(n):null,r=n?d.default.dirname(n):null;if(!s||!r||!t)return{};let i=d.default.isAbsolute(t)?t:d.default.resolve(t),l=d.default.relative(r,i).split(d.default.sep).join("/");if(!W(s,l))return{};let c=s.layers?.find(p=>p.name===R(l,s.layers));if(!c)return{};let g=new Set(ae(c));if(g.size===0)return{};let f=(p,o,a,u)=>{if(a||typeof o!="string"||K(o,c.forbiddenGlobals??[]))return;let m=ie(o);!m||!g.has(m)||w(e,p,"deniedCapability",{ruleId:"CAPABILITY_VIOLATION",file:l,fromLayer:c.name,target:o,capability:m,edgeKind:u,message:`${c.name} denies the ${m} capability; found import of "${o}".`},{layer:c.name,capability:m,specifier:o})};return{ImportDeclaration(p){let o=p,a=(o.specifiers??[]).filter(m=>m.type==="ImportSpecifier"),u=a.length>0&&a.length===(o.specifiers??[]).length&&a.every(m=>m.importKind==="type");f(p,o.source?.value,o.importKind==="type"||u,"import")},ImportExpression(p){let o=p;o.source?.type==="Literal"&&f(p,o.source.value,!1,"dynamic-import")},TSImportEqualsDeclaration(p){let o=p;f(p,o.moduleReference?.expression?.value,o.importKind==="type"||o.isTypeOnly===!0,"require")},ExportNamedDeclaration(p){let o=p;if(!o.source)return;let a=o.specifiers??[],u=a.length>0&&a.every(m=>m.exportKind==="type");f(p,o.source.value,o.exportKind==="type"||u,"export")},ExportAllDeclaration(p){let o=p;f(p,o.source?.value,o.exportKind==="type","export")},CallExpression(p){let o=p;o.callee?.type==="Identifier"&&o.callee.name==="require"&&o.arguments?.[0]?.type==="Literal"&&!v(e,p,"require")&&f(p,o.arguments[0].value,!1,"require")}}}},ot={"no-domain-infra-imports":we,"no-raw-event-publish":Ee,"require-publish-source":Ce,"no-forbidden-globals":Ne,"no-denied-capabilities":Le},$={rules:ot};$.configs={recommended:{plugins:{ark:$},rules:{"ark/no-domain-infra-imports":"error","ark/no-raw-event-publish":"error","ark/require-publish-source":"error","ark/no-forbidden-globals":"error","ark/no-denied-capabilities":"error"}}};var it=$;0&&(module.exports={findConfigPath,globToRegExp,isEdgeDenied,layerForRelativePath,loadArkConfig,noDeniedCapabilities,noDomainInfraImports,noForbiddenGlobals,noRawEventPublish,patternSpecificity,plugin,readTsconfigPathAliases,requirePublishSource,resolveImportSpecifier,resolveRelativeImport});
1
+ "use strict";var Oe=Object.create;var N=Object.defineProperty;var _e=Object.getOwnPropertyDescriptor;var Pe=Object.getOwnPropertyNames;var $e=Object.getPrototypeOf,ve=Object.prototype.hasOwnProperty;var Te=(e,t)=>{for(var n in t)N(e,n,{get:t[n],enumerable:!0})},Q=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Pe(t))!ve.call(e,s)&&s!==n&&N(e,s,{get:()=>t[s],enumerable:!(r=_e(t,s))||r.enumerable});return e};var ee=(e,t,n)=>(n=e!=null?Oe($e(e)):{},Q(t||!e||!e.__esModule?N(n,"default",{value:e,enumerable:!0}):n,e)),je=e=>Q(N({},"__esModule",{value:!0}),e);var pt={};Te(pt,{default:()=>dt,findConfigPath:()=>T,globToRegExp:()=>E,isEdgeDenied:()=>F,layerForRelativePath:()=>R,loadArkConfig:()=>j,noDeniedCapabilities:()=>Ne,noDomainInfraImports:()=>we,noForbiddenGlobals:()=>Le,noRawEventPublish:()=>Ee,patternSpecificity:()=>M,plugin:()=>v,readTsconfigPathAliases:()=>he,requirePublishSource:()=>Ce,resolveImportSpecifier:()=>Se,resolveRelativeImport:()=>Ae});module.exports=je(pt);var k=ee(require("fs"),1),p=ee(require("path"),1);var te=new Map;function ne(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function O(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let s=e[n+1];if("*?{}[],".includes(s)||s==="\\"){t+="\\"+s,n+=1;continue}t+="/";continue}t+=r}return t}function De(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(e){let t=te.get(e);if(t)return t;let n=O(e),r=De(n),s="",i=0;for(let c=0;c<n.length;c+=1){let g=n[c];g==="\\"&&c+1<n.length?(s+=ne(n[c+1]),c+=1):g==="*"?n[c+1]==="*"?n[c+2]==="/"?(s+="(?:.*/)?",c+=2):(s+=".*",c+=1):s+="[^/]*":g==="?"?s+="[^/]":g==="{"&&r?(s+="(?:",i+=1):g==="}"&&r&&i>0?(s+=")",i-=1):g===","&&r&&i>0?s+="|":s+=ne(g)}let a=new RegExp(`^${s}$`);return te.set(e,a),a}function Me(e){return O(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}function M(e,t){let n=O(String(e)),r=Me(n),s=n.replace(/\*/g,"").length,i=r.length*1e4+s;if(t==null||t==="")return i;let a=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return s;let c=0,g=-1;for(let f of r){let d=-1;for(let o=c;o<a.length;o+=1)if(a[o]===f){d=o;break}if(d<0)return i;g=d,c=d+1}return(g+1)*1e6+r.length*1e4+s}function R(e,t){let n=String(e).split(/[/\\]/).join("/"),r,s=-1;for(let i of t??[])if(!(i.exclude??[]).some(a=>E(a).test(n))){for(let a of i.patterns??[])if(E(a).test(n)){let c=M(a,n);c>s&&(s=c,r=i.name)}}return r}function re(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),r=new Set(t.map(s=>String(s).toLowerCase()));for(let s=0;s<n.length-1;s+=1)if(r.has(n[s].toLowerCase()))return`${n[s].toLowerCase()}/${n[s+1].toLowerCase()}`}function Ve(e){let t=new Set;for(let n of e??[]){let s=O(String(n)).split("/").filter(Boolean);for(let i=0;i<s.length;i+=1){let a=s[i];if((a==="**"||a==="*")&&i>0){let c=s[i-1];c&&!c.includes("*")&&!c.includes("{")&&!c.includes("}")&&t.add(c)}}}return[...t]}function Fe(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(s=>typeof s=="string"&&s.length>0);let r=(n??[]).find(s=>s.name===t);return Ve(r?.patterns)}function V(e,t,n,r){for(let s of e??[])if(!(s.from!==t||s.to!==n)&&s.allowed===!1){if(s.peerIsolation){let i=r?.fromPath,a=r?.toPath;if(!i||!a)return s;let c=Fe(s,t,r?.layers);if(c.length===0)return s;let g=re(i,c),f=re(a,c);if(!g||!f||g!==f)return s;continue}if(t!==n)return s}}function F(e,t,n,r){return V(e,t,n,r)!==void 0}var Ke=["**/*.gen.ts","**/*.gen.tsx","**/*.generated.ts","**/*.generated.tsx"];function He(e){let t=Array.isArray(e?.exclude)?e.exclude.filter(r=>typeof r=="string"):[];return[...e?.excludeGenerated===!1?[]:Ke,...t]}function se(e,t){let n=String(e).split(/[/\\]/).join("/");return He(t).some(r=>E(r).test(n))}var oe=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),Ge=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),gt=Object.freeze(Object.keys(Ge).sort()),K=Object.freeze({fs:"filesystem","node:fs":"filesystem","fs/promises":"filesystem","node:fs/promises":"filesystem","fs-extra":"filesystem","graceful-fs":"filesystem",memfs:"filesystem",chokidar:"filesystem",http:"network",https:"network",http2:"network",net:"network",tls:"network",dgram:"network",dns:"network","node:http":"network","node:https":"network","node:http2":"network","node:net":"network","node:tls":"network","node:dgram":"network","node:dns":"network",axios:"network",undici:"network","node-fetch":"network",got:"network",ky:"network",superagent:"network",ws:"network",process:"process","node:process":"process",child_process:"process","node:child_process":"process","@prisma/client":"persistence",prisma:"persistence",pg:"persistence",mysql:"persistence",mysql2:"persistence",mongodb:"persistence",mongoose:"persistence",sqlite3:"persistence","better-sqlite3":"persistence",redis:"persistence",ioredis:"persistence",typeorm:"persistence",knex:"persistence","drizzle-orm":"persistence",sequelize:"persistence",kysely:"persistence","@supabase/supabase-js":"persistence"}),Be=Object.freeze({process:Object.freeze(["process","node:process"])});function ie(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=K[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),s=K[r];if(s)return s;let i=e.indexOf("/",n+1);return i<0?null:K[e.slice(0,i)]??null}function H(e,t){for(let n of t)if(Be[n]?.includes(e))return n;return null}function ae(e){if(e?.pure===!0)return[...oe].sort();let n=(e?.capabilities?.deny??[]).filter(r=>oe.includes(r));return[...new Set(n)].sort()}var G="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",le=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Ue=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function qe(){let e=[];for(let t of le)for(let n of le)t===n||Ue.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var de=qe(),B=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"}],I={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},ce={$schema:"https://json-schema.org/draft/2020-12/schema",$id:G,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:G,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:"1.1",default:"1.1"},name:{type:"string",minLength:1},include:{...I,minItems:1,default:["src"]},exclude:{...I,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:de,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...I,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...I,minItems:1},exclude:I,intentPrefixes:I,description:{type:"string",minLength:1},forbiddenGlobals:I,capabilities:{type:"object",additionalProperties:!1,properties:{deny:{type:"array",uniqueItems:!0,items:{type:"string",enum:["network","filesystem","clock","randomness","environment","process","persistence"]}}}},pure:{type:"boolean"},mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...I,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}}}}},S=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
2
+ ${n.map(r=>`- ${r.path}: ${r.message}`).join(`
3
+ `)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function pe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function _(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function x(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function We(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function C(e,t,n,r,s){if(t.$ref){let i=We(t.$ref,r);if(!i){s.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}C(e,i,n,r,s);return}if(t.const!==void 0&&!Object.is(e,t.const)){s.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(i=>Object.is(i,e))){s.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!pe(e)){s.push({path:n,message:`must be an object; received ${x(e)}`});return}let i=t.properties??{};for(let a of t.required??[])e[a]===void 0&&s.push({path:_(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in i||s.push({path:_(n,a),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let a=t.additionalProperties;for(let c of Object.keys(e))c in i||C(e[c],a,_(n,c),r,s)}for(let[a,c]of Object.entries(i))e[a]!==void 0&&C(e[a],c,_(n,a),r,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:n,message:`must be an array; received ${x(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&s.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let i=e.map(a=>JSON.stringify(a));new Set(i).size!==i.length&&s.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((i,a)=>C(i,t.items,`${n}[${a}]`,r,s));return}if(t.type==="string"){if(typeof e!="string"){s.push({path:n,message:`must be a string; received ${x(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&s.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&s.push({path:n,message:`must be a boolean; received ${x(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){s.push({path:n,message:`must be an integer; received ${x(e)}`});return}t.minimum!==void 0&&e<t.minimum&&s.push({path:n,message:`must be at least ${t.minimum}`})}}function Ye(e){return{...e,$schema:e.$schema===void 0?G:e.$schema,schemaVersion:e.schemaVersion===void 0?"1.1":e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?de.map(t=>({...t})):e.rules}}function Je(){let e=new Set(["1.1"]);for(let t of B)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}function ze(e,t="ark.config.json"){if(!pe(e))throw new S(t,[{path:"$",message:`must be an object; received ${x(e)}`}]);let n=Je(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new S(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.1`}]);if(r!=="unversioned"&&!n.has(r))throw new S(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected 1.1`}]);let s=r,i={...e},a=0;for(;s!=="1.1"&&a<B.length+1;){a+=1;let g=B.find(f=>f.from===s);if(!g)throw new S(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(s)}; expected 1.1`}]);s=g.to,i.schemaVersion=s}if(s!=="1.1")throw new S(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected 1.1`}]);let c=r==="unversioned"?"unversioned":r==="1.0"?"1.0":null;return{candidate:Ye(i),migratedFrom:c}}function Ze(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=ze(e,t),s=[];if(C(n,ce,"$",ce,s),s.length>0)throw new S(t,s);return{config:n,migratedFrom:r}}function ue(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new S(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return Ze(n,t)}var Xe="docs/diagnostics.md";function b(e){return typeof e=="string"&&e.length>0?e:void 0}function fe(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function Qe(e){let t=typeof e.ruleId=="string"?e.ruleId:typeof e.code=="string"?e.code:void 0,n=typeof e.file=="string"?e.file:void 0,r=typeof e.fromLayer=="string"?e.fromLayer:void 0,s=typeof e.toLayer=="string"?e.toLayer:void 0,i=typeof e.target=="string"?e.target:void 0;return[t,n,r??"",s??"",i??""].join("|")}function et(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 tt(e){return`${Xe}#${e}`}function nt(e,t,n){if(e==="LAYER_IMPORT_VIOLATION")return t.typeOnly||n.targetTypeOnlyExports===!0||n.namedBindingsTypeOnly===!0?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":n.peerIsolation===!0?"Extract the shared dependency to a shared layer, then preflight again.":`Define a port in ${t.fromLayer??"the source layer"}, inject the ${t.toLayer??"outer-layer"} implementation, then preflight again.`;if(e==="FORBIDDEN_GLOBAL")return`Inject ${t.target??"the capability"} through a port, then preflight again.`;if(e==="CAPABILITY_VIOLATION")return`Define a ${b(n.capability)??"capability"} port in ${t.fromLayer??"the walled layer"}, bind the implementation outside it, then preflight again.`;if(e==="CIRCULAR_DEPENDENCY")return"Extract the shared dependency into a third module, then preflight again.";if(e==="RAW_EVENT_PUBLISH")return"Publish through a registered intent creator, then run Ark again.";if(e==="PUBLISH_MISSING_SOURCE")return"Add metadata.source to the publish call, then run Ark again.";if(e==="ARKRULE_STRUCTURE"||e==="ARKRULE_INVARIANT"||e==="INVARIANT_UNCOVERED"||e.startsWith("ARKRULE_")){let r=t.arkruleSource??"arkrules/<Layer>.json";return`Fix the structure or invariant for ${t.arkruleId??"the ArkRule"} (declared in ${r}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`}return`Resolve ${e} without weakening ark.config.json, then run Ark again.`}function ge(e,t="error",n){let r=b(e.ruleId)??b(e.code)??"ARK_UNKNOWN",s=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,i={...b(e.target)?{target:b(e.target)}:{},...b(e.fromLayer)?{fromLayer:b(e.fromLayer)}:{},...b(e.toLayer)?{toLayer:b(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{},...typeof e.targetTypeOnlyExports=="boolean"?{targetTypeOnlyExports:e.targetTypeOnlyExports}:{},...typeof e.sourcePureTypeModule=="boolean"?{sourcePureTypeModule:e.sourcePureTypeModule}:{},...typeof e.namedBindingsTypeOnly=="boolean"?{namedBindingsTypeOnly:e.namedBindingsTypeOnly}:{},...typeof e.portProofEligible=="boolean"?{portProofEligible:e.portProofEligible}:{},...typeof e.peerIsolation=="boolean"?{peerIsolation:e.peerIsolation}:{},...b(e.capability)?{capability:b(e.capability)}:{},...b(e.edgeKind)?{edgeKind:b(e.edgeKind)}:{},...b(e.arkruleId)?{arkruleId:b(e.arkruleId)}:{},...b(e.arkruleSource)?{arkruleSource:b(e.arkruleSource)}:{}},a=n??Qe(e),c=et(a);return{ruleId:r,severity:s,message:b(e.message)??r,location:{file:b(e.file)??"<unknown>",line:fe(e.line,1),column:fe(e.column,1)},evidence:i,nextAction:b(e.nextAction)??nt(r,i,e),findingRef:c,targetKey:a,docsCodePath:tt(r)}}var me={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."},ht=Object.freeze([{layer:"DomainModel",prefixes:["Domain."]},{layer:"ApplicationOrchestration",prefixes:["Application."]},{layer:"PersistenceAdapters",prefixes:["Adapter.Persistence.","Adapter.Repository."]},{layer:"IntegrationAdapters",prefixes:["Adapter.Integration.","Adapter.External."]},{layer:"WorkflowSagaEngine",prefixes:["Workflow."]},{layer:"BackgroundJobsScheduling",prefixes:["Job."]},{layer:"PresentationAdapters",prefixes:["Presentation.","Adapter.Presentation.","Adapter.Api."]},{layer:"ReportingReadModels",prefixes:["Reporting."]},{layer:"ExtensibilityMetadata",prefixes:["Metadata."]},{layer:"SecurityAuditObservability",prefixes:["Security.","Audit.","Observability."]},{layer:"Kernel",prefixes:["Kernel."]}]);function rt(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function U(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&rt(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:me.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:me.PUBLISH_MISSING_SOURCE}),t}function L(e){if(typeof e.physicalFilename=="string"&&e.physicalFilename.length>0)return e.physicalFilename;if(typeof e.filename=="string"&&e.filename.length>0)return e.filename;if(typeof e.getFilename=="function")try{let t=e.getFilename();if(typeof t=="string"&&t.length>0)return t}catch{}return""}function w(e,t,n,r,s){let i=ge({...r,line:r.line??t.loc?.start?.line,column:r.column??(typeof t.loc?.start?.column=="number"?t.loc.start.column+1:void 0)});return e.report({node:t,messageId:n,...s?{data:s}:{},diagnostic:i}),i}function T(e){if(!e||e==="<input>"||e.startsWith("stdin"))return null;let t=p.default.dirname(p.default.resolve(e));for(;;){let n=p.default.join(t,"ark.config.json");if(k.default.existsSync(n))return n;let r=p.default.dirname(t);if(r===t)return null;t=r}}var ye=new Map;function j(e){if(!k.default.existsSync(e))return null;let t=k.default.readFileSync(e,"utf8"),n=ye.get(e);if(n?.source===t)return n.config;let r=ue(t,e).config;return ye.set(e,{source:t,config:r}),r}function W(e,t){return(e.include??[]).some(r=>{let s=String(r).replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/$/,"");return s==="."||t===s||t.startsWith(`${s}/`)})&&!se(t,e)}function be(e){let t=[e,`${e}.ts`,`${e}.tsx`,`${e}.mts`,`${e}.cts`,`${e}.js`,`${e}.jsx`,p.default.join(e,"index.ts"),p.default.join(e,"index.tsx"),p.default.join(e,"index.js")];for(let n of t)try{if(k.default.existsSync(n)&&k.default.statSync(n).isFile())return n}catch{}return null}function he(e){let t=p.default.resolve(e),n=null;for(;;){let f=p.default.join(t,"tsconfig.json");if(k.default.existsSync(f)){n=f;break}let d=p.default.dirname(t);if(d===t)break;t=d}if(!n)return{baseUrl:e,aliases:[]};let r=f=>{try{let d=k.default.readFileSync(f,"utf8");return d=d.replace(/\/\*[\s\S]*?\*\//g,"").replace(/(^|[^:])\/\/.*$/gm,"$1"),JSON.parse(d)}catch{return null}},s=(f,d)=>{if(d>4)return{};let o=r(f);if(!o)return{};let l=o.compilerOptions??{},u=l.baseUrl,m=l.paths,y=o.extends;if(typeof y=="string"&&!y.startsWith("@")){let h=p.default.resolve(p.default.dirname(f),y.endsWith(".json")?y:`${y}.json`);if(k.default.existsSync(h)){let A=s(h,d+1);u=u??A.baseUrl,m={...A.paths??{},...m??{}}}}return{baseUrl:u,paths:m}},i=s(n,0),a=p.default.dirname(n),c=p.default.resolve(a,i.baseUrl||"."),g=[];for(let[f,d]of Object.entries(i.paths||{})){if(!Array.isArray(d)||d.length===0)continue;let o=f.replace(/\*$/,"");o&&g.push({from:o,to:String(d[0]).replace(/\*$/,"")})}return g.sort((f,d)=>d.from.length-f.from.length),{baseUrl:c,aliases:g}}function Ae(e,t){if(!t.startsWith("."))return null;let n=p.default.resolve(p.default.dirname(e),t);return be(n)}function Se(e,t,n){if(!t)return null;if(t.startsWith("."))return Ae(e,t);let r=n||p.default.dirname(e),{baseUrl:s,aliases:i}=he(r),a=i.find(g=>t.startsWith(g.from));if(!a)return null;let c=p.default.resolve(s,`${a.to}${t.slice(a.from.length)}`);return be(c)}function D(e){return typeof e?.value=="string"?e.value:void 0}function Y(e){return e?.name??D(e)}function J(e){return e.sourceCode??e.getSourceCode?.()}function ke(e,t){let n=J(e)?.getScope?.(t);for(;n;){let r=n.references?.find(s=>s.identifier===t);if(r)return r;n=n.upper??void 0}}function P(e,t,n){let r=ke(e,t);if(r?.resolved)return(r.resolved.defs?.length??0)>0;let s=J(e)?.getScope?.(t);for(;s;){let i=s.set?.get(n);if(i)return(i.defs?.length??0)>0;s=s.upper??void 0}return!1}function st(e,t){let n=ke(e,t);return n?n.isValueReference!==!1:t.parent?.type==="VariableDeclarator"&&t.parent.init===t}function Ie(e){if(e?.type==="Identifier"&&e.name)return{root:e,segments:[e.name]};if(!e||!(e.type==="MemberExpression"||!!(e.object&&e.property))||e.computed===!0)return;let n=Ie(e.object),r=Y(e.property);if(!(!n||!r))return{root:n.root,segments:[...n.segments,r]}}function ot(e){return Y(e.callee?.property)}function Re(e,t){return e?.properties?.find(n=>Y(n.key)===t)}function $(e,t){return Re(e,t)!==void 0}function it(e){let t=Re(e,"metadata")?.value;return $(t,"source")}function xe(e){return ot(e)==="publish"}function q(e){if(e.importKind==="type"||e.exportKind==="type")return!0;let t=e.specifiers??[];return t.length===0?!1:t.every(n=>n.type==="ImportSpecifier")?t.every(n=>n.importKind==="type"):t.every(n=>n.exportKind==="type")}function at(e){let t=e;for(;t?.parent;)t=t.parent;return t?.type==="Program"?t:void 0}function lt(e){let t=at(e)?.body;if(!t)return!1;let n=!1;for(let r of t){if(r.type==="ImportDeclaration"){if(!q(r))return!1;continue}if(!(r.type==="TSInterfaceDeclaration"||r.type==="TSTypeAliasDeclaration")){if(r.type==="ExportNamedDeclaration"){if(r.declaration){if(r.declaration.type!=="TSInterfaceDeclaration"&&r.declaration.type!=="TSTypeAliasDeclaration")return!1}else if(!q(r))return!1;n=!0;continue}return!1}}return n}var we={meta:{type:"problem",docs:{description:"Disallow imports that violate ark.config.json layer rules (same contract as arkgate-check)."},messages:{forbiddenImport:"Architecture: {{fromLayer}} must not import {{toLayer}} (ark.config.json). Specifier: {{specifier}}",forbiddenImportHeuristic:"Domain code must not import infrastructure, adapters, repositories, or database modules."},schema:[]},create(e){let t=L(e),n=T(t),r=n?j(n):null,s=n?p.default.dirname(n):null,i=a=>{let c=D(a.source);if(c&&r&&s&&t){let g=p.default.isAbsolute(t)?t:p.default.resolve(t),f=p.default.relative(s,g).split(p.default.sep).join("/");if(!W(r,f))return;let d=R(f,r.layers);if(!d)return;let o=Se(g,c,s);if(!o)return;let l=p.default.relative(s,o).split(p.default.sep).join("/");if(l.startsWith(".."))return;let u=R(l,r.layers);if(!u)return;let m={fromPath:f,toPath:l,layers:r.layers},y=V(r.rules,d,u,m);if(y||F(r.rules,d,u,m)){let h=a.type?.startsWith("Export")?"export":"import",A=q(a),z=!!y?.peerIsolation,Z=A&&!z,X=y?.message??`${d} must not ${h} ${u}.`;w(e,a,"forbiddenImport",{ruleId:"LAYER_IMPORT_VIOLATION",file:f,fromLayer:d,toLayer:u,target:l,edgeKind:h,...z?{peerIsolation:!0}:{},...A?{typeOnly:!0}:{},...Z?{severity:"warning"}:{},...lt(a)?{sourcePureTypeModule:!0}:{},message:Z?`${X} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:X},{fromLayer:d,toLayer:u,specifier:c})}return}};return{ImportDeclaration:i,ExportNamedDeclaration:i,ExportAllDeclaration:i}}},Ee={meta:{type:"problem",docs:{description:"Require event bus publish calls to use registered intent creators instead of raw event objects or intent strings."},messages:{rawPublish:"Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts."},schema:[]},create(e){return{CallExpression(t){let n=t.arguments?.[0],r=D(n),s=U({publishCall:xe(t),rawIntentName:r,objectHasIntent:$(n,"intent"),arkPublishCandidate:!1,hasSource:!0});if(s.some(i=>i.ruleId==="RAW_EVENT_PUBLISH")){let i=s.find(a=>a.ruleId==="RAW_EVENT_PUBLISH");w(e,t,"rawPublish",{...i,file:L(e)})}}}}},Ce={meta:{type:"problem",docs:{description:"Require event bus publish calls to include source metadata."},messages:{missingSource:"Strict Ark publish calls must include metadata.source."},schema:[]},create(e){return{CallExpression(t){let n=t.arguments?.[0],r=t.arguments?.[2],i=U({publishCall:xe(t),rawIntentName:D(n),objectHasIntent:$(n,"intent"),arkPublishCandidate:!0,hasSource:it(n)||$(r,"source")}).find(a=>a.ruleId==="PUBLISH_MISSING_SOURCE");i&&w(e,t,"missingSource",{...i,file:L(e)})}}}},Le={meta:{type:"problem",docs:{description:"Disallow ambient globals from the layer\u2019s forbiddenGlobals in ark.config.json (same purity surface as ark-check). Option `globals` is a standalone fallback when no project config applies."},messages:{forbiddenGlobal:'Ambient global "{{name}}" is forbidden in {{layer}} (ark.config.json); inject the capability through a port instead.',forbiddenGlobalDefault:'Ambient global "{{name}}" is forbidden here; inject the capability through a port instead.',forbiddenModule:'{{layer}} must not use module "{{specifier}}" because it is the import form of forbidden global "{{name}}".'},schema:[{type:"object",properties:{globals:{type:"array",items:{type:"string"}}},additionalProperties:!1}]},create(e){let t=L(e),n=e.options?.[0],r=T(t),s=r?j(r):null,i=r?p.default.dirname(r):null,a=null,c="this layer";if(s&&i&&t){let o=p.default.isAbsolute(t)?t:p.default.resolve(t),l=p.default.relative(i,o).split(p.default.sep).join("/");if(!W(s,l))return{};let u=s.layers?.find(m=>m.name===R(l,s.layers));u?.forbiddenGlobals?.length?(a=new Set(u.forbiddenGlobals),c=u.name):a=null}else n?.globals&&(a=new Set(n.globals));if(!a)return{};let g=typeof J(e)?.getScope=="function",f=(o,l)=>{let u=p.default.isAbsolute(t)?t:p.default.resolve(t),m=i?p.default.relative(i,u).split(p.default.sep).join("/"):t;w(e,o,s?"forbiddenGlobal":"forbiddenGlobalDefault",{ruleId:"FORBIDDEN_GLOBAL",file:m,fromLayer:c,target:l,message:`${c} must not use the ambient global "${l}".`},{name:l,layer:c})},d=(o,l,u,m)=>{if(u||typeof l!="string")return;let y=H(l,a);if(!y)return;let h=p.default.isAbsolute(t)?t:p.default.resolve(t),A=i?p.default.relative(i,h).split(p.default.sep).join("/"):t;w(e,o,"forbiddenModule",{ruleId:"FORBIDDEN_GLOBAL",file:A,fromLayer:c,target:l,edgeKind:m,message:`${c} must not use module "${l}" because it is the import form of forbidden global "${y}".`},{layer:c,name:y,specifier:l,importKind:m})};return{MemberExpression(o){if(o.parent?.type==="MemberExpression"&&o.parent.object===o)return;let l=Ie(o);if(!l||P(e,l.root,l.segments[0]))return;let u=l.segments[0]==="globalThis",m=u?l.segments.slice(1):l.segments,y;for(let h=m.length;h>=(u?1:2);h-=1){let A=m.slice(0,h).join(".");if(a.has(A)){y=A;break}}y?f(o,y):!g&&a.has(l.segments[0])&&f(o,l.segments[0])},CallExpression(o){let l=o;if(l.callee?.type==="Identifier"&&l.callee.name==="require"&&l.arguments?.[0]?.type==="Literal"&&!P(e,o,"require")&&d(o,l.arguments[0].value,!1,"require"),g)return;let u=l.callee?.type==="Identifier"?l.callee.name:void 0;u&&a.has(u)&&f(o,u)},ImportDeclaration(o){let l=o,u=(l.specifiers??[]).filter(y=>y.type==="ImportSpecifier"),m=u.length>0&&u.length===(l.specifiers??[]).length&&u.every(y=>y.importKind==="type");d(o,l.source?.value,l.importKind==="type"||m,"import")},ImportExpression(o){let l=o;l.source?.type==="Literal"&&d(o,l.source.value,!1,"dynamic-import")},TSImportEqualsDeclaration(o){let l=o;d(o,l.moduleReference?.expression?.value,l.importKind==="type"||l.isTypeOnly===!0,"require")},ExportNamedDeclaration(o){let l=o;if(!l.source)return;let u=l.specifiers??[],m=u.length>0&&u.every(y=>y.exportKind==="type");d(o,l.source.value,l.exportKind==="type"||m,"export")},ExportAllDeclaration(o){let l=o;d(o,l.source?.value,l.exportKind==="type","export")},NewExpression(o){if(g)return;let l=o.callee?.type==="Identifier"?o.callee.name:void 0;l&&a.has(l)&&f(o,l)},Identifier(o){!g||!o.name||!a.has(o.name)||!st(e,o)||P(e,o,o.name)||f(o,o.name)}}}},Ne={meta:{type:"problem",docs:{description:"Disallow importing modules whose effect capability the layer denies (ark.config.json capabilities.deny / pure \u2014 same wall surface as ark-check). Import dimension only: ambient globals stay with no-forbidden-globals and the CLI/hook symbol path."},messages:{deniedCapability:'{{layer}} denies the {{capability}} capability (ark.config.json); "{{specifier}}" imports it. Define a port and bind the implementation in an adapter layer.'},schema:[]},create(e){let t=L(e),n=T(t),r=n?j(n):null,s=n?p.default.dirname(n):null;if(!r||!s||!t)return{};let i=p.default.isAbsolute(t)?t:p.default.resolve(t),a=p.default.relative(s,i).split(p.default.sep).join("/");if(!W(r,a))return{};let c=r.layers?.find(d=>d.name===R(a,r.layers));if(!c)return{};let g=new Set(ae(c));if(g.size===0)return{};let f=(d,o,l,u)=>{if(l||typeof o!="string"||H(o,c.forbiddenGlobals??[]))return;let m=ie(o);!m||!g.has(m)||w(e,d,"deniedCapability",{ruleId:"CAPABILITY_VIOLATION",file:a,fromLayer:c.name,target:o,capability:m,edgeKind:u,message:`${c.name} denies the ${m} capability; found import of "${o}".`},{layer:c.name,capability:m,specifier:o})};return{ImportDeclaration(d){let o=d,l=(o.specifiers??[]).filter(m=>m.type==="ImportSpecifier"),u=l.length>0&&l.length===(o.specifiers??[]).length&&l.every(m=>m.importKind==="type");f(d,o.source?.value,o.importKind==="type"||u,"import")},ImportExpression(d){let o=d;o.source?.type==="Literal"&&f(d,o.source.value,!1,"dynamic-import")},TSImportEqualsDeclaration(d){let o=d;f(d,o.moduleReference?.expression?.value,o.importKind==="type"||o.isTypeOnly===!0,"require")},ExportNamedDeclaration(d){let o=d;if(!o.source)return;let l=o.specifiers??[],u=l.length>0&&l.every(m=>m.exportKind==="type");f(d,o.source.value,o.exportKind==="type"||u,"export")},ExportAllDeclaration(d){let o=d;f(d,o.source?.value,o.exportKind==="type","export")},CallExpression(d){let o=d;o.callee?.type==="Identifier"&&o.callee.name==="require"&&o.arguments?.[0]?.type==="Literal"&&!P(e,d,"require")&&f(d,o.arguments[0].value,!1,"require")}}}},ct={"no-domain-infra-imports":we,"no-raw-event-publish":Ee,"require-publish-source":Ce,"no-forbidden-globals":Le,"no-denied-capabilities":Ne},v={rules:ct};v.configs={recommended:{plugins:{ark:v},rules:{"ark/no-domain-infra-imports":"error","ark/no-raw-event-publish":"error","ark/require-publish-source":"error","ark/no-forbidden-globals":"error","ark/no-denied-capabilities":"error"}}};var dt=v;0&&(module.exports={findConfigPath,globToRegExp,isEdgeDenied,layerForRelativePath,loadArkConfig,noDeniedCapabilities,noDomainInfraImports,noForbiddenGlobals,noRawEventPublish,patternSpecificity,plugin,readTsconfigPathAliases,requirePublishSource,resolveImportSpecifier,resolveRelativeImport});