@almadar/core 7.2.0 → 7.4.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.
@@ -1,4 +1,4 @@
1
- import { S as SExpr } from '../expression-eBO9-SQM.js';
1
+ import { b as EventPayload, S as SExpr } from '../expression-eBO9-SQM.js';
2
2
  import 'zod';
3
3
 
4
4
  /**
@@ -40,7 +40,7 @@ interface ReplayStep {
40
40
  /** True if this step requires entity rows to be visible before clicking */
41
41
  needsEntityData: boolean;
42
42
  /** Payload to supply for this step (derived from guard pass case if guarded) */
43
- guardPayload?: Record<string, unknown>;
43
+ guardPayload?: EventPayload;
44
44
  /** Full payload schema for mock data generation */
45
45
  payloadSchema?: PayloadFieldSchema[];
46
46
  }
@@ -52,8 +52,8 @@ interface PayloadFieldSchema {
52
52
  }
53
53
  /** Pass and fail payloads derived from a guard s-expression */
54
54
  interface GuardPayload {
55
- pass: Record<string, unknown>;
56
- fail: Record<string, unknown>;
55
+ pass: EventPayload;
56
+ fail: EventPayload;
57
57
  }
58
58
  /**
59
59
  * Minimal transition interface for graph algorithms.
@@ -107,7 +107,7 @@ interface WalkStep {
107
107
  /** Guard branch: null for unguarded, 'pass' or 'fail' for guarded */
108
108
  guardCase: 'pass' | 'fail' | null;
109
109
  /** Payload to send with the event */
110
- payload: Record<string, unknown>;
110
+ payload: EventPayload;
111
111
  /** True if this step is a repositioning step (navigating to reach a source state with uncovered edges) */
112
112
  isRepositioning: boolean;
113
113
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/state-machine/graph.ts","../../src/state-machine/bfs.ts","../../src/state-machine/guard-payloads.ts","../../src/state-machine/replay-paths.ts","../../src/state-machine/edge-walk.ts"],"names":[],"mappings":";AA2BO,SAAS,gBACd,WAAA,EAC0B;AAC1B,EAAA,MAAM,KAAA,uBAAY,GAAA,EAAyB;AAC3C,EAAA,KAAA,MAAW,KAAK,WAAA,EAAa;AAC3B,IAAA,IAAI,CAAA,CAAE,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AAI,CAAA,GAAI,CAAA;AAAA,MACxB,CAAA,MAAA,IAAW,KAAA,CAAM,IAAA,KAAS,SAAA,EAAW;AACnC,QAAA,OAAA,CAAQ,KAAA,CAAM,IAAI,CAAA,GAAI,IAAA;AAAA,MACxB,WAAW,KAAA,CAAM,IAAA,KAAS,QAAA,IAAY,KAAA,CAAM,SAAS,KAAA,EAAO;AAQ1D,QAAA,OAAA,CAAQ,KAAA,CAAM,IAAI,CAAA,GAAI,EAAC;AAAA,MACzB,CAAA,MAAO;AACL,QAAA,OAAA,CAAQ,KAAA,CAAM,IAAI,CAAA,GAAI,CAAA,KAAA,EAAQ,MAAM,IAAI,CAAA,CAAA;AAAA,MAC1C;AAAA,IACF;AACA,IAAA,OAAO,OAAA;AAAA,EACT;AAEA,EAAA,OAAO,EAAC;AACV","file":"index.js","sourcesContent":["/**\n * State Graph Construction\n *\n * Build an adjacency list from state machine transitions.\n * Extracted from orbital-verify-unified/src/analyze.ts.\n *\n * @packageDocumentation\n */\n\nimport type { GraphTransition, StateEdge } from './types.js';\n\n/**\n * Builds an adjacency list from state machine transitions.\n * \n * Constructs a state transition graph where each state maps to an array\n * of outgoing edges (events and target states). Wildcard transitions\n * (from === '*') are excluded since they don't represent fixed edges.\n * Used as the foundation for state machine analysis, traversal, and verification.\n * \n * @param {GraphTransition[]} transitions - Array of state transitions\n * @returns {Map<string, StateEdge[]>} State transition graph\n * \n * @example\n * const graph = buildStateGraph(transitions);\n * const edgesFromInitial = graph.get('initial'); // Array of outgoing edges\n * console.log(`Initial state has ${edgesFromInitial?.length} transitions`);\n */\nexport function buildStateGraph(\n transitions: GraphTransition[]\n): Map<string, StateEdge[]> {\n const graph = new Map<string, StateEdge[]>();\n for (const t of transitions) {\n if (t.from === '*') continue;\n if (!graph.has(t.from)) graph.set(t.from, []);\n graph.get(t.from)!.push({ event: t.event, to: t.to });\n }\n return graph;\n}\n","/**\n * BFS Reachability Algorithms\n *\n * Breadth-first search over state machine graphs.\n * Extracted from orbital-verify-unified/src/analyze.ts and phase3-server.ts.\n *\n * @packageDocumentation\n */\n\nimport type { BFSNode, StateEdge } from './types.js';\nimport { buildStateGraph } from './graph.js';\nimport type { GraphTransition } from './types.js';\n\n/**\n * Collects all reachable states from an initial state using breadth-first search.\n * \n * Performs BFS traversal of the state machine to find all states reachable\n * from the initial state, up to the specified maximum depth. Used for\n * state machine analysis, verification, and test coverage assessment.\n * \n * @param {GraphTransition[]} transitions - Array of state transitions\n * @param {string} initialState - Starting state name\n * @param {number} [maxDepth=5] - Maximum search depth\n * @returns {Set<string>} Set of reachable state names\n * \n * @example\n * const reachable = collectReachableStates(transitions, 'initial', 10);\n * console.log('Reachable states:', Array.from(reachable));\n */\nexport function collectReachableStates(\n transitions: GraphTransition[],\n initialState: string,\n maxDepth = 5\n): Set<string> {\n const graph = buildStateGraph(transitions);\n const visited = new Set<string>([initialState]);\n const queue: BFSNode[] = [{ state: initialState, depth: 0 }];\n\n while (queue.length > 0) {\n const current = queue.shift()!;\n if (current.depth >= maxDepth) continue;\n\n const edges = graph.get(current.state) ?? [];\n for (const edge of edges) {\n if (!visited.has(edge.to)) {\n visited.add(edge.to);\n queue.push({ state: edge.to, depth: current.depth + 1 });\n }\n }\n }\n\n return visited;\n}\n\n/**\n * Walks all reachable (state, event) pairs using BFS and invokes callback for each.\n * \n * Traverses the state machine using breadth-first search and calls the visitor\n * function for each (state, edge) pair encountered. Used by server verification\n * to test transitions by POSTing to endpoints and checking responses.\n * \n * @param {GraphTransition[]} transitions - Array of state transitions\n * @param {string} initialState - Starting state name\n * @param {number} maxDepth - Maximum BFS depth\n * @param {(state: string, edge: StateEdge, depth: number) => Promise<boolean>} visitor - Callback for each pair\n * @returns {Promise<{ visitedPairs: Set<string>; walkedEdges: number }>} Traversal statistics\n * \n * @example\n * const result = await walkStatePairs(transitions, 'initial', 5, async (state, edge) => {\n * console.log(`Transition: ${state} --${edge.event}--> ${edge.to}`);\n * return true; // Continue exploration\n * });\n * console.log(`Visited ${result.visitedPairs.size} state-event pairs`);\n */\nexport async function walkStatePairs(\n transitions: GraphTransition[],\n initialState: string,\n maxDepth: number,\n visitor: (state: string, edge: StateEdge, depth: number) => Promise<boolean>\n): Promise<{ visitedPairs: Set<string>; walkedEdges: number }> {\n const graph = buildStateGraph(transitions);\n const visitedPairs = new Set<string>();\n const queue: BFSNode[] = [{ state: initialState, depth: 0 }];\n let walkedEdges = 0;\n\n while (queue.length > 0) {\n const current = queue.shift()!;\n if (current.depth >= maxDepth) continue;\n\n const edges = graph.get(current.state) ?? [];\n for (const edge of edges) {\n const pairKey = `${current.state}:${edge.event}`;\n if (visitedPairs.has(pairKey)) continue;\n visitedPairs.add(pairKey);\n\n const shouldEnqueue = await visitor(current.state, edge, current.depth);\n walkedEdges++;\n\n if (shouldEnqueue) {\n const stateVisited = [...visitedPairs].some((k) => k.startsWith(`${edge.to}:`));\n if (!stateVisited) {\n queue.push({ state: edge.to, depth: current.depth + 1 });\n }\n }\n }\n }\n\n return { visitedPairs, walkedEdges };\n}\n","/**\n * Guard Payload Builder\n *\n * Derive pass and fail payloads from guard s-expressions.\n * Extracted from orbital-verify-unified/src/analyze.ts.\n *\n * @packageDocumentation\n */\n\nimport type { GuardPayload } from './types.js';\n\n/**\n * Extracts the first segment of a payload field reference.\n * \n * Parses binding references in the format \"@payload.field\" and extracts\n * the first field name segment. Used for identifying payload fields in\n * guard conditions for test data generation.\n * \n * @param {unknown} ref - Binding reference to extract from\n * @returns {string | null} First field segment or null for non-payload references\n * \n * @example\n * extractPayloadFieldRef('@payload.item'); // returns 'item'\n * extractPayloadFieldRef('@payload.data.weight'); // returns 'data'\n * extractPayloadFieldRef('@entity.id'); // returns null\n * extractPayloadFieldRef('@user.name'); // returns null\n */\nexport function extractPayloadFieldRef(ref: unknown): string | null {\n if (typeof ref !== 'string') return null;\n const match = ref.match(/^@payload\\.([A-Za-z0-9_]+)/);\n return match ? match[1] : null;\n}\n\n/**\n * Builds test payloads that satisfy or violate guard conditions.\n * \n * Generates pass/fail test data for guard s-expressions used in state machine\n * transitions. Pass payloads satisfy the guard condition (allowing transition),\n * fail payloads violate it (blocking transition). Used for automated testing\n * and validation of state machine behavior.\n * \n * Supports operators: not-nil, nil, eq, not-eq, gt, gte, lt, lte, and, or, not\n * \n * @param {unknown} guard - Guard s-expression to analyze\n * @returns {GuardPayload} Object with pass and fail payloads\n * \n * @example\n * // Guard: ['not-nil', '@payload.completed']\n * buildGuardPayloads(['not-nil', '@payload.completed']);\n * // Returns: { pass: { completed: 'mock-test-value' }, fail: { completed: null } }\n * \n * @example\n * // Guard: ['eq', '@payload.status', 'active']\n * buildGuardPayloads(['eq', '@payload.status', 'active']);\n * // Returns: { pass: { status: 'active' }, fail: { status: 'not-active' } }\n * \n * @example\n * // Guard: ['and', ['not-nil', '@payload.id'], ['eq', '@payload.status', 'ready']]\n * buildGuardPayloads(['and', ['not-nil', '@payload.id'], ['eq', '@payload.status', 'ready']]);\n * // Returns: { pass: { id: 'mock-test-value', status: 'ready' }, fail: { id: null } }\n */\nexport function buildGuardPayloads(guard: unknown): GuardPayload {\n // Bare-binding existence guard: e.g. `when @payload.row` lowers to\n // the string `\"@payload.row\"`. The transition fires iff that field is\n // truthy. Synthesize pass with a truthy mock and fail with null so\n // the verifier can drive both branches. Without this, std-confirmation\n // and std-modal's existence guards (REQUEST/EDIT requiring @payload.row)\n // get empty payloads in both cases — the pass case then fails the\n // server-side guard and the portal observer flags \"slot not mounted\".\n if (typeof guard === 'string') {\n const field = extractPayloadFieldRef(guard);\n if (field) return { pass: { [field]: { id: 'mock-test-id', name: 'mock-test-name' } }, fail: { [field]: null } };\n }\n\n if (!Array.isArray(guard) || guard.length === 0) {\n return { pass: {}, fail: {} };\n }\n\n const op = String(guard[0]);\n\n if (op === 'not-nil' || op === 'not_nil') {\n const field = extractPayloadFieldRef(guard[1]);\n if (field) return { pass: { [field]: 'mock-test-value' }, fail: { [field]: null } };\n }\n\n if (op === 'nil') {\n const field = extractPayloadFieldRef(guard[1]);\n if (field) return { pass: {}, fail: { [field]: 'mock-test-value' } };\n }\n\n if (op === 'eq' || op === '==' || op === '=') {\n const field = extractPayloadFieldRef(guard[1]);\n const val = guard[2];\n if (field && val !== undefined) {\n const failVal =\n typeof val === 'number' ? val + 1\n : typeof val === 'string' ? `not-${val}`\n : null;\n return { pass: { [field]: val }, fail: { [field]: failVal } };\n }\n }\n\n if (op === 'not-eq' || op === '!=' || op === 'neq') {\n const field = extractPayloadFieldRef(guard[1]);\n const val = guard[2];\n if (field && val !== undefined) {\n const passVal =\n typeof val === 'number' ? val + 1\n : typeof val === 'string' ? `not-${val}`\n : 'other';\n return { pass: { [field]: passVal }, fail: { [field]: val } };\n }\n }\n\n if (op === 'gt' || op === '>') {\n const field = extractPayloadFieldRef(guard[1]);\n const n = typeof guard[2] === 'number' ? guard[2] : 0;\n if (field) return { pass: { [field]: n + 1 }, fail: { [field]: n - 1 } };\n }\n\n if (op === 'gte' || op === '>=') {\n const field = extractPayloadFieldRef(guard[1]);\n const n = typeof guard[2] === 'number' ? guard[2] : 0;\n if (field) return { pass: { [field]: n }, fail: { [field]: n - 1 } };\n }\n\n if (op === 'lt' || op === '<') {\n const field = extractPayloadFieldRef(guard[1]);\n const n = typeof guard[2] === 'number' ? guard[2] : 0;\n if (field) return { pass: { [field]: n - 1 }, fail: { [field]: n + 1 } };\n }\n\n if (op === 'lte' || op === '<=') {\n const field = extractPayloadFieldRef(guard[1]);\n const n = typeof guard[2] === 'number' ? guard[2] : 0;\n if (field) return { pass: { [field]: n }, fail: { [field]: n + 1 } };\n }\n\n if (op === 'and') {\n const subs = (guard.slice(1) as unknown[]).filter(Array.isArray);\n if (subs.length >= 2) {\n const s1 = buildGuardPayloads(subs[0]);\n const s2 = buildGuardPayloads(subs[1]);\n return { pass: { ...s1.pass, ...s2.pass }, fail: s1.fail };\n }\n if (subs.length === 1) return buildGuardPayloads(subs[0]);\n }\n\n if (op === 'or') {\n // Accept BOTH array sub-guards and bare-binding string sub-guards\n // (post-substitution mode-aware guards like\n // `(or (= \"edit\" \"create\") \"@payload.row\")` mix array + string children).\n const subs = guard.slice(1) as unknown[];\n if (subs.length >= 2) {\n const s1 = buildGuardPayloads(subs[0]);\n const s2 = buildGuardPayloads(subs[1]);\n // For OR: pass if EITHER branch passes. Prefer the second branch's\n // pass payload if the first yields nothing useful — the literal-fold\n // case `(= \"edit\" \"create\") || @payload.row` has the first branch\n // return `{}` and the row-payload comes from the second.\n const combinedPass = Object.keys(s1.pass).length > 0 ? s1.pass : s2.pass;\n return { pass: combinedPass, fail: { ...s1.fail, ...s2.fail } };\n }\n if (subs.length === 1) return buildGuardPayloads(subs[0]);\n }\n\n if (op === 'not') {\n const inner = buildGuardPayloads(guard[1]);\n return { pass: inner.fail, fail: inner.pass };\n }\n\n // Agent pure operators used in guards\n if (op === 'agent/is-pinned') {\n const field = extractPayloadFieldRef(guard[1]);\n if (field) return { pass: { [field]: 'mem_test_unpinned' }, fail: { [field]: 'mem_test_pinned' } };\n }\n\n if (op === 'agent/memory-strength') {\n const field = extractPayloadFieldRef(guard[1]);\n if (field) return { pass: { [field]: 'mem_test_id' }, fail: { [field]: 'mem_nonexistent' } };\n }\n\n // Agent operators in comparison contexts (e.g., [\">=\", [\"agent/context-usage\"], 0.85])\n // These don't use @payload, they query agent state directly. Return empty payloads\n // since the guard result depends on agent context, not event payload.\n if (op.startsWith('agent/')) {\n return { pass: {}, fail: {} };\n }\n\n return { pass: {}, fail: {} };\n}\n","/**\n * Replay Path Builder\n *\n * Compute the shortest path (replay steps) from an initial state\n * to every reachable state in a state machine. Used by browser\n * verification to navigate through states before running assertions.\n *\n * Extracted from orbital-verify-unified/src/analyze.ts (collectDataMutationTests).\n *\n * @packageDocumentation\n */\n\nimport type { GraphTransition, ReplayStep, PayloadFieldSchema } from './types.js';\n\n/** Entity-data sentinel payload fields: presence means transition needs a selected row */\nconst ENTITY_PAYLOAD_FIELDS = new Set(['data', 'row', 'item', 'id']);\n\n/**\n * Extended transition with render and payload info needed for replay path building.\n * Compatible with orbital-verify's UnifiedTransition.\n */\nexport interface ReplayTransition extends GraphTransition {\n hasGuard: boolean;\n guard?: unknown[];\n payloadFields: string[];\n payloadSchema: PayloadFieldSchema[];\n renderEffects: Array<{\n slot: string;\n patternType: string | null;\n }>;\n}\n\n/**\n * Builds the shortest replay paths from initial state to all reachable states.\n * \n * Computes step-by-step navigation paths for state machine testing and verification.\n * Uses breadth-first search to find shortest paths up to specified depth limit.\n * Each path contains replay steps with event, state, and payload information\n * needed to reproduce state transitions in tests.\n * \n * @param {ReplayTransition[]} transitions - Transitions with render/payload information\n * @param {string} initialState - Starting state name\n * @param {number} [maxDepth=3] - Maximum path length (default: 3)\n * @returns {Map<string, ReplayStep[]>} Map of state names to replay step arrays\n * \n * @example\n * // Build paths from 'initial' state\n * const paths = buildReplayPaths(transitions, 'initial', 5);\n * \n * // Get steps to reach 'completed' state\n * const stepsToComplete = paths.get('completed');\n * \n * // Execute replay steps\n * for (const step of stepsToComplete) {\n * await dispatchEvent(step.event, step.payload);\n * }\n */\nexport function buildReplayPaths(\n transitions: ReplayTransition[],\n initialState: string,\n maxDepth = 3\n): Map<string, ReplayStep[]> {\n type QueueNode = { state: string; path: ReplayStep[] };\n\n const queue: QueueNode[] = [{ state: initialState, path: [] }];\n const replayPaths = new Map<string, ReplayStep[]>();\n replayPaths.set(initialState, []);\n\n while (queue.length > 0) {\n const { state, path } = queue.shift()!;\n if (path.length >= maxDepth) continue;\n\n const fromHere = transitions.filter(\n (t) => t.from === state && t.event !== 'INIT',\n );\n\n for (const transition of fromHere) {\n if (replayPaths.has(transition.to)) continue;\n\n const renderEffect = transition.renderEffects.find((re) => re.patternType !== null);\n const stepNeedsEntityData =\n transition.hasGuard ||\n transition.payloadFields.some((f) => ENTITY_PAYLOAD_FIELDS.has(f));\n\n const step: ReplayStep = {\n event: transition.event,\n fromState: state,\n toState: transition.to,\n slot: renderEffect?.slot ?? 'main',\n expectedPattern: renderEffect?.patternType ?? undefined,\n needsEntityData: stepNeedsEntityData,\n payloadSchema: transition.payloadSchema.length > 0 ? transition.payloadSchema : undefined,\n };\n\n const newPath = [...path, step];\n replayPaths.set(transition.to, newPath);\n queue.push({ state: transition.to, path: newPath });\n }\n }\n\n return replayPaths;\n}\n","/**\n * Edge-Covering Walk Algorithm\n *\n * Computes an ordered sequence of events (WalkStep[]) that covers every\n * transition (edge) in a state machine graph at least once. This guarantees\n * 100% transition coverage regardless of graph topology.\n *\n * Algorithm:\n * 1. Build adjacency list and edge universe (guarded transitions produce two edges)\n * 2. Precompute BFS shortest paths between all state pairs (for repositioning)\n * 3. Greedy DFS: at each state, prefer uncovered outgoing edges\n * 4. When stuck, insert repositioning steps to nearest state with uncovered edges\n * 5. Guard-fail steps don't advance state (guard blocks transition)\n *\n * Used by StateWalkEngine in @almadar-io/verify. Both orbital-verify and\n * runtime-verify share this algorithm for consistent coverage.\n *\n * @packageDocumentation\n */\n\nimport type { EdgeWalkTransition, WalkStep, StateEdge } from './types.js';\nimport { buildGuardPayloads } from './guard-payloads.js';\n\n/**\n * Build an ordered walk that covers every edge in the state machine.\n *\n * @param transitions - All transitions in the state machine\n * @param initialState - Starting state\n * @returns Ordered walk steps covering every edge\n */\nexport function buildEdgeCoveringWalk(\n transitions: EdgeWalkTransition[],\n initialState: string,\n): WalkStep[] {\n // 1. Build adjacency list. Skip wildcards (pseudostates) and skip the\n // boot INIT (the runtime auto-fires INIT from the initial state on\n // mount, so the walker doesn't need to fire it). User-triggered INITs\n // from non-initial states (refresh, retry) ARE walkable edges and\n // stay in the graph so coverage can reach them.\n const filtered = transitions.filter(\n (t) => t.from !== '*' && !(t.event === 'INIT' && t.from === initialState),\n );\n\n const graph = new Map<string, Array<{ event: string; to: string; transition: EdgeWalkTransition }>>();\n const allStates = new Set<string>();\n\n for (const t of filtered) {\n allStates.add(t.from);\n allStates.add(t.to);\n if (!graph.has(t.from)) graph.set(t.from, []);\n graph.get(t.from)!.push({ event: t.event, to: t.to, transition: t });\n }\n\n // Ensure initial state is in the set\n allStates.add(initialState);\n\n // 2. Build edge universe. Guarded transitions produce pass + fail edges.\n const uncovered = new Set<string>();\n const edgeMeta = new Map<string, { transition: EdgeWalkTransition; guardCase: 'pass' | 'fail' | null }>();\n\n for (const t of filtered) {\n if (t.hasGuard) {\n const keyPass = `${t.from}+${t.event}->${t.to}[pass]`;\n const keyFail = `${t.from}+${t.event}->${t.to}[fail]`;\n uncovered.add(keyPass);\n uncovered.add(keyFail);\n edgeMeta.set(keyPass, { transition: t, guardCase: 'pass' });\n edgeMeta.set(keyFail, { transition: t, guardCase: 'fail' });\n } else {\n const key = `${t.from}+${t.event}->${t.to}`;\n uncovered.add(key);\n edgeMeta.set(key, { transition: t, guardCase: null });\n }\n }\n\n if (uncovered.size === 0) return [];\n\n // 3. Precompute BFS shortest paths between all state pairs\n const shortestPaths = new Map<string, Map<string, Array<{ event: string; to: string }>>>();\n for (const state of allStates) {\n shortestPaths.set(state, bfsShortestPaths(state, graph));\n }\n\n // 4. Greedy walk\n const walk: WalkStep[] = [];\n let currentState = initialState;\n const maxIterations = uncovered.size * allStates.size * 2; // safety bound\n let iterations = 0;\n\n while (uncovered.size > 0 && iterations < maxIterations) {\n iterations++;\n\n // Find uncovered edges from currentState\n const outgoing = findUncoveredEdges(currentState, graph, uncovered);\n\n if (outgoing.length > 0) {\n // Pick first uncovered edge\n const pick = outgoing[0];\n const payload = buildPayloadForEdge(pick.transition, pick.guardCase);\n\n walk.push({\n from: currentState,\n event: pick.transition.event,\n to: pick.transition.to,\n guardCase: pick.guardCase,\n payload,\n isRepositioning: false,\n });\n\n uncovered.delete(pick.key);\n\n // Guard-fail doesn't advance state\n if (pick.guardCase !== 'fail') {\n currentState = pick.transition.to;\n }\n } else {\n // Stuck: find nearest state with uncovered edges\n const target = findNearestUncoveredState(currentState, graph, uncovered, shortestPaths);\n\n if (!target) {\n // No reachable state with uncovered edges. Remaining edges are unreachable.\n break;\n }\n\n // Insert repositioning steps\n const repoPath = shortestPaths.get(currentState)?.get(target);\n if (!repoPath || repoPath.length === 0) break;\n\n for (const step of repoPath) {\n walk.push({\n from: currentState,\n event: step.event,\n to: step.to,\n guardCase: null,\n payload: {},\n isRepositioning: true,\n });\n currentState = step.to;\n }\n }\n }\n\n return walk;\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\n/**\n * BFS from a source state, returning shortest paths to all reachable states.\n * Each path is an array of {event, to} steps.\n */\nfunction bfsShortestPaths(\n source: string,\n graph: Map<string, Array<{ event: string; to: string; transition: EdgeWalkTransition }>>,\n): Map<string, Array<{ event: string; to: string }>> {\n const paths = new Map<string, Array<{ event: string; to: string }>>();\n const visited = new Set<string>([source]);\n const queue: Array<{ state: string; path: Array<{ event: string; to: string }> }> = [\n { state: source, path: [] },\n ];\n\n while (queue.length > 0) {\n const { state, path } = queue.shift()!;\n const edges = graph.get(state) ?? [];\n\n for (const edge of edges) {\n if (visited.has(edge.to)) continue;\n visited.add(edge.to);\n const newPath = [...path, { event: edge.event, to: edge.to }];\n paths.set(edge.to, newPath);\n queue.push({ state: edge.to, path: newPath });\n }\n }\n\n return paths;\n}\n\n/**\n * Find uncovered edges from a given state.\n */\nfunction findUncoveredEdges(\n state: string,\n graph: Map<string, Array<{ event: string; to: string; transition: EdgeWalkTransition }>>,\n uncovered: Set<string>,\n): Array<{ key: string; transition: EdgeWalkTransition; guardCase: 'pass' | 'fail' | null }> {\n const edges = graph.get(state) ?? [];\n const result: Array<{ key: string; transition: EdgeWalkTransition; guardCase: 'pass' | 'fail' | null }> = [];\n\n for (const edge of edges) {\n if (edge.transition.hasGuard) {\n const keyPass = `${state}+${edge.event}->${edge.to}[pass]`;\n const keyFail = `${state}+${edge.event}->${edge.to}[fail]`;\n // Prefer pass first (advances state), then fail\n if (uncovered.has(keyPass)) {\n result.push({ key: keyPass, transition: edge.transition, guardCase: 'pass' });\n }\n if (uncovered.has(keyFail)) {\n result.push({ key: keyFail, transition: edge.transition, guardCase: 'fail' });\n }\n } else {\n const key = `${state}+${edge.event}->${edge.to}`;\n if (uncovered.has(key)) {\n result.push({ key, transition: edge.transition, guardCase: null });\n }\n }\n }\n\n return result;\n}\n\n/**\n * Find the nearest state (from currentState) that has uncovered outgoing edges.\n */\nfunction findNearestUncoveredState(\n currentState: string,\n graph: Map<string, Array<{ event: string; to: string; transition: EdgeWalkTransition }>>,\n uncovered: Set<string>,\n shortestPaths: Map<string, Map<string, Array<{ event: string; to: string }>>>,\n): string | null {\n // Collect states that have uncovered edges\n const statesWithUncovered = new Set<string>();\n for (const key of uncovered) {\n // Key format: \"state+EVENT->target\" or \"state+EVENT->target[pass]\"\n const fromState = key.split('+')[0];\n statesWithUncovered.add(fromState);\n }\n\n // If current state has uncovered edges, return it (shouldn't happen, but handle it)\n if (statesWithUncovered.has(currentState)) return currentState;\n\n // Find nearest reachable state with uncovered edges\n const paths = shortestPaths.get(currentState);\n if (!paths) return null;\n\n let nearestState: string | null = null;\n let nearestDist = Infinity;\n\n for (const target of statesWithUncovered) {\n const path = paths.get(target);\n if (path && path.length < nearestDist) {\n nearestDist = path.length;\n nearestState = target;\n }\n }\n\n return nearestState;\n}\n\n/**\n * Build a payload for a given edge based on its guard case and payload schema.\n * For guarded transitions, uses guard expressions to generate pass/fail payloads.\n * For unguarded transitions with payload schemas (e.g., EDIT/VIEW with { id }),\n * generates mock values so fetch-by-ID effects can resolve entity data.\n */\nfunction buildPayloadForEdge(\n transition: EdgeWalkTransition,\n guardCase: 'pass' | 'fail' | null,\n// eslint-disable-next-line almadar/no-record-string-unknown -- Payloads are dynamically typed per event schema\n): Record<string, unknown> {\n // Guard-based payload generation (existing behavior)\n if (transition.hasGuard && transition.guard && guardCase) {\n const payloads = buildGuardPayloads(transition.guard);\n return guardCase === 'pass' ? payloads.pass : payloads.fail;\n }\n\n // Schema-based payload generation for events that declare required fields\n // (e.g., EDIT/VIEW declare { name: \"id\", type: \"string\", required: true })\n if (transition.payloadSchema && transition.payloadSchema.length > 0) {\n // eslint-disable-next-line almadar/no-record-string-unknown -- Mock payloads are dynamically typed per event schema\n const payload: Record<string, unknown> = {};\n for (const field of transition.payloadSchema) {\n // Use caller-provided mockValue if available (set from entity context)\n if (field.mockValue !== undefined) {\n payload[field.name] = field.mockValue;\n } else if (field.type === 'string') {\n payload[field.name] = `mock-${field.name}`;\n } else if (field.type === 'number') {\n payload[field.name] = 1;\n } else if (field.type === 'boolean') {\n payload[field.name] = true;\n } else if (field.type === 'object' || field.type === 'any') {\n // `mock-<name>` is a plain string; persisting that for an object\n // field (e.g. SAVE's `data: object` carrying a form row) spreads\n // the string's characters across numeric keys server-side and\n // the downstream grid renders blank cards. An empty object is a\n // safer default — callers that need entity-shaped mocks should\n // set `mockValue` at the call site (see orbital-verify-unified's\n // phase4-browser TraitWalkConfig builder).\n payload[field.name] = {};\n } else {\n payload[field.name] = `mock-${field.name}`;\n }\n }\n return payload;\n }\n\n return {};\n}\n"]}
1
+ {"version":3,"sources":["../../src/state-machine/graph.ts","../../src/state-machine/bfs.ts","../../src/state-machine/guard-payloads.ts","../../src/state-machine/replay-paths.ts","../../src/state-machine/edge-walk.ts"],"names":[],"mappings":";AA2BO,SAAS,gBACd,WAAA,EAC0B;AAC1B,EAAA,MAAM,KAAA,uBAAY,GAAA,EAAyB;AAC3C,EAAA,KAAA,MAAW,KAAK,WAAA,EAAa;AAC3B,IAAA,IAAI,CAAA,CAAE,SAAS,GAAA,EAAK;AACpB,IAAA,IAAI,CAAC,KAAA,CAAM,GAAA,CAAI,CAAA,CAAE,IAAI,CAAA,EAAG,KAAA,CAAM,GAAA,CAAI,CAAA,CAAE,IAAA,EAAM,EAAE,CAAA;AAC5C,IAAA,KAAA,CAAM,GAAA,CAAI,CAAA,CAAE,IAAI,CAAA,CAAG,IAAA,CAAK,EAAE,KAAA,EAAO,CAAA,CAAE,KAAA,EAAO,EAAA,EAAI,CAAA,CAAE,EAAA,EAAI,CAAA;AAAA,EACtD;AACA,EAAA,OAAO,KAAA;AACT;;;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AA,GAAI,CAAA,KAAA,EAAQ,MAAM,IAAI,CAAA,CAAA;AAAA,MAC1C;AAAA,IACF;AACA,IAAA,OAAO,OAAA;AAAA,EACT;AAEA,EAAA,OAAO,EAAC;AACV","file":"index.js","sourcesContent":["/**\n * State Graph Construction\n *\n * Build an adjacency list from state machine transitions.\n * Extracted from orbital-verify-unified/src/analyze.ts.\n *\n * @packageDocumentation\n */\n\nimport type { GraphTransition, StateEdge } from './types.js';\n\n/**\n * Builds an adjacency list from state machine transitions.\n * \n * Constructs a state transition graph where each state maps to an array\n * of outgoing edges (events and target states). Wildcard transitions\n * (from === '*') are excluded since they don't represent fixed edges.\n * Used as the foundation for state machine analysis, traversal, and verification.\n * \n * @param {GraphTransition[]} transitions - Array of state transitions\n * @returns {Map<string, StateEdge[]>} State transition graph\n * \n * @example\n * const graph = buildStateGraph(transitions);\n * const edgesFromInitial = graph.get('initial'); // Array of outgoing edges\n * console.log(`Initial state has ${edgesFromInitial?.length} transitions`);\n */\nexport function buildStateGraph(\n transitions: GraphTransition[]\n): Map<string, StateEdge[]> {\n const graph = new Map<string, StateEdge[]>();\n for (const t of transitions) {\n if (t.from === '*') continue;\n if (!graph.has(t.from)) graph.set(t.from, []);\n graph.get(t.from)!.push({ event: t.event, to: t.to });\n }\n return graph;\n}\n","/**\n * BFS Reachability Algorithms\n *\n * Breadth-first search over state machine graphs.\n * Extracted from orbital-verify-unified/src/analyze.ts and phase3-server.ts.\n *\n * @packageDocumentation\n */\n\nimport type { BFSNode, StateEdge } from './types.js';\nimport { buildStateGraph } from './graph.js';\nimport type { GraphTransition } from './types.js';\n\n/**\n * Collects all reachable states from an initial state using breadth-first search.\n * \n * Performs BFS traversal of the state machine to find all states reachable\n * from the initial state, up to the specified maximum depth. Used for\n * state machine analysis, verification, and test coverage assessment.\n * \n * @param {GraphTransition[]} transitions - Array of state transitions\n * @param {string} initialState - Starting state name\n * @param {number} [maxDepth=5] - Maximum search depth\n * @returns {Set<string>} Set of reachable state names\n * \n * @example\n * const reachable = collectReachableStates(transitions, 'initial', 10);\n * console.log('Reachable states:', Array.from(reachable));\n */\nexport function collectReachableStates(\n transitions: GraphTransition[],\n initialState: string,\n maxDepth = 5\n): Set<string> {\n const graph = buildStateGraph(transitions);\n const visited = new Set<string>([initialState]);\n const queue: BFSNode[] = [{ state: initialState, depth: 0 }];\n\n while (queue.length > 0) {\n const current = queue.shift()!;\n if (current.depth >= maxDepth) continue;\n\n const edges = graph.get(current.state) ?? [];\n for (const edge of edges) {\n if (!visited.has(edge.to)) {\n visited.add(edge.to);\n queue.push({ state: edge.to, depth: current.depth + 1 });\n }\n }\n }\n\n return visited;\n}\n\n/**\n * Walks all reachable (state, event) pairs using BFS and invokes callback for each.\n * \n * Traverses the state machine using breadth-first search and calls the visitor\n * function for each (state, edge) pair encountered. Used by server verification\n * to test transitions by POSTing to endpoints and checking responses.\n * \n * @param {GraphTransition[]} transitions - Array of state transitions\n * @param {string} initialState - Starting state name\n * @param {number} maxDepth - Maximum BFS depth\n * @param {(state: string, edge: StateEdge, depth: number) => Promise<boolean>} visitor - Callback for each pair\n * @returns {Promise<{ visitedPairs: Set<string>; walkedEdges: number }>} Traversal statistics\n * \n * @example\n * const result = await walkStatePairs(transitions, 'initial', 5, async (state, edge) => {\n * console.log(`Transition: ${state} --${edge.event}--> ${edge.to}`);\n * return true; // Continue exploration\n * });\n * console.log(`Visited ${result.visitedPairs.size} state-event pairs`);\n */\nexport async function walkStatePairs(\n transitions: GraphTransition[],\n initialState: string,\n maxDepth: number,\n visitor: (state: string, edge: StateEdge, depth: number) => Promise<boolean>\n): Promise<{ visitedPairs: Set<string>; walkedEdges: number }> {\n const graph = buildStateGraph(transitions);\n const visitedPairs = new Set<string>();\n const queue: BFSNode[] = [{ state: initialState, depth: 0 }];\n let walkedEdges = 0;\n\n while (queue.length > 0) {\n const current = queue.shift()!;\n if (current.depth >= maxDepth) continue;\n\n const edges = graph.get(current.state) ?? [];\n for (const edge of edges) {\n const pairKey = `${current.state}:${edge.event}`;\n if (visitedPairs.has(pairKey)) continue;\n visitedPairs.add(pairKey);\n\n const shouldEnqueue = await visitor(current.state, edge, current.depth);\n walkedEdges++;\n\n if (shouldEnqueue) {\n const stateVisited = [...visitedPairs].some((k) => k.startsWith(`${edge.to}:`));\n if (!stateVisited) {\n queue.push({ state: edge.to, depth: current.depth + 1 });\n }\n }\n }\n }\n\n return { visitedPairs, walkedEdges };\n}\n","/**\n * Guard Payload Builder\n *\n * Derive pass and fail payloads from guard s-expressions.\n * Extracted from orbital-verify-unified/src/analyze.ts.\n *\n * @packageDocumentation\n */\n\nimport type { GuardPayload } from './types.js';\n\n/**\n * Extracts the first segment of a payload field reference.\n * \n * Parses binding references in the format \"@payload.field\" and extracts\n * the first field name segment. Used for identifying payload fields in\n * guard conditions for test data generation.\n * \n * @param {unknown} ref - Binding reference to extract from\n * @returns {string | null} First field segment or null for non-payload references\n * \n * @example\n * extractPayloadFieldRef('@payload.item'); // returns 'item'\n * extractPayloadFieldRef('@payload.data.weight'); // returns 'data'\n * extractPayloadFieldRef('@entity.id'); // returns null\n * extractPayloadFieldRef('@user.name'); // returns null\n */\nexport function extractPayloadFieldRef(ref: unknown): string | null {\n if (typeof ref !== 'string') return null;\n const match = ref.match(/^@payload\\.([A-Za-z0-9_]+)/);\n return match ? match[1] : null;\n}\n\n/**\n * Builds test payloads that satisfy or violate guard conditions.\n * \n * Generates pass/fail test data for guard s-expressions used in state machine\n * transitions. Pass payloads satisfy the guard condition (allowing transition),\n * fail payloads violate it (blocking transition). Used for automated testing\n * and validation of state machine behavior.\n * \n * Supports operators: not-nil, nil, eq, not-eq, gt, gte, lt, lte, and, or, not\n * \n * @param {unknown} guard - Guard s-expression to analyze\n * @returns {GuardPayload} Object with pass and fail payloads\n * \n * @example\n * // Guard: ['not-nil', '@payload.completed']\n * buildGuardPayloads(['not-nil', '@payload.completed']);\n * // Returns: { pass: { completed: 'mock-test-value' }, fail: { completed: null } }\n * \n * @example\n * // Guard: ['eq', '@payload.status', 'active']\n * buildGuardPayloads(['eq', '@payload.status', 'active']);\n * // Returns: { pass: { status: 'active' }, fail: { status: 'not-active' } }\n * \n * @example\n * // Guard: ['and', ['not-nil', '@payload.id'], ['eq', '@payload.status', 'ready']]\n * buildGuardPayloads(['and', ['not-nil', '@payload.id'], ['eq', '@payload.status', 'ready']]);\n * // Returns: { pass: { id: 'mock-test-value', status: 'ready' }, fail: { id: null } }\n */\nexport function buildGuardPayloads(guard: unknown): GuardPayload {\n // Bare-binding existence guard: e.g. `when @payload.row` lowers to\n // the string `\"@payload.row\"`. The transition fires iff that field is\n // truthy. Synthesize pass with a truthy mock and fail with null so\n // the verifier can drive both branches. Without this, std-confirmation\n // and std-modal's existence guards (REQUEST/EDIT requiring @payload.row)\n // get empty payloads in both cases — the pass case then fails the\n // server-side guard and the portal observer flags \"slot not mounted\".\n if (typeof guard === 'string') {\n const field = extractPayloadFieldRef(guard);\n if (field) return { pass: { [field]: { id: 'mock-test-id', name: 'mock-test-name' } }, fail: { [field]: null } };\n }\n\n if (!Array.isArray(guard) || guard.length === 0) {\n return { pass: {}, fail: {} };\n }\n\n const op = String(guard[0]);\n\n if (op === 'not-nil' || op === 'not_nil') {\n const field = extractPayloadFieldRef(guard[1]);\n if (field) return { pass: { [field]: 'mock-test-value' }, fail: { [field]: null } };\n }\n\n if (op === 'nil') {\n const field = extractPayloadFieldRef(guard[1]);\n if (field) return { pass: {}, fail: { [field]: 'mock-test-value' } };\n }\n\n if (op === 'eq' || op === '==' || op === '=') {\n const field = extractPayloadFieldRef(guard[1]);\n const val = guard[2];\n if (field && val !== undefined) {\n const failVal =\n typeof val === 'number' ? val + 1\n : typeof val === 'string' ? `not-${val}`\n : null;\n return { pass: { [field]: val }, fail: { [field]: failVal } };\n }\n }\n\n if (op === 'not-eq' || op === '!=' || op === 'neq') {\n const field = extractPayloadFieldRef(guard[1]);\n const val = guard[2];\n if (field && val !== undefined) {\n const passVal =\n typeof val === 'number' ? val + 1\n : typeof val === 'string' ? `not-${val}`\n : 'other';\n return { pass: { [field]: passVal }, fail: { [field]: val } };\n }\n }\n\n if (op === 'gt' || op === '>') {\n const field = extractPayloadFieldRef(guard[1]);\n const n = typeof guard[2] === 'number' ? guard[2] : 0;\n if (field) return { pass: { [field]: n + 1 }, fail: { [field]: n - 1 } };\n }\n\n if (op === 'gte' || op === '>=') {\n const field = extractPayloadFieldRef(guard[1]);\n const n = typeof guard[2] === 'number' ? guard[2] : 0;\n if (field) return { pass: { [field]: n }, fail: { [field]: n - 1 } };\n }\n\n if (op === 'lt' || op === '<') {\n const field = extractPayloadFieldRef(guard[1]);\n const n = typeof guard[2] === 'number' ? guard[2] : 0;\n if (field) return { pass: { [field]: n - 1 }, fail: { [field]: n + 1 } };\n }\n\n if (op === 'lte' || op === '<=') {\n const field = extractPayloadFieldRef(guard[1]);\n const n = typeof guard[2] === 'number' ? guard[2] : 0;\n if (field) return { pass: { [field]: n }, fail: { [field]: n + 1 } };\n }\n\n if (op === 'and') {\n const subs = (guard.slice(1) as unknown[]).filter(Array.isArray);\n if (subs.length >= 2) {\n const s1 = buildGuardPayloads(subs[0]);\n const s2 = buildGuardPayloads(subs[1]);\n return { pass: { ...s1.pass, ...s2.pass }, fail: s1.fail };\n }\n if (subs.length === 1) return buildGuardPayloads(subs[0]);\n }\n\n if (op === 'or') {\n // Accept BOTH array sub-guards and bare-binding string sub-guards\n // (post-substitution mode-aware guards like\n // `(or (= \"edit\" \"create\") \"@payload.row\")` mix array + string children).\n const subs = guard.slice(1) as unknown[];\n if (subs.length >= 2) {\n const s1 = buildGuardPayloads(subs[0]);\n const s2 = buildGuardPayloads(subs[1]);\n // For OR: pass if EITHER branch passes. Prefer the second branch's\n // pass payload if the first yields nothing useful — the literal-fold\n // case `(= \"edit\" \"create\") || @payload.row` has the first branch\n // return `{}` and the row-payload comes from the second.\n const combinedPass = Object.keys(s1.pass).length > 0 ? s1.pass : s2.pass;\n return { pass: combinedPass, fail: { ...s1.fail, ...s2.fail } };\n }\n if (subs.length === 1) return buildGuardPayloads(subs[0]);\n }\n\n if (op === 'not') {\n const inner = buildGuardPayloads(guard[1]);\n return { pass: inner.fail, fail: inner.pass };\n }\n\n // Agent pure operators used in guards\n if (op === 'agent/is-pinned') {\n const field = extractPayloadFieldRef(guard[1]);\n if (field) return { pass: { [field]: 'mem_test_unpinned' }, fail: { [field]: 'mem_test_pinned' } };\n }\n\n if (op === 'agent/memory-strength') {\n const field = extractPayloadFieldRef(guard[1]);\n if (field) return { pass: { [field]: 'mem_test_id' }, fail: { [field]: 'mem_nonexistent' } };\n }\n\n // Agent operators in comparison contexts (e.g., [\">=\", [\"agent/context-usage\"], 0.85])\n // These don't use @payload, they query agent state directly. Return empty payloads\n // since the guard result depends on agent context, not event payload.\n if (op.startsWith('agent/')) {\n return { pass: {}, fail: {} };\n }\n\n return { pass: {}, fail: {} };\n}\n","/**\n * Replay Path Builder\n *\n * Compute the shortest path (replay steps) from an initial state\n * to every reachable state in a state machine. Used by browser\n * verification to navigate through states before running assertions.\n *\n * Extracted from orbital-verify-unified/src/analyze.ts (collectDataMutationTests).\n *\n * @packageDocumentation\n */\n\nimport type { GraphTransition, ReplayStep, PayloadFieldSchema } from './types.js';\n\n/** Entity-data sentinel payload fields: presence means transition needs a selected row */\nconst ENTITY_PAYLOAD_FIELDS = new Set(['data', 'row', 'item', 'id']);\n\n/**\n * Extended transition with render and payload info needed for replay path building.\n * Compatible with orbital-verify's UnifiedTransition.\n */\nexport interface ReplayTransition extends GraphTransition {\n hasGuard: boolean;\n guard?: unknown[];\n payloadFields: string[];\n payloadSchema: PayloadFieldSchema[];\n renderEffects: Array<{\n slot: string;\n patternType: string | null;\n }>;\n}\n\n/**\n * Builds the shortest replay paths from initial state to all reachable states.\n * \n * Computes step-by-step navigation paths for state machine testing and verification.\n * Uses breadth-first search to find shortest paths up to specified depth limit.\n * Each path contains replay steps with event, state, and payload information\n * needed to reproduce state transitions in tests.\n * \n * @param {ReplayTransition[]} transitions - Transitions with render/payload information\n * @param {string} initialState - Starting state name\n * @param {number} [maxDepth=3] - Maximum path length (default: 3)\n * @returns {Map<string, ReplayStep[]>} Map of state names to replay step arrays\n * \n * @example\n * // Build paths from 'initial' state\n * const paths = buildReplayPaths(transitions, 'initial', 5);\n * \n * // Get steps to reach 'completed' state\n * const stepsToComplete = paths.get('completed');\n * \n * // Execute replay steps\n * for (const step of stepsToComplete) {\n * await dispatchEvent(step.event, step.payload);\n * }\n */\nexport function buildReplayPaths(\n transitions: ReplayTransition[],\n initialState: string,\n maxDepth = 3\n): Map<string, ReplayStep[]> {\n type QueueNode = { state: string; path: ReplayStep[] };\n\n const queue: QueueNode[] = [{ state: initialState, path: [] }];\n const replayPaths = new Map<string, ReplayStep[]>();\n replayPaths.set(initialState, []);\n\n while (queue.length > 0) {\n const { state, path } = queue.shift()!;\n if (path.length >= maxDepth) continue;\n\n const fromHere = transitions.filter(\n (t) => t.from === state && t.event !== 'INIT',\n );\n\n for (const transition of fromHere) {\n if (replayPaths.has(transition.to)) continue;\n\n const renderEffect = transition.renderEffects.find((re) => re.patternType !== null);\n const stepNeedsEntityData =\n transition.hasGuard ||\n transition.payloadFields.some((f) => ENTITY_PAYLOAD_FIELDS.has(f));\n\n const step: ReplayStep = {\n event: transition.event,\n fromState: state,\n toState: transition.to,\n slot: renderEffect?.slot ?? 'main',\n expectedPattern: renderEffect?.patternType ?? undefined,\n needsEntityData: stepNeedsEntityData,\n payloadSchema: transition.payloadSchema.length > 0 ? transition.payloadSchema : undefined,\n };\n\n const newPath = [...path, step];\n replayPaths.set(transition.to, newPath);\n queue.push({ state: transition.to, path: newPath });\n }\n }\n\n return replayPaths;\n}\n","/**\n * Edge-Covering Walk Algorithm\n *\n * Computes an ordered sequence of events (WalkStep[]) that covers every\n * transition (edge) in a state machine graph at least once. This guarantees\n * 100% transition coverage regardless of graph topology.\n *\n * Algorithm:\n * 1. Build adjacency list and edge universe (guarded transitions produce two edges)\n * 2. Precompute BFS shortest paths between all state pairs (for repositioning)\n * 3. Greedy DFS: at each state, prefer uncovered outgoing edges\n * 4. When stuck, insert repositioning steps to nearest state with uncovered edges\n * 5. Guard-fail steps don't advance state (guard blocks transition)\n *\n * Used by StateWalkEngine in @almadar-io/verify. Both orbital-verify and\n * runtime-verify share this algorithm for consistent coverage.\n *\n * @packageDocumentation\n */\n\nimport type { EdgeWalkTransition, WalkStep, StateEdge } from './types.js';\nimport type { EventPayload, EventPayloadValue } from '../types/expression.js';\nimport { buildGuardPayloads } from './guard-payloads.js';\n\n/**\n * Build an ordered walk that covers every edge in the state machine.\n *\n * @param transitions - All transitions in the state machine\n * @param initialState - Starting state\n * @returns Ordered walk steps covering every edge\n */\nexport function buildEdgeCoveringWalk(\n transitions: EdgeWalkTransition[],\n initialState: string,\n): WalkStep[] {\n // 1. Build adjacency list. Skip wildcards (pseudostates) and skip the\n // boot INIT (the runtime auto-fires INIT from the initial state on\n // mount, so the walker doesn't need to fire it). User-triggered INITs\n // from non-initial states (refresh, retry) ARE walkable edges and\n // stay in the graph so coverage can reach them.\n const filtered = transitions.filter(\n (t) => t.from !== '*' && !(t.event === 'INIT' && t.from === initialState),\n );\n\n const graph = new Map<string, Array<{ event: string; to: string; transition: EdgeWalkTransition }>>();\n const allStates = new Set<string>();\n\n for (const t of filtered) {\n allStates.add(t.from);\n allStates.add(t.to);\n if (!graph.has(t.from)) graph.set(t.from, []);\n graph.get(t.from)!.push({ event: t.event, to: t.to, transition: t });\n }\n\n // Ensure initial state is in the set\n allStates.add(initialState);\n\n // 2. Build edge universe. Guarded transitions produce pass + fail edges.\n const uncovered = new Set<string>();\n const edgeMeta = new Map<string, { transition: EdgeWalkTransition; guardCase: 'pass' | 'fail' | null }>();\n\n for (const t of filtered) {\n if (t.hasGuard) {\n const keyPass = `${t.from}+${t.event}->${t.to}[pass]`;\n const keyFail = `${t.from}+${t.event}->${t.to}[fail]`;\n uncovered.add(keyPass);\n uncovered.add(keyFail);\n edgeMeta.set(keyPass, { transition: t, guardCase: 'pass' });\n edgeMeta.set(keyFail, { transition: t, guardCase: 'fail' });\n } else {\n const key = `${t.from}+${t.event}->${t.to}`;\n uncovered.add(key);\n edgeMeta.set(key, { transition: t, guardCase: null });\n }\n }\n\n if (uncovered.size === 0) return [];\n\n // 3. Precompute BFS shortest paths between all state pairs\n const shortestPaths = new Map<string, Map<string, Array<{ event: string; to: string }>>>();\n for (const state of allStates) {\n shortestPaths.set(state, bfsShortestPaths(state, graph));\n }\n\n // 4. Greedy walk\n const walk: WalkStep[] = [];\n let currentState = initialState;\n const maxIterations = uncovered.size * allStates.size * 2; // safety bound\n let iterations = 0;\n\n while (uncovered.size > 0 && iterations < maxIterations) {\n iterations++;\n\n // Find uncovered edges from currentState\n const outgoing = findUncoveredEdges(currentState, graph, uncovered);\n\n if (outgoing.length > 0) {\n // Pick first uncovered edge\n const pick = outgoing[0];\n const payload = buildPayloadForEdge(pick.transition, pick.guardCase);\n\n walk.push({\n from: currentState,\n event: pick.transition.event,\n to: pick.transition.to,\n guardCase: pick.guardCase,\n payload,\n isRepositioning: false,\n });\n\n uncovered.delete(pick.key);\n\n // Guard-fail doesn't advance state\n if (pick.guardCase !== 'fail') {\n currentState = pick.transition.to;\n }\n } else {\n // Stuck: find nearest state with uncovered edges\n const target = findNearestUncoveredState(currentState, graph, uncovered, shortestPaths);\n\n if (!target) {\n // No reachable state with uncovered edges. Remaining edges are unreachable.\n break;\n }\n\n // Insert repositioning steps\n const repoPath = shortestPaths.get(currentState)?.get(target);\n if (!repoPath || repoPath.length === 0) break;\n\n for (const step of repoPath) {\n walk.push({\n from: currentState,\n event: step.event,\n to: step.to,\n guardCase: null,\n payload: {},\n isRepositioning: true,\n });\n currentState = step.to;\n }\n }\n }\n\n return walk;\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\n/**\n * BFS from a source state, returning shortest paths to all reachable states.\n * Each path is an array of {event, to} steps.\n */\nfunction bfsShortestPaths(\n source: string,\n graph: Map<string, Array<{ event: string; to: string; transition: EdgeWalkTransition }>>,\n): Map<string, Array<{ event: string; to: string }>> {\n const paths = new Map<string, Array<{ event: string; to: string }>>();\n const visited = new Set<string>([source]);\n const queue: Array<{ state: string; path: Array<{ event: string; to: string }> }> = [\n { state: source, path: [] },\n ];\n\n while (queue.length > 0) {\n const { state, path } = queue.shift()!;\n const edges = graph.get(state) ?? [];\n\n for (const edge of edges) {\n if (visited.has(edge.to)) continue;\n visited.add(edge.to);\n const newPath = [...path, { event: edge.event, to: edge.to }];\n paths.set(edge.to, newPath);\n queue.push({ state: edge.to, path: newPath });\n }\n }\n\n return paths;\n}\n\n/**\n * Find uncovered edges from a given state.\n */\nfunction findUncoveredEdges(\n state: string,\n graph: Map<string, Array<{ event: string; to: string; transition: EdgeWalkTransition }>>,\n uncovered: Set<string>,\n): Array<{ key: string; transition: EdgeWalkTransition; guardCase: 'pass' | 'fail' | null }> {\n const edges = graph.get(state) ?? [];\n const result: Array<{ key: string; transition: EdgeWalkTransition; guardCase: 'pass' | 'fail' | null }> = [];\n\n for (const edge of edges) {\n if (edge.transition.hasGuard) {\n const keyPass = `${state}+${edge.event}->${edge.to}[pass]`;\n const keyFail = `${state}+${edge.event}->${edge.to}[fail]`;\n // Prefer pass first (advances state), then fail\n if (uncovered.has(keyPass)) {\n result.push({ key: keyPass, transition: edge.transition, guardCase: 'pass' });\n }\n if (uncovered.has(keyFail)) {\n result.push({ key: keyFail, transition: edge.transition, guardCase: 'fail' });\n }\n } else {\n const key = `${state}+${edge.event}->${edge.to}`;\n if (uncovered.has(key)) {\n result.push({ key, transition: edge.transition, guardCase: null });\n }\n }\n }\n\n return result;\n}\n\n/**\n * Find the nearest state (from currentState) that has uncovered outgoing edges.\n */\nfunction findNearestUncoveredState(\n currentState: string,\n graph: Map<string, Array<{ event: string; to: string; transition: EdgeWalkTransition }>>,\n uncovered: Set<string>,\n shortestPaths: Map<string, Map<string, Array<{ event: string; to: string }>>>,\n): string | null {\n // Collect states that have uncovered edges\n const statesWithUncovered = new Set<string>();\n for (const key of uncovered) {\n // Key format: \"state+EVENT->target\" or \"state+EVENT->target[pass]\"\n const fromState = key.split('+')[0];\n statesWithUncovered.add(fromState);\n }\n\n // If current state has uncovered edges, return it (shouldn't happen, but handle it)\n if (statesWithUncovered.has(currentState)) return currentState;\n\n // Find nearest reachable state with uncovered edges\n const paths = shortestPaths.get(currentState);\n if (!paths) return null;\n\n let nearestState: string | null = null;\n let nearestDist = Infinity;\n\n for (const target of statesWithUncovered) {\n const path = paths.get(target);\n if (path && path.length < nearestDist) {\n nearestDist = path.length;\n nearestState = target;\n }\n }\n\n return nearestState;\n}\n\n/**\n * Build a payload for a given edge based on its guard case and payload schema.\n * For guarded transitions, uses guard expressions to generate pass/fail payloads.\n * For unguarded transitions with payload schemas (e.g., EDIT/VIEW with { id }),\n * generates mock values so fetch-by-ID effects can resolve entity data.\n */\nfunction buildPayloadForEdge(\n transition: EdgeWalkTransition,\n guardCase: 'pass' | 'fail' | null,\n): EventPayload {\n // Guard-based payload generation (existing behavior)\n if (transition.hasGuard && transition.guard && guardCase) {\n const payloads = buildGuardPayloads(transition.guard);\n return guardCase === 'pass' ? payloads.pass : payloads.fail;\n }\n\n // Schema-based payload generation for events that declare required fields\n // (e.g., EDIT/VIEW declare { name: \"id\", type: \"string\", required: true })\n if (transition.payloadSchema && transition.payloadSchema.length > 0) {\n const payload: EventPayload = {};\n for (const field of transition.payloadSchema) {\n // Use caller-provided mockValue if available (set from entity context)\n if (field.mockValue !== undefined) {\n payload[field.name] = field.mockValue as EventPayloadValue;\n } else if (field.type === 'string') {\n payload[field.name] = `mock-${field.name}`;\n } else if (field.type === 'number') {\n payload[field.name] = 1;\n } else if (field.type === 'boolean') {\n payload[field.name] = true;\n } else if (field.type === 'object' || field.type === 'any') {\n // `mock-<name>` is a plain string; persisting that for an object\n // field (e.g. SAVE's `data: object` carrying a form row) spreads\n // the string's characters across numeric keys server-side and\n // the downstream grid renders blank cards. An empty object is a\n // safer default — callers that need entity-shaped mocks should\n // set `mockValue` at the call site (see orbital-verify-unified's\n // phase4-browser TraitWalkConfig builder).\n payload[field.name] = {};\n } else {\n payload[field.name] = `mock-${field.name}`;\n }\n }\n return payload;\n }\n\n return {};\n}\n"]}
@@ -1,8 +1,9 @@
1
- import { e as EntityRow, aL as FieldValue, b as TraitConfig } from '../schema-OhIbVaYu.js';
2
- export { A as AGENT_DOMAIN_CATEGORIES, m as ALLOWED_CUSTOM_COMPONENTS, n as AgentDomainCategory, o as AgentDomainCategorySchema, p as AgentEffect, q as AllowedCustomComponent, r as AnimationDef, s as AnimationDefInput, t as AnimationDefSchema, h as AppSchema, u as AssetMap, v as AssetMapInput, w as AssetMapSchema, x as AssetMapping, y as AssetMappingInput, z as AssetMappingSchema, B as AtomicEffect, C as CallServiceConfig, D as CallServiceEffect, F as ComputedEventContract, G as ComputedEventContractSchema, H as ComputedEventListener, I as ComputedEventListenerSchema, J as CustomPatternDefinition, K as CustomPatternDefinitionInput, L as CustomPatternDefinitionSchema, M as CustomPatternMap, N as CustomPatternMapInput, Q as CustomPatternMapSchema, R as DerefEffect, V as DesignPreferences, W as DesignPreferencesInput, X as DesignPreferencesSchema, Y as DesignTokens, Z as DesignTokensInput, _ as DesignTokensSchema, $ as DespawnEffect, a0 as DoEffect, a1 as DomainCategory, a2 as DomainCategorySchema, a3 as DomainContext, a4 as DomainContextInput, a5 as DomainContextSchema, a6 as DomainVocabulary, a7 as DomainVocabularySchema, a8 as ENTITY_ROLES, a9 as Effect, aa as EffectInput, ab as EffectSchema, ac as EmitConfig, ad as EmitEffect, E as Entity, ae as EntityCall, af as EntityCallSchema, ag as EntityData, c as EntityField, ah as EntityFieldInput, ai as EntityFieldSchema, d as EntityPersistence, aj as EntityPersistenceSchema, f as EntityRef, ak as EntityRefSchema, al as EntityRefStringSchema, am as EntityRole, an as EntityRoleSchema, ao as EntitySchema, ap as EntitySemanticRole, aq as EntitySemanticRoleSchema, ar as Event, as as EventInput, at as EventListener, au as EventListenerSchema, av as EventPayloadField, aw as EventPayloadFieldSchema, ax as EventSchema, ay as EventScope, az as EventScopeSchema, aA as EventSemanticRole, aB as EventSemanticRoleSchema, aC as EventSource, aD as EventSourceSchema, aE as FetchEffect, aF as Field, aG as FieldFormat, aH as FieldFormatSchema, aI as FieldSchema, aJ as FieldType, aK as FieldTypeSchema, aM as FullOrbitalUnit, aN as GAME_TYPES, aO as GameSubCategory, aP as GameSubCategorySchema, aQ as GameType, aR as GameTypeSchema, aS as Guard, aT as GuardInput, aU as GuardSchema, aV as ListenSource, aW as ListenSourceSchema, aX as LogEffect, aY as McpServiceDef, aZ as McpServiceDefSchema, a_ as NavigateEffect, a$ as NodeClassification, b0 as NodeClassificationSchema, b1 as NotifyEffect, aM as Orbital, b2 as OrbitalConfig, b3 as OrbitalConfigInput, b4 as OrbitalConfigSchema, O as OrbitalDefinition, b5 as OrbitalDefinitionSchema, b6 as OrbitalEntity, b7 as OrbitalEntityInput, b8 as OrbitalEntitySchema, b9 as OrbitalInput, ba as OrbitalPage, bb as OrbitalPageInput, bc as OrbitalPageSchema, bd as OrbitalPageStrictInput, be as OrbitalPageStrictSchema, h as OrbitalSchema, bf as OrbitalSchemaInput, bg as OrbitalSchemaSchema, bh as OrbitalTraitRef, bi as OrbitalTraitRefSchema, bj as OrbitalUnit, bk as OrbitalUnitSchema, bl as OrbitalZodSchema, j as Page, P as PageRef, k as PageRefObject, bm as PageRefObjectSchema, bn as PageRefSchema, bo as PageRefStringSchema, bp as PageSchema, bq as PageTraitRef, br as PageTraitRefSchema, bs as PayloadField, bt as PayloadFieldSchema, bu as PersistEffect, bv as PresentationType, bw as RefEffect, bx as RelatedLink, by as RelatedLinkSchema, bz as RelationConfig, bA as RelationConfigSchema, bB as RenderItemLambda, bC as RenderUIConfig, bD as RenderUIEffect, bE as RenderUINode, bF as RequiredField, bG as RequiredFieldSchema, bH as ResolvedAsset, bI as ResolvedAssetInput, bJ as ResolvedAssetSchema, bK as ResolvedPatternProps, bL as RestAuthConfig, bM as RestAuthConfigSchema, bN as RestServiceDef, bO as RestServiceDefSchema, bP as SERVICE_TYPES, bQ as SemanticAssetRef, bR as SemanticAssetRefInput, bS as SemanticAssetRefSchema, bT as ServiceDefinition, bU as ServiceDefinitionSchema, bV as ServiceParams, bW as ServiceRef, bX as ServiceRefObject, bY as ServiceRefObjectSchema, bZ as ServiceRefSchema, b_ as ServiceRefStringSchema, b$ as ServiceType, c0 as ServiceTypeSchema, c1 as SetEffect, c2 as SocketEvents, c3 as SocketEventsSchema, c4 as SocketServiceDef, c5 as SocketServiceDefSchema, c6 as SpawnEffect, S as State, c7 as StateInput, c8 as StateMachine, c9 as StateMachineInput, ca as StateMachineSchema, cb as StateSchema, cc as StateSemanticRole, cd as StateSemanticRoleSchema, ce as SuggestedGuard, cf as SuggestedGuardSchema, cg as SwapEffect, ch as ThemeDefinition, ci as ThemeDefinitionSchema, cj as ThemeRef, ck as ThemeRefSchema, cl as ThemeRefStringSchema, cm as ThemeTokens, cn as ThemeTokensSchema, co as ThemeVariant, cp as ThemeVariantSchema, i as Trait, cq as TraitCategory, cr as TraitCategorySchema, cs as TraitConfigObject, ct as TraitConfigSchema, cu as TraitConfigValue, cv as TraitConfigValueSchema, cw as TraitDataEntity, cx as TraitDataEntitySchema, cy as TraitEntityField, cz as TraitEntityFieldSchema, T as TraitEventContract, cA as TraitEventContractSchema, a as TraitEventListener, cB as TraitEventListenerSchema, cC as TraitInput, g as TraitRef, cD as TraitRefSchema, l as TraitReference, cE as TraitReferenceInput, cF as TraitReferenceSchema, cG as TraitSchema, cH as TraitTick, cI as TraitTickSchema, cJ as TraitUIBinding, cK as Transition, cL as TransitionInput, cM as TransitionSchema, cN as TypedEffect, cO as UISlot, cP as UISlotSchema, cQ as UI_SLOTS, cR as UXHints, cS as UXHintsSchema, U as UseDeclaration, cT as UseDeclarationSchema, cU as UserPersona, cV as UserPersonaInput, cW as UserPersonaSchema, cX as VISUAL_STYLES, cY as ViewType, cZ as ViewTypeSchema, c_ as VisualStyle, c$ as VisualStyleSchema, d0 as WatchEffect, d1 as WatchOptions, d2 as atomic, d3 as callService, d4 as createAssetKey, d5 as deref, d6 as deriveCollection, d7 as despawn, d8 as doEffects, d9 as emit, da as findService, db as getDefaultAnimationsForRole, dc as getServiceNames, dd as getTraitConfig, de as getTraitName, df as hasService, dg as isCircuitEvent, dh as isEffect, di as isEntityCall, dj as isEntityReference, dk as isEntityReferenceAny, dl as isImportedTraitRef, dm as isInlineTrait, dn as isMcpService, dp as isOrbitalDefinition, dq as isPageReference, dr as isPageReferenceObject, ds as isPageReferenceString, dt as isRestService, du as isRuntimeEntity, dv as isSExprEffect, dw as isServiceReference, dx as isServiceReferenceObject, dy as isSingletonEntity, dz as isSocketService, dA as isThemeReference, dB as navigate, dC as normalizeTraitRef, dD as notify, dE as parseAssetKey, dF as parseEntityRef, dG as parseImportedTraitRef, dH as parseOrbitalSchema, dI as parsePageRef, dJ as parseServiceRef, dK as persist, dL as ref, dM as renderUI, dN as safeParseOrbitalSchema, dO as set, dP as spawn, dQ as swap, dR as validateAssetAnimations, dS as watch } from '../schema-OhIbVaYu.js';
3
- import { S as SExpr, b as EventPayload } from '../expression-eBO9-SQM.js';
4
- export { C as CORE_BINDINGS, a as CoreBinding, E as EvalContext, c as EventPayloadValue, d as Expression, e as ExpressionInput, f as ExpressionSchema, L as LogMeta, P as ParsedBinding, g as SExprAtom, h as SExprAtomSchema, i as SExprInput, j as SExprSchema, k as collectBindings, l as getArgs, m as getOperator, n as isBinding, o as isSExpr, p as isSExprAtom, q as isSExprCall, r as isValidBinding, s as parseBinding, t as sexpr, w as walkSExpr } from '../expression-eBO9-SQM.js';
1
+ import { c4 as ServiceParams, h as OrbitalSchema, e as EntityRow, aQ as FieldValue, b as TraitConfig } from '../schema-CI7VxcmO.js';
2
+ export { A as AGENT_DOMAIN_CATEGORIES, m as ALLOWED_CUSTOM_COMPONENTS, n as AgentDomainCategory, o as AgentDomainCategorySchema, p as AgentEffect, q as AllowedCustomComponent, r as AnimationDef, s as AnimationDefInput, t as AnimationDefSchema, u as AssetMap, v as AssetMapInput, w as AssetMapSchema, x as AssetMapping, y as AssetMappingInput, z as AssetMappingSchema, B as AtomicEffect, C as CallServiceConfig, D as CallServiceEffect, F as CheckpointLoadEffect, G as CheckpointSaveEffect, H as ComputedEventContract, I as ComputedEventContractSchema, J as ComputedEventListener, K as ComputedEventListenerSchema, L as CustomPatternDefinition, M as CustomPatternDefinitionInput, N as CustomPatternDefinitionSchema, Q as CustomPatternMap, R as CustomPatternMapInput, V as CustomPatternMapSchema, W as DerefEffect, X as DesignPreferences, Y as DesignPreferencesInput, Z as DesignPreferencesSchema, _ as DesignTokens, $ as DesignTokensInput, a0 as DesignTokensSchema, a1 as DespawnEffect, a2 as DoEffect, a3 as DomainCategory, a4 as DomainCategorySchema, a5 as DomainContext, a6 as DomainContextInput, a7 as DomainContextSchema, a8 as DomainVocabulary, a9 as DomainVocabularySchema, aa as ENTITY_ROLES, ab as Effect, ac as EffectInput, ad as EffectSchema, ae as EmitConfig, af as EmitEffect, E as Entity, ag as EntityCall, ah as EntityCallSchema, ai as EntityData, c as EntityField, aj as EntityFieldInput, ak as EntityFieldSchema, d as EntityPersistence, al as EntityPersistenceSchema, f as EntityRef, am as EntityRefSchema, an as EntityRefStringSchema, ao as EntityRole, ap as EntityRoleSchema, aq as EntitySchema, ar as EntitySemanticRole, as as EntitySemanticRoleSchema, at as EvaluateConfig, au as EvaluateEffect, av as Event, aw as EventInput, ax as EventListener, ay as EventListenerSchema, az as EventPayloadField, aA as EventPayloadFieldSchema, aB as EventSchema, aC as EventScope, aD as EventScopeSchema, aE as EventSemanticRole, aF as EventSemanticRoleSchema, aG as EventSource, aH as EventSourceSchema, aI as FetchEffect, aJ as FetchOptions, aK as Field, aL as FieldFormat, aM as FieldFormatSchema, aN as FieldSchema, aO as FieldType, aP as FieldTypeSchema, aR as ForwardConfig, aS as ForwardEffect, aT as FullOrbitalUnit, aU as GAME_TYPES, aV as GameSubCategory, aW as GameSubCategorySchema, aX as GameType, aY as GameTypeSchema, aZ as Guard, a_ as GuardInput, a$ as GuardSchema, b0 as ListenSource, b1 as ListenSourceSchema, b2 as LogEffect, b3 as McpServiceDef, b4 as McpServiceDefSchema, b5 as NavigateEffect, b6 as NnConfig, b7 as NnLayer, b8 as NodeClassification, b9 as NodeClassificationSchema, ba as NotifyEffect, aT as Orbital, bb as OrbitalConfig, bc as OrbitalConfigInput, bd as OrbitalConfigSchema, O as OrbitalDefinition, be as OrbitalDefinitionSchema, bf as OrbitalEntity, bg as OrbitalEntityInput, bh as OrbitalEntitySchema, bi as OrbitalInput, bj as OrbitalPage, bk as OrbitalPageInput, bl as OrbitalPageSchema, bm as OrbitalPageStrictInput, bn as OrbitalPageStrictSchema, bo as OrbitalSchemaInput, bp as OrbitalSchemaSchema, bq as OrbitalTraitRef, br as OrbitalTraitRefSchema, bs as OrbitalUnit, bt as OrbitalUnitSchema, bu as OrbitalZodSchema, j as Page, P as PageRef, k as PageRefObject, bv as PageRefObjectSchema, bw as PageRefSchema, bx as PageRefStringSchema, by as PageSchema, bz as PageTraitRef, bA as PageTraitRefSchema, bB as PayloadField, bC as PayloadFieldSchema, bD as PersistData, bE as PersistEffect, bF as PersistEmitConfig, bG as PresentationType, bH as RefEffect, bI as RelatedLink, bJ as RelatedLinkSchema, bK as RelationConfig, bL as RelationConfigSchema, bM as RenderItemLambda, bN as RenderUIConfig, bO as RenderUIEffect, bP as RenderUINode, bQ as RequiredField, bR as RequiredFieldSchema, bS as ResolvedAsset, bT as ResolvedAssetInput, bU as ResolvedAssetSchema, bV as ResolvedPatternProps, bW as RestAuthConfig, bX as RestAuthConfigSchema, bY as RestServiceDef, bZ as RestServiceDefSchema, b_ as SERVICE_TYPES, b$ as SemanticAssetRef, c0 as SemanticAssetRefInput, c1 as SemanticAssetRefSchema, c2 as ServiceDefinition, c3 as ServiceDefinitionSchema, c5 as ServiceRef, c6 as ServiceRefObject, c7 as ServiceRefObjectSchema, c8 as ServiceRefSchema, c9 as ServiceRefStringSchema, ca as ServiceType, cb as ServiceTypeSchema, cc as SetEffect, cd as SocketEvents, ce as SocketEventsSchema, cf as SocketServiceDef, cg as SocketServiceDefSchema, ch as SpawnEffect, S as State, ci as StateInput, cj as StateMachine, ck as StateMachineInput, cl as StateMachineSchema, cm as StateSchema, cn as StateSemanticRole, co as StateSemanticRoleSchema, cp as SuggestedGuard, cq as SuggestedGuardSchema, cr as SwapEffect, cs as ThemeDefinition, ct as ThemeDefinitionSchema, cu as ThemeRef, cv as ThemeRefSchema, cw as ThemeRefStringSchema, cx as ThemeTokens, cy as ThemeTokensSchema, cz as ThemeVariant, cA as ThemeVariantSchema, cB as TrainConfig, cC as TrainEffect, i as Trait, cD as TraitCategory, cE as TraitCategorySchema, cF as TraitConfigObject, cG as TraitConfigSchema, cH as TraitConfigValue, cI as TraitConfigValueSchema, cJ as TraitDataEntity, cK as TraitDataEntitySchema, cL as TraitEntityField, cM as TraitEntityFieldSchema, T as TraitEventContract, cN as TraitEventContractSchema, a as TraitEventListener, cO as TraitEventListenerSchema, cP as TraitInput, g as TraitRef, cQ as TraitRefSchema, l as TraitReference, cR as TraitReferenceInput, cS as TraitReferenceSchema, cT as TraitSchema, cU as TraitTick, cV as TraitTickSchema, cW as TraitUIBinding, cX as Transition, cY as TransitionInput, cZ as TransitionSchema, c_ as TypedEffect, c$ as UISlot, d0 as UISlotSchema, d1 as UI_SLOTS, d2 as UXHints, d3 as UXHintsSchema, U as UseDeclaration, d4 as UseDeclarationSchema, d5 as UserPersona, d6 as UserPersonaInput, d7 as UserPersonaSchema, d8 as VISUAL_STYLES, d9 as ViewType, da as ViewTypeSchema, db as VisualStyle, dc as VisualStyleSchema, dd as WatchEffect, de as WatchOptions, df as atomic, dg as callService, dh as createAssetKey, di as deref, dj as deriveCollection, dk as despawn, dl as doEffects, dm as emit, dn as findService, dp as getDefaultAnimationsForRole, dq as getServiceNames, dr as getTraitConfig, ds as getTraitName, dt as hasService, du as isCircuitEvent, dv as isEffect, dw as isEntityCall, dx as isEntityReference, dy as isEntityReferenceAny, dz as isImportedTraitRef, dA as isInlineTrait, dB as isMcpService, dC as isOrbitalDefinition, dD as isPageReference, dE as isPageReferenceObject, dF as isPageReferenceString, dG as isRestService, dH as isRuntimeEntity, dI as isSExprEffect, dJ as isServiceReference, dK as isServiceReferenceObject, dL as isSingletonEntity, dM as isSocketService, dN as isThemeReference, dO as navigate, dP as normalizeTraitRef, dQ as notify, dR as parseAssetKey, dS as parseEntityRef, dT as parseImportedTraitRef, dU as parseOrbitalSchema, dV as parsePageRef, dW as parseServiceRef, dX as persist, dY as ref, dZ as renderUI, d_ as safeParseOrbitalSchema, d$ as set, e0 as spawn, e1 as swap, e2 as validateAssetAnimations, e3 as watch } from '../schema-CI7VxcmO.js';
3
+ import { c as EventPayloadValue, b as EventPayload, L as LogMeta, S as SExpr } from '../expression-eBO9-SQM.js';
4
+ export { C as CORE_BINDINGS, a as CoreBinding, E as EvalContext, d as Expression, e as ExpressionInput, f as ExpressionSchema, P as ParsedBinding, g as SExprAtom, h as SExprAtomSchema, i as SExprInput, j as SExprSchema, k as collectBindings, l as getArgs, m as getOperator, n as isBinding, o as isSExpr, p as isSExprAtom, q as isSExprCall, r as isValidBinding, s as parseBinding, t as sexpr, w as walkSExpr } from '../expression-eBO9-SQM.js';
5
5
  import { z } from 'zod';
6
+ import { AnyPatternConfig } from '@almadar/patterns';
6
7
  export { PATTERN_TYPES, PatternConfig, PatternType, isValidPatternType } from '@almadar/patterns';
7
8
 
8
9
  /**
@@ -158,6 +159,7 @@ declare function toBindingRoot(root: string): BindingRoot;
158
159
  *
159
160
  * @packageDocumentation
160
161
  */
162
+
161
163
  /**
162
164
  * Categories for agent memories.
163
165
  */
@@ -247,7 +249,7 @@ interface AgentContext {
247
249
  generate(prompt: string, options?: AgentGenerateOptions): Promise<string>;
248
250
  switchProvider(provider: string, model?: string): void;
249
251
  tools(): string[];
250
- invoke(toolName: string, args: Record<string, unknown>): Promise<unknown>;
252
+ invoke(toolName: string, args: ServiceParams): Promise<EventPayloadValue>;
251
253
  tokenCount(): number;
252
254
  contextUsage(): number;
253
255
  compact(strategy?: AgentCompactStrategy): Promise<AgentCompactResult>;
@@ -391,6 +393,7 @@ declare function getAllPatternTypes(): string[];
391
393
  * Unified types for schema change tracking, snapshots, and removal categorization.
392
394
  * Used by @almadar/server for Firestore storage and by consumers for type safety.
393
395
  */
396
+
394
397
  /**
395
398
  * A single change within a changeset.
396
399
  */
@@ -445,7 +448,7 @@ interface ChangeSetDocument {
445
448
  interface SnapshotDocument {
446
449
  id: string;
447
450
  timestamp: number;
448
- schema: Record<string, unknown>;
451
+ schema: OrbitalSchema;
449
452
  reason: string;
450
453
  version?: number;
451
454
  }
@@ -621,6 +624,7 @@ interface ValidationDocument {
621
624
  *
622
625
  * @packageDocumentation
623
626
  */
627
+
624
628
  /**
625
629
  * All known service action names across all contracts.
626
630
  * Kept in sync with `tools/almadar-service-sync/services-registry.json`.
@@ -635,11 +639,20 @@ type PersistActionName = "create" | "update" | "delete" | "list" | "query";
635
639
  type ServiceActionName = PersistActionName | "get" | "getById" | "set" | "remove" | "size" | "generate" | "classify" | "extract" | "summarize" | "send" | "sendMessage" | "sendSMS" | "sendWhatsApp" | "authorize" | "revoke" | "token" | "refresh" | "userinfo" | "register" | "cloneRepo" | "commit" | "createBranch" | "createPR" | "getPRComments" | "pull" | "push" | "build" | "compile" | "compileSchema" | "run" | "validate" | "validateSchema" | "publish" | "enqueue" | "dequeue" | "cancel" | "upload" | "download" | "getSignedUrl" | "search" | "getIssue" | "listIssues" | "generateAll" | "generateDomainLanguage" | "generateFix" | "generateOrbitals" | "cancelGeneration" | "getGenerationHistory" | "recordGeneration" | "startSpan" | "endSpan" | "getSpan" | "recordMetric" | "getMetrics" | "increment" | "logs" | "addEvent" | "emit" | "findEmitters" | "findListeners" | "getListenerCounts" | "getChannel" | "subscribe" | "getUserPreferences" | "updateUserPreferences" | "getThreadHistory" | "getVideo" | "createPaymentIntent" | "confirmPayment" | "refund" | "complete" | "fail" | "expire" | "resume" | "status" | "stop" | "lock" | "unlock" | "clear";
636
640
  /**
637
641
  * Action definition for a service contract.
638
- * Each action has typed params and a typed result.
642
+ *
643
+ * - `params` is bus-payload-shaped (`ServiceParams`): JSON-serializable
644
+ * key/value bag with optional nesting. Service contracts override this
645
+ * with stricter shapes via the generic position on `ServiceContract`.
646
+ *
647
+ * - `result` is JSON-serializable too (`EventPayloadValue`): a primitive,
648
+ * `null`/`undefined`, an array of values, or an `EventPayload` object.
649
+ * This is the same recursive shape the bus accepts when an effect's
650
+ * `success` event fires with the call-service result, so no boundary
651
+ * widening is needed when the runtime forwards the value.
639
652
  */
640
653
  interface ServiceAction {
641
- params: Record<string, unknown>;
642
- result: unknown;
654
+ params: ServiceParams;
655
+ result: EventPayloadValue;
643
656
  }
644
657
  /**
645
658
  * What `["call-service", "name", "action", {...}]` actually calls at runtime.
@@ -678,7 +691,7 @@ interface ServiceContract<Actions extends Record<string, ServiceAction>> {
678
691
  * events.emit('LLM_RESPONSE', { requestId: '1', content: '...', tokensUsed: 42 });
679
692
  * ```
680
693
  */
681
- interface ServiceEvents<EventMap extends Record<string, Record<string, unknown>>> {
694
+ interface ServiceEvents<EventMap extends Record<string, EventPayload>> {
682
695
  emit<E extends keyof EventMap & string>(event: E, payload: EventMap[E]): void;
683
696
  on<E extends keyof EventMap & string>(event: E, handler: (payload: EventMap[E]) => void): () => void;
684
697
  }
@@ -719,9 +732,9 @@ interface ServiceEvents<EventMap extends Record<string, Record<string, unknown>>
719
732
  * const typedBus = createTypedEventBus<MyEvents>(rawBus);
720
733
  * typedBus.emit('user.created', { id: '123', name: 'Alice' });
721
734
  */
722
- declare function createTypedEventBus<EventMap extends Record<string, Record<string, unknown>>>(bus: {
723
- emit(event: string, payload?: unknown, meta?: Record<string, unknown>): void;
724
- on(event: string, handler: (payload: unknown, meta?: Record<string, unknown>) => void): () => void;
735
+ declare function createTypedEventBus<EventMap extends Record<string, EventPayload>>(bus: {
736
+ emit(event: string, payload?: unknown, meta?: LogMeta): void;
737
+ on(event: string, handler: (payload: unknown, meta?: LogMeta) => void): () => void;
725
738
  }): ServiceEvents<EventMap>;
726
739
  /** Filter operator for store queries. */
727
740
  type StoreFilterOp = "==" | "!=" | "<" | "<=" | ">" | ">=" | "in" | "not-in" | "contains";
@@ -896,7 +909,7 @@ interface ResolvedTraitUIBinding {
896
909
  /** Presentation type: modal, drawer, popover, inline, confirm-dialog */
897
910
  presentation: string;
898
911
  /** Content pattern(s) to render */
899
- content: Record<string, unknown> | Record<string, unknown>[];
912
+ content: AnyPatternConfig | AnyPatternConfig[];
900
913
  /** Presentation props */
901
914
  props?: {
902
915
  size?: string;
@@ -951,7 +964,7 @@ interface ResolvedPattern {
951
964
  /** Pattern type (e.g., 'page-header', 'entity-list', 'game-canvas') */
952
965
  type: string;
953
966
  /** Pattern configuration */
954
- config: Record<string, unknown>;
967
+ config: AnyPatternConfig;
955
968
  /** Shell component to use */
956
969
  shellComponent?: string;
957
970
  }
@@ -1351,8 +1364,16 @@ interface OrbitalVerificationAPI {
1351
1364
  * Send an event into the runtime. Requires {@link bindEventBus} (in
1352
1365
  * `@almadar/ui`) to have run at least once. Payload typed as
1353
1366
  * {@link EventPayload} so callers can't slip non-bus-shaped data in.
1367
+ *
1368
+ * `traitScope` is the qualified `Orbital.Trait` (or `App.Trait`)
1369
+ * scope that bus listeners subscribe under. The bridge constructs
1370
+ * `UI:${traitScope}.${event}` and emits that on the bus, matching
1371
+ * the codegen-emitted subscription keys (gap #13). When omitted,
1372
+ * the legacy bare-prefix form `UI:${event}` is used — kept only
1373
+ * for system-scope events like `UI:NOTIFY`; trait-driven dispatch
1374
+ * MUST pass a `traitScope`.
1354
1375
  */
1355
- sendEvent?: (event: string, payload?: EventPayload) => void;
1376
+ sendEvent?: (event: string, payload?: EventPayload, traitScope?: string) => void;
1356
1377
  /** Current state name for a given trait, if known. */
1357
1378
  getTraitState?: (traitName: string) => string | undefined;
1358
1379
  /** Per-trait reducer snapshots (VG4/VG6/VG11a/b/c). */
@@ -1367,4 +1388,4 @@ interface OrbitalVerificationAPI {
1367
1388
  clearEventLog?: () => void;
1368
1389
  }
1369
1390
 
1370
- export { type AgentCodeSearchResult, type AgentCompactResult, type AgentCompactStrategy, type AgentContext, type AgentGenerateOptions, type AgentMemoryCategory, type AgentMemoryRecord, type AppSummary, type AssetLoadStatus, BINDING_CONTEXT_RULES, BINDING_DOCS, BINDING_ROOTS, type BindingContext, type BindingRoot, BindingSchema, type BridgeHealth, type BusEvent, type BusEventListener, type BusEventSource, type CategorizedRemovals, type ChangeAuthor, type ChangeSetDocument, type ChangeSummary, type CheckStatus, type ContextExtensions, type CreateFlow, DEFAULT_INTERACTION_MODELS, type DeleteFlow, type EditFlow, type EffectTrace, EntityRow, type EventKey, type EventLogEntry, EventPayload, FieldValue, type GitHubLink, type HistoryMeta, type InteractionModel, type InteractionModelInput, InteractionModelSchema, type LazyService, type ListInteraction, type OrbitalVerificationAPI, type PageContentReduction, PatternTypeSchema, type PersistActionName, type ResolvedEntity, type ResolvedEntityBinding, type ResolvedField, type ResolvedIR, type ResolvedNavigation, type ResolvedPage, type ResolvedPattern, type ResolvedSection, type ResolvedSectionEvent, type ResolvedTrait, type ResolvedTraitBinding, type ResolvedTraitDataEntity, type ResolvedTraitEvent, type ResolvedTraitGuard, type ResolvedTraitListener, type ResolvedTraitState, type ResolvedTraitTick, type ResolvedTraitTransition, type ResolvedTraitUIBinding, SExpr, type SaveOptions, type SaveResult, type SchemaChange, type SemanticChangeKind, type SemanticSchemaChange, type ServerResponseTrace, type ServiceAction, type ServiceActionName, type ServiceContract, type ServiceEvents, type SnapshotDocument, type StatsView, type StoreContract, type StoreFilter, type StoreFilterOp, TraitConfig, type TraitStateSnapshot, type TransitionFrom, type TransitionTrace, type Unsubscribe, type ValidationDocument, type ValidationIssue, type ValidationMeta, type ValidationResults, type VerificationCheck, type VerificationSnapshot, type VerificationSummary, type ViewFlow, createEmptyResolvedPage, createEmptyResolvedTrait, createLazyService, createResolvedField, createTypedEventBus, getAllPatternTypes, getBindingExamples, getInteractionModelForDomain, inferTsType, isResolvedIR, toBindingRoot, validateBindingInContext };
1391
+ export { type AgentCodeSearchResult, type AgentCompactResult, type AgentCompactStrategy, type AgentContext, type AgentGenerateOptions, type AgentMemoryCategory, type AgentMemoryRecord, OrbitalSchema as AppSchema, type AppSummary, type AssetLoadStatus, BINDING_CONTEXT_RULES, BINDING_DOCS, BINDING_ROOTS, type BindingContext, type BindingRoot, BindingSchema, type BridgeHealth, type BusEvent, type BusEventListener, type BusEventSource, type CategorizedRemovals, type ChangeAuthor, type ChangeSetDocument, type ChangeSummary, type CheckStatus, type ContextExtensions, type CreateFlow, DEFAULT_INTERACTION_MODELS, type DeleteFlow, type EditFlow, type EffectTrace, EntityRow, type EventKey, type EventLogEntry, EventPayload, EventPayloadValue, FieldValue, type GitHubLink, type HistoryMeta, type InteractionModel, type InteractionModelInput, InteractionModelSchema, type LazyService, type ListInteraction, LogMeta, OrbitalSchema, type OrbitalVerificationAPI, type PageContentReduction, PatternTypeSchema, type PersistActionName, type ResolvedEntity, type ResolvedEntityBinding, type ResolvedField, type ResolvedIR, type ResolvedNavigation, type ResolvedPage, type ResolvedPattern, type ResolvedSection, type ResolvedSectionEvent, type ResolvedTrait, type ResolvedTraitBinding, type ResolvedTraitDataEntity, type ResolvedTraitEvent, type ResolvedTraitGuard, type ResolvedTraitListener, type ResolvedTraitState, type ResolvedTraitTick, type ResolvedTraitTransition, type ResolvedTraitUIBinding, SExpr, type SaveOptions, type SaveResult, type SchemaChange, type SemanticChangeKind, type SemanticSchemaChange, type ServerResponseTrace, type ServiceAction, type ServiceActionName, type ServiceContract, type ServiceEvents, ServiceParams, type SnapshotDocument, type StatsView, type StoreContract, type StoreFilter, type StoreFilterOp, TraitConfig, type TraitStateSnapshot, type TransitionFrom, type TransitionTrace, type Unsubscribe, type ValidationDocument, type ValidationIssue, type ValidationMeta, type ValidationResults, type VerificationCheck, type VerificationSnapshot, type VerificationSummary, type ViewFlow, createEmptyResolvedPage, createEmptyResolvedTrait, createLazyService, createResolvedField, createTypedEventBus, getAllPatternTypes, getBindingExamples, getInteractionModelForDomain, inferTsType, isResolvedIR, toBindingRoot, validateBindingInContext };