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.
- k0ntrol/__init__.py +1 -0
- k0ntrol/agents.py +998 -0
- k0ntrol/cli.py +190 -0
- k0ntrol/config.py +330 -0
- k0ntrol/credentials.py +78 -0
- k0ntrol/defaults/config.yaml +23 -0
- k0ntrol/events.py +838 -0
- k0ntrol/frontends/__init__.py +1 -0
- k0ntrol/frontends/ask.py +218 -0
- k0ntrol/frontends/badges.py +228 -0
- k0ntrol/frontends/banner.py +128 -0
- k0ntrol/frontends/diffview.py +174 -0
- k0ntrol/frontends/editor.py +701 -0
- k0ntrol/frontends/klog.html +740 -0
- k0ntrol/frontends/klog.py +403 -0
- k0ntrol/frontends/logo.py +12 -0
- k0ntrol/frontends/mentions.py +29 -0
- k0ntrol/frontends/prompt.py +340 -0
- k0ntrol/frontends/render.py +485 -0
- k0ntrol/frontends/session.py +717 -0
- k0ntrol/frontends/setup.py +442 -0
- k0ntrol/frontends/terminal.py +396 -0
- k0ntrol/frontends/theme.py +24 -0
- k0ntrol/helpers.py +108 -0
- k0ntrol/init_flow.py +362 -0
- k0ntrol/langfuse.py +173 -0
- k0ntrol/memory/__init__.py +0 -0
- k0ntrol/memory/index.py +235 -0
- k0ntrol/memory/layout.py +66 -0
- k0ntrol/memory/python_extract.py +189 -0
- k0ntrol/memory/reflect.py +366 -0
- k0ntrol/memory/refresh.py +21 -0
- k0ntrol/memory/scan.py +538 -0
- k0ntrol/memory/session.py +145 -0
- k0ntrol/otel.py +429 -0
- k0ntrol/pricing.py +29 -0
- k0ntrol/prompts/chatty.md +17 -0
- k0ntrol/prompts/implementer.md +14 -0
- k0ntrol/prompts/planner.md +42 -0
- k0ntrol/prompts/researcher.md +20 -0
- k0ntrol/prompts/reviewer.md +34 -0
- k0ntrol/providers.py +718 -0
- k0ntrol/search.py +133 -0
- k0ntrol/tools/__init__.py +0 -0
- k0ntrol/tools/bulk_read.py +93 -0
- k0ntrol/tools/errors.py +50 -0
- k0ntrol/tools/fetch_url.py +212 -0
- k0ntrol/tools/net.py +317 -0
- k0ntrol/tools/path_guard.py +45 -0
- k0ntrol/tools/read.py +174 -0
- k0ntrol/tools/run_tests.py +66 -0
- k0ntrol/tools/runner.py +177 -0
- k0ntrol/tools/search_memory.py +32 -0
- k0ntrol/tools/slice_guard.py +166 -0
- k0ntrol/tools/slice_journal.py +481 -0
- k0ntrol/tools/tracker.py +115 -0
- k0ntrol/tools/web_search.py +199 -0
- k0ntrol/tools/write.py +123 -0
- k0ntrol/tracker/__init__.py +31 -0
- k0ntrol/tracker/github.py +371 -0
- k0ntrol/tracker/local_files.py +241 -0
- k0ntrol/tracker/protocol.py +210 -0
- k0ntrol/workflow/__init__.py +29 -0
- k0ntrol/workflow/change.py +605 -0
- k0ntrol/workflow/ci_gate.py +96 -0
- k0ntrol/workflow/context.py +137 -0
- k0ntrol/workflow/implement.py +1150 -0
- k0ntrol/workflow/nodes.py +331 -0
- k0ntrol/workflow/plan.py +675 -0
- k0ntrol/workflow/qa.py +98 -0
- k0ntrol/workflow/research.py +533 -0
- k0ntrol/workflow/routers.py +273 -0
- k0ntrol/workflow/run.py +1165 -0
- k0ntrol/workflow/state.py +146 -0
- k0ntrol/workflow/triage.py +269 -0
- k0ntrol_cli-0.1.0.dist-info/METADATA +154 -0
- k0ntrol_cli-0.1.0.dist-info/RECORD +80 -0
- k0ntrol_cli-0.1.0.dist-info/WHEEL +4 -0
- k0ntrol_cli-0.1.0.dist-info/entry_points.txt +2 -0
- k0ntrol_cli-0.1.0.dist-info/licenses/LICENSE +201 -0
k0ntrol/workflow/qa.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""The Q&A round machinery ``/plan``'s Q&A definition and ``/research
|
|
2
|
+
#<n>``'s Q&A decision tickets share (#120, #125).
|
|
3
|
+
|
|
4
|
+
A round is one fresh agent run's numbered questions — each with its
|
|
5
|
+
recommended answer — shown at the round gate; the human answers in one
|
|
6
|
+
line and the next run's fresh context carries every earlier question
|
|
7
|
+
and the line that answered it. The numbers the human answers by are
|
|
8
|
+
always ``1..n``, assigned in code whatever the model emitted.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from collections.abc import Callable
|
|
12
|
+
|
|
13
|
+
from langgraph.types import interrupt
|
|
14
|
+
|
|
15
|
+
from k0ntrol.workflow.context import RunContext
|
|
16
|
+
|
|
17
|
+
DEFAULT_MAX_ROUND_QUESTIONS = 7
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def make_round_gate(ctx: RunContext) -> Callable[[dict], dict]:
|
|
21
|
+
"""The round gate: the round's numbered questions, each with its
|
|
22
|
+
recommended answer; the human's one line answers the whole round and
|
|
23
|
+
joins the Q&A every later agent run sees. Free text, so the gate
|
|
24
|
+
takes any line — ``_check_decision`` only polices listed answers.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
def node(state: dict) -> dict:
|
|
28
|
+
decision = interrupt(
|
|
29
|
+
{
|
|
30
|
+
"gate": "round",
|
|
31
|
+
"question": "answer the round's questions in one line",
|
|
32
|
+
"answers": [],
|
|
33
|
+
"detail": _round_detail(state.get("questions", [])),
|
|
34
|
+
}
|
|
35
|
+
)
|
|
36
|
+
answered = {
|
|
37
|
+
"questions": state.get("questions", []),
|
|
38
|
+
"answer": str(decision).strip(),
|
|
39
|
+
}
|
|
40
|
+
return {
|
|
41
|
+
"rounds": [*state.get("rounds", []), answered],
|
|
42
|
+
"questions": [],
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
return node
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _questions(result, cap: int) -> list[dict]:
|
|
49
|
+
"""The round's questions as plain dicts, capped in code, never in the
|
|
50
|
+
prompt alone — and numbered in code too, so the numbers the human
|
|
51
|
+
answers by are always ``1..n`` whatever the model emitted.
|
|
52
|
+
|
|
53
|
+
PLANNER's other outputs (Spec, TicketList) carry no questions:
|
|
54
|
+
answering early ends the Q&A like an empty round.
|
|
55
|
+
"""
|
|
56
|
+
questions = getattr(result.structured_response, "questions", None) or []
|
|
57
|
+
return [
|
|
58
|
+
{**question.model_dump(), "number": index}
|
|
59
|
+
for index, question in enumerate(questions[:cap], 1)
|
|
60
|
+
]
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _cap(state: dict) -> int:
|
|
64
|
+
return int(state.get("max_round_questions", DEFAULT_MAX_ROUND_QUESTIONS))
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _round_detail(questions: list[dict]) -> str:
|
|
68
|
+
"""What the gate shows: ``n. question`` over ``recommended: answer
|
|
69
|
+
(why)``, one pair of lines per question."""
|
|
70
|
+
lines = []
|
|
71
|
+
for question in questions:
|
|
72
|
+
lines.append(f"{question['number']}. {question['question']}")
|
|
73
|
+
recommended = f" recommended: {question['recommendation']}"
|
|
74
|
+
if question.get("rationale"):
|
|
75
|
+
recommended += f" ({question['rationale']})"
|
|
76
|
+
lines.append(recommended)
|
|
77
|
+
return "\n".join(lines)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _answered_lines(round_: dict) -> list[str]:
|
|
81
|
+
"""One answered round as a fresh agent run reads it back: its
|
|
82
|
+
questions, then the line the human answered them with."""
|
|
83
|
+
lines = [
|
|
84
|
+
f" {question['number']}. {question['question']} "
|
|
85
|
+
f"(recommended: {question['recommendation']})"
|
|
86
|
+
for question in round_["questions"]
|
|
87
|
+
]
|
|
88
|
+
return [*lines, f" answer: {round_['answer']}"]
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _answered_rounds(state: dict) -> list[str]:
|
|
92
|
+
"""Every answered round as a fresh agent run reads it back: a
|
|
93
|
+
``Round n:`` block per round, its questions and answering line."""
|
|
94
|
+
lines = []
|
|
95
|
+
for index, round_ in enumerate(state.get("rounds", []), 1):
|
|
96
|
+
lines.append(f"\nRound {index}:")
|
|
97
|
+
lines.extend(_answered_lines(round_))
|
|
98
|
+
return lines
|
|
@@ -0,0 +1,533 @@
|
|
|
1
|
+
"""The ``/research`` graph: PLANNER charts a Map (#124), the map's decision
|
|
2
|
+
tickets get worked one run at a time (#125).
|
|
3
|
+
|
|
4
|
+
``/research <question>`` runs one fresh PLANNER pass that charts the
|
|
5
|
+
question's open decisions into a ``ChartedMap``: the map's title,
|
|
6
|
+
destination and notes, and one decision ticket per open question typed
|
|
7
|
+
research, Q&A or human. The harness then publishes the Map work item —
|
|
8
|
+
destination, notes, an empty Decisions so far — with each decision
|
|
9
|
+
ticket as its child and the blocker links where one decision waits on
|
|
10
|
+
another.
|
|
11
|
+
|
|
12
|
+
``/research #<n>`` picks the map's first open decision ticket whose
|
|
13
|
+
blockers are all closed. A research ticket gets a fresh RESEARCHER run
|
|
14
|
+
whose cited findings are commented before the decision gate; a Q&A
|
|
15
|
+
ticket a short Q&A with PLANNER; a human ticket goes straight to the
|
|
16
|
+
gate. ``ok`` at the gate takes the proposal, any other line is the
|
|
17
|
+
human's own decision: the ticket closes with it and the map's Decisions
|
|
18
|
+
so far gains its one-line gist and link. The REPL command is #129.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from collections.abc import Callable, Iterable
|
|
22
|
+
|
|
23
|
+
from langgraph.checkpoint.base import BaseCheckpointSaver
|
|
24
|
+
from langgraph.graph import END, START, StateGraph
|
|
25
|
+
from langgraph.graph.state import CompiledStateGraph
|
|
26
|
+
from langgraph.types import interrupt
|
|
27
|
+
|
|
28
|
+
from k0ntrol.agents import ChartedMap, DecisionProposal
|
|
29
|
+
from k0ntrol.tracker import (
|
|
30
|
+
ChildWorkItem,
|
|
31
|
+
WorkItem,
|
|
32
|
+
comment_marker,
|
|
33
|
+
is_k0_work_item,
|
|
34
|
+
is_trusted_author,
|
|
35
|
+
)
|
|
36
|
+
from k0ntrol.workflow.context import RunContext
|
|
37
|
+
from k0ntrol.workflow.nodes import (
|
|
38
|
+
_attempt_limit,
|
|
39
|
+
_invoke_counted,
|
|
40
|
+
_last_output,
|
|
41
|
+
make_limit_hit,
|
|
42
|
+
)
|
|
43
|
+
from k0ntrol.workflow.qa import (
|
|
44
|
+
_answered_rounds,
|
|
45
|
+
_cap,
|
|
46
|
+
_questions,
|
|
47
|
+
make_round_gate,
|
|
48
|
+
)
|
|
49
|
+
from k0ntrol.workflow.routers import (
|
|
50
|
+
_exhausted,
|
|
51
|
+
route_after_chart,
|
|
52
|
+
route_after_map_gate,
|
|
53
|
+
route_after_decision_planner,
|
|
54
|
+
route_after_pick,
|
|
55
|
+
route_after_researcher,
|
|
56
|
+
route_limit_hit,
|
|
57
|
+
route_research_start,
|
|
58
|
+
)
|
|
59
|
+
from k0ntrol.workflow.state import RunState
|
|
60
|
+
|
|
61
|
+
_BLANK = "—"
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def build_research_graph(
|
|
65
|
+
ctx: RunContext, checkpointer: BaseCheckpointSaver | None
|
|
66
|
+
) -> CompiledStateGraph:
|
|
67
|
+
"""Compile the ``/research`` graph for one run context."""
|
|
68
|
+
graph = StateGraph(RunState)
|
|
69
|
+
graph.add_node("planner", make_chart_node(ctx))
|
|
70
|
+
graph.add_node("map_gate", make_map_gate(ctx))
|
|
71
|
+
graph.add_node("publish_map", make_publish_map(ctx))
|
|
72
|
+
graph.add_node("publish_decisions", make_publish_decisions(ctx))
|
|
73
|
+
graph.add_node("pick_decision", make_pick_decision(ctx))
|
|
74
|
+
graph.add_node("researcher", make_researcher_node(ctx))
|
|
75
|
+
graph.add_node("comment_findings", make_comment_findings(ctx))
|
|
76
|
+
graph.add_node("decision_planner", make_decision_planner_node(ctx))
|
|
77
|
+
graph.add_node("round_gate", make_round_gate(ctx))
|
|
78
|
+
graph.add_node("decision_gate", make_decision_gate(ctx))
|
|
79
|
+
graph.add_node("record_decision", make_record_decision(ctx))
|
|
80
|
+
graph.add_node("limit_hit", make_limit_hit(ctx))
|
|
81
|
+
graph.add_conditional_edges(START, route_research_start)
|
|
82
|
+
graph.add_conditional_edges("planner", route_after_chart)
|
|
83
|
+
graph.add_conditional_edges("map_gate", route_after_map_gate)
|
|
84
|
+
graph.add_edge("publish_map", "publish_decisions")
|
|
85
|
+
graph.add_edge("publish_decisions", END)
|
|
86
|
+
graph.add_conditional_edges("pick_decision", route_after_pick)
|
|
87
|
+
graph.add_conditional_edges("researcher", route_after_researcher)
|
|
88
|
+
graph.add_edge("comment_findings", "decision_gate")
|
|
89
|
+
graph.add_conditional_edges("decision_planner", route_after_decision_planner)
|
|
90
|
+
graph.add_edge("round_gate", "decision_planner")
|
|
91
|
+
graph.add_edge("decision_gate", "record_decision")
|
|
92
|
+
graph.add_edge("record_decision", END)
|
|
93
|
+
graph.add_conditional_edges("limit_hit", route_limit_hit)
|
|
94
|
+
return graph.compile(checkpointer=checkpointer)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def make_chart_node(ctx: RunContext) -> Callable[[dict], dict]:
|
|
98
|
+
"""One charting pass: a fresh PLANNER run returning a ChartedMap.
|
|
99
|
+
|
|
100
|
+
A run that answers with another structured output charts again while
|
|
101
|
+
attempts remain — the limit pause carries the last output, the same
|
|
102
|
+
resumable path a model-call limit takes.
|
|
103
|
+
"""
|
|
104
|
+
|
|
105
|
+
def node(state: dict) -> dict:
|
|
106
|
+
result, updates = _invoke_counted(ctx, "planner", state, chart_brief)
|
|
107
|
+
if result.limit_hit:
|
|
108
|
+
return updates
|
|
109
|
+
chart = result.structured_response
|
|
110
|
+
if isinstance(chart, ChartedMap):
|
|
111
|
+
updates["map"] = chart.model_dump()
|
|
112
|
+
return updates
|
|
113
|
+
merged = {**state, **updates}
|
|
114
|
+
if _exhausted(merged, "planner_attempts"):
|
|
115
|
+
updates["limit"] = _attempt_limit(
|
|
116
|
+
merged, "planner", "planner", _last_output(result)
|
|
117
|
+
)
|
|
118
|
+
return updates
|
|
119
|
+
|
|
120
|
+
return node
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def make_map_gate(ctx: RunContext) -> Callable[[dict], dict]:
|
|
124
|
+
"""The Map gate: the drafted Map before anything is published (#205).
|
|
125
|
+
``ok`` publishes it; ``redo [feedback]`` charts again. Abandoning the
|
|
126
|
+
paused run publishes nothing."""
|
|
127
|
+
|
|
128
|
+
def node(state: dict) -> dict:
|
|
129
|
+
chart = state["map"]
|
|
130
|
+
decision = interrupt(
|
|
131
|
+
{
|
|
132
|
+
"gate": "map",
|
|
133
|
+
"question": "publish this Map?",
|
|
134
|
+
"answers": ["ok", "redo"],
|
|
135
|
+
"detail": f"# {chart['title']}\n\n{map_body(chart)}",
|
|
136
|
+
}
|
|
137
|
+
)
|
|
138
|
+
word, _, feedback = str(decision).strip().partition(" ")
|
|
139
|
+
if word.lower() == "ok":
|
|
140
|
+
return {"map_feedback": None}
|
|
141
|
+
return {"map": None, "map_feedback": feedback.strip() or "chart it again"}
|
|
142
|
+
|
|
143
|
+
return node
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def make_publish_map(ctx: RunContext) -> Callable[[dict], dict]:
|
|
147
|
+
"""The Map work item, marker-idempotent (carrier contract, #13)."""
|
|
148
|
+
|
|
149
|
+
def node(state: dict) -> dict:
|
|
150
|
+
chart = state["map"]
|
|
151
|
+
item = ctx.tracker.ensure_work_item(
|
|
152
|
+
chart["title"], map_body(chart), run=ctx.run_id, node="publish_map"
|
|
153
|
+
)
|
|
154
|
+
return {"item_ref": item.ref, "item_title": item.title}
|
|
155
|
+
|
|
156
|
+
return node
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def make_publish_decisions(ctx: RunContext) -> Callable[[dict], dict]:
|
|
160
|
+
"""Each decision ticket as a marked child of the Map, then its blocker
|
|
161
|
+
links — one node marker per decision so a resume recovers each child
|
|
162
|
+
on its own.
|
|
163
|
+
"""
|
|
164
|
+
|
|
165
|
+
def node(state: dict) -> dict:
|
|
166
|
+
refs = []
|
|
167
|
+
for index, decision in enumerate(state["map"]["decisions"]):
|
|
168
|
+
child = ctx.tracker.create_child_work_item(
|
|
169
|
+
state["item_ref"],
|
|
170
|
+
decision["question"],
|
|
171
|
+
decision_body(decision),
|
|
172
|
+
run=ctx.run_id,
|
|
173
|
+
node=f"publish_decision_{index}",
|
|
174
|
+
)
|
|
175
|
+
refs.append(child.ref)
|
|
176
|
+
for blocker in decision.get("blocked_by", []):
|
|
177
|
+
ctx.tracker.link_blocked_by(child.ref, refs[blocker])
|
|
178
|
+
return {"decision_refs": refs, "outcome": "done"}
|
|
179
|
+
|
|
180
|
+
return node
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
#: The sections ``map_body`` writes — how a ``/research #<n>`` carrier is
|
|
184
|
+
#: known to be a Map and not another work item's children holder.
|
|
185
|
+
MAP_SECTIONS = (
|
|
186
|
+
"Destination",
|
|
187
|
+
"Notes",
|
|
188
|
+
"Decisions so far",
|
|
189
|
+
"Not yet specified",
|
|
190
|
+
"Out of scope",
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def is_map(item: WorkItem) -> bool:
|
|
195
|
+
"""Whether the work item is a Map: its body carries the sections
|
|
196
|
+
``map_body`` writes."""
|
|
197
|
+
lines = item.body.splitlines()
|
|
198
|
+
return all(f"## {title}" in lines for title in MAP_SECTIONS)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def map_body(chart: dict) -> str:
|
|
202
|
+
"""The Map body: Destination, Notes, Decisions so far (empty — the
|
|
203
|
+
confirmed decisions land one line at a time, #125), Not yet
|
|
204
|
+
specified, Out of scope."""
|
|
205
|
+
parts = [
|
|
206
|
+
_prose("Destination", chart["destination"]),
|
|
207
|
+
_prose("Notes", chart.get("notes", "")),
|
|
208
|
+
"## Decisions so far",
|
|
209
|
+
_bullets("Not yet specified", chart.get("not_yet_specified", [])),
|
|
210
|
+
_bullets("Out of scope", chart.get("out_of_scope", [])),
|
|
211
|
+
]
|
|
212
|
+
return "\n\n".join(parts)
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def decision_body(decision: dict) -> str:
|
|
216
|
+
"""A decision ticket body: its question and its type."""
|
|
217
|
+
return f"## Question\n\n{decision['question']}\n\n## Type\n\n{decision['type']}"
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def chart_brief(state: dict) -> str:
|
|
221
|
+
"""PLANNER's fresh context for the chart: the research question, and
|
|
222
|
+
on a re-chart the note that its last answer was no map."""
|
|
223
|
+
text = (
|
|
224
|
+
f"Research question: {state['task']}\n\n"
|
|
225
|
+
"Chart the map for this question: answer with ChartedMap — the "
|
|
226
|
+
"map's title, its destination, notes, one decision ticket per "
|
|
227
|
+
"open question (typed research, Q&A or human, with the "
|
|
228
|
+
"blocked_by indexes of the earlier decisions they wait on), "
|
|
229
|
+
"what is not yet specified and what is out of scope."
|
|
230
|
+
)
|
|
231
|
+
if state.get("map_feedback"):
|
|
232
|
+
text += f"\n\nThe human sent the last map back: {state['map_feedback']}"
|
|
233
|
+
elif state.get("planner_attempts"):
|
|
234
|
+
text += (
|
|
235
|
+
"\n\nYour last answer did not chart a map — answer with ChartedMap."
|
|
236
|
+
)
|
|
237
|
+
return text
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _prose(title: str, text: str) -> str:
|
|
241
|
+
return f"## {title}\n\n{text or _BLANK}"
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _bullets(title: str, lines: list[str]) -> str:
|
|
245
|
+
body = "\n".join(f"- {line}" for line in lines) or _BLANK
|
|
246
|
+
return f"## {title}\n\n{body}"
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
# --- /research #<n>: work the map's next decision ticket (#125) ------------------
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def make_pick_decision(ctx: RunContext) -> Callable[[dict], dict]:
|
|
253
|
+
"""The map's first open decision ticket whose blockers are all closed.
|
|
254
|
+
|
|
255
|
+
Children come in tracker order: a closed child is done, an open child
|
|
256
|
+
with an open blocker still waits. The picked ticket's type — the
|
|
257
|
+
``## Type`` section k0 wrote, ``human`` when there is none or the
|
|
258
|
+
author is not trusted (ADR 0006) — decides who answers it.
|
|
259
|
+
"""
|
|
260
|
+
|
|
261
|
+
def node(state: dict) -> dict:
|
|
262
|
+
for child in ctx.tracker.list_children(state["item_ref"]):
|
|
263
|
+
if child.state != "open" or _blocked(ctx, child.ref):
|
|
264
|
+
continue
|
|
265
|
+
item = ctx.tracker.read_work_item(child.ref)
|
|
266
|
+
return {
|
|
267
|
+
"decision": _decision_dict(
|
|
268
|
+
child, item, ctx.tracker.trusted_authors
|
|
269
|
+
)
|
|
270
|
+
}
|
|
271
|
+
return {"decision": None, "outcome": "done"}
|
|
272
|
+
|
|
273
|
+
return node
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def _blocked(ctx: RunContext, ref: str) -> bool:
|
|
277
|
+
return any(
|
|
278
|
+
blocker.state != "closed" for blocker in ctx.tracker.list_blockers(ref)
|
|
279
|
+
)
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def _decision_dict(
|
|
283
|
+
child: ChildWorkItem, item: WorkItem, trusted_authors: Iterable[str] = ()
|
|
284
|
+
) -> dict:
|
|
285
|
+
return {
|
|
286
|
+
"ref": child.ref,
|
|
287
|
+
"question": item.title,
|
|
288
|
+
"type": _decision_type(item, trusted_authors),
|
|
289
|
+
"url": item.url,
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
_DECISION_TYPES = ("research", "Q&A", "human")
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def _decision_type(item: WorkItem, trusted_authors: Iterable[str] = ()) -> str:
|
|
297
|
+
"""The ticket's ``## Type``: who answers it.
|
|
298
|
+
|
|
299
|
+
A child with no readable type — or one an untrusted author filed —
|
|
300
|
+
is worked as a human decision: only a gate ever reads its content,
|
|
301
|
+
never an agent (ADR 0006).
|
|
302
|
+
"""
|
|
303
|
+
trusted = is_k0_work_item(item) or is_trusted_author(
|
|
304
|
+
item.author, item.author_association, trusted_authors
|
|
305
|
+
)
|
|
306
|
+
lines = _section(item.body, "Type").splitlines()
|
|
307
|
+
type_ = lines[0].strip() if lines else ""
|
|
308
|
+
return type_ if trusted and type_ in _DECISION_TYPES else "human"
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def _section(body: str, title: str) -> str:
|
|
312
|
+
"""The text between ``## <title>`` and the next ``##`` heading."""
|
|
313
|
+
lines = body.splitlines()
|
|
314
|
+
if f"## {title}" not in lines:
|
|
315
|
+
return ""
|
|
316
|
+
collected = []
|
|
317
|
+
for line in lines[lines.index(f"## {title}") + 1 :]:
|
|
318
|
+
if line.startswith("## "):
|
|
319
|
+
break
|
|
320
|
+
collected.append(line)
|
|
321
|
+
return "\n".join(collected).strip()
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def make_researcher_node(ctx: RunContext) -> Callable[[dict], dict]:
|
|
325
|
+
"""A fresh RESEARCHER run on the picked research ticket: its cited
|
|
326
|
+
findings and proposed decision feed the comment and the gate."""
|
|
327
|
+
|
|
328
|
+
def node(state: dict) -> dict:
|
|
329
|
+
result, updates = _invoke_counted(
|
|
330
|
+
ctx, "researcher", state, researcher_brief
|
|
331
|
+
)
|
|
332
|
+
if result.limit_hit:
|
|
333
|
+
return updates
|
|
334
|
+
finding = result.structured_response
|
|
335
|
+
updates["finding"] = finding.model_dump()
|
|
336
|
+
updates["proposal"] = finding.proposed_decision
|
|
337
|
+
return updates
|
|
338
|
+
|
|
339
|
+
return node
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def _decision_header(state: dict) -> str:
|
|
343
|
+
"""The line the decision-ticket briefs open with: the ticket and the
|
|
344
|
+
map it belongs to."""
|
|
345
|
+
return (
|
|
346
|
+
f"Decision ticket #{state['decision']['ref']} on map "
|
|
347
|
+
f"#{state['item_ref']} ({state.get('item_title', '')}):"
|
|
348
|
+
)
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def researcher_brief(state: dict) -> str:
|
|
352
|
+
"""RESEARCHER's fresh context: the decision ticket to answer."""
|
|
353
|
+
return (
|
|
354
|
+
f"{_decision_header(state)}\n"
|
|
355
|
+
f"{state['decision']['question']}\n\n"
|
|
356
|
+
"Answer it from primary sources and answer with ResearchFinding — "
|
|
357
|
+
"the cited findings, your proposed decision and each source's "
|
|
358
|
+
"title and URL."
|
|
359
|
+
)
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def make_comment_findings(ctx: RunContext) -> Callable[[dict], dict]:
|
|
363
|
+
"""RESEARCHER's cited findings as a marked comment on the ticket: the
|
|
364
|
+
evidence sits on the work item before the decision gate asks."""
|
|
365
|
+
|
|
366
|
+
def node(state: dict) -> dict:
|
|
367
|
+
ctx.tracker.comment_work_item(
|
|
368
|
+
state["decision"]["ref"],
|
|
369
|
+
_findings_comment(state["finding"]),
|
|
370
|
+
run=ctx.run_id,
|
|
371
|
+
node="comment_findings",
|
|
372
|
+
)
|
|
373
|
+
return {}
|
|
374
|
+
|
|
375
|
+
return node
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
def _findings_comment(finding: dict) -> str:
|
|
379
|
+
lines = ["## Findings", ""]
|
|
380
|
+
lines += [f"- {item}" for item in finding["findings"]]
|
|
381
|
+
lines += ["", "## Citations", ""]
|
|
382
|
+
lines += [
|
|
383
|
+
f"- [{citation['title']}]({citation['url']})"
|
|
384
|
+
for citation in finding["citations"]
|
|
385
|
+
]
|
|
386
|
+
lines += ["", "## Proposed decision", "", finding["proposed_decision"]]
|
|
387
|
+
return "\n".join(lines)
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def make_decision_planner_node(ctx: RunContext) -> Callable[[dict], dict]:
|
|
391
|
+
"""A Q&A ticket's PLANNER run: the next round of questions, or a
|
|
392
|
+
DecisionProposal once it can propose the decision.
|
|
393
|
+
|
|
394
|
+
The shared round machinery counts each run under ``planner_attempts``
|
|
395
|
+
and caps a round's questions in code; an off-shape or empty answer
|
|
396
|
+
ends the Q&A at the decision gate, like /plan's (#120).
|
|
397
|
+
"""
|
|
398
|
+
|
|
399
|
+
def node(state: dict) -> dict:
|
|
400
|
+
result, updates = _invoke_counted(
|
|
401
|
+
ctx,
|
|
402
|
+
"planner",
|
|
403
|
+
state,
|
|
404
|
+
decision_brief,
|
|
405
|
+
limit_node="decision_planner",
|
|
406
|
+
)
|
|
407
|
+
if result.limit_hit:
|
|
408
|
+
return updates
|
|
409
|
+
proposal = result.structured_response
|
|
410
|
+
if isinstance(proposal, DecisionProposal):
|
|
411
|
+
updates["proposal"] = _proposal_text(proposal)
|
|
412
|
+
updates["questions"] = []
|
|
413
|
+
return updates
|
|
414
|
+
updates["questions"] = _questions(result, _cap(state))
|
|
415
|
+
return updates
|
|
416
|
+
|
|
417
|
+
return node
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
def _proposal_text(proposal: DecisionProposal) -> str:
|
|
421
|
+
text = proposal.proposed_decision
|
|
422
|
+
if proposal.rationale:
|
|
423
|
+
text += f"\n\n{proposal.rationale}"
|
|
424
|
+
return text
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def decision_brief(state: dict) -> str:
|
|
428
|
+
"""PLANNER's fresh context for a Q&A decision ticket: the question,
|
|
429
|
+
then every earlier round's questions and the line that answered
|
|
430
|
+
them."""
|
|
431
|
+
decision = state["decision"]
|
|
432
|
+
lines = [
|
|
433
|
+
_decision_header(state),
|
|
434
|
+
f"{decision['question']}",
|
|
435
|
+
"",
|
|
436
|
+
f"Ask the next round of questions — at most {_cap(state)}, each "
|
|
437
|
+
"numbered with your recommended answer — or answer with "
|
|
438
|
+
"DecisionProposal once you can propose the decision.",
|
|
439
|
+
]
|
|
440
|
+
lines.extend(_answered_rounds(state))
|
|
441
|
+
return "\n".join(lines)
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
def make_decision_gate(ctx: RunContext) -> Callable[[dict], dict]:
|
|
445
|
+
"""The decision gate: the proposal — or, for a human ticket, the bare
|
|
446
|
+
question. ``ok`` takes the proposal; any other line is the human's
|
|
447
|
+
own decision — free text, like the round gate. With no proposal a
|
|
448
|
+
bare ``ok`` confirms nothing, so the gate asks again."""
|
|
449
|
+
|
|
450
|
+
def node(state: dict) -> dict:
|
|
451
|
+
proposal = state.get("proposal", "")
|
|
452
|
+
answer = str(interrupt(_gate_payload(state))).strip()
|
|
453
|
+
while not proposal and answer.lower() == "ok":
|
|
454
|
+
answer = str(interrupt(_gate_payload(state))).strip()
|
|
455
|
+
if proposal and answer.lower() == "ok":
|
|
456
|
+
return {"decided": proposal}
|
|
457
|
+
return {"decided": answer}
|
|
458
|
+
|
|
459
|
+
return node
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
def _gate_payload(state: dict) -> dict:
|
|
463
|
+
"""The interrupt payload the decision gate shows (and re-shows)."""
|
|
464
|
+
return {
|
|
465
|
+
"gate": "decision",
|
|
466
|
+
"question": _gate_question(state["decision"], state.get("proposal", "")),
|
|
467
|
+
"answers": [],
|
|
468
|
+
"detail": _gate_detail(state),
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
|
|
472
|
+
def _gate_question(decision: dict, proposal: str) -> str:
|
|
473
|
+
base = f"#{decision['ref']}: {decision['question']}"
|
|
474
|
+
if proposal:
|
|
475
|
+
return f"{base} — ok takes the proposal, anything else is yours"
|
|
476
|
+
return f"{base} — type the decision"
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
def _gate_detail(state: dict) -> str:
|
|
480
|
+
finding = state.get("finding")
|
|
481
|
+
if finding:
|
|
482
|
+
return _findings_comment(finding)
|
|
483
|
+
return state.get("proposal") or state["decision"]["question"]
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def make_record_decision(ctx: RunContext) -> Callable[[dict], dict]:
|
|
487
|
+
"""Close the ticket with the confirmed decision and index it on the
|
|
488
|
+
map: one line — gist and link — under Decisions so far,
|
|
489
|
+
marker-idempotent like every k0 write (carrier contract, #13)."""
|
|
490
|
+
|
|
491
|
+
def node(state: dict) -> dict:
|
|
492
|
+
decision = state["decision"]
|
|
493
|
+
ctx.tracker.close_work_item(
|
|
494
|
+
decision["ref"],
|
|
495
|
+
f"## Decision\n\n{state['decided']}",
|
|
496
|
+
run=ctx.run_id,
|
|
497
|
+
node="record_decision",
|
|
498
|
+
)
|
|
499
|
+
_index_on_map(ctx, state)
|
|
500
|
+
return {"outcome": "done"}
|
|
501
|
+
|
|
502
|
+
return node
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
def _index_on_map(ctx: RunContext, state: dict) -> None:
|
|
506
|
+
marker = comment_marker(ctx.run_id, "record_decision")
|
|
507
|
+
item = ctx.tracker.read_work_item(state["item_ref"])
|
|
508
|
+
if marker in item.body:
|
|
509
|
+
return
|
|
510
|
+
line = _map_line(state["decision"], state["decided"], marker)
|
|
511
|
+
ctx.tracker.edit_work_item_body(
|
|
512
|
+
state["item_ref"], _with_decision_line(item.body, line)
|
|
513
|
+
)
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
def _map_line(decision: dict, decided: str, marker: str) -> str:
|
|
517
|
+
gist = decided.splitlines()[0].strip()
|
|
518
|
+
return f"- [{decision['question']}]({decision['url']}): {gist} {marker}"
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
def _with_decision_line(body: str, line: str) -> str:
|
|
522
|
+
"""Append ``line`` under ``## Decisions so far`` — kept entries first;
|
|
523
|
+
a hand-made map without the section gets it."""
|
|
524
|
+
lines = body.splitlines()
|
|
525
|
+
if "## Decisions so far" not in lines:
|
|
526
|
+
return f"{body.rstrip()}\n\n## Decisions so far\n\n{line}"
|
|
527
|
+
head = lines.index("## Decisions so far")
|
|
528
|
+
end = next(
|
|
529
|
+
(i for i in range(head + 1, len(lines)) if lines[i].startswith("## ")),
|
|
530
|
+
len(lines),
|
|
531
|
+
)
|
|
532
|
+
entries = [l for l in lines[head + 1 : end] if l.strip()]
|
|
533
|
+
return "\n".join([*lines[: head + 1], "", *entries, line, "", *lines[end:]])
|