kaabalah 5.5.1 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +72 -0
  2. package/dist/astrology/index.d.mts +16 -1
  3. package/dist/astrology/index.d.ts +16 -1
  4. package/dist/astrology/index.js +55 -51
  5. package/dist/astrology/index.mjs +1 -1
  6. package/dist/{chunk-BJUCABP4.js → chunk-3HYK4Q4B.js} +123 -10
  7. package/dist/chunk-3HYK4Q4B.js.map +1 -0
  8. package/dist/{chunk-27IU6FA2.mjs → chunk-3SFBJHP2.mjs} +3 -3
  9. package/dist/{chunk-27IU6FA2.mjs.map → chunk-3SFBJHP2.mjs.map} +1 -1
  10. package/dist/chunk-4NMXTZX4.mjs +525 -0
  11. package/dist/chunk-4NMXTZX4.mjs.map +1 -0
  12. package/dist/{chunk-T6Y4DLMA.mjs → chunk-5NCI7UPZ.mjs} +176 -11
  13. package/dist/chunk-5NCI7UPZ.mjs.map +1 -0
  14. package/dist/chunk-7IXAG4KW.mjs +2136 -0
  15. package/dist/chunk-7IXAG4KW.mjs.map +1 -0
  16. package/dist/{chunk-HGEWHDIX.js → chunk-DU5HI6CU.js} +176 -10
  17. package/dist/chunk-DU5HI6CU.js.map +1 -0
  18. package/dist/{chunk-PEAOQ7YH.js → chunk-EVQ432JA.js} +23 -23
  19. package/dist/{chunk-PEAOQ7YH.js.map → chunk-EVQ432JA.js.map} +1 -1
  20. package/dist/{chunk-PPSRTX52.mjs → chunk-IHQPXEB7.mjs} +123 -11
  21. package/dist/chunk-IHQPXEB7.mjs.map +1 -0
  22. package/dist/{chunk-W5UTGQI2.mjs → chunk-S6BFRUJQ.mjs} +3 -3
  23. package/dist/{chunk-W5UTGQI2.mjs.map → chunk-S6BFRUJQ.mjs.map} +1 -1
  24. package/dist/chunk-XB6PXEKO.js +529 -0
  25. package/dist/chunk-XB6PXEKO.js.map +1 -0
  26. package/dist/chunk-XNJ6UHWN.js +2150 -0
  27. package/dist/chunk-XNJ6UHWN.js.map +1 -0
  28. package/dist/{chunk-ZQ2ZZPOW.js → chunk-XTVGQXCL.js} +4 -4
  29. package/dist/{chunk-ZQ2ZZPOW.js.map → chunk-XTVGQXCL.js.map} +1 -1
  30. package/dist/cli.js +1817 -97
  31. package/dist/cli.js.map +1 -1
  32. package/dist/{registry-DOiHyH-r.d.mts → constants-DbFwuCjR.d.mts} +1 -177
  33. package/dist/{registry-DOiHyH-r.d.ts → constants-DbFwuCjR.d.ts} +1 -177
  34. package/dist/core/index.d.mts +66 -3
  35. package/dist/core/index.d.ts +66 -3
  36. package/dist/core/index.js +55 -39
  37. package/dist/core/index.mjs +2 -2
  38. package/dist/correspondence-model-D8c42J4c.d.mts +281 -0
  39. package/dist/correspondence-model-DhmBYoMf.d.ts +281 -0
  40. package/dist/gematria/index.d.mts +2 -1
  41. package/dist/gematria/index.d.ts +2 -1
  42. package/dist/gematria/index.js +5 -5
  43. package/dist/gematria/index.mjs +2 -2
  44. package/dist/index.d.mts +5 -4
  45. package/dist/index.d.ts +5 -4
  46. package/dist/index.js +179 -119
  47. package/dist/index.mjs +6 -6
  48. package/dist/numerology/index.js +18 -18
  49. package/dist/numerology/index.mjs +3 -3
  50. package/dist/tarot/index.d.mts +157 -2
  51. package/dist/tarot/index.d.ts +157 -2
  52. package/dist/tarot/index.js +46 -4
  53. package/dist/tarot/index.mjs +3 -1
  54. package/package.json +1 -1
  55. package/dist/chunk-3IPH7UTM.mjs +0 -878
  56. package/dist/chunk-3IPH7UTM.mjs.map +0 -1
  57. package/dist/chunk-AD7T42HJ.js +0 -4
  58. package/dist/chunk-AD7T42HJ.js.map +0 -1
  59. package/dist/chunk-BJUCABP4.js.map +0 -1
  60. package/dist/chunk-FYR5Z7M2.js +0 -882
  61. package/dist/chunk-FYR5Z7M2.js.map +0 -1
  62. package/dist/chunk-HGEWHDIX.js.map +0 -1
  63. package/dist/chunk-PPSRTX52.mjs.map +0 -1
  64. package/dist/chunk-RFSO3JRG.mjs +0 -3
  65. package/dist/chunk-RFSO3JRG.mjs.map +0 -1
  66. package/dist/chunk-T6Y4DLMA.mjs.map +0 -1
package/dist/cli.js CHANGED
@@ -7053,8 +7053,164 @@ __export(swisseph_exports, {
7053
7053
  inspectVirtualEphemerisPath: () => inspectVirtualEphemerisPath,
7054
7054
  normalizeAngle: () => normalizeAngle,
7055
7055
  resolveNodeEphemerisPath: () => resolveNodeEphemerisPath,
7056
+ resolveSwissEphRuntimeAssets: () => resolveSwissEphRuntimeAssets,
7056
7057
  toUtcDate: () => toUtcDate
7057
7058
  });
7059
+ function emitRuntimeNotice(message) {
7060
+ if (typeof process !== "undefined" && process.stderr && typeof process.stderr.write === "function") {
7061
+ process.stderr.write(`${message}
7062
+ `);
7063
+ return;
7064
+ }
7065
+ console.info(message);
7066
+ }
7067
+ function getRuntimeEnv(env) {
7068
+ if (env) {
7069
+ return env;
7070
+ }
7071
+ if (typeof process !== "undefined" && process.env) {
7072
+ return process.env;
7073
+ }
7074
+ return {};
7075
+ }
7076
+ function firstDefinedEnvValue(env, keys) {
7077
+ for (const key of keys) {
7078
+ const value = env[key];
7079
+ if (typeof value === "string" && value.length > 0) {
7080
+ return value;
7081
+ }
7082
+ }
7083
+ return void 0;
7084
+ }
7085
+ function getBundledNodeSwissEphAssets(options) {
7086
+ if (options.bundledNodeWasmPath && options.bundledNodeEphePath) {
7087
+ return {
7088
+ wasmPaths: [options.bundledNodeWasmPath],
7089
+ ephePaths: [options.bundledNodeEphePath]
7090
+ };
7091
+ }
7092
+ const resolvePath = options.nodePathResolve ?? ((...paths) => require("path").resolve(...paths));
7093
+ return {
7094
+ wasmPaths: [
7095
+ options.bundledNodeWasmPath,
7096
+ resolvePath(__dirname, swisseph_node_default),
7097
+ resolvePath(__dirname, "../../wasm/build/swisseph.node.wasm"),
7098
+ resolvePath(__dirname, "../wasm/build/swisseph.node.wasm")
7099
+ ].filter((value) => typeof value === "string"),
7100
+ ephePaths: [
7101
+ options.bundledNodeEphePath,
7102
+ resolvePath(__dirname, "../../ephe"),
7103
+ resolvePath(__dirname, "../ephe")
7104
+ ].filter((value) => typeof value === "string")
7105
+ };
7106
+ }
7107
+ function getBundledBrowserSwissEphAssets(options) {
7108
+ return {
7109
+ wasmPath: options.bundledBrowserWasmPath ?? swisseph_web_default,
7110
+ ephePath: options.bundledBrowserEphePath ?? "../ephe"
7111
+ };
7112
+ }
7113
+ function formatCandidatePaths(paths) {
7114
+ return paths.length > 0 ? paths.join(", ") : "(none)";
7115
+ }
7116
+ function resolveBundledRuntimeAssetPath(label, bundledPaths, existsSync2) {
7117
+ for (const bundledPath of bundledPaths) {
7118
+ if (existsSync2(bundledPath)) {
7119
+ return {
7120
+ path: bundledPath,
7121
+ source: "bundled"
7122
+ };
7123
+ }
7124
+ }
7125
+ throw new Error(
7126
+ `Unable to resolve Swiss Ephemeris ${label}. Bundled paths checked: ${formatCandidatePaths(
7127
+ bundledPaths
7128
+ )}.`
7129
+ );
7130
+ }
7131
+ function resolveRuntimeAssetPath(label, explicitPath, envPath, candidatePaths, bundledPaths, existsSync2) {
7132
+ if (explicitPath) {
7133
+ if (!existsSync2(explicitPath)) {
7134
+ throw new Error(
7135
+ `Swiss Ephemeris ${label} override does not exist: "${explicitPath}".`
7136
+ );
7137
+ }
7138
+ return {
7139
+ path: explicitPath,
7140
+ source: "explicit"
7141
+ };
7142
+ }
7143
+ if (envPath) {
7144
+ if (!existsSync2(envPath)) {
7145
+ throw new Error(
7146
+ `Swiss Ephemeris ${label} from environment does not exist: "${envPath}".`
7147
+ );
7148
+ }
7149
+ return {
7150
+ path: envPath,
7151
+ source: "env"
7152
+ };
7153
+ }
7154
+ for (const candidatePath of candidatePaths) {
7155
+ if (existsSync2(candidatePath)) {
7156
+ return {
7157
+ path: candidatePath,
7158
+ source: "candidate"
7159
+ };
7160
+ }
7161
+ }
7162
+ try {
7163
+ return resolveBundledRuntimeAssetPath(label, bundledPaths, existsSync2);
7164
+ } catch (error) {
7165
+ throw new Error(
7166
+ `Unable to resolve Swiss Ephemeris ${label}. Checked candidate paths: ${formatCandidatePaths(
7167
+ candidatePaths
7168
+ )}. ${toError(error).message}`
7169
+ );
7170
+ }
7171
+ }
7172
+ function resolveSwissEphRuntimeAssetsInternal(options = {}) {
7173
+ const isBrowser = options.isBrowser ?? typeof window !== "undefined";
7174
+ if (isBrowser) {
7175
+ const bundledAssets2 = getBundledBrowserSwissEphAssets(options);
7176
+ return {
7177
+ wasmPath: options.wasmPath ?? bundledAssets2.wasmPath,
7178
+ ephePath: options.ephePath ?? bundledAssets2.ephePath,
7179
+ wasmPathSource: options.wasmPath ? "explicit" : "bundled",
7180
+ ephePathSource: options.ephePath ? "explicit" : "bundled"
7181
+ };
7182
+ }
7183
+ const env = getRuntimeEnv(options.env);
7184
+ const existsSync2 = options.existsSync ?? ((path) => require("fs").existsSync(path));
7185
+ const bundledAssets = getBundledNodeSwissEphAssets(options);
7186
+ const envWasmPath = firstDefinedEnvValue(env, SWISS_EPH_RUNTIME_WASM_ENV_KEYS);
7187
+ const envEphePath = firstDefinedEnvValue(env, SWISS_EPH_RUNTIME_EPHE_ENV_KEYS);
7188
+ const resolvedWasm = resolveRuntimeAssetPath(
7189
+ "wasmPath",
7190
+ options.wasmPath,
7191
+ envWasmPath,
7192
+ options.wasmPathCandidates ?? [],
7193
+ bundledAssets.wasmPaths,
7194
+ existsSync2
7195
+ );
7196
+ const resolvedEphe = resolveRuntimeAssetPath(
7197
+ "ephePath",
7198
+ options.ephePath,
7199
+ envEphePath,
7200
+ options.ephePathCandidates ?? [],
7201
+ bundledAssets.ephePaths,
7202
+ existsSync2
7203
+ );
7204
+ return {
7205
+ wasmPath: resolvedWasm.path,
7206
+ ephePath: resolvedEphe.path,
7207
+ wasmPathSource: resolvedWasm.source,
7208
+ ephePathSource: resolvedEphe.source
7209
+ };
7210
+ }
7211
+ function resolveSwissEphRuntimeAssets(options = {}) {
7212
+ return resolveSwissEphRuntimeAssetsInternal(options);
7213
+ }
7058
7214
  function normalizeVirtualPath(path) {
7059
7215
  if (path === "/") {
7060
7216
  return path;
@@ -7228,15 +7384,17 @@ async function getSwissEph(options = {}) {
7228
7384
  }
7229
7385
  try {
7230
7386
  const isBrowser = typeof window !== "undefined";
7231
- const wasmUrl = isBrowser ? swisseph_web_default : swisseph_node_default;
7232
- const finalWasmPath = options.wasmPath || (isBrowser ? wasmUrl : require("path").resolve(__dirname, wasmUrl));
7387
+ const runtimeAssets = resolveSwissEphRuntimeAssets({
7388
+ wasmPath: options.wasmPath,
7389
+ ephePath: options.ephePath
7390
+ });
7391
+ const finalWasmPath = runtimeAssets.wasmPath;
7233
7392
  const moduleFactory = isBrowser ? (await Promise.resolve().then(() => __toESM(require_swisseph_web()))).default : (await Promise.resolve().then(() => __toESM(require_swisseph_node()))).default;
7234
7393
  const module2 = await moduleFactory({
7235
7394
  locateFile: () => finalWasmPath
7236
7395
  });
7237
7396
  const instance = new SwissEph(module2);
7238
- const defaultEphePath = isBrowser ? "../ephe" : require("path").resolve(__dirname, "../ephe");
7239
- const finalEphePath = options.ephePath || defaultEphePath;
7397
+ const finalEphePath = runtimeAssets.ephePath;
7240
7398
  if (isBrowser) {
7241
7399
  const epheFsPath = "/ephe";
7242
7400
  try {
@@ -7264,16 +7422,16 @@ async function getSwissEph(options = {}) {
7264
7422
  `Failed to materialize browser ephemeris files at "${epheFsPath}". Missing: ${browserCheck.missingFiles.join(", ")}.`
7265
7423
  );
7266
7424
  }
7267
- console.info(`Setting ephemeris path to: ${epheFsPath}`);
7425
+ emitRuntimeNotice(`Setting ephemeris path to: ${epheFsPath}`);
7268
7426
  instance.setEphemerisPath(epheFsPath);
7269
7427
  } else {
7270
7428
  const resolution = resolveNodeEphemerisPath(module2, finalEphePath);
7271
7429
  if (resolution.strategy === "nodefs-mount") {
7272
- console.info(`Setting ephemeris path to: ${resolution.path} (mounted from ${finalEphePath})`);
7430
+ emitRuntimeNotice(`Setting ephemeris path to: ${resolution.path} (mounted from ${finalEphePath})`);
7273
7431
  } else if (resolution.strategy === "memfs-copy") {
7274
- console.info(`Setting ephemeris path to: ${resolution.path} (copied from ${finalEphePath})`);
7432
+ emitRuntimeNotice(`Setting ephemeris path to: ${resolution.path} (copied from ${finalEphePath})`);
7275
7433
  } else {
7276
- console.info(`Setting ephemeris path to: ${resolution.path}`);
7434
+ emitRuntimeNotice(`Setting ephemeris path to: ${resolution.path}`);
7277
7435
  }
7278
7436
  instance.setEphemerisPath(resolution.path);
7279
7437
  }
@@ -7495,7 +7653,7 @@ async function localToUtcDate(local, latitude, longitude, opts = {}) {
7495
7653
  async function toUtcDate(local, latitude, longitude, options = {}) {
7496
7654
  return localToUtcDate(local, latitude, longitude, options);
7497
7655
  }
7498
- var swissEph, DEFAULT_FLAGS, REQUIRED_EPHE_FILES, NODE_EPHE_MOUNT_POINT, NODE_EPHE_MEMFS_PATH;
7656
+ var swissEph, DEFAULT_FLAGS, REQUIRED_EPHE_FILES, NODE_EPHE_MOUNT_POINT, NODE_EPHE_MEMFS_PATH, SWISS_EPH_RUNTIME_WASM_ENV_KEYS, SWISS_EPH_RUNTIME_EPHE_ENV_KEYS;
7499
7657
  var init_swisseph2 = __esm({
7500
7658
  "src/astrology/swisseph.ts"() {
7501
7659
  "use strict";
@@ -7507,6 +7665,14 @@ var init_swisseph2 = __esm({
7507
7665
  REQUIRED_EPHE_FILES = ["seas_18.se1", "semo_18.se1", "sepl_18.se1"];
7508
7666
  NODE_EPHE_MOUNT_POINT = "/ephefs";
7509
7667
  NODE_EPHE_MEMFS_PATH = "/ephemem";
7668
+ SWISS_EPH_RUNTIME_WASM_ENV_KEYS = [
7669
+ "KAABALAH_SWISSEPH_WASM_PATH",
7670
+ "KAABALAH_WASM_PATH"
7671
+ ];
7672
+ SWISS_EPH_RUNTIME_EPHE_ENV_KEYS = [
7673
+ "KAABALAH_SWISSEPH_EPHE_PATH",
7674
+ "KAABALAH_EPHE_PATH"
7675
+ ];
7510
7676
  }
7511
7677
  });
7512
7678
 
@@ -8192,6 +8358,7 @@ __export(astrology_exports, {
8192
8358
  getZodiacPosition: () => getZodiacPosition,
8193
8359
  normalizeAngle: () => normalizeAngle,
8194
8360
  queryAstrocartographyLocation: () => queryAstrocartographyLocation,
8361
+ resolveSwissEphRuntimeAssets: () => resolveSwissEphRuntimeAssets,
8195
8362
  shorterArcMidpoint: () => shorterArcMidpoint
8196
8363
  });
8197
8364
  function validateInputs(options) {
@@ -8735,7 +8902,7 @@ var import_config3 = require("dotenv/config");
8735
8902
  // package.json
8736
8903
  var package_default = {
8737
8904
  name: "kaabalah",
8738
- version: "5.5.1",
8905
+ version: "6.0.0",
8739
8906
  description: "The de-facto library for any esoteric calculations and tooling",
8740
8907
  engines: {
8741
8908
  node: ">=18.18.0"
@@ -8961,7 +9128,7 @@ var COMMANDS = [
8961
9128
  },
8962
9129
  {
8963
9130
  name: "tree",
8964
- description: "Show Tree of Life structure with all nodes, data, and edges",
9131
+ description: "Show Tree of Life structure with nodes and first-class correspondence edges",
8965
9132
  args: [],
8966
9133
  flags: [],
8967
9134
  examples: ["kaabalah tree --json --compact", "kaabalah tree --json --fields=nodes"]
@@ -8981,6 +9148,20 @@ var COMMANDS = [
8981
9148
  "kaabalah tree:node path:1 --depth=2 --json"
8982
9149
  ]
8983
9150
  },
9151
+ {
9152
+ name: "tree:find",
9153
+ description: "Find tree nodes by ID, name, or type",
9154
+ args: [{ name: "query", type: "string", required: false, description: "Search string matched against node IDs and names" }],
9155
+ flags: [
9156
+ { name: "type", type: "string", description: "Filter matches by node type (e.g. sphere, tarotArkAnnu, planet)" },
9157
+ { name: "limit", type: "number", default: 20, description: "Maximum matches to return (default: 20)" }
9158
+ ],
9159
+ examples: [
9160
+ "kaabalah tree:find magician --json",
9161
+ "kaabalah tree:find --type=planet --json",
9162
+ "kaabalah tree:find kether --type=sphere --json --compact"
9163
+ ]
9164
+ },
8984
9165
  {
8985
9166
  name: "tree:types",
8986
9167
  description: "List all node types and their counts",
@@ -9001,6 +9182,8 @@ var COMMANDS = [
9001
9182
  { name: "location", type: "string", description: "Location string for geocoding (requires GOOGLE_MAPS_API_KEY or KAABALAH_GOOGLE_MAPS_API_KEY)" },
9002
9183
  { name: "house-system", type: "string", default: "placidus", description: "House system: placidus, koch, porphyrius, regiomontanus, campanus, equal, whole-sign, meridian, morinus, krusinski, alcabitius" },
9003
9184
  { name: "timezone", type: "string", description: "IANA timezone string (e.g. America/New_York). Auto-resolved from coordinates if omitted" },
9185
+ { name: "max-orb", type: "number", description: "Maximum orb in degrees to include in the returned aspects array" },
9186
+ { name: "aspect-types", type: "string", description: "Comma-separated aspect names, or 'major' for conjunction,sextile,square,trine,opposition" },
9004
9187
  { name: "wasm-path", type: "string", description: "Override the Swiss Ephemeris WASM runtime path" },
9005
9188
  { name: "ephe-path", type: "string", description: "Override the ephemeris data directory path" }
9006
9189
  ],
@@ -9017,6 +9200,8 @@ var COMMANDS = [
9017
9200
  flags: [
9018
9201
  { name: "house-system", type: "string", default: "placidus", description: "House system for both charts" },
9019
9202
  { name: "timezone", type: "string", description: "Default timezone for both charts when omitted in chartA/chartB" },
9203
+ { name: "max-orb", type: "number", description: "Maximum orb in degrees to include in the returned aspect arrays" },
9204
+ { name: "aspect-types", type: "string", description: "Comma-separated aspect names, or 'major' for conjunction,sextile,square,trine,opposition" },
9020
9205
  { name: "wasm-path", type: "string", description: "Override the Swiss Ephemeris WASM runtime path" },
9021
9206
  { name: "ephe-path", type: "string", description: "Override the ephemeris data directory path" }
9022
9207
  ],
@@ -9031,6 +9216,8 @@ var COMMANDS = [
9031
9216
  flags: [
9032
9217
  { name: "house-system", type: "string", default: "placidus", description: "House system for both charts" },
9033
9218
  { name: "timezone", type: "string", description: "Default timezone for both charts when omitted in chartA/chartB" },
9219
+ { name: "max-orb", type: "number", description: "Maximum orb in degrees to include in the returned aspect arrays" },
9220
+ { name: "aspect-types", type: "string", description: "Comma-separated aspect names, or 'major' for conjunction,sextile,square,trine,opposition" },
9034
9221
  { name: "wasm-path", type: "string", description: "Override the Swiss Ephemeris WASM runtime path" },
9035
9222
  { name: "ephe-path", type: "string", description: "Override the ephemeris data directory path" }
9036
9223
  ],
@@ -9058,6 +9245,7 @@ var COMMANDS = [
9058
9245
  { name: "transit-timezone", type: "string", description: "Transit IANA timezone (default: natal timezone)" },
9059
9246
  { name: "max-orb", type: "number", description: "Maximum orb in degrees to include" },
9060
9247
  { name: "aspects", type: "string", description: "Comma-separated aspect names, or 'major' for conjunction,sextile,square,trine,opposition" },
9248
+ { name: "aspect-types", type: "string", description: "Alias for --aspects" },
9061
9249
  { name: "transit-planets", type: "string", description: "Comma-separated transit planet names to include" },
9062
9250
  { name: "natal-planets", type: "string", description: "Comma-separated natal planet/point names to include" },
9063
9251
  { name: "from", type: "string", description: "Range start date YYYY-MM-DD (enables date range mode)" },
@@ -9090,6 +9278,8 @@ var COMMANDS = [
9090
9278
  { name: "sr-lon", type: "number", description: "Solar return location longitude (default: natal lon)" },
9091
9279
  { name: "sr-location", type: "string", description: "Solar return location for geocoding" },
9092
9280
  { name: "sr-house-system", type: "string", description: "House system for solar return chart (default: natal house system)" },
9281
+ { name: "max-orb", type: "number", description: "Maximum orb in degrees to include in natal and solar return aspect arrays" },
9282
+ { name: "aspect-types", type: "string", description: "Comma-separated aspect names, or 'major' for conjunction,sextile,square,trine,opposition" },
9093
9283
  { name: "wasm-path", type: "string", description: "Override the Swiss Ephemeris WASM runtime path" },
9094
9284
  { name: "ephe-path", type: "string", description: "Override the ephemeris data directory path" }
9095
9285
  ],
@@ -10056,7 +10246,7 @@ function rethrowInterruptedOrError(err, executionContext) {
10056
10246
  throw err;
10057
10247
  }
10058
10248
  function describeTimeZoneSettings(timeZoneSettings) {
10059
- return "timeZone" in timeZoneSettings ? timeZoneSettings.timeZone : "auto";
10249
+ return "timeZone" in timeZoneSettings && timeZoneSettings.timeZone != null ? timeZoneSettings.timeZone : "auto";
10060
10250
  }
10061
10251
  async function geocodeLocation(location, flags, executionContext) {
10062
10252
  const apiKey = getGoogleMapsApiKey();
@@ -10157,6 +10347,46 @@ function formatInputEcho(chartAInput, chartBInput) {
10157
10347
  }
10158
10348
  };
10159
10349
  }
10350
+ var MAJOR_ASPECTS = ["conjunction", "sextile", "square", "trine", "opposition"];
10351
+ function parseMaxOrb(flags, inputPayload) {
10352
+ const maxOrb = inputPayload?.maxOrb != null ? Number(inputPayload.maxOrb) : getFlagNumber(flags, "max-orb");
10353
+ if (maxOrb == null) {
10354
+ return void 0;
10355
+ }
10356
+ if (Number.isNaN(maxOrb) || maxOrb < 0) {
10357
+ exitWithError("INVALID_ARGUMENT", `--max-orb must be a non-negative number, got "${maxOrb}".`, flags);
10358
+ }
10359
+ return maxOrb;
10360
+ }
10361
+ function parseAspectTypeFilter(flags, inputPayload) {
10362
+ const rawValue = inputPayload?.aspectTypes ?? inputPayload?.aspects ?? getFlagString(flags, "aspect-types") ?? getFlagString(flags, "aspects");
10363
+ if (!rawValue) {
10364
+ return void 0;
10365
+ }
10366
+ const items = Array.isArray(rawValue) ? rawValue : rawValue.split(",");
10367
+ const normalized = items.map((item) => item.trim().toLowerCase()).filter(Boolean).flatMap((item) => item === "major" ? MAJOR_ASPECTS : [item]);
10368
+ return normalized.length > 0 ? normalized : void 0;
10369
+ }
10370
+ function filterAspects(aspects, { maxOrb, aspectFilter }) {
10371
+ return aspects.filter((aspect) => {
10372
+ if (maxOrb != null) {
10373
+ const orb = aspect.orb ?? aspect.exactOrb;
10374
+ if (orb == null || orb > maxOrb) {
10375
+ return false;
10376
+ }
10377
+ }
10378
+ if (aspectFilter && !aspectFilter.includes(aspect.aspect)) {
10379
+ return false;
10380
+ }
10381
+ return true;
10382
+ });
10383
+ }
10384
+ function filterChartAspects(chart, options) {
10385
+ return {
10386
+ ...chart,
10387
+ aspects: filterAspects(chart.aspects, options)
10388
+ };
10389
+ }
10160
10390
  async function parseTwoChartCommand(flags, inputPayload, commandName, executionContext) {
10161
10391
  if (!inputPayload?.chartA || !inputPayload?.chartB) {
10162
10392
  exitWithError("MISSING_ARGUMENT", `Usage: kaabalah ${commandName} --input-json=- < payload.json`, flags);
@@ -10279,6 +10509,8 @@ async function cmdAstrologySynastry(flags, inputPayload, executionContext) {
10279
10509
  releaseSwissEphCleanup
10280
10510
  } = await parseTwoChartCommand(flags, inputPayload, "astrology:synastry", executionContext);
10281
10511
  const { getSynastryChart: getSynastryChart2, closeSwissEph: closeSwissEph2, HouseSystem: HouseSystem2 } = astroModule;
10512
+ const maxOrb = parseMaxOrb(flags, inputPayload);
10513
+ const aspectFilter = parseAspectTypeFilter(flags, inputPayload);
10282
10514
  try {
10283
10515
  debugLog("astrology", "Running astrology:synastry.", {
10284
10516
  chartA: { date: chartAInput.dateStr, time: chartAInput.timeStr },
@@ -10289,12 +10521,18 @@ async function cmdAstrologySynastry(flags, inputPayload, executionContext) {
10289
10521
  chartB: buildBirthChartOptions(chartBInput, HouseSystem2),
10290
10522
  aspectSpecs
10291
10523
  });
10524
+ const filteredResult = {
10525
+ ...result,
10526
+ chartA: filterChartAspects(result.chartA, { maxOrb, aspectFilter }),
10527
+ chartB: filterChartAspects(result.chartB, { maxOrb, aspectFilter }),
10528
+ aspects: filterAspects(result.aspects, { maxOrb, aspectFilter })
10529
+ };
10292
10530
  executionContext.throwIfInterrupted();
10293
10531
  debugLog("astrology", "Completed astrology:synastry.", {
10294
- aspects: result.aspects.length
10532
+ aspects: filteredResult.aspects.length
10295
10533
  });
10296
10534
  if (isJsonMode(flags)) {
10297
- outputJson({ ...result, input: formatInputEcho(chartAInput, chartBInput) }, flags);
10535
+ outputJson({ ...filteredResult, input: formatInputEcho(chartAInput, chartBInput) }, flags);
10298
10536
  return;
10299
10537
  }
10300
10538
  console.log(`
@@ -10303,9 +10541,9 @@ Synastry Chart
10303
10541
  console.log(` Chart A: ${chartAInput.dateStr} ${chartAInput.timeStr} (${chartAInput.latitude}, ${chartAInput.longitude})`);
10304
10542
  console.log(` Chart B: ${chartBInput.dateStr} ${chartBInput.timeStr} (${chartBInput.latitude}, ${chartBInput.longitude})`);
10305
10543
  console.log(`
10306
- Cross-chart Aspects (${result.aspects.length}):
10544
+ Cross-chart Aspects (${filteredResult.aspects.length}):
10307
10545
  `);
10308
- for (const aspect of result.aspects) {
10546
+ for (const aspect of filteredResult.aspects) {
10309
10547
  console.log(` ${aspect.planetA.padEnd(14)} ${aspect.aspect.padEnd(12)} ${aspect.planetB.padEnd(14)} orb ${aspect.orb.toFixed(2)}\xB0`);
10310
10548
  }
10311
10549
  console.log();
@@ -10325,6 +10563,8 @@ async function cmdAstrologyComposite(flags, inputPayload, executionContext) {
10325
10563
  releaseSwissEphCleanup
10326
10564
  } = await parseTwoChartCommand(flags, inputPayload, "astrology:composite", executionContext);
10327
10565
  const { getCompositeChart: getCompositeChart2, closeSwissEph: closeSwissEph2, HouseSystem: HouseSystem2 } = astroModule;
10566
+ const maxOrb = parseMaxOrb(flags, inputPayload);
10567
+ const aspectFilter = parseAspectTypeFilter(flags, inputPayload);
10328
10568
  try {
10329
10569
  debugLog("astrology", "Running astrology:composite.", {
10330
10570
  chartA: { date: chartAInput.dateStr, time: chartAInput.timeStr },
@@ -10335,13 +10575,19 @@ async function cmdAstrologyComposite(flags, inputPayload, executionContext) {
10335
10575
  chartB: buildBirthChartOptions(chartBInput, HouseSystem2),
10336
10576
  aspectSpecs
10337
10577
  });
10578
+ const filteredResult = {
10579
+ ...result,
10580
+ chartA: filterChartAspects(result.chartA, { maxOrb, aspectFilter }),
10581
+ chartB: filterChartAspects(result.chartB, { maxOrb, aspectFilter }),
10582
+ aspects: filterAspects(result.aspects, { maxOrb, aspectFilter })
10583
+ };
10338
10584
  executionContext.throwIfInterrupted();
10339
10585
  debugLog("astrology", "Completed astrology:composite.", {
10340
- aspects: result.aspects.length,
10341
- compositePlanets: Object.keys(result.compositePlanets).length
10586
+ aspects: filteredResult.aspects.length,
10587
+ compositePlanets: Object.keys(filteredResult.compositePlanets).length
10342
10588
  });
10343
10589
  if (isJsonMode(flags)) {
10344
- outputJson({ ...result, input: formatInputEcho(chartAInput, chartBInput) }, flags);
10590
+ outputJson({ ...filteredResult, input: formatInputEcho(chartAInput, chartBInput) }, flags);
10345
10591
  return;
10346
10592
  }
10347
10593
  console.log(`
@@ -10351,20 +10597,20 @@ Composite Chart (Midpoint Method)
10351
10597
  console.log(` Chart B: ${chartBInput.dateStr} ${chartBInput.timeStr} (${chartBInput.latitude}, ${chartBInput.longitude})`);
10352
10598
  console.log(`
10353
10599
  Composite Planets:`);
10354
- for (const [name, planet] of Object.entries(result.compositePlanets)) {
10600
+ for (const [name, planet] of Object.entries(filteredResult.compositePlanets)) {
10355
10601
  const zodiacPosition = planet.zodiacPosition;
10356
10602
  console.log(` ${name.padEnd(14)} ${zodiacPosition.sign.padEnd(12)} ${zodiacPosition.traditionalFormat.padEnd(8)} House ${zodiacPosition.house}`);
10357
10603
  }
10358
10604
  console.log(`
10359
10605
  Composite House Cusps:`);
10360
- for (let i = 0; i < result.compositeHouses.length; i++) {
10361
- const house = result.compositeHouses[i];
10606
+ for (let i = 0; i < filteredResult.compositeHouses.length; i++) {
10607
+ const house = filteredResult.compositeHouses[i];
10362
10608
  console.log(` House ${String(i + 1).padStart(2)}: ${house.sign.padEnd(12)} ${house.traditionalFormat}`);
10363
10609
  }
10364
10610
  console.log(`
10365
- Composite Aspects (${result.aspects.length}):
10611
+ Composite Aspects (${filteredResult.aspects.length}):
10366
10612
  `);
10367
- for (const aspect of result.aspects) {
10613
+ for (const aspect of filteredResult.aspects) {
10368
10614
  console.log(` ${aspect.planetA.padEnd(14)} ${aspect.aspect.padEnd(12)} ${aspect.planetB.padEnd(14)} orb ${aspect.orb.toFixed(2)}\xB0`);
10369
10615
  }
10370
10616
  console.log();
@@ -10375,7 +10621,6 @@ Composite Chart (Midpoint Method)
10375
10621
  closeSwissEph2();
10376
10622
  }
10377
10623
  }
10378
- var MAJOR_ASPECTS = ["conjunction", "sextile", "square", "trine", "opposition"];
10379
10624
  async function cmdAstrologyTransits(args, flags, inputPayload, executionContext) {
10380
10625
  const natalPayload = inputPayload?.natal;
10381
10626
  const effectiveArgs = natalPayload ? [] : args;
@@ -10401,8 +10646,8 @@ async function cmdAstrologyTransits(args, flags, inputPayload, executionContext)
10401
10646
  const transitLatFlag = inputPayload?.transitLat != null ? Number(inputPayload.transitLat) : getFlagNumber(flags, "transit-lat");
10402
10647
  const transitLonFlag = inputPayload?.transitLon != null ? Number(inputPayload.transitLon) : getFlagNumber(flags, "transit-lon");
10403
10648
  const transitTzStr = inputPayload?.transitTimezone ?? getFlagString(flags, "transit-timezone");
10404
- const maxOrbFlag = inputPayload?.maxOrb != null ? Number(inputPayload.maxOrb) : getFlagNumber(flags, "max-orb");
10405
- const aspectsStr = inputPayload?.aspects ?? getFlagString(flags, "aspects");
10649
+ const maxOrbFlag = parseMaxOrb(flags, inputPayload);
10650
+ const aspectFilter = parseAspectTypeFilter(flags, inputPayload);
10406
10651
  const transitPlanetsStr = inputPayload?.transitPlanets ?? getFlagString(flags, "transit-planets");
10407
10652
  const natalPlanetsStr = inputPayload?.natalPlanets ?? getFlagString(flags, "natal-planets");
10408
10653
  const fromStr = inputPayload?.from ?? getFlagString(flags, "from");
@@ -10411,11 +10656,6 @@ async function cmdAstrologyTransits(args, flags, inputPayload, executionContext)
10411
10656
  if (stepDaysFlag != null && (isNaN(stepDaysFlag) || stepDaysFlag <= 0)) {
10412
10657
  exitWithError("INVALID_ARGUMENT", `--step-days must be a positive number, got "${stepDaysFlag}".`, flags);
10413
10658
  }
10414
- let aspectFilter;
10415
- if (aspectsStr) {
10416
- const raw = Array.isArray(aspectsStr) ? aspectsStr : aspectsStr.split(",").map((s) => s.trim());
10417
- aspectFilter = raw.flatMap((a) => a === "major" ? MAJOR_ASPECTS : [a]);
10418
- }
10419
10659
  const transitPlanets = transitPlanetsStr ? Array.isArray(transitPlanetsStr) ? transitPlanetsStr : transitPlanetsStr.split(",").map((s) => s.trim().toLowerCase()) : void 0;
10420
10660
  const natalPlanets = natalPlanetsStr ? Array.isArray(natalPlanetsStr) ? natalPlanetsStr : natalPlanetsStr.split(",").map((s) => s.trim().toLowerCase()) : void 0;
10421
10661
  const natalOpts = buildBirthChartOptions(natalInput, HouseSystem2);
@@ -10562,6 +10802,8 @@ async function cmdAstrologySolarReturn(args, flags, inputPayload, executionConte
10562
10802
  const natalInput = await parseSingleChartRequest(effectiveArgs, flags, effectiveInputPayload, executionContext);
10563
10803
  const astroModule = await Promise.resolve().then(() => (init_astrology(), astrology_exports));
10564
10804
  const { getSolarReturnChart: getSolarReturnChart2, closeSwissEph: closeSwissEph2, HouseSystem: HouseSystem2 } = astroModule;
10805
+ const maxOrb = parseMaxOrb(flags, inputPayload);
10806
+ const aspectFilter = parseAspectTypeFilter(flags, inputPayload);
10565
10807
  const releaseSwissEphCleanup = executionContext.registerCleanup(() => {
10566
10808
  astroModule.closeSwissEph();
10567
10809
  });
@@ -10604,14 +10846,19 @@ async function cmdAstrologySolarReturn(args, flags, inputPayload, executionConte
10604
10846
  solarReturnLongitude: srLon ?? void 0,
10605
10847
  solarReturnHouseSystem: srHouseSystem
10606
10848
  });
10849
+ const filteredResult = {
10850
+ ...result,
10851
+ natalChart: filterChartAspects(result.natalChart, { maxOrb, aspectFilter }),
10852
+ solarReturnChart: filterChartAspects(result.solarReturnChart, { maxOrb, aspectFilter })
10853
+ };
10607
10854
  executionContext.throwIfInterrupted();
10608
10855
  debugLog("astrology", "Completed astrology:solar-return.", {
10609
- exactReturnDate: result.exactReturnDate.toISOString(),
10610
- natalSunLongitude: result.natalSunLongitude
10856
+ exactReturnDate: filteredResult.exactReturnDate.toISOString(),
10857
+ natalSunLongitude: filteredResult.natalSunLongitude
10611
10858
  });
10612
10859
  if (isJsonMode(flags)) {
10613
10860
  outputJson({
10614
- ...result,
10861
+ ...filteredResult,
10615
10862
  input: {
10616
10863
  natal: { date: natalInput.dateStr, time: natalInput.timeStr, lat: natalInput.latitude, lon: natalInput.longitude },
10617
10864
  year,
@@ -10621,14 +10868,14 @@ async function cmdAstrologySolarReturn(args, flags, inputPayload, executionConte
10621
10868
  }, flags);
10622
10869
  return;
10623
10870
  }
10624
- const srChart = result.solarReturnChart;
10625
- const natalSun = result.natalChart.planets.sun.zodiacPosition;
10626
- const returnDateStr = result.exactReturnDate.toISOString().replace("T", " ").replace(/\.\d{3}Z$/, " UTC");
10871
+ const srChart = filteredResult.solarReturnChart;
10872
+ const natalSun = filteredResult.natalChart.planets.sun.zodiacPosition;
10873
+ const returnDateStr = filteredResult.exactReturnDate.toISOString().replace("T", " ").replace(/\.\d{3}Z$/, " UTC");
10627
10874
  console.log(`
10628
10875
  Solar Return ${year}
10629
10876
  `);
10630
10877
  console.log(` Natal: ${natalInput.dateStr} ${natalInput.timeStr} (${natalInput.latitude}, ${natalInput.longitude})`);
10631
- console.log(` Natal Sun: ${natalSun.sign} ${natalSun.traditionalFormat} (${result.natalSunLongitude.toFixed(4)}\xB0)`);
10878
+ console.log(` Natal Sun: ${natalSun.sign} ${natalSun.traditionalFormat} (${filteredResult.natalSunLongitude.toFixed(4)}\xB0)`);
10632
10879
  console.log(` Exact Return: ${returnDateStr}`);
10633
10880
  console.log(` SR Sun: ${srChart.planets.sun.zodiacPosition.sign} ${srChart.planets.sun.zodiacPosition.traditionalFormat} (${srChart.planets.sun.longitude.toFixed(4)}\xB0)`);
10634
10881
  console.log(`
@@ -10914,6 +11161,8 @@ async function cmdAstrology(args, flags, inputPayload, executionContext) {
10914
11161
  const input = await parseSingleChartRequest(args, flags, inputPayload, executionContext);
10915
11162
  const astroModule = await Promise.resolve().then(() => (init_astrology(), astrology_exports));
10916
11163
  const { getSwissEph: getSwissEph2, closeSwissEph: closeSwissEph2, getBirthChart: getBirthChart2, HouseSystem: HouseSystem2 } = astroModule;
11164
+ const maxOrb = parseMaxOrb(flags, inputPayload);
11165
+ const aspectFilter = parseAspectTypeFilter(flags, inputPayload);
10917
11166
  const releaseSwissEphCleanup = executionContext.registerCleanup(() => {
10918
11167
  astroModule.closeSwissEph();
10919
11168
  });
@@ -10942,14 +11191,15 @@ async function cmdAstrology(args, flags, inputPayload, executionContext) {
10942
11191
  houseSystem: input.houseSystemCode,
10943
11192
  timeZoneSettings: input.timeZoneSettings
10944
11193
  });
11194
+ const filteredChart = filterChartAspects(chart, { maxOrb, aspectFilter });
10945
11195
  executionContext.throwIfInterrupted();
10946
11196
  debugLog("astrology", "Completed astrology.", {
10947
- planets: Object.keys(chart.planets).length,
10948
- nodes: Object.keys(chart.nodes ?? {}).length,
10949
- aspects: chart.aspects.length
11197
+ planets: Object.keys(filteredChart.planets).length,
11198
+ nodes: Object.keys(filteredChart.nodes ?? {}).length,
11199
+ aspects: filteredChart.aspects.length
10950
11200
  });
10951
11201
  if (isJsonMode(flags)) {
10952
- const result = { ...chart };
11202
+ const result = { ...filteredChart };
10953
11203
  if (input.resolvedLocation) {
10954
11204
  result.resolvedLocation = input.resolvedLocation;
10955
11205
  }
@@ -10972,29 +11222,29 @@ Birth Chart: ${input.dateStr} ${input.timeStr}
10972
11222
  }
10973
11223
  console.log(` Coordinates: ${input.latitude.toFixed(4)}, ${input.longitude.toFixed(4)}`);
10974
11224
  console.log(` House System: ${input.houseSystem}`);
10975
- console.log(` UTC Date: ${chart.dateUtc.toISOString()}`);
11225
+ console.log(` UTC Date: ${filteredChart.dateUtc.toISOString()}`);
10976
11226
  console.log(`
10977
11227
  Planets:`);
10978
- for (const [name, planet] of Object.entries(chart.planets)) {
11228
+ for (const [name, planet] of Object.entries(filteredChart.planets)) {
10979
11229
  const zodiacPosition = planet.zodiacPosition;
10980
11230
  console.log(` ${name.padEnd(14)} ${zodiacPosition.sign.padEnd(12)} ${zodiacPosition.traditionalFormat.padEnd(8)} House ${zodiacPosition.house}`);
10981
11231
  }
10982
11232
  console.log(`
10983
11233
  Houses:`);
10984
- console.log(` Ascendant: ${chart.houses.ascendant.sign} ${chart.houses.ascendant.traditionalFormat}`);
10985
- console.log(` Midheaven: ${chart.houses.mc.sign} ${chart.houses.mc.traditionalFormat}`);
10986
- console.log(` Descendant: ${chart.houses.dc.sign} ${chart.houses.dc.traditionalFormat}`);
10987
- console.log(` IC: ${chart.houses.ic.sign} ${chart.houses.ic.traditionalFormat}`);
11234
+ console.log(` Ascendant: ${filteredChart.houses.ascendant.sign} ${filteredChart.houses.ascendant.traditionalFormat}`);
11235
+ console.log(` Midheaven: ${filteredChart.houses.mc.sign} ${filteredChart.houses.mc.traditionalFormat}`);
11236
+ console.log(` Descendant: ${filteredChart.houses.dc.sign} ${filteredChart.houses.dc.traditionalFormat}`);
11237
+ console.log(` IC: ${filteredChart.houses.ic.sign} ${filteredChart.houses.ic.traditionalFormat}`);
10988
11238
  console.log(`
10989
11239
  House Cusps:`);
10990
- for (let i = 0; i < chart.houses.houses.length; i++) {
10991
- const house = chart.houses.houses[i];
11240
+ for (let i = 0; i < filteredChart.houses.houses.length; i++) {
11241
+ const house = filteredChart.houses.houses[i];
10992
11242
  console.log(` House ${String(i + 1).padStart(2)}: ${house.sign.padEnd(12)} ${house.traditionalFormat}`);
10993
11243
  }
10994
- if (chart.nodes && Object.keys(chart.nodes).length > 0) {
11244
+ if (filteredChart.nodes && Object.keys(filteredChart.nodes).length > 0) {
10995
11245
  console.log(`
10996
11246
  Nodes:`);
10997
- for (const [, node] of Object.entries(chart.nodes)) {
11247
+ for (const [, node] of Object.entries(filteredChart.nodes)) {
10998
11248
  console.log(` ${node.name.padEnd(18)} ${node.sign.padEnd(12)} ${node.traditionalFormat.padEnd(8)} House ${node.house}`);
10999
11249
  }
11000
11250
  }
@@ -13273,6 +13523,11 @@ var COLORS_DATA = {
13273
13523
  }
13274
13524
  };
13275
13525
 
13526
+ // src/core/correspondence-model.ts
13527
+ function makeCorrespondenceId(left, right) {
13528
+ return [left, right].sort().join("<->");
13529
+ }
13530
+
13276
13531
  // src/core/systems/hermetic-qabalah.ts
13277
13532
  var hermetic_qabalah_exports = {};
13278
13533
  __export(hermetic_qabalah_exports, {
@@ -17619,7 +17874,13 @@ var ModuleManager = class {
17619
17874
  if (!loadedSystem) {
17620
17875
  throw new Error(`System ${systemKey} not found`);
17621
17876
  }
17622
- loadedSystem.LOADERS.base(this.t);
17877
+ this.t.runWithMutationSource(
17878
+ {
17879
+ kind: "system",
17880
+ system: systemKey
17881
+ },
17882
+ () => loadedSystem.LOADERS.base(this.t)
17883
+ );
17623
17884
  this.activeSystem = systemKey;
17624
17885
  this.loadedParts.clear();
17625
17886
  this.loadedParts.add("base");
@@ -17639,13 +17900,28 @@ var ModuleManager = class {
17639
17900
  if (this.loadedParts.has(partKey)) {
17640
17901
  return;
17641
17902
  }
17642
- system.LOADERS[partKey](this.t);
17903
+ this.t.runWithMutationSource(
17904
+ {
17905
+ kind: "part",
17906
+ system: this.activeSystem,
17907
+ part: partKey
17908
+ },
17909
+ () => system.LOADERS[partKey](this.t)
17910
+ );
17643
17911
  this.loadedParts.add(partKey);
17644
17912
  const possiblePartBridges = system.BRIDGES.filter(
17645
17913
  (b) => b.needs.includes(partKey) && !this.bridgedParts.has(b.id) && b.needs.every((n) => this.loadedParts.has(n))
17646
17914
  );
17647
17915
  for (const bridge of possiblePartBridges) {
17648
- bridge.run(this.t);
17916
+ this.t.runWithMutationSource(
17917
+ {
17918
+ kind: "bridge",
17919
+ system: this.activeSystem,
17920
+ bridgeId: bridge.id,
17921
+ parts: [...bridge.needs]
17922
+ },
17923
+ () => bridge.run(this.t)
17924
+ );
17649
17925
  this.bridgedParts.add(bridge.id);
17650
17926
  }
17651
17927
  }
@@ -17682,7 +17958,15 @@ var ModuleManager = class {
17682
17958
  throw new Error(`Bridge ${bridgeKey} not found`);
17683
17959
  }
17684
17960
  if (!this.bridgedParts.has(bridge.id) && bridge.needs.every((n) => this.loadedParts.has(n))) {
17685
- bridge.run(this.t);
17961
+ this.t.runWithMutationSource(
17962
+ {
17963
+ kind: "bridge",
17964
+ system: this.activeSystem,
17965
+ bridgeId: bridge.id,
17966
+ parts: [...bridge.needs]
17967
+ },
17968
+ () => bridge.run(this.t)
17969
+ );
17686
17970
  this.bridgedParts.add(bridge.id);
17687
17971
  }
17688
17972
  }
@@ -17718,12 +18002,60 @@ var ModuleManager = class {
17718
18002
  };
17719
18003
 
17720
18004
  // src/core/tree-of-life.ts
18005
+ function mergeCorrespondenceMetadata(current, next) {
18006
+ if (!current) {
18007
+ return next ? { ...next } : void 0;
18008
+ }
18009
+ if (!next) {
18010
+ return { ...current };
18011
+ }
18012
+ return {
18013
+ ...current,
18014
+ ...next,
18015
+ tags: [.../* @__PURE__ */ new Set([...current.tags ?? [], ...next.tags ?? []])],
18016
+ attributes: {
18017
+ ...current.attributes ?? {},
18018
+ ...next.attributes ?? {}
18019
+ }
18020
+ };
18021
+ }
18022
+ function mergeCorrespondenceSources(current, next) {
18023
+ const seen = /* @__PURE__ */ new Set();
18024
+ const merged = [];
18025
+ for (const source of [...current, next]) {
18026
+ const key = JSON.stringify(source);
18027
+ if (seen.has(key)) {
18028
+ continue;
18029
+ }
18030
+ seen.add(key);
18031
+ merged.push({
18032
+ ...source,
18033
+ ...source.kind === "bridge" ? { parts: [...source.parts] } : {}
18034
+ });
18035
+ }
18036
+ return merged;
18037
+ }
17721
18038
  var TreeOfLife = class {
17722
18039
  constructor() {
17723
18040
  this.nodes = /* @__PURE__ */ new Map();
17724
18041
  this.adjacent = /* @__PURE__ */ new Map();
18042
+ this.edges = /* @__PURE__ */ new Map();
18043
+ this.mutationSources = [{ kind: "manual" }];
17725
18044
  this.modules = new ModuleManager(this);
17726
18045
  }
18046
+ getCurrentMutationSource() {
18047
+ return this.mutationSources[this.mutationSources.length - 1] ?? {
18048
+ kind: "manual"
18049
+ };
18050
+ }
18051
+ runWithMutationSource(source, fn) {
18052
+ this.mutationSources.push(source);
18053
+ try {
18054
+ return fn();
18055
+ } finally {
18056
+ this.mutationSources.pop();
18057
+ }
18058
+ }
17727
18059
  /**
17728
18060
  * Loads the tree of life system to be used
17729
18061
  * @param systemKey - the key of the system to load
@@ -17785,28 +18117,57 @@ var TreeOfLife = class {
17785
18117
  getNodes() {
17786
18118
  return [...this.nodes.values()];
17787
18119
  }
18120
+ getEdge(left, right) {
18121
+ return this.edges.get(makeCorrespondenceId(left, right));
18122
+ }
18123
+ getEdges(nodeId) {
18124
+ if (!nodeId) {
18125
+ return [...this.edges.values()];
18126
+ }
18127
+ return [...this.adjacent.get(nodeId) ?? []].map((relatedNodeId) => this.getEdge(nodeId, relatedNodeId)).filter((edge) => Boolean(edge));
18128
+ }
17788
18129
  /**
17789
18130
  * Links two nodes bi-directionally
17790
18131
  * @param firstNode - the id of the first node
17791
18132
  * @param secondNode - the id of the second node
17792
18133
  */
17793
- link(firstNode, secondNode) {
18134
+ link(firstNode, secondNode, options = {}) {
17794
18135
  if (!this.nodes.has(firstNode) || !this.nodes.has(secondNode)) {
17795
18136
  throw new Error("unknown node id");
17796
18137
  }
17797
18138
  if (firstNode === secondNode) {
17798
18139
  return;
17799
18140
  }
17800
- if (this.adjacent.has(firstNode) && this.adjacent.get(firstNode)?.has(secondNode)) {
17801
- return;
17802
- }
18141
+ const edgeId = makeCorrespondenceId(firstNode, secondNode);
18142
+ const source = options.source ?? this.getCurrentMutationSource();
18143
+ const existingEdge = this.edges.get(edgeId);
17803
18144
  const put = (leftNode, rightNode) => {
17804
18145
  const set = this.adjacent.get(leftNode) ?? /* @__PURE__ */ new Set();
17805
18146
  set.add(rightNode);
17806
18147
  this.adjacent.set(leftNode, set);
17807
18148
  };
18149
+ if (existingEdge) {
18150
+ this.edges.set(edgeId, {
18151
+ ...existingEdge,
18152
+ metadata: mergeCorrespondenceMetadata(
18153
+ existingEdge.metadata,
18154
+ options.metadata
18155
+ ),
18156
+ sources: mergeCorrespondenceSources(existingEdge.sources, source)
18157
+ });
18158
+ put(firstNode, secondNode);
18159
+ put(secondNode, firstNode);
18160
+ return;
18161
+ }
17808
18162
  put(firstNode, secondNode);
17809
18163
  put(secondNode, firstNode);
18164
+ this.edges.set(edgeId, {
18165
+ id: edgeId,
18166
+ left: firstNode,
18167
+ right: secondNode,
18168
+ metadata: mergeCorrespondenceMetadata(void 0, options.metadata),
18169
+ sources: mergeCorrespondenceSources([], source)
18170
+ });
17810
18171
  }
17811
18172
  /**
17812
18173
  * Gets the current node and all its direct relations, or, when filtered by node type, only the direct relations of that type.
@@ -17891,6 +18252,7 @@ var TreeOfLife = class {
17891
18252
  const neighbors = this.adjacent.get(id2);
17892
18253
  if (neighbors) {
17893
18254
  for (const neighbor of neighbors) {
18255
+ this.edges.delete(makeCorrespondenceId(id2, neighbor));
17894
18256
  const set = this.adjacent.get(neighbor);
17895
18257
  if (!set) {
17896
18258
  continue;
@@ -19908,7 +20270,551 @@ Fibonacci Cycle: ${dateStr} (age ${result.currentAge})
19908
20270
  console.log();
19909
20271
  }
19910
20272
 
20273
+ // src/core/workspace.ts
20274
+ function cloneNode(node) {
20275
+ return Object.freeze({
20276
+ id: node.id,
20277
+ type: node.type,
20278
+ name: node.name,
20279
+ data: node.data && typeof node.data === "object" ? { ...node.data } : node.data
20280
+ });
20281
+ }
20282
+ function cloneMetadata(metadata) {
20283
+ if (!metadata) {
20284
+ return void 0;
20285
+ }
20286
+ return {
20287
+ ...metadata,
20288
+ tags: metadata.tags ? [...metadata.tags] : void 0,
20289
+ attributes: metadata.attributes ? { ...metadata.attributes } : void 0
20290
+ };
20291
+ }
20292
+ function cloneSource(source) {
20293
+ if (source.kind === "bridge") {
20294
+ return {
20295
+ ...source,
20296
+ parts: [...source.parts]
20297
+ };
20298
+ }
20299
+ return { ...source };
20300
+ }
20301
+ function cloneEdge(edge) {
20302
+ return Object.freeze({
20303
+ ...edge,
20304
+ metadata: cloneMetadata(edge.metadata),
20305
+ sources: edge.sources.map(cloneSource)
20306
+ });
20307
+ }
20308
+ function cloneNote(note) {
20309
+ return Object.freeze({
20310
+ ...note,
20311
+ target: { ...note.target },
20312
+ metadata: note.metadata ? { ...note.metadata } : void 0
20313
+ });
20314
+ }
20315
+ function mergeMetadata(current, next) {
20316
+ if (!current) {
20317
+ return cloneMetadata(next);
20318
+ }
20319
+ if (!next) {
20320
+ return cloneMetadata(current);
20321
+ }
20322
+ return {
20323
+ ...current,
20324
+ ...next,
20325
+ tags: [.../* @__PURE__ */ new Set([...current.tags ?? [], ...next.tags ?? []])],
20326
+ attributes: {
20327
+ ...current.attributes ?? {},
20328
+ ...next.attributes ?? {}
20329
+ }
20330
+ };
20331
+ }
20332
+ function mergeSources(current, next) {
20333
+ const seen = /* @__PURE__ */ new Set();
20334
+ const merged = [];
20335
+ for (const source of [...current, next]) {
20336
+ const key = JSON.stringify(source);
20337
+ if (seen.has(key)) {
20338
+ continue;
20339
+ }
20340
+ seen.add(key);
20341
+ merged.push(cloneSource(source));
20342
+ }
20343
+ return merged;
20344
+ }
20345
+ function normalizeTypes(type) {
20346
+ if (!type) {
20347
+ return void 0;
20348
+ }
20349
+ return new Set(Array.isArray(type) ? type : [type]);
20350
+ }
20351
+ function sortNodes(nodes) {
20352
+ return [...nodes].sort((left, right) => {
20353
+ if (left.type !== right.type) {
20354
+ return left.type.localeCompare(right.type);
20355
+ }
20356
+ const leftLabel = String(left.name ?? left.id);
20357
+ const rightLabel = String(right.name ?? right.id);
20358
+ return leftLabel.localeCompare(rightLabel);
20359
+ });
20360
+ }
20361
+ function sortMatches(matches) {
20362
+ return [...matches].sort((left, right) => {
20363
+ if (left.distance !== right.distance) {
20364
+ return left.distance - right.distance;
20365
+ }
20366
+ if (left.node.type !== right.node.type) {
20367
+ return left.node.type.localeCompare(right.node.type);
20368
+ }
20369
+ const leftLabel = String(left.node.name ?? left.node.id);
20370
+ const rightLabel = String(right.node.name ?? right.node.id);
20371
+ return leftLabel.localeCompare(rightLabel);
20372
+ });
20373
+ }
20374
+ function createGraphData(descriptor, nodes, edges, notes) {
20375
+ const nodesById = /* @__PURE__ */ new Map();
20376
+ const nodeIdsByType = /* @__PURE__ */ new Map();
20377
+ const edgesById = /* @__PURE__ */ new Map();
20378
+ const edgeIdsByNodeId = /* @__PURE__ */ new Map();
20379
+ const notesById = /* @__PURE__ */ new Map();
20380
+ const noteIdsByNodeId = /* @__PURE__ */ new Map();
20381
+ const noteIdsByCorrespondenceId = /* @__PURE__ */ new Map();
20382
+ for (const node of nodes) {
20383
+ const clonedNode = cloneNode(node);
20384
+ nodesById.set(clonedNode.id, clonedNode);
20385
+ const typedIds = nodeIdsByType.get(clonedNode.type) ?? [];
20386
+ typedIds.push(clonedNode.id);
20387
+ nodeIdsByType.set(clonedNode.type, typedIds);
20388
+ }
20389
+ for (const edge of edges) {
20390
+ const clonedEdge = cloneEdge(edge);
20391
+ edgesById.set(clonedEdge.id, clonedEdge);
20392
+ const leftEdges = edgeIdsByNodeId.get(clonedEdge.left) ?? [];
20393
+ leftEdges.push(clonedEdge.id);
20394
+ edgeIdsByNodeId.set(clonedEdge.left, leftEdges);
20395
+ const rightEdges = edgeIdsByNodeId.get(clonedEdge.right) ?? [];
20396
+ rightEdges.push(clonedEdge.id);
20397
+ edgeIdsByNodeId.set(clonedEdge.right, rightEdges);
20398
+ }
20399
+ for (const note of notes) {
20400
+ const clonedNote = cloneNote(note);
20401
+ notesById.set(clonedNote.id, clonedNote);
20402
+ if (clonedNote.target.kind === "node") {
20403
+ const nodeNoteIds = noteIdsByNodeId.get(clonedNote.target.nodeId) ?? [];
20404
+ nodeNoteIds.push(clonedNote.id);
20405
+ noteIdsByNodeId.set(clonedNote.target.nodeId, nodeNoteIds);
20406
+ continue;
20407
+ }
20408
+ const edgeId = makeCorrespondenceId(
20409
+ clonedNote.target.left,
20410
+ clonedNote.target.right
20411
+ );
20412
+ const correspondenceNoteIds = noteIdsByCorrespondenceId.get(edgeId) ?? [];
20413
+ correspondenceNoteIds.push(clonedNote.id);
20414
+ noteIdsByCorrespondenceId.set(edgeId, correspondenceNoteIds);
20415
+ }
20416
+ for (const ids of nodeIdsByType.values()) {
20417
+ ids.sort((left, right) => String(left).localeCompare(String(right)));
20418
+ }
20419
+ for (const ids of edgeIdsByNodeId.values()) {
20420
+ ids.sort((left, right) => left.localeCompare(right));
20421
+ }
20422
+ for (const ids of noteIdsByNodeId.values()) {
20423
+ ids.sort((left, right) => left.localeCompare(right));
20424
+ }
20425
+ for (const ids of noteIdsByCorrespondenceId.values()) {
20426
+ ids.sort((left, right) => left.localeCompare(right));
20427
+ }
20428
+ return {
20429
+ descriptor: Object.freeze({ ...descriptor }),
20430
+ nodesById,
20431
+ nodeIdsByType,
20432
+ edgesById,
20433
+ edgeIdsByNodeId,
20434
+ notesById,
20435
+ noteIdsByNodeId,
20436
+ noteIdsByCorrespondenceId
20437
+ };
20438
+ }
20439
+ function normalizeBase(base) {
20440
+ if (!base) {
20441
+ return {
20442
+ descriptor: {},
20443
+ nodes: [],
20444
+ edges: [],
20445
+ notes: []
20446
+ };
20447
+ }
20448
+ if (base instanceof TreeWorkspace) {
20449
+ return {
20450
+ descriptor: base.descriptor,
20451
+ nodes: base.getNodes(),
20452
+ edges: base.getEdges(),
20453
+ notes: base.getNotes()
20454
+ };
20455
+ }
20456
+ return {
20457
+ descriptor: {
20458
+ system: base.activeSystem ?? void 0,
20459
+ parts: base.loadedParts.filter((part) => part !== "base")
20460
+ },
20461
+ nodes: base.getNodes(),
20462
+ edges: base.getEdges(),
20463
+ notes: []
20464
+ };
20465
+ }
20466
+ function applyOverlays(base, overlays) {
20467
+ const nodesById = /* @__PURE__ */ new Map();
20468
+ const edgesById = /* @__PURE__ */ new Map();
20469
+ const notes = [];
20470
+ for (const node of base.nodes) {
20471
+ nodesById.set(node.id, cloneNode(node));
20472
+ }
20473
+ for (const edge of base.edges) {
20474
+ edgesById.set(edge.id, cloneEdge(edge));
20475
+ }
20476
+ for (const note of base.notes) {
20477
+ notes.push(cloneNote(note));
20478
+ }
20479
+ for (const overlay of overlays) {
20480
+ for (const node of overlay.nodes ?? []) {
20481
+ const existing = nodesById.get(node.id);
20482
+ if (existing && existing.type !== node.type) {
20483
+ throw new Error(
20484
+ `Overlay ${overlay.id} tried to upsert ${node.id} with a different type`
20485
+ );
20486
+ }
20487
+ nodesById.set(
20488
+ node.id,
20489
+ cloneNode(
20490
+ existing ? {
20491
+ ...existing,
20492
+ ...node,
20493
+ data: {
20494
+ ...existing.data ?? {},
20495
+ ...node.data ?? {}
20496
+ }
20497
+ } : node
20498
+ )
20499
+ );
20500
+ }
20501
+ for (const correspondence of overlay.correspondences ?? []) {
20502
+ if (!nodesById.has(correspondence.left) || !nodesById.has(correspondence.right)) {
20503
+ throw new Error(
20504
+ `Overlay ${overlay.id} references unknown nodes in ${correspondence.left} <-> ${correspondence.right}`
20505
+ );
20506
+ }
20507
+ const edgeId = makeCorrespondenceId(
20508
+ correspondence.left,
20509
+ correspondence.right
20510
+ );
20511
+ if (correspondence.op === "remove") {
20512
+ edgesById.delete(edgeId);
20513
+ continue;
20514
+ }
20515
+ const existingEdge = edgesById.get(edgeId);
20516
+ const overlaySource = {
20517
+ kind: "overlay",
20518
+ overlayId: overlay.id,
20519
+ label: overlay.name
20520
+ };
20521
+ if (!existingEdge) {
20522
+ if (correspondence.op !== "add") {
20523
+ throw new Error(
20524
+ `Overlay ${overlay.id} cannot annotate missing correspondence ${edgeId}`
20525
+ );
20526
+ }
20527
+ edgesById.set(
20528
+ edgeId,
20529
+ cloneEdge({
20530
+ id: edgeId,
20531
+ left: correspondence.left,
20532
+ right: correspondence.right,
20533
+ metadata: cloneMetadata(correspondence.metadata),
20534
+ sources: [overlaySource]
20535
+ })
20536
+ );
20537
+ continue;
20538
+ }
20539
+ edgesById.set(
20540
+ edgeId,
20541
+ cloneEdge({
20542
+ ...existingEdge,
20543
+ metadata: mergeMetadata(existingEdge.metadata, correspondence.metadata),
20544
+ sources: mergeSources(existingEdge.sources, overlaySource)
20545
+ })
20546
+ );
20547
+ }
20548
+ for (const note of overlay.notes ?? []) {
20549
+ notes.push(
20550
+ cloneNote({
20551
+ ...note,
20552
+ metadata: note.metadata ? { ...note.metadata } : void 0
20553
+ })
20554
+ );
20555
+ }
20556
+ }
20557
+ const filteredNotes = notes.filter((note) => {
20558
+ if (note.target.kind === "node") {
20559
+ return nodesById.has(note.target.nodeId);
20560
+ }
20561
+ return edgesById.has(
20562
+ makeCorrespondenceId(note.target.left, note.target.right)
20563
+ );
20564
+ });
20565
+ return {
20566
+ nodes: [...nodesById.values()],
20567
+ edges: [...edgesById.values()],
20568
+ notes: filteredNotes
20569
+ };
20570
+ }
20571
+ function reconstructPath(startId, targetId, previous, edgesById) {
20572
+ const steps = [];
20573
+ let current = targetId;
20574
+ while (current !== startId) {
20575
+ const link = previous.get(current);
20576
+ if (!link) {
20577
+ break;
20578
+ }
20579
+ const edge = edgesById.get(link.edgeId);
20580
+ if (!edge) {
20581
+ break;
20582
+ }
20583
+ steps.push({
20584
+ from: link.from,
20585
+ to: current,
20586
+ edge
20587
+ });
20588
+ current = link.from;
20589
+ }
20590
+ return steps.reverse();
20591
+ }
20592
+ function buildCanonicalDescriptor(opts, cacheKey) {
20593
+ return {
20594
+ id: `canonical:${cacheKey}`,
20595
+ name: "Canonical Tree",
20596
+ system: opts.system,
20597
+ parts: [...opts.parts ?? []],
20598
+ cacheKey
20599
+ };
20600
+ }
20601
+ var canonicalTreeCache = /* @__PURE__ */ new Map();
20602
+ var TreeWorkspace = class {
20603
+ constructor(graph, visualResolvers = []) {
20604
+ this.graph = graph;
20605
+ this.visualResolvers = visualResolvers;
20606
+ this.descriptor = graph.descriptor;
20607
+ }
20608
+ getNode(id2) {
20609
+ return this.graph.nodesById.get(id2);
20610
+ }
20611
+ hasNode(id2) {
20612
+ return this.graph.nodesById.has(id2);
20613
+ }
20614
+ getNodes(type) {
20615
+ if (!type) {
20616
+ return sortNodes(
20617
+ [...this.graph.nodesById.values()]
20618
+ );
20619
+ }
20620
+ const ids = this.graph.nodeIdsByType.get(type) ?? [];
20621
+ return ids.map((id2) => this.graph.nodesById.get(id2)).filter((node) => Boolean(node));
20622
+ }
20623
+ findNodes(options = {}) {
20624
+ const typeFilter = normalizeTypes(options.type);
20625
+ const search = options.search?.trim().toLowerCase();
20626
+ const candidates = options.ids ? options.ids.map((id2) => this.graph.nodesById.get(id2)).filter((node) => Boolean(node)) : typeFilter ? [...typeFilter].flatMap((type) => this.getNodes(type)) : this.getNodes();
20627
+ return sortNodes(
20628
+ candidates.filter((node) => {
20629
+ if (typeFilter && !typeFilter.has(node.type)) {
20630
+ return false;
20631
+ }
20632
+ if (search) {
20633
+ const haystacks = [
20634
+ String(node.id).toLowerCase(),
20635
+ String(node.name ?? "").toLowerCase()
20636
+ ];
20637
+ if (!haystacks.some((value) => value.includes(search))) {
20638
+ return false;
20639
+ }
20640
+ }
20641
+ return options.predicate ? options.predicate(node) : true;
20642
+ })
20643
+ );
20644
+ }
20645
+ getEdge(left, right) {
20646
+ return this.graph.edgesById.get(makeCorrespondenceId(left, right));
20647
+ }
20648
+ getEdges(nodeId) {
20649
+ if (!nodeId) {
20650
+ return [...this.graph.edgesById.values()];
20651
+ }
20652
+ return (this.graph.edgeIdsByNodeId.get(nodeId) ?? []).map((edgeId) => this.graph.edgesById.get(edgeId)).filter((edge) => Boolean(edge));
20653
+ }
20654
+ getNotes(target) {
20655
+ if (!target) {
20656
+ return [...this.graph.notesById.values()];
20657
+ }
20658
+ if (target.kind === "node") {
20659
+ return (this.graph.noteIdsByNodeId.get(target.nodeId) ?? []).map((noteId) => this.graph.notesById.get(noteId)).filter((note) => Boolean(note));
20660
+ }
20661
+ const edgeId = makeCorrespondenceId(target.left, target.right);
20662
+ return (this.graph.noteIdsByCorrespondenceId.get(edgeId) ?? []).map((noteId) => this.graph.notesById.get(noteId)).filter((note) => Boolean(note));
20663
+ }
20664
+ getCorrespondences(nodeId, options = {}) {
20665
+ if (!this.graph.nodesById.has(nodeId)) {
20666
+ return [];
20667
+ }
20668
+ const typeFilter = normalizeTypes(options.type);
20669
+ const includeSelf = options.includeSelf ?? false;
20670
+ const depth = Math.max(1, options.depth ?? 1);
20671
+ const limit = options.limit ?? Infinity;
20672
+ const previous = /* @__PURE__ */ new Map();
20673
+ const visited = /* @__PURE__ */ new Set([nodeId]);
20674
+ const queue = [
20675
+ {
20676
+ nodeId,
20677
+ distance: 0
20678
+ }
20679
+ ];
20680
+ const matches = [];
20681
+ while (queue.length > 0 && matches.length < limit) {
20682
+ const current = queue.shift();
20683
+ if (current.distance >= depth) {
20684
+ continue;
20685
+ }
20686
+ for (const edgeId of this.graph.edgeIdsByNodeId.get(current.nodeId) ?? []) {
20687
+ const edge = this.graph.edgesById.get(edgeId);
20688
+ if (!edge) {
20689
+ continue;
20690
+ }
20691
+ const nextNodeId = edge.left === current.nodeId ? edge.right : edge.left;
20692
+ if (visited.has(nextNodeId)) {
20693
+ continue;
20694
+ }
20695
+ visited.add(nextNodeId);
20696
+ previous.set(nextNodeId, {
20697
+ from: current.nodeId,
20698
+ edgeId
20699
+ });
20700
+ const distance = current.distance + 1;
20701
+ const nextNode = this.graph.nodesById.get(nextNodeId);
20702
+ if (!nextNode) {
20703
+ continue;
20704
+ }
20705
+ if ((!typeFilter || typeFilter.has(nextNode.type)) && distance > 0) {
20706
+ matches.push({
20707
+ node: nextNode,
20708
+ distance,
20709
+ path: reconstructPath(
20710
+ nodeId,
20711
+ nextNodeId,
20712
+ previous,
20713
+ this.graph.edgesById
20714
+ )
20715
+ });
20716
+ }
20717
+ queue.push({
20718
+ nodeId: nextNodeId,
20719
+ distance
20720
+ });
20721
+ }
20722
+ }
20723
+ if (includeSelf) {
20724
+ const sourceNode = this.graph.nodesById.get(nodeId);
20725
+ if (sourceNode && (!typeFilter || typeFilter.has(sourceNode.type)) && matches.length < limit) {
20726
+ matches.unshift({
20727
+ node: sourceNode,
20728
+ distance: 0,
20729
+ path: []
20730
+ });
20731
+ }
20732
+ }
20733
+ return sortMatches(matches).slice(0, limit);
20734
+ }
20735
+ getCorrespondenceMap(nodeId, options = {}) {
20736
+ const grouped = {};
20737
+ for (const match of this.getCorrespondences(nodeId, options)) {
20738
+ const typeKey = match.node.type;
20739
+ const typeMatches = grouped[typeKey] ?? [];
20740
+ typeMatches.push(match);
20741
+ grouped[typeKey] = typeMatches;
20742
+ }
20743
+ return grouped;
20744
+ }
20745
+ resolveVisual(request) {
20746
+ for (const resolver of this.visualResolvers) {
20747
+ const resolved = resolver({
20748
+ request,
20749
+ workspace: this
20750
+ });
20751
+ if (resolved) {
20752
+ return resolved;
20753
+ }
20754
+ }
20755
+ return void 0;
20756
+ }
20757
+ };
20758
+ function createTreeWorkspace(options = {}) {
20759
+ const base = normalizeBase(options.base);
20760
+ const overlays = options.overlays ?? [];
20761
+ const applied = applyOverlays(base, overlays);
20762
+ const descriptor = {
20763
+ ...base.descriptor,
20764
+ ...options.descriptor
20765
+ };
20766
+ return new TreeWorkspace(
20767
+ createGraphData(descriptor, applied.nodes, applied.edges, applied.notes),
20768
+ options.visualResolvers ?? []
20769
+ );
20770
+ }
20771
+ function getCanonicalTree(opts = {
20772
+ system: "kaabalah",
20773
+ parts: []
20774
+ }) {
20775
+ const parts = [...opts.parts ?? []];
20776
+ const cacheKey = `${opts.system}:${parts.join(",")}`;
20777
+ const cachedTree = canonicalTreeCache.get(cacheKey);
20778
+ if (cachedTree) {
20779
+ return cachedTree;
20780
+ }
20781
+ const tree = createTree({
20782
+ system: opts.system,
20783
+ parts
20784
+ });
20785
+ const canonicalTree = createTreeWorkspace({
20786
+ base: tree,
20787
+ descriptor: buildCanonicalDescriptor(opts, cacheKey)
20788
+ });
20789
+ canonicalTreeCache.set(cacheKey, canonicalTree);
20790
+ return canonicalTree;
20791
+ }
20792
+
19911
20793
  // src/tarot/index.ts
20794
+ var majorArcana = [
20795
+ "01_the_magician",
20796
+ "02_the_high_priestess",
20797
+ "03_the_empress",
20798
+ "04_the_emperor",
20799
+ "05_the_hierophant",
20800
+ "06_the_lover",
20801
+ "07_the_chariot",
20802
+ "08_justice",
20803
+ "09_the_hermit",
20804
+ "10_the_wheel_of_fortune",
20805
+ "11_strength",
20806
+ "12_the_hanged_man",
20807
+ "13_death",
20808
+ "14_temperance",
20809
+ "15_the_devil",
20810
+ "16_the_house_of_god",
20811
+ "17_the_star",
20812
+ "18_the_moon",
20813
+ "19_the_sun",
20814
+ "20_judgement",
20815
+ "21_the_fool",
20816
+ "22_the_world"
20817
+ ];
19912
20818
  var ARKANNUS = [
19913
20819
  // Major Arcana (1-22)
19914
20820
  {
@@ -20758,6 +21664,658 @@ async function shuffleTarotDeck(cards, includeInvertedCards = false, shuffleCoun
20758
21664
  }
20759
21665
  return shuffledCards;
20760
21666
  }
21667
+ var MAJOR_ARCANA_CARDS = ARKANNUS.filter(
21668
+ (card) => card.type === "major" && majorArcana.includes(card.tarotCardFilename)
21669
+ );
21670
+ var EVENT_INNER_SLOT_KEYS = [
21671
+ "inner-1",
21672
+ "inner-2",
21673
+ "inner-3",
21674
+ "inner-4",
21675
+ "inner-5",
21676
+ "inner-6",
21677
+ "inner-7"
21678
+ ];
21679
+ var TAROT_CARD_BY_NUMBER = new Map(
21680
+ ARKANNUS.map((card) => [card.number, card])
21681
+ );
21682
+ function createEventOuterSlot(index, temporalPhase) {
21683
+ return {
21684
+ slotKey: `outer-${index}`,
21685
+ label: String(index),
21686
+ order: index,
21687
+ minCards: 1,
21688
+ maxCards: 1,
21689
+ validationRules: {
21690
+ allowedTypes: ["minor", "daat+royalship"]
21691
+ },
21692
+ manualSelectionRules: {
21693
+ allowedTypes: ["minor", "daat+royalship"]
21694
+ },
21695
+ drawRules: {
21696
+ allowedTypes: ["minor", "daat+royalship"]
21697
+ },
21698
+ metadata: {
21699
+ displayLabel: String(index),
21700
+ groupKey: "outer",
21701
+ temporalPhase
21702
+ }
21703
+ };
21704
+ }
21705
+ function createEventInnerSlot(index, label, note) {
21706
+ return {
21707
+ slotKey: `inner-${index}`,
21708
+ label,
21709
+ order: 100 + index,
21710
+ minCards: 1,
21711
+ maxCards: 1,
21712
+ validationRules: {
21713
+ allowedTypes: ["major"]
21714
+ },
21715
+ manualSelectionRules: {
21716
+ allowedTypes: ["major"],
21717
+ excludedCardFilenames: [
21718
+ "01_the_magician",
21719
+ "02_the_high_priestess"
21720
+ ]
21721
+ },
21722
+ drawRules: {
21723
+ allowedTypes: ["major"]
21724
+ },
21725
+ metadata: {
21726
+ displayLabel: `${index}.`,
21727
+ groupKey: "inner",
21728
+ note
21729
+ }
21730
+ };
21731
+ }
21732
+ var TAROT_SPREADS = [
21733
+ {
21734
+ spreadId: "quick-insight",
21735
+ label: "Quick Insight",
21736
+ description: "A single-card reading for immediate insight.",
21737
+ slots: [
21738
+ {
21739
+ slotKey: "quick-insight",
21740
+ label: "Quick Insight",
21741
+ order: 1,
21742
+ minCards: 1,
21743
+ maxCards: 1
21744
+ }
21745
+ ]
21746
+ },
21747
+ {
21748
+ spreadId: "conscious-reading",
21749
+ label: "Conscious Reading",
21750
+ description: "Three-card spread for conscious, unconscious, and subconscious layers.",
21751
+ slots: [
21752
+ {
21753
+ slotKey: "conscious",
21754
+ label: "Conscious",
21755
+ order: 1,
21756
+ minCards: 1,
21757
+ maxCards: 1,
21758
+ validationRules: {
21759
+ allowedTypes: ["major"]
21760
+ },
21761
+ manualSelectionRules: {
21762
+ allowedTypes: ["major"]
21763
+ },
21764
+ drawRules: {
21765
+ allowedTypes: ["major"]
21766
+ }
21767
+ },
21768
+ {
21769
+ slotKey: "unconscious",
21770
+ label: "Unconscious",
21771
+ order: 2,
21772
+ minCards: 1,
21773
+ maxCards: 1,
21774
+ validationRules: {
21775
+ allowedTypes: ["daat+royalship"]
21776
+ },
21777
+ manualSelectionRules: {
21778
+ allowedTypes: ["daat+royalship"]
21779
+ },
21780
+ drawRules: {
21781
+ allowedTypes: ["daat+royalship"]
21782
+ }
21783
+ },
21784
+ {
21785
+ slotKey: "subconscious",
21786
+ label: "Subconscious",
21787
+ order: 3,
21788
+ minCards: 1,
21789
+ maxCards: 1,
21790
+ validationRules: {
21791
+ allowedTypes: ["minor"]
21792
+ },
21793
+ manualSelectionRules: {
21794
+ allowedTypes: ["minor"]
21795
+ },
21796
+ drawRules: {
21797
+ allowedTypes: ["minor"]
21798
+ }
21799
+ }
21800
+ ]
21801
+ },
21802
+ {
21803
+ spreadId: "time-reading",
21804
+ label: "Time Reading",
21805
+ description: "Three major arcana cards for past, present, and future.",
21806
+ slots: [
21807
+ {
21808
+ slotKey: "past",
21809
+ label: "Past",
21810
+ order: 1,
21811
+ minCards: 1,
21812
+ maxCards: 1,
21813
+ validationRules: {
21814
+ allowedTypes: ["major"]
21815
+ },
21816
+ manualSelectionRules: {
21817
+ allowedTypes: ["major"]
21818
+ },
21819
+ drawRules: {
21820
+ allowedTypes: ["major"]
21821
+ }
21822
+ },
21823
+ {
21824
+ slotKey: "present",
21825
+ label: "Present",
21826
+ order: 2,
21827
+ minCards: 1,
21828
+ maxCards: 1,
21829
+ validationRules: {
21830
+ allowedTypes: ["major"]
21831
+ },
21832
+ manualSelectionRules: {
21833
+ allowedTypes: ["major"]
21834
+ },
21835
+ drawRules: {
21836
+ allowedTypes: ["major"]
21837
+ }
21838
+ },
21839
+ {
21840
+ slotKey: "future",
21841
+ label: "Future",
21842
+ order: 3,
21843
+ minCards: 1,
21844
+ maxCards: 1,
21845
+ validationRules: {
21846
+ allowedTypes: ["major"]
21847
+ },
21848
+ manualSelectionRules: {
21849
+ allowedTypes: ["major"]
21850
+ },
21851
+ drawRules: {
21852
+ allowedTypes: ["major"]
21853
+ }
21854
+ }
21855
+ ]
21856
+ },
21857
+ {
21858
+ spreadId: "dialectic-reading",
21859
+ label: "Dialectic Reading",
21860
+ description: "Three major arcana cards for thesis, antithesis, and synthesis.",
21861
+ slots: [
21862
+ {
21863
+ slotKey: "thesis",
21864
+ label: "Thesis",
21865
+ order: 1,
21866
+ minCards: 1,
21867
+ maxCards: 1,
21868
+ validationRules: {
21869
+ allowedTypes: ["major"]
21870
+ },
21871
+ manualSelectionRules: {
21872
+ allowedTypes: ["major"]
21873
+ },
21874
+ drawRules: {
21875
+ allowedTypes: ["major"]
21876
+ }
21877
+ },
21878
+ {
21879
+ slotKey: "antithesis",
21880
+ label: "Antithesis",
21881
+ order: 2,
21882
+ minCards: 1,
21883
+ maxCards: 1,
21884
+ validationRules: {
21885
+ allowedTypes: ["major"]
21886
+ },
21887
+ manualSelectionRules: {
21888
+ allowedTypes: ["major"]
21889
+ },
21890
+ drawRules: {
21891
+ allowedTypes: ["major"]
21892
+ }
21893
+ },
21894
+ {
21895
+ slotKey: "synthesis",
21896
+ label: "Synthesis",
21897
+ order: 3,
21898
+ minCards: 1,
21899
+ maxCards: 1,
21900
+ validationRules: {
21901
+ allowedTypes: ["major"]
21902
+ },
21903
+ manualSelectionRules: {
21904
+ allowedTypes: ["major"]
21905
+ },
21906
+ drawRules: {
21907
+ allowedTypes: ["major"]
21908
+ }
21909
+ }
21910
+ ]
21911
+ },
21912
+ {
21913
+ spreadId: "tree-of-life-reading",
21914
+ label: "Tree of Life Reading",
21915
+ description: "Ten numbered minor arcana slots mapped to the spheres plus four Daath court cards.",
21916
+ slots: [
21917
+ {
21918
+ slotKey: "kether",
21919
+ label: "Kether",
21920
+ order: 1,
21921
+ minCards: 1,
21922
+ maxCards: 1,
21923
+ validationRules: {
21924
+ allowedTypes: ["minor"],
21925
+ requiredRank: "ace"
21926
+ },
21927
+ manualSelectionRules: {
21928
+ allowedTypes: ["minor"],
21929
+ requiredRank: "ace"
21930
+ },
21931
+ drawRules: {
21932
+ allowedTypes: ["minor"],
21933
+ requiredRank: "ace"
21934
+ }
21935
+ },
21936
+ {
21937
+ slotKey: "chokhmah",
21938
+ label: "Chokhmah",
21939
+ order: 2,
21940
+ minCards: 1,
21941
+ maxCards: 1,
21942
+ validationRules: {
21943
+ allowedTypes: ["minor"],
21944
+ requiredRank: "2"
21945
+ },
21946
+ manualSelectionRules: {
21947
+ allowedTypes: ["minor"],
21948
+ requiredRank: "2"
21949
+ },
21950
+ drawRules: {
21951
+ allowedTypes: ["minor"],
21952
+ requiredRank: "2"
21953
+ }
21954
+ },
21955
+ {
21956
+ slotKey: "binah",
21957
+ label: "Binah",
21958
+ order: 3,
21959
+ minCards: 1,
21960
+ maxCards: 1,
21961
+ validationRules: {
21962
+ allowedTypes: ["minor"],
21963
+ requiredRank: "3"
21964
+ },
21965
+ manualSelectionRules: {
21966
+ allowedTypes: ["minor"],
21967
+ requiredRank: "3"
21968
+ },
21969
+ drawRules: {
21970
+ allowedTypes: ["minor"],
21971
+ requiredRank: "3"
21972
+ }
21973
+ },
21974
+ {
21975
+ slotKey: "chesed",
21976
+ label: "Chesed",
21977
+ order: 4,
21978
+ minCards: 1,
21979
+ maxCards: 1,
21980
+ validationRules: {
21981
+ allowedTypes: ["minor"],
21982
+ requiredRank: "4"
21983
+ },
21984
+ manualSelectionRules: {
21985
+ allowedTypes: ["minor"],
21986
+ requiredRank: "4"
21987
+ },
21988
+ drawRules: {
21989
+ allowedTypes: ["minor"],
21990
+ requiredRank: "4"
21991
+ }
21992
+ },
21993
+ {
21994
+ slotKey: "geburah",
21995
+ label: "Geburah",
21996
+ order: 5,
21997
+ minCards: 1,
21998
+ maxCards: 1,
21999
+ validationRules: {
22000
+ allowedTypes: ["minor"],
22001
+ requiredRank: "5"
22002
+ },
22003
+ manualSelectionRules: {
22004
+ allowedTypes: ["minor"],
22005
+ requiredRank: "5"
22006
+ },
22007
+ drawRules: {
22008
+ allowedTypes: ["minor"],
22009
+ requiredRank: "5"
22010
+ }
22011
+ },
22012
+ {
22013
+ slotKey: "tiphareth",
22014
+ label: "Tiphareth",
22015
+ order: 6,
22016
+ minCards: 1,
22017
+ maxCards: 1,
22018
+ validationRules: {
22019
+ allowedTypes: ["minor"],
22020
+ requiredRank: "6"
22021
+ },
22022
+ manualSelectionRules: {
22023
+ allowedTypes: ["minor"],
22024
+ requiredRank: "6"
22025
+ },
22026
+ drawRules: {
22027
+ allowedTypes: ["minor"],
22028
+ requiredRank: "6"
22029
+ }
22030
+ },
22031
+ {
22032
+ slotKey: "netzach",
22033
+ label: "Netzach",
22034
+ order: 7,
22035
+ minCards: 1,
22036
+ maxCards: 1,
22037
+ validationRules: {
22038
+ allowedTypes: ["minor"],
22039
+ requiredRank: "7"
22040
+ },
22041
+ manualSelectionRules: {
22042
+ allowedTypes: ["minor"],
22043
+ requiredRank: "7"
22044
+ },
22045
+ drawRules: {
22046
+ allowedTypes: ["minor"],
22047
+ requiredRank: "7"
22048
+ }
22049
+ },
22050
+ {
22051
+ slotKey: "hod",
22052
+ label: "Hod",
22053
+ order: 8,
22054
+ minCards: 1,
22055
+ maxCards: 1,
22056
+ validationRules: {
22057
+ allowedTypes: ["minor"],
22058
+ requiredRank: "8"
22059
+ },
22060
+ manualSelectionRules: {
22061
+ allowedTypes: ["minor"],
22062
+ requiredRank: "8"
22063
+ },
22064
+ drawRules: {
22065
+ allowedTypes: ["minor"],
22066
+ requiredRank: "8"
22067
+ }
22068
+ },
22069
+ {
22070
+ slotKey: "yesod",
22071
+ label: "Yesod",
22072
+ order: 9,
22073
+ minCards: 1,
22074
+ maxCards: 1,
22075
+ validationRules: {
22076
+ allowedTypes: ["minor"],
22077
+ requiredRank: "9"
22078
+ },
22079
+ manualSelectionRules: {
22080
+ allowedTypes: ["minor"],
22081
+ requiredRank: "9"
22082
+ },
22083
+ drawRules: {
22084
+ allowedTypes: ["minor"],
22085
+ requiredRank: "9"
22086
+ }
22087
+ },
22088
+ {
22089
+ slotKey: "malkuth",
22090
+ label: "Malkuth",
22091
+ order: 10,
22092
+ minCards: 1,
22093
+ maxCards: 1,
22094
+ validationRules: {
22095
+ allowedTypes: ["minor"],
22096
+ requiredRank: "10"
22097
+ },
22098
+ manualSelectionRules: {
22099
+ allowedTypes: ["minor"],
22100
+ requiredRank: "10"
22101
+ },
22102
+ drawRules: {
22103
+ allowedTypes: ["minor"],
22104
+ requiredRank: "10"
22105
+ }
22106
+ },
22107
+ {
22108
+ slotKey: "daath",
22109
+ label: "Daath",
22110
+ order: 11,
22111
+ minCards: 4,
22112
+ maxCards: 4,
22113
+ validationRules: {
22114
+ allowedTypes: ["daat+royalship"]
22115
+ },
22116
+ manualSelectionRules: {
22117
+ allowedTypes: ["daat+royalship"]
22118
+ },
22119
+ drawRules: {
22120
+ allowedTypes: ["daat+royalship"]
22121
+ }
22122
+ }
22123
+ ]
22124
+ },
22125
+ {
22126
+ spreadId: "celtic-cross",
22127
+ label: "Celtic Cross",
22128
+ description: "Classic ten-card Celtic Cross spread.",
22129
+ slots: [
22130
+ {
22131
+ slotKey: "present",
22132
+ label: "The Present",
22133
+ order: 1,
22134
+ minCards: 1,
22135
+ maxCards: 1,
22136
+ metadata: {
22137
+ displayLabel: "1."
22138
+ }
22139
+ },
22140
+ {
22141
+ slotKey: "challenge",
22142
+ label: "The Challenge",
22143
+ order: 2,
22144
+ minCards: 1,
22145
+ maxCards: 1,
22146
+ metadata: {
22147
+ displayLabel: "2.",
22148
+ orientation: "sideways"
22149
+ }
22150
+ },
22151
+ {
22152
+ slotKey: "above",
22153
+ label: "Above",
22154
+ order: 3,
22155
+ minCards: 1,
22156
+ maxCards: 1,
22157
+ metadata: {
22158
+ displayLabel: "3."
22159
+ }
22160
+ },
22161
+ {
22162
+ slotKey: "below",
22163
+ label: "Below",
22164
+ order: 4,
22165
+ minCards: 1,
22166
+ maxCards: 1,
22167
+ metadata: {
22168
+ displayLabel: "4."
22169
+ }
22170
+ },
22171
+ {
22172
+ slotKey: "behind",
22173
+ label: "Behind",
22174
+ order: 5,
22175
+ minCards: 1,
22176
+ maxCards: 1,
22177
+ metadata: {
22178
+ displayLabel: "5."
22179
+ }
22180
+ },
22181
+ {
22182
+ slotKey: "before",
22183
+ label: "Before",
22184
+ order: 6,
22185
+ minCards: 1,
22186
+ maxCards: 1,
22187
+ metadata: {
22188
+ displayLabel: "6."
22189
+ }
22190
+ },
22191
+ {
22192
+ slotKey: "self",
22193
+ label: "Self",
22194
+ order: 7,
22195
+ minCards: 1,
22196
+ maxCards: 1,
22197
+ metadata: {
22198
+ displayLabel: "7."
22199
+ }
22200
+ },
22201
+ {
22202
+ slotKey: "environment",
22203
+ label: "Environment",
22204
+ order: 8,
22205
+ minCards: 1,
22206
+ maxCards: 1,
22207
+ metadata: {
22208
+ displayLabel: "8."
22209
+ }
22210
+ },
22211
+ {
22212
+ slotKey: "hopes-fears",
22213
+ label: "Hopes/Fears",
22214
+ order: 9,
22215
+ minCards: 1,
22216
+ maxCards: 1,
22217
+ metadata: {
22218
+ displayLabel: "9."
22219
+ }
22220
+ },
22221
+ {
22222
+ slotKey: "outcome",
22223
+ label: "Outcome",
22224
+ order: 10,
22225
+ minCards: 1,
22226
+ maxCards: 1,
22227
+ metadata: {
22228
+ displayLabel: "10."
22229
+ }
22230
+ }
22231
+ ]
22232
+ },
22233
+ {
22234
+ spreadId: "event-reading",
22235
+ label: "Event Reading",
22236
+ description: "Papus-style event spread with outer minor/court cards, seven major cards, and an inquirer card.",
22237
+ contextRequirements: ["inquirerGender"],
22238
+ slots: [
22239
+ createEventOuterSlot(1, "past"),
22240
+ createEventOuterSlot(2, "past"),
22241
+ createEventOuterSlot(3, "past"),
22242
+ createEventOuterSlot(4, "past"),
22243
+ createEventOuterSlot(5, "present"),
22244
+ createEventOuterSlot(6, "present"),
22245
+ createEventOuterSlot(7, "present"),
22246
+ createEventOuterSlot(8, "present"),
22247
+ createEventOuterSlot(9, "future"),
22248
+ createEventOuterSlot(10, "future"),
22249
+ createEventOuterSlot(11, "future"),
22250
+ createEventOuterSlot(12, "future"),
22251
+ createEventInnerSlot(
22252
+ 1,
22253
+ "Commencement",
22254
+ "Character of the beginning phase."
22255
+ ),
22256
+ createEventInnerSlot(2, "Apogee", "Peak or zenith of the event."),
22257
+ createEventInnerSlot(
22258
+ 3,
22259
+ "Decline/Obstacle",
22260
+ "Challenges, obstacles, or decline."
22261
+ ),
22262
+ createEventInnerSlot(4, "Fall", "Conclusion or end phase."),
22263
+ createEventInnerSlot(
22264
+ 5,
22265
+ "The Past",
22266
+ "Special character or influence in the past."
22267
+ ),
22268
+ createEventInnerSlot(
22269
+ 6,
22270
+ "The Present",
22271
+ "Special character or influence in the present."
22272
+ ),
22273
+ createEventInnerSlot(
22274
+ 7,
22275
+ "The Future",
22276
+ "Special character or influence to come."
22277
+ ),
22278
+ {
22279
+ slotKey: "inquirer",
22280
+ label: "Inquirer",
22281
+ order: 200,
22282
+ minCards: 1,
22283
+ maxCards: 1,
22284
+ validationRules: {
22285
+ allowedTypes: ["major"]
22286
+ },
22287
+ manualSelectionRules: {
22288
+ allowedTypes: ["major"],
22289
+ allowedCardFilenames: [
22290
+ "01_the_magician",
22291
+ "02_the_high_priestess"
22292
+ ]
22293
+ },
22294
+ drawRules: {
22295
+ allowedTypes: ["major"]
22296
+ },
22297
+ metadata: {
22298
+ displayLabel: "Inquirer",
22299
+ groupKey: "center",
22300
+ note: "The querent's energy in this reading."
22301
+ }
22302
+ }
22303
+ ],
22304
+ specialRules: {
22305
+ inquirerCard: {
22306
+ slotKey: "inquirer",
22307
+ sourceSlotKeys: [...EVENT_INNER_SLOT_KEYS],
22308
+ cardNumbersByGender: {
22309
+ man: 1,
22310
+ woman: 2
22311
+ }
22312
+ }
22313
+ }
22314
+ }
22315
+ ];
22316
+ var TAROT_SPREAD_BY_ID = new Map(
22317
+ TAROT_SPREADS.map((spread) => [spread.spreadId, spread])
22318
+ );
20761
22319
 
20762
22320
  // src/cli/commands/tarot.ts
20763
22321
  function findCardsByQuery(query) {
@@ -20858,7 +22416,10 @@ function cmdTarotSpread(cardQueries, flags) {
20858
22416
 
20859
22417
  // src/cli/commands/tree.ts
20860
22418
  function getTree() {
20861
- return createTree({ system: SYSTEM2, parts: ["westernAstrology", "tarot"] });
22419
+ return getCanonicalTree({
22420
+ system: SYSTEM2,
22421
+ parts: ["westernAstrology", "tarot"]
22422
+ });
20862
22423
  }
20863
22424
  function serializeNode(node) {
20864
22425
  const result = { id: node.id, type: node.type };
@@ -20870,37 +22431,109 @@ function serializeNode(node) {
20870
22431
  }
20871
22432
  return result;
20872
22433
  }
22434
+ function serializeSource(source) {
22435
+ return source.kind === "bridge" ? { ...source, parts: [...source.parts] } : { ...source };
22436
+ }
22437
+ function serializeEdge(edge) {
22438
+ const serialized = {
22439
+ id: edge.id,
22440
+ from: edge.left,
22441
+ to: edge.right
22442
+ };
22443
+ if (edge.metadata) {
22444
+ serialized.metadata = edge.metadata;
22445
+ }
22446
+ if (edge.sources.length > 0) {
22447
+ serialized.sources = edge.sources.map(serializeSource);
22448
+ }
22449
+ return serialized;
22450
+ }
22451
+ function serializeMatch(match) {
22452
+ return {
22453
+ node: serializeNode(match.node),
22454
+ distance: match.distance,
22455
+ path: match.path.map((step) => ({
22456
+ from: step.from,
22457
+ to: step.to,
22458
+ edge: serializeEdge(step.edge)
22459
+ }))
22460
+ };
22461
+ }
22462
+ function getRelatedTypes(tree, nodeId) {
22463
+ return [...new Set(
22464
+ tree.getEdges(nodeId).map((edge) => {
22465
+ const relatedNodeId = edge.left === nodeId ? edge.right : edge.left;
22466
+ return tree.getNode(relatedNodeId)?.type;
22467
+ }).filter((type) => Boolean(type))
22468
+ )].sort((left, right) => left.localeCompare(right));
22469
+ }
22470
+ function groupSerializedMatches(matches) {
22471
+ const grouped = {};
22472
+ for (const match of matches) {
22473
+ const bucket = grouped[match.node.type] ?? [];
22474
+ bucket.push(serializeMatch(match));
22475
+ grouped[match.node.type] = bucket;
22476
+ }
22477
+ return grouped;
22478
+ }
22479
+ function humanLabel(node) {
22480
+ const data = node.data;
22481
+ return data?.name ?? data?.character ?? data?.englishName ?? data?.meaning ?? node.name ?? "";
22482
+ }
22483
+ function describeSources(edge) {
22484
+ const parts = /* @__PURE__ */ new Set();
22485
+ for (const source of edge.sources) {
22486
+ if (source.kind === "system") {
22487
+ parts.add(`system:${source.system}`);
22488
+ continue;
22489
+ }
22490
+ if (source.kind === "part") {
22491
+ parts.add(`part:${source.part}`);
22492
+ continue;
22493
+ }
22494
+ if (source.kind === "bridge") {
22495
+ parts.add(`bridge:${source.bridgeId}`);
22496
+ continue;
22497
+ }
22498
+ if (source.kind === "overlay") {
22499
+ parts.add(`overlay:${source.overlayId}`);
22500
+ continue;
22501
+ }
22502
+ parts.add(source.kind);
22503
+ }
22504
+ return [...parts].join(", ");
22505
+ }
20873
22506
  function cmdTree(flags) {
20874
22507
  const tree = getTree();
20875
22508
  const allNodes = tree.getNodes();
20876
22509
  if (isJsonMode(flags)) {
20877
22510
  const nodes = allNodes.map((node) => {
20878
22511
  const serialized = serializeNode(node);
20879
- const relatedTypes = tree.relatedTypes(node.id);
22512
+ const relatedTypes = getRelatedTypes(tree, node.id);
20880
22513
  if (relatedTypes.length > 0) {
20881
22514
  serialized.relatedTypes = relatedTypes;
20882
22515
  }
20883
22516
  return serialized;
20884
22517
  });
20885
- const edgeSet = /* @__PURE__ */ new Set();
20886
- const edges = [];
20887
- for (const node of allNodes) {
20888
- const related = tree.related(node.id);
20889
- for (const relation of related) {
20890
- const key = node.id < relation.id ? `${node.id}|${relation.id}` : `${relation.id}|${node.id}`;
20891
- if (!edgeSet.has(key)) {
20892
- edgeSet.add(key);
20893
- edges.push({ from: node.id, to: relation.id });
20894
- }
20895
- }
20896
- }
20897
- outputJson({ system: SYSTEM2, totalNodes: allNodes.length, totalEdges: edges.length, nodes, edges }, flags);
22518
+ const edges = tree.getEdges().map(serializeEdge);
22519
+ outputJson(
22520
+ {
22521
+ descriptor: tree.descriptor,
22522
+ system: SYSTEM2,
22523
+ totalNodes: allNodes.length,
22524
+ totalEdges: edges.length,
22525
+ nodes,
22526
+ edges
22527
+ },
22528
+ flags
22529
+ );
20898
22530
  return;
20899
22531
  }
20900
22532
  console.log(`
20901
22533
  Tree of Life (${SYSTEM2})
20902
22534
  `);
20903
22535
  console.log(` Total nodes: ${allNodes.length}`);
22536
+ console.log(` Total correspondences: ${tree.getEdges().length}`);
20904
22537
  const byType = /* @__PURE__ */ new Map();
20905
22538
  for (const node of allNodes) {
20906
22539
  if (!byType.has(node.type)) {
@@ -20912,9 +22545,8 @@ Tree of Life (${SYSTEM2})
20912
22545
  console.log(`
20913
22546
  ${type} (${nodes.length}):`);
20914
22547
  for (const node of nodes.slice(0, 15)) {
20915
- const data = node.data;
20916
- const name = data?.name ?? data?.character ?? "";
20917
- console.log(` ${node.id}${name ? ` \u2014 ${name}` : ""}`);
22548
+ const label = humanLabel(node);
22549
+ console.log(` ${node.id}${label ? ` \u2014 ${label}` : ""}`);
20918
22550
  }
20919
22551
  if (nodes.length > 15) {
20920
22552
  console.log(` ... and ${nodes.length - 15} more`);
@@ -20926,17 +22558,36 @@ function cmdTreeNode(idStr, flags) {
20926
22558
  const tree = getTree();
20927
22559
  const node = tree.getNode(idStr);
20928
22560
  if (!node) {
20929
- exitWithError("INVALID_ARGUMENT", `Node "${idStr}" not found. Use "kaabalah tree:types --json" to see valid node types, or "kaabalah tree --json --fields=nodes" to list all node IDs.`, flags);
22561
+ exitWithError(
22562
+ "INVALID_ARGUMENT",
22563
+ `Node "${idStr}" not found. Use "kaabalah tree:types --json" to see valid node types, or "kaabalah tree --json --fields=nodes" to list all node IDs.`,
22564
+ flags
22565
+ );
20930
22566
  }
20931
22567
  const typeFilter = getFlagString(flags, "type");
20932
22568
  const depth = getFlagNumber(flags, "depth") ?? 1;
20933
- const related = depth > 1 ? tree.walk(node.id, depth, typeFilter || void 0) : typeFilter ? tree.related(node.id, typeFilter) : tree.related(node.id);
22569
+ const correspondences = tree.getCorrespondences(node.id, {
22570
+ depth,
22571
+ type: typeFilter ?? void 0
22572
+ });
22573
+ const related = correspondences.map(({ node: relatedNode }) => relatedNode);
22574
+ const directEdges = tree.getEdges(node.id);
22575
+ const relatedTypes = getRelatedTypes(tree, node.id);
20934
22576
  if (isJsonMode(flags)) {
20935
- outputJson({
20936
- node: serializeNode(node),
20937
- relatedTypes: tree.relatedTypes(node.id),
20938
- related: related.map(serializeNode)
20939
- }, flags);
22577
+ outputJson(
22578
+ {
22579
+ descriptor: tree.descriptor,
22580
+ node: serializeNode(node),
22581
+ relatedTypes,
22582
+ depth,
22583
+ ...typeFilter ? { typeFilter } : {},
22584
+ related: related.map(serializeNode),
22585
+ directEdges: directEdges.map(serializeEdge),
22586
+ correspondences: correspondences.map(serializeMatch),
22587
+ correspondenceMap: groupSerializedMatches(correspondences)
22588
+ },
22589
+ flags
22590
+ );
20940
22591
  return;
20941
22592
  }
20942
22593
  console.log(`
@@ -20950,21 +22601,26 @@ function cmdTreeNode(idStr, flags) {
20950
22601
  }
20951
22602
  }
20952
22603
  console.log(`
20953
- Related types: ${tree.relatedTypes(node.id).join(", ")}`);
22604
+ Related types: ${relatedTypes.join(", ")}`);
20954
22605
  const byType = /* @__PURE__ */ new Map();
20955
- for (const relation of related) {
20956
- if (!byType.has(relation.type)) {
20957
- byType.set(relation.type, []);
22606
+ for (const relation of correspondences) {
22607
+ if (!byType.has(relation.node.type)) {
22608
+ byType.set(relation.node.type, []);
20958
22609
  }
20959
- byType.get(relation.type).push(relation);
22610
+ byType.get(relation.node.type).push(relation);
20960
22611
  }
20961
- for (const [type, nodes] of byType) {
22612
+ for (const [type, matches] of byType) {
20962
22613
  console.log(`
20963
22614
  ${type}:`);
20964
- for (const relation of nodes) {
20965
- const relationData = relation.data;
20966
- const label = relationData?.name ?? relationData?.character ?? relationData?.englishName ?? relationData?.meaning ?? "";
20967
- console.log(` ${relation.id}${label ? ` \u2014 ${label}` : ""}`);
22615
+ for (const match of matches) {
22616
+ const label = humanLabel(match.node);
22617
+ const sources = match.path.length > 0 ? describeSources(match.path[match.path.length - 1].edge) : "";
22618
+ const details = [
22619
+ label ? `\u2014 ${label}` : "",
22620
+ match.distance > 1 ? `(depth ${match.distance})` : "",
22621
+ sources ? `[${sources}]` : ""
22622
+ ].filter(Boolean).join(" ");
22623
+ console.log(` ${match.node.id}${details ? ` ${details}` : ""}`);
20968
22624
  }
20969
22625
  }
20970
22626
  console.log();
@@ -20981,7 +22637,13 @@ function cmdTreeTypes(flags) {
20981
22637
  counts[node.type].ids.push(node.id);
20982
22638
  }
20983
22639
  if (isJsonMode(flags)) {
20984
- outputJson(counts, flags);
22640
+ outputJson(
22641
+ {
22642
+ descriptor: tree.descriptor,
22643
+ types: counts
22644
+ },
22645
+ flags
22646
+ );
20985
22647
  return;
20986
22648
  }
20987
22649
  console.log(`
@@ -20992,6 +22654,58 @@ Node types (${Object.keys(counts).length}):
20992
22654
  }
20993
22655
  console.log();
20994
22656
  }
22657
+ function cmdTreeFind(query, flags) {
22658
+ const tree = getTree();
22659
+ const typeFilter = getFlagString(flags, "type");
22660
+ const limit = getFlagNumber(flags, "limit") ?? 20;
22661
+ const search = query?.trim() || void 0;
22662
+ if (!search && !typeFilter) {
22663
+ exitWithError(
22664
+ "MISSING_ARGUMENT",
22665
+ "Usage: kaabalah tree:find <query> [--type=<nodeType>] or kaabalah tree:find --type=<nodeType>",
22666
+ flags
22667
+ );
22668
+ }
22669
+ const matches = tree.findNodes({
22670
+ search,
22671
+ type: typeFilter ?? void 0
22672
+ });
22673
+ const limitedMatches = matches.slice(0, Math.max(1, limit));
22674
+ if (isJsonMode(flags)) {
22675
+ outputJson(
22676
+ {
22677
+ descriptor: tree.descriptor,
22678
+ query: search ?? null,
22679
+ ...typeFilter ? { typeFilter } : {},
22680
+ totalMatches: matches.length,
22681
+ returnedMatches: limitedMatches.length,
22682
+ matches: limitedMatches.map(serializeNode)
22683
+ },
22684
+ flags
22685
+ );
22686
+ return;
22687
+ }
22688
+ console.log(`
22689
+ Tree search
22690
+ `);
22691
+ if (search) {
22692
+ console.log(` Query: ${search}`);
22693
+ }
22694
+ if (typeFilter) {
22695
+ console.log(` Type: ${typeFilter}`);
22696
+ }
22697
+ console.log(` Matches: ${matches.length}
22698
+ `);
22699
+ for (const match of limitedMatches) {
22700
+ const label = humanLabel(match);
22701
+ console.log(` ${match.id}${label ? ` \u2014 ${label}` : ""}`);
22702
+ }
22703
+ if (matches.length > limitedMatches.length) {
22704
+ console.log(`
22705
+ ... and ${matches.length - limitedMatches.length} more`);
22706
+ }
22707
+ console.log();
22708
+ }
20995
22709
 
20996
22710
  // src/cli/app.ts
20997
22711
  function outputVersion(flags) {
@@ -21148,6 +22862,12 @@ async function runCli(argv) {
21148
22862
  }
21149
22863
  cmdTreeNode(inputPayload?.id ?? args.slice(1).join(" "), flags);
21150
22864
  return;
22865
+ case "tree:find":
22866
+ cmdTreeFind(
22867
+ inputPayload?.query ?? (args.slice(1).join(" ") || void 0),
22868
+ flags
22869
+ );
22870
+ return;
21151
22871
  case "tree:types":
21152
22872
  cmdTreeTypes(flags);
21153
22873
  return;