arkgate 4.8.5 → 4.8.6

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 (62) hide show
  1. package/CHANGELOG.md +33 -2
  2. package/README.md +15 -9
  3. package/bin/lib/analysis-engine.mjs +4 -4
  4. package/bin/lib/ark-order-invariants.mjs +163 -14
  5. package/bin/lib/ark-order-types.mjs +3 -0
  6. package/bin/lib/diagnostic-catalog.mjs +5 -4
  7. package/bin/lib/remediation.mjs +11 -5
  8. package/dist/{diagnosticCatalog-DMO30svh.d.ts → diagnosticCatalog-D_DI7qrZ.d.ts} +1 -1
  9. package/dist/eslint/index.cjs +1 -1
  10. package/dist/eslint/index.js +1 -1
  11. package/dist/index.cjs +11 -11
  12. package/dist/index.d.ts +2 -2
  13. package/dist/index.js +10 -10
  14. package/dist/nestjs/index.cjs +5 -5
  15. package/dist/nestjs/index.d.ts +1 -1
  16. package/dist/nestjs/index.js +5 -5
  17. package/dist/order/index.cjs +1 -1
  18. package/dist/order/index.d.ts +61 -10
  19. package/dist/order/index.js +1 -1
  20. package/dist/runtime/index.cjs +11 -11
  21. package/dist/runtime/index.d.ts +3 -3
  22. package/dist/runtime/index.js +11 -11
  23. package/dist/{types-CzE6LMaW.d.ts → types-DrqsOiTY.d.ts} +21 -6
  24. package/docs/README.md +5 -4
  25. package/docs/agent-guide.md +2 -0
  26. package/docs/ai-gates.md +5 -2
  27. package/docs/arkorder.md +32 -14
  28. package/docs/configuration.md +5 -3
  29. package/docs/develop.md +7 -2
  30. package/docs/diagnostics.md +15 -5
  31. package/docs/package-surface.md +13 -10
  32. package/docs/product-voice.md +3 -3
  33. package/docs/use.md +1 -1
  34. package/package.json +1 -1
  35. package/server.json +2 -2
  36. package/templates/agent-skills/README.md +1 -1
  37. package/templates/agent-skills/ark-adopt/SKILL.md +4 -4
  38. package/templates/agent-skills/ark-architect/SKILL.md +1 -1
  39. package/templates/agent-skills/ark-autopilot/SKILL.md +4 -4
  40. package/templates/agent-skills/ark-contract/SKILL.md +1 -1
  41. package/templates/agent-skills/ark-coverage/SKILL.md +3 -2
  42. package/templates/agent-skills/ark-explain/SKILL.md +3 -2
  43. package/templates/agent-skills/ark-explore/SKILL.md +3 -2
  44. package/templates/agent-skills/ark-fix/SKILL.md +1 -1
  45. package/templates/agent-skills/ark-loop/SKILL.md +1 -1
  46. package/templates/agent-skills/ark-place/SKILL.md +8 -8
  47. package/templates/agent-skills/ark-runtime/SKILL.md +3 -0
  48. package/templates/agent-skills/ark-think/SKILL.md +2 -2
  49. package/templates/agent-skills/ark-upgrade/SKILL.md +2 -2
  50. package/templates/skills/ark-adopt.md +4 -4
  51. package/templates/skills/ark-architect.md +1 -1
  52. package/templates/skills/ark-autopilot.md +4 -4
  53. package/templates/skills/ark-contract.md +1 -1
  54. package/templates/skills/ark-coverage.md +3 -2
  55. package/templates/skills/ark-explain.md +3 -2
  56. package/templates/skills/ark-explore.md +3 -2
  57. package/templates/skills/ark-fix.md +1 -1
  58. package/templates/skills/ark-loop.md +1 -1
  59. package/templates/skills/ark-place.md +8 -8
  60. package/templates/skills/ark-runtime.md +3 -0
  61. package/templates/skills/ark-think.md +2 -2
  62. package/templates/skills/ark-upgrade.md +2 -2
@@ -9,9 +9,17 @@
9
9
  */
10
10
 
11
11
  import { ArkOrderError } from './ark-order-error.mjs';
12
- import { DEFAULT_MAX_XI_KEYS } from './ark-order-types.mjs';
12
+ import { CAPACITY_OPS, DEFAULT_MAX_XI_KEYS } from './ark-order-types.mjs';
13
13
  import { deterministicHash, stableSerialize } from './stableHash';
14
14
  export { DEFAULT_MAX_XI_KEYS };
15
+ /** D7: consumer still owns handlers — this only names the travel verb. */
16
+ export function ingestTravelAction(residual) {
17
+ if (residual.kind === 'absorb')
18
+ return 'send';
19
+ if (residual.kind === 'escalate_up' && residual.target === 'human')
20
+ return 'raises';
21
+ return 'none';
22
+ }
15
23
  const FORBIDDEN_PLANE_METHODS = ['update', 'patch', 'set', 'mutate'];
16
24
  export function isForbiddenPlaneMethod(name) {
17
25
  return FORBIDDEN_PLANE_METHODS.includes(name);
@@ -70,9 +78,39 @@ export function assertXiSchema(xi, schema) {
70
78
  }
71
79
  }
72
80
  }
73
- export function hashReleasePayload(xi, sigma) {
81
+ function catalogDigestFor(xi, catalogDigest) {
82
+ if (typeof catalogDigest !== 'string')
83
+ return undefined;
84
+ if (!Object.prototype.hasOwnProperty.call(xi, 'catalogReleaseId'))
85
+ return undefined;
86
+ return catalogDigest;
87
+ }
88
+ export function hashReleasePayload(xi, sigma, catalogDigest) {
89
+ const digest = catalogDigestFor(xi, catalogDigest);
90
+ if (digest !== undefined)
91
+ return deterministicHash(stableSerialize({ xi, sigma, catalogDigest: digest }));
74
92
  return deterministicHash(stableSerialize({ xi, sigma }));
75
93
  }
94
+ export function hashXiIdentity(xi, catalogDigest) {
95
+ const digest = catalogDigestFor(xi, catalogDigest);
96
+ if (digest !== undefined)
97
+ return deterministicHash(stableSerialize({ xi, catalogDigest: digest }));
98
+ return deterministicHash(stableSerialize({ xi }));
99
+ }
100
+ export function hashSigmaIdentity(sigma) {
101
+ return deterministicHash(stableSerialize({ sigma }));
102
+ }
103
+ export function xiRecordsEqual(left, right) {
104
+ return stableSerialize(left) === stableSerialize(right);
105
+ }
106
+ /** D1: after the first freeze, a later release() may not change ξ. */
107
+ export function assertUnvalvedRelease(current, nextXi) {
108
+ if (!current)
109
+ return;
110
+ if (xiRecordsEqual(current.xi, nextXi))
111
+ return;
112
+ throw new ArkOrderError('ARKORDER_UNVALVED_RELEASE', 'ξ is frozen; change the pattern with proposeRelease then apply(ProposeResult)');
113
+ }
76
114
  export function createFrozenRelease(input) {
77
115
  assertXiKeyCap(input.xi, input.maxXiKeys);
78
116
  const xi = freezeRecord(input.xi, 'ξ');
@@ -81,13 +119,28 @@ export function createFrozenRelease(input) {
81
119
  const sigma = freezeRecord(input.sigma ?? {}, 'σ');
82
120
  const release = Object.freeze({
83
121
  version: input.version,
84
- hash: hashReleasePayload(xi, sigma),
122
+ hash: hashReleasePayload(xi, sigma, input.catalogDigest),
123
+ xiHash: hashXiIdentity(xi, input.catalogDigest),
124
+ sigmaHash: hashSigmaIdentity(sigma),
85
125
  xi,
86
126
  sigma,
87
127
  releasedAt: input.now,
88
128
  });
89
129
  return release;
90
130
  }
131
+ /** D2: refresh σ without minting a pattern. xiHash must not change. */
132
+ export function refreshSigmaRecord(input) {
133
+ const sigma = freezeRecord(input.sigma, 'σ');
134
+ return Object.freeze({
135
+ version: input.current.version,
136
+ hash: hashReleasePayload(input.current.xi, sigma, input.catalogDigest),
137
+ xiHash: input.current.xiHash,
138
+ sigmaHash: hashSigmaIdentity(sigma),
139
+ xi: input.current.xi,
140
+ sigma,
141
+ releasedAt: input.now,
142
+ });
143
+ }
91
144
  const XI_TTL_KEY_RE = /^(ttl|freshUntil|fresh_until|maxAge|max_age)$/i;
92
145
  export function assertXiHasNoTtl(xi) {
93
146
  for (const key of Object.keys(xi)) {
@@ -121,28 +174,101 @@ export function assertSigmaFresh(input) {
121
174
  throw new ArkOrderError('ARKORDER_STALE_SIGMA', 'σ is older than sigmaMaxAgeMs; ξ does not TTL');
122
175
  }
123
176
  }
124
- export function classifyIngest(projection, event, packs = []) {
177
+ export function fieldEventIdentity(event) {
178
+ return deterministicHash(stableSerialize({ kind: event.kind, payload: event.payload ?? null }));
179
+ }
180
+ function bindResidual(event, xiHash) {
181
+ return { event, xiHash, eventId: fieldEventIdentity(event) };
182
+ }
183
+ const CAPACITY_OP_SET = new Set(CAPACITY_OPS);
184
+ function isCapacityOp(value) {
185
+ return typeof value === 'string' && CAPACITY_OP_SET.has(value);
186
+ }
187
+ function numericLeaf(value) {
188
+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
189
+ }
190
+ function compareCapacity(left, op, right) {
191
+ if (op === 'lte')
192
+ return left <= right;
193
+ if (op === 'lt')
194
+ return left < right;
195
+ if (op === 'gte')
196
+ return left >= right;
197
+ return left > right;
198
+ }
199
+ function packHasFunction(value) {
200
+ if (typeof value === 'function')
201
+ return true;
202
+ if (value === null || typeof value !== 'object')
203
+ return false;
204
+ if (Array.isArray(value))
205
+ return value.some(packHasFunction);
206
+ return Object.values(value).some(packHasFunction);
207
+ }
208
+ function evaluateCapacity(event, sigma, pack) {
209
+ const rows = pack.capacity ?? [];
210
+ for (const row of rows) {
211
+ if (packHasFunction(row) || !isCapacityOp(row.op))
212
+ return 'pack';
213
+ if (row.kind !== event.kind)
214
+ continue;
215
+ const payload = event.payload && typeof event.payload === 'object' && !Array.isArray(event.payload)
216
+ ? numericLeaf(event.payload[row.payloadKey])
217
+ : undefined;
218
+ const limit = numericLeaf(sigma[row.sigmaKey]);
219
+ if (payload === undefined || limit === undefined)
220
+ return 'pack';
221
+ if (!compareCapacity(payload, row.op, limit))
222
+ return 'capacity';
223
+ }
224
+ return 'ok';
225
+ }
226
+ export function classifyIngest(projection, event, packs = [], xiHash = '', sigma = Object.freeze({})) {
125
227
  const kind = event.kind;
228
+ const bound = bindResidual(event, xiHash);
126
229
  for (const pack of packs) {
230
+ if (packHasFunction(pack.capacity) || packHasFunction(pack.escalateKinds)) {
231
+ return {
232
+ ...bound,
233
+ kind: 'hold',
234
+ reasonCode: 'pack',
235
+ reason: `pack ${pack.id} is not data-only; user predicates are forbidden`,
236
+ };
237
+ }
127
238
  if (pack.escalateKinds?.includes(kind)) {
128
239
  const target = pack.escalateTarget ?? 'human';
129
240
  return {
130
- kind: 'escalate',
131
- event,
241
+ ...bound,
242
+ kind: 'escalate_up',
243
+ reasonCode: 'pack',
132
244
  reason: `pack ${pack.id} slaves kind ${JSON.stringify(kind)} to a pattern change`,
133
245
  target,
134
246
  };
135
247
  }
136
248
  }
137
- if (projection.allowedKinds.includes(kind)) {
138
- return { kind: 'absorb', event };
249
+ if (!projection.allowedKinds.includes(kind)) {
250
+ return {
251
+ ...bound,
252
+ kind: 'escalate_up',
253
+ reasonCode: 'not-in-pattern',
254
+ reason: `kind ${JSON.stringify(kind)} is not allowed by h(ξ); field cannot rewrite the pattern`,
255
+ target: 'human',
256
+ };
139
257
  }
140
- return {
141
- kind: 'escalate',
142
- event,
143
- reason: `kind ${JSON.stringify(kind)} is not allowed by h(ξ); field cannot rewrite the pattern`,
144
- target: 'human',
145
- };
258
+ for (const pack of packs) {
259
+ const cap = evaluateCapacity(event, sigma, pack);
260
+ if (cap === 'ok')
261
+ continue;
262
+ return {
263
+ ...bound,
264
+ kind: 'hold',
265
+ reasonCode: cap,
266
+ reason: cap === 'capacity'
267
+ ? `pack ${pack.id} capacity ${JSON.stringify(event.kind)} does not hold`
268
+ : `pack ${pack.id} capacity is not numeric data`,
269
+ };
270
+ }
271
+ return { ...bound, kind: 'absorb' };
146
272
  }
147
273
  export function blastRadiusOf(previous, next) {
148
274
  const prev = new Set(previous.allowedKinds);
@@ -179,6 +305,7 @@ export function proposePatternChange(input) {
179
305
  now: input.now,
180
306
  maxXiKeys: input.maxXiKeys,
181
307
  xiSchema: input.xiSchema,
308
+ catalogDigest: input.catalogDigest,
182
309
  });
183
310
  if (candidate.hash === input.current.hash) {
184
311
  throw new ArkOrderError('ARKORDER_EMPTY_BLAST', 'delta does not change ξ; that is not a pattern change');
@@ -195,3 +322,25 @@ export function proposePatternChange(input) {
195
322
  invalidations,
196
323
  };
197
324
  }
325
+ /** D1 valve: freeze ProposeResult.nextXi. Empty blast still fails. */
326
+ export function applyProposedRelease(input) {
327
+ const candidate = createFrozenRelease({
328
+ xi: { ...input.proposal.nextXi },
329
+ sigma: { ...input.current.sigma },
330
+ version: input.current.version + 1,
331
+ now: input.now,
332
+ maxXiKeys: input.maxXiKeys,
333
+ xiSchema: input.xiSchema,
334
+ catalogDigest: input.catalogDigest,
335
+ });
336
+ if (xiRecordsEqual(candidate.xi, input.current.xi)) {
337
+ throw new ArkOrderError('ARKORDER_EMPTY_BLAST', 'delta does not change ξ; that is not a pattern change');
338
+ }
339
+ const previous = input.projector(input.current, input.current.sigma);
340
+ const next = input.projector(candidate, candidate.sigma);
341
+ const { blastRadius } = blastRadiusOf(previous, next);
342
+ if (blastRadius.length === 0) {
343
+ throw new ArkOrderError('ARKORDER_EMPTY_BLAST', 'pattern change has empty blast radius; that key is not an order parameter');
344
+ }
345
+ return candidate;
346
+ }
@@ -9,3 +9,6 @@
9
9
  */
10
10
 
11
11
  export const DEFAULT_MAX_XI_KEYS = 7;
12
+ export const INGEST_RESIDUAL_KINDS = ['absorb', 'escalate_up', 'hold'];
13
+ export const INGEST_REASON_CODES = ['not-in-pattern', 'stale-sigma', 'pack', 'capacity'];
14
+ export const CAPACITY_OPS = ['lte', 'lt', 'gte', 'gt'];
@@ -67,13 +67,14 @@ export const DIAGNOSTIC_CATALOG = Object.freeze([
67
67
  entry('ARKRUN_TRANSPORT_BYPASS', 'arkrun', 'Homemade broker or emitter import', 'A managed layer imports a closed broker/queue/emitter specifier (EventEmitter, queue clients, …) instead of the ArkRun kernel transport.', 'Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe — homemade buses stay judgment.'),
68
68
  entry('ARKORDER_MISSING_PLANE', 'arkorder', 'No createOrderPlane in plane roots', 'The ArkOrder extra is on but no createOrderPlane factory was found in arkOrder.planeRoots, so agents can skip the pattern plane while the write gate stays green.', 'Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe — factory placement is a design decision.'),
69
69
  entry('ARKORDER_KERNEL_IN_DOMAIN', 'arkorder', 'Domain-role layer imports the order plane', 'A Domain-role layer imports arkgate/order. Domain stays plane-free; planeRoots own the factory.', 'Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe.'),
70
- entry('ARKORDER_GENERIC_UPDATE', 'arkorder', 'Generic update of ξ', 'A call to update/patch/set on the order plane rewrites the slow pattern. Haken slaving forbids generic ξ mutation.', 'Use release() to freeze ξ or proposeRelease() for a pattern change with blast radius, then preflight again. Never mechanical-safe.'),
70
+ entry('ARKORDER_GENERIC_UPDATE', 'arkorder', 'Generic update of ξ', 'A call to update/patch/set on the order plane rewrites the slow pattern. Haken slaving forbids generic ξ mutation.', 'Use release() for the first freeze of ξ. Later pattern change is proposeRelease then apply(ProposeResult). Never update/patch/set. Never mechanical-safe.'),
71
71
  entry('ARKORDER_TOO_MANY_PARAMS', 'arkorder', 'Too many slow keys', 'ξ has more keys than arkOrder.maxXiKeys. Haken requires a few slow modes, not a dump of microstate.', 'Cut ξ to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe.'),
72
- entry('ARKORDER_INGEST_WRITES_XI', 'arkorder', 'ingest assigned into ξ', 'An ingest() result is written into a Release or ξ store. ingest may absorb or escalate; it never mints a pattern.', 'Keep ingest results as absorb/escalate only. Change ξ with proposeRelease + release. Never mechanical-safe.'),
73
- entry('ARKORDER_XI_FIELD_WRITE', 'arkorder', 'Slow key written around the order plane', 'A managed-layer file imports a persistence driver and writes a declared arkOrder.xiKeys name. Field events absorb or escalate; they do not PATCH the slow pattern.', 'Keep invoices, seats, hours, and logs on ingest. Change the slow key with proposeRelease + release, then preflight again. Never mechanical-safe.'),
72
+ entry('ARKORDER_INGEST_WRITES_XI', 'arkorder', 'ingest assigned into ξ', 'An ingest() result is written into a Release or ξ store. ingest may absorb, escalate_up, or hold; it never mints a pattern.', 'Keep ingest results as absorb/escalate_up/hold only. Change ξ with proposeRelease then apply(ProposeResult). Never mechanical-safe.'),
73
+ entry('ARKORDER_XI_FIELD_WRITE', 'arkorder', 'Slow key written around the order plane', 'A managed-layer file imports a persistence driver and writes a declared arkOrder.xiKeys name. Field events absorb or escalate; they do not PATCH the slow pattern.', 'Keep invoices, seats, hours, and logs on ingest. Change the slow key with proposeRelease then apply(ProposeResult), then preflight again. Never mechanical-safe.'),
74
74
  entry('ARKORDER_INFORMATION_BUDGET', 'arkorder', 'Projection observes a forbidden kind', 'h(ξ) allowedKinds includes a kind listed in informationBudget.cannotObserve. A scale may not look at what it was told not to see.', 'Cut that kind from the projector or from cannotObserve, then preflight again. Never mechanical-safe.'),
75
75
  entry('ARKORDER_XI_TTL', 'arkorder', 'Slow key carries a freshness field', 'ξ named ttl/freshUntil/maxAge. Freshness belongs on σ. A slow parameter that expires per transaction is not slow.', 'Move freshness onto σ (freshUntil) and keep ξ stable, then preflight again. Never mechanical-safe.'),
76
- entry('ARKORDER_STALE_SIGMA', 'arkorder', 'σ is stale', 'ingest ran after σ.freshUntil (or sigmaMaxAgeMs). ξ does not TTL.', 'Refresh σ and ingest again, or freeze a new release if the pattern changed. Never mechanical-safe.'),
76
+ entry('ARKORDER_STALE_SIGMA', 'arkorder', 'σ is stale', 'ingest ran after σ.freshUntil (or sigmaMaxAgeMs). ξ does not TTL.', 'Call refreshSigma and ingest again, or proposeRelease then apply(ProposeResult) if the pattern changed. Never mechanical-safe.'),
77
+ entry('ARKORDER_UNVALVED_RELEASE', 'arkorder', 'Unvalved second freeze of ξ', 'release() ran after a pattern was already frozen and the new ξ differs. First freeze is release(); later pattern change is proposeRelease then apply.', 'Change ξ with proposeRelease then apply(ProposeResult). release() is only the first freeze. Never mechanical-safe.'),
77
78
  // ── atomic preflight / change set ────────────────────────────────────────
78
79
  entry('INVALID_CHANGE_PATH', 'preflight', 'Unsafe change path', 'A change set entry is not a safe, non-empty project-relative path (absolute, escape, empty, or NUL).', 'Use canonical project-relative paths only in the atomic change set, then preflight again.'),
79
80
  entry('DUPLICATE_CHANGE_PATH', 'preflight', 'Duplicate path in change set', 'The atomic change set lists more than one operation for the same path.', 'Collapse to one create/update/delete per path, then preflight again.'),
@@ -107,6 +107,7 @@ const ARKORDER_JUDGMENT_RULE_IDS = new Set([
107
107
  'ARKORDER_TOO_MANY_PARAMS',
108
108
  'ARKORDER_INGEST_WRITES_XI',
109
109
  'ARKORDER_XI_FIELD_WRITE',
110
+ 'ARKORDER_UNVALVED_RELEASE',
110
111
  ]);
111
112
  function arkRunCallSiteName(violation) {
112
113
  return typeof violation.target === 'string' && violation.target.trim().length > 0
@@ -238,15 +239,17 @@ export function deterministicNextAction(violation) {
238
239
  case 'ARKORDER_KERNEL_IN_DOMAIN':
239
240
  return 'Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe.';
240
241
  case 'ARKORDER_GENERIC_UPDATE':
241
- return 'Use release() to freeze ξ or proposeRelease() for a pattern change with blast radius, then preflight again. Never mechanical-safe.';
242
+ return 'Use release() for the first freeze of ξ. Later pattern change is proposeRelease then apply(ProposeResult). Never update/patch/set. Never mechanical-safe.';
242
243
  case 'ARKORDER_TOO_MANY_PARAMS':
243
244
  return 'Cut ξ to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe.';
244
245
  case 'ARKORDER_INGEST_WRITES_XI':
245
- return 'Keep ingest results as absorb/escalate only. Change ξ with proposeRelease + release. Never mechanical-safe.';
246
+ return 'Keep ingest results as absorb/escalate_up/hold only. Change ξ with proposeRelease then apply(ProposeResult). Never mechanical-safe.';
246
247
  case 'ARKORDER_XI_FIELD_WRITE':
247
248
  return typeof violation.target === 'string' && violation.target.length > 0
248
- ? `Do not persist slow key ${violation.target} from a use-case. Absorb the field with ingest() or change the pattern with proposeRelease(), then preflight again.`
249
- : 'Do not persist a declared slow key from a use-case. Absorb the field with ingest() or change the pattern with proposeRelease(), then preflight again. Never mechanical-safe.';
249
+ ? `Do not persist slow key ${violation.target} from a use-case. Absorb the field with ingest() or change the pattern with proposeRelease then apply, then preflight again.`
250
+ : 'Do not persist a declared slow key from a use-case. Absorb the field with ingest() or change the pattern with proposeRelease then apply, then preflight again. Never mechanical-safe.';
251
+ case 'ARKORDER_UNVALVED_RELEASE':
252
+ return 'Change ξ with proposeRelease then apply(ProposeResult). release() is only the first freeze. Never mechanical-safe.';
250
253
  default:
251
254
  if (typeof violation.ruleId === 'string' && violation.ruleId.startsWith('ARKRULE_')) {
252
255
  return `Fix the ArkRule ${typeof violation.arkruleId === 'string' ? violation.arkruleId : violation.ruleId}, then preflight again.`;
@@ -520,6 +523,7 @@ export function enrichViolationWithFixClass(violation) {
520
523
  case 'ARKORDER_INFORMATION_BUDGET':
521
524
  case 'ARKORDER_XI_TTL':
522
525
  case 'ARKORDER_STALE_SIGMA':
526
+ case 'ARKORDER_UNVALVED_RELEASE':
523
527
  enriched.fixClass = 'arkorder-usage';
524
528
  enriched.effort = 'medium';
525
529
  enriched.enthusiastHint =
@@ -539,7 +543,9 @@ export function enrichViolationWithFixClass(violation) {
539
543
  ? 'TTL is σ, never ξ. A slow key that expires is not an order parameter.'
540
544
  : violation.ruleId === 'ARKORDER_STALE_SIGMA'
541
545
  ? 'Refresh σ. ξ does not expire.'
542
- : 'Call createOrderPlane from arkgate/order in a listed plane root so the app actually freezes a pattern.';
546
+ : violation.ruleId === 'ARKORDER_UNVALVED_RELEASE'
547
+ ? 'The pattern is frozen. proposeRelease then apply — do not call release() again with a different ξ.'
548
+ : 'Call createOrderPlane from arkgate/order in a listed plane root so the app actually freezes a pattern.';
543
549
  break;
544
550
  default:
545
551
  enriched.fixClass = 'review-contract';
@@ -409,7 +409,7 @@ declare const ARK_ANALYSIS_RESULT_SCHEMA: {
409
409
  };
410
410
 
411
411
  /** ArkGate library version — single source of truth. */
412
- declare const version = "4.8.5";
412
+ declare const version = "4.8.6";
413
413
 
414
414
  /**
415
415
  * AI Code Gate (basic).
@@ -1,6 +1,6 @@
1
1
  "use strict";var Br=Object.create;var V=Object.defineProperty;var Wr=Object.getOwnPropertyDescriptor;var zr=Object.getOwnPropertyNames;var qr=Object.getPrototypeOf,Zr=Object.prototype.hasOwnProperty;var c=(e,r)=>V(e,"name",{value:r,configurable:!0});var Yr=(e,r)=>{for(var t in r)V(e,t,{get:r[t],enumerable:!0})},Ce=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let s of zr(r))!Zr.call(e,s)&&s!==t&&V(e,s,{get:()=>r[s],enumerable:!(n=Wr(r,s))||n.enumerable});return e};var J=(e,r,t)=>(t=e!=null?Br(qr(e)):{},Ce(r||!e||!e.__esModule?V(t,"default",{value:e,enumerable:!0}):t,e)),Xr=e=>Ce(V({},"__esModule",{value:!0}),e);var Sn={};Yr(Sn,{default:()=>En,findConfigPath:()=>$,globToRegExp:()=>x,isEdgeDenied:()=>Me,layerForRelativePath:()=>E,loadArkConfig:()=>U,noArkOrderGenericUpdate:()=>jr,noArkOrderKernelInDomain:()=>Hr,noArkRunDirectNew:()=>$r,noArkRunKernelInDomain:()=>Mr,noArkRunTransportBypass:()=>Ur,noDeniedCapabilities:()=>Pr,noDomainInfraImports:()=>Tr,noForbiddenGlobals:()=>Kr,noRawEventPublish:()=>Dr,patternSpecificity:()=>de,plugin:()=>ae,readTsconfigPathAliases:()=>_r,requirePublishSource:()=>Fr,resolveImportSpecifier:()=>Ie,resolveRelativeImport:()=>Or});module.exports=Xr(Sn);var C=J(require("fs"),1),m=J(require("path"),1);var we=new Map;function ve(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}c(ve,"escapeLiteral");function Q(e){let r="";for(let t=0;t<e.length;t+=1){let n=e[t];if(n==="\\"&&t+1<e.length){let s=e[t+1];if("*?{}[],".includes(s)||s==="\\"){r+="\\"+s,t+=1;continue}r+="/";continue}r+=n}return r}c(Q,"normalizeGlobSeparators");function Jr(e){let r=0;for(let t=0;t<e.length;t+=1){let n=e[t];if(n==="\\"){t+=1;continue}if(n==="{")r+=1;else if(n==="}"&&(r-=1,r<0))return!1}return r===0}c(Jr,"bracesBalanced");function x(e){let r=we.get(e);if(r)return r;let t=Q(e),n=Jr(t),s="",o=0;for(let a=0;a<t.length;a+=1){let l=t[a];l==="\\"&&a+1<t.length?(s+=ve(t[a+1]),a+=1):l==="*"?t[a+1]==="*"?t[a+2]==="/"?(s+="(?:.*/)?",a+=2):(s+=".*",a+=1):s+="[^/]*":l==="?"?s+="[^/]":l==="{"&&n?(s+="(?:",o+=1):l==="}"&&n&&o>0?(s+=")",o-=1):l===","&&n&&o>0?s+="|":s+=ve(l)}let i=new RegExp(`^${s}$`);return we.set(e,i),i}c(x,"globToRegExp");function Qr(e){return Q(String(e)).split("/").filter(Boolean).filter(t=>t!=="**"&&t!=="*"&&!t.includes("*")&&!t.includes("?")&&!t.includes("{")&&!t.includes("["))}c(Qr,"concreteGlobSegments");function de(e,r){let t=Q(String(e)),n=Qr(t),s=t.replace(/\*/g,"").length,o=n.length*1e4+s;if(r==null||r==="")return o;let i=String(r).split(/[/\\]/).filter(Boolean);if(n.length===0)return s;let a=0,l=-1;for(let u of n){let d=-1;for(let p=a;p<i.length;p+=1)if(i[p]===u){d=p;break}if(d<0)return o;l=d,a=d+1}return(l+1)*1e6+n.length*1e4+s}c(de,"patternSpecificity");function E(e,r){let t=String(e).split(/[/\\]/).join("/"),n,s=-1;for(let o of r??[])if(!(o.exclude??[]).some(i=>x(i).test(t))){for(let i of o.patterns??[])if(x(i).test(t)){let a=de(i,t);a>s&&(s=a,n=o.name)}}return n}c(E,"layerForRelativePath");function Le(e,r){if(!r?.length)return;let t=String(e).split(/[/\\]/).filter(Boolean),n=new Set(r.map(s=>String(s).toLowerCase()));for(let s=0;s<t.length-1;s+=1)if(n.has(t[s].toLowerCase()))return`${t[s].toLowerCase()}/${t[s+1].toLowerCase()}`}c(Le,"sliceIdForPath");function et(e){let r=new Set;for(let t of e??[]){let s=Q(String(t)).split("/").filter(Boolean);for(let o=0;o<s.length;o+=1){let i=s[o];if((i==="**"||i==="*")&&o>0){let a=s[o-1];a&&!a.includes("*")&&!a.includes("{")&&!a.includes("}")&&r.add(a)}}}return[...r]}c(et,"inferSliceFoldersFromPatterns");function rt(e,r,t){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(s=>typeof s=="string"&&s.length>0);let n=(t??[]).find(s=>s.name===r);return et(n?.patterns)}c(rt,"resolveSliceFolders");function Te(e){return String(e).split(/[/\\]/).filter(r=>!!r&&r!==".").map(r=>r.toLowerCase())}c(Te,"normalizeSegments");function Ke(e){let r=e.length;for(;r>0&&e[r-1]==="/";)r-=1;return e.slice(0,r)}c(Ke,"trimTrailingSlashes");var tt=["src","app"];function nt(e){let r=Ke(e.replace(/^[./]+/,""));return r==="*"||r==="**"}c(nt,"isBlanketRoot");function De(e,r){if(!e||!r?.length)return!1;let t=String(e).split(/[/\\]/).join("/"),n=t.toLowerCase(),s=Te(t);for(let o of r){if(typeof o!="string"||o.length===0||nt(o))continue;if(o.includes("*")){let l=Ke(o.toLowerCase());if(x(l).test(n)||x(`${l}/**`).test(n))return!0;continue}let i=Te(o);if(i.length===0)continue;let a=tt.includes(s[0])&&i[0]!==s[0]?[0,1]:[0];for(let l of a){if(l+i.length>s.length)continue;let u=!0;for(let d=0;d<i.length;d+=1)if(s[l+d]!==i[d]){u=!1;break}if(u)return!0}}return!1}c(De,"pathUnderSharedRoot");function Fe(e,r){let t=String(e).split(/[/\\]/).filter(Boolean).join("/").toLowerCase();if(!t)return!1;let n=r.toLowerCase();return t===n?!0:!t.includes("/")&&n.endsWith(`/${t}`)}c(Fe,"sliceMatchesDeclaration");function st(e,r,t){return!e?.length||!r||!t?!1:e.some(n=>n&&typeof n.from=="string"&&typeof n.to=="string"&&Fe(n.from,r)&&Fe(n.to,t))}c(st,"crossSliceEdgeAllowed");function ot(e){if(!e.fromPath||!e.toPath)return{denied:!0,reason:"missing-path"};if(e.folderCount<=0)return{denied:!0,reason:"no-slice-folders"};let r=!!e.fromSlice||e.fromShared===!0,t=!!e.toSlice||e.toShared===!0;return!r||!t?{denied:!0,reason:"unclassifiable-path"}:!e.fromSlice||!e.toSlice?{denied:!1}:e.fromSlice===e.toSlice?{denied:!1}:e.crossSliceAllowed?{denied:!1}:{denied:!0,reason:"cross-slice"}}c(ot,"peerIsolationDecision");function Pe(e,r){switch(e){case"cross-slice":return`cross-slice edge ${r.fromSlice??"?"} \u2192 ${r.toSlice??"?"}. Extract the shared code, use events/ports across slices, or declare the edge in the rule's allowedCrossSlice.`;case"unclassifiable-path":{let t=[r.fromSlice?void 0:r.fromPath,r.toSlice?void 0:r.toPath].filter(s=>!!s);return`unclassifiable path${t.length>0?` (${t.join(", ")})`:""} \u2014 ArkGate cannot place it in a slice, so it cannot prove this is not a cross-slice edge. Move it into a slice, or declare its root in the rule's sharedRoots.`}case"no-slice-folders":return"no slice folders \u2014 peerIsolation is on but no slice folder resolves from the rule or the layer patterns. Set sliceFolders on the rule.";default:return"no path evidence for this edge \u2014 peerIsolation needs the importer and importee paths."}}c(Pe,"peerIsolationDenyExplanation");function it(e,r,t,n){return ue(e,r,t,n)?.rule}c(it,"findDeniedEdgeRule");function ue(e,r,t,n){for(let s of e??[])if(!(s.from!==r||s.to!==t)&&s.allowed===!1){if(s.peerIsolation){let o=n?.fromPath,i=n?.toPath,a=rt(s,r,n?.layers),l=o&&i?Le(o,a):void 0,u=o&&i?Le(i,a):void 0,d=ot({fromPath:o,toPath:i,folderCount:a.length,fromSlice:l,toSlice:u,fromShared:!l&&De(o,s.sharedRoots),toShared:!u&&De(i,s.sharedRoots),crossSliceAllowed:st(s.allowedCrossSlice,l,u)});if(d.denied)return{rule:s,peerIsolationReason:d.reason,fromSlice:l,toSlice:u};continue}if(r!==t)return{rule:s}}}c(ue,"findDeniedEdgeDecision");function Me(e,r,t,n){return it(e,r,t,n)!==void 0}c(Me,"isEdgeDenied");var at=["**/*.gen.ts","**/*.gen.tsx","**/*.generated.ts","**/*.generated.tsx"];function lt(e){let r=Array.isArray(e?.exclude)?e.exclude.filter(n=>typeof n=="string"):[];return[...e?.excludeGenerated===!1?[]:at,...r]}c(lt,"scanExcludePatterns");function $e(e,r){let t=String(e).split(/[/\\]/).join("/");return lt(r).some(n=>x(n).test(t))}c($e,"isScanExcludedRelative");var Ue=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),ct=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),On=Object.freeze(Object.keys(ct).sort()),pe=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"}),dt=Object.freeze({process:Object.freeze(["process","node:process"])});function He(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let r=pe[e];if(r)return r;let t=e.indexOf("/");if(t<0)return null;let n=e.slice(0,t),s=pe[n];if(s)return s;let o=e.indexOf("/",t+1);return o<0?null:pe[e.slice(0,o)]??null}c(He,"capabilityForModuleSpecifier");function fe(e,r){for(let t of r)if(dt[t]?.includes(e))return t;return null}c(fe,"forbiddenGlobalForModuleSpecifier");function je(e){if(e?.pure===!0)return[...Ue].sort();let t=(e?.capabilities?.deny??[]).filter(n=>Ue.includes(n));return[...new Set(t)].sort()}c(je,"effectiveCapabilityDeny");var F={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Ve={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...F,default:[]},kernelRoots:{...F},managedLayers:{...F,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},Ge={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...F,default:[]},managedLayers:{...F,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...F,default:[]}}};function G(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}c(G,"isObject");function Be(e){let r=new Set;if(!Array.isArray(e.layers))return r;for(let t of e.layers)G(t)&&typeof t.name=="string"&&t.name.length>0&&r.add(t.name);return r}c(Be,"declaredLayerNames");function We(e){if(!G(e))return e;let r={mode:e.mode===void 0?"advisory":e.mode,compositionRoots:e.compositionRoots===void 0?[]:e.compositionRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,requireDeclarations:e.requireDeclarations===void 0?!0:e.requireDeclarations};return e.kernelRoots!==void 0&&(r.kernelRoots=e.kernelRoots),e.ignoreDirectNewForErrors!==void 0&&(r.ignoreDirectNewForErrors=e.ignoreDirectNewForErrors),{...e,...r}}c(We,"defaultedArkRun");function ze(e){if(!G(e))return e;let r=typeof e.maxXiKeys=="number"&&e.maxXiKeys>0?e.maxXiKeys:7;return{...e,mode:e.mode===void 0?"advisory":e.mode,planeRoots:e.planeRoots===void 0?[]:e.planeRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,maxXiKeys:r,xiKeys:e.xiKeys===void 0?[]:e.xiKeys}}c(ze,"defaultedArkOrder");function qe(e,r){let t=e.arkRun;if(t===void 0||!G(t))return;let n=Be(e),s=t.managedLayers;if(Array.isArray(s)&&s.forEach((o,i)=>{typeof o=="string"&&o.length>0&&!n.has(o)&&r.push({path:`$.arkRun.managedLayers[${i}]`,message:`layer ${JSON.stringify(o)} is not declared in layers[]`})}),t.mode==="enforced"){let o=t.kernelRoots??t.compositionRoots;(!Array.isArray(o)||o.length===0)&&r.push({path:t.kernelRoots!==void 0?"$.arkRun.kernelRoots":"$.arkRun.compositionRoots",message:"ARKRUN_MISSING_ROOT: enforced mode requires at least one kernel root"}),(!Array.isArray(s)||s.length===0)&&r.push({path:"$.arkRun.managedLayers",message:"enforced mode requires at least one managed layer"})}}c(qe,"validateArkRunExtra");function Ze(e,r){let t=e.arkOrder;if(t===void 0||!G(t))return;let n=Be(e),s=t.managedLayers;if(Array.isArray(s)&&s.forEach((o,i)=>{typeof o=="string"&&o.length>0&&!n.has(o)&&r.push({path:`$.arkOrder.managedLayers[${i}]`,message:`layer ${JSON.stringify(o)} is not declared in layers[]`})}),t.mode==="enforced"){let o=t.planeRoots;(!Array.isArray(o)||o.length===0)&&r.push({path:"$.arkOrder.planeRoots",message:"ARKORDER_MISSING_PLANE: enforced mode requires at least one plane root"}),(!Array.isArray(s)||s.length===0)&&r.push({path:"$.arkOrder.managedLayers",message:"enforced mode requires at least one managed layer"})}}c(Ze,"validateArkOrderExtra");var I="1.3",ge="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",Ye=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],ut=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function pt(){let e=[];for(let r of Ye)for(let t of Ye)r===t||ut.has(`${r}->${t}`)||e.push({from:r,to:t,allowed:!1});return e}c(pt,"createDefaultRules");var Je=pt(),me=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"},{from:"1.1",to:"1.2"},{from:"1.2",to:"1.3"}],S={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Xe={$schema:"https://json-schema.org/draft/2020-12/schema",$id:ge,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:ge,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:I,default:I},name:{type:"string",minLength:1},include:{...S,minItems:1,default:["src"]},exclude:{...S,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:Je,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...S,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},coverage:{$ref:"#/$defs/coverage"},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},arkRun:{$ref:"#/$defs/arkRun"},arkOrder:{$ref:"#/$defs/arkOrder"},stewards:{...S,default:[]}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...S,minItems:1},exclude:S,intentPrefixes:S,description:{type:"string",minLength:1},forbiddenGlobals:S,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"},reserved:{type:"boolean"},allowEmpty:{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:{...S,minItems:1},sharedRoots:{...S,minItems:1},allowedCrossSlice:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength: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}}},coverage:{type:"object",additionalProperties:!1,description:"Invariant coverage scan controls. testGlobs replaces the built-in test-name heuristic; maxFiles raises or lowers the evidence file budget; coverageRoots declares where the project runs its tests, so a covering test found outside them is reported instead of silently certifying an invariant.",properties:{testGlobs:{...S,minItems:1},maxFiles:{type:"integer",minimum:1},coverageRoots:{...S,minItems:1}}},arkRun:Ve,arkOrder:Ge}},N=class extends Error{static{c(this,"ArkConfigValidationError")}issues;source;constructor(r,t){super(`Invalid ArkGate config (${r}):
2
2
  ${t.map(n=>`- ${n.path}: ${n.message}`).join(`
3
- `)}`),this.name="ArkConfigValidationError",this.source=r,this.issues=t}};function Qe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}c(Qe,"isObject");function ee(e,r){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(r)?`${e}.${r}`:`${e}[${JSON.stringify(r)}]`}c(ee,"propertyPath");function K(e){return e===null?"null":Array.isArray(e)?"array":typeof e}c(K,"valueType");function ft(e,r){let t="#/$defs/";if(e.startsWith(t))return r.$defs[e.slice(t.length)]}c(ft,"resolveSchemaRef");function B(e,r,t,n,s){if(r.$ref){let o=ft(r.$ref,n);if(!o){s.push({path:t,message:`schema reference ${r.$ref} cannot be resolved`});return}B(e,o,t,n,s);return}if(r.const!==void 0&&!Object.is(e,r.const)){s.push({path:t,message:`must equal ${JSON.stringify(r.const)}`});return}if(r.enum&&!r.enum.some(o=>Object.is(o,e))){s.push({path:t,message:`must be one of ${r.enum.map(String).join(", ")}`});return}if(r.type==="object"){if(!Qe(e)){s.push({path:t,message:`must be an object; received ${K(e)}`});return}let o=r.properties??{};for(let i of r.required??[])e[i]===void 0&&s.push({path:ee(t,i),message:"is required"});if(r.additionalProperties===!1)for(let i of Object.keys(e))i in o||s.push({path:ee(t,i),message:"unknown field"});else if(r.additionalProperties!==void 0&&r.additionalProperties!==!0&&typeof r.additionalProperties=="object"){let i=r.additionalProperties;for(let a of Object.keys(e))a in o||B(e[a],i,ee(t,a),n,s)}for(let[i,a]of Object.entries(o))e[i]!==void 0&&B(e[i],a,ee(t,i),n,s);return}if(r.type==="array"){if(!Array.isArray(e)){s.push({path:t,message:`must be an array; received ${K(e)}`});return}if(r.minItems!==void 0&&e.length<r.minItems&&s.push({path:t,message:`must contain at least ${r.minItems} item(s)`}),r.uniqueItems){let o=e.map(i=>JSON.stringify(i));new Set(o).size!==o.length&&s.push({path:t,message:"must not contain duplicate items"})}r.items&&e.forEach((o,i)=>B(o,r.items,`${t}[${i}]`,n,s));return}if(r.type==="string"){if(typeof e!="string"){s.push({path:t,message:`must be a string; received ${K(e)}`});return}r.minLength!==void 0&&e.length<r.minLength&&s.push({path:t,message:`must contain at least ${r.minLength} character(s)`});return}if(r.type==="boolean"){typeof e!="boolean"&&s.push({path:t,message:`must be a boolean; received ${K(e)}`});return}if(r.type==="integer"){if(!Number.isInteger(e)){s.push({path:t,message:`must be an integer; received ${K(e)}`});return}r.minimum!==void 0&&e<r.minimum&&s.push({path:t,message:`must be at least ${r.minimum}`})}}c(B,"validateNode");function gt(e){let r={...e,$schema:e.$schema===void 0?ge:e.$schema,schemaVersion:e.schemaVersion===void 0?I:e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?Je.map(t=>({...t})):e.rules};return e.arkRun!==void 0&&(r.arkRun=We(e.arkRun)),e.arkOrder!==void 0&&(r.arkOrder=ze(e.arkOrder)),r}c(gt,"defaultedConfig");function mt(e){return e===I?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}c(mt,"migratedFromOf");function yt(){let e=new Set([I]);for(let r of me)r.from!=="unversioned"&&e.add(r.from),e.add(r.to);return e}c(yt,"knownInputVersions");function Rt(e,r="ark.config.json"){if(!Qe(e))throw new N(r,[{path:"$",message:`must be an object; received ${K(e)}`}]);let t=yt(),n=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(n===null)throw new N(r,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected ${I}`}]);if(n!=="unversioned"&&!t.has(n))throw new N(r,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(n)}; expected ${I}`}]);let s=n,o={...e},i=0;for(;s!==I&&i<me.length+1;){i+=1;let a=me.find(l=>l.from===s);if(!a)throw new N(r,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(s)}; expected ${I}`}]);s=a.to,o.schemaVersion=s}if(s!==I)throw new N(r,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(n)}; expected ${I}`}]);return{candidate:gt(o),migratedFrom:mt(n)}}c(Rt,"migrateArkConfig");function ht(e,r="ark.config.json"){let{candidate:t,migratedFrom:n}=Rt(e,r),s=[];if(B(t,Xe,"$",Xe,s),qe(t,s),Ze(t,s),s.length>0)throw new N(r,s);return{config:t,migratedFrom:n}}c(ht,"loadArkConfigContract");function er(e,r="ark.config.json"){let t;try{t=JSON.parse(e)}catch(n){throw new N(r,[{path:"$",message:`invalid JSON: ${n instanceof Error?n.message:String(n)}`}])}return ht(t,r)}c(er,"parseArkConfigJson");var At=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,kt=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,bt=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function Et(e,r){let t=String(e??"").replace(/\\/g,"/").trim(),n=String(r?.fromLayer??""),s=String(r?.toLayer??"");return At.test(t)?"pure-shared":n==="PersistenceAdapters"&&(kt.test(t)||/events?|intents?|kernel|bootstrap/i.test(`${s} ${t}`))?"kernel-emit":bt.test(t)||(n==="DomainModel"||n==="ApplicationOrchestration")&&s==="PersistenceAdapters"?"use-case":"unknown"}c(Et,"classifyLayerImportKind");function St(e){if(e.typeOnly||e.targetTypeOnlyExports||e.namedBindingsTypeOnly)return"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.";if(e.peerIsolation)return"Extract the shared dependency to a shared layer, test at the public interface, then preflight again.";let r=Et(typeof e.target=="string"?e.target:"",{fromLayer:typeof e.fromLayer=="string"?e.fromLayer:void 0,toLayer:typeof e.toLayer=="string"?e.toLayer:void 0});return r==="pure-shared"?"Adopt the imported constants/types/pure module into DomainModel or SharedKernel (do not inject a port). Then preflight again.":r==="kernel-emit"?"Persistence must not emit. Inject a port or move the event map to SharedTypes; do not import kernel/events/bootstrap from a repository. Then preflight again.":r==="use-case"||e.portProofEligible?`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, test at the public interface, then preflight again.`:"Classify the import: if it is constants/types/pure, adopt into DomainModel or SharedKernel; define a port only if the target is a real use-case. Then preflight again."}c(St,"layerImportNextAction");function It(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}c(It,"arkRunCallSiteName");function xt(e){let r=It(e),t=typeof e.fromLayer=="string"&&e.fromLayer.length>0?e.fromLayer:void 0;switch(e.ruleId){case"ARKRUN_MISSING_ROOT":return r?`Import createStrictArkKernel from arkgate/runtime and call it in composition root ${r} listed in arkRun.compositionRoots, then preflight again.`:"Import createStrictArkKernel from arkgate/runtime (same npm package; @arkgate/runtime is deprecated) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKRUN_KERNEL_IN_DOMAIN":return r?`Move the kernel import of ${r} out of ${t??"the Domain-role layer"} into a composition root or adapter. Import from arkgate/runtime, then preflight again.`:"Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from arkgate/runtime (same npm package; @arkgate/runtime is deprecated), then preflight again. Never mechanical-safe.";case"ARKRUN_DIRECT_NEW":return r?`Resolve ${r} from the kernel instead of constructing it with new, then preflight again.`:"Resolve the type from the kernel instead of constructing it with new, then preflight again. Never mechanical-safe \u2014 rewiring construction is a design decision.";case"ARKRUN_UNDECLARED_EMIT":return r?`Add ${r} to raises or sends on the managed component, then preflight again.`:"Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment.";case"ARKRUN_UNDECLARED_HANDLE":return r?`Add ${r} to reactsTo on the managed component, then preflight again.`:"Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment.";case"ARKRUN_UNDECLARED_DEPEND":return r?`Add ${r} to uses on the managed component, then preflight again.`:"Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment.";case"ARKRUN_TRANSPORT_BYPASS":return r?`Send through the ArkRun kernel transport instead of importing ${r}, then preflight again.`:"Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe \u2014 homemade buses stay judgment.";default:return`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}c(xt,"arkRunNextAction");function P(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return St(e);case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, test at the public interface, then preflight again.`;case"CAPABILITY_VIOLATION":return`Define a ${String(e.capability??"capability")} port in ${e.fromLayer??"the walled layer"}, bind the implementation outside it, test at the public interface, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, test at the public interface, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"LITERAL_PATH_DRIFT":return typeof e.target=="string"&&e.target.length>0?`Rewrite the literal to ${e.target}, or run \`arkgate-check --path-drift --base-ref <ref> --write\` to apply every anchored replacement.`:"Rewrite the literal to the rename destination, or run `arkgate-check --path-drift --base-ref <ref> --write` to apply every anchored replacement.";case"LITERAL_PATH_UNRESOLVED":return"Read the candidate and decide: fix the path, or leave it. Advisory \u2014 with no rename to anchor it there is no destination to propose, so --write never touches it.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";case"INVARIANT_COVERAGE_OUTSIDE_ROOTS":return"Move the covering test under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json, then run Ark again.";case"ARKRULE_STRUCTURE":case"ARKRULE_INVARIANT":case"INVARIANT_UNCOVERED":return`Fix the structure or invariant for ${typeof e.arkruleId=="string"&&e.arkruleId.length>0?e.arkruleId:"the ArkRule"} (declared in ${typeof e.arkruleSource=="string"&&e.arkruleSource.length>0?e.arkruleSource:"arkrules/<Layer>.json"}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`;case"ARKRUN_MISSING_ROOT":case"ARKRUN_KERNEL_IN_DOMAIN":case"ARKRUN_DIRECT_NEW":case"ARKRUN_UNDECLARED_EMIT":case"ARKRUN_UNDECLARED_HANDLE":case"ARKRUN_UNDECLARED_DEPEND":case"ARKRUN_TRANSPORT_BYPASS":return xt(e);case"ARKORDER_MISSING_PLANE":return typeof e.target=="string"&&e.target.length>0?`Import createOrderPlane from arkgate/order and call it in plane root ${e.target} listed in arkOrder.planeRoots, then preflight again.`:"Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKORDER_KERNEL_IN_DOMAIN":return"Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe.";case"ARKORDER_GENERIC_UPDATE":return"Use release() to freeze \u03BE or proposeRelease() for a pattern change with blast radius, then preflight again. Never mechanical-safe.";case"ARKORDER_TOO_MANY_PARAMS":return"Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe.";case"ARKORDER_INGEST_WRITES_XI":return"Keep ingest results as absorb/escalate only. Change \u03BE with proposeRelease + release. Never mechanical-safe.";case"ARKORDER_XI_FIELD_WRITE":return typeof e.target=="string"&&e.target.length>0?`Do not persist slow key ${e.target} from a use-case. Absorb the field with ingest() or change the pattern with proposeRelease(), then preflight again.`:"Do not persist a declared slow key from a use-case. Absorb the field with ingest() or change the pattern with proposeRelease(), then preflight again. Never mechanical-safe.";default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}c(P,"deterministicNextAction");var Nt="docs/diagnostics.md";function R(e){return typeof e=="string"&&e.length>0?e:void 0}c(R,"text");function rr(e,r){return Number.isInteger(e)&&Number(e)>0?Number(e):r}c(rr,"positiveInteger");function _t(e){let r=typeof e.ruleId=="string"?e.ruleId:typeof e.code=="string"?e.code:void 0,t=typeof e.file=="string"?e.file:void 0,n=typeof e.fromLayer=="string"?e.fromLayer:void 0,s=typeof e.toLayer=="string"?e.toLayer:void 0,o=typeof e.target=="string"?e.target:void 0;return[r,t,n??"",s??"",o??""].join("|")}c(_t,"adapterFindingTargetKey");function Ot(e){let r=2166136261;for(let t=0;t<e.length;t+=1)r^=e.charCodeAt(t),r=Math.imul(r,16777619);return`fnv1a-${(r>>>0).toString(16).padStart(8,"0")}`}c(Ot,"adapterFindingRefFromTargetKey");function Ct(e){return`${Nt}#${e}`}c(Ct,"adapterDocsCodePath");function wt(e,r,t){return P({ruleId:e,target:R(r.target)??R(t.target)??void 0,fromLayer:R(r.fromLayer)??void 0,toLayer:R(r.toLayer)??void 0,typeOnly:r.typeOnly===!0,targetTypeOnlyExports:r.targetTypeOnlyExports===!0,namedBindingsTypeOnly:r.namedBindingsTypeOnly===!0,portProofEligible:r.portProofEligible===!0,peerIsolation:r.peerIsolation===!0,sourcePureTypeModule:r.sourcePureTypeModule===!0,edgeKind:R(r.edgeKind)??void 0,capability:R(r.capability)??R(t.capability)??void 0,arkruleId:R(r.arkruleId)??void 0,arkruleSource:R(r.arkruleSource)??void 0})}c(wt,"nextActionForDiagnostic");function tr(e,r="error",t){let n=R(e.ruleId)??R(e.code)??"ARK_UNKNOWN",s=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":r,o={...R(e.target)?{target:R(e.target)}:{},...R(e.fromLayer)?{fromLayer:R(e.fromLayer)}:{},...R(e.toLayer)?{toLayer:R(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}:{},...R(e.capability)?{capability:R(e.capability)}:{},...R(e.edgeKind)?{edgeKind:R(e.edgeKind)}:{},...R(e.arkruleId)?{arkruleId:R(e.arkruleId)}:{},...R(e.arkruleSource)?{arkruleSource:R(e.arkruleSource)}:{}},i=t??_t(e),a=Ot(i);return{ruleId:n,severity:s,message:R(e.message)??n,location:{file:R(e.file)??"<unknown>",line:rr(e.line,1),column:rr(e.column,1)},evidence:o,nextAction:R(e.nextAction)??wt(n,o,e),findingRef:a,targetKey:i,docsCodePath:Ct(n)}}c(tr,"toAdapterDiagnostic");var nr={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."},Hn=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 vt(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}c(vt,"looksLikeArkIntent");function ye(e){if(!e.publishCall)return[];let r=[];return(e.rawIntentName!==void 0&&vt(e.rawIntentName)||e.objectHasIntent)&&r.push({ruleId:"RAW_EVENT_PUBLISH",message:nr.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&r.push({ruleId:"PUBLISH_MISSING_SOURCE",message:nr.PUBLISH_MISSING_SOURCE}),r}c(ye,"classifyPublishFacts");var Ee=J(require("fs"),1),w=J(require("path"),1);var Lt=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"];var Tt=new Set(Lt),Dt=new Set(["AggregateError","Array","ArrayBuffer","BigInt64Array","BigUint64Array","Boolean","DataView","Date","Error","EvalError","FinalizationRegistry","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Number","Object","Promise","Proxy","RangeError","ReferenceError","RegExp","Set","SharedArrayBuffer","String","Symbol","SyntaxError","TypeError","URIError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","WeakRef","WeakSet"]),Ft=new Set(["Array","Atomics","Buffer","JSON","Math","Number","Object","Promise","Reflect","String","console","fs","path","url","util"]);function M(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")}c(M,"isArkRunKernelModuleSpecifier");var Kt=["events","node:events","eventemitter2","eventemitter3","emittery","kafkajs","kafka-node","amqplib","amqp","bull","bullmq","mqtt","nats","@aws-sdk/client-sqs","@aws-sdk/client-sns","@aws-sdk/client-eventbridge","@google-cloud/pubsub","@azure/service-bus"],Re=new Set(Kt);function ir(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(Re.has(e))return!0;let r=e.indexOf("/");if(r<0)return!1;let t=e.slice(0,r);if(Re.has(t))return!0;let n=e.indexOf("/",r+1);return n<0?!1:Re.has(e.slice(0,n))}c(ir,"isArkRunTransportBypassSpecifier");function sr(e){if(Tt.has(e))return"factory";switch(e){case"publisher":return"publisher";case"publish":return"publish";case"raise":case"raiseAsync":return"raise";case"send":case"sendTo":return"send";case"subscribe":return"subscribe";case"registerHandler":return"register-handler";case"resolve":return"resolve";case"resolveSingleton":return"resolve-singleton";default:return}}c(sr,"arkRunKernelCallKind");function ar(e,r){let t=1;for(let n=0;n<r;n+=1)e.charCodeAt(n)===10&&(t+=1);return t}c(ar,"lineAt");function he(e){return e.replace(/\/\*[\s\S]*?\*\//g,r=>r.replace(/[^\n]/g," ")).replace(/(^|[^:\\])\/\/.*$/gm,r=>r.replace(/\/\/.*$/,t=>" ".repeat(t.length)))}c(he,"stripCommentsPreservingLines");function Pt(e,r){let t=e.slice(r),n=/^\s*(['"])((?:\\.|[^\\])*?)\1/.exec(t);if(!n)return;let s=n[2]??"";return s.length>0?s:void 0}c(Pt,"firstStringLiteralArg");function or(e,r,t){let n=Math.max(0,r-t.length-8),s=e.slice(n,r);return new RegExp(`\\b${t}\\s+$`).test(s)}c(or,"keywordBefore");function re(e,r){let t=/\b(?:import|export)(\s+type)?\s+([\s\S]*?)\s+from\s*['"]([^'"]+)['"]/g,n;for(;(n=t.exec(e))!==null;)n[1]||r(n[2]??"",n[3]??"")}c(re,"parseValueImportClause");function lr(e,r){re(he(e),r)}c(lr,"forEachArkRunValueImportClause");function Mt(e){let r=new Map,t=new Set;return re(e,(n,s)=>{if(!M(s))return;let o=/\*\s+as\s+([A-Za-z_][A-Za-z0-9_]*)/.exec(n);o?.[1]&&t.add(o[1]);let i=/^([A-Za-z_][A-Za-z0-9_]*)\s*(?:,|$)/.exec(n.trim());i?.[1]&&r.set(i[1],i[1]);let a=/\{([^}]*)\}/.exec(n);if(a?.[1])for(let l of a[1].split(",")){let u=l.trim();if(!u||u.startsWith("type "))continue;let d=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(u);if(d){r.set(d[2],d[1]);continue}let p=/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(u);p?.[1]&&r.set(p[1],p[1])}}),{named:r,namespaces:t}}c(Mt,"collectKernelImportBindings");function $t(e,r){let t=new Set(r);return re(e,(n,s)=>{let o=/\{([^}]*)\}/.exec(n);if(o?.[1])for(let i of o[1].split(",")){let a=i.trim();if(!a||a.startsWith("type "))continue;let l=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(a),u=l?.[2]??/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(a)?.[1],d=l?.[1]??u;!u||!d||!/^[A-Z]/.test(d)||(M(s)||r.has(d)||r.has(u))&&(t.add(u),t.add(d))}}),t}c($t,"collectImportedConstructors");function Ut(e,r){let t;return re(e,(n,s)=>{!t&&new RegExp(`\\b${r}\\b`).test(n)&&(t=s)}),t}c(Ut,"importedFromForName");function te(e,r){let t=he(r),n=Mt(t),s=[],o=/\b([A-Za-z_][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,i;for(;(i=o.exec(t))!==null;){let a=i[1],l=i.index;if(or(t,l,"function")||or(t,l,"class"))continue;let d=t.slice(0,l).match(/([A-Za-z_][A-Za-z0-9_]*)\s*\.\s*$/)?.[1],p=n.named.get(a)??a,f=sr(p)??sr(a);if(!f)continue;let g=n.named.has(a)||d!==void 0&&n.namespaces.has(d);if(f!=="factory"&&(!g&&d===void 0||d&&Ft.has(d)&&!g))continue;let y=Pt(t,l+i[0].length);s.push({file:e,line:ar(r,l),kind:f,callee:a,viaImport:g,...d?{receiver:d}:{},...y?{nameLiteral:y}:{}})}return s}c(te,"extractArkRunKernelCallsFromSource");function Ae(e,r,t){let n=he(r),s=$t(n,t),o=[],i=/\bnew\s+(?:[A-Za-z_][A-Za-z0-9_]*\s*\.\s*)*([A-Z][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,a;for(;(a=i.exec(n))!==null;){let l=a[1];if(Dt.has(l)||!s.has(l))continue;let u=Ut(n,l);o.push({file:e,line:ar(r,a.index),typeName:l,...u?{importedFrom:u}:{}})}return o}c(Ae,"extractArkRunManagedNewsFromSource");function ke(e,r){let t=[],n=/export\s+(?:abstract\s+)?class\s+([A-Za-z_][A-Za-z0-9_]*)\s*(?:extends\s+[^{]+)?(?:implements\s+[^{]+)?\{/g,s;for(;(s=n.exec(r))!==null;){let o=s[1],i=s.index+s[0].length,a=1,l=i;for(;l<r.length&&a>0;){let b=r[l];b==="{"?a+=1:b==="}"&&(a-=1),l+=1}let u=r.slice(i,l-1),d=u.split(`
3
+ `)}`),this.name="ArkConfigValidationError",this.source=r,this.issues=t}};function Qe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}c(Qe,"isObject");function ee(e,r){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(r)?`${e}.${r}`:`${e}[${JSON.stringify(r)}]`}c(ee,"propertyPath");function K(e){return e===null?"null":Array.isArray(e)?"array":typeof e}c(K,"valueType");function ft(e,r){let t="#/$defs/";if(e.startsWith(t))return r.$defs[e.slice(t.length)]}c(ft,"resolveSchemaRef");function B(e,r,t,n,s){if(r.$ref){let o=ft(r.$ref,n);if(!o){s.push({path:t,message:`schema reference ${r.$ref} cannot be resolved`});return}B(e,o,t,n,s);return}if(r.const!==void 0&&!Object.is(e,r.const)){s.push({path:t,message:`must equal ${JSON.stringify(r.const)}`});return}if(r.enum&&!r.enum.some(o=>Object.is(o,e))){s.push({path:t,message:`must be one of ${r.enum.map(String).join(", ")}`});return}if(r.type==="object"){if(!Qe(e)){s.push({path:t,message:`must be an object; received ${K(e)}`});return}let o=r.properties??{};for(let i of r.required??[])e[i]===void 0&&s.push({path:ee(t,i),message:"is required"});if(r.additionalProperties===!1)for(let i of Object.keys(e))i in o||s.push({path:ee(t,i),message:"unknown field"});else if(r.additionalProperties!==void 0&&r.additionalProperties!==!0&&typeof r.additionalProperties=="object"){let i=r.additionalProperties;for(let a of Object.keys(e))a in o||B(e[a],i,ee(t,a),n,s)}for(let[i,a]of Object.entries(o))e[i]!==void 0&&B(e[i],a,ee(t,i),n,s);return}if(r.type==="array"){if(!Array.isArray(e)){s.push({path:t,message:`must be an array; received ${K(e)}`});return}if(r.minItems!==void 0&&e.length<r.minItems&&s.push({path:t,message:`must contain at least ${r.minItems} item(s)`}),r.uniqueItems){let o=e.map(i=>JSON.stringify(i));new Set(o).size!==o.length&&s.push({path:t,message:"must not contain duplicate items"})}r.items&&e.forEach((o,i)=>B(o,r.items,`${t}[${i}]`,n,s));return}if(r.type==="string"){if(typeof e!="string"){s.push({path:t,message:`must be a string; received ${K(e)}`});return}r.minLength!==void 0&&e.length<r.minLength&&s.push({path:t,message:`must contain at least ${r.minLength} character(s)`});return}if(r.type==="boolean"){typeof e!="boolean"&&s.push({path:t,message:`must be a boolean; received ${K(e)}`});return}if(r.type==="integer"){if(!Number.isInteger(e)){s.push({path:t,message:`must be an integer; received ${K(e)}`});return}r.minimum!==void 0&&e<r.minimum&&s.push({path:t,message:`must be at least ${r.minimum}`})}}c(B,"validateNode");function gt(e){let r={...e,$schema:e.$schema===void 0?ge:e.$schema,schemaVersion:e.schemaVersion===void 0?I:e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?Je.map(t=>({...t})):e.rules};return e.arkRun!==void 0&&(r.arkRun=We(e.arkRun)),e.arkOrder!==void 0&&(r.arkOrder=ze(e.arkOrder)),r}c(gt,"defaultedConfig");function mt(e){return e===I?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}c(mt,"migratedFromOf");function yt(){let e=new Set([I]);for(let r of me)r.from!=="unversioned"&&e.add(r.from),e.add(r.to);return e}c(yt,"knownInputVersions");function Rt(e,r="ark.config.json"){if(!Qe(e))throw new N(r,[{path:"$",message:`must be an object; received ${K(e)}`}]);let t=yt(),n=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(n===null)throw new N(r,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected ${I}`}]);if(n!=="unversioned"&&!t.has(n))throw new N(r,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(n)}; expected ${I}`}]);let s=n,o={...e},i=0;for(;s!==I&&i<me.length+1;){i+=1;let a=me.find(l=>l.from===s);if(!a)throw new N(r,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(s)}; expected ${I}`}]);s=a.to,o.schemaVersion=s}if(s!==I)throw new N(r,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(n)}; expected ${I}`}]);return{candidate:gt(o),migratedFrom:mt(n)}}c(Rt,"migrateArkConfig");function ht(e,r="ark.config.json"){let{candidate:t,migratedFrom:n}=Rt(e,r),s=[];if(B(t,Xe,"$",Xe,s),qe(t,s),Ze(t,s),s.length>0)throw new N(r,s);return{config:t,migratedFrom:n}}c(ht,"loadArkConfigContract");function er(e,r="ark.config.json"){let t;try{t=JSON.parse(e)}catch(n){throw new N(r,[{path:"$",message:`invalid JSON: ${n instanceof Error?n.message:String(n)}`}])}return ht(t,r)}c(er,"parseArkConfigJson");var At=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,kt=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,bt=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function Et(e,r){let t=String(e??"").replace(/\\/g,"/").trim(),n=String(r?.fromLayer??""),s=String(r?.toLayer??"");return At.test(t)?"pure-shared":n==="PersistenceAdapters"&&(kt.test(t)||/events?|intents?|kernel|bootstrap/i.test(`${s} ${t}`))?"kernel-emit":bt.test(t)||(n==="DomainModel"||n==="ApplicationOrchestration")&&s==="PersistenceAdapters"?"use-case":"unknown"}c(Et,"classifyLayerImportKind");function St(e){if(e.typeOnly||e.targetTypeOnlyExports||e.namedBindingsTypeOnly)return"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.";if(e.peerIsolation)return"Extract the shared dependency to a shared layer, test at the public interface, then preflight again.";let r=Et(typeof e.target=="string"?e.target:"",{fromLayer:typeof e.fromLayer=="string"?e.fromLayer:void 0,toLayer:typeof e.toLayer=="string"?e.toLayer:void 0});return r==="pure-shared"?"Adopt the imported constants/types/pure module into DomainModel or SharedKernel (do not inject a port). Then preflight again.":r==="kernel-emit"?"Persistence must not emit. Inject a port or move the event map to SharedTypes; do not import kernel/events/bootstrap from a repository. Then preflight again.":r==="use-case"||e.portProofEligible?`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, test at the public interface, then preflight again.`:"Classify the import: if it is constants/types/pure, adopt into DomainModel or SharedKernel; define a port only if the target is a real use-case. Then preflight again."}c(St,"layerImportNextAction");function It(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}c(It,"arkRunCallSiteName");function xt(e){let r=It(e),t=typeof e.fromLayer=="string"&&e.fromLayer.length>0?e.fromLayer:void 0;switch(e.ruleId){case"ARKRUN_MISSING_ROOT":return r?`Import createStrictArkKernel from arkgate/runtime and call it in composition root ${r} listed in arkRun.compositionRoots, then preflight again.`:"Import createStrictArkKernel from arkgate/runtime (same npm package; @arkgate/runtime is deprecated) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKRUN_KERNEL_IN_DOMAIN":return r?`Move the kernel import of ${r} out of ${t??"the Domain-role layer"} into a composition root or adapter. Import from arkgate/runtime, then preflight again.`:"Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from arkgate/runtime (same npm package; @arkgate/runtime is deprecated), then preflight again. Never mechanical-safe.";case"ARKRUN_DIRECT_NEW":return r?`Resolve ${r} from the kernel instead of constructing it with new, then preflight again.`:"Resolve the type from the kernel instead of constructing it with new, then preflight again. Never mechanical-safe \u2014 rewiring construction is a design decision.";case"ARKRUN_UNDECLARED_EMIT":return r?`Add ${r} to raises or sends on the managed component, then preflight again.`:"Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment.";case"ARKRUN_UNDECLARED_HANDLE":return r?`Add ${r} to reactsTo on the managed component, then preflight again.`:"Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment.";case"ARKRUN_UNDECLARED_DEPEND":return r?`Add ${r} to uses on the managed component, then preflight again.`:"Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment.";case"ARKRUN_TRANSPORT_BYPASS":return r?`Send through the ArkRun kernel transport instead of importing ${r}, then preflight again.`:"Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe \u2014 homemade buses stay judgment.";default:return`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}c(xt,"arkRunNextAction");function P(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return St(e);case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, test at the public interface, then preflight again.`;case"CAPABILITY_VIOLATION":return`Define a ${String(e.capability??"capability")} port in ${e.fromLayer??"the walled layer"}, bind the implementation outside it, test at the public interface, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, test at the public interface, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"LITERAL_PATH_DRIFT":return typeof e.target=="string"&&e.target.length>0?`Rewrite the literal to ${e.target}, or run \`arkgate-check --path-drift --base-ref <ref> --write\` to apply every anchored replacement.`:"Rewrite the literal to the rename destination, or run `arkgate-check --path-drift --base-ref <ref> --write` to apply every anchored replacement.";case"LITERAL_PATH_UNRESOLVED":return"Read the candidate and decide: fix the path, or leave it. Advisory \u2014 with no rename to anchor it there is no destination to propose, so --write never touches it.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";case"INVARIANT_COVERAGE_OUTSIDE_ROOTS":return"Move the covering test under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json, then run Ark again.";case"ARKRULE_STRUCTURE":case"ARKRULE_INVARIANT":case"INVARIANT_UNCOVERED":return`Fix the structure or invariant for ${typeof e.arkruleId=="string"&&e.arkruleId.length>0?e.arkruleId:"the ArkRule"} (declared in ${typeof e.arkruleSource=="string"&&e.arkruleSource.length>0?e.arkruleSource:"arkrules/<Layer>.json"}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`;case"ARKRUN_MISSING_ROOT":case"ARKRUN_KERNEL_IN_DOMAIN":case"ARKRUN_DIRECT_NEW":case"ARKRUN_UNDECLARED_EMIT":case"ARKRUN_UNDECLARED_HANDLE":case"ARKRUN_UNDECLARED_DEPEND":case"ARKRUN_TRANSPORT_BYPASS":return xt(e);case"ARKORDER_MISSING_PLANE":return typeof e.target=="string"&&e.target.length>0?`Import createOrderPlane from arkgate/order and call it in plane root ${e.target} listed in arkOrder.planeRoots, then preflight again.`:"Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKORDER_KERNEL_IN_DOMAIN":return"Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe.";case"ARKORDER_GENERIC_UPDATE":return"Use release() for the first freeze of \u03BE. Later pattern change is proposeRelease then apply(ProposeResult). Never update/patch/set. Never mechanical-safe.";case"ARKORDER_TOO_MANY_PARAMS":return"Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe.";case"ARKORDER_INGEST_WRITES_XI":return"Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe.";case"ARKORDER_XI_FIELD_WRITE":return typeof e.target=="string"&&e.target.length>0?`Do not persist slow key ${e.target} from a use-case. Absorb the field with ingest() or change the pattern with proposeRelease then apply, then preflight again.`:"Do not persist a declared slow key from a use-case. Absorb the field with ingest() or change the pattern with proposeRelease then apply, then preflight again. Never mechanical-safe.";case"ARKORDER_UNVALVED_RELEASE":return"Change \u03BE with proposeRelease then apply(ProposeResult). release() is only the first freeze. Never mechanical-safe.";default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}c(P,"deterministicNextAction");var Nt="docs/diagnostics.md";function R(e){return typeof e=="string"&&e.length>0?e:void 0}c(R,"text");function rr(e,r){return Number.isInteger(e)&&Number(e)>0?Number(e):r}c(rr,"positiveInteger");function _t(e){let r=typeof e.ruleId=="string"?e.ruleId:typeof e.code=="string"?e.code:void 0,t=typeof e.file=="string"?e.file:void 0,n=typeof e.fromLayer=="string"?e.fromLayer:void 0,s=typeof e.toLayer=="string"?e.toLayer:void 0,o=typeof e.target=="string"?e.target:void 0;return[r,t,n??"",s??"",o??""].join("|")}c(_t,"adapterFindingTargetKey");function Ot(e){let r=2166136261;for(let t=0;t<e.length;t+=1)r^=e.charCodeAt(t),r=Math.imul(r,16777619);return`fnv1a-${(r>>>0).toString(16).padStart(8,"0")}`}c(Ot,"adapterFindingRefFromTargetKey");function Ct(e){return`${Nt}#${e}`}c(Ct,"adapterDocsCodePath");function wt(e,r,t){return P({ruleId:e,target:R(r.target)??R(t.target)??void 0,fromLayer:R(r.fromLayer)??void 0,toLayer:R(r.toLayer)??void 0,typeOnly:r.typeOnly===!0,targetTypeOnlyExports:r.targetTypeOnlyExports===!0,namedBindingsTypeOnly:r.namedBindingsTypeOnly===!0,portProofEligible:r.portProofEligible===!0,peerIsolation:r.peerIsolation===!0,sourcePureTypeModule:r.sourcePureTypeModule===!0,edgeKind:R(r.edgeKind)??void 0,capability:R(r.capability)??R(t.capability)??void 0,arkruleId:R(r.arkruleId)??void 0,arkruleSource:R(r.arkruleSource)??void 0})}c(wt,"nextActionForDiagnostic");function tr(e,r="error",t){let n=R(e.ruleId)??R(e.code)??"ARK_UNKNOWN",s=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":r,o={...R(e.target)?{target:R(e.target)}:{},...R(e.fromLayer)?{fromLayer:R(e.fromLayer)}:{},...R(e.toLayer)?{toLayer:R(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}:{},...R(e.capability)?{capability:R(e.capability)}:{},...R(e.edgeKind)?{edgeKind:R(e.edgeKind)}:{},...R(e.arkruleId)?{arkruleId:R(e.arkruleId)}:{},...R(e.arkruleSource)?{arkruleSource:R(e.arkruleSource)}:{}},i=t??_t(e),a=Ot(i);return{ruleId:n,severity:s,message:R(e.message)??n,location:{file:R(e.file)??"<unknown>",line:rr(e.line,1),column:rr(e.column,1)},evidence:o,nextAction:R(e.nextAction)??wt(n,o,e),findingRef:a,targetKey:i,docsCodePath:Ct(n)}}c(tr,"toAdapterDiagnostic");var nr={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."},Hn=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 vt(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}c(vt,"looksLikeArkIntent");function ye(e){if(!e.publishCall)return[];let r=[];return(e.rawIntentName!==void 0&&vt(e.rawIntentName)||e.objectHasIntent)&&r.push({ruleId:"RAW_EVENT_PUBLISH",message:nr.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&r.push({ruleId:"PUBLISH_MISSING_SOURCE",message:nr.PUBLISH_MISSING_SOURCE}),r}c(ye,"classifyPublishFacts");var Ee=J(require("fs"),1),w=J(require("path"),1);var Lt=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"];var Tt=new Set(Lt),Dt=new Set(["AggregateError","Array","ArrayBuffer","BigInt64Array","BigUint64Array","Boolean","DataView","Date","Error","EvalError","FinalizationRegistry","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Number","Object","Promise","Proxy","RangeError","ReferenceError","RegExp","Set","SharedArrayBuffer","String","Symbol","SyntaxError","TypeError","URIError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","WeakRef","WeakSet"]),Ft=new Set(["Array","Atomics","Buffer","JSON","Math","Number","Object","Promise","Reflect","String","console","fs","path","url","util"]);function M(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")}c(M,"isArkRunKernelModuleSpecifier");var Kt=["events","node:events","eventemitter2","eventemitter3","emittery","kafkajs","kafka-node","amqplib","amqp","bull","bullmq","mqtt","nats","@aws-sdk/client-sqs","@aws-sdk/client-sns","@aws-sdk/client-eventbridge","@google-cloud/pubsub","@azure/service-bus"],Re=new Set(Kt);function ir(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(Re.has(e))return!0;let r=e.indexOf("/");if(r<0)return!1;let t=e.slice(0,r);if(Re.has(t))return!0;let n=e.indexOf("/",r+1);return n<0?!1:Re.has(e.slice(0,n))}c(ir,"isArkRunTransportBypassSpecifier");function sr(e){if(Tt.has(e))return"factory";switch(e){case"publisher":return"publisher";case"publish":return"publish";case"raise":case"raiseAsync":return"raise";case"send":case"sendTo":return"send";case"subscribe":return"subscribe";case"registerHandler":return"register-handler";case"resolve":return"resolve";case"resolveSingleton":return"resolve-singleton";default:return}}c(sr,"arkRunKernelCallKind");function ar(e,r){let t=1;for(let n=0;n<r;n+=1)e.charCodeAt(n)===10&&(t+=1);return t}c(ar,"lineAt");function he(e){return e.replace(/\/\*[\s\S]*?\*\//g,r=>r.replace(/[^\n]/g," ")).replace(/(^|[^:\\])\/\/.*$/gm,r=>r.replace(/\/\/.*$/,t=>" ".repeat(t.length)))}c(he,"stripCommentsPreservingLines");function Pt(e,r){let t=e.slice(r),n=/^\s*(['"])((?:\\.|[^\\])*?)\1/.exec(t);if(!n)return;let s=n[2]??"";return s.length>0?s:void 0}c(Pt,"firstStringLiteralArg");function or(e,r,t){let n=Math.max(0,r-t.length-8),s=e.slice(n,r);return new RegExp(`\\b${t}\\s+$`).test(s)}c(or,"keywordBefore");function re(e,r){let t=/\b(?:import|export)(\s+type)?\s+([\s\S]*?)\s+from\s*['"]([^'"]+)['"]/g,n;for(;(n=t.exec(e))!==null;)n[1]||r(n[2]??"",n[3]??"")}c(re,"parseValueImportClause");function lr(e,r){re(he(e),r)}c(lr,"forEachArkRunValueImportClause");function Mt(e){let r=new Map,t=new Set;return re(e,(n,s)=>{if(!M(s))return;let o=/\*\s+as\s+([A-Za-z_][A-Za-z0-9_]*)/.exec(n);o?.[1]&&t.add(o[1]);let i=/^([A-Za-z_][A-Za-z0-9_]*)\s*(?:,|$)/.exec(n.trim());i?.[1]&&r.set(i[1],i[1]);let a=/\{([^}]*)\}/.exec(n);if(a?.[1])for(let l of a[1].split(",")){let u=l.trim();if(!u||u.startsWith("type "))continue;let d=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(u);if(d){r.set(d[2],d[1]);continue}let p=/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(u);p?.[1]&&r.set(p[1],p[1])}}),{named:r,namespaces:t}}c(Mt,"collectKernelImportBindings");function $t(e,r){let t=new Set(r);return re(e,(n,s)=>{let o=/\{([^}]*)\}/.exec(n);if(o?.[1])for(let i of o[1].split(",")){let a=i.trim();if(!a||a.startsWith("type "))continue;let l=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(a),u=l?.[2]??/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(a)?.[1],d=l?.[1]??u;!u||!d||!/^[A-Z]/.test(d)||(M(s)||r.has(d)||r.has(u))&&(t.add(u),t.add(d))}}),t}c($t,"collectImportedConstructors");function Ut(e,r){let t;return re(e,(n,s)=>{!t&&new RegExp(`\\b${r}\\b`).test(n)&&(t=s)}),t}c(Ut,"importedFromForName");function te(e,r){let t=he(r),n=Mt(t),s=[],o=/\b([A-Za-z_][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,i;for(;(i=o.exec(t))!==null;){let a=i[1],l=i.index;if(or(t,l,"function")||or(t,l,"class"))continue;let d=t.slice(0,l).match(/([A-Za-z_][A-Za-z0-9_]*)\s*\.\s*$/)?.[1],p=n.named.get(a)??a,f=sr(p)??sr(a);if(!f)continue;let g=n.named.has(a)||d!==void 0&&n.namespaces.has(d);if(f!=="factory"&&(!g&&d===void 0||d&&Ft.has(d)&&!g))continue;let y=Pt(t,l+i[0].length);s.push({file:e,line:ar(r,l),kind:f,callee:a,viaImport:g,...d?{receiver:d}:{},...y?{nameLiteral:y}:{}})}return s}c(te,"extractArkRunKernelCallsFromSource");function Ae(e,r,t){let n=he(r),s=$t(n,t),o=[],i=/\bnew\s+(?:[A-Za-z_][A-Za-z0-9_]*\s*\.\s*)*([A-Z][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,a;for(;(a=i.exec(n))!==null;){let l=a[1];if(Dt.has(l)||!s.has(l))continue;let u=Ut(n,l);o.push({file:e,line:ar(r,a.index),typeName:l,...u?{importedFrom:u}:{}})}return o}c(Ae,"extractArkRunManagedNewsFromSource");function ke(e,r){let t=[],n=/export\s+(?:abstract\s+)?class\s+([A-Za-z_][A-Za-z0-9_]*)\s*(?:extends\s+[^{]+)?(?:implements\s+[^{]+)?\{/g,s;for(;(s=n.exec(r))!==null;){let o=s[1],i=s.index+s[0].length,a=1,l=i;for(;l<r.length&&a>0;){let b=r[l];b==="{"?a+=1:b==="}"&&(a-=1),l+=1}let u=r.slice(i,l-1),d=u.split(`
4
4
  `).map(b=>/^\s*\/\//.test(b)||/^\s*\/\*|\*\//.test(b)?b:b.replace(/(?:public\s+|protected\s+)?readonly\s+[a-zA-Z_][a-zA-Z0-9_]*\s*(?::[^=;]+)?(?:=\s*[^;]+)?[;,]?/g,"").replace(/(?:^|[\s;{])readonly\s+[a-zA-Z_][a-zA-Z0-9_]*\s*(?::[^=;]+)?(?:=\s*[^;]+)?[;,]?/g," ")).join(`
5
5
  `),p=/(?:^|\n)\s*(?:public\s+)?[a-zA-Z_][a-zA-Z0-9_]*\s*[:=]/m.test(d.replace(/(?:public\s+|private\s+|protected\s+|static\s+|async\s+|get\s+|set\s+)/g,""))&&/(?:^|\n)\s*(public\s+)?(?!constructor|static|get|set|private|protected|readonly)[a-zA-Z_][a-zA-Z0-9_]*\s*[:=]/m.test(d),f=/(?:^|\n)\s*public\s+(?!static|async|get|set|constructor|readonly)[a-zA-Z_]/.test(d)||/(?:^|[\n;])\s*[a-zA-Z_][a-zA-Z0-9_]*\s*:\s*[^=;\n]+[;=]/m.test(d.split(`
6
6
  `).filter(b=>!/^\s*(private|protected|static|constructor|get |set |async |\/)/.test(b)).join(`