ticket-docket 1.0.0__py3-none-any.whl

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.
docket/core/errors.py ADDED
@@ -0,0 +1,122 @@
1
+ """
2
+ Docket Errors
3
+
4
+ The exception hierarchy raised by the core and translated by each shell.
5
+ """
6
+
7
+ # MARK: Classes
8
+
9
+
10
+ class DocketError(Exception):
11
+ """
12
+ Base class for every error the core raises.
13
+
14
+ A shell catches this to turn a core failure into a CLI message or an MCP tool error.
15
+ """
16
+
17
+
18
+ class ConfigNotFoundError(DocketError):
19
+ """
20
+ Raised when no `.docket.toml` was found between the starting directory and the repository root.
21
+ """
22
+
23
+
24
+ class ConfigError(DocketError):
25
+ """
26
+ Raised when a `.docket.toml` exists but is malformed or missing a required field.
27
+ """
28
+
29
+
30
+ class InvalidKeyError(DocketError):
31
+ """
32
+ Raised when a key does not match the required `[A-Z][A-Z0-9]*` form.
33
+ """
34
+
35
+
36
+ class UnknownKeyError(DocketError):
37
+ """
38
+ Raised when a key is not registered.
39
+ """
40
+
41
+
42
+ class InvalidIdError(DocketError):
43
+ """
44
+ Raised when a ticket id does not match the required `<KEY>-<NUM>` form.
45
+ """
46
+
47
+
48
+ class InvalidArgumentError(DocketError):
49
+ """
50
+ Raised when an argument's value cannot be read as anything that argument accepts.
51
+
52
+ A shell that takes bare positional tokens needs this, since which filter a token names is decided by the token's own shape rather than by a flag standing beside it.
53
+ """
54
+
55
+
56
+ class DeployError(DocketError):
57
+ """
58
+ Raised when docket cannot be installed into a consumer repository.
59
+
60
+ This covers a target that is not a directory, and an existing `.mcp.json` that cannot be safely merged into.
61
+ """
62
+
63
+
64
+ class TicketNotFoundError(DocketError):
65
+ """
66
+ Raised when no ticket carries the requested id.
67
+ """
68
+
69
+
70
+ class InvalidStatusError(DocketError):
71
+ """
72
+ Raised when a status outside `todo`, `wip`, `done` is written through the tool.
73
+
74
+ A status that arrived by hand-editing is reported by `validate` instead, since refusing to load it would hide the problem.
75
+ """
76
+
77
+
78
+ class InvalidPriorityError(DocketError):
79
+ """
80
+ Raised when a priority outside `0` through `maxPriority` is written through the tool.
81
+ """
82
+
83
+
84
+ class EmptyValueError(DocketError):
85
+ """
86
+ Raised when a value that must carry text arrived empty or as only whitespace.
87
+
88
+ A shell that drops an empty argument before the process starts turns this into its own usage error instead, which is why this exists for the shells that pass one through.
89
+ """
90
+
91
+
92
+ class ConflictingArgumentsError(DocketError):
93
+ """
94
+ Raised when two arguments in one call ask for contradictory things.
95
+
96
+ Replacing a dependency list and editing that same list in place is the case this exists for, since honoring both would mean picking an order the caller never stated.
97
+ """
98
+
99
+
100
+ class OutputPathError(DocketError):
101
+ """
102
+ Raised when a path supplied as a destination cannot be written to.
103
+
104
+ This covers an empty path, a path naming an existing directory, and a location the filesystem refuses.
105
+ """
106
+
107
+
108
+ class LockTimeoutError(DocketError):
109
+ """
110
+ Raised when another docket process held the repository lock for longer than the configured `lockTimeout`.
111
+
112
+ Nothing was written when this is raised, so retrying the same call is always safe.
113
+ """
114
+
115
+
116
+ class TicketParseError(DocketError):
117
+ """
118
+ Raised when a file under the ticket root is not a readable ticket.
119
+
120
+ This covers a missing frontmatter block, unparseable YAML, and a required field that is absent or of the wrong type.
121
+ It does not cover a field whose value breaks a rule, such as an out-of-range priority, because those are reported by `validate` instead.
122
+ """
docket/core/fields.py ADDED
@@ -0,0 +1,166 @@
1
+ """
2
+ Docket Fields
3
+
4
+ Typed reading of untrusted mapping fields, shared by frontmatter parsing and configuration parsing.
5
+
6
+ Both surfaces read a mapping that came from a file a human or an agent may have written badly, and both need the same presence and type checks. Only the exception they raise differs, so it is passed in.
7
+ """
8
+
9
+ # MARK: Imports
10
+
11
+ from typing import Any, Mapping, Optional, Type
12
+
13
+ from docket.core.errors import DocketError
14
+
15
+ # MARK: Functions
16
+
17
+
18
+ def readString(mapping: Mapping[str, Any], name: str, errorType: Type[DocketError], source: str, fallback: Optional[str] = None) -> str:
19
+ """
20
+ Read a string field.
21
+
22
+ mapping: The parsed mapping to read from.
23
+ name: The field name.
24
+ errorType: The exception raised when the field is absent or of the wrong type.
25
+ source: What to name in the error message, for example `Frontmatter`.
26
+ fallback: The value used when the field is absent, or `None` to make the field required.
27
+
28
+ Returns the field value.
29
+ """
30
+
31
+ value: Any = _readRaw(mapping, name, errorType, source, fallback)
32
+
33
+ if not isinstance(value, str):
34
+ raise errorType(f"{source} field '{name}' must be a string, got {type(value).__name__}.")
35
+
36
+ # Narrow to exactly `str`, since a parser may hand back a subclass. `tomlkit` does, and `pyyaml` dispatches its representers on exact type, so a subclass leaking this far fails at serialization instead of here.
37
+ return str(value)
38
+
39
+
40
+ def readInt(mapping: Mapping[str, Any], name: str, errorType: Type[DocketError], source: str, fallback: Optional[int] = None) -> int:
41
+ """
42
+ Read an integer field.
43
+
44
+ mapping: The parsed mapping to read from.
45
+ name: The field name.
46
+ errorType: The exception raised when the field is absent or of the wrong type.
47
+ source: What to name in the error message, for example `Frontmatter`.
48
+ fallback: The value used when the field is absent, or `None` to make the field required.
49
+
50
+ Returns the field value.
51
+ """
52
+
53
+ value: Any = _readRaw(mapping, name, errorType, source, fallback)
54
+
55
+ # `bool` subclasses `int` in Python, so exclude it explicitly rather than reading `true` as 1.
56
+ if isinstance(value, bool) or not isinstance(value, int):
57
+ raise errorType(f"{source} field '{name}' must be an integer, got {type(value).__name__}.")
58
+
59
+ # Narrow to exactly `int`, for the same reason as `readString`.
60
+ return int(value)
61
+
62
+
63
+ def readFloat(mapping: Mapping[str, Any], name: str, errorType: Type[DocketError], source: str, fallback: Optional[float] = None) -> float:
64
+ """
65
+ Read a number field as a float.
66
+
67
+ An integer is accepted and widened, since a configuration writing `5` rather than `5.0` means the same thing and refusing it would be pedantic.
68
+
69
+ mapping: The parsed mapping to read from.
70
+ name: The field name.
71
+ errorType: The exception raised when the field is absent or of the wrong type.
72
+ source: What to name in the error message, for example `Configuration`.
73
+ fallback: The value used when the field is absent, or `None` to make the field required.
74
+
75
+ Returns the field value.
76
+ """
77
+
78
+ value: Any = _readRaw(mapping, name, errorType, source, fallback)
79
+
80
+ # `bool` subclasses `int` in Python, so exclude it explicitly rather than reading `true` as 1.0.
81
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
82
+ raise errorType(f"{source} field '{name}' must be a number, got {type(value).__name__}.")
83
+
84
+ # Narrow to exactly `float`, for the same reason as `readString`.
85
+ return float(value)
86
+
87
+
88
+ def readStringList(mapping: Mapping[str, Any], name: str, errorType: Type[DocketError], source: str) -> list[str]:
89
+ """
90
+ Read a list-of-strings field.
91
+
92
+ An absent or null field reads as empty, since an empty list is the common case and refusing to load over it would be hostile.
93
+
94
+ mapping: The parsed mapping to read from.
95
+ name: The field name.
96
+ errorType: The exception raised when the field is of the wrong type.
97
+ source: What to name in the error message, for example `Frontmatter`.
98
+
99
+ Returns the field value.
100
+ """
101
+
102
+ if name not in mapping or mapping[name] is None:
103
+ return []
104
+
105
+ value: Any = mapping[name]
106
+ if not isinstance(value, list):
107
+ raise errorType(f"{source} field '{name}' must be a list, got {type(value).__name__}.")
108
+
109
+ # Reject a non-string entry here, since every later stage treats these as ids.
110
+ for entry in value:
111
+ if not isinstance(entry, str):
112
+ raise errorType(f"{source} field '{name}' must contain only strings, found {type(entry).__name__}.")
113
+
114
+ # Narrow every entry to exactly `str`, for the same reason as `readString`.
115
+ return [str(entry) for entry in value]
116
+
117
+
118
+ def readDict(mapping: Mapping[str, Any], name: str, errorType: Type[DocketError], source: str) -> dict[str, Any]:
119
+ """
120
+ Read a mapping-of-strings-to-anything field.
121
+
122
+ An absent or null field reads as empty, for the same reason as `readStringList`.
123
+
124
+ mapping: The parsed mapping to read from.
125
+ name: The field name.
126
+ errorType: The exception raised when the field is of the wrong type.
127
+ source: What to name in the error message, for example `Frontmatter`.
128
+
129
+ Returns the field value.
130
+ """
131
+
132
+ if name not in mapping or mapping[name] is None:
133
+ return {}
134
+
135
+ value: Any = mapping[name]
136
+ if not isinstance(value, dict):
137
+ raise errorType(f"{source} field '{name}' must be a mapping, got {type(value).__name__}.")
138
+
139
+ # Reject a non-string key here, since every later stage treats these as named entries.
140
+ for entry in value:
141
+ if not isinstance(entry, str):
142
+ raise errorType(f"{source} field '{name}' must have only string keys, found {type(entry).__name__}.")
143
+
144
+ return dict(value)
145
+
146
+
147
+ def _readRaw(mapping: Mapping[str, Any], name: str, errorType: Type[DocketError], source: str, fallback: Optional[Any]) -> Any:
148
+ """
149
+ Fetch a field, applying its fallback or raising when it is required and absent.
150
+
151
+ mapping: The parsed mapping to read from.
152
+ name: The field name.
153
+ errorType: The exception raised when a required field is absent.
154
+ source: What to name in the error message.
155
+ fallback: The value used when the field is absent, or `None` to make the field required.
156
+
157
+ Returns the raw value, still untyped.
158
+ """
159
+
160
+ if name in mapping:
161
+ return mapping[name]
162
+
163
+ if fallback is None:
164
+ raise errorType(f"{source} is missing the required field '{name}'.")
165
+
166
+ return fallback
docket/core/graph.py ADDED
@@ -0,0 +1,418 @@
1
+ """
2
+ Docket Graph
3
+
4
+ Forward and reverse edge resolution, traversal, and cycle detection.
5
+
6
+ This produces a resolved structure and nothing else. Rendering lives in `mermaid.py`, which is what keeps a second renderer cheap to add later.
7
+ """
8
+
9
+ # MARK: Imports
10
+
11
+ from dataclasses import dataclass, field, replace
12
+ from typing import Iterable, Optional
13
+
14
+ from docket.core.ids import parseId
15
+ from docket.core.store import TicketSet
16
+ from docket.core.ticket import Ticket
17
+
18
+ # MARK: Classes
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class GraphNode:
23
+ """
24
+ One ticket as it appears in a resolved graph, carrying both edge directions.
25
+
26
+ The reverse direction is derived here rather than stored on the ticket, which is what makes a one-sided edge impossible by construction.
27
+ """
28
+
29
+ # MARK: Properties
30
+
31
+ id: str
32
+ title: str
33
+ status: str
34
+ priority: int
35
+ key: str
36
+
37
+ # Ids this ticket depends on, narrowed to the ones that actually exist.
38
+ requires: tuple[str, ...] = ()
39
+
40
+ # Ids that depend on this ticket, derived by scanning every other ticket's `requires`.
41
+ requiredBy: tuple[str, ...] = ()
42
+
43
+ # Set on a node pulled into a key-scoped graph only because it neighbors that key, so a renderer can show the boundary.
44
+ isExternal: bool = False
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class Edge:
49
+ """
50
+ One dependency edge.
51
+
52
+ The direction is dependency to dependent, so an arrow reads as "must happen before".
53
+ """
54
+
55
+ # MARK: Properties
56
+
57
+ fromId: str
58
+ toId: str
59
+
60
+
61
+ @dataclass
62
+ class ResolvedGraph:
63
+ """
64
+ A set of nodes and the edges between them, ready to render or traverse.
65
+ """
66
+
67
+ # MARK: Properties
68
+
69
+ nodes: dict[str, GraphNode] = field(default_factory=dict)
70
+ edges: list[Edge] = field(default_factory=list)
71
+
72
+ # What the graph was scoped to, for a renderer to title with. Absent for the whole set.
73
+ scope: Optional[str] = None
74
+
75
+ # MARK: Python Functions
76
+
77
+ def __len__(self) -> int:
78
+ """
79
+ Count the nodes.
80
+
81
+ Returns the node count.
82
+ """
83
+
84
+ return len(self.nodes)
85
+
86
+ def __contains__(self, ticketId: str) -> bool:
87
+ """
88
+ Report whether a node is present.
89
+
90
+ ticketId: The id to test.
91
+
92
+ Returns `True` when the graph holds the node.
93
+ """
94
+
95
+ return ticketId in self.nodes
96
+
97
+ # MARK: Functions
98
+
99
+ def keys(self) -> list[str]:
100
+ """
101
+ List every key present, sorted.
102
+
103
+ Returns the keys.
104
+ """
105
+
106
+ return sorted({node.key for node in self.nodes.values()})
107
+
108
+ def nodesForKey(self, key: str) -> list[GraphNode]:
109
+ """
110
+ List the nodes carrying one key, ordered by ticket number.
111
+
112
+ key: The key to select.
113
+
114
+ Returns the ordered nodes.
115
+ """
116
+
117
+ return sorted((node for node in self.nodes.values() if node.key == key), key=lambda node: parseId(node.id)[1])
118
+
119
+
120
+ # MARK: Functions
121
+
122
+
123
+ def resolveGraph(ticketSet: TicketSet) -> ResolvedGraph:
124
+ """
125
+ Build the full graph for a ticket set, deriving every reverse edge.
126
+
127
+ A `requires` entry naming an id that does not exist is dropped here rather than raising, because reporting it is `validate`'s job and the graph still has to render around it.
128
+
129
+ ticketSet: The loaded tickets.
130
+
131
+ Returns the resolved graph.
132
+ """
133
+
134
+ tickets: dict[str, Ticket] = ticketSet.tickets
135
+
136
+ # Collect forward edges first, keeping only dependencies that resolve to a real ticket.
137
+ forward: dict[str, list[str]] = {}
138
+ reverse: dict[str, list[str]] = {ticketId: [] for ticketId in tickets}
139
+ for ticketId, ticket in tickets.items():
140
+ resolved: list[str] = [required for required in ticket.requires if required in tickets]
141
+ forward[ticketId] = resolved
142
+
143
+ # Derive the reverse direction in the same pass, which is the whole reason the ticket file never stores it.
144
+ for required in resolved:
145
+ reverse[required].append(ticketId)
146
+
147
+ graph: ResolvedGraph = ResolvedGraph()
148
+
149
+ for ticketId, ticket in tickets.items():
150
+ graph.nodes[ticketId] = GraphNode(
151
+ id=ticketId,
152
+ title=ticket.title,
153
+ status=ticket.status,
154
+ priority=ticket.priority,
155
+ key=ticket.key,
156
+ requires=tuple(_orderedIds(forward[ticketId])),
157
+ requiredBy=tuple(_orderedIds(reverse[ticketId])),
158
+ )
159
+
160
+ graph.edges = _buildEdges(graph.nodes)
161
+
162
+ return graph
163
+
164
+
165
+ def subgraphForId(graph: ResolvedGraph, ticketId: str) -> ResolvedGraph:
166
+ """
167
+ Scope a graph to one ticket's transitive ancestors and descendants.
168
+
169
+ ticketId: The ticket at the centre.
170
+
171
+ Returns the scoped graph.
172
+ """
173
+
174
+ if ticketId not in graph.nodes:
175
+ return ResolvedGraph(scope=ticketId)
176
+
177
+ # Walk both directions from the centre, which together give everything this ticket blocks or is blocked by.
178
+ included: set[str] = {ticketId}
179
+ included |= _reachable(graph, ticketId, forward=True)
180
+ included |= _reachable(graph, ticketId, forward=False)
181
+
182
+ return _restrict(graph, included, scope=ticketId)
183
+
184
+
185
+ def subgraphForKey(graph: ResolvedGraph, key: str) -> ResolvedGraph:
186
+ """
187
+ Scope a graph to one key, plus the immediate neighbors of that key on either side.
188
+
189
+ The neighbors are marked external so a renderer can show where the key ends.
190
+
191
+ key: The key to scope to.
192
+
193
+ Returns the scoped graph.
194
+ """
195
+
196
+ members: set[str] = {node.id for node in graph.nodes.values() if node.key == key}
197
+
198
+ # Pull in direct neighbors only, on both edge directions, so the boundary is visible without dragging in the whole set.
199
+ neighbors: set[str] = set()
200
+ for memberId in members:
201
+ node: GraphNode = graph.nodes[memberId]
202
+ neighbors |= set(node.requires) | set(node.requiredBy)
203
+
204
+ neighbors -= members
205
+
206
+ scoped: ResolvedGraph = _restrict(graph, members | neighbors, scope=key)
207
+
208
+ # Mark the borrowed nodes, which is what tells a renderer to style them differently.
209
+ for neighborId in neighbors:
210
+ scoped.nodes[neighborId] = replace(scoped.nodes[neighborId], isExternal=True)
211
+
212
+ return scoped
213
+
214
+
215
+ def dependencyContext(ticketSet: TicketSet, ticketId: str) -> dict[str, list[dict[str, object]]]:
216
+ """
217
+ Resolve the context a raw ticket file deliberately does not carry.
218
+
219
+ The file stores bare ids in one direction only, so both the title and status of each dependency, and the entire reverse direction, have to be resolved here. This is what lets `read_ticket` be useful without the file duplicating anything.
220
+
221
+ ticketSet: The loaded tickets.
222
+ ticketId: The ticket to resolve context for.
223
+
224
+ Returns a mapping of `requires` and `requiredBy` to summary records.
225
+ """
226
+
227
+ graph: ResolvedGraph = resolveGraph(ticketSet)
228
+ ticket: Ticket = ticketSet.get(ticketId)
229
+
230
+ # A dependency naming a missing id still has to appear, since hiding it would make a broken link invisible to the reader.
231
+ requires: list[dict[str, object]] = []
232
+ for requiredId in ticket.requires:
233
+ requires.append(_contextEntry(graph, requiredId))
234
+
235
+ node: Optional[GraphNode] = graph.nodes.get(ticketId)
236
+ requiredBy: list[dict[str, object]] = [_contextEntry(graph, dependentId) for dependentId in (node.requiredBy if node is not None else ())]
237
+
238
+ return {"requires": requires, "requiredBy": requiredBy}
239
+
240
+
241
+ def findCycles(graph: ResolvedGraph) -> list[list[str]]:
242
+ """
243
+ Find every dependency cycle, reporting one representative per strongly connected component.
244
+
245
+ Tarjan's algorithm is used iteratively rather than recursively, so a deep chain cannot exhaust the interpreter stack.
246
+
247
+ graph: The graph to search.
248
+
249
+ Returns one sorted member list per cycle, ordered for stable output.
250
+ """
251
+
252
+ index: dict[str, int] = {}
253
+ lowLink: dict[str, int] = {}
254
+ onStack: set[str] = set()
255
+ stack: list[str] = []
256
+ counter: int = 0
257
+ cycles: list[list[str]] = []
258
+
259
+ # Iterate roots in sorted order so the reported cycles do not shift between runs.
260
+ for rootId in sorted(graph.nodes):
261
+ if rootId in index:
262
+ continue
263
+
264
+ # Each frame holds a node and how far through its successors the walk has got.
265
+ work: list[tuple[str, int]] = [(rootId, 0)]
266
+ while work:
267
+ nodeId, successorIndex = work[-1]
268
+
269
+ # First visit to this node, so assign it a discovery index.
270
+ if successorIndex == 0:
271
+ index[nodeId] = counter
272
+ lowLink[nodeId] = counter
273
+ counter += 1
274
+ stack.append(nodeId)
275
+ onStack.add(nodeId)
276
+
277
+ successors: tuple[str, ...] = graph.nodes[nodeId].requires
278
+ if successorIndex < len(successors):
279
+ work[-1] = (nodeId, successorIndex + 1)
280
+ successorId: str = successors[successorIndex]
281
+
282
+ # Descend into an unvisited successor, or fold a back edge into this node's low link.
283
+ if successorId not in index:
284
+ work.append((successorId, 0))
285
+ elif successorId in onStack:
286
+ lowLink[nodeId] = min(lowLink[nodeId], index[successorId])
287
+
288
+ continue
289
+
290
+ # Every successor is done, so this node's component is decided.
291
+ work.pop()
292
+ if work:
293
+ parentId: str = work[-1][0]
294
+ lowLink[parentId] = min(lowLink[parentId], lowLink[nodeId])
295
+
296
+ if lowLink[nodeId] != index[nodeId]:
297
+ continue
298
+
299
+ # Pop the component this node roots.
300
+ component: list[str] = []
301
+ while True:
302
+ memberId: str = stack.pop()
303
+ onStack.discard(memberId)
304
+ component.append(memberId)
305
+ if memberId == nodeId:
306
+ break
307
+
308
+ # A component of one is a cycle only when the node depends on itself.
309
+ if len(component) > 1 or nodeId in graph.nodes[nodeId].requires:
310
+ cycles.append(sorted(component))
311
+
312
+ return sorted(cycles)
313
+
314
+
315
+ def _contextEntry(graph: ResolvedGraph, ticketId: str) -> dict[str, object]:
316
+ """
317
+ Build one resolved dependency record.
318
+
319
+ graph: The resolved graph to look the ticket up in.
320
+ ticketId: The id to describe.
321
+
322
+ Returns the record, flagged when the id names nothing that exists.
323
+ """
324
+
325
+ node: Optional[GraphNode] = graph.nodes.get(ticketId)
326
+ if node is None:
327
+ return {"id": ticketId, "title": None, "status": None, "priority": None, "exists": False}
328
+
329
+ return {"id": node.id, "title": node.title, "status": node.status, "priority": node.priority, "exists": True}
330
+
331
+
332
+ def _reachable(graph: ResolvedGraph, startId: str, forward: bool) -> set[str]:
333
+ """
334
+ Collect every node reachable from a start node in one direction.
335
+
336
+ The visited set makes this safe on a graph that already contains a cycle, which matters because `validate` has to render a broken graph in order to explain it.
337
+
338
+ graph: The graph to walk.
339
+ startId: The node to walk from.
340
+ forward: Walk `requires` when `True`, `requiredBy` when `False`.
341
+
342
+ Returns the reachable ids, excluding the start unless a cycle leads back to it.
343
+ """
344
+
345
+ seen: set[str] = set()
346
+ pending: list[str] = list(graph.nodes[startId].requires if forward else graph.nodes[startId].requiredBy)
347
+
348
+ while pending:
349
+ currentId: str = pending.pop()
350
+ if currentId in seen or currentId not in graph.nodes:
351
+ continue
352
+
353
+ seen.add(currentId)
354
+
355
+ node: GraphNode = graph.nodes[currentId]
356
+ pending.extend(node.requires if forward else node.requiredBy)
357
+
358
+ return seen
359
+
360
+
361
+ def _restrict(graph: ResolvedGraph, included: set[str], scope: Optional[str]) -> ResolvedGraph:
362
+ """
363
+ Build a graph holding only the named nodes and the edges between them.
364
+
365
+ Each node keeps its full edge lists, so a caller can still see that a node has neighbors outside the scope. Only the rendered edges are narrowed.
366
+
367
+ graph: The graph to restrict.
368
+ included: The ids to keep.
369
+ scope: What the result is scoped to.
370
+
371
+ Returns the restricted graph.
372
+ """
373
+
374
+ nodes: dict[str, GraphNode] = {ticketId: graph.nodes[ticketId] for ticketId in included if ticketId in graph.nodes}
375
+
376
+ return ResolvedGraph(nodes=nodes, edges=_buildEdges(nodes), scope=scope)
377
+
378
+
379
+ def _buildEdges(nodes: dict[str, GraphNode]) -> list[Edge]:
380
+ """
381
+ Build the edge list for a node set, keeping only edges with both ends present.
382
+
383
+ nodes: The nodes to connect.
384
+
385
+ Returns the edges, sorted for stable output.
386
+ """
387
+
388
+ edges: list[Edge] = []
389
+ for node in nodes.values():
390
+ for requiredId in node.requires:
391
+ if requiredId in nodes:
392
+ edges.append(Edge(fromId=requiredId, toId=node.id))
393
+
394
+ return sorted(edges, key=lambda edge: (_idSortKey(edge.fromId), _idSortKey(edge.toId)))
395
+
396
+
397
+ def _orderedIds(ids: Iterable[str]) -> list[str]:
398
+ """
399
+ Sort ids by key and then numerically, so `CORE-2` precedes `CORE-10`.
400
+
401
+ ids: The ids to sort.
402
+
403
+ Returns the sorted ids.
404
+ """
405
+
406
+ return sorted(ids, key=_idSortKey)
407
+
408
+
409
+ def _idSortKey(ticketId: str) -> tuple[str, int]:
410
+ """
411
+ Build the ordering key for one id.
412
+
413
+ ticketId: The id to order.
414
+
415
+ Returns a `(key, number)` tuple.
416
+ """
417
+
418
+ return parseId(ticketId)