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.
Files changed (67) hide show
  1. roadkeep/__init__.py +79 -0
  2. roadkeep/adopting.py +2347 -0
  3. roadkeep/attesting.py +293 -0
  4. roadkeep/authoring.py +2117 -0
  5. roadkeep/backlog.py +767 -0
  6. roadkeep/blocking.py +1622 -0
  7. roadkeep/briefing.py +970 -0
  8. roadkeep/budgeting.py +2056 -0
  9. roadkeep/capturing.py +1699 -0
  10. roadkeep/claiming.py +1019 -0
  11. roadkeep/cli.py +638 -0
  12. roadkeep/commanding.py +487 -0
  13. roadkeep/config.py +1832 -0
  14. roadkeep/counting.py +376 -0
  15. roadkeep/criteria.py +933 -0
  16. roadkeep/deferring.py +708 -0
  17. roadkeep/describing.py +568 -0
  18. roadkeep/exporting.py +808 -0
  19. roadkeep/fixing.py +629 -0
  20. roadkeep/governing.py +934 -0
  21. roadkeep/graph.py +395 -0
  22. roadkeep/guarding.py +1028 -0
  23. roadkeep/history.py +2403 -0
  24. roadkeep/ids.py +301 -0
  25. roadkeep/installing.py +2145 -0
  26. roadkeep/kernel/__init__.py +24 -0
  27. roadkeep/kernel/document.py +1719 -0
  28. roadkeep/kernel/schema.py +2308 -0
  29. roadkeep/linting.py +4420 -0
  30. roadkeep/locking.py +209 -0
  31. roadkeep/markers.py +172 -0
  32. roadkeep/merging.py +1159 -0
  33. roadkeep/picking.py +772 -0
  34. roadkeep/provenance.py +789 -0
  35. roadkeep/queueing.py +752 -0
  36. roadkeep/ranking.py +139 -0
  37. roadkeep/referring.py +231 -0
  38. roadkeep/remaining.py +336 -0
  39. roadkeep/remedying.py +1989 -0
  40. roadkeep/rendering.py +1601 -0
  41. roadkeep/renumbering.py +503 -0
  42. roadkeep/repairing.py +295 -0
  43. roadkeep/reverting.py +144 -0
  44. roadkeep/scoping.py +708 -0
  45. roadkeep/screening.py +196 -0
  46. roadkeep/sections.py +4121 -0
  47. roadkeep/serving.py +2909 -0
  48. roadkeep/shipping.py +3993 -0
  49. roadkeep/showing.py +613 -0
  50. roadkeep/storing.py +224 -0
  51. roadkeep/verbs/__init__.py +26 -0
  52. roadkeep/verbs/adopting.py +974 -0
  53. roadkeep/verbs/authoring.py +566 -0
  54. roadkeep/verbs/declaring.py +335 -0
  55. roadkeep/verbs/linting.py +645 -0
  56. roadkeep/verbs/querying.py +2138 -0
  57. roadkeep/verbs/reading.py +307 -0
  58. roadkeep/verbs/refusing.py +146 -0
  59. roadkeep/verbs/sections.py +1433 -0
  60. roadkeep/verbs/shipping.py +819 -0
  61. roadkeep/weighing.py +380 -0
  62. roadkeep-0.2.0.dist-info/METADATA +453 -0
  63. roadkeep-0.2.0.dist-info/RECORD +67 -0
  64. roadkeep-0.2.0.dist-info/WHEEL +5 -0
  65. roadkeep-0.2.0.dist-info/entry_points.txt +2 -0
  66. roadkeep-0.2.0.dist-info/licenses/LICENSE +202 -0
  67. roadkeep-0.2.0.dist-info/top_level.txt +1 -0
roadkeep/merging.py ADDED
@@ -0,0 +1,1159 @@
1
+ """The merge git cannot make, in a file only this tool may write (RK120).
2
+
3
+ `renumber` (RK97) is the repair for two branches that spent one id. This is the door that
4
+ stops the collision from arriving as a hand edit. Two worktrees each scan their own tree,
5
+ each derive the same next id, and each append under the same block heading — so git sees
6
+ two insertions at one line and writes conflict markers into a file whose only legal writer
7
+ is this tool. Resolving them means editing the format by hand, which the guard (RK22)
8
+ denies and the gate (RK14) refuses. Worse is the case that does **not** conflict: two
9
+ branches touching different blocks merge clean, and the duplicate id lands in silence.
10
+
11
+ A textual merge guesses because it reads lines. This file is a schema, which makes the
12
+ merge **decidable**: a task line is keyed by its id and filed under a declared heading, so
13
+ "what changed" is a question about ids and never about line numbers.
14
+
15
+ * **Every id is decided on its own.** Against the ancestor: unchanged on one side takes the
16
+ other side's line, identical on both sides takes either, absent from both is a deletion
17
+ both sides made. Nothing here is a position in a file, so two branches appending under
18
+ one heading is not a conflict at all — it is two additions.
19
+ * **Only what both sides spent is singled out.** An id **both branches created**, carrying
20
+ different work, is the collision — reported by id, because `renumber` is what moves one
21
+ of them and a driver that picked a side would be choosing whose task disappears. An id
22
+ both sides *edited* differently is the ordinary content conflict, reported the same way
23
+ and kept apart in the answer: one wants an address, the other wants a sentence.
24
+ * **The frame is one side's.** Headings, the preamble and the non-goals are prose, and the
25
+ tool does not merge prose (L4). One side may have changed them — that side's file is the
26
+ frame the entries are written into. Both, differently, and the merge is refused.
27
+ * **It gates what it composed.** The merged file is held to
28
+ :func:`~roadkeep.linting.within` and to :func:`~roadkeep.linting.resolving` — what one
29
+ file answers, and what only the backlog can (RK1353) — and the findings it refuses over
30
+ are the ones **no version already had** (RK1352). The second half is not an extra: a dep
31
+ on a line the other side removed exists in no version and in the merged file alone, which
32
+ is the one class a merge is uniquely able to write, and the per-file half cannot be asked
33
+ about it. Measured: one branch adding `RK3 (deps: RK2)` while the other removed `RK2`
34
+ landed clean and failed `lint` afterwards; and a **cycle** is the purer case of it
35
+ (RK1354), well-formed on both sides and present in the merged file alone, so neither
36
+ author ever held the state they would be asked to review.
37
+ A defect the merge creates is one nobody chose and nobody would find, the file having been
38
+ written by a program; a defect it inherited is somebody's committed line, which `lint`
39
+ refuses on that branch and refuses again after this lands.
40
+ Held to every finding until RK1352 measured what that cost: a base whose `RK9` carried an
41
+ over-long `why`, one branch adding `RK1` and the other `RK2`, neither touching `RK9` —
42
+ refused, naming `RK9` to a reviewer mid-merge who did not choose that work, and leaving
43
+ the project without a driver for that file until somebody cleaned a line the merge had no
44
+ opinion about. Compared by `(code, id)` and never by line, a merge moving lines by
45
+ construction. What that trades away is a side making an already-bad field worse: the pair
46
+ is unchanged, so this lets it through and the gate does not — which is the division the
47
+ first sentence of this module states, a driver being a driver.
48
+
49
+ Anything refused falls back to git's own conflict markers, whole-file, and exits non-zero.
50
+ That is not a failure of the driver: it is the driver declining to write a file it cannot
51
+ prove, leaving the reviewer exactly where a repository with no driver would have left them.
52
+
53
+ Registered per file in `.gitattributes` and per checkout in `git config`, so it is opt-in
54
+ configuration and never a rule this tool assumes (L6): `merge --register` writes both, and
55
+ prints the two lines it wrote. The command it names is derived and absolute (RK255) — a
56
+ config value is executed by git months after the shell that printed it exited, so a name
57
+ that resolved on that shell's PATH is a driver that fails at the merge it was wired for.
58
+ """
59
+
60
+ from __future__ import annotations
61
+
62
+ import shlex
63
+ import shutil
64
+ from dataclasses import dataclass, replace
65
+ from pathlib import Path
66
+
67
+ from roadkeep.authoring import place, remove_entry
68
+ from roadkeep.config import PROSE_ROLES, Config
69
+ from roadkeep.kernel.document import Document, Entry
70
+ from roadkeep.linting import within
71
+ from roadkeep.provenance import invocation, persisted
72
+ from roadkeep.kernel.schema import SchemaError
73
+
74
+ __all__ = [
75
+ "Attributes",
76
+ "Driver",
77
+ "Merge",
78
+ "Registration",
79
+ "Wiring",
80
+ "attributed",
81
+ "config_command",
82
+ "merge",
83
+ "markers",
84
+ "register",
85
+ "registered",
86
+ "role_of",
87
+ "wiring",
88
+ ]
89
+
90
+ #: Git's default conflict-marker width, and the labels this driver writes when it declines.
91
+ #: Whole-file rather than per-hunk: the driver made no decision, so it has no hunk to name,
92
+ #: and a marker pair around the whole file is the honest report of that.
93
+ MARKER = 7
94
+ OURS = "ours"
95
+ THEIRS = "theirs"
96
+
97
+ #: The line `.gitattributes` carries per governed file, and the driver's name in `git
98
+ #: config`. One name, so a project that registers twice registers the same thing.
99
+ DRIVER = "roadkeep"
100
+
101
+ #: The key `.gitattributes` sends git to, and the one :func:`registered` reads back.
102
+ DRIVER_KEY = f"merge.{DRIVER}.driver"
103
+
104
+ #: What `.git/config` holds for this driver, as five distinguishable facts (RK266). Kept apart
105
+ #: because the remedies differ and only one of them is a defect: `UNRUNNABLE` is a driver git
106
+ #: will call and fail, `MOVED` is one that still works and is not what this machine would write,
107
+ #: and reporting the second as the first would be crying wolf on every second checkout.
108
+ ABSENT = "absent"
109
+ CURRENT = "current"
110
+ MOVED = "moved"
111
+ UNRUNNABLE = "unrunnable"
112
+ #: Some governed files sent to the driver and not others (RK270) — the state a `.gitattributes`
113
+ #: reaches when a role was declared after it was written, and the one a whole-file yes/no hides.
114
+ PARTIAL = "partial"
115
+ #: Not an answer either way: no git, no repository, or a git too old for `config --default`.
116
+ UNKNOWN = "unknown"
117
+
118
+ #: git's own word for a path carrying no value for the attribute. Spelled here as well as in
119
+ #: :mod:`roadkeep.history`, because this module may not import that one at module level (RK260)
120
+ #: and a property cannot pay a lazy import — a test holds the two spellings together.
121
+ UNSPECIFIED = "unspecified"
122
+
123
+
124
+ @dataclass(frozen=True, slots=True)
125
+ class Merge:
126
+ """The result of one three-way merge, and everything the answer has to say."""
127
+
128
+ role: str
129
+ #: The merged file, or None when it was refused — the whole clean/not-clean question.
130
+ text: str | None
131
+ #: Ids whose line came from the other side: added there, or edited there alone.
132
+ took: tuple[str, ...] = ()
133
+ #: Ids the other side removed, and this side did not touch.
134
+ removed: tuple[str, ...] = ()
135
+ #: Ids **both branches created**, carrying different work — the collision RK120 names.
136
+ #: `renumber` moves one of them; a driver that picked would be deleting somebody's task.
137
+ doubled: tuple[str, ...] = ()
138
+ #: Ids both branches edited differently. A content conflict, kept apart from the above
139
+ #: because the remedy is a sentence and not an address.
140
+ contested: tuple[str, ...] = ()
141
+ #: Ids one branch **removed** — shipped, retired, deferred out — while the other edited
142
+ #: the line (RK482). The third remedy, and the reason it is not `contested`: nobody wrote
143
+ #: a second sentence, so asking a reviewer to choose one describes a merge that did not
144
+ #: happen. What is decided is whether the removal stands, and where the edit goes.
145
+ withdrawn: tuple[str, ...] = ()
146
+ #: Why it was refused, empty when it was not. Printed, because a driver that exits 1
147
+ #: with no reason is one the reviewer resolves without knowing what it saw.
148
+ reason: str = ""
149
+
150
+ @property
151
+ def clean(self) -> bool:
152
+ return self.text is not None
153
+
154
+
155
+ #: The file whose lines send git to this driver. Named here because `install` has to
156
+ #: know the path before it writes anything (RK394), and a second spelling at that call site
157
+ #: is the two ends of one write disagreeing.
158
+ ATTRIBUTES = ".gitattributes"
159
+
160
+
161
+ @dataclass(frozen=True, slots=True)
162
+ class Attributes:
163
+ """Which governed files `.gitattributes` sends to this driver, and which it does not (RK270).
164
+
165
+ A driver is two writes and RK266 read back one. `.gitattributes` sends git to the driver by
166
+ name; :data:`DRIVER_KEY` says what that name runs. Either alone is a repository where
167
+ nothing happens — the attribute without the config falls back to a textual merge, the
168
+ config without the attribute is never asked — so a check that answers about one of them is
169
+ answering truthfully and not answering the question.
170
+
171
+ Kept apart from :class:`Driver` rather than folded into it: this is a committed file and
172
+ that is a per-checkout config, they go missing for different reasons and are repaired by
173
+ different writes, and one dataclass spanning both would have to say which file each of its
174
+ fields was about.
175
+ """
176
+
177
+ path: Path
178
+ #: One line per governed file — what the root `.gitattributes` would have to carry.
179
+ wanted: tuple[str, ...]
180
+ #: Those of :attr:`wanted` the root file already carries. `register`'s view, and only that:
181
+ #: where to *put* a line is a decision about this file, and it stays one (RK273).
182
+ present: tuple[str, ...]
183
+ #: Git's own answer per governed path — this driver's name, another's, or `unspecified`
184
+ #: (RK273). The *fact* about what git sends where, which the root file cannot give.
185
+ resolved: tuple[tuple[str, str], ...] = ()
186
+ #: False when git could not be asked, the reading :class:`Driver` already has.
187
+ known: bool = True
188
+
189
+ @property
190
+ def missing(self) -> tuple[str, ...]:
191
+ """The lines `register` writes: wanted, not already in the root file, **not claimed**.
192
+
193
+ The exclusion is RK274. git takes the *last* matching rule, so appending
194
+ `<path> merge=roadkeep` under somebody's `<path> merge=theirs` wins over it — the
195
+ overridden line is still in the file, inert, which keeps the letter of "every other
196
+ line carried through untouched" and none of its meaning. Measured: `--check` reported
197
+ `docs/CHANGELOG.md → theirs` and the repair it named silently flipped git's answer.
198
+
199
+ Where git could not be asked there is no claim to see, so the root file decides alone —
200
+ the same fallback :attr:`state` makes, and the direction that keeps `register` working
201
+ on a machine with no git rather than writing nothing at all.
202
+ """
203
+ skip = {path for path, _ in self.claimed}
204
+ return tuple(
205
+ line
206
+ for line, (path, _) in zip(self.wanted, self.resolved or self._unasked())
207
+ if line not in self.present and path not in skip
208
+ )
209
+
210
+ def _unasked(self) -> tuple[tuple[str, str], ...]:
211
+ """What :attr:`resolved` would say if nothing were known — every path undecided."""
212
+ return tuple((line.split(f" merge={DRIVER}")[0], UNSPECIFIED) for line in self.wanted)
213
+
214
+ @property
215
+ def sent(self) -> tuple[str, ...]:
216
+ """The governed paths git resolves to **this** driver."""
217
+ return tuple(path for path, value in self.resolved if value == DRIVER)
218
+
219
+ @property
220
+ def unsent(self) -> tuple[str, ...]:
221
+ """Governed paths git sends nowhere — undecided, and so the ones `register` settles.
222
+
223
+ Claimed paths are **not** here (RK274). They are decided, just not for us: reporting a
224
+ deliberate wiring as a thing still to do is what made the check fail forever on a
225
+ repository that was finished, and it is the same argument RK273 settled when it chose
226
+ to report another driver rather than argue with it.
227
+ """
228
+ claimed = {path for path, _ in self.claimed}
229
+ return tuple(
230
+ path for path, value in self.resolved if value != DRIVER and path not in claimed
231
+ )
232
+
233
+ @property
234
+ def claimed(self) -> tuple[tuple[str, str], ...]:
235
+ """Governed paths some **other** driver is named for — a deliberate act, so it is said.
236
+
237
+ Invisible to the string comparison this used to be, which could only find its own name
238
+ and read everything else as nothing set. A project that wired a different driver for one
239
+ file did so on purpose, and a check that reports it as unwired is arguing with a choice.
240
+ """
241
+ return tuple(
242
+ (path, value)
243
+ for path, value in self.resolved
244
+ if value not in (DRIVER, UNSPECIFIED, "set", "unset")
245
+ )
246
+
247
+ @property
248
+ def state(self) -> str:
249
+ """What git would do with the governed files: the four states, plus :data:`UNKNOWN`.
250
+
251
+ Read off :attr:`resolved` and not off the root file, because "would git send this to
252
+ the driver" is git's question — and answering it from one file reported three unsent
253
+ while `check-attr` answered `roadkeep` from `.git/info/attributes` (RK273).
254
+
255
+ :data:`CURRENT` is "nothing is undecided" and not "everything is ours" (RK274): a
256
+ governed file another driver is named for is settled, so it does not hold the answer
257
+ open. What it does do is stay in the reported line, because a count that dropped it
258
+ would be a check quietly agreeing that the file is ours after all.
259
+ """
260
+ if not self.known:
261
+ return UNKNOWN
262
+ if not self.unsent:
263
+ return CURRENT
264
+ return ABSENT if not self.sent else PARTIAL
265
+
266
+ @property
267
+ def wired(self) -> bool:
268
+ return self.state == CURRENT
269
+
270
+ @property
271
+ def routes_here(self) -> bool:
272
+ """Whether any governed file reaches this driver — now, or once `register` has run.
273
+
274
+ The one relation between the two halves (RK277). The config exists to answer *for the
275
+ files the attributes route here*, so where none are and none will be, an unset driver
276
+ is not a missing repair: it is the right state of a repository that chose something
277
+ else. Measured on `docs/*.md merge=theirs`, where the check asked for a value no merge
278
+ would ever reach.
279
+
280
+ False in exactly two cases, both settled: every governed file is claimed by another
281
+ driver, or the project declares none. An **unregistered** project is not one of them —
282
+ its files are undecided, so they route here the moment the attribute half is repaired,
283
+ and withdrawing the config repair there would answer about the repository as it is
284
+ rather than the one the reader is in the middle of making. That is why this is not the
285
+ `sent`-is-empty test it first looks like.
286
+
287
+ Unknown reads as True: nothing was established, and not withdrawing a repair is the
288
+ direction that cannot be wrong by silence.
289
+ """
290
+ return not self.known or bool(self.sent or self.unsent)
291
+
292
+
293
+ @dataclass(frozen=True, slots=True)
294
+ class Driver:
295
+ """What this checkout's `git config` holds for the driver, against what it would hold now.
296
+
297
+ RK255 made the stored command absolute and named the condition that ends it. This is the
298
+ other half: naming an expiry is not observing one, and the value lives in `.git/config`,
299
+ which nothing in this tool read — so the first evidence a driver rotted was git writing
300
+ conflict markers into the file whose whole point is that its merge is decidable.
301
+ """
302
+
303
+ #: The command found under :data:`DRIVER_KEY`, empty when the key is not set.
304
+ stored: str
305
+ #: The command :func:`register` would write now, from :func:`~roadkeep.provenance.persisted`.
306
+ wanted: str
307
+ #: False when git could not be asked at all — the answer is absent, not negative, the same
308
+ #: reading :class:`~roadkeep.history.HistoryUnavailable` gets everywhere else.
309
+ known: bool = True
310
+
311
+ @property
312
+ def state(self) -> str:
313
+ """One of the five above. Runnability is asked before equality, deliberately.
314
+
315
+ A driver that differs from what this machine would write is not thereby broken: a
316
+ checkout registered where the console script was on PATH keeps working after this
317
+ package also grows a launcher. What git cannot execute is the defect; what merely
318
+ moved is a fact, and answering the second question first would report both as one.
319
+ """
320
+ if not self.known:
321
+ return UNKNOWN
322
+ if not self.stored:
323
+ return ABSENT
324
+ if not _resolves(self.stored):
325
+ return UNRUNNABLE
326
+ return CURRENT if self.stored == self.wanted else MOVED
327
+
328
+ @property
329
+ def wired(self) -> bool:
330
+ """Whether git has a driver here it can actually run — the one yes/no a caller needs."""
331
+ return self.state in (CURRENT, MOVED)
332
+
333
+
334
+ @dataclass(frozen=True, slots=True)
335
+ class Wiring:
336
+ """Both halves of the driver, and the questions only the two together answer (RK278).
337
+
338
+ The halves are read apart because they go missing for different reasons and are repaired by
339
+ different writes — that is RK270 and it stands. What kept going wrong is everything that
340
+ needs *both*: RK272's per-half repair, RK277's "no governed file routes here", and the
341
+ qualifier RK277 then shipped to one surface out of two. Three commits, three facts one
342
+ caller knew and another did not, each repaired where it showed rather than where it came
343
+ from.
344
+
345
+ So the joining is a value, computed once and passed. A caller that has this cannot render
346
+ half the answer, because there is no half to reach for.
347
+ """
348
+
349
+ attributes: Attributes
350
+ driver: Driver
351
+
352
+ @property
353
+ def needs_attributes(self) -> bool:
354
+ """Whether governed files are still undecided — the half `merge --register` repairs."""
355
+ return self.attributes.state in (ABSENT, PARTIAL)
356
+
357
+ @property
358
+ def demands_driver(self) -> bool:
359
+ """Whether a driver has to be configured: git has none it can run, **and** files reach it.
360
+
361
+ The conjunction RK277 established. Where every governed file is claimed by another
362
+ driver, or none is declared, an unset driver is not a missing repair but the settled
363
+ state of a repository that chose otherwise — so this narrows what is *demanded* and
364
+ never what is reported, which stays :attr:`driver` and is printed either way.
365
+ """
366
+ return self.driver.state in (ABSENT, UNRUNNABLE) and self.attributes.routes_here
367
+
368
+ def repairs(self) -> list[str]:
369
+ """The repair of each half that is actually broken, in the order reported (RK272).
370
+
371
+ Measured before it was written: one `merge --register` named for both halves sent a
372
+ reader into a loop — the verb writes the attribute lines and *prints* the config line,
373
+ so the check that suggested it answered identically afterwards. Advice a reader can
374
+ follow and land back on is worse than none, because it is the kind they stop reading.
375
+
376
+ Two halves, two remedies, and neither is `register` running `git config` after all:
377
+ that write is outside the files this tool was given (L2), and the half left to the
378
+ reader is a decision rather than an oversight. `UNKNOWN` gets none — the question was
379
+ never resolved, so naming a repair for it would be answering one nobody asked.
380
+ """
381
+ from roadkeep.provenance import invocation # noqa: PLC0415 - RK260
382
+
383
+ out = []
384
+ if self.needs_attributes:
385
+ # `UNKNOWN` is excluded by that property, not here: a question git could not
386
+ # answer (RK273) names no repair, the same overreach the config half declines.
387
+ out.append(f"{invocation()} merge --register")
388
+ if self.demands_driver:
389
+ out.append(config_command())
390
+ return out
391
+
392
+ def stated(self) -> str:
393
+ """Both halves and what each needs, which is the whole of `--check` (RK270, RK277)."""
394
+ from roadkeep.rendering import ( # noqa: PLC0415 - RK260
395
+ _attributes_line,
396
+ _other_copy,
397
+ _wiring_line,
398
+ )
399
+
400
+ rows = [
401
+ f" attributes {_attributes_line(self.attributes)}",
402
+ f" config {_wiring_line(self)}",
403
+ ]
404
+ rows += [f" fix {one}" for one in self.repairs()]
405
+ # **And the other copy, where this machine has one** (RK1389). RK1386 put this beside
406
+ # the config command on the report a `register` prints, and left this verb — the one
407
+ # RK1388 then made two other reads defer to — offering the installed script alone.
408
+ #
409
+ # The renderer and never a second sentence, which is RK276's rule about these two
410
+ # surfaces: one rendering serves both registration reports because a third copy of a
411
+ # line is the drift that task removed, and this is that line's third caller.
412
+ #
413
+ # Under `fix` rather than among the repairs: what `repairs` returns is commands, and a
414
+ # payload listing this among them would call an alternative a remedy.
415
+ if self.demands_driver and (other := _other_copy(config_command())):
416
+ rows.append(f" or {other}")
417
+ return chr(10).join(rows)
418
+
419
+ def payload(self, config: Config) -> dict[str, object]:
420
+ """The halves as fields, because they are two lines for a reason (RK275).
421
+
422
+ The MCP surface reaches this as `merge_check` and passes `--json` on every call: a
423
+ caller that got one string would have to parse which half is broken out of prose this
424
+ tool is free to reword. `sound` is the exit code as a boolean, so nothing has to infer
425
+ it from the absence of repairs.
426
+ """
427
+ from roadkeep.rendering import ( # noqa: PLC0415 - RK260
428
+ _attributes_line,
429
+ _other_copy,
430
+ _wiring_line,
431
+ )
432
+
433
+ return {
434
+ "attributes": {
435
+ "state": self.attributes.state,
436
+ "file": config.relative(self.attributes.path),
437
+ "reported": _attributes_line(self.attributes),
438
+ "routes_here": self.attributes.routes_here,
439
+ },
440
+ "driver": {"state": self.driver.state, "reported": _wiring_line(self)},
441
+ "sound": self.sound,
442
+ "fix": self.repairs(),
443
+ # The alternative beside the repairs and never inside them (RK1389): a consumer
444
+ # running `fix` in order would otherwise run a sentence. `""` where this machine
445
+ # has one copy, which is every adopter, and never omitted.
446
+ "other_copy": _other_copy(config_command()) if self.demands_driver else "",
447
+ }
448
+
449
+ @property
450
+ def sound(self) -> bool:
451
+ """Whether git would run this driver over everything routed to it."""
452
+ return not (self.needs_attributes or self.demands_driver)
453
+
454
+
455
+ def wiring(config: Config) -> Wiring:
456
+ """Read both halves of the driver's wiring in one call — the only way they are read."""
457
+ return Wiring(attributes=attributed(config), driver=registered(config))
458
+
459
+
460
+ @dataclass(frozen=True, slots=True)
461
+ class Registration:
462
+ """What `merge --register` wrote: the attribute lines, and the config it needs."""
463
+
464
+ attributes: Path
465
+ added: tuple[str, ...]
466
+ #: Already present, so not written again — re-running is not an accumulating file.
467
+ present: tuple[str, ...]
468
+ #: `git config merge.roadkeep.driver <…>`, as it must be set. Printed and not run: a
469
+ #: driver command is a path into somebody's checkout, and running `git config` for them
470
+ #: would be this tool writing outside the files it was given (L2).
471
+ command: str
472
+ #: What would stop that command resolving later (RK255) — the half of the answer a value
473
+ #: this tool prints once and git executes months afterwards cannot leave to the reader.
474
+ invalidated_by: str = ""
475
+ #: What `git config` holds **now** (RK266), read after the attribute lines were written:
476
+ #: the re-run that reports three lines already there is exactly the one where the config
477
+ #: is the half that moved, so the answer that says nothing changed must not be the whole
478
+ #: Both halves as they stand **now** (RK266, RK278), read after the attribute lines were
479
+ #: written: the re-run that reports three lines already there is exactly the one where the
480
+ #: config is the half that moved, so an answer saying nothing changed must not be the whole
481
+ #: answer — and the report needs the attribute verdict too, or it names a driver the check
482
+ #: has stopped asking for. `None` only where a caller constructed this without asking.
483
+ wiring: Wiring | None = None
484
+ #: Governed files left alone because another driver is named for them (RK274), with that
485
+ #: driver's name. Reported and never written over: git takes the last matching rule, so a
486
+ #: line added under theirs would win, and a repair that overrides what the check just
487
+ #: reported is this tool arguing with a decision it can see.
488
+ left_alone: tuple[tuple[str, str], ...] = ()
489
+
490
+
491
+ def merge(config: Config, role: str, base: str, ours: str, theirs: str) -> Merge:
492
+ """Merge three versions of one governed file, or refuse with a reason.
493
+
494
+ Refuses — text None — when any version carries a line this tool cannot reproduce (L3),
495
+ when both sides changed the prose around the entries, when an id was spent or edited
496
+ twice, or when the result is a file the gate would refuse.
497
+ """
498
+ schema = config.schema_for(role)
499
+ versions = {
500
+ "the ancestor": Document.parse(base, schema),
501
+ OURS: Document.parse(ours, schema),
502
+ THEIRS: Document.parse(theirs, schema),
503
+ }
504
+ for name, document in versions.items():
505
+ if document.non_canonical:
506
+ named = ", ".join(e.task.id for e in document.non_canonical)
507
+ return Merge(role, None, reason=_unreadable(name, named))
508
+ ancestor, mine, yours = versions["the ancestor"], versions[OURS], versions[THEIRS]
509
+ if role in PROSE_ROLES:
510
+ return _merge_prose(config, role, ancestor, mine, yours)
511
+
512
+ decided, doubled, contested, withdrawn = _decide(ancestor, mine, yours)
513
+ if doubled or contested or withdrawn:
514
+ return Merge(
515
+ role,
516
+ None,
517
+ doubled=doubled,
518
+ contested=contested,
519
+ withdrawn=withdrawn,
520
+ reason=_spent(doubled, contested, withdrawn),
521
+ )
522
+
523
+ frame, source = _frame(ancestor, mine, yours)
524
+ if frame is None:
525
+ return Merge(role, None, reason=_both_sides_moved_the_prose())
526
+
527
+ took = tuple(
528
+ task_id
529
+ for task_id, entry in decided.items()
530
+ if entry is not None and _raw(frame, task_id) != entry.raw
531
+ )
532
+ removed = tuple(
533
+ task_id for task_id, entry in decided.items() if entry is None and _raw(frame, task_id)
534
+ )
535
+ result = _materialize(frame, decided, where=config.relative(config.path(role)))
536
+ findings = _introduced(config, role, result, *versions.values())
537
+ if findings:
538
+ return Merge(role, None, took=took, removed=removed, reason=_refused(findings))
539
+ return Merge(
540
+ role,
541
+ result.render(),
542
+ took=took,
543
+ removed=removed,
544
+ reason="" if source is None else f"prose taken from {source}",
545
+ )
546
+
547
+
548
+ def markers(ours: str, theirs: str, *, width: int = MARKER) -> str:
549
+ """The whole file, between conflict markers — what a refusal leaves in the worktree.
550
+
551
+ Git's own fallback, written by this driver rather than left to it: once the driver runs,
552
+ git has handed the merge over, and a non-zero exit with an untouched `%A` would leave the
553
+ reviewer a file that looks like one side won.
554
+ """
555
+ mark = "<" * width, "=" * width, ">" * width
556
+ return (
557
+ f"{mark[0]} {OURS}\n{_terminated(ours)}{mark[1]}\n{_terminated(theirs)}"
558
+ f"{mark[2]} {THEIRS}\n"
559
+ )
560
+
561
+
562
+ def role_of(config: Config, path: str | Path) -> str | None:
563
+ """Which governed file this pathname is, or None — the driver's one lookup.
564
+
565
+ Compared as resolved paths, because git hands the driver `%P` as the path *in the
566
+ repository* and the command may be run from anywhere inside it.
567
+ """
568
+ target = (config.root / Path(path)).resolve()
569
+ for role in config.paths:
570
+ if config.path(role).resolve() == target:
571
+ return role
572
+ return None
573
+
574
+
575
+ def register(config: Config) -> Registration:
576
+ """Write one `.gitattributes` line per governed file, and name the config it needs.
577
+
578
+ Additive and idempotent: a line already there is reported and not written twice, and
579
+ every other line in the file is carried through untouched — it is the repository's file
580
+ and this command owns three lines in it, the same contract `install` keeps (RK100).
581
+
582
+ The driver command is :func:`~roadkeep.provenance.persisted` and never the console script
583
+ literal (RK255). What is named here is stored in `.git/config` and **executed by git**
584
+ when a governed file conflicts, so a name PATH happened to resolve in the terminal that
585
+ ran `register` is a driver that fails at the one moment this file exists for — and git's
586
+ fallback is conflict markers in the file whose whole point is that its merge is decidable.
587
+
588
+ A governed file some **other** driver is named for is skipped and reported (RK274). Writing
589
+ under it would win — git takes the last matching rule — so the promise that every other
590
+ line is carried through untouched would be kept while the line stopped meaning anything.
591
+ """
592
+ before = attributed(config)
593
+ if before.missing:
594
+ body = "".join(f"{line}\n" for line in before.missing)
595
+ current = before.path.read_text(encoding="utf-8") if before.path.is_file() else ""
596
+ if current and not current.endswith("\n"):
597
+ current += "\n"
598
+ before.path.write_text(current + body, encoding="utf-8", newline="")
599
+ stored = persisted()
600
+ return Registration(
601
+ attributes=before.path,
602
+ added=before.missing,
603
+ present=before.present,
604
+ command=config_command(),
605
+ invalidated_by=stored.invalidated_by,
606
+ wiring=wiring(config),
607
+ left_alone=before.claimed,
608
+ )
609
+
610
+
611
+ def attributed(config: Config) -> Attributes:
612
+ """Which governed files git sends to this driver, and what the root file carries (RK270/273).
613
+
614
+ The read half of :func:`register`, which is why that function is written on top of it: two
615
+ computations of "the line this role wants" would be the way the check and the write drift
616
+ apart, and a check that agreed with nothing but itself is worse than no check.
617
+
618
+ Two questions, deliberately, because they have two answers. What the root `.gitattributes`
619
+ holds decides what `register` writes — a decision about one file, and one this tool owns
620
+ three lines of. What git *resolves* decides whether a merge reaches the driver at all, and
621
+ that is asked of git (RK273): the attribute may be set in a subdirectory, in
622
+ `.git/info/attributes`, or in `core.attributesFile`, none of which the root file mentions.
623
+ """
624
+ # Imported here and not at module level (RK260), the reason :func:`registered` gives: the
625
+ # driver runs on git's merge path and `history` reaches `backlog` and `sections`.
626
+ from roadkeep.history import HistoryUnavailable, check_attr # noqa: PLC0415
627
+
628
+ path = config.root / ATTRIBUTES
629
+ existing = _attribute_lines(path)
630
+ paths = tuple(config.relative(config.path(role)) for role in config.paths)
631
+ wanted = tuple(f"{name} merge={DRIVER}" for name in paths)
632
+ try:
633
+ answered = check_attr(config.root, "merge", paths)
634
+ known = True
635
+ except HistoryUnavailable:
636
+ answered, known = {}, False
637
+ return Attributes(
638
+ path=path,
639
+ wanted=wanted,
640
+ present=tuple(line for line in wanted if line in existing),
641
+ resolved=tuple((name, answered.get(name, UNSPECIFIED)) for name in paths),
642
+ known=known,
643
+ )
644
+
645
+
646
+ def config_command() -> str:
647
+ """The `git config …` line that wires the config half — the repair, spelled once (RK272).
648
+
649
+ Composed here rather than at the two call sites, because `register` prints it as what to do
650
+ next and `merge --check` prints it as what to do *now*: two spellings would be two repairs,
651
+ and the one the check names is the one that has to work.
652
+
653
+ Never run, in either. Setting somebody's git config is a write outside the files this tool
654
+ was given (L2) — the half that is not written is not an oversight, and RK272 is about the
655
+ check naming that half accurately rather than about closing it.
656
+ """
657
+ return f'git config {DRIVER_KEY} "{driver_value(persisted().command)}"'
658
+
659
+
660
+ def driver_value(command: str) -> str:
661
+ """The `.git/config` value for a driver reached by `command` — git's four placeholders.
662
+
663
+ One spelling, read by :func:`register` when it composes the line and by :func:`registered`
664
+ when it compares what a checkout actually holds: two spellings would make every registered
665
+ driver read as :data:`MOVED` the day one of them gained a placeholder.
666
+ """
667
+ return f"{command} merge %O %A %B --path %P"
668
+
669
+
670
+ def registered(config: Config) -> Driver:
671
+ """Read this checkout's driver back out of `git config` (RK266).
672
+
673
+ A read and never a write: setting somebody's git config is outside the files this tool was
674
+ given (L2), which is why `register` prints that line rather than running it — and it is the
675
+ same reason nothing had read it back until now.
676
+
677
+ `--default ""` and not a bare `--get`, because git exits 1 for a key that is not set and
678
+ exits 1 for a repository that is not there, and the two are a wired-nothing and a
679
+ question-that-could-not-be-asked. A git too old for `--default` answers :data:`UNKNOWN`,
680
+ which is the honest reading of a tool that could not tell us either way.
681
+ """
682
+ # Imported here and not at module level (RK260): the driver itself is on git's merge path
683
+ # and every governed write reaches this module, while `history` pulls in `backlog` and
684
+ # `sections` — modules a merge never asks anything of.
685
+ from roadkeep.history import HistoryUnavailable, _run as _git # noqa: PLC0415
686
+
687
+ wanted = driver_value(persisted().command)
688
+ try:
689
+ stored = _git(config.root, "config", "--default", "", "--get", DRIVER_KEY).strip()
690
+ except HistoryUnavailable:
691
+ return Driver(stored="", wanted=wanted, known=False)
692
+ return Driver(stored=stored, wanted=wanted)
693
+
694
+
695
+ def _resolves(command: str) -> bool:
696
+ """Whether the thing a stored driver command names is still on this machine.
697
+
698
+ Asked of the file and never by running it: a driver is invoked by git with three paths and
699
+ a `--path`, and this tool executing somebody's recorded command to find out whether it
700
+ executes is a side effect nobody asked for.
701
+
702
+ `python <script>` is the launcher case, and there the interpreter is the part that stays
703
+ while the script is the part a plugin update moves — so both halves are asked about, which
704
+ is exactly the failure :func:`~roadkeep.provenance.persisted` names as the expiry.
705
+ """
706
+ try:
707
+ argv = shlex.split(command)
708
+ except ValueError: # an unbalanced quote is a value no shell would run either
709
+ return False
710
+ if not argv:
711
+ return False
712
+ head = argv[0]
713
+ if not Path(head).is_file() and not shutil.which(head):
714
+ return False
715
+ if len(argv) > 1 and Path(head).stem.startswith("python") and argv[1].endswith(".py"):
716
+ return Path(argv[1]).is_file()
717
+ return True
718
+
719
+
720
+ # -- the decision ------------------------------------------------------------
721
+
722
+
723
+ def _decide(
724
+ ancestor: Document, mine: Document, yours: Document
725
+ ) -> tuple[dict[str, Entry | None], tuple[str, ...], tuple[str, ...], tuple[str, ...]]:
726
+ """One answer per id: the line it ends up with, None for gone, or a conflict.
727
+
728
+ Read off the raw lines and not off the parsed fields, because "did this side change it"
729
+ is a question about what was written — two spellings of one task are two lines, and the
730
+ round-trip guarantee above is what makes comparing them exact.
731
+ """
732
+ decided: dict[str, Entry | None] = {}
733
+ doubled: list[str] = []
734
+ contested: list[str] = []
735
+ withdrawn: list[str] = []
736
+ was, here, there = ancestor.by_id(), mine.by_id(), yours.by_id()
737
+ for task_id in dict.fromkeys((*was, *here, *there)):
738
+ before, ours, theirs = was.get(task_id), here.get(task_id), there.get(task_id)
739
+ if _raw(mine, task_id) == _raw(yours, task_id):
740
+ decided[task_id] = ours
741
+ elif _raw(mine, task_id) == _raw(ancestor, task_id):
742
+ decided[task_id] = theirs
743
+ elif _raw(yours, task_id) == _raw(ancestor, task_id):
744
+ decided[task_id] = ours
745
+ elif before is None:
746
+ doubled.append(task_id)
747
+ elif ours is None or theirs is None:
748
+ # One side's line is *gone* (RK482) — shipped, retired, deferred out — and the
749
+ # other edited it. Kept apart from `contested` for RK120's reason: that clause
750
+ # asks a reviewer to choose a sentence, and nobody wrote a second one here. The
751
+ # decision is whether the removal stands and where the edit goes.
752
+ withdrawn.append(task_id)
753
+ else:
754
+ contested.append(task_id)
755
+ return decided, tuple(doubled), tuple(contested), tuple(withdrawn)
756
+
757
+
758
+ def _merge_prose(
759
+ config: Config, role: str, ancestor: Document, mine: Document, yours: Document
760
+ ) -> Merge:
761
+ """The same merge, over §sections instead of task lines (RK483).
762
+
763
+ A rationale file has no task lines at all, so `_skeleton` was the whole file and `_frame`
764
+ compared three whole files: any two differing sides refused. `ship` drops a section and
765
+ one task is one commit, so two branches that shipped anything landed there — measured on
766
+ a scaffold as two disjoint drops answering *both branches changed the prose*.
767
+
768
+ The address is what makes it decidable, and this file has one: a §section is keyed by the
769
+ anchor `section drop` already takes, so *which section changed* is a question about
770
+ anchors and never about line numbers. Every rule above is reused with that key.
771
+
772
+ **L4 is not weakened.** Taking a whole section from one side is the decision the roadmap
773
+ makes; merging *inside* one is prose, so a body differing on both sides is `contested`
774
+ and stays the reviewer's. What is outside the sections is the frame, and both sides
775
+ moving that still refuses.
776
+ """
777
+ decided, doubled, contested, withdrawn = _decide_sections(ancestor, mine, yours)
778
+ if doubled or contested or withdrawn:
779
+ return Merge(
780
+ role,
781
+ None,
782
+ doubled=doubled,
783
+ contested=contested,
784
+ withdrawn=withdrawn,
785
+ reason=_spent(doubled, contested, withdrawn),
786
+ )
787
+ frame, source, other = _prose_frame(ancestor, mine, yours)
788
+ if frame is None:
789
+ return Merge(role, None, reason=_both_sides_moved_the_prose())
790
+ held = _sections_of(frame)
791
+ took = tuple(
792
+ anchor for anchor, lines in decided.items() if lines is not None and held.get(anchor) != lines
793
+ )
794
+ removed = tuple(anchor for anchor, lines in decided.items() if lines is None and anchor in held)
795
+ result = Document.parse(_written(frame, other, decided), config.schema_for(role))
796
+ findings = _introduced(config, role, result, ancestor, mine, yours)
797
+ if findings:
798
+ return Merge(role, None, took=took, removed=removed, reason=_refused(findings))
799
+ return Merge(
800
+ role,
801
+ result.render(),
802
+ took=took,
803
+ removed=removed,
804
+ reason="" if source is None else f"prose taken from {source}",
805
+ )
806
+
807
+
808
+ def _sections_of(document: Document) -> dict[str, tuple[str, ...]]:
809
+ """Every §section's raw lines, keyed by anchor — the unit a prose merge decides.
810
+
811
+ **Trailing blanks are off the comparison.** `Section.last` runs to whatever follows, so
812
+ dropping the section *below* one extends its region to the end of the file — and the
813
+ first run of this read reported the section nobody touched as `withdrawn`. The blank is
814
+ a separator between sections and not a fact about either, so it is normalised the way
815
+ `_skeleton` normalises line endings, and for the same reason: refusing over it refuses
816
+ every merge.
817
+ """
818
+ from roadkeep.sections import anchored # noqa: PLC0415 - RK260, the prose path only
819
+
820
+ found = {}
821
+ for section in anchored(document):
822
+ lines = list(document.lines[section.first - 1 : section.last])
823
+ while lines and not lines[-1].strip():
824
+ lines.pop()
825
+ found[section.anchor] = tuple(lines)
826
+ return found
827
+
828
+
829
+ def _decide_sections(
830
+ ancestor: Document, mine: Document, yours: Document
831
+ ) -> tuple[dict[str, tuple[str, ...] | None], tuple[str, ...], tuple[str, ...], tuple[str, ...]]:
832
+ """`_decide`'s four-way rule with the anchor as the key and the region as the text."""
833
+ decided: dict[str, tuple[str, ...] | None] = {}
834
+ doubled: list[str] = []
835
+ contested: list[str] = []
836
+ withdrawn: list[str] = []
837
+ was, here, there = _sections_of(ancestor), _sections_of(mine), _sections_of(yours)
838
+ for anchor in dict.fromkeys((*was, *here, *there)):
839
+ before, ours, theirs = was.get(anchor), here.get(anchor), there.get(anchor)
840
+ if ours == theirs:
841
+ decided[anchor] = ours
842
+ elif ours == before:
843
+ decided[anchor] = theirs
844
+ elif theirs == before:
845
+ decided[anchor] = ours
846
+ elif before is None:
847
+ doubled.append(anchor)
848
+ elif ours is None or theirs is None:
849
+ withdrawn.append(anchor)
850
+ else:
851
+ contested.append(anchor)
852
+ return decided, tuple(doubled), tuple(contested), tuple(withdrawn)
853
+
854
+
855
+ def _prose_skeleton(document: Document) -> tuple[str, ...]:
856
+ """The file with its §sections taken out — what `_skeleton` is for a roadmap."""
857
+ from roadkeep.sections import anchored # noqa: PLC0415 - RK260, the prose path only
858
+
859
+ inside: set[int] = set()
860
+ for section in anchored(document):
861
+ inside |= set(range(section.first, section.last + 1))
862
+ return tuple(
863
+ line.rstrip("\r\n")
864
+ for number, line in enumerate(document.lines, start=1)
865
+ if number not in inside
866
+ )
867
+
868
+
869
+ def _prose_frame(
870
+ ancestor: Document, mine: Document, yours: Document
871
+ ) -> tuple[Document | None, str | None, Document | None]:
872
+ """Whose frame the merged file keeps, and the other side, whose new sections still land."""
873
+ was, here, there = (
874
+ _prose_skeleton(ancestor),
875
+ _prose_skeleton(mine),
876
+ _prose_skeleton(yours),
877
+ )
878
+ if there == was or here == there:
879
+ return mine, None, yours
880
+ if here == was:
881
+ return yours, THEIRS, mine
882
+ return None, None, None
883
+
884
+
885
+ def _written(
886
+ frame: Document, other: Document | None, decided: dict[str, tuple[str, ...] | None]
887
+ ) -> str:
888
+ """The frame with every decided section written into it, and the other side's new ones.
889
+
890
+ A walk and not a head/tail split, because a `## Block` heading sits *between* sections in
891
+ every file organised by blocks, and slicing around the first and last would swallow it.
892
+
893
+ A section the frame never had is placed after the anchor that preceded it on its own
894
+ side, so the order that side chose survives. The ones nothing of the frame's precedes go
895
+ after the last section rather than at the end of the file — and the ones that follow
896
+ nothing go before the first. Written down because the first cut of this dropped the
897
+ trailing case on the floor while reporting it as `took`, which is the silent loss this
898
+ whole driver exists to refuse.
899
+ """
900
+ from roadkeep.sections import anchored # noqa: PLC0415 - RK260, the prose path only
901
+
902
+ held = _sections_of(frame)
903
+ leading, before, trailing = _arriving(frame, other, decided)
904
+ spans = sorted((one.first, one.last, one.anchor) for one in anchored(frame))
905
+ blank = frame.newline
906
+ # How many blank lines the frame kept after each section, so an unchanged file comes
907
+ # back byte-identical (L3). `_sections_of` takes them off to compare, and assuming one
908
+ # back added a line at EOF on every corpus this was run against.
909
+ pad = {
910
+ anchor: last - (first - 1) - len(held.get(anchor, ()))
911
+ for first, last, anchor in spans
912
+ }
913
+ out: list[str] = []
914
+ at = 0
915
+ for index, (first, last, anchor) in enumerate(spans):
916
+ out.extend(frame.lines[at : first - 1])
917
+ if index == 0:
918
+ out.extend(_spaced(leading, blank))
919
+ out.extend(_spaced(before.get(anchor, []), blank))
920
+ lines = decided.get(anchor, held.get(anchor))
921
+ if lines is not None:
922
+ out.extend(lines)
923
+ out.extend([blank] * pad.get(anchor, 1))
924
+ if index == len(spans) - 1:
925
+ out.extend(_spaced(trailing, blank))
926
+ at = last
927
+ if not spans: # a frame with no section at all: everything arriving goes after the prose
928
+ out.extend(frame.lines)
929
+ out.extend(_spaced([*leading, *before.values(), *trailing], blank))
930
+ return "".join(out)
931
+ out.extend(frame.lines[at:])
932
+ return "".join(out)
933
+
934
+
935
+ def _spaced(blocks: list[list[str]], blank: str) -> list[str]:
936
+ """Section blocks with one blank line after each — the separator `_sections_of` took off."""
937
+ out: list[str] = []
938
+ for block in blocks:
939
+ out.extend(block)
940
+ out.append(blank)
941
+ return out
942
+
943
+
944
+ def _arriving(
945
+ frame: Document, other: Document | None, decided: dict[str, tuple[str, ...] | None]
946
+ ) -> tuple[list[list[str]], dict[str, list[list[str]]], list[list[str]]]:
947
+ """New sections as (before the first, before a named anchor, after the last).
948
+
949
+ Three buckets rather than one, because a new section can precede every anchor the frame
950
+ has, follow every one, or sit between two — and a single map keyed by "what comes after"
951
+ has no key for the last case.
952
+ """
953
+ from roadkeep.sections import anchored # noqa: PLC0415 - RK260, the prose path only
954
+
955
+ leading: list[list[str]] = []
956
+ before: dict[str, list[list[str]]] = {}
957
+ trailing: list[list[str]] = []
958
+ if other is None:
959
+ return leading, before, trailing
960
+ held = _sections_of(frame)
961
+ order = [one.anchor for one in anchored(other)]
962
+ for index, anchor in enumerate(order):
963
+ lines = decided.get(anchor)
964
+ if anchor in held or lines is None:
965
+ continue
966
+ following = next((one for one in order[index + 1 :] if one in held), None)
967
+ preceding = next((one for one in reversed(order[:index]) if one in held), None)
968
+ if following is not None:
969
+ before.setdefault(following, []).append(list(lines))
970
+ elif preceding is not None:
971
+ trailing.append(list(lines))
972
+ else:
973
+ leading.append(list(lines))
974
+ return leading, before, trailing
975
+
976
+
977
+ def _frame(
978
+ ancestor: Document, mine: Document, yours: Document
979
+ ) -> tuple[Document | None, str | None]:
980
+ """Whose headings and prose the merged file keeps, and None when both sides moved them.
981
+
982
+ The skeleton is every line that is not a task line, which is exactly the part of a
983
+ governed file this tool does not write (L4). One side changing it is a decision the
984
+ merge can carry; both changing it differently is prose, and prose is the reviewer's.
985
+ """
986
+ was, here, there = _skeleton(ancestor), _skeleton(mine), _skeleton(yours)
987
+ if there == was or here == there:
988
+ return mine, None
989
+ if here == was:
990
+ return yours, THEIRS
991
+ return None, None
992
+
993
+
994
+ def _skeleton(document: Document) -> tuple[str, ...]:
995
+ """The file with its task lines taken out, endings normalised.
996
+
997
+ Normalised because a branch checked out on Windows and one on Linux differ in every
998
+ line, and refusing a merge over that is refusing every merge.
999
+ """
1000
+ entries = {entry.lineno for entry in document.entries}
1001
+ return tuple(
1002
+ line.rstrip("\r\n")
1003
+ for number, line in enumerate(document.lines, start=1)
1004
+ if number not in entries
1005
+ )
1006
+
1007
+
1008
+ def _materialize(
1009
+ frame: Document, decided: dict[str, Entry | None], *, where: str = ""
1010
+ ) -> Document:
1011
+ """Write the decided lines into the frame: replace, remove, then place what is new.
1012
+
1013
+ In that order and re-located by id at every step, because each edit reparses and a line
1014
+ number held across one is a line number that has already moved — the care every mutator
1015
+ in :mod:`roadkeep.kernel.document` takes, for the same reason.
1016
+
1017
+ ``where`` is the file being merged, which is what makes a refusal here readable (RK361):
1018
+ this is the fourth caller of `place` and it was the one passing neither the path nor an
1019
+ id, so a merged line the schema refuses reported a rule and a number about a file the
1020
+ caller is holding two versions of.
1021
+ """
1022
+ result = frame
1023
+ for task_id, entry in decided.items():
1024
+ held = result.by_id().get(task_id)
1025
+ if entry is not None and held is not None and held.raw != entry.raw:
1026
+ result = result.replace_line(held.index, entry.raw)
1027
+ for task_id, entry in decided.items():
1028
+ held = result.by_id().get(task_id)
1029
+ if entry is None and held is not None:
1030
+ result = remove_entry(result, held)
1031
+ for task_id, entry in decided.items():
1032
+ if entry is not None and task_id not in result.by_id():
1033
+ # `place` re-renders from the task, which is the same bytes: every version was
1034
+ # held to the round-trip above, so nothing arrives here that would come back
1035
+ # spelled differently — and the blank-line and block rules are `add`'s, once.
1036
+ # True of the *rendering* and not of the schema, which is why the refusal below
1037
+ # is reachable at all: a dep this tool re-derives during the merge grows the line
1038
+ # by the two characters RK348 was filed about.
1039
+ try:
1040
+ result = place(result, entry.task, where=where).document
1041
+ except SchemaError as error:
1042
+ raise _naming_the_merged_line(task_id, where, error) from None
1043
+ return result
1044
+
1045
+
1046
+ def _naming_the_merged_line(task_id: str, where: str, error: SchemaError) -> SchemaError:
1047
+ """The same refusal, told which id and which file it is about (RK361).
1048
+
1049
+ RK348's rule, at the one door that did not keep it: a length is reported against a line
1050
+ somebody can find, never as a bare number. Here the number is about a line neither side
1051
+ typed in this state — it is one branch's line landing in the other's file — so a caller
1052
+ reading it has two versions open and nothing saying which one the count belongs to.
1053
+
1054
+ Not `anchors`, which is the clause the other three doors carry (RK349): this caller is
1055
+ inside git's merge driver rather than at a prompt, and a command they cannot run until
1056
+ the merge is over is noise on a refusal that already needs reading twice.
1057
+ """
1058
+ at = f" merging {where}" if where else " in the merge"
1059
+ said = f" — on {task_id}'s line,{at}"
1060
+ return type(error)(
1061
+ tuple(replace(one, message=f"{one.message}{said}") for one in error.violations)
1062
+ )
1063
+
1064
+
1065
+ def _raw(document: Document, task_id: str) -> str | None:
1066
+ entry = document.by_id().get(task_id)
1067
+ return entry.raw if entry is not None else None
1068
+
1069
+
1070
+ def _attribute_lines(path: Path) -> set[str]:
1071
+ if not path.is_file():
1072
+ return set()
1073
+ return {line.strip() for line in path.read_text(encoding="utf-8").splitlines()}
1074
+
1075
+
1076
+ def _terminated(text: str) -> str:
1077
+ return text if text.endswith("\n") or not text else text + "\n"
1078
+
1079
+
1080
+ # -- the reasons -------------------------------------------------------------
1081
+
1082
+
1083
+ def _unreadable(version: str, named: str) -> str:
1084
+ return (
1085
+ f"{version} carries {named} written differently from what the schema renders: a "
1086
+ f"merge of lines this tool cannot reproduce would normalise work nobody reviewed"
1087
+ )
1088
+
1089
+
1090
+ def _spent(
1091
+ doubled: tuple[str, ...], contested: tuple[str, ...], withdrawn: tuple[str, ...] = ()
1092
+ ) -> str:
1093
+ out = []
1094
+ if doubled:
1095
+ out.append(
1096
+ f"both branches created {', '.join(doubled)}: one address, two tasks — "
1097
+ f"`{invocation()} renumber <id>` on one side, then merge again"
1098
+ )
1099
+ if contested:
1100
+ out.append(
1101
+ f"both branches rewrote {', '.join(contested)}: one line, two sentences — "
1102
+ f"the wording is the reviewer's and this driver does not pick one"
1103
+ )
1104
+ if withdrawn:
1105
+ # Not "rewrote" (RK482): one side's line is gone and the other edited it, so what is
1106
+ # asked for is not a sentence. Taking the removal would delete the edit silently,
1107
+ # which is the ground RK97 refuses to pick on for `doubled`.
1108
+ out.append(
1109
+ f"one branch removed {', '.join(withdrawn)} and the other edited it: a line that "
1110
+ f"shipped, retired or deferred against an edit to the same line — decide whether "
1111
+ f"the removal stands, then where that edit goes"
1112
+ )
1113
+ return "; ".join(out)
1114
+
1115
+
1116
+ def _both_sides_moved_the_prose() -> str:
1117
+ return (
1118
+ "both branches changed the headings or the prose around the entries, and this "
1119
+ "tool does not merge prose (L4)"
1120
+ )
1121
+
1122
+
1123
+ def _introduced(
1124
+ config: Config, role: str, result: Document, *inputs: Document
1125
+ ) -> list:
1126
+ """The findings this merge composed, which are the ones it may refuse over (RK1352).
1127
+
1128
+ The driver gated its output against `within` and asked nothing about its inputs, so a
1129
+ defect in the ancestor blocked every merge of that file until somebody cleaned it — and
1130
+ cleaning it is a different task from the merge. Reproduced: a base whose `RK9` carries a
1131
+ 283-character `why`, one branch adding `RK1`, the other adding `RK2`, neither touching
1132
+ `RK9` — refused, naming `RK9` to somebody mid-merge who did not choose that work.
1133
+
1134
+ Keyed by `(code, id)` and never by line: a merge moves lines by construction, so a
1135
+ position is the one part of a finding that cannot survive the comparison. What that
1136
+ trades away is the case where a side makes an already-bad field worse — the pair is
1137
+ unchanged, so the driver lets it through and `lint` refuses it, which is the right
1138
+ division: this is a driver, and the gate is the gate (RK120).
1139
+
1140
+ The gate stays for what it is for — a merge that *creates* a defect is one nobody chose
1141
+ and nobody would find, the file having been written by a program.
1142
+ """
1143
+ from roadkeep.linting import resolving, within # noqa: PLC0415 - the module's own edge
1144
+
1145
+ def asked(document: Document) -> list:
1146
+ # Both halves (RK1353): what one file answers, and what only the backlog can. A dep
1147
+ # naming a line the other side removed exists in no version and in the merged file
1148
+ # alone, which is the one class a merge is uniquely able to write — and the half
1149
+ # `within` runs cannot be asked about it.
1150
+ return [*within(config, role, document), *resolving(config, role, document)]
1151
+
1152
+ held = {(finding.code, finding.id) for document in inputs for finding in asked(document)}
1153
+ return [finding for finding in asked(result) if (finding.code, finding.id) not in held]
1154
+
1155
+
1156
+ def _refused(findings: list) -> str:
1157
+ named = "; ".join(str(finding) for finding in findings[:3])
1158
+ more = f" (+{len(findings) - 3} more)" if len(findings) > 3 else ""
1159
+ return f"the merged file is one the gate refuses: {named}{more}"