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/control.py ADDED
@@ -0,0 +1,156 @@
1
+ """Starting, watching and stopping runs: shared by the command line and the page."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import signal
7
+ import subprocess
8
+ import sys
9
+ from datetime import UTC, datetime
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ from comitia import findings as fd
14
+ from comitia import plan as planning
15
+ from comitia import store
16
+ from comitia.discussion.journal import EventType
17
+
18
+ ACTIVE = frozenset({"starting", "running"})
19
+ # A run is `starting` only until its process takes over, which takes a moment.
20
+ STARTING_SECONDS = 120.0
21
+
22
+
23
+ class ControlError(Exception):
24
+ """A run cannot be controlled as asked."""
25
+
26
+
27
+ def spawn_background(run: store.RunFolder) -> None:
28
+ """Execute a prepared, approved run in a process of its own."""
29
+ log = (run.path / "run.log").open("ab")
30
+ subprocess.Popen(
31
+ [sys.executable, "-m", "comitia", "execute", str(run.id)],
32
+ cwd=run.root,
33
+ stdin=subprocess.DEVNULL,
34
+ stdout=log,
35
+ stderr=log,
36
+ start_new_session=True,
37
+ )
38
+
39
+
40
+ def alive(pid: Any) -> bool:
41
+ if not isinstance(pid, int):
42
+ return False
43
+ try:
44
+ os.kill(pid, 0)
45
+ except ProcessLookupError:
46
+ return False
47
+ except PermissionError:
48
+ return True
49
+ return True
50
+
51
+
52
+ def current_status(state: dict[str, Any]) -> str:
53
+ """A run's status; a run whose process died without ending is ``interrupted``."""
54
+ current = str(state.get("status", "unknown"))
55
+ if current == "running" and not alive(state.get("pid")):
56
+ return "interrupted"
57
+ since = state.get("resumed_at") if state.get("resuming") else state.get("started")
58
+ if current == "starting" and _age(since) > STARTING_SECONDS:
59
+ # Its process never took over: it died before it began.
60
+ return "interrupted"
61
+ return current
62
+
63
+
64
+ def _age(started: Any) -> float:
65
+ try:
66
+ return (datetime.now(tz=UTC) - datetime.fromisoformat(str(started))).total_seconds()
67
+ except ValueError:
68
+ return 0.0
69
+
70
+
71
+ def progress(folder: store.RunFolder) -> list[dict[str, Any]]:
72
+ """Each seat: waiting, writing, answered, stopped or failed, and for how long."""
73
+ plan = planning.Plan.model_validate(store.read_json(folder.plan))
74
+ seats: dict[str, dict[str, Any]] = {
75
+ seat.id: {"participant": seat.id, "model": planning.seat_label(seat), "state": "waiting"}
76
+ for seat in plan.seats
77
+ }
78
+ now = datetime.now(tz=UTC)
79
+ for event in store.read_events(folder.events):
80
+ seat = seats.get(str(event.data.get("participant")))
81
+ if seat is None:
82
+ continue
83
+ if event.type is EventType.TURN_STARTED:
84
+ seat.update(state="writing", phase=event.data.get("phase"), since=event.ts)
85
+ elif event.type is EventType.TURN_FINISHED:
86
+ ended = str(event.data.get("status"))
87
+ outcome = {"succeeded": "answered", "cancelled": "stopped"}.get(ended, "failed")
88
+ seat.update(state=outcome, error=event.data.get("error"))
89
+ seat["seconds"] = round(event.data.get("duration_seconds") or 0)
90
+ seat.pop("since", None)
91
+ for seat in seats.values():
92
+ since = seat.pop("since", None)
93
+ if since is not None:
94
+ seat["seconds"] = round((now - since).total_seconds())
95
+ return list(seats.values())
96
+
97
+
98
+ def status(folder: store.RunFolder) -> dict[str, Any]:
99
+ state = folder.read_state()
100
+ return {
101
+ "run": folder.id,
102
+ "recipe": state.get("recipe"),
103
+ "status": current_status(state),
104
+ "reason": state.get("reason"),
105
+ "seats": progress(folder),
106
+ }
107
+
108
+
109
+ def counts(outcome: fd.Outcome, prior: int | None) -> dict[str, int]:
110
+ """How many findings stand where; a first review has no resolved or new ones."""
111
+ items = outcome.findings
112
+ dismissed = sum(1 for item in items if item.status == "dismissed")
113
+ if prior is None:
114
+ return {"open": sum(1 for item in items if item.status == "open"), "dismissed": dismissed}
115
+ return {
116
+ "resolved": sum(1 for item in items if item.status == "resolved"),
117
+ "open": sum(1 for item in items if item.status == "open" and not item.new),
118
+ "dismissed": dismissed,
119
+ "new": sum(1 for item in items if item.new and item.status == "open"),
120
+ }
121
+
122
+
123
+ def list_runs(root: Path) -> list[dict[str, Any]]:
124
+ rows = []
125
+ for run_id in store.run_ids(root):
126
+ folder = store.RunFolder(root, run_id)
127
+ if not folder.exists():
128
+ continue
129
+ plan = store.read_json(folder.plan)
130
+ state = folder.read_state()
131
+ row: dict[str, Any] = {
132
+ "run": run_id,
133
+ "recipe": plan["recipe"],
134
+ "material": [item["path"] for item in plan["material"]],
135
+ "goal": plan.get("goal"),
136
+ "prior": plan.get("prior"),
137
+ "status": current_status(state),
138
+ "started": state.get("started"),
139
+ "ended": state.get("ended"),
140
+ "counts": None,
141
+ }
142
+ if folder.findings.is_file():
143
+ try:
144
+ row["counts"] = counts(fd.load(folder), plan.get("prior"))
145
+ except (fd.FindingError, store.StoreError, ValueError):
146
+ row["counts"] = None
147
+ rows.append(row)
148
+ return rows
149
+
150
+
151
+ def stop(folder: store.RunFolder) -> None:
152
+ state = folder.read_state()
153
+ pid = state.get("pid")
154
+ if state.get("status") != "running" or not isinstance(pid, int) or not alive(pid):
155
+ raise ControlError(f"Run {folder.id} is not running (status: {current_status(state)}).")
156
+ os.kill(pid, signal.SIGTERM)
comitia/diffs.py ADDED
@@ -0,0 +1,120 @@
1
+ """A diff as material: a Git range in the project, or a pull request.
2
+
3
+ The diff is written to a file in the project's store, outside the working tree,
4
+ and that file is the material. ``check`` names it in the command it prints, so
5
+ the run discusses the diff the user saw, not whatever the range means later.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import re
12
+ import subprocess
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ from comitia import store
17
+
18
+ _TIMEOUT = 60
19
+
20
+
21
+ class DiffError(Exception):
22
+ """The diff could not be produced."""
23
+
24
+
25
+ def _capture(command: list[str], root: Path, what: str) -> str:
26
+ try:
27
+ done = subprocess.run(command, cwd=root, capture_output=True, timeout=_TIMEOUT, check=False)
28
+ except FileNotFoundError:
29
+ raise DiffError(f"{what} needs `{command[0]}`, which is not installed.") from None
30
+ except subprocess.TimeoutExpired:
31
+ raise DiffError(f"{what} took longer than {_TIMEOUT}s.") from None
32
+ if done.returncode != 0:
33
+ reason = done.stderr.decode("utf-8", "replace").strip().splitlines()
34
+ raise DiffError(f"{what} failed: {reason[-1] if reason else 'no reason given'}")
35
+ return done.stdout.decode("utf-8", "replace")
36
+
37
+
38
+ def _folder(root: Path) -> Path:
39
+ return store.project_store(root) / "diffs"
40
+
41
+
42
+ def _save(root: Path, name: str, text: str, what: str, origin: dict[str, Any]) -> Path:
43
+ if not text.strip():
44
+ raise DiffError(f"{what} is empty; there is nothing to review.")
45
+ path = _folder(root) / f"{name}.diff"
46
+ path.parent.mkdir(parents=True, exist_ok=True)
47
+ path.write_text(text, encoding="utf-8")
48
+ path.with_suffix(".json").write_text(json.dumps(origin), encoding="utf-8")
49
+ return path
50
+
51
+
52
+ def source(root: Path, path: str | Path) -> dict[str, Any] | None:
53
+ """Where a saved diff came from: ``{"pr": 12}`` or ``{"diff": "main...HEAD"}``."""
54
+ saved = Path(path)
55
+ if saved.parent != _folder(root) or saved.suffix != ".diff":
56
+ return None
57
+ try:
58
+ origin = json.loads(saved.with_suffix(".json").read_text(encoding="utf-8"))
59
+ except (OSError, ValueError):
60
+ # Saved before origins were recorded: a pull request's diff still says so by name.
61
+ named = re.fullmatch(r"pr-(\d+)", saved.stem)
62
+ return {"pr": int(named[1])} if named else None
63
+ return origin if isinstance(origin, dict) else None
64
+
65
+
66
+ def label(path: str) -> str:
67
+ """A material path as people say it: a saved diff is named by where it came from."""
68
+ saved = Path(path)
69
+ if saved.parent.name == "diffs" and saved.suffix == ".diff":
70
+ pull = re.fullmatch(r"pr-(\d+)", saved.stem)
71
+ if pull:
72
+ return f"PR #{pull[1]}"
73
+ if saved.stem.startswith("diff-"):
74
+ return f"diff {saved.stem[len('diff-') :]}"
75
+ return path
76
+
77
+
78
+ def from_range(root: Path, revisions: str) -> Path:
79
+ """``git diff REVISIONS`` in the project, as a material file."""
80
+ revisions = revisions.strip()
81
+ if not revisions or revisions.startswith("-") or any(c.isspace() for c in revisions):
82
+ raise DiffError("--diff takes one Git range, such as main...HEAD.")
83
+ what = f"The diff {revisions}"
84
+ text = _capture(["git", "diff", "--no-color", "--no-ext-diff", revisions, "--"], root, what)
85
+ # Keeps what makes a range readable (HEAD~1..HEAD); a slash becomes an underscore.
86
+ slug = re.sub(r"[^A-Za-z0-9_.~^@-]+", "_", revisions)[:60].strip("_.") or "range"
87
+ return _save(root, f"diff-{slug}", text, what, {"diff": revisions})
88
+
89
+
90
+ def from_pull_request(root: Path, number: int) -> Path:
91
+ """``gh pr diff NUMBER`` for the project's repository, as a material file."""
92
+ if number <= 0:
93
+ raise DiffError("--pr takes a pull request number.")
94
+ what = f"The diff of pull request {number}"
95
+ return _save(root, f"pr-{number}", fetch_pull_request(root, number), what, {"pr": number})
96
+
97
+
98
+ def fetch_pull_request(root: Path, number: int) -> str:
99
+ """The pull request's diff as it is now."""
100
+ what = f"The diff of pull request {number}"
101
+ return _capture(["gh", "pr", "diff", str(number), "--color", "never"], root, what)
102
+
103
+
104
+ def pull_request_head(root: Path, number: int) -> str | None:
105
+ """Why the working tree is not the pull request's code, or ``None`` when it is."""
106
+ try:
107
+ head = _capture(
108
+ ["gh", "pr", "view", str(number), "--json", "headRefOid", "--jq", ".headRefOid"],
109
+ root,
110
+ "pr",
111
+ ).strip()
112
+ here = _capture(["git", "rev-parse", "HEAD"], root, "git").strip()
113
+ except DiffError:
114
+ return None
115
+ if head and head != here:
116
+ return (
117
+ f"The working tree is not at pull request {number}'s head ({head[:9]}): reviewers "
118
+ f"who read other files will see different code. `gh pr checkout {number}` fixes that."
119
+ )
120
+ return None
File without changes
@@ -0,0 +1,152 @@
1
+ """Run, continue and read panels and consultations on comitia's own engine.
2
+
3
+ Copied from crossby v0.71.0 (``crossby/api.py``): ``panel``,
4
+ ``continue_panel``, ``read_panel``, ``read_conversation`` and their helper
5
+ ``_with_journal``.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import threading
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ from comitia.discussion.converse import ConversationResult, ConverseError
15
+ from comitia.discussion.journal import EventSink
16
+ from comitia.discussion.panel import HumanInput, PanelError, PanelResult, PanelSpec
17
+
18
+
19
+ def panel(
20
+ spec: PanelSpec,
21
+ *,
22
+ on_event: EventSink | None = None,
23
+ events_path: Path | None = None,
24
+ inputs: HumanInput | None = None,
25
+ cancel: threading.Event | None = None,
26
+ ) -> PanelResult:
27
+ """Run a panel: a lead consults read-only members by id until it answers.
28
+
29
+ ``on_event`` receives every journal event, in order, on a dispatcher
30
+ thread (it can never slow a turn, and an exception drops it). With
31
+ ``events_path`` the events are also appended to that JSONL file as they
32
+ happen. Agent members are always read-only, and so is the lead with
33
+ ``Lead(read_only=True)``; see :class:`PanelSpec`. Human seats
34
+ (``HumanBackend``) get their replies from ``inputs``: call
35
+ ``inputs.submit(request_id, text)`` for each ``input.requested`` event.
36
+
37
+ Setting ``cancel`` stops the running sessions and starts no new one; the
38
+ result's ``stop_reason`` is then ``interrupted``, with every reply already
39
+ committed, and :func:`continue_panel` can carry on from its journal.
40
+
41
+ A journal problem never stops the panel: the result's ``journal_error``
42
+ says why the events file is missing or incomplete, and ``sink_errors``
43
+ lists each ``on_event`` failure that dropped the sink.
44
+ """
45
+ import uuid
46
+
47
+ from comitia.discussion.journal import Journal, JournalError, JournalExistsError
48
+ from comitia.discussion.panel import run_panel
49
+
50
+ try:
51
+ # Created exclusively and locked: a panel never appends to another
52
+ # run's journal, and a run refused before it starts leaves none behind.
53
+ journal = Journal(
54
+ uuid.uuid4().hex, path=events_path, sinks=[on_event] if on_event is not None else []
55
+ )
56
+ except JournalExistsError:
57
+ raise PanelError(
58
+ f"{events_path} already holds a journal; choose another events_path."
59
+ ) from None
60
+ except JournalError as exc:
61
+ raise PanelError(str(exc)) from None
62
+ try:
63
+ result = run_panel(spec, journal=journal, inputs=inputs, cancel=cancel)
64
+ finally:
65
+ journal.close()
66
+ return _with_journal(result, journal)
67
+
68
+
69
+ def continue_panel(
70
+ spec: PanelSpec,
71
+ events_path: Path,
72
+ *,
73
+ on_event: EventSink | None = None,
74
+ inputs: HumanInput | None = None,
75
+ cancel: threading.Event | None = None,
76
+ added_rounds: int | None = None,
77
+ ) -> PanelResult:
78
+ """Continue a panel that stopped without a final answer, from its journal.
79
+
80
+ ``spec`` is the panel as first run: the same seats, each with the same
81
+ tool, model and effort, or :class:`PanelError` is raised; its limits apply
82
+ afresh, and the lead may send up to ``added_rounds`` more messages (by
83
+ default ``spec.max_rounds``; 0 lets it only give its final answer).
84
+ Every seat resumes its own session, members that had not answered the
85
+ lead's last message are asked it again, and the events are appended to
86
+ ``events_path``, which no other process may be writing. The result holds
87
+ the whole panel, turns from before included.
88
+ """
89
+ from comitia.discussion.journal import Journal, JournalError
90
+ from comitia.discussion.panel import result_from_journal, run_panel
91
+
92
+ try:
93
+ journal, events = Journal.reopen(
94
+ events_path, sinks=[on_event] if on_event is not None else []
95
+ )
96
+ except JournalError as exc:
97
+ raise PanelError(str(exc)) from None
98
+ try:
99
+ prior = result_from_journal(spec, events)
100
+ result = run_panel(
101
+ spec,
102
+ journal=journal,
103
+ inputs=inputs,
104
+ cancel=cancel,
105
+ resume=prior,
106
+ added_rounds=added_rounds,
107
+ )
108
+ finally:
109
+ journal.close()
110
+ return _with_journal(result, journal)
111
+
112
+
113
+ def read_panel(spec: PanelSpec, events_path: Path) -> PanelResult:
114
+ """A panel's result as its journal records it, without running anything.
115
+
116
+ ``spec`` names the panel's seats, as for :func:`continue_panel`. A panel
117
+ that never recorded its end reads as ``interrupted``.
118
+ """
119
+ from comitia.discussion.journal import JournalError, read_journal
120
+ from comitia.discussion.panel import result_from_journal
121
+
122
+ try:
123
+ events = read_journal(events_path)
124
+ except JournalError as exc:
125
+ raise PanelError(str(exc)) from None
126
+ return result_from_journal(spec, events)
127
+
128
+
129
+ def read_conversation(events_path: Path) -> ConversationResult:
130
+ """A ``crossby converse`` consultation as its journal records it.
131
+
132
+ The goal, both sides with their tools, models and efforts, and every
133
+ committed message in order; a consultation that never recorded its end
134
+ reads as ``interrupted``. Raises :class:`ConverseError` when the file is
135
+ not a consultation's journal.
136
+ """
137
+ from comitia.discussion.converse import result_from_journal
138
+ from comitia.discussion.journal import JournalError, read_journal
139
+
140
+ try:
141
+ events = read_journal(events_path)
142
+ except JournalError as exc:
143
+ raise ConverseError(str(exc)) from None
144
+ return result_from_journal(events)
145
+
146
+
147
+ def _with_journal(result: PanelResult, journal: Any) -> PanelResult:
148
+ import dataclasses
149
+
150
+ return dataclasses.replace(
151
+ result, journal_error=journal.store_error, sink_errors=tuple(journal.sink_errors)
152
+ )