arkgate 4.8.25 → 4.8.27

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 (64) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +2 -2
  3. package/bin/ark-layer-match.mjs +23 -0
  4. package/bin/ark-mcp-runtime.mjs +45 -4
  5. package/bin/ark-mcp.mjs +9 -3
  6. package/bin/ark.mjs +27 -1
  7. package/bin/lib/analysis-engine.mjs +10 -10
  8. package/bin/lib/arkrules-sensors.mjs +9 -4
  9. package/bin/lib/class-source-scan.mjs +1 -1
  10. package/bin/lib/config-contract.mjs +5 -0
  11. package/bin/lib/policy-delta-io.mjs +5 -4
  12. package/bin/lib/prepare-change.mjs +10 -6
  13. package/bin/lib/prepare-write.mjs +7 -0
  14. package/bin/lib/project-root.mjs +12 -23
  15. package/bin/lib/remediation.mjs +84 -0
  16. package/bin/lib/resolved-candidate-facts.mjs +19 -2
  17. package/bin/lib/snippet-analysis.mjs +82 -1
  18. package/dist/chunk-A5EIY3HI.cjs +3 -3
  19. package/dist/chunk-H5I3GARV.js +16 -0
  20. package/dist/chunk-QQ4SJEJ7.cjs +16 -0
  21. package/dist/chunk-SVSQVGFJ.js +3 -3
  22. package/dist/{configTypes-GPvvdleM.d.cts → configTypes-D1oxws6x.d.cts} +6 -0
  23. package/dist/{configTypes-GPvvdleM.d.ts → configTypes-D1oxws6x.d.ts} +6 -0
  24. package/dist/eslint/index.cjs +11 -12
  25. package/dist/eslint/index.d.cts +7 -1
  26. package/dist/eslint/index.d.ts +7 -1
  27. package/dist/eslint/index.js +11 -11
  28. package/dist/index.cjs +32 -32
  29. package/dist/index.d.cts +13 -2
  30. package/dist/index.d.ts +13 -2
  31. package/dist/index.js +32 -32
  32. package/dist/inspectorListen-6DQVJ4DC.js +2 -1
  33. package/dist/inspectorListen-KGMIQ2TF.cjs +2 -1
  34. package/dist/nestjs/index.cjs +1 -1
  35. package/dist/nestjs/index.d.cts +1 -1
  36. package/dist/nestjs/index.d.ts +1 -1
  37. package/dist/nestjs/index.js +1 -1
  38. package/dist/order/index.cjs +1 -1
  39. package/dist/order/index.js +1 -1
  40. package/dist/runtime/index.cjs +10 -10
  41. package/dist/runtime/index.d.cts +4 -3
  42. package/dist/runtime/index.d.ts +4 -3
  43. package/dist/runtime/index.js +10 -10
  44. package/dist/{types-CnauMQQL.d.cts → types-DBiqlOWZ.d.cts} +6 -0
  45. package/dist/{types-CnauMQQL.d.ts → types-DBiqlOWZ.d.ts} +6 -0
  46. package/docs/README.md +3 -1
  47. package/docs/agent-guide.md +9 -6
  48. package/docs/ai-gates.md +1 -1
  49. package/docs/configuration.md +11 -0
  50. package/docs/diagnostics.md +1 -1
  51. package/docs/package-surface.md +2 -1
  52. package/docs/product-voice.md +1 -1
  53. package/package.json +1 -1
  54. package/schemas/ark.config.schema.json +10 -0
  55. package/server.json +2 -2
  56. package/templates/agent-skills/README.md +1 -1
  57. package/templates/agent-skills/ark-adopt/SKILL.md +6 -0
  58. package/templates/agent-skills/ark-autopilot/SKILL.md +1 -1
  59. package/templates/agent-skills/ark-place/SKILL.md +4 -0
  60. package/templates/skills/ark-adopt.md +6 -0
  61. package/templates/skills/ark-autopilot.md +1 -1
  62. package/templates/skills/ark-place.md +4 -0
  63. package/dist/chunk-AHACEKSV.js +0 -16
  64. package/dist/chunk-UN5EH4QV.cjs +0 -16
@@ -8,7 +8,7 @@
8
8
  * Pure CLI helper (bin/lib/arkrules-sensors.mjs). Zero Node I/O.
9
9
  */
10
10
 
11
- import { findClassDeclarations, scanClassMembers } from './class-source-scan.mjs';
11
+ import { findClassDeclarations, maskStringsAndComments, scanClassMembers } from './class-source-scan.mjs';
12
12
  import { sourceHasPersistenceWrite, sourceHasTaggedSqlWrite, sourceImportsPersistenceDriverText, } from './persistence-write-hint.mjs';
13
13
  /** Keep in lockstep with arkRulesTypes.ARK_RULE_TIER2_SENSOR_IDS (self-contained for CLI gen). */
14
14
  const ARK_RULE_TIER2_SENSOR_IDS = ['no-anemic-model'];
@@ -29,6 +29,7 @@ export const DOMAIN_INVARIANT_WORDS = [
29
29
  export const DOMAIN_INVARIANT_WORD_RE = new RegExp(`\\b(${DOMAIN_INVARIANT_WORDS.join('|')})\\b`);
30
30
  const EVENTS_ARRAY_PROP = '(?:_?pendingEvents|domainEvents|uncommittedEvents|recordedEvents)';
31
31
  export const DOMAIN_EVENTS_PUSH_RE = new RegExp(`\\bthis\\.${EVENTS_ARRAY_PROP}\\.push\\s*\\(`);
32
+ const STRUCTURAL_GUARD_CLAUSE_RE = /\bif\s*\([^)]*\)\s*(?:\{[^}]*\bthrow\b|\bthrow\b)/;
32
33
  const EVENTS_ARRAY_RESET_RE = new RegExp(`^this\\.${EVENTS_ARRAY_PROP}\\s*=\\s*\\[\\s*\\]`);
33
34
  const ANY_THIS_EMPTY_ARRAY_RE = /^this\.[A-Za-z_][A-Za-z0-9_]*\s*=\s*\[\s*\]/;
34
35
  const THIS_FIELD_ASSIGNMENT_RE = /\bthis\.[A-Za-z_][A-Za-z0-9_]*\s*=(?!=)/g;
@@ -36,7 +37,10 @@ export function expectedDomainInvariantWordsPhrase() {
36
37
  return `${DOMAIN_INVARIANT_WORDS.join(', ')}, or events-array .push(`;
37
38
  }
38
39
  function referencesGuardOrPublish(source) {
39
- return DOMAIN_INVARIANT_WORD_RE.test(source) || DOMAIN_EVENTS_PUSH_RE.test(source);
40
+ const code = maskStringsAndComments(source);
41
+ return (DOMAIN_INVARIANT_WORD_RE.test(code) ||
42
+ DOMAIN_EVENTS_PUSH_RE.test(code) ||
43
+ STRUCTURAL_GUARD_CLAUSE_RE.test(code));
40
44
  }
41
45
  export function isIdiomaticEventsReset(source, assignIndex, methodName) {
42
46
  const slice = source.slice(assignIndex);
@@ -50,10 +54,11 @@ export function isIdiomaticEventsReset(source, assignIndex, methodName) {
50
54
  return /\bpullEvents\b/.test(source.slice(windowStart, assignIndex + 200));
51
55
  }
52
56
  function methodAssignsThis(methodName, methodBody) {
57
+ const code = maskStringsAndComments(methodBody);
53
58
  const re = new RegExp(THIS_FIELD_ASSIGNMENT_RE.source, 'g');
54
59
  let match;
55
- while ((match = re.exec(methodBody)) !== null) {
56
- if (isIdiomaticEventsReset(methodBody, match.index, methodName))
60
+ while ((match = re.exec(code)) !== null) {
61
+ if (isIdiomaticEventsReset(code, match.index, methodName))
57
62
  continue;
58
63
  return true;
59
64
  }
@@ -366,7 +366,7 @@ export function findClassDeclarations(content, options = {}) {
366
366
  return out;
367
367
  }
368
368
  /** Same length as `content`; string and comment characters become spaces (newlines kept). */
369
- function maskStringsAndComments(content) {
369
+ export function maskStringsAndComments(content) {
370
370
  let out = '';
371
371
  let i = 0;
372
372
  while (i < content.length) {
@@ -180,6 +180,11 @@ export const ARK_CONFIG_SCHEMA = {
180
180
  name: { type: 'string', minLength: 1 },
181
181
  patterns: { ...stringArraySchema, minItems: 1 },
182
182
  exclude: stringArraySchema,
183
+ entrypoints: {
184
+ ...stringArraySchema,
185
+ minItems: 1,
186
+ description: 'Optional public surface globs for this layer. When non-empty, cross-layer imports into this layer must target a file matching one of these globs; deep imports into internal layer files are denied.',
187
+ },
183
188
  intentPrefixes: stringArraySchema,
184
189
  description: { type: 'string', minLength: 1 },
185
190
  trustBoundary: { type: 'string', enum: [...LAYER_TRUST_BOUNDARIES] },
@@ -355,16 +355,17 @@ export function analyzePolicyTransition({
355
355
  acknowledgementPath,
356
356
  }) {
357
357
  if (!strictMerge && !basePath && !baseRef && !acknowledgementPath) return undefined;
358
+ if (strictMerge && !basePath) {
359
+ const top = repositoryRoot(root);
360
+ if (top) configPathInRepository(root, configPath, top);
361
+ }
358
362
  const base = resolvePolicyBaseConfig({ root, configPath, basePath, baseRef, adoptMissingBase });
359
363
  if (!base && (basePath || (baseRef && !adoptMissingBase) || acknowledgementPath)) {
360
364
  throw new Error('Policy delta was requested but no policy base could be resolved.');
361
365
  }
362
366
  if (!base) return undefined;
363
367
 
364
- // AR02/AR11: load Effective ArkRules so mode edits inside arkrules/*.json classify,
365
- // and attach candidate coverage so covered advisory→enforced can auto-allow.
366
- // Base ArkRules come from the SAME source as the base config (git ref or the
367
- // base file's directory), never from the candidate working tree.
368
+ // Base ArkRules come from the base ref or base file, never the candidate tree.
368
369
  const baseArkRules = loadBaseArkRules(base);
369
370
  const candidateLoad = loadEffectiveArkRulesFromDisk(root, candidateConfig);
370
371
  if (candidateLoad.errors.length > 0) {
@@ -180,6 +180,8 @@ export function prepareChangeFromRoot({
180
180
  tsconfig,
181
181
  manifest,
182
182
  overlayChanges,
183
+ ingestCache,
184
+ contractSession,
183
185
  }) {
184
186
  const normalizedChanges = normalizeChangeSet(changes);
185
187
  const normalizedOverlayChanges =
@@ -187,7 +189,9 @@ export function prepareChangeFromRoot({
187
189
  const lawGate = evaluateTeamGate({
188
190
  changeSet: classifyChangeSet(normalizedChanges.map((change) => change.path)),
189
191
  contractSession:
190
- process.env.ARK_CONTRACT_SESSION === '1' || process.env.ARK_CONTRACT_SESSION === 'true',
192
+ contractSession === true ||
193
+ process.env.ARK_CONTRACT_SESSION === '1' ||
194
+ process.env.ARK_CONTRACT_SESSION === 'true',
191
195
  });
192
196
  if (lawGate.deny && lawGate.reasonId === 'mixed-law-and-product') {
193
197
  throw new Error(lawGate.message);
@@ -216,24 +220,24 @@ export function prepareChangeFromRoot({
216
220
  changes: normalizedChanges,
217
221
  });
218
222
  for (const change of canonicalChanges) assertGovernedSource(effectiveConfig, change.path);
219
- // Files the overlay does not touch are parsed once for both trees.
220
- const ingestCache = createResolverIngestCache(contract.config);
223
+ // Files the overlay does not touch are parsed once for both trees (and reused across warm calls).
224
+ const sharedIngestCache = ingestCache ?? createResolverIngestCache(contract.config);
221
225
  const baseFacts = resolveCandidateFacts({
222
226
  root,
223
227
  config: contract.config,
224
228
  ts,
225
- ingestCache,
229
+ ingestCache: sharedIngestCache,
226
230
  ...(tsconfig ? { tsconfig } : {}),
227
231
  });
228
232
  const candidateFacts = resolveCandidateFacts({
229
233
  root,
230
234
  config: contract.config,
231
235
  ts,
232
- ingestCache,
236
+ ingestCache: sharedIngestCache,
233
237
  changes: normalizedOverlayChanges,
234
238
  ...(tsconfig ? { tsconfig } : {}),
235
239
  });
236
- ingestCache.records.clear();
240
+ if (!ingestCache) sharedIngestCache.records.clear();
237
241
  const { baseAnalysisInputs, candidateAnalysisInputs } = arkRulesAnalysisInputs({
238
242
  root,
239
243
  config: effectiveConfig,
@@ -45,6 +45,7 @@ export function buildJudgmentBrief(violations) {
45
45
  fromLayer: v.fromLayer,
46
46
  toLayer: v.toLayer,
47
47
  target: v.target,
48
+ capability: v.capability,
48
49
  message: v.message,
49
50
  };
50
51
  const verdict = classifyRemediation(shaped);
@@ -55,6 +56,7 @@ export function buildJudgmentBrief(violations) {
55
56
  decision: enriched.enthusiastHint,
56
57
  remediationClass: verdict.class,
57
58
  ...(verdict.remediationKind ? { remediationKind: verdict.remediationKind } : {}),
59
+ ...(enriched.blueprint ? { blueprint: enriched.blueprint } : {}),
58
60
  };
59
61
  }
60
62
  // All mechanical-safe or unclassifiable — still offer first enriched hint
@@ -68,6 +70,7 @@ export function buildJudgmentBrief(violations) {
68
70
  decision: enriched.enthusiastHint,
69
71
  remediationClass: verdict.class,
70
72
  ...(verdict.remediationKind ? { remediationKind: verdict.remediationKind } : {}),
73
+ ...(enriched.blueprint ? { blueprint: enriched.blueprint } : {}),
71
74
  };
72
75
  }
73
76
 
@@ -117,6 +120,10 @@ export function composePrepareWrite(opts) {
117
120
  mustNotImport: placement?.mustNotImport,
118
121
  forbiddenGlobals: placement?.forbiddenGlobals ?? [],
119
122
  ...(placement?.mayImportInfrastructure ? { mayImportInfrastructure: true } : {}),
123
+ ...(Array.isArray(placement?.entrypoints) && placement.entrypoints.length > 0
124
+ ? { entrypoints: placement.entrypoints }
125
+ : {}),
126
+ ...(placement?.targetEntrypoints ? { targetEntrypoints: placement.targetEntrypoints } : {}),
120
127
  ...(placement?.suggestedLayers ? { suggestedLayers: placement.suggestedLayers } : {}),
121
128
  ...(placement?.message ? { placementMessage: placement.message } : {}),
122
129
  ...(placement?.note ? { placementNote: placement.note } : {}),
@@ -4,6 +4,12 @@
4
4
  * Monorepo honesty (NEW-MONOREPO-CWD-WALKUP): when cwd (or --root) has no
5
5
  * ark.config.json, walk parent directories until one is found. Never invent a
6
6
  * silent 11-layer / empty ADAPT world while a parent monorepo contract exists.
7
+ * That ancestor contains the directory the caller named, so the requested tree
8
+ * stays inside the analysis.
9
+ *
10
+ * An explicit --config path (absolute, or any name with a separator) is a file.
11
+ * Layer patterns resolve against the caller's --root. The file's directory is
12
+ * never a fallback analysis root (#352).
7
13
  *
8
14
  * Security (S0 walk-up review):
9
15
  * - Split **config discovery root** from **write root**.
@@ -104,11 +110,6 @@ function configNameIsPath(configName) {
104
110
  );
105
111
  }
106
112
 
107
- function isInsideRoot(root, target) {
108
- const rel = path.relative(root, target);
109
- return rel === '' || (!rel.startsWith(`..${path.sep}`) && rel !== '..' && !path.isAbsolute(rel));
110
- }
111
-
112
113
  /**
113
114
  * Resolve a nested/absolute --config path without walking parents.
114
115
  * `--root examples/app --config examples/app/ark.config.json` must load the nested
@@ -145,7 +146,8 @@ function resolveConfigPathCandidate(startDir, configName) {
145
146
  * Walk parents from startDir looking for configName (default ark.config.json).
146
147
  * Bounds: filesystem root, max depth, git root, workspaces package root.
147
148
  * Config found at a bound root is accepted; walking above a bound is refused.
148
- * Nested relative --config (`examples/app/ark.config.json`) is a file path, never a walk-up name.
149
+ * An explicit --config path is a file. The returned root stays `startDir`.
150
+ * Basename walk-up (`ark.config.json`) may still adopt an ancestor.
149
151
  *
150
152
  * @param {string} startDir
151
153
  * @param {string} [configName='ark.config.json']
@@ -157,26 +159,12 @@ export function findNearestArkConfig(startDir, configName = 'ark.config.json', o
157
159
  const boundAtGit = opts.boundAtGitRoot !== false;
158
160
  const boundAtWorkspaces = opts.boundAtWorkspacesRoot !== false;
159
161
 
160
- if (typeof configName === 'string' && path.isAbsolute(configName)) {
161
- if (isFile(configName)) {
162
- const root = path.dirname(configName);
163
- const start = path.resolve(startDir || process.cwd());
164
- return { root, configPath: path.resolve(configName), walkedUp: path.resolve(root) !== start };
165
- }
166
- return null;
167
- }
168
-
169
162
  const name = configName || 'ark.config.json';
170
163
  if (configNameIsPath(name)) {
171
164
  const resolved = resolveConfigPathCandidate(startDir, name);
172
165
  if (!resolved) return null;
173
166
  const start = path.resolve(startDir || process.cwd());
174
- const inside = isInsideRoot(start, resolved);
175
- return {
176
- root: inside ? start : path.dirname(resolved),
177
- configPath: resolved,
178
- walkedUp: !inside,
179
- };
167
+ return { root: start, configPath: resolved, walkedUp: false };
180
168
  }
181
169
 
182
170
  let dir = path.resolve(startDir || process.cwd());
@@ -213,9 +201,10 @@ export function findNearestArkConfig(startDir, configName = 'ark.config.json', o
213
201
  * Resolve config discovery vs write roots for CLI invocation.
214
202
  *
215
203
  * - If config exists at startRoot → use startRoot for both.
216
- * - Else walk parents for config (bounded) → configRoot may differ from writeRoot.
204
+ * - An explicit --config path keeps `root` at startRoot. The file's directory is not a fallback.
205
+ * - Else walk parents for a basename config (bounded) → configRoot may differ from writeRoot.
217
206
  * - writeMode without followConfigRoot: keep writeRoot/start as `root` (do not rewrite parent).
218
- * - writeMode + followConfigRoot (or read mode): adopt walked config root as `root`.
207
+ * - writeMode + followConfigRoot (or read mode): adopt a basename walk-up root as `root`.
219
208
  *
220
209
  * @param {string} startRoot
221
210
  * @param {{
@@ -588,5 +588,89 @@ export function enrichViolationWithFixClass(violation) {
588
588
  'Read the violation message and the layer rules in ark.config.json, then adjust imports or move code to the correct layer.';
589
589
  }
590
590
  enriched.nextAction = deterministicNextAction(violation);
591
+ const blueprint = remediationBlueprint(violation);
592
+ if (blueprint)
593
+ enriched.blueprint = blueprint;
591
594
  return enriched;
592
595
  }
596
+ function pascalCaseStem(raw) {
597
+ const cleaned = raw
598
+ .replace(/\\/g, '/')
599
+ .split('/')
600
+ .pop()
601
+ ?.replace(/\.[cm]?[jt]sx?$/i, '')
602
+ .replace(/[^a-zA-Z0-9]+/g, ' ')
603
+ .trim();
604
+ if (!cleaned)
605
+ return 'Capability';
606
+ return cleaned
607
+ .split(/\s+/)
608
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
609
+ .join('');
610
+ }
611
+ /**
612
+ * Deterministic TypeScript blueprint skeleton for judgment-class rejections
613
+ * (Port interfaces for FORBIDDEN_GLOBAL / CAPABILITY_VIOLATION / LAYER_IMPORT_VIOLATION,
614
+ * two-step valve for ARKORDER_XI_FIELD_WRITE / ARKORDER_GENERIC_UPDATE / ARKORDER_UNVALVED_RELEASE,
615
+ * and kernel resolution for ARKRUN_DIRECT_NEW).
616
+ */
617
+ export function remediationBlueprint(violation) {
618
+ if (!violation || typeof violation.ruleId !== 'string')
619
+ return undefined;
620
+ const target = typeof violation.target === 'string' ? violation.target.trim() : '';
621
+ const capability = typeof violation.capability === 'string' ? violation.capability.trim() : '';
622
+ if (violation.ruleId === 'FORBIDDEN_GLOBAL' || violation.ruleId === 'CAPABILITY_VIOLATION') {
623
+ if (capability === 'clock' || /^Date\b/.test(target)) {
624
+ return 'export interface ClockPort {\n now(): number;\n}';
625
+ }
626
+ if (capability === 'randomness' || /^(Math\.random|crypto\.randomUUID)\b/.test(target)) {
627
+ return 'export interface RandomPort {\n nextId(): string;\n}';
628
+ }
629
+ if (capability === 'network' || /^(fetch|http|https|undici)\b/i.test(target)) {
630
+ return 'export interface HttpPort {\n request<T = unknown>(url: string, init?: unknown): Promise<T>;\n}';
631
+ }
632
+ if (capability === 'filesystem' || /^(node:)?fs\b/i.test(target)) {
633
+ return 'export interface StoragePort {\n readText(path: string): Promise<string>;\n}';
634
+ }
635
+ if (capability === 'environment' || /^process\.env\b/.test(target)) {
636
+ return 'export interface ConfigPort {\n get(key: string): string | undefined;\n}';
637
+ }
638
+ const portName = `${pascalCaseStem(capability || target)}Port`;
639
+ return `export interface ${portName} {\n execute(...args: unknown[]): unknown;\n}`;
640
+ }
641
+ if (violation.ruleId === 'LAYER_IMPORT_VIOLATION') {
642
+ if (violation.typeOnly ||
643
+ violation.targetTypeOnlyExports ||
644
+ violation.namedBindingsTypeOnly ||
645
+ violation.peerIsolation) {
646
+ return undefined;
647
+ }
648
+ const msg = typeof violation.message === 'string' ? violation.message : '';
649
+ const entrypointMatch = msg.match(/declared entrypoints \(([^)]+)\)/);
650
+ if (entrypointMatch?.[1]) {
651
+ const firstEntrypoint = entrypointMatch[1].split(',')[0]?.trim() ?? 'index.ts';
652
+ return `// Import from declared public entrypoint (${firstEntrypoint}) instead of deep module "${target || 'internal'}":\nimport { /* public API */ } from '${firstEntrypoint.replace(/\.[cm]?[jt]sx?$/, '')}';`;
653
+ }
654
+ const kind = classifyLayerImportKind(target, {
655
+ fromLayer: typeof violation.fromLayer === 'string' ? violation.fromLayer : undefined,
656
+ toLayer: typeof violation.toLayer === 'string' ? violation.toLayer : undefined,
657
+ });
658
+ if (kind === 'use-case' || violation.portProofEligible) {
659
+ const stem = pascalCaseStem(target || String(violation.toLayer ?? 'Outbound'));
660
+ const portName = stem.endsWith('Port') ? stem : `${stem}Port`;
661
+ return `export interface ${portName} {\n // Declared in ${violation.fromLayer ?? 'caller layer'}, implemented in ${violation.toLayer ?? 'adapter layer'}\n}`;
662
+ }
663
+ return undefined;
664
+ }
665
+ if (violation.ruleId === 'ARKORDER_XI_FIELD_WRITE' ||
666
+ violation.ruleId === 'ARKORDER_GENERIC_UPDATE' ||
667
+ violation.ruleId === 'ARKORDER_UNVALVED_RELEASE') {
668
+ const key = target ? target.split('.').pop() || target : 'xiKey';
669
+ return `const proposal = plane.proposeRelease({ key: '${key}', nextValue, reason });\nif (proposal.ok) {\n plane.apply(proposal);\n}`;
670
+ }
671
+ if (violation.ruleId === 'ARKRUN_DIRECT_NEW') {
672
+ const typeName = target || 'ManagedComponent';
673
+ return `const instance = kernel.resolve(${typeName});`;
674
+ }
675
+ return undefined;
676
+ }
@@ -1171,7 +1171,11 @@ const SOURCE_READ_FAILURE = Symbol('ark.sourceReadFailure');
1171
1171
  * used while `config` is the identical object.
1172
1172
  */
1173
1173
  export function createResolverIngestCache(config) {
1174
- return { config, records: new Map() };
1174
+ return {
1175
+ config,
1176
+ evidenceHash: config ? resolvedFactsEvidenceRequirementsHash(config) : undefined,
1177
+ records: new Map(),
1178
+ };
1175
1179
  }
1176
1180
 
1177
1181
  /** Overlay text when present; otherwise read the on-disk source now (not held afterwards). */
@@ -1506,7 +1510,20 @@ export function resolveCandidateFacts({
1506
1510
  arkOrderBudgetLeaks,
1507
1511
  };
1508
1512
  const accumulatorNames = Object.keys(accumulators);
1509
- const reusable = ingestCache?.config === config ? ingestCache.records : undefined;
1513
+ const currentEvidenceHash = resolvedFactsEvidenceRequirementsHash(config);
1514
+ if (
1515
+ ingestCache &&
1516
+ ingestCache.config !== config &&
1517
+ ingestCache.evidenceHash !== currentEvidenceHash
1518
+ ) {
1519
+ ingestCache.records.clear();
1520
+ }
1521
+ if (ingestCache) {
1522
+ ingestCache.config = config;
1523
+ ingestCache.evidenceHash = currentEvidenceHash;
1524
+ if (ingestCache.records.size > 5000) ingestCache.records.clear();
1525
+ }
1526
+ const reusable = ingestCache?.records;
1510
1527
  const ingest = (candidate, fullExtract) => {
1511
1528
  if (!reusable || !fullExtract || typeof candidate.content === 'string') {
1512
1529
  ingestFresh(candidate, fullExtract);
@@ -1,6 +1,9 @@
1
1
  /** Fail-closed completeness evidence for one proposed source snippet. */
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
2
4
  import { layerForRelativePath } from '../ark-layer-match.mjs';
3
5
  import { ANALYSIS_COMPLETENESS } from './analysis-completeness.mjs';
6
+ import { extractSemanticDependencies } from './analysis-engine.mjs';
4
7
  import { evaluateArkRunEditorSensorsFromSource } from './ark-run-sensors.mjs';
5
8
  import { evaluateArkOrderEditorSensors } from './ark-order-sensors.mjs';
6
9
  import {
@@ -209,6 +212,79 @@ function extraPlaneSnippetViolations(source, context = {}) {
209
212
  ];
210
213
  }
211
214
 
215
+ /**
216
+ * Immediate 2-hop value cycle check (A -> B -> A) for single-file write hooks and prepare_write.
217
+ * Inspects only the direct resolved targets of `parsed` (typically 1–5 files) so it stays sub-millisecond.
218
+ */
219
+ function detectImmediateCycleViolations(ts, parsed, context = {}, existingViolations = []) {
220
+ if (
221
+ !ts ||
222
+ !parsed ||
223
+ typeof context.root !== 'string' ||
224
+ typeof context.resolveImportTarget !== 'function' ||
225
+ typeof context.relFile !== 'string' ||
226
+ !context.relFile
227
+ ) {
228
+ return [];
229
+ }
230
+ if (String(context.cyclePolicy ?? 'strict').toLowerCase() !== 'strict') return [];
231
+ let deps;
232
+ try {
233
+ deps = extractSemanticDependencies(ts, parsed);
234
+ } catch {
235
+ return [];
236
+ }
237
+ const blockedTargets = new Set(
238
+ existingViolations
239
+ .filter((v) => (v.ruleId || v.code) === 'LAYER_IMPORT_VIOLATION')
240
+ .flatMap((v) => [v.target, v.source].filter(Boolean))
241
+ );
242
+ const seenTargets = new Set();
243
+ const out = [];
244
+ for (const dep of deps ?? []) {
245
+ if (dep.typeOnly || typeof dep.specifier !== 'string' || !dep.specifier) continue;
246
+ if (blockedTargets.has(dep.specifier)) continue;
247
+ const hit = context.resolveImportTarget(dep.specifier, context.filePath);
248
+ const targetRel = hit?.relPath;
249
+ if (!targetRel || targetRel === context.relFile || seenTargets.has(targetRel)) continue;
250
+ if (blockedTargets.has(targetRel)) continue;
251
+ seenTargets.add(targetRel);
252
+ const targetAbs = path.join(context.root, targetRel);
253
+ let targetText;
254
+ try {
255
+ targetText = fs.readFileSync(targetAbs, 'utf8');
256
+ } catch {
257
+ continue;
258
+ }
259
+ try {
260
+ const targetParsed = ts.createSourceFile(targetAbs, targetText, ts.ScriptTarget.Latest, true);
261
+ const targetDeps = extractSemanticDependencies(ts, targetParsed);
262
+ const importsBack = (targetDeps ?? []).some((tDep) => {
263
+ if (tDep.typeOnly || typeof tDep.specifier !== 'string' || !tDep.specifier) return false;
264
+ return context.resolveImportTarget(tDep.specifier, targetAbs)?.relPath === context.relFile;
265
+ });
266
+ if (!importsBack) continue;
267
+ const members = [context.relFile, targetRel].sort();
268
+ out.push({
269
+ ruleId: 'CIRCULAR_DEPENDENCY',
270
+ code: 'CIRCULAR_DEPENDENCY',
271
+ file: context.relFile,
272
+ line: dep.line ?? 1,
273
+ target: members.join(' → '),
274
+ message: `Circular dependency among 2 files: ${members[0]} → ${members[1]} → ${members[0]}.`,
275
+ nextAction:
276
+ getDiagnosticCatalogEntry('CIRCULAR_DEPENDENCY')?.fix ??
277
+ 'Break the cycle: extract the shared code into a module both sides import, invert one edge behind a port/interface, or merge the files if they are really one unit.',
278
+ failsStrict: true,
279
+ severity: 'error',
280
+ });
281
+ } catch {
282
+ /* ignore unreadable/unparseable target */
283
+ }
284
+ }
285
+ return out;
286
+ }
287
+
212
288
  export function validateSnippetAnalysis({ gate, ts, source, context = {} }) {
213
289
  const observed = gate.validate(source, context);
214
290
  const arkRunViolations = arkRunSnippetViolations(source, context);
@@ -297,11 +373,16 @@ export function validateSnippetAnalysis({ gate, ts, source, context = {} }) {
297
373
  ],
298
374
  };
299
375
  }
376
+ const cycleViolations = detectImmediateCycleViolations(ts, parsed, context, base.violations);
377
+ const mergedViolations =
378
+ cycleViolations.length > 0 ? [...base.violations, ...cycleViolations] : base.violations;
379
+ const lexicalValid = base.valid && cycleViolations.length === 0;
300
380
  return {
301
381
  ...base,
382
+ violations: mergedViolations,
302
383
  mode: 'lexical-compatibility',
303
384
  valid: false,
304
- lexicalValid: base.valid,
385
+ lexicalValid,
305
386
  completeness: ANALYSIS_COMPLETENESS.partial,
306
387
  completenessReasons: [lexicalEvidenceIncompleteMessage(file, context)],
307
388
  };
@@ -1,5 +1,5 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var G=Object.defineProperty;var v=Object.getOwnPropertyDescriptor;var i=(n,e)=>G(n,"name",{value:e,configurable:!0});var Jn=(n,e,r,t)=>{for(var s=t>1?void 0:t?v(e,r):e,u=n.length-1,a;u>=0;u--)(a=n[u])&&(s=(t?a(e,r,s):a(s))||s);return t&&s&&G(e,r,s),s};var D="1.0",nn= exports.d =["singleton","transient"],en=["absorb","escalate_up","hold"],rn=new Set(nn);function E(n,e){return n<e?-1:n>e?1:0}i(E,"compare");function tn(n){return[...new Set(n)].sort(E)}i(tn,"uniqueSorted");function k(n){if(!Array.isArray(n))return[];let e=[];for(let r of n)typeof r=="string"&&r.length>0&&e.push(r);return tn(e)}i(k,"nameList");function on(n){if(n===null)return null;if(typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n))return n}i(on,"jsonPrimitive");function sn(n){return typeof n=="string"&&rn.has(n)?n:"singleton"}i(sn,"closedLifetime");function L(n){if(n===null||typeof n!="object"||Array.isArray(n))return;let e={};for(let r of Object.keys(n).sort(E)){if(r.length===0)continue;let t=on(n[r]);t!==void 0&&(e[r]=t)}return Object.keys(e).length>0?e:void 0}i(L,"sanitizeMetadata");function un(n){if(n===null||typeof n!="object"||Array.isArray(n))return;let e=n,r={};typeof e.label=="string"&&e.label.length>0&&(r.label=e.label),typeof e.architectureKind=="string"&&e.architectureKind.length>0&&(r.architectureKind=e.architectureKind);let t=k(e.tags);t.length>0&&(r.tags=t),typeof e.group=="string"&&e.group.length>0&&(r.group=e.group);let s=L(e.metadata);return s&&(r.metadata=s),Object.keys(r).length>0?r:void 0}i(un,"sanitizeArkRunExtendedInfo");function an(n){if(n===null||typeof n!="object"||Array.isArray(n))return;let e=n,r=typeof e.id=="string"?e.id.trim():"";if(!r)return;let t={id:r,lifetime:sn(e.lifetime),uses:k(e.uses),reactsTo:k(e.reactsTo),raises:k(e.raises),sends:k(e.sends)},s=un(e.extendedInfo);return s&&(t.extendedInfo=s),t}i(an,"sanitizeArkRunComponent");var cn=new Set(en);function dn(n){return L(n)}i(dn,"sanitizeTapePayload");function U(n){if(n===null||typeof n!="object"||Array.isArray(n))return;let e=n,r=typeof e.xiHash=="string"?e.xiHash.trim():"";if(!r)return;let t=e.event;if(t===null||typeof t!="object"||Array.isArray(t))return;let s=t,u=typeof s.kind=="string"?s.kind.trim():"";if(!u)return;let a=e.residual;if(a===null||typeof a!="object"||Array.isArray(a))return;let o=a,c=typeof o.kind=="string"&&cn.has(o.kind)?o.kind:void 0;if(!c)return;let d={kind:u},p=dn(s.payload);p&&(d.payload=p);let w={kind:c};return typeof o.reasonCode=="string"&&o.reasonCode.length>0&&(w.reasonCode=o.reasonCode),typeof o.eventId=="string"&&o.eventId.length>0&&(w.eventId=o.eventId),typeof o.target=="string"&&o.target.length>0&&(w.target=o.target),{xiHash:r,event:d,residual:w}}i(U,"sanitizeDecisionTapeRecord");function pn(n){if(!Array.isArray(n))return[];let e=[];for(let r of n){let t=U(r);t&&e.push(t)}return e}i(pn,"sanitizeDecisionTape");function R(n){let e=typeof n.kernelInstanceId=="string"?n.kernelInstanceId:"",r=Array.isArray(n.components)?n.components:[],t=new Set,s=[];for(let a of r){let o=an(a);!o||t.has(o.id)||(t.add(o.id),s.push(o))}s.sort((a,o)=>E(a.id,o.id));let u=pn(n.decisionTape);return{schemaVersion:"1.0",kernelInstanceId:e,components:s,...u.length>0?{decisionTape:u}:{}}}i(R,"buildDependencyInformationPackage");function Yn(n,e){let r=U(e),t=_nullishCoalesce(n.decisionTape, () => ([])),s=r?[...t,r]:[...t];return{schemaVersion:n.schemaVersion,kernelInstanceId:n.kernelInstanceId,components:n.components,...s.length>0?{decisionTape:s}:{}}}i(Yn,"appendDecisionTape");var fn="1.0",ln= exports.i ="process",gn= exports.j =["process","technical"],ee= exports.k =["component","interaction"],re= exports.l =["raises","reactsTo","sends"],te= exports.m =["uses"],l= exports.n =class extends Error{static{i(this,"InvalidArkRunGraphQueryError")}constructor(e,r){super(_nullishCoalesce(r, () => ((e==="slice"?'ArkRun graph slice must be "process" or "technical".':e==="degreesOfSeparation"?"ArkRun graph degreesOfSeparation must be a non-negative integer.":`ArkRun graph ${e} is not a closed query.`)))),this.name="InvalidArkRunGraphQueryError",this.option=e}},kn=new Set(gn),Rn=new Set(["slice","nodeIds","degreesOfSeparation","include","exclude"]),An=new Set(["ids","labels","tags","groups","architectureKinds"]);function y(n,e){return n<e?-1:n>e?1:0}i(y,"compare");function C(n){return[...new Set(n)].sort(y)}i(C,"uniqueSorted");function H(){return{tokens:[],ids:[],labels:[],tags:[],groups:[],architectureKinds:[]}}i(H,"emptyMatch");function T(n){return n.tokens.length+n.ids.length+n.labels.length+n.tags.length+n.groups.length+n.architectureKinds.length>0}i(T,"matchHasCriteria");function f(n,e){if(n==null||n==="")return[];if(typeof n=="string")return C(n.split(",").map(t=>t.trim()).filter(t=>t.length>0));if(!Array.isArray(n))throw new l(e);let r=[];for(let t of n){if(typeof t!="string")throw new l(e);let s=t.trim();s.length>0&&r.push(s)}return C(r)}i(f,"nameList");function V(n,e){if(e==="*")return n.length>0;if(!e.includes("*"))return n===e;let r="^";for(let t of e)t==="*"?r+=".*":/[.*+?^${}()|[\]\\]/.test(t)?r+=`\\${t}`:r+=t;return r+="$",new RegExp(r).test(n)}i(V,"globMatch");function A(n,e){return n?e.some(r=>V(n,r)):!1}i(A,"anyGlob");function j(n){if(n==null||n==="")return ln;if(typeof n=="string"&&kn.has(n))return n;throw new l("slice")}i(j,"closedSlice");function W(n){if(n==null||n==="")return null;if(typeof n=="string"&&/^(0|[1-9]\d*)$/.test(n))return Number(n);if(typeof n=="number"&&Number.isInteger(n)&&n>=0)return n;throw new l("degreesOfSeparation")}i(W,"closedDegrees");function F(n,e){if(n==null||n==="")return H();if(typeof n=="string"||Array.isArray(n))return{...H(),tokens:f(n,e)};if(typeof n!="object")throw new l(e);let r=n;for(let t of Object.keys(r))if(!An.has(t))throw new l(e);return{tokens:[],ids:f(r.ids,e),labels:f(r.labels,e),tags:f(r.tags,e),groups:f(r.groups,e),architectureKinds:f(r.architectureKinds,e)}}i(F,"closedMatch");function Q(n={}){if(n==null||n==="")return Q({});if(typeof n!="object"||Array.isArray(n))throw new l("slice","ArkRun graph query must be an object.");let e=n;for(let r of Object.keys(e))if(!Rn.has(r))throw new l("slice",`ArkRun graph query key "${r}" is not closed.`);return{slice:j(e.slice),nodeIds:f(e.nodeIds,"nodeIds"),degreesOfSeparation:W(e.degreesOfSeparation),include:F(e.include,"include"),exclude:F(e.exclude,"exclude")}}i(Q,"closeArkRunGraphQuery");function oe(n){let e={};n.slice&&(e.slice=j(n.slice));let r=f(_nullishCoalesce(n.nodeIds, () => (void 0)),"nodeIds");r.length>0&&(e.nodeIds=r);let t=W(_nullishCoalesce(n.degreesOfSeparation, () => (void 0)));t!==null&&(e.degreesOfSeparation=t);let s=f(_nullishCoalesce(n.include, () => (void 0)),"include");s.length>0&&(e.include=s);let u=f(_nullishCoalesce(n.exclude, () => (void 0)),"exclude");return u.length>0&&(e.exclude=u),e}i(oe,"arkRunGraphQueryFromSearchParams");function mn(n){let e=[n.id];return n.label&&e.push(n.label),n.group&&e.push(n.group),n.architectureKind&&e.push(n.architectureKind),n.tags&&e.push(...n.tags),e}i(mn,"nodeFields");function $(n,e){if(!T(e))return!0;let r=mn(n);return e.tokens.some(t=>r.some(s=>V(s,t)))||A(n.id,e.ids)||A(n.label,e.labels)||_optionalChain([n, 'access', _2 => _2.tags, 'optionalAccess', _3 => _3.some, 'call', _4 => _4(t=>A(t,e.tags))])||A(n.group,e.groups)?!0:A(n.architectureKind,e.architectureKinds)}i($,"nodeMatches");function yn(n){if(n&&typeof n=="object"&&!Array.isArray(n)){let e=n;return R({kernelInstanceId:e.kernelInstanceId,components:e.components})}return R({})}i(yn,"asPackage");function hn(n){let e={id:n.id,kind:"component",lifetime:n.lifetime},r=n.extendedInfo;return _optionalChain([r, 'optionalAccess', _5 => _5.label])&&(e.label=r.label),_optionalChain([r, 'optionalAccess', _6 => _6.group])&&(e.group=r.group),_optionalChain([r, 'optionalAccess', _7 => _7.architectureKind])&&(e.architectureKind=r.architectureKind),_optionalChain([r, 'optionalAccess', _8 => _8.tags])&&r.tags.length>0&&(e.tags=[...r.tags]),e}i(hn,"componentNode");function S(n){return{id:n,kind:"interaction"}}i(S,"interactionNode");function m(n,e){let r=n.get(e.id);(!r||r.kind==="interaction"&&e.kind==="component")&&n.set(e.id,e)}i(m,"addNode");function _(n,e,r,t,s){let u=`${r}\0${s}\0${t}`;e.has(u)||(e.add(u),n.push({from:r,to:t,kind:s}))}i(_,"addEdge");function bn(n,e){let r=new Map,t=[],s=new Set;for(let u of n){if(m(r,hn(u)),e==="technical"){for(let a of u.uses)m(r,_nullishCoalesce(r.get(a), () => (S(a)))),_(t,s,u.id,a,"uses");continue}for(let a of u.raises)m(r,_nullishCoalesce(r.get(a), () => (S(a)))),_(t,s,u.id,a,"raises");for(let a of u.reactsTo)m(r,_nullishCoalesce(r.get(a), () => (S(a)))),_(t,s,a,u.id,"reactsTo");for(let a of u.sends)m(r,_nullishCoalesce(r.get(a), () => (S(a)))),_(t,s,u.id,a,"sends")}return{nodes:r,edges:t}}i(bn,"buildSlice");function In(n){let e=new Map,r=i((t,s)=>{let u=e.get(t);u?u.push(s):e.set(t,[s])},"push");for(let t of n)r(t.from,t.to),r(t.to,t.from);return e}i(In,"adjacency");function wn(n,e,r,t){let s=e.filter(o=>n.has(o));if(s.length===0)return new Set;let u=new Set,a=s.map(o=>({id:o,depth:0}));for(;a.length>0;){let o=a.shift();if(!(!o||u.has(o.id))&&(u.add(o.id),!(r!==null&&o.depth>=r)))for(let c of _nullishCoalesce(t.get(o.id), () => ([])))!u.has(c)&&n.has(c)&&a.push({id:c,depth:o.depth+1})}return u}i(wn,"neighborhood");function h(n){let e=n.replace(/[^A-Za-z0-9_]/g,"_");return/^[A-Za-z_]/.test(e)?e:`n_${e}`}i(h,"mermaidSafeId");function B(n){return n.replace(/\\/g,"\\\\").replace(/"/g,"#quot;").replace(/]/g,"#93;")}i(B,"mermaidLabel");function Sn(n){let e=new Set,r=new Map;for(let t of n){let s=h(t),u=s,a=2;for(;e.has(u);)u=`${s}_${a}`,a+=1;e.add(u),r.set(t,u)}return r}i(Sn,"uniqueMermaidIds");function _n(n){let e=n.slice==="technical"?"TD":"LR",r=n.nodes.map(o=>o.id),t=Sn(r),s=C(n.nodes.map(o=>o.group).filter(o=>!!o)),u=[`flowchart ${e}`],a=i((o,c)=>{let d=_nullishCoalesce(t.get(o.id), () => (h(o.id))),p=B(_nullishCoalesce(o.label, () => (o.id)));u.push(`${c}${d}["${p}"]`)},"emitNode");for(let o of s){let c=h(`group_${o}`);u.push(` subgraph ${c}["${B(o)}"]`);for(let d of n.nodes)d.group===o&&a(d," ");u.push(" end")}for(let o of n.nodes)o.group||a(o," ");for(let o of n.edges){let c=_nullishCoalesce(t.get(o.from), () => (h(o.from))),d=_nullishCoalesce(t.get(o.to), () => (h(o.to)));u.push(` ${c} -->|${o.kind}| ${d}`)}return u.join(`
2
- `)}i(_n,"formatArkRunGraphMermaid");function xn(n,e,r){let t=new Set(n.keys());if(T(r.include)&&(t=new Set([...t].filter(o=>{let c=n.get(o);return c!==void 0&&$(c,r.include)}))),T(r.exclude))for(let o of[...t]){let c=n.get(o);c&&$(c,r.exclude)&&t.delete(o)}let s=e.filter(o=>t.has(o.from)&&t.has(o.to));r.nodeIds.length>0&&(t=wn(t,r.nodeIds,r.degreesOfSeparation,In(s)));let u=[...t].sort(y).map(o=>n.get(o)).filter(o=>!!o),a=s.filter(o=>t.has(o.from)&&t.has(o.to)).sort((o,c)=>y(o.from,c.from)||y(o.kind,c.kind)||y(o.to,c.to));return{nodes:u,edges:a}}i(xn,"filterGraph");function se(n={},e={}){let r=yn(n),t=Q(e),s=bn(r.components,t.slice),u=xn(s.nodes,s.edges,t),a={schemaVersion:fn,kernelInstanceId:r.kernelInstanceId,slice:t.slice,query:t,nodes:u.nodes,edges:u.edges,mermaid:""};return a.mermaid=_n(a),a}i(se,"requestArkRunGraph");var O=["local","localBlocking","broker"],z= exports.t =!0,Nn=new Set(O),x= exports.u =class extends Error{static{i(this,"InvalidArkRunSendOptionError")}constructor(e){super(e==="transport"?'ArkRun transport must be "local", "localBlocking", or "broker".':"ArkRun ephemeral must be a boolean."),this.name="InvalidArkRunSendOptionError",this.option=e}};function En(n){if(n===void 0)return"local";if(typeof n=="string"&&Nn.has(n))return n;throw new x("transport")}i(En,"closedArkRunTransportKind");function Cn(n){if(n===void 0)return!0;if(n===!0||n===!1)return n;throw new x("ephemeral")}i(Cn,"closedArkRunEphemeral");function ae(n){let e=En(n.transport),r=Cn(n.ephemeral),t=e==="broker"&&n.brokerBound!==!0,s=e==="broker"&&!t?"broker":"local",u=e==="localBlocking";return{transport:e,ephemeral:r,deliveredVia:s,fallbackToLocal:t,notifySubscribers:s==="local",awaitHandlers:u,awaitHandoff:r||u}}i(ae,"resolveArkRunSendPlan");var Tn="1.0",q= exports.z ="127.0.0.1",On= exports.A =0,le= exports.B ="/snapshot",ge= exports.C ="/events",ke= exports.D ="/graph",Re= exports.E ="/outbox",Ae= exports.F ="/workflows",Kn= exports.G ="snapshot",Mn= exports.H ="in-process-local",b= exports.I =32;var P=class extends Error{static{i(this,"ArkRunInspectorProductionError")}constructor(){super("ArkRun inspector refuses to start when NODE_ENV=production."),this.name="ArkRunInspectorProductionError"}},I= exports.K =class extends Error{static{i(this,"ArkRunInspectorBindError")}constructor(e){super(`ArkRun inspector binds loopback only (default 127.0.0.1). Public host "${e}" is rejected.`),this.name="ArkRunInspectorBindError"}},Pn=new Set(["","*","0","0.0.0.0","::","::0","[::]","[::0]","::ffff:0.0.0.0","[::ffff:0.0.0.0]"]);function J(n){return n==="production"}i(J,"isArkRunInspectorProductionEnv");function Gn(n){let e=n.split(".");if(e.length!==4)return;let r=[];for(let t of e){if(!/^\d{1,3}$/.test(t))return;let s=Number(t);if(s>255)return;r.push(s)}return r}i(Gn,"ipv4Octets");function X(n){if(n.startsWith("[::ffff:")&&n.endsWith("]"))return n.slice(8,-1);if(n.startsWith("::ffff:"))return n.slice(7)}i(X,"unwrapIpv4Mapped");function Y(n){if(typeof n!="string")return!1;let e=n.trim().toLowerCase();if(e==="localhost"||e==="::1"||e==="[::1]")return!0;let r=X(e);if(r)return Y(r);let t=Gn(e);return t!==void 0&&t[0]===127}i(Y,"isArkRunInspectorLoopbackHost");function Z(n){if(n===void 0)return q;if(typeof n!="string")throw new I(String(n));let e=n.trim();if(Pn.has(e.toLowerCase())||!Y(e))throw new I(e);let r=e.toLowerCase();if(r==="localhost")return q;if(r==="[::1]")return"::1";let t=X(r);return t?Z(t):r}i(Z,"closedHost");function Dn(n){if(n===void 0)return On;if(typeof n!="number"||!Number.isInteger(n)||n<0||n>65535)throw new I(`port:${String(n)}`);return n}i(Dn,"closedPort");function Ln(n={}){if(J(n.nodeEnv)||J(n.processNodeEnv))throw new P;return{host:Z(n.host),port:Dn(n.port)}}i(Ln,"resolveArkRunInspectorBind");function me(n,e,r){return`http://${n.includes(":")?`[${n}]`:n}:${e}${r}`}i(me,"arkRunInspectorUrl");function Un(n){if(n!==void 0)try{return JSON.parse(JSON.stringify(n))}catch (e2){return}}i(Un,"jsonClone");function Hn(n){return{kinds:[...O],ephemeralDefault:n.ephemeralDefault===!1?!1:!0,brokerBound:n.brokerBound===!0,cloudSdksShipped:!1,fallback:Mn}}i(Hn,"closedTransportFacts");function g(n){if(!(!n||typeof n!="object"||Array.isArray(n)))return n}i(g,"asRecord");function Fn(n){let e=g(n);if(!e||typeof e.id!="string")return;let r=e.status;if(r!=="pending"&&r!=="failed")return;let t=g(e.event),s=t&&typeof t.intent=="string"?t.intent:typeof e.intent=="string"?e.intent:void 0,u={id:e.id,status:r,attempts:typeof e.attempts=="number"&&Number.isFinite(e.attempts)?e.attempts:0};return s&&(u.intent=s),typeof e.error=="string"&&e.error.length>0&&(u.error=e.error),typeof e.updatedAt=="string"&&(u.updatedAt=e.updatedAt),u}i(Fn,"closedOutboxSummary");function N(n){if(typeof n!="number"||!Number.isFinite(n))return b;let e=Math.trunc(n);return e<0?0:e>b?b:e}i(N,"closedSampleLimit");function $n(n,e){let r=typeof n=="string"&&n.trim().length>0?n.trim():n&&typeof n=="object"&&"constructor"in n?String(_nullishCoalesce(_optionalChain([n, 'access', _9 => _9.constructor, 'optionalAccess', _10 => _10.name]), () => (e))):e,t=/^InMemory/i.test(r)?"memory":"durable";return{role:e,id:r,kind:t}}i($n,"classifyArkRunInspectorStoreDurability");function Bn(n={}){let e=g(n),r=_nullishCoalesce(g(_optionalChain([e, 'optionalAccess', _11 => _11.durability])), () => (e)),t=Array.isArray(_optionalChain([r, 'optionalAccess', _12 => _12.stores]))?r.stores:Array.isArray(_optionalChain([e, 'optionalAccess', _13 => _13.stores]))?e.stores:[],s=[];for(let u of t){let a=g(u);if(!a)continue;let o=a.role;if(o!=="outbox"&&o!=="audit"&&o!=="workflow")continue;let c=typeof a.id=="string"?a.id:typeof a.name=="string"?a.name:void 0;if(!c)continue;let d=a.kind==="memory"||a.kind==="durable"?a.kind:$n(c,o).kind;s.push({role:o,id:c,kind:d})}return{durability:{stores:s}}}i(Bn,"buildArkRunInspectorHardening");function Vn(n=[],e={}){let r=N(e.sampleLimit),t=Array.isArray(n)?n:[],s=[],u=[];for(let a of t){let o=Fn(a);o&&(o.status==="pending"?s.push(o):u.push(o))}return{available:!0,pendingCount:s.length,failedCount:u.length,pending:s.slice(0,r),failed:u.slice(0,r),sampleLimit:r}}i(Vn,"buildArkRunInspectorOutboxMonitor");function K(){return{available:!1,pendingCount:0,failedCount:0,pending:[],failed:[],sampleLimit:b}}i(K,"unavailableArkRunInspectorOutboxMonitor");function jn(n){let e=g(n);if(!e||typeof e.id!="string")return;let r=typeof e.workflowName=="string"?e.workflowName:typeof e.name=="string"?e.name:void 0;if(!r)return;let t={id:e.id,name:r,status:typeof e.status=="string"?e.status:"unknown"};return typeof e.currentStep=="string"&&(t.currentStep=e.currentStep),typeof e.error=="string"&&e.error.length>0&&(t.error=e.error),t}i(jn,"closedWorkflowSummary");function Wn(n){return n==="idle"||n==="waiting"}i(Wn,"isPendingWorkflowStatus");function Qn(n=[],e={}){let r=N(e.sampleLimit),t=Array.isArray(n)?n:[],s=[],u=0,a=0,o=0,c=0;for(let d of t){let p=jn(d);p&&(s.push(p),p.status==="running"?u+=1:p.status==="compensating"?a+=1:p.status==="failed"?o+=1:Wn(p.status)&&(c+=1))}return{available:!0,total:s.length,runningCount:u,compensatingCount:a,failedCount:o,pendingCount:c,workflows:s.slice(0,r),sampleLimit:r}}i(Qn,"buildArkRunInspectorWorkflowsMonitor");function M(){return{available:!1,total:0,runningCount:0,compensatingCount:0,failedCount:0,pendingCount:0,workflows:[],sampleLimit:b}}i(M,"unavailableArkRunInspectorWorkflowsMonitor");function zn(n){if(n===void 0)return;let e=g(n);if(!e||e.available===!1)return K();let r=N(e.sampleLimit);if(Array.isArray(e.pending)||Array.isArray(e.failed)||Array.isArray(e.records)){let t=[...Array.isArray(e.pending)?e.pending:[],...Array.isArray(e.failed)?e.failed:[],...Array.isArray(e.records)?e.records:[]],s=Vn(t,{sampleLimit:r}),u=typeof e.pendingCount=="number"&&Number.isFinite(e.pendingCount)?Math.max(0,Math.trunc(e.pendingCount)):s.pendingCount,a=typeof e.failedCount=="number"&&Number.isFinite(e.failedCount)?Math.max(0,Math.trunc(e.failedCount)):s.failedCount;return{...s,pendingCount:u,failedCount:a,sampleLimit:r}}return K()}i(zn,"closedOutboxMonitor");function qn(n){if(n===void 0)return;let e=g(n);if(!e||e.available===!1)return M();let r=N(e.sampleLimit);if(Array.isArray(e.workflows)){let t=Qn(e.workflows,{sampleLimit:r}),s=typeof e.total=="number"&&Number.isFinite(e.total)?Math.max(0,Math.trunc(e.total)):t.total,u=typeof e.runningCount=="number"&&Number.isFinite(e.runningCount)?Math.max(0,Math.trunc(e.runningCount)):t.runningCount,a=typeof e.compensatingCount=="number"&&Number.isFinite(e.compensatingCount)?Math.max(0,Math.trunc(e.compensatingCount)):t.compensatingCount,o=typeof e.failedCount=="number"&&Number.isFinite(e.failedCount)?Math.max(0,Math.trunc(e.failedCount)):t.failedCount,c=typeof e.pendingCount=="number"&&Number.isFinite(e.pendingCount)?Math.max(0,Math.trunc(e.pendingCount)):t.pendingCount;return{...t,total:s,runningCount:u,compensatingCount:a,failedCount:o,pendingCount:c,sampleLimit:r}}return M()}i(qn,"closedWorkflowsMonitor");function ye(n={}){let e=Ln({host:n.host,port:n.port}),r=R({kernelInstanceId:n.kernelInstanceId,components:n.package&&typeof n.package=="object"&&!Array.isArray(n.package)&&Array.isArray(n.package.components)?n.package.components:[]}),t=zn(n.outbox),s=qn(n.workflows),u={schemaVersion:Tn,kernelInstanceId:typeof n.kernelInstanceId=="string"?n.kernelInstanceId:r.kernelInstanceId,bind:{host:e.host,port:e.port,loopback:!0},package:{...r,schemaVersion:"1.0"},transport:Hn(n),observability:_nullishCoalesce(Un(n.observability), () => ({})),hardening:Bn(n.hardening)};return t&&(u.outbox=t),s&&(u.workflows=s),u}i(ye,"buildArkRunInspectorSnapshot");function he(n){return`event: ${Kn}
1
+ 'use strict';var G=Object.defineProperty;var v=Object.getOwnPropertyDescriptor;var i=(n,e)=>G(n,"name",{value:e,configurable:true});var Jn=(n,e,r,t)=>{for(var s=t>1?void 0:t?v(e,r):e,u=n.length-1,a;u>=0;u--)(a=n[u])&&(s=(t?a(e,r,s):a(s))||s);return t&&s&&G(e,r,s),s};var D="1.0",nn=["singleton","transient"],en=["absorb","escalate_up","hold"],rn=new Set(nn);function E(n,e){return n<e?-1:n>e?1:0}i(E,"compare");function tn(n){return [...new Set(n)].sort(E)}i(tn,"uniqueSorted");function k(n){if(!Array.isArray(n))return [];let e=[];for(let r of n)typeof r=="string"&&r.length>0&&e.push(r);return tn(e)}i(k,"nameList");function on(n){if(n===null)return null;if(typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n))return n}i(on,"jsonPrimitive");function sn(n){return typeof n=="string"&&rn.has(n)?n:"singleton"}i(sn,"closedLifetime");function L(n){if(n===null||typeof n!="object"||Array.isArray(n))return;let e={};for(let r of Object.keys(n).sort(E)){if(r.length===0)continue;let t=on(n[r]);t!==void 0&&(e[r]=t);}return Object.keys(e).length>0?e:void 0}i(L,"sanitizeMetadata");function un(n){if(n===null||typeof n!="object"||Array.isArray(n))return;let e=n,r={};typeof e.label=="string"&&e.label.length>0&&(r.label=e.label),typeof e.architectureKind=="string"&&e.architectureKind.length>0&&(r.architectureKind=e.architectureKind);let t=k(e.tags);t.length>0&&(r.tags=t),typeof e.group=="string"&&e.group.length>0&&(r.group=e.group);let s=L(e.metadata);return s&&(r.metadata=s),Object.keys(r).length>0?r:void 0}i(un,"sanitizeArkRunExtendedInfo");function an(n){if(n===null||typeof n!="object"||Array.isArray(n))return;let e=n,r=typeof e.id=="string"?e.id.trim():"";if(!r)return;let t={id:r,lifetime:sn(e.lifetime),uses:k(e.uses),reactsTo:k(e.reactsTo),raises:k(e.raises),sends:k(e.sends)},s=un(e.extendedInfo);return s&&(t.extendedInfo=s),t}i(an,"sanitizeArkRunComponent");var cn=new Set(en);function dn(n){return L(n)}i(dn,"sanitizeTapePayload");function U(n){if(n===null||typeof n!="object"||Array.isArray(n))return;let e=n,r=typeof e.xiHash=="string"?e.xiHash.trim():"";if(!r)return;let t=e.event;if(t===null||typeof t!="object"||Array.isArray(t))return;let s=t,u=typeof s.kind=="string"?s.kind.trim():"";if(!u)return;let a=e.residual;if(a===null||typeof a!="object"||Array.isArray(a))return;let o=a,c=typeof o.kind=="string"&&cn.has(o.kind)?o.kind:void 0;if(!c)return;let d={kind:u},p=dn(s.payload);p&&(d.payload=p);let w={kind:c};return typeof o.reasonCode=="string"&&o.reasonCode.length>0&&(w.reasonCode=o.reasonCode),typeof o.eventId=="string"&&o.eventId.length>0&&(w.eventId=o.eventId),typeof o.target=="string"&&o.target.length>0&&(w.target=o.target),{xiHash:r,event:d,residual:w}}i(U,"sanitizeDecisionTapeRecord");function pn(n){if(!Array.isArray(n))return [];let e=[];for(let r of n){let t=U(r);t&&e.push(t);}return e}i(pn,"sanitizeDecisionTape");function R(n){let e=typeof n.kernelInstanceId=="string"?n.kernelInstanceId:"",r=Array.isArray(n.components)?n.components:[],t=new Set,s=[];for(let a of r){let o=an(a);!o||t.has(o.id)||(t.add(o.id),s.push(o));}s.sort((a,o)=>E(a.id,o.id));let u=pn(n.decisionTape);return {schemaVersion:"1.0",kernelInstanceId:e,components:s,...u.length>0?{decisionTape:u}:{}}}i(R,"buildDependencyInformationPackage");function Yn(n,e){let r=U(e),t=n.decisionTape??[],s=r?[...t,r]:[...t];return {schemaVersion:n.schemaVersion,kernelInstanceId:n.kernelInstanceId,components:n.components,...s.length>0?{decisionTape:s}:{}}}i(Yn,"appendDecisionTape");var fn="1.0",ln="process",gn=["process","technical"],ee=["component","interaction"],re=["raises","reactsTo","sends"],te=["uses"],l=class extends Error{static{i(this,"InvalidArkRunGraphQueryError");}option;constructor(e,r){super(r??(e==="slice"?'ArkRun graph slice must be "process" or "technical".':e==="degreesOfSeparation"?"ArkRun graph degreesOfSeparation must be a non-negative integer.":`ArkRun graph ${e} is not a closed query.`)),this.name="InvalidArkRunGraphQueryError",this.option=e;}},kn=new Set(gn),Rn=new Set(["slice","nodeIds","degreesOfSeparation","include","exclude"]),An=new Set(["ids","labels","tags","groups","architectureKinds"]);function y(n,e){return n<e?-1:n>e?1:0}i(y,"compare");function C(n){return [...new Set(n)].sort(y)}i(C,"uniqueSorted");function H(){return {tokens:[],ids:[],labels:[],tags:[],groups:[],architectureKinds:[]}}i(H,"emptyMatch");function T(n){return n.tokens.length+n.ids.length+n.labels.length+n.tags.length+n.groups.length+n.architectureKinds.length>0}i(T,"matchHasCriteria");function f(n,e){if(n==null||n==="")return [];if(typeof n=="string")return C(n.split(",").map(t=>t.trim()).filter(t=>t.length>0));if(!Array.isArray(n))throw new l(e);let r=[];for(let t of n){if(typeof t!="string")throw new l(e);let s=t.trim();s.length>0&&r.push(s);}return C(r)}i(f,"nameList");function V(n,e){if(e==="*")return n.length>0;if(!e.includes("*"))return n===e;let r="^";for(let t of e)t==="*"?r+=".*":/[.*+?^${}()|[\]\\]/.test(t)?r+=`\\${t}`:r+=t;return r+="$",new RegExp(r).test(n)}i(V,"globMatch");function A(n,e){return n?e.some(r=>V(n,r)):false}i(A,"anyGlob");function j(n){if(n==null||n==="")return ln;if(typeof n=="string"&&kn.has(n))return n;throw new l("slice")}i(j,"closedSlice");function W(n){if(n==null||n==="")return null;if(typeof n=="string"&&/^(0|[1-9]\d*)$/.test(n))return Number(n);if(typeof n=="number"&&Number.isInteger(n)&&n>=0)return n;throw new l("degreesOfSeparation")}i(W,"closedDegrees");function F(n,e){if(n==null||n==="")return H();if(typeof n=="string"||Array.isArray(n))return {...H(),tokens:f(n,e)};if(typeof n!="object")throw new l(e);let r=n;for(let t of Object.keys(r))if(!An.has(t))throw new l(e);return {tokens:[],ids:f(r.ids,e),labels:f(r.labels,e),tags:f(r.tags,e),groups:f(r.groups,e),architectureKinds:f(r.architectureKinds,e)}}i(F,"closedMatch");function Q(n={}){if(n==null||n==="")return Q({});if(typeof n!="object"||Array.isArray(n))throw new l("slice","ArkRun graph query must be an object.");let e=n;for(let r of Object.keys(e))if(!Rn.has(r))throw new l("slice",`ArkRun graph query key "${r}" is not closed.`);return {slice:j(e.slice),nodeIds:f(e.nodeIds,"nodeIds"),degreesOfSeparation:W(e.degreesOfSeparation),include:F(e.include,"include"),exclude:F(e.exclude,"exclude")}}i(Q,"closeArkRunGraphQuery");function oe(n){let e={};n.slice&&(e.slice=j(n.slice));let r=f(n.nodeIds??void 0,"nodeIds");r.length>0&&(e.nodeIds=r);let t=W(n.degreesOfSeparation??void 0);t!==null&&(e.degreesOfSeparation=t);let s=f(n.include??void 0,"include");s.length>0&&(e.include=s);let u=f(n.exclude??void 0,"exclude");return u.length>0&&(e.exclude=u),e}i(oe,"arkRunGraphQueryFromSearchParams");function mn(n){let e=[n.id];return n.label&&e.push(n.label),n.group&&e.push(n.group),n.architectureKind&&e.push(n.architectureKind),n.tags&&e.push(...n.tags),e}i(mn,"nodeFields");function $(n,e){if(!T(e))return true;let r=mn(n);return e.tokens.some(t=>r.some(s=>V(s,t)))||A(n.id,e.ids)||A(n.label,e.labels)||n.tags?.some(t=>A(t,e.tags))||A(n.group,e.groups)?true:A(n.architectureKind,e.architectureKinds)}i($,"nodeMatches");function yn(n){if(n&&typeof n=="object"&&!Array.isArray(n)){let e=n;return R({kernelInstanceId:e.kernelInstanceId,components:e.components})}return R({})}i(yn,"asPackage");function hn(n){let e={id:n.id,kind:"component",lifetime:n.lifetime},r=n.extendedInfo;return r?.label&&(e.label=r.label),r?.group&&(e.group=r.group),r?.architectureKind&&(e.architectureKind=r.architectureKind),r?.tags&&r.tags.length>0&&(e.tags=[...r.tags]),e}i(hn,"componentNode");function S(n){return {id:n,kind:"interaction"}}i(S,"interactionNode");function m(n,e){let r=n.get(e.id);(!r||r.kind==="interaction"&&e.kind==="component")&&n.set(e.id,e);}i(m,"addNode");function _(n,e,r,t,s){let u=`${r}\0${s}\0${t}`;e.has(u)||(e.add(u),n.push({from:r,to:t,kind:s}));}i(_,"addEdge");function bn(n,e){let r=new Map,t=[],s=new Set;for(let u of n){if(m(r,hn(u)),e==="technical"){for(let a of u.uses)m(r,r.get(a)??S(a)),_(t,s,u.id,a,"uses");continue}for(let a of u.raises)m(r,r.get(a)??S(a)),_(t,s,u.id,a,"raises");for(let a of u.reactsTo)m(r,r.get(a)??S(a)),_(t,s,a,u.id,"reactsTo");for(let a of u.sends)m(r,r.get(a)??S(a)),_(t,s,u.id,a,"sends");}return {nodes:r,edges:t}}i(bn,"buildSlice");function In(n){let e=new Map,r=i((t,s)=>{let u=e.get(t);u?u.push(s):e.set(t,[s]);},"push");for(let t of n)r(t.from,t.to),r(t.to,t.from);return e}i(In,"adjacency");function wn(n,e,r,t){let s=e.filter(o=>n.has(o));if(s.length===0)return new Set;let u=new Set,a=s.map(o=>({id:o,depth:0}));for(;a.length>0;){let o=a.shift();if(!(!o||u.has(o.id))&&(u.add(o.id),!(r!==null&&o.depth>=r)))for(let c of t.get(o.id)??[])!u.has(c)&&n.has(c)&&a.push({id:c,depth:o.depth+1});}return u}i(wn,"neighborhood");function h(n){let e=n.replace(/[^A-Za-z0-9_]/g,"_");return /^[A-Za-z_]/.test(e)?e:`n_${e}`}i(h,"mermaidSafeId");function B(n){return n.replace(/\\/g,"\\\\").replace(/"/g,"#quot;").replace(/]/g,"#93;")}i(B,"mermaidLabel");function Sn(n){let e=new Set,r=new Map;for(let t of n){let s=h(t),u=s,a=2;for(;e.has(u);)u=`${s}_${a}`,a+=1;e.add(u),r.set(t,u);}return r}i(Sn,"uniqueMermaidIds");function _n(n){let e=n.slice==="technical"?"TD":"LR",r=n.nodes.map(o=>o.id),t=Sn(r),s=C(n.nodes.map(o=>o.group).filter(o=>!!o)),u=[`flowchart ${e}`],a=i((o,c)=>{let d=t.get(o.id)??h(o.id),p=B(o.label??o.id);u.push(`${c}${d}["${p}"]`);},"emitNode");for(let o of s){let c=h(`group_${o}`);u.push(` subgraph ${c}["${B(o)}"]`);for(let d of n.nodes)d.group===o&&a(d," ");u.push(" end");}for(let o of n.nodes)o.group||a(o," ");for(let o of n.edges){let c=t.get(o.from)??h(o.from),d=t.get(o.to)??h(o.to);u.push(` ${c} -->|${o.kind}| ${d}`);}return u.join(`
2
+ `)}i(_n,"formatArkRunGraphMermaid");function xn(n,e,r){let t=new Set(n.keys());if(T(r.include)&&(t=new Set([...t].filter(o=>{let c=n.get(o);return c!==void 0&&$(c,r.include)}))),T(r.exclude))for(let o of [...t]){let c=n.get(o);c&&$(c,r.exclude)&&t.delete(o);}let s=e.filter(o=>t.has(o.from)&&t.has(o.to));r.nodeIds.length>0&&(t=wn(t,r.nodeIds,r.degreesOfSeparation,In(s)));let u=[...t].sort(y).map(o=>n.get(o)).filter(o=>!!o),a=s.filter(o=>t.has(o.from)&&t.has(o.to)).sort((o,c)=>y(o.from,c.from)||y(o.kind,c.kind)||y(o.to,c.to));return {nodes:u,edges:a}}i(xn,"filterGraph");function se(n={},e={}){let r=yn(n),t=Q(e),s=bn(r.components,t.slice),u=xn(s.nodes,s.edges,t),a={schemaVersion:fn,kernelInstanceId:r.kernelInstanceId,slice:t.slice,query:t,nodes:u.nodes,edges:u.edges,mermaid:""};return a.mermaid=_n(a),a}i(se,"requestArkRunGraph");var O=["local","localBlocking","broker"],z=true,Nn=new Set(O),x=class extends Error{static{i(this,"InvalidArkRunSendOptionError");}option;constructor(e){super(e==="transport"?'ArkRun transport must be "local", "localBlocking", or "broker".':"ArkRun ephemeral must be a boolean."),this.name="InvalidArkRunSendOptionError",this.option=e;}};function En(n){if(n===void 0)return "local";if(typeof n=="string"&&Nn.has(n))return n;throw new x("transport")}i(En,"closedArkRunTransportKind");function Cn(n){if(n===void 0)return true;if(n===true||n===false)return n;throw new x("ephemeral")}i(Cn,"closedArkRunEphemeral");function ae(n){let e=En(n.transport),r=Cn(n.ephemeral),t=e==="broker"&&n.brokerBound!==true,s=e==="broker"&&!t?"broker":"local",u=e==="localBlocking";return {transport:e,ephemeral:r,deliveredVia:s,fallbackToLocal:t,notifySubscribers:s==="local",awaitHandlers:u,awaitHandoff:r||u}}i(ae,"resolveArkRunSendPlan");var Tn="1.0",q="127.0.0.1",On=0,le="/snapshot",ge="/events",ke="/graph",Re="/outbox",Ae="/workflows",Kn="snapshot",Mn="in-process-local",b=32;var P=class extends Error{static{i(this,"ArkRunInspectorProductionError");}constructor(){super("ArkRun inspector refuses to start when NODE_ENV=production."),this.name="ArkRunInspectorProductionError";}},I=class extends Error{static{i(this,"ArkRunInspectorBindError");}constructor(e){super(`ArkRun inspector binds loopback only (default 127.0.0.1). Public host "${e}" is rejected.`),this.name="ArkRunInspectorBindError";}},Pn=new Set(["","*","0","0.0.0.0","::","::0","[::]","[::0]","::ffff:0.0.0.0","[::ffff:0.0.0.0]"]);function J(n){return n==="production"}i(J,"isArkRunInspectorProductionEnv");function Gn(n){let e=n.split(".");if(e.length!==4)return;let r=[];for(let t of e){if(!/^\d{1,3}$/.test(t))return;let s=Number(t);if(s>255)return;r.push(s);}return r}i(Gn,"ipv4Octets");function X(n){if(n.startsWith("[::ffff:")&&n.endsWith("]"))return n.slice(8,-1);if(n.startsWith("::ffff:"))return n.slice(7)}i(X,"unwrapIpv4Mapped");function Y(n){if(typeof n!="string")return false;let e=n.trim().toLowerCase();if(e==="localhost"||e==="::1"||e==="[::1]")return true;let r=X(e);if(r)return Y(r);let t=Gn(e);return t!==void 0&&t[0]===127}i(Y,"isArkRunInspectorLoopbackHost");function Z(n){if(n===void 0)return q;if(typeof n!="string")throw new I(String(n));let e=n.trim();if(Pn.has(e.toLowerCase())||!Y(e))throw new I(e);let r=e.toLowerCase();if(r==="localhost")return q;if(r==="[::1]")return "::1";let t=X(r);return t?Z(t):r}i(Z,"closedHost");function Dn(n){if(n===void 0)return On;if(typeof n!="number"||!Number.isInteger(n)||n<0||n>65535)throw new I(`port:${String(n)}`);return n}i(Dn,"closedPort");function Ln(n={}){if(J(n.nodeEnv)||J(n.processNodeEnv))throw new P;return {host:Z(n.host),port:Dn(n.port)}}i(Ln,"resolveArkRunInspectorBind");function me(n,e,r){return `http://${n.includes(":")?`[${n}]`:n}:${e}${r}`}i(me,"arkRunInspectorUrl");function Un(n){if(n!==void 0)try{return JSON.parse(JSON.stringify(n))}catch{return}}i(Un,"jsonClone");function Hn(n){return {kinds:[...O],ephemeralDefault:n.ephemeralDefault===false?false:true,brokerBound:n.brokerBound===true,cloudSdksShipped:false,fallback:Mn}}i(Hn,"closedTransportFacts");function g(n){if(!(!n||typeof n!="object"||Array.isArray(n)))return n}i(g,"asRecord");function Fn(n){let e=g(n);if(!e||typeof e.id!="string")return;let r=e.status;if(r!=="pending"&&r!=="failed")return;let t=g(e.event),s=t&&typeof t.intent=="string"?t.intent:typeof e.intent=="string"?e.intent:void 0,u={id:e.id,status:r,attempts:typeof e.attempts=="number"&&Number.isFinite(e.attempts)?e.attempts:0};return s&&(u.intent=s),typeof e.error=="string"&&e.error.length>0&&(u.error=e.error),typeof e.updatedAt=="string"&&(u.updatedAt=e.updatedAt),u}i(Fn,"closedOutboxSummary");function N(n){if(typeof n!="number"||!Number.isFinite(n))return b;let e=Math.trunc(n);return e<0?0:e>b?b:e}i(N,"closedSampleLimit");function $n(n,e){let r=typeof n=="string"&&n.trim().length>0?n.trim():n&&typeof n=="object"&&"constructor"in n?String(n.constructor?.name??e):e,t=/^InMemory/i.test(r)?"memory":"durable";return {role:e,id:r,kind:t}}i($n,"classifyArkRunInspectorStoreDurability");function Bn(n={}){let e=g(n),r=g(e?.durability)??e,t=Array.isArray(r?.stores)?r.stores:Array.isArray(e?.stores)?e.stores:[],s=[];for(let u of t){let a=g(u);if(!a)continue;let o=a.role;if(o!=="outbox"&&o!=="audit"&&o!=="workflow")continue;let c=typeof a.id=="string"?a.id:typeof a.name=="string"?a.name:void 0;if(!c)continue;let d=a.kind==="memory"||a.kind==="durable"?a.kind:$n(c,o).kind;s.push({role:o,id:c,kind:d});}return {durability:{stores:s}}}i(Bn,"buildArkRunInspectorHardening");function Vn(n=[],e={}){let r=N(e.sampleLimit),t=Array.isArray(n)?n:[],s=[],u=[];for(let a of t){let o=Fn(a);o&&(o.status==="pending"?s.push(o):u.push(o));}return {available:true,pendingCount:s.length,failedCount:u.length,pending:s.slice(0,r),failed:u.slice(0,r),sampleLimit:r}}i(Vn,"buildArkRunInspectorOutboxMonitor");function K(){return {available:false,pendingCount:0,failedCount:0,pending:[],failed:[],sampleLimit:b}}i(K,"unavailableArkRunInspectorOutboxMonitor");function jn(n){let e=g(n);if(!e||typeof e.id!="string")return;let r=typeof e.workflowName=="string"?e.workflowName:typeof e.name=="string"?e.name:void 0;if(!r)return;let t={id:e.id,name:r,status:typeof e.status=="string"?e.status:"unknown"};return typeof e.currentStep=="string"&&(t.currentStep=e.currentStep),typeof e.error=="string"&&e.error.length>0&&(t.error=e.error),t}i(jn,"closedWorkflowSummary");function Wn(n){return n==="idle"||n==="waiting"}i(Wn,"isPendingWorkflowStatus");function Qn(n=[],e={}){let r=N(e.sampleLimit),t=Array.isArray(n)?n:[],s=[],u=0,a=0,o=0,c=0;for(let d of t){let p=jn(d);p&&(s.push(p),p.status==="running"?u+=1:p.status==="compensating"?a+=1:p.status==="failed"?o+=1:Wn(p.status)&&(c+=1));}return {available:true,total:s.length,runningCount:u,compensatingCount:a,failedCount:o,pendingCount:c,workflows:s.slice(0,r),sampleLimit:r}}i(Qn,"buildArkRunInspectorWorkflowsMonitor");function M(){return {available:false,total:0,runningCount:0,compensatingCount:0,failedCount:0,pendingCount:0,workflows:[],sampleLimit:b}}i(M,"unavailableArkRunInspectorWorkflowsMonitor");function zn(n){if(n===void 0)return;let e=g(n);if(!e||e.available===false)return K();let r=N(e.sampleLimit);if(Array.isArray(e.pending)||Array.isArray(e.failed)||Array.isArray(e.records)){let t=[...Array.isArray(e.pending)?e.pending:[],...Array.isArray(e.failed)?e.failed:[],...Array.isArray(e.records)?e.records:[]],s=Vn(t,{sampleLimit:r}),u=typeof e.pendingCount=="number"&&Number.isFinite(e.pendingCount)?Math.max(0,Math.trunc(e.pendingCount)):s.pendingCount,a=typeof e.failedCount=="number"&&Number.isFinite(e.failedCount)?Math.max(0,Math.trunc(e.failedCount)):s.failedCount;return {...s,pendingCount:u,failedCount:a,sampleLimit:r}}return K()}i(zn,"closedOutboxMonitor");function qn(n){if(n===void 0)return;let e=g(n);if(!e||e.available===false)return M();let r=N(e.sampleLimit);if(Array.isArray(e.workflows)){let t=Qn(e.workflows,{sampleLimit:r}),s=typeof e.total=="number"&&Number.isFinite(e.total)?Math.max(0,Math.trunc(e.total)):t.total,u=typeof e.runningCount=="number"&&Number.isFinite(e.runningCount)?Math.max(0,Math.trunc(e.runningCount)):t.runningCount,a=typeof e.compensatingCount=="number"&&Number.isFinite(e.compensatingCount)?Math.max(0,Math.trunc(e.compensatingCount)):t.compensatingCount,o=typeof e.failedCount=="number"&&Number.isFinite(e.failedCount)?Math.max(0,Math.trunc(e.failedCount)):t.failedCount,c=typeof e.pendingCount=="number"&&Number.isFinite(e.pendingCount)?Math.max(0,Math.trunc(e.pendingCount)):t.pendingCount;return {...t,total:s,runningCount:u,compensatingCount:a,failedCount:o,pendingCount:c,sampleLimit:r}}return M()}i(qn,"closedWorkflowsMonitor");function ye(n={}){let e=Ln({host:n.host,port:n.port}),r=R({kernelInstanceId:n.kernelInstanceId,components:n.package&&typeof n.package=="object"&&!Array.isArray(n.package)&&Array.isArray(n.package.components)?n.package.components:[]}),t=zn(n.outbox),s=qn(n.workflows),u={schemaVersion:Tn,kernelInstanceId:typeof n.kernelInstanceId=="string"?n.kernelInstanceId:r.kernelInstanceId,bind:{host:e.host,port:e.port,loopback:true},package:{...r,schemaVersion:"1.0"},transport:Hn(n),observability:Un(n.observability)??{},hardening:Bn(n.hardening)};return t&&(u.outbox=t),s&&(u.workflows=s),u}i(ye,"buildArkRunInspectorSnapshot");function he(n){return `event: ${Kn}
3
3
  data: ${JSON.stringify(n)}
4
4
 
5
- `}i(he,"formatArkRunInspectorSseEvent");exports.a = i; exports.b = Jn; exports.c = D; exports.d = nn; exports.e = an; exports.f = R; exports.g = Yn; exports.h = fn; exports.i = ln; exports.j = gn; exports.k = ee; exports.l = re; exports.m = te; exports.n = l; exports.o = Q; exports.p = oe; exports.q = _n; exports.r = se; exports.s = O; exports.t = z; exports.u = x; exports.v = En; exports.w = Cn; exports.x = ae; exports.y = Tn; exports.z = q; exports.A = On; exports.B = le; exports.C = ge; exports.D = ke; exports.E = Re; exports.F = Ae; exports.G = Kn; exports.H = Mn; exports.I = b; exports.J = P; exports.K = I; exports.L = J; exports.M = Y; exports.N = Ln; exports.O = me; exports.P = $n; exports.Q = Bn; exports.R = Vn; exports.S = K; exports.T = Qn; exports.U = M; exports.V = ye; exports.W = he;
5
+ `}i(he,"formatArkRunInspectorSseEvent");exports.A=On;exports.B=le;exports.C=ge;exports.D=ke;exports.E=Re;exports.F=Ae;exports.G=Kn;exports.H=Mn;exports.I=b;exports.J=P;exports.K=I;exports.L=J;exports.M=Y;exports.N=Ln;exports.O=me;exports.P=$n;exports.Q=Bn;exports.R=Vn;exports.S=K;exports.T=Qn;exports.U=M;exports.V=ye;exports.W=he;exports.a=i;exports.b=Jn;exports.c=D;exports.d=nn;exports.e=an;exports.f=R;exports.g=Yn;exports.h=fn;exports.i=ln;exports.j=gn;exports.k=ee;exports.l=re;exports.m=te;exports.n=l;exports.o=Q;exports.p=oe;exports.q=_n;exports.r=se;exports.s=O;exports.t=z;exports.u=x;exports.v=En;exports.w=Cn;exports.x=ae;exports.y=Tn;exports.z=q;