roadkeep 0.2.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.
- roadkeep/__init__.py +79 -0
- roadkeep/adopting.py +2347 -0
- roadkeep/attesting.py +293 -0
- roadkeep/authoring.py +2117 -0
- roadkeep/backlog.py +767 -0
- roadkeep/blocking.py +1622 -0
- roadkeep/briefing.py +970 -0
- roadkeep/budgeting.py +2056 -0
- roadkeep/capturing.py +1699 -0
- roadkeep/claiming.py +1019 -0
- roadkeep/cli.py +638 -0
- roadkeep/commanding.py +487 -0
- roadkeep/config.py +1832 -0
- roadkeep/counting.py +376 -0
- roadkeep/criteria.py +933 -0
- roadkeep/deferring.py +708 -0
- roadkeep/describing.py +568 -0
- roadkeep/exporting.py +808 -0
- roadkeep/fixing.py +629 -0
- roadkeep/governing.py +934 -0
- roadkeep/graph.py +395 -0
- roadkeep/guarding.py +1028 -0
- roadkeep/history.py +2403 -0
- roadkeep/ids.py +301 -0
- roadkeep/installing.py +2145 -0
- roadkeep/kernel/__init__.py +24 -0
- roadkeep/kernel/document.py +1719 -0
- roadkeep/kernel/schema.py +2308 -0
- roadkeep/linting.py +4420 -0
- roadkeep/locking.py +209 -0
- roadkeep/markers.py +172 -0
- roadkeep/merging.py +1159 -0
- roadkeep/picking.py +772 -0
- roadkeep/provenance.py +789 -0
- roadkeep/queueing.py +752 -0
- roadkeep/ranking.py +139 -0
- roadkeep/referring.py +231 -0
- roadkeep/remaining.py +336 -0
- roadkeep/remedying.py +1989 -0
- roadkeep/rendering.py +1601 -0
- roadkeep/renumbering.py +503 -0
- roadkeep/repairing.py +295 -0
- roadkeep/reverting.py +144 -0
- roadkeep/scoping.py +708 -0
- roadkeep/screening.py +196 -0
- roadkeep/sections.py +4121 -0
- roadkeep/serving.py +2909 -0
- roadkeep/shipping.py +3993 -0
- roadkeep/showing.py +613 -0
- roadkeep/storing.py +224 -0
- roadkeep/verbs/__init__.py +26 -0
- roadkeep/verbs/adopting.py +974 -0
- roadkeep/verbs/authoring.py +566 -0
- roadkeep/verbs/declaring.py +335 -0
- roadkeep/verbs/linting.py +645 -0
- roadkeep/verbs/querying.py +2138 -0
- roadkeep/verbs/reading.py +307 -0
- roadkeep/verbs/refusing.py +146 -0
- roadkeep/verbs/sections.py +1433 -0
- roadkeep/verbs/shipping.py +819 -0
- roadkeep/weighing.py +380 -0
- roadkeep-0.2.0.dist-info/METADATA +453 -0
- roadkeep-0.2.0.dist-info/RECORD +67 -0
- roadkeep-0.2.0.dist-info/WHEEL +5 -0
- roadkeep-0.2.0.dist-info/entry_points.txt +2 -0
- roadkeep-0.2.0.dist-info/licenses/LICENSE +202 -0
- roadkeep-0.2.0.dist-info/top_level.txt +1 -0
roadkeep/serving.py
ADDED
|
@@ -0,0 +1,2909 @@
|
|
|
1
|
+
"""The commands as MCP tools, so the field schema *is* the tool's input schema (RK24, RK59).
|
|
2
|
+
|
|
3
|
+
A CLI reached through `Bash` puts the field names in prose. `--symptom` is typed from memory,
|
|
4
|
+
`--dep` is guessed as `--deps`, and the answer is a usage string the caller pays for after the
|
|
5
|
+
sentence was already composed. Over MCP the same fields arrive as a JSON Schema the client
|
|
6
|
+
validates *before* the call, which is L1 moved one layer further out: not the write path
|
|
7
|
+
refusing bad prose, but the protocol refusing a wrong argument name.
|
|
8
|
+
|
|
9
|
+
What that costs, and how each cost is avoided here:
|
|
10
|
+
|
|
11
|
+
* **No second implementation.** A tool call is translated into the argv the CLI accepts and
|
|
12
|
+
dispatched through :func:`~roadkeep.cli.build_parser`'s own handler, in-process. The exit
|
|
13
|
+
code becomes `isError`, and the refusal an agent reads over MCP is byte-identical to the one
|
|
14
|
+
it reads in a terminal. Two code paths that both "add a task" is the drift this repo exists
|
|
15
|
+
to remove, so there is one.
|
|
16
|
+
* **No duplicated schema.** Every property is derived: its type and description come from the
|
|
17
|
+
argparse action, its bounds from `roadkeep.toml` — `maxLength` is this project's `symptom`
|
|
18
|
+
and `why` limits, `enum` is its declared markers, `pattern` is its id shape, and a prose
|
|
19
|
+
body's budget is said in words because that is the unit it is declared in (L6). A tool
|
|
20
|
+
description is the subcommand's own `description`, so a flag renamed in `cli.py` cannot
|
|
21
|
+
leave the schema describing something that is gone.
|
|
22
|
+
* **stdio, and no listener.** "No server" is a non-goal about *the store*: this speaks
|
|
23
|
+
JSON-RPC on stdin and stdout, binds no port and caches no file. The config is re-read per
|
|
24
|
+
message, so a `roadkeep.toml` edited mid-session is the one the next `tools/list`
|
|
25
|
+
describes — and because the *code* reading it is not, a refusal says so when this package's
|
|
26
|
+
own modules moved after they were imported (RK155). The one thing held between messages is
|
|
27
|
+
:class:`Watch`, and it holds no fact about the project: only a digest of the tool list this
|
|
28
|
+
connection was **sent**, so `notifications/tools/list_changed` can be sent when it ages
|
|
29
|
+
(RK177). A stateless server cannot derive what it already told somebody.
|
|
30
|
+
* **stdin is the transport, so a handler never gets it.** `call` dispatches in-process through
|
|
31
|
+
the CLI's own parser, and three handlers read a paragraph from a pipe (RK9). Given the
|
|
32
|
+
client's pipe, one of them waits for an EOF no live client sends and eats every message queued
|
|
33
|
+
behind it — 18 minutes, holding the lock (RK170). :func:`_spent_stdin` substitutes a stream
|
|
34
|
+
already at EOF, which turns the deadlock into the refusal the format already owns. *Which*
|
|
35
|
+
three is :class:`Prose` on their own parsers rather than a comment in one handler (RK171), so
|
|
36
|
+
the argv is refused before it gets there and a fourth is named by a test and not by a session.
|
|
37
|
+
* **A broken config still starts.** `mcp` tolerates a `ConfigError` for the reason `guard`
|
|
38
|
+
does: the process is launched once for the whole session, and refusing to start would take
|
|
39
|
+
the tools away exactly when a typo in the config most needs the gate. `tools/list` then
|
|
40
|
+
describes the defaults, and the error is what the first `tools/call` returns.
|
|
41
|
+
|
|
42
|
+
The surface is what a task needs end to end, which RK24 got wrong by half. It exposed four
|
|
43
|
+
because one roadmap line named four, on the argument that the reads were "one `Bash` call
|
|
44
|
+
away" — and RK57 then made a plugin install with no console script at all, so on that machine
|
|
45
|
+
there is no shell command to fall back to. Starting a task needs `brief`, writing a rationale
|
|
46
|
+
needs `section add`, a line that leaves without shipping needs `retire`.
|
|
47
|
+
|
|
48
|
+
What stays out is what a tool cannot be: `init` and `adopt` run once, before the project is
|
|
49
|
+
governed, and `guard` and `mcp` are the harness's own entry points. `lint` exposes one argument
|
|
50
|
+
and deliberately not `--fix` — that one writes, and RK16 belongs where a human is standing (the
|
|
51
|
+
pre-commit hook), which is what keeps this tool honestly read-only.
|
|
52
|
+
|
|
53
|
+
`repair` (RK422) is not that decision reversed, and the distinction is worth stating because it
|
|
54
|
+
looks like one. Withholding `--fix` is a claim about **`lint`**: a tool a caller reaches for to
|
|
55
|
+
*read* a report must not write while answering. It was never a claim that the agent may not
|
|
56
|
+
repair — the agent already writes through twenty tools here, and what `repair` runs is those
|
|
57
|
+
same verbs, chosen from a table (RK420) instead of from a caller's reading of an English
|
|
58
|
+
message. So it grants no capability this surface did not have; it removes the turn spent
|
|
59
|
+
composing each command, which is the entire cost RK420 measured. Declared a writer, so the
|
|
60
|
+
read-only hint stays true of both, and `dry_run` is the read.
|
|
61
|
+
|
|
62
|
+
A nested subcommand is one tool: `section add` is `section_add` to the protocol, which has no
|
|
63
|
+
space in a name, and two argv words here. One :class:`Tool` holds both spellings rather than a
|
|
64
|
+
table mapping between them.
|
|
65
|
+
|
|
66
|
+
And what stays out is **this project's** question, not the package's (RK1360). `[files]` already
|
|
67
|
+
decided which roles a `role` argument may name; it did not decide whether the verb naming that
|
|
68
|
+
role existed, so `defer`, `resume` and `supersede` were 2,313 units every adopter paid for two
|
|
69
|
+
stores most of them never declare — and the consequence, which is the one that matters for every
|
|
70
|
+
vocabulary after this, is that a new role cost every project and so was argued against a ceiling
|
|
71
|
+
the arguing project was not using. :meth:`Tool.published` inverts that: the ceiling becomes what
|
|
72
|
+
this checkout can call, and `cost --tools` answers per checkout rather than per build. The honest
|
|
73
|
+
half is :class:`Withheld` — a name absent from the list still resolves and is still refused with
|
|
74
|
+
the `declare` that opens it, because an agent reads a missing name as a verb that does not exist.
|
|
75
|
+
"""
|
|
76
|
+
|
|
77
|
+
from __future__ import annotations
|
|
78
|
+
|
|
79
|
+
import argparse
|
|
80
|
+
import contextlib
|
|
81
|
+
import hashlib
|
|
82
|
+
import io
|
|
83
|
+
import json
|
|
84
|
+
import re
|
|
85
|
+
import sys
|
|
86
|
+
from collections.abc import Callable, Iterator, Mapping, Sequence
|
|
87
|
+
from dataclasses import dataclass, field
|
|
88
|
+
from functools import lru_cache
|
|
89
|
+
from pathlib import Path
|
|
90
|
+
from typing import Any, TextIO
|
|
91
|
+
|
|
92
|
+
from roadkeep import __version__
|
|
93
|
+
from roadkeep.adopting import OPT_IN
|
|
94
|
+
from roadkeep.config import PROSE_ROLES, ROLES, Config, ConfigError, Scope
|
|
95
|
+
from roadkeep import provenance
|
|
96
|
+
from roadkeep.provenance import engine, invocation, serving
|
|
97
|
+
# `words` from where it is *defined* and not from `budgeting`, which re-exports it (RK260):
|
|
98
|
+
# `config` already loads `schema`, and reaching the name through `budgeting` cost the guard
|
|
99
|
+
# 30 ms and eight modules — `authoring`, `sections`, `claiming`, `ids`, `markers` and the
|
|
100
|
+
# rest of the write path — on every denied edit, for one character-to-word division.
|
|
101
|
+
from roadkeep.kernel.schema import body_aim, width, words
|
|
102
|
+
|
|
103
|
+
#: The protocol revision this server answers with when the client asks for one it does not
|
|
104
|
+
#: know. Negotiation is "echo what the client asked for if we understand it": a server that
|
|
105
|
+
#: always answers with its own newest version fails clients that pinned an older one.
|
|
106
|
+
PROTOCOL = "2025-06-18"
|
|
107
|
+
KNOWN_PROTOCOLS = (PROTOCOL, "2025-03-26", "2024-11-05")
|
|
108
|
+
|
|
109
|
+
#: JSON-RPC's own codes. Only these three are reachable: a tool that fails is *not* a
|
|
110
|
+
#: protocol error — it answers with `isError`, so the model reads the refusal and retries,
|
|
111
|
+
#: instead of the client reporting a transport failure it cannot act on.
|
|
112
|
+
PARSE_ERROR = -32700
|
|
113
|
+
INVALID_REQUEST = -32600
|
|
114
|
+
METHOD_NOT_FOUND = -32601
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
@dataclass(frozen=True, slots=True)
|
|
118
|
+
class Prose:
|
|
119
|
+
"""A command that takes a paragraph off a pipe, declared beside the argument (RK171).
|
|
120
|
+
|
|
121
|
+
Three exposed tools reach `sys.stdin.read()` and neither `TOOLS` nor `cli.py` said which:
|
|
122
|
+
`add` on a section named with no body, `section add` on a body omitted, `section amend` on
|
|
123
|
+
the `-` its own help documents. `record add` cannot, exposing no body at all — and that
|
|
124
|
+
asymmetry is the point, because it is a property of the two files together and a comment in
|
|
125
|
+
one handler was the whole of it. So the parser declares it, the way :attr:`Tool.writes` made
|
|
126
|
+
`reads_only`/`writes_when` the parser's claim rather than a table beside it (RK167).
|
|
127
|
+
|
|
128
|
+
What it buys is not the deadlock — :func:`_spent_stdin` closed that whatever this says — but
|
|
129
|
+
that every one of the three refuses by *naming the argument*, and that a fourth exposed
|
|
130
|
+
tomorrow is named by a test rather than by the session that meets it.
|
|
131
|
+
"""
|
|
132
|
+
|
|
133
|
+
#: The argument carrying the prose. Omitting it or setting it to :attr:`sentinel` is what
|
|
134
|
+
#: sends the handler to the pipe.
|
|
135
|
+
dest: str
|
|
136
|
+
#: The spelling the CLI documents for "read it from stdin". One string, because a second
|
|
137
|
+
#: sentinel would be a second thing a caller has to know.
|
|
138
|
+
sentinel: str = "-"
|
|
139
|
+
#: Whether *omitting* the argument reads the pipe too, or only the sentinel does. False for
|
|
140
|
+
#: `section amend`, which refuses an amend with neither field rather than defaulting to it.
|
|
141
|
+
omitted: bool = True
|
|
142
|
+
#: The argument whose presence makes the read happen at all, where one does. `add` reads
|
|
143
|
+
#: only when a section was named: an `add` with no rationale must never block on a pipe,
|
|
144
|
+
#: which used to be a comment and is now the thing that says so.
|
|
145
|
+
gated_by: str = ""
|
|
146
|
+
#: The argument whose presence means this one does *not* read the pipe (RK1176). A body
|
|
147
|
+
#: named as a path is a body that arrived, so the omitted-argument read is off — which the
|
|
148
|
+
#: handler knew and this did not, and a resolution pass reading only this would have
|
|
149
|
+
#: refused `add --why - --section X --section-body-file f.md` for a clash that is not one.
|
|
150
|
+
unless: str = ""
|
|
151
|
+
|
|
152
|
+
def reached_by(self, arguments: Mapping[str, Any]) -> bool:
|
|
153
|
+
"""Whether this argv sends the handler to the pipe.
|
|
154
|
+
|
|
155
|
+
:attr:`unless` is read here for the reason `cli._reaches` reads it (RK1176), and it
|
|
156
|
+
became reachable when this surface started offering the path (RK1260): a body named as
|
|
157
|
+
a file is a body that arrived, so an `add` whose section body is a path is not one
|
|
158
|
+
:func:`_companioned` may refuse for having gone to a pipe that is not there.
|
|
159
|
+
"""
|
|
160
|
+
if self.gated_by and self.gated_by not in arguments:
|
|
161
|
+
return False
|
|
162
|
+
if self.unless and self.unless in arguments:
|
|
163
|
+
return False
|
|
164
|
+
if self.dest not in arguments:
|
|
165
|
+
return self.omitted
|
|
166
|
+
return arguments[self.dest] == self.sentinel
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
@dataclass(frozen=True, slots=True)
|
|
170
|
+
class Tool:
|
|
171
|
+
"""One subcommand, and which of its arguments an agent is allowed to set.
|
|
172
|
+
|
|
173
|
+
:attr:`unconditional` is a whitelist and not a filter: `add --ref` exists for adoption
|
|
174
|
+
(RK18) and would let a caller choose a pointer the tool derives, which is the one thing a
|
|
175
|
+
schema cannot then check.
|
|
176
|
+
|
|
177
|
+
**Declared here and not on the `add_argument`, which is where the withheld reasons went**
|
|
178
|
+
(RK1169). The asymmetry is that task's answer, and it is measured rather than argued: a
|
|
179
|
+
reason is prose about one argument that only a description reads, while exposure is the
|
|
180
|
+
fact :func:`serves` asks inside a `PreToolUse` the harness waits on — 44.6 ms by RK261,
|
|
181
|
+
against the 117 ms it costs to build the parser index. A whitelist on the parsers would
|
|
182
|
+
make the guard pay that to compose every denial. Nor is it a restatement in the first
|
|
183
|
+
place: the parser declares an argument and never who may set it, so which of them this
|
|
184
|
+
surface offers is a decision about *this* surface, and `cli.py` holding it inverts the
|
|
185
|
+
import `_DIVERGENT` is kept out of there for.
|
|
186
|
+
|
|
187
|
+
:attr:`conditional` is the exception that proves the rule (RK111): where a project declares
|
|
188
|
+
a shape the deriver cannot spell, withholding the field leaves that surface unable to write
|
|
189
|
+
a legal id at all.
|
|
190
|
+
|
|
191
|
+
**The answer is :meth:`exposed`, and the two declarations are its halves** (RK1157). That
|
|
192
|
+
field was called `exposes` — one letter from `exposed(config)`, and the shorter of the two —
|
|
193
|
+
so a reader asking what a tool offers got the half that is true on every project and reads
|
|
194
|
+
as total. Two tasks were filed against that reading in three iterations and one was shipped
|
|
195
|
+
before it surfaced: `add exposes: (block, symptom, why, …)` says an outline project cannot
|
|
196
|
+
name its anchor, and `exposed(config)` on that project ends in `ref`. Named for the
|
|
197
|
+
condition it is one side of, so the half is visible as a half.
|
|
198
|
+
"""
|
|
199
|
+
|
|
200
|
+
#: The subcommand path, space-separated where it is nested (`"section add"`). The argv
|
|
201
|
+
#: is this split; the tool's name is the same with `_`, because a protocol name may not
|
|
202
|
+
#: carry a space and a client shows what it is given.
|
|
203
|
+
command: str
|
|
204
|
+
unconditional: tuple[str, ...] = ()
|
|
205
|
+
#: Arguments this tool always passes, by dest — never exposed, so a caller cannot unset
|
|
206
|
+
#: one. This is how a **flag becomes a tool** (RK150): `readOnlyHint` is one boolean per
|
|
207
|
+
#: tool and `brief --claim` writes while `brief` does not, so the two are two tools over
|
|
208
|
+
#: one command, and the query keeps the hint that makes it free to ask (L5). By dest and
|
|
209
|
+
#: not as literal argv, so the flag is resolved through the same parser every exposed
|
|
210
|
+
#: argument is and a rename cannot leave a tool passing something that is gone.
|
|
211
|
+
always: tuple[str, ...] = ()
|
|
212
|
+
#: The protocol name where it is not the command path. Needed only where :attr:`always`
|
|
213
|
+
#: has put two tools on one command, and it names the **act** rather than the command,
|
|
214
|
+
#: because two names for one path is what a client would otherwise have to tell apart.
|
|
215
|
+
named: str = ""
|
|
216
|
+
#: Arguments exposed only where this project's config makes them the **one** way to spell
|
|
217
|
+
#: a legal value, by dest — the predicate is :data:`_CONDITIONAL` and the bound that then
|
|
218
|
+
#: narrows them to exactly that value is :data:`_BOUNDS` (RK111). By dest and by config,
|
|
219
|
+
#: never by hand: a field a caller may set on one project and not another is a difference
|
|
220
|
+
#: `roadkeep.toml` states (L6), so the tool schema varying is the config being read rather
|
|
221
|
+
#: than this surface holding a second opinion about it.
|
|
222
|
+
conditional: tuple[str, ...] = ()
|
|
223
|
+
#: The role this tool is the vocabulary of, where it has one — published only on a project
|
|
224
|
+
#: whose `[files]` declares it (RK1360). One role and never a set: a tool that would be
|
|
225
|
+
#: published under either of two roles is one whose refusal cannot name a single `declare`,
|
|
226
|
+
#: and a surface that withholds a verb owes the caller the command that opens it.
|
|
227
|
+
needs: str = ""
|
|
228
|
+
|
|
229
|
+
def published(self, config: Config) -> bool:
|
|
230
|
+
"""Whether this project is sent this tool at all (RK1360).
|
|
231
|
+
|
|
232
|
+
The narrowing :attr:`conditional` makes to a *field*, made to the tool: `[files]`
|
|
233
|
+
already decides which roles a `role` argument may name, and until now it did not
|
|
234
|
+
decide whether the verb naming that role existed. So `defer` and `resume` were 1,381
|
|
235
|
+
units every project paid for a store most of them never declared, and every vocabulary
|
|
236
|
+
added after this would have been charged to every adopter — which is what made
|
|
237
|
+
`[tools] session` an argument against a total no single project spends.
|
|
238
|
+
|
|
239
|
+
The other direction is the honest half: a tool absent here is still :func:`tool_named`
|
|
240
|
+
and still refused by :func:`call` with the `declare` that opens it, because an agent
|
|
241
|
+
reads a missing name as a verb that does not exist.
|
|
242
|
+
"""
|
|
243
|
+
return not self.needs or config.has(self.needs)
|
|
244
|
+
|
|
245
|
+
def exposed(self, config: Config) -> tuple[str, ...]:
|
|
246
|
+
"""Every argument a caller may set on *this* project, in declaration order.
|
|
247
|
+
|
|
248
|
+
The conditional ones come last, so the argv stays stable and diffable when a project
|
|
249
|
+
turns one on — a field that reordered the others would make the same call render two
|
|
250
|
+
command lines.
|
|
251
|
+
"""
|
|
252
|
+
opened = tuple(dest for dest in self.conditional if _CONDITIONAL[dest].opens(config))
|
|
253
|
+
return (*self.unconditional, *opened)
|
|
254
|
+
|
|
255
|
+
@property
|
|
256
|
+
def name(self) -> str:
|
|
257
|
+
"""The protocol name: the command path with `_` where its space is (RK59).
|
|
258
|
+
|
|
259
|
+
A tool name may not carry a space, and a client shows the name it is given — so
|
|
260
|
+
`section add` is `section_add` there and stays two argv words here. A hyphen goes the
|
|
261
|
+
same way (RK70): `non-goal add` is one command spelled in two conventions, and the
|
|
262
|
+
name a client renders should not be where that shows.
|
|
263
|
+
"""
|
|
264
|
+
return self.named or self.command.replace(" ", "_").replace("-", "_")
|
|
265
|
+
|
|
266
|
+
@property
|
|
267
|
+
def argv_head(self) -> list[str]:
|
|
268
|
+
return self.command.split()
|
|
269
|
+
|
|
270
|
+
@property
|
|
271
|
+
def writes(self) -> bool:
|
|
272
|
+
"""Whether a successful call changes a governed file — `readOnlyHint`, derived (RK168).
|
|
273
|
+
|
|
274
|
+
Stated per tool until now, and the reason given was `lint`: it writes when `--fix` is
|
|
275
|
+
passed and is read-only *here* only because that flag is not exposed. RK167 gave a
|
|
276
|
+
parser the way to say which flag makes a read a write, and RK168 put it on `lint` — so
|
|
277
|
+
the answer is derivable and stops being a boolean two places could disagree about.
|
|
278
|
+
|
|
279
|
+
Two clauses and no table: a command whose parser does not call itself a read writes, and
|
|
280
|
+
a read writes exactly when this tool passes the flag its parser names — exposed, so a
|
|
281
|
+
caller may, or in :attr:`always`, so it always does.
|
|
282
|
+
|
|
283
|
+
:attr:`conditional` counts as exposed without asking the config, which is the safe
|
|
284
|
+
direction: a hint that flipped to read-only on some projects would be a client caching
|
|
285
|
+
"free to ask" for a tool that writes, and `readOnlyHint` is a promise or it is noise.
|
|
286
|
+
"""
|
|
287
|
+
return self.writes_of(_subparser(self.command))
|
|
288
|
+
|
|
289
|
+
def writes_of(self, parser: argparse.ArgumentParser) -> bool:
|
|
290
|
+
""":attr:`writes`, read off a parser the caller already resolved (RK174).
|
|
291
|
+
|
|
292
|
+
The same two clauses, against a parser passed in rather than looked up: `descriptor`
|
|
293
|
+
holds this tool's own parser by the time it needs the hint, and resolving it a second
|
|
294
|
+
time was half of what `tools/list` spent.
|
|
295
|
+
"""
|
|
296
|
+
if not parser.get_default("reads_only"):
|
|
297
|
+
return True
|
|
298
|
+
# One argument or several (RK307), read through the CLI's own accessor rather than
|
|
299
|
+
# off the default: a tuple compared as a string is a tool whose `readOnlyHint` says
|
|
300
|
+
# free-to-ask about an argv that writes.
|
|
301
|
+
from roadkeep.verbs.declaring import writes_when # noqa: PLC0415 - RK1171
|
|
302
|
+
|
|
303
|
+
settable = (*self.unconditional, *self.conditional, *self.always)
|
|
304
|
+
return any(flag in settable for flag in writes_when(parser))
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
#: What a task needs end to end (RK24's four, extended by RK59). Order is the order
|
|
308
|
+
#: `tools/list` reports: the write path first, then the reads, because that is the order a
|
|
309
|
+
#: session uses them in and a client renders the list as given.
|
|
310
|
+
#:
|
|
311
|
+
#: `init` and `adopt` are deliberately absent — they run once, before the project is
|
|
312
|
+
#: governed — and so are `guard` and `mcp`, which are the harness's own entry points.
|
|
313
|
+
TOOLS: tuple[Tool, ...] = (
|
|
314
|
+
# `section` and `section_body` are exposed for the reason `section add`'s body is: the
|
|
315
|
+
# rationale is the second half of one write (RK93), and a client that cannot pass it
|
|
316
|
+
# here is one whose every `add` leaves a pointer for the gate to refuse.
|
|
317
|
+
# `task_id` is conditional and every other id on the write path is derived (RK111): a
|
|
318
|
+
# project that declares `[ids] suffix` has a legal shape `spell_id` never produces, so the
|
|
319
|
+
# split the skill prescribes was an invocation only the CLI could make. Opened only there,
|
|
320
|
+
# and bounded to *require* the letter — so what the field buys is the id the counter cannot
|
|
321
|
+
# reach, and never the number it would have handed out.
|
|
322
|
+
# `ref` is conditional for the same reason, one field over (RK241): under `ref_scheme =
|
|
323
|
+
# "outline"` the anchor is the caller's to name and nothing derives it, so withholding it
|
|
324
|
+
# made every `add` on such a project refuse `ref.missing` — the RK141/RK144 deadlock again,
|
|
325
|
+
# with a source checkout as the only remaining door. Closed where the scheme derives the
|
|
326
|
+
# pointer, which is where offering it would be choosing what the tool computes.
|
|
327
|
+
# `section_body_file` is exposed for the reason the body is, read one step further (RK1260):
|
|
328
|
+
# the rationale is the longest thing an author writes and its limit is the one most often
|
|
329
|
+
# met, so over a transport where a refusal costs the whole payload again this is the surface
|
|
330
|
+
# where a path is worth most — and a stdio server shares the caller's disk, which is what
|
|
331
|
+
# the withheld reason said it did not.
|
|
332
|
+
Tool(
|
|
333
|
+
"add",
|
|
334
|
+
# `requires` rides with `deps` (RK1297): the two groups are the line's two statements
|
|
335
|
+
# about whether it can be started, and the agent this surface serves is the one
|
|
336
|
+
# filing the task it just discovered it cannot finish.
|
|
337
|
+
("block", "symptom", "why", "deps", "requires", "status", "section", "section_body",
|
|
338
|
+
"section_body_file"),
|
|
339
|
+
conditional=("task_id", "ref"),
|
|
340
|
+
),
|
|
341
|
+
# The key to a deadlock the agent meets first (RK141): `ship` refuses an undeclared
|
|
342
|
+
# block, the guard denies the edit that would declare it, and no other verb writes a
|
|
343
|
+
# heading — so a correctly wired project could not open a block at all.
|
|
344
|
+
# `after` rides with it (RK145): block order is what `list` reports and what a reader takes
|
|
345
|
+
# for the shape of the plan, and without it a phase belonging between two existing ones was
|
|
346
|
+
# appended after both — repaired only by reordering three files by hand.
|
|
347
|
+
# `organise` rides with them (RK405): a ledger organised by nothing is a project every
|
|
348
|
+
# `ship` refuses and no bare `block add` repairs, and the agent that meets that refusal
|
|
349
|
+
# is the one the guard denies the hand-edit to — a flag only the CLI can reach would
|
|
350
|
+
# leave this surface holding the deadlock the two above exist to break.
|
|
351
|
+
Tool("block add", ("label", "title", "after", "organise")),
|
|
352
|
+
# And the key that could not close the door (RK144). Exposed for the same reason: the
|
|
353
|
+
# caller that opened a label by mistake is the one the guard denies the hand-edit to, and
|
|
354
|
+
# the removal is refused by name over anything filed under it.
|
|
355
|
+
# `prose` rides with it (RK237): the agent that finds a block whose every line shipped is
|
|
356
|
+
# the one the guard denies the `Edit` to, and the note under that heading was the whole
|
|
357
|
+
# obstacle — a flag only a human can pass is no door on the surface this ships for.
|
|
358
|
+
Tool("block drop", ("label", "prose")),
|
|
359
|
+
# The third key those two left unmade (RK1204). Exposed for the reason both of them are,
|
|
360
|
+
# and more sharply: `drop` plus `add` is refused the moment a line is filed under the
|
|
361
|
+
# label, so after the first `add` the hand-edit the guard denies was the only repair — and
|
|
362
|
+
# over this transport there is no hand-edit at all.
|
|
363
|
+
Tool("block amend", ("label", "title")),
|
|
364
|
+
# The key RK141/RK144's pair never cut (RK403): a doubled heading is the state every write
|
|
365
|
+
# refuses with `merge the two regions by hand`, and the guard denies exactly that edit — so
|
|
366
|
+
# an agent that reaches it over MCP, where there is no hand-edit at all, had no door out.
|
|
367
|
+
# `prose` rides with it (RK237) for the same reason it rides with `block drop`.
|
|
368
|
+
Tool("block merge", ("label", "prose")),
|
|
369
|
+
# The declaration `init` could not make twice (RK1264), and the three keys above read one
|
|
370
|
+
# table over: `[files]` is written once, by the command that refuses to run twice, so a role
|
|
371
|
+
# declined at scaffold time was retrofitted by hand-editing configuration — which on this
|
|
372
|
+
# surface is the hand edit the guard denies and so no edit at all. `init` and `adopt` stay
|
|
373
|
+
# withheld beside it and the line between them is *when*: those run before a project is
|
|
374
|
+
# governed, and this is a write on one that already is, reached from a `defer` refusal.
|
|
375
|
+
Tool("declare", ("role", "path")),
|
|
376
|
+
# The write a session makes first, and the one flag that became a tool (RK149, RK150): it
|
|
377
|
+
# is `brief --claim`, so the answer is everything needed to start the task *and* the
|
|
378
|
+
# marker that stops the next agent being handed it — while `brief` and `pick` below stay
|
|
379
|
+
# honestly read-only, which is what keeps consulting the backlog free.
|
|
380
|
+
# `have` beside them for the reason it is on `brief` and `pick` below (RK1297), found
|
|
381
|
+
# missing here by RK1369: this is the call that *starts* a task, so a requirement the
|
|
382
|
+
# machine does satisfy is one the caller has to be able to state at the moment it takes
|
|
383
|
+
# the line — and without it this tool sets aside the very lines `brief` would have offered.
|
|
384
|
+
Tool(
|
|
385
|
+
"brief",
|
|
386
|
+
("id", "block", "designed", "have"),
|
|
387
|
+
always=("claim",),
|
|
388
|
+
named="claim",
|
|
389
|
+
),
|
|
390
|
+
# The *other* verb with that word on it, which the tool above is why nobody noticed was
|
|
391
|
+
# missing (RK308). RK150's own sentence is the finding — a flag only the CLI can reach is a
|
|
392
|
+
# flag the agent this ships for cannot pass — and it applies unchanged to the whole of RK280:
|
|
393
|
+
# an agent driving this over the protocol declared no scope, so every changed path came back
|
|
394
|
+
# `loose` and the analysis `git add -A` cannot make was the one it could not ask for.
|
|
395
|
+
#
|
|
396
|
+
# `named` for the act, which is what the collision argues for rather than against: the tool
|
|
397
|
+
# above *takes a line* and this one *says what the commit owns*. The read half stays at the
|
|
398
|
+
# terminal — `theirs` and `loose` are `git status` in the answering process's checkout, and
|
|
399
|
+
# `ship` already prints the scope it releases at the one moment it is wanted (RK298), so
|
|
400
|
+
# exposing it would add a second answer to a question that is already answered.
|
|
401
|
+
#
|
|
402
|
+
# `have` rides with the tool above rather than with this one, and that is not a choice:
|
|
403
|
+
# this is the `claim` *command*, whose act is declaring a scope, and the requirement word
|
|
404
|
+
# belongs to `pick` and `brief` (RK1297). The tool that starts a task is `claim` two entries
|
|
405
|
+
# up — where RK1369 found the flag missing, `brief` offering it and its own sibling not.
|
|
406
|
+
Tool("claim", ("id", "path", "add_path"), named="scope"),
|
|
407
|
+
Tool("status", ("id", "marker")),
|
|
408
|
+
# `lines` for `record amend`'s reason one file over (RK195): this is the door an adopting
|
|
409
|
+
# project reaches for, and an adopted roadmap is the only place a wrapped line comes from.
|
|
410
|
+
# `requires` beside `deps` for `add`'s reason, and one the remedy table makes binding
|
|
411
|
+
# (RK1297): all four `requires.*` findings name this flag as their door, and a door only
|
|
412
|
+
# a terminal can open is a finding the agent that caused it cannot close.
|
|
413
|
+
Tool("amend", ("id", "why", "deps", "requires", "ref", "lines")),
|
|
414
|
+
# The field `amend` excludes, at its own door (RK178). Exposed beside it because the agent
|
|
415
|
+
# that discovers a premise is false is the one executing the line, and the exit designed
|
|
416
|
+
# for it — retire plus add — spends an id and deletes a section that was already right.
|
|
417
|
+
# `typo` rides with it (RK414): which of the two acts a rewording is cannot be inferred
|
|
418
|
+
# from the strings, so it is the caller's declaration — and the caller this surface is
|
|
419
|
+
# for is the one whose every restatement would otherwise read as a premise turning false.
|
|
420
|
+
Tool("restate", ("id", "symptom", "lines", "typo")),
|
|
421
|
+
# The repair a merge needs, exposed for the reason it exists at all (RK97): the agent
|
|
422
|
+
# that hits a doubled id is the one the hook denies a hand-edit to, so a door only a
|
|
423
|
+
# human can reach is no door. `to` is offered because the derived answer is not always
|
|
424
|
+
# the wanted one — it is refused against every source either way.
|
|
425
|
+
Tool("renumber", ("id", "to")),
|
|
426
|
+
# `part` is exposed because the agent shipping half of something is the one that needs
|
|
427
|
+
# it (RK121): without it the only honest options are a ledger entry that overstates and
|
|
428
|
+
# a hand-edited qualifier the grammar reads and no verb maintains.
|
|
429
|
+
# `why` is required on the write path and not merely offered (RK142): the roadmap's
|
|
430
|
+
# sentence is a problem statement, and the entry that inherited it read as a defect
|
|
431
|
+
# report filed under a heading meaning "done".
|
|
432
|
+
# `lines` for `record amend`'s reason (RK193): the ship that completes a partial rewrites
|
|
433
|
+
# that entry's span, and where the ledger arrived wrapped the count is the same door.
|
|
434
|
+
# `superseded_design` because the agent that finds the design stale is this one (RK310):
|
|
435
|
+
# it claimed the line, read the section, and is the only reader who will ever know — and
|
|
436
|
+
# the trace it would otherwise leave is a hand-edit to the file the guard denies.
|
|
437
|
+
# `remainder` rides with `part` (RK1233): the agent shipping a half is the one that will
|
|
438
|
+
# pick the line up later, and over this transport there is no file to read the rest out of
|
|
439
|
+
# — which is the subtraction the whole task exists to remove.
|
|
440
|
+
# `recorded_in` for the same reason pointed the other way (RK1267): the agent deleting the
|
|
441
|
+
# section is the one that just moved the half of it worth keeping, so the destination is
|
|
442
|
+
# known here and nowhere later.
|
|
443
|
+
# `decides` for the same reason again (RK1269): the constraint that outlives the code is
|
|
444
|
+
# read out of the design by the agent about to delete it, and nowhere later.
|
|
445
|
+
Tool(
|
|
446
|
+
"ship",
|
|
447
|
+
(
|
|
448
|
+
"id",
|
|
449
|
+
"why",
|
|
450
|
+
"part",
|
|
451
|
+
"remainder",
|
|
452
|
+
"lines",
|
|
453
|
+
"superseded_design",
|
|
454
|
+
"recorded_in",
|
|
455
|
+
"decides",
|
|
456
|
+
),
|
|
457
|
+
# Where the decision's body goes, on a project whose anchors are addresses (RK1363).
|
|
458
|
+
# Conditional for `add --ref`'s reason exactly: nothing derives it there, so a
|
|
459
|
+
# `--decides` without it files a record whose body no later call can reach.
|
|
460
|
+
conditional=("decides_ref",),
|
|
461
|
+
),
|
|
462
|
+
Tool("retire", ("id", "reason", "superseded_by")),
|
|
463
|
+
# The decisions role's one departure (RK1274), served for the reason `ship --decides` is:
|
|
464
|
+
# the session that just replaced a constraint is the one that knows which it replaced, and
|
|
465
|
+
# over this transport the alternative is a hand edit the guard denies.
|
|
466
|
+
# `needs` beside it for the first time (RK1360): this verb is the decisions role's grammar
|
|
467
|
+
# and nothing else's, so a project that files no decisions was reading its 932 units before
|
|
468
|
+
# every call it made.
|
|
469
|
+
Tool("supersede", ("id", "by"), needs="decisions"),
|
|
470
|
+
# The pause and the return, both of which already refuse where `[files]` declares no store
|
|
471
|
+
# — so publishing them there was 1,381 units describing a refusal (RK1360). The refusal
|
|
472
|
+
# stays reachable and now names `declare deferred`, which is the door it always named.
|
|
473
|
+
Tool("defer", ("id", "reason"), needs="deferred"),
|
|
474
|
+
Tool("resume", ("id", "marker"), needs="deferred"),
|
|
475
|
+
# `supersedes` rides with it because the revert is one transaction (RK395): the entry that
|
|
476
|
+
# says the work did not hold and the pointer on the entry that says it shipped are two
|
|
477
|
+
# edits an agent cannot make separately — the second one is a hand edit the guard denies.
|
|
478
|
+
#
|
|
479
|
+
# `lines` rode with it until RK1053 narrowed that pointer to the entry's first line, and
|
|
480
|
+
# is withdrawn here (RK1056): the write it authorised no longer exists, so every call it
|
|
481
|
+
# can appear in is refused. The CLI keeps declaring it — a flag somebody's script spells
|
|
482
|
+
# is answered better by `NoSpan` than by argparse — and this surface is re-derived every
|
|
483
|
+
# session, so it has no legacy to keep and pays the cost of one: a published property
|
|
484
|
+
# whose whole description is *refused* is bytes an agent reads before every call it makes.
|
|
485
|
+
Tool("record add", ("block", "symptom", "why", "supersedes")),
|
|
486
|
+
# The ledger's update (RK124). `part` rides with it because a qualifier that stopped
|
|
487
|
+
# being true is the commonest correction an entry needs, and the agent that wrote it is
|
|
488
|
+
# the one the hook denies a hand-edit to.
|
|
489
|
+
# `lines` rides with it for `record drop --line`'s reason (RK179): on a ledger whose
|
|
490
|
+
# bullets wrap, the correction replaces text the parse never held, and the count is the
|
|
491
|
+
# caller saying they read it — a door the agent this ships for has to be able to reach.
|
|
492
|
+
Tool("record amend", ("id", "why", "part", "lines")),
|
|
493
|
+
# The move `record amend` refuses to spell as a correction (RK143). Exposed beside it
|
|
494
|
+
# because an entry filed under the wrong block is what `ship` writes from a line filed
|
|
495
|
+
# under the wrong block — an agent's own slip, and the hand-edit that repaired it is the
|
|
496
|
+
# one the guard denies that agent.
|
|
497
|
+
Tool("record move", ("id", "to_block")),
|
|
498
|
+
# `line` rides with both because the choice is the fix (RK127): two entries for one id
|
|
499
|
+
# can be one slip or two deliveries, and the default picked the entry that earned the id.
|
|
500
|
+
Tool("record drop", ("id", "line")),
|
|
501
|
+
Tool("record renumber", ("id", "line", "to")),
|
|
502
|
+
Tool("non-goal add", ("lead", "why")),
|
|
503
|
+
# The correction the other two bullet grammars had and this one did not (RK368). Exposed
|
|
504
|
+
# beside them for `record amend`'s reason: without it a reworded constraint is a drop and
|
|
505
|
+
# an append, which moves the bullet to the end of a list a reader takes for the plan's shape.
|
|
506
|
+
Tool("non-goal amend", ("lead", "why")),
|
|
507
|
+
Tool("non-goal drop", ("lead",)),
|
|
508
|
+
# The roadmap's third list (RK1265), and the three writes are exposed for the reason the
|
|
509
|
+
# non-goals' are: the caller that has to say what finishes a block is the agent driving it,
|
|
510
|
+
# and a bullet only a hand edit could write is one the guard denies outright. `list` rides
|
|
511
|
+
# with them and not with `brief`: that command prints this task's block, and the question
|
|
512
|
+
# *which blocks claim what* is asked before a task exists to brief.
|
|
513
|
+
# `task` rides beside `block` on all four (RK1268): the unit an agent executes is the line,
|
|
514
|
+
# so the address it wants is the one this transport is reached from — and a field that
|
|
515
|
+
# existed only on the CLI would be a criterion an agent could read and never write.
|
|
516
|
+
Tool("criterion add", ("block", "task", "lead", "why")),
|
|
517
|
+
Tool("criterion amend", ("lead", "block", "task", "why")),
|
|
518
|
+
Tool("criterion drop", ("lead", "block", "task")),
|
|
519
|
+
Tool("criterion list", ("block", "task")),
|
|
520
|
+
# The other list this file holds that is not task lines (RK325). Exposed for the reason
|
|
521
|
+
# the non-goals are: the agent that ships a queued id is the one that has to take it out,
|
|
522
|
+
# and the file it now lives in is the one the guard denies an edit to.
|
|
523
|
+
Tool("priority add", ("token", "first", "after")),
|
|
524
|
+
Tool("priority drop", ("token",)),
|
|
525
|
+
# The door the other two could not be reached without (RK427). Exposed because the caller
|
|
526
|
+
# that meets the deadlock is this one: the gate names a defect in `roadkeep.toml`, both
|
|
527
|
+
# verbs above refuse having never opened it, and the hand edit is what the guard denies.
|
|
528
|
+
Tool("priority migrate", ()),
|
|
529
|
+
# `body_file` rides with the body on both (RK1260), and these are the two verbs whose whole
|
|
530
|
+
# input is a paragraph: a section refused at 257 words costs the other 250 again here, where
|
|
531
|
+
# at a terminal it costs an edit and a path. The same disk either way — this server speaks
|
|
532
|
+
# over the caller's own stdin, so the file it is handed is one it can open.
|
|
533
|
+
Tool("section add", ("anchor", "title", "body", "body_file", "role")),
|
|
534
|
+
# The correction an open task's design needs (RK123). Exposed for the reason the whole
|
|
535
|
+
# write path is: the agent that narrowed a hypothesis is the one the hook denies a hand
|
|
536
|
+
# edit to, and until this verb existed the only way through was shipping the task.
|
|
537
|
+
# `replace` and `replacement` ride with them (RK1263), and this transport is where the
|
|
538
|
+
# whole-body form costs most: a refusal on a 250-word body re-sends the table and the fence
|
|
539
|
+
# with it, and a one-clause correction names two strings. Exposed because the caller with
|
|
540
|
+
# eight sections to correct is this one, the hand edit being what the guard denies.
|
|
541
|
+
Tool(
|
|
542
|
+
"section amend",
|
|
543
|
+
("anchor", "title", "body", "body_file", "replace", "replacement", "role"),
|
|
544
|
+
),
|
|
545
|
+
# The address `section amend` refuses to spell as a correction (RK377), and `renumber`
|
|
546
|
+
# cannot reach under an outline. Exposed beside them because the state it repairs is one
|
|
547
|
+
# an adopting corpus arrives with — 13 doubled addresses in Turing — and the only other
|
|
548
|
+
# way through is the hand edit this server's own guard denies the agent making it.
|
|
549
|
+
Tool("section move", ("anchor", "to", "role")),
|
|
550
|
+
Tool("section drop", ("anchor", "role")),
|
|
551
|
+
# The direction a pointer does not go (RK1310), and this transport is the whole reason it
|
|
552
|
+
# is a verb: an id resolves to a section and nothing resolved a sentence to one, so a
|
|
553
|
+
# caller holding only the text looped through `section show` — which over MCP is a file
|
|
554
|
+
# printed into a context window, once per guess, against a read whose answer is a count.
|
|
555
|
+
Tool("section find", ("text", "role")),
|
|
556
|
+
# The read the four `block` writes above assume has happened (RK1188), beside the other
|
|
557
|
+
# read a proposal makes: `non-goal list` answers what may not be proposed and this one
|
|
558
|
+
# answers where it would go. Exposed for a sharper version of their reason — the agent
|
|
559
|
+
# that may not hand-edit the roadmap may not grep it either, so over this transport the
|
|
560
|
+
# labels were unobtainable and `add --block` was a guess.
|
|
561
|
+
Tool("block list"),
|
|
562
|
+
Tool("non-goal list"),
|
|
563
|
+
Tool("priority list"),
|
|
564
|
+
# `records` is exposed because the caller paying for them is this one (RK264): the
|
|
565
|
+
# percentiles are the answer and the sample was 95% of the payload, so the evidence is
|
|
566
|
+
# a flag an agent disputing the figure can still pass rather than a read it cannot make.
|
|
567
|
+
Tool("weight", ("block", "records")),
|
|
568
|
+
# That read's mirror (RK492), and served for the same reason it is: an agent about to
|
|
569
|
+
# continue a migration asks how many sites are left, and the alternative to a command is
|
|
570
|
+
# a grep whose pattern it composed itself and whose misses are silent (L5).
|
|
571
|
+
Tool("remaining", ("id",)),
|
|
572
|
+
# The mirror of that mirror (RK1184), served for the same reason: an agent about to
|
|
573
|
+
# ship asks what would show the task finished, and the alternative to a command is a
|
|
574
|
+
# grep whose pattern it composed itself and whose misses are silent (L5).
|
|
575
|
+
Tool("evidence", ("id",)),
|
|
576
|
+
# The other pre-`add` read, and the one this transport needs most (RK190): `maxLength`
|
|
577
|
+
# publishes the field's own ceiling and cannot publish the line's, so without this the
|
|
578
|
+
# binding number reaches the author only as a refusal — a linter, one layer in.
|
|
579
|
+
# `ref` rides with it for the reason the budget exists (RK265): under the outline scheme
|
|
580
|
+
# the pointer is the caller's, and a budget that did not count it approved a why the
|
|
581
|
+
# `add` one call later refused — the verdict-after-the-prose, from the verb that
|
|
582
|
+
# replaces it. Conditional, because under the id scheme there is nothing to name.
|
|
583
|
+
# `anchor`, `role`, `non_goal` and `lead` ride with it because they are the *other two*
|
|
584
|
+
# prose limits (RK283), and both are larger than the line's: a section body is the longest
|
|
585
|
+
# thing an author writes and its ceiling reached them only as a refusal, at 366 words
|
|
586
|
+
# against 300. Over this transport most of all — `maxLength` cannot publish a word count.
|
|
587
|
+
# `file` is the fourth subject (RK345) and the one this transport cannot answer any other
|
|
588
|
+
# way: an agent editing an every-turn file has no `wc` here, so the room it is composing
|
|
589
|
+
# against would otherwise arrive as a gate at the end of the turn.
|
|
590
|
+
# `tools` is the fifth (RK464), and the one subject on this list that is about *this
|
|
591
|
+
# list*: what the schema published here costs a session, which is the read RK30 makes
|
|
592
|
+
# about an every-turn file and nobody had made about the surface. Exposed for `file`'s
|
|
593
|
+
# reason read back — the caller paying it is the one connected to this server.
|
|
594
|
+
Tool(
|
|
595
|
+
"budget",
|
|
596
|
+
# `session` joins them for `tools`' reason and one more (RK1097): it is the read the
|
|
597
|
+
# gate's own message sends a caller to, and a door this surface serves whose call it
|
|
598
|
+
# withholds is the shape `Door.call` returns None for.
|
|
599
|
+
# `why` and `body` are the drafts (RK1190), and this transport is where they matter
|
|
600
|
+
# most: `maxLength` publishes a character ceiling and the write measures against an
|
|
601
|
+
# allowance the line moves, so the agent composing here learned the difference by
|
|
602
|
+
# being refused — and a refusal over MCP costs the whole payload again.
|
|
603
|
+
# `body_file` is **not** exposed, and it is the one path this surface still withholds
|
|
604
|
+
# (RK1260): the three verbs that *write* a body take one now, and a body refused there
|
|
605
|
+
# costs the corrected field alone — so the payload this read exists to save re-sending
|
|
606
|
+
# is the draft that arrived in the call, which is the only one left to price.
|
|
607
|
+
# `brief` is the sixth (RK1286), and the one subject about a **read**: what the answer
|
|
608
|
+
# this project recommends over reading the file costs a tool result. Exposed for
|
|
609
|
+
# `tools`' reason exactly — the caller paying it is the one on the other end of it.
|
|
610
|
+
# `retire` is the seventh (RK1305), and the write off this line that nothing priced:
|
|
611
|
+
# a retirement's reason shares the ledger's limit with a derived prefix, so the number
|
|
612
|
+
# that binds is neither the published ceiling nor the one a ship is quoted — and over
|
|
613
|
+
# this transport the refusal it replaces costs the whole payload again.
|
|
614
|
+
("id", "block", "deps", "status", "symptom", "why", "anchor", "role", "body",
|
|
615
|
+
"non_goal", "lead", "file", "retire"),
|
|
616
|
+
conditional=("ref",),
|
|
617
|
+
),
|
|
618
|
+
# The other tense (RK1321). `tools`, `session` and `brief` left `budget` with the verb
|
|
619
|
+
# they belong to: eight subjects under one name made it the largest served tool, so
|
|
620
|
+
# whichever arrived last was refused by a per-tool ceiling none of them was about. Exposed
|
|
621
|
+
# for the reason RK464 and RK1286 exposed them at all — the caller paying this surface is
|
|
622
|
+
# the one on the other end of it, and it has no `wc` here to ask with.
|
|
623
|
+
Tool("cost", ("tools", "brief", "session")),
|
|
624
|
+
# `designed` is exposed on both for the reason it exists (RK83): the caller that asks
|
|
625
|
+
# to execute a block over MCP is the one that was handed a design session, and a flag
|
|
626
|
+
# only the CLI can reach is a flag the agent this ships for cannot pass.
|
|
627
|
+
# `have` rides with it for that argument read backwards (RK1297): the caller this
|
|
628
|
+
# surface serves is the one with no hands, so it is the caller that passes **nothing**
|
|
629
|
+
# and gets the hardware lines set aside. Exposed all the same, because an agent working
|
|
630
|
+
# a checkout where the machine does have the thing is the one that can say so — and a
|
|
631
|
+
# flag it could not pass would make that a fact only a terminal can state.
|
|
632
|
+
Tool("brief", ("id", "block", "designed", "have")),
|
|
633
|
+
Tool("pick", ("block", "designed", "have")),
|
|
634
|
+
Tool("list", ("block", "role", "marker")),
|
|
635
|
+
Tool("deps", ("id",)),
|
|
636
|
+
# `baseline` and nothing else (RK84): it is the flag that makes the answer readable on a
|
|
637
|
+
# project with standing debt — "did what I just wrote add anything" rather than a count
|
|
638
|
+
# of 317 the caller cannot attribute — and it reads a revision without writing one.
|
|
639
|
+
Tool("lint", ("baseline",)),
|
|
640
|
+
# The verb this whole surface exists for (RK422). `lint` says what drifted and now says
|
|
641
|
+
# what closes each one; this spends that in a single call, which is the difference
|
|
642
|
+
# between a caller that fixes a file and a caller that spends a turn per finding
|
|
643
|
+
# composing the command from a sentence. `dry_run` is the flag that makes it readable
|
|
644
|
+
# before it is trusted — the same argument `install --check` and `adopt` are built on,
|
|
645
|
+
# and the one flag here that changes whether anything is written at all.
|
|
646
|
+
Tool("repair", ("dry_run",)),
|
|
647
|
+
# And the read beside the pair (RK423). A code is the only stable name a defect has, and
|
|
648
|
+
# a caller meeting one first had nowhere to look it up — so the alternative to this tool
|
|
649
|
+
# is grepping the package, which is the context cost L5 exists to remove. `code` is
|
|
650
|
+
# optional here for the reason it is on the CLI: with none, the answer is the vocabulary.
|
|
651
|
+
Tool("explain", ("code",)),
|
|
652
|
+
# The read before a proposal that `non_goal_list` is the other half of (RK385). Exposed
|
|
653
|
+
# because the caller filing the duplicate is this one: RK378 restated RK340 the day after
|
|
654
|
+
# it shipped, and the collision surfaced only once a worker claimed the line.
|
|
655
|
+
# `near` is exposed for the reason the whitelist exists at all, read the other way: it
|
|
656
|
+
# is the caller's sentence and nothing derives it (RK442). This is the read an agent
|
|
657
|
+
# makes immediately before an `add`, over a transport where the whole block arriving as
|
|
658
|
+
# a tool result is the cost L5 is about — so withholding it here would leave the one
|
|
659
|
+
# surface that most needs the narrow answer asking for the file.
|
|
660
|
+
Tool("delivered", ("block", "near")),
|
|
661
|
+
# The eight reads the shipped skill names and this surface withheld (RK463). `serving`'s
|
|
662
|
+
# own opening records that argument being had and settled once: RK24 exposed four tools
|
|
663
|
+
# because one roadmap line named four, on the ground that the reads were "one `Bash` call
|
|
664
|
+
# away" — and RK57 then made a plugin install with no console script at all, so on that
|
|
665
|
+
# machine there is no shell command to fall back to. Counted by the spelling the skill
|
|
666
|
+
# uses for a command: `anchors` five times, `origin` and `reversals` twice, the rest once.
|
|
667
|
+
#
|
|
668
|
+
# `anchors` is the sharpest of them. Under `ref_scheme = "outline"` the pointer is the
|
|
669
|
+
# caller's to name, and the skill says `--next` "is the read an `add --ref` makes every
|
|
670
|
+
# time" — so on a plugin-installed outline project an agent was told to derive an address
|
|
671
|
+
# by a command it had no way to run, while the tool that refuses a wrong one was served.
|
|
672
|
+
#
|
|
673
|
+
# None of the eight writes, so each keeps the read-only hint that makes asking free (L5).
|
|
674
|
+
# What is *not* added is every remaining read: `guard` and `mcp` are the harness's own
|
|
675
|
+
# entry points, `report`, `replay`, `capture filed` and `capture sweep` are the capture
|
|
676
|
+
# family a person runs against paths on their own disk (RK87, RK1142, RK1394) — the sweep
|
|
677
|
+
# most of all, deletion being the one write here whose subject is evidence — and a
|
|
678
|
+
# tool list is context an agent pays for on every turn — so the line is the skill, which
|
|
679
|
+
# is the same authority that decides which command to call in the first place.
|
|
680
|
+
Tool("anchors", ("family", "block", "role", "only_next", "claims")),
|
|
681
|
+
# The one read whose subject is `roadkeep.toml` rather than a governed file (RK1270). Served
|
|
682
|
+
# because the caller that has to declare a key is the agent this transport is reached from,
|
|
683
|
+
# and the file it would otherwise guess at is the one every other rule here is read out of.
|
|
684
|
+
Tool("config", ("table",)),
|
|
685
|
+
# And the write beside that read (RK1272), which is the one table an agent could describe
|
|
686
|
+
# and not touch: `[limits]`, `[budgets]`, `[tools]` and `[claims]` were a hand edit, and
|
|
687
|
+
# over this transport a hand edit is no edit at all.
|
|
688
|
+
# `--because` is served for that same reason and no weaker one (RK1293): the argument for a
|
|
689
|
+
# number was ruled into the commit body, which on this transport is composed by a tool this
|
|
690
|
+
# project does not own — so withholding it is deciding the agent's numbers carry no reason.
|
|
691
|
+
# `instead` rides with it (RK1367) and is the half that could not be withheld: that flag
|
|
692
|
+
# exists because dropping a withdrawn argument was a hand edit to this file, so serving the
|
|
693
|
+
# stacking one alone leaves the agent exactly where the defect was.
|
|
694
|
+
Tool("govern", ("key", "at", "role", "file", "because", "instead")),
|
|
695
|
+
Tool("origin", ("id", "why")),
|
|
696
|
+
Tool("reversals", ("task_id",)),
|
|
697
|
+
# `--prune` writes the registry, so it is withheld exactly as `lint --fix` is (RK16).
|
|
698
|
+
Tool("claims", ()),
|
|
699
|
+
Tool("gaps", ()),
|
|
700
|
+
Tool("next-id", ("family",)),
|
|
701
|
+
Tool("show", ("id", "no_body")),
|
|
702
|
+
Tool("writes", ()),
|
|
703
|
+
# The other end of `gaps` (RK1201), and served for the reason the eight reads above
|
|
704
|
+
# are: the caller this catches is an agent driving a block, whose own session is where
|
|
705
|
+
# a line gets left open — and a read it cannot make is one nobody makes.
|
|
706
|
+
Tool("unclosed", ()),
|
|
707
|
+
# Which copies of this tool write, judge and gate the project (RK415). Exposed because
|
|
708
|
+
# the agent is the one it happens to: its writes go through whatever `roadkeep` the
|
|
709
|
+
# session reaches and its hand edits are denied by whatever the harness installed, and
|
|
710
|
+
# measured live those were 133 versions apart with nothing anywhere saying so.
|
|
711
|
+
# `invoke` rides with it (RK1230), and this surface is exactly who needs it: the tools
|
|
712
|
+
# here always reach the right copy and a `Bash` call does not — `lint --fix` is withheld
|
|
713
|
+
# from this list, so every repair goes through a shell, and the copy to name there was
|
|
714
|
+
# findable only by listing a plugins cache. Measured on a session that listed the wrong one.
|
|
715
|
+
Tool("engines", ("invoke",)),
|
|
716
|
+
# The one query on this list that is not its own subcommand (RK275). `merge` is git's driver
|
|
717
|
+
# contract — three positional paths and an exit code git reads — and none of that belongs in
|
|
718
|
+
# a tool an agent calls, so the verb stays unexposed. `--check` is not that verb sharing a
|
|
719
|
+
# name: it writes nothing, reads the wiring back out of git config, and answers in three
|
|
720
|
+
# lines. RK150's mechanism is what makes that expressible without renaming a flag five
|
|
721
|
+
# decisions now sit behind — `always` puts the act on the surface and `named` calls it what
|
|
722
|
+
# it is, exactly as `claim` is `brief --claim`. Last, because an unwired driver is silent
|
|
723
|
+
# until the merge it was registered for, which is a thing to ask once and never in a loop.
|
|
724
|
+
Tool("merge", always=("check",), named="merge_check"),
|
|
725
|
+
)
|
|
726
|
+
|
|
727
|
+
#: The subcommands above by their first word. Kept because a caller asking "is this command
|
|
728
|
+
#: served as a tool" asks about `section`, not `section add`; the refusal that names one
|
|
729
|
+
#: (RK58) resolves the full path itself.
|
|
730
|
+
TOOL_NAMES = frozenset(tool.argv_head[0] for tool in TOOLS)
|
|
731
|
+
|
|
732
|
+
|
|
733
|
+
#: The long options this CLI declares a dest for, rather than letting argparse derive one,
|
|
734
|
+
#: **by subcommand**. Not a flat table and it cannot be one: `--marker` sets `status` on `add`
|
|
735
|
+
#: and `--status` sets `marker` on `resume`, so the two spellings cross and a global mapping
|
|
736
|
+
#: would answer one of them backwards.
|
|
737
|
+
#:
|
|
738
|
+
#: Held here so :func:`serves` can answer without building a parser, and asserted **total** in
|
|
739
|
+
#: `tests/test_serving.py` against every option every subcommand declares (RK488): the cheap
|
|
740
|
+
#: reader and the parser are allowed to differ in cost and not in answer, and a flag renamed
|
|
741
|
+
#: in `cli.py` fails there rather than silently costing a door its served spelling.
|
|
742
|
+
_DESTS: Mapping[str, Mapping[str, str]] = {
|
|
743
|
+
"add": {"--dep": "deps", "--marker": "status", "--id": "task_id", "--prefix": "family"},
|
|
744
|
+
"amend": {"--dep": "deps"},
|
|
745
|
+
"anchors": {"--next": "only_next"},
|
|
746
|
+
"budget": {"--dep": "deps", "--marker": "status", "--prefix": "family"},
|
|
747
|
+
# The two that call the one sentence `--reason` and accept `--why` beside it (RK1038):
|
|
748
|
+
# the same crossing `--marker` and `--status` make, so the same rows.
|
|
749
|
+
"defer": {"--why": "reason"},
|
|
750
|
+
"list": {"--status": "marker"},
|
|
751
|
+
"next-id": {"--prefix": "family"},
|
|
752
|
+
"record add": {"--id": "task_id"},
|
|
753
|
+
"resume": {"--status": "marker"},
|
|
754
|
+
"retire": {"--why": "reason"},
|
|
755
|
+
"reversals": {"--id": "task_id"},
|
|
756
|
+
# The one row whose dest is not a rename but a **keyword** (RK1263): `--with` reads as the
|
|
757
|
+
# preposition the pair needs and `with` is not a name Python lets an attribute be spelled,
|
|
758
|
+
# so the flag and the dest differ for a reason no other row has.
|
|
759
|
+
"section amend": {"--with": "replacement"},
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
|
|
763
|
+
def dest_of(option: str, command: str = "") -> str:
|
|
764
|
+
"""The dest this long option sets on ``command`` — `--to-block` is `to_block` (RK488).
|
|
765
|
+
|
|
766
|
+
Argparse's own rule where the CLI leaves the dest to argparse, and :data:`_DESTS` where it
|
|
767
|
+
does not. Restated here rather than read off the parser because :func:`serves` is asked
|
|
768
|
+
this inside a hook the harness waits on, and building the parser index costs 117 ms.
|
|
769
|
+
"""
|
|
770
|
+
return _DESTS.get(command, {}).get(option) or option.lstrip("-").replace("-", "_")
|
|
771
|
+
|
|
772
|
+
|
|
773
|
+
def serves(argv: Sequence[str]) -> str | None:
|
|
774
|
+
"""The tool this session offers for ``argv``, or ``None`` where it offers none (RK488).
|
|
775
|
+
|
|
776
|
+
The **cheap** half of what :meth:`~roadkeep.remedying.Door.call` answers, and the half
|
|
777
|
+
the guard can afford: a denial is composed inside a `PreToolUse` the harness waits on,
|
|
778
|
+
held at 44.6 ms by RK261, and building the CLI's parser index to name one tool costs 117
|
|
779
|
+
ms of that. So this reads :data:`TOOLS` and nothing else — the subcommand path answers
|
|
780
|
+
*which* tool, and :attr:`Tool.unconditional` answers whether the flags in the argv are ones
|
|
781
|
+
a caller may pass on **every** project — the half this reader can afford (RK1157). The parser is then only ever asked for the field **values**.
|
|
782
|
+
|
|
783
|
+
That second question is the one `guarding._tool_for` did not ask, and `lint --fix` is the
|
|
784
|
+
row that proves it has to be: RK16 keeps the writing flag where a human is standing, so
|
|
785
|
+
the served `lint` has no `--fix` — and the denial's own table offered it as a tool call,
|
|
786
|
+
which is naming a route the session cannot take, on the surface that just stopped an edit.
|
|
787
|
+
|
|
788
|
+
Conservative on the two edges, because both fall back to a shell line that is right
|
|
789
|
+
wherever a shell exists: a tool whose :attr:`Tool.always` names a flag serves a narrower
|
|
790
|
+
command than the argv asks about (RK150) and is never the answer to *what runs this*, and
|
|
791
|
+
a :attr:`Tool.conditional` argument is read as withheld, since whether a project opens one
|
|
792
|
+
is a fact about that project (L6) and this reader is given none.
|
|
793
|
+
"""
|
|
794
|
+
words = list(argv)
|
|
795
|
+
for length in (2, 1):
|
|
796
|
+
for tool in TOOLS:
|
|
797
|
+
if tool.always or tool.argv_head != words[:length]:
|
|
798
|
+
continue
|
|
799
|
+
passed = (
|
|
800
|
+
dest_of(word, tool.command) for word in words[length:] if word.startswith("--")
|
|
801
|
+
)
|
|
802
|
+
return (
|
|
803
|
+
tool.name
|
|
804
|
+
if all(dest in tool.unconditional for dest in passed)
|
|
805
|
+
else None
|
|
806
|
+
)
|
|
807
|
+
return None
|
|
808
|
+
|
|
809
|
+
|
|
810
|
+
#: Structural, and the reason it is not in the table below: every tool answers as JSON, so
|
|
811
|
+
#: `--json` is not a field a caller could set — it is what the transport already is.
|
|
812
|
+
STRUCTURAL = "json"
|
|
813
|
+
|
|
814
|
+
|
|
815
|
+
def withheld() -> Mapping[str, Mapping[str, str]]:
|
|
816
|
+
"""Every argument a served verb has and does not offer, with the reason it does not (RK1099).
|
|
817
|
+
|
|
818
|
+
`unconditional` is a whitelist, which makes withholding the default: a flag added to `cli.py`
|
|
819
|
+
and not listed there is unreachable over MCP and nothing says so. Measured, that is not
|
|
820
|
+
hypothetical — RK1095 added `cost --session` and left it off, and it stayed CLI-only through
|
|
821
|
+
two more tasks. What caught it was a *remedy door* naming the flag; a flag no door names would
|
|
822
|
+
still be missing. :data:`STRUCTURAL` is excluded, being the transport rather than a decision.
|
|
823
|
+
|
|
824
|
+
**Read from the parsers and no longer restated here** (RK1169). This was a table of the same
|
|
825
|
+
rows keyed by verb, held true by a test asserting that it and the parsers agreed — which is
|
|
826
|
+
the shape that task is about: not a defect waiting to happen, but a test written to prove two
|
|
827
|
+
places say one thing. `cli.withheld` declares each reason beside the argument it explains, so
|
|
828
|
+
the two cannot disagree and the assertion that held them apart is gone.
|
|
829
|
+
|
|
830
|
+
Three kinds of reason, and they are worth telling apart when reading them: **it writes** (RK16
|
|
831
|
+
keeps those where a human is standing), **the tool derives it** (exposing it would let a
|
|
832
|
+
caller choose what the schema then cannot check), and **the shape does not cross** — a path on
|
|
833
|
+
this machine, or a flag whose whole purpose is to change how a terminal prints.
|
|
834
|
+
|
|
835
|
+
Not on the hook path: `serves` answers *which tool* from :data:`_DESTS` alone, which is the
|
|
836
|
+
budget RK261 bought, and this builds the parser index that reader deliberately avoids. Every
|
|
837
|
+
caller here is composing a description or a refusal, where that cost is already paid.
|
|
838
|
+
"""
|
|
839
|
+
from roadkeep.cli import build_parser # noqa: PLC0415 - RK260
|
|
840
|
+
|
|
841
|
+
out: dict[str, dict[str, str]] = {}
|
|
842
|
+
|
|
843
|
+
def walk(parser: argparse.ArgumentParser, path: tuple[str, ...] = ()) -> None:
|
|
844
|
+
for action in parser._actions: # noqa: SLF001 - argparse exposes no public reader
|
|
845
|
+
if isinstance(action, argparse._SubParsersAction): # noqa: SLF001
|
|
846
|
+
for name, sub in action.choices.items():
|
|
847
|
+
walk(sub, (*path, name))
|
|
848
|
+
rows = parser.get_default("withheld")
|
|
849
|
+
if rows:
|
|
850
|
+
out[" ".join(path)] = dict(rows)
|
|
851
|
+
|
|
852
|
+
walk(build_parser())
|
|
853
|
+
return out
|
|
854
|
+
|
|
855
|
+
|
|
856
|
+
def _markers(config: Config) -> dict[str, Any]:
|
|
857
|
+
"""The open markers a caller may write, wherever the field means that set (RK314).
|
|
858
|
+
|
|
859
|
+
Above the table rather than beside the other bound functions, because the table names it
|
|
860
|
+
directly and not through a lambda: two dests share one bound here, and a wrapper per dest
|
|
861
|
+
would be the second spelling this exists to prevent.
|
|
862
|
+
|
|
863
|
+
The **roadmap's** set, which is what every dest reaching this writes into: `status` refuses
|
|
864
|
+
`✅` as `status.shipped`, so the shipped marker is not a value any of them may carry. The
|
|
865
|
+
changelog's own set is a different question and `list` is the only tool that asks it.
|
|
866
|
+
"""
|
|
867
|
+
return {"enum": list(config.schema.markers)}
|
|
868
|
+
|
|
869
|
+
|
|
870
|
+
#: What the config knows about a field that argparse does not: the limit, the marker set, the
|
|
871
|
+
#: id shape. This is the whole of RK24 — the bound that refuses the prose and the bound the
|
|
872
|
+
#: client validates against are read from the same `roadkeep.toml` (L6).
|
|
873
|
+
_BOUNDS = {
|
|
874
|
+
# `maxLength` is what refuses; the word figure is what an author can aim at (RK185). A
|
|
875
|
+
# model has no characters, so a ceiling published only in them is a target reached by
|
|
876
|
+
# trial — and the aim is stated in the sentence rather than as a second keyword, because
|
|
877
|
+
# a client validating word counts would refuse prose this server accepts.
|
|
878
|
+
"symptom": lambda config: {
|
|
879
|
+
"maxLength": config.schema.symptom_max,
|
|
880
|
+
"note": _aimed(config.schema.symptom_max),
|
|
881
|
+
},
|
|
882
|
+
# `maxLength` is the field's own ceiling and not the one that binds (RK183): the line
|
|
883
|
+
# is, and how much of it this field has left depends on the symptom and the deps of the
|
|
884
|
+
# call being composed, which no static number can state. So the ceiling is published as
|
|
885
|
+
# what it is, and the joint rule is said in words beside it — a lower number here would
|
|
886
|
+
# refuse on the client a line the server accepts, which is a bound on the client.
|
|
887
|
+
"why": lambda config: {
|
|
888
|
+
"maxLength": config.schema.why_max,
|
|
889
|
+
"note": (
|
|
890
|
+
f"{_aimed(config.schema.why_max)} The binding limit is the rendered line "
|
|
891
|
+
f"({config.schema.line_max}), which this sentence shares with the symptom and "
|
|
892
|
+
f"with the line's own structure, so the usable maximum is lower than "
|
|
893
|
+
f"{config.schema.why_max} and lower again where the line carries deps. "
|
|
894
|
+
f"`budget` answers it in both units before a word is written (RK190); the "
|
|
895
|
+
f"refusal names what was left, in both units too (RK201)."
|
|
896
|
+
),
|
|
897
|
+
},
|
|
898
|
+
# The one field whose limit needs no translation, and the one that published none (RK258).
|
|
899
|
+
# `symptom` and `why` get a ceiling and a word aim; the three prose bodies said what the
|
|
900
|
+
# field was and never that a bound existed, so `section = 250` reached an author only as a
|
|
901
|
+
# refusal — measured at two of them in one task, each costing a re-send of the paragraph.
|
|
902
|
+
# No `maxLength`: JSON Schema counts characters, and a character bound derived from a word
|
|
903
|
+
# count would refuse prose this tool accepts, which is a bound on the client (RK183's rule).
|
|
904
|
+
"body": lambda config: {"note": _paragraphed(config)},
|
|
905
|
+
"section_body": lambda config: {"note": _paragraphed(config)},
|
|
906
|
+
# The same paragraph named by path (RK1260), and the one thing a caller here has to know
|
|
907
|
+
# that a caller at a terminal does not: this is a `caller` path in `PATH_ARGUMENTS`, so it
|
|
908
|
+
# is read from the answering process's own directory and never resolved against the project
|
|
909
|
+
# `-C` selected. Two trees over MCP, and a relative path that found a file in the wrong one
|
|
910
|
+
# would be measured, filled and written with nothing in the answer naming what it read —
|
|
911
|
+
# which is `Config.locate`'s own argument, arriving on the class of path it excludes.
|
|
912
|
+
# One bound and two dests, for `status`/`marker`'s reason: the dest is a spelling.
|
|
913
|
+
"section_body_file": lambda config: {"note": _pathed(config)},
|
|
914
|
+
"body_file": lambda config: {"note": _pathed(config)},
|
|
915
|
+
# One bound and two dests, because the dest is a spelling and the set is the fact (RK314).
|
|
916
|
+
# `budget --status` is dest `status` and the `status` command's own positional is dest
|
|
917
|
+
# `marker` — the same closed set, and keying by dest published it to the tool that *prices*
|
|
918
|
+
# a line while missing the tool that writes one, which is the call an agent makes on every
|
|
919
|
+
# task it starts. `resume --marker` is the third and was missing for the same reason.
|
|
920
|
+
"status": _markers,
|
|
921
|
+
"marker": _markers,
|
|
922
|
+
# The remaining closed set, and the one that published a sentence (RK304). `section_add`,
|
|
923
|
+
# `section_amend`, `section_drop` and `budget` each describe this as *"which prose file"* and
|
|
924
|
+
# gave the client nothing to validate, so `role = "notes"` was a well-formed call the server
|
|
925
|
+
# refused after it was made. The set is the project's declared prose files — `config.has` over
|
|
926
|
+
# `PROSE_ROLES`, the same narrowing `_paragraphed` makes to decide which limits to publish
|
|
927
|
+
# (RK259), because a role a project declares no file for is one every reader here refuses.
|
|
928
|
+
"role": lambda config: _roles(config, PROSE_ROLES),
|
|
929
|
+
"id": lambda config: {"pattern": config.schema.id_pattern().pattern},
|
|
930
|
+
# Not `id_pattern` (RK111): this is the *chosen* id, and the shape that admits a bare
|
|
931
|
+
# number would admit exactly the choice deriving already makes. The narrower pattern is
|
|
932
|
+
# what keeps the field from being a way around the counter, so it is also checked here and
|
|
933
|
+
# not only published — a bound a client may skip is a bound on the client.
|
|
934
|
+
"task_id": lambda config: {"pattern": config.schema.split_id_pattern().pattern},
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
|
|
938
|
+
@dataclass(frozen=True, slots=True)
|
|
939
|
+
class Conditional:
|
|
940
|
+
"""What opens a :attr:`Tool.conditional` argument, and what a refusal says when it is shut.
|
|
941
|
+
|
|
942
|
+
One record and not two tables agreeing (RK252). RK111 wrote the predicate, RK241 wrote the
|
|
943
|
+
sentence beside it, and they are one fact — `ref` is open where `ref_scheme = "outline"`, and
|
|
944
|
+
the refusal says exactly that — so held apart, opening a dest on a second declaration grew
|
|
945
|
+
the predicate a clause while the sentence went on naming only the first. That is the
|
|
946
|
+
arrangement this tool exists to remove, one layer out. Held together, a dest has both halves
|
|
947
|
+
or is not a dest: :func:`_withheld` indexes without a guard, and the failure lands on the
|
|
948
|
+
edit rather than on the caller who passed the closed field (RK251).
|
|
949
|
+
|
|
950
|
+
What this cannot do is derive the prose from the predicate. A lambda over `Config` names no
|
|
951
|
+
table, and writing the sentence is what L4 rules out — so the available half is making them
|
|
952
|
+
one object, and it is the half that fails early.
|
|
953
|
+
"""
|
|
954
|
+
|
|
955
|
+
#: Whether *this* project's config makes the field the only way to write something legal.
|
|
956
|
+
#: A predicate and not a config key, because the question is re-asked per call: a
|
|
957
|
+
#: `roadkeep.toml` edited mid-session is the one this server answers with (RK155's neighbour).
|
|
958
|
+
opens: Callable[[Config], bool]
|
|
959
|
+
#: The clause a refusal adds when it is closed — which declaration would have opened it, and
|
|
960
|
+
#: what the project derives instead. Read as prose after `<dest>: `, so it starts lowercase
|
|
961
|
+
#: and carries no full stop.
|
|
962
|
+
because: str
|
|
963
|
+
|
|
964
|
+
|
|
965
|
+
#: Every conditional argument this surface has, by dest (RK111, RK241, RK252).
|
|
966
|
+
_CONDITIONAL: Mapping[str, Conditional] = {
|
|
967
|
+
"task_id": Conditional(
|
|
968
|
+
opens=lambda config: config.schema.id_suffix,
|
|
969
|
+
because=(
|
|
970
|
+
"offered only where `roadkeep.toml` declares an id shape the counter cannot spell "
|
|
971
|
+
"(`[ids] suffix`), and this project declares none — so every legal id here is the "
|
|
972
|
+
"one `add` derives"
|
|
973
|
+
),
|
|
974
|
+
),
|
|
975
|
+
"ref": Conditional(
|
|
976
|
+
opens=lambda config: config.schema.ref_scheme == "outline",
|
|
977
|
+
because=(
|
|
978
|
+
'offered only where `roadkeep.toml` sets `ref_scheme = "outline"`, which makes the '
|
|
979
|
+
"anchor the caller's to name; this project derives the pointer from the id, and one "
|
|
980
|
+
"chosen by hand is what `ref.mismatch` refuses"
|
|
981
|
+
),
|
|
982
|
+
),
|
|
983
|
+
# The same field on the line a `--decides` files (RK1363). Its own key and not `ref`'s,
|
|
984
|
+
# because the two are two pointers in one call: `ship --ref` does not exist at all, and a
|
|
985
|
+
# tool offering one dest for both would let an outline project address the decision's body
|
|
986
|
+
# with a flag whose description is about the task's design.
|
|
987
|
+
"decides_ref": Conditional(
|
|
988
|
+
opens=lambda config: config.schema.ref_scheme == "outline",
|
|
989
|
+
because=(
|
|
990
|
+
'offered only where `roadkeep.toml` sets `ref_scheme = "outline"`; this project '
|
|
991
|
+
"addresses a decision's body by the decision's own id, so there is nothing to name"
|
|
992
|
+
),
|
|
993
|
+
),
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
#: `list --role` is *which governed file*, not which prose file (RK304) — its universe is every
|
|
997
|
+
#: role this project declares, `roadmap` included, and that is the default. Published through the
|
|
998
|
+
#: same table with the one key overridden, so a bound added to `_BOUNDS` tomorrow reaches this
|
|
999
|
+
#: tool too: an enum of the prose files here would refuse the most common call this surface makes.
|
|
1000
|
+
#: — and its `marker` is every marker any of those files can carry (RK314), because the set is
|
|
1001
|
+
#: read per role: the changelog declares `✅ 🗑` where the roadmap declares the open four, so a
|
|
1002
|
+
#: filter is checked against `schema_for(--role)`. A schema cannot make one enum depend on
|
|
1003
|
+
#: another field, so this is the union — over-permissive by exactly the markers legal on a role
|
|
1004
|
+
#: the call did not name, which the read beneath refuses, where the narrow answer would refuse
|
|
1005
|
+
#: `--role changelog --marker ✅` on the client and never reach it.
|
|
1006
|
+
_FILE_BOUNDS = {
|
|
1007
|
+
**_BOUNDS,
|
|
1008
|
+
"role": lambda config: _roles(config, ROLES),
|
|
1009
|
+
"marker": lambda config: _listed_markers(config),
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
#: The non-goals are their own two limits (RK70), so the same `why` means a different number
|
|
1013
|
+
#: here — a client validating a bullet against the *task* limit would refuse prose the tool
|
|
1014
|
+
#: accepts, which is the one way this derivation can be wrong while looking right.
|
|
1015
|
+
_SCOPE_BOUNDS = {
|
|
1016
|
+
"lead": lambda config: {
|
|
1017
|
+
"maxLength": (config.non_goals or Scope()).lead,
|
|
1018
|
+
"note": _aimed((config.non_goals or Scope()).lead),
|
|
1019
|
+
},
|
|
1020
|
+
"why": lambda config: {
|
|
1021
|
+
"maxLength": (config.non_goals or Scope()).why,
|
|
1022
|
+
"note": _aimed((config.non_goals or Scope()).why),
|
|
1023
|
+
},
|
|
1024
|
+
}
|
|
1025
|
+
|
|
1026
|
+
|
|
1027
|
+
#: The roadmap's third list, whose two limits are `[criteria]`' and not `[limits]`' (RK1265).
|
|
1028
|
+
#: :data:`_SCOPE_BOUNDS`' argument exactly, and it is the one that measures: published through
|
|
1029
|
+
#: the common table, a criterion's `why` carried the **task line's** note — 529 characters
|
|
1030
|
+
#: about `line_max`, a rendered line this bullet is not part of, and a `budget` call that
|
|
1031
|
+
#: answers about a different field. Wrong twice over: the number would refuse prose this
|
|
1032
|
+
#: server accepts on a project declaring a wider list, and the sentence describes arithmetic
|
|
1033
|
+
#: no criterion is subject to.
|
|
1034
|
+
_CRITERIA_BOUNDS = {
|
|
1035
|
+
"lead": lambda config: {
|
|
1036
|
+
"maxLength": (config.criteria or Scope()).lead,
|
|
1037
|
+
"note": _aimed((config.criteria or Scope()).lead),
|
|
1038
|
+
},
|
|
1039
|
+
"why": lambda config: {
|
|
1040
|
+
"maxLength": (config.criteria or Scope()).why,
|
|
1041
|
+
"note": _aimed((config.criteria or Scope()).why),
|
|
1042
|
+
},
|
|
1043
|
+
}
|
|
1044
|
+
|
|
1045
|
+
#: The two verbs whose `why` has a **second shape** (RK1049, RK1053, RK1055). With `--lines`
|
|
1046
|
+
#: above one the field carries a wrapped ledger entry whole, and only its first line is measured
|
|
1047
|
+
#: against `limits.<role>.why` — so no character ceiling describes both calls, and publishing the
|
|
1048
|
+
#: single-line one refuses a span this server takes. That is RK183's rule, and the answer is the
|
|
1049
|
+
#: one `body` and `section_body` already give for the same shape: no `maxLength`, and the bound
|
|
1050
|
+
#: said in the note.
|
|
1051
|
+
#:
|
|
1052
|
+
#: **The affordance is not said here** (RK1273). It was, on the argument that a schema is the
|
|
1053
|
+
#: whole of what an agent has — and then both flags' own `help` came to carry it, so one field's
|
|
1054
|
+
#: description stated one rule twice, at 941 characters on the verb that has the least room of
|
|
1055
|
+
#: any served here. A note says what the *bound* is; a help says what the flag does; and where
|
|
1056
|
+
#: the two overlap the note gives way, being the half a terminal never prints — a fact kept only
|
|
1057
|
+
#: here is a fact lost at `--help`.
|
|
1058
|
+
_SPAN_BOUNDS = {
|
|
1059
|
+
**_BOUNDS,
|
|
1060
|
+
"why": lambda config: {
|
|
1061
|
+
"note": (
|
|
1062
|
+
f"Aim for {words(config.schema.why_max)} words. **No `maxLength` here, and the "
|
|
1063
|
+
f"limit is per line**: {config.schema.why_max} characters is what refuses a "
|
|
1064
|
+
f"one-line field, counted in UTF-16 code units, and the rendered line "
|
|
1065
|
+
f"({config.schema.line_max}) is what binds — `budget` answers both before a word "
|
|
1066
|
+
f"is written (RK190). A span passed with `--lines` above one is measured on its "
|
|
1067
|
+
f"first line alone, so the total has no ceiling and one published here would "
|
|
1068
|
+
f"refuse a call this tool accepts."
|
|
1069
|
+
)
|
|
1070
|
+
},
|
|
1071
|
+
}
|
|
1072
|
+
|
|
1073
|
+
|
|
1074
|
+
#: The one verb whose prose fields are **drafts to measure** and not fields to write (RK1190).
|
|
1075
|
+
#: Every other table above publishes `maxLength`, and here that number is the defect: a client
|
|
1076
|
+
#: validating a draft against the ceiling would refuse exactly the over-long paragraph this read
|
|
1077
|
+
#: exists to report on, so the caller learns the overrun by being refused — which is the state
|
|
1078
|
+
#: the whole verb was built to end, arriving one layer out and from this server's own schema.
|
|
1079
|
+
#:
|
|
1080
|
+
#: So no ceiling, and the limit said in the note as :data:`_SPAN_BOUNDS` says it. `body` needs no
|
|
1081
|
+
#: row: its bound was already a note and never a keyword (RK258), so a draft was always passable.
|
|
1082
|
+
_DRAFT_BOUNDS = {
|
|
1083
|
+
**_BOUNDS,
|
|
1084
|
+
"symptom": lambda config: {"note": _measuring(config.schema.symptom_max)},
|
|
1085
|
+
"why": lambda config: {"note": _measuring(config.schema.why_max)},
|
|
1086
|
+
# `body` had no ceiling to remove and still needed a row: :func:`_paragraphed` ends with
|
|
1087
|
+
# *"`budget` states it per call, before the body exists"*, which is a pointer at this verb
|
|
1088
|
+
# published on this verb — and the body here does exist, being the draft in the caller's hand.
|
|
1089
|
+
"body": lambda config: {
|
|
1090
|
+
"note": f"{config.schema.section_max} words bounds the write, not this read."
|
|
1091
|
+
},
|
|
1092
|
+
}
|
|
1093
|
+
|
|
1094
|
+
|
|
1095
|
+
def _measuring(limit: int) -> str:
|
|
1096
|
+
"""What a draft field publishes instead of a ceiling (RK1190).
|
|
1097
|
+
|
|
1098
|
+
Short on purpose: the verb's own description already says every draft here is measured and
|
|
1099
|
+
never composed, and this is the one thing a *schema* has to add — that the missing keyword
|
|
1100
|
+
is a decision. The budget this tool is held to is the reason it is one sentence (RK1059).
|
|
1101
|
+
"""
|
|
1102
|
+
return f"**No `maxLength`**: a draft — {limit} bounds the write, not this read."
|
|
1103
|
+
|
|
1104
|
+
|
|
1105
|
+
#: The verbs that mean something of their own by a field name every other verb shares, and the
|
|
1106
|
+
#: table that says what (RK316). By the **full command** and then by its first word, which is
|
|
1107
|
+
#: the order the divergences now need: `non-goal add` and `non-goal drop` share `[non_goals]`'
|
|
1108
|
+
#: limits, while `record amend` takes a span and `record add` — placing a new entry — does not,
|
|
1109
|
+
#: so a first-word key would publish the loose bound to the one door that still has the tight
|
|
1110
|
+
#: one. Every key is asserted to name a subcommand this CLI accepts, so the one way this can
|
|
1111
|
+
#: be wrong — a rename leaving nothing matched and the defaults silently published — is a test
|
|
1112
|
+
#: failure and not a client refusing a call the tool would have taken.
|
|
1113
|
+
#: The one verb whose `role` means a file this project **does not have** (RK1264). Every other
|
|
1114
|
+
#: reader of that dest narrows to the declared ones, and this is the exact inverse: `declare`
|
|
1115
|
+
#: refuses a role already in `[files]`, so publishing the declared set would be an enum of the
|
|
1116
|
+
#: only five values the tool is certain to reject.
|
|
1117
|
+
#:
|
|
1118
|
+
#: Narrower than the parser accepts, which :func:`_roles` warns against and this is the case it
|
|
1119
|
+
#: does not cover: what the narrowing leaves out is not a legal call refused on the client but a
|
|
1120
|
+
#: value every call of which is `RoleDeclared` — so no answerable argv is lost, which is the
|
|
1121
|
+
#: property RK183's rule is actually about.
|
|
1122
|
+
_ABSENT_BOUNDS = {**_BOUNDS, "role": lambda config: _undeclared(config)}
|
|
1123
|
+
|
|
1124
|
+
_DIVERGENT: Mapping[str, Mapping[str, Any]] = {
|
|
1125
|
+
"non-goal": _SCOPE_BOUNDS,
|
|
1126
|
+
"list": _FILE_BOUNDS,
|
|
1127
|
+
"ship": _SPAN_BOUNDS,
|
|
1128
|
+
"record amend": _SPAN_BOUNDS,
|
|
1129
|
+
"budget": _DRAFT_BOUNDS,
|
|
1130
|
+
"declare": _ABSENT_BOUNDS,
|
|
1131
|
+
"criterion": _CRITERIA_BOUNDS,
|
|
1132
|
+
}
|
|
1133
|
+
|
|
1134
|
+
|
|
1135
|
+
def _aimed(limit: int) -> str:
|
|
1136
|
+
"""The character ceiling restated as the word count a model can count towards (RK185).
|
|
1137
|
+
|
|
1138
|
+
**And in the unit it is counted in** (RK436). `maxLength` is the one figure this tool
|
|
1139
|
+
publishes and does not own: the keyword is defined over the string's *characters* —
|
|
1140
|
+
code points — and RK430 made every gate here count UTF-16 code units, which is the
|
|
1141
|
+
stricter of the two. So the number is right and its unit is the client's, and a field
|
|
1142
|
+
carrying an astral character validates locally, passes, and is refused by a bound it
|
|
1143
|
+
was told it had met.
|
|
1144
|
+
|
|
1145
|
+
Three answers existed and this is the one the surface already ruled the other two out
|
|
1146
|
+
of. Publishing the stricter figure is what the `why` bound refuses to do for the line
|
|
1147
|
+
limit and what `body` refuses to do for the word one: a lower `maxLength` refuses on
|
|
1148
|
+
the client prose this server accepts, which is a bound on the client (RK183) — and it
|
|
1149
|
+
would cost that room on every ASCII field to buy it on the rare astral one. Leaving it
|
|
1150
|
+
unsaid is the state the defect describes. What is left is naming the residual in the
|
|
1151
|
+
one place a client author reading the field is already looking, beside the aim.
|
|
1152
|
+
|
|
1153
|
+
Said on every field rather than only where the counters disagree, which is where
|
|
1154
|
+
:func:`~roadkeep.kernel.schema._counted` says it: a refusal has the string in hand and can
|
|
1155
|
+
compare, and a schema is composed before any string exists.
|
|
1156
|
+
|
|
1157
|
+
**Said once, and not per field** (RK1060). The residual belongs here and the paragraph
|
|
1158
|
+
stating it did not: identical on 13 properties, 322 characters each, 4,186 of the tool
|
|
1159
|
+
list — one sentence in every twelve a session read before its first call. What varies is
|
|
1160
|
+
the number and the aim, and that is what stays; the caveat is a fact about every bound
|
|
1161
|
+
this surface publishes, so it moved to :data:`INSTRUCTIONS`, which a client is given once
|
|
1162
|
+
at the handshake. Not `$ref`: a model is handed the tool list as text, so a definition it
|
|
1163
|
+
has to resolve is worse for the reader than a repeated sentence — the saving has to come
|
|
1164
|
+
from saying it somewhere a reader already is, which the handshake is and a sibling
|
|
1165
|
+
property is not.
|
|
1166
|
+
"""
|
|
1167
|
+
return (
|
|
1168
|
+
f"Aim for {words(limit)} words; {limit} characters is what refuses, counted in "
|
|
1169
|
+
f"UTF-16 code units."
|
|
1170
|
+
)
|
|
1171
|
+
|
|
1172
|
+
|
|
1173
|
+
#: The residual :func:`_aimed` used to repeat on every prose field, said once (RK1060). A
|
|
1174
|
+
#: client is given this at the handshake and the tool list on every session that connects,
|
|
1175
|
+
#: so a fact true of *every* published bound belongs in the one of them that is delivered
|
|
1176
|
+
#: once. Beside the engine line RK79 put there for the same reason — which tree answered is
|
|
1177
|
+
#: also a fact about the whole surface rather than about any tool on it.
|
|
1178
|
+
_COUNTING = (
|
|
1179
|
+
"Every `maxLength` here is its field's ceiling under JSON Schema's own count, which "
|
|
1180
|
+
"is code points; this tool counts UTF-16 code units, the stricter of the two. So a "
|
|
1181
|
+
"field carrying an emoji or other astral character can validate on the client and "
|
|
1182
|
+
"still be refused — the published number is the looser one on purpose, a stricter "
|
|
1183
|
+
"bound being one that would refuse prose this server accepts."
|
|
1184
|
+
)
|
|
1185
|
+
|
|
1186
|
+
|
|
1187
|
+
@dataclass(frozen=True, slots=True)
|
|
1188
|
+
class Surface:
|
|
1189
|
+
"""What a session is sent, measured once (RK1096).
|
|
1190
|
+
|
|
1191
|
+
Two reads answer this and each did its own arithmetic: `cost --tools` summed the
|
|
1192
|
+
descriptors and the handshake, and `cost --session` summed the same two under a
|
|
1193
|
+
different heading. They agreed, which is the property a duplicate has right up to the
|
|
1194
|
+
edit that moves one — the shape RK1073 closed for the provenance note and RK1080 for the
|
|
1195
|
+
partial predicate, both found the same way.
|
|
1196
|
+
|
|
1197
|
+
Here rather than in `budgeting`, and that is the import direction rather than a
|
|
1198
|
+
preference: `serving` reaches `cli`, `cli` reaches the verbs, and a verb reaches
|
|
1199
|
+
`budgeting` — so a measurement of the surface placed there would close the cycle. The
|
|
1200
|
+
module that composes the payload is the module that can say what it costs.
|
|
1201
|
+
"""
|
|
1202
|
+
|
|
1203
|
+
#: Every tool and what it costs, largest first — the ranking `--tools` prints.
|
|
1204
|
+
tools: tuple[tuple[str, int], ...]
|
|
1205
|
+
#: The handshake, which is sent once beside the list and counted with it (RK1078/RK1062).
|
|
1206
|
+
handshake: int
|
|
1207
|
+
#: The part of that handshake which is the checkout's rather than the surface's — the
|
|
1208
|
+
#: version, the commit, the word `modified` and the absolute path this package was
|
|
1209
|
+
#: imported from (RK1334). Counted into :attr:`characters`, because a session really is
|
|
1210
|
+
#: sent it, and out of :attr:`held`, because no author can edit it: the same tree read
|
|
1211
|
+
#: 64,679 clean and 64,688 dirty against a ceiling with twelve to spare, so a surface four
|
|
1212
|
+
#: characters larger passed on a clean tree and was refused on a dirty one — which is the
|
|
1213
|
+
#: state the pre-commit hook this project ships runs in.
|
|
1214
|
+
provenance: int = 0
|
|
1215
|
+
|
|
1216
|
+
def stated(
|
|
1217
|
+
self, unit: str, each: int | None, largest: int, session: int | None = None
|
|
1218
|
+
) -> str:
|
|
1219
|
+
"""The ranking, with the room each tool has before the gate says no (RK345, RK1059).
|
|
1220
|
+
|
|
1221
|
+
Beside :meth:`payload` since RK1170. The terminal gets the largest few and the payload
|
|
1222
|
+
gets every one: a caller reading this to decide what to cut is reading a payload, where
|
|
1223
|
+
a person is reading a report.
|
|
1224
|
+
"""
|
|
1225
|
+
ranked = list(self.tools)
|
|
1226
|
+
# The gate's own figure and its ceiling, on the read somebody runs *because* a budget
|
|
1227
|
+
# is tight (RK1335): this is the apparatus for deciding what to cut — the ranking and
|
|
1228
|
+
# the room each description has — and it stated the total `budget.session` stopped
|
|
1229
|
+
# refusing after RK1334, beside the per-tool ceiling and never the session one. So the
|
|
1230
|
+
# reader arriving here under session pressure was given neither deciding number.
|
|
1231
|
+
held = (
|
|
1232
|
+
""
|
|
1233
|
+
if session is None
|
|
1234
|
+
else f" — {self.held} of {session} held, the rest naming the checkout"
|
|
1235
|
+
)
|
|
1236
|
+
rows = [
|
|
1237
|
+
f"session {len(self.tools)} tool(s) and the handshake, {self.characters} "
|
|
1238
|
+
f"{unit}{held}"
|
|
1239
|
+
]
|
|
1240
|
+
for name, size in ranked[:largest]:
|
|
1241
|
+
# The room before the gate says no, said beside the figure it is about: a budget
|
|
1242
|
+
# reported only as a total leaves the author to subtract per tool.
|
|
1243
|
+
room = "" if each is None else f" {each - size:+}"
|
|
1244
|
+
rows.append(f" {name:<16} {size}{room}")
|
|
1245
|
+
if len(ranked) > largest:
|
|
1246
|
+
rows.append(f" … and {len(ranked) - largest} more — `--json` lists every one")
|
|
1247
|
+
# Under the ranking and not folded into it: it is not a tool, no per-tool ceiling is
|
|
1248
|
+
# about it, and a row among them would read as one that had escaped the gate.
|
|
1249
|
+
rows.append(f" {'handshake':<16} {self.handshake} (instructions, sent once)")
|
|
1250
|
+
if each is not None:
|
|
1251
|
+
over = sum(1 for _name, size in ranked if size > each)
|
|
1252
|
+
rows.append(
|
|
1253
|
+
f" each {each} {unit}, {over} over — `lint` is what refuses one"
|
|
1254
|
+
)
|
|
1255
|
+
return chr(10).join(rows)
|
|
1256
|
+
|
|
1257
|
+
def payload(
|
|
1258
|
+
self, unit: str, each: int | None, session: int | None = None
|
|
1259
|
+
) -> dict[str, object]:
|
|
1260
|
+
return {
|
|
1261
|
+
"tools": len(self.tools),
|
|
1262
|
+
# The session's whole cost, which is what the verb exists to answer; the two
|
|
1263
|
+
# halves are named beside it rather than left to be added.
|
|
1264
|
+
"characters": self.characters,
|
|
1265
|
+
"tool_list": self.listed,
|
|
1266
|
+
"handshake": self.handshake,
|
|
1267
|
+
# What `budget.session` refuses and what it refuses it against, so this read and
|
|
1268
|
+
# that gate cannot come to disagree the way this read and `--session` had
|
|
1269
|
+
# (RK1335). Held apart from `characters` rather than replacing it: a session is
|
|
1270
|
+
# sent the whole thing, and only part of it is anybody's to edit (RK1334).
|
|
1271
|
+
"provenance": self.provenance,
|
|
1272
|
+
"held": self.held,
|
|
1273
|
+
"session": session,
|
|
1274
|
+
"unit": unit,
|
|
1275
|
+
# Every tool and not the largest few, for the reason above.
|
|
1276
|
+
"by_tool": [{"name": name, "characters": size} for name, size in self.tools],
|
|
1277
|
+
# What one tool may cost, and null where the project declares none (RK1059) — the
|
|
1278
|
+
# gate's number, so the read and the refusal are one.
|
|
1279
|
+
"each": each,
|
|
1280
|
+
"over": [
|
|
1281
|
+
name
|
|
1282
|
+
for name, size in self.tools
|
|
1283
|
+
if each is not None and size > each
|
|
1284
|
+
],
|
|
1285
|
+
}
|
|
1286
|
+
|
|
1287
|
+
@property
|
|
1288
|
+
def listed(self) -> int:
|
|
1289
|
+
"""The tool list alone, which is the half `[tools] characters` is a ceiling on."""
|
|
1290
|
+
return sum(cost for _name, cost in self.tools)
|
|
1291
|
+
|
|
1292
|
+
@property
|
|
1293
|
+
def characters(self) -> int:
|
|
1294
|
+
"""Everything a client is sent before its first call."""
|
|
1295
|
+
return self.listed + self.handshake
|
|
1296
|
+
|
|
1297
|
+
@property
|
|
1298
|
+
def held(self) -> int:
|
|
1299
|
+
"""The part of that a ceiling is about — everything except the provenance (RK1334).
|
|
1300
|
+
|
|
1301
|
+
`budget.session` refuses the surface against a number declared in `roadkeep.toml`,
|
|
1302
|
+
and until now it refused :attr:`characters`, three of whose facts are properties of
|
|
1303
|
+
the checkout: the commit, whether the tree has uncommitted changes, and the absolute
|
|
1304
|
+
path the package was imported from. A verdict that moves with any of those is a
|
|
1305
|
+
verdict about the environment, and the two that move most are the two a gate meets —
|
|
1306
|
+
a pre-commit hook always runs dirty, and a CI checkout is never at the author's path.
|
|
1307
|
+
|
|
1308
|
+
Not a second measurement of the surface but a subtraction from the one there is, so
|
|
1309
|
+
the read and the gate cannot drift: :attr:`characters` stays the truth about what a
|
|
1310
|
+
session is sent, and this is the half of it somebody can act on.
|
|
1311
|
+
"""
|
|
1312
|
+
return self.characters - self.provenance
|
|
1313
|
+
|
|
1314
|
+
|
|
1315
|
+
def surface(config: Config) -> Surface:
|
|
1316
|
+
"""What connecting to this server costs, as both reads of it ask (RK1096).
|
|
1317
|
+
|
|
1318
|
+
Derived from :func:`descriptors` and :func:`instructions` — the payloads themselves and
|
|
1319
|
+
never a second estimate of them — so a description reworded in `cli.py` moves this
|
|
1320
|
+
figure, which is the whole reason the number is worth reading.
|
|
1321
|
+
"""
|
|
1322
|
+
sizes = {
|
|
1323
|
+
one["name"]: width(json.dumps(one, ensure_ascii=False)) for one in descriptors(config)
|
|
1324
|
+
}
|
|
1325
|
+
return Surface(
|
|
1326
|
+
tools=tuple(sorted(sizes.items(), key=lambda row: (-row[1], row[0]))),
|
|
1327
|
+
handshake=width(instructions()),
|
|
1328
|
+
# Measured off the same composer rather than by re-deriving the line (L3's rule about
|
|
1329
|
+
# one writer): `instructions` is `engine()` and then the counting prose, so what the
|
|
1330
|
+
# checkout contributes is exactly what that first part costs (RK1334).
|
|
1331
|
+
provenance=width(str(engine())),
|
|
1332
|
+
)
|
|
1333
|
+
|
|
1334
|
+
|
|
1335
|
+
#: What the ranking calls the tool's own sentence, which is a cost with no argument to name
|
|
1336
|
+
#: it. Parenthesised so it cannot be mistaken for a field a caller could set.
|
|
1337
|
+
DESCRIPTION = "(description)"
|
|
1338
|
+
|
|
1339
|
+
|
|
1340
|
+
@dataclass(frozen=True, slots=True)
|
|
1341
|
+
class Detail:
|
|
1342
|
+
"""One tool's cost, by the field that spent it (RK1236).
|
|
1343
|
+
|
|
1344
|
+
:class:`Surface` ranks the tools and answers *which one is over*, which is never the
|
|
1345
|
+
question a caller has at that moment — the finding already named the tool. What was
|
|
1346
|
+
missing is which of its arguments the bytes went to, and twice in one block the answer
|
|
1347
|
+
came from a throwaway script that serialised each property and sorted by length.
|
|
1348
|
+
|
|
1349
|
+
The parts do not sum to the total, deliberately and visibly: a descriptor is JSON, so its
|
|
1350
|
+
name, its keys, its `required` list and its brackets are bytes no argument spent. They are
|
|
1351
|
+
reported as one **envelope** row rather than distributed, because a breakdown that
|
|
1352
|
+
quietly balanced would be a breakdown that had assigned structure to whichever field
|
|
1353
|
+
rounded best.
|
|
1354
|
+
"""
|
|
1355
|
+
|
|
1356
|
+
name: str
|
|
1357
|
+
#: Every property and the description, largest first — the ranking a caller reads.
|
|
1358
|
+
parts: tuple[tuple[str, int], ...]
|
|
1359
|
+
#: The whole descriptor, which is what `--tools` ranks and `lint` refuses (RK1059).
|
|
1360
|
+
characters: int
|
|
1361
|
+
#: The module declaring this verb's parser, which is where a `help=` string is edited.
|
|
1362
|
+
where: str
|
|
1363
|
+
#: What the description row is composed of, where it is more than the parser's own
|
|
1364
|
+
#: sentence (RK1239) — `(source, characters)`, and empty where there is nothing to split.
|
|
1365
|
+
#: The clause as written, so these sum to the sentence and not to the serialised row.
|
|
1366
|
+
described: tuple[tuple[str, int], ...] = ()
|
|
1367
|
+
|
|
1368
|
+
@property
|
|
1369
|
+
def envelope(self) -> int:
|
|
1370
|
+
"""The JSON around the fields: the name, the keys, the brackets, `required`."""
|
|
1371
|
+
return self.characters - sum(size for _part, size in self.parts)
|
|
1372
|
+
|
|
1373
|
+
@property
|
|
1374
|
+
def quoting(self) -> int:
|
|
1375
|
+
"""What the description's clauses do not account for: its key, its quotes, its
|
|
1376
|
+
escaping and the space between each pair (RK1241).
|
|
1377
|
+
|
|
1378
|
+
The same row the outer :attr:`envelope` is, one level in. RK1236 named the difference
|
|
1379
|
+
between a tool's total and the sum of its fields, on the argument that a breakdown
|
|
1380
|
+
which quietly balanced would have assigned structure to whichever field rounded best;
|
|
1381
|
+
RK1239 then split the description and left the reader to notice 725 over 576 and 129.
|
|
1382
|
+
An accounting honest at the top and silent underneath teaches a reader to distrust
|
|
1383
|
+
both.
|
|
1384
|
+
|
|
1385
|
+
Zero where there is nothing to split, which is where :attr:`described` is empty.
|
|
1386
|
+
"""
|
|
1387
|
+
if not self.described:
|
|
1388
|
+
return 0
|
|
1389
|
+
row = next((size for part, size in self.parts if part == DESCRIPTION), 0)
|
|
1390
|
+
return row - sum(size for _source, size in self.described)
|
|
1391
|
+
|
|
1392
|
+
def stated(self, unit: str, each: int | None) -> str:
|
|
1393
|
+
room = "" if each is None else f", {each - self.characters:+} of {each}"
|
|
1394
|
+
rows = [f"{self.name} {self.characters} {unit}{room} ({self.where})"]
|
|
1395
|
+
for part, size in self.parts:
|
|
1396
|
+
rows.append(f" {size:>6} {part}")
|
|
1397
|
+
if part == DESCRIPTION:
|
|
1398
|
+
# Indented under the row it decomposes, and only where there is more than one
|
|
1399
|
+
# part: a description that is the parser's sentence alone would print its own
|
|
1400
|
+
# total twice, which is the rule `_print_parts` already keeps one read over.
|
|
1401
|
+
rows += [
|
|
1402
|
+
f" {clause:>6} from {source}" for source, clause in self.described
|
|
1403
|
+
]
|
|
1404
|
+
if self.quoting:
|
|
1405
|
+
rows.append(
|
|
1406
|
+
f" {self.quoting:>6} (its key, quoting, and the space between)"
|
|
1407
|
+
)
|
|
1408
|
+
rows.append(f" {self.envelope:>6} (the JSON around them: name, keys, required)")
|
|
1409
|
+
return chr(10).join(rows)
|
|
1410
|
+
|
|
1411
|
+
def payload(self, unit: str, each: int | None) -> dict[str, Any]:
|
|
1412
|
+
return {
|
|
1413
|
+
"tool": self.name,
|
|
1414
|
+
"characters": self.characters,
|
|
1415
|
+
"unit": unit,
|
|
1416
|
+
"each": each,
|
|
1417
|
+
"declared_in": self.where,
|
|
1418
|
+
"by_field": [{"field": part, "characters": size} for part, size in self.parts],
|
|
1419
|
+
# The seam inside the largest row, where there is one (RK1239). Measured as the
|
|
1420
|
+
# clause is written, so it sums to the sentence rather than to the serialised
|
|
1421
|
+
# property above — the difference being that property's key, quotes and joins.
|
|
1422
|
+
"description_from": [
|
|
1423
|
+
{"source": source, "characters": size} for source, size in self.described
|
|
1424
|
+
],
|
|
1425
|
+
# And what those clauses do not account for, named rather than left to be
|
|
1426
|
+
# subtracted (RK1241) — the same row `envelope` is, one level in.
|
|
1427
|
+
"description_quoting": self.quoting,
|
|
1428
|
+
"envelope": self.envelope,
|
|
1429
|
+
}
|
|
1430
|
+
|
|
1431
|
+
|
|
1432
|
+
def detail(config: Config, name: str) -> Detail:
|
|
1433
|
+
"""One published tool, ranked by what each field of it costs (RK1236).
|
|
1434
|
+
|
|
1435
|
+
Measured off :func:`descriptor` for :func:`surface`'s own reason: the payload itself and
|
|
1436
|
+
never a second estimate of it, so a sentence reworded in `verbs/` moves this figure.
|
|
1437
|
+
|
|
1438
|
+
Each part is the field **as it is sent** — `json.dumps` of its schema, keyed — so the
|
|
1439
|
+
numbers are in the units the ceiling counts and a row can be subtracted from the total.
|
|
1440
|
+
"""
|
|
1441
|
+
parsers = _parsers()
|
|
1442
|
+
for tool in TOOLS:
|
|
1443
|
+
if tool.name != name:
|
|
1444
|
+
continue
|
|
1445
|
+
# Named and withheld is not named and unknown (RK1360): the caller asking what a tool
|
|
1446
|
+
# costs on a project that is not sent it has asked a well-formed question, and the
|
|
1447
|
+
# answer is the role, not `no such tool`.
|
|
1448
|
+
if not tool.published(config):
|
|
1449
|
+
raise Withheld(tool.name, tool.needs)
|
|
1450
|
+
payload = descriptor(tool, config, parsers)
|
|
1451
|
+
parts = {
|
|
1452
|
+
DESCRIPTION: width(json.dumps({"description": payload["description"]},
|
|
1453
|
+
ensure_ascii=False))
|
|
1454
|
+
}
|
|
1455
|
+
for field, schema in payload["inputSchema"]["properties"].items():
|
|
1456
|
+
parts[field] = width(json.dumps({field: schema}, ensure_ascii=False))
|
|
1457
|
+
written = _described(tool, _subparser(tool.command, parsers))
|
|
1458
|
+
return Detail(
|
|
1459
|
+
name=name,
|
|
1460
|
+
parts=tuple(sorted(parts.items(), key=lambda row: (-row[1], row[0]))),
|
|
1461
|
+
characters=width(json.dumps(payload, ensure_ascii=False)),
|
|
1462
|
+
where=_declared_in(tool, parsers, config),
|
|
1463
|
+
# Nothing to split where the description is the parser's own sentence alone.
|
|
1464
|
+
described=(
|
|
1465
|
+
()
|
|
1466
|
+
if len(written) < 2
|
|
1467
|
+
else tuple((source, width(text)) for source, text in written)
|
|
1468
|
+
),
|
|
1469
|
+
)
|
|
1470
|
+
raise KeyError(name)
|
|
1471
|
+
|
|
1472
|
+
|
|
1473
|
+
def _declared_in(
|
|
1474
|
+
tool: Tool, parsers: Mapping[str, argparse.ArgumentParser], config: Config
|
|
1475
|
+
) -> str:
|
|
1476
|
+
"""Which file declares this verb, which is where a `help=` string is edited.
|
|
1477
|
+
|
|
1478
|
+
The address RK1192 found actionable, and the one argparse itself cannot give: an action
|
|
1479
|
+
records no source location, so what is resolvable is the module the *handler* was defined
|
|
1480
|
+
in — which is the module its parser is built in, every verb family declaring both.
|
|
1481
|
+
|
|
1482
|
+
Relative to the project where the engine is inside it, which is the developing checkout
|
|
1483
|
+
and the only reader who can act on this at all; absolute otherwise, because a path
|
|
1484
|
+
shortened against a tree it is not under would name a file that is not there.
|
|
1485
|
+
"""
|
|
1486
|
+
handler = _subparser(tool.command, parsers).get_default("handler")
|
|
1487
|
+
module = sys.modules.get(getattr(handler, "__module__", ""))
|
|
1488
|
+
found = getattr(module, "__file__", None)
|
|
1489
|
+
if found is None:
|
|
1490
|
+
return "unknown"
|
|
1491
|
+
where = Path(found).resolve()
|
|
1492
|
+
try:
|
|
1493
|
+
return where.relative_to(config.root).as_posix()
|
|
1494
|
+
except ValueError:
|
|
1495
|
+
return where.as_posix()
|
|
1496
|
+
|
|
1497
|
+
|
|
1498
|
+
def instructions() -> str:
|
|
1499
|
+
"""What a client is told once, at the handshake (RK79, RK1060).
|
|
1500
|
+
|
|
1501
|
+
Two facts, and both are about the whole surface rather than about any tool on it: which
|
|
1502
|
+
copy of this package answered, and how every bound in the schema is counted. The second
|
|
1503
|
+
was published 13 times over instead, once per prose field, which is 4,186 characters a
|
|
1504
|
+
session read before making a call — the cost RK464 measured and `[tools] characters` now
|
|
1505
|
+
holds one tool of.
|
|
1506
|
+
"""
|
|
1507
|
+
return f"{engine()}\n\n{_COUNTING}"
|
|
1508
|
+
|
|
1509
|
+
|
|
1510
|
+
def _roles(config: Config, universe: Sequence[str]) -> dict[str, Any]:
|
|
1511
|
+
"""The roles a caller may name, as the enum a client validates against (RK304).
|
|
1512
|
+
|
|
1513
|
+
``universe`` is what the *command* means by a role and the config is what this project has,
|
|
1514
|
+
and the answer is the intersection: `section add` writes into a prose file and `list` prints
|
|
1515
|
+
any governed one, so one enum over both would refuse `roadmap` on the read or offer it on the
|
|
1516
|
+
write. Passed in rather than inferred, because it is a fact about the verb.
|
|
1517
|
+
|
|
1518
|
+
Not argparse `choices`, for the reason §RK304 gives: `--role` accepts what the *project*
|
|
1519
|
+
declares, and a parser built once per process cannot say so without being rebuilt per project.
|
|
1520
|
+
Nothing is checked here either — unlike a conditional field's `pattern` (:func:`_bounded`),
|
|
1521
|
+
every role this narrows is one the write path beneath already refuses by name, so a check
|
|
1522
|
+
here would be a second spelling of a refusal `Config.path` owns.
|
|
1523
|
+
|
|
1524
|
+
**Empty publishes nothing.** A project that declares no file of this kind has no legal value
|
|
1525
|
+
to offer, and `"enum": []` is a keyword no value satisfies — a client holding it could not make
|
|
1526
|
+
the call that earns the refusal explaining why, which is the one useful thing left to say.
|
|
1527
|
+
"""
|
|
1528
|
+
declared = [role for role in universe if config.has(role)]
|
|
1529
|
+
return {"enum": declared} if declared else {}
|
|
1530
|
+
|
|
1531
|
+
|
|
1532
|
+
def _undeclared(config: Config) -> dict[str, Any]:
|
|
1533
|
+
"""What `declare` could still add, as the enum a client validates against (RK1264).
|
|
1534
|
+
|
|
1535
|
+
:func:`_roles`' complement, and empty for the same reason it publishes nothing: a project
|
|
1536
|
+
declaring all five has no role left to add, and `"enum": []` is a keyword no value satisfies
|
|
1537
|
+
— a client holding it could not make the call that earns the refusal saying so.
|
|
1538
|
+
|
|
1539
|
+
**Two vocabularies since RK1328**: a role adds a file and its `[files]` key, an opt-in table
|
|
1540
|
+
opens a list, and the argument carries both because both are *this file, one key, refused
|
|
1541
|
+
where it is already declared*. Undeclared on each axis is asked of that axis — `config.has`
|
|
1542
|
+
for a file, the parsed table for a list — so a project that opened one and not the other is
|
|
1543
|
+
offered exactly what it is missing.
|
|
1544
|
+
"""
|
|
1545
|
+
absent = [role for role in ROLES if not config.has(role)]
|
|
1546
|
+
absent += [table for table in OPT_IN if getattr(config, table) is None]
|
|
1547
|
+
return {"enum": absent} if absent else {}
|
|
1548
|
+
|
|
1549
|
+
|
|
1550
|
+
def _listed_markers(config: Config) -> dict[str, Any]:
|
|
1551
|
+
"""Every marker a declared file can carry, for the one filter that reads any of them (RK314).
|
|
1552
|
+
|
|
1553
|
+
`list --marker` is checked against `schema_for(--role)` — the changelog declares `✅ 🗑`, the
|
|
1554
|
+
roadmap the open four — and JSON Schema cannot make one field's enum depend on another's
|
|
1555
|
+
value. So the union, in the order `ROLES` declares the files, first occurrence winning: it is
|
|
1556
|
+
over-permissive by the markers legal on some *other* role, and every one of those is refused
|
|
1557
|
+
by the read beneath with the set that role does declare.
|
|
1558
|
+
|
|
1559
|
+
The direction matters and is the one rule this whole derivation keeps: a bound that refuses
|
|
1560
|
+
what the tool accepts is a bound on the client (RK183), and a per-role enum would refuse
|
|
1561
|
+
`--role changelog --marker ✅` before the call was ever made.
|
|
1562
|
+
"""
|
|
1563
|
+
seen: list[str] = []
|
|
1564
|
+
for role in ROLES:
|
|
1565
|
+
if not config.has(role):
|
|
1566
|
+
continue
|
|
1567
|
+
schema = config.schema_for(role)
|
|
1568
|
+
for marker in (*schema.markers, schema.shipped_marker):
|
|
1569
|
+
if marker not in seen:
|
|
1570
|
+
seen.append(marker)
|
|
1571
|
+
return {"enum": seen} if seen else {}
|
|
1572
|
+
|
|
1573
|
+
|
|
1574
|
+
def _pathed(config: Config) -> str: # noqa: ARG001 - the table's signature, not this fact's
|
|
1575
|
+
"""The one thing a path means differently here than at a terminal (RK1260).
|
|
1576
|
+
|
|
1577
|
+
`PATH_ARGUMENTS` classes a body file as the **caller's**, read the way `cat` reads one — and
|
|
1578
|
+
at a terminal the caller's directory and the project are usually the same tree, so the
|
|
1579
|
+
distinction never shows. Over MCP they are two: `-C` selects the project and this process
|
|
1580
|
+
sits wherever the harness launched it, which is `Config.locate`'s own argument arriving on
|
|
1581
|
+
the class of path it excludes. So the resolution is published rather than assumed, and the
|
|
1582
|
+
spelling that cannot be wrong is named.
|
|
1583
|
+
|
|
1584
|
+
Takes a config it does not read, because the table is one signature and a lambda-shaped
|
|
1585
|
+
exception would be the second thing a reader of :data:`_BOUNDS` has to know.
|
|
1586
|
+
"""
|
|
1587
|
+
return (
|
|
1588
|
+
"Opened by this server, from its own directory and not the project `-C` names — so an "
|
|
1589
|
+
"absolute path is the one spelling that cannot mean two files."
|
|
1590
|
+
)
|
|
1591
|
+
|
|
1592
|
+
|
|
1593
|
+
def _paragraphed(config: Config) -> str:
|
|
1594
|
+
"""A ceiling already stated in words, published as one (RK258).
|
|
1595
|
+
|
|
1596
|
+
:func:`_aimed`'s inverse and the easier half: RK185 translates characters into words because
|
|
1597
|
+
a model cannot count the former, and a section's budget is *declared* in words (RK9), so it
|
|
1598
|
+
needs no translation at all — which is why it publishing nothing was the odd case.
|
|
1599
|
+
|
|
1600
|
+
Per role, because `[limits.<role>]` can give one prose file its own number (RK50) and this one
|
|
1601
|
+
field reaches two: the default `role` is named with its figure, and a role that differs is
|
|
1602
|
+
named beside it rather than averaged into a number true of neither.
|
|
1603
|
+
|
|
1604
|
+
The roles it may name are the ones the project **declares** (RK259). `schema_for` answers for
|
|
1605
|
+
any role, composing `[limits.<role>]` over the base and having no reason to check for a file —
|
|
1606
|
+
so walking `PROSE_ROLES` published a figure for `strategy` on a project carrying
|
|
1607
|
+
`[limits.strategy]` and no `[files] strategy`, naming a role `section add --role` would refuse.
|
|
1608
|
+
`config.has` and :func:`~roadkeep.authoring.prose_role` are the same narrowing every other
|
|
1609
|
+
reader of this question already makes, on the argument that a command naming a file nobody
|
|
1610
|
+
created cannot run — and with nothing declared at all the base number is still the honest
|
|
1611
|
+
answer, the field existing on the tool whatever this project's `[files]` says.
|
|
1612
|
+
"""
|
|
1613
|
+
from roadkeep.authoring import prose_role # noqa: PLC0415 - `authoring` reaches `sections`
|
|
1614
|
+
|
|
1615
|
+
limits = {
|
|
1616
|
+
role: config.schema_for(role).section_max for role in PROSE_ROLES if config.has(role)
|
|
1617
|
+
}
|
|
1618
|
+
binding = limits.get(prose_role(config) or "", config.schema.section_max)
|
|
1619
|
+
# The aim beside the gate, as every other bound here publishes one (RK301): a ceiling
|
|
1620
|
+
# published as its own target is a target hit from above, measured at thirteen refusals
|
|
1621
|
+
# in one session — and over this transport the retry re-sends the whole body.
|
|
1622
|
+
said = (
|
|
1623
|
+
f"Aim for {body_aim(binding)} words; {binding} is what refuses, counted as words "
|
|
1624
|
+
f"rather than characters. `budget` states it per call, before the body exists."
|
|
1625
|
+
)
|
|
1626
|
+
differing = sorted(
|
|
1627
|
+
f"{role} {limit}" for role, limit in limits.items() if limit != binding
|
|
1628
|
+
)
|
|
1629
|
+
if differing:
|
|
1630
|
+
said += f" Where `role` names {', '.join(differing)}, that file's own number binds."
|
|
1631
|
+
return said
|
|
1632
|
+
|
|
1633
|
+
|
|
1634
|
+
class ToolError(Exception):
|
|
1635
|
+
"""An argument name or shape the schema already rules out — refused before dispatch."""
|
|
1636
|
+
|
|
1637
|
+
|
|
1638
|
+
class Withheld(KeyError):
|
|
1639
|
+
"""A tool this build has and this project is not sent, named with the role that opens it.
|
|
1640
|
+
|
|
1641
|
+
A `KeyError`, because the one caller that already handled a name this surface does not
|
|
1642
|
+
answer for handled it as one (RK1360) — and a subclass, because "not a tool" and "not a
|
|
1643
|
+
tool *here*" are two answers and only the second one has a remedy. :attr:`role` is what
|
|
1644
|
+
the remedy names, so no reader of this composes `declare` from a table of its own.
|
|
1645
|
+
"""
|
|
1646
|
+
|
|
1647
|
+
def __init__(self, tool: str, role: str) -> None:
|
|
1648
|
+
super().__init__(tool)
|
|
1649
|
+
self.tool = tool
|
|
1650
|
+
self.role = role
|
|
1651
|
+
|
|
1652
|
+
def __str__(self) -> str:
|
|
1653
|
+
return (
|
|
1654
|
+
f"{self.tool} is the {self.role} role's verb and this project declares no "
|
|
1655
|
+
f"{self.role} file, so the tool is not published here — `declare {self.role}` "
|
|
1656
|
+
f"writes the file and the `[files]` key, and the tool arrives with it"
|
|
1657
|
+
)
|
|
1658
|
+
|
|
1659
|
+
|
|
1660
|
+
# -- describing the tools ----------------------------------------------------
|
|
1661
|
+
|
|
1662
|
+
|
|
1663
|
+
def _action(parser: argparse.ArgumentParser, dest: str) -> argparse.Action:
|
|
1664
|
+
for candidate in parser._actions: # noqa: SLF001 - argparse exposes no public reader
|
|
1665
|
+
if candidate.dest == dest:
|
|
1666
|
+
return candidate
|
|
1667
|
+
raise KeyError(f"{parser.prog} declares no {dest!r}")
|
|
1668
|
+
|
|
1669
|
+
|
|
1670
|
+
@lru_cache(maxsize=1)
|
|
1671
|
+
def _root() -> argparse.ArgumentParser:
|
|
1672
|
+
"""The CLI parser, built once for the life of this process (RK202).
|
|
1673
|
+
|
|
1674
|
+
RK174 and RK198 each removed a rebuild and left the last one on an argument: that a
|
|
1675
|
+
parser held across messages would stop a `roadkeep.toml` edited mid-session from being
|
|
1676
|
+
described. Counted, that is false. `build_parser` reads no configuration at all — two
|
|
1677
|
+
builds under two different configs on disk are identical action for action — and every
|
|
1678
|
+
configured value reaches a descriptor through `_BOUNDS`, off a config this server
|
|
1679
|
+
re-reads per message. A parser is a pure function of `cli.py`.
|
|
1680
|
+
|
|
1681
|
+
Nor is it staler than what is already here: `cli.py` is imported once, so a parser built
|
|
1682
|
+
from the loaded module cannot describe a file edited after that import whether it is
|
|
1683
|
+
cached or not. RK155 reports that, and reports it the same either way.
|
|
1684
|
+
|
|
1685
|
+
What the cache does assume is that nobody mutates the parser it hands out. Nothing in
|
|
1686
|
+
this package does — `parse_args` builds a Namespace, `descriptor` and `argv` read
|
|
1687
|
+
actions — and `tests/test_serving.py` holds it rather than this sentence.
|
|
1688
|
+
|
|
1689
|
+
**The second build is real and is left alone** (RK1061). `main` builds a tree to
|
|
1690
|
+
dispatch the verb and this builds another to describe the surface, so a `lint` holding
|
|
1691
|
+
`[tools] characters` builds two — and `remedying._reading` is a third caller caching its
|
|
1692
|
+
own derivation of the same uncached object (RK1015). Caching `build_parser` removes the
|
|
1693
|
+
duplicate and was tried and reverted: measured at **6.3 ms once per process**, against a
|
|
1694
|
+
`lint` process of ~460 ms, and it is bought by freezing every `handler=` the parser
|
|
1695
|
+
holds at first build. A `monkeypatch` on one then silently does nothing — which is not a
|
|
1696
|
+
hypothetical, it is what the revert was written from. 1.4% is not worth a change that
|
|
1697
|
+
makes a patch fail by having no effect.
|
|
1698
|
+
"""
|
|
1699
|
+
from roadkeep.cli import build_parser
|
|
1700
|
+
|
|
1701
|
+
return build_parser()
|
|
1702
|
+
|
|
1703
|
+
|
|
1704
|
+
def _parsers(
|
|
1705
|
+
root: argparse.ArgumentParser | None = None,
|
|
1706
|
+
) -> Mapping[str, argparse.ArgumentParser]:
|
|
1707
|
+
"""Every subcommand path in the CLI, indexed by it, off **one** parser (RK174).
|
|
1708
|
+
|
|
1709
|
+
Reaching one subcommand means building the whole CLI, so a caller with more than one to
|
|
1710
|
+
resolve pays that per lookup — 58 builds and 195 ms for the `tools/list` a client sends
|
|
1711
|
+
first. The walk is the same descent :func:`_subparser` makes, done once and kept.
|
|
1712
|
+
|
|
1713
|
+
``root`` is the parser to index, for the caller that has to keep it anyway (RK198):
|
|
1714
|
+
:func:`call` parses the argv it built through the root, so building a second one to
|
|
1715
|
+
index was a third of what a `tools/call` spent. Defaulted to :func:`_root`, so the
|
|
1716
|
+
index is walked per call and the parser under it is built per process.
|
|
1717
|
+
"""
|
|
1718
|
+
if root is None:
|
|
1719
|
+
root = _root()
|
|
1720
|
+
index: dict[str, argparse.ArgumentParser] = {}
|
|
1721
|
+
|
|
1722
|
+
def walk(parser: argparse.ArgumentParser, path: str) -> None:
|
|
1723
|
+
for action in parser._actions: # noqa: SLF001 - argparse exposes no public reader
|
|
1724
|
+
if not isinstance(action, argparse._SubParsersAction): # noqa: SLF001
|
|
1725
|
+
continue
|
|
1726
|
+
for step, sub in action.choices.items():
|
|
1727
|
+
index[f"{path} {step}".strip()] = sub
|
|
1728
|
+
walk(sub, f"{path} {step}".strip())
|
|
1729
|
+
|
|
1730
|
+
walk(root, "")
|
|
1731
|
+
return index
|
|
1732
|
+
|
|
1733
|
+
|
|
1734
|
+
def _subparser(
|
|
1735
|
+
command: str, parsers: Mapping[str, argparse.ArgumentParser] | None = None
|
|
1736
|
+
) -> argparse.ArgumentParser:
|
|
1737
|
+
"""The parser for a subcommand path, descending where it is nested (`section add`).
|
|
1738
|
+
|
|
1739
|
+
Takes an index where the caller has one, and builds itself one where it does not — so
|
|
1740
|
+
`descriptor(tool, config)` stays callable with a single tool, which is how the tests ask
|
|
1741
|
+
what one schema is.
|
|
1742
|
+
"""
|
|
1743
|
+
return (_parsers() if parsers is None else parsers)[command]
|
|
1744
|
+
|
|
1745
|
+
|
|
1746
|
+
def _property(
|
|
1747
|
+
action: argparse.Action,
|
|
1748
|
+
config: Config,
|
|
1749
|
+
bounds_for: Mapping[str, Any] = _BOUNDS,
|
|
1750
|
+
*,
|
|
1751
|
+
piped: bool = False,
|
|
1752
|
+
) -> dict[str, Any]:
|
|
1753
|
+
"""One argparse argument, as the JSON Schema a client validates before calling.
|
|
1754
|
+
|
|
1755
|
+
``piped`` says this argument is one the CLI documents as reading stdin, which is the one
|
|
1756
|
+
sentence this surface may not repeat (RK1260): there is no stdin here and no shell, so a
|
|
1757
|
+
clause about how a backtick survives one described a channel the agent loading the schema
|
|
1758
|
+
cannot reach — and it did so in every session that connects, per tool. What stands in its
|
|
1759
|
+
place is what the transport actually does, which :func:`_companioned` then refuses by.
|
|
1760
|
+
"""
|
|
1761
|
+
bounds = dict(bounds_for.get(action.dest, lambda _: {})(config))
|
|
1762
|
+
# A bound the schema has no keyword for. `maxLength` says how long the field may be and
|
|
1763
|
+
# cannot say what else the length depends on, so the part that is a *joint* rule is
|
|
1764
|
+
# appended to the sentence the CLI already prints for the flag rather than dropped.
|
|
1765
|
+
note = bounds.pop("note", "")
|
|
1766
|
+
help_ = (action.help or "").strip()
|
|
1767
|
+
if piped:
|
|
1768
|
+
help_ = _unpiped(help_)
|
|
1769
|
+
described = {"description": _joined(help_, note)}
|
|
1770
|
+
if isinstance(action, argparse._StoreTrueAction): # noqa: SLF001
|
|
1771
|
+
return {"type": "boolean", **described}
|
|
1772
|
+
if isinstance(action, argparse._AppendAction): # noqa: SLF001
|
|
1773
|
+
return {"type": "array", "items": {"type": "string", **bounds}, **described}
|
|
1774
|
+
return {"type": "string", **bounds, **described}
|
|
1775
|
+
|
|
1776
|
+
|
|
1777
|
+
def _unpiped(help_: str) -> str:
|
|
1778
|
+
"""The CLI's sentence with its pipe clause replaced by what is true here (RK1260).
|
|
1779
|
+
|
|
1780
|
+
Declared clauses only, and the clause is removed **wherever it sits** rather than assumed
|
|
1781
|
+
to end the sentence: `--section-body` says "; omitted or '-' reads stdin. Read only with
|
|
1782
|
+
--section", and a rewrite that took the tail would have taken the half that still holds.
|
|
1783
|
+
A help string carrying none is left exactly as written — this transport does not edit prose
|
|
1784
|
+
it did not compose (L4), and a `Prose` whose spelling drifted out of the list is a test
|
|
1785
|
+
failure where the list lives rather than a schema quietly still promising a pipe.
|
|
1786
|
+
"""
|
|
1787
|
+
from roadkeep.verbs.declaring import ( # noqa: PLC0415 - RK1171
|
|
1788
|
+
PIPE_CLAUSES,
|
|
1789
|
+
SERVED_PIPE,
|
|
1790
|
+
)
|
|
1791
|
+
|
|
1792
|
+
for clause in PIPE_CLAUSES:
|
|
1793
|
+
if clause in help_:
|
|
1794
|
+
return help_.replace(clause, "", 1).rstrip() + SERVED_PIPE
|
|
1795
|
+
return help_
|
|
1796
|
+
|
|
1797
|
+
|
|
1798
|
+
def _required(action: argparse.Action) -> bool:
|
|
1799
|
+
# A positional is required by being one; `nargs="?"` is the exception, and `ship id` is
|
|
1800
|
+
# not one. Reading it off the action keeps the two lists from disagreeing.
|
|
1801
|
+
return bool(action.required) or (not action.option_strings and action.nargs != "?")
|
|
1802
|
+
|
|
1803
|
+
|
|
1804
|
+
def _joined(help_: str, note: str) -> str:
|
|
1805
|
+
"""The flag's own sentence and what the config adds to it, as one readable string.
|
|
1806
|
+
|
|
1807
|
+
The CLI's `help` is a fragment with no full stop — it is read under a column heading —
|
|
1808
|
+
so a note appended with a space ran the two together into "never a fix Aim for 18
|
|
1809
|
+
words". Ending the first is the whole fix, and it is here rather than in each note
|
|
1810
|
+
because the notes are composed by the config and the fragment by argparse.
|
|
1811
|
+
"""
|
|
1812
|
+
if not note:
|
|
1813
|
+
return help_
|
|
1814
|
+
if help_ and help_[-1] not in ".!?:;":
|
|
1815
|
+
help_ += "."
|
|
1816
|
+
return " ".join(part for part in (help_, note) if part)
|
|
1817
|
+
|
|
1818
|
+
|
|
1819
|
+
def _description(tool: Tool, parser: argparse.ArgumentParser) -> str:
|
|
1820
|
+
"""The subcommand's own description, plus what an always-passed flag adds to it (RK150).
|
|
1821
|
+
|
|
1822
|
+
Derived and never written here: the flag's help is the sentence the CLI prints for it, so
|
|
1823
|
+
two tools over one command cannot come to describe that difference in two ways — and a
|
|
1824
|
+
tool whose whole point is a flag it never mentioned would be a tool a client mistakes for
|
|
1825
|
+
the read it was split off from.
|
|
1826
|
+
"""
|
|
1827
|
+
return " ".join(text for _source, text in _described(tool, parser))
|
|
1828
|
+
|
|
1829
|
+
|
|
1830
|
+
def _described(
|
|
1831
|
+
tool: Tool, parser: argparse.ArgumentParser
|
|
1832
|
+
) -> tuple[tuple[str, str], ...]:
|
|
1833
|
+
"""The same sentence as the parts it is composed of, each named by where it is written.
|
|
1834
|
+
|
|
1835
|
+
:func:`_description` joins these and every caller wanted the join, so the seam was thrown
|
|
1836
|
+
away — and on the two tools measured here that seam is the largest row `cost --tools
|
|
1837
|
+
<name>` prints: 725 of `merge_check`'s 871, 427 of `claim`'s 949 (RK1239). A reader
|
|
1838
|
+
shortening the `description=` in front of them is cutting a fraction of what the row
|
|
1839
|
+
measured, because the rest was written as another flag's `help` in another file.
|
|
1840
|
+
|
|
1841
|
+
Named by the flag and not by an index: what a caller needs is which text to open, and
|
|
1842
|
+
`--check`'s sentence is edited where `--check` is declared.
|
|
1843
|
+
"""
|
|
1844
|
+
parts = [("description", (parser.description or "").strip())]
|
|
1845
|
+
for dest in tool.always:
|
|
1846
|
+
action = _action(parser, dest)
|
|
1847
|
+
flag, help_ = action.option_strings[0], (action.help or "").strip()
|
|
1848
|
+
parts.append((flag, f"This tool always passes {flag}, which is to {help_}."))
|
|
1849
|
+
return tuple(parts)
|
|
1850
|
+
|
|
1851
|
+
|
|
1852
|
+
def _bounds_for(tool: Tool) -> Mapping[str, Any]:
|
|
1853
|
+
"""Which bounds table describes this tool's fields, by the verb and never by the dest.
|
|
1854
|
+
|
|
1855
|
+
Commands mean something of their own by a name every other command shares: `non-goal`'s
|
|
1856
|
+
`why` is `[non_goals]`' limit and not `[limits]`' (RK70), `list`'s `role` is any governed
|
|
1857
|
+
file and its `marker` any marker one can carry (RK304, RK314), and `ship`'s and `record
|
|
1858
|
+
amend`'s `why` has a shape no ceiling describes (RK1055). All are properties of the verb
|
|
1859
|
+
rather than of the dest, so all are read off it, here and in one place: a second `if` at the
|
|
1860
|
+
caller is how two tools over one dest come to publish two answers.
|
|
1861
|
+
|
|
1862
|
+
**The full command first, then its first word** (RK1055). `record amend` takes a span and
|
|
1863
|
+
`record add` does not, so the two doors under one head need different answers — and the
|
|
1864
|
+
fallback is what keeps `non-goal add` and `non-goal drop` one entry rather than two.
|
|
1865
|
+
|
|
1866
|
+
Read from :data:`_DIVERGENT` and no longer from an `if` chain (RK316). The chain's failure was
|
|
1867
|
+
silent and in the forbidden direction: a command renamed in `cli.py` left every `Tool` correct
|
|
1868
|
+
and no branch matching, so the fields fell back to `_BOUNDS` — narrower than the verb accepts,
|
|
1869
|
+
which is a bound on the client (RK183). A table has the same words in it and is *checkable*,
|
|
1870
|
+
which is RK167's own answer to a declaration that can stop matching: a key naming no command
|
|
1871
|
+
is a test failure (`tests/test_serving.py`) rather than a schema quietly refusing a legal call.
|
|
1872
|
+
Not moved onto :class:`Tool` — the tables are composed from the config below this line, and
|
|
1873
|
+
two divergent verbs out of thirty-odd is a fact about those two rather than a field for all.
|
|
1874
|
+
"""
|
|
1875
|
+
if tool.command in _DIVERGENT:
|
|
1876
|
+
return _DIVERGENT[tool.command]
|
|
1877
|
+
return _DIVERGENT.get(tool.argv_head[0], _BOUNDS)
|
|
1878
|
+
|
|
1879
|
+
|
|
1880
|
+
def descriptor(
|
|
1881
|
+
tool: Tool, config: Config, parsers: Mapping[str, argparse.ArgumentParser] | None = None
|
|
1882
|
+
) -> dict[str, Any]:
|
|
1883
|
+
parser = _subparser(tool.command, parsers)
|
|
1884
|
+
# Which table holds this tool's numbers: the non-goals are governed by `[non_goals]` and
|
|
1885
|
+
# every other command by `[limits]`, and `why` is a field both of them name (RK70) — plus the
|
|
1886
|
+
# one command whose `role` means *which governed file* rather than which prose file (RK304).
|
|
1887
|
+
bounds_for = _bounds_for(tool)
|
|
1888
|
+
# Which of this command's arguments the CLI documents as reading the pipe (RK1260), off the
|
|
1889
|
+
# declaration `_companioned` already refuses by — so the schema and the refusal cannot come
|
|
1890
|
+
# to say two different things about the same field.
|
|
1891
|
+
piped = {prose.dest for prose in prose_of(tool.command, parsers)}
|
|
1892
|
+
properties: dict[str, Any] = {}
|
|
1893
|
+
required: list[str] = []
|
|
1894
|
+
for dest in tool.exposed(config):
|
|
1895
|
+
action = _action(parser, dest)
|
|
1896
|
+
properties[dest] = _property(action, config, bounds_for, piped=dest in piped)
|
|
1897
|
+
if _required(action):
|
|
1898
|
+
required.append(dest)
|
|
1899
|
+
payload: dict[str, Any] = {
|
|
1900
|
+
"name": tool.name,
|
|
1901
|
+
"description": _description(tool, parser),
|
|
1902
|
+
"inputSchema": {
|
|
1903
|
+
"type": "object",
|
|
1904
|
+
"properties": properties,
|
|
1905
|
+
# Closed on purpose: a misspelt argument is the failure RK24 names, and an open
|
|
1906
|
+
# object would forward it to a parser that answers with a usage string.
|
|
1907
|
+
"additionalProperties": False,
|
|
1908
|
+
},
|
|
1909
|
+
"annotations": {"readOnlyHint": not tool.writes_of(parser)},
|
|
1910
|
+
}
|
|
1911
|
+
if required:
|
|
1912
|
+
payload["inputSchema"]["required"] = required
|
|
1913
|
+
return payload
|
|
1914
|
+
|
|
1915
|
+
|
|
1916
|
+
def published(config: Config) -> tuple[Tool, ...]:
|
|
1917
|
+
"""The tools *this* project is sent, in :data:`TOOLS` order (RK1360).
|
|
1918
|
+
|
|
1919
|
+
Every read of the surface goes through here rather than through :data:`TOOLS` — the
|
|
1920
|
+
descriptors, the ranking, `cost --tools` and the digest a `list_changed` compares — so
|
|
1921
|
+
the figure answers per checkout instead of per build, and a `declare` mid-session moves
|
|
1922
|
+
the digest and sends the notification without anything else being asked to notice.
|
|
1923
|
+
|
|
1924
|
+
:func:`tool_named` deliberately does not: a name is resolved against the package, so a
|
|
1925
|
+
call to a withheld tool is refused by :func:`call` with the role it needs rather than by
|
|
1926
|
+
a lookup that says no such verb exists.
|
|
1927
|
+
"""
|
|
1928
|
+
return tuple(tool for tool in TOOLS if tool.published(config))
|
|
1929
|
+
|
|
1930
|
+
|
|
1931
|
+
def descriptors(config: Config) -> list[dict[str, Any]]:
|
|
1932
|
+
parsers = _parsers()
|
|
1933
|
+
return [descriptor(tool, config, parsers) for tool in published(config)]
|
|
1934
|
+
|
|
1935
|
+
|
|
1936
|
+
# -- calling one ------------------------------------------------------------
|
|
1937
|
+
|
|
1938
|
+
|
|
1939
|
+
@dataclass(frozen=True, slots=True)
|
|
1940
|
+
class Answer:
|
|
1941
|
+
"""What one `tools/call` returns: the CLI's own output, and its exit code as a flag."""
|
|
1942
|
+
|
|
1943
|
+
text: str
|
|
1944
|
+
is_error: bool
|
|
1945
|
+
|
|
1946
|
+
def content(self) -> dict[str, Any]:
|
|
1947
|
+
return {"content": [{"type": "text", "text": self.text}], "isError": self.is_error}
|
|
1948
|
+
|
|
1949
|
+
|
|
1950
|
+
def argv(
|
|
1951
|
+
tool: Tool,
|
|
1952
|
+
arguments: Mapping[str, Any],
|
|
1953
|
+
config: Config,
|
|
1954
|
+
parsers: Mapping[str, argparse.ArgumentParser] | None = None,
|
|
1955
|
+
) -> list[str]:
|
|
1956
|
+
"""The command line the CLI accepts, or `ToolError` naming what may be set instead.
|
|
1957
|
+
|
|
1958
|
+
Takes the config because what may be set is a question about the project (RK111), and
|
|
1959
|
+
because a bound the descriptor published is a bound this has to hold: a client that
|
|
1960
|
+
validated is not the same as a call that was checked.
|
|
1961
|
+
|
|
1962
|
+
``parsers`` is the index the caller already built (RK198). Optional, and defaulted the
|
|
1963
|
+
same way :func:`descriptor`'s is: a test asking what one tool's argv is has one lookup
|
|
1964
|
+
and nothing to amortise it over.
|
|
1965
|
+
"""
|
|
1966
|
+
parser = _subparser(tool.command, parsers)
|
|
1967
|
+
exposed = tool.exposed(config)
|
|
1968
|
+
unknown = [name for name in arguments if name not in exposed]
|
|
1969
|
+
if unknown:
|
|
1970
|
+
# This parser's own reasons and never `withheld()` (RK1371): that one walks the whole
|
|
1971
|
+
# CLI, which is the second build RK198 took off the refusal path — and the answer is
|
|
1972
|
+
# the same map, read where the parser is already in hand.
|
|
1973
|
+
raise ToolError(
|
|
1974
|
+
_unrecognised(tool, unknown, exposed, parser.get_default("withheld") or {})
|
|
1975
|
+
)
|
|
1976
|
+
_companioned(tool, arguments, parsers)
|
|
1977
|
+
positional: list[str] = []
|
|
1978
|
+
optional: list[str] = []
|
|
1979
|
+
for dest in exposed: # declaration order, so the argv is stable and diffable
|
|
1980
|
+
if dest not in arguments:
|
|
1981
|
+
continue
|
|
1982
|
+
action = _action(parser, dest)
|
|
1983
|
+
fragment = _rendered(action, dest, arguments[dest])
|
|
1984
|
+
_bounded(dest, arguments[dest], config)
|
|
1985
|
+
(optional if action.option_strings else positional).extend(fragment)
|
|
1986
|
+
# What makes this tool the act it is named for (RK150), resolved through the parser like
|
|
1987
|
+
# every exposed argument: a client cannot pass these and cannot unset them.
|
|
1988
|
+
always = [_action(parser, dest).option_strings[0] for dest in tool.always]
|
|
1989
|
+
# `--json` is never exposed and always passed: the provenance is the difference between
|
|
1990
|
+
# an answer an agent can audit and one it re-reads the file to check (L5).
|
|
1991
|
+
return [*tool.argv_head, *positional, *optional, *always, "--json"]
|
|
1992
|
+
|
|
1993
|
+
|
|
1994
|
+
def prose_of(
|
|
1995
|
+
command: str, parsers: Mapping[str, argparse.ArgumentParser] | None = None
|
|
1996
|
+
) -> tuple[Prose, ...]:
|
|
1997
|
+
"""What this subcommand takes off a pipe, as its own parser declares it (RK171).
|
|
1998
|
+
|
|
1999
|
+
The inventory neither `TOOLS` nor `cli.py` stated. Read from the parser rather than held
|
|
2000
|
+
here, so exposing a fourth command that reads a paragraph declares itself instead of being
|
|
2001
|
+
found by the session that hangs on it — and so `tests/test_serving.py` can ask the question
|
|
2002
|
+
over every tool at once, which is the instrument RK170 was fixed without.
|
|
2003
|
+
|
|
2004
|
+
``parsers`` stays optional because that test asks one command at a time (RK198); the call
|
|
2005
|
+
path threads its index through, this lookup having been the second build of every call.
|
|
2006
|
+
|
|
2007
|
+
**A tuple, because one command can have two** (RK329). `--why` reads the pipe wherever it
|
|
2008
|
+
appears, and on `add` that is beside `--section-body` — the field whose sentence carries
|
|
2009
|
+
an apostrophe, a backtick and a `§` being the one a shell reads first. A single answer here
|
|
2010
|
+
would have named one of the two and left the other to be found by the session that meets it,
|
|
2011
|
+
which is the state RK171 exists to have ended.
|
|
2012
|
+
"""
|
|
2013
|
+
declared = _subparser(command, parsers).get_default("reads_stdin")
|
|
2014
|
+
return () if declared is None else tuple(declared)
|
|
2015
|
+
|
|
2016
|
+
|
|
2017
|
+
def _companioned(
|
|
2018
|
+
tool: Tool,
|
|
2019
|
+
arguments: Mapping[str, Any],
|
|
2020
|
+
parsers: Mapping[str, argparse.ArgumentParser] | None = None,
|
|
2021
|
+
) -> None:
|
|
2022
|
+
"""Refuse an argv that would have gone to the pipe, naming the argument (RK170, RK171).
|
|
2023
|
+
|
|
2024
|
+
The deadlock is closed by :func:`_spent_stdin` whatever this says, so what is bought here is
|
|
2025
|
+
only *which* refusal the caller reads: without it, `add` with a section title and no body
|
|
2026
|
+
answers `body.empty` — true, and about the prose, when the fact is that the argument carrying
|
|
2027
|
+
it did not arrive. Derived from :func:`prose_of` and not a table beside it, so all three
|
|
2028
|
+
declared paths answer the same way and a fourth cannot be the one that was forgotten.
|
|
2029
|
+
"""
|
|
2030
|
+
for prose in prose_of(tool.command, parsers):
|
|
2031
|
+
if prose.dest not in tool.unconditional or not prose.reached_by(arguments):
|
|
2032
|
+
continue
|
|
2033
|
+
raise ToolError(
|
|
2034
|
+
f"{tool.name}: {prose.dest} is the prose itself, and over this transport there "
|
|
2035
|
+
f"is no pipe to read it from — pass it as a string. Omitted, or "
|
|
2036
|
+
f"{prose.sentinel!r}, it is nothing, and this format has no slot that may be "
|
|
2037
|
+
f"empty"
|
|
2038
|
+
)
|
|
2039
|
+
|
|
2040
|
+
|
|
2041
|
+
def _unrecognised(
|
|
2042
|
+
tool: Tool,
|
|
2043
|
+
unknown: Sequence[str],
|
|
2044
|
+
exposed: Sequence[str],
|
|
2045
|
+
kept: Mapping[str, str] | None = None,
|
|
2046
|
+
) -> str:
|
|
2047
|
+
"""Why these names did not reach the argv, told apart from each other (RK253).
|
|
2048
|
+
|
|
2049
|
+
An argument this project *closed* is not one that does not exist. `--ref` and `--id` are
|
|
2050
|
+
declared by the CLI, printed by its `--help` and reachable at a terminal; what is true over
|
|
2051
|
+
this transport is that `roadkeep.toml` shut them here (RK111). Led with "no such argument"
|
|
2052
|
+
they read as a misspelling, and the caller looks for a typo in a name spelled correctly —
|
|
2053
|
+
RK111 saw that reading and answered it by appending :func:`_withheld` rather than by
|
|
2054
|
+
correcting the claim, which leaves the correction arriving after the sentence that is wrong.
|
|
2055
|
+
|
|
2056
|
+
So the two are stated separately, over their own names, and a call that guessed both ways
|
|
2057
|
+
earns both. The partition is free: :attr:`Tool.conditional` is exactly the names that exist
|
|
2058
|
+
and are shut, and every other unknown one is a name nothing declares.
|
|
2059
|
+
|
|
2060
|
+
**Three and no longer two** (RK1371). A dest this verb declares and this surface withholds
|
|
2061
|
+
*by decision* — `fix`, `prune`, `body_file` — is neither of the above, and it landed under
|
|
2062
|
+
"no such argument", which is RK253's own misreading one category along: the caller looks for
|
|
2063
|
+
a typo in a name spelled correctly, and the sentence that would have answered them has been
|
|
2064
|
+
declared beside the argument since RK1169 and read by nothing but a test. Here it is read by
|
|
2065
|
+
the one moment somebody is asking, which is the call that just tried to pass it.
|
|
2066
|
+
|
|
2067
|
+
``kept`` is that parser's own reasons, handed in by the caller that already resolved it: a
|
|
2068
|
+
`withheld()` here walks the whole CLI, which is the second parser build RK198 took off this
|
|
2069
|
+
exact path. Defaulted for a test asking one tool what its refusal says.
|
|
2070
|
+
|
|
2071
|
+
A dest in :attr:`Tool.always` is **not** withheld however the parser reads: the reasons are
|
|
2072
|
+
per parser and two tools share one, so `brief`'s `claim` is a decision about that tool and
|
|
2073
|
+
unsettable on this one — which is a name it does not take, not a sentence about it (RK150).
|
|
2074
|
+
"""
|
|
2075
|
+
if kept is None:
|
|
2076
|
+
kept = withheld().get(tool.command, {})
|
|
2077
|
+
closed = sorted(set(unknown) & set(tool.conditional))
|
|
2078
|
+
held = sorted(
|
|
2079
|
+
name
|
|
2080
|
+
for name in set(unknown) - set(closed) - set(tool.always)
|
|
2081
|
+
if name in kept
|
|
2082
|
+
)
|
|
2083
|
+
absent = sorted(set(unknown) - set(closed) - set(held))
|
|
2084
|
+
stated = []
|
|
2085
|
+
if absent:
|
|
2086
|
+
stated.append(f"no such argument {', '.join(absent)}")
|
|
2087
|
+
if closed:
|
|
2088
|
+
stated.append(
|
|
2089
|
+
f"{', '.join(closed)} {'is' if len(closed) == 1 else 'are'} declared by the CLI "
|
|
2090
|
+
f"and closed by this project's config"
|
|
2091
|
+
)
|
|
2092
|
+
if held:
|
|
2093
|
+
stated.append(
|
|
2094
|
+
f"{', '.join(held)} {'is' if len(held) == 1 else 'are'} declared by this verb "
|
|
2095
|
+
f"and withheld from this surface"
|
|
2096
|
+
)
|
|
2097
|
+
return (
|
|
2098
|
+
f"{tool.name}: {'; '.join(stated)} — this tool takes "
|
|
2099
|
+
f"{', '.join(exposed) or 'no arguments'}"
|
|
2100
|
+
f"{_withheld(closed)}{_reasoned(held, kept)}"
|
|
2101
|
+
)
|
|
2102
|
+
|
|
2103
|
+
|
|
2104
|
+
def _reasoned(held: Sequence[str], kept: Mapping[str, str]) -> str:
|
|
2105
|
+
"""Why each withheld argument is not offered, in the words declared beside it (RK1371).
|
|
2106
|
+
|
|
2107
|
+
One clause per field, which is :func:`_withheld`'s rule and for its reason (RK241): two
|
|
2108
|
+
joined into one sentence name one cause for both, and these three kinds of reason — *it
|
|
2109
|
+
writes*, *the tool derives it*, *the shape does not cross* — are exactly what a caller has
|
|
2110
|
+
to tell apart to know whether to stop asking or to reach for the CLI.
|
|
2111
|
+
|
|
2112
|
+
Verbatim, and never summarised: the sentence is the author's and this places it (L4), which
|
|
2113
|
+
is the same division `govern --because` draws over a number in `roadkeep.toml`.
|
|
2114
|
+
"""
|
|
2115
|
+
return "".join(f". {dest}: {kept[dest]}" for dest in held)
|
|
2116
|
+
|
|
2117
|
+
|
|
2118
|
+
def _withheld(closed: Sequence[str]) -> str:
|
|
2119
|
+
"""Which declaration would have opened each closed field (RK111).
|
|
2120
|
+
|
|
2121
|
+
Which arguments a tool takes is a fact about `roadkeep.toml` (L6), so the refusal names the
|
|
2122
|
+
declaration to edit rather than only that the field is absent — and one clause per field
|
|
2123
|
+
(RK241), because two joined into one sentence named one table for both, and a caller told to
|
|
2124
|
+
declare an id shape to name an anchor is a caller sent to edit the wrong table.
|
|
2125
|
+
|
|
2126
|
+
Indexed and not guarded, which is what :class:`Conditional` buys (RK252): the reason travels
|
|
2127
|
+
with the predicate that opens the field, so a dest reaching one and not the other is not a
|
|
2128
|
+
state the record admits. RK251 needed a fallback here because two tables could disagree, and
|
|
2129
|
+
this ran on exactly one path — a caller passing a field this project closed — so the miss
|
|
2130
|
+
surfaced as a `KeyError` composing the refusal, for the caller who most needed the sentence.
|
|
2131
|
+
|
|
2132
|
+
Takes the partition :func:`_unrecognised` already made rather than making it again (RK253):
|
|
2133
|
+
the lead clause and these depend on the same split, and computing it twice is how the two
|
|
2134
|
+
come to disagree about which names are which.
|
|
2135
|
+
"""
|
|
2136
|
+
return "".join(f". {dest}: {_CONDITIONAL[dest].because}" for dest in closed)
|
|
2137
|
+
|
|
2138
|
+
|
|
2139
|
+
def _spelled(tool: Tool, parsers: Mapping[str, argparse.ArgumentParser] | None = None) -> str:
|
|
2140
|
+
"""This tool's **act** as a command line: the verb, and the flags that make it that one (RK318).
|
|
2141
|
+
|
|
2142
|
+
`tool.command` alone is a different act wherever :attr:`Tool.always` is what names the tool,
|
|
2143
|
+
which is RK150's whole mechanism — and a note advising it sends the reader somewhere else.
|
|
2144
|
+
Measured on all three tools that have one: `claim` is `brief --claim`, and `brief` *succeeds*,
|
|
2145
|
+
prints a briefing and takes no line, so the write the caller asked for silently does not
|
|
2146
|
+
happen; `merge_check` is `merge --check`, and `merge` exits 2 on its own usage string; `scope`
|
|
2147
|
+
is the real `claim` command and was right only by having no always flag.
|
|
2148
|
+
|
|
2149
|
+
Resolved through the parser and by dest, exactly as :func:`argv` resolves the same flags, so a
|
|
2150
|
+
rename in `cli.py` cannot leave this sentence naming something that is gone.
|
|
2151
|
+
|
|
2152
|
+
The always flags and no arguments. Those are the caller's — they were just sent — and every
|
|
2153
|
+
`always` dest is a `store_true` by construction, because `argv` renders it as the option
|
|
2154
|
+
string alone: so there is no value here to quote, which is the second grammar §RK313 declined.
|
|
2155
|
+
"""
|
|
2156
|
+
if not tool.always:
|
|
2157
|
+
return tool.command
|
|
2158
|
+
parser = _subparser(tool.command, parsers)
|
|
2159
|
+
flags = (_action(parser, dest).option_strings[0] for dest in tool.always)
|
|
2160
|
+
return " ".join((tool.command, *flags))
|
|
2161
|
+
|
|
2162
|
+
|
|
2163
|
+
def spelled(name: str) -> str | None:
|
|
2164
|
+
"""The command line for a name this tool publishes **over MCP**, or None (RK353).
|
|
2165
|
+
|
|
2166
|
+
Two surfaces name one act differently on purpose — `scope` is the tool for declaring what
|
|
2167
|
+
a commit owns, and at the CLI that act is `claim <id> --path …`, because there `claim`
|
|
2168
|
+
without a path is the other act — and the skill teaches the tool name. What a session that
|
|
2169
|
+
reads it and types `roadkeep scope RK345 --path …` gets is argparse's `invalid choice`
|
|
2170
|
+
followed by forty verbs, none of which is the one it was sent for.
|
|
2171
|
+
|
|
2172
|
+
The **tool table is the authority on a name**, which is the question §RK353 left open: it
|
|
2173
|
+
is what publishes the other spelling, it already carries the flags that make an act that
|
|
2174
|
+
one (:func:`_spelled`, RK318), and a second mapping in `cli.py` would be a second thing to
|
|
2175
|
+
keep in step with this one. So the parser asks here rather than answering itself.
|
|
2176
|
+
|
|
2177
|
+
A qualified name is taken too — `mcp__roadkeep__scope`, and the longer
|
|
2178
|
+
`mcp__plugin_roadkeep_roadkeep__scope` a plugin-provided server gives it (RK333) — because
|
|
2179
|
+
a name pasted out of a tool list arrives with its prefix, and the refusal that only knew
|
|
2180
|
+
the bare form would be the same defect one surface along.
|
|
2181
|
+
"""
|
|
2182
|
+
tool = next((one for one in TOOLS if one.name == name.rpartition("__")[2]), None)
|
|
2183
|
+
return None if tool is None else _spelled(tool)
|
|
2184
|
+
|
|
2185
|
+
|
|
2186
|
+
def _bounded(dest: str, value: Any, config: Config) -> None:
|
|
2187
|
+
"""Hold a conditional argument to the bound that opened it (RK111).
|
|
2188
|
+
|
|
2189
|
+
Only the conditional ones, and only their `pattern`: every other bound in :data:`_BOUNDS`
|
|
2190
|
+
is the schema's, so the write path beneath refuses a violation whatever a client sent. A
|
|
2191
|
+
conditional field's is this surface's alone — `add --id T24` stays legal at a terminal,
|
|
2192
|
+
where `adopt` writes ids a corpus already spent — so unchecked here is unchecked.
|
|
2193
|
+
|
|
2194
|
+
Conditional and still the schema's is the third case, and `ref` is it (RK241): an anchor
|
|
2195
|
+
that is not `<x.y>` is `ref.format` from `validate`, and where the pointer is derived the
|
|
2196
|
+
field is not exposed at all — so there is nothing this surface would be the only checker
|
|
2197
|
+
of, and a bound published here would be a second spelling of one the schema already holds.
|
|
2198
|
+
"""
|
|
2199
|
+
if dest not in _CONDITIONAL or dest not in _BOUNDS:
|
|
2200
|
+
return
|
|
2201
|
+
pattern = _BOUNDS[dest](config).get("pattern")
|
|
2202
|
+
if pattern and not re.match(pattern, _one(dest, value)):
|
|
2203
|
+
raise ToolError(
|
|
2204
|
+
f"{dest} must match {pattern}, got {_one(dest, value)!r} — the id you may "
|
|
2205
|
+
f"choose is the split of one that already exists, and a number without the "
|
|
2206
|
+
f"letter is one the counter derives: leave the field out and it is derived"
|
|
2207
|
+
)
|
|
2208
|
+
|
|
2209
|
+
|
|
2210
|
+
def _rendered(action: argparse.Action, dest: str, value: Any) -> list[str]:
|
|
2211
|
+
"""One JSON value as the argv fragment its own argparse action reads."""
|
|
2212
|
+
if not action.option_strings:
|
|
2213
|
+
return [_one(dest, value)]
|
|
2214
|
+
flag = action.option_strings[0]
|
|
2215
|
+
if isinstance(action, argparse._StoreTrueAction): # noqa: SLF001
|
|
2216
|
+
return [flag] if value else []
|
|
2217
|
+
if isinstance(action, argparse._AppendAction): # noqa: SLF001
|
|
2218
|
+
return [part for item in _many(dest, value) for part in (flag, item)]
|
|
2219
|
+
return [flag, _one(dest, value)]
|
|
2220
|
+
|
|
2221
|
+
|
|
2222
|
+
def _one(dest: str, value: Any) -> str:
|
|
2223
|
+
if isinstance(value, str):
|
|
2224
|
+
return value
|
|
2225
|
+
raise ToolError(f"{dest} must be a string, got {type(value).__name__}")
|
|
2226
|
+
|
|
2227
|
+
|
|
2228
|
+
def _many(dest: str, value: Any) -> list[str]:
|
|
2229
|
+
if isinstance(value, str) or not isinstance(value, Sequence):
|
|
2230
|
+
raise ToolError(f"{dest} must be an array of strings")
|
|
2231
|
+
return [_one(dest, item) for item in value]
|
|
2232
|
+
|
|
2233
|
+
|
|
2234
|
+
def call(tool: Tool, arguments: Mapping[str, Any], directory: str = ".") -> Answer:
|
|
2235
|
+
"""Dispatch through the real parser and handler, with stdout and stderr captured.
|
|
2236
|
+
|
|
2237
|
+
In-process rather than a subprocess: the tool is already running in one, and a second
|
|
2238
|
+
interpreter per call would make an `add` cost more over MCP than over `Bash`.
|
|
2239
|
+
"""
|
|
2240
|
+
from roadkeep.cli import dispatch
|
|
2241
|
+
|
|
2242
|
+
# Beside `dispatch`, and for the reason it is here rather than at the top (RK261): the guard
|
|
2243
|
+
# imports this module for `TOOLS` and never dispatches anything, so a module-level
|
|
2244
|
+
# `LockBusy` cost every denied edit 12 ms for an `except` only this function reaches.
|
|
2245
|
+
from roadkeep.locking import LockBusy # noqa: PLC0415 - RK261
|
|
2246
|
+
|
|
2247
|
+
# Discovered before the argv is built, because which arguments this tool takes is read
|
|
2248
|
+
# from it (RK111) — and discovered once, so the call cannot be checked against one config
|
|
2249
|
+
# and dispatched against another.
|
|
2250
|
+
# Before anything that could refuse, so the note can never be composed from an earlier call's
|
|
2251
|
+
# refusal (RK267): the slot is one call's out-parameter and this is where the call begins.
|
|
2252
|
+
provenance.witness(None)
|
|
2253
|
+
# And the argv beside it, for the same reason and under the same rule (RK1149): this surface
|
|
2254
|
+
# dispatches a parsed namespace and has no argv at all, so anything left in that slot is the
|
|
2255
|
+
# last *terminal* call this process served — and a retry spelled from it would offer a caller
|
|
2256
|
+
# here a command about somebody else's invocation. One call, one out-parameter, cleared where
|
|
2257
|
+
# the call begins.
|
|
2258
|
+
provenance.invoked(())
|
|
2259
|
+
try:
|
|
2260
|
+
config = Config.discover(directory)
|
|
2261
|
+
except ConfigError as error:
|
|
2262
|
+
# The engine is named on this one refusal unconditionally (RK155): a key the file
|
|
2263
|
+
# declares and the code does not know is the shape stale code produces, and which
|
|
2264
|
+
# build read the config is the fact that turns the puzzle into an instruction.
|
|
2265
|
+
# The one refusal with no root to name, the config that would have stated it being the
|
|
2266
|
+
# thing that failed (RK248). The launch path is what is left, and it is the safe half.
|
|
2267
|
+
provenance.witness(error)
|
|
2268
|
+
return _answered(
|
|
2269
|
+
f"roadkeep: {error}{provenance.read_by()}",
|
|
2270
|
+
Path(directory),
|
|
2271
|
+
is_error=True,
|
|
2272
|
+
served=_spelled(tool),
|
|
2273
|
+
)
|
|
2274
|
+
# Published here or not, asked before the argv is composed (RK1360). A withheld tool is
|
|
2275
|
+
# still resolved by name and still answers, because a client validating against a cached
|
|
2276
|
+
# list, an agent spelling a name out of the skill, or a session that connected before a
|
|
2277
|
+
# `declare` all reach this — and a name that simply vanished reads as a verb this tool
|
|
2278
|
+
# does not have. `isError` and never a JSON-RPC error, so the remedy reaches the model.
|
|
2279
|
+
if not tool.published(config):
|
|
2280
|
+
withheld = Withheld(tool.name, tool.needs)
|
|
2281
|
+
return _answered(
|
|
2282
|
+
f"roadkeep: refused: {withheld}",
|
|
2283
|
+
config.root,
|
|
2284
|
+
is_error=True,
|
|
2285
|
+
served=_spelled(tool),
|
|
2286
|
+
)
|
|
2287
|
+
# One build for the whole call (RK198), and then one for the whole process (RK202). The
|
|
2288
|
+
# argv is rendered through the subcommands and parsed through the root they belong to,
|
|
2289
|
+
# and until this was threaded each of those three lookups built the entire CLI — 10.2 ms
|
|
2290
|
+
# of a 12.7 ms call, on the path every write takes.
|
|
2291
|
+
root = _root()
|
|
2292
|
+
parsers = _parsers(root)
|
|
2293
|
+
try:
|
|
2294
|
+
line = argv(tool, arguments, config, parsers)
|
|
2295
|
+
except ToolError as error:
|
|
2296
|
+
# The three refusals this function raises or catches itself still have the exception, so
|
|
2297
|
+
# they witness here rather than leave the note with nothing to intersect (RK267).
|
|
2298
|
+
provenance.witness(error)
|
|
2299
|
+
return _answered(str(error), config.root, is_error=True, served=_spelled(tool, parsers))
|
|
2300
|
+
out, err = io.StringIO(), io.StringIO()
|
|
2301
|
+
try:
|
|
2302
|
+
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err), _spent_stdin():
|
|
2303
|
+
args = root.parse_args(["-C", directory, *line])
|
|
2304
|
+
# Through the CLI's own dispatch and not straight to the handler, so a write
|
|
2305
|
+
# over MCP takes the same lock a write over `Bash` does (RK117) — this is the
|
|
2306
|
+
# path an agent uses, so it is the path the duplicate id was minted on.
|
|
2307
|
+
code = dispatch(config, args)
|
|
2308
|
+
except SystemExit as exit_: # argparse refused the argv: a missing required argument
|
|
2309
|
+
code = exit_.code if isinstance(exit_.code, int) else 2
|
|
2310
|
+
except LockBusy as busy:
|
|
2311
|
+
provenance.witness(busy)
|
|
2312
|
+
return _answered(
|
|
2313
|
+
f"roadkeep: {busy}", config.root, is_error=True, served=_spelled(tool, parsers)
|
|
2314
|
+
)
|
|
2315
|
+
reported = "\n".join(part for part in (err.getvalue().strip(), out.getvalue().strip()) if part)
|
|
2316
|
+
return _answered(
|
|
2317
|
+
reported or f"{tool.name}: exit {code}",
|
|
2318
|
+
config.root,
|
|
2319
|
+
is_error=bool(code),
|
|
2320
|
+
served=_spelled(tool, parsers),
|
|
2321
|
+
# The one return that dispatched, so the only one that can have written (RK1368). The
|
|
2322
|
+
# three above it refuse before the handler runs and are already the refusal branch. The
|
|
2323
|
+
# same derived hint `tools/list` publishes as `readOnlyHint`, so a tool this surface
|
|
2324
|
+
# calls free to ask is one this note stays silent about — one answer, two readers.
|
|
2325
|
+
wrote=tool.writes_of(_subparser(tool.command, parsers)),
|
|
2326
|
+
)
|
|
2327
|
+
|
|
2328
|
+
|
|
2329
|
+
@contextlib.contextmanager
|
|
2330
|
+
def _spent_stdin() -> Iterator[None]:
|
|
2331
|
+
"""Hand the handler a stream already at EOF, for the length of one call (RK170).
|
|
2332
|
+
|
|
2333
|
+
stdout and stderr are redirected because their output *is* the answer. stdin is redirected
|
|
2334
|
+
because it is the **transport**: `_add --section` with no `--section-body` reads
|
|
2335
|
+
`sys.stdin.read()`, and the only guard against that was a comment true of the `add` that
|
|
2336
|
+
names no section at all. Over `Bash` the read sees EOF and the call refuses. Over MCP it
|
|
2337
|
+
waits for an EOF no live client sends, and swallows every message queued behind it —
|
|
2338
|
+
measured in Shio at 18 minutes, 0% CPU, still holding the lock it claimed (RK117), with the
|
|
2339
|
+
`add` unanswered and a `status` sent after it unanswered too.
|
|
2340
|
+
|
|
2341
|
+
Exhausted and not closed: `read()` on a closed stream raises `ValueError`, which
|
|
2342
|
+
:data:`~roadkeep.cli.REFUSALS` reports as bad input, and the honest answer is the refusal
|
|
2343
|
+
the format already owns for prose that is not there — `body.empty`, *a section with no prose
|
|
2344
|
+
is a heading*. So every handler that reads the pipe answers the same way instead of hanging,
|
|
2345
|
+
whether or not this surface knew it could.
|
|
2346
|
+
"""
|
|
2347
|
+
saved = sys.stdin
|
|
2348
|
+
sys.stdin = io.StringIO("")
|
|
2349
|
+
try:
|
|
2350
|
+
yield
|
|
2351
|
+
finally:
|
|
2352
|
+
sys.stdin = saved
|
|
2353
|
+
|
|
2354
|
+
|
|
2355
|
+
def _rerouted(text: str, root: Path) -> str:
|
|
2356
|
+
"""Spell any command this answer names as the tool that serves it (RK475).
|
|
2357
|
+
|
|
2358
|
+
RK444, RK447 and RK448 moved the four routes `guarding` composes. The **write path**
|
|
2359
|
+
raises its own refusals, and those were not in that count: an `add` on an outline project
|
|
2360
|
+
answers `ref.missing` and names `<invocation> anchors --block A`, handed to a caller on
|
|
2361
|
+
the surface where `anchors` has been a tool since RK463 — and to a machine that, since
|
|
2362
|
+
RK57, may have no console script at all.
|
|
2363
|
+
|
|
2364
|
+
**At the print and not at the raise**, which is the question §RK475 left open. A
|
|
2365
|
+
`SchemaError` raised in `sections` knows nothing about the transport it will be shown on,
|
|
2366
|
+
and giving it one would be the write path importing the surface; this function is the one
|
|
2367
|
+
place that holds the message and the transport at once, so the substitution is made once
|
|
2368
|
+
here rather than at the twenty-nine sites that compose an invocation.
|
|
2369
|
+
|
|
2370
|
+
Narrow on purpose: only `<invocation> <verb>` where the verb is one this surface serves,
|
|
2371
|
+
and only the two-word nested spelling where that is the tool. Everything else — a verb
|
|
2372
|
+
withheld here, a flag, a sentence that happens to contain the word — is left exactly as
|
|
2373
|
+
the CLI wrote it, because a rewrite that guessed would be this transport editing prose it
|
|
2374
|
+
did not compose (L4).
|
|
2375
|
+
"""
|
|
2376
|
+
prefix = serving(root)
|
|
2377
|
+
if prefix is None:
|
|
2378
|
+
return text
|
|
2379
|
+
text = re.sub(
|
|
2380
|
+
r'("needs": )("(?:[^"\\]|\\.)*")', lambda found: _as_field(found, prefix), text
|
|
2381
|
+
)
|
|
2382
|
+
# And every call in the path beside it (RK1205, RK1476's rule). A second key holding argv
|
|
2383
|
+
# is a second key this transport owes the rewrite: `needs` alone would answer a tool call
|
|
2384
|
+
# and the list under it shell spellings, on the surface RK57 says may have no shell.
|
|
2385
|
+
text = re.sub(
|
|
2386
|
+
r'("needs_path": )(\[[^\]]*\])', lambda found: _as_path(found, prefix), text
|
|
2387
|
+
)
|
|
2388
|
+
reached = invocation()
|
|
2389
|
+
if reached not in text:
|
|
2390
|
+
return text
|
|
2391
|
+
return re.sub(
|
|
2392
|
+
r"`" + re.escape(reached) + r" ([^`]*)`",
|
|
2393
|
+
lambda found: _as_call(found.group(1), prefix) or found.group(0),
|
|
2394
|
+
text,
|
|
2395
|
+
)
|
|
2396
|
+
|
|
2397
|
+
|
|
2398
|
+
def _as_field(found: re.Match[str], prefix: str) -> str:
|
|
2399
|
+
"""`add`'s `needs` as the call that closes it, or the argv the CLI wrote (RK476).
|
|
2400
|
+
|
|
2401
|
+
The **one** JSON value this pass touches, and named rather than matched by shape: `needs`
|
|
2402
|
+
is documented as a command, so it is the field that is known argv and not prose. A pass
|
|
2403
|
+
over every string would meet a `why` that opens with a verb, and rewriting that would be
|
|
2404
|
+
this transport editing text it did not compose — the line `_rerouted` already holds.
|
|
2405
|
+
|
|
2406
|
+
Backtick-free, because a field is read by a caller and not printed to one. Left exactly as
|
|
2407
|
+
it is wherever `_as_call` declines, which includes `null`: the regex reaches quoted values
|
|
2408
|
+
only, so a pointer that already resolves is never seen here.
|
|
2409
|
+
|
|
2410
|
+
The value is **decoded before it is read and re-encoded after** — `json.dumps` escapes the
|
|
2411
|
+
ellipsis `--title …` ends on, and matching the raw span cost this its first measurement.
|
|
2412
|
+
"""
|
|
2413
|
+
rewritten = _as_value(found.group(2), prefix)
|
|
2414
|
+
return found.group(1) + rewritten if rewritten != found.group(2) else found.group(0)
|
|
2415
|
+
|
|
2416
|
+
|
|
2417
|
+
def _as_path(found: re.Match[str], prefix: str) -> str:
|
|
2418
|
+
"""`add`'s `needs_path`, element by element (RK1205).
|
|
2419
|
+
|
|
2420
|
+
Each string rewritten **in place** rather than the list re-encoded, so the indentation
|
|
2421
|
+
`json.dumps` wrote survives: a value this pass declines to touch has to come back
|
|
2422
|
+
byte-identical, which is the promise `_as_field` keeps one key over.
|
|
2423
|
+
"""
|
|
2424
|
+
return found.group(1) + re.sub(
|
|
2425
|
+
r'"(?:[^"\\]|\\.)*"', lambda one: _as_value(one.group(0), prefix), found.group(2)
|
|
2426
|
+
)
|
|
2427
|
+
|
|
2428
|
+
|
|
2429
|
+
def _as_value(encoded: str, prefix: str) -> str:
|
|
2430
|
+
"""One JSON-encoded argv as the call that serves it, or the same bytes back.
|
|
2431
|
+
|
|
2432
|
+
The decode/re-encode both keys share: `json.dumps` escapes the ellipsis `--title …` ends
|
|
2433
|
+
on, and matching the raw span cost this its first measurement (RK476).
|
|
2434
|
+
"""
|
|
2435
|
+
call = _as_call(json.loads(encoded), prefix, plain=True)
|
|
2436
|
+
return json.dumps(call) if call else encoded
|
|
2437
|
+
|
|
2438
|
+
|
|
2439
|
+
def _as_call(argv: str, prefix: str, *, plain: bool = False) -> str:
|
|
2440
|
+
"""One backticked command as the call that serves it, or `""` to leave it alone.
|
|
2441
|
+
|
|
2442
|
+
A flag is not a word over this transport (RK449's finding, RK475's case): rewriting the
|
|
2443
|
+
head and keeping `--block A` would name the right tool and an argument nobody can pass.
|
|
2444
|
+
So the tail goes through the **subcommand's own parser** — the same reader `_property`
|
|
2445
|
+
uses to publish the schema — and comes back as the fields a call carries.
|
|
2446
|
+
|
|
2447
|
+
Empty on anything this surface cannot answer for: a verb it withholds, an argv the parser
|
|
2448
|
+
refuses, a field outside the tool's `unconditional`. There the shell spelling stays, which is
|
|
2449
|
+
what the CLI wrote and what is at least right where a shell exists.
|
|
2450
|
+
|
|
2451
|
+
Composed by :meth:`~roadkeep.remedying.Door.mention` and no longer here (RK488). This was
|
|
2452
|
+
the third module holding its own copy of *a command in the spelling this session has*, and
|
|
2453
|
+
the copy was honest about it — the docstring under :func:`_fields_of` said the two were
|
|
2454
|
+
kept apart on purpose. What that bought is a transport whose rewriting rule can drift from
|
|
2455
|
+
the report's own composition, silently, because both keep printing.
|
|
2456
|
+
"""
|
|
2457
|
+
from roadkeep.remedying import Door # noqa: PLC0415 - RK260, the rewriting path only
|
|
2458
|
+
|
|
2459
|
+
door = Door(tuple(argv.split()), "")
|
|
2460
|
+
if door.call() is None:
|
|
2461
|
+
return ""
|
|
2462
|
+
# No backtick where this lands in a *field* rather than in a sentence printed to somebody
|
|
2463
|
+
# (RK476) — which is the only thing this transport still decides about the spelling.
|
|
2464
|
+
return door.mention(prefix, quote="" if plain else "`")
|
|
2465
|
+
|
|
2466
|
+
|
|
2467
|
+
def _fields_of(
|
|
2468
|
+
parser: argparse.ArgumentParser, rest: Sequence[str], exposes: Sequence[str]
|
|
2469
|
+
) -> dict[str, object] | None:
|
|
2470
|
+
"""The tail of a command as the fields a call carries, or ``None`` where it has none.
|
|
2471
|
+
|
|
2472
|
+
The one reader of a command's **values**, for both halves of the problem (RK488): this
|
|
2473
|
+
read prose the CLI printed and `remedying._fields` read a table's argv, kept apart on the
|
|
2474
|
+
argument that a shared helper would tie the report's composition to this transport — and
|
|
2475
|
+
what it tied instead was two rules about `exposes` that had to stay equal by hand.
|
|
2476
|
+
:meth:`~roadkeep.remedying.Door.call` asks :func:`serves` *which* tool and asks this one
|
|
2477
|
+
what the tail says; nothing else parses a door.
|
|
2478
|
+
|
|
2479
|
+
``None`` on three states, and each is a command that genuinely has no call: an argv the
|
|
2480
|
+
parser refuses, a word it does not recognise arriving as a leftover, and a field outside
|
|
2481
|
+
``exposes`` — `lint --fix`, since RK16 keeps the writing half where a human is standing.
|
|
2482
|
+
"""
|
|
2483
|
+
with contextlib.redirect_stderr(io.StringIO()):
|
|
2484
|
+
try:
|
|
2485
|
+
parsed, unknown = parser.parse_known_args(list(rest))
|
|
2486
|
+
except SystemExit:
|
|
2487
|
+
return None
|
|
2488
|
+
if unknown:
|
|
2489
|
+
return None
|
|
2490
|
+
fields: dict[str, object] = {}
|
|
2491
|
+
for dest, value in vars(parsed).items():
|
|
2492
|
+
if value == parser.get_default(dest) or value is None or value is False:
|
|
2493
|
+
continue
|
|
2494
|
+
if dest not in exposes:
|
|
2495
|
+
return None
|
|
2496
|
+
fields[dest] = value
|
|
2497
|
+
return fields
|
|
2498
|
+
|
|
2499
|
+
|
|
2500
|
+
def _answered(
|
|
2501
|
+
text: str, root: Path, *, is_error: bool, served: str = "", wrote: bool = False
|
|
2502
|
+
) -> Answer:
|
|
2503
|
+
"""One tool's answer, plus the note a **refusal** needs when the code answering moved.
|
|
2504
|
+
|
|
2505
|
+
RK155, measured twice in one session: the config is re-read per message on purpose, so a
|
|
2506
|
+
`roadkeep.toml` edited mid-session is the one the next `tools/list` describes — but the code
|
|
2507
|
+
reading it was imported once at session start. `[claims] held` added to the file and to
|
|
2508
|
+
`config.py` in one commit made every MCP write refuse `unknown key 'claims'` while the CLI
|
|
2509
|
+
in a terminal accepted it, and the fallback was to stop using the write path this project
|
|
2510
|
+
ships. The refusal was correct about the code and wrong about the project.
|
|
2511
|
+
|
|
2512
|
+
Only when something actually moved, a note on every answer being a note that stops being
|
|
2513
|
+
read. Nothing reloads — see :attr:`~roadkeep.provenance.Engine.stale` for why that is the
|
|
2514
|
+
harness's job and not this server's.
|
|
2515
|
+
|
|
2516
|
+
On a refusal, and — since RK1368 — on a **successful write**, which is ``wrote``. The rule
|
|
2517
|
+
here was *a successful call has nothing to explain*, and that holds for a read: a stale
|
|
2518
|
+
figure costs the caller a second question. A write is the other direction and the worse
|
|
2519
|
+
one, so the note is absent exactly where it is dear. :func:`_landed` is that sentence and
|
|
2520
|
+
carries the argument; a successful read is still silent.
|
|
2521
|
+
|
|
2522
|
+
What it may not do is argue with the refusal it rides on (RK242). The sentence here said the
|
|
2523
|
+
refusal "may be a build behind rather than a fact about this project", attached to every
|
|
2524
|
+
refusal alike — and mtimes cannot know whether the files that moved reach the verb that
|
|
2525
|
+
refused, so a correct `ref.missing` arrived pre-doubted. Measured, that costs calls: the
|
|
2526
|
+
caller re-ran the command, tried a second spelling of the flag, then imported the CLI from a
|
|
2527
|
+
source checkout to obtain the answer it already had. So the drift is stated as what it is, a
|
|
2528
|
+
fact about this process, beside a refusal that stands as the answer the running code gave.
|
|
2529
|
+
|
|
2530
|
+
And the remedy is the one that applies to the server reading it (RK246): a patch bump reloads
|
|
2531
|
+
a *plugin*, so on a project running the tool from its own checkout the note's first clause
|
|
2532
|
+
named a mechanism never in play — measured here at five bumps in one session, with the note
|
|
2533
|
+
still naming seven changed files. Which wiring answered is
|
|
2534
|
+
:meth:`~roadkeep.provenance.Engine.carried_by`, so it is read and not guessed. What stays
|
|
2535
|
+
untouched is the decision above it: nothing reloads itself (RK155).
|
|
2536
|
+
|
|
2537
|
+
``root`` is the **project** root and not the path the server was launched from (RK248):
|
|
2538
|
+
`Config.discover` walks up for a `roadkeep.toml`, so a server started in any subdirectory of
|
|
2539
|
+
a governed checkout has a root above its `-C` — and there `<root>/src/roadkeep` is not under
|
|
2540
|
+
the launch path, `carried_by` answers False, and the note names the bump on exactly the tree
|
|
2541
|
+
RK246 measured the bump never reaching. Every caller past discovery passes `config.root`; the
|
|
2542
|
+
`ConfigError` above it has no config to read one from and passes the launch path, which is
|
|
2543
|
+
the safe direction because that branch ends in restarting the session either way.
|
|
2544
|
+
|
|
2545
|
+
**And it may not hand the relevance question back** (RK267). The note used to list every
|
|
2546
|
+
module :attr:`~roadkeep.provenance.Engine.stale` found and close with "re-run only where the
|
|
2547
|
+
changed files are the ones that would decide this", which is the reader being asked to know
|
|
2548
|
+
the call graph of a refusal they did not raise. Measured while shipping RK255: a
|
|
2549
|
+
`why.too-long` decided by `schema.py`, unchanged, arrived naming `cli.py`, `merging.py` and
|
|
2550
|
+
`provenance.py` — 450 characters of correct and irrelevant text on a refusal that had already
|
|
2551
|
+
said everything actionable in one line, fired on every error in every session that edits this
|
|
2552
|
+
package.
|
|
2553
|
+
|
|
2554
|
+
Which modules decided it is knowable, so it is answered rather than delegated:
|
|
2555
|
+
:func:`~roadkeep.provenance.raised_in` reads them off the traceback and
|
|
2556
|
+
:func:`~roadkeep.provenance.witness` carries them across the exit code, and the note turns on
|
|
2557
|
+
the **intersection**. Disjoint sets say nothing at all — that is the RK255 case, and a note
|
|
2558
|
+
that fires there is the one nobody reads by the third time. An overlap names the module both
|
|
2559
|
+
sets hold and keeps the rest behind it, because a helper whose frame has already returned is
|
|
2560
|
+
the miss §RK267 accepts, and dropping the others would hide it.
|
|
2561
|
+
|
|
2562
|
+
A refusal this process never witnessed is neither case: nothing decided it *here* — argparse
|
|
2563
|
+
refusing an argv, a handler exiting non-zero without raising — and the honest answer is then
|
|
2564
|
+
the inventory RK155 shipped, because suppressing on no evidence is the opposite mistake.
|
|
2565
|
+
|
|
2566
|
+
**And whatever it says, it closes with something the reader can do** (RK313). Every remedy
|
|
2567
|
+
this note had named was a patch bump or a session restart, and the agent it is written for can
|
|
2568
|
+
perform neither — measured as one session abandoning the protocol surface and driving the CLI
|
|
2569
|
+
for all thirteen of its filings, which worked and left the served path untested for a session
|
|
2570
|
+
of real use. ``served`` is what makes the alternative nameable: the command this call would
|
|
2571
|
+
have run, so :func:`_now` says it.
|
|
2572
|
+
"""
|
|
2573
|
+
text = _rerouted(text, root)
|
|
2574
|
+
changed = engine().stale
|
|
2575
|
+
if not is_error:
|
|
2576
|
+
if not (wrote and changed):
|
|
2577
|
+
return Answer(text, is_error=False)
|
|
2578
|
+
return Answer(f"{text}\n\n{_landed(changed, root)}", is_error=False)
|
|
2579
|
+
if not changed:
|
|
2580
|
+
return Answer(text, is_error=True)
|
|
2581
|
+
decided = provenance.witnessed()
|
|
2582
|
+
if decided is None:
|
|
2583
|
+
# Relevance is genuinely unknown, so the full list is what there is to say.
|
|
2584
|
+
return Answer(f"{text}\n\n{_inventory(changed, root, served)}", is_error=True)
|
|
2585
|
+
both = tuple(one for one in changed if one in decided)
|
|
2586
|
+
if not both:
|
|
2587
|
+
return Answer(text, is_error=True)
|
|
2588
|
+
rest = tuple(one for one in changed if one not in decided)
|
|
2589
|
+
behind = f" ({', '.join(rest)} also changed and did not.)" if rest else ""
|
|
2590
|
+
return Answer(
|
|
2591
|
+
f"{text}\n\n"
|
|
2592
|
+
f"Separately, about this process and not about the refusal above: "
|
|
2593
|
+
f"{', '.join(both)} decided this refusal and changed on disk after this server imported "
|
|
2594
|
+
f"roadkeep, so the answer above is what the code it did import said — read it first, "
|
|
2595
|
+
f"then re-run.{behind} {_remedy(root)}{_now(served)}",
|
|
2596
|
+
is_error=True,
|
|
2597
|
+
)
|
|
2598
|
+
|
|
2599
|
+
|
|
2600
|
+
def _landed(changed: Sequence[str], root: Path) -> str:
|
|
2601
|
+
"""The note a successful **write** needs, which the refusal's argument never reached (RK1368).
|
|
2602
|
+
|
|
2603
|
+
Measured here: a `govern tools.session` over MCP answered with a surface reading two verbs
|
|
2604
|
+
out of date, and the guard that refuses a limit the corpus already breaks was applied to a
|
|
2605
|
+
corpus that had moved — so re-declaring the old ceiling would have passed the verb and been
|
|
2606
|
+
refused by `lint` on the next call. A refusal read against stale code costs a re-run; a
|
|
2607
|
+
number accepted against stale code is committed.
|
|
2608
|
+
|
|
2609
|
+
**The count and not the list** (RK267). Relevance is computed off a traceback and a
|
|
2610
|
+
successful call has none, so naming the modules would be exactly the correct-and-irrelevant
|
|
2611
|
+
text that task removed, and asking which of them decided the write is handing the question
|
|
2612
|
+
back. What is left is the fact, the remedy, and one command.
|
|
2613
|
+
|
|
2614
|
+
**And that command is `lint`, not this call re-run** (RK313). The write has happened, so
|
|
2615
|
+
re-running it is a second entry or a refusal about the first; what the reader needs is the
|
|
2616
|
+
gate reading the tree with the code on disk, which is what caught the measured case.
|
|
2617
|
+
"""
|
|
2618
|
+
from roadkeep.remedying import Door # noqa: PLC0415 - RK260, this note's path only
|
|
2619
|
+
|
|
2620
|
+
return (
|
|
2621
|
+
f"Separately, about this process and not about the write above: {len(changed)} "
|
|
2622
|
+
f"module(s) of this package changed on disk after this server imported roadkeep, so "
|
|
2623
|
+
f"what was just written was validated by the code it did import and not by the code "
|
|
2624
|
+
f"in the tree. {_remedy(root)} Available now, in this session: "
|
|
2625
|
+
f"`{Door(('lint',), '').command}` judges what landed, the CLI importing the changed "
|
|
2626
|
+
f"files per process."
|
|
2627
|
+
)
|
|
2628
|
+
|
|
2629
|
+
|
|
2630
|
+
def _inventory(changed: Sequence[str], root: Path, served: str = "") -> str:
|
|
2631
|
+
"""The note on a refusal nothing witnessed, which is RK155's and claims no relevance (RK267).
|
|
2632
|
+
|
|
2633
|
+
It cannot ask the reader to establish one either, so it does not close with the sentence that
|
|
2634
|
+
did: what is left is the fact, the remedy, and the one thing available now (RK313).
|
|
2635
|
+
"""
|
|
2636
|
+
return (
|
|
2637
|
+
f"Separately, about this process and not about the refusal above: this server "
|
|
2638
|
+
f"imported roadkeep before {', '.join(changed)} changed on disk, and the refusal is "
|
|
2639
|
+
f"what the code it did import answered — read it first. {_remedy(root)}{_now(served)}"
|
|
2640
|
+
)
|
|
2641
|
+
|
|
2642
|
+
|
|
2643
|
+
def _now(served: str) -> str:
|
|
2644
|
+
"""The remedy available **inside** the session that reads this, or nothing (RK313).
|
|
2645
|
+
|
|
2646
|
+
Every other sentence in this note is about a process the reader cannot address: a patch bump
|
|
2647
|
+
is the harness's and a restart is the user's, both correct about the cause and empty as an
|
|
2648
|
+
instruction. The one action that exists is the one the measured session found by itself — the
|
|
2649
|
+
same verb through the CLI, which loads the changed files on the spot.
|
|
2650
|
+
|
|
2651
|
+
Not circular, which is RK272's bar for advice: this note fires only where the drift is a fact
|
|
2652
|
+
about *this process*, so a run that imports fresh is the one place a different answer can come
|
|
2653
|
+
from. And spelled through :func:`~roadkeep.provenance.invocation`, because a command named
|
|
2654
|
+
literally is one that answers `command not found` on a plugin-installed machine (RK254).
|
|
2655
|
+
|
|
2656
|
+
The verb and never the arguments. The reader has those — they just sent them — and a rendered
|
|
2657
|
+
argv would have to quote a `--why` sentence to be correct, which is a second grammar for
|
|
2658
|
+
stating a call this surface already accepts as JSON.
|
|
2659
|
+
"""
|
|
2660
|
+
from roadkeep.remedying import Door # noqa: PLC0415 - RK260, this note's path only
|
|
2661
|
+
|
|
2662
|
+
if not served:
|
|
2663
|
+
# Nothing to name, so nothing is claimed. Every branch in :func:`call` passes the command
|
|
2664
|
+
# — the tool was resolved before dispatch — and this is the guard that keeps a caller
|
|
2665
|
+
# composing a note by hand from getting a sentence about a verb it never named.
|
|
2666
|
+
return ""
|
|
2667
|
+
return (
|
|
2668
|
+
f" Available now, in this session: `{Door(tuple(served.split()), '').command}` runs "
|
|
2669
|
+
f"the changed files, the CLI importing them per process."
|
|
2670
|
+
)
|
|
2671
|
+
|
|
2672
|
+
|
|
2673
|
+
def _remedy(root: Path) -> str:
|
|
2674
|
+
"""What actually restarts *this* server, which of the two wirings decides (RK246).
|
|
2675
|
+
|
|
2676
|
+
Resolved here and not asked of the caller: a `Config.root` already is, and the launch path the
|
|
2677
|
+
`ConfigError` branch passes is the one that is not (RK248).
|
|
2678
|
+
|
|
2679
|
+
What it says is bounded by what :meth:`~roadkeep.provenance.Engine.carried_by` establishes,
|
|
2680
|
+
which is a directory relation and not a launcher (RK250). It used to name `.mcp.json` and
|
|
2681
|
+
`scripts/roadkeep.py` — true of this repository and of nothing else that satisfies the same
|
|
2682
|
+
relation: a `pip install -e .` into a `.venv` inside the governed tree, or a marketplace
|
|
2683
|
+
pointing at a local path, would read two files they have not got. That is the very defect
|
|
2684
|
+
RK242 and RK246 each removed one instance of, so the sentence states the fact the relation
|
|
2685
|
+
gives and the remedy that follows from it, and names no mechanism it did not observe.
|
|
2686
|
+
"""
|
|
2687
|
+
try:
|
|
2688
|
+
root = root.resolve()
|
|
2689
|
+
except OSError: # a path that cannot be resolved is not evidence about either wiring
|
|
2690
|
+
return "Restart the session to run the changed files."
|
|
2691
|
+
if engine().carried_by(root):
|
|
2692
|
+
return (
|
|
2693
|
+
"The code answering lives inside the tree it is governing, so nothing the harness "
|
|
2694
|
+
"versions addresses this process and restarting the session is the only remedy."
|
|
2695
|
+
)
|
|
2696
|
+
return (
|
|
2697
|
+
"Every commit bumps the patch version so the harness reloads the plugin (RK153); "
|
|
2698
|
+
"restart the session if it has not."
|
|
2699
|
+
)
|
|
2700
|
+
|
|
2701
|
+
|
|
2702
|
+
def tool_named(name: str) -> Tool:
|
|
2703
|
+
for tool in TOOLS:
|
|
2704
|
+
if tool.name == name:
|
|
2705
|
+
return tool
|
|
2706
|
+
raise ToolError(
|
|
2707
|
+
f"no such tool {name!r} — this server offers "
|
|
2708
|
+
f"{', '.join(tool.name for tool in TOOLS)}"
|
|
2709
|
+
)
|
|
2710
|
+
|
|
2711
|
+
|
|
2712
|
+
# -- the protocol -----------------------------------------------------------
|
|
2713
|
+
|
|
2714
|
+
|
|
2715
|
+
@dataclass
|
|
2716
|
+
class Watch:
|
|
2717
|
+
"""What this connection was told the tool list is — the one thing held between messages.
|
|
2718
|
+
|
|
2719
|
+
The schema *varies by config* (RK111): `[ids] suffix` decides whether `add` accepts a
|
|
2720
|
+
`task_id` at all, and `[limits]`, `[markers]` and the id shape decide the bounds on
|
|
2721
|
+
every field. The server already re-reads `roadkeep.toml` per message, so a `tools/list`
|
|
2722
|
+
always describes the file as it is now — but a client asks once, at the handshake, and
|
|
2723
|
+
then validates every call against what it cached. Edit the config mid-session and the
|
|
2724
|
+
call it refuses is one this server would have accepted, with a message the *client*
|
|
2725
|
+
composed from a schema nobody told it was out of date.
|
|
2726
|
+
|
|
2727
|
+
The protocol's answer is `notifications/tools/list_changed`, and sending it costs the
|
|
2728
|
+
claim that this holds no state between messages. That claim is kept where it means
|
|
2729
|
+
something: nothing here is a fact about the project, about a task or about a file's
|
|
2730
|
+
contents — it is a memory of *what this connection was sent*, which is the one thing a
|
|
2731
|
+
stateless server cannot derive and the one thing the notification is about. The
|
|
2732
|
+
alternative considered was to leave it and say "restart the session" in the refusal,
|
|
2733
|
+
which is a workaround for a message this server is able to send.
|
|
2734
|
+
|
|
2735
|
+
Two costs kept small on purpose. Nothing is computed until the client has actually asked
|
|
2736
|
+
for a list, so a session that never lists pays nothing; and after that the per-message
|
|
2737
|
+
cost is one `stat` of the config file, with the descriptors rebuilt only when its bytes
|
|
2738
|
+
moved — the build is what RK174 and RK198 are about, and doing it per message to detect
|
|
2739
|
+
a change nobody made would cost more than the staleness it fixes.
|
|
2740
|
+
"""
|
|
2741
|
+
|
|
2742
|
+
#: The digest of the descriptors last handed to this client, or ``None`` before it asked.
|
|
2743
|
+
described: str | None = None
|
|
2744
|
+
#: The config file as it was when that answer was composed: path, mtime and size. Not the
|
|
2745
|
+
#: digest of its bytes — this is read on every message and the point is that it is a stat.
|
|
2746
|
+
stamp: tuple[str, int, int] | None = None
|
|
2747
|
+
#: Whether a list has ever been sent. Distinct from :attr:`stamp`, which is ``None`` both
|
|
2748
|
+
#: before the first list and on a project that declares no config at all.
|
|
2749
|
+
told: bool = field(default=False)
|
|
2750
|
+
|
|
2751
|
+
def describing(self, config: Config, described: list[dict[str, Any]]) -> None:
|
|
2752
|
+
"""Remember the answer being sent, so a later message can tell that it aged."""
|
|
2753
|
+
self.described = _digest(described)
|
|
2754
|
+
self.stamp = _stamp(config)
|
|
2755
|
+
self.told = True
|
|
2756
|
+
|
|
2757
|
+
def moved(self, directory: str) -> dict[str, Any] | None:
|
|
2758
|
+
"""The notification this connection is owed, or ``None`` — and never twice for one edit.
|
|
2759
|
+
|
|
2760
|
+
The new digest is kept rather than cleared: a client that ignores the notification
|
|
2761
|
+
is not told again about the same edit, and a *second* edit still reaches it.
|
|
2762
|
+
"""
|
|
2763
|
+
if not self.told:
|
|
2764
|
+
return None
|
|
2765
|
+
try:
|
|
2766
|
+
config = _config(directory)
|
|
2767
|
+
except OSError:
|
|
2768
|
+
return None
|
|
2769
|
+
stamp = _stamp(config)
|
|
2770
|
+
if stamp == self.stamp:
|
|
2771
|
+
return None
|
|
2772
|
+
self.stamp = stamp
|
|
2773
|
+
digest = _digest(descriptors(config))
|
|
2774
|
+
if digest == self.described:
|
|
2775
|
+
# The file moved and the schema did not — a comment edited, a `[report]` line
|
|
2776
|
+
# added. Nothing to tell the client, and the new stamp above means nothing to
|
|
2777
|
+
# rebuild until it moves again.
|
|
2778
|
+
return None
|
|
2779
|
+
self.described = digest
|
|
2780
|
+
return {"jsonrpc": "2.0", "method": "notifications/tools/list_changed"}
|
|
2781
|
+
|
|
2782
|
+
|
|
2783
|
+
def handle(message: Any, directory: str = ".", watch: Watch | None = None) -> dict[str, Any] | None:
|
|
2784
|
+
"""One JSON-RPC message in, one response out — or `None`, which is a notification.
|
|
2785
|
+
|
|
2786
|
+
A notification answered is a protocol violation, and `notifications/initialized` is the
|
|
2787
|
+
first thing every client sends, so the `None` here is load-bearing rather than tidy.
|
|
2788
|
+
|
|
2789
|
+
``watch`` is the connection's memory of what it was last told (RK177), optional because
|
|
2790
|
+
a caller answering one message in isolation has no connection to keep one for.
|
|
2791
|
+
"""
|
|
2792
|
+
if not isinstance(message, Mapping) or message.get("jsonrpc") != "2.0":
|
|
2793
|
+
return _error(None, INVALID_REQUEST, "expected a JSON-RPC 2.0 object")
|
|
2794
|
+
identifier = message.get("id")
|
|
2795
|
+
method = message.get("method")
|
|
2796
|
+
params = message.get("params") if isinstance(message.get("params"), Mapping) else {}
|
|
2797
|
+
if identifier is None:
|
|
2798
|
+
return None # every notification, including the ones a later spec adds
|
|
2799
|
+
if method == "initialize":
|
|
2800
|
+
return _result(identifier, _handshake(params))
|
|
2801
|
+
if method == "ping":
|
|
2802
|
+
return _result(identifier, {})
|
|
2803
|
+
if method == "tools/list":
|
|
2804
|
+
config = _config(directory)
|
|
2805
|
+
described = descriptors(config)
|
|
2806
|
+
if watch is not None:
|
|
2807
|
+
watch.describing(config, described)
|
|
2808
|
+
return _result(identifier, {"tools": described})
|
|
2809
|
+
if method == "tools/call":
|
|
2810
|
+
return _result(identifier, _called(params, directory))
|
|
2811
|
+
return _error(identifier, METHOD_NOT_FOUND, f"unsupported method {method!r}")
|
|
2812
|
+
|
|
2813
|
+
|
|
2814
|
+
def _digest(described: list[dict[str, Any]]) -> str:
|
|
2815
|
+
"""The tool list as one comparable string, ordered so equal lists compare equal."""
|
|
2816
|
+
return hashlib.sha256(
|
|
2817
|
+
json.dumps(described, sort_keys=True, ensure_ascii=False).encode("utf-8")
|
|
2818
|
+
).hexdigest()
|
|
2819
|
+
|
|
2820
|
+
|
|
2821
|
+
def _stamp(config: Config) -> tuple[str, int, int] | None:
|
|
2822
|
+
"""The config file as a stat, or ``None`` where this project declares none."""
|
|
2823
|
+
source = config.source
|
|
2824
|
+
if source is None:
|
|
2825
|
+
return None
|
|
2826
|
+
try:
|
|
2827
|
+
info = Path(source).stat()
|
|
2828
|
+
except OSError:
|
|
2829
|
+
return None
|
|
2830
|
+
return (str(source), info.st_mtime_ns, info.st_size)
|
|
2831
|
+
|
|
2832
|
+
|
|
2833
|
+
def _handshake(params: Mapping[str, Any]) -> dict[str, Any]:
|
|
2834
|
+
asked = params.get("protocolVersion")
|
|
2835
|
+
return {
|
|
2836
|
+
"protocolVersion": asked if asked in KNOWN_PROTOCOLS else PROTOCOL,
|
|
2837
|
+
# `listChanged` is what makes the notification above mean anything: a client that was
|
|
2838
|
+
# never told the list can change is entitled to ignore one that says it did (RK177).
|
|
2839
|
+
"capabilities": {"tools": {"listChanged": True}},
|
|
2840
|
+
"serverInfo": {"name": "roadkeep", "version": __version__},
|
|
2841
|
+
# The startup line RK79 asks for, and what every published bound is counted in
|
|
2842
|
+
# (RK1060). `serverInfo.version` stays the release number a client may have pinned
|
|
2843
|
+
# against, so which tree answered goes here — the one field of the handshake that
|
|
2844
|
+
# reaches a session, and the only moment this server has one.
|
|
2845
|
+
"instructions": instructions(),
|
|
2846
|
+
}
|
|
2847
|
+
|
|
2848
|
+
|
|
2849
|
+
def _called(params: Mapping[str, Any], directory: str) -> dict[str, Any]:
|
|
2850
|
+
arguments = params.get("arguments") if isinstance(params.get("arguments"), Mapping) else {}
|
|
2851
|
+
try:
|
|
2852
|
+
tool = tool_named(str(params.get("name")))
|
|
2853
|
+
except ToolError as error:
|
|
2854
|
+
# `isError` and not a JSON-RPC error, so the allowed set reaches the model that
|
|
2855
|
+
# guessed the name rather than the client that forwarded it.
|
|
2856
|
+
return Answer(str(error), is_error=True).content()
|
|
2857
|
+
return call(tool, arguments, directory).content()
|
|
2858
|
+
|
|
2859
|
+
|
|
2860
|
+
def _config(directory: str) -> Config:
|
|
2861
|
+
try:
|
|
2862
|
+
return Config.discover(directory)
|
|
2863
|
+
except ConfigError:
|
|
2864
|
+
# The limits are then the defaults, which is a schema that is wrong about this
|
|
2865
|
+
# project rather than no schema at all — and `lint` is the tool that says why.
|
|
2866
|
+
return Config.default(directory)
|
|
2867
|
+
|
|
2868
|
+
|
|
2869
|
+
def _result(identifier: Any, result: Mapping[str, Any]) -> dict[str, Any]:
|
|
2870
|
+
return {"jsonrpc": "2.0", "id": identifier, "result": dict(result)}
|
|
2871
|
+
|
|
2872
|
+
|
|
2873
|
+
def _error(identifier: Any, code: int, message: str) -> dict[str, Any]:
|
|
2874
|
+
return {"jsonrpc": "2.0", "id": identifier, "error": {"code": code, "message": message}}
|
|
2875
|
+
|
|
2876
|
+
|
|
2877
|
+
def serve(reader: TextIO, writer: TextIO, directory: str = ".") -> int:
|
|
2878
|
+
"""Read line-delimited JSON-RPC until the client closes stdin.
|
|
2879
|
+
|
|
2880
|
+
The loop never raises: a malformed line is a parse error the client can read, and a
|
|
2881
|
+
server that dies on one takes every tool in the session with it.
|
|
2882
|
+
|
|
2883
|
+
The :class:`Watch` is the connection, and lives exactly as long as it (RK177): a second
|
|
2884
|
+
message may find `roadkeep.toml` describing different tools than the first one answered
|
|
2885
|
+
with, and the client is told so rather than left validating against what it cached.
|
|
2886
|
+
"""
|
|
2887
|
+
watch = Watch()
|
|
2888
|
+
for line in reader:
|
|
2889
|
+
if not line.strip():
|
|
2890
|
+
continue
|
|
2891
|
+
try:
|
|
2892
|
+
message = json.loads(line)
|
|
2893
|
+
except ValueError:
|
|
2894
|
+
response: dict[str, Any] | None = _error(None, PARSE_ERROR, "invalid JSON")
|
|
2895
|
+
else:
|
|
2896
|
+
response = handle(message, directory, watch)
|
|
2897
|
+
if response is not None:
|
|
2898
|
+
_send(writer, response)
|
|
2899
|
+
# After the answer, never instead of it: the response is what the client is waiting
|
|
2900
|
+
# on, and a notification that arrived first would sit in front of it in the pipe.
|
|
2901
|
+
notice = watch.moved(directory)
|
|
2902
|
+
if notice is not None:
|
|
2903
|
+
_send(writer, notice)
|
|
2904
|
+
return 0
|
|
2905
|
+
|
|
2906
|
+
|
|
2907
|
+
def _send(writer: TextIO, message: Mapping[str, Any]) -> None:
|
|
2908
|
+
writer.write(json.dumps(message) + "\n")
|
|
2909
|
+
writer.flush()
|