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/ticket.py ADDED
@@ -0,0 +1,272 @@
1
+ """
2
+ Docket Ticket
3
+
4
+ The `Ticket` dataclass, frontmatter parsing, and serialization back to markdown.
5
+ """
6
+
7
+ # MARK: Imports
8
+
9
+ from dataclasses import dataclass, field
10
+ from pathlib import Path
11
+ from typing import Any, Optional
12
+
13
+ import yaml
14
+
15
+ from docket.core.errors import TicketParseError
16
+ from docket.core.fields import readDict, readInt, readString, readStringList
17
+ from docket.core.ids import keyOf
18
+
19
+ # MARK: Constants
20
+
21
+ # The status vocabulary is fixed in the tool, not configurable, because only a fixed set can carry the rule that exactly one status moves the file.
22
+ STATUS_TODO: str = "todo"
23
+ STATUS_WIP: str = "wip"
24
+ STATUS_DONE: str = "done"
25
+ STATUSES: tuple[str, ...] = (STATUS_TODO, STATUS_WIP, STATUS_DONE)
26
+
27
+ # The line that opens and closes a frontmatter block.
28
+ FRONTMATTER_DELIMITER: str = "---"
29
+
30
+ # Field order is explicit rather than incidental, so a rewrite never churns the diff.
31
+ CANONICAL_FIELDS: tuple[str, ...] = ("id", "title", "status", "priority", "requires", "metadata")
32
+
33
+ # A very large width keeps `pyyaml` from wrapping a long title across lines.
34
+ YAML_WIDTH: int = 1 << 20
35
+
36
+ # What field errors name, since a ticket's fields all come from its frontmatter block.
37
+ FIELD_SOURCE: str = "Frontmatter"
38
+
39
+ # MARK: Classes
40
+
41
+
42
+ class FlowList(list):
43
+ """
44
+ A list that serializes in YAML flow style.
45
+
46
+ This exists so `requires` renders as `[CORE-9, GEN-3]` on one line, and so an empty list reads as `requires: []` rather than as a blank.
47
+ """
48
+
49
+
50
+ class TicketDumper(yaml.SafeDumper):
51
+ """
52
+ A dumper carrying docket's representers.
53
+
54
+ Subclassed rather than configured globally so registering a representer cannot affect another consumer of `pyyaml` in the same process.
55
+ """
56
+
57
+
58
+ @dataclass
59
+ class Ticket:
60
+ """
61
+ One ticket, holding its frontmatter fields, any unrecognized fields, and its body.
62
+ """
63
+
64
+ # MARK: Properties
65
+
66
+ id: str
67
+ title: str
68
+ status: str
69
+ priority: int
70
+ requires: list[str] = field(default_factory=list)
71
+
72
+ # Free-form entries any tool or skill can attach to a ticket, namespaced by whatever key that consumer chooses.
73
+ metadata: dict[str, Any] = field(default_factory=dict)
74
+
75
+ body: str = ""
76
+
77
+ # Fields the tool does not recognize, kept in the order they were read so a consumer repo can extend the schema without a tool change.
78
+ extra: dict[str, Any] = field(default_factory=dict)
79
+
80
+ # Where the ticket was loaded from, absent for a ticket that has not been written yet.
81
+ path: Optional[Path] = None
82
+
83
+ @property
84
+ def key(self) -> str:
85
+ """
86
+ The key portion of the ticket's id.
87
+ """
88
+
89
+ return keyOf(self.id)
90
+
91
+ @property
92
+ def isDone(self) -> bool:
93
+ """
94
+ Whether the ticket's status is the one that moves the file.
95
+ """
96
+
97
+ return self.status == STATUS_DONE
98
+
99
+ # MARK: Functions
100
+
101
+ def toFrontmatter(self) -> dict[str, Any]:
102
+ """
103
+ Build the frontmatter mapping in canonical order.
104
+
105
+ The explicit ordering is the whole mechanism, since dumping with sorting disabled follows insertion order.
106
+
107
+ Returns the ordered mapping.
108
+ """
109
+
110
+ # Place the recognized fields first, in the documented order.
111
+ mapping: dict[str, Any] = {
112
+ "id": self.id,
113
+ "title": self.title,
114
+ "status": self.status,
115
+ "priority": self.priority,
116
+ "requires": FlowList(self.requires),
117
+ "metadata": dict(self.metadata),
118
+ }
119
+
120
+ # Append preserved fields after them, in the order they were read.
121
+ for name, value in self.extra.items():
122
+ mapping[name] = value
123
+
124
+ return mapping
125
+
126
+ def summary(self) -> dict[str, Any]:
127
+ """
128
+ Build the summary form used by listings, which never carries the body.
129
+
130
+ Returns the summary mapping.
131
+ """
132
+
133
+ return {
134
+ "id": self.id,
135
+ "title": self.title,
136
+ "status": self.status,
137
+ "priority": self.priority,
138
+ "key": self.key,
139
+ }
140
+
141
+
142
+ # MARK: Functions
143
+
144
+
145
+ def _representFlowList(dumper: yaml.SafeDumper, data: FlowList) -> yaml.Node:
146
+ """
147
+ Represent a `FlowList` as an inline YAML sequence.
148
+
149
+ dumper: The active dumper.
150
+ data: The list being represented.
151
+
152
+ Returns the sequence node.
153
+ """
154
+
155
+ return dumper.represent_sequence("tag:yaml.org,2002:seq", list(data), flow_style=True)
156
+
157
+
158
+ TicketDumper.add_representer(FlowList, _representFlowList)
159
+
160
+
161
+ def splitFrontmatter(text: str) -> tuple[str, str]:
162
+ """
163
+ Split raw file text into its frontmatter block and its body.
164
+
165
+ The body is returned verbatim, including the blank line that conventionally follows the closing delimiter, so a round-trip reproduces the file exactly.
166
+
167
+ text: The full file text, with newlines already normalized to `\\n`.
168
+
169
+ Returns a `(frontmatterText, body)` pair.
170
+ """
171
+
172
+ lines: list[str] = text.split("\n")
173
+
174
+ # A ticket must open with the delimiter on its very first line.
175
+ if not lines or lines[0] != FRONTMATTER_DELIMITER:
176
+ raise TicketParseError(f"File does not open with a '{FRONTMATTER_DELIMITER}' frontmatter delimiter.")
177
+
178
+ # Find the closing delimiter, which is the first later line consisting of exactly the delimiter.
179
+ for index in range(1, len(lines)):
180
+ if lines[index] == FRONTMATTER_DELIMITER:
181
+ return "\n".join(lines[1:index]), "\n".join(lines[index + 1 :])
182
+
183
+ raise TicketParseError(f"Frontmatter block was opened but never closed with '{FRONTMATTER_DELIMITER}'.")
184
+
185
+
186
+ def parseTicket(text: str, path: Optional[Path] = None) -> Ticket:
187
+ """
188
+ Parse raw file text into a `Ticket`.
189
+
190
+ Structural problems raise here. Rule violations such as an out-of-range priority or an unrecognized status do not, because reporting those is `validate`'s job and it needs the ticket loaded to do it.
191
+
192
+ text: The full file text.
193
+ path: Where the text came from, recorded on the result.
194
+
195
+ Returns the parsed `Ticket`.
196
+ """
197
+
198
+ # Normalize line endings so a CRLF checkout parses identically to an LF one. Files are always written back as LF.
199
+ normalized: str = text.replace("\r\n", "\n").replace("\r", "\n")
200
+
201
+ frontmatterText, body = splitFrontmatter(normalized)
202
+
203
+ # Parse the block, turning any YAML failure into a docket error the shells already know how to report.
204
+ try:
205
+ loaded: Any = yaml.safe_load(frontmatterText)
206
+ except yaml.YAMLError as error:
207
+ raise TicketParseError(f"Frontmatter is not valid YAML: {error}") from error
208
+
209
+ # An empty block loads as `None`, which is a missing-fields problem rather than a mapping.
210
+ if loaded is None:
211
+ raise TicketParseError("Frontmatter block is empty.")
212
+ if not isinstance(loaded, dict):
213
+ raise TicketParseError(f"Frontmatter must be a mapping, got {type(loaded).__name__}.")
214
+
215
+ ticketId: str = readString(loaded, "id", TicketParseError, FIELD_SOURCE)
216
+ title: str = readString(loaded, "title", TicketParseError, FIELD_SOURCE)
217
+ status: str = readString(loaded, "status", TicketParseError, FIELD_SOURCE)
218
+ priority: int = readInt(loaded, "priority", TicketParseError, FIELD_SOURCE)
219
+ requires: list[str] = readStringList(loaded, "requires", TicketParseError, FIELD_SOURCE)
220
+ metadata: dict[str, Any] = readDict(loaded, "metadata", TicketParseError, FIELD_SOURCE)
221
+
222
+ # Keep everything the tool does not recognize, in the order it was read.
223
+ extra: dict[str, Any] = {name: value for name, value in loaded.items() if name not in CANONICAL_FIELDS}
224
+
225
+ return Ticket(id=ticketId, title=title, status=status, priority=priority, requires=requires, metadata=metadata, body=body, extra=extra, path=path)
226
+
227
+
228
+ def serializeTicket(ticket: Ticket) -> str:
229
+ """
230
+ Serialize a `Ticket` back to markdown.
231
+
232
+ ticket: The ticket to serialize.
233
+
234
+ Returns the full file text, with `\\n` newlines.
235
+ """
236
+
237
+ # Sorting must stay off, since the explicit field order in the mapping is what keeps diffs clean.
238
+ frontmatterText: str = yaml.dump(
239
+ ticket.toFrontmatter(),
240
+ Dumper=TicketDumper,
241
+ sort_keys=False,
242
+ allow_unicode=True,
243
+ default_flow_style=False,
244
+ width=YAML_WIDTH,
245
+ )
246
+
247
+ return f"{FRONTMATTER_DELIMITER}\n{frontmatterText}{FRONTMATTER_DELIMITER}\n{ticket.body}"
248
+
249
+
250
+ def buildBody(title: str, body: Optional[str] = None) -> str:
251
+ """
252
+ Assemble a new ticket's body.
253
+
254
+ The file always leads with an H1, because that is the shape the format documents. A supplied body that already opens with its own H1 is used as-is, so a caller writing a complete document does not end up with two headings.
255
+
256
+ title: The ticket title, used for the heading when one is needed.
257
+ body: The prose to place under the heading, if any.
258
+
259
+ Returns the body text, including the leading blank line that follows the closing frontmatter delimiter.
260
+ """
261
+
262
+ # Trim surrounding blank lines so spacing is decided here rather than by the caller.
263
+ prose: str = (body or "").strip("\n")
264
+
265
+ # A body that already leads with a heading owns its own structure.
266
+ if prose.startswith("# "):
267
+ return f"\n{prose}\n"
268
+
269
+ if not prose:
270
+ return f"\n# {title}\n"
271
+
272
+ return f"\n# {title}\n\n{prose}\n"
@@ -0,0 +1,378 @@
1
+ """
2
+ Docket Validate
3
+
4
+ Every integrity rule, returned as structured findings.
5
+
6
+ This is what makes the system trustworthy under a pre-commit hook or in CI, so it loads once and derives everything else from that single pass.
7
+ """
8
+
9
+ # MARK: Imports
10
+
11
+ from dataclasses import dataclass, field
12
+ from pathlib import Path
13
+ from typing import Optional
14
+
15
+ from docket.core.config import Config
16
+ from docket.core.graph import ResolvedGraph, findCycles, resolveGraph
17
+ from docket.core.store import Store, TicketSet
18
+ from docket.core.ticket import STATUSES, Ticket
19
+
20
+ # MARK: Constants
21
+
22
+ # The two severities a finding can carry. An error blocks, a warning informs.
23
+ SEVERITY_ERROR: str = "error"
24
+ SEVERITY_WARNING: str = "warning"
25
+
26
+ # Rule identifiers, so a consumer can filter or suppress by rule rather than by matching message text.
27
+ RULE_UNREADABLE: str = "unreadableTicket"
28
+ RULE_MISSING_DEPENDENCY: str = "missingDependency"
29
+ RULE_CYCLE: str = "dependencyCycle"
30
+ RULE_DUPLICATE_ID: str = "duplicateId"
31
+ RULE_UNKNOWN_KEY: str = "unknownKey"
32
+ RULE_FILENAME_MISMATCH: str = "filenameMismatch"
33
+ RULE_STATUS_DIRECTORY: str = "statusDirectoryMismatch"
34
+ RULE_PRIORITY_RANGE: str = "priorityOutOfRange"
35
+ RULE_UNKNOWN_STATUS: str = "unknownStatus"
36
+
37
+ # MARK: Classes
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class Finding:
42
+ """
43
+ One validation result.
44
+ """
45
+
46
+ # MARK: Properties
47
+
48
+ severity: str
49
+ rule: str
50
+ message: str
51
+
52
+ # The ticket the finding concerns, absent for a finding about a key or a file that never parsed.
53
+ ticketId: Optional[str] = None
54
+
55
+ # The file the finding concerns, absent for a finding about configuration.
56
+ path: Optional[Path] = None
57
+
58
+ # MARK: Functions
59
+
60
+ def toDict(self) -> dict[str, Optional[str]]:
61
+ """
62
+ Build the serializable form, used by the MCP surface.
63
+
64
+ Returns the finding as plain data.
65
+ """
66
+
67
+ return {
68
+ "severity": self.severity,
69
+ "rule": self.rule,
70
+ "message": self.message,
71
+ "id": self.ticketId,
72
+ "path": str(self.path) if self.path is not None else None,
73
+ }
74
+
75
+
76
+ @dataclass
77
+ class ValidationReport:
78
+ """
79
+ Every finding from one validation pass.
80
+ """
81
+
82
+ # MARK: Properties
83
+
84
+ findings: list[Finding] = field(default_factory=list)
85
+
86
+ @property
87
+ def errors(self) -> list[Finding]:
88
+ """
89
+ Findings that block.
90
+ """
91
+
92
+ return [finding for finding in self.findings if finding.severity == SEVERITY_ERROR]
93
+
94
+ @property
95
+ def warnings(self) -> list[Finding]:
96
+ """
97
+ Findings that inform.
98
+ """
99
+
100
+ return [finding for finding in self.findings if finding.severity == SEVERITY_WARNING]
101
+
102
+ @property
103
+ def isValid(self) -> bool:
104
+ """
105
+ Whether the set is free of errors. Warnings alone still count as valid.
106
+ """
107
+
108
+ return not self.errors
109
+
110
+ # MARK: Functions
111
+
112
+ def toDict(self) -> dict[str, object]:
113
+ """
114
+ Build the serializable form, used by the MCP surface.
115
+
116
+ Returns the report as plain data.
117
+ """
118
+
119
+ return {
120
+ "valid": self.isValid,
121
+ "errorCount": len(self.errors),
122
+ "warningCount": len(self.warnings),
123
+ "findings": [finding.toDict() for finding in self.findings],
124
+ }
125
+
126
+
127
+ # MARK: Functions
128
+
129
+
130
+ def validate(store: Store, ticketSet: Optional[TicketSet] = None) -> ValidationReport:
131
+ """
132
+ Run every rule against a ticket set.
133
+
134
+ store: The store naming the configuration and the ticket root.
135
+ ticketSet: An already-loaded set, loaded here when omitted.
136
+
137
+ Returns the report.
138
+ """
139
+
140
+ loaded: TicketSet = ticketSet if ticketSet is not None else store.loadAll()
141
+ config: Config = store.config
142
+ graph: ResolvedGraph = resolveGraph(loaded)
143
+
144
+ findings: list[Finding] = []
145
+
146
+ # Report what could not be read first, since every later rule is blind to those files.
147
+ findings.extend(_checkLoadFailures(loaded))
148
+ findings.extend(_checkDuplicateIds(loaded))
149
+
150
+ # Per-ticket rules, walked once in sorted order so output is stable.
151
+ for ticket in loaded.sorted():
152
+ findings.extend(_checkDependencies(ticket, loaded))
153
+ findings.extend(_checkKey(ticket, config))
154
+ findings.extend(_checkFilename(ticket))
155
+ findings.extend(_checkStatusDirectory(ticket, store))
156
+ findings.extend(_checkPriority(ticket, config))
157
+ findings.extend(_checkStatus(ticket))
158
+
159
+ findings.extend(_checkCycles(graph))
160
+
161
+ return ValidationReport(findings=findings)
162
+
163
+
164
+ def _checkLoadFailures(ticketSet: TicketSet) -> list[Finding]:
165
+ """
166
+ Report files under a status directory that could not be read as tickets.
167
+
168
+ ticketSet: The loaded set.
169
+
170
+ Returns the findings.
171
+ """
172
+
173
+ return [
174
+ Finding(severity=SEVERITY_ERROR, rule=RULE_UNREADABLE, message=f"{failure.path.name} could not be read as a ticket: {failure.message}", path=failure.path)
175
+ for failure in ticketSet.failures
176
+ ]
177
+
178
+
179
+ def _checkDuplicateIds(ticketSet: TicketSet) -> list[Finding]:
180
+ """
181
+ Report two tickets claiming one id.
182
+
183
+ This is the collision two branches minting under the same key produce, and catching it here at merge time is the accepted cost of having no counter file.
184
+
185
+ ticketSet: The loaded set.
186
+
187
+ Returns the findings.
188
+ """
189
+
190
+ return [
191
+ Finding(
192
+ severity=SEVERITY_ERROR,
193
+ rule=RULE_DUPLICATE_ID,
194
+ message=f"Id '{duplicate.id}' is claimed by both {duplicate.existingPath.name} and {duplicate.path.name}.",
195
+ ticketId=duplicate.id,
196
+ path=duplicate.path,
197
+ )
198
+ for duplicate in ticketSet.duplicates
199
+ ]
200
+
201
+
202
+ def _checkDependencies(ticket: Ticket, ticketSet: TicketSet) -> list[Finding]:
203
+ """
204
+ Report a `requires` entry naming an id that does not exist.
205
+
206
+ ticket: The ticket to check.
207
+ ticketSet: The loaded set to resolve against.
208
+
209
+ Returns the findings.
210
+ """
211
+
212
+ return [
213
+ Finding(
214
+ severity=SEVERITY_ERROR,
215
+ rule=RULE_MISSING_DEPENDENCY,
216
+ message=f"Ticket '{ticket.id}' requires '{requiredId}', which does not exist.",
217
+ ticketId=ticket.id,
218
+ path=ticket.path,
219
+ )
220
+ for requiredId in ticket.requires
221
+ if requiredId not in ticketSet
222
+ ]
223
+
224
+
225
+ def _checkKey(ticket: Ticket, config: Config) -> list[Finding]:
226
+ """
227
+ Report a ticket whose key is not registered.
228
+
229
+ ticket: The ticket to check.
230
+ config: The configuration holding the key registry.
231
+
232
+ Returns the findings.
233
+ """
234
+
235
+ if config.isRegisteredKey(ticket.key):
236
+ return []
237
+
238
+ return [
239
+ Finding(
240
+ severity=SEVERITY_ERROR,
241
+ rule=RULE_UNKNOWN_KEY,
242
+ message=f"Ticket '{ticket.id}' uses key '{ticket.key}', which is not registered.",
243
+ ticketId=ticket.id,
244
+ path=ticket.path,
245
+ )
246
+ ]
247
+
248
+
249
+ def _checkFilename(ticket: Ticket) -> list[Finding]:
250
+ """
251
+ Report a ticket whose id does not match its filename prefix.
252
+
253
+ The slug is deliberately not checked, because filenames are frozen at creation and a retitle is expected to leave the slug stale.
254
+
255
+ ticket: The ticket to check.
256
+
257
+ Returns the findings.
258
+ """
259
+
260
+ if ticket.path is None:
261
+ return []
262
+
263
+ # The prefix is everything before the first underscore, which is where the id ends.
264
+ prefix: str = ticket.path.stem.split("_", 1)[0]
265
+ if prefix == ticket.id:
266
+ return []
267
+
268
+ return [
269
+ Finding(
270
+ severity=SEVERITY_ERROR,
271
+ rule=RULE_FILENAME_MISMATCH,
272
+ message=f"Ticket '{ticket.id}' sits in {ticket.path.name}, whose filename prefix is '{prefix}'.",
273
+ ticketId=ticket.id,
274
+ path=ticket.path,
275
+ )
276
+ ]
277
+
278
+
279
+ def _checkStatusDirectory(ticket: Ticket, store: Store) -> list[Finding]:
280
+ """
281
+ Report a ticket whose status disagrees with the directory holding it.
282
+
283
+ The status field is the truth and the directory is a projection of it, so this catches a file a human moved by hand.
284
+
285
+ ticket: The ticket to check.
286
+ store: The store resolving a status to its directory.
287
+
288
+ Returns the findings.
289
+ """
290
+
291
+ if ticket.path is None:
292
+ return []
293
+
294
+ # An unrecognized status has no directory to agree with, and is reported by its own rule instead.
295
+ if ticket.status not in STATUSES:
296
+ return []
297
+
298
+ expected: Path = store.directoryFor(ticket.status)
299
+ if ticket.path.parent == expected:
300
+ return []
301
+
302
+ return [
303
+ Finding(
304
+ severity=SEVERITY_ERROR,
305
+ rule=RULE_STATUS_DIRECTORY,
306
+ message=f"Ticket '{ticket.id}' has status '{ticket.status}' but sits in '{ticket.path.parent.name}/' rather than '{expected.name}/'. Use 'docket {ticket.id} {ticket.status}' rather than moving files by hand.",
307
+ ticketId=ticket.id,
308
+ path=ticket.path,
309
+ )
310
+ ]
311
+
312
+
313
+ def _checkPriority(ticket: Ticket, config: Config) -> list[Finding]:
314
+ """
315
+ Report a priority outside the configured band.
316
+
317
+ ticket: The ticket to check.
318
+ config: The configuration holding the ceiling.
319
+
320
+ Returns the findings.
321
+ """
322
+
323
+ if 0 <= ticket.priority <= config.maxPriority:
324
+ return []
325
+
326
+ return [
327
+ Finding(
328
+ severity=SEVERITY_ERROR,
329
+ rule=RULE_PRIORITY_RANGE,
330
+ message=f"Ticket '{ticket.id}' has priority {ticket.priority}, outside 0 through {config.maxPriority}.",
331
+ ticketId=ticket.id,
332
+ path=ticket.path,
333
+ )
334
+ ]
335
+
336
+
337
+ def _checkStatus(ticket: Ticket) -> list[Finding]:
338
+ """
339
+ Report a status outside the fixed vocabulary.
340
+
341
+ ticket: The ticket to check.
342
+
343
+ Returns the findings.
344
+ """
345
+
346
+ if ticket.status in STATUSES:
347
+ return []
348
+
349
+ return [
350
+ Finding(
351
+ severity=SEVERITY_ERROR,
352
+ rule=RULE_UNKNOWN_STATUS,
353
+ message=f"Ticket '{ticket.id}' has status '{ticket.status}', which is not one of {', '.join(STATUSES)}.",
354
+ ticketId=ticket.id,
355
+ path=ticket.path,
356
+ )
357
+ ]
358
+
359
+
360
+ def _checkCycles(graph: ResolvedGraph) -> list[Finding]:
361
+ """
362
+ Report every dependency cycle.
363
+
364
+ graph: The resolved graph to search.
365
+
366
+ Returns the findings.
367
+ """
368
+
369
+ findings: list[Finding] = []
370
+ for cycle in findCycles(graph):
371
+ # A one-member cycle is a ticket requiring itself, which reads better stated plainly.
372
+ if len(cycle) == 1:
373
+ findings.append(Finding(severity=SEVERITY_ERROR, rule=RULE_CYCLE, message=f"Ticket '{cycle[0]}' requires itself.", ticketId=cycle[0]))
374
+ continue
375
+
376
+ findings.append(Finding(severity=SEVERITY_ERROR, rule=RULE_CYCLE, message=f"Dependency cycle between {', '.join(cycle)}.", ticketId=cycle[0]))
377
+
378
+ return findings
docket/py.typed ADDED
File without changes