comitia 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 (48) hide show
  1. comitia/__init__.py +3 -0
  2. comitia/__main__.py +3 -0
  3. comitia/api.py +68 -0
  4. comitia/catalog.py +82 -0
  5. comitia/cli.py +950 -0
  6. comitia/control.py +156 -0
  7. comitia/diffs.py +120 -0
  8. comitia/discussion/__init__.py +0 -0
  9. comitia/discussion/api.py +152 -0
  10. comitia/discussion/cli.py +1254 -0
  11. comitia/discussion/config.py +167 -0
  12. comitia/discussion/console.py +366 -0
  13. comitia/discussion/converse.py +1221 -0
  14. comitia/discussion/journal.py +382 -0
  15. comitia/discussion/panel.py +1647 -0
  16. comitia/discussion/panel_view.py +445 -0
  17. comitia/discussion/prompts/converse_asker.md +3 -0
  18. comitia/discussion/prompts/converse_summary.md +27 -0
  19. comitia/discussion/transcript.py +88 -0
  20. comitia/engine.py +1223 -0
  21. comitia/findings.py +270 -0
  22. comitia/host.py +2067 -0
  23. comitia/plan.py +957 -0
  24. comitia/posting.py +328 -0
  25. comitia/prompts.py +750 -0
  26. comitia/recipe.py +430 -0
  27. comitia/report.py +581 -0
  28. comitia/settings.py +66 -0
  29. comitia/skill/SKILL.md +75 -0
  30. comitia/starters/decision-debate.yml +27 -0
  31. comitia/starters/deep-review.yml +12 -0
  32. comitia/starters/message-test.yml +15 -0
  33. comitia/starters/pr-review-light.yml +78 -0
  34. comitia/starters/pr-review.yml +100 -0
  35. comitia/starters/prd-review.yml +10 -0
  36. comitia/store.py +212 -0
  37. comitia/web/__init__.py +13 -0
  38. comitia/web/server.py +244 -0
  39. comitia/web/service.py +679 -0
  40. comitia/web/static/app.js +1521 -0
  41. comitia/web/static/index.html +38 -0
  42. comitia/web/static/styles.css +262 -0
  43. comitia-0.1.0.dist-info/METADATA +589 -0
  44. comitia-0.1.0.dist-info/RECORD +48 -0
  45. comitia-0.1.0.dist-info/WHEEL +4 -0
  46. comitia-0.1.0.dist-info/entry_points.txt +2 -0
  47. comitia-0.1.0.dist-info/licenses/LICENSE +21 -0
  48. comitia-0.1.0.dist-info/licenses/LICENSES/crossby-MIT.txt +21 -0
comitia/cli.py ADDED
@@ -0,0 +1,950 @@
1
+ """The comitia command line: the contract an agent's skill, or a person, drives.
2
+
3
+ Every command prints ``--json``. Exit codes: 0 done (a partial result is
4
+ flagged in the output), 1 an error or a failed run, 2 the plan is refused,
5
+ 3 the run was not approved.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import shlex
12
+ import signal
13
+ import sys
14
+ import threading
15
+ from pathlib import Path
16
+ from typing import Any, NoReturn
17
+
18
+ import typer
19
+
20
+ from comitia import control, diffs, engine, host, posting, recipe, report, store
21
+ from comitia import findings as fd
22
+ from comitia import plan as planning
23
+ from comitia.discussion import cli as discussion_cli
24
+ from comitia.settings import Approval, SettingsError, effective_approval, load_settings
25
+
26
+ app = typer.Typer(
27
+ add_completion=False,
28
+ no_args_is_help=True,
29
+ help="Several AI models review a spec; every finding keeps its ID from run to run.",
30
+ )
31
+ recipe_app = typer.Typer(no_args_is_help=True, help="Recipes: who discusses and how.")
32
+ app.add_typer(recipe_app, name="recipe")
33
+
34
+ EXIT_ERROR, EXIT_REFUSED, EXIT_NOT_APPROVED = 1, 2, 3
35
+ JSON = typer.Option(False, "--json", help="Print JSON.")
36
+ MATERIAL = typer.Option(None, "--material", "-m", help="A file to discuss; repeat for more.")
37
+ DIFF = typer.Option(None, "--diff", help="Discuss a Git diff, such as main...HEAD.")
38
+ PR = typer.Option(None, "--pr", help="Discuss a pull request's diff, by number (needs gh).")
39
+ GOAL = typer.Option(None, "--goal", help="The question every participant gets.")
40
+ PRIOR = typer.Option(None, "--prior", help="A run to check against: its number, or `last`.")
41
+ RUN = typer.Argument("last", help="A run: its number, or `last`.")
42
+ RUN_OPTION = typer.Option("last", "--run", help="The run the finding is in.")
43
+
44
+
45
+ def _out(as_json: bool, data: Any, text: str) -> None:
46
+ typer.echo(json.dumps(data, indent=2, ensure_ascii=False) if as_json else text)
47
+
48
+
49
+ def _fail(message: str, *, code: int = EXIT_ERROR, as_json: bool = False) -> NoReturn:
50
+ if as_json:
51
+ typer.echo(json.dumps({"error": message}, ensure_ascii=False))
52
+ else:
53
+ typer.echo(message, err=True)
54
+ raise typer.Exit(code)
55
+
56
+
57
+ def _interactive() -> bool:
58
+ """Whether the user is at this terminal. One a coding agent may have made does not count."""
59
+ return sys.stdin.isatty() and sys.stdout.isatty() and not host.under_agent()
60
+
61
+
62
+ def _confirm(question: str) -> bool:
63
+ return typer.confirm(question, default=False)
64
+
65
+
66
+ def _root() -> Path:
67
+ return store.project_root()
68
+
69
+
70
+ def _preset(root: Path, *, as_json: bool) -> Approval:
71
+ """The project's approval preset, for a command with no plan of its own."""
72
+ try:
73
+ return load_settings(root).approval
74
+ except SettingsError as exc:
75
+ _fail(str(exc), as_json=as_json)
76
+
77
+
78
+ def _approve(root: Path, command: str, question: str, *, as_json: bool, approval: Approval) -> str:
79
+ """Get approval as the preset says, or refuse; returns how it was given.
80
+
81
+ ``none``: nobody is asked. ``host``: the user's terminal asks; under a coding agent,
82
+ the host's own permission flow already decided, in whatever mode the user set.
83
+ ``strict``: only the user's own prompt counts, this terminal or a host's explicit
84
+ ``ask`` rule, and everything that could get around that rule is refused.
85
+ """
86
+ if approval == "none":
87
+ return "approval: none (.comitia.yml)"
88
+ if approval == "host":
89
+ if _interactive():
90
+ if not _confirm(question):
91
+ _fail("Not approved; nothing ran.", code=EXIT_NOT_APPROVED, as_json=as_json)
92
+ return "the terminal"
93
+ if host.under_agent():
94
+ return f"the host's own permission flow ({host.agent_name()})"
95
+ _fail(
96
+ f"Nobody here can approve `comitia {command}`: no terminal and no coding agent. "
97
+ "Set `approval: none` in .comitia.yml to run unattended.",
98
+ code=EXIT_NOT_APPROVED,
99
+ as_json=as_json,
100
+ )
101
+ if _interactive():
102
+ if not _confirm(question):
103
+ _fail("Not approved; nothing ran.", code=EXIT_NOT_APPROVED, as_json=as_json)
104
+ return "the terminal"
105
+ # The command as given, so a host's rules judge exactly what is about to run.
106
+ reason = host.refusal(root, command, invocation=[host.COMMAND, *sys.argv[1:]])
107
+ if reason is None:
108
+ return host.approved_via()
109
+ _fail(reason, code=EXIT_NOT_APPROVED, as_json=as_json)
110
+
111
+
112
+ def _material(
113
+ root: Path, files: list[Path] | None, diff: str | None, pr: int | None, *, as_json: bool
114
+ ) -> list[Path]:
115
+ """The files to discuss: the ones named, then the diffs asked for."""
116
+ found = list(files or [])
117
+ try:
118
+ if diff is not None:
119
+ found.append(diffs.from_range(root, diff))
120
+ if pr is not None:
121
+ found.append(diffs.from_pull_request(root, pr))
122
+ warning = diffs.pull_request_head(root, pr)
123
+ if warning:
124
+ typer.echo(warning, err=True)
125
+ except diffs.DiffError as exc:
126
+ _fail(str(exc), as_json=as_json)
127
+ return found
128
+
129
+
130
+ def _build(
131
+ root: Path,
132
+ reference: str,
133
+ material: list[Path],
134
+ goal: str | None,
135
+ prior: str | None,
136
+ *,
137
+ as_json: bool,
138
+ ) -> tuple[planning.Plan, planning.Inputs]:
139
+ try:
140
+ loaded = recipe.load(root, reference)
141
+ return planning.build(root, loaded, material, goal=goal, prior=prior)
142
+ except (recipe.RecipeError, planning.PlanError, store.StoreError, fd.FindingError) as exc:
143
+ _fail(str(exc), as_json=as_json)
144
+
145
+
146
+ def _run_command(reference: str, plan: planning.Plan, goal: str | None, prior: str | None) -> str:
147
+ parts = ["comitia", "run", reference]
148
+ for item in plan.material:
149
+ parts += ["--material", item.path]
150
+ if goal:
151
+ parts += ["--goal", goal]
152
+ if prior:
153
+ parts += ["--prior", str(plan.prior)]
154
+ parts += ["--plan", plan.plan_id]
155
+ return shlex.join(parts)
156
+
157
+
158
+ # -- recipes -------------------------------------------------------------------
159
+
160
+
161
+ @recipe_app.command("new")
162
+ def recipe_new(
163
+ name: str,
164
+ starter: str | None = typer.Option(None, "--from", help="A starter recipe to copy."),
165
+ as_json: bool = JSON,
166
+ ) -> None:
167
+ """Write recipes/NAME.yml, from scratch or from a starter."""
168
+ try:
169
+ path = recipe.new(_root(), name, starter=starter)
170
+ except recipe.RecipeError as exc:
171
+ _fail(str(exc), as_json=as_json)
172
+ _out(as_json, {"recipe": name, "path": str(path)}, f"Wrote {path}. Edit it, then check it.")
173
+
174
+
175
+ @recipe_app.command("list")
176
+ def recipe_list(as_json: bool = JSON) -> None:
177
+ """The project's recipes, and the starters that ship with comitia."""
178
+ root = _root()
179
+ folder = root / recipe.RECIPES_DIR
180
+ own = sorted(path.stem for path in folder.glob("*.y*ml")) if folder.is_dir() else []
181
+ shipped = list(recipe.starters())
182
+ lines = ["Your recipes (recipes/):", *(f" {name}" for name in own or ["(none yet)"])]
183
+ lines += ["Starters:", *(f" {name}" for name in shipped)]
184
+ _out(as_json, {"recipes": own, "starters": shipped}, "\n".join(lines))
185
+
186
+
187
+ # -- check and run ---------------------------------------------------------------
188
+
189
+
190
+ @app.command()
191
+ def check(
192
+ recipe_name: str = typer.Argument(..., metavar="RECIPE"),
193
+ material: list[Path] = MATERIAL,
194
+ diff: str | None = DIFF,
195
+ pr: int | None = PR,
196
+ goal: str | None = GOAL,
197
+ prior: str | None = PRIOR,
198
+ as_json: bool = JSON,
199
+ ) -> None:
200
+ """Show the plan a run would follow. Starts no agent."""
201
+ root = _root()
202
+ material = _material(root, material, diff, pr, as_json=as_json)
203
+ plan, inputs = _build(root, recipe_name, material, goal, prior, as_json=as_json)
204
+ command = _run_command(recipe_name, plan, goal, prior)
205
+ data = plan.dump()
206
+ data["instructions"] = inputs.instructions
207
+ # Only under `strict` does the host's own setup decide whether a run would be refused.
208
+ warning = host.check_warning(root) if plan.approval == "strict" else None
209
+ # The plan's own warnings, then whether the host would refuse the run it prints.
210
+ data["warnings"] = [*plan.warnings, *([warning] if warning else [])]
211
+ text = planning.render(plan, inputs.instructions)
212
+ if warning:
213
+ text += f"\n\n! {warning}"
214
+ if plan.refusals:
215
+ _out(as_json, data, text)
216
+ raise typer.Exit(EXIT_REFUSED)
217
+ store.record_shown(root, plan.plan_id)
218
+ data["run_command"] = command
219
+ _out(as_json, data, f"{text}\n\nTo run exactly this plan, once the user approves:\n {command}")
220
+
221
+
222
+ def _execute_here(run: store.RunFolder, *, resume: bool = False) -> dict[str, Any]:
223
+ cancel = threading.Event()
224
+
225
+ def stop(_signal: int, _frame: Any) -> None:
226
+ cancel.set()
227
+
228
+ previous = {sig: signal.signal(sig, stop) for sig in (signal.SIGINT, signal.SIGTERM)}
229
+ try:
230
+ return engine.execute(run, cancel=cancel, resume=resume)
231
+ finally:
232
+ for sig, handler in previous.items():
233
+ signal.signal(sig, handler)
234
+ if resume:
235
+ run.update_state(resuming=False)
236
+
237
+
238
+ def _print_ending(run: store.RunFolder, state: dict[str, Any], *, as_json: bool) -> None:
239
+ status = state.get("status")
240
+ if status in {"done", "partial"}:
241
+ data = report.write(run)
242
+ _out(as_json, data, report.render_text(data))
243
+ return
244
+ data = {"run": run.id, "status": status, "reason": state.get("reason")}
245
+ _out(as_json, data, f"Run {run.id} {status}: {state.get('reason')}. There is no report.")
246
+ raise typer.Exit(EXIT_ERROR)
247
+
248
+
249
+ @app.command()
250
+ def run(
251
+ recipe_name: str = typer.Argument(..., metavar="RECIPE"),
252
+ material: list[Path] = MATERIAL,
253
+ diff: str | None = DIFF,
254
+ pr: int | None = PR,
255
+ goal: str | None = GOAL,
256
+ prior: str | None = PRIOR,
257
+ plan_id: str | None = typer.Option(
258
+ None, "--plan", help="The ID of the plan `check` showed; the run refuses any other."
259
+ ),
260
+ background: bool = typer.Option(
261
+ False, "--background", help="Return at once; for people in a terminal."
262
+ ),
263
+ as_json: bool = JSON,
264
+ ) -> None:
265
+ """Run the approved plan and return when it ends."""
266
+ root = _root()
267
+ material = _material(root, material, diff, pr, as_json=as_json)
268
+ plan, inputs = _build(root, recipe_name, material, goal, prior, as_json=as_json)
269
+ if plan.refusals:
270
+ _out(as_json, plan.dump(), planning.render(plan, inputs.instructions))
271
+ raise typer.Exit(EXIT_REFUSED)
272
+ if plan_id is not None:
273
+ if plan_id != plan.plan_id:
274
+ _fail(
275
+ f"The plan changed since it was shown: it is now {plan.plan_id}, not {plan_id}, "
276
+ "so the approval no longer holds. Run `comitia check` again and show the "
277
+ "user the new plan.",
278
+ code=EXIT_NOT_APPROVED,
279
+ as_json=as_json,
280
+ )
281
+ if not store.was_shown(root, plan_id):
282
+ _fail(
283
+ f"Plan {plan_id} was never shown by `comitia check` in this project.",
284
+ code=EXIT_NOT_APPROVED,
285
+ as_json=as_json,
286
+ )
287
+ elif not _interactive():
288
+ _fail(
289
+ "Nothing ran. Run `comitia check` first, show the user the plan, then run the "
290
+ "command it prints, with `--plan`.",
291
+ code=EXIT_NOT_APPROVED,
292
+ as_json=as_json,
293
+ )
294
+ if _interactive() and not as_json:
295
+ typer.echo(planning.render(plan, inputs.instructions) + "\n")
296
+ approved = _approve(
297
+ root,
298
+ "run",
299
+ f"Run this plan ({plan.max_sessions} sessions at most)?",
300
+ as_json=as_json,
301
+ approval=plan.approval,
302
+ )
303
+ folder = engine.prepare(root, plan, inputs)
304
+ folder.update_state(approved_via=approved, approval=plan.approval)
305
+ if background:
306
+ control.spawn_background(folder)
307
+ _out(
308
+ as_json,
309
+ {"run": folder.id, "status": "starting"},
310
+ f"Run {folder.id} started. `comitia status {folder.id}` shows who is writing; "
311
+ f"`comitia report {folder.id}` prints the report when it ends.",
312
+ )
313
+ return
314
+ if not as_json:
315
+ typer.echo(f"Run {folder.id} started; it returns when it ends.", err=True)
316
+ _print_ending(folder, _execute_here(folder), as_json=as_json)
317
+
318
+
319
+ @app.command("import-journal")
320
+ def import_command(
321
+ journal: Path = typer.Argument(
322
+ ..., metavar="JOURNAL", help="A `crossby converse` consultation's events.jsonl."
323
+ ),
324
+ material: list[Path] = MATERIAL,
325
+ plan_id: str | None = typer.Option(
326
+ None, "--plan", help="The ID of the plan `--check` showed; the import refuses any other."
327
+ ),
328
+ check_only: bool = typer.Option(
329
+ False, "--check", help="Show the plan the import would follow. Starts no agent."
330
+ ),
331
+ background: bool = typer.Option(
332
+ False, "--background", help="Return at once; for people in a terminal."
333
+ ),
334
+ as_json: bool = JSON,
335
+ ) -> None:
336
+ """Make a report of an earlier `crossby converse` consultation, once the user approves.
337
+
338
+ The material is what the consultation discussed, given again: the run keeps a copy.
339
+ """
340
+ root = _root()
341
+ try:
342
+ plan, inputs = planning.build_import(root, journal, list(material or []))
343
+ except (planning.PlanError, store.StoreError) as exc:
344
+ _fail(str(exc), as_json=as_json)
345
+ parts = ["comitia", "import-journal", str(journal)]
346
+ for item in plan.material:
347
+ parts += ["--material", item.path]
348
+ command = shlex.join([*parts, "--plan", plan.plan_id])
349
+ text = planning.render(plan, inputs.instructions)
350
+ data = plan.dump()
351
+ if plan.refusals:
352
+ _out(as_json, data, text)
353
+ raise typer.Exit(EXIT_REFUSED)
354
+ if check_only:
355
+ store.record_shown(root, plan.plan_id)
356
+ warning = (
357
+ host.check_warning(root, command="import-journal")
358
+ if plan.approval == "strict"
359
+ else None
360
+ )
361
+ if warning:
362
+ text += f"\n\n! {warning}"
363
+ data["import_command"] = command
364
+ _out(
365
+ as_json, data, f"{text}\n\nTo import exactly this, once the user approves:\n {command}"
366
+ )
367
+ return
368
+ if plan_id is not None:
369
+ if plan_id != plan.plan_id or not store.was_shown(root, plan_id):
370
+ _fail(
371
+ f"This is not the plan that was shown (it is now {plan.plan_id}), so the "
372
+ "approval no longer holds. Run `comitia import-journal ... --check` again "
373
+ "and show the user the plan.",
374
+ code=EXIT_NOT_APPROVED,
375
+ as_json=as_json,
376
+ )
377
+ elif not _interactive():
378
+ _fail(
379
+ "Nothing ran. Run `comitia import-journal JOURNAL --material FILE --check` "
380
+ "first, show the user the plan, then run the command it prints.",
381
+ code=EXIT_NOT_APPROVED,
382
+ as_json=as_json,
383
+ )
384
+ if _interactive() and not as_json:
385
+ typer.echo(text + "\n")
386
+ approved = _approve(
387
+ root,
388
+ "import-journal",
389
+ f"Import it ({plan.max_sessions} sessions at most)?",
390
+ as_json=as_json,
391
+ approval=plan.approval,
392
+ )
393
+ copy = Path(str(plan.imported)).read_bytes()
394
+ if store.sha256(copy) != plan.recipe_sha:
395
+ _fail(
396
+ f"{journal} changed after its plan was shown; nothing ran.",
397
+ code=EXIT_NOT_APPROVED,
398
+ as_json=as_json,
399
+ )
400
+ folder = engine.prepare(root, plan, inputs)
401
+ (folder.path / planning.IMPORTED_FILE).write_bytes(copy)
402
+ folder.update_state(approved_via=approved, approval=plan.approval)
403
+ if background:
404
+ control.spawn_background(folder)
405
+ _out(as_json, {"run": folder.id, "status": "starting"}, f"Run {folder.id} started.")
406
+ return
407
+ if not as_json:
408
+ typer.echo(f"Run {folder.id} started; it returns when it ends.", err=True)
409
+ _print_ending(folder, _execute_here(folder), as_json=as_json)
410
+
411
+
412
+ @app.command(hidden=True)
413
+ def execute(run_ref: str) -> None:
414
+ """Run an already approved, prepared run (the body of `run --background`)."""
415
+ folder = store.find_run(_root(), run_ref)
416
+ state = folder.read_state()
417
+ if state.get("status") != "starting":
418
+ _fail(f"Run {folder.id} is not waiting to start.")
419
+ _execute_here(folder, resume=bool(state.get("resuming")))
420
+
421
+
422
+ def _resume_text(
423
+ folder: store.RunFolder,
424
+ plan: planning.Plan,
425
+ inputs: planning.Inputs,
426
+ left: engine.Remaining,
427
+ checked: planning.Recheck,
428
+ ) -> str:
429
+ state = folder.read_state()
430
+ lines = [
431
+ planning.render(plan, inputs.instructions),
432
+ "",
433
+ f"Resume run {folder.id} · {plan.recipe} · {planning.describe_format(plan)}",
434
+ f"It ended {control.current_status(state)}: {state.get('reason') or 'no reason recorded'}",
435
+ f"Keeps {'; '.join(left.kept) or 'nothing'}",
436
+ f"Runs {'; '.join(left.todo)}",
437
+ f"Sessions: at most {left.max_sessions} more, each up to "
438
+ f"{recipe.duration(plan.turn_timeout)}",
439
+ ]
440
+ if checked.refusals:
441
+ lines += ["", "The plan no longer holds, so nothing will run:"]
442
+ lines += [f" - {reason}" for reason in checked.refusals]
443
+ elif checked.changes:
444
+ lines.append("Checked again just now; a tool has updated since, and resuming uses it:")
445
+ lines += [f" - {change}" for change in checked.changes]
446
+ else:
447
+ lines.append("Every participant was checked again just now and is as the plan shows.")
448
+ return "\n".join(lines)
449
+
450
+
451
+ @app.command()
452
+ def resume(
453
+ run_ref: str = typer.Argument(..., metavar="RUN", help="The run: its number, or `last`."),
454
+ check_only: bool = typer.Option(
455
+ False, "--check", help="Show what resuming would keep and run. Starts no agent."
456
+ ),
457
+ background: bool = typer.Option(
458
+ False, "--background", help="Return at once; for people in a terminal."
459
+ ),
460
+ as_json: bool = JSON,
461
+ ) -> None:
462
+ """Take a stopped run up from where it stopped, once the user approves."""
463
+ root = _root()
464
+ try:
465
+ folder = store.find_run(root, run_ref)
466
+ except store.StoreError as exc:
467
+ _fail(str(exc), as_json=as_json)
468
+ why = engine.resumable(folder)
469
+ if why is not None:
470
+ _fail(why, as_json=as_json)
471
+ plan = planning.Plan.model_validate(store.read_json(folder.plan))
472
+ inputs = planning.Inputs.model_validate(store.read_json(folder.inputs))
473
+ try:
474
+ checked = planning.recheck(plan, inputs)
475
+ left = engine.remaining(folder)
476
+ except (planning.PlanError, store.StoreError, ValueError) as exc:
477
+ _fail(f"Run {folder.id} cannot be resumed: {exc}", as_json=as_json)
478
+ refusals = checked.refusals
479
+ # A run planned before a stricter preset was set resumes under the stricter one.
480
+ approval = effective_approval(_preset(root, as_json=as_json), plan.approval)
481
+ text = _resume_text(folder, plan, inputs, left, checked)
482
+ command = f"comitia resume {folder.id}"
483
+ data = {
484
+ "run": folder.id,
485
+ "kept": left.kept,
486
+ "todo": left.todo,
487
+ "max_sessions": left.max_sessions,
488
+ "refusals": refusals,
489
+ "changes": checked.changes,
490
+ "resume_command": command,
491
+ }
492
+ if refusals:
493
+ _out(as_json, data, text)
494
+ raise typer.Exit(EXIT_REFUSED)
495
+ if check_only:
496
+ warning = host.check_warning(root, command="resume") if approval == "strict" else None
497
+ if warning:
498
+ text += f"\n\n! {warning}"
499
+ _out(as_json, data, f"{text}\n\nTo resume it, once the user approves:\n {command}")
500
+ return
501
+ if _interactive() and not as_json:
502
+ typer.echo(text + "\n")
503
+ approved = _approve(
504
+ root,
505
+ "resume",
506
+ f"Resume run {folder.id} ({left.max_sessions} sessions at most)?",
507
+ as_json=as_json,
508
+ approval=approval,
509
+ )
510
+ try:
511
+ engine.claim_resume(folder, approved, checked.changes)
512
+ except engine.ResumeError as exc:
513
+ _fail(str(exc), as_json=as_json)
514
+ if background:
515
+ control.spawn_background(folder)
516
+ _out(
517
+ as_json,
518
+ {"run": folder.id, "status": "starting"},
519
+ f"Run {folder.id} resumed. `comitia status {folder.id}` shows who is writing.",
520
+ )
521
+ return
522
+ if not as_json:
523
+ typer.echo(f"Run {folder.id} resumed; it returns when it ends.", err=True)
524
+ _print_ending(folder, _execute_here(folder, resume=True), as_json=as_json)
525
+
526
+
527
+ # -- looking at runs ---------------------------------------------------------------
528
+
529
+
530
+ def _time(seconds: int) -> str:
531
+ return f"{seconds // 60}m {seconds % 60:02d}s" if seconds >= 60 else f"{seconds}s"
532
+
533
+
534
+ @app.command()
535
+ def status(run_ref: str = RUN, as_json: bool = JSON) -> None:
536
+ """Who is writing, done or failed."""
537
+ try:
538
+ folder = store.find_run(_root(), run_ref)
539
+ except store.StoreError as exc:
540
+ _fail(str(exc), as_json=as_json)
541
+ data = control.status(folder)
542
+ lines = [f"Run {folder.id} · {data['recipe']} · {data['status']}"]
543
+ if data["reason"]:
544
+ lines.append(f" {data['reason']}")
545
+ for seat in data["seats"]:
546
+ detail = seat["state"]
547
+ if "seconds" in seat:
548
+ detail += f" {_time(seat['seconds'])}"
549
+ if seat.get("phase"):
550
+ detail += f" · {seat['phase']}"
551
+ if seat["state"] == "failed" and seat.get("error"):
552
+ detail += f" · {seat['error']}"
553
+ lines.append(f" {seat['participant']:<10} {seat['model']:<34} {detail}")
554
+ data.pop("recipe")
555
+ _out(as_json, data, "\n".join(lines))
556
+
557
+
558
+ @app.command("report")
559
+ def report_command(run_ref: str = RUN, as_json: bool = JSON) -> None:
560
+ """The report, and the path to report.html."""
561
+ try:
562
+ folder = store.find_run(_root(), run_ref)
563
+ data = report.write(folder)
564
+ except (store.StoreError, fd.FindingError) as exc:
565
+ _fail(str(exc), as_json=as_json)
566
+ _out(as_json, data, report.render_text(data))
567
+
568
+
569
+ @app.command()
570
+ def runs(as_json: bool = JSON) -> None:
571
+ """Past runs, by recipe and material."""
572
+ rows = control.list_runs(_root())
573
+ lines = [
574
+ f"{row['run']:>4} {row['recipe']:<18} "
575
+ f"{', '.join(diffs.label(path) for path in row['material']):<28} "
576
+ f"{row['status']:<9} {row['started'] or ''}"
577
+ + (f" against run {row['prior']}" if row["prior"] is not None else "")
578
+ for row in rows
579
+ ]
580
+ _out(as_json, {"runs": rows}, "\n".join(lines) if lines else "This project has no runs yet.")
581
+
582
+
583
+ @app.command()
584
+ def stop(run_ref: str = RUN, as_json: bool = JSON) -> None:
585
+ """Stop a run."""
586
+ try:
587
+ folder = store.find_run(_root(), run_ref)
588
+ except store.StoreError as exc:
589
+ _fail(str(exc), as_json=as_json)
590
+ try:
591
+ control.stop(folder)
592
+ except control.ControlError as exc:
593
+ _fail(str(exc), as_json=as_json)
594
+ _out(as_json, {"run": folder.id, "stopping": True}, f"Run {folder.id} was told to stop.")
595
+
596
+
597
+ # -- the author's word on findings ---------------------------------------------------
598
+
599
+
600
+ def _batch(
601
+ findings: list[str] | None,
602
+ text: str | None,
603
+ from_file: Path | None,
604
+ *,
605
+ flag: str,
606
+ as_json: bool,
607
+ ) -> list[tuple[str, str]]:
608
+ """What a command was given: finding IDs with one ``flag`` text, or ``--from-file``'s
609
+ ``ID: text`` lines (blank lines and ``#`` comments skipped)."""
610
+ if from_file is None:
611
+ if not findings or text is None:
612
+ _fail(
613
+ f"Give one or more finding IDs with {flag} TEXT, or --from-file PATH.",
614
+ as_json=as_json,
615
+ )
616
+ given = [item.strip().upper() for item in findings]
617
+ twice = sorted({item for item in given if given.count(item) > 1})
618
+ if twice:
619
+ _fail(f"{', '.join(twice)} given more than once.", as_json=as_json)
620
+ return [(item, text) for item in findings]
621
+ if findings or text is not None:
622
+ _fail(f"Give finding IDs with {flag} TEXT, or --from-file PATH alone.", as_json=as_json)
623
+ try:
624
+ lines = from_file.read_text(encoding="utf-8").splitlines()
625
+ except (OSError, UnicodeDecodeError) as exc:
626
+ _fail(f"Cannot read {from_file}: {exc}", as_json=as_json)
627
+ pairs: list[tuple[str, str]] = []
628
+ seen: dict[str, int] = {}
629
+ for number, line in enumerate(lines, start=1):
630
+ stripped = line.strip()
631
+ if not stripped or stripped.startswith("#"):
632
+ continue
633
+ finding, colon, rest = stripped.partition(":")
634
+ if not colon or not finding.strip():
635
+ _fail(f"{from_file}, line {number}: write `ID: text`.", as_json=as_json)
636
+ key = finding.strip().upper()
637
+ if key in seen:
638
+ _fail(f"{from_file}, line {number}: {key} is on line {seen[key]} too.", as_json=as_json)
639
+ seen[key] = number
640
+ pairs.append((finding.strip(), rest.strip()))
641
+ if not pairs:
642
+ _fail(f"{from_file} names no finding.", as_json=as_json)
643
+ return pairs
644
+
645
+
646
+ def _targets(
647
+ folder: store.RunFolder, pairs: list[tuple[str, str]], *, as_json: bool
648
+ ) -> list[tuple[fd.Finding, str]]:
649
+ """Each finding with its text, all checked before anything is written."""
650
+ try:
651
+ outcome = fd.load(folder)
652
+ except (store.StoreError, fd.FindingError) as exc:
653
+ _fail(str(exc), as_json=as_json)
654
+ found: list[tuple[fd.Finding, str]] = []
655
+ unknown: list[str] = []
656
+ for finding_id, text in pairs:
657
+ try:
658
+ found.append((outcome.get(finding_id), text))
659
+ except fd.FindingError:
660
+ unknown.append(finding_id)
661
+ if unknown:
662
+ _fail(
663
+ f"No finding {', '.join(unknown)} in run {folder.id}; nothing was changed.",
664
+ as_json=as_json,
665
+ )
666
+ empty = [target.id for target, text in found if not text.strip()]
667
+ if empty:
668
+ _fail(f"{', '.join(empty)}: give a text for each; nothing was changed.", as_json=as_json)
669
+ return found
670
+
671
+
672
+ FINDINGS = typer.Argument(None, metavar="FINDING...", help="One or more finding IDs, e.g. F3.")
673
+ FROM_FILE = typer.Option(
674
+ None, "--from-file", help="A file of `ID: text` lines, one per finding, instead."
675
+ )
676
+
677
+
678
+ @app.command()
679
+ def dismiss(
680
+ findings: list[str] | None = FINDINGS,
681
+ note: str | None = typer.Option(None, "--note", help="Why the author rejects them."),
682
+ from_file: Path | None = FROM_FILE,
683
+ run_ref: str = RUN_OPTION,
684
+ as_json: bool = JSON,
685
+ ) -> None:
686
+ """Dismiss findings, with the author's approval once; later runs keep them dismissed.
687
+
688
+ Several findings for one reason: `dismiss F4 F5 --note "..."`. For different reasons,
689
+ `--from-file` with one `ID: note` line each.
690
+ """
691
+ root = _root()
692
+ pairs = _batch(findings, note, from_file, flag="--note", as_json=as_json)
693
+ try:
694
+ folder = store.find_run(root, run_ref)
695
+ except store.StoreError as exc:
696
+ _fail(str(exc), as_json=as_json)
697
+ targets = _targets(folder, pairs, as_json=as_json)
698
+ closed = [target.id for target, _text in targets if target.status != "open"]
699
+ if closed:
700
+ _fail(
701
+ f"{', '.join(closed)}: only an open finding is dismissed; nothing was changed.",
702
+ as_json=as_json,
703
+ )
704
+ if len(targets) == 1:
705
+ target, text = targets[0]
706
+ question = f"Dismiss {target.id} “{target.title}” with the note “{text}”?"
707
+ else:
708
+ question = f"Dismiss these {len(targets)} findings?\n" + "\n".join(
709
+ f" {target.id} “{target.title}”: {text}" for target, text in targets
710
+ )
711
+ _approve(
712
+ root,
713
+ "dismiss",
714
+ question,
715
+ as_json=as_json,
716
+ approval=_preset(root, as_json=as_json),
717
+ )
718
+ updated: list[fd.Finding] = []
719
+ for target, text in targets:
720
+ try:
721
+ updated.append(fd.dismiss(folder, target.id, text))
722
+ except fd.FindingError as exc:
723
+ _fail(str(exc), as_json=as_json)
724
+ report.write(folder)
725
+ _out(
726
+ as_json,
727
+ _one_or_many(updated, findings, from_file),
728
+ "\n".join(
729
+ f"{item.id} is dismissed in run {folder.id}; later runs keep it dismissed and show it."
730
+ for item in updated
731
+ ),
732
+ )
733
+
734
+
735
+ def _one_or_many(
736
+ updated: list[fd.Finding], findings: list[str] | None, from_file: Path | None
737
+ ) -> Any:
738
+ """One finding given as one ID prints its object, as before; anything else a list."""
739
+ items = [item.model_dump(mode="json") for item in updated]
740
+ return items[0] if from_file is None and findings is not None and len(findings) == 1 else items
741
+
742
+
743
+ @app.command()
744
+ def post(
745
+ run_ref: str = RUN,
746
+ finding: list[str] = typer.Option(
747
+ None, "--finding", "-f", help="A finding to send; repeat for more. Default: every open one."
748
+ ),
749
+ as_markdown: bool = typer.Option(
750
+ False, "--markdown", help="Print the findings as Markdown instead of posting them."
751
+ ),
752
+ as_json: bool = JSON,
753
+ ) -> None:
754
+ """Post a run's findings on the pull request it reviewed, with the user's approval."""
755
+ root = _root()
756
+ try:
757
+ folder = store.find_run(root, run_ref)
758
+ composed = posting.compose(root, folder, list(finding or []))
759
+ except (store.StoreError, posting.PostError) as exc:
760
+ _fail(str(exc), as_json=as_json)
761
+ described = {
762
+ "run": composed.run,
763
+ "to": composed.where,
764
+ "digest": composed.digest,
765
+ "findings": list(composed.findings),
766
+ "body": composed.body,
767
+ "comments": [vars(item) for item in composed.comments],
768
+ "warnings": list(composed.warnings),
769
+ }
770
+ if as_markdown or composed.destination is None:
771
+ note_ = (
772
+ ""
773
+ if as_markdown
774
+ else f"Run {composed.run} did not review a pull request, so here it is as Markdown.\n\n"
775
+ )
776
+ _out(as_json, {**described, "posted": False}, note_ + posting.markdown(composed))
777
+ return
778
+ if not as_json:
779
+ typer.echo(posting.preview(composed) + "\n")
780
+ via = _approve(
781
+ root,
782
+ "post",
783
+ f"Post this review of {len(composed.findings)} findings to {composed.where}?",
784
+ as_json=as_json,
785
+ approval=_preset(root, as_json=as_json),
786
+ )
787
+ try:
788
+ url = posting.send(root, folder, composed, approved_via=via)
789
+ except posting.PostError as exc:
790
+ _fail(str(exc), as_json=as_json)
791
+ _out(as_json, {**described, "posted": True, "url": url}, f"Posted to {composed.where}: {url}")
792
+
793
+
794
+ @app.command()
795
+ def note(
796
+ findings: list[str] | None = FINDINGS,
797
+ text: str | None = typer.Option(None, "--text", help="What was done about them."),
798
+ from_file: Path | None = FROM_FILE,
799
+ run_ref: str = RUN_OPTION,
800
+ as_json: bool = JSON,
801
+ ) -> None:
802
+ """Note what was done about findings. A note is a claim, never evidence.
803
+
804
+ Several findings with one note: `note F3 F4 --text "..."`. For different notes,
805
+ `--from-file` with one `ID: text` line each.
806
+ """
807
+ pairs = _batch(findings, text, from_file, flag="--text", as_json=as_json)
808
+ try:
809
+ folder = store.find_run(_root(), run_ref)
810
+ except store.StoreError as exc:
811
+ _fail(str(exc), as_json=as_json)
812
+ updated: list[fd.Finding] = []
813
+ for target, given in _targets(folder, pairs, as_json=as_json):
814
+ try:
815
+ updated.append(fd.note(folder, target.id, given))
816
+ except fd.FindingError as exc:
817
+ _fail(str(exc), as_json=as_json)
818
+ report.write(folder)
819
+ _out(
820
+ as_json,
821
+ _one_or_many(updated, findings, from_file),
822
+ "\n".join(
823
+ f"Noted on {item.id}. It stays {item.status} until a check finds evidence."
824
+ for item in updated
825
+ ),
826
+ )
827
+
828
+
829
+ # -- the host ------------------------------------------------------------------------
830
+
831
+
832
+ @app.command()
833
+ def setup(as_json: bool = JSON) -> None:
834
+ """Install the `discuss` skill and what makes each installed host ask before a run."""
835
+ root = _root()
836
+ approval = _preset(root, as_json=as_json)
837
+ strict = approval == "strict"
838
+ try:
839
+ changes = (
840
+ host.setup_claude(root, strict=strict)
841
+ + host.setup_codex(root, strict=strict)
842
+ + host.setup_antigravity(root, strict=strict)
843
+ + host.setup_cursor(root, strict=strict)
844
+ )
845
+ except host.HostError as exc:
846
+ _fail(str(exc), as_json=as_json)
847
+ text = "\n".join(f"- {change}" for change in changes) or "Already set up; nothing changed."
848
+ # Only under `strict` does a run need the plain command a host's rule asks about.
849
+ warning = host.path_warning() if strict else None
850
+ if warning:
851
+ text += f"\n! {warning}"
852
+ note = None if strict else _setup_note(approval)
853
+ if note:
854
+ text += f"\n{note}"
855
+ data = {
856
+ "project": str(root),
857
+ "changes": changes,
858
+ "warnings": [warning] if warning else [],
859
+ "approval": approval,
860
+ "note": note,
861
+ }
862
+ _out(as_json, data, text)
863
+
864
+
865
+ def _setup_note(approval: Approval) -> str:
866
+ """What `setup` says when it installs no approval rules or hooks."""
867
+ return (
868
+ f"approval is `{approval}`: comitia follows your host's own permission settings. "
869
+ "For a prompt before every run, add a rule in your host, or set `approval: strict` "
870
+ "in .comitia.yml and run `comitia setup` again."
871
+ )
872
+
873
+
874
+ @app.command(hidden=True)
875
+ def hook(
876
+ dialect: str = typer.Argument(
877
+ "", help="The host's hook dialect, past Claude Code's: antigravity or cursor."
878
+ ),
879
+ ) -> None:
880
+ """The host's hook before a tool runs, installed by `setup`: refuses a wrapped comitia
881
+ command (and, under Antigravity or Cursor, asks about the plain one)."""
882
+ if dialect and dialect not in host.DIALECTS:
883
+ _fail(f"Unknown hook dialect `{dialect}`: use {', '.join(host.DIALECTS)}.")
884
+ decision = host.hook_decision(sys.stdin.read(), dialect or None)
885
+ if decision is not None:
886
+ typer.echo(json.dumps(decision))
887
+
888
+
889
+ @app.command()
890
+ def ui(
891
+ port: int = typer.Option(0, "--port", help="The port to listen on; any free one by default."),
892
+ no_open: bool = typer.Option(False, "--no-open", help="Do not open the browser."),
893
+ ) -> None:
894
+ """Open the page: start reviews, watch them, read reports, edit recipes."""
895
+ from comitia import web
896
+
897
+ interactive = _interactive()
898
+ root = _root()
899
+ # Under `host` and `none` the host let `comitia ui` start, as it lets any command.
900
+ can_approve = interactive or _preset(root, as_json=False) in {"host", "none"}
901
+ service = web.Service(root, can_approve=can_approve, from_terminal=interactive)
902
+ try:
903
+ server = web.serve(service, port=port)
904
+ except OSError as exc:
905
+ _fail(f"Could not listen on port {port}: {exc}")
906
+ typer.echo(f"comitia for {service.root}\n {server.url()}\nCtrl+C stops it.")
907
+ if not can_approve:
908
+ typer.echo(
909
+ "Started without a terminal of yours (by an agent, say): the page shows "
910
+ "everything, but cannot start a run or dismiss a finding.",
911
+ err=True,
912
+ )
913
+ if interactive and not no_open:
914
+ import webbrowser
915
+
916
+ webbrowser.open(server.url())
917
+ try:
918
+ server.serve_forever()
919
+ except KeyboardInterrupt:
920
+ pass
921
+ finally:
922
+ server.server_close()
923
+
924
+
925
+ # Quick consultations from the terminal: no recipe, no plan, no findings. The flags,
926
+ # defaults and exit codes are crossby's, so `crossby converse` and `crossby panel` move here.
927
+ app.command()(discussion_cli.converse)
928
+ app.command()(discussion_cli.panel)
929
+
930
+
931
+ def _not_permitted(error: PermissionError) -> str:
932
+ """What to do when comitia may not use a file, most often inside an agent's sandbox."""
933
+ where = f"`{error.filename}`" if error.filename else "a file it needs"
934
+ return (
935
+ f"comitia was not allowed to use {where} ({error.strerror or error}). If an agent runs "
936
+ "comitia inside its sandbox, have it run comitia outside the sandbox: comitia keeps "
937
+ f"its records in {store.home()}, and the tools it starts need their own logins."
938
+ )
939
+
940
+
941
+ def main() -> None:
942
+ try:
943
+ app()
944
+ except PermissionError as error:
945
+ message = _not_permitted(error)
946
+ if "--json" in sys.argv[1:]:
947
+ typer.echo(json.dumps({"error": message}, ensure_ascii=False))
948
+ else:
949
+ typer.echo(message, err=True)
950
+ sys.exit(EXIT_ERROR)