k0ntrol-cli 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 (80) hide show
  1. k0ntrol/__init__.py +1 -0
  2. k0ntrol/agents.py +998 -0
  3. k0ntrol/cli.py +190 -0
  4. k0ntrol/config.py +330 -0
  5. k0ntrol/credentials.py +78 -0
  6. k0ntrol/defaults/config.yaml +23 -0
  7. k0ntrol/events.py +838 -0
  8. k0ntrol/frontends/__init__.py +1 -0
  9. k0ntrol/frontends/ask.py +218 -0
  10. k0ntrol/frontends/badges.py +228 -0
  11. k0ntrol/frontends/banner.py +128 -0
  12. k0ntrol/frontends/diffview.py +174 -0
  13. k0ntrol/frontends/editor.py +701 -0
  14. k0ntrol/frontends/klog.html +740 -0
  15. k0ntrol/frontends/klog.py +403 -0
  16. k0ntrol/frontends/logo.py +12 -0
  17. k0ntrol/frontends/mentions.py +29 -0
  18. k0ntrol/frontends/prompt.py +340 -0
  19. k0ntrol/frontends/render.py +485 -0
  20. k0ntrol/frontends/session.py +717 -0
  21. k0ntrol/frontends/setup.py +442 -0
  22. k0ntrol/frontends/terminal.py +396 -0
  23. k0ntrol/frontends/theme.py +24 -0
  24. k0ntrol/helpers.py +108 -0
  25. k0ntrol/init_flow.py +362 -0
  26. k0ntrol/langfuse.py +173 -0
  27. k0ntrol/memory/__init__.py +0 -0
  28. k0ntrol/memory/index.py +235 -0
  29. k0ntrol/memory/layout.py +66 -0
  30. k0ntrol/memory/python_extract.py +189 -0
  31. k0ntrol/memory/reflect.py +366 -0
  32. k0ntrol/memory/refresh.py +21 -0
  33. k0ntrol/memory/scan.py +538 -0
  34. k0ntrol/memory/session.py +145 -0
  35. k0ntrol/otel.py +429 -0
  36. k0ntrol/pricing.py +29 -0
  37. k0ntrol/prompts/chatty.md +17 -0
  38. k0ntrol/prompts/implementer.md +14 -0
  39. k0ntrol/prompts/planner.md +42 -0
  40. k0ntrol/prompts/researcher.md +20 -0
  41. k0ntrol/prompts/reviewer.md +34 -0
  42. k0ntrol/providers.py +718 -0
  43. k0ntrol/search.py +133 -0
  44. k0ntrol/tools/__init__.py +0 -0
  45. k0ntrol/tools/bulk_read.py +93 -0
  46. k0ntrol/tools/errors.py +50 -0
  47. k0ntrol/tools/fetch_url.py +212 -0
  48. k0ntrol/tools/net.py +317 -0
  49. k0ntrol/tools/path_guard.py +45 -0
  50. k0ntrol/tools/read.py +174 -0
  51. k0ntrol/tools/run_tests.py +66 -0
  52. k0ntrol/tools/runner.py +177 -0
  53. k0ntrol/tools/search_memory.py +32 -0
  54. k0ntrol/tools/slice_guard.py +166 -0
  55. k0ntrol/tools/slice_journal.py +481 -0
  56. k0ntrol/tools/tracker.py +115 -0
  57. k0ntrol/tools/web_search.py +199 -0
  58. k0ntrol/tools/write.py +123 -0
  59. k0ntrol/tracker/__init__.py +31 -0
  60. k0ntrol/tracker/github.py +371 -0
  61. k0ntrol/tracker/local_files.py +241 -0
  62. k0ntrol/tracker/protocol.py +210 -0
  63. k0ntrol/workflow/__init__.py +29 -0
  64. k0ntrol/workflow/change.py +605 -0
  65. k0ntrol/workflow/ci_gate.py +96 -0
  66. k0ntrol/workflow/context.py +137 -0
  67. k0ntrol/workflow/implement.py +1150 -0
  68. k0ntrol/workflow/nodes.py +331 -0
  69. k0ntrol/workflow/plan.py +675 -0
  70. k0ntrol/workflow/qa.py +98 -0
  71. k0ntrol/workflow/research.py +533 -0
  72. k0ntrol/workflow/routers.py +273 -0
  73. k0ntrol/workflow/run.py +1165 -0
  74. k0ntrol/workflow/state.py +146 -0
  75. k0ntrol/workflow/triage.py +269 -0
  76. k0ntrol_cli-0.1.0.dist-info/METADATA +154 -0
  77. k0ntrol_cli-0.1.0.dist-info/RECORD +80 -0
  78. k0ntrol_cli-0.1.0.dist-info/WHEEL +4 -0
  79. k0ntrol_cli-0.1.0.dist-info/entry_points.txt +2 -0
  80. k0ntrol_cli-0.1.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,1165 @@
1
+ """The run module: the one seam between the REPL and the graphs.
2
+
3
+ ``start(kind, input) -> Result`` and ``resume(run_id, decision) -> Result``,
4
+ where ``Result`` is ``Outcome(done|stuck|rejected)`` or
5
+ ``Pending(gate, what to show)``. Gates never read input inside the graph:
6
+ the REPL shows the ``Pending``, reads the answer and calls ``resume``.
7
+ Progress reaches the REPL through the event writer, never return values.
8
+
9
+ Checkpoints are a ``SqliteSaver`` at ``.k0-mem/checkpoints.sqlite`` with
10
+ ``durability="sync"``, strict msgpack and ``thread_id`` = run id, so a run
11
+ survives the process dying: a later ``resume`` compiles a fresh graph on
12
+ the same DB and picks up at the gate.
13
+
14
+ One run per checkout (ADR 0007). ``#<n>`` for the open run's own
15
+ work item gets it back as ``Unfinished`` (#46), and so does a text task
16
+ when the open run is of the same kind and has no work item to name: the
17
+ REPL asks whether to resume it, and ``abandon`` drops its checkpoint
18
+ thread on a ``n`` (#69: not while the tree is dirty). Any other second
19
+ run is refused with the command that resumes the open one, or a
20
+ git-worktree hint.
21
+ """
22
+
23
+ import os
24
+ import sqlite3
25
+ import time
26
+ from collections.abc import Callable
27
+ from dataclasses import dataclass, field
28
+ from pathlib import Path
29
+ from typing import Any, Literal, cast
30
+
31
+ from langchain.chat_models import init_chat_model
32
+ from langchain_core.callbacks import BaseCallbackHandler
33
+ from langchain_core.runnables import RunnableConfig
34
+ from langgraph.graph.state import CompiledStateGraph
35
+ from langgraph.types import Command
36
+
37
+ os.environ.setdefault("LANGGRAPH_STRICT_MSGPACK", "true")
38
+
39
+ from langgraph.checkpoint.sqlite import SqliteSaver # noqa: E402
40
+
41
+ from k0ntrol import __version__ # noqa: E402
42
+ from k0ntrol.agents import ALLOWLISTS # noqa: E402
43
+ from k0ntrol.events import ( # noqa: E402
44
+ EventWriter,
45
+ EventWriteError,
46
+ ProgressRenderer,
47
+ events_path,
48
+ new_run_id,
49
+ run_cost,
50
+ )
51
+ from k0ntrol.memory.refresh import refresh_memory # noqa: E402
52
+ from k0ntrol.tools.tracker import latest_agent_brief_comment # noqa: E402
53
+ from k0ntrol.memory.scan import ScanError # noqa: E402
54
+ from k0ntrol.otel import build_run_trace, otel_callbacks # noqa: E402
55
+ from k0ntrol.providers import error_lines, free_checks, has_errors # noqa: E402
56
+ from k0ntrol.tracker import ( # noqa: E402
57
+ Comment,
58
+ TRUSTED_ASSOCIATIONS,
59
+ Tracker,
60
+ TrackerError,
61
+ WorkItem,
62
+ is_k0_work_item,
63
+ is_trusted_author,
64
+ )
65
+ from k0ntrol.tracker.github import GhTracker, subprocess_runner # noqa: E402
66
+ from k0ntrol.workflow.change import ( # noqa: E402
67
+ current_branch,
68
+ dirty_paths,
69
+ drop_worktree_snapshot,
70
+ existing_branch,
71
+ has_origin,
72
+ is_git_repo,
73
+ snapshot_worktree,
74
+ worktree_snapshot_dir,
75
+ )
76
+ from k0ntrol.workflow.context import RunContext # noqa: E402
77
+ from k0ntrol.workflow.implement import build_implement_graph # noqa: E402
78
+ from k0ntrol.workflow.plan import ( # noqa: E402
79
+ DEFAULT_MAX_ROUND_QUESTIONS,
80
+ build_plan_graph,
81
+ )
82
+ from k0ntrol.workflow.research import ( # noqa: E402
83
+ build_research_graph,
84
+ is_map,
85
+ )
86
+ from k0ntrol.workflow.routers import DEFAULT_MAX_QUESTIONS # noqa: E402
87
+ from k0ntrol.workflow.triage import build_triage_graph # noqa: E402
88
+
89
+ _BUILDERS = {
90
+ "implement": build_implement_graph,
91
+ "plan": build_plan_graph,
92
+ "research": build_research_graph,
93
+ "triage": build_triage_graph,
94
+ }
95
+
96
+ # The roster each run kind uses; the free doctor checks gate start on it.
97
+ # Every agent gets the bulk_read tool, so the helper is part of each roster
98
+ # (#61, same gate /ask already applies).
99
+ _ROSTER = {
100
+ "implement": ("agents.implementer", "helpers.bulk_read"),
101
+ "plan": ("agents.planner", "helpers.bulk_read"),
102
+ "research": ("agents.planner", "helpers.bulk_read"),
103
+ "triage": ("agents.planner", "helpers.bulk_read"),
104
+ }
105
+
106
+ # Outer recursion limit: each loop iteration costs two super-steps at most.
107
+ _OUTER_STEPS_PER_ATTEMPT = 4
108
+ _OUTER_STEPS_SLACK = 8
109
+
110
+
111
+ class RunRefused(Exception):
112
+ """The run never started (or a resume answer was rejected)."""
113
+
114
+ def __init__(self, lines: str | list[str]) -> None:
115
+ self.lines = tuple([lines] if isinstance(lines, str) else lines)
116
+ super().__init__("\n".join(self.lines))
117
+
118
+
119
+ @dataclass(frozen=True)
120
+ class Outcome:
121
+ """A finished run: ``done``, ``stuck`` or ``rejected``.
122
+
123
+ ``ms`` and the counts are what the ``run_end`` event recorded — the
124
+ one-line cost the session shows (#150); a run a broken log ended has
125
+ none.
126
+ """
127
+
128
+ run: str
129
+ outcome: str
130
+ reason: str | None = None
131
+ node: str | None = None
132
+ redone: bool = False
133
+ ms: int | None = None
134
+ agent_runs: dict[str, int] = field(default_factory=dict)
135
+ validator_reds: int = 0
136
+ model_calls: int = 0
137
+
138
+
139
+ @dataclass(frozen=True)
140
+ class Pending:
141
+ """A run waiting at a gate: the question and answers to show."""
142
+
143
+ run: str
144
+ gate: str
145
+ question: str
146
+ answers: tuple[str, ...]
147
+ detail: str = ""
148
+ diff: str = "" # the change as a git diff, drawn file by file
149
+
150
+
151
+ @dataclass(frozen=True)
152
+ class Unfinished:
153
+ """A run is unfinished: resume it or abandon it."""
154
+
155
+ run: str
156
+ node: str
157
+
158
+
159
+ Result = Outcome | Pending | Unfinished
160
+
161
+
162
+ def checkpoints_path(root: Path) -> Path:
163
+ """The checkpoint DB for the project rooted at ``root``."""
164
+ return root / ".k0-mem" / "checkpoints.sqlite"
165
+
166
+
167
+ def start(
168
+ kind: str,
169
+ input: str,
170
+ *,
171
+ root: Path,
172
+ cfg: dict,
173
+ write: Callable[[str], None] | None = None,
174
+ init: Callable = init_chat_model,
175
+ check: Callable = free_checks,
176
+ scan: Callable = refresh_memory,
177
+ tracker=None,
178
+ tracing: Callable = build_run_trace,
179
+ session: str | None = None,
180
+ ) -> Result:
181
+ """Start a run of ``kind`` for ``input``.
182
+
183
+ ``/implement <task>`` runs the working-tree path (#116) and
184
+ ``/implement #<n>`` the tracker path on a ready work item (#117);
185
+ ``/plan <idea>`` and ``/plan #<n>`` run the Q&A definition (#120);
186
+ ``/research <question>`` charts a Map of decision tickets (#124) and
187
+ ``/research #<n>`` works the map's next unblocked one (#125);
188
+ ``/triage #<n>`` runs the Q&A and the outcome gate (#128).
189
+ Refuses — ``RunRefused`` — on bad usage, a missing tracker or work
190
+ item, an untrusted issue body, a work item not ready for an agent, a
191
+ dirty tree (``.k0-mem/`` ignored), failed doctor checks, a failed
192
+ rescan or another open run.
193
+ ``#<n>`` answers an open run for item ``n`` with ``Unfinished``.
194
+ """
195
+ if kind not in _BUILDERS:
196
+ raise RunRefused(f"unknown run: {kind}")
197
+ kind = cast(Literal["implement", "plan", "research", "triage"], kind) # _BUILDERS' keys
198
+ input_text = _checked_input(kind, input)
199
+ tracker = _tracker_for(
200
+ kind,
201
+ cfg,
202
+ root,
203
+ tracker,
204
+ required=_tracker_required(kind, input_text),
205
+ )
206
+ conn, saver = _open_checkpoints(root)
207
+ try:
208
+ ctx = RunContext(
209
+ root=root, cfg=cfg, kind=kind, init=init, tracker=tracker, scan=scan,
210
+ session=session,
211
+ )
212
+ busy = _busy_run(saver, ctx, input_text, tracker, root)
213
+ if busy is not None:
214
+ return busy
215
+ _doctor_gate(check, cfg, kind, root, input_text)
216
+ _rescan(scan, root)
217
+ item = _item_preflight(kind, input_text, tracker, root)
218
+ graph = _BUILDERS[kind](ctx, saver)
219
+ run_id = new_run_id()
220
+ _implement_preflight(kind, item, root, run_id)
221
+ _warn_local_only(kind, item, root, write)
222
+ _bind_events(ctx, root, run_id, write)
223
+ ctx.trace = tracing(run_id)
224
+ session_id = item.qualified_ref if item else _sitting_session(ctx)
225
+ config = _runnable(run_id, ctx, session_id)
226
+ try:
227
+ ctx.writer.run_start(
228
+ kind,
229
+ work_item=item.qualified_ref if item else None,
230
+ version=__version__,
231
+ session=session,
232
+ **_header(kind, item, input_text, root),
233
+ )
234
+ graph.invoke(
235
+ _initial_state(
236
+ kind,
237
+ input_text,
238
+ cfg,
239
+ item,
240
+ tracker.trusted_authors if tracker else (),
241
+ ),
242
+ config=config,
243
+ durability="sync",
244
+ )
245
+ return _finish(ctx, graph, run_id, config)
246
+ except EventWriteError:
247
+ return _log_failed(ctx, graph, config, run_id, session_id)
248
+ finally:
249
+ conn.close()
250
+
251
+
252
+ def resume(
253
+ run_id: str,
254
+ decision: str | None,
255
+ *,
256
+ root: Path,
257
+ cfg: dict,
258
+ write: Callable[[str], None] | None = None,
259
+ init: Callable = init_chat_model,
260
+ scan: Callable = refresh_memory,
261
+ tracker=None,
262
+ tracing: Callable = build_run_trace,
263
+ session: str | None = None,
264
+ ) -> Result:
265
+ """Continue run ``run_id`` with the human's ``decision``.
266
+
267
+ ``decision=None`` answers nothing: a run at a gate shows it again, a
268
+ run paused between nodes continues.
269
+
270
+ Rebuilds the graph and checkpoint connection from scratch — this is
271
+ also how a fresh process resumes a run after a crash or a ``/quit``
272
+ at a gate.
273
+ """
274
+ conn, saver = _open_checkpoints(root)
275
+ try:
276
+ kind = _run_kind(saver, run_id)
277
+ if kind is None or kind not in _BUILDERS:
278
+ raise RunRefused(f"no run {run_id} in this checkout")
279
+ tracker = _tracker_for(
280
+ kind,
281
+ cfg,
282
+ root,
283
+ tracker,
284
+ required=kind in ("research", "triage")
285
+ or _run_item_ref(saver, run_id) is not None,
286
+ )
287
+ ctx = RunContext(
288
+ root=root, cfg=cfg, kind=kind, init=init, tracker=tracker, scan=scan,
289
+ session=session,
290
+ )
291
+ graph = _BUILDERS[kind](ctx, saver)
292
+ state = graph.get_state(_thread(run_id))
293
+ _refuse_finished(state, run_id)
294
+ _refuse_revoked_app_authors(state.values, tracker)
295
+ _bind_events(ctx, root, run_id, write)
296
+ ctx.trace = tracing(run_id)
297
+ session_id = _session_id(ctx, state.values)
298
+ config = _runnable(run_id, ctx, session_id)
299
+ try:
300
+ ctx.writer.run_start(
301
+ kind,
302
+ resumed=True,
303
+ branch=current_branch(root),
304
+ version=__version__,
305
+ session=session,
306
+ )
307
+ _advance(ctx, graph, state, decision, config)
308
+ return _finish(ctx, graph, run_id, config)
309
+ except EventWriteError:
310
+ return _log_failed(ctx, graph, config, run_id, session_id)
311
+ finally:
312
+ conn.close()
313
+
314
+
315
+ def abandon(run_id: str, *, root: Path) -> None:
316
+ """Drop run ``run_id``'s checkpoint thread: the run can no longer resume.
317
+
318
+ Refuses — ``RunRefused``, the dirty-tree refusal — and keeps
319
+ the checkpoint while the tree is dirty: the fresh run that follows
320
+ would be refused too, and a run paused at the test gate holds
321
+ uncommitted files only its own checkpoint can finish. Files are never
322
+ touched.
323
+ """
324
+ conn, saver = _open_checkpoints(root)
325
+ try:
326
+ kind = _run_kind(saver, run_id)
327
+ if kind not in ("plan", "research", "triage"): # no uncommitted work
328
+ _refuse_dirty(root, f"/{kind}" if kind else "another run")
329
+ saver.delete_thread(run_id)
330
+ if kind == "implement":
331
+ drop_worktree_snapshot(root, worktree_snapshot_dir(root, run_id))
332
+ finally:
333
+ conn.close()
334
+
335
+
336
+ def open_runs(saver: SqliteSaver, ctx: RunContext) -> list[tuple[str, str, dict]]:
337
+ """``[(run_id, pending_node, values)]`` for every unfinished checkpoint
338
+ thread, each read through its own kind's graph: another kind's graph
339
+ does not know the thread's nodes and would see it as finished."""
340
+ graphs = {kind: build(ctx, saver) for kind, build in _BUILDERS.items()}
341
+ threads = {
342
+ tuple_.config["configurable"]["thread_id"]
343
+ for tuple_ in saver.list(None)
344
+ }
345
+ return [
346
+ open_run
347
+ for thread_id in sorted(threads)
348
+ if (open_run := _open_run(graphs, saver, thread_id)) is not None
349
+ ]
350
+
351
+
352
+ def _open_run(
353
+ graphs: dict[str, CompiledStateGraph], saver: SqliteSaver, thread_id: str
354
+ ) -> tuple[str, str, dict] | None:
355
+ """One checkpoint read through its own kind's graph — ``None`` for a
356
+ thread whose kind is gone (a retired workflow's checkpoint is dead
357
+ weight) or whose graph sees no pending node."""
358
+ graph = graphs.get(_run_kind(saver, thread_id) or "")
359
+ if graph is None:
360
+ return None
361
+ state = graph.get_state(_thread(thread_id))
362
+ if not state.next:
363
+ return None
364
+ return (thread_id, state.next[0], state.values)
365
+
366
+
367
+ def _open_checkpoints(root: Path) -> tuple[sqlite3.Connection, SqliteSaver]:
368
+ path = checkpoints_path(root)
369
+ path.parent.mkdir(parents=True, exist_ok=True)
370
+ conn = sqlite3.connect(str(path), check_same_thread=False)
371
+ return conn, SqliteSaver(conn)
372
+
373
+
374
+ def _busy_run(
375
+ saver: SqliteSaver, ctx: RunContext, input_text: str, tracker, root: Path
376
+ ) -> Unfinished | None:
377
+ """An open run answers ``#<n>`` for its own work item, and a run of its
378
+ own kind when it has no work item (a ``<task>``, ``<idea>`` or
379
+ ``<question>`` run before it names a work item).
380
+
381
+ Anything else is refused. The refusals for an ended work item (closed
382
+ issue, merged or closed PR) come before the resume prompt.
383
+ """
384
+ busy = open_runs(saver, ctx)
385
+ if not busy:
386
+ return None
387
+ if ctx.kind in ("implement", "plan", "research", "triage"):
388
+ same = _same_item_run(busy, input_text)
389
+ if same is not None:
390
+ _work_item(input_text, tracker, root, ctx.kind)
391
+ return Unfinished(run=same[0], node=same[1])
392
+ itemless = _itemless_run(busy, ctx.kind, input_text)
393
+ if itemless is not None:
394
+ return Unfinished(run=itemless[0], node=itemless[1])
395
+ run_id, node, values = busy[0]
396
+ raise RunRefused(
397
+ f"a run is already open in this checkout: {run_id} at {node}\n"
398
+ f"resume it with {_resume_command(values)}, or run k0 from another "
399
+ "git worktree: git worktree add <path>"
400
+ )
401
+
402
+
403
+ def _same_item_run(busy: list[tuple[str, str, dict]], input_text: str):
404
+ """The open ``(run, node)`` whose work item is the ``#<n>`` asked for."""
405
+ if not input_text.startswith("#"):
406
+ return None
407
+ ref = input_text[1:].strip()
408
+ for run_id, node, values in busy:
409
+ if values.get("item_ref") == ref:
410
+ return run_id, node
411
+ return None
412
+
413
+
414
+ def _itemless_run(busy: list[tuple[str, str, dict]], kind: str, input_text: str):
415
+ """The open ``(run, node)`` of ``kind`` with no work item, if any:
416
+ the same command with free text is the only way back to it."""
417
+ if input_text.startswith("#"):
418
+ return None
419
+ for run_id, node, values in busy:
420
+ if values.get("kind") == kind and not values.get("item_ref"):
421
+ return run_id, node
422
+ return None
423
+
424
+
425
+ def _resume_command(values: dict) -> str:
426
+ """The REPL command that offers an open run back."""
427
+ if values.get("item_ref"):
428
+ return f"/{values.get('kind', 'implement')} #{values['item_ref']}"
429
+ return f"/{values.get('kind')} <task>"
430
+
431
+
432
+ def _doctor_gate(
433
+ check: Callable, cfg: dict, kind: str, root: Path, input_text: str
434
+ ) -> None:
435
+ roster = _roster_for(kind, input_text)
436
+ checks = check(
437
+ cfg,
438
+ names=roster,
439
+ root=root,
440
+ services=_services_for(kind, input_text, roster),
441
+ )
442
+ if has_errors(checks):
443
+ raise RunRefused(error_lines(checks))
444
+
445
+
446
+ def _services_for(
447
+ kind: str, input_text: str, roster: tuple[str, ...]
448
+ ) -> tuple[str, ...]:
449
+ """The non-model services this run's path needs (#179).
450
+
451
+ ``"github"`` — ``gh`` auth and an ``origin`` remote — gates the same
452
+ paths that require a tracker: every ``/research`` and ``/triage`` run
453
+ and the ``#<n>`` forms of ``/implement`` and ``/plan``. ``"search"``
454
+ gates only when a rostered agent's allowlist carries ``web_search``,
455
+ so a missing optional search credential never blocks unaffected
456
+ agents.
457
+ """
458
+ services = []
459
+ if _tracker_required(kind, input_text):
460
+ services.append("github")
461
+ if _roster_searches(roster):
462
+ services.append("search")
463
+ return tuple(services)
464
+
465
+
466
+ def _roster_searches(roster: tuple[str, ...]) -> bool:
467
+ """True when a rostered agent's allowlist carries ``web_search``."""
468
+ return any(
469
+ "web_search" in ALLOWLISTS.get(label.split(".", 1)[-1], ())
470
+ for label in roster
471
+ )
472
+
473
+
474
+ def _tracker_required(kind: str, input_text: str) -> bool:
475
+ """The paths that cannot run trackerless — and so need GitHub auth and
476
+ an ``origin`` remote (#179): every ``/research`` and ``/triage`` run,
477
+ and the ``#<n>`` forms of ``/implement`` and ``/plan``."""
478
+ return kind in ("research", "triage") or (
479
+ kind in ("implement", "plan") and input_text.startswith("#")
480
+ )
481
+
482
+
483
+ def _roster_for(kind: str, input_text: str) -> tuple[str, ...]:
484
+ """The roster the doctor gate checks on this run's path:
485
+ ``/implement #<n>`` also runs REVIEWER (#118); the working-tree path
486
+ never does, so it must not be refused for a reviewer's provider.
487
+ ``/research #<n>`` may run RESEARCHER on a decision ticket (#125)."""
488
+ if kind == "implement" and input_text.startswith("#"):
489
+ return ("agents.implementer", "agents.reviewer", "helpers.bulk_read")
490
+ if kind == "research" and input_text.startswith("#"):
491
+ return ("agents.planner", "agents.researcher", "helpers.bulk_read")
492
+ return _ROSTER[kind]
493
+
494
+
495
+ def _rescan(scan: Callable, root: Path) -> None:
496
+ try:
497
+ scan(root)
498
+ except ScanError as error:
499
+ raise RunRefused(f"scan failed: {error}") from error
500
+
501
+
502
+ def _snapshot_worktree(root: Path, run_id: str) -> None:
503
+ """``/implement <task>``'s diff-gate ``n`` restores this pre-run snapshot."""
504
+ try:
505
+ snapshot_worktree(root, worktree_snapshot_dir(root, run_id))
506
+ except OSError as error:
507
+ raise RunRefused(f"could not snapshot the working tree: {error}") from error
508
+
509
+
510
+ def _bind_events(
511
+ ctx: RunContext, root: Path, run_id: str, write: Callable | None
512
+ ) -> None:
513
+ path = events_path(root)
514
+ path.parent.mkdir(parents=True, exist_ok=True)
515
+ writer = EventWriter(
516
+ path,
517
+ run=run_id,
518
+ progress=ProgressRenderer(write) if write is not None else None,
519
+ )
520
+ ctx.bind(writer)
521
+
522
+
523
+ def _checked_input(kind: str, input) -> str:
524
+ """Non-empty input in the kind's accepted forms, or a usage refusal."""
525
+ text = str(input).strip()
526
+ if not text or not _form_ok(kind, text):
527
+ raise RunRefused(_usage(kind))
528
+ return text
529
+
530
+
531
+ def _form_ok(kind: str, text: str) -> bool:
532
+ """The input shape a kind takes: ``/triage`` always names a work item,
533
+ the work-item commands take text or ``#<n>``, the rest take anything."""
534
+ if kind == "triage":
535
+ return text.startswith("#") and _usage_ok(text)
536
+ if kind in ("implement", "plan", "research"):
537
+ return _usage_ok(text)
538
+ return True
539
+
540
+
541
+ def _usage(kind: str) -> str:
542
+ if kind == "research":
543
+ return "usage: /research <question> | /research #<issue>"
544
+ if kind in ("implement", "plan"):
545
+ return f"usage: /{kind} <task> | /{kind} #<issue>"
546
+ if kind == "triage":
547
+ return "usage: /triage #<issue>"
548
+ return f"usage: /{kind} <task>"
549
+
550
+
551
+ def _usage_ok(input_text: str) -> bool:
552
+ """The work-item commands' two forms: free text, or ``#`` plus a number."""
553
+ return not input_text.startswith("#") or input_text[1:].strip().isdigit()
554
+
555
+
556
+ def _implement_preflight(kind: str, item, root: Path, run_id: str) -> None:
557
+ """The working-tree path snapshots the tree for its diff gate; the
558
+ tracker path works on a branch it cuts itself, so there is nothing to
559
+ restore to.
560
+ """
561
+ if kind != "implement":
562
+ return
563
+ if not is_git_repo(root):
564
+ raise RunRefused("/implement needs a git repository")
565
+ if item is None:
566
+ _snapshot_worktree(root, run_id)
567
+
568
+
569
+ def _header(kind: str, item, input_text: str, root: Path) -> dict:
570
+ """What the run header names: a ``/research <question>`` its question,
571
+ every other run its branch (#205)."""
572
+ if kind == "research" and item is None:
573
+ return {"question": input_text}
574
+ return {"branch": current_branch(root)}
575
+
576
+
577
+ _LOCAL_ONLY = (
578
+ "no 'origin' remote: the change stays on your local branch; nothing is pushed"
579
+ )
580
+
581
+
582
+ def _warn_local_only(kind: str, item, root: Path, write) -> None:
583
+ """A working-tree ``/implement`` runs without a remote, but says so
584
+ before any model call (#179, #204)."""
585
+ if kind == "implement" and item is None and write and not has_origin(root):
586
+ write(_LOCAL_ONLY)
587
+
588
+
589
+ def _tracker_for(kind: str, cfg: dict, root: Path, tracker, *, required: bool):
590
+ """A work-item run cannot run trackerless: build the configured adapter.
591
+
592
+ ``/plan <idea>`` never requires one, but the question-limit hand off
593
+ publishes a Map (#127), so a configured tracker joins a plan run too.
594
+ """
595
+ if tracker is not None:
596
+ return tracker
597
+ if not required:
598
+ return _optional_tracker(kind, cfg, root)
599
+ return _required_tracker(kind, cfg, root)
600
+
601
+
602
+ def _optional_tracker(kind: str, cfg: dict, root: Path):
603
+ """The tracker a run may use but needn't: a configured GitHub tracker
604
+ joins ``/plan`` runs so the hand off can publish (#127)."""
605
+ if kind == "plan" and cfg.get("tracker") == "github":
606
+ return GhTracker(
607
+ subprocess_runner(root), trusted_authors=_trusted_authors(cfg)
608
+ )
609
+ return None
610
+
611
+
612
+ def _required_tracker(kind: str, cfg: dict, root: Path):
613
+ """The configured adapter or the refusal: only GitHub ships in 0.1.0."""
614
+ unshipped = next(
615
+ (cfg[key] for key in ("vcs", "tracker") if cfg.get(key, "github") != "github"), None
616
+ )
617
+ if unshipped:
618
+ raise RunRefused(f"/{kind} only works with GitHub in 0.1.0, not {unshipped}")
619
+ if cfg.get("tracker") is None:
620
+ raise RunRefused(f"/{kind} needs a tracker; run k0 init --tracker github")
621
+ return GhTracker(
622
+ subprocess_runner(root), trusted_authors=_trusted_authors(cfg)
623
+ )
624
+
625
+
626
+ def _trusted_authors(cfg: dict) -> tuple[str, ...]:
627
+ """The config's expressly trusted author logins (#176, ADR 0016)."""
628
+ return tuple(cfg.get("trusted_authors") or ())
629
+
630
+
631
+ def _log_failed(
632
+ ctx: RunContext, graph, config: RunnableConfig, run_id: str, session_id
633
+ ) -> Outcome:
634
+ """A broken event log ends the run stuck (events contract, #16).
635
+
636
+ There is no ``run_end`` — the log cannot take it. ``/implement``'s
637
+ checkpoint is left where the write failed: still resumable, so its
638
+ rollback snapshot stays until the graph actually ends.
639
+ """
640
+ state = graph.get_state(config)
641
+ _trace_finish(ctx, "stuck", session_id, state.values)
642
+ if ctx.kind == "implement" and not state.next:
643
+ drop_worktree_snapshot(ctx.root, worktree_snapshot_dir(ctx.root, run_id))
644
+ return Outcome(run=run_id, outcome="stuck")
645
+
646
+
647
+ def _item_preflight(kind: str, input_text: str, tracker, root: Path):
648
+ """The work-item commands' last refusals: dirty tree, then the item read.
649
+
650
+ ``/implement`` goes through it only for ``#<n>``, whose
651
+ item must also be ready for an agent (#117). ``/plan`` and ``/research``
652
+ read the ``#<n>`` item but never touch the tree, so no dirt or label is
653
+ checked — planning is what readies work (#120), and the map a research
654
+ run works is the carrier it indexes onto (#125). ``/triage`` reads it
655
+ the same way (#128). A ``/research #<n>`` carrier must be a Map —
656
+ another parent's children are no decision tickets.
657
+ """
658
+ if kind in ("plan", "research", "triage"):
659
+ return _read_only_item(kind, input_text, tracker, root)
660
+ if kind != "implement" or not input_text.startswith("#"):
661
+ return None
662
+ _refuse_dirty(root, f"/{kind}")
663
+ item = _work_item(input_text, tracker, root, kind)
664
+ if kind == "implement" and item is not None:
665
+ _refuse_not_ready(item, tracker)
666
+ return item
667
+
668
+
669
+ def _read_only_item(kind: str, input_text: str, tracker, root: Path):
670
+ """The ``#<n>`` read for the planning kinds — no tree, no label; but
671
+ a ``/research #<n>`` carrier must be a Map, and ``/plan #<n>`` on
672
+ a Map waits for its decision tickets to be all decided (#126)."""
673
+ item = _work_item(input_text, tracker, root, kind)
674
+ if kind == "research" and item is not None:
675
+ _refuse_not_map(item)
676
+ if kind == "plan" and item is not None and is_map(item):
677
+ _refuse_open_decisions(item, tracker)
678
+ return item
679
+
680
+
681
+ def _refuse_open_decisions(item, tracker) -> None:
682
+ """``/plan #<n>`` on a Map drafts the spec from its decisions —
683
+ only once they are all decided; a map with decision tickets still
684
+ open is refused, naming how many (#126)."""
685
+ try:
686
+ children = tracker.list_children(item.ref)
687
+ pending = sum(
688
+ 1 for child in children if _undecided(child, item, tracker)
689
+ )
690
+ except TrackerError as error:
691
+ raise RunRefused(str(error)) from error
692
+ if pending:
693
+ raise RunRefused(
694
+ f"map #{item.ref} still has {pending} open decision "
695
+ f"ticket{'s' if pending != 1 else ''} — work them "
696
+ f"with /research #{item.ref} first"
697
+ )
698
+
699
+
700
+ def _undecided(child, item, tracker) -> bool:
701
+ """A decision ticket that still counts: open, or closed before its
702
+ decision was indexed on the map — a run that died between closing
703
+ the ticket and writing the map line must not be planned over (#126)."""
704
+ if child.state == "open":
705
+ return True
706
+ return tracker.read_work_item(child.ref).url not in item.body
707
+
708
+
709
+ def _refuse_not_map(item) -> None:
710
+ """``/research #<n>`` works a Map's decision tickets — a work item
711
+ whose body carries no Map sections has none to pick."""
712
+ if is_map(item):
713
+ return
714
+ raise RunRefused(
715
+ f"work item #{item.ref} is not a Map — /research #<n> works a "
716
+ "Map's decision tickets; chart one with /research <question>"
717
+ )
718
+
719
+
720
+ def _refuse_not_ready(item, tracker) -> None:
721
+ """``/implement #<n>`` runs ready work only: the label, or a ticket k0 created."""
722
+ if is_k0_work_item(item) or "ready-for-agent" in tracker.read_labels(item.ref):
723
+ return
724
+ raise RunRefused(
725
+ f"work item #{item.ref} is not ready for an agent "
726
+ f"(no ready-for-agent label) — run /triage #{item.ref} first"
727
+ )
728
+
729
+
730
+ def _refuse_dirty(root: Path, what: str) -> None:
731
+ dirty = dirty_paths(root)
732
+ if dirty:
733
+ raise RunRefused(
734
+ [f"refusing to run {what} on a dirty working tree:", *dirty]
735
+ )
736
+
737
+
738
+ def _work_item(input_text: str, tracker, root: Path, kind: str):
739
+ """The ``#<n>`` commands' issue: must exist and come from a trusted author."""
740
+ if not input_text.startswith("#"):
741
+ return None
742
+ ref = input_text[1:].strip()
743
+ try:
744
+ item = tracker.read_work_item(ref)
745
+ _refuse_ended_work(item, tracker, root)
746
+ except TrackerError as error:
747
+ raise RunRefused(str(error)) from error
748
+ if not is_trusted_author(
749
+ item.author, item.author_association, tracker.trusted_authors
750
+ ):
751
+ raise RunRefused(
752
+ f"work item #{ref} was written by {item.author} "
753
+ f"({item.author_association}), not a trusted author — "
754
+ f"{_untrusted_next_step(kind)}"
755
+ )
756
+ return item
757
+
758
+
759
+ def _untrusted_next_step(kind: str) -> str:
760
+ """The refile step an untrusted refusal names: ``/triage`` takes only
761
+ ``#<n>``, so it routes through a new trusted-author issue (#180)."""
762
+ if kind == "triage":
763
+ return "restate the work yourself as a new issue, then /triage #<new-issue>"
764
+ return f"restate the work yourself: /{kind} <task>"
765
+
766
+
767
+ def _refuse_ended_work(item, tracker, root: Path) -> None:
768
+ """A closed issue, or a merged or closed PR, is not worked on again."""
769
+ if item.state != "open":
770
+ raise TrackerError(f"work item #{item.ref} is {item.state}")
771
+ branch = existing_branch(root, item.ref)
772
+ change = tracker.read_change(branch) if branch else None
773
+ if change is not None and change.state != "open":
774
+ raise TrackerError(
775
+ f"pull request #{change.ref} for {branch} is {change.state}"
776
+ )
777
+
778
+
779
+ def _initial_state(
780
+ kind: str,
781
+ input_text: str,
782
+ cfg: dict,
783
+ item: WorkItem | None = None,
784
+ trusted_authors: tuple[str, ...] = (),
785
+ ) -> dict:
786
+ brief = (
787
+ latest_agent_brief_comment(item, trusted_authors)
788
+ if kind == "implement" and item is not None
789
+ else None
790
+ )
791
+ state = {
792
+ "kind": kind,
793
+ "task": str(input_text).strip(),
794
+ "start_ms": _now_ms(),
795
+ "max_attempts": cfg.get("max_attempts", 2),
796
+ "validator_ok": False,
797
+ "limit": None,
798
+ "required_app_authors": _required_app_authors(item, brief),
799
+ }
800
+ state.update(_kind_state(kind, cfg, item, brief))
801
+ return state
802
+
803
+
804
+ def _required_app_authors(*sources: WorkItem | Comment | None) -> list[str]:
805
+ """Authors of cached intake content admitted solely by the App allowlist."""
806
+ return sorted({
807
+ source.author
808
+ for source in sources
809
+ if source is not None and source.author_association not in TRUSTED_ASSOCIATIONS
810
+ })
811
+
812
+
813
+ def _kind_state(
814
+ kind: str, cfg: dict, item: WorkItem | None, brief: Comment | None
815
+ ) -> dict:
816
+ """The per-kind fields layered over the shared run state."""
817
+ if kind == "implement":
818
+ return _implement_state(item, brief)
819
+ if kind == "plan":
820
+ return _plan_state(cfg, item)
821
+ if kind == "research":
822
+ return _research_state(cfg, item)
823
+ if kind == "triage":
824
+ return _triage_state(cfg, item)
825
+ return {}
826
+
827
+
828
+ def _research_state(cfg: dict, item) -> dict:
829
+ """``/research``'s fields: the charted map's own, plus — for
830
+ ``/research #<n>`` — the decision-ticket path layered on top (#125)."""
831
+ state: dict = {"map": None, "decision_refs": [], "planner_attempts": 0}
832
+ if item is not None:
833
+ state.update(_research_item_state(cfg, item))
834
+ return state
835
+
836
+
837
+ def _triage_state(cfg: dict, item) -> dict:
838
+ """The ``/triage`` fields layered over the shared run state (#128).
839
+
840
+ Triage always names a work item: its body is what PLANNER reads and
841
+ its title joins the briefs.
842
+ """
843
+ state = {
844
+ "rounds": [],
845
+ "questions": [],
846
+ "planner_attempts": 0,
847
+ "max_round_questions": cfg.get(
848
+ "max_round_questions", DEFAULT_MAX_ROUND_QUESTIONS
849
+ ),
850
+ "max_questions": cfg.get("max_questions", DEFAULT_MAX_QUESTIONS),
851
+ "triage_outcome": None,
852
+ "outcome_attempts": 0,
853
+ "triage_approved": False,
854
+ "triage_rejections": [],
855
+ "triage_feedback": None,
856
+ }
857
+ if item is not None:
858
+ state.update(
859
+ {"task": item.body, "item_ref": item.ref, "item_title": item.title}
860
+ )
861
+ return state
862
+
863
+
864
+ def _research_item_state(cfg: dict, item) -> dict:
865
+ """The ``/research #<n>`` fields layered over the shared run state
866
+ (#125): the map's next unblocked decision ticket and the short Q&A a
867
+ Q&A ticket may take before its gate.
868
+ """
869
+ return {
870
+ "task": item.body,
871
+ "item_ref": item.ref,
872
+ "item_title": item.title,
873
+ "decision": None,
874
+ "finding": None,
875
+ "proposal": "",
876
+ "decided": "",
877
+ "researcher_attempts": 0,
878
+ "rounds": [],
879
+ "questions": [],
880
+ "max_round_questions": cfg.get(
881
+ "max_round_questions", DEFAULT_MAX_ROUND_QUESTIONS
882
+ ),
883
+ "max_questions": cfg.get("max_questions", DEFAULT_MAX_QUESTIONS),
884
+ }
885
+
886
+
887
+ def _plan_state(cfg: dict, item) -> dict:
888
+ """The ``/plan`` fields layered over the shared run state (#120).
889
+
890
+ For ``/plan #<n>`` the idea is the work item's body; the title goes to
891
+ PLANNER's brief alongside it.
892
+ """
893
+ state = {
894
+ "rounds": [],
895
+ "questions": [],
896
+ "planner_attempts": 0,
897
+ "max_round_questions": cfg.get(
898
+ "max_round_questions", DEFAULT_MAX_ROUND_QUESTIONS
899
+ ),
900
+ "max_questions": cfg.get("max_questions", DEFAULT_MAX_QUESTIONS),
901
+ "spec": None,
902
+ "spec_attempts": 0,
903
+ "spec_approved": False,
904
+ "spec_rejections": [],
905
+ "spec_feedback": None,
906
+ "ticket_size": cfg.get("ticket_size", "small"),
907
+ "tickets": None,
908
+ "tickets_approved": False,
909
+ "tickets_attempts": 0,
910
+ "ticket_rejections": [],
911
+ "ticket_feedback": None,
912
+ "decided_map": False,
913
+ }
914
+ if item is not None:
915
+ state.update(
916
+ {"task": item.body, "item_ref": item.ref, "item_title": item.title}
917
+ )
918
+ state["decided_map"] = is_map(item)
919
+ return state
920
+
921
+
922
+ def _implement_state(item: WorkItem | None, brief: Comment | None) -> dict:
923
+ """The ``/implement`` fields layered over the shared run state.
924
+
925
+ For ``/implement #<n>`` the run's task is the item's latest agent
926
+ brief, or its body when there is none (#117, ADR 0012).
927
+ """
928
+ state = {
929
+ "files": [],
930
+ "seam_attempts": 0,
931
+ "seam_proposal": "",
932
+ "seam_questions": "",
933
+ "seam_approved": False,
934
+ "seam_feedback": None,
935
+ "seam_answers": None,
936
+ "implementer_attempts": 0,
937
+ }
938
+ if item is not None:
939
+ state.update(
940
+ {
941
+ "task": brief.body if brief is not None else item.body,
942
+ "item_ref": item.ref,
943
+ "item_title": item.title,
944
+ "conventions_review_attempts": 0,
945
+ "contract_review_attempts": 0,
946
+ "conventions_review_round": 0,
947
+ "contract_review_round": 0,
948
+ }
949
+ )
950
+ return state
951
+
952
+
953
+ def _runnable(run_id: str, ctx: RunContext, session_id=None) -> RunnableConfig:
954
+ config = _thread(run_id)
955
+ assert ctx.handler is not None
956
+ callbacks: list[BaseCallbackHandler] = [ctx.handler]
957
+ config["callbacks"] = callbacks
958
+ # Always explicit (langgraph's default is a safety net, not a budget):
959
+ # each loop-back costs at most two super-steps per agent node.
960
+ attempts = ctx.cfg.get("max_attempts", 2)
961
+ slack = 16 if ctx.kind == "implement" else _OUTER_STEPS_SLACK
962
+ config["recursion_limit"] = _OUTER_STEPS_PER_ATTEMPT * attempts + slack
963
+ if ctx.trace is not None and ctx.trace.handler is not None:
964
+ callbacks.append(ctx.trace.handler)
965
+ config["metadata"] = _langfuse_metadata(ctx.kind, session_id)
966
+ callbacks.extend(otel_callbacks(ctx.trace))
967
+ return config
968
+
969
+
970
+ def _langfuse_metadata(kind: str, session_id) -> dict:
971
+ """Root-run metadata the Langfuse handler reads: session + kind tag."""
972
+ metadata = {"langfuse_tags": [kind]}
973
+ if session_id:
974
+ metadata["langfuse_session_id"] = session_id
975
+ return metadata
976
+
977
+
978
+ def _session_id(ctx: RunContext, values: dict) -> str | None:
979
+ """The run's Langfuse session: its work item, resolved through the
980
+ tracker, else the REPL sitting."""
981
+ ref = values.get("item_ref")
982
+ if not ref or ctx.tracker is None:
983
+ return _sitting_session(ctx)
984
+ try:
985
+ return ctx.tracker.read_work_item(ref).qualified_ref
986
+ except TrackerError:
987
+ return _sitting_session(ctx)
988
+
989
+
990
+ def _sitting_session(ctx: RunContext) -> str | None:
991
+ """``/implement <task>``, ``/plan <idea>`` and
992
+ ``/research <question>`` have no work item: their session is the
993
+ sitting. A ``#<n>`` run's is always the work item, which outlives any
994
+ one sitting."""
995
+ return ctx.session if ctx.kind in ("implement", "plan", "research") else None
996
+
997
+
998
+ def _trace_metadata(ctx: RunContext, values: dict) -> dict:
999
+ """The trace's metadata (#49): branch, change URL and k0 version."""
1000
+ metadata = {"k0_version": __version__}
1001
+ branch = values.get("branch") or current_branch(ctx.root)
1002
+ if branch:
1003
+ metadata["branch"] = branch
1004
+ if values.get("change_url"):
1005
+ metadata["change_url"] = values["change_url"]
1006
+ return metadata
1007
+
1008
+
1009
+ def _trace_finish(ctx: RunContext, outcome: str, session_id, values: dict) -> None:
1010
+ """Close the run's trace — enabled-only, never raising (#49)."""
1011
+ if ctx.trace is None:
1012
+ return
1013
+ ctx.trace.finish(
1014
+ kind=ctx.kind,
1015
+ outcome=outcome,
1016
+ session_id=session_id,
1017
+ metadata=_trace_metadata(ctx, values),
1018
+ )
1019
+
1020
+
1021
+ def _thread(run_id: str) -> RunnableConfig:
1022
+ return {"configurable": {"thread_id": run_id}}
1023
+
1024
+
1025
+ def _run_kind(
1026
+ saver: SqliteSaver, run_id: str
1027
+ ) -> Literal["implement", "plan", "research", "triage"] | None:
1028
+ """The run's kind, read from the checkpoint before a graph is built."""
1029
+ tuple_ = saver.get_tuple(_thread(run_id))
1030
+ if tuple_ is None:
1031
+ return None
1032
+ return tuple_.checkpoint["channel_values"].get("kind")
1033
+
1034
+
1035
+ def _run_item_ref(saver: SqliteSaver, run_id: str) -> str | None:
1036
+ """The checkpointed run's work item ref, if it carries one."""
1037
+ tuple_ = saver.get_tuple(_thread(run_id))
1038
+ if tuple_ is None:
1039
+ return None
1040
+ return tuple_.checkpoint["channel_values"].get("item_ref")
1041
+
1042
+
1043
+ def _refuse_finished(state, run_id: str) -> None:
1044
+ if state.next or state.interrupts:
1045
+ return
1046
+ outcome = state.values.get("outcome", "finished")
1047
+ raise RunRefused(f"run {run_id} already ended {outcome}")
1048
+
1049
+
1050
+ def _refuse_revoked_app_authors(values: dict, tracker: Tracker | None) -> None:
1051
+ allowed = tracker.trusted_authors if tracker is not None else ()
1052
+ missing = set(values.get("required_app_authors", ())).difference(allowed)
1053
+ if missing:
1054
+ raise RunRefused(
1055
+ "cannot resume: checkpointed authors are no longer trusted: "
1056
+ f"{', '.join(sorted(missing))}. Abandon the run and start it again."
1057
+ )
1058
+
1059
+
1060
+ def _advance(
1061
+ ctx: RunContext, graph, state, decision: str | None, config: RunnableConfig
1062
+ ) -> None:
1063
+ if state.interrupts and (decision is None or not str(decision).strip()):
1064
+ return # nothing answered: _finish shows the gate again
1065
+ if state.interrupts:
1066
+ payload = state.interrupts[0].value
1067
+ assert decision is not None
1068
+ _check_decision(payload, decision)
1069
+ # A gate with no listed answers takes a free line (the Q&A round):
1070
+ # the event records that it was answered, never the line itself.
1071
+ verb = _decision_verb(decision) if payload.get("answers") else "answered"
1072
+ ctx.writer.gate(payload["gate"], _DECISIONS.get(verb, verb))
1073
+ graph.invoke(_gate_command(decision, verb), config=config, durability="sync")
1074
+ return
1075
+ # Paused between nodes (crash or kill): continue from the checkpoint.
1076
+ graph.invoke(None, config=config, durability="sync")
1077
+
1078
+
1079
+ def _check_decision(payload: dict, decision: str) -> None:
1080
+ """The decision's verb must be one of the payload's answers.
1081
+
1082
+ Matching is on the first word so ``retry [feedback]`` answers the
1083
+ ``limit_hit`` pause with its feedback intact (#42).
1084
+ """
1085
+ answers = [str(a) for a in payload.get("answers", [])]
1086
+ if answers and _decision_verb(decision) not in [a.lower() for a in answers]:
1087
+ raise RunRefused(
1088
+ f"answer {decision!r} is not one of: {', '.join(answers)}"
1089
+ )
1090
+
1091
+
1092
+ def _decision_verb(decision: str) -> str:
1093
+ parts = str(decision).strip().split(maxsplit=1)
1094
+ return parts[0].lower() if parts else ""
1095
+
1096
+
1097
+ # The first word decides; the rest is feedback for the looping-back node.
1098
+ _DECISIONS = {
1099
+ "y": "approve",
1100
+ "yes": "approve",
1101
+ "ok": "approve",
1102
+ "n": "reject",
1103
+ "no": "reject",
1104
+ "redo": "reject",
1105
+ }
1106
+
1107
+
1108
+ def _gate_command(decision: str, verb: str) -> Command:
1109
+ """Checkpoint a redo with the accepted gate answer, across sittings."""
1110
+ update = {"redone": True} if verb == "redo" else None
1111
+ return Command(resume=decision, update=update)
1112
+
1113
+
1114
+ def _finish(ctx: RunContext, graph, run_id: str, config: RunnableConfig) -> Result:
1115
+ state = graph.get_state(config)
1116
+ if state.interrupts:
1117
+ if ctx.trace is not None:
1118
+ ctx.trace.flush()
1119
+ return _pending(run_id, state.interrupts[0].value)
1120
+ if state.next:
1121
+ raise RunRefused(
1122
+ f"run {run_id} is paused outside a gate; resume it to continue"
1123
+ )
1124
+ values = state.values
1125
+ outcome = values.get("outcome", "stuck")
1126
+ ms = _now_ms() - values.get("start_ms", _now_ms())
1127
+ cost = run_cost(events_path(ctx.root), run_id)
1128
+ ctx.writer.run_end(
1129
+ outcome,
1130
+ ms,
1131
+ reason=values.get("reason"),
1132
+ node=values.get("node"),
1133
+ agent_runs=cost["agent_runs"] or None,
1134
+ validator_reds=cost["validator_reds"],
1135
+ model_calls=cost["model_calls"],
1136
+ )
1137
+ _trace_finish(ctx, outcome, _session_id(ctx, values), values)
1138
+ if ctx.kind == "implement":
1139
+ drop_worktree_snapshot(ctx.root, worktree_snapshot_dir(ctx.root, run_id))
1140
+ return Outcome(
1141
+ run=run_id,
1142
+ outcome=outcome,
1143
+ reason=values.get("reason"),
1144
+ node=values.get("node"),
1145
+ redone=values.get("redone", False),
1146
+ ms=ms,
1147
+ agent_runs=cost["agent_runs"],
1148
+ validator_reds=cost["validator_reds"],
1149
+ model_calls=cost["model_calls"],
1150
+ )
1151
+
1152
+
1153
+ def _pending(run_id: str, payload: dict) -> Pending:
1154
+ return Pending(
1155
+ run=run_id,
1156
+ gate=str(payload.get("gate", "")),
1157
+ question=str(payload.get("question", "")),
1158
+ answers=tuple(str(a) for a in payload.get("answers", ())),
1159
+ detail=str(payload.get("detail", "")),
1160
+ diff=str(payload.get("diff", "")),
1161
+ )
1162
+
1163
+
1164
+ def _now_ms() -> int:
1165
+ return round(time.time() * 1000)