feat(app): add graph domain model for runs and definitions

Pure-Dart graph foundation mirroring the current web client:
terminal targets and labels, definition edges and nodes with web
outcome ordering, recorded run evidence (visited stages, taken
routes, current stage and live start), and sequence-ordered stage
visit selection with clamping.

No layout, widgets, screens or coordinates; fixtures cover linear,
diamond, self-loop, repeated visits, mixed outcomes, terminals and
missing/malformed evidence.
This commit is contained in:
2026-10-21 15:31:43 +01:00
parent 804e531704
commit 2c105074aa
11 changed files with 1330 additions and 0 deletions
@@ -0,0 +1,152 @@
import 'graph_protocol.dart';
/// The graph definition: nodes and edges declared by a pipeline, never the
/// evidence that a run executed them. Run evidence lives in
/// `run_graph_state.dart`; keeping the two shapes separate means a definition
/// can be drawn without claiming a visit happened.
///
/// Mirrors `stageOutcomes`, `edgeLabel`, `graphEdges` and `nodeDisplayLabel`
/// from `web/src/graph.js` (and `web/src/runDetail.js`). Pure data only.
/// Ordering priority: success first, error last, every other outcome
/// alphabetical in between (the web client's `outcomePriority`).
int _outcomePriority(String outcome) {
if (outcome == 'success') return 0;
if (outcome == 'error') return 2;
return 1;
}
/// A stage's edge outcomes in the app's one stable order.
List<String> stageOutcomes(dynamic stage) {
final edges = stage is Map ? stage['edges'] : null;
if (edges is! Map) return const <String>[];
final outcomes = edges.keys.map((key) => '$key').toList();
outcomes.sort((a, b) {
final priority = _outcomePriority(a) - _outcomePriority(b);
return priority != 0 ? priority : a.compareTo(b);
});
return outcomes;
}
/// The outcome label on an edge: `error*` for an implicit fallback error route.
String edgeLabel(dynamic stage, String outcome) {
final implicitFallback = stage is Map && stage['fallback_error'] == true;
return outcome == 'error' && implicitFallback ? 'error*' : outcome;
}
/// One declared edge, in stable definition order.
class GraphEdge {
const GraphEdge({
required this.id,
required this.source,
required this.outcome,
required this.target,
required this.label,
required this.fallback,
required this.knownTarget,
});
/// The 1-based id assigned in stable definition order (`Graph.edges()`).
final int id;
final String source;
final String outcome;
/// The resolved target: `#` has already become `#success`/`#failure`.
final String target;
final String label;
/// True only for the parser's implicit `error -> #failure` route.
final bool fallback;
/// True when [target] is a terminal or a stage declared in this graph.
///
/// An empty or unknown target is kept exactly as recorded, with this flag
/// false, so callers can show it honestly instead of inventing a node.
final bool knownTarget;
bool get isTerminal => isTerminalTarget(target);
}
/// One graph definition node: a declared stage, or a terminal the definition
/// routes to.
class GraphNode {
const GraphNode({required this.key, required this.terminal, this.stageIndex});
final String key;
final bool terminal;
/// The node's stage declaration index, or null for a terminal.
final int? stageIndex;
String get label => nodeDisplayLabel(key);
String get shortLabel => nodeLabel(key);
}
List<Map<String, dynamic>> _stages(dynamic graph) {
if (graph is! Map) return const <Map<String, dynamic>>[];
final stages = graph['stages'];
if (stages is! List) return const <Map<String, dynamic>>[];
return stages.whereType<Map>().map(Map<String, dynamic>.from).toList();
}
String _stageKey(Map<String, dynamic> stage) => '${stage['key'] ?? ''}';
/// Every definition edge in stable id order.
///
/// Stages keep declaration order and each stage's outcomes use
/// [stageOutcomes]; ids are contiguous in that order. An absent (null) edge
/// value declares no edge and is skipped, while an empty or unknown target is
/// preserved with [GraphEdge.knownTarget] false.
List<GraphEdge> graphEdges(dynamic graph) {
final stages = _stages(graph);
final stageKeys = <String>{
for (final stage in stages)
if (_stageKey(stage).isNotEmpty) _stageKey(stage),
};
final result = <GraphEdge>[];
for (final stage in stages) {
final edges = stage['edges'];
if (edges is! Map) continue;
final source = _stageKey(stage);
for (final outcome in stageOutcomes(stage)) {
final raw = edges[outcome];
if (raw == null) continue;
final target = resolveTarget(outcome, '$raw') ?? '';
result.add(
GraphEdge(
id: result.length + 1,
source: source,
outcome: outcome,
target: target,
label: edgeLabel(stage, outcome),
fallback: outcome == 'error' && stage['fallback_error'] == true,
knownTarget: isTerminalTarget(target) || stageKeys.contains(target),
),
);
}
}
return result;
}
/// The definition's nodes in declaration order.
///
/// A stage key identifies one node even when it is declared twice; self edges
/// and loops therefore never duplicate identity. Terminal nodes are appended
/// failure first, then success, once any declared edge resolves to a terminal
/// (the same `hasTerminal` rule the web layout uses). They are still
/// definition nodes, not evidence that a run reached them.
List<GraphNode> graphNodes(dynamic graph) {
final stages = _stages(graph);
final seen = <String>{};
final nodes = <GraphNode>[];
for (var index = 0; index < stages.length; index += 1) {
final key = _stageKey(stages[index]);
if (key.isEmpty || !seen.add(key)) continue;
nodes.add(GraphNode(key: key, terminal: false, stageIndex: index));
}
if (graphEdges(graph).any((edge) => edge.isTerminal)) {
nodes.add(const GraphNode(key: failureEnd, terminal: true));
nodes.add(const GraphNode(key: successEnd, terminal: true));
}
return nodes;
}
@@ -0,0 +1,43 @@
/// Protocol terminal targets and the labels the graph uses for them.
///
/// Mirrors `web/src/protocol.js` (`SUCCESS_END`, `FAILURE_END`,
/// `isTerminal`, `resolveTarget`) and the label helpers in `web/src/graph.js`.
/// Pure Dart: no Flutter imports and no layout or rendering decisions.
library;
/// The explicit success terminal (`Protocol.SUCCESS_END`).
const String successEnd = '#success';
/// The explicit failure terminal (`Protocol.FAILURE_END`).
const String failureEnd = '#failure';
/// True only for the two explicit terminal targets.
///
/// A bare `#` is not itself terminal; [resolveTarget] turns it into one using
/// the outcome, exactly as the server and the web client do.
bool isTerminalTarget(String? target) =>
target == successEnd || target == failureEnd;
/// Mirrors `Protocol.resolveTarget`: a bare `#` is the outcome's terminal.
///
/// Every other value is preserved verbatim, including an empty or unknown
/// stage key. A missing target stays null rather than becoming a terminal, so
/// a blank edge cannot fabricate a visit or a terminal node.
String? resolveTarget(String? outcome, String? target) {
if (target != '#') return target;
return outcome == 'error' ? failureEnd : successEnd;
}
/// A graph node title: a stage keeps its key, a terminal reads Success/Failure.
String nodeDisplayLabel(String? key) {
if (key == successEnd) return 'Success';
if (key == failureEnd) return 'Failure';
return key ?? '';
}
/// The TUI-mirroring label: terminal targets are all caps.
String nodeLabel(String? key) {
if (key == successEnd) return 'SUCCESS';
if (key == failureEnd) return 'FAILURE';
return key ?? '';
}
@@ -0,0 +1,124 @@
import 'graph_protocol.dart';
/// Which stages and routes a run actually recorded.
///
/// This is executed-route evidence, deliberately distinct from the graph
/// definition's nodes and edges. It mirrors `runGraphState` from
/// `web/src/runDetail.js` (Android `RunGraphState.from`): every recorded step's
/// stage is visited once in first-appearance order, a step with a non-blank
/// outcome and target contributes one deduplicated `source\0outcome\0target`
/// route, and only a resolved terminal is added by its target. A non-terminal
/// target is not visited until a step lands on it.
///
/// The run map is the same detail produced by the runs feature; this helper
/// reads recorded steps and never folds live events a second time.
class RunGraphState {
RunGraphState({
required List<String> visitedStages,
required List<String> takenRoutes,
required this.currentStage,
required this.executing,
required this.currentStageStartedAt,
}) : visitedStages = List.unmodifiable(visitedStages),
takenRoutes = List.unmodifiable(takenRoutes);
/// Visited stage keys in first-appearance order, without duplicates.
final List<String> visitedStages;
/// Taken routes as `source\0outcome\0resolvedTarget`, in recorded order.
final List<String> takenRoutes;
/// The run's current stage, else the last recorded visit's stage, else null.
final String? currentStage;
final bool executing;
/// The running visit's start for [currentStage], only while executing.
final String? currentStageStartedAt;
bool isStageVisited(String key) => visitedStages.contains(key);
/// True when a recorded visit took this definition route. The target is
/// resolved with the same `#` rule the definition edges use.
bool isRouteTaken(String source, String outcome, String target) {
final resolved = resolveTarget(outcome, target);
if (resolved == null || resolved.isEmpty) return false;
return takenRoutes.contains('$source\u0000$outcome\u0000$resolved');
}
/// The active stage for a live run, else null. A finished run has none.
String? get activeStage {
if (!executing || currentStage == null || currentStage!.isEmpty) {
return null;
}
return currentStage;
}
}
List<Map<String, dynamic>> _steps(dynamic run) {
if (run is! Map) return const <Map<String, dynamic>>[];
final steps = run['steps'];
if (steps is! List) return const <Map<String, dynamic>>[];
return steps.whereType<Map>().map(Map<String, dynamic>.from).toList();
}
String _text(dynamic value) => '${value ?? ''}';
/// Derives [RunGraphState] from one run detail map.
///
/// Missing or malformed steps yield no visits and no routes; nothing is
/// fabricated from a missing capture. Repeated visits stay one identity per
/// stage, and self edges or loops never recurse.
RunGraphState runGraphState(dynamic run) {
final steps = _steps(run);
final visitedStages = <String>[];
final seenStages = <String>{};
final takenRoutes = <String>[];
final seenRoutes = <String>{};
void visit(String? key) {
if (key == null || key.isEmpty || !seenStages.add(key)) return;
visitedStages.add(key);
}
for (final step in steps) {
final stage = _text(step['stage']);
if (stage.isNotEmpty) visit(stage);
final outcome = _text(step['outcome']);
final target = _text(step['target']);
if (outcome.trim().isEmpty || target.trim().isEmpty) continue;
final resolved = resolveTarget(outcome, target);
if (resolved == null || resolved.isEmpty) continue;
final route = '$stage\u0000$outcome\u0000$resolved';
if (seenRoutes.add(route)) takenRoutes.add(route);
if (isTerminalTarget(resolved)) visit(resolved);
}
final lastStage = steps.isEmpty ? '' : _text(steps.last['stage']);
final rawCurrent = _text(run is Map ? run['current_stage'] : null);
final currentStage = rawCurrent.trim().isNotEmpty
? rawCurrent
: (lastStage.trim().isNotEmpty ? lastStage : null);
final executing = run is Map && run['executing'] == true;
String? currentStageStartedAt;
if (executing && currentStage != null) {
for (var index = steps.length - 1; index >= 0; index -= 1) {
final step = steps[index];
if (_text(step['stage']) != currentStage) continue;
if (_text(step['status']) != 'running') continue;
final started = _text(step['started_at']);
if (started.trim().isNotEmpty) currentStageStartedAt = started;
break;
}
}
return RunGraphState(
visitedStages: visitedStages,
takenRoutes: takenRoutes,
currentStage: currentStage,
executing: executing,
currentStageStartedAt: currentStageStartedAt,
);
}
@@ -0,0 +1,107 @@
import '../../../core/api_gateway.dart';
/// Recorded stage-visit selection, matching the web client's timeline and
/// stage pane. Visits are ordered by their recorded sequence, never by the
/// order a caller happens to pass them in; repeated visits to one stage stay
/// separate entries. Pure data: no widgets, layout or coordinates.
int _sequenceOf(JsonMap step) {
final sequence = step['sequence'];
return sequence is num ? sequence.toInt() : 0;
}
int _positiveVisit(dynamic control) {
if (control is! Map) return 0;
final visit = control['visit'];
if (visit is num) return visit > 0 ? visit.toInt() : 0;
return int.tryParse('${visit ?? ''}') ?? 0;
}
/// The visit number a timeline row shows: the recorded `control.visit` when it
/// is positive, else the position within the stage's ordered visits.
int displayVisit(JsonMap step, int index) {
final recorded = _positiveVisit(step['control']);
return recorded > 0 ? recorded : index + 1;
}
/// Clamps a visit index into `[0, count)`; an empty list yields 0.
int clampVisitIndex(int index, int count) {
if (count <= 0) return 0;
if (index < 0) return 0;
return index >= count ? count - 1 : index;
}
List<JsonMap> _ordered(List<JsonMap> visits) {
final indexed = <({int position, JsonMap step})>[
for (var index = 0; index < visits.length; index += 1)
(position: index, step: visits[index]),
];
indexed.sort((a, b) {
final bySequence = _sequenceOf(a.step).compareTo(_sequenceOf(b.step));
return bySequence != 0 ? bySequence : a.position.compareTo(b.position);
});
return [for (final entry in indexed) entry.step];
}
/// Every stage's recorded visits, ordered by sequence.
///
/// The map keeps stage first-appearance order. Equal sequences keep their
/// recorded order (the web client's stable sort), and a stage with no recorded
/// visit is simply absent rather than present with a synthetic visit.
Map<String, List<JsonMap>> visitsByStage(List<JsonMap> steps) {
final grouped = <String, List<JsonMap>>{};
for (final step in steps) {
final stage = '${step['stage'] ?? ''}';
grouped.putIfAbsent(stage, () => <JsonMap>[]).add(step);
}
return <String, List<JsonMap>>{
for (final entry in grouped.entries) entry.key: _ordered(entry.value),
};
}
/// One selected stage visit. [step] is null when the stage has no recorded
/// visit, so callers cannot mistake an absent capture for an execution.
class StageVisitSelection {
const StageVisitSelection({
required this.stageKey,
required this.visits,
required this.index,
});
final String stageKey;
/// The stage's visits ordered by sequence.
final List<JsonMap> visits;
/// The clamped index into [visits]; 0 when there are none.
final int index;
bool get hasVisit => visits.isNotEmpty;
JsonMap? get step => hasVisit ? visits[index] : null;
int get visitNumber => step == null ? 0 : displayVisit(step!, index);
/// True when an explicit requested index was clamped, so a caller can
/// correct its route exactly as the web stage route does.
bool correctedRequest(int? requested) =>
requested != null && requested != index;
}
/// Selects a stage's visit exactly as the web stage pane does.
///
/// A null [visitIndex] means the stage's most recent recorded visit; an
/// out-of-range index is clamped to the last visit (negative values to the
/// first). A stage with no recorded visits returns [StageVisitSelection.step]
/// null instead of a fabricated visit.
StageVisitSelection selectStageVisit(
List<JsonMap> steps,
String stageKey, {
int? visitIndex,
}) {
final visits = visitsByStage(steps)[stageKey] ?? const <JsonMap>[];
final wanted = visitIndex ?? (visits.isEmpty ? 0 : visits.length - 1);
return StageVisitSelection(
stageKey: stageKey,
visits: visits,
index: clampVisitIndex(wanted, visits.length),
);
}
+112
View File
@@ -0,0 +1,112 @@
# P2a — graph domain: nodes, edges, terminals, run evidence and stage visits
## What changed
New, app-only, pure-Dart files. No server, web client, legacy client, shell,
`main.dart`, pubspec, other feature or platform source was edited.
| File | Lines | Responsibility |
| --- | --- | --- |
| `lib/features/graph/domain/graph_protocol.dart` | 43 | terminal constants, `resolveTarget`, terminal labels |
| `lib/features/graph/domain/graph_definition.dart` | 152 | outcome/edge order, definition edges, definition nodes |
| `lib/features/graph/domain/run_graph_state.dart` | 124 | recorded visited stages/routes, current-stage fallback, live start |
| `lib/features/graph/domain/stage_visits.dart` | 107 | sequence-ordered visits, display visit, clamped visit selection |
| `test/features/graph/domain/graph_fixtures.dart` | 96 | linear/diamond/self-loop/incomplete definitions and step fixtures |
| `test/features/graph/domain/graph_protocol_test.dart` | 56 | shorthand and terminal-label regressions |
| `test/features/graph/domain/graph_definition_test.dart` | 229 | edge order/ids, loops, duplicate keys, missing/unknown targets |
| `test/features/graph/domain/run_graph_state_test.dart` | 170 | linear/diamond/self-loop/repeated visits/outcomes/terminals/no evidence |
| `test/features/graph/domain/run_graph_state_live_test.dart` | 91 | current/last-stage fallback, live start, finished run |
| `test/features/graph/domain/stage_visits_test.dart` | 150 | repeated visits by sequence, latest default, clamping, absent visit |
No layout, coordinates, widgets, styles or rendering were added.
## Behavior copied from the current web client
- **Terminals and `#`** (`web/src/protocol.js`): `#success`, `#failure`,
`isTerminal` only for the explicit keys, and `resolveTarget`: a bare `#`
becomes `#failure` for the `error` outcome and `#success` for every other
outcome. All other values are preserved verbatim, including `""` and unknown
stage keys. A missing target stays `null`, never a fabricated terminal.
- **Labels** (`web/src/graph.js`): `nodeDisplayLabel` gives `Success` /
`Failure` for graph nodes; `nodeLabel` gives the TUI-mirroring `SUCCESS` /
`FAILURE`. Stage keys are unchanged.
- **Definition edges** (`web/src/graph.js`): outcomes are success first, other
outcomes alphabetical, `error` last; stages keep declaration order; ids are
contiguous in that order; the label carries `error*` only when
`fallback_error` is true. A `null` edge value declares no edge and is
skipped. Empty/unknown targets are kept, with `knownTarget == false`.
- **Definition nodes** (`web/src/graph.js` `layoutGraph`): stage nodes keep
declaration order and one identity per key; terminal nodes are appended
failure then success once any declared edge resolves to a terminal. These
are definition nodes only, never run evidence.
- **Run evidence** (`web/src/runDetail.js` `runGraphState`): visited stages in
first-appearance order without duplicates; routes keyed
`source\0outcome\0resolvedTarget` without duplicates; only a resolved
terminal is visited by its target; a non-terminal target is not visited until
a step lands there. Current stage is `current_stage` when non-blank, else the
last recorded step's stage, else `null`. A start timestamp is read only while
executing, for a `running` visit of the current stage.
- **Visits** (`web/src/runDetail.js` `runTimeline`, `clampVisitIndex`,
`displayVisit`, and `web/src/app.js` stage routing): visits are grouped by
stage and ordered by recorded sequence with stable ties; the display visit
is a positive `control.visit`, else position + 1; no requested visit selects
the stage's most recent visit; an explicit index clamps to `[0, count)`; a
stage with no recorded visit yields `step == null`.
The run map is the same detail the runs feature already holds; this slice only
reads `steps`, so it adds no second event fold. Live-event merging remains in
`lib/features/runs/domain/run_step_evidence.dart` and `run_events.dart`.
## Honest edge handling
- A missing/`null` definition edge produces no edge and no node.
- An empty or unknown target is returned as recorded, flagged `knownTarget:
false`; it never becomes a stage node or terminal and never produces a
visited stage.
- A blank recorded stage key is not turned into an empty visited identity. A
step with a blank outcome or target records no route and no terminal visit.
- Self edges and loops record one route and one node identity; nothing recurses.
- A stage with no recorded visits cannot be presented as visited: selection
exposes a null step rather than synthesizing one.
## Checks actually run
```
flutter pub get
dart format lib/features/graph test/features/graph # 10 files, 0 changed after formatting
flutter test test/features/graph/domain # 41 passed
flutter analyze # No issues found! (0.8s)
flutter test # 139 passed
```
Focused coverage is the requested matrix:
- **Linear**: plan -> build -> ship, contiguous ids, implicit `error*`
fallback, terminals.
- **Diamond**: fan-out/fan-in edges stay distinct and ordered; converging
routes do not merge.
- **Self loop**: `a/retry -> a` is one edge and one node identity; one run
self-loop is one route and one visited stage.
- **Repeated stage**: repeated visits remain separate ordered entries; visited
stage identity is not duplicated; repeated identical routes collapse.
- **Different outcomes**: success/approved/rejected routes to the same target
remain distinct.
- **Terminals**: bare `#` resolves by outcome, explicit terminals normalize,
labels are `SUCCESS`/`FAILURE`, mid-run targets do not fabricate visits.
- **Missing evidence**: null/absent/malformed steps and graphs yield empty
evidence, no terminals and no fabricated visits.
## Honest limits
- **No UI, layout or wiring.** This is deliberately the nonvisual foundation
slice; the native graph screen, layout, highlighting and interaction are
later work and are not claimed here.
- **No browser evidence.** A nonvisual pure-Dart change has no rendered
behavior to capture; no browser or screenshot check applies.
- **No live server or device used.** All tests use local fixtures. No run,
pipeline, schedule, workflow or service was created, changed or restarted.
- **Mobile unverified.** Only web-targeted Flutter tests and analysis ran; no
Android/iOS build, emulator, ADB or device.
- **Not committed, pushed or deployed.** The stage instruction for this visit
forbids commit/push/deploy, so the candidate remains as new untracked files
in the `flutter/p2-model` worktree for the manager to inspect and land.
@@ -0,0 +1,229 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/graph/domain/graph_definition.dart';
import 'package:pipelines_app/features/graph/domain/graph_protocol.dart';
import 'graph_fixtures.dart';
void main() {
group('outcome and edge order', () {
test('success first, other outcomes alphabetical, error last', () {
expect(
stageOutcomes(
stage(
'a',
edges: <String, String?>{
'error': '#',
'rejected': 'a',
'success': 'b',
'approved': 'b',
'retry': 'a',
},
),
),
<String>['success', 'approved', 'rejected', 'retry', 'error'],
);
expect(stageOutcomes(<String, dynamic>{}), isEmpty);
expect(stageOutcomes(null), isEmpty);
});
test('edgeLabel marks only an implicit fallback error route', () {
expect(
edgeLabel(<String, dynamic>{'fallback_error': true}, 'error'),
'error*',
);
expect(
edgeLabel(<String, dynamic>{'fallback_error': false}, 'error'),
'error',
);
expect(
edgeLabel(<String, dynamic>{'fallback_error': true}, 'success'),
'success',
);
expect(edgeLabel(<String, dynamic>{}, 'rejected'), 'rejected');
});
});
group('linear definition', () {
test('edges keep stage and outcome order with contiguous ids', () {
final edges = graphEdges(linearGraph());
expect(edges.map((edge) => edge.id), <int>[1, 2, 3, 4, 5]);
expect(edges.map((edge) => edge.source), <String>[
'plan',
'plan',
'build',
'ship',
'ship',
]);
expect(edges.map((edge) => edge.outcome), <String>[
'success',
'error',
'success',
'success',
'error',
]);
expect(edges.map((edge) => edge.target), <String>[
'build',
'#failure',
'ship',
'#success',
'#failure',
]);
expect(edges.map((edge) => edge.label), <String>[
'success',
'error*',
'success',
'success',
'error',
]);
expect(edges.where((edge) => edge.fallback).map((edge) => edge.id), <int>[
2,
]);
expect(edges.every((edge) => edge.knownTarget), isTrue);
});
test('nodes are declaration order plus failure then success terminals', () {
final nodes = graphNodes(linearGraph());
expect(nodes.map((node) => node.key), <String>[
'plan',
'build',
'ship',
failureEnd,
successEnd,
]);
expect(nodes.map((node) => node.stageIndex), <int?>[0, 1, 2, null, null]);
expect(nodes.map((node) => node.terminal), <bool>[
false,
false,
false,
true,
true,
]);
expect(nodes[3].label, 'Failure');
expect(nodes[3].shortLabel, 'FAILURE');
expect(nodes[4].label, 'Success');
expect(nodes[4].shortLabel, 'SUCCESS');
});
});
group('diamond definition', () {
test('keeps every converging edge distinct in stable order', () {
final edges = graphEdges(diamondGraph());
expect(
edges.map((edge) => '${edge.source}/${edge.outcome}->${edge.target}'),
<String>[
'a/success->b',
'a/approved->c',
'a/error->#failure',
'b/success->d',
'c/success->d',
'd/success->#success',
],
);
expect(edges.every((edge) => edge.knownTarget), isTrue);
});
});
group('self loops', () {
test('a self edge is one edge and never duplicates node identity', () {
final graph = selfLoopGraph();
final edges = graphEdges(graph);
expect(
edges.map((edge) => '${edge.source}/${edge.outcome}->${edge.target}'),
<String>[
'a/success->b',
'a/retry->a',
'b/success->#success',
'b/error->#failure',
],
);
expect(edges[1].source, edges[1].target);
expect(edges[1].knownTarget, isTrue);
final nodes = graphNodes(graph);
expect(nodes.map((node) => node.key), <String>[
'a',
'b',
failureEnd,
successEnd,
]);
expect(nodes.where((node) => node.key == 'a'), hasLength(1));
});
test(
'a stage declared twice keeps one node and one set of edges per key',
() {
final graph = <String, dynamic>{
'stages': <dynamic>[
stage('a', edges: <String, String?>{'retry': 'a'}),
stage('a', edges: <String, String?>{'success': '#success'}),
],
};
expect(graphNodes(graph).map((node) => node.key), <String>[
'a',
failureEnd,
successEnd,
]);
// Both declarations are still definition data, with unique edge ids.
expect(graphEdges(graph).map((edge) => edge.id), <int>[1, 2]);
},
);
});
group('missing and unknown targets', () {
test(
'an absent edge declares nothing; empty and unknown targets stay honest',
() {
final edges = graphEdges(incompleteGraph());
expect(edges.map((edge) => edge.id), <int>[1, 2, 3, 4]);
expect(edges.map((edge) => edge.outcome), <String>[
'blocked',
'retry',
'error',
'success',
]);
expect(edges[0].target, '');
expect(edges[0].knownTarget, isFalse);
expect(edges[1].target, 'ghost');
expect(edges[1].knownTarget, isFalse);
expect(edges[2].target, failureEnd);
expect(edges[2].fallback, isTrue);
expect(edges[3].target, successEnd);
},
);
test('an unknown target does not become a node or a terminal', () {
final graph = <String, dynamic>{
'stages': <dynamic>[
stage('a', edges: <String, String?>{'retry': 'ghost'}),
],
};
expect(graphNodes(graph).map((node) => node.key), <String>['a']);
expect(graphEdges(graph).single.knownTarget, isFalse);
});
test('a graph with no stages has no nodes or edges', () {
expect(graphNodes(<String, dynamic>{}), isEmpty);
expect(graphEdges(<String, dynamic>{'stages': null}), isEmpty);
expect(graphNodes(null), isEmpty);
});
});
test(
'definition nodes ignore run evidence even when the graph map carries it',
() {
final graph = <String, dynamic>{
'stages': <dynamic>[
stage('a', edges: <String, String?>{'success': 'b'}),
stage('b'),
],
'steps': <dynamic>[
step(sequence: 1, stage: 'a', outcome: 'success', target: 'b'),
],
'visited_stages': <String>['a', 'b'],
};
final nodes = graphNodes(graph);
expect(nodes.map((node) => node.key), <String>['a', 'b']);
expect(nodes.every((node) => !node.terminal), isTrue);
},
);
}
@@ -0,0 +1,96 @@
import 'package:pipelines_app/core/api_gateway.dart';
/// Small, server-shaped fixtures shared by the graph domain tests.
JsonMap step({
int sequence = 0,
String stage = '',
String status = 'completed',
String outcome = '',
String target = '',
String startedAt = '',
Map<String, dynamic>? control,
}) {
return <String, dynamic>{
'sequence': sequence,
'stage': stage,
'status': status,
'outcome': outcome,
'target': target,
if (startedAt.isNotEmpty) 'started_at': startedAt,
'control': ?control,
};
}
JsonMap stage(
String key, {
Map<String, String?> edges = const {},
bool fallbackError = false,
String type = 'model',
}) {
return <String, dynamic>{
'key': key,
'type': type,
'edges': edges,
if (fallbackError) 'fallback_error': true,
};
}
/// plan -> build -> ship, with an implicit failure fallback on plan and an
/// explicit terminal pair on ship.
JsonMap linearGraph() => <String, dynamic>{
'stages': <dynamic>[
stage(
'plan',
edges: <String, String?>{'success': 'build', 'error': '#'},
fallbackError: true,
),
stage('build', edges: <String, String?>{'success': 'ship'}),
stage(
'ship',
edges: <String, String?>{'success': '#success', 'error': '#failure'},
),
],
};
/// a fans out to b/c and both converge on d.
JsonMap diamondGraph() => <String, dynamic>{
'stages': <dynamic>[
stage(
'a',
edges: <String, String?>{'success': 'b', 'approved': 'c', 'error': '#'},
fallbackError: true,
),
stage('b', edges: <String, String?>{'success': 'd'}),
stage('c', edges: <String, String?>{'success': 'd'}),
stage('d', edges: <String, String?>{'success': '#success'}),
],
};
/// a retries itself and can still succeed into b; terminal pair on b.
JsonMap selfLoopGraph() => <String, dynamic>{
'stages': <dynamic>[
stage('a', edges: <String, String?>{'success': 'b', 'retry': 'a'}),
stage(
'b',
edges: <String, String?>{'success': '#success', 'error': '#failure'},
),
],
};
/// A definition with an absent edge, an empty target and an unknown target.
JsonMap incompleteGraph() => <String, dynamic>{
'stages': <dynamic>[
stage(
'a',
edges: <String, String?>{
'success': null,
'blocked': '',
'retry': 'ghost',
'error': '#',
},
fallbackError: true,
),
stage('b', edges: <String, String?>{'success': '#success'}),
],
};
@@ -0,0 +1,56 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/graph/domain/graph_protocol.dart';
void main() {
group('terminal target normalization', () {
test('a bare # resolves by outcome exactly like the web protocol', () {
expect(resolveTarget('error', '#'), failureEnd);
expect(resolveTarget('success', '#'), successEnd);
expect(resolveTarget('approved', '#'), successEnd);
expect(resolveTarget('', '#'), successEnd);
});
test('explicit, empty and unknown targets are preserved verbatim', () {
expect(resolveTarget('success', successEnd), successEnd);
expect(resolveTarget('error', failureEnd), failureEnd);
expect(resolveTarget('success', 'review'), 'review');
expect(resolveTarget('blocked', ''), '');
expect(resolveTarget('retry', 'ghost'), 'ghost');
expect(resolveTarget('success', ' #success'), ' #success');
});
test(
'a missing target stays missing instead of fabricating a terminal',
() {
expect(resolveTarget('success', null), isNull);
expect(resolveTarget(null, null), isNull);
},
);
test('only the explicit terminal keys are terminals', () {
expect(isTerminalTarget(successEnd), isTrue);
expect(isTerminalTarget(failureEnd), isTrue);
expect(isTerminalTarget('#'), isFalse);
expect(isTerminalTarget('review'), isFalse);
expect(isTerminalTarget(''), isFalse);
expect(isTerminalTarget(null), isFalse);
});
});
group('terminal labels', () {
test('TUI labels are SUCCESS and FAILURE', () {
expect(nodeLabel(successEnd), 'SUCCESS');
expect(nodeLabel(failureEnd), 'FAILURE');
expect(nodeLabel('implementer'), 'implementer');
expect(nodeLabel(''), '');
expect(nodeLabel(null), '');
});
test('display labels title-case the terminals and keep stage keys', () {
expect(nodeDisplayLabel(successEnd), 'Success');
expect(nodeDisplayLabel(failureEnd), 'Failure');
expect(nodeDisplayLabel('implementer'), 'implementer');
expect(nodeDisplayLabel(null), '');
});
});
}
@@ -0,0 +1,91 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/graph/domain/run_graph_state.dart';
import 'graph_fixtures.dart';
void main() {
group('current stage fallback', () {
test('the run current stage wins over the last recorded visit', () {
final state = runGraphState(<String, dynamic>{
'current_stage': 'committer',
'steps': <dynamic>[step(sequence: 1, stage: 'review')],
});
expect(state.currentStage, 'committer');
});
test('a blank current stage falls back to the last visit, else null', () {
final fallback = runGraphState(<String, dynamic>{
'current_stage': ' ',
'steps': <dynamic>[
step(sequence: 1, stage: 'a'),
step(sequence: 2, stage: 'b'),
],
});
expect(fallback.currentStage, 'b');
final blankLast = runGraphState(<String, dynamic>{
'steps': <dynamic>[step(sequence: 1)],
});
expect(blankLast.currentStage, isNull);
});
});
group('active stage and start', () {
test('a live run exposes its running visit start', () {
final state = runGraphState(<String, dynamic>{
'executing': true,
'current_stage': 'review',
'steps': <dynamic>[
step(
sequence: 1,
stage: 'review',
status: 'running',
startedAt: '2026-01-01T00:00:00Z',
),
],
});
expect(state.executing, isTrue);
expect(state.activeStage, 'review');
expect(state.currentStageStartedAt, '2026-01-01T00:00:00Z');
});
test('a finished run has no active stage or start', () {
final state = runGraphState(<String, dynamic>{
'executing': false,
'current_stage': 'review',
'steps': <dynamic>[
step(
sequence: 1,
stage: 'review',
status: 'running',
startedAt: '2026-01-01T00:00:00Z',
),
],
});
expect(state.activeStage, isNull);
expect(state.currentStageStartedAt, isNull);
});
test('only an exact running status with a non-blank start is used', () {
final state = runGraphState(<String, dynamic>{
'executing': true,
'current_stage': 'review',
'steps': <dynamic>[
step(
sequence: 1,
stage: 'review',
status: 'Running',
startedAt: '2026-01-01T00:00:00Z',
),
step(
sequence: 2,
stage: 'review',
status: 'running',
startedAt: ' ',
),
],
});
expect(state.currentStageStartedAt, isNull);
});
});
}
@@ -0,0 +1,170 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/graph/domain/graph_protocol.dart';
import 'package:pipelines_app/features/graph/domain/run_graph_state.dart';
import 'graph_fixtures.dart';
void main() {
group('linear run evidence', () {
test('visits and routes follow the recorded visits', () {
final state = runGraphState(<String, dynamic>{
'executing': false,
'steps': <dynamic>[
step(sequence: 1, stage: 'plan', outcome: 'success', target: 'build'),
step(sequence: 2, stage: 'build', outcome: 'success', target: 'ship'),
step(
sequence: 3,
stage: 'ship',
outcome: 'success',
target: '#success',
),
],
});
expect(state.visitedStages, <String>[
'plan',
'build',
'ship',
successEnd,
]);
expect(state.takenRoutes, <String>[
'plan\u0000success\u0000build',
'build\u0000success\u0000ship',
'ship\u0000success\u0000#success',
]);
expect(state.currentStage, 'ship');
expect(state.executing, isFalse);
expect(state.currentStageStartedAt, isNull);
expect(state.activeStage, isNull);
});
});
group('diamond run evidence', () {
test('repeated visits keep one identity and loop routes stay distinct', () {
final state = runGraphState(<String, dynamic>{
'executing': false,
'steps': <dynamic>[
step(sequence: 1, stage: 'a', outcome: 'success', target: 'b'),
step(sequence: 2, stage: 'b', outcome: 'success', target: 'd'),
step(sequence: 3, stage: 'd', outcome: 'rejected', target: 'b'),
step(sequence: 4, stage: 'b', outcome: 'success', target: 'd'),
step(sequence: 5, stage: 'd', outcome: 'success', target: '#success'),
],
});
expect(state.visitedStages, <String>['a', 'b', 'd', successEnd]);
expect(state.visitedStages.where((key) => key == 'b'), hasLength(1));
expect(state.takenRoutes, <String>[
'a\u0000success\u0000b',
'b\u0000success\u0000d',
'd\u0000rejected\u0000b',
'd\u0000success\u0000#success',
]);
});
test('different outcomes to the same target stay separate routes', () {
final state = runGraphState(<String, dynamic>{
'executing': false,
'steps': <dynamic>[
step(sequence: 1, stage: 'a', outcome: 'success', target: 'b'),
step(sequence: 2, stage: 'a', outcome: 'approved', target: 'b'),
step(sequence: 3, stage: 'a', outcome: 'success', target: 'b'),
],
});
expect(state.visitedStages, <String>['a']);
expect(state.takenRoutes, <String>[
'a\u0000success\u0000b',
'a\u0000approved\u0000b',
]);
});
});
group('self edges', () {
test('a self edge is evidence, not a second visit or recursion', () {
final state = runGraphState(<String, dynamic>{
'executing': false,
'steps': <dynamic>[
step(sequence: 1, stage: 'a', outcome: 'retry', target: 'a'),
step(sequence: 2, stage: 'a', outcome: 'success', target: 'b'),
],
});
expect(state.visitedStages, <String>['a']);
expect(state.takenRoutes, <String>[
'a\u0000retry\u0000a',
'a\u0000success\u0000b',
]);
});
});
group('terminals', () {
test('a bare # resolves to failure on error and success otherwise', () {
final failed = runGraphState(<String, dynamic>{
'steps': <dynamic>[
step(sequence: 1, stage: 'impl', outcome: 'error', target: '#'),
],
});
expect(failed.visitedStages, <String>['impl', failureEnd]);
expect(failed.visitedStages, isNot(contains(successEnd)));
expect(failed.isRouteTaken('impl', 'error', '#'), isTrue);
final succeeded = runGraphState(<String, dynamic>{
'steps': <dynamic>[
step(sequence: 1, stage: 'impl', outcome: 'done', target: '#'),
],
});
expect(succeeded.visitedStages, <String>['impl', successEnd]);
expect(succeeded.visitedStages, isNot(contains(failureEnd)));
});
test('a non-terminal target is not visited until a step lands on it', () {
final state = runGraphState(<String, dynamic>{
'steps': <dynamic>[
step(
sequence: 1,
stage: 'impl',
outcome: 'success',
target: 'review',
),
],
});
expect(state.visitedStages, <String>['impl']);
expect(state.isStageVisited('review'), isFalse);
expect(state.isRouteTaken('impl', 'success', 'review'), isTrue);
});
test('blank outcome or target records no route and no terminal visit', () {
final state = runGraphState(<String, dynamic>{
'steps': <dynamic>[
step(sequence: 1, stage: 'impl', outcome: 'success', target: ''),
step(sequence: 2, stage: 'impl', outcome: '', target: '#success'),
],
});
expect(state.visitedStages, <String>['impl']);
expect(state.takenRoutes, isEmpty);
});
});
group('missing evidence', () {
test('absent run or steps fabricates no visits', () {
for (final run in <dynamic>[
null,
<String, dynamic>{},
<String, dynamic>{'steps': null},
<String, dynamic>{'steps': <dynamic>[]},
]) {
final state = runGraphState(run);
expect(state.visitedStages, isEmpty);
expect(state.takenRoutes, isEmpty);
expect(state.currentStage, isNull);
expect(state.executing, isFalse);
expect(state.currentStageStartedAt, isNull);
}
});
test('malformed step entries are ignored, not invented', () {
final state = runGraphState(<String, dynamic>{
'steps': <dynamic>['nope', 42, null],
});
expect(state.visitedStages, isEmpty);
expect(state.takenRoutes, isEmpty);
});
});
}
@@ -0,0 +1,150 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/graph/domain/stage_visits.dart';
import 'graph_fixtures.dart';
void main() {
group('ordered stage visits', () {
test('repeated visits are ordered by sequence, not input order', () {
final steps = <dynamic>[
step(
sequence: 5,
stage: 'review',
outcome: 'rejected',
target: 'implementer',
control: <String, dynamic>{'visit': 2},
),
step(sequence: 3, stage: 'implementer'),
step(
sequence: 2,
stage: 'review',
outcome: 'success',
target: 'done',
control: <String, dynamic>{'visit': 1},
),
].cast<Map<String, dynamic>>();
final byStage = visitsByStage(steps);
expect(byStage.keys, <String>['review', 'implementer']);
expect(byStage['review']!.map((visit) => visit['sequence']), <int>[2, 5]);
expect(byStage['review']!.map((visit) => visit['outcome']), <String>[
'success',
'rejected',
]);
expect(displayVisit(byStage['review']![0], 0), 1);
expect(displayVisit(byStage['review']![1], 1), 2);
});
test('equal sequences keep their recorded order', () {
final steps = <dynamic>[
step(sequence: 1, stage: 'a', outcome: 'first'),
step(sequence: 1, stage: 'a', outcome: 'second'),
].cast<Map<String, dynamic>>();
expect(
visitsByStage(steps)['a']!.map((visit) => visit['outcome']),
<String>['first', 'second'],
);
});
test('a missing control visit falls back to the position', () {
final steps = <dynamic>[
step(sequence: 1, stage: 'a'),
step(sequence: 2, stage: 'a'),
].cast<Map<String, dynamic>>();
final visits = visitsByStage(steps)['a']!;
expect(displayVisit(visits[0], 0), 1);
expect(displayVisit(visits[1], 1), 2);
});
test(
'a non-positive or malformed control visit falls back to position',
() {
expect(
displayVisit(step(control: <String, dynamic>{'visit': 0}), 2),
3,
);
expect(
displayVisit(step(control: <String, dynamic>{'visit': -1}), 2),
3,
);
expect(
displayVisit(step(control: <String, dynamic>{'visit': '3'}), 0),
3,
);
expect(displayVisit(step(), 4), 5);
},
);
});
group('clamping', () {
test('keeps a valid index and handles an empty list', () {
expect(clampVisitIndex(0, 3), 0);
expect(clampVisitIndex(2, 3), 2);
expect(clampVisitIndex(99, 3), 2);
expect(clampVisitIndex(-4, 3), 0);
expect(clampVisitIndex(5, 0), 0);
});
});
group('selection', () {
List<Map<String, dynamic>> repeatedVisits() => <dynamic>[
step(sequence: 5, stage: 'review', outcome: 'rejected'),
step(sequence: 2, stage: 'review', outcome: 'success'),
].cast<Map<String, dynamic>>();
test('no requested visit selects the stage most recent recorded visit', () {
final selection = selectStageVisit(repeatedVisits(), 'review');
expect(selection.hasVisit, isTrue);
expect(selection.index, 1);
expect(selection.step!['sequence'], 5);
expect(selection.visitNumber, 2);
});
test('an explicit visit selects that recorded visit', () {
final selection = selectStageVisit(
repeatedVisits(),
'review',
visitIndex: 0,
);
expect(selection.step!['sequence'], 2);
expect(selection.visitNumber, 1);
});
test('out-of-range indexes clamp to the nearest recorded visit', () {
final late = selectStageVisit(repeatedVisits(), 'review', visitIndex: 99);
expect(late.index, 1);
expect(late.step!['sequence'], 5);
expect(late.correctedRequest(99), isTrue);
final early = selectStageVisit(
repeatedVisits(),
'review',
visitIndex: -4,
);
expect(early.index, 0);
expect(early.step!['sequence'], 2);
expect(early.correctedRequest(-4), isTrue);
expect(early.correctedRequest(null), isFalse);
});
test('a stage with no recorded visit returns no fabricated step', () {
final selection = selectStageVisit(repeatedVisits(), 'never-ran');
expect(selection.hasVisit, isFalse);
expect(selection.step, isNull);
expect(selection.index, 0);
expect(selection.visitNumber, 0);
final empty = selectStageVisit(const <Map<String, dynamic>>[], 'review');
expect(empty.hasVisit, isFalse);
expect(empty.step, isNull);
});
test('an absent capture for one stage does not hide another stage', () {
final steps = <dynamic>[
step(sequence: 1, stage: 'a', outcome: 'success', target: 'b'),
].cast<Map<String, dynamic>>();
expect(selectStageVisit(steps, 'a').hasVisit, isTrue);
expect(selectStageVisit(steps, 'b').hasVisit, isFalse);
});
});
}