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 ADDED
@@ -0,0 +1,8 @@
1
+ """workplan: plan and record development work in git."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ try:
6
+ __version__ = version("workplan")
7
+ except PackageNotFoundError:
8
+ __version__ = "0+unknown"
workplan/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from workplan.cli import main
4
+
5
+ sys.exit(main())
workplan/agent.py ADDED
@@ -0,0 +1,377 @@
1
+ """define-tasks and produce-patch: an agent's work in a worktree.
2
+
3
+ workplan owns the worktree for every agent:
4
+
5
+ 1. git worktree add --detach <tmp> <base>, where base is the
6
+ workplan's definition branch, else HEAD
7
+ 2. copy workplans/ from this tree, so uncommitted edits are seen
8
+ 3. run agent.setup in the worktree
9
+ 4. render the prompt and run the adapter in the worktree
10
+ 5. bring the result back:
11
+ produce-patch the diff outside workplans/ becomes output.patch,
12
+ and COMMIT_MSG is copied out
13
+ define-tasks new task directories under workplans/<id>/ are
14
+ copied back, listed in WORKPLAN.md and committed
15
+ 6. remove the worktree
16
+
17
+ An adapter is run(workdir, prompt, cfg, action, target) -> str, where
18
+ action is define-tasks (target: a workplan id) or produce-patch
19
+ (target: a task id). It changes files in workdir and returns the
20
+ agent's final message:
21
+
22
+ produce-patch edit files outside workplans/; write the commit message
23
+ to workplans/<task id>/COMMIT_MSG
24
+ define-tasks write workplans/<id>/<nnnn>/TASK.md and BREAKDOWN.md
25
+ for each new task
26
+
27
+ none completions from an OpenAI-compatible endpoint: the reply
28
+ holds a unified diff and the commit message line, or task
29
+ files each after a line '===== <path> ====='; a reply that
30
+ cannot be used goes back with the error, up to agent.attempts
31
+ times
32
+ command agent.command, else a preset, run in the worktree; a
33
+ "{prompt}" argument is replaced by the prompt, else it goes on
34
+ stdin; WORKPLAN_ACTION, WORKPLAN_TARGET and, for
35
+ produce-patch, WORKPLAN_COMMIT_MSG are set in its environment
36
+ """
37
+
38
+ import os
39
+ import re
40
+ import shutil
41
+ import subprocess
42
+ import tempfile
43
+ from functools import partial
44
+ from pathlib import Path
45
+ from typing import Callable
46
+
47
+ from workplan import git, llm, plans
48
+ from workplan.git import Fail
49
+ from workplan.plans import commit_for
50
+
51
+ EXCLUDE = f":(exclude){plans.ROOT}/"
52
+ TASK_FILES = ("TASK.md", "BREAKDOWN.md", "NOTES.md")
53
+ FILE_LIMIT = 64 * 1024
54
+ CONTEXT_LIMIT = 256 * 1024
55
+ PATHLIKE = re.compile(r"[\w.-]+(?:/[\w.-]+)*\.\w+|[\w.-]+(?:/[\w.-]+)+")
56
+
57
+
58
+ # ---------------------------------------------------------------------------
59
+ # context
60
+ # ---------------------------------------------------------------------------
61
+
62
+ def named_files(texts: list[str], root: Path) -> list[Path]:
63
+ """Files outside workplans/ that the plan's text names and the tree holds."""
64
+ found: list[Path] = []
65
+ for text in texts:
66
+ for token in PATHLIKE.findall(text):
67
+ path = Path(token[2:] if token.startswith("./") else token)
68
+ if not path.parts or path.parts[0] in (plans.ROOT.name, ".git"):
69
+ continue
70
+ full = root / path
71
+ if (path not in found and full.is_file()
72
+ and full.resolve().is_relative_to(root.resolve())
73
+ and full.stat().st_size <= FILE_LIMIT):
74
+ found.append(path)
75
+ return found
76
+
77
+
78
+ def context(files: list[Path], workdir: Path, embed: bool) -> str:
79
+ """The prompt's $context: file contents for an agent without tools,
80
+ a list of paths for one with tools."""
81
+ files = [p for p in files if (workdir / p).is_file()]
82
+ if not embed:
83
+ return "\n".join(f"- {p}" for p in files)
84
+
85
+ texts = [(workdir / p).read_text(errors="replace") for p in files]
86
+ blocks, size = [], 0
87
+ for path in [*files, *named_files(texts, workdir)]:
88
+ text = (workdir / path).read_text(errors="replace")
89
+ if size + len(text) > CONTEXT_LIMIT:
90
+ blocks.append(f"===== {path} (left out: context limit) =====")
91
+ continue
92
+ size += len(text)
93
+ blocks.append(f"===== {path} =====\n{text.rstrip()}\n")
94
+ return "\n".join(blocks)
95
+
96
+
97
+ # ---------------------------------------------------------------------------
98
+ # the worktree
99
+ # ---------------------------------------------------------------------------
100
+
101
+ def adapter_for(cfg: dict):
102
+ name = cfg["agent"]["name"]
103
+ if name not in ADAPTERS:
104
+ raise Fail(f"agent {name}: one of {', '.join(ADAPTERS)}")
105
+ return name, ADAPTERS[name]
106
+
107
+
108
+ def in_worktree(wid: str, cfg: dict, work: Callable[[Path], dict]) -> dict:
109
+ """Run work(workdir) in a fresh worktree of the workplan's branch."""
110
+ branch = plans.branch_of(wid)
111
+ base = branch if git.ref_exists(f"refs/heads/{branch}") else "HEAD"
112
+ workdir = Path(tempfile.mkdtemp(prefix="workplan-"))
113
+ git.run("worktree", "add", "--detach", str(workdir), base)
114
+ try:
115
+ shutil.copytree(plans.ROOT, workdir / plans.ROOT, dirs_exist_ok=True,
116
+ ignore=shutil.ignore_patterns("output.patch", "COMMIT_MSG"))
117
+ if setup := cfg["agent"]["setup"]:
118
+ result = subprocess.run(setup, shell=True, cwd=workdir, capture_output=True,
119
+ text=True)
120
+ if result.returncode != 0:
121
+ raise Fail(f"agent.setup failed: {(result.stderr or result.stdout).strip()[-800:]}")
122
+ result = work(workdir)
123
+ finally:
124
+ git.ok("worktree", "remove", "--force", str(workdir))
125
+ shutil.rmtree(workdir, ignore_errors=True)
126
+ git.ok("worktree", "prune")
127
+ result["base"] = base
128
+ return result
129
+
130
+
131
+ # ---------------------------------------------------------------------------
132
+ # produce-patch
133
+ # ---------------------------------------------------------------------------
134
+
135
+ def produce_patch(task: str, cfg: dict) -> dict:
136
+ tid = plans.task_id(task)
137
+ wid = tid.split("/")[0]
138
+ directory = plans.ROOT / tid
139
+ if not (directory / "TASK.md").is_file():
140
+ raise Fail(f"{directory}/TASK.md: not found")
141
+ if commit := commit_for(tid, "HEAD"):
142
+ raise Fail(f"{tid} is committed: {commit}")
143
+ name, adapter = adapter_for(cfg)
144
+ files = [plans.ROOT / "PRINCIPLES.md", plans.plan_path(wid),
145
+ *(directory / f for f in TASK_FILES)]
146
+
147
+ def work(workdir: Path) -> dict:
148
+ prompt = plans.render(
149
+ "prompts", "produce-patch-none.md" if name == "none" else "produce-patch.md",
150
+ id=tid, workplan=wid, commit_msg=str(directory / "COMMIT_MSG"),
151
+ context=context(files, workdir, embed=name == "none"),
152
+ )
153
+ report = adapter(workdir, prompt, cfg, "produce-patch", tid)
154
+ git.run("add", "-A", "--", ".", EXCLUDE, cwd=workdir)
155
+ patch = git.run("diff", "--cached", "--binary", "--", ".", EXCLUDE, cwd=workdir,
156
+ strip=False)
157
+ if not patch.strip():
158
+ raise Fail(f"the agent made no change outside {plans.ROOT}/\n{report.strip()[-800:]}")
159
+ message, note = commit_message(workdir / directory / "COMMIT_MSG", tid)
160
+ return {"patch": patch, "commit_msg": message, "note": note, "report": report.strip()}
161
+
162
+ result = in_worktree(wid, cfg, work)
163
+ (directory / "output.patch").write_text(result.pop("patch"))
164
+ (directory / "COMMIT_MSG").write_text(result["commit_msg"] + "\n")
165
+ result.update(task=tid, agent=name, patch=str(directory / "output.patch"))
166
+ return result
167
+
168
+
169
+ def commit_message(path: Path, tid: str) -> tuple[str, str]:
170
+ """The agent's COMMIT_MSG, or the task id and title when it wrote
171
+ none or one in another form."""
172
+ if path.is_file():
173
+ lines = path.read_text().strip().splitlines()
174
+ if len(lines) == 1 and lines[0].startswith(f"{tid} "):
175
+ return lines[0], ""
176
+ title = plans.task_title(tid) or "change"
177
+ return f"{tid} {title}", "COMMIT_MSG was missing or malformed; written from TASK.md's title"
178
+
179
+
180
+ # ---------------------------------------------------------------------------
181
+ # define-tasks
182
+ # ---------------------------------------------------------------------------
183
+
184
+ def define_tasks(arg: str | None, cfg: dict) -> dict:
185
+ """The agent writes the workplan's tasks. New task directories are
186
+ copied back and listed in WORKPLAN.md; existing ones are left alone.
187
+ WORKPLAN.md and the new tasks are committed together."""
188
+ wid = plans.workplan_id(arg)
189
+ branch = plans.branch_of(wid)
190
+ plan_file = _need_plan(wid)
191
+ if git.branch() != branch:
192
+ raise Fail(f"define-tasks commits on {branch}; switch to it first")
193
+ name, adapter = adapter_for(cfg)
194
+
195
+ existing = set(plans.task_dirs(wid))
196
+ files = [plans.ROOT / "PRINCIPLES.md", plan_file,
197
+ *(plans.ROOT / wid / n / f for n in sorted(existing) for f in TASK_FILES)]
198
+
199
+ def work(workdir: Path) -> dict:
200
+ prompt = plans.render(
201
+ "prompts", "define-tasks-none.md" if name == "none" else "define-tasks.md",
202
+ id=wid, next=plans.next_number(wid),
203
+ task_template=plans.template_text("documents", "TASK.md"),
204
+ breakdown_template=plans.template_text("documents", "BREAKDOWN.md"),
205
+ context=context(files, workdir, embed=name == "none"),
206
+ )
207
+ report = adapter(workdir, prompt, cfg, "define-tasks", wid)
208
+ base = workdir / plans.ROOT / wid
209
+ new = sorted(p.name for p in base.iterdir()
210
+ if p.is_dir() and plans.NNNN.fullmatch(p.name)
211
+ and p.name not in existing and (p / "TASK.md").is_file())
212
+ copied = {n: {f: (base / n / f).read_text() for f in TASK_FILES
213
+ if (base / n / f).is_file()} for n in new}
214
+ return {"copied": copied, "report": report.strip()}
215
+
216
+ result = in_worktree(wid, cfg, work)
217
+ copied = result.pop("copied")
218
+ if not copied:
219
+ raise Fail(f"the agent wrote no new task under {plans.ROOT / wid}/\n{result['report'][-800:]}")
220
+
221
+ tasks, dropped = plans.listed(wid)
222
+ for nnnn, documents in copied.items():
223
+ for filename, text in documents.items():
224
+ path = plans.ROOT / wid / nnnn / filename
225
+ path.parent.mkdir(parents=True, exist_ok=True)
226
+ path.write_text(text)
227
+ if nnnn not in tasks and nnnn not in dropped:
228
+ plans.add_task_line(wid, f"{nnnn} {plans.task_title(f'{wid}/{nnnn}')}")
229
+
230
+ paths = [str(plan_file), *(str(plans.ROOT / wid / n) for n in copied)]
231
+ git.run("add", "--", *paths)
232
+ git.run("commit", "-q", "-m", f"{wid} define tasks", "--", *paths)
233
+ result.update(workplan=wid, agent=name, tasks=[f"{wid}/{n}" for n in copied],
234
+ commit=git.run("log", "-1", "--format=%h %s"))
235
+ return result
236
+
237
+
238
+ def _need_plan(wid: str) -> Path:
239
+ path = plans.plan_path(wid)
240
+ if not path.is_file():
241
+ raise Fail(f"{path}: not found")
242
+ return path
243
+
244
+ # ---------------------------------------------------------------------------
245
+ # adapters
246
+ # ---------------------------------------------------------------------------
247
+
248
+ FENCE = re.compile(r"```(?:diff|patch)?[ \t]*\n(.*?)```", re.S)
249
+ FILE_HEADER = re.compile(r"^=====\s*(\S+)\s*=====\s*$", re.M)
250
+
251
+
252
+ def parse_patch(reply: str, tid: str) -> tuple[str, str]:
253
+ """The commit message line and the diff in a reply."""
254
+ message = ""
255
+ for line in reply.splitlines():
256
+ line = line.strip().strip("`")
257
+ line = re.sub(r"^(COMMIT_MSG|Commit message)\s*:\s*", "", line, flags=re.I)
258
+ if line.startswith(f"{tid} "):
259
+ message = line
260
+ break
261
+
262
+ patch = ""
263
+ for block in FENCE.findall(reply):
264
+ if re.search(r"^(diff --git|--- )", block, re.M):
265
+ patch = block
266
+ break
267
+ if not patch:
268
+ m = re.search(r"^(diff --git|--- )", reply, re.M)
269
+ patch = reply[m.start():] if m else ""
270
+ if patch and not patch.endswith("\n"):
271
+ patch += "\n"
272
+ return message, patch
273
+
274
+
275
+ def parse_files(reply: str, wid: str) -> dict[str, str]:
276
+ """Task files in a reply, keyed by path; other paths are ignored."""
277
+ allowed = re.compile(rf"^{re.escape(str(plans.ROOT))}/{re.escape(wid)}/\d{{4}}/"
278
+ r"(TASK|BREAKDOWN|NOTES)\.md$")
279
+ parts = FILE_HEADER.split(reply)
280
+ files = {}
281
+ for path, body in zip(parts[1::2], parts[2::2]):
282
+ if allowed.match(path):
283
+ body = re.sub(r"^\s*```[a-z]*\n|\n```\s*$", "", body.strip("\n"))
284
+ files[path] = body.strip("\n") + "\n"
285
+ return files
286
+
287
+
288
+ def use_patch(reply: str, workdir: Path, tid: str) -> str:
289
+ """Apply the reply's diff; return an error, or empty on success."""
290
+ message, patch = parse_patch(reply, tid)
291
+ if not patch:
292
+ return "the reply holds no unified diff"
293
+ result = subprocess.run(["git", "apply", "--recount", "--whitespace=nowarn", "-"],
294
+ cwd=workdir, input=patch, capture_output=True, text=True)
295
+ if result.returncode != 0:
296
+ return f"the diff did not apply: {result.stderr.strip()}"
297
+ if message:
298
+ path = workdir / plans.ROOT / tid / "COMMIT_MSG"
299
+ path.parent.mkdir(parents=True, exist_ok=True)
300
+ path.write_text(message + "\n")
301
+ return ""
302
+
303
+
304
+ def use_files(reply: str, workdir: Path, wid: str) -> str:
305
+ """Write the reply's task files; return an error, or empty on success."""
306
+ files = parse_files(reply, wid)
307
+ if not any(path.endswith("/TASK.md") for path in files):
308
+ return ("the reply holds no TASK.md under a "
309
+ f"'===== {plans.ROOT}/{wid}/<nnnn>/TASK.md =====' line")
310
+ for path, text in files.items():
311
+ full = workdir / path
312
+ full.parent.mkdir(parents=True, exist_ok=True)
313
+ full.write_text(text)
314
+ return ""
315
+
316
+
317
+ def run_none(workdir: Path, prompt: str, cfg: dict, action: str, target: str) -> str:
318
+ agent = cfg["agent"]
319
+ messages = [{"role": "user", "content": prompt}]
320
+ attempts = max(1, int(agent["attempts"]))
321
+ use = use_patch if action == "produce-patch" else use_files
322
+ error = ""
323
+
324
+ for _ in range(attempts):
325
+ reply = llm.chat(cfg, agent["model"], messages, float(agent["timeout"]))
326
+ error = use(reply, workdir, target)
327
+ if not error:
328
+ return reply
329
+ messages += [
330
+ {"role": "assistant", "content": reply},
331
+ {"role": "user", "content": f"That reply could not be used: {error}\n"
332
+ "Reply again, in full, in the form asked for."},
333
+ ]
334
+
335
+ raise Fail(f"no usable reply after {attempts} attempts: {error}")
336
+
337
+
338
+ PRESETS = {
339
+ "claude-code": ["claude", "-p", "--allowedTools", "Read,Edit,Write,Glob,Grep,Bash"],
340
+ "codex": ["codex", "exec", "--sandbox", "workspace-write", "{prompt}"],
341
+ }
342
+
343
+
344
+ def run_command(workdir: Path, prompt: str, cfg: dict, action: str, target: str,
345
+ preset: str | None = None) -> str:
346
+ argv = list(cfg["agent"]["command"]) or list(PRESETS.get(preset or "", []))
347
+ if not argv:
348
+ raise Fail("agent.command is empty")
349
+
350
+ stdin = prompt
351
+ if "{prompt}" in argv:
352
+ argv = [prompt if a == "{prompt}" else a for a in argv]
353
+ stdin = None
354
+
355
+ env = {**os.environ, "WORKPLAN_ACTION": action, "WORKPLAN_TARGET": target}
356
+ if action == "produce-patch":
357
+ env["WORKPLAN_COMMIT_MSG"] = str(plans.ROOT / target / "COMMIT_MSG")
358
+ try:
359
+ result = subprocess.run(argv, cwd=workdir, input=stdin, capture_output=True, text=True,
360
+ env=env, timeout=float(cfg["agent"]["timeout"]))
361
+ except FileNotFoundError as e:
362
+ raise Fail(f"agent command not found: {argv[0]}") from e
363
+ except subprocess.TimeoutExpired as e:
364
+ raise Fail(f"agent timed out after {cfg['agent']['timeout']}s") from e
365
+
366
+ if result.returncode != 0:
367
+ detail = (result.stderr or result.stdout).strip()[-800:]
368
+ raise Fail(f"agent exited {result.returncode}: {detail}")
369
+ return result.stdout
370
+
371
+
372
+ ADAPTERS = {
373
+ "none": run_none,
374
+ "command": run_command,
375
+ "claude-code": partial(run_command, preset="claude-code"),
376
+ "codex": partial(run_command, preset="codex"),
377
+ }
workplan/cli.py ADDED
@@ -0,0 +1,144 @@
1
+ """The workplan command. Formats what the operations return."""
2
+
3
+ import argparse
4
+ import json
5
+ import os
6
+ import shlex
7
+ import signal
8
+ import subprocess
9
+ import sys
10
+
11
+ from workplan import __version__, agent, config, git, ops, route
12
+ from workplan.git import Fail
13
+
14
+
15
+ def page(text: str) -> None:
16
+ if not sys.stdout.isatty():
17
+ sys.stdout.write(text)
18
+ return
19
+ pager = shlex.split(os.environ.get("PAGER", "less -R"))
20
+ try:
21
+ subprocess.run(pager, input=text, text=True)
22
+ except FileNotFoundError:
23
+ sys.stdout.write(text)
24
+
25
+
26
+ def print_status(data: dict) -> None:
27
+ for task in data["tasks"]:
28
+ detail = task["detail"] or task["title"]
29
+ print(f"{task['id']:<28} {task['state']:<12} {detail}".rstrip())
30
+
31
+
32
+ def print_agent(result: dict) -> None:
33
+ if result["report"]:
34
+ print(result["report"])
35
+ print()
36
+
37
+
38
+ def parser() -> argparse.ArgumentParser:
39
+ p = argparse.ArgumentParser(prog="workplan",
40
+ description="Plan and record development work in git.")
41
+ p.add_argument("--version", action="version", version=f"workplan {__version__}")
42
+ sub = p.add_subparsers(dest="command", required=True, metavar="command")
43
+
44
+ sub.add_parser("init", help="create and commit workplans/")
45
+
46
+ pl = sub.add_parser("plan", help="a workplan on a new branch")
47
+ pl.add_argument("name")
48
+ pl.add_argument("-m", "--goal", help="the goal; skips the editor")
49
+
50
+ sub.add_parser("define-tasks", help="the agent writes the tasks; commits the plan") \
51
+ .add_argument("id", nargs="?")
52
+
53
+ for name, text in (
54
+ ("produce-patch", "the agent writes output.patch and COMMIT_MSG"),
55
+ ("apply", "stage the patch in the tree and the index"),
56
+ ("diff", "the staged change if applied, else the patch"),
57
+ ("accept", "commit the patch with the task's files"),
58
+ ("reject", "take an applied, uncommitted patch back out"),
59
+ ):
60
+ sub.add_parser(name, help=text).add_argument("task", metavar="[ID/]NNNN")
61
+
62
+ sub.add_parser("merge", help="squash the workplan into master") \
63
+ .add_argument("id", nargs="?")
64
+
65
+ st = sub.add_parser("status", help="where a workplan or a task stands")
66
+ st.add_argument("id", nargs="?")
67
+ st.add_argument("--json", action="store_true")
68
+
69
+ rt = sub.add_parser("route", help="the next step after a commit")
70
+ rt.add_argument("rev", nargs="?", default="HEAD")
71
+ rt.add_argument("--dispatch", action="store_true",
72
+ help="record the decision and run route.dispatch")
73
+
74
+ sub.add_parser("install", help="hooks that run route after each commit")
75
+ return p
76
+
77
+
78
+ def run(args: argparse.Namespace) -> None:
79
+ os.chdir(git.toplevel())
80
+ cfg = config.load()
81
+ master = cfg["master"]
82
+
83
+ match args.command:
84
+ case "init":
85
+ for line in ops.init():
86
+ print(line)
87
+ case "plan":
88
+ result = ops.plan(args.name, master, goal=args.goal)
89
+ print(f"switched to {result['branch']}\ncreated {result['created']}")
90
+ case "define-tasks":
91
+ result = agent.define_tasks(args.id, cfg)
92
+ print_agent(result)
93
+ for tid in result["tasks"]:
94
+ print(f"defined {tid}")
95
+ print(f"committed {result['commit']}")
96
+ case "produce-patch":
97
+ result = agent.produce_patch(args.task, cfg)
98
+ print_agent(result)
99
+ print(f"{result['patch']}: against {result['base']}, by {result['agent']}")
100
+ print(f"COMMIT_MSG: {result['commit_msg']}")
101
+ if result["note"]:
102
+ print(f"note: {result['note']}")
103
+ case "apply":
104
+ print(ops.apply(args.task))
105
+ case "diff":
106
+ page(ops.diff(args.task))
107
+ case "accept":
108
+ print(ops.accept(args.task, master))
109
+ case "reject":
110
+ print(ops.reject(args.task))
111
+ case "merge":
112
+ result = ops.merge(args.id, master)
113
+ print(result["commit"])
114
+ print("\nnext:")
115
+ for line in result["next"]:
116
+ print(f" {line}")
117
+ case "status":
118
+ data = ops.status(args.id, master)
119
+ if args.json:
120
+ print(json.dumps(data, indent=2))
121
+ else:
122
+ print_status(data)
123
+ case "route":
124
+ decision = route.decide(args.rev, cfg)
125
+ print(f"route: {decision['source']} chose {decision['action']}; "
126
+ f"the rules chose {decision['rule']}", file=sys.stderr)
127
+ if args.dispatch:
128
+ route.dispatch(decision, cfg)
129
+ print(" ".join([decision["action"], *decision["targets"]]))
130
+ case "install":
131
+ for line in ops.install():
132
+ print(line)
133
+
134
+
135
+ def main(argv: list[str] | None = None) -> int:
136
+ args = parser().parse_args(argv)
137
+ if hasattr(signal, "SIGPIPE"):
138
+ signal.signal(signal.SIGPIPE, signal.SIG_DFL)
139
+ try:
140
+ run(args)
141
+ except Fail as e:
142
+ print(f"workplan: {e}", file=sys.stderr)
143
+ return 1
144
+ return 0
workplan/config.py ADDED
@@ -0,0 +1,74 @@
1
+ """workplans/config.toml, with environment overrides.
2
+
3
+ API keys come from the environment only: the variable named by
4
+ llm.api_key_env, else WORKPLAN_API_KEY.
5
+ """
6
+
7
+ import copy
8
+ import os
9
+ import shlex
10
+ import tomllib
11
+
12
+ from workplan import plans
13
+ from workplan.git import Fail
14
+
15
+ DEFAULTS = {
16
+ "master": "master",
17
+ "llm": {
18
+ "api_base": "http://localhost:8000/v1",
19
+ "api_key_env": "WORKPLAN_API_KEY",
20
+ "params": {},
21
+ },
22
+ "route": {
23
+ "classifier": "rules",
24
+ "model": "",
25
+ "timeout": 120,
26
+ "dispatch": "",
27
+ },
28
+ "agent": {
29
+ "name": "none",
30
+ "model": "",
31
+ "attempts": 3,
32
+ "timeout": 1800,
33
+ "setup": "",
34
+ "command": [],
35
+ },
36
+ }
37
+
38
+ # environment variable -> (section or None, key, conversion)
39
+ OVERRIDES = {
40
+ "WORKPLAN_MASTER": (None, "master", str),
41
+ "WORKPLAN_API_BASE": ("llm", "api_base", str),
42
+ "WORKPLAN_ROUTE_CLASSIFIER": ("route", "classifier", str),
43
+ "WORKPLAN_ROUTE_MODEL": ("route", "model", str),
44
+ "WORKPLAN_ROUTE_DISPATCH": ("route", "dispatch", str),
45
+ "WORKPLAN_AGENT": ("agent", "name", str),
46
+ "WORKPLAN_AGENT_MODEL": ("agent", "model", str),
47
+ "WORKPLAN_AGENT_SETUP": ("agent", "setup", str),
48
+ "WORKPLAN_AGENT_COMMAND": ("agent", "command", shlex.split),
49
+ }
50
+
51
+ PATH = plans.ROOT / "config.toml"
52
+
53
+
54
+ def load() -> dict:
55
+ cfg = copy.deepcopy(DEFAULTS)
56
+ if PATH.is_file():
57
+ try:
58
+ data = tomllib.loads(PATH.read_text())
59
+ except tomllib.TOMLDecodeError as e:
60
+ raise Fail(f"{PATH}: {e}") from e
61
+ for key, value in data.items():
62
+ if isinstance(value, dict) and isinstance(cfg.get(key), dict):
63
+ cfg[key].update(value)
64
+ else:
65
+ cfg[key] = value
66
+ for var, (section, key, convert) in OVERRIDES.items():
67
+ if var in os.environ:
68
+ target = cfg[section] if section else cfg
69
+ target[key] = convert(os.environ[var])
70
+ return cfg
71
+
72
+
73
+ def api_key(cfg: dict) -> str:
74
+ return os.environ.get(cfg["llm"]["api_key_env"]) or os.environ.get("WORKPLAN_API_KEY", "")
workplan/git.py ADDED
@@ -0,0 +1,69 @@
1
+ """Running git. No other module calls the git binary."""
2
+
3
+ import subprocess
4
+ from pathlib import Path
5
+
6
+
7
+ class Fail(Exception):
8
+ """An operation that cannot go on; the CLI prints it and exits 1."""
9
+
10
+
11
+ def run(*args: str, input: str | None = None, cwd: Path | str | None = None,
12
+ strip: bool = True) -> str:
13
+ """Run git and return its output, or raise Fail with its error.
14
+
15
+ strip=False returns stdout unchanged, as a diff needs.
16
+ """
17
+ result = subprocess.run(
18
+ ["git", *args], text=True, input=input, capture_output=True, cwd=cwd,
19
+ )
20
+ if result.returncode != 0:
21
+ detail = result.stderr.strip() or result.stdout.strip()
22
+ raise Fail(f"git {' '.join(args)} failed" + (f": {detail}" if detail else ""))
23
+ return result.stdout.strip() if strip else result.stdout
24
+
25
+
26
+ def ok(*args: str, cwd: Path | str | None = None) -> bool:
27
+ """True when the git command exits 0."""
28
+ return subprocess.run(["git", *args], capture_output=True, cwd=cwd).returncode == 0
29
+
30
+
31
+ def toplevel() -> Path:
32
+ return Path(run("rev-parse", "--show-toplevel"))
33
+
34
+
35
+ def branch() -> str:
36
+ """The current branch, or HEAD when detached."""
37
+ return run("rev-parse", "--abbrev-ref", "HEAD")
38
+
39
+
40
+ def ref_exists(ref: str) -> bool:
41
+ return ok("rev-parse", "--verify", "-q", ref)
42
+
43
+
44
+ def clean() -> bool:
45
+ return ok("diff", "--quiet") and ok("diff", "--cached", "--quiet")
46
+
47
+
48
+ def is_ancestor(a: str, b: str) -> bool:
49
+ return ok("merge-base", "--is-ancestor", a, b)
50
+
51
+
52
+ def git_path(name: str) -> Path:
53
+ """A path inside the repository's git directory, such as hooks."""
54
+ return Path(run("rev-parse", "--git-path", name))
55
+
56
+
57
+ def interactive(*args: str) -> None:
58
+ """Run git attached to the terminal, as an editor needs; raise Fail
59
+ when it exits non-zero."""
60
+ if subprocess.run(["git", *args]).returncode != 0:
61
+ raise Fail(f"git {' '.join(args)} failed")
62
+
63
+
64
+ def edit(path: Path) -> None:
65
+ """Open path in the editor git uses for commit messages
66
+ (GIT_EDITOR, core.editor, VISUAL, EDITOR), the way git runs it."""
67
+ editor = run("var", "GIT_EDITOR")
68
+ if subprocess.run(["sh", "-c", f'{editor} "$@"', editor, str(path)]).returncode != 0:
69
+ raise Fail(f"the editor ({editor}) exited with an error")