# Framework API

## Purpose

The Operational Topology Framework exposes stable source-level entry points for
building axial operational worlds without importing the demonstration
application.

The extraction separates five responsibilities:

```txt
framework core
browser integration
lab and animation fixtures
scene presets and templates
application configuration and content
```

The framework is reusable inside and outside this repository. It is published
on npm with core, browser, labs, and presets entry points. The API follows a
`0.x` semantic-versioning policy while external usage continues to shape the
public boundary.

## Entry Points

### Core

```ts
import {
  createOperationalTopology,
  type OperationalTopologyDefinition,
} from "../src/framework/index.ts";
```

`src/framework/index.ts` exports:

- axial geometry and grid generation
- topology and world models
- camera math
- connector contracts
- signal engine, policy, and coordinator
- relationship context
- render-frame and SVG renderer contracts
- knowledge repository
- reusable scene configuration defaults
- reusable scene presets and template contracts
- presentation slide definitions and topology generation
- semantic theme contracts
- the `createOperationalTopology()` composition factory

The core entry focuses on environment-neutral topology construction. Portfolio
records, page profiles, browser event controllers, Developer API registration,
and lab animations belong to their scoped entry points.

### Browser

```ts
import {
  createTopologyContentPageController,
  createSceneNavigationController,
} from "../src/framework/browser.ts";
```

`src/framework/browser.ts` owns DOM and interaction integration:

- selection events
- page navigation orchestration
- viewport and scene navigation controllers
- content-page controller
- same-SVG dataset transitions for replacing one topology with another
- development registration and `window.otf` support

Consumers that only need geometry, normalization, rendering preparation, or
server-side world construction should not import this entry. Browser consumers
that render an interactive scene should use this entry for DOM-bound controllers
and dataset transitions.

Dataset transitions use the existing scene SVG and preserve the canonical grid.
They are intentionally browser-scoped because they operate on live SVG DOM:

```ts
import {
  createTopologyDatasetTransition,
} from "operational-topology/browser";

const transition = createTopologyDatasetTransition({
  sceneGrid,
  cells,
  radius: 28,
  connectorRouting: "straight",
});

transition.setTransitionMode("fault-line");

await transition.transition({
  nodes,
  relationships,
});
```

The consumer owns dataset creation and Inspector updates. The transition
controller owns staging, ordered reveal, cancellation, and swapping the active
content layer without creating a second scene.

### Animations

```ts
import {
  ANIMATION_PRESETS,
  HEX_AXIAL_DIRECTIONS,
  getAxialRayCells,
  getBreathingFieldFrame,
  getCascadeTransitionFrame,
  getCenterSplitTransitionFrame,
  getConstellationFrame,
  getCenterBloomFrame,
  getEdgeCurrentFrame,
  getFaultLineFrame,
  getGhLogoFrame,
  getNetworkPulseFrame,
  getNetworkConvergeFrame,
  getOrbitalCurrentFrame,
  getRandomTelemetryFrame,
  getRadialSignalEndpoints,
  getRadialSignalFrame,
  getScatterTransitionFrame,
  getSystemResetTimeline,
  getSystemResetTransitionFrame,
  getSixWayBurstFrame,
} from "../src/framework/animations.ts";
```

`src/framework/animations.ts` contains reusable motion presets that are safe
for package consumers. It exposes the shared grid and GH logo animation
helpers without pulling in the demo page.

Navigation Transitions are a separate fourth animation family. They provide visual continuity across a host application page or route change without changing topology data or performing navigation. The host owns the route lifecycle:

```txt
flow(out) -> host changes route -> flow(in)
```

The 0.5.0 catalog includes `navigation.flow`, `navigation.converge`, `navigation.expand`, `navigation.originArrival`, and `navigation.nodeFlicker`. Its `phase` is explicit, and `direction` is deterministic: `forward` and `backward` use opposite axial projections.

```ts
import {
  NAVIGATION_ANIMATIONS,
  getNavigationFlowFrame,
  toGridCellStateMap,
} from "operational-topology/animations";

const states = getNavigationFlowFrame({
  cells,
  frame: elapsedMilliseconds,
  phase: "out",
  direction: "forward",
  duration: 240,
  intensity: 0.3,
});

const navigationFlow = NAVIGATION_ANIMATIONS.flow;
const cellStates = toGridCellStateMap(states);
```

Use the same `direction`, duration, and intensity for the complementary `in` phase. Navigation flow is non-destructive: it returns cell states only and does not remove occupants, replace datasets, or invoke Presentation Transitions.

For browser-rendered OTF scenes, import `createTopologySceneAnimationAdapter` from `operational-topology/browser`. It applies `navigation.flow` frames to the existing scene and provides occupant/connector layer visibility controls; it does not perform route changes or replace topology data.

The navigation family is intentionally separate from Signal Animations, Presentation Transitions, and Ambient Animations:

| Family | Cause | Responsibility |
| --- | --- | --- |
| Signal | A topology node was interacted with | Local/topology-aware response |
| Presentation | The displayed topology changes | Transition occupants and datasets |
| Ambient | Nothing specific changed | Keep the field quietly alive |
| Navigation | The host changes pages/routes | Bridge the application boundary without navigating |

Navigation semantics are capabilities, not route rules. The host selects `flow`, `converge`, `expand`, `originArrival`, or `nodeFlicker`; OTF does not inspect URLs, routers, links, browser history, or storage.

`breathingField` keeps every cell semantically idle while slowly varying
intensity across correlated axial regions:

```ts
const states = getBreathingFieldFrame({
  cells,
  frame: elapsedMilliseconds / 1000,
  seed: "operations-background",
  baseIntensity: 0.07,
  amplitude: 0.025,
  spatialScale: 0.42,
  speed: 0.55,
  excludedCellIds: occupiedCellIds,
});
```

Keep `amplitude` small for persistent backgrounds. `spatialScale` controls
the size of correlated regions, and `speed` controls how quickly those
regions drift through their breathing cycle. Excluded cells remain at a stable
low intensity.
Because the field changes slowly, rendering it at 12-15 FPS is usually
sufficient. CSS transitions can interpolate the visual updates without running
the topology calculation every display frame.
`constellation` activates one compact 2–5-cell subsystem at a time, then
returns to a quiet grid before selecting a distant center:

```ts
const states = getConstellationFrame({
  cells,
  frame: elapsedMilliseconds / 1000,
  seed: "operations-constellation",
  minClusterSize: 2,
  maxClusterSize: 5,
  interval: 5.8,
  minSourceDistance: 6,
  excludedCellIds: occupiedCellIds,
});
```

The center and immediate axial neighbors fade in with a short stagger, hold,
and fade together. Use `attack`, `hold`, `release`, and `stagger` to tune
that envelope. The distributed center sequence and cell index are cached, and a
15 FPS cadence is sufficient for continuous ambient use.

`orbitalCurrent` moves sparse signals around cached hex-distance rings. Adjacent
rings alternate direction and outer rings move slightly more slowly:

```ts
const states = getOrbitalCurrentFrame({
  cells,
  frame: elapsedMilliseconds / 1000,
  origin: { q: 0, r: 0 },
  seed: "operations-orbit",
  minRadius: 2,
  maxRadius: 6,
  ringStep: 2,
  signalsPerRing: 1,
  speed: 0.9,
  trail: 2,
  excludedCellIds: occupiedCellIds,
});
```

Keep `signalsPerRing` at one for persistent backgrounds. Ring membership and
clockwise ordering are cached. `ringStep: 2` leaves one inactive hex-distance
ring between each orbit. Each frame keeps a faint baseline around every orbit
and layers sparse heads and trails above it. A 12-15 FPS render cadence is
sufficient for the ambient version.

`edgeCurrent` traces the visible grid boundary once, caches that ordering, and
moves one to three sparse signal heads around it:

```ts
const states = getEdgeCurrentFrame({
  cells,
  frame: elapsedMilliseconds / 1000,
  seed: "operations-edge",
  signals: 2,
  speed: 1.1,
  trail: 3,
  excludedCellIds: occupiedCellIds,
});
```

Use one or two signals for persistent backgrounds. The perimeter keeps a faint
baseline so its direction remains legible, while excluded boundary cells remain
semantically idle. A 12-15 FPS cadence is sufficient.

`randomTelemetry` uses a deterministic event schedule rather than selecting
random cells every frame. Each event fades through signal, highlight, signal,
and idle phases:

```ts
const states = getRandomTelemetryFrame({
  cells,
  frame: elapsedMilliseconds / 1000,
  seed: "operations-telemetry",
  interval: 0.9,
  maxConcurrent: 2,
  minSourceDistance: 4,
  excludedCellIds: occupiedCellIds,
});
```

`interval` controls event spacing, `maxConcurrent` bounds overlap, and
`attack`, `hold`, and `release` tune the event envelope. Scheduled origins
rotate through a cached, spatially separated sequence, keeping activity sparse
and reproducible. A 12-15 FPS cadence is sufficient.

`networkPulse` uses a deterministic event scheduler rather than fixed repeating
origins:

```ts
const states = getNetworkPulseFrame({
  cells,
  frame,
  seed: "operations-background",
  maxConcurrent: 2,
  interval: 4,
  maxRadius: 3,
  minSourceDistance: 6,
  sourceHold: 1.25,
  excludedCellIds: occupiedCellIds,
});
```

`maxConcurrent` caps overlapping events. `interval` controls the spacing
between event starts, while `quiet` still influences the derived interval when
an explicit interval is omitted. `excludedCellIds` prevents both pulse origins
and wave states from covering occupied or text-bearing cells. The legacy
`pulses` option remains available as an alias for `maxConcurrent`.

`radialSignal` builds a deterministic center-origin awareness scan across twelve
hex-aligned radial endpoints. Odd and even endpoints alternate between inner and
outer distances, then signal in a seeded order before a synchronized confirmation
pulse and return to the center:

```ts
const states = getRadialSignalFrame({
  cells,
  origin: { q: 0, r: 0 },
  frame: elapsedMilliseconds,
  seed: "operations-scan",
  sequence: "random",
  synchronizedPulse: true,
  returnToCenter: true,
  settle: true,
});
```

Use the endpoint helper when a renderer needs the participating cells or connector
geometry. The helper preserves the point-top grid and the alternating radial
distance rule.

`sixWayBurst` emits one shared path pulse along each selected axial direction:

```ts
const states = getSixWayBurstFrame({
  cells,
  origin: { q: 0, r: 0 },
  frame: elapsedMilliseconds / 120,
  maxDistance: 6,
  trail: 2,
  directionIndexes: [0, 1, 2, 3, 4, 5],
  excludedCellIds: occupiedCellIds,
});
```

Direction indexes correspond to `HEX_AXIAL_DIRECTIONS`. Use
`getAxialRayCells()` when composing another effect from the same geometry.
Rays stop at the first missing or excluded cell, so they do not jump topology
gaps or occupied content. This is a framework primitive for composed motion;
it is intentionally not a standalone Animation Lab or transition selector.

`networkConverge` reverses those axial rays so scattered signals gather on a
target cell:

```ts
const states = getNetworkConvergeFrame({
  cells,
  origin: { q: target.q, r: target.r },
  progress,
  maxDistance: 10,
  trail: 2.4,
});
```

Use `createTopologyDatasetTransition()` with
`setTransitionMode("network-converge")` for slide transitions. The controller
targets the incoming root, then the selected or active node, then the first
node as a fallback. Signals render in a transient group inside the existing
scene SVG while outgoing and incoming layers overlap, so no embedded viewport
or black handoff frame is introduced.

`cascade` derives transition order from topology relationships instead of
grid position:

```ts
const frame = getCascadeTransitionFrame({
  nodes,
  relationships,
  progress,
  direction: "incoming",
});
```

Incoming frames reveal roots before their dependents; outgoing frames collapse
leaves before their parents. For deck transitions, use
`createTopologyDatasetTransition()` with `setTransitionMode("cascade")`. Nodes
scale within the existing scene layers, connectors follow endpoint visibility,
and cyclic or disconnected nodes receive deterministic fallback depths.

`scatter` and `assemble` are complementary directions of one spatial frame
primitive:

```ts
const frame = getScatterTransitionFrame({
  nodes,
  relationships,
  progress,
  direction: "scatter",
});
```

Use `direction: "assemble"` to reverse the motion. The frame returns normalized
outward offsets, scale, node opacity, and connector opacity. Deck transitions
use `setTransitionMode("scatter-assemble")` to overlap outgoing fragmentation
with incoming recomposition in the existing scene SVG.


`centerSplit` parts the outgoing topology across a vertical centerline and
reveals the incoming topology from the middle toward both edges:

```ts
const incoming = getCenterSplitTransitionFrame({
  nodes,
  relationships,
  progress,
  direction: "reveal",
});
```

Use `direction: "split"` for the outgoing half motion. The frame derives its
centerline from the axial horizontal projection `q + r / 2`, returns normalized
horizontal offsets, and fades connectors with their endpoints. Deck consumers
enable the overlapping sequence with `setTransitionMode("center-split")`.

`systemReset` is a deliberate shutdown/reboot sequence for special moments:

```ts
const timeline = getSystemResetTimeline(progress);
const outgoing = getSystemResetTransitionFrame({
  nodes,
  relationships,
  progress: timeline.shutdownProgress,
  direction: "shutdown",
});
```

The shutdown drops deterministic nodes before retaining and dimming one final
root. The timeline then provides a bounded offline interval before the incoming
topology boots in dependency order. Deck consumers enable the complete sequence
with `setTransitionMode("system-reset")`. Reduced-motion mode skips directly to
the online scene.

`faultLine` is the axial state-replacement primitive used by scene transitions.
Its incoming and outgoing frames are complementary masks:

```ts
const incoming = getFaultLineFrame({
  cells,
  progress,
  axis: "q+r",
  direction: 1,
  trail: 0.8,
  mode: "incoming",
});

const outgoing = getFaultLineFrame({
  cells,
  progress,
  axis: "q+r",
  direction: 1,
  trail: 0.8,
  mode: "outgoing",
});
```

For presentation and page navigation, prefer
`createTopologyDatasetTransition()` with `setTransitionMode("fault-line")`.
The browser controller applies both masks to the existing scene SVG so nodes,
connectors, and boundaries are replaced together without a global crossfade.
Fault Line is available in the Presentation Simulator and Transition Lab, not
the ambient Animation Lab.

### Labs

```ts
import {
  getCenterBloomFrame,
  getGhLogoFrame,
} from "../src/framework/labs.ts";
```

`src/framework/labs.ts` remains a compatibility alias for the animation
helpers plus motion utilities.

### Presets

```ts
import {
  TOPOLOGY_SCENE_PRESETS,
  createTopologyScenePreset,
} from "../src/framework/presets.ts";
```

`src/framework/presets.ts` contains reusable scene presets and template
definitions for application shells, intro scenes, main site scenes, and page
families that share camera, minimap, and signal defaults.

Labs support experiments, demos, and animation testing. Presets provide
reusable templates that production pages can compose.

Presets should be exportable without dragging in animation-only fixtures.

For a one-page element map, see [OTF Elements Cheat Sheet](./OTF_ELEMENTS_CHEATSHEET.md).

### Presentations

Presentation data can be defined independently from the page that renders it:

```ts
import {
  createPresentationDeck,
  createPresentationSlides,
} from "operational-topology";

const deck = createPresentationDeck({
  id: "architecture-deck",
  title: "Architecture Deck",
  defaultSlideId: "architecture",
  sceneLayout: "world-grid",
  topologyLayout: "ring",
  slides: [
    {
      id: "architecture",
      title: "System Architecture",
      subtitle: "Services and dependencies",
      summary: "A presentation slide with an interactive topology.",
      status: "ready",
      route: "/system-architecture",
      role: "architecture",
      anchors: [
        {
          id: "edge",
          label: "Edge",
          children: [{ id: "gateway", label: "Gateway" }],
        },
        {
          id: "application",
          label: "Application",
          children: [
            { id: "api", label: "API" },
            { id: "services", label: "Services" },
          ],
        },
        {
          id: "data",
          label: "Data",
          children: [{ id: "database", label: "Database" }],
        },
      ],
    },
  ],
});

const slides = createPresentationSlides(deck);
```

Each slide contains a reusable `TopologyDataset` and Inspector records. A
presentation page can pass the datasets to
`createTopologyDatasetTransition()` and control the sequence independently.

The current topology layouts are:

- `ring` - root-centered radial topology for contextual maps
- `linear` - left-to-right anchor chain with vertically aligned child branches
- `fishspine` - left-to-right anchor chain with alternating upper and lower child branches
- `radial-sectors` - centered layout with exclusive domain sectors

For a step-by-step first presentation deck, see [Creating Your First OTF Presentation](./FRAMEWORK_API_HELLO_WORLD_DECK.md).
For a quick entry point, see [OTF Elements Cheat Sheet](./OTF_ELEMENTS_CHEATSHEET.md).

Scene layouts:

- `viewport-fit` - fit the operational world to the viewport
- `world-grid` - render the world over a larger grid-backed scene

Astro applications can author slide definitions in a Markdown collection and
map the validated frontmatter to `PresentationSlideDefinition`. The sample
application uses `src/content/presentations/` for this purpose. The collection
owns authored titles, summaries, routes, roles, anchors, and child labels;
rendering and transition behavior remain framework responsibilities.

## Composition Factory

`createOperationalTopology()` creates one coherent runtime from a declarative
definition.

```ts
import { createOperationalTopology } from "../src/framework/index.ts";

const topology = createOperationalTopology({
  grid: {
    radius: 28,
    columns: 12,
    rows: 10,
    originQ: -6,
    originR: -5,
  },
  entities: [
    {
      id: "root",
      label: "Root",
      q: 0,
      r: 0,
      variant: "root",
    },
    {
      id: "journal",
      label: "Journal",
      q: 3,
      r: 2,
      variant: "anchor",
    },
  ],
  relationships: [
    {
      from: "root",
      to: "journal",
      kind: "parent",
    },
  ],
  signal: {
    transitionSpeed: 1.35,
  },
});
```

The returned runtime exposes:

```ts
topology.model
topology.world
topology.repository
topology.signalPolicy
topology.getEntity(id)
topology.getRelationshipContext(id)
topology.createRenderFrame(options)
```

This keeps geometry, normalized knowledge, semantic relationships, signals, and
render preparation aligned around the same definition.

## Definition Validation

The factory rejects:

- non-positive radius
- non-positive or non-integer rows and columns
- duplicate entity identifiers
- relationships that reference missing entities

Definitions may be checked without creating a runtime:

```ts
const issues = inspectOperationalTopologyDefinition(definition);
```

Validation is intentionally structural. Domain-specific content validation
remains the responsibility of the application or its content collection schema.

## Application Boundary

Application-owned modules remain outside the public core:

```txt
src/config/topologyPageProfiles.ts
src/topology/siteKnowledge.ts
src/topology/worldMapRecords.ts
src/content/
src/pages/
```

Page profiles may compose reusable framework defaults, but the framework does
not know about `home`, `lab`, `worldMap`, personal records, or demonstration
routes.

## Compatibility

`src/topology/index.ts` remains as a backward-compatible aggregate for existing
code. New code should use one of the scoped framework entry points so its runtime
and dependency requirements are explicit.

Astro components now consume the public core entry for shared model and geometry
contracts. Existing implementation modules remain in `src/topology/` to avoid a
high-risk physical move while the API boundary stabilizes.

## Package Readiness

The package has published core, browser, labs, and presets entry points. The
browser entry now includes the dataset transition contract, so external browser
consumers can use the same scene-swapping capability as the application.

Remaining release work is limited to normal API evolution:

- keep browser and core entry-point exports covered by boundary tests
- exercise new contracts in an external consumer fixture
- preserve the documented semantic-versioning policy for future releases

Framework extraction does not require changing canonical axial coordinates,
world behavior, or renderer semantics.

## Transition Lifecycle

Use createTransitionLifecycle when the host application needs a consistent visual sequence around a page or route change. OTF owns the ordering; the host owns navigation and supplies the concrete render callbacks.

```ts
import { createTransitionLifecycle } from "operational-topology";

const lifecycle = createTransitionLifecycle({
  playNavigation: (phase) => renderNavigationFlow(phase),
  playPresentation: (phase) => renderPresentationHandoff(phase),
  setAmbientEnabled: (enabled) => ambient.setEnabled(enabled),
  setSignalsEnabled: (enabled) => signals.setEnabled(enabled),
  setOccupantsVisible: (visible) => occupants.setVisible(visible),
});

await lifecycle.exit();
await hostNavigate();
await lifecycle.enter();
```

The default exit sequence is: disable signals, yield ambient activity, Presentation OUT, Navigation OUT. The default entrance sequence is: hide occupants, keep activity paused, Navigation IN, Presentation IN, reveal occupants, resume ambient activity, enable signals. The coordinator never reads URLs, routes, or topology datasets.
