workplan 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.
- workplan/__init__.py +8 -0
- workplan/__main__.py +5 -0
- workplan/agent.py +377 -0
- workplan/cli.py +144 -0
- workplan/config.py +74 -0
- workplan/git.py +69 -0
- workplan/llm.py +37 -0
- workplan/ops.py +287 -0
- workplan/plans.py +254 -0
- workplan/route.py +111 -0
- workplan/templates/documents/BREAKDOWN.md +3 -0
- workplan/templates/documents/NOTES.md +3 -0
- workplan/templates/documents/SQUASH_COMMIT_MSG +7 -0
- workplan/templates/documents/TASK.md +9 -0
- workplan/templates/documents/WORKPLAN.md +23 -0
- workplan/templates/project/PRINCIPLES.md +10 -0
- workplan/templates/project/README.md +9 -0
- workplan/templates/project/config.toml +28 -0
- workplan/templates/prompts/define-tasks-none.md +31 -0
- workplan/templates/prompts/define-tasks.md +29 -0
- workplan/templates/prompts/produce-patch-none.md +21 -0
- workplan/templates/prompts/produce-patch.md +23 -0
- workplan/templates/prompts/route.md +21 -0
- workplan-0.1.0.dist-info/METADATA +263 -0
- workplan-0.1.0.dist-info/RECORD +29 -0
- workplan-0.1.0.dist-info/WHEEL +5 -0
- workplan-0.1.0.dist-info/entry_points.txt +3 -0
- workplan-0.1.0.dist-info/licenses/LICENSE +21 -0
- workplan-0.1.0.dist-info/top_level.txt +1 -0
workplan/llm.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""A client for any OpenAI-compatible chat completions endpoint.
|
|
2
|
+
The only module that makes HTTP requests."""
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import urllib.error
|
|
6
|
+
import urllib.request
|
|
7
|
+
|
|
8
|
+
from workplan import config
|
|
9
|
+
from workplan.git import Fail
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def chat(cfg: dict, model: str, messages: list[dict], timeout: float) -> str:
|
|
13
|
+
"""Post messages to <api_base>/chat/completions; return the reply text."""
|
|
14
|
+
if not model:
|
|
15
|
+
raise Fail("no model configured")
|
|
16
|
+
base = cfg["llm"]["api_base"].rstrip("/")
|
|
17
|
+
body = {"model": model, "messages": messages, **cfg["llm"].get("params", {})}
|
|
18
|
+
headers = {"Content-Type": "application/json"}
|
|
19
|
+
if key := config.api_key(cfg):
|
|
20
|
+
headers["Authorization"] = f"Bearer {key}"
|
|
21
|
+
|
|
22
|
+
request = urllib.request.Request(
|
|
23
|
+
f"{base}/chat/completions", data=json.dumps(body).encode(), headers=headers,
|
|
24
|
+
)
|
|
25
|
+
try:
|
|
26
|
+
with urllib.request.urlopen(request, timeout=timeout) as response:
|
|
27
|
+
data = json.load(response)
|
|
28
|
+
except urllib.error.HTTPError as e:
|
|
29
|
+
detail = e.read().decode(errors="replace")[:500]
|
|
30
|
+
raise Fail(f"{base}: HTTP {e.code}: {detail}") from e
|
|
31
|
+
except (urllib.error.URLError, TimeoutError, json.JSONDecodeError) as e:
|
|
32
|
+
raise Fail(f"{base}: {e}") from e
|
|
33
|
+
|
|
34
|
+
try:
|
|
35
|
+
return data["choices"][0]["message"]["content"] or ""
|
|
36
|
+
except (KeyError, IndexError, TypeError) as e:
|
|
37
|
+
raise Fail(f"{base}: unexpected response: {str(data)[:300]}") from e
|
workplan/ops.py
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
"""The protocol's operations. Each returns data and prints nothing;
|
|
2
|
+
the CLI formats it as text and a web server could send it as JSON."""
|
|
3
|
+
|
|
4
|
+
import datetime
|
|
5
|
+
import re
|
|
6
|
+
import stat
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from workplan import git, plans
|
|
10
|
+
from workplan.git import Fail
|
|
11
|
+
from workplan.plans import commit_for, master_ref, patch_applied, state
|
|
12
|
+
|
|
13
|
+
GITIGNORE = (
|
|
14
|
+
"workplans/*/*/output.patch",
|
|
15
|
+
"workplans/*/*/COMMIT_MSG",
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
GOAL_PLACEHOLDER = "<What is true when this workplan reaches master, in a few sentences.>"
|
|
19
|
+
|
|
20
|
+
HOOK_MARK = "# installed by workplan"
|
|
21
|
+
HOOK = f"""#!/bin/sh
|
|
22
|
+
{HOOK_MARK}
|
|
23
|
+
command -v workplan >/dev/null 2>&1 || exit 0
|
|
24
|
+
( workplan route --dispatch HEAD >/dev/null 2>&1 & )
|
|
25
|
+
"""
|
|
26
|
+
HOOKS = ("post-commit", "post-merge")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _need(path: Path) -> Path:
|
|
30
|
+
if not path.is_file():
|
|
31
|
+
raise Fail(f"{path}: not found")
|
|
32
|
+
return path
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
# ---------------------------------------------------------------------------
|
|
36
|
+
# init and plan
|
|
37
|
+
# ---------------------------------------------------------------------------
|
|
38
|
+
|
|
39
|
+
def init() -> list[str]:
|
|
40
|
+
"""Create workplans/ with its README, principles and config, add the
|
|
41
|
+
working files to .gitignore, and commit them. Existing files are
|
|
42
|
+
left alone."""
|
|
43
|
+
done, paths = [], []
|
|
44
|
+
for name in ("README.md", "PRINCIPLES.md", "config.toml"):
|
|
45
|
+
path = plans.ROOT / name
|
|
46
|
+
if not path.exists():
|
|
47
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
48
|
+
path.write_text(plans.render("project", name))
|
|
49
|
+
done.append(f"created {path}")
|
|
50
|
+
paths.append(str(path))
|
|
51
|
+
|
|
52
|
+
ignore = Path(".gitignore")
|
|
53
|
+
lines = ignore.read_text().splitlines() if ignore.is_file() else []
|
|
54
|
+
missing = [line for line in GITIGNORE if line not in lines]
|
|
55
|
+
if missing:
|
|
56
|
+
text = ignore.read_text() if ignore.is_file() else ""
|
|
57
|
+
if text and not text.endswith("\n"):
|
|
58
|
+
text += "\n"
|
|
59
|
+
ignore.write_text(text + "\n".join(missing) + "\n")
|
|
60
|
+
done.append("added to .gitignore: " + ", ".join(missing))
|
|
61
|
+
paths.append(str(ignore))
|
|
62
|
+
|
|
63
|
+
if paths:
|
|
64
|
+
git.run("add", "--", *paths)
|
|
65
|
+
git.run("commit", "-q", "-m", "workplan init", "--", *paths)
|
|
66
|
+
done.append("committed: " + git.run("log", "-1", "--format=%h %s"))
|
|
67
|
+
return done
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def plan(name: str, master: str, goal: str | None = None, today: str | None = None) -> dict:
|
|
71
|
+
"""A new workplan: WORKPLAN.md from its template, on a new branch
|
|
72
|
+
from master. With no goal, the editor opens on the rendered template,
|
|
73
|
+
as git commit does; leaving it unchanged creates nothing."""
|
|
74
|
+
if not plans.NAME.fullmatch(name):
|
|
75
|
+
raise Fail(f"{name}: a workplan name is lower-case words joined by '-'")
|
|
76
|
+
wid = f"{today or datetime.date.today().isoformat()}-{name}"
|
|
77
|
+
branch = plans.branch_of(wid)
|
|
78
|
+
if (plans.ROOT / wid).exists():
|
|
79
|
+
raise Fail(f"workplan {wid} exists")
|
|
80
|
+
if git.ref_exists(f"refs/heads/{branch}"):
|
|
81
|
+
raise Fail(f"branch {branch} exists")
|
|
82
|
+
start = master_ref(master)
|
|
83
|
+
|
|
84
|
+
rendered = plans.render("documents", "WORKPLAN.md", id=wid,
|
|
85
|
+
title=name.replace("-", " "),
|
|
86
|
+
goal=" ".join(goal.split()) if goal else GOAL_PLACEHOLDER)
|
|
87
|
+
if goal:
|
|
88
|
+
text = rendered
|
|
89
|
+
else:
|
|
90
|
+
draft = git.git_path("workplan") / "WORKPLAN.md"
|
|
91
|
+
draft.parent.mkdir(parents=True, exist_ok=True)
|
|
92
|
+
draft.write_text(rendered)
|
|
93
|
+
git.edit(draft)
|
|
94
|
+
text = draft.read_text()
|
|
95
|
+
if not text.strip() or text == rendered:
|
|
96
|
+
raise Fail("WORKPLAN.md unchanged; no workplan created")
|
|
97
|
+
|
|
98
|
+
git.run("switch", "-q", "-c", branch, start)
|
|
99
|
+
path = plans.plan_path(wid)
|
|
100
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
101
|
+
path.write_text(text)
|
|
102
|
+
return {"workplan": wid, "branch": branch, "created": str(path)}
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
# ---------------------------------------------------------------------------
|
|
106
|
+
# status
|
|
107
|
+
# ---------------------------------------------------------------------------
|
|
108
|
+
|
|
109
|
+
def task_status(tid: str, master: str) -> dict:
|
|
110
|
+
name, detail = state(tid, master)
|
|
111
|
+
return {
|
|
112
|
+
"id": tid,
|
|
113
|
+
"state": name,
|
|
114
|
+
"detail": detail,
|
|
115
|
+
"title": plans.task_title(tid),
|
|
116
|
+
"depends": plans.depends_on(tid),
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def status(arg: str | None, master: str) -> dict:
|
|
121
|
+
if arg and ("/" in arg or plans.NNNN.fullmatch(arg)):
|
|
122
|
+
tid = plans.task_id(arg)
|
|
123
|
+
return {"workplan": tid.split("/")[0], "tasks": [task_status(tid, master)]}
|
|
124
|
+
wid = plans.workplan_id(arg)
|
|
125
|
+
return {
|
|
126
|
+
"workplan": wid,
|
|
127
|
+
"title": plans.workplan_title(wid),
|
|
128
|
+
"goal": plans.goal(wid),
|
|
129
|
+
"branch": plans.branch_of(wid),
|
|
130
|
+
"tasks": [task_status(tid, master) for tid in plans.workplan_tasks(wid)],
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
# ---------------------------------------------------------------------------
|
|
135
|
+
# the patch loop
|
|
136
|
+
# ---------------------------------------------------------------------------
|
|
137
|
+
|
|
138
|
+
def _patch(task: str) -> tuple[str, Path]:
|
|
139
|
+
tid = plans.task_id(task)
|
|
140
|
+
return tid, _need(plans.ROOT / tid / "output.patch")
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def apply(task: str) -> str:
|
|
144
|
+
"""Stage the patch in the tree and the index; return its stat."""
|
|
145
|
+
_, patch = _patch(task)
|
|
146
|
+
if patch_applied(patch):
|
|
147
|
+
raise Fail(f"{patch}: already applied")
|
|
148
|
+
git.run("apply", "--index", str(patch))
|
|
149
|
+
return git.run("diff", "--cached", "--stat")
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def diff(task: str) -> str:
|
|
153
|
+
"""The staged change when applied, else the patch itself."""
|
|
154
|
+
_, patch = _patch(task)
|
|
155
|
+
if patch_applied(patch):
|
|
156
|
+
return git.run("diff", "--cached", strip=False)
|
|
157
|
+
return patch.read_text()
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def accept(task: str, master: str) -> str:
|
|
161
|
+
"""Apply the patch if needed, and commit it with COMMIT_MSG, together
|
|
162
|
+
with the task's directory and WORKPLAN.md."""
|
|
163
|
+
tid, patch = _patch(task)
|
|
164
|
+
wid = tid.split("/")[0]
|
|
165
|
+
msg = _need(plans.ROOT / tid / "COMMIT_MSG")
|
|
166
|
+
|
|
167
|
+
if git.branch() == master:
|
|
168
|
+
raise Fail(f"HEAD is {master}; accept commits on the workplan branch")
|
|
169
|
+
lines = msg.read_text().strip().splitlines()
|
|
170
|
+
if len(lines) != 1 or not lines[0].startswith(f"{tid} "):
|
|
171
|
+
raise Fail(f"{msg}: one line, starting '{tid} '")
|
|
172
|
+
name, commit = state(tid, master)
|
|
173
|
+
if name in ("merged", "complete"):
|
|
174
|
+
raise Fail(f"{tid} is {name}: {commit}")
|
|
175
|
+
|
|
176
|
+
if not patch_applied(patch):
|
|
177
|
+
git.run("apply", "--index", str(patch))
|
|
178
|
+
git.run("add", "--", str(plans.ROOT / tid), str(plans.plan_path(wid)))
|
|
179
|
+
git.run("commit", "-q", "-F", str(msg))
|
|
180
|
+
return git.run("log", "-1", "--format=%h %s")
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def reject(task: str) -> str:
|
|
184
|
+
"""Take an applied, uncommitted patch back out of the tree and index."""
|
|
185
|
+
_, patch = _patch(task)
|
|
186
|
+
if not patch_applied(patch):
|
|
187
|
+
raise Fail(f"{patch}: not applied")
|
|
188
|
+
if not git.ok("apply", "--index", "-R", "--check", str(patch)):
|
|
189
|
+
raise Fail(f"{patch}: the tree has edits to the patch's files; restore them first")
|
|
190
|
+
git.run("apply", "--index", "-R", str(patch))
|
|
191
|
+
return f"{patch}: rejected"
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
# ---------------------------------------------------------------------------
|
|
195
|
+
# merge
|
|
196
|
+
# ---------------------------------------------------------------------------
|
|
197
|
+
|
|
198
|
+
def squash_message(wid: str, master: str, branch: str) -> str:
|
|
199
|
+
subjects = [
|
|
200
|
+
s for s in git.run("log", "--reverse", "--format=%s", f"{master}..{branch}").splitlines()
|
|
201
|
+
if re.match(rf"{re.escape(wid)}/\d{{4}} ", s)
|
|
202
|
+
]
|
|
203
|
+
if not subjects:
|
|
204
|
+
raise Fail(f"no task commits on {branch} beyond {master}")
|
|
205
|
+
return plans.render(
|
|
206
|
+
"documents", "SQUASH_COMMIT_MSG",
|
|
207
|
+
id=wid,
|
|
208
|
+
title=plans.workplan_title(wid),
|
|
209
|
+
goal=plans.goal(wid),
|
|
210
|
+
tasks="\n".join(subjects),
|
|
211
|
+
path=str(plans.plan_path(wid)),
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def merge(arg: str | None, master: str, edit: bool = True) -> dict:
|
|
216
|
+
"""Squash workplan/<id>/definition into master, with the message
|
|
217
|
+
rendered from the SQUASH_COMMIT_MSG template and opened in the
|
|
218
|
+
editor, as git commit does.
|
|
219
|
+
|
|
220
|
+
Every listed task must be committed or dropped, and the branch must
|
|
221
|
+
contain master. On any failure, master and the tree are restored.
|
|
222
|
+
"""
|
|
223
|
+
wid = plans.workplan_id(arg)
|
|
224
|
+
branch = plans.branch_of(wid)
|
|
225
|
+
|
|
226
|
+
if not git.ref_exists(f"refs/heads/{branch}"):
|
|
227
|
+
raise Fail(f"branch {branch} does not exist")
|
|
228
|
+
if not git.ref_exists(f"refs/heads/{master}"):
|
|
229
|
+
raise Fail(f"no local branch {master}")
|
|
230
|
+
if not git.clean():
|
|
231
|
+
raise Fail("the tree has uncommitted changes")
|
|
232
|
+
if not git.is_ancestor(master, branch):
|
|
233
|
+
raise Fail(f"{branch} does not contain {master}; rebase it onto {master} first")
|
|
234
|
+
|
|
235
|
+
_, dropped = plans.listed(wid)
|
|
236
|
+
open_tasks = [
|
|
237
|
+
tid for tid in plans.workplan_tasks(wid)
|
|
238
|
+
if tid.split("/")[1] not in dropped
|
|
239
|
+
and not (commit_for(tid, branch) or commit_for(tid, master))
|
|
240
|
+
]
|
|
241
|
+
if open_tasks:
|
|
242
|
+
raise Fail(f"not committed on {branch}: " + ", ".join(open_tasks))
|
|
243
|
+
|
|
244
|
+
draft = git.git_path("workplan") / "SQUASH_COMMIT_MSG"
|
|
245
|
+
draft.parent.mkdir(parents=True, exist_ok=True)
|
|
246
|
+
draft.write_text(squash_message(wid, master, branch))
|
|
247
|
+
|
|
248
|
+
previous = git.branch()
|
|
249
|
+
git.run("switch", "-q", master)
|
|
250
|
+
try:
|
|
251
|
+
git.run("merge", "--squash", branch)
|
|
252
|
+
if edit:
|
|
253
|
+
git.interactive("commit", "-q", "-e", "-F", str(draft))
|
|
254
|
+
else:
|
|
255
|
+
git.run("commit", "-q", "-F", str(draft))
|
|
256
|
+
except Fail:
|
|
257
|
+
git.ok("reset", "--merge")
|
|
258
|
+
git.ok("switch", "-q", previous)
|
|
259
|
+
raise
|
|
260
|
+
|
|
261
|
+
return {
|
|
262
|
+
"workplan": wid,
|
|
263
|
+
"commit": git.run("log", "-1", "--format=%h %s"),
|
|
264
|
+
"next": [f"git push origin {master}", f"git push origin --delete {branch}",
|
|
265
|
+
f"git branch -D {branch}"],
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
# ---------------------------------------------------------------------------
|
|
270
|
+
# hooks
|
|
271
|
+
# ---------------------------------------------------------------------------
|
|
272
|
+
|
|
273
|
+
def install() -> list[str]:
|
|
274
|
+
"""Write post-commit and post-merge hooks that run `workplan route`.
|
|
275
|
+
A hook not written by workplan is left in place."""
|
|
276
|
+
hooks = git.git_path("hooks")
|
|
277
|
+
hooks.mkdir(parents=True, exist_ok=True)
|
|
278
|
+
done = []
|
|
279
|
+
for name in HOOKS:
|
|
280
|
+
path = hooks / name
|
|
281
|
+
if path.exists() and HOOK_MARK not in path.read_text():
|
|
282
|
+
done.append(f"skipped {path}: an existing hook; add `workplan route --dispatch HEAD` to it")
|
|
283
|
+
continue
|
|
284
|
+
path.write_text(HOOK)
|
|
285
|
+
path.chmod(path.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
|
|
286
|
+
done.append(f"wrote {path}")
|
|
287
|
+
return done
|
workplan/plans.py
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
"""Workplans on disk: ids and documents, templates, and task states.
|
|
2
|
+
|
|
3
|
+
Paths are relative to the repository root; the CLI runs from there.
|
|
4
|
+
|
|
5
|
+
Templates are looked up in workplans/templates/<kind>/<name> first,
|
|
6
|
+
then in the package, and rendered with string.Template substitution
|
|
7
|
+
only: $name is replaced, $$ is a literal dollar sign.
|
|
8
|
+
|
|
9
|
+
A task's state is derived from git history and the files alone; the
|
|
10
|
+
first state in STATES that holds is the state.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import re
|
|
14
|
+
from importlib import resources
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from string import Template
|
|
17
|
+
|
|
18
|
+
from workplan import git
|
|
19
|
+
from workplan.git import Fail
|
|
20
|
+
|
|
21
|
+
ROOT = Path("workplans")
|
|
22
|
+
|
|
23
|
+
ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*") # a workplan id
|
|
24
|
+
DATED = re.compile(r"\d{4}-\d{2}-\d{2}") # a dated id starts so
|
|
25
|
+
NNNN = re.compile(r"\d{4}") # a task number
|
|
26
|
+
NAME = re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)*") # the name in a new id
|
|
27
|
+
|
|
28
|
+
TASK_LINE = re.compile(r"^(\d{4})\s", re.M) # a task line in WORKPLAN.md
|
|
29
|
+
DEPENDS = re.compile(r"^Depends on (.+)$", re.M) # the dependency line in TASK.md
|
|
30
|
+
TITLE = re.compile(r"^# (.+)$", re.M) # the title line of a document
|
|
31
|
+
BRANCH = re.compile(r"^workplan/([^/]+)/") # a workplan's branches
|
|
32
|
+
HEADING = re.compile(r"^## (.+)$", re.M)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def branch_of(wid: str) -> str:
|
|
36
|
+
return f"workplan/{wid}/definition"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def plan_path(wid: str) -> Path:
|
|
40
|
+
return ROOT / wid / "WORKPLAN.md"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def sections(text: str) -> dict[str, str]:
|
|
44
|
+
"""The text under each '## ' heading, keyed by the lower-cased heading."""
|
|
45
|
+
found: dict[str, str] = {}
|
|
46
|
+
matches = list(HEADING.finditer(text))
|
|
47
|
+
for i, m in enumerate(matches):
|
|
48
|
+
end = matches[i + 1].start() if i + 1 < len(matches) else len(text)
|
|
49
|
+
found[m[1].strip().lower()] = text[m.end():end]
|
|
50
|
+
return found
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def workplans() -> list[str]:
|
|
54
|
+
if not ROOT.is_dir():
|
|
55
|
+
return []
|
|
56
|
+
return sorted(p.name for p in ROOT.iterdir() if p.is_dir() and ID.fullmatch(p.name)
|
|
57
|
+
and p.name != "templates")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def current_workplan() -> str:
|
|
61
|
+
"""The current branch's workplan, else the newest dated workplan,
|
|
62
|
+
else the only workplan."""
|
|
63
|
+
branch = git.branch()
|
|
64
|
+
if m := BRANCH.match(branch + "/"):
|
|
65
|
+
return m[1]
|
|
66
|
+
names = workplans()
|
|
67
|
+
dated = [n for n in names if DATED.match(n)]
|
|
68
|
+
if dated:
|
|
69
|
+
return dated[-1]
|
|
70
|
+
if len(names) == 1:
|
|
71
|
+
return names[0]
|
|
72
|
+
raise Fail(f"no workplan for branch {branch}; name one")
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def workplan_id(arg: str | None) -> str:
|
|
76
|
+
wid = arg or current_workplan()
|
|
77
|
+
if not ID.fullmatch(wid) or not (ROOT / wid).is_dir():
|
|
78
|
+
raise Fail(f"workplan {wid} does not exist under {ROOT}/")
|
|
79
|
+
return wid
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def task_id(arg: str) -> str:
|
|
83
|
+
"""ID/NNNN as given, or NNNN in the current workplan."""
|
|
84
|
+
tid = arg if "/" in arg else f"{current_workplan()}/{arg}"
|
|
85
|
+
parts = tid.split("/")
|
|
86
|
+
if len(parts) != 2 or not ID.fullmatch(parts[0]) or not NNNN.fullmatch(parts[1]):
|
|
87
|
+
raise Fail(f"{arg}: a task id is <workplan>/<nnnn>, or <nnnn>")
|
|
88
|
+
return tid
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def listed(wid: str) -> tuple[list[str], list[str]]:
|
|
92
|
+
"""The task numbers WORKPLAN.md lists under Tasks and under Dropped."""
|
|
93
|
+
path = plan_path(wid)
|
|
94
|
+
if not path.is_file():
|
|
95
|
+
return [], []
|
|
96
|
+
parts = sections(path.read_text())
|
|
97
|
+
return (TASK_LINE.findall(parts.get("tasks", "")),
|
|
98
|
+
TASK_LINE.findall(parts.get("dropped", "")))
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def task_dirs(wid: str) -> list[str]:
|
|
102
|
+
base = ROOT / wid
|
|
103
|
+
if not base.is_dir():
|
|
104
|
+
return []
|
|
105
|
+
return sorted(p.name for p in base.iterdir() if p.is_dir() and NNNN.fullmatch(p.name))
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def workplan_tasks(wid: str) -> list[str]:
|
|
109
|
+
"""Every task WORKPLAN.md lists or workplans/<wid>/ holds."""
|
|
110
|
+
tasks, dropped = listed(wid)
|
|
111
|
+
return [f"{wid}/{n}" for n in sorted(set(tasks) | set(dropped) | set(task_dirs(wid)))]
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def next_number(wid: str) -> str:
|
|
115
|
+
tasks, dropped = listed(wid)
|
|
116
|
+
numbers = [int(n) for n in [*tasks, *dropped, *task_dirs(wid)]]
|
|
117
|
+
return f"{max(numbers) + 1 if numbers else 0:04d}"
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def depends_on(tid: str) -> list[str]:
|
|
121
|
+
"""The tasks named on TASK.md's 'Depends on' line, in the same workplan."""
|
|
122
|
+
path = ROOT / tid / "TASK.md"
|
|
123
|
+
if not path.is_file():
|
|
124
|
+
return []
|
|
125
|
+
wid = tid.split("/")[0]
|
|
126
|
+
return [f"{wid}/{n}" for line in DEPENDS.findall(path.read_text())
|
|
127
|
+
for n in NNNN.findall(line)]
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def title(path: Path) -> str:
|
|
131
|
+
if not path.is_file():
|
|
132
|
+
return ""
|
|
133
|
+
m = TITLE.search(path.read_text())
|
|
134
|
+
return m[1].strip() if m else ""
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def task_title(tid: str) -> str:
|
|
138
|
+
return title(ROOT / tid / "TASK.md")
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def goal(wid: str) -> str:
|
|
142
|
+
"""The text of WORKPLAN.md's Goal section."""
|
|
143
|
+
path = plan_path(wid)
|
|
144
|
+
if not path.is_file():
|
|
145
|
+
return ""
|
|
146
|
+
return sections(path.read_text()).get("goal", "").strip()
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def workplan_title(wid: str) -> str:
|
|
150
|
+
"""The title in WORKPLAN.md's first line, '# Workplan <id>: <title>'."""
|
|
151
|
+
text = title(plan_path(wid))
|
|
152
|
+
return text.split(": ", 1)[1].strip() if ": " in text else text
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def add_task_line(wid: str, line: str) -> None:
|
|
156
|
+
"""Add a task line at the end of WORKPLAN.md's Tasks section."""
|
|
157
|
+
path = plan_path(wid)
|
|
158
|
+
text = path.read_text()
|
|
159
|
+
matches = list(HEADING.finditer(text))
|
|
160
|
+
tasks = next((i for i, m in enumerate(matches) if m[1].strip().lower() == "tasks"), None)
|
|
161
|
+
if tasks is None:
|
|
162
|
+
raise Fail(f"{path}: no '## Tasks' section")
|
|
163
|
+
end = matches[tasks + 1].start() if tasks + 1 < len(matches) else len(text)
|
|
164
|
+
body = text[matches[tasks].end():end].strip("\n")
|
|
165
|
+
body = f"{body}\n\n{line}" if body else line
|
|
166
|
+
result = text[:matches[tasks].end()] + "\n\n" + body + "\n\n" + text[end:].lstrip("\n")
|
|
167
|
+
path.write_text(result.rstrip("\n") + "\n")
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
# ---------------------------------------------------------------------------
|
|
171
|
+
# templates
|
|
172
|
+
# ---------------------------------------------------------------------------
|
|
173
|
+
|
|
174
|
+
def template_text(kind: str, name: str) -> str:
|
|
175
|
+
local = ROOT / "templates" / kind / name
|
|
176
|
+
if local.is_file():
|
|
177
|
+
return local.read_text()
|
|
178
|
+
packaged = resources.files("workplan") / "templates" / kind / name
|
|
179
|
+
if not packaged.is_file():
|
|
180
|
+
raise Fail(f"no template {kind}/{name}")
|
|
181
|
+
return packaged.read_text()
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def render(kind: str, name: str, **values: str) -> str:
|
|
185
|
+
try:
|
|
186
|
+
return Template(template_text(kind, name)).substitute(values)
|
|
187
|
+
except (KeyError, ValueError) as e:
|
|
188
|
+
raise Fail(f"template {kind}/{name}: {e}") from e
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
# ---------------------------------------------------------------------------
|
|
192
|
+
# states
|
|
193
|
+
# ---------------------------------------------------------------------------
|
|
194
|
+
|
|
195
|
+
STATES = (
|
|
196
|
+
"merged", "complete", "dropped", "testing", "development",
|
|
197
|
+
"waiting", "stale", "refinement", "unspecified", "unknown",
|
|
198
|
+
)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def master_ref(master: str) -> str:
|
|
202
|
+
"""Master, locally if it exists there, else on origin."""
|
|
203
|
+
for ref in (master, f"origin/{master}"):
|
|
204
|
+
if git.ref_exists(ref):
|
|
205
|
+
return ref
|
|
206
|
+
raise Fail(f"no branch {master}, locally or on origin")
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def commit_for(tid: str, ref: str) -> str:
|
|
210
|
+
"""The latest commit in ref's history with a line starting with the
|
|
211
|
+
task id: the task's commit, or the squash that lists it."""
|
|
212
|
+
pattern = "^(\\+ )?" + tid.replace(".", "\\.") + " "
|
|
213
|
+
return git.run("log", ref, "-E", f"--grep={pattern}", "--format=%h %s", "-n", "1")
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def patch_applied(patch: Path) -> bool:
|
|
217
|
+
"""True when the index or the tree already holds the patch."""
|
|
218
|
+
return (git.ok("apply", "--cached", "-R", "--check", str(patch))
|
|
219
|
+
or git.ok("apply", "-R", "--check", str(patch)))
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def state(tid: str, master: str, seen: frozenset = frozenset()) -> tuple[str, str]:
|
|
223
|
+
"""A task's state and its detail: the commit, or the tasks waited on.
|
|
224
|
+
The first state in STATES that holds is the state."""
|
|
225
|
+
for ref, name in ((master_ref(master), "merged"), ("HEAD", "complete")):
|
|
226
|
+
if commit := commit_for(tid, ref):
|
|
227
|
+
return name, commit
|
|
228
|
+
|
|
229
|
+
wid, nnnn = tid.split("/")
|
|
230
|
+
tasks, dropped = listed(wid)
|
|
231
|
+
if nnnn in dropped:
|
|
232
|
+
return "dropped", ""
|
|
233
|
+
|
|
234
|
+
directory = ROOT / tid
|
|
235
|
+
patch = directory / "output.patch"
|
|
236
|
+
if patch.is_file():
|
|
237
|
+
if patch_applied(patch):
|
|
238
|
+
return "testing", ""
|
|
239
|
+
if git.ok("apply", "--check", str(patch)):
|
|
240
|
+
return "development", ""
|
|
241
|
+
pending = [
|
|
242
|
+
dep for dep in depends_on(tid)
|
|
243
|
+
if dep not in seen
|
|
244
|
+
and state(dep, master, seen | {tid})[0] not in ("merged", "complete")
|
|
245
|
+
]
|
|
246
|
+
if pending:
|
|
247
|
+
return "waiting", "on " + ", ".join(pending)
|
|
248
|
+
return "stale", ""
|
|
249
|
+
|
|
250
|
+
if (directory / "TASK.md").is_file():
|
|
251
|
+
return "refinement", ""
|
|
252
|
+
if nnnn in tasks:
|
|
253
|
+
return "unspecified", ""
|
|
254
|
+
return "unknown", ""
|
workplan/route.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""The next step after a commit.
|
|
2
|
+
|
|
3
|
+
The targets always come from the commit. The action comes from the
|
|
4
|
+
rules, the first of ACTIONS that has targets, or from a model when
|
|
5
|
+
route.classifier is "llm", falling back to the rules when the model's
|
|
6
|
+
answer is not an action with targets.
|
|
7
|
+
|
|
8
|
+
define-tasks and produce-patch are also the names of the commands that
|
|
9
|
+
carry them out.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import re
|
|
13
|
+
import shlex
|
|
14
|
+
import subprocess
|
|
15
|
+
import sys
|
|
16
|
+
|
|
17
|
+
from workplan import git, llm, plans
|
|
18
|
+
from workplan.git import Fail
|
|
19
|
+
|
|
20
|
+
ACTIONS = ("complete", "review", "produce-patch", "define-tasks", "none")
|
|
21
|
+
|
|
22
|
+
PLAN_PATH = re.compile(r"^workplans/([^/]+)/WORKPLAN\.md$")
|
|
23
|
+
TASK_PATH = re.compile(r"^workplans/([^/]+)/(\d{4})/(?:TASK|BREAKDOWN)\.md$")
|
|
24
|
+
TASK_SUBJECT = re.compile(r"^([^/\s]+)/(\d{4}) ")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def facts(rev: str) -> dict:
|
|
28
|
+
"""What a commit is: the current branch, its parents, subject,
|
|
29
|
+
trailer and paths."""
|
|
30
|
+
parents = git.run("rev-list", "--parents", "-n", "1", rev).split()[1:]
|
|
31
|
+
if len(parents) > 1:
|
|
32
|
+
out = git.run("diff", "--name-only", "-z", parents[0], rev, strip=False)
|
|
33
|
+
else:
|
|
34
|
+
out = git.run("diff-tree", "--no-commit-id", "--name-only", "-r", "-z", "--root",
|
|
35
|
+
rev, strip=False)
|
|
36
|
+
return {
|
|
37
|
+
"rev": git.run("rev-parse", "--short", rev),
|
|
38
|
+
"branch": git.branch(),
|
|
39
|
+
"parents": len(parents),
|
|
40
|
+
"subject": git.run("log", "-1", "--format=%s", rev),
|
|
41
|
+
"workplan": git.run("log", "-1", "--format=%(trailers:key=Workplan,valueonly)", rev),
|
|
42
|
+
"paths": [p for p in out.split("\0") if p],
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def candidates(f: dict, master: str) -> dict[str, list[str]]:
|
|
47
|
+
"""Each action the commit could lead to, with its targets."""
|
|
48
|
+
found: dict[str, list[str]] = {}
|
|
49
|
+
|
|
50
|
+
if f["branch"] == master:
|
|
51
|
+
if m := PLAN_PATH.match(f["workplan"]):
|
|
52
|
+
found["complete"] = [m[1]]
|
|
53
|
+
|
|
54
|
+
m = TASK_SUBJECT.match(f["subject"])
|
|
55
|
+
if m and any(not p.startswith(f"{plans.ROOT}/") for p in f["paths"]):
|
|
56
|
+
found["review"] = [f"{m[1]}/{m[2]}"]
|
|
57
|
+
|
|
58
|
+
if tids := sorted({f"{m[1]}/{m[2]}" for p in f["paths"] if (m := TASK_PATH.match(p))}):
|
|
59
|
+
found["produce-patch"] = tids
|
|
60
|
+
|
|
61
|
+
if wids := sorted({m[1] for p in f["paths"] if (m := PLAN_PATH.match(p))}):
|
|
62
|
+
found["define-tasks"] = wids
|
|
63
|
+
|
|
64
|
+
return found
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def decide(rev: str, cfg: dict) -> dict:
|
|
68
|
+
"""The action and its targets, from the rules or the model."""
|
|
69
|
+
f = facts(rev)
|
|
70
|
+
found = candidates(f, cfg["master"])
|
|
71
|
+
rule = next((a for a in ACTIONS if a in found), "none")
|
|
72
|
+
action, source, model = rule, "rules", None
|
|
73
|
+
|
|
74
|
+
if cfg["route"]["classifier"] == "llm":
|
|
75
|
+
prompt = plans.render(
|
|
76
|
+
"prompts", "route.md",
|
|
77
|
+
branch=f["branch"],
|
|
78
|
+
parents=str(f["parents"]),
|
|
79
|
+
subject=f["subject"],
|
|
80
|
+
workplan=f["workplan"] or "(none)",
|
|
81
|
+
paths="\n".join(f["paths"][:50]) or "(none)",
|
|
82
|
+
)
|
|
83
|
+
try:
|
|
84
|
+
answer = llm.chat(cfg, cfg["route"]["model"], [{"role": "user", "content": prompt}],
|
|
85
|
+
float(cfg["route"]["timeout"]))
|
|
86
|
+
model = next((w for w in re.findall(r"[a-z-]+", answer.lower()) if w in ACTIONS),
|
|
87
|
+
None)
|
|
88
|
+
if model is None:
|
|
89
|
+
print(f"route: classifier answered {answer!r}", file=sys.stderr)
|
|
90
|
+
except Fail as e:
|
|
91
|
+
print(f"route: classifier failed: {e}", file=sys.stderr)
|
|
92
|
+
if model == "none" or model in found:
|
|
93
|
+
action, source = model, "llm"
|
|
94
|
+
|
|
95
|
+
return {
|
|
96
|
+
"rev": f["rev"],
|
|
97
|
+
"branch": f["branch"],
|
|
98
|
+
"action": action,
|
|
99
|
+
"targets": found.get(action, []),
|
|
100
|
+
"source": source,
|
|
101
|
+
"rule": rule,
|
|
102
|
+
"model": model,
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def dispatch(decision: dict, cfg: dict) -> None:
|
|
107
|
+
"""Run route.dispatch with the action and its targets, unless the
|
|
108
|
+
action is none."""
|
|
109
|
+
command = cfg["route"]["dispatch"]
|
|
110
|
+
if command and decision["action"] != "none":
|
|
111
|
+
subprocess.run([*shlex.split(command), decision["action"], *decision["targets"]])
|