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,190 @@
1
+ """Reading a shell command well enough to apply the guard rails.
2
+
3
+ This is not a shell parser and not a security boundary. It finds the programs
4
+ a command line runs and their first argument, which is enough to stop the
5
+ mistakes and shortcuts the workflow rules out.
6
+ """
7
+
8
+ import re
9
+ import shlex
10
+ from dataclasses import dataclass
11
+
12
+ READ_COMMANDS = frozenset(
13
+ {"status", "inbox", "show", "ls", "check", "instructions", "context", "hook", "doctor", "pr"}
14
+ )
15
+ """The wm commands that never write."""
16
+
17
+ READ_GROUP_COMMANDS = {"atlas": frozenset({"doctor"})}
18
+ """Commands in a group that never write, such as "wm atlas doctor"."""
19
+
20
+
21
+ def _reads(call: "Invocation") -> bool:
22
+ if call.subcommand in READ_COMMANDS:
23
+ return True
24
+ reading = READ_GROUP_COMMANDS.get(call.subcommand or "")
25
+ if reading is None:
26
+ return False
27
+ rest = [arg for arg in call.arguments if not arg.startswith("-")]
28
+ return rest[1:2] != [] and rest[1] in reading
29
+
30
+
31
+ _SEPARATOR = re.compile(r"\|\||&&|[;\n|&]")
32
+ _WRAPPERS = frozenset({"sudo", "env", "command", "time", "nohup", "exec", "call", "start"})
33
+ _RUNNERS = frozenset({"uv", "uvx", "pipx", "poetry", "hatch"})
34
+ _PYTHON = re.compile(r"^(python[\d.]*|py)$")
35
+ _ASSIGNMENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=")
36
+ _WINDOWS_SEPARATOR = re.compile(r"\\(?=[\w.])")
37
+ """A backslash inside a Windows path, which a POSIX reading would swallow."""
38
+ _REDIRECT = re.compile(
39
+ r"(?<![0-9&>])>>?(?!&)\s*(?!/dev/null\b|\$null\b|nul\b)[^\s>]", re.IGNORECASE
40
+ )
41
+
42
+ _GIT_WRITES = frozenset({"commit", "push"})
43
+ _GIT_STATE = frozenset(
44
+ {
45
+ "add",
46
+ "am",
47
+ "apply",
48
+ "branch",
49
+ "checkout",
50
+ "cherry-pick",
51
+ "clean",
52
+ "commit",
53
+ "merge",
54
+ "mv",
55
+ "pull",
56
+ "push",
57
+ "rebase",
58
+ "reset",
59
+ "restore",
60
+ "revert",
61
+ "rm",
62
+ "stash",
63
+ "switch",
64
+ "tag",
65
+ "worktree",
66
+ }
67
+ )
68
+ _MUTATORS = frozenset(
69
+ {
70
+ "rm",
71
+ "rmdir",
72
+ "mv",
73
+ "cp",
74
+ "mkdir",
75
+ "touch",
76
+ "chmod",
77
+ "chown",
78
+ "ln",
79
+ "dd",
80
+ "truncate",
81
+ "tee",
82
+ "del",
83
+ "erase",
84
+ "move",
85
+ "copy",
86
+ "ren",
87
+ "rename",
88
+ "remove-item",
89
+ "move-item",
90
+ "copy-item",
91
+ "new-item",
92
+ "rename-item",
93
+ "set-content",
94
+ "add-content",
95
+ "clear-content",
96
+ "out-file",
97
+ }
98
+ )
99
+ _PACKAGE_TOOLS = frozenset({"pip", "pip3", "npm", "yarn", "pnpm", "uv", "poetry", "cargo", "go"})
100
+ _PACKAGE_WRITES = frozenset(
101
+ {"install", "uninstall", "add", "remove", "update", "upgrade", "publish", "sync", "lock", "get"}
102
+ )
103
+
104
+
105
+ @dataclass(frozen=True)
106
+ class Invocation:
107
+ """One program a command line runs, its first plain argument, and all its arguments."""
108
+
109
+ program: str
110
+ subcommand: str | None
111
+ arguments: tuple[str, ...]
112
+ text: str
113
+
114
+
115
+ def _name(token: str) -> str:
116
+ """A program's name without its folder or a Windows extension."""
117
+ name = token.replace("\\", "/").rsplit("/", 1)[-1].lower()
118
+ return re.sub(r"\.(exe|cmd|bat|ps1)$", "", name)
119
+
120
+
121
+ def _invocation(text: str) -> Invocation | None:
122
+ try:
123
+ tokens = shlex.split(_WINDOWS_SEPARATOR.sub("/", text), posix=True)
124
+ except ValueError:
125
+ tokens = text.split()
126
+ index = 0
127
+ while index < len(tokens):
128
+ token = tokens[index]
129
+ name = _name(token)
130
+ if _ASSIGNMENT.match(token) or name in _WRAPPERS or token.startswith("-"):
131
+ index += 1
132
+ elif name in _RUNNERS and tokens[index + 1 : index + 2] == ["run"]:
133
+ index += 2
134
+ elif _PYTHON.match(name) and tokens[index + 1 : index + 3] == ["-m", "waymark"]:
135
+ tokens = ["wm", *tokens[index + 3 :]]
136
+ index = 0
137
+ break
138
+ else:
139
+ break
140
+ if index >= len(tokens):
141
+ return None
142
+ arguments = tuple(tokens[index + 1 :])
143
+ plain = list(arguments)
144
+ while _name(tokens[index]) == "git" and plain[:1] in (["-C"], ["-c"]):
145
+ plain = plain[2:]
146
+ subcommand = next((arg for arg in plain if not arg.startswith("-")), None)
147
+ return Invocation(_name(tokens[index]), subcommand, arguments, text.strip())
148
+
149
+
150
+ def invocations(command: str) -> tuple[Invocation, ...]:
151
+ """Every program a command line runs, in order."""
152
+ found = (_invocation(part) for part in _SEPARATOR.split(command) if part.strip())
153
+ return tuple(invocation for invocation in found if invocation is not None)
154
+
155
+
156
+ def wm_calls(command: str) -> tuple[Invocation, ...]:
157
+ """The wm commands in a command line."""
158
+ return tuple(call for call in invocations(command) if call.program == "wm")
159
+
160
+
161
+ def writing_wm_call(command: str) -> Invocation | None:
162
+ """The first wm command in a command line that writes, if any."""
163
+ for call in wm_calls(command):
164
+ if call.subcommand is not None and not _reads(call):
165
+ return call
166
+ return None
167
+
168
+
169
+ def commits_or_pushes(command: str) -> Invocation | None:
170
+ """The first git commit or push in a command line, if any."""
171
+ for call in invocations(command):
172
+ if call.program == "git" and call.subcommand in _GIT_WRITES:
173
+ return call
174
+ return None
175
+
176
+
177
+ def state_change(command: str) -> str | None:
178
+ """What in a command line changes state, in a few words; None when nothing does."""
179
+ if _REDIRECT.search(command):
180
+ return "it writes to a file"
181
+ for call in invocations(command):
182
+ if call.program in _MUTATORS:
183
+ return f'"{call.program}" changes files'
184
+ if call.program == "git" and call.subcommand in _GIT_STATE:
185
+ return f'"git {call.subcommand}" changes the repository'
186
+ if call.program == "sed" and any(arg.startswith("-i") for arg in call.arguments):
187
+ return '"sed -i" edits files in place'
188
+ if call.program in _PACKAGE_TOOLS and call.subcommand in _PACKAGE_WRITES:
189
+ return f'"{call.program} {call.subcommand}" changes what is installed'
190
+ return None
@@ -0,0 +1,314 @@
1
+ """The decisions: is this delegation, edit or command allowed, and what does a stop record?
2
+
3
+ These are guard rails against mistakes, drift and shortcuts. They are not a
4
+ security boundary and don't claim to stop deliberate circumvention.
5
+ """
6
+
7
+ import datetime
8
+ import re
9
+ from pathlib import Path
10
+
11
+ from waymark import assets
12
+ from waymark.hooks import commands
13
+ from waymark.hooks.events import ALLOW, Decision, Event, EventKind, Role
14
+ from waymark.record.atlas import contains
15
+ from waymark.record.changes import TASKS_FILE
16
+ from waymark.record.evidence import evidence_changes, only_adds_notes
17
+ from waymark.record.files import RecordFiles
18
+ from waymark.record.project import RECORD_DIR, Project, ProjectNotFoundError, find_project
19
+ from waymark.record.record import ARCHIVE, CHANGES, SPECS, Record, load_record
20
+ from waymark.record.state import AcceptanceState, StepKind, derive_state
21
+ from waymark.record.terms import Layout, Verdict
22
+ from waymark.services import lifecycle
23
+ from waymark.services.common import Done, Refusal, find_change, find_item, repo_locations
24
+ from waymark.services.context import (
25
+ IMPLEMENT,
26
+ RESULT_LINE,
27
+ REVIEW,
28
+ VERDICT_LINE,
29
+ delegation_problems,
30
+ )
31
+ from waymark.views import payloads, render
32
+ from waymark.views.style import Style
33
+
34
+ _ADDRESS = re.compile(r"(\S+)\s+(\d+\.\d+)")
35
+ _ITEM_LINE = re.compile(r"^\s*ITEM:\s*(\S+)\s+(\d+\.\d+)\s*$", re.MULTILINE)
36
+ _RESULT = re.compile(r"^\s*RESULT:\s*(done|partial|spec-gap|blocked)\b[^\w\n]*(.*)$", re.MULTILINE)
37
+ _VERDICT = re.compile(r"^\s*VERDICT:\s*(pass|changes|spec-gap)\b[^\w\n]*(.*)$", re.MULTILINE)
38
+
39
+ _AGENT_ROLES = {assets.IMPLEMENTER: IMPLEMENT, assets.REVIEWER: REVIEW}
40
+ _EVIDENCE_COMMANDS = (
41
+ "wm tick, wm block, wm gap, wm review, wm verdict, wm reopen or wm resolve; "
42
+ "accepting is for the human, with wm accept"
43
+ )
44
+
45
+
46
+ def _refuse(reason: str) -> Decision:
47
+ return Decision(allow=False, reason=reason)
48
+
49
+
50
+ def _relative(project: Project, path: Path) -> str | None:
51
+ """A path inside the record, relative to its root; None for a path outside it."""
52
+ try:
53
+ relative = path.resolve().relative_to(project.record_root.resolve())
54
+ except ValueError:
55
+ return None
56
+ return relative.as_posix()
57
+
58
+
59
+ def _session_start(project: Project) -> Decision:
60
+ record = load_record(project)
61
+ status = render.to_text(payloads.status(record), Style())
62
+ lead = (
63
+ "This project uses Waymark: the written record in the waymark/ folder is the source "
64
+ "of truth, and wm says what comes next. Where things stand:"
65
+ )
66
+ tail = 'Run "wm inbox" for what needs the human, and "wm instructions" for the next step.'
67
+ return Decision(context=f"{lead}\n\n{status}\n\n{tail}")
68
+
69
+
70
+ def _delegate(project: Project, event: Event) -> Decision:
71
+ role = _AGENT_ROLES.get(event.agent)
72
+ if role is None:
73
+ return ALLOW
74
+ address = _ADDRESS.fullmatch(event.prompt.strip())
75
+ if address is None:
76
+ return _refuse(
77
+ f'Start the {event.agent} agent with exactly "<change> <item>", for example '
78
+ '"add-search-limit 1.2", and nothing else. It builds its own context from the '
79
+ "record; anything it needs that isn't there is a spec gap."
80
+ )
81
+ record = load_record(project)
82
+ try:
83
+ change = find_change(record, address.group(1))
84
+ item = find_item(change, address.group(2))
85
+ except Refusal as refusal:
86
+ return _refuse(str(refusal))
87
+ problems = delegation_problems(record, change, item, role)
88
+ return _refuse(problems[0]) if problems else ALLOW
89
+
90
+
91
+ def _new_text(files: RecordFiles, relative: str, event: Event) -> tuple[str, str | None]:
92
+ """A file's text now, and after the edit; the second is None when it can't be known."""
93
+ before = files.read(relative, []) or "" if files.is_file(relative) else ""
94
+ if event.content is not None:
95
+ return before, event.content
96
+ if not event.replacements:
97
+ return before, None
98
+ after = before
99
+ for replacement in event.replacements:
100
+ if not replacement.old or replacement.old not in after:
101
+ return before, None
102
+ count = -1 if replacement.everywhere else 1
103
+ after = after.replace(replacement.old, replacement.new, count)
104
+ return before, after
105
+
106
+
107
+ def working_repos(record: Record) -> dict[str, list[str]]:
108
+ """The code repos implementers may edit now, each with the items that name it.
109
+
110
+ The hook can't see which item an implementer was started on, so the record
111
+ answers: in each accepted change, the next item to apply is the one being
112
+ built, and its repo is the one an implementer may edit.
113
+ """
114
+ repos: dict[str, list[str]] = {}
115
+ for name, state in sorted(derive_state(record).changes.items()):
116
+ step = state.next_step
117
+ if state.acceptance is not AcceptanceState.VALID or step.kind is not StepKind.APPLY:
118
+ continue
119
+ tasks = record.changes[name].tasks
120
+ item = tasks.item(step.item) if tasks and step.item else None
121
+ if item is not None and item.repo:
122
+ repos.setdefault(item.repo, []).append(f"{name} {item.number}")
123
+ return repos
124
+
125
+
126
+ def _outside_record(project: Project, event: Event) -> Decision:
127
+ """Edit limits across an atlas's code repos; elsewhere every role but the reviewer may edit."""
128
+ record = load_record(project)
129
+ if event.path is None or record.layout is not Layout.ATLAS:
130
+ return ALLOW
131
+ locations = repo_locations(record)
132
+ inside = next(
133
+ (
134
+ name
135
+ for name, location in locations.items()
136
+ if location.folder is not None and contains(location.folder, event.path)
137
+ ),
138
+ None,
139
+ )
140
+ if event.role is Role.PLANNER:
141
+ if inside is None:
142
+ return ALLOW
143
+ return _refuse(
144
+ f'The planner edits only the record, and this file is in the code repo "{inside}". '
145
+ 'Code is built by an implementer: start the wm-implementer agent with "<change> '
146
+ '<item>".'
147
+ )
148
+ allowed = working_repos(record)
149
+ if inside is not None and inside in allowed:
150
+ return ALLOW
151
+ if not allowed:
152
+ return _refuse(
153
+ "No accepted change has an item to apply right now, so there is no repo an "
154
+ "implementer may edit. Check the item with wm show <change>."
155
+ )
156
+ places = []
157
+ for repo, items in sorted(allowed.items()):
158
+ location = locations.get(repo)
159
+ folder = location.folder if location else None
160
+ where = str(folder) if folder else "not found on this machine; register it with wm atlas"
161
+ places.append(f'"{repo}" ({where}) for {", ".join(items)}')
162
+ return _refuse(
163
+ "An implementer edits only inside the code repo its item names: "
164
+ f"{'; '.join(places)}. This file is outside it. If the item needs changes elsewhere, "
165
+ "end with RESULT: spec-gap and say what is missing."
166
+ )
167
+
168
+
169
+ def _edit(project: Project, event: Event) -> Decision: # noqa: PLR0911 - one return per rule
170
+ if event.role is Role.REVIEWER:
171
+ return _refuse(
172
+ "A reviewer edits nothing: not the code and not the record. Report what you "
173
+ "found in your verdict instead."
174
+ )
175
+ relative = _relative(project, event.path) if event.path else None
176
+ if relative is None:
177
+ return _outside_record(project, event)
178
+ parts = relative.split("/")
179
+ if parts[0] == SPECS:
180
+ return _refuse(
181
+ "Specs are never edited by hand: they change only when a change is archived or "
182
+ "synced. Write a delta in the change's specs folder instead."
183
+ )
184
+ before, after = _new_text(RecordFiles(project.record_root), relative, event)
185
+ if event.role is Role.IMPLEMENTER:
186
+ own_tasks = parts[0] == CHANGES and parts[1:2] != [ARCHIVE] and parts[-1] == TASKS_FILE
187
+ if not own_tasks or after is None or not only_adds_notes(before, after):
188
+ return _refuse(
189
+ 'An implementer may add " - Note: <text>" lines under its own item in the '
190
+ f"change's {TASKS_FILE}, and nothing else in the record. If the record needs "
191
+ "to change, end with RESULT: spec-gap and say what is missing."
192
+ )
193
+ if after is None:
194
+ return ALLOW
195
+ changed = evidence_changes(relative, before, after)
196
+ if changed:
197
+ return _refuse(
198
+ f"This edit {changed[0]}. That is evidence, and only wm writes evidence. "
199
+ f"Leave those lines as they are and use a command instead: {_EVIDENCE_COMMANDS}."
200
+ )
201
+ return ALLOW
202
+
203
+
204
+ def _edited(project: Project, event: Event) -> Decision:
205
+ relative = _relative(project, event.path) if event.path else None
206
+ if relative is None:
207
+ return ALLOW
208
+ problems = [problem for problem in load_record(project).problems if problem.path == relative]
209
+ if not problems:
210
+ return ALLOW
211
+ lines = [f"- line {problem.line}: {problem.message}" for problem in problems]
212
+ count = f"{len(problems)} format problem{'s' if len(problems) != 1 else ''}"
213
+ return _refuse(
214
+ f"{RECORD_DIR}/{relative} has {count} that wm can't read past. Fix "
215
+ f"{'them' if len(problems) != 1 else 'it'} in the file:\n" + "\n".join(lines)
216
+ )
217
+
218
+
219
+ def _command(event: Event) -> Decision: # noqa: PLR0911 - one return per rule
220
+ for call in commands.wm_calls(event.command):
221
+ if call.subcommand == "accept":
222
+ return _refuse(
223
+ "Only the human accepts a change. Summarize it for them and ask them to run "
224
+ f'"{call.text}" themselves.'
225
+ )
226
+ if call.subcommand == "archive" and any(a.startswith("--override") for a in call.arguments):
227
+ return _refuse(
228
+ "Only the human may archive past a missing review. Tell them which review is "
229
+ "missing; they can run the command with --override themselves."
230
+ )
231
+ if event.role is Role.PLANNER:
232
+ return ALLOW
233
+ writing = commands.writing_wm_call(event.command)
234
+ if writing is not None:
235
+ return _refuse(
236
+ f'"wm {writing.subcommand}" writes the record, and a delegated agent does not. '
237
+ "wm records your result from your final lines. Reading commands such as "
238
+ '"wm context" and "wm show" are fine.'
239
+ )
240
+ pushing = commands.commits_or_pushes(event.command)
241
+ if pushing is not None:
242
+ return _refuse(
243
+ f'A delegated agent does not run "git {pushing.subcommand}". The planner commits '
244
+ "once the item's review has passed."
245
+ )
246
+ if event.role is Role.REVIEWER:
247
+ change = commands.state_change(event.command)
248
+ if change is not None:
249
+ return _refuse(
250
+ f"A reviewer runs read-only commands, and here {change}. Read the code and "
251
+ "run the tests; report anything that needs changing in your verdict."
252
+ )
253
+ return ALLOW
254
+
255
+
256
+ def _ending(role: Role) -> str:
257
+ line = RESULT_LINE if role is Role.IMPLEMENTER else VERDICT_LINE
258
+ return (
259
+ 'End your reply with two lines and nothing after them: "ITEM: <change> <item>", '
260
+ f'then "{line}" followed by a short note.'
261
+ )
262
+
263
+
264
+ def _record(project: Project, role: Role, message: str, today: datetime.date) -> Done:
265
+ """Write what the agent's final lines report; refused when they can't be recorded."""
266
+ address = _ITEM_LINE.findall(message)
267
+ outcome = (_RESULT if role is Role.IMPLEMENTER else _VERDICT).findall(message)
268
+ if not address or not outcome:
269
+ raise Refusal(_ending(role))
270
+ (name, number), (word, note) = address[-1], outcome[-1]
271
+ root = project.root
272
+ if role is Role.REVIEWER:
273
+ return lifecycle.verdict(root, name, number, Verdict(word), note, today)
274
+ if word == "done":
275
+ return lifecycle.tick(root, name, number)
276
+ if word == "blocked":
277
+ return lifecycle.block(root, name, number, note)
278
+ if word == "spec-gap":
279
+ return lifecycle.report_gap(root, name, number, note)
280
+ return lifecycle.add_note(root, name, number, f"partial: {note}" if note else "partial")
281
+
282
+
283
+ def _agent_stop(project: Project, event: Event, today: datetime.date) -> Decision:
284
+ if event.role is Role.PLANNER:
285
+ return ALLOW
286
+ try:
287
+ done = _record(project, event.role, event.message, today)
288
+ except Refusal as refusal:
289
+ if event.retried:
290
+ return Decision(
291
+ notice=f"Waymark recorded nothing for the {event.role.value}: {refusal} "
292
+ "Record its result yourself with the wm commands."
293
+ )
294
+ return _refuse(f"wm could not record your result. {refusal}")
295
+ return Decision(notice=f"Waymark: {done.message}")
296
+
297
+
298
+ def decide(event: Event, today: datetime.date) -> Decision: # noqa: PLR0911
299
+ """Answer one event. Outside a Waymark project every event is allowed."""
300
+ try:
301
+ project = find_project(event.cwd)
302
+ except ProjectNotFoundError:
303
+ return ALLOW
304
+ if event.kind is EventKind.SESSION_START:
305
+ return _session_start(project)
306
+ if event.kind is EventKind.DELEGATE:
307
+ return _delegate(project, event)
308
+ if event.kind is EventKind.EDIT:
309
+ return _edit(project, event)
310
+ if event.kind is EventKind.EDITED:
311
+ return _edited(project, event)
312
+ if event.kind is EventKind.COMMAND:
313
+ return _command(event)
314
+ return _agent_stop(project, event, today)
@@ -0,0 +1,79 @@
1
+ """The neutral events an agent tool reports, and the decisions it gets back."""
2
+
3
+ from dataclasses import dataclass
4
+ from enum import StrEnum
5
+ from pathlib import Path
6
+
7
+
8
+ class Role(StrEnum):
9
+ """Who is acting: the main session, or one of the two delegated agents."""
10
+
11
+ PLANNER = "planner"
12
+ IMPLEMENTER = "implementer"
13
+ REVIEWER = "reviewer"
14
+
15
+
16
+ class EventKind(StrEnum):
17
+ """The moments wm is asked about."""
18
+
19
+ SESSION_START = "session-start"
20
+ DELEGATE = "delegate"
21
+ EDIT = "edit"
22
+ EDITED = "edited"
23
+ COMMAND = "command"
24
+ AGENT_STOP = "agent-stop"
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class Replacement:
29
+ """One text replacement an edit makes in a file."""
30
+
31
+ old: str
32
+ new: str
33
+ everywhere: bool = False
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class Event:
38
+ """One thing an agent is about to do, or has just done.
39
+
40
+ Only the fields that belong to the event's kind are set:
41
+
42
+ - ``DELEGATE``: ``agent`` (the agent being started) and ``prompt``;
43
+ - ``EDIT``: ``path``, and either the file's whole new ``content`` or the
44
+ ``replacements`` the edit makes;
45
+ - ``EDITED``: ``path``;
46
+ - ``COMMAND``: ``command``;
47
+ - ``AGENT_STOP``: ``message`` (the agent's final words) and ``retried``
48
+ (it was already asked once to fix its ending).
49
+ """
50
+
51
+ kind: EventKind
52
+ cwd: Path
53
+ role: Role = Role.PLANNER
54
+ agent: str = ""
55
+ prompt: str = ""
56
+ path: Path | None = None
57
+ content: str | None = None
58
+ replacements: tuple[Replacement, ...] = ()
59
+ command: str = ""
60
+ message: str = ""
61
+ retried: bool = False
62
+
63
+
64
+ @dataclass(frozen=True)
65
+ class Decision:
66
+ """The answer to an event.
67
+
68
+ ``allow`` false refuses the action, with ``reason`` saying what is wrong
69
+ and what to do. ``context`` is text for the agent to read. ``notice`` is
70
+ text for the human.
71
+ """
72
+
73
+ allow: bool = True
74
+ reason: str = ""
75
+ context: str = ""
76
+ notice: str = ""
77
+
78
+
79
+ ALLOW = Decision()
waymark/py.typed ADDED
File without changes
@@ -0,0 +1,5 @@
1
+ """The record model: the only code that reads or writes the record's files.
2
+
3
+ It finds the project, parses every artifact, derives state from the files and
4
+ git, merges deltas into specs, and validates links.
5
+ """