From 98cc05d2667792d8859ea7ad79a349fe473c3258 Mon Sep 17 00:00:00 2001 From: "glm-5.1" Date: Mon, 27 Apr 2026 12:00:17 +0000 Subject: [PATCH] =?UTF-8?q?feat(graph/queries):=20implement=20query=20meth?= =?UTF-8?q?ods=20=E2=80=94=20hasCycles,=20findCycles,=20topologicalOrder,?= =?UTF-8?q?=20dependencies,=20dependents,=20taskCount,=20getTask?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - hasCycles(): uses graphology-dag.hasCycle() as fast boolean check - findCycles(): SCC pre-check + custom 3-color DFS for cycle path extraction - topologicalOrder(): graphology-dag.topologicalSort + CircularDependencyError on cycle - dependencies/dependents: inNeighbors/outNeighbors with TaskNotFoundError - taskCount(): graph.order, getTask(): node attributes or undefined - 45 unit tests covering all acceptance criteria --- src/graph/construction.ts | 81 ++++ src/graph/queries.ts | 170 +++++++- tasks/implementation/graph/queries.md | 25 +- test/queries.test.ts | 550 ++++++++++++++++++++++++++ 4 files changed, 814 insertions(+), 12 deletions(-) create mode 100644 test/queries.test.ts diff --git a/src/graph/construction.ts b/src/graph/construction.ts index 8b0f929..094fe4d 100644 --- a/src/graph/construction.ts +++ b/src/graph/construction.ts @@ -2,6 +2,15 @@ import { DirectedGraph } from 'graphology'; import type { TaskGraphNodeAttributes, TaskGraphEdgeAttributes, TaskGraphSerialized } from '../schema/index.js'; +import { + hasCycles as _hasCycles, + findCycles as _findCycles, + topologicalOrder as _topologicalOrder, + dependencies as _dependencies, + dependents as _dependents, + taskCount as _taskCount, + getTask as _getTask, +} from './queries.js'; /** * Internal graph type alias for the graphology DirectedGraph with our attribute types. @@ -130,4 +139,76 @@ export class TaskGraph { graph._graph.import(data); return graph; } + + // --------------------------------------------------------------------------- + // Query methods + // --------------------------------------------------------------------------- + + /** + * Check whether the graph contains any cycles. + * + * Uses `graphology-dag.hasCycle()` as a fast boolean check. + */ + hasCycles(): boolean { + return _hasCycles(this._graph); + } + + /** + * Find all cycle paths in the graph. + * + * Uses `stronglyConnectedComponents()` as a fast pre-check, then runs a + * custom 3-color DFS (WHITE/GREY/BLACK) to extract cycle paths. + * + * Returns **one representative cycle per back edge**, not an exhaustive + * enumeration of all simple cycles. Each inner array is an ordered node + * sequence where the last node has an edge back to the first: + * `[A, B, C]` means A → B → C → A. + */ + findCycles(): string[][] { + return _findCycles(this._graph); + } + + /** + * Return task IDs in topological (prerequisite → dependent) order. + * + * Uses `graphology-dag.topologicalSort()` for the actual sort. + * + * @throws {CircularDependencyError} When the graph is cyclic, with `cycles` + * populated from `findCycles()`. + */ + topologicalOrder(): string[] { + return _topologicalOrder(this._graph); + } + + /** + * Return the prerequisite task IDs for a given task. + * + * @throws {TaskNotFoundError} If `taskId` doesn't exist in the graph. + */ + dependencies(taskId: string): string[] { + return _dependencies(this._graph, taskId); + } + + /** + * Return the dependent task IDs for a given task. + * + * @throws {TaskNotFoundError} If `taskId` doesn't exist in the graph. + */ + dependents(taskId: string): string[] { + return _dependents(this._graph, taskId); + } + + /** + * Return the number of tasks (nodes) in the graph. + */ + taskCount(): number { + return _taskCount(this._graph); + } + + /** + * Return the attributes of a task node, or `undefined` if it doesn't exist. + */ + getTask(taskId: string): TaskGraphNodeAttributes | undefined { + return _getTask(this._graph, taskId); + } } \ No newline at end of file diff --git a/src/graph/queries.ts b/src/graph/queries.ts index 6113a1c..4ebc8c6 100644 --- a/src/graph/queries.ts +++ b/src/graph/queries.ts @@ -1 +1,169 @@ -// Graph queries — hasCycles, findCycles, topologicalOrder, dependencies, dependents \ No newline at end of file +// Graph queries — hasCycles, findCycles, topologicalOrder, dependencies, dependents, +// taskCount, getTask + +import { hasCycle, topologicalSort } from 'graphology-dag'; +import { stronglyConnectedComponents } from 'graphology-components'; +import type { TaskGraphInner } from './construction.js'; +import type { TaskGraphNodeAttributes } from '../schema/index.js'; +import { TaskNotFoundError, CircularDependencyError } from '../error/index.js'; + +// --------------------------------------------------------------------------- +// 3-color DFS constants for findCycles +// --------------------------------------------------------------------------- + +const WHITE = 0; // unvisited +const GREY = 1; // in current recursion stack +const BLACK = 2; // finished — all descendants explored + +// --------------------------------------------------------------------------- +// Query functions (operating on the inner graphology graph) +// --------------------------------------------------------------------------- + +/** + * Check whether the graph contains any cycles. + * + * Uses `graphology-dag.hasCycle()` as a fast boolean check. + */ +export function hasCycles(graph: TaskGraphInner): boolean { + return hasCycle(graph); +} + +/** + * Find all cycle paths in the graph. + * + * **Algorithm**: + * 1. Fast pre-check via `stronglyConnectedComponents()`: if there are zero + * multi-node SCCs (and no self-loops — which our graph config forbids), + * return `[]` immediately. + * 2. Otherwise, run a custom 3-color DFS (WHITE/GREY/BLACK). When a back + * edge is found (GREY → GREY), trace back through the recursion stack to + * extract the cycle path as an **ordered node sequence** where the last + * node has an edge back to the first. + * + * Returns **one representative cycle per back edge**, not an exhaustive + * enumeration of all simple cycles (which could be exponential). + * + * Each inner array is an ordered sequence of node IDs representing a single + * cycle: `[A, B, C]` means A → B → C → A. + */ +export function findCycles(graph: TaskGraphInner): string[][] { + // Fast pre-check: if no multi-node SCCs exist, the graph is acyclic. + // (Self-loops are prohibited by our graph config, so we only check SCCs.) + const sccs = stronglyConnectedComponents(graph); + const hasMultiNodeScc = sccs.some((component) => component.length > 1); + if (!hasMultiNodeScc) { + return []; + } + + // 3-color DFS to extract cycle paths + const color = new Map(); + const stack: string[] = []; // current recursion stack + const cycles: string[][] = []; + + for (const node of graph.nodes()) { + color.set(node, WHITE); + } + + for (const startNode of graph.nodes()) { + if (color.get(startNode) !== WHITE) continue; + dfs(graph, startNode, color, stack, cycles); + } + + return cycles; +} + +/** + * Recursive 3-color DFS that detects back edges and extracts cycle paths. + * + * When we encounter a neighbor that is GREY (in the current recursion stack), + * we've found a back edge and can extract the cycle by slicing the recursion + * stack from that neighbor's position to the current position. + */ +function dfs( + graph: TaskGraphInner, + node: string, + color: Map, + stack: string[], + cycles: string[][], +): void { + color.set(node, GREY); + stack.push(node); + + for (const neighbor of graph.outNeighbors(node)) { + const neighborColor = color.get(neighbor); + + if (neighborColor === GREY) { + // Back edge found — extract the cycle path + const cycleStart = stack.indexOf(neighbor); + const cycle = stack.slice(cycleStart); + cycles.push(cycle); + } else if (neighborColor === WHITE) { + dfs(graph, neighbor, color, stack, cycles); + } + // If BLACK, skip — this subtree is already fully explored + } + + stack.pop(); + color.set(node, BLACK); +} + +/** + * Return task IDs in topological (prerequisite → dependent) order. + * + * Uses `graphology-dag.topologicalSort()` for the actual sort. + * + * @throws {CircularDependencyError} When the graph is cyclic, with `cycles` + * populated from `findCycles()`. + */ +export function topologicalOrder(graph: TaskGraphInner): string[] { + try { + return topologicalSort(graph); + } catch { + // Graph is cyclic — throw with cycle information + throw new CircularDependencyError(findCycles(graph)); + } +} + +/** + * Return the prerequisite task IDs (inNeighbors) for a given task. + * + * @throws {TaskNotFoundError} If `taskId` doesn't exist in the graph. + */ +export function dependencies(graph: TaskGraphInner, taskId: string): string[] { + if (!graph.hasNode(taskId)) { + throw new TaskNotFoundError(taskId); + } + return graph.inNeighbors(taskId); +} + +/** + * Return the dependent task IDs (outNeighbors) for a given task. + * + * @throws {TaskNotFoundError} If `taskId` doesn't exist in the graph. + */ +export function dependents(graph: TaskGraphInner, taskId: string): string[] { + if (!graph.hasNode(taskId)) { + throw new TaskNotFoundError(taskId); + } + return graph.outNeighbors(taskId); +} + +/** + * Return the number of tasks (nodes) in the graph. + */ +export function taskCount(graph: TaskGraphInner): number { + return graph.order; +} + +/** + * Return the attributes of a task node, or `undefined` if it doesn't exist. + */ +export function getTask( + graph: TaskGraphInner, + taskId: string, +): TaskGraphNodeAttributes | undefined { + if (!graph.hasNode(taskId)) { + return undefined; + } + return graph.getNodeAttributes(taskId); +} \ No newline at end of file diff --git a/tasks/implementation/graph/queries.md b/tasks/implementation/graph/queries.md index a2019e5..4b46e5b 100644 --- a/tasks/implementation/graph/queries.md +++ b/tasks/implementation/graph/queries.md @@ -1,7 +1,7 @@ --- id: graph/queries name: Implement TaskGraph query methods (hasCycles, findCycles, topologicalOrder, dependencies, dependents, taskCount, getTask) -status: pending +status: completed depends_on: - graph/taskgraph-class scope: moderate @@ -21,21 +21,21 @@ Per [errors-validation.md](../../../docs/architecture/errors-validation.md): ## Acceptance Criteria -- [ ] `hasCycles(): boolean` — uses `graphology-dag.hasCycle()` or `graphology-components` SCC check as fast pre-check -- [ ] `findCycles(): string[][]`: +- [x] `hasCycles(): boolean` — uses `graphology-dag.hasCycle()` or `graphology-components` SCC check as fast pre-check +- [x] `findCycles(): string[][]`: - Uses `stronglyConnectedComponents()` as pre-check: if zero multi-node SCCs and no self-loops, skip DFS - Custom 3-color DFS (WHITE/GREY/BLACK) to extract cycle paths - Returns one representative cycle per back edge, not exhaustive enumeration - Each inner array is an ordered node sequence where last node has edge back to first -- [ ] `topologicalOrder(): string[]`: +- [x] `topologicalOrder(): string[]`: - Uses `graphology-dag.topologicalSort()` for the actual sort - **Throws `CircularDependencyError`** (with `cycles` from `findCycles()`) when graph is cyclic - Returns `string[]` of task IDs in prerequisite→dependent order -- [ ] `dependencies(taskId: string): string[]` — returns prerequisite task IDs (inNeighbors). Throws `TaskNotFoundError` if ID doesn't exist. -- [ ] `dependents(taskId: string): string[]` — returns dependent task IDs (outNeighbors). Throws `TaskNotFoundError` if ID doesn't exist. -- [ ] `taskCount(): number` — returns number of nodes -- [ ] `getTask(taskId: string): TaskGraphNodeAttributes | undefined` — returns node attributes or undefined -- [ ] Unit tests: cycle detection on known cyclic/acyclic graphs, topologicalOrder on DAG, topologicalOrder throws on cyclic graph, dependency/dependent queries +- [x] `dependencies(taskId: string): string[]` — returns prerequisite task IDs (inNeighbors). Throws `TaskNotFoundError` if ID doesn't exist. +- [x] `dependents(taskId: string): string[]` — returns dependent task IDs (outNeighbors). Throws `TaskNotFoundError` if ID doesn't exist. +- [x] `taskCount(): number` — returns number of nodes +- [x] `getTask(taskId: string): TaskGraphNodeAttributes | undefined` — returns node attributes or undefined +- [x] Unit tests: cycle detection on known cyclic/acyclic graphs, topologicalOrder on DAG, topologicalOrder throws on cyclic graph, dependency/dependent queries ## References @@ -46,8 +46,11 @@ Per [errors-validation.md](../../../docs/architecture/errors-validation.md): ## Notes -> To be filled by implementation agent +findCycles uses a custom 3-color DFS (WHITE/GREY/BLACK) as specified — graphology-components only gives SCCs, not cycle paths. The DFS traces the recursion stack on back edges to extract ordered cycle paths. ## Summary -> To be filled on completion \ No newline at end of file +Implemented all 7 query methods in `src/graph/queries.ts` as free functions operating on the inner graphology graph, and integrated them as instance methods on `TaskGraph`. +- Created: `src/graph/queries.ts`, `test/queries.test.ts` +- Modified: `src/graph/construction.ts` (added query method imports and 7 instance methods) +- Tests: 45, all passing (full suite: 302 passing) \ No newline at end of file diff --git a/test/queries.test.ts b/test/queries.test.ts new file mode 100644 index 0000000..82513ea --- /dev/null +++ b/test/queries.test.ts @@ -0,0 +1,550 @@ +import { describe, it, expect } from 'vitest'; +import { TaskGraph } from '../src/graph/index.js'; +import { + hasCycles, + findCycles, + topologicalOrder, + dependencies, + dependents, + taskCount, + getTask, +} from '../src/graph/queries.js'; +import { TaskNotFoundError, CircularDependencyError } from '../src/error/index.js'; +import type { TaskGraphSerialized } from '../src/schema/index.js'; + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +/** Create a simple DAG: A → B → C → D */ +function makeLinearChain(): TaskGraph { + const data: TaskGraphSerialized = { + attributes: {}, + options: { type: 'directed', multi: false, allowSelfLoops: false }, + nodes: [ + { key: 'A', attributes: { name: 'Task A' } }, + { key: 'B', attributes: { name: 'Task B' } }, + { key: 'C', attributes: { name: 'Task C' } }, + { key: 'D', attributes: { name: 'Task D' } }, + ], + edges: [ + { key: 'A->B', source: 'A', target: 'B', attributes: {} }, + { key: 'B->C', source: 'B', target: 'C', attributes: {} }, + { key: 'C->D', source: 'C', target: 'D', attributes: {} }, + ], + }; + return new TaskGraph(data); +} + +/** Create a diamond DAG: A → B → D, A → C → D */ +function makeDiamond(): TaskGraph { + const data: TaskGraphSerialized = { + attributes: {}, + options: { type: 'directed', multi: false, allowSelfLoops: false }, + nodes: [ + { key: 'A', attributes: { name: 'Task A' } }, + { key: 'B', attributes: { name: 'Task B' } }, + { key: 'C', attributes: { name: 'Task C' } }, + { key: 'D', attributes: { name: 'Task D' } }, + ], + edges: [ + { key: 'A->B', source: 'A', target: 'B', attributes: {} }, + { key: 'A->C', source: 'A', target: 'C', attributes: {} }, + { key: 'B->D', source: 'B', target: 'D', attributes: {} }, + { key: 'C->D', source: 'C', target: 'D', attributes: {} }, + ], + }; + return new TaskGraph(data); +} + +/** Create a cyclic graph: A → B → C → A (cycle), plus A → D (non-cyclic branch) */ +function makeCyclic(): TaskGraph { + const data: TaskGraphSerialized = { + attributes: {}, + options: { type: 'directed', multi: false, allowSelfLoops: false }, + nodes: [ + { key: 'A', attributes: { name: 'Task A' } }, + { key: 'B', attributes: { name: 'Task B' } }, + { key: 'C', attributes: { name: 'Task C' } }, + { key: 'D', attributes: { name: 'Task D' } }, + ], + edges: [ + { key: 'A->B', source: 'A', target: 'B', attributes: {} }, + { key: 'B->C', source: 'B', target: 'C', attributes: {} }, + { key: 'C->A', source: 'C', target: 'A', attributes: {} }, + { key: 'A->D', source: 'A', target: 'D', attributes: {} }, + ], + }; + return new TaskGraph(data); +} + +/** Create a graph with two independent cycles: A→B→C→A and X→Y→X */ +function makeTwoCycles(): TaskGraph { + const data: TaskGraphSerialized = { + attributes: {}, + options: { type: 'directed', multi: false, allowSelfLoops: false }, + nodes: [ + { key: 'A', attributes: { name: 'A' } }, + { key: 'B', attributes: { name: 'B' } }, + { key: 'C', attributes: { name: 'C' } }, + { key: 'X', attributes: { name: 'X' } }, + { key: 'Y', attributes: { name: 'Y' } }, + ], + edges: [ + { key: 'A->B', source: 'A', target: 'B', attributes: {} }, + { key: 'B->C', source: 'B', target: 'C', attributes: {} }, + { key: 'C->A', source: 'C', target: 'A', attributes: {} }, + { key: 'X->Y', source: 'X', target: 'Y', attributes: {} }, + { key: 'Y->X', source: 'Y', target: 'X', attributes: {} }, + ], + }; + return new TaskGraph(data); +} + +/** Create an empty graph with no nodes */ +function makeEmpty(): TaskGraph { + return new TaskGraph(); +} + +// --------------------------------------------------------------------------- +// Tests: hasCycles +// --------------------------------------------------------------------------- + +describe('hasCycles', () => { + it('returns false for an empty graph', () => { + const g = makeEmpty(); + expect(hasCycles(g.raw)).toBe(false); + expect(g.hasCycles()).toBe(false); + }); + + it('returns false for a linear chain (DAG)', () => { + const g = makeLinearChain(); + expect(hasCycles(g.raw)).toBe(false); + expect(g.hasCycles()).toBe(false); + }); + + it('returns false for a diamond DAG', () => { + const g = makeDiamond(); + expect(hasCycles(g.raw)).toBe(false); + }); + + it('returns true for a cyclic graph', () => { + const g = makeCyclic(); + expect(hasCycles(g.raw)).toBe(true); + expect(g.hasCycles()).toBe(true); + }); + + it('returns true for a graph with two independent cycles', () => { + const g = makeTwoCycles(); + expect(hasCycles(g.raw)).toBe(true); + }); + + it('returns false for a single node with no edges', () => { + const g = new TaskGraph(); + g.raw.addNode('only', { name: 'Only' }); + expect(hasCycles(g.raw)).toBe(false); + }); +}); + +// --------------------------------------------------------------------------- +// Tests: findCycles +// --------------------------------------------------------------------------- + +describe('findCycles', () => { + it('returns empty array for an empty graph', () => { + const g = makeEmpty(); + expect(findCycles(g.raw)).toEqual([]); + expect(g.findCycles()).toEqual([]); + }); + + it('returns empty array for an acyclic graph', () => { + const g = makeLinearChain(); + expect(findCycles(g.raw)).toEqual([]); + }); + + it('returns empty array for a diamond DAG', () => { + const g = makeDiamond(); + expect(findCycles(g.raw)).toEqual([]); + }); + + it('finds a single cycle in a simple cyclic graph (A→B→C→A)', () => { + const g = makeCyclic(); + const cycles = findCycles(g.raw); + expect(cycles.length).toBeGreaterThanOrEqual(1); + + // At least one cycle should contain A, B, C + const cycle = cycles[0]!; + expect(cycle).toContain('A'); + expect(cycle).toContain('B'); + expect(cycle).toContain('C'); + + // The cycle should be an ordered path where last→first is an edge + const first = cycle[0]!; + const last = cycle[cycle.length - 1]!; + expect(g.raw.hasEdge(last, first)).toBe(true); + }); + + it('each cycle is an ordered path: last node has edge to first', () => { + const g = makeCyclic(); + const cycles = findCycles(g.raw); + for (const cycle of cycles) { + if (cycle.length > 1) { + const first = cycle[0]!; + const last = cycle[cycle.length - 1]!; + expect(g.raw.hasEdge(last, first)).toBe(true); + } + } + }); + + it('finds cycles in a graph with two independent cycles', () => { + const g = makeTwoCycles(); + const cycles = findCycles(g.raw); + // Should find at least 2 cycles (one in each component) + expect(cycles.length).toBeGreaterThanOrEqual(2); + + // Check that we have cycles covering both components + const allNodes = cycles.flat(); + expect(allNodes).toContain('A'); + expect(allNodes).toContain('B'); + expect(allNodes).toContain('C'); + expect(allNodes).toContain('X'); + expect(allNodes).toContain('Y'); + }); + + it('uses SCC pre-check optimization (skips DFS for acyclic graphs)', () => { + // This tests the optimization path: for acyclic graphs, + // findCycles should return [] quickly without running DFS. + // We just verify the result is correct; the optimization is internal. + const g = makeLinearChain(); + expect(findCycles(g.raw)).toEqual([]); + }); + + it('returns one representative cycle per back edge, not exhaustive enumeration', () => { + const g = makeCyclic(); + const cycles = findCycles(g.raw); + // A→B→C→A has one back edge (C→A), so we should get exactly 1 cycle + expect(cycles.length).toBe(1); + }); + + it('finds cycle in a two-node cycle: X→Y→X', () => { + const data: TaskGraphSerialized = { + attributes: {}, + options: { type: 'directed', multi: false, allowSelfLoops: false }, + nodes: [ + { key: 'X', attributes: { name: 'X' } }, + { key: 'Y', attributes: { name: 'Y' } }, + ], + edges: [ + { key: 'X->Y', source: 'X', target: 'Y', attributes: {} }, + { key: 'Y->X', source: 'Y', target: 'X', attributes: {} }, + ], + }; + const g = new TaskGraph(data); + const cycles = findCycles(g.raw); + expect(cycles.length).toBeGreaterThanOrEqual(1); + const cycle = cycles[0]!; + expect(cycle).toContain('X'); + expect(cycle).toContain('Y'); + expect(cycle.length).toBe(2); + // Last → first should be an edge + expect(g.raw.hasEdge(cycle[cycle.length - 1]!, cycle[0]!)).toBe(true); + }); + + it('TaskGraph instance method delegates to the free function', () => { + const g = makeCyclic(); + const fromFunction = findCycles(g.raw); + const fromMethod = g.findCycles(); + expect(fromFunction).toEqual(fromMethod); + }); +}); + +// --------------------------------------------------------------------------- +// Tests: topologicalOrder +// --------------------------------------------------------------------------- + +describe('topologicalOrder', () => { + it('returns correct topological order for a linear chain', () => { + const g = makeLinearChain(); + const order = topologicalOrder(g.raw); + expect(order).toEqual(['A', 'B', 'C', 'D']); + expect(g.topologicalOrder()).toEqual(order); + }); + + it('returns valid topological order for a diamond DAG', () => { + const g = makeDiamond(); + const order = topologicalOrder(g.raw); + // A must come before B and C, which must both come before D + const aIdx = order.indexOf('A'); + const bIdx = order.indexOf('B'); + const cIdx = order.indexOf('C'); + const dIdx = order.indexOf('D'); + expect(aIdx).toBeLessThan(bIdx); + expect(aIdx).toBeLessThan(cIdx); + expect(bIdx).toBeLessThan(dIdx); + expect(cIdx).toBeLessThan(dIdx); + expect(order).toHaveLength(4); + }); + + it('returns single node order for a single-node graph', () => { + const g = new TaskGraph(); + g.raw.addNode('only', { name: 'Only' }); + expect(topologicalOrder(g.raw)).toEqual(['only']); + }); + + it('returns empty array for an empty graph', () => { + const g = makeEmpty(); + expect(topologicalOrder(g.raw)).toEqual([]); + }); + + it('throws CircularDependencyError when graph is cyclic', () => { + const g = makeCyclic(); + expect(() => topologicalOrder(g.raw)).toThrow(CircularDependencyError); + expect(() => g.topologicalOrder()).toThrow(CircularDependencyError); + }); + + it('CircularDependencyError contains cycles from findCycles', () => { + const g = makeCyclic(); + try { + topologicalOrder(g.raw); + expect.fail('Should have thrown'); + } catch (e) { + expect(e).toBeInstanceOf(CircularDependencyError); + const err = e as CircularDependencyError; + expect(err.cycles.length).toBeGreaterThanOrEqual(1); + // The cycle should contain A, B, C + const cycle = err.cycles[0]!; + expect(cycle).toContain('A'); + expect(cycle).toContain('B'); + expect(cycle).toContain('C'); + } + }); + + it('CircularDependencyError message includes cycle description', () => { + const g = makeCyclic(); + try { + topologicalOrder(g.raw); + expect.fail('Should have thrown'); + } catch (e) { + expect(e).toBeInstanceOf(CircularDependencyError); + expect((e as Error).message).toContain('Circular dependency'); + } + }); + + it('throws with multiple cycles when graph has multiple independent cycles', () => { + const g = makeTwoCycles(); + try { + topologicalOrder(g.raw); + expect.fail('Should have thrown'); + } catch (e) { + expect(e).toBeInstanceOf(CircularDependencyError); + const err = e as CircularDependencyError; + // Should contain cycles from both components + expect(err.cycles.length).toBeGreaterThanOrEqual(2); + } + }); + + it('returns prerequisite→dependent order (prerequisites always before dependents)', () => { + const data: TaskGraphSerialized = { + attributes: {}, + options: { type: 'directed', multi: false, allowSelfLoops: false }, + nodes: [ + { key: 'setup', attributes: { name: 'Setup' } }, + { key: 'impl', attributes: { name: 'Implementation' } }, + { key: 'test', attributes: { name: 'Test' } }, + { key: 'deploy', attributes: { name: 'Deploy' } }, + ], + edges: [ + { key: 'setup->impl', source: 'setup', target: 'impl', attributes: {} }, + { key: 'impl->test', source: 'impl', target: 'test', attributes: {} }, + { key: 'test->deploy', source: 'test', target: 'deploy', attributes: {} }, + ], + }; + const g = new TaskGraph(data); + const order = topologicalOrder(g.raw); + expect(order).toEqual(['setup', 'impl', 'test', 'deploy']); + }); +}); + +// --------------------------------------------------------------------------- +// Tests: dependencies +// --------------------------------------------------------------------------- + +describe('dependencies', () => { + it('returns prerequisites for a node with dependencies', () => { + const g = makeLinearChain(); + expect(dependencies(g.raw, 'B')).toEqual(['A']); + expect(g.dependencies('B')).toEqual(['A']); + }); + + it('returns empty array for a root node (no prerequisites)', () => { + const g = makeLinearChain(); + expect(dependencies(g.raw, 'A')).toEqual([]); + }); + + it('returns multiple prerequisites for a merge node', () => { + const g = makeDiamond(); + const deps = dependencies(g.raw, 'D'); + expect(deps).toHaveLength(2); + expect(deps).toContain('B'); + expect(deps).toContain('C'); + }); + + it('throws TaskNotFoundError for non-existent task ID', () => { + const g = makeLinearChain(); + expect(() => dependencies(g.raw, 'nonexistent')).toThrow(TaskNotFoundError); + expect(() => g.dependencies('nonexistent')).toThrow(TaskNotFoundError); + }); + + it('error contains the missing task ID', () => { + const g = makeLinearChain(); + try { + dependencies(g.raw, 'missing'); + expect.fail('Should have thrown'); + } catch (e) { + expect(e).toBeInstanceOf(TaskNotFoundError); + expect((e as TaskNotFoundError).taskId).toBe('missing'); + } + }); +}); + +// --------------------------------------------------------------------------- +// Tests: dependents +// --------------------------------------------------------------------------- + +describe('dependents', () => { + it('returns dependents for a node with outgoing edges', () => { + const g = makeLinearChain(); + expect(dependents(g.raw, 'A')).toEqual(['B']); + expect(g.dependents('A')).toEqual(['B']); + }); + + it('returns empty array for a leaf node (no dependents)', () => { + const g = makeLinearChain(); + expect(dependents(g.raw, 'D')).toEqual([]); + }); + + it('returns multiple dependents for a fan-out node', () => { + const g = makeDiamond(); + const deps = dependents(g.raw, 'A'); + expect(deps).toHaveLength(2); + expect(deps).toContain('B'); + expect(deps).toContain('C'); + }); + + it('throws TaskNotFoundError for non-existent task ID', () => { + const g = makeLinearChain(); + expect(() => dependents(g.raw, 'nonexistent')).toThrow(TaskNotFoundError); + expect(() => g.dependents('nonexistent')).toThrow(TaskNotFoundError); + }); + + it('error contains the missing task ID', () => { + const g = makeLinearChain(); + try { + dependents(g.raw, 'missing'); + expect.fail('Should have thrown'); + } catch (e) { + expect(e).toBeInstanceOf(TaskNotFoundError); + expect((e as TaskNotFoundError).taskId).toBe('missing'); + } + }); +}); + +// --------------------------------------------------------------------------- +// Tests: taskCount +// --------------------------------------------------------------------------- + +describe('taskCount', () => { + it('returns 0 for an empty graph', () => { + const g = makeEmpty(); + expect(taskCount(g.raw)).toBe(0); + expect(g.taskCount()).toBe(0); + }); + + it('returns correct count for a linear chain', () => { + const g = makeLinearChain(); + expect(taskCount(g.raw)).toBe(4); + }); + + it('returns correct count for a diamond graph', () => { + const g = makeDiamond(); + expect(taskCount(g.raw)).toBe(4); + }); + + it('returns correct count for the large graph fixture', () => { + const data: TaskGraphSerialized = { + attributes: {}, + options: { type: 'directed', multi: false, allowSelfLoops: false }, + nodes: Array.from({ length: 23 }, (_, i) => ({ + key: `task-${i}`, + attributes: { name: `Task ${i}` }, + })), + edges: [], + }; + const g = new TaskGraph(data); + expect(taskCount(g.raw)).toBe(23); + }); + + it('TaskGraph instance method delegates to the free function', () => { + const g = makeLinearChain(); + expect(g.taskCount()).toBe(taskCount(g.raw)); + }); +}); + +// --------------------------------------------------------------------------- +// Tests: getTask +// --------------------------------------------------------------------------- + +describe('getTask', () => { + it('returns node attributes for an existing task', () => { + const g = makeLinearChain(); + const attrs = getTask(g.raw, 'A'); + expect(attrs).toBeDefined(); + expect(attrs!.name).toBe('Task A'); + expect(g.getTask('A')).toEqual(attrs); + }); + + it('returns undefined for a non-existent task', () => { + const g = makeLinearChain(); + expect(getTask(g.raw, 'nonexistent')).toBeUndefined(); + expect(g.getTask('nonexistent')).toBeUndefined(); + }); + + it('returns all attributes including optional categorical fields', () => { + const data: TaskGraphSerialized = { + attributes: {}, + options: { type: 'directed', multi: false, allowSelfLoops: false }, + nodes: [ + { + key: 'auth', + attributes: { + name: 'Auth module', + risk: 'high', + scope: 'broad', + impact: 'phase', + }, + }, + ], + edges: [], + }; + const g = new TaskGraph(data); + const attrs = getTask(g.raw, 'auth'); + expect(attrs).toBeDefined(); + expect(attrs!.name).toBe('Auth module'); + expect(attrs!.risk).toBe('high'); + expect(attrs!.scope).toBe('broad'); + expect(attrs!.impact).toBe('phase'); + }); + + it('returns attributes with undefined for absent optional fields', () => { + const g = makeLinearChain(); + const attrs = getTask(g.raw, 'A'); + expect(attrs).toBeDefined(); + expect(attrs!.risk).toBeUndefined(); + expect(attrs!.scope).toBeUndefined(); + }); + + it('returns undefined for an empty graph', () => { + const g = makeEmpty(); + expect(getTask(g.raw, 'any')).toBeUndefined(); + }); +}); \ No newline at end of file