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
@@ -0,0 +1,382 @@
1
+ # Copied from crossby v0.71.0 (src/crossby/services/journal.py), imports aside.
2
+ """The event journal of a consultation: one ordered stream every view is built from.
3
+
4
+ Every consultation emits :class:`ConversationEvent` values with a sequence
5
+ number, appended to ``events.jsonl`` as they happen. The transcript,
6
+ ``--json`` and ``--continue`` are all rebuilt from that stream, and a UI can
7
+ follow it live, by reading the file or through an :data:`EventSink`.
8
+
9
+ Sinks never run inside a session: the journal hands each event to a
10
+ dispatcher thread, so a slow or failing sink can delay only itself, never a
11
+ turn, and a sink that raises is dropped and noted while the consultation goes
12
+ on. Events carry messages as written but never native output: progress events
13
+ name only the kind of step a tool took.
14
+
15
+ One process writes a journal at a time: a :class:`Journal` holds an exclusive
16
+ lock on its file from opening until :meth:`Journal.close`, and a second
17
+ writer is refused with :class:`JournalBusyError`. Readers never take it.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import contextlib
23
+ import json
24
+ import os
25
+ import queue
26
+ import stat
27
+ import sys
28
+ import threading
29
+ from collections.abc import Callable, Sequence
30
+ from datetime import UTC, datetime
31
+ from enum import StrEnum
32
+ from pathlib import Path
33
+ from typing import Any
34
+
35
+ from pydantic import BaseModel, ConfigDict, Field, ValidationError
36
+
37
+ SCHEMA_VERSION = 1
38
+ JOURNAL_FILE = "events.jsonl"
39
+
40
+
41
+ class EventType(StrEnum):
42
+ """What happened. See ``docs/ask.md`` for each type's ``data`` fields."""
43
+
44
+ CONVERSATION_STARTED = "conversation.started"
45
+ CONVERSATION_CONTINUED = "conversation.continued"
46
+ PARTICIPANT_READY = "participant.ready"
47
+ TURN_STARTED = "turn.started"
48
+ TURN_PROGRESS = "turn.progress"
49
+ TURN_FINISHED = "turn.finished"
50
+ MESSAGE_COMMITTED = "message.committed"
51
+ INPUT_REQUESTED = "input.requested"
52
+ INPUT_RESOLVED = "input.resolved"
53
+ CONVERSATION_FINISHED = "conversation.finished"
54
+
55
+
56
+ class ConversationEvent(BaseModel):
57
+ """One journal entry."""
58
+
59
+ model_config = ConfigDict(extra="forbid", frozen=True)
60
+
61
+ schema_version: int = SCHEMA_VERSION
62
+ run_id: str
63
+ seq: int = Field(ge=1)
64
+ ts: datetime
65
+ type: EventType
66
+ data: dict[str, Any] = Field(default_factory=dict)
67
+
68
+
69
+ EventSink = Callable[[ConversationEvent], None]
70
+
71
+
72
+ class JournalError(Exception):
73
+ """A journal file is not a readable consultation journal."""
74
+
75
+
76
+ class JournalBusyError(JournalError):
77
+ """Another process is writing this journal."""
78
+
79
+
80
+ class JournalExistsError(JournalError):
81
+ """A new journal was asked for where one already holds events."""
82
+
83
+
84
+ _STOP = object()
85
+ # Windows byte-range locks are mandatory, so the lock sits on a byte no event
86
+ # reaches: readers in other processes are never blocked.
87
+ _WINDOWS_LOCK_OFFSET = 1 << 30
88
+ _OPEN_FLAGS = os.O_RDWR | os.O_APPEND | getattr(os, "O_BINARY", 0)
89
+
90
+
91
+ class Journal:
92
+ """Sequences events, appends them to a file, and delivers them to sinks.
93
+
94
+ ``emit`` is safe from any thread and does only bounded work: the file
95
+ append and a queue put. Sinks run in order on one dispatcher thread.
96
+
97
+ With ``path``, the journal is new: an existing file that holds anything
98
+ raises :class:`JournalExistsError`, and one another process is writing
99
+ raises :class:`JournalBusyError`. A file it created but never wrote to is
100
+ removed on :meth:`close`, so a run that failed to start leaves nothing to
101
+ refuse or continue. Any other failure to open or append is kept in
102
+ ``store_error`` and the consultation goes on. :meth:`reopen` continues an
103
+ existing journal.
104
+ """
105
+
106
+ def __init__(
107
+ self,
108
+ run_id: str,
109
+ *,
110
+ path: Path | None = None,
111
+ sinks: Sequence[EventSink] = (),
112
+ start_seq: int = 1,
113
+ clock: Callable[[], datetime] = lambda: datetime.now(tz=UTC),
114
+ ) -> None:
115
+ self.run_id = run_id
116
+ self.path = path
117
+ self.events: list[ConversationEvent] = []
118
+ self.store_error: str | None = None
119
+ self.sink_errors: list[str] = []
120
+ self._seq = start_seq - 1
121
+ self._clock = clock
122
+ self._lock = threading.Lock()
123
+ self._fd: int | None = None
124
+ self._created = False
125
+ self._written = 0
126
+ if path is not None:
127
+ try:
128
+ self._fd, self._created = _create(path)
129
+ except OSError as exc:
130
+ self.store_error = f"could not open {path}: {exc}"
131
+ self._sinks = list(sinks)
132
+ self._queue: queue.Queue[object] = queue.Queue()
133
+ self._dispatcher: threading.Thread | None = None
134
+ if self._sinks:
135
+ self._dispatcher = threading.Thread(
136
+ target=self._dispatch, daemon=True, name="crossby-journal"
137
+ )
138
+ self._dispatcher.start()
139
+
140
+ @classmethod
141
+ def reopen(
142
+ cls,
143
+ path: Path,
144
+ *,
145
+ sinks: Sequence[EventSink] = (),
146
+ clock: Callable[[], datetime] = lambda: datetime.now(tz=UTC),
147
+ ) -> tuple[Journal, list[ConversationEvent]]:
148
+ """Lock an existing journal, then return it with its events, ready to append.
149
+
150
+ The lock is taken before reading, so the events are the whole journal
151
+ and no other process appends until :meth:`close`. An unfinished last
152
+ line is dropped and a complete one terminated. Raises
153
+ :class:`JournalBusyError` if another process is writing it, and
154
+ :class:`JournalError` if it cannot be read or holds no events.
155
+ """
156
+ try:
157
+ fd = os.open(path, _OPEN_FLAGS)
158
+ except OSError as exc:
159
+ raise JournalError(f"Cannot open {path}: {exc}") from None
160
+ try:
161
+ _claim(fd, path)
162
+ raw = _repair_tail(fd)
163
+ events = _parse(raw.decode("utf-8", errors="surrogateescape"), path)
164
+ if not events:
165
+ raise JournalError(f"{path} holds no events.")
166
+ except OSError as exc:
167
+ os.close(fd)
168
+ raise JournalError(f"Cannot open {path}: {exc}") from None
169
+ except BaseException:
170
+ os.close(fd)
171
+ raise
172
+ journal = cls(events[-1].run_id, sinks=sinks, start_seq=events[-1].seq + 1, clock=clock)
173
+ journal.path = path
174
+ journal._fd = fd
175
+ return journal, events
176
+
177
+ def emit(self, type_: EventType, **data: Any) -> ConversationEvent:
178
+ with self._lock:
179
+ self._seq += 1
180
+ event = ConversationEvent(
181
+ run_id=self.run_id, seq=self._seq, ts=self._clock(), type=type_, data=data
182
+ )
183
+ self.events.append(event)
184
+ if self._fd is not None:
185
+ try:
186
+ _write_all(self._fd, (event.model_dump_json() + "\n").encode())
187
+ self._written += 1
188
+ except OSError as exc:
189
+ # Keep the consultation going; the caller can report it.
190
+ self.store_error = f"could not append to {self.path}: {exc}"
191
+ if self._dispatcher is not None:
192
+ self._queue.put(event)
193
+ return event
194
+
195
+ def _dispatch(self) -> None:
196
+ while True:
197
+ item = self._queue.get()
198
+ if item is _STOP:
199
+ return
200
+ assert isinstance(item, ConversationEvent)
201
+ for sink in list(self._sinks):
202
+ try:
203
+ sink(item)
204
+ except Exception as exc:
205
+ self._sinks.remove(sink)
206
+ self.sink_errors.append(f"an event sink failed and was dropped: {exc!r}")
207
+
208
+ def close(self, timeout: float = 5.0) -> None:
209
+ """Deliver what is queued (up to ``timeout``), close the file and release it."""
210
+ if self._dispatcher is not None:
211
+ self._queue.put(_STOP)
212
+ self._dispatcher.join(timeout)
213
+ self._dispatcher = None
214
+ with self._lock:
215
+ fd, self._fd = self._fd, None
216
+ if fd is None:
217
+ return
218
+ if not (self._created and self._written == 0 and self.path is not None):
219
+ os.close(fd)
220
+ return
221
+ # Nothing was recorded: drop the empty file this journal created.
222
+ # Unlink while still holding the lock where the platform allows it.
223
+ if sys.platform == "win32":
224
+ os.close(fd)
225
+ with contextlib.suppress(OSError):
226
+ if os.stat(self.path).st_size == 0:
227
+ self.path.unlink()
228
+ return
229
+ with contextlib.suppress(OSError):
230
+ if _same_file(fd, self.path) and os.fstat(fd).st_size == 0:
231
+ self.path.unlink()
232
+ os.close(fd)
233
+
234
+
235
+ def _create(path: Path) -> tuple[int, bool]:
236
+ """Open a new journal at ``path``, locked; ``(fd, created)``.
237
+
238
+ An existing empty regular file is taken over (not ``created``); one that
239
+ holds anything raises :class:`JournalExistsError`.
240
+ """
241
+ path.parent.mkdir(parents=True, exist_ok=True)
242
+ try:
243
+ fd = os.open(path, _OPEN_FLAGS | os.O_CREAT | os.O_EXCL, 0o666)
244
+ created = True
245
+ except FileExistsError:
246
+ fd = os.open(path, _OPEN_FLAGS)
247
+ created = False
248
+ try:
249
+ if not stat.S_ISREG(os.fstat(fd).st_mode):
250
+ raise JournalError(f"{path} is not a regular file.")
251
+ _claim(fd, path)
252
+ if not created and os.fstat(fd).st_size:
253
+ raise JournalExistsError(f"{path} already holds a journal.")
254
+ except BaseException:
255
+ os.close(fd)
256
+ raise
257
+ return fd, created
258
+
259
+
260
+ def _claim(fd: int, path: Path) -> None:
261
+ """Take this process's exclusive lock on an open journal, without waiting.
262
+
263
+ The lock goes with the descriptor: closing it, or the process ending,
264
+ releases it, so a crash never leaves a journal claimed.
265
+ """
266
+ try:
267
+ if sys.platform == "win32":
268
+ import msvcrt
269
+
270
+ os.lseek(fd, _WINDOWS_LOCK_OFFSET, os.SEEK_SET)
271
+ msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)
272
+ else:
273
+ import fcntl
274
+
275
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
276
+ except OSError as exc:
277
+ if sys.platform == "win32" or isinstance(exc, BlockingIOError):
278
+ raise JournalBusyError(
279
+ f"Another process is writing {path}; wait for it to finish."
280
+ ) from None
281
+ raise
282
+
283
+
284
+ def _same_file(fd: int, path: Path) -> bool:
285
+ held, named = os.fstat(fd), os.stat(path, follow_symlinks=False)
286
+ return (held.st_dev, held.st_ino) == (named.st_dev, named.st_ino)
287
+
288
+
289
+ def _write_all(fd: int, data: bytes) -> None:
290
+ view = memoryview(data)
291
+ while view:
292
+ view = view[os.write(fd, view) :]
293
+
294
+
295
+ def _read_all(fd: int) -> bytes:
296
+ os.lseek(fd, 0, os.SEEK_SET)
297
+ chunks = []
298
+ while chunk := os.read(fd, 1 << 16):
299
+ chunks.append(chunk)
300
+ return b"".join(chunks)
301
+
302
+
303
+ def _repair_tail(fd: int) -> bytes:
304
+ """Make an open, locked journal safe to append to; return its bytes as kept.
305
+
306
+ A last line without its newline is either an append that did not finish
307
+ (dropped, as :func:`read_journal` ignores it) or a complete event that
308
+ only lacks its newline (kept, and terminated).
309
+ """
310
+ raw = _read_all(fd)
311
+ if not raw or raw.endswith(b"\n"):
312
+ return raw
313
+ cut = raw.rfind(b"\n") + 1
314
+ try:
315
+ ConversationEvent.model_validate(json.loads(raw[cut:]))
316
+ except (ValueError, ValidationError):
317
+ os.ftruncate(fd, cut)
318
+ return raw[:cut]
319
+ _write_all(fd, b"\n")
320
+ return raw + b"\n"
321
+
322
+
323
+ def read_journal(path: Path) -> list[ConversationEvent]:
324
+ """Every event in a journal file, in order.
325
+
326
+ A last line without its newline is an append the process did not finish
327
+ and is ignored; any other unreadable line raises :class:`JournalError`.
328
+ Reading takes no lock, so it is safe while a consultation is running.
329
+ """
330
+ try:
331
+ raw = path.read_text(encoding="utf-8", errors="surrogateescape")
332
+ except OSError as exc:
333
+ raise JournalError(f"Cannot read {path}: {exc}") from None
334
+ return _parse(raw, path)
335
+
336
+
337
+ def _parse(raw: str, path: Path) -> list[ConversationEvent]:
338
+ lines = raw.split("\n")
339
+ complete, last = lines[:-1], lines[-1]
340
+ events: list[ConversationEvent] = []
341
+ for number, line in enumerate(complete, start=1):
342
+ if not line.strip():
343
+ continue
344
+ try:
345
+ events.append(ConversationEvent.model_validate(json.loads(line)))
346
+ except (ValueError, ValidationError) as exc:
347
+ raise JournalError(f"{path} line {number} is not a journal event: {exc}") from None
348
+ if last.strip():
349
+ # A last line without its newline is an append that did not finish.
350
+ with contextlib.suppress(ValueError, ValidationError):
351
+ events.append(ConversationEvent.model_validate(json.loads(last)))
352
+ for expected, event in enumerate(events, start=1):
353
+ if event.seq != expected:
354
+ raise JournalError(f"{path} skips from event {expected - 1} to {event.seq}.")
355
+ if event.schema_version != SCHEMA_VERSION:
356
+ raise JournalError(f"{path} uses journal schema {event.schema_version}.")
357
+ return events
358
+
359
+
360
+ def finished(events: Sequence[ConversationEvent]) -> bool:
361
+ """Whether the last run recorded in ``events`` reached its end."""
362
+ for event in reversed(events):
363
+ if event.type is EventType.CONVERSATION_FINISHED:
364
+ return True
365
+ if event.type in {EventType.CONVERSATION_STARTED, EventType.CONVERSATION_CONTINUED}:
366
+ return False
367
+ return False
368
+
369
+
370
+ __all__ = [
371
+ "JOURNAL_FILE",
372
+ "SCHEMA_VERSION",
373
+ "ConversationEvent",
374
+ "EventSink",
375
+ "EventType",
376
+ "Journal",
377
+ "JournalBusyError",
378
+ "JournalError",
379
+ "JournalExistsError",
380
+ "finished",
381
+ "read_journal",
382
+ ]