Relation Queries

Query the relation system to find items and their relationships.

Basic Queries

Get Relations for Item

// All relations
const relations = app.getRelations(itemId);

// Specific relation type
const orbits = app.getRelations(itemId, 'orbits');

Inverse Query

Find items that have a relation TO a target:

// What items orbit Earth?
const orbiters = app.queryByRelationTarget(earthId, 'orbits');

orbiters.forEach(({ itemId, item, params }) => {
  console.log(`${itemId} orbits at radius ${params.radius}`);
});

Check Relation Exists

if (app.hasRelation(moonId, earthId, 'orbits')) {
  console.log('Moon orbits Earth');
}

Advanced Queries

Custom Predicate

const orbiting = app.queryRelationPredicate((itemId, associations, entry) => {
  return associations.some(a => a.relation === 'orbits');
});

Negation Query

Find items that do NOT have a relation:

// Items that don't orbit anything
const notOrbiting = app.queryNotRelation('orbits');

// Items not orbiting a specific target
const notOrbitingEarth = app.queryNotRelation('orbits', earthId);

Compound Query (AND logic)

const results = app.queryCompound([
  { relation: 'orbits' },                    // Must orbit something
  { relation: 'follows', not: true },        // Must NOT follow anything
  { relation: 'attached_to', target: itemId }  // Must be attached to specific item
]);

Chain Query

Follow relation chains:

// Find items that follow something that orbits something
const chains = app.queryRelationChain(['follows', 'orbits']);
// Returns arrays of paths: [[item1, item2, item3], ...]

// Start from specific item
const fromMoon = app.queryRelationChain(['follows', 'orbits'], moonId);

Utility Queries

Active Relations

const active = app.queryActiveRelations();

Isolated Items

Find items with no relations (no outgoing, no incoming):

const isolated = app.queryIsolatedItems();

isolated.forEach(({ itemId, item }) => {
  console.log(`${itemId} has no relations`);
});

Query Examples

Find Unlabeled Planets

// Items that orbit the sun but don't have labels attached
const unlabeledPlanets = app.queryCompound([
  { relation: 'orbits', target: sunId },
  { relation: 'attached_to', not: true }
]);

Find Behavior Chain Endpoints

// What does the thing that follows the moon orbit?
const endpoints = app.queryRelationChain(['follows', 'orbits'], satelliteId);

Cleanup Orphaned Items

const isolated = app.queryIsolatedItems();
isolated.forEach(({ itemId }) => {
  console.log(`Consider connecting: ${itemId}`);
});

Statistics

const stats = app.getRelationStats();
// {
//   activeItems: 5,
//   ruleCount: 8,
//   associationsByType: { orbits: 2, follows: 3 }
// }