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/__init__.py ADDED
@@ -0,0 +1,11 @@
1
+ """
2
+ Docket
3
+
4
+ A per-repo ticketing system that is plain markdown for humans and structured MCP for agents.
5
+ """
6
+
7
+ # MARK: Constants
8
+
9
+ # No type check to comply with hatch's requirements.
10
+ # Do not re-add.
11
+ __version__ = "1.0.0"
docket/cli/__init__.py ADDED
@@ -0,0 +1,171 @@
1
+ """
2
+ Docket CLI
3
+
4
+ Argument parsing and command dispatch, a thin shell over `docket.core`.
5
+
6
+ This holds no rules of its own. Every decision belongs to the core, so the CLI and the MCP server can never disagree about one.
7
+ """
8
+
9
+ # MARK: Imports
10
+
11
+ import argparse
12
+ import sys
13
+ from typing import Optional
14
+
15
+ from docket.cli.commands import (
16
+ commandDeploy,
17
+ commandGraph,
18
+ commandKey,
19
+ commandList,
20
+ commandMeta,
21
+ commandNew,
22
+ commandSet,
23
+ commandShow,
24
+ commandStatus,
25
+ commandStatusRead,
26
+ commandTicket,
27
+ commandValidate,
28
+ )
29
+ from docket.cli.grammar import (
30
+ CLEAR_SENTINEL,
31
+ EXIT_INVALID,
32
+ EXIT_OK,
33
+ EXIT_USAGE,
34
+ OUT_ARGUMENT,
35
+ PROGRAM_NAME,
36
+ TICKET_COMMAND,
37
+ TOKEN_ID,
38
+ TOKEN_KEY,
39
+ TOKEN_PRIORITY,
40
+ TOKEN_STATUS,
41
+ buildParser,
42
+ classifyToken,
43
+ describeKeys,
44
+ describePriorities,
45
+ parseEditIdList,
46
+ parseIdList,
47
+ resolveGraphScope,
48
+ resolveListFilters,
49
+ rewriteIdFirst,
50
+ tryDiscoverConfig,
51
+ )
52
+ from docket.cli.output import STATUS_STYLES, Output, buildContextTable, relativeToRoot
53
+ from docket.core.config import Config, discoverConfig
54
+ from docket.core.errors import DocketError
55
+ from docket.core.store import Store
56
+
57
+ # MARK: Constants
58
+
59
+ # `docket.cli` was one module before it was a package, and it is what `pyproject.toml` names as the console script. Everything the outside world reached for then is still reachable by the same path.
60
+ __all__: list[str] = [
61
+ "CLEAR_SENTINEL",
62
+ "EXIT_INVALID",
63
+ "EXIT_OK",
64
+ "EXIT_USAGE",
65
+ "OUT_ARGUMENT",
66
+ "PROGRAM_NAME",
67
+ "STATUS_STYLES",
68
+ "TICKET_COMMAND",
69
+ "TOKEN_ID",
70
+ "TOKEN_KEY",
71
+ "TOKEN_PRIORITY",
72
+ "TOKEN_STATUS",
73
+ "Output",
74
+ "buildContextTable",
75
+ "buildParser",
76
+ "classifyToken",
77
+ "commandDeploy",
78
+ "commandGraph",
79
+ "commandKey",
80
+ "commandList",
81
+ "commandMeta",
82
+ "commandNew",
83
+ "commandSet",
84
+ "commandShow",
85
+ "commandStatus",
86
+ "commandStatusRead",
87
+ "commandTicket",
88
+ "commandValidate",
89
+ "describeKeys",
90
+ "describePriorities",
91
+ "dispatch",
92
+ "main",
93
+ "parseEditIdList",
94
+ "parseIdList",
95
+ "relativeToRoot",
96
+ "resolveGraphScope",
97
+ "resolveListFilters",
98
+ "rewriteIdFirst",
99
+ "tryDiscoverConfig",
100
+ ]
101
+
102
+ # MARK: Functions
103
+
104
+
105
+ def main(argv: Optional[list[str]] = None) -> int:
106
+ """
107
+ Entry point for the `docket` console script.
108
+
109
+ argv: Argument list to parse, defaulting to `sys.argv[1:]`.
110
+
111
+ Returns the process exit code.
112
+ """
113
+
114
+ # Read the configuration before the parser is built, so the help text can name the keys and priorities this repository actually allows. A missing one is not fatal here, since the commands that need it say so themselves.
115
+ config: Optional[Config] = tryDiscoverConfig()
116
+
117
+ parser: argparse.ArgumentParser = buildParser(config)
118
+
119
+ # A leading ticket id is the shape a person types, so it is named as the branch that handles it before the parser is ever asked about it.
120
+ arguments: list[str] = sys.argv[1:] if argv is None else argv
121
+ args: argparse.Namespace = parser.parse_args(rewriteIdFirst(arguments))
122
+
123
+ output: Output = Output()
124
+
125
+ # With no subcommand there is nothing to dispatch, so show help and report a usage error.
126
+ if args.command is None:
127
+ parser.print_help()
128
+ return EXIT_USAGE
129
+
130
+ # Every core failure surfaces here as a message and an exit code, which is the whole of the CLI's error handling.
131
+ try:
132
+ return dispatch(args, config, output)
133
+ except DocketError as error:
134
+ output.error(str(error))
135
+ return EXIT_USAGE
136
+
137
+
138
+ def dispatch(args: argparse.Namespace, config: Optional[Config], output: Output) -> int:
139
+ """
140
+ Route parsed arguments to the command that handles them.
141
+
142
+ args: The parsed arguments.
143
+ config: The configuration already discovered for the help text, or `None` when none was found.
144
+ output: Where to write.
145
+
146
+ Returns the process exit code.
147
+ """
148
+
149
+ # Deploy and upgrade run before a configuration exists, or in order to repair one, so they must not require discovering it first.
150
+ if args.command in ("deploy", "upgrade"):
151
+ return commandDeploy(args, output)
152
+
153
+ # Every other command works against the configuration governing the current directory. Discovery is repeated when the parser was built without one, so the reason it could not be found is reported by the code that knows it.
154
+ store: Store = Store(config if config is not None else discoverConfig())
155
+
156
+ handlers = {
157
+ TICKET_COMMAND: commandTicket,
158
+ "new": commandNew,
159
+ "list": commandList,
160
+ "graph": commandGraph,
161
+ "key": commandKey,
162
+ "validate": commandValidate,
163
+ }
164
+
165
+ return handlers[args.command](args, store, output)
166
+
167
+
168
+ # MARK: Main
169
+
170
+ if __name__ == "__main__":
171
+ sys.exit(main())
docket/cli/__main__.py ADDED
@@ -0,0 +1,16 @@
1
+ """
2
+ Docket CLI Module Entry
3
+
4
+ Runs the CLI as `python -m docket.cli`, which is what the single-module layout gave for free.
5
+ """
6
+
7
+ # MARK: Imports
8
+
9
+ import sys
10
+
11
+ from docket.cli import main
12
+
13
+ # MARK: Main
14
+
15
+ if __name__ == "__main__":
16
+ sys.exit(main())
docket/cli/commands.py ADDED
@@ -0,0 +1,428 @@
1
+ """
2
+ Docket CLI Commands
3
+
4
+ One handler per subcommand, each turning parsed arguments into core calls and printed output.
5
+
6
+ No rules live here either. A handler decides what to say, never what is true.
7
+ """
8
+
9
+ # MARK: Imports
10
+
11
+ import argparse
12
+ from pathlib import Path
13
+
14
+ from rich.table import Table
15
+ from rich.text import Text
16
+
17
+ from docket.cli.grammar import EXIT_INVALID, EXIT_OK, EXIT_USAGE, OUT_ARGUMENT, parseEditIdList, parseIdList, resolveGraphScope, resolveListFilters
18
+ from docket.cli.output import STATUS_STYLES, Output, buildContextTable, relativeToRoot
19
+ from docket.core.config import Config
20
+ from docket.core.deploy import DeployReport, deploy, upgrade
21
+ from docket.core.graph import ResolvedGraph, dependencyContext, resolveGraph, subgraphForId, subgraphForKey
22
+ from docket.core.inputs import requireWritableFile, writeFile
23
+ from docket.core.mermaid import renderGraph
24
+ from docket.core.store import Store, TicketResult, TicketSet
25
+ from docket.core.ticket import STATUSES, Ticket
26
+ from docket.core.validate import SEVERITY_ERROR, ValidationReport, validate
27
+
28
+ # MARK: Functions
29
+
30
+
31
+ def commandTicket(args: argparse.Namespace, store: Store, output: Output) -> int:
32
+ """
33
+ Route one ticket's command to the handler for it.
34
+
35
+ A bare id shows the ticket, since showing it is what naming one almost always means.
36
+
37
+ args: The parsed arguments.
38
+ store: The store to read from or write through.
39
+ output: Where to write.
40
+
41
+ Returns the process exit code.
42
+ """
43
+
44
+ # A status word is not a command carrying a value, it is the whole instruction.
45
+ if args.ticketCommand in STATUSES:
46
+ return commandStatus(args, store, output)
47
+
48
+ handlers = {
49
+ None: commandShow,
50
+ "show": commandShow,
51
+ "status": commandStatusRead,
52
+ "set": commandSet,
53
+ "meta": commandMeta,
54
+ }
55
+
56
+ return handlers[args.ticketCommand](args, store, output)
57
+
58
+
59
+ def commandNew(args: argparse.Namespace, store: Store, output: Output) -> int:
60
+ """
61
+ Create a ticket.
62
+
63
+ args: The parsed arguments.
64
+ store: The store to write through.
65
+ output: Where to write.
66
+
67
+ Returns the process exit code.
68
+ """
69
+
70
+ result: TicketResult = store.create(
71
+ key=args.key,
72
+ title=args.title,
73
+ body=args.body,
74
+ requires=parseIdList(args.requires),
75
+ priority=args.priority,
76
+ )
77
+
78
+ # A dangling dependency is a warning here, so a batch written out of order still completes.
79
+ for warning in result.warnings:
80
+ output.warn(warning)
81
+
82
+ output.print(f"Created [bold]{result.ticket.id}[/bold] at {relativeToRoot(result.ticket.path, store.config.repoRoot)}")
83
+
84
+ return EXIT_OK
85
+
86
+
87
+ def commandShow(args: argparse.Namespace, store: Store, output: Output) -> int:
88
+ """
89
+ Show a ticket with its resolved dependency context.
90
+
91
+ The raw file carries bare ids in one direction only, so this resolves the titles and statuses the file deliberately does not duplicate. Use `cat` for the raw file.
92
+
93
+ args: The parsed arguments.
94
+ store: The store to read from.
95
+ output: Where to write.
96
+
97
+ Returns the process exit code.
98
+ """
99
+
100
+ loaded: TicketSet = store.loadAll()
101
+ ticket: Ticket = loaded.get(args.id)
102
+ context = dependencyContext(loaded, args.id)
103
+
104
+ output.print(Text(f"{ticket.id} {ticket.title}", style="bold"))
105
+ output.print(f"status [{STATUS_STYLES.get(ticket.status, 'white')}]{ticket.status}[/] priority {ticket.priority} key {ticket.key}")
106
+
107
+ # Show both directions, since the reverse one is the whole reason the file can afford to store only forward edges.
108
+ output.print("")
109
+ output.print(buildContextTable("Requires", context["requires"]))
110
+ output.print("")
111
+ output.print(buildContextTable("Required by", context["requiredBy"]))
112
+
113
+ output.print("")
114
+ output.print(ticket.body.strip("\n"))
115
+
116
+ return EXIT_OK
117
+
118
+
119
+ def commandList(args: argparse.Namespace, store: Store, output: Output) -> int:
120
+ """
121
+ List ticket summaries.
122
+
123
+ args: The parsed arguments.
124
+ store: The store to read from.
125
+ output: Where to write.
126
+
127
+ Returns the process exit code.
128
+ """
129
+
130
+ status, key, priorityMax = resolveListFilters(args.filters, args.status, args.key, args.priorityMax)
131
+
132
+ # An unregistered key cannot match a ticket, so name it rather than reporting an empty result the user would read as "no work here".
133
+ if key is not None:
134
+ store.config.requireKnownKey(key)
135
+
136
+ tickets: list[Ticket] = store.loadAll().filtered(status=status, key=key, priorityMax=priorityMax)
137
+
138
+ if not tickets:
139
+ output.print("[dim]No tickets matched.[/dim]")
140
+ return EXIT_OK
141
+
142
+ table: Table = Table(box=None, pad_edge=False)
143
+ table.add_column("ID", style="bold")
144
+ table.add_column("P", justify="right")
145
+ table.add_column("STATUS")
146
+ table.add_column("TITLE")
147
+
148
+ for ticket in tickets:
149
+ table.add_row(ticket.id, str(ticket.priority), Text(ticket.status, style=STATUS_STYLES.get(ticket.status, "white")), ticket.title)
150
+
151
+ output.print(table)
152
+
153
+ return EXIT_OK
154
+
155
+
156
+ def commandSet(args: argparse.Namespace, store: Store, output: Output) -> int:
157
+ """
158
+ Change a ticket's title, priority, or dependencies.
159
+
160
+ args: The parsed arguments.
161
+ store: The store to write through.
162
+ output: Where to write.
163
+
164
+ Returns the process exit code.
165
+ """
166
+
167
+ # Nothing to do is a usage error rather than a silent success, since the caller clearly meant to change something.
168
+ if args.title is None and args.priority is None and args.requires is None and args.requiresAdd is None and args.requiresRemove is None:
169
+ output.error("Nothing to change. Pass at least one of --title, --priority, --requires, --requires-add, or --requires-remove.")
170
+ return EXIT_USAGE
171
+
172
+ result: TicketResult = store.update(
173
+ ticketId=args.id,
174
+ title=args.title,
175
+ priority=args.priority,
176
+ requires=parseIdList(args.requires) if args.requires is not None else None,
177
+ requiresAdd=parseEditIdList(args.requiresAdd, "--requires-add"),
178
+ requiresRemove=parseEditIdList(args.requiresRemove, "--requires-remove"),
179
+ )
180
+
181
+ for warning in result.warnings:
182
+ output.warn(warning)
183
+
184
+ output.print(f"Updated [bold]{result.ticket.id}[/bold]")
185
+
186
+ return EXIT_OK
187
+
188
+
189
+ def commandStatus(args: argparse.Namespace, store: Store, output: Output) -> int:
190
+ """
191
+ Change a ticket's status, moving its file in the same operation.
192
+
193
+ args: The parsed arguments.
194
+ store: The store to write through.
195
+ output: Where to write.
196
+
197
+ Returns the process exit code.
198
+ """
199
+
200
+ # The command that was typed is the status, since each status is its own command rather than a value handed to a shared one.
201
+ ticket: Ticket = store.setStatus(args.id, args.ticketCommand)
202
+
203
+ output.print(f"[bold]{ticket.id}[/bold] is now [{STATUS_STYLES.get(ticket.status, 'white')}]{ticket.status}[/] at {relativeToRoot(ticket.path, store.config.repoRoot)}")
204
+
205
+ return EXIT_OK
206
+
207
+
208
+ def commandStatusRead(args: argparse.Namespace, store: Store, output: Output) -> int:
209
+ """
210
+ Print a ticket's status and nothing else.
211
+
212
+ This goes out raw, with no styling and no surrounding words, so a shell can read the answer as easily as a person can.
213
+
214
+ args: The parsed arguments.
215
+ store: The store to read from.
216
+ output: Where to write.
217
+
218
+ Returns the process exit code.
219
+ """
220
+
221
+ ticket: Ticket = store.load(args.id)
222
+
223
+ output.raw(f"{ticket.status}\n")
224
+
225
+ return EXIT_OK
226
+
227
+
228
+ def commandMeta(args: argparse.Namespace, store: Store, output: Output) -> int:
229
+ """
230
+ Inspect and manage a ticket's metadata map.
231
+
232
+ How much of the call was typed is what it means. No key reads the whole map, a key alone reads that one entry, and a key with a value writes it, which is the same shape a status has.
233
+
234
+ args: The parsed arguments.
235
+ store: The store to read from or write through.
236
+ output: Where to write.
237
+
238
+ Returns the process exit code.
239
+ """
240
+
241
+ if args.key is None:
242
+ # Clearing needs to know what to clear, and the whole map is not it.
243
+ if args.clear:
244
+ output.error("Nothing to clear. Name the metadata key to remove.")
245
+ return EXIT_USAGE
246
+
247
+ ticket: Ticket = store.load(args.id)
248
+
249
+ if not ticket.metadata:
250
+ output.print("[dim]No metadata.[/dim]")
251
+ return EXIT_OK
252
+
253
+ table: Table = Table(box=None, pad_edge=False)
254
+ table.add_column("KEY", style="bold")
255
+ table.add_column("VALUE")
256
+
257
+ for key, value in ticket.metadata.items():
258
+ table.add_row(key, str(value))
259
+
260
+ output.print(table)
261
+
262
+ return EXIT_OK
263
+
264
+ if args.clear and args.value is not None:
265
+ output.error("Cannot pass a value together with -c/--clear.")
266
+ return EXIT_USAGE
267
+
268
+ # A key with no value reads that entry, raw, for the same reason `status` does.
269
+ if not args.clear and args.value is None:
270
+ ticket = store.load(args.id)
271
+
272
+ if args.key not in ticket.metadata:
273
+ output.error(f"'{args.key}' is not set on {ticket.id}.")
274
+ return EXIT_USAGE
275
+
276
+ output.raw(f"{ticket.metadata[args.key]}\n")
277
+
278
+ return EXIT_OK
279
+
280
+ result: TicketResult = store.setMetadata(ticketId=args.id, key=args.key, value=None if args.clear else args.value)
281
+
282
+ for warning in result.warnings:
283
+ output.warn(warning)
284
+
285
+ verb: str = "Cleared" if args.clear else "Set"
286
+ output.print(f"{verb} [bold]{args.key}[/bold] on [bold]{result.ticket.id}[/bold]")
287
+
288
+ return EXIT_OK
289
+
290
+
291
+ def commandGraph(args: argparse.Namespace, store: Store, output: Output) -> int:
292
+ """
293
+ Render the dependency graph as mermaid source.
294
+
295
+ args: The parsed arguments.
296
+ store: The store to read from.
297
+ output: Where to write.
298
+
299
+ Returns the process exit code.
300
+ """
301
+
302
+ ticketId, key = resolveGraphScope(args.scope, args.id, args.key)
303
+
304
+ graph: ResolvedGraph = resolveGraph(store.loadAll())
305
+
306
+ # Scope the graph when asked. At most one of the two survives resolution.
307
+ if ticketId is not None:
308
+ graph = subgraphForId(graph, ticketId)
309
+ elif key is not None:
310
+ # For the same reason as `list`, an unregistered key here would render an empty graph rather than admitting the key does not exist.
311
+ store.config.requireKnownKey(key)
312
+ graph = subgraphForKey(graph, key)
313
+
314
+ source: str = renderGraph(graph)
315
+
316
+ if args.out is not None:
317
+ # Check the destination before rendering work is spent on it, and translate whatever the filesystem still refuses, so no write failure reaches the user as a traceback.
318
+ outPath: Path = writeFile(requireWritableFile(args.out, OUT_ARGUMENT), source, OUT_ARGUMENT)
319
+ output.print(f"Wrote {outPath}")
320
+
321
+ return EXIT_OK
322
+
323
+ # Straight to stdout with no styling, so a redirect captures exactly the mermaid source.
324
+ output.raw(source)
325
+
326
+ return EXIT_OK
327
+
328
+
329
+ def commandKey(args: argparse.Namespace, store: Store, output: Output) -> int:
330
+ """
331
+ Inspect and manage the key registry.
332
+
333
+ args: The parsed arguments.
334
+ store: The store, which also reports which keys are in use.
335
+ output: Where to write.
336
+
337
+ Returns the process exit code.
338
+ """
339
+
340
+ config: Config = store.config
341
+
342
+ if args.keyCommand == "add":
343
+ config.addKey(args.key, args.description, rationale=args.rationale)
344
+ output.print(f"Added [bold]{args.key}[/bold]")
345
+
346
+ return EXIT_OK
347
+
348
+ if args.keyCommand == "remove":
349
+ # Hand the store's view of usage in, so a key with tickets behind it fails loudly and names them.
350
+ config.removeKey(args.key, usedBy=store.usedKeys().get(args.key))
351
+ output.print(f"Removed [bold]{args.key}[/bold]")
352
+
353
+ return EXIT_OK
354
+
355
+ if args.keyCommand != "list":
356
+ output.error("Expected one of: list, add, remove.")
357
+ return EXIT_USAGE
358
+
359
+ table: Table = Table(box=None, pad_edge=False)
360
+ table.add_column("KEY", style="bold")
361
+ table.add_column("DESCRIPTION")
362
+
363
+ for key, description in sorted(config.registeredKeys.items()):
364
+ table.add_row(key, description)
365
+
366
+ if not table.rows:
367
+ output.print("[dim]No keys.[/dim]")
368
+ return EXIT_OK
369
+
370
+ output.print(table)
371
+
372
+ return EXIT_OK
373
+
374
+
375
+ def commandValidate(args: argparse.Namespace, store: Store, output: Output) -> int:
376
+ """
377
+ Run every integrity rule.
378
+
379
+ args: The parsed arguments.
380
+ store: The store to validate.
381
+ output: Where to write.
382
+
383
+ Returns the process exit code, non-zero when errors were found.
384
+ """
385
+
386
+ report: ValidationReport = validate(store)
387
+
388
+ if not report.findings:
389
+ output.print("[green]No findings.[/green]")
390
+ return EXIT_OK
391
+
392
+ for finding in report.findings:
393
+ style: str = "bold red" if finding.severity == SEVERITY_ERROR else "yellow"
394
+ location: str = f" [dim]{finding.path.name}[/dim]" if finding.path is not None else ""
395
+ output.print(Text.from_markup(f"[{style}]{finding.severity}[/] [dim]{finding.rule}[/dim] {finding.message}{location}"))
396
+
397
+ output.print(f"\n{len(report.errors)} error(s), {len(report.warnings)} warning(s)")
398
+
399
+ # Warnings alone must not fail a pre-commit hook, so only errors change the exit code.
400
+ return EXIT_INVALID if report.errors else EXIT_OK
401
+
402
+
403
+ def commandDeploy(args: argparse.Namespace, output: Output) -> int:
404
+ """
405
+ Install docket into a repository, or refresh what is already deployed there.
406
+
407
+ args: The parsed arguments.
408
+ output: Where to write.
409
+
410
+ Returns the process exit code.
411
+ """
412
+
413
+ target: Path = Path(args.path)
414
+ report: DeployReport = deploy(target) if args.command == "deploy" else upgrade(target)
415
+
416
+ # Report every step, since deploy is idempotent and the useful information is which steps actually changed something.
417
+ root: Path = target.resolve()
418
+ for path in report.created:
419
+ output.print(f"[green]created[/green] {relativeToRoot(path, root)}")
420
+ for path in report.updated:
421
+ output.print(f"[yellow]updated[/yellow] {relativeToRoot(path, root)}")
422
+ for path in report.skipped:
423
+ output.print(f"[dim]kept {relativeToRoot(path, root)}[/dim]")
424
+
425
+ if args.command == "deploy":
426
+ output.print("\nAdd your keys to [bold].docket.toml[/bold] before creating tickets.")
427
+
428
+ return EXIT_OK