waymark-cli 0.1.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.
Files changed (92) hide show
  1. waymark/__init__.py +3 -0
  2. waymark/__main__.py +8 -0
  3. waymark/adapters/__init__.py +102 -0
  4. waymark/adapters/claude_code.py +238 -0
  5. waymark/assets/__init__.py +43 -0
  6. waymark/assets/agents/wm-implementer.md +45 -0
  7. waymark/assets/agents/wm-reviewer.md +43 -0
  8. waymark/assets/skills/wm-apply/SKILL.md +58 -0
  9. waymark/assets/skills/wm-archive/SKILL.md +32 -0
  10. waymark/assets/skills/wm-explore/SKILL.md +34 -0
  11. waymark/assets/skills/wm-kickoff/SKILL.md +34 -0
  12. waymark/assets/skills/wm-onboard/SKILL.md +27 -0
  13. waymark/assets/skills/wm-pr/SKILL.md +24 -0
  14. waymark/assets/skills/wm-propose/SKILL.md +32 -0
  15. waymark/assets/skills/wm-update/SKILL.md +31 -0
  16. waymark/cli.py +537 -0
  17. waymark/hooks/__init__.py +6 -0
  18. waymark/hooks/commands.py +190 -0
  19. waymark/hooks/decide.py +314 -0
  20. waymark/hooks/events.py +79 -0
  21. waymark/py.typed +0 -0
  22. waymark/record/__init__.py +5 -0
  23. waymark/record/atlas.py +156 -0
  24. waymark/record/changes.py +202 -0
  25. waymark/record/charter.py +75 -0
  26. waymark/record/commits.py +78 -0
  27. waymark/record/config.py +215 -0
  28. waymark/record/deltas.py +318 -0
  29. waymark/record/design.py +80 -0
  30. waymark/record/edits.py +95 -0
  31. waymark/record/evidence.py +58 -0
  32. waymark/record/explorations.py +66 -0
  33. waymark/record/files.py +75 -0
  34. waymark/record/fingerprint.py +73 -0
  35. waymark/record/git.py +167 -0
  36. waymark/record/githooks.py +106 -0
  37. waymark/record/links.py +104 -0
  38. waymark/record/milestones.py +84 -0
  39. waymark/record/moves.py +60 -0
  40. waymark/record/names.py +39 -0
  41. waymark/record/outline.py +144 -0
  42. waymark/record/pointer.py +56 -0
  43. waymark/record/problems.py +20 -0
  44. waymark/record/project.py +118 -0
  45. waymark/record/proposal.py +171 -0
  46. waymark/record/record.py +340 -0
  47. waymark/record/registry.py +158 -0
  48. waymark/record/specs.py +227 -0
  49. waymark/record/state.py +472 -0
  50. waymark/record/store.py +88 -0
  51. waymark/record/tasks.py +415 -0
  52. waymark/record/templates/charter.md +45 -0
  53. waymark/record/templates/ci-workflow.yml +29 -0
  54. waymark/record/templates/config-atlas.toml +8 -0
  55. waymark/record/templates/config.toml +19 -0
  56. waymark/record/templates/delta.md +29 -0
  57. waymark/record/templates/design.md +20 -0
  58. waymark/record/templates/exploration.md +22 -0
  59. waymark/record/templates/goal.md +13 -0
  60. waymark/record/templates/hook-commit-msg +8 -0
  61. waymark/record/templates/hook-pre-commit +8 -0
  62. waymark/record/templates/proposal.md +18 -0
  63. waymark/record/templates/roadmap.md +4 -0
  64. waymark/record/templates/tasks.md +10 -0
  65. waymark/record/templates.py +30 -0
  66. waymark/record/terms.py +51 -0
  67. waymark/record/text.py +197 -0
  68. waymark/services/__init__.py +1 -0
  69. waymark/services/atlas.py +162 -0
  70. waymark/services/check.py +129 -0
  71. waymark/services/ci.py +44 -0
  72. waymark/services/common.py +154 -0
  73. waymark/services/context.py +296 -0
  74. waymark/services/doctor.py +367 -0
  75. waymark/services/githooks.py +132 -0
  76. waymark/services/instructions.py +304 -0
  77. waymark/services/integration.py +170 -0
  78. waymark/services/lifecycle.py +454 -0
  79. waymark/services/migrations.py +90 -0
  80. waymark/services/pr.py +177 -0
  81. waymark/services/references.py +27 -0
  82. waymark/services/setup.py +127 -0
  83. waymark/views/__init__.py +5 -0
  84. waymark/views/payloads.py +568 -0
  85. waymark/views/render.py +506 -0
  86. waymark/views/schemas.py +413 -0
  87. waymark/views/style.py +102 -0
  88. waymark_cli-0.1.0.dist-info/METADATA +313 -0
  89. waymark_cli-0.1.0.dist-info/RECORD +92 -0
  90. waymark_cli-0.1.0.dist-info/WHEEL +4 -0
  91. waymark_cli-0.1.0.dist-info/entry_points.txt +2 -0
  92. waymark_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,27 @@
1
+ ---
2
+ name: wm-onboard
3
+ description: Guide the human through their first Waymark change on their own code, explaining each step as it happens. Use after kickoff, or when someone is new to Waymark.
4
+ ---
5
+
6
+ # Onboard
7
+
8
+ You are the planner, and this once also a guide. You run one real, small change through the whole workflow on the human's own code, and before each step you say in a sentence or two what the step is for. There is no demo project: the change is real and it stays.
9
+
10
+ ## Steps
11
+
12
+ 1. Run `wm status`. If the charter is still a skeleton, run the `wm-kickoff` skill first.
13
+ 2. **Pick the change.** Ask the human for something small and real they want anyway: a fix, a doc correction, a small behavior. It should fit in one or two task items. Explain: everything in Waymark is a change, even the first one.
14
+ 3. **Propose.** Explain: a proposal says why and what, before anything is built. Follow the `wm-propose` skill, on the short path if the change allows it.
15
+ 4. **Specs.** If the change affects what the system does, explain: specs say what the system does; a delta is this change's edit to them. On existing code, the spec grows only where the change touches it.
16
+ 5. **Tasks.** Explain: each item carries criteria and a way to verify it, so an agent can build it from the record alone.
17
+ 6. **Accept.** Explain: this is the first of two approvals. Nothing is built before it, and only the human gives it. Ask them to run `wm accept <name>`.
18
+ 7. **Apply and review.** Explain: a fresh implementer builds each item from the record; the review is recorded under the item. Follow the `wm-apply` skill.
19
+ 8. **Look around.** Show `wm status`, `wm show <name>` and `wm inbox`. Explain: these come from the files alone, so any session can pick up from here.
20
+ 9. **Archive.** Explain: this is the second approval. The deltas merge into the specs and the change moves to the dated archive. Follow the `wm-archive` skill.
21
+ 10. **Wrap up.** Show `wm ls specs` and the archived change. Name what the human will use from now on: `wm-explore` for fuzzy ideas, `wm-propose` to start a change, `wm-apply` to build it, `wm-archive` to finish it, and `wm status` to see where things stand.
22
+
23
+ ## Rules
24
+
25
+ - Keep each explanation to a sentence or two, given just before the step it explains.
26
+ - Every rule of the skills you follow applies here too. In particular, never run `wm accept`.
27
+ - If the human wants to stop partway, stop. `wm status` will show where to resume.
@@ -0,0 +1,24 @@
1
+ ---
2
+ name: wm-pr
3
+ description: Open a pull request described from a Waymark change, after asking the human. Use when a change's work is committed and the human wants it reviewed or merged.
4
+ ---
5
+
6
+ # Pull request
7
+
8
+ You are the planner. A pull request is an outward action, so you open one only when the human asks, and you show them the text first.
9
+
10
+ ## Steps
11
+
12
+ 1. Find the change. If the human didn't name it, run `wm ls changes` and ask which one.
13
+ 2. Run `wm show <name> --json`. Check that the work is committed on the change's branch; the branch is named after the change.
14
+ 3. Run `wm pr <name> --json` for the title and description. In a project that spans several repositories, run it once per repository: without `--repo` for the atlas, which carries the record, and with `--repo <repo>` for each code repo the change's items name. The description already says why, what changes, the specs touched, the items with how each was reviewed, and links to the change and to the other repositories' pull requests.
15
+ 4. Show the human the title and description. You may add a line on what a reviewer should look at first. Ask whether to open the pull request, and against which branch.
16
+ 5. Only after they say yes: push the branch and open the pull request with the git host's own command-line tool, using that title and description.
17
+ 6. Give the human the link.
18
+
19
+ ## Rules
20
+
21
+ - Don't push and don't open a pull request without the human's yes in this conversation.
22
+ - Don't merge.
23
+ - Don't name the change or its items in commit messages; the record links work to changes.
24
+ - In a project that spans several repositories, each repository gets its own pull request, opened from its own folder. Open them one at a time.
@@ -0,0 +1,32 @@
1
+ ---
2
+ name: wm-propose
3
+ description: Draft a Waymark change for the human to accept - the proposal, the spec deltas, the design and the task list. Use when the human wants to build or change something.
4
+ ---
5
+
6
+ # Propose
7
+
8
+ You are the planner. You draft every artifact of a change; the human reads them and decides. Nothing is built until they accept the change.
9
+
10
+ ## Steps
11
+
12
+ 1. Agree on a name with the human: kebab-case, starting with a verb, such as `add-search-limit`. Ask whether this is a small change. A small change takes the short path: no design, and no item that needs independent review. Then run `wm new change <name>`, with `--short` for the short path.
13
+ 2. Repeat until the next step is `accept`:
14
+ - Run `wm instructions --change <name> --json`. It names the step, the file to write, its template, the project's rules for this step, and what to read first.
15
+ - Read what it lists. Draft the file from the template. Keep the headings and formats exactly; they are parsed.
16
+ - Run `wm check`. Fix every error in the files you wrote before moving on.
17
+ - Show the human what you drafted and take their corrections.
18
+ 3. The steps come in this order:
19
+ - **propose**: why, what changes, non-goals, impact. Under Impact, name the specs the change touches or write "No spec changes".
20
+ - **specs**: one delta file per spec. Agree on what the system does before deciding how.
21
+ - **design**: how it will be built, with each decision's options, choice and reason. Skipped on the short path.
22
+ - **tasks**: items small enough for one agent to build from the record alone. Every item needs criteria that can be checked and a way to verify it.
23
+ 4. Suggest a review level for each item. Tag an item `review: independent` when it modifies or removes an existing requirement, touches security, data integrity or money, or is being redone after a failed review. Leave ordinary items at the project default.
24
+ 5. When `wm instructions` says the next step is `accept`, summarize the change for the human: what it does, the deltas, the decisions, and the review levels you suggested. Ask them to run `wm accept <name>` themselves.
25
+
26
+ ## Rules
27
+
28
+ - Only the human accepts a change. Never run `wm accept`.
29
+ - Don't tick items, and don't write `Accepted:`, `Blocked:`, `Spec gap:` or review lines. `wm` writes those.
30
+ - Don't edit files under `waymark/specs/`. Write deltas in the change instead.
31
+ - If the record doesn't say enough to draft something, ask the human. Don't guess.
32
+ - Write no code in this skill.
@@ -0,0 +1,31 @@
1
+ ---
2
+ name: wm-update
3
+ description: Revise an existing Waymark change - its proposal, deltas, design or tasks - confirming each edit with the human. Use to fix a spec gap, resolve a conflict, or change a change's scope.
4
+ ---
5
+
6
+ # Update
7
+
8
+ You are the planner. You revise a change that already exists. Every edit is confirmed by the human before you make it.
9
+
10
+ ## Steps
11
+
12
+ 1. Find the change. If the human didn't name it, run `wm ls changes` and ask which one.
13
+ 2. Run `wm show <name> --json` and `wm instructions --change <name> --json` to see where it stands and what is wrong, if anything.
14
+ 3. Before editing, tell the human whether the edit withdraws acceptance:
15
+ - Editing the proposal, a delta, the design, or an item's definition (its number, title, criteria, verification, repo or review level) **withdraws acceptance**. The human must accept the change again before any more items are applied.
16
+ - Adding a note under an item does not.
17
+ 4. For each edit: say what you will change and why, wait for the human to confirm, then make it. For the format of a file, run `wm instructions <step> --change <name>`; it carries the template.
18
+ 5. Run `wm check` after your edits and fix every error in the files you touched.
19
+ 6. If acceptance was withdrawn, summarize what changed and ask the human to run `wm accept <name>`.
20
+
21
+ ## Common cases
22
+
23
+ - **A spec gap.** An implementer or reviewer found the record wasn't enough. Bring the gap to the human, write their answer into the delta or the item's criteria, and once the change is accepted again run `wm resolve <name> <item> "<what was decided>"`.
24
+ - **A conflict.** A delta no longer applies to its spec, usually because another change was archived first. Rewrite the delta against the spec as it now reads (`wm show <spec>`).
25
+ - **New work discovered.** Append new items at the end of a section. Never renumber or reuse an item number.
26
+
27
+ ## Rules
28
+
29
+ - Never run `wm accept`. Only the human accepts.
30
+ - Don't tick items or write `Blocked:`, `Spec gap:` or review lines by hand; use the `wm` commands.
31
+ - Don't edit files under `waymark/specs/`.
waymark/cli.py ADDED
@@ -0,0 +1,537 @@
1
+ """The ``wm`` command: parses arguments, calls services, prints what they return.
2
+
3
+ This layer stays thin. Every decision is made by a service; a refused command
4
+ prints why and what to do next, and exits with ``EXIT_REFUSED``.
5
+ """
6
+
7
+ import argparse
8
+ import datetime
9
+ import json
10
+ import os
11
+ import sys
12
+ from collections.abc import Callable, Sequence
13
+ from pathlib import Path
14
+
15
+ from waymark import __version__, adapters
16
+ from waymark.record.terms import Step, Verdict
17
+ from waymark.services import atlas as atlas_service
18
+ from waymark.services import ci as ci_service
19
+ from waymark.services import context as context_service
20
+ from waymark.services import doctor as doctor_service
21
+ from waymark.services import githooks as githooks_service
22
+ from waymark.services import instructions as instructions_service
23
+ from waymark.services import integration, lifecycle, references, setup
24
+ from waymark.services import pr as pr_service
25
+ from waymark.services.common import Done, Refusal, open_record, take_notices
26
+ from waymark.views import payloads, render
27
+ from waymark.views.payloads import Payload
28
+ from waymark.views.style import Style
29
+
30
+ EXIT_OK = 0
31
+ """The command succeeded."""
32
+
33
+ EXIT_REFUSED = 1
34
+ """The command was refused, or it found problems."""
35
+
36
+ EXIT_USAGE = 2
37
+ """The command line was wrong."""
38
+
39
+ PROG = "wm"
40
+
41
+ Handler = Callable[[argparse.Namespace], int]
42
+
43
+
44
+ def _report(done: Done) -> int:
45
+ if done.message:
46
+ print(done.message)
47
+ return EXIT_OK
48
+
49
+
50
+ def _here() -> Path:
51
+ return Path.cwd()
52
+
53
+
54
+ def _today() -> datetime.date:
55
+ return datetime.date.today()
56
+
57
+
58
+ def _init(args: argparse.Namespace) -> int:
59
+ tools = tuple(args.tool) if args.tool else None
60
+ return _report(setup.init_project(_here(), args.atlas, tools))
61
+
62
+
63
+ def _update(_: argparse.Namespace) -> int:
64
+ return _report(integration.update(_here()))
65
+
66
+
67
+ def _atlas_register(args: argparse.Namespace) -> int:
68
+ if (args.repo is None) != (args.folder is None):
69
+ raise Refusal("Give both the code repo's name and its folder, or neither.")
70
+ return _report(atlas_service.register(_here(), args.repo, args.folder))
71
+
72
+
73
+ def _atlas_point(args: argparse.Namespace) -> int:
74
+ return _report(atlas_service.point(_here(), args.atlas, args.path))
75
+
76
+
77
+ def _git_hooks(_: argparse.Namespace) -> int:
78
+ return _report(githooks_service.git_hooks(_here()))
79
+
80
+
81
+ def _run_hook(args: argparse.Namespace) -> int:
82
+ if args.name == "commit-msg":
83
+ if not args.file:
84
+ raise Refusal("The commit-msg hook needs the commit message file git passes it.")
85
+ return _report(githooks_service.check_commit_message(_here(), args.file))
86
+ now = datetime.datetime.now(datetime.UTC)
87
+ return _report(githooks_service.check_staged_record(_here(), now))
88
+
89
+
90
+ def _ci(_: argparse.Namespace) -> int:
91
+ return _report(ci_service.add_workflow(_here()))
92
+
93
+
94
+ def _pr(args: argparse.Namespace) -> int:
95
+ _show_payload(pr_service.describe(open_record(_here()), args.change, args.repo), args)
96
+ return EXIT_OK
97
+
98
+
99
+ def _doctor_report(report: doctor_service.Report, args: argparse.Namespace) -> int:
100
+ _show_payload(payloads.doctor(report), args)
101
+ return EXIT_REFUSED if report.failed else EXIT_OK
102
+
103
+
104
+ def _doctor(args: argparse.Namespace) -> int:
105
+ return _doctor_report(doctor_service.doctor(_here()), args)
106
+
107
+
108
+ def _atlas_doctor(args: argparse.Namespace) -> int:
109
+ return _doctor_report(doctor_service.atlas_doctor(_here()), args)
110
+
111
+
112
+ def _hook(args: argparse.Namespace) -> int:
113
+ """Answer an agent tool's hook. A fault here never blocks the agent: it exits 1."""
114
+ try:
115
+ adapter = adapters.get(args.tool)
116
+ except adapters.UnknownToolError:
117
+ known = ", ".join(adapters.names())
118
+ raise Refusal(
119
+ f'"{args.tool}" is not an agent tool wm knows. Known tools: {known}.'
120
+ ) from None
121
+ raw = getattr(sys.stdin, "buffer", None)
122
+ text = raw.read().decode("utf-8", errors="replace") if raw is not None else sys.stdin.read()
123
+ try:
124
+ payload = json.loads(text) if text.strip() else {}
125
+ except json.JSONDecodeError as error:
126
+ raise Refusal(f"The hook's input is not JSON ({error}).") from error
127
+ if not isinstance(payload, dict):
128
+ raise Refusal("The hook's input is not a JSON object.")
129
+ reply = adapter.hook(args.event, payload, _here(), _today())
130
+ if reply.stdout:
131
+ print(reply.stdout)
132
+ if reply.stderr:
133
+ print(reply.stderr, file=sys.stderr)
134
+ return reply.code
135
+
136
+
137
+ def _new(args: argparse.Namespace) -> int:
138
+ if args.kind == "change":
139
+ return _report(setup.create_change(_here(), args.name, short=args.short, owner=args.owner))
140
+ if args.short or args.owner:
141
+ raise Refusal("--short and --owner apply to a change only.")
142
+ if args.kind == "milestone":
143
+ return _report(setup.create_milestone(_here(), args.name))
144
+ return _report(setup.create_exploration(_here(), args.name))
145
+
146
+
147
+ def _accept(args: argparse.Namespace) -> int:
148
+ return _report(lifecycle.accept(_here(), args.change, _today()))
149
+
150
+
151
+ def _tick(args: argparse.Namespace) -> int:
152
+ return _report(lifecycle.tick(_here(), args.change, args.item))
153
+
154
+
155
+ def _block(args: argparse.Namespace) -> int:
156
+ return _report(lifecycle.block(_here(), args.change, args.item, args.reason))
157
+
158
+
159
+ def _gap(args: argparse.Namespace) -> int:
160
+ return _report(lifecycle.report_gap(_here(), args.change, args.item, args.note))
161
+
162
+
163
+ def _review(args: argparse.Namespace) -> int:
164
+ done = lifecycle.self_review(_here(), args.change, args.item, args.self_summary, _today())
165
+ return _report(done)
166
+
167
+
168
+ def _verdict(args: argparse.Namespace) -> int:
169
+ result = Verdict(args.verdict)
170
+ done = lifecycle.verdict(_here(), args.change, args.item, result, args.reasons, _today())
171
+ return _report(done)
172
+
173
+
174
+ def _reopen(args: argparse.Namespace) -> int:
175
+ return _report(lifecycle.reopen(_here(), args.change, args.item, _today()))
176
+
177
+
178
+ def _resolve(args: argparse.Namespace) -> int:
179
+ return _report(lifecycle.resolve(_here(), args.change, args.item, args.decision, _today()))
180
+
181
+
182
+ def _sync(args: argparse.Namespace) -> int:
183
+ return _report(lifecycle.sync(_here(), args.change, _today()))
184
+
185
+
186
+ def _archive(args: argparse.Namespace) -> int:
187
+ done = lifecycle.archive(
188
+ _here(), args.change, _today(), outcome=args.outcome, override=args.override
189
+ )
190
+ return _report(done)
191
+
192
+
193
+ def _close(args: argparse.Namespace) -> int:
194
+ return _report(lifecycle.close_milestone(_here(), args.milestone, _today()))
195
+
196
+
197
+ def _show_payload(payload: Payload, args: argparse.Namespace) -> None:
198
+ """Print a view: as JSON when asked, otherwise as text styled for this terminal."""
199
+ if args.json:
200
+ print(render.to_json(payload))
201
+ else:
202
+ print(render.to_text(payload, Style.detect(sys.stdout, os.environ)))
203
+
204
+
205
+ def _status(args: argparse.Namespace) -> int:
206
+ _show_payload(payloads.status(open_record(_here())), args)
207
+ return EXIT_OK
208
+
209
+
210
+ def _inbox(args: argparse.Namespace) -> int:
211
+ _show_payload(payloads.inbox(open_record(_here())), args)
212
+ return EXIT_OK
213
+
214
+
215
+ def _show(args: argparse.Namespace) -> int:
216
+ record = open_record(_here())
217
+ if args.source is None:
218
+ _show_payload(payloads.show(record, args.name, args.kind), args)
219
+ return EXIT_OK
220
+ if args.kind not in (None, "spec"):
221
+ raise Refusal("--from reads another atlas's specs only.")
222
+ other = references.reference_record(record, args.source)
223
+ spec = other.specs.get(args.name)
224
+ if spec is None:
225
+ listed = ", ".join(sorted(other.specs)) or "none"
226
+ raise Refusal(f'The atlas "{args.source}" has no spec "{args.name}" (specs: {listed}).')
227
+ _show_payload(payloads.show_spec(other, spec, args.source), args)
228
+ return EXIT_OK
229
+
230
+
231
+ def _ls(args: argparse.Namespace) -> int:
232
+ kind = args.kind.removesuffix("s")
233
+ record = open_record(_here())
234
+ if args.source is not None:
235
+ if kind != "spec":
236
+ raise Refusal("--from lists another atlas's specs only: wm ls specs --from <atlas>")
237
+ record = references.reference_record(record, args.source)
238
+ payload = payloads.ls(record, kind, archived=args.archived, source=args.source)
239
+ _show_payload(payload, args)
240
+ return EXIT_OK
241
+
242
+
243
+ def _instructions(args: argparse.Namespace) -> int:
244
+ payload = instructions_service.instructions(open_record(_here()), args.step, args.change)
245
+ _show_payload(payload, args)
246
+ return EXIT_OK
247
+
248
+
249
+ def _context(args: argparse.Namespace) -> int:
250
+ payload = context_service.context_pack(open_record(_here()), args.role, args.change, args.item)
251
+ _show_payload(payload, args)
252
+ return EXIT_OK
253
+
254
+
255
+ def _check(args: argparse.Namespace) -> int:
256
+ now = datetime.datetime.now(datetime.UTC)
257
+ payload = payloads.check(open_record(_here()), now)
258
+ _show_payload(payload, args)
259
+ return EXIT_REFUSED if payload["errors"] else EXIT_OK
260
+
261
+
262
+ def _usage(parser: argparse.ArgumentParser) -> int:
263
+ parser.print_help()
264
+ return EXIT_OK
265
+
266
+
267
+ def _view_command(
268
+ commands: "argparse._SubParsersAction[argparse.ArgumentParser]",
269
+ name: str,
270
+ handler: Handler,
271
+ summary: str,
272
+ ) -> argparse.ArgumentParser:
273
+ parser = commands.add_parser(name, help=summary, description=summary)
274
+ parser.add_argument(
275
+ "--json", action="store_true", help="print the view as JSON, with its schema version"
276
+ )
277
+ parser.set_defaults(handler=handler)
278
+ return parser
279
+
280
+
281
+ def _item_command(
282
+ commands: "argparse._SubParsersAction[argparse.ArgumentParser]",
283
+ name: str,
284
+ handler: Handler,
285
+ summary: str,
286
+ ) -> argparse.ArgumentParser:
287
+ parser = commands.add_parser(name, help=summary, description=summary)
288
+ parser.add_argument("change", help="the change's name")
289
+ parser.add_argument("item", help="the item's number, for example 1.2")
290
+ parser.set_defaults(handler=handler)
291
+ return parser
292
+
293
+
294
+ def build_parser() -> argparse.ArgumentParser: # noqa: PLR0915 - one flat list of commands
295
+ """Build the argument parser for ``wm``."""
296
+ parser = argparse.ArgumentParser(
297
+ prog=PROG,
298
+ description=(
299
+ "Waymark keeps a written record of a project in plain markdown and "
300
+ "tells an agent what to do next."
301
+ ),
302
+ allow_abbrev=False,
303
+ )
304
+ parser.add_argument("--version", action="version", version=f"{PROG} {__version__}")
305
+ commands = parser.add_subparsers(title="commands", metavar="<command>")
306
+
307
+ summary = "Create the record in this git repository."
308
+ init = commands.add_parser("init", help=summary, description=summary)
309
+ init.add_argument(
310
+ "--atlas",
311
+ metavar="NAME",
312
+ help="make this repository an atlas: a record that several code repos share",
313
+ )
314
+ init.add_argument(
315
+ "--tool",
316
+ action="append",
317
+ metavar="NAME",
318
+ help=f"an agent tool to set up; repeatable (default: {', '.join(adapters.names())})",
319
+ )
320
+ init.set_defaults(handler=_init)
321
+
322
+ summary = "Migrate the record to this version and regenerate the files Waymark owns."
323
+ update = commands.add_parser("update", help=summary, description=summary)
324
+ update.set_defaults(handler=_update)
325
+
326
+ _view_command(
327
+ commands, "doctor", _doctor, "Check wm, git and this project's setup; changes nothing."
328
+ )
329
+
330
+ summary = "Put the committed git hooks in this repository and point this clone's git at them."
331
+ commands.add_parser("git-hooks", help=summary, description=summary).set_defaults(
332
+ handler=_git_hooks
333
+ )
334
+ summary = "Run one of the git hooks' checks; the hooks call this."
335
+ run_hook = commands.add_parser("run-hook", help=summary, description=summary)
336
+ run_hook.add_argument("name", choices=list(githooks_service.HOOK_NAMES))
337
+ run_hook.add_argument("file", nargs="?", help="the commit message file (commit-msg only)")
338
+ run_hook.set_defaults(handler=_run_hook)
339
+ summary = "Add a GitHub Actions workflow that installs the pinned wm and runs wm check."
340
+ commands.add_parser("ci", help=summary, description=summary).set_defaults(handler=_ci)
341
+ pr = _view_command(
342
+ commands, "pr", _pr, "Describe a pull request from a change: its title and description."
343
+ )
344
+ pr.add_argument("change", help="the change's name")
345
+ pr.add_argument("--repo", metavar="NAME", help="in an atlas, the code repo it is for")
346
+
347
+ summary = "Register atlases on this machine, point code repos at them, check their setup."
348
+ atlas = commands.add_parser("atlas", help=summary, description=summary)
349
+ atlas_commands = atlas.add_subparsers(title="atlas commands", metavar="<command>")
350
+ atlas.set_defaults(handler=lambda _: _usage(atlas))
351
+ summary = (
352
+ "Register this atlas on this machine, with its code repos found through their path "
353
+ "hints, or one code repo at a folder."
354
+ )
355
+ register = atlas_commands.add_parser("register", help=summary, description=summary)
356
+ register.add_argument("repo", nargs="?", help="a code repo's name, from the atlas's settings")
357
+ register.add_argument("folder", nargs="?", help="that code repo's folder")
358
+ register.set_defaults(handler=_atlas_register)
359
+ summary = "Write the pointer file that tells this code repo which atlas holds its record."
360
+ point = atlas_commands.add_parser("point", help=summary, description=summary)
361
+ point.add_argument("atlas", help="the atlas's name")
362
+ point.add_argument(
363
+ "--path", metavar="FOLDER", help="the atlas's folder, relative to this repository's top"
364
+ )
365
+ point.set_defaults(handler=_atlas_point)
366
+ _view_command(
367
+ atlas_commands,
368
+ "doctor",
369
+ _atlas_doctor,
370
+ "Check this atlas's registry entries, code repos, branches and pins; changes nothing.",
371
+ )
372
+
373
+ summary = "Answer an agent tool's hook event, read as JSON from standard input."
374
+ hook = commands.add_parser("hook", help=summary, description=summary)
375
+ hook.add_argument("tool", help="the agent tool whose hook this is")
376
+ hook.add_argument("event", help="the tool's name for the event")
377
+ hook.set_defaults(handler=_hook)
378
+
379
+ summary = "Create a change, milestone or exploration from the built-in template."
380
+ new = commands.add_parser("new", help=summary, description=summary)
381
+ new.add_argument("kind", choices=["change", "milestone", "exploration"])
382
+ new.add_argument("name", help="a kebab-case name, for example add-search-limit")
383
+ new.add_argument("--short", action="store_true", help="put a change on the short path")
384
+ new.add_argument("--owner", metavar="NAME", help="a change's owner (default: your git name)")
385
+ new.set_defaults(handler=_new)
386
+
387
+ summary = "Accept a change, so its items can be applied. For the human to run."
388
+ accept = commands.add_parser("accept", help=summary, description=summary)
389
+ accept.add_argument("change", help="the change's name")
390
+ accept.set_defaults(handler=_accept)
391
+
392
+ _item_command(commands, "tick", _tick, "Tick an item: it has been applied.")
393
+ block = _item_command(commands, "block", _block, "Record that an item is blocked.")
394
+ block.add_argument("reason", help="why it is blocked")
395
+ gap = _item_command(
396
+ commands, "gap", _gap, "Record a spec gap: the record wasn't enough to build an item."
397
+ )
398
+ gap.add_argument("note", help="what is missing from the record")
399
+ review = _item_command(commands, "review", _review, "Record a self-review of an item.")
400
+ review.add_argument(
401
+ "--self",
402
+ dest="self_summary",
403
+ metavar="SUMMARY",
404
+ required=True,
405
+ help="what the review checked and found",
406
+ )
407
+ verdict = _item_command(
408
+ commands, "verdict", _verdict, "Record a reviewer's verdict on an item."
409
+ )
410
+ verdict.add_argument("verdict", choices=[v.value for v in Verdict])
411
+ verdict.add_argument("reasons", help="the reviewer's reasons")
412
+ _item_command(commands, "reopen", _reopen, "Reopen an item after a review asked for changes.")
413
+ resolve = _item_command(
414
+ commands,
415
+ "resolve",
416
+ _resolve,
417
+ "Record what was decided about an item that went to the human, and free it.",
418
+ )
419
+ resolve.add_argument("decision", help="what was decided")
420
+
421
+ summary = "Merge an applied change's deltas into the specs without archiving it."
422
+ sync = commands.add_parser("sync", help=summary, description=summary)
423
+ sync.add_argument("change", help="the change's name")
424
+ sync.set_defaults(handler=_sync)
425
+
426
+ summary = "Archive an applied change. For the human to run."
427
+ archive = commands.add_parser("archive", help=summary, description=summary)
428
+ archive.add_argument("change", help="the change's name")
429
+ archive.add_argument("--outcome", metavar="TEXT", help="what came of the change")
430
+ archive.add_argument(
431
+ "--override",
432
+ metavar="REASON",
433
+ help="archive although review records are missing; the reason is recorded",
434
+ )
435
+ archive.set_defaults(handler=_archive)
436
+
437
+ summary = "Close a milestone whose changes are all archived."
438
+ close = commands.add_parser("close", help=summary, description=summary)
439
+ close.add_argument("milestone", help="the milestone's name")
440
+ close.set_defaults(handler=_close)
441
+
442
+ _view_command(
443
+ commands, "status", _status, "Show where things stand: changes, milestones, what needs you."
444
+ )
445
+ _view_command(commands, "inbox", _inbox, "Show what only the human can resolve.")
446
+ show = _view_command(
447
+ commands, "show", _show, "Show everything about one change, spec, milestone or exploration."
448
+ )
449
+ show.add_argument("name", help="its name; an archived change also by its dated folder name")
450
+ show.add_argument(
451
+ "--kind", choices=list(payloads.KINDS), help="which kind, if the name is shared"
452
+ )
453
+ show.add_argument(
454
+ "--from",
455
+ dest="source",
456
+ metavar="ATLAS",
457
+ help="read a spec from an atlas this project references",
458
+ )
459
+ ls = _view_command(commands, "ls", _ls, "List changes, specs, milestones or explorations.")
460
+ ls.add_argument("kind", choices=[f"{kind}s" for kind in payloads.KINDS])
461
+ ls.add_argument(
462
+ "--archived", action="store_true", help="include archived changes or milestones"
463
+ )
464
+ ls.add_argument(
465
+ "--from",
466
+ dest="source",
467
+ metavar="ATLAS",
468
+ help="list the specs of an atlas this project references",
469
+ )
470
+ instructions = _view_command(
471
+ commands,
472
+ "instructions",
473
+ _instructions,
474
+ "Say what to do at a step of a change: the file, its template, the rules, the commands.",
475
+ )
476
+ instructions.add_argument(
477
+ "step",
478
+ nargs="?",
479
+ choices=[step.value for step in Step],
480
+ help="the step (default: the change's next step)",
481
+ )
482
+ instructions.add_argument("--change", metavar="NAME", help="the change (default: the only one)")
483
+ context = _view_command(
484
+ commands,
485
+ "context",
486
+ _context,
487
+ "Print the context pack for exploring, or for implementing or reviewing one item.",
488
+ )
489
+ context.add_argument("change", nargs="?", help="the change's name")
490
+ context.add_argument("item", nargs="?", help="the item's number, for example 1.2")
491
+ context.add_argument(
492
+ "--for",
493
+ dest="role",
494
+ required=True,
495
+ choices=list(context_service.ROLES),
496
+ help="the job the pack is for",
497
+ )
498
+ _view_command(
499
+ commands, "check", _check, "Check the record's health: format, links, conflicts, evidence."
500
+ )
501
+ return parser
502
+
503
+
504
+ def main(argv: Sequence[str] | None = None) -> int:
505
+ """Run ``wm`` and return its exit code.
506
+
507
+ A usage error exits through ``argparse`` with ``EXIT_USAGE``.
508
+ """
509
+ for stream in (sys.stdout, sys.stderr):
510
+ # A console that can't show a character gets a stand-in instead of an error.
511
+ reconfigure = getattr(stream, "reconfigure", None)
512
+ if reconfigure is not None:
513
+ reconfigure(errors="replace")
514
+ parser = build_parser()
515
+ args = parser.parse_args(argv)
516
+ handler: Handler | None = getattr(args, "handler", None)
517
+ if handler is None:
518
+ parser.print_help()
519
+ return EXIT_OK
520
+ take_notices()
521
+ try:
522
+ return handler(args)
523
+ except Refusal as refusal:
524
+ print(f"{PROG}: {refusal}", file=sys.stderr)
525
+ return EXIT_REFUSED
526
+ except Exception as error:
527
+ if handler is not _hook:
528
+ raise
529
+ # A hook that breaks must not stop the agent's work: report it and step aside.
530
+ print(f"{PROG}: the hook failed ({type(error).__name__}: {error})", file=sys.stderr)
531
+ return EXIT_REFUSED
532
+ finally:
533
+ # A hook's reply is the tool's protocol; notices go only to a person at a terminal.
534
+ notices = take_notices()
535
+ if handler is not _hook:
536
+ for note in notices:
537
+ print(f"{PROG}: note: {note}", file=sys.stderr)
@@ -0,0 +1,6 @@
1
+ """Hook decisions: what an agent may do, decided once, for every agent tool.
2
+
3
+ An adapter translates its tool's hook events into the neutral events here and
4
+ translates the decisions back. Every rule lives on this side, so behavior
5
+ can't drift between tools.
6
+ """