diff --git a/tests/fixtures/lanes-edit-v1.1.0/SHA256SUMS b/tests/fixtures/lanes-edit-v1.1.0/SHA256SUMS new file mode 100644 index 00000000..1fa16287 --- /dev/null +++ b/tests/fixtures/lanes-edit-v1.1.0/SHA256SUMS @@ -0,0 +1 @@ +b68d0cbac35ac3bbac9e70790cafe63538821be582ca28cec0f7ec0f5c4745d2 lanes-edit.sh diff --git a/tests/fixtures/lanes-edit-v1.1.0/lanes-edit.sh b/tests/fixtures/lanes-edit-v1.1.0/lanes-edit.sh new file mode 100644 index 00000000..d28ed8f2 --- /dev/null +++ b/tests/fixtures/lanes-edit-v1.1.0/lanes-edit.sh @@ -0,0 +1,18977 @@ +#!/usr/bin/env bash +# +# lanes-edit.sh — the sanctioned writer for the estate lane registry (LANES.md). +# +# Protocol: ~/.agents/protocols/lane-collision-protocol.md, Rule 9 (registry in +# git) and Rule 10 (workstation designation), Amendment 3, 2026-09-09 — moved +# to the person's workspace repository by Amendment 5, 2026-09-10. +# +# WHERE THE REGISTER LIVES (Amendment 5, 2026-09-10; Amendment 9(a), 2026-09-13) +# `lanes/LANES.md` on `main` of THE PERSON'S OWN workspace repository — the +# `/-wip` that `$AGENT_PROTOCOL_ROOT/workspace.yaml` names, which +# is `opensoft/brett-wip` for the person this file was written for and +# `opensoft/scott-wip` for the next one. This file names no repository of its +# own: Amendment 5's second-person clause put a second person's register in a +# second repository, and Amendment 9 is what made that reachable. Direct commits to +# `main` are the norm THERE by design: the repository is excluded from the +# organisation's PR-only ruleset precisely so that a per-edit registry +# commit can land, which is what Rule 9 requires and what the orphan +# `lanes` branch of `opensoft/xFactory` used to be for. That branch is +# RETIRED, and its history came across whole with this file. +# +# Every path a lane already uses keeps resolving: +# `~/projects/xFactory/LANES.md` and `~/projects/xFactory/lanes-edit.sh` +# are symlinks into the checkout, placed by `link-estates`. +# This script never spells the checkout's own path, and since Amendment 9(a) +# it no longer derives it from its own location either: it reads +# `repository:` and `path:` from `$AGENT_PROTOCOL_ROOT/workspace.yaml`, the +# same pointer file `resume` and `status` already read. This file is an +# installed command in `~/.local/bin` with no register anywhere near it, so +# its own directory is evidence about the command and not about a person's +# data. Failing to find the workspace is a refusal naming +# `openRepoTools wip init`, never a guess. +# +# WHY THIS EXISTS +# LANES.md is edited by many concurrent lanes on more than one workstation. +# On 2026-09-08T23:46Z a whole-file write from one session dropped two other +# lanes' rows and a day of Rule 6 LANDED lines, and there was no history to +# recover from. Every write now goes through this script (or an equivalent +# single-line in-place edit followed by commit + pull --rebase + push), so the +# registry has a history and a lost row is one `git show` away. +# +# HAZARD — `sed -i` REPLACES A SYMLINK WITH A REGULAR FILE. +# ~/projects/xFactory/LANES.md is a SYMLINK into this worktree. Plain +# `sed -i` unlinks it and writes a new regular file, silently detaching the +# registry from git. Use this helper, or `sed -i --follow-symlinks`, or +# `cat tmp > LANES.md` (a redirect follows the symlink). `>>` appends, +# `cat`, `cut`, `head`, `tail`, `grep`, `python open(...,'a')` are all safe. +# +# USAGE +# lanes-edit.sh [--no-sweep|--sweep] verify-row +# lanes-edit.sh [--no-sweep|--sweep] set-row-state " · " +# lanes-edit.sh [--no-sweep|--sweep] replace-in-row "" "" [""] +# lanes-edit.sh [--no-sweep|--sweep] append-session-id "" "" [""] +# (the anchor is matched INSIDE THE +# SESSION CELL and nowhere else, and the +# text is appended at the END of it) +# lanes-edit.sh [--no-sweep|--sweep] append-line "" # LANDING/LANDED lines +# (attribution: $LANES_LANE, else the +# "lane " the text itself names) +# lanes-edit.sh [--no-sweep|--sweep] add-row "" +# lanes-edit.sh commit "" # commit a hand edit; with +# nothing staged, publish the stranded +# register and handoff commits (#194) +# lanes-edit.sh migrate-state-cells [--yes] # Amendment 13(e), once +# lanes-edit.sh retire-rows … [--reason ""] [--writer ] +# lanes-edit.sh archive-rows [--yes] # Amendment 19(d) +# +# AMENDMENT 19 — A CLOSED OR DORMANT LANE LEAVES THE LISTING +# lanes-edit.sh lanes [--closed] # CLOSED and DORMANT rows too +# lane-end --retire-dormant [--reason ""] [--yes] +# lanes-edit.sh archive-rows [--yes] +# +# CLOSED is a lane whose object log's last lane-kind line is `ENDED` or +# `RETIRED`; DORMANT is a ROW WITH NO OBJECT LOG and no live session here — +# the rows that predate Amendment 7 and that no `lane-end` can close, because +# it wants a live session or a log to write into. `lanes` lists neither by +# default; `--closed` adds them, and the NEXT FREE POSITION is computed over +# every row of the repository — the hidden ones and the archive included — so +# a retired `-` is never reissued. +# +# `lane-end --retire-dormant ` is a DRY RUN that names every dormant row +# of that repository with its start, its workstation and its state cell's +# head, and FLAGS the cells that say the work was unpushed, lost, a loss or +# owed, or that still say LIVE. With `--yes` it is ONE commit — `retire-rows` +# below it — creating each lane's log with a single `RETIRED` line that +# carries the row's own last words, and setting the row's state to +# `RETIRED · · ; was: `. +# +# AMENDMENT 13 — THE ROW IS CURRENT STATE; THE LOG IS HISTORY +# lanes-edit.sh set-row-state " · " +# lanes-edit.sh log NOTED lane: "" +# lanes-edit.sh log RULED lane: [→ ] "" +# lanes-edit.sh history [--since ] [--index] +# lanes-edit.sh history --all | --repo [--since ] [--index] +# lanes-edit.sh migrate-state-cells [--yes] +# +# The `state` column holds ONE PHRASE — ` · · ` — and +# every write REPLACES it. `set-row-state` stamps the UTC itself; the STATE is +# one of LIVE, PAUSED, LANDING #, LANDED, ENDED, RETIRED, HANDED OFF (Rule +# 6's reading of the cell is unchanged and is now the whole of what the cell +# says at that moment), and the line is at most 240 characters (ratified +# decision O1) carrying neither a `|` nor a second ` · `. +# +# `append-row-status` is RETIRED and refuses, naming these. It appended and +# never replaced, which is how the column that says where a lane IS came to +# hold 96,228 characters in one row and 7,016 in another after ONE day — a +# diary in a table nobody can read in the table. +# +# THE NARRATIVE GOES TO THE LANE'S OWN LOG, under two Amendment 7 verbs that +# are lane-kind lines and NOT transitions: `NOTED` is a status note and +# `RULED` a ruling recorded verbatim, with the object it bears on as its +# payload where there is one. Neither ever changes a lane's state on any +# object or on itself — `who`, `lane-end`, `lanes` and `swapped` skip them +# exactly as they skip `STARTED` and `RESUMED` — and `history` prints them in +# file order, which is the diary the cell used to be. +# +# `migrate-state-cells` is clause (e)'s ONE act, on Brett Heap's word: a DRY +# RUN by default, and with `--yes` one commit carrying the archive +# `lanes/archive/LANES-pre-amendment-13-.md`, every lane's log and the +# register. It REFUSES when no cell holds a ` · ` entry, so a second run is a +# no-op that says so. +# +# AMENDMENT 14 — THE DERIVED INDEX (`lanes-index`), WHICH NOTHING HERE ACTS ON +# lanes-edit.sh lanes … --index # the listing, out of the index +# lanes-edit.sh history … --index # the diary, out of the index +# lanes-edit.sh worktrees … --index # the inventory, out of its table (#161) +# +# The register's truth stays where it is. `lanes-index` (placed by +# `openRepoTools --install`) keeps a DERIVED copy — SQLite, or QA Postgres +# where this workstation is configured for it — written BEHIND the sources: +# after every write whose push LANDED, and after the mutex is released, this +# file starts one DETACHED `lanes-index sync` (stdin closed, never waited, +# its status never read; skipped where `lanes-index` is not on PATH or +# `LANES_INDEX=off`). No act reads the index or waits on it. `--index` is the +# only way a read consults it, typed per invocation, and it says on stderr +# which it read: `read: index () at register@; commits +# behind`, or `read: sources (index )` and the sources answer. +# +# THE INVENTORY HAS A TABLE TOO (opensoft/openRepoTools#161): `worktrees`, +# under the source `inventory:`, copied from `worktrees --all` +# by `lanes-index sync --source inventory` — which every inventory write +# (`set-lane-state`, `set-lane-tree`, the lifecycle follow, a rename's move +# of the control root) nudges exactly as a landed push nudges the register's. +# No act reads it: `lane-reconcile`, `lane-start` and `lane-end` read the +# sidecars and the disk. With `--index` the stderr line is `read: index +# () at inventory: synced `, followed by `(last error: +# )`, the last error `status` shows for that source: one a sync or a +# reconcile on this workstation refused or failed with, a `--dry-run` +# included, until a sync or a reconcile that is not a dry run succeeds. +# +# AMENDMENT 7 — the per-lane object log (`lanes/log/.md`) +# lanes-edit.sh log [→|← ] [""] [--text ""] +# lanes-edit.sh claim [--force] [--no-github] [--home owner/repo] +# lanes-edit.sh release [""] [--no-github] [--home owner/repo] +# lanes-edit.sh who | --lane | --landing owner/repo +# +# AMENDMENT 8 — swap and restart, the READ side (both read-only, never write) +# lanes-edit.sh swapped [] +# lanes-edit.sh session-start # the SessionStart hook; JSON on stdin +# +# AMENDMENT 12 — the name guard and the lock (the blocking hook) +# lanes-edit.sh guard # the UserPromptSubmit hook; JSON on stdin +# +# `guard` is the ONLY verb here that refuses a person's work. It reads the +# hook's JSON, takes the WINDOW from tmux, the SESSION's own name from the +# live record and the ROW from `origin/`, and where the three are not +# one name it REFUSES THE PROMPT (exit 2) with the triple and the one command +# that cures it. THE LOCK types `/rename ` into this pane for the TWO +# drifts that are not decisions — a name differing from the row's only by +# CASE, which is the same lane under Amendment 15, and a name that is a +# FORMER name of the row's lane, which is the same lane under Amendment +# 16(e) and is what a rename run from another window leaves behind. EVERY +# OTHER READABLE MISMATCH IS AN OFFER OF THREE CHOICES, answered `1` (allow +# this lane for this transcript), `2` (adjust the lane to the session) or `3` +# (adjust the session to the lane, which types the `/rename`) at the next +# prompt; an answer to a question the state has moved past is dropped rather +# than acted on, and the unreadable, ambiguous, duplicate and superseded still +# refuse outright. It is silent and cheap where the three agree, silent +# outside `$PROJECTS_ROOT` and silent for a subagent's prompt. +# +# AMENDMENT 16 — a lane is renamed by ONE WORD, in ONE COMMIT, and its old name +# resolves for ever +# lanes-edit.sh rename-lane [""] [--verbatim] [--no-github] +# +# `lane-rename ` on PATH is the word; this is its write. ONE +# commit, refused or whole, and its four moves are the amendment's clauses +# (b)–(e): the row's key cell becomes `` `` `` with `*(ex ``, +# renamed )*` beside it; `lanes/log/.md` is renamed to +# `lanes/log/.md` and gains a `RENAMED` line; the handoff the row names +# is renamed to the same date with `lane-` and gains a Rule 3 stamp, +# with the row's handoff column following; and `lanes/aliases.tsv` gains +# ` `. +# +# THE ALIAS TABLE IS WHAT MAKES THE OLD NAME KEEP WORKING (clause (e)). +# `canon_lane` — Amendment 15's resolver, which every `` argument and +# every `$LANES_LANE` already passes through — resolves a name with NO ROW +# through that table, case-insensitively, chains to their end, before it +# answers. So an old name in a line, a window, a session record or a person's +# typing lands on the current row, in every reader at once, rather than in a +# list of readers somebody has to keep complete. A ROW WINS OVER AN ALIAS: +# a name that is a lane today IS that lane, which is also what makes a rename +# back again readable. +# +# `RENAMED` is a LANE-KIND verb that changes no object's state. Every +# last-line state reader here enumerates the five verbs that DO +# (`STARTED PAUSED RESUMED ENDED RETIRED`), so the new verb is outside that +# rule by construction and no reader had to be taught to skip it. +# +# AMENDMENT 18 — ONE BINDING PER LANE +# lanes-edit.sh binding # where this lane is bound +# lanes-edit.sh request-handoff [--wait ] [--session ] +# lanes-edit.sh request-handoff --force "" +# +# A lane's BINDING is the `host`, `container` and `window` of its last +# `STARTED`/`RESUMED` with no `PAUSED`/`ENDED`/`RETIRED` after it, and those +# three sub-fields are written by `write_event` beside Amendment 11(c)'s +# `dir`/`profile`/`window` — read from `LANES_HOST`/`LANES_OS`/ +# `LANES_CONTAINER`, which the launcher exports, with clause (a)'s fallbacks. +# **Liveness is pronounced only from inside the binding's own host and +# container**: from anywhere else it is UNKNOWN and never dead, whatever +# `kill -0` of a pid in another namespace would say. The ONE exception is a +# window that is gone from a tmux server the two share, which is dead and is +# today's takeover path. A second place ASKS — `request-handoff` writes the +# line and pushes it, types `/handoff --exit requested by …` into the bound +# pane where that pane is here, and waits; an empty wait refuses with the +# facts and names `--force`, which is a second invocation that releases the +# binding on the bound session's behalf in the requester's own session field. +# The prompt guard answers both from the bound side (clauses (d) and (e)). +# +# AMENDMENT 18(h) — one live process per transcript +# lanes-edit.sh transcript-holders # every live process carrying it +# +# A transcript is held by ONE live process; the harness can fork one or resume +# one twice. This read is what `lane-start` asks before it binds or resumes an +# id, what `lane-end --retire ` proves a duplicate with, and what +# `guard` refuses a prompt on. It sweeps EVERY profile's `sessions/`, because a +# duplicate's record sits in another profile's — measured four times on +# 2026-09-14. +# +# A SWAP is a planned stop — a usage reset, a profile switch — and a RESTART +# is the launch that follows it. The RECORD a swap leaves is not a new file: +# it is the lane's own `PAUSED` line, payload +# `swap; window :; workstation `. A lane is SWAPPED +# on a workstation when that PAUSED is its LAST lane-kind line — no later +# RESUMED, STARTED, ENDED or RETIRED — and `swapped` lists those lanes, which +# is how a restart finds its lane once the new tmux session has lost the +# window name. `session-start` is the whole output of the SessionStart hook: +# it resolves the lane from the tmux window name, else from the session id in +# the hook's JSON, prints ONE block, and ALWAYS exits 0 — a hook that fails +# is a hook that breaks the session it was meant to orient. +# +# AMENDMENT 17 — the handoff is the swap, and the record names the agent +# lanes-edit.sh lane-agent # the last record's `agent ` +# lanes-edit.sh lane-transcript # its `transcript ` +# lanes-edit.sh lane-last # its LAST lane-kind line, as +# # +# lanes-edit.sh workspace-root # the workspace repository's path +# lanes-edit.sh log PAUSED … --utc # date a LATE record by its own field +# +# Clause (b) gives the `PAUSED` payload two sub-fields beside Amendment +# 11(c)'s `window`, `dir` and `profile`: `agent ` — `claude`, `codex`, +# or the launcher's name for whatever wrote the line, a manifest key (letters, +# digits, `.`, `_`, `-`) — and `transcript `, the agent's own +# resumable id where it has one. THE WRITER VALIDATES BOTH (`pause_subfields_check`, +# called from `write_event`) because the log is append-only: a malformed +# sub-field there is malformed for ever, and `lane-start --agent` launches on +# what it reads. `swapped` prints them as its sixth and seventh fields, after +# the five it already had, and a record written before this amendment carries +# neither — which is EMPTY in that output and 8 from the two reads, never a +# guess (Amendment 7(i)'s cutover rule). +# +# `--utc ` IS FOR THE LATE RECORD AND NOTHING ELSE (adoption act 7): the +# `PAUSED` a swap never left, written after the fact and dated by the moment +# the old session ENDED rather than by the clock of the shell writing it. It +# changes which instant the line NAMES and never where the line goes: the log +# is append-only and FILE ORDER is what every state read means by "last", so +# `lane-handoff --late` refuses to write one that would land after the +# relaunch's `RESUMED` — a lane that is running must never read as paused. +# +# `--home owner/repo` is an option of all FIVE of `claim`, `release`, `who`, +# `log` and `lane-end`, for a lane whose log has no STARTED line. All five +# resolve it AFTER the fetch (R30), because the STARTED line that refuses it +# may be a peer's and live only on `origin/`. +# +# An object is `owner/repo#`, `owner/repo:openspec/changes/`, `#` +# for the lane's OWN home repo, or `lane:` for the lane-kind lines. +# `lanes/repos.tsv` (`aliasowner/repo`) resolves an omitted owner and +# the register's legacy spellings; an unknown alias is refused, never guessed. +# A LANE'S HOME GOES THROUGH THE SAME TABLE (R20, Addendum 5) — `lane-start` +# resolves it before writing STARTED, and every comparison of an object's +# repository against a home resolves BOTH sides. A home is inherited by every +# `#` that lane writes, so a legacy org spelling there gave one GitHub +# issue two object keys and two lanes held it with no collision detected. +# +# STATE IS PER LANE: a lane's state on an object is its own LAST line naming +# it, and it HOLDS the object while that verb is open. Open is +# {CLAIMED, TAKEOVER, OPENED, LANDING, WITHDRAWN}; closed — and it closes +# only the writing lane's hold — is {RELEASED, CLAIM-LOST, CLOSED, LANDED}. +# +# THAT APPLIES TO A TAKEOVER TOO (R18, Addendum 5): lane B's TAKEOVER on an +# object supersedes lane A's CLAIMED only while the TAKEOVER is B's OWN LAST +# LINE on it. Once B writes RELEASED, CLOSED or LANDED there, A's later +# CLAIMED holds normally. A TAKEOVER is never removed from an append-only +# log, so treating one as superseding for ever made a legitimate re-claim +# invisible: `who` called a held object FREE and `claim` did not refuse the +# next lane. Known and deliberate: two lanes each ending on a TAKEOVER of one +# object are BOTH reported as holders — a visible conflict, and not reachable +# through the helpers, since `claim --force` takes over a stale CLAIMED only. +# +# AND "LAST" IS THE LAST LINE IN THE FILE (R14, Addendum 4). A lane's log is +# append-only and single-writer, so the ORDER OF ITS LINES is the order of +# that lane's writes. No state read here — `lane_objects`, `superseded_by`, +# PER_LANE_AWK, `who` in any mode, `lane-end`'s refusal, `claim`'s pre-check +# and its rescan — selects or orders lines by their UTC field. The UTC stays +# on every line as INFORMATION, and is compared only where a DURATION is the +# rule: Rule 1's four-hour staleness and Rule 6's thirty minutes, where a few +# seconds are immaterial. On 2026-09-11 this workstation's realtime clock was +# observed jumping ±25s in bursts and a log commit landed whose content +# carried a UTC 26s after its own committer date; a max-UTC read made that +# lane's newest line invisible. Two workstations never share a clock either. +# +# `claim` is Rule 1 as one act, and THE RACE IS DECIDED BY WHICH CLAIMED +# LANDS ON `main` FIRST, never by comparing timestamps: fetch, pre-check +# against `origin/main`, append, commit, push; on a rebase, rescan, and if +# another lane's claim is already there, write `CLAIM-LOST` and stop. Git's +# push serialization is the arbiter between workstations; the `mkdir` mutex +# below only serializes this one. +# +# EVERY STATE READ IS OF `origin/`, AFTER A FETCH — never of the +# working tree. What has LANDED is what other lanes can see; a working tree +# can be behind by a peer's whole day. `who`, the pre-check, staleness, the +# superseded filter, the crossing warning, `lane-end`'s refusal and +# `lane-start`'s home lookup all read the same source, so they cannot +# disagree with each other either. +# +# THE REGISTER'S ROWS ARE READ THE SAME WAY (R19, Addendum 5). The session +# cell, the handoff path and the workstation column come from +# `git show origin/:lanes/LANES.md`; nothing in `who` reads the +# working tree. THE ONE EXCEPTION IS THE `live-holder` SUBCOMMAND, and only +# its id SET (R25, Addendum 6): it is the published row's union this +# checkout's, because a session stamps its uuid on the row with +# `replace-in-row` and that write is a LOCAL COMMIT until its push lands — +# read from `origin` alone the rename gate would not see the uuid of the very +# session it is being asked to rename over, would answer 8, and `lane-start` +# would take the name. That is what mints ` (2)` (AGENTS.md rule 7). +# Liveness fails closed, so an id `origin` has not seen is a reason to refuse +# a rename, never to allow one, and nothing that PRINTS uses the union. +# +# A LANDED CLOSES THE LANDING IT ANSWERS (R17, Addendum 5): `who --landing` +# pairs them by (lane, PR) in FILE ORDER and keys the result on +# (lane, repository, PR). Most of the register's LANDED lines carry no +# `into main` clause, and keying those on the repository they name +# reported 232 phantom merge holds where one was real. +# +# openRepoTools#91 — THE CRASH-CONSISTENT LANE LIFECYCLE AND THE INVENTORY +# lanes-edit.sh lane-state +# lanes-edit.sh set-lane-state \ +# [--expect ] [--expect-generation ] \ +# [--expect-operation ] [--operation ] \ +# [--owner ] [--agent ] [--profile ] \ +# [--kind ] +# lanes-edit.sh lane-trees +# lanes-edit.sh set-lane-tree [--checkout ] \ +# [--branch ] [--head ] [--upstream ] \ +# [--dirty ] [--unpushed ] [--writer ] \ +# [--generation ] [--operation ] +# lanes-edit.sh lane-tree-now +# lanes-edit.sh project-legs # an assembly's legs, by path (T018) +# lanes-edit.sh lane-reconcile +# lanes-edit.sh worktrees [ | --all] [--index] [--fetch] +# lanes-edit.sh pathspec-check ... # opensoft/openRepoTools#162 +# +# A lane is RUNNING, SWAPPING, SWAPPED or CLOSED, and WHICH OF THOSE IT IS +# WITH NO LIVE HOLDER is what says where its session stopped: `RUNNING` with +# no holder is an UNGRACEFUL STOP (nothing was handed off) and `SWAPPING` +# with no holder is an INTERRUPTED SWAP (the handoff began and did not +# finish). Every transition carries a monotonic `generation` and a unique +# `operation`, and `--expect*` is the compare-and-swap that refuses a stale +# finalizer with exit 7 rather than letting it overwrite a newer owner. +# +# NO LANE-KIND VERB IS ADDED TO THE APPEND-ONLY LOG BY THIS CHANGE. Amendment +# 7's five state verbs stand and every reader of them is untouched (Amendment +# 18(g) has since added a sixth lane-kind verb, `HANDOFF-REQUESTED`, which +# changes no state; this adds none). This is a SNAPSHOT beside that +# history, local to the workstation, replaced atomically, and never committed +# — see the section above the dispatcher for where it lives and why it is +# neither in the register nor inside a git worktree. +# +# `set-lane-tree` records ONE worktree of the lane — its path, checkout, +# branch, head, upstream, dirty and unpushed counts and writer — as an +# OBSERVATION; `lane-reconcile` recomputes every one of them and REPORTS the +# difference. It resets nothing, deletes nothing and creates nothing: a +# missing tree's only rebuild is the estate's own `resume `, and a +# missing tree that last held uncommitted work is reported as possible loss, +# because no metadata reconstructs a file's contents. +# +# `lane-tree-now` IS THAT OBSERVATION ON ITS OWN, and it is here so that the +# handoff's WRITERS section, the sidecar it files and the reconciliation that +# recomputes against it are one implementation with one error handling. A git +# read that FAILED is never converted into a clean-looking value by any of the +# three: `unknown`, `none` and `0` are answers, and the reads that could not +# be made are said instead (R22, Amendment 7(d)). +# +# THE TWO WRITERS REFUSE A SIDECAR THEY CANNOT READ. A snapshot or a tree +# record carrying a schema this helper does not write is never replaced — a +# reader that fails closed and a writer that walks past it protect nothing — +# and neither is one of THIS schema that is not a whole record: a key its +# writer writes missing or out of shape, or an id that is not its file's +# (#115). `set-lane-tree`'s `--generation`/`--operation` are COMPARED with +# the lane's own snapshot under the mutex before the record is filed, so a +# poll from an operation a recovery has superseded, or from one already +# finalized (`SWAPPED`, #114), cannot be filed over the current one. +# +# THE SEAM — A MANAGED-OWNED LANE IS NOT THIS TOOLING'S (Brett Heap's ruling of +# 2026-10-04, verbatim: "managed ledger owns enrolled lanes; #97 owns legacy — +# rework both") +# lanes-edit.sh managed-projection +# +# 0 with the owner on stdout where the lane's register row carries a valid +# managed-owner marker, 8 where it carries none (a LEGACY lane, which is +# every lane today), 1 where it carries managed-owner vocabulary that does +# not parse as a marker, where only THIS checkout's row carries the +# vocabulary (#157 item 4a), or the register could not be read (ownership +# UNKNOWN), 64 usage. Every legacy act that would write for a lane asks this +# first and refuses a managed lane with 2 and an unknown one with 1, before +# a byte is written: the lane-kind lines `log` writes (STARTED, RESUMED, +# ENDED, RETIRED), `set-lane-state`, `set-lane-tree`, `retire-rows`, +# `set-row-state`, `replace-in-row` and `rename-lane`, the entry of +# `lane-start` and `lane-handoff`, and `lane-end` before its first act on +# each of its paths. `lane-reconcile` pronounces +# nothing on a managed lane (`VERDICT managed-owned`), and no legacy writer +# may write the marker's vocabulary into a row at all. +# +# EXIT CODES — every subcommand, one table, no two meanings on one number +# 0 done (and #194's publish whose queue `pull --rebase` emptied) +# 1 environment (no register, no writer) +# 2 refusal: bad arguments, the object is held, an unknown alias, a +# checkout that cannot be rebased, — Amendment 15 — a register holding +# two rows whose lane names differ only by case, which every writer and +# `canon-lane` refuse until 15(d)'s merge, or AMENDMENT 12's BLOCKED +# PROMPT, or — opensoft/openRepoTools#162 — a commit whose pathspec +# would stage bytecode, a cache or a virtual environment +# (`commit_push`, `pathspec-check`), or — #194 — `commit` refusing to +# publish local commits that are not register or handoff writes, from a +# checkout whose HEAD is off the branch, or that it cannot read +# (`cp_publish_fence`), and pushes none of them. EIGHT MEANINGS ON ONE NUMBER, and they +# stay readable only because of where each can occur: bad arguments to a +# subcommand that predates Amendment 11; `register-row`'s "not lane-shaped"; +# AN UNKNOWN SUBCOMMAND (the `*)` arm below), which is how a caller detects +# a helper predating the amendment that added the read it asked for; and +# Amendment 11's container refusal. The last is on WRITERS ONLY (the +# dispatcher guard), so no READ can return it and clause (h)'s +# fall-to-the-next-rung rule is unaffected by it. +# THE SIXTH IS NOT THIS FILE'S NUMBER AT ALL: 2 is what a `UserPromptSubmit` +# hook must exit to BLOCK a prompt (code.claude.com/docs/en/hooks), so +# `guard` spends the one number the harness reads, and every refusal it +# makes — a mismatch, an unreadable read, a pending offer's question and +# its answer — is that 2. `guard` never exits anything else but 0. +# 64 usage — a caller's bad arguments to one of the reads Amendment 11 added +# (`window-lane`, `lane-dir`, `lane-profile`, `last-session`, `forks`, +# `duplicate-holder` (issue #39), `workstation`, `fetch-age`, `lanes`, +# `session-lane`, and `swapped`, which +# took it first), to Amendment 13's `history`, and to Amendment 15's +# `canon-lane`, which takes the same +# contract because its four callers sit in front of a launch as those do. IT WAS IN NO TABLE AT ALL until this round (F-X16), while +# being the code the contract gives every one of those reads. +# +# 66 EX_NOINPUT — AMENDMENT 16(e)'s ALIAS TABLE COULD NOT BE READ, and +# `canon-lane` is the one verb that spends it. `lanes/aliases.tsv` is what +# makes a renamed lane's OLD name resolve, so a table nobody can read is +# not an estate with no renames: a former name would read as a lane nobody +# has, and `lane-start` would append a SECOND row for one that has been +# running all day. It is a number of its own because 2 already carries two +# meanings to `lane-start`, `lane-end`, `lane` and `lane-handoff` — 15(d)'s +# two-rows refusal, told by its words, and the unknown-subcommand 2 of an +# older helper, which they carry on past — and a third meaning there is the +# fail-open this refusal exists to close. +# +# WHY A SECOND USAGE CODE RATHER THAN 2. A read in front of a launch has to +# tell "you called me wrong" from "this helper has never heard of you" — +# and the second of those IS a 2, emitted by the `*)` arm, on every +# workstation until adoption act 3's install reaches it. One number cannot +# carry both without the caller guessing, so the newer reads spend a number +# of their own and the older half of this file keeps 2 where it always was. +# Clause (h)'s table is the contract for which read uses which. +# 3 the edit is never a permanent loss, but this attempt cannot confirm +# whether it also reached origin. THREE CAUSES (Copilot round 3 on #50, +# 5203261904, naming the other two this row used to leave out): a +# rebase conflict this attempt could not resolve — not pushed BY THIS +# ATTEMPT; a later write from this checkout may already carry it to +# origin, so LOOK by CONTENT before you retry (round 4, 5203455553: +# SHA ancestry alone misses a peer's rebase of it, which changes the +# hash but not the patch); `git_timeout_die`'s network timeout on a +# push OR a pull, where a hung one often already landed; or six +# attempts exhausted because a peer's own uncommitted file blocks +# every rebase. +# 4 the mutex could not be taken within 60s +# 5 an edit moved more than one line and was refused — or, Amendment 15, a +# lane's object log could not be renamed to the row's own spelling — or, +# #120 item 1, a register rewrite (`replace_line`, `delete_lines`) whose +# copy, write or result could not be proved; where the write had cut the +# register short its earlier bytes are put back first, and the refusal +# says which of the two the register holds +# 6 git add / commit / push failed +# 7 ANOTHER ACT GOT THERE FIRST, and this one wrote nothing. `claim`: +# CLAIM-LOST, another lane's claim landed on main first. +# `set-lane-state`: the lifecycle fence did not match — the state, the +# generation or the operation id moved under this process — so a stale +# finalizer cannot overwrite a newer owner (openRepoTools#91). +# `set-lane-tree`: the `--generation`/`--operation` this observation was +# taken under is no longer the lane's — or the lane is `SWAPPED` and the +# operation it names is finished (#114) — so a superseded poll cannot be +# filed over the current inventory. ONE MEANING ON THE NUMBER, in three +# places: you lost the race. +# 8 no record — `who` found nothing; `lane-objects` has no log file for the +# lane; `live-holder` READ this workstation's session records and none of +# them holds it; `swapped` found no lane swapped on the workstation; +# `history` READ the lane's log and it carries no `NOTED` or `RULED` line; +# `window-session` found no live session in the window. A read that could +# not be performed is never 8 (R22). `session-start` never exits 8, or +# anything but 0: it is a hook. `guard` never exits 8 either — it is a hook +# too, and a BLOCKING one, so its two codes are 0 and 2 (see 2 above). +# 9 CLAIM-LOST — issue #30's own dead-lane verdict could not be +# reconfirmed before this takeover's push landed: the source lane's own +# log moved past its terminal line, a live session on this workstation +# now backs it up, or that could not be read at all (`claim` only, +# `--force` over a dead lane's hold). NEVER coerced to 7: that code +# means a RIVAL's claim landed first, and this is the same lane the +# takeover was granted over, alive again rather than beaten to main. +# 10 THE RECORD IS THERE AND COULD NOT BE READ, which is the other half of 8 +# and never 8 itself (Copilot round 6 on openRepoTools#97). `lane-state` +# spends it for a lifecycle snapshot that EXISTS at the control root and +# cannot be opened — a permission, an I/O error, a name whose bytes are +# gone. 8 says *this lane has no snapshot*, which a launcher answers by +# going on; 10 says *this lane may be mid-crash and nobody could look*, +# which it answers by reading the lane by hand. One number could not carry +# both, and the one that was carrying both was 8 (R22, Amendment 7(d)). +# IT WAS 9 until main's #61 landed with 9 as `claim --force`'s abandoned +# takeover; each PR had taken 9 as unused, and the later one moved. +# `lane-trees` spends it for an inventory directory that EXISTS and +# cannot be listed, which is never "this lane recorded no tree" (#157 +# item 4e). And `lane-state` spends it for a snapshot of this schema that +# opens and is not a WHOLE record — cut short, or a key missing or out of +# shape (#115): nothing can be read out of it as a snapshot, so it is +# the same answer, and the message says which of the two it is. +# +# --no-sweep (DEFAULT, added 2026-09-09 after 0d84d34/a1f2438 swept another +# lane's uncommitted hand edit into an unrelated commit): every mutating +# subcommand checks, before making its own edit, whether LANES.md is +# already dirty. If it is, that content is someone else's — never this +# invocation's — so it is committed FIRST, on its own, as +# `LANES(pre-existing@): capture an uncommitted registry edit +# (row )`, before this invocation's own edit is made and committed. +# A WARNING (with `git diff --stat` and the first 200 chars of every +# changed line) always prints first. This never fails the call — the +# write still goes through. Amendment 7's `log`, `claim` and `release` take +# the same capture for the REGISTER between the two halves of their +# dirty-checkout guard, which is why a peer's half-written `lanes/LANES.md` +# does not refuse them (Addendum 3, R11); any OTHER modified tracked file +# still does, and is refused before the capture rather than after it. +# --sweep — the old behaviour: leave the pre-existing content staged so it +# lands inside this invocation's own commit. Still warns exactly as above, +# and appends " + sweeps uncommitted edit to row " to the commit +# subject, so the sweep is never silent. +# `commit` has no edit of its own to separate from a pre-existing one — its +# job IS to wrap whatever is already dirty. It instead warns and appends +# the same " + sweeps uncommitted edit to row " note when the dirty +# content touches a row other than the caller's own $LANES_LANE. +# +# ENVIRONMENT +# LANES_FILE registry path (default: /LANES.md) +# LANES_DIR dir holding it (default: /lanes) +# LANES_REPO checkout root (default: the `path:` in +# $AGENT_PROTOCOL_ROOT/workspace.yaml, +# checked to be a checkout of the +# `repository:` beside it — Amendment +# 9(a); never a literal path) +# LANES_WORKSPACE_ROOT that `path:`, overridden (the test seam; nothing else +# sets it) +# AGENT_PROTOCOL_ROOT dir holding workspace.yaml (default: ~/.agents) +# LANES_PATH pathspec of the register RELATIVE to LANES_REPO +# (default: `lanes/LANES.md`, derived +# with `git rev-parse --show-prefix`) +# LANES_BRANCH branch to commit on (default: main) +# LANES_LANE lane name for the commit subject when no lane argument +# LANES_WORKSTATION workstation name (the launcher exports it; else +# `hostname -s` outside a container, +# and inside one WITH NO VALUE every +# WRITER refuses — Amendment 11, +# decision 8(d), R-A11-14) +# LANES_HOST the MACHINE's short hostname as it reads OUTSIDE any +# container (Amendment 18(a); the launcher exports it). +# Fallback: `hostname -s` outside a container, and inside +# one the Rule 10 workstation name +# LANES_OS linux | macos | wsl | windows — the HOST's, as the person +# means it. Fallback: the kernel probe (Darwin -> macos, +# /proc/version naming microsoft -> wsl, linuxkit -> macos, +# any other Linux -> linux). `windows` is a launcher's word +# only: this file is bash and runs in WSL2 there +# LANES_CONTAINER the bench's name (`py-bench`, …). Fallback: inside a +# container, that container's own `hostname` — read LIVE at +# every write, never cached; outside one, `none` +# LANES_POLL_SECONDS the interval `request-handoff`'s wait polls the published +# log at (default 15). The test seam, and only that +# LANES_IN_CONTAINER 1|0 force the container probe (test seam) +# LANES_NO_GIT=1 edit only, no commit/push (used by the test harness) +# LANES_LOG_DIR the object logs (default: /log) +# LANES_REPOS_TSV the per-wip alias OVERRIDE (default: /repos.tsv) +# LANES_REPOS_TSV_SHIPPED the organisation's alias table shipped by +# openRepoTools (default: beside this command) +# LANES_ALIASES_TSV Amendment 16(e)'s LANE alias table, ` +# ` (default: /aliases.tsv) +# LANES_ALIASES_PATH its pathspec relative to LANES_REPO +# (default: `lanes/aliases.tsv`) +# LANES_SESSION this session's TRANSCRIPT uuid, for the event lines +# (default: the last uuid in the lane's row — Amendment 6(b)) +# LANES_LANE_DIR the lane's checkout, for project.yaml leg detection +# (default: $PROJECTS_ROOT/) +# LANES_NO_GITHUB=1 skip every `gh` call (tests, offline); same as --no-github +# LANES_NO_FETCH=1 skip the `git fetch` a read does first (offline; tests). +# It does NOT change WHAT is read: every state read is of +# `origin/`, which without the fetch is simply the +# ref as it already stands here. +# LANES_STALE_HOURS Rule 1's stale threshold, reused (default: 4) +# LANES_DEBUG non-empty: a refusal also prints its exit code +# LANES_INDEX=off no `lanes-index sync` after a write, and `--index` reads +# the sources (Amendment 14). It never turns a read ON: +# only a typed `--index` does +# +# Dependencies: bash, git, coreutils. No sed/awk substitution on the payload — +# every edit is computed with bash string operations, so `/`, `&`, `\` and `|` +# in the text are literal. + +set -u + +# Parse the global flags before probing paths, git or workstation identity. +# A profile-only prompt must not depend on any of that lane infrastructure. +SWEEP_MODE="no-sweep" +while [ $# -gt 0 ]; do + case "${1-}" in + --no-sweep) SWEEP_MODE="no-sweep"; shift ;; + --sweep) SWEEP_MODE="sweep"; shift ;; + --no-github) LANES_NO_GITHUB=1; shift ;; + *) break ;; + esac +done + +if [ "${1-}" = guard ] && [ "${CLAUDE_NO_LANE:-}" = 1 ]; then + if [ "$#" -ne 1 ]; then + printf '%s\n' "lanes-edit: usage: guard (the UserPromptSubmit hook; the hook's JSON on stdin)" >&2 + exit 2 + fi + exit 0 +fi + +SELF="$0" +if command -v readlink >/dev/null 2>&1; then + RESOLVED="$(readlink -f "$SELF" 2>/dev/null || printf '%s' "$SELF")" +else + RESOLVED="$SELF" +fi +SCRIPT_DIR="$(cd -- "$(dirname -- "$RESOLVED")" && pwd)" + +# --- THE WORKSPACE REPOSITORY (lane-collision-protocol Amendment 9(a)) ------- +# +# The person's data — the register `lanes/LANES.md`, the object logs +# `lanes/log/`, the handoffs, the manifests `park` writes, and a +# `lanes/repos.tsv` override — is found through +# `$AGENT_PROTOCOL_ROOT/workspace.yaml`, and NEVER from this file's own +# location. `resume:466` and `status:1673` already read that same file under +# that same name, and Amendment 9(a) mints no second one: a second way to find +# it is a second answer. +# +# Deriving it from here stopped being POSSIBLE the moment this became an +# installed regular file in `~/.local/bin` with no register anywhere near it, +# and it stopped being WANTED for a subtler reason: a file's location on disk +# is evidence about the file, not about a person's data. +# +# THESE FOUR FUNCTIONS ARE A DELIBERATE COPY, byte for byte, across +# `lanes-edit.sh`, `lane-start`, `lane-end` and `link-estates` — the same trade +# openRepoTools already makes for its own fetch shim (`openRepoTools:93-100`). +# A shared `lanes-common.sh` would be a TENTH file for `--install` to place and +# a broken helper the first time somebody copied only some of them. Each of +# these is one file a person has on PATH. +# +# FAILING TO FIND IT IS A REFUSAL, NEVER A GUESS. No file, no `path:`, no +# `repository:`, or a `path:` that is not the root of a checkout of the +# `repository:` named beside it → the caller refuses, exit 1 — the code +# `lanes-edit.sh` has always used for *registry not found* — with the fix +# named: `openRepoTools wip init`. Nothing here ever creates that file, writes +# a register, or falls back to a path derived from its own location. THE +# CHECKOUT TEST IS NEW: nothing validated it before this, so a `path:` pointing +# at some other repository used to be accepted and now is not. +# +# `LANES_WORKSPACE_ROOT` is the test seam and the only override — the seam +# `lane-start` already spelled for handoff resolution, widened to the whole +# question so `test_lane_helpers.sh` can point every helper at one sandbox. +# --- BEGIN shared workspace resolver (Amendment 9(a)) ---------------------- +# BYTE-IDENTICAL IN ALL FOUR LANE HELPERS, and held there by +# `tests/test_repo_hygiene.py`. The estate commands carry the same discipline +# for their own estate resolver and for the same reason its guard gives: a +# drifted copy is TWO ANSWERS to one question, and "where is this person's +# workspace" is exactly the question Amendment 9(a) exists to give one answer +# to. Edit it in one file and the test names the other three. +LANES_WS_WHY="" + +lanes_ws_yaml() { printf '%s\n' "${AGENT_PROTOCOL_ROOT:-$HOME/.agents}/workspace.yaml"; } + +# `key: value` at the TOP LEVEL only, first occurrence, with an inline `#` +# comment and surrounding quotes stripped and a leading `~` expanded against +# $HOME (nothing expands a bare `~` inside a file). The anchored `^key:` never +# reaches into the INDENTED `orgs:` map, which Amendment 9(a) puts out of +# scope: these helpers read `repository:` and `path:` and nothing else, because +# one register in the first workspace repository is the whole rule — the +# register never follows that map. Two lines of sed, because a YAML parser is +# not a dependency any of these files will take for one scalar. +lanes_ws_field() { + local v + v="$(sed -n -e "s/^$1:[[:space:]]*//p" "$2" 2>/dev/null | head -n 1 | + sed -e 's/[[:space:]]*#.*$//' -e 's/[[:space:]]*$//')" + v="${v%\"}"; v="${v#\"}" + v="${v%\'}"; v="${v#\'}" + case "$v" in + '~') v="$HOME" ;; + '~/'*) v="$HOME/${v#'~/'}" ;; + esac + printf '%s\n' "$v" +} + +# THE WORKSTATION'S NAME IS READ, NEVER INVENTED — AND NEVER `hostname` INSIDE A +# CONTAINER (lane-collision-protocol Amendment 11, ratified decision 8(d), as +# corrected by A11 Addendum 3's `R-A11-14`). +# +# WHAT WENT WRONG. `opensoft/brett-wip` `origin/main` carries SIX lines in +# `lanes/log/openRepoProject-1.md` whose workstation is a container id — five +# `@0e7d1a79a07e`, one `@55cceb3e5bc9` — in an append-only file, written by every +# writer inside that container and not only by Evidence 6's fork. A row on a +# workstation that does not exist is a row no reader can match, no crossing can +# detect and no `swapped ` can answer for; and the log is never rewritten, so +# each one is wrong for ever. +# +# WHO OWNS THE VALUE. `R-A11-14`: the **workBenches launcher**, which runs on the +# host and exports `LANES_WORKSTATION=` into every +# session AND every container it starts, beside the `CLAUDE_PROFILE_NAME` it +# already exports. These helpers READ it. They do not write it, they do not +# derive it from a second file, and THEY NEVER SUBSTITUTE A PLACEHOLDER: an +# `@unknown-workstation` is the same defect one field along from the `unknown` +# clause (e) refuses in the session field, and the rejected alternative — a +# `workstation:` key in `workspace.yaml` — is a SECOND PLACE FOR THE TRUTH TO BE +# WRONG beside the variable the launcher already sets. +# +# THE THREE ANSWERS, as ``: +# +# seam `$LANES_WORKSTATION` is set. This is the ordinary case +# wherever the launcher started the session. +# hostname no seam, and this is NOT a container: `hostname -s`, which +# is what the seam has defaulted to since Amendment 6 and +# what every row written before this rung was written by. +# container-unset no seam, and this IS a container. The NAME still answers, +# because a read in front of every launch may not refuse — +# it will simply match nothing, which is the honest answer — +# but every WRITER refuses, exit 2, naming the variable and +# the launcher that sets it. +# +# IT ANSWERS AS A PAIR, AND THAT IS NOT A STYLE CHOICE. A caller reads the name +# with `$(lanes_workstation)`, which is a COMMAND SUBSTITUTION and therefore a +# subshell: a global the function set there dies with it. The source is on the +# same line as the name, which is the only way out of a subshell there is. +# +# $LANES_IN_CONTAINER 1 or 0, forcing the probe. THE TEST SEAM, and nothing +# else sets it: the suite must be able to exercise both +# halves of this rule on one host, and the host it runs +# on is a container exactly when it is. +lanes_in_container() { + case "${LANES_IN_CONTAINER:-}" in + 1) return 0 ;; + 0) return 1 ;; + esac + [ -e /.dockerenv ] || [ -e /run/.containerenv ] +} + +lanes_workstation_pair() { + local v + if [ -n "${LANES_WORKSTATION:-}" ]; then + printf '%s\t%s\n' "$LANES_WORKSTATION" seam + return 0 + fi + v="$(hostname -s 2>/dev/null || hostname 2>/dev/null || printf 'unknown')" + if lanes_in_container; then + printf '%s\t%s\n' "$v" container-unset + else + printf '%s\t%s\n' "$v" hostname + fi +} + +# THE NAME ALONE, which is what every writer of the workstation column wants. +lanes_workstation() { lanes_workstation_pair | cut -f1; } + +# The ONE SENTENCE a writer refuses with, in one place, so the three writers +# cannot word it three ways. Empty on every other source, so +# `[ -n "$(lanes_workstation_why "$src")" ]` is the whole of the test. +lanes_workstation_why() { # + [ "${1:-}" = container-unset ] || return 0 + printf '%s\n' "this is a container and \$LANES_WORKSTATION is not set, so there is no workstation name to write. This host's own \`hostname\` is the CONTAINER'S id, not a workstation, and a row on a workstation that does not exist is a row no reader can match — in a log nothing ever rewrites (Amendment 11, decision 8(d); R-A11-14). The value is the workBenches launcher's to export into every session and container it starts. Set it for this one and re-run: export LANES_WORKSTATION=" +} + +# One of the spellings `git remote get-url origin` prints for one GitHub +# repository, reduced to a bare lowercased `/` so it can be +# compared against workspace.yaml's own `/`. A URL that is not +# GitHub's is compared as it stands, lowercased — which is what lets a sandbox +# name a bare local origin and still be checked. +lanes_ws_norm() { + local u="${1%.git}" + case "$u" in + https://github.com/*) u="${u#https://github.com/}" ;; + ssh://git@github.com/*) u="${u#ssh://git@github.com/}" ;; + git@github.com:*) u="${u#git@github.com:}" ;; + esac + printf '%s' "$u" | tr '[:upper:]' '[:lower:]' +} + +# Do these two name one repository? Equal after normalisation, OR the origin's +# path ENDS in the `/` the pointer file spells — which is how a +# GitHub Enterprise host, an ssh alias and a local bare mirror laid out by +# owner and name all say the same thing as `https://github.com//`. +# The pointer file spells `/` because that is what a person types; +# `git remote get-url` spells a URL because that is what git stores. +lanes_ws_same_repo() { + local a b + a="$(lanes_ws_norm "$1")" + b="$(lanes_ws_norm "$2")" + [ -n "$a" ] && [ -n "$b" ] || return 1 + [ "$a" = "$b" ] && return 0 + case "$a" in */"$b") return 0 ;; esac + return 1 +} + +# Prints the workspace checkout's real root, or returns 1 having set +# $LANES_WS_WHY to the one sentence that says which of the five ways it failed. +# ROOT-NESS IS ITS OWN CHECK: `rev-parse --is-inside-work-tree` and +# `remote get-url origin` both succeed from any SUBDIRECTORY of a work tree, so +# a `path:` naming a subdirectory would otherwise be accepted and resolve +# `/lanes/LANES.md` inside the wrong directory. +lanes_workspace_root() { + local yaml repo path origin toplevel real + LANES_WS_WHY="" + if [ -n "${LANES_WORKSPACE_ROOT:-}" ]; then + printf '%s\n' "$LANES_WORKSPACE_ROOT" + return 0 + fi + yaml="$(lanes_ws_yaml)" + if [ ! -r "$yaml" ]; then + LANES_WS_WHY="there is no $yaml" + return 1 + fi + repo="$(lanes_ws_field repository "$yaml")" + path="$(lanes_ws_field path "$yaml")" + if [ -z "$repo" ]; then + LANES_WS_WHY="$yaml names no \`repository:\`" + return 1 + fi + if [ -z "$path" ]; then + LANES_WS_WHY="$yaml names no \`path:\`" + return 1 + fi + if ! git -C "$path" rev-parse --is-inside-work-tree >/dev/null 2>&1; then + LANES_WS_WHY="$yaml names path: $path, which is not a git checkout" + return 1 + fi + origin="$(git -C "$path" remote get-url origin 2>/dev/null || :)" + if ! lanes_ws_same_repo "$origin" "$repo"; then + LANES_WS_WHY="$yaml names repository: $repo, but $path is a checkout of ${origin:-no origin at all}" + return 1 + fi + toplevel="$(git -C "$path" rev-parse --show-toplevel 2>/dev/null || :)" + real="$(cd -- "$path" 2>/dev/null && pwd -P)" || real="" + if [ -z "$real" ] || [ "$toplevel" != "$real" ]; then + LANES_WS_WHY="$yaml names path: $path, which is not the ROOT of that checkout (${toplevel:-unknown} is)" + return 1 + fi + printf '%s\n' "$real" +} + +# The refusal's body, so all four helpers say the same thing in the same words. +# +# THE REASON IS RE-DERIVED HERE, IN THE PARENT SHELL, and that is the whole +# point of this line. Every caller reaches the resolver through a command +# substitution — `LANES_WS_ROOT="$(lanes_workspace_root || :)"` — which runs it +# in a SUBSHELL, so the $LANES_WS_WHY it set died with that subshell and the +# parent still holds the empty string it started with. Six distinct diagnoses +# were being computed and all six were being thrown away; every one of the +# refusals Amendment 9(a) enumerates printed the same "no reason recorded". +# The resolver is read-only and cheap — two `sed`s and three `git` reads — and +# it is reached on the refusal path only, so running it again HERE is the one +# place its answer survives to be printed. +lanes_workspace_why() { + [ -n "$LANES_WS_WHY" ] || lanes_workspace_root >/dev/null 2>&1 || : + printf '%s' "the workspace repository could not be found — ${LANES_WS_WHY:-no reason recorded}. + Amendment 9(a): every lane helper reads \`repository:\` and \`path:\` from + $(lanes_ws_yaml), never from its own location. One command writes that + file, creates or clones the repository and places the symlinks: + openRepoTools wip init" +} +# --- END shared workspace resolver ------------------------------------------ + +# ======================= AMENDMENT 18(a) — WHERE THE LANE IS ================ +# +# **A LANE HAS ONE BINDING, AND THE RECORD SAYS WHERE IT IS.** Ratified +# 2026-09-14T13:15:18Z as revision 4; `brettheap/new-workstation#34`/#35, +# opensoft/openRepoTools#38. Clause (a) gives the lane-kind payload three +# sub-fields beside Amendment 11(c)'s `window`, `dir` and `profile`: +# +# host the MACHINE's short hostname as it reads OUTSIDE any +# container. The launcher exports it (`LANES_HOST`); a +# writer outside a container reads `hostname -s`; a writer +# INSIDE one with no export writes the Rule 10 workstation +# name, because in this estate a workstation is one host and +# a container's own `hostname` is its id. +# os +# the HOST's operating system as the person means it. The +# launcher exports it (`LANES_OS`); with no export the +# kernel is probed: `Darwin` -> macos; `Linux` whose +# `/proc/version` names `microsoft` -> wsl; one naming +# `linuxkit` -> macos (Docker Desktop's VM); any other +# `Linux` -> linux. `windows` is written ONLY by a launcher +# on the Windows host itself — this toolset is bash and runs +# in WSL2 there, so its own probe never says it. +# container +# the bench's name as the launcher exports it +# (`LANES_CONTAINER`: `py-bench`, `cloud-bench`, …); inside +# a container with no export, THAT CONTAINER'S OWN +# `hostname`, which for Docker's default is its id — a true +# name of that container and the one thing that tells two +# unnamed containers apart; outside every container, `none`. +# +# WHY THE RULE EXISTS AT ALL, in the amendment's own words: *"a pid does not +# cross a pid namespace, and the tooling pretends it does."* Two bench +# containers on one host share the profile directory, so pyBench can read a +# session record cloudBench wrote and then `kill -0` a pid in cloudBench's +# namespace — which is either nothing or some other process. A lane live and +# writing in cloudBench reads NOT LIVE from pyBench, and `lane-start` there took +# the name. The three facts are what let a reader say UNKNOWN instead. +# +# READ LIVE, EVERY TIME, AND NEVER CACHED — MEASURED 2026-09-15T12:17Z. This +# bench container was recreated with a new hostname (`cb999b9fd177`) and its +# `~/.local/bin` was wiped with it. A container's `hostname` names THIS +# container for as long as it exists and names nothing afterwards, so it is +# asked at the moment a line is written and is never carried in a variable +# across a run, let alone read back out of a record as though it were the +# workstation's name. A binding written by a container that has since been +# recreated therefore does NOT match this one — which is correct, because its +# pid namespace went with it — and the window-gone exception in clause (b) is +# what makes such a binding readable as dead rather than stranding the lane. +# +# EACH ANSWERS AS A PAIR, ``, for the reason +# `lanes_workstation_pair` states: a caller reads the value with `$( … )`, which +# is a subshell, so a global the function set there dies with it. The source is +# what `workstation` prints in its two new columns. +# +# NOT IN THE SHARED RESOLVER BLOCK ABOVE, deliberately. That block is +# byte-identical in four files and `tests/test_repo_hygiene.py` holds it there; +# these three are read by the WRITER and by the reads built on it, all of which +# are in this file, so a fourth copy would be three more places for one answer +# to be given differently. + +# `hostname -s` where there is one, else `hostname`, else empty. BSD and GNU +# both take `-s`; a busybox one may not, and an empty answer is honest. +lanes_host_probe() { + hostname -s 2>/dev/null || hostname 2>/dev/null || printf '' +} + +lanes_host_pair() { + if [ -n "${LANES_HOST:-}" ]; then + printf '%s\t%s\n' "$LANES_HOST" seam + return 0 + fi + if lanes_in_container; then + # INSIDE A CONTAINER `hostname` IS THE CONTAINER'S ID AND NOT THE HOST'S + # (Amendment 11 decision 8(d), R-A11-14, one field along): the Rule 10 + # workstation name is the host in this estate, so it is what is written. + printf '%s\t%s\n' "$WS" workstation + return 0 + fi + printf '%s\t%s\n' "$(lanes_host_probe)" hostname +} + +# THE KERNEL, PROBED — and `windows` is not one of its answers, which is the +# clause's own sentence and not an omission. +lanes_os_pair() { + if [ -n "${LANES_OS:-}" ]; then + printf '%s\t%s\n' "$LANES_OS" seam + return 0 + fi + lop_u="$(uname -s 2>/dev/null || printf '')" + case "$lop_u" in + Darwin) printf '%s\t%s\n' macos kernel; return 0 ;; + Linux) : ;; + *) printf '%s\t%s\n' linux kernel; return 0 ;; + esac + # `/proc/version` IS ABSENT ON A BSD USERLAND AND THAT IS NOT AN ERROR (#52's + # fixture lesson): the read is guarded, and a Linux kernel naming neither + # string is plain `linux`. + lop_v="" + [ -r /proc/version ] && lop_v="$(cat /proc/version 2>/dev/null || printf '')" + case "$lop_v" in + *microsoft*|*Microsoft*|*WSL*) printf '%s\t%s\n' wsl kernel ;; + *linuxkit*|*Linuxkit*) printf '%s\t%s\n' macos kernel ;; + *) printf '%s\t%s\n' linux kernel ;; + esac +} + +lanes_container_pair() { + if [ -n "${LANES_CONTAINER:-}" ]; then + printf '%s\t%s\n' "$LANES_CONTAINER" seam + return 0 + fi + if lanes_in_container; then + printf '%s\t%s\n' "$(lanes_host_probe)" hostname + return 0 + fi + printf '%s\t%s\n' none outside +} + +# THE ONE FENCE ALL THREE VALUES PASS, and it is Amendment 7(b)'s grammar +# rather than a taste: a sub-field's refs are separated by SPACES and its +# siblings by `; `, the line's fields by `, ` and its free text by ` — `, and +# the log is APPEND-ONLY. A hostname carrying any of those is a line no parser +# can read, for ever. A value that fails is DROPPED with a note (the sub-field, +# never the line — `R-A11-11`'s posture for the swap record, one field along): +# a binding that loses its `container` still says which host it is on, while a +# lane-kind line that was never written loses the lane. +lanes_binding_value_ok() { # + case "${1-}" in + '') return 1 ;; + *[!A-Za-z0-9._:-]*) return 1 ;; + esac + return 0 +} + +# The register is no longer the whole of its own worktree: since Amendment 5 +# it is one file, `lanes/LANES.md`, inside the workspace repository. So every +# git call needs the checkout ROOT and a pathspec RELATIVE to it. Amendment +# 9(a) says where the root comes from; `--show-prefix` still derives the +# pathspec, because `LANES_DIR` may be pointed anywhere by a caller and the +# pathspec must follow it. +# +# RESOLVED HERE, REFUSED LATER. An empty answer is carried rather than fatal, +# so `--help`, the usage and `session-start` — a hook that must exit 0 on a +# machine with no register at all — still run. The refusal is the +# `registry not found` guard below, which is exit 1: the code this script has +# always used for it and the code Amendment 9(a) quotes. +LANES_WS_ROOT="" +if [ -z "${LANES_REPO:-}" ] || { [ -z "${LANES_DIR:-}" ] && [ -z "${LANES_FILE:-}" ]; }; then + LANES_WS_ROOT="$(lanes_workspace_root || :)" +fi +: "${LANES_REPO:=$LANES_WS_ROOT}" +if [ -z "${LANES_DIR:-}" ]; then + if [ -n "${LANES_FILE:-}" ]; then + LANES_DIR="$(dirname -- "$LANES_FILE")" + else + LANES_DIR="${LANES_WS_ROOT:+$LANES_WS_ROOT/lanes}" + fi +fi +LANES_FILE="${LANES_FILE:-$LANES_DIR/LANES.md}" +WS_PAIR="$(lanes_workstation_pair)" +WS="${WS_PAIR%% *}" +WS_SOURCE="${WS_PAIR##* }" +# AMENDMENT 18(a) — THE THREE FACTS BENEATH THE WORKSTATION'S NAME, probed here +# for the READS and probed AGAIN by the writer for every line it appends, and +# always AFTER `WS`, because the `host` fallback inside a container IS the +# workstation's name. Every one of them is a live read of this process's own +# environment and kernel: nothing here is ever taken from a record. +LANES_HOST_NAME=""; LANES_HOST_SOURCE="" +LANES_OS_NAME=""; LANES_OS_SOURCE="" +LANES_CONTAINER_NAME=""; LANES_CONTAINER_SOURCE="" +# ONE FUNCTION PROBES ALL THREE, AND THE WRITER CALLS IT AGAIN AT THE WRITE +# (Copilot round 3 on opensoft/openRepoTools#83). A process-start snapshot is +# what every reader wants — the values cannot change under a short read — but +# the sentence this file makes about them is *"read live at every write and +# never cached"*, and a `request-handoff` can sit in a five-minute wait between +# its start and a later act. The probe is two forks; making the words true costs +# nothing and leaves nothing for a reader to have to reason about. +lanes_binding_probe() { + HOST_PAIR="$(lanes_host_pair)" + LANES_HOST_NAME="${HOST_PAIR%% *}" + LANES_HOST_SOURCE="${HOST_PAIR##* }" + OS_PAIR="$(lanes_os_pair)" + LANES_OS_NAME="${OS_PAIR%% *}" + LANES_OS_SOURCE="${OS_PAIR##* }" + CONTAINER_PAIR="$(lanes_container_pair)" + LANES_CONTAINER_NAME="${CONTAINER_PAIR%% *}" + LANES_CONTAINER_SOURCE="${CONTAINER_PAIR##* }" + # The lower-cased cache the locality rule reads is derived from them, so it + # is dropped here rather than left saying what the probe used to say. + LANES_HOST_LC=""; LANES_WS_LC=""; LANES_CONTAINER_LC="" + return 0 +} +lanes_binding_probe +NO_GIT="${LANES_NO_GIT:-0}" +LOCK="$LANES_DIR/.lanes-edit.lock" +# AMENDMENT 14 — TWO VALUES ONLY THIS PROCESS SETS, AND NEVER THE ENVIRONMENT. +# The index is consulted behind a flag typed for the invocation, "never by +# default, environment or configuration" (clause (b)), and the nudge follows a +# push THIS process made (clause (d)). Both are assigned here unconditionally, +# so an exported variable of either name changes nothing. +LANES_IDX_DIR="" +LANES_INDEX_NUDGE=0 +# AND THE INVENTORY'S OWN TWO (opensoft/openRepoTools#161), for the same reason: +# the `worktrees` table's export directory, set only by `index_open worktrees`, +# and the nudge an inventory write leaves for `cleanup` - set only by a write +# of a lifecycle snapshot or a tree record that this process made. +LANES_WT_IDX_DIR="" +LANES_INDEX_NUDGE_INV=0 +LOCK_HELD=0 +LANES_PATH="${LANES_PATH:-$(git -C "${LANES_DIR:-.}" rev-parse --show-prefix 2>/dev/null || :)${LANES_FILE##*/}}" + +# The pathspecs the current invocation is writing. Every subcommand that +# predates Amendment 7 writes exactly one, the register; a LANDING or LANDED +# writes two. CP_AFTER_REBASE is a function commit_push calls after each +# `pull --rebase`, before it pushes — `claim` uses it to notice that another +# lane's claim landed first. +CP_PATHS=("$LANES_PATH") +CP_AFTER_REBASE="" +# Set by `commit` alone, and never taken from the environment: with nothing +# staged, commit_push publishes the local commits ahead of origin for that one +# write and for no other (#194). +CP_PUBLISH_AHEAD=0 +# A publish's push sends the commit its fence read, `:refs/heads/`; +# empty, every push sends the branch as it stands, as it always has (#194). +CP_PUSH_SPEC="" +CP_FENCE_TIP="" +CP_FENCE_AHEAD=0 + +# die "" [] — the MESSAGE is $1 alone. It used to be "$*", +# which joined the exit code on to the end of every refusal that passed one: +# `… is not a stale claim. 2`. The code is the caller's business and the +# process's, not the reader's; LANES_DEBUG=1 prints it for whoever is debugging +# the codes themselves. +die() { + printf 'lanes-edit: %s\n' "${1-}" >&2 + [ -n "${LANES_DEBUG:-}" ] && printf 'lanes-edit: (exit %s)\n' "${2:-1}" >&2 + exit "${2:-1}" +} +note() { printf 'lanes-edit: %s\n' "$*" >&2; } + +# AMENDMENT 8, ruling (h): THE LOCK NAMES ITS HOLDER, so a lock nobody holds can +# be told from a lock somebody does. The directory alone could only be aged out, +# and ten minutes of every lane on the workstation blocked is not a recovery. +release_lock() { + rm -f -- "$LOCK/pid" 2>/dev/null || : + rmdir -- "$LOCK" 2>/dev/null || : + LOCK_HELD=0 + return 0 +} + +# ====================================================== AMENDMENT 16 ======= +# +# THE RENAME'S UNDO, AND WHY IT IS A TRAP AND NOT A LINE BEFORE EACH `die`. +# +# `rename-lane` is ONE COMMIT, REFUSED OR WHOLE, and its refusals all happen +# before the first byte — but the four MOVES themselves can still fail on a +# filesystem: a `mv` across a mount, a handoff this user may not write, a disk +# that fills between the log and the alias table. Copilot round 1 on +# openRepoTools#81 named the state that left: *"the log has already been moved +# and its `RENAMED` line appended, and this `die` exits without rolling either +# change back"* — a half-renamed checkout, which is exactly what the contract +# says cannot happen and what no re-run can finish. +# +# So the writes are made against a SNAPSHOT taken before the first of them, and +# every exit path between the first write and the commit restores it. It hangs +# off `cleanup`, not off each `die`, for the reason `replace_line` makes +# unavoidable: that function dies inside itself when its own proof fails, and a +# caller cannot put a line after it. `cleanup` runs on EXIT and on the two +# signals, so one hook covers every way out, the shell's included. +# +# THE REGISTER IS NOT IN IT. `replace_line` builds the new file in a temporary +# directory and proves it — one line added, one removed, the same line count — +# BEFORE it writes a byte of `LANES.md`, so the register is never half-written +# and there is nothing there to restore. +RL_ACTIVE=0; RL_SNAP=""; RL_HEAD_BEFORE="" +RL_LOG_OLD=""; RL_LOG_NEW=""; RL_H_OLD=""; RL_H_NEW="" +RL_ALIAS=""; RL_ALIAS_EXISTED=0; RL_REG="" +RL_PATHS_FOR_UNDO=() +rename_undo() { + [ "$RL_ACTIVE" = 1 ] || return 0 + RL_ACTIVE=0 + # A COMMIT THAT EXISTS IS NOT UNDONE. The undo is armed through `commit_push` + # because that function can die before it commits anything; once it HAS + # committed, the four moves are in that commit and restoring the working tree + # would be an inverse change nobody asked for, on top of a commit whose own + # recovery `commit_push` prints. HEAD is the whole test. + if [ -n "$RL_HEAD_BEFORE" ]; then + ru_head="$(git -C "$LANES_REPO" rev-parse HEAD 2>/dev/null || printf '')" + if [ -n "$ru_head" ] && [ "$ru_head" != "$RL_HEAD_BEFORE" ]; then + note "the rename is COMMITTED as $ru_head and is not rolled back; what follows is about getting that commit to origin, and the four files are whole." + return 0 + fi + fi + [ -n "$RL_LOG_NEW" ] && [ -f "$RL_LOG_NEW" ] && rm -f -- "$RL_LOG_NEW" + [ -n "$RL_LOG_OLD" ] && [ -n "$RL_SNAP" ] && [ -f "$RL_SNAP/log" ] && cat -- "$RL_SNAP/log" > "$RL_LOG_OLD" + if [ -n "$RL_H_NEW" ] && [ "$RL_H_NEW" != "$RL_H_OLD" ] && [ -f "$RL_H_NEW" ]; then rm -f -- "$RL_H_NEW"; fi + [ -n "$RL_H_OLD" ] && [ -n "$RL_SNAP" ] && [ -f "$RL_SNAP/handoff" ] && cat -- "$RL_SNAP/handoff" > "$RL_H_OLD" + if [ -n "$RL_ALIAS" ]; then + if [ "$RL_ALIAS_EXISTED" = 1 ]; then + [ -n "$RL_SNAP" ] && [ -f "$RL_SNAP/aliases" ] && cat -- "$RL_SNAP/aliases" > "$RL_ALIAS" + else + rm -f -- "$RL_ALIAS" + fi + fi + # THE REGISTER LAST, and with the `cat >` every writer here uses for it: the + # register reached through `~/projects//LANES.md` is a SYMLINK, and a + # redirect follows it where `mv` or `cp` would replace it with a regular file + # and detach the register from git — the hazard this file's own header opens + # with. + [ -n "$RL_REG" ] && [ -n "$RL_SNAP" ] && [ -f "$RL_SNAP/register" ] && cat -- "$RL_SNAP/register" > "$RL_REG" + # AND THE INDEX WITH IT, because `commit_push` STAGES before it commits: a + # `git add` that succeeded and a `git commit` that did not leaves the four + # paths staged, so restoring only the working tree would leave the rename in + # the index for the next writer to commit by accident. + # THE PATHSPECS STAY AN ARRAY (Copilot round 8 on openRepoTools#81). Flattened + # into one string and expanded unquoted, a handoff under `handoffs/team + # notes/…` — a path this estate supports, and the one every other line here + # quotes — became `handoffs/team` and `notes/…`, two pathspecs that match + # nothing. AND `git reset` SAYS NOTHING ABOUT ONE IT CANNOT MATCH: measured, + # it resets the paths it does match, leaves that file staged and exits 0, so + # the `|| :` above was never reached and no line of output said so. The + # rename then stayed in the index for the next writer to commit by accident, + # which is the half-transaction this whole snapshot exists to prevent. + if [ -n "$RL_REG" ] && [ "$NO_GIT" != 1 ] && [ "${#RL_PATHS_FOR_UNDO[@]}" -gt 0 ]; then + git -C "$LANES_REPO" reset -q HEAD -- "${RL_PATHS_FOR_UNDO[@]}" 2>/dev/null || : + fi + note "the rename was rolled back: the object log, the handoff and ${LANES_ALIASES_PATH:-lanes/aliases.tsv} are as they were, and nothing was committed. A rename is ONE commit, refused or whole (Amendment 16)." + return 0 +} + +# `cleanup`'S TEMPORARIES START EMPTY, so none of them is a path the CALLER +# chose. It runs on every exit and removes each one by name, and a variable +# exported into the environment used to arrive here already set: `rl_htmp` +# made a read-only `canon-lane` delete the file it named, and `TMPD` made it +# `rm -rf` the directory (the reviews of #212 and #213; `pbh_tmp` and `TMPD` +# had the hole before `rl_htmp` joined them). `SE_CACHE_FILE` is assigned only +# at the state-event cache below, so a signal before that line removed what it +# inherited. Every other path `cleanup`, `rename_undo` and `release_lock` +# remove is set above, before the trap: `RL_*`, `LANES_IDX_DIR`, +# `LANES_WT_IDX_DIR`, `LOCK` and `LOCK_HELD`. +TMPD=""; pbh_tmp=""; rl_htmp=""; SE_CACHE_FILE="" +cleanup() { + [ -z "${pbh_tmp:-}" ] || rm -f -- "$pbh_tmp" + [ -z "${rl_htmp:-}" ] || rm -f -- "$rl_htmp" # rename-lane's stamp before its replace (#158) + rename_undo + if [ "$LOCK_HELD" = 1 ]; then release_lock; fi + [ -n "${RL_SNAP:-}" ] && [ -d "${RL_SNAP:-}" ] && rm -rf -- "$RL_SNAP" + [ -n "${TMPD:-}" ] && [ -d "${TMPD:-}" ] && rm -rf -- "$TMPD" + [ -n "${SE_CACHE_FILE:-}" ] && rm -f -- "$SE_CACHE_FILE" "$SE_CACHE_FILE".* 2>/dev/null + [ -n "${LANES_IDX_DIR:-}" ] && [ -d "${LANES_IDX_DIR:-}" ] && rm -rf -- "$LANES_IDX_DIR" + [ -n "${LANES_WT_IDX_DIR:-}" ] && [ -d "${LANES_WT_IDX_DIR:-}" ] && rm -rf -- "$LANES_WT_IDX_DIR" + # AMENDMENT 14(d) — THE NUDGE IS THE LAST THING THIS PROCESS DOES: after the + # lock is released at the top of this function, and only where `commit_push` recorded a push + # that landed - or, opensoft/openRepoTools#161, where an inventory writer + # recorded a snapshot or a tree record it had just replaced. Tested here rather + # than inside the function, because `cleanup` also runs for a process that died + # before `index_nudge` was ever defined. + if [ "${LANES_INDEX_NUDGE:-0}" = 1 ] || [ "${LANES_INDEX_NUDGE_INV:-0}" = 1 ]; then index_nudge; fi + return 0 +} +# AND A SIGNAL ACTUALLY STOPS IT (Amendment 8, ruling (h)). `trap cleanup EXIT +# INT TERM` ran the handler and then CARRIED ON, because a trap that returns +# resumes the command after the one that was interrupted — so a `kill` of a +# writer stuck in `acquire_lock`'s 60-second wait released the lock and then +# went on waiting for it, and a `kill` of one mid-write released the lock while +# it still had the register open. Measured: SIGTERM at 8s, the process still +# running at 56s. The handler now re-raises with the default disposition, which +# is the only way a shell reports "killed by that signal" and the only way the +# process actually stops. +trap cleanup EXIT +trap 'cleanup; trap - INT; kill -INT $$' INT +trap 'cleanup; trap - TERM; kill -TERM $$' TERM + +# A LOCK WHOSE HOLDER IS DEAD IS STALE THE INSTANT ITS PID IS GONE — not ten +# minutes later. A helper killed at a usage reset, or an ssh that took the +# process down with it, leaves a directory no living process will ever remove, +# and until Amendment 8(h) every writer on the workstation waited out the full +# age-out behind it. A lock with NO pid file is from an older version of this +# script and keeps the age test, which is the only thing that could be said +# about it. +lock_steal_if_dead() { + [ -d "$LOCK" ] || return 0 + lsd_pid="$(cat -- "$LOCK/pid" 2>/dev/null || :)" + case "$lsd_pid" in ''|*[!0-9]*) return 0 ;; esac + [ "$lsd_pid" = "$$" ] && return 0 + kill -0 "$lsd_pid" 2>/dev/null && return 0 + note "taking over $LOCK: its holder (pid $lsd_pid) is gone" + rm -f -- "$LOCK/pid" 2>/dev/null || : + rmdir -- "$LOCK" 2>/dev/null || : + return 0 +} + +# THE MUTEX, TAKEN WITHOUT DYING FOR IT — 0 taken, 1 not taken, and no exit +# either way. `acquire_lock` below is this with the refusal on the end, so the +# `mkdir` mutex, the pid test and the age-out are written ONCE and every taker +# of the lock obeys the same three. +# +# THE NON-FATAL FORM IS WHAT THE LIFECYCLE FOLLOW-UP TAKES (openRepoTools#91). +# It runs at the foot of `write_event`, AFTER the event line has landed and been +# committed, and a `die` there would abort a caller whose write is already on +# disk — so the snapshot that could not be taken under the mutex is left alone +# and SAID, exactly as a snapshot that could not be written is. +lock_try() { # [] + lt_max="${1:-60}" + lock_steal_if_dead + # Stale lock (>10 min) is removed: a helper run never takes that long. The + # age test is now the FALLBACK — the pid test above is the real one. + if [ -d "$LOCK" ]; then + if [ -z "$(find "$LOCK" -maxdepth 0 -mmin -10 2>/dev/null)" ]; then + note "removing stale lock $LOCK" + rm -f -- "$LOCK/pid" 2>/dev/null || : + rmdir -- "$LOCK" 2>/dev/null || : + fi + fi + lt_i=0 + while [ "$lt_i" -lt "$lt_max" ]; do + if mkdir -- "$LOCK" 2>/dev/null; then + LOCK_HELD=1 + printf '%s\n' "$$" > "$LOCK/pid" 2>/dev/null || : + return 0 + fi + lock_steal_if_dead # it may have died while we were waiting + lt_i=$((lt_i + 1)) + sleep 1 + done + return 1 +} + +acquire_lock() { + lock_try 60 && return 0 + die "could not acquire $LOCK after 60s — another lanes-edit run is active (holder pid $(cat -- "$LOCK/pid" 2>/dev/null || printf 'unrecorded'))" 4 +} + +# ---------------------------------------------------------------- row lookup + +# AMENDMENT 15 — A LANE NAME IS ONE NAME UNDER ANY CASE, AND THE ROW'S SPELLING +# IS THE ONE IT CARRIES (ratified 2026-09-14T00:07:18Z). +# +# Every spelling the WORKING TREE's register carries for a name, compared +# case-insensitively, one per line. This is the set `row_line` counts and the +# set every refusal below NAMES: at 2026-09-13T23:51:56Z a `lane-start +# openxfactory 2` typed in lowercase for the lane `openXfactory-2` found NO row +# here — the row key was the one exact comparison left in this file — and +# appended a SECOND row for a lane that had run since 2026-09-02, while its +# object log went on into the one file both spellings had always shared. +rows_named_ci_local() { # + awk -v want="$1" ' + substr($0,1,1) == "|" { + p1 = index($0, "`"); if (p1 == 0) next + rest = substr($0, p1 + 1); p2 = index(rest, "`"); if (p2 == 0) next + t = substr(rest, 1, p2 - 1) + if (tolower(t) == tolower(want)) print t + }' "$LANES_FILE" +} + +# Prints the 1-based line number of the row whose FIRST backticked token is the +# lane name, COMPARED CASE-INSENSITIVELY (Amendment 15). Exactly one match is +# required — and where there are two, that is the amendment's own refusal and +# not a puzzle about which row to edit: 15(d) says the two are merged into one, +# by hand, in a commit that names both spellings. +# +# THE LINE IT RETURNS IS STILL THE EXACT LINE. What changed is how the line is +# FOUND; every editor above still rewrites that one line byte for byte, so a row +# spelled `openXfactory-2` keeps its spelling when a caller typed the lowercase +# form. Which spelling gets WRITTEN into new text is `canon_lane`'s answer, one +# function along. +row_line() { + lane="$1" + hits="$( + awk -v lane="$lane" ' + substr($0,1,1) == "|" { + p1 = index($0, "`") + if (p1 == 0) next + rest = substr($0, p1 + 1) + p2 = index(rest, "`") + if (p2 == 0) next + if (tolower(substr(rest, 1, p2 - 1)) == tolower(lane)) print NR + }' "$LANES_FILE" + )" + n="$(printf '%s' "$hits" | grep -c . || :)" + if [ "$n" != 1 ]; then + # NOTE: row_line runs inside $( ), so it must RETURN, not exit — an `exit` + # here would only leave the command substitution's subshell and the caller + # would carry on with an empty line number. + note "expected exactly 1 row for lane '$lane', found $n${hits:+ (lines: $(printf '%s' "$hits" | tr '\n' ' '))}" + if [ "$n" -gt 1 ]; then + note "those rows are spelled $(rows_named_ci_local "$lane" | tr '\n' ' ')— a lane name is ONE name under any case (Amendment 15), so merge them into one row (Amendment 15(d)): append the newer row's session id(s) to the older row's session cell, in order, and remove the newer row in the SAME commit" + fi + return 2 + fi + printf '%s' "$hits" +} + +count_occurrences() { # $1=haystack $2=needle + hay="$1"; needle="$2"; c=0 + if [ -z "$needle" ]; then note "empty search string"; return 2; fi + while :; do + case "$hay" in + *"$needle"*) c=$((c + 1)); hay="${hay#*"$needle"}" ;; + *) break ;; + esac + done + printf '%s' "$c" +} + +# A row split into HEAD (everything up to and including the SECOND `|`), the +# SESSION CELL, and TAIL (from the THIRD `|` on) — the three pieces +# `append-session-id` needs, and the only safe way to reach cell 3 of a row +# whose LATER cells may contain a literal `|` (the live register has two such +# rows). It splits from the LEFT for that reason, never from NF. The three +# pieces are asserted to reassemble into the row before anything is written. +RSC_HEAD=""; RSC_CELL=""; RSC_TAIL="" +row_split_session_cell() { # + rsc_row="$1"; RSC_HEAD=""; RSC_CELL=""; RSC_TAIL="" + case "$rsc_row" in *"|"*) : ;; *) return 1 ;; esac + rsc_rest="${rsc_row#*|}" # after the 1st | + case "$rsc_rest" in *"|"*) : ;; *) return 1 ;; esac + rsc_rest2="${rsc_rest#*|}" # after the 2nd | + case "$rsc_rest2" in *"|"*) : ;; *) return 1 ;; esac + RSC_CELL="${rsc_rest2%%|*}" + RSC_TAIL="|${rsc_rest2#*|}" + RSC_HEAD="${rsc_row%%|*}|${rsc_rest%%|*}|" + [ "$RSC_HEAD$RSC_CELL$RSC_TAIL" = "$rsc_row" ] || return 1 + return 0 +} +rstrip_spaces() { s="$1"; while [ "${s% }" != "$s" ]; do s="${s% }"; done; printf '%s' "$s"; } + +# --------------------------------------------- AMENDMENT 13: THE ROW IS STATE +# +# **THE ROW IS THE LANE'S CURRENT STATE, ONE LINE A PERSON CAN READ; ITS HISTORY +# IS THE LANE'S OWN LOG** — lane-collision-protocol Amendment 13, in force +# 2026-09-13T21:08:36Z. Clause (a): the `state` column holds ONE PHRASE, +# ` · · `, and every write REPLACES it. `set-row-state` +# is the writer; `append-row-status` is RETIRED, so the cell can never grow into +# a diary again. Measured on the day the amendment was drafted: the register was +# 1,141,283 bytes over 46 rows, its longest row 96,228 characters, and this +# lane's own cell 7,016 characters after ONE day of appending. +# +# WHERE THE CELL IS: SPLIT THE ROW ON ` | `, AND SIX SEPARATORS ARE THE PROOF. +# A seven-column row has exactly six of them, and then the two readings of the +# row — count six from the left, take the last cell from the right — are the +# same text. A row with MORE has a ` | ` inside one of its cells, and nothing +# here can tell WHICH cell it is in: the two readings disagree, and one of them +# writes the new state over the row's handoff path. So more than six is a +# REFUSAL naming the row, never a choice between them. +# +# MEASURED ON THE LIVE REGISTER, 2026-09-15 (1,335,595 bytes, 52 rows): 50 of +# them carry exactly six separators and split cleanly. `openXfactory-2` carries +# seven — one of them is inside its `objects owned` cell, so the two readings +# disagree about the HANDOFF PATH — and `openxfactory-4` eight, both inside its +# state cell. Those two are refused by name, and the fix is a person's: escape +# the pipe as `\|`, which is how a Markdown table carries a literal one, in a +# hand edit wrapped by `lanes-edit.sh commit`. A BARE `|` THAT IS NOT SPELLED +# ` | ` IS HARMLESS and stays inside whichever cell holds it: the state cells of +# `openRepoProject-1` and `openRepoTools-3` carry nineteen and four of them +# (`'| true'`, a quoted shell fragment), and both of those rows split exactly. +# +# It splits from the LEFT for the reason `row_split_session_cell` does — the +# cells that may carry a stray separator are the free-text ones at the end — and +# the three pieces are asserted to reassemble into the row before anything is +# written. +RSS_HEAD=""; RSS_CELL=""; RSS_TAIL="" +row_split_state_cell() { # — 0 with the pieces · 1 not a row · 2 ambiguous + rss_row="$1"; RSS_HEAD=""; RSS_CELL=""; RSS_TAIL="" + case "$rss_row" in "|"*) : ;; *) return 1 ;; esac + rss_body="$(rstrip_spaces "$rss_row")" + case "$rss_body" in *"|") : ;; *) return 1 ;; esac + # `${row:N}` AND NEVER `${row#"$body"}`. Removing a literal prefix walks every + # prefix length in turn, so a 90,751-character row cost ELEVEN SECONDS in that + # one expansion — measured 2026-09-15 against the live register's longest row, + # and it is the whole of what made a dry run of the migration take a minute + # and a half. A substring by offset is linear, and both `${#s}` and `${s:n}` + # count CHARACTERS, so the two agree on a row full of `·`, `—` and `→`. + rss_pad="${rss_row:${#rss_body}}" # the row's own trailing spaces, kept + rss_inner="${rss_body%|}" # everything before the closing pipe + rss_n="$(count_occurrences "$rss_inner" " | ")" || return 1 + [ "$rss_n" = 6 ] || return 2 + rss_rest="$rss_inner"; rss_head=""; rss_i=0 + while [ "$rss_i" -lt 6 ]; do + rss_one="${rss_rest%% | *}" + rss_head="$rss_head$rss_one | " + rss_rest="${rss_rest:$(( ${#rss_one} + 3 ))}" # 3 = the separator + rss_i=$((rss_i + 1)) + done + RSS_HEAD="$rss_head"; RSS_CELL="$rss_rest"; RSS_TAIL="|$rss_pad" + [ "$RSS_HEAD$RSS_CELL$RSS_TAIL" = "$rss_row" ] || { RSS_HEAD=""; RSS_CELL=""; RSS_TAIL=""; return 1; } + return 0 +} + +# How many ` | ` a row carries, for the refusal above to be able to say so. +row_sep_count() { # + count_occurrences "$(rstrip_spaces "$1")" " | " 2>/dev/null || printf '?' +} + +# Clause (a)'s seven states, and O1's cap on the one line beside them. +ROW_STATES='LIVE, PAUSED, LANDING #, LANDED, ENDED, RETIRED, HANDED OFF' +ROW_STATE_CAP=240 +ROW_STATE=""; ROW_STATE_LINE="" +state_word_is_valid() { # + case "${1-}" in + LIVE|PAUSED|LANDED|ENDED|RETIRED|'HANDED OFF') return 0 ;; + 'LANDING #'*) + # Rule 6's reading of the cell is unchanged by Amendment 13 and is now the + # whole of what the cell says at that moment, so the number is checked: + # `LANDING #` with nothing after it is a merge hold no lane can pair with + # a PR. + case "${1#LANDING #}" in + '' | *[!0-9]*) return 1 ;; + *) return 0 ;; + esac ;; + esac + return 1 +} + +# ` · ` → ROW_STATE and ROW_STATE_LINE, or a refusal. Every +# test is made BEFORE the lock and before the row is touched, so a refusal +# leaves the register exactly as it found it. +row_state_check() { # " · " + rst_in="${1-}"; ROW_STATE=""; ROW_STATE_LINE="" + case "$rst_in" in + *' · '*) : ;; + *) die "the phrase is ' · ' and this carries no ' · ' separator: '$rst_in'. The STATE is one of $ROW_STATES; the line says what the last act was, in at most $ROW_STATE_CAP characters. The narrative goes to the lane's own log — \`log NOTED\` / \`log RULED\` (Amendment 13(b))." 2 ;; + esac + ROW_STATE="${rst_in%% · *}" + ROW_STATE_LINE="${rst_in#* · }" + state_word_is_valid "$ROW_STATE" || + die "'$ROW_STATE' is not one of Amendment 13(a)'s states ($ROW_STATES). The cell is the lane's CURRENT STATE and nothing else, so an eighth word is a state no reader of Rule 6 or of the listing knows." 2 + [ -n "$ROW_STATE_LINE" ] || + die "the phrase is ' · ' and the line is empty: say what the last act was. A state with no line is a cell a person cannot read anything out of." 2 + case "$ROW_STATE_LINE" in + *' · '*) die "the line may not contain ' · ': that separator is what divides the cell's three parts — ' · · ' — and a second one inside the line reads back as a fourth part. Use a semicolon: '$ROW_STATE_LINE'" 2 ;; + *'|'*) die "the line may not contain '|': it would forge a cell boundary in the row, which is the one edit no reader of the register could recover from. Got: '$ROW_STATE_LINE'" 2 ;; + esac + if [ "${ROW_STATE_LINE//[$'\n\r']/}" != "$ROW_STATE_LINE" ]; then + die "the line is ONE line: a newline in it would split the row in two and every row after it would be read as a lane" 2 + fi + # THE MARKER'S VOCABULARY IS NOT A LEGACY WRITER'S TO WRITE (ruling + # 2026-10-04). The projection reader matches it anywhere in a row, so a + # phrase carrying it would make this lane read as managed, or as UNKNOWN. + if managed_projection_hint "$rst_in"; then + die "the phrase carries managed-owner vocabulary ('managed owner', 'managed binding', 'mode=managed' or 'managed:'), and only the managed ledger's own writer writes a managed-owner marker, and a legacy writer that wrote its vocabulary into a row would forge that lane's ownership (ruling 2026-10-04: \"managed ledger owns enrolled lanes; #97 owns legacy\"). Reword it: '$rst_in'" 2 + fi + # ${#s} COUNTS CHARACTERS and the cap is O1's 240 of them — these lines are + # full of `·`, `—` and `→`, so a byte count would refuse a line that is inside + # the cap and accept one that is not. + [ "${#ROW_STATE_LINE}" -le "$ROW_STATE_CAP" ] || + die "the line is ${#ROW_STATE_LINE} characters and the cap is $ROW_STATE_CAP (Amendment 13, ratified decision O1). Shorten it, and put what will not fit in the lane's own log, which is where the history lives: LANES_LANE= lanes-edit.sh log NOTED lane: \"\"" 2 + return 0 +} + +# Prints the row's OWN spelling of a lane name that matches $1 ignoring case, +# when exactly one row does. Attribution only — never used to pick the line an +# edit rewrites, which stays exact-match. Rule 10's wire form is lowercase +# (`Lane: openxfactory-2`) while the row's token may be camel (`openXfactory-2`), +# so an exact lookup alone loses the author of a Rule 6 line. +row_lane_ci() { + awk -v want="$1" ' + substr($0,1,1) == "|" { + p1 = index($0, "`"); if (p1 == 0) next + rest = substr($0, p1 + 1); p2 = index(rest, "`"); if (p2 == 0) next + t = substr(rest, 1, p2 - 1) + if (tolower(t) == tolower(want)) { n++; hit = t } + } + END { if (n == 1) print hit }' "$LANES_FILE" +} + +# A Rule 6 line names its own lane in its text — "LANDING — lane , …", +# "LANDED — lane (), …". `append-line` takes no lane argument, +# so with LANES_LANE unset it used to commit as LANES(unknown@) and the +# line's author was lost from the log (this predates Amendment 5: the same +# `${LANES_LANE:-unknown}` is in the pre-move script). Read the name out of +# the text instead, and fall back to unknown only when there is nothing to +# read. Anything outside [A-Za-z0-9._-] is rejected rather than sanitised, +# and the caller checks the candidate against the register's own rows before +# trusting it — "…names no lane at all" must not be attributed to a lane +# called "at". +lane_from_text() { + t="$1"; l="" + case "$t" in + *"lane "*) + l="${t#*lane }" + l="${l%%[ ,;:)]*}" + l="${l//\`/}" + ;; + esac + case "$l" in + "" | *[!A-Za-z0-9._-]*) printf '' ;; + *) printf '%s' "$l" ;; + esac +} + +# --------------------------------------------------------------- file writes + +# THE REGISTER IS REWRITTEN IN TWO PLACES, `replace_line` AND `delete_lines`, +# AND BOTH PROVE WHAT THEY COPIED AND WHAT LANDED (opensoft/openRepoTools#120 +# item 1, Copilot round 5 on #93). The appends below them prove their result +# with `cmp`; the rewrites proved only the file they built, and two steps of +# theirs were never checked at all: +# +# * THE COPY. Every proof of a rewrite (the line count, `numstat`, the no-op) +# is made against `$pre`, a `cat` of the register into a temporary file, and +# that `cat` had no status. A copy that came out short (a full temporary +# filesystem, a read that failed part-way) made a SHORT register look like a +# one-line edit of itself: every proof passed and the short copy was written +# back as the register and committed. Measured at 5e88a2c with the copy cut +# at half its lines: a 156,611-byte register rewritten as 78,306, exit 0. +# * THE WRITE. `cat -- > LANES.md` had its status read and not its +# result, and `>` TRUNCATES before `cat` writes a byte. A write that failed +# part-way left a half register behind a refusal that called it UNCHANGED, +# and one that came out short and said nothing was a half register +# committed. Even an uncommitted half register is one write from being +# published: the next writer in this checkout commits a dirty register as a +# peer's pre-existing edit (`handle_preexisting`). +# +# So the copy is compared with the register and the result with what was built. +# Where the result is not what was built, the copy's bytes are put back and +# proved before the refusal (5) says which of the two the register now holds. +# Both still write through `cat` and a redirection, which FOLLOW a symlinked +# register; a rename beside it would replace the link with a file. +# +# A REFUSAL SAYS WHAT IS ALREADY ON DISK (the review of #263, S2). The sweeps +# write their logs, their archive and their earlier rows before a row's +# rewrite, so a refusal that said "Nothing was written" was false there: `git +# status` showed those files, and a re-run read them back. What holds is that +# THIS ACT has committed nothing — not "nothing has been committed": a peer's +# uncommitted register edit found first is captured as a commit of its own +# (`handle_preexisting`) before the act's edit, and the one caller that HAS +# committed when it rewrites (add-row's after-rebase take-back) says so through +# `REG_COMMITTED_HERE` (the delta review of #263). Each sweep names its local +# writes with `reg_wrote`, which the refusals list. AND WHERE THE REGISTER MAY +# BE TRUNCATED the copy is KEPT (S2's NIT 6): it is the only exact copy of the +# register as it was, uncommitted edits included, and the exit trap removes +# `$TMPD`. So it is copied into the checkout's own git directory — mode 0600, +# under a name nothing else holds, proved byte for byte — where a restart that +# empties the temporary directory leaves it; only where that cannot be done is +# it renamed beside `$TMPD` instead (a rename needs no free space). +REG_WRITTEN_HERE="" +REG_COMMITTED_HERE="" +DL_SAYS_UNCHANGED="" +DL_SAYS_AFTER_WRITE="" +reg_wrote() { # + REG_WRITTEN_HERE="$REG_WRITTEN_HERE, $1" +} +reg_committed() { # — what this act has committed, as a refusal says it + printf '%s' "${REG_COMMITTED_HERE:-this act has committed nothing}" +} +reg_written_here() { # — the sentence a refusal ends with, or nothing + [ -n "$REG_WRITTEN_HERE" ] || return 0 + printf ' This act has already written, in this checkout and NOT committed: %s. `git -C %s status` shows them; commit or undo them before re-running.' \ + "${REG_WRITTEN_HERE#, }" "$LANES_REPO" +} +register_copy() { # + cat -- "$LANES_FILE" > "$1" && cmp -s -- "$LANES_FILE" "$1" || + die "the register at $LANES_FILE could not be copied whole to $1, and every proof of this edit is made against that copy: a short one would make a short register look like a one-line edit of itself. The register is as it was and $(reg_committed): $2.$(reg_written_here)" 5 +} +register_rewrite() { # + cat -- "$2" > "$LANES_FILE" && cmp -s -- "$LANES_FILE" "$2" && return 0 + if cmp -s -- "$LANES_FILE" "$1"; then + die "could not write the rewritten register $LANES_FILE: the write did not reach it, and it is byte for byte as it was before this edit. $3$(reg_written_here)" 5 + fi + if cat -- "$1" > "$LANES_FILE" && cmp -s -- "$LANES_FILE" "$1"; then + die "the rewritten register $LANES_FILE did not land as it was written: the write cut it short, and its earlier bytes have been put back and proved. $3$(reg_written_here)" 5 + fi + rgw_keep=""; rgw_where="" + rgw_git="$(git -C "$LANES_REPO" rev-parse --absolute-git-dir 2>/dev/null)" || rgw_git="" + if [ -n "$rgw_git" ] && [ -d "$rgw_git" ]; then + rgw_to="$rgw_git/lanes-edit-register-before-edit.$(date -u +%Y%m%dT%H%M%SZ).$$" + if [ ! -e "$rgw_to" ] && [ ! -L "$rgw_to" ]; then + if ( umask 077 && set -C && cat -- "$1" > "$rgw_to" ) 2>/dev/null && cmp -s -- "$1" "$rgw_to"; then + rgw_keep="$rgw_to" + else + rm -f -- "$rgw_to" 2>/dev/null || : + fi + fi + fi + if [ -z "$rgw_keep" ]; then + rgw_to="${1%/*}.register-before-edit" + if [ ! -e "$rgw_to" ] && [ ! -L "$rgw_to" ] && chmod 600 -- "$1" 2>/dev/null && mv -- "$1" "$rgw_to" 2>/dev/null; then + rgw_keep="$rgw_to" + rgw_where=" That is the temporary directory, because the checkout's git directory could not take the copy: a restart that empties it loses them, so restore them first." + fi + fi + if [ -n "$rgw_keep" ]; then + rgw_copy="Its exact bytes from before this edit, with any uncommitted edit they held, are kept in $rgw_keep (mode 0600; \`cat -- $rgw_keep > $LANES_FILE\` puts them back, and \`git -C $LANES_REPO diff -- $LANES_PATH\` shows what it lost meanwhile); \`git checkout\` would bring back only its last commit and drop any uncommitted edit.$rgw_where" + else + rgw_copy="Its bytes from before this edit could not be kept either: \`git -C $LANES_REPO diff -- $LANES_PATH\` shows what it lost, and \`git -C $LANES_REPO checkout -- $LANES_PATH\` brings back its last commit, dropping any uncommitted edit it held." + fi + die "could not write the rewritten register $LANES_FILE, and the bytes it had before this edit could not be put back either: IT MAY NOW BE TRUNCATED. Restore it before any other write in $LANES_REPO, because the next one would commit it as a pre-existing edit. $rgw_copy $3$(reg_written_here)" 5 +} + +# Replace line N with $2, leaving every other byte untouched. Verified with +# `git diff --no-index --numstat` (must be exactly 1 added / 1 deleted). +replace_line() { + n="$1"; newline="$2" + # 1 where the line was already exactly what was asked for and nothing was + # written. A caller that prints what it did reads this rather than announcing + # a replacement that did not happen. + REPLACE_LINE_NOOP=0 + TMPD="$(mktemp -d)" + pre="$TMPD/pre"; out="$TMPD/out" + register_copy "$pre" "its line $n is as it was and this edit is not made" + before="$(wc -l < "$pre" | tr -d ' ')" + { + [ "$n" -gt 1 ] && head -n "$((n - 1))" -- "$pre" + printf '%s\n' "$newline" + tail -n "+$((n + 1))" -- "$pre" + } > "$out" + after="$(wc -l < "$out" | tr -d ' ')" + [ "$before" = "$after" ] || die "line count changed ($before -> $after); refusing" 5 + # A LINE THAT IS ALREADY EXACTLY WHAT WAS ASKED FOR IS A WRITE THAT IS DONE, + # AND NOT A PROOF THAT FAILED (measured 2026-09-16, `lanes-edit.sh`). The + # `numstat` below proves this edit touched ONE line by demanding `1 1` from + # `git diff --no-index` — and an edit that changes nothing produces NO OUTPUT + # AT ALL, so `$stat` came back empty, the equality was false, and the act + # died 5 with `numstat: none`. The guard read "nothing changed" as "more than + # one line changed", which are opposite facts. + # + # IT IS REACHED BY ORDINARY USE AND NOT BY A CONTRIVANCE. `set-row-state` + # writes ` · $(utc_now) · ` and `utc_now` is seconds, so two + # stamps of the SAME state phrase inside one second are byte-identical — two + # `lane-start --no-launch` runs of one lane in one window, which is exactly + # what `tests/test_lane_helpers.sh`'s Amendment 15 `--confirm` case does, and + # what made it fail about one run in two with `expected [0], got [5]`. On a + # workstation it is a lane stamped twice in a second being told its write was + # refused, when the register already says precisely what the caller asked for. + # + # THE CALLERS ARE SAFE WITH IT: nothing is written, so `commit_push` finds + # nothing staged and says so on its own line, and every one of the four + # callers (`set-row-state`, `append-session-id`, `replace-in-row` and + # `migrate-state-cells`) wanted the file to SAY something rather than to + # differ from what it said. Nor does it push: a write with nothing staged + # publishes nothing, whatever this shared checkout has queued ahead of + # origin; only `commit` does that, and only what its path filter passes (#194). + if cmp -s -- "$pre" "$out"; then + REPLACE_LINE_NOOP=1 + note "line $n of $LANES_FILE is already exactly what this write asked for — nothing rewritten, and nothing to commit" + return 0 + fi + stat="$(git --no-pager diff --no-index --numstat -- "$pre" "$out" 2>/dev/null | head -n1 | cut -f1,2)" + [ "$stat" = "$(printf '1\t1')" ] || die "edit touched more than one line (numstat: ${stat:-none}); refusing" 5 + # THE WRITE IS CHECKED (Copilot round 3 on openRepoTools#81). `cat > file` + # here is the last act of every row edit in this file — `append-row-status`, + # `replace-in-row`, `append-session-id` and Amendment 16's `rename-lane` — + # and unchecked it returns 0 having written NOTHING when `LANES.md` is not + # writable: the two proofs above pass (they are made against a temporary + # file), the note says the line was rewritten, and the caller commits whatever + # else it changed. For a rename that is the alias landing while the row it + # points at never moves. AND ITS RESULT IS PROVED, not only its status, with + # the register put back where the write cut it short (#120 item 1, above). + register_rewrite "$pre" "$out" "Its line $n is not rewritten, and $(reg_committed)." + note "line $n rewritten in $LANES_FILE" +} + +# LINES REMOVED AND NOTHING ELSE TOUCHED — `replace_line`'s proof, for the one +# act that takes rows OUT of the register (Amendment 19(d): `archive-rows` +# MOVES a repository's RETIRED rows to `lanes/archive/LANES-retired.md`). The +# rows are appended to the archive FIRST and removed here second, so a refusal +# between the two leaves the register whole and the archive holding a copy — +# never the other way round, which would be the one order that loses a row. +# +# THE NUMBERS ARE THE PROOF: exactly N fewer lines, and `git diff --numstat` +# showing N deleted and ZERO added. A deletion that also rewrote a line would +# pass a line count and fail this. +delete_lines() { # + dl_list="$1" + dl_n="$(printf '%s\n' "$dl_list" | grep -c . || :)" + [ "$dl_n" -gt 0 ] || return 0 + TMPD="$(mktemp -d)" + dl_pre="$TMPD/pre"; dl_out="$TMPD/out" + # WHAT A REFUSAL HERE SAYS ABOUT THE ROWS IS THE CALLER'S (the delta review of + # #263, NIT). archive-rows' sentences are the default: its rows are already in + # the archive. add-row's take-back passes its own, because there the row is + # add-row's committed one and no archive is involved. + dl_unchanged="${DL_SAYS_UNCHANGED:-no row was removed, the rows are in $LANES_ARCH_PATH, and the register is whole}" + dl_after_write="${DL_SAYS_AFTER_WRITE:-The archive may have been appended locally, but $(reg_committed); resolve that partial move before retrying.}" + register_copy "$dl_pre" "$dl_unchanged" + # AND EVERY LATER REFUSAL HERE SAYS IT AS WELL (delta review 4 of #263, N1 + # and S4's N2). The pass, the line count and `numstat` below refused with no + # word of what the act had committed: add-row's take-back, which HAS committed + # its row, died saying only "the removal added or rewrote lines" or "that row + # is still in it and in that commit", with no row and no commit named, and the + # next write published the row. Each now ends as `register_copy`'s refusal + # does: the register as it was, what this act has committed, the caller's + # sentence, and what the act has already written in this checkout. + dl_as_was="The register is as it was and $(reg_committed): $dl_unchanged.$(reg_written_here)" + dl_before="$(wc -l < "$dl_pre" | tr -d ' ')" + # `awk -v` CARRIES ONE LINE, AND THIS LIST IS MANY — the finding `who_landing` + # took in round 5 of A9 Addendum 4 (R-A9-11), re-made here and answered by + # `tests-macos` at `758a536` with six red lines and nothing saying why. A + # `-v name=value` is processed as if it were a STRING LITERAL, and a string + # literal cannot span lines: macOS's awk (one-true-awk) refuses it outright — + # `awk: newline in string … at source line 1`, exit 2, NO OUTPUT AT ALL — + # while gawk and mawk accept it silently, so no Linux job and no workstation + # here can see it. What it cost is exactly what it cost there: an empty + # `$dl_out`, a line count that fails its own proof, and `archive-rows --yes` + # dying 5 with the rows already in the archive and the register untouched. + # `ENVIRON` has no such restriction and is POSIX awk, so the list goes through + # the environment of this one command, which is the spelling `who_landing` + # settled on. Asserted on every platform by a shim that IS the one-true-awk + # rule (`tests/test_lane_helpers.sh`, the `repo19d` case). + # + # AND THE PASS IS READ WITH ITS OWN STATUS. An awk that failed writes an empty + # file, and an empty file is not "no rows matched" (Amendment 7(d)) — it is a + # read that failed, and it must say so rather than arrive at the line-count + # proof as a wrong number, which is the shape the macOS job had to be + # reverse-engineered from. + if ! LANES_DROP_LINES="$dl_list" awk ' + BEGIN { k = split(ENVIRON["LANES_DROP_LINES"], a, "\n") + for (i = 1; i <= k; i++) if (a[i] != "") drop[a[i] + 0] = 1 } + !(NR in drop)' "$dl_pre" > "$dl_out"; then + die "the pass that removes $dl_n row(s) from $LANES_FILE failed, so what the register would become is not known — and that is not an empty register (Amendment 7(d)). $dl_as_was" 5 + fi + dl_after="$(wc -l < "$dl_out" | tr -d ' ')" + [ "$dl_after" -eq "$((dl_before - dl_n))" ] || + die "removing $dl_n row(s) changed the line count by $((dl_before - dl_after)); refusing. $dl_as_was" 5 + # AND IT COUNTS LINES WHATEVER THE REGISTER'S SIZE (delta review 4 of #263, + # S4). Under a `core.bigFileThreshold` below the register's size git classes + # both copies as binary, and `numstat` prints a `-` for each count, which + # `--text` does not change: add-row's take-back refused there, and its row + # stayed committed for the next write to publish. A `-c` on the command line + # outranks every config file and `GIT_CONFIG_*` in the environment (measured + # on git 2.43). An attribute or a NUL byte that classes the copies as binary + # still makes this proof refuse, in the words above. + dl_stat="$(git --no-pager -c core.bigFileThreshold=2g diff --no-index --numstat -- "$dl_pre" "$dl_out" 2>/dev/null | head -n1 | cut -f1,2)" + [ "$dl_stat" = "$(printf '0\t%s' "$dl_n")" ] || + die "the removal added or rewrote lines (numstat: ${dl_stat:-none}); refusing. $dl_as_was" 5 + # The redirection follows the register symlink, but its status is still a + # write fence. An unwritable target must not let archive-rows commit the + # appended archive while the source rows remain in the register. And its + # RESULT is the fence as well, with the register put back where the write cut + # it short (#120 item 1, above `replace_line`). + register_rewrite "$dl_pre" "$dl_out" "$dl_after_write" + note "$dl_n row(s) removed from $LANES_FILE" +} + +# $2 is the file to append to, defaulting to the register. Amendment 7's +# per-lane object logs are appended with exactly the same proof — one line +# more, not one existing byte different. +append_text_line() { + newline="$1"; target="${2:-$LANES_FILE}" + # ONE LINE IS REFUSED A NEWLINE BEFORE IT IS WRITTEN, NOT PROVED ONE AFTER + # (opensoft/openRepoTools#85). The proofs below are made AFTER the `>>`, so a + # text carrying a newline was appended whole — two physical lines where one + # was meant — and only then refused: `append changed line count by 2`, exit + # 5, the file left modified and uncommitted. What came next was worse than + # the refusal. A dirty object log is refused by every later writer in that + # checkout; a dirty REGISTER is committed by the next one, as a peer's + # `pre-existing` edit (`handle_preexisting`) — measured in `lane-handoff`'s own + # flow, where the row flip right after the refused PAUSED line committed the + # two lines. A carriage return is refused with it: `wc -l` does not count one, so it + # passed the proof and put a line no reader splits the same way into a file + # nothing rewrites. `write_event` has refused both since R21; this is the + # same gate in the one function every append goes through, which is the + # reason this file gives for putting the container guard at the dispatcher: + # *"nine copies of one rule is how eight of them would come to disagree"*. + # FIRST, before the `mktemp` and the copy, so a refusal touches nothing. + if [ "${newline//[$'\n\r']/}" != "$newline" ]; then + die "an appended line is ONE line, and this text carries a newline or a carriage return: appended, it would put several lines into $target where one was meant, and the proof that only one was added fails after the write, not before it. Nothing was written. Spell the break '; ' and re-run." 2 + fi + TMPD="$(mktemp -d)" + pre="$TMPD/pre" + cat -- "$target" > "$pre" + # `| tr -d ' '`, THE SPELLING `park:564` AND `status:746` ALREADY USE — and + # the one function that did not use it was the macOS job's LARGEST SINGLE + # CAUSE (A9 Addendum 4, R-A9-11). BSD `wc` right-aligns every count in a + # fixed-width field, so `wc -l < f` answers `" 5"` on macOS where GNU + # answers `"5"`, while `$((before_lines + 1))` is arithmetic and is never + # padded. `[ " 5" = "5" ]` is FALSE — so on BSD this refused EVERY + # append it was ever asked to make, and refused it HAVING ALREADY APPENDED: + # the `>>` on the line between them had run, so the `die` left the file + # modified and uncommitted, and then every later `lanes-edit.sh` in that + # checkout refused as well (`unstaged tracked change — so the race cannot be + # run safely here`, 48 times in the macOS transcript at `9000e86`). The + # message it died with read `append changed line count by 1`: the very + # equality the test above it had just denied, which is what a comparison of + # a padded string against an unpadded one looks like from the outside. + # Measured: transcript line 454 of the macOS job at `9000e86`. And + # reproduced on Linux under NOTHING BUT a `wc` that pads — the rest of the + # tree exactly as `d3d59b5` shipped it — for **575 passed, 423 failed** + # against that runner's own 560 / 438. Fifteen assertions apart, which is + # about what the second defect (a liveness `sleep` too short for a 900 s + # run, `tests/test_lane_helpers.sh:446`) has left to contribute once this + # one has already taken the checkout down with it. + before_lines="$(wc -l < "$pre" | tr -d ' ')" + printf '%s\n' "$newline" >> "$target" # >> FOLLOWS the symlink + after_lines="$(wc -l < "$target" | tr -d ' ')" + # `-eq`, not `=`: these are NUMBERS, and saying so is what makes a second + # padded spelling arriving from anywhere unable to resurrect the defect. + [ "$after_lines" -eq "$((before_lines + 1))" ] || die "append changed line count by $((after_lines - before_lines)); inspect $target" 5 + # THE WHOLE FILE REBUILT, and no `cmp -n`: the `-n ` that reads + # "compare at most this many bytes" is GNU's, and BSD `cmp`'s trailing + # numbers are SKIPS, not a limit — so where GNU compared a prefix, BSD + # answers `illegal option -- n`, exits 2, and this proof becomes a REFUSAL + # of a write that was perfectly correct, dying 5 with the log line already + # on disk and uncommitted. What the file must now be is exactly its old + # bytes followed by the one new line, so that is what is built and compared: + # `cat`, `printf` and cmp's `-` operand are POSIX, no byte count is needed + # (`head -c 0` is an ERROR on BSD, which is what the first append to an + # empty log would have hit), and the claim is STRONGER than the old one — + # not merely that no existing byte moved, but that the line appended is the + # line that was asked for. + { cat -- "$pre"; printf '%s\n' "$newline"; } | cmp -s -- "$target" - || + die "append rewrote existing bytes; inspect $target" 5 + note "1 line appended to $target" +} + +# ------------------------------------------------------------------ git side + +LANES_BRANCH="${LANES_BRANCH:-main}" + +# Bounded like every other network call (Amendment 8(h)). A timeout here is not +# fatal: the callers already degrade to "no remote branch", which costs a fetch +# that would have hung anyway. +remote_has_branch() { + git_net -C "$LANES_REPO" ls-remote --exit-code --heads origin "$LANES_BRANCH" >/dev/null 2>&1 || { + [ "$GIT_TIMED_OUT" = 1 ] && note "ls-remote timed out after ${GIT_TIMEOUT}s — treating origin/$LANES_BRANCH as unreachable" + return 1 + } + return 0 +} + +# Unstaged changes to TRACKED files OTHER than the register. New in Amendment +# 5 and unavoidable: the register shares its checkout with handoffs/ and +# workspaces/, which other lanes write. `git pull --rebase` refuses outright +# on ANY unstaged tracked change, so without this the refusal would surface as +# a bogus "REBASE CONFLICT" and the writer would be sent to a recovery that +# does not apply. Prints the offending paths, one per line. +dirty_elsewhere() { + git -C "$LANES_REPO" --no-pager diff --name-only 2>/dev/null \ + | grep -v -x -F -- "$(printf '%s\n' "${CP_PATHS[@]}")" || : +} + +# Every TRACKED file in this checkout that differs from HEAD — staged or not, +# and whatever pathspec the caller happens to be writing. That is exactly the +# set `git pull --rebase` refuses on. `git status --porcelain` reports the same +# thing, with rename records and path quoting to parse first; these two +# plumbing reads answer the same question unambiguously, and neither reports an +# untracked file, which does not block a rebase. +tracked_dirty() { + { git -C "$LANES_REPO" --no-pager diff --name-only 2>/dev/null + git -C "$LANES_REPO" --no-pager diff --name-only --cached 2>/dev/null + } | LC_ALL=C sort -u +} + +# AMENDMENT 7 — `log`, `claim` and `release` REFUSE a checkout that cannot be +# rebased. $1 names the act; every remaining argument is a pathspec THIS write +# is about to append to and is therefore exempt. +# +# `lanes/LANES.md` is the one exemption that is not a pathspec of the write: +# it is CAPTURED rather than refused, by capture_register_edit below, and the +# guard is then re-run against the checkout that capture left behind. See +# there for why (Addendum 3, R11). +# +# The guard is computed over the WHOLE checkout, and from the same set the +# write will use, because the first version of it was not: `claim` measured +# "dirty elsewhere" against (log + LANES.md) while a CLAIMED writes the log +# alone, so a dirty `lanes/LANES.md` — the one dirty file this repository +# actually has, at ~500 register commits a day — passed the guard and then took +# commit_push's Amendment 5(d) branch, which skips `pull --rebase` and with it +# the rescan that decides the race. Two lanes ended up holding one object with +# no CLAIM-LOST. The guard and the write must never disagree about what this +# invocation is writing. +refuse_dirty_checkout() { + rd_what="$1"; shift + [ "$NO_GIT" = 1 ] && return 0 + git -C "$LANES_REPO" rev-parse --git-dir >/dev/null 2>&1 || return 0 + if [ "$#" -gt 0 ]; then + rd_others="$(tracked_dirty | grep -v -x -F -- "$(printf '%s\n' "$@")" || :)" + else + rd_others="$(tracked_dirty)" + fi + [ -n "$rd_others" ] || return 0 + note "this checkout has uncommitted changes to tracked files that are not this $rd_what's:" + printf ' %s\n' $rd_others >&2 + case "$rd_what" in + claim) note "a claim is decided by which CLAIMED lands on main first, and 'pull --rebase' refuses on any" + note "unstaged tracked change — so the race cannot be run safely here." ;; + *) note "an object-log write is ordered against other lanes by landing on main, and 'pull --rebase'" + note "refuses on any unstaged tracked change — so this write cannot be ordered safely here." ;; + esac + note "RECOVERY — whoever wrote those files commits them:" + note " lanes/LANES.md LANES_LANE= lanes-edit.sh commit \"\"" + note " anything else git -C $LANES_REPO commit -m \"handoff(@): \" -- " + note "then re-run the refused $rd_what: its own push publishes their commits with it (#194)." + die "refusing to $rd_what on a checkout that cannot be rebased" 2 +} + +# ------------------------------------------- AMENDMENT 8, ruling (h): THE +# WRITER NEVER BLOCKS THE ESTATE. +# +# On 2026-09-12 at about 01:44Z an ssh `git-receive-pack` hung for five minutes +# AFTER its push had already landed, and `lanes-edit.sh append-row-status` sat +# inside it holding the mutex for the whole five minutes. Every lane on Eagle +# that wanted to write a row waited behind a lock whose holder was blocked on a +# socket, and the estate only moved again when the ssh was killed by hand. +# +# So every git call that touches the NETWORK — push, pull, fetch, ls-remote — +# runs under a timeout, and a timeout is not a failure to retry: it is a +# refusal to hold the mutex any longer. The helper aborts any rebase it started, +# releases the lock, prints how to find out whether the push landed anyway, and +# exits 3 with the edit safe in a local commit. +# +# `LANES_GIT_TIMEOUT` is the budget in seconds (default 60; 0 disables the +# bound). `LANES_GIT` is the binary, so a test can hand these calls — and ONLY +# these calls — a git that hangs, without shadowing git for the rest of the +# script. +GIT_TIMEOUT="${LANES_GIT_TIMEOUT:-60}" +GIT_BIN="${LANES_GIT:-git}" +GIT_TIMED_OUT=0 +git_net() { + GIT_TIMED_OUT=0 + gn_rc=0 + case "$GIT_TIMEOUT" in + ''|0|*[!0-9]*) "$GIT_BIN" "$@" || gn_rc=$? ;; + *) + if command -v timeout >/dev/null 2>&1; then + timeout -k 5 "$GIT_TIMEOUT" "$GIT_BIN" "$@" || gn_rc=$? + case "$gn_rc" in 124|137) GIT_TIMED_OUT=1 ;; esac + else + "$GIT_BIN" "$@" || gn_rc=$? + fi ;; + esac + return "$gn_rc" +} + +# What a timed-out network call does. NEVER a retry: the point is to stop +# holding the lock, and a second call to the same hung endpoint holds it twice +# as long. +git_timeout_die() { # + note "TIMED OUT after ${GIT_TIMEOUT}s: $1" + note " Amendment 8(h): the writer does not hold the estate's mutex on a hung" + note " network call. The lock is being released now, before this exits." + "$GIT_BIN" -C "$LANES_REPO" rebase --abort 2>/dev/null || : + note " YOUR EDIT IS SAFE — it is already a local commit:" + "$GIT_BIN" -C "$LANES_REPO" --no-pager log --oneline "origin/$LANES_BRANCH..HEAD" 2>/dev/null | head -n 5 >&2 || : + note " RECOVERY — a hung push often means it LANDED and the connection did not close," + note " so look before you push again:" + note " git -C $LANES_REPO fetch origin $LANES_BRANCH && git -C $LANES_REPO log --oneline origin/$LANES_BRANCH -3" + note " git -C $LANES_REPO push origin $LANES_BRANCH # only if it is not there" + release_lock + die "timed out after ${GIT_TIMEOUT}s on '$1' — the mutex is released and your commit is local; nothing was lost." 3 +} + +# BYTECODE NEVER RIDES A WORKSPACE COMMIT (opensoft/openRepoTools#162, cause +# 19: a handoff's attachments were committed with a whole virtualenv's +# `__pycache__` inside them, and the workspace repository carries them for +# ever). What `git add` WOULD stage for a pathspec is asked of git itself +# (`add --dry-run`, which honours `.gitignore` exactly as the real add does), +# and every path in that answer with a cache, bytecode or environment +# component is printed. Empty means the pathspec is clean. +# ONE PER LINE AND READ WITH `read`, never word-split: `*.pyc` unquoted is a +# glob, and the shell would expand it against whatever directory this runs in. +BYTECODE_IGNORES='__pycache__/ +*.pyc +*.pyo +.pytest_cache/ +.mypy_cache/ +.ruff_cache/ +node_modules/ +.venv/ +venv/ +site-packages/' +bytecode_in_pathspec() { # ... 0 read (the paths printed) · 3 a read FAILED + bip_repo="${1-}"; shift || : + [ "$#" -gt 0 ] || return 0 + # WHAT THE ADD WOULD STAGE, AND WHAT IS STAGED ALREADY: `add --dry-run` says + # nothing of a path the index already holds at these bytes, and the commit + # takes it all the same. A staged DELETION of bytecode is a cleanup and is + # let through (`--diff-filter=d`). + # + # A READ THAT FAILED IS NO "CLEAN" (#170 G13): a malformed magic pathspec, or + # an index git cannot read, made both reads exit 128 with their stderr thrown + # away and printed nothing, and the check passed. Each status is kept now. + # `add --dry-run`'s 1 is the one answer that is not a failure: it means some + # NAMED path is ignored, which the add would not stage. + # + # BOTH READS IN THE C LOCALE AND UNQUOTED (#170 E1, E2): the `add ''` + # lines are parsed, and a translated git words them otherwise; and `diff + # --name-only` C-quotes a path that is not ASCII (`"caf\303\251.pyc"`), whose + # closing quote hid the `.pyc` - so a staged non-ASCII bytecode file passed. + # `core.quotePath=false` leaves such a path as its bytes; one git still + # quotes (a control character, a `"` or a `\`) has its quotes taken off + # before it is judged. + bip_add=""; bip_rc=0 + bip_add="$(LC_ALL=C git -C "$bip_repo" -c core.quotePath=false add --dry-run --ignore-missing -- "$@" 2>/dev/null)" || bip_rc=$? + [ "$bip_rc" -le 1 ] || return 3 + bip_staged="" + bip_staged="$(LC_ALL=C git -C "$bip_repo" -c core.quotePath=false diff --cached --name-only --diff-filter=d -- "$@" 2>/dev/null)" || return 3 + { + printf '%s\n' "$bip_add" | LC_ALL=C sed -n "s/^add '\(.*\)'\$/\1/p" + printf '%s\n' "$bip_staged" + } | + LC_ALL=C awk '{ if ($0 ~ /^".*"$/) $0 = substr($0, 2, length($0) - 2) } + !seen[$0]++ { + n = split($0, part, "/"); hit = 0 + for (i = 1; i <= n; i++) + if (part[i] == "__pycache__" || part[i] == ".pytest_cache" || + part[i] == ".mypy_cache" || part[i] == ".ruff_cache" || + part[i] == "node_modules" || part[i] == ".venv" || + part[i] == "venv" || part[i] == "site-packages") hit = 1 + if ($0 ~ /\.py[co]$/) hit = 1 + if (hit) print }' +} + +# The refusal's words, and the OFFER beside them: the ignore lines the +# workspace's own `.gitignore` lacks, with the one command that adds them. +# `openRepoTools wip init` seeds them into a new workspace; an older one is +# offered them here, where they are missing. +bytecode_refusal_text() { # + brt_n="$(printf '%s\n' "${1-}" | awk 'NF { n++ } END { print n + 0 }')" + brt_missing="" + while IFS= read -r brt_l; do + [ -n "$brt_l" ] || continue + command grep -Fqx -- "$brt_l" "$LANES_REPO/.gitignore" 2>/dev/null || + brt_missing="$brt_missing '$brt_l'" + done <> %s\n' \ + "$brt_missing" "$brt_missing" "$brt_target" + fi + printf 'Nothing was staged or committed. Unstage or delete those paths, then re-run.' +} + +# #194, AS #214's ADVERSARIAL CHECK HARDENED IT — WHAT `commit` MAY PUBLISH +# WITH NOTHING STAGED, read from the objects the push will send and nothing +# else. Three ordinary checkout states got a deletion past the first fence, +# which read `git log --name-status origin/..HEAD`: +# +# * A MERGE's own changes: `log` prints no diff for a merge, so a deletion +# made while resolving one passed unread. A merge or root commit refuses. +# * HEAD ON ANOTHER BRANCH: the fence read HEAD and the push sent +# `refs/heads/`. The range is the branch, and HEAD must be it, because +# `pull --rebase` moves HEAD and the push moves the branch. +# * A LOCAL BRANCH NAMED `origin/`, which shadows the tracking ref. Both +# ends of the range are spelled in full. +# +# The reads are plumbing (`rev-list`, `diff-tree --raw`), which no `color.*` or +# `diff.ignoreSubmodules` reshapes, under `--no-replace-objects`, so a replace +# ref cannot show the fence one commit while the push sends another. A change +# passes only as an ADDED or MODIFIED REGULAR FILE under the register's own +# directory (`$LANES_PREFIX`, derived, as every path of the register's is) or +# `handoffs/`, and never as bytecode, a cache or an environment (#162's list). +# A deletion, a type change, a symlink or a gitlink refuses, and so does a path +# anywhere else. IT IS A PATH AND KIND FILTER: it vouches for where a change +# lands and what it is, never for whose it is (it reads no subject, author or +# trailer), so another lane's register write passes it. That includes lane +# tooling's own lane rename, +# which deletes a log to re-add it: a deletion is the one change origin cannot +# get back, and the fence keeps one rule for it. A read or a classification +# that fails refuses too (2), because it proves nothing. +# +# Two guards have a test each (lane openRepoShape-2's SHOULD 4). `--no-renames` +# reads a rename as the deletion it is: read as an `R` line, the refusal would +# name a rename and not the path origin loses. And the register's directories +# are matched with their trailing `/`, so `lanes-archive/` beside `lanes/` is +# not inside it. +# +# It leaves CP_FENCE_TIP at the commit it read and CP_FENCE_AHEAD at how many +# it read, and the publish pushes exactly that commit (`:refs/heads/`). +# A commit another lane makes in this shared checkout between the read and the +# push stays local. +cp_publish_fence() { + cpf_ref="refs/heads/$LANES_BRANCH" + cpf_head="$(git -C "$LANES_REPO" symbolic-ref -q HEAD 2>/dev/null || :)" + [ "$cpf_head" = "$cpf_ref" ] || die "refusing to publish: HEAD is ${cpf_head:-detached}, not $cpf_ref, and the push sends $cpf_ref while \`pull --rebase\` moves HEAD, so what would be published is not what HEAD shows, and nothing was pushed (#194). Whoever moved this shared checkout off $LANES_BRANCH puts it back; never reset or check out over their work." 2 + cpf_rc=0 + cpf_base="$(git --no-replace-objects -C "$LANES_REPO" rev-parse -q --verify "refs/remotes/origin/$LANES_BRANCH^{commit}")" || cpf_rc=$? + cpf_tip="$(git --no-replace-objects -C "$LANES_REPO" rev-parse -q --verify "$cpf_ref^{commit}")" || cpf_rc=$? + cpf_revs="$(git --no-replace-objects -C "$LANES_REPO" rev-list --parents "$cpf_base..$cpf_tip")" || cpf_rc=$? + cpf_odd="$(printf '%s\n' "$cpf_revs" | awk 'NF > 0 && NF != 2 { printf " %s %s\n", substr($1, 1, 12), (NF > 2 ? "is a merge commit" : "is a root commit") }')" || cpf_rc=$? + cpf_pairs="$(printf '%s\n' "$cpf_revs" | awk 'NF == 2')" || cpf_rc=$? + # `diff-tree --stdin` SKIPS A COMMIT IT CANNOT READ and still exits 0, and + # prints no header for an empty diff unless told `--always`: so every commit + # handed to it must come back as a header, or the read refuses. + cpf_raw=""; cpf_n=0 + if [ -n "$cpf_pairs" ]; then + cpf_n="$(printf '%s\n' "$cpf_pairs" | awk 'END { print NR }')" || cpf_rc=$? + cpf_raw="$(printf '%s\n' "$cpf_pairs" | git --no-replace-objects -C "$LANES_REPO" -c core.quotePath=false diff-tree --stdin --always -r --no-renames --raw --ignore-submodules=none)" || cpf_rc=$? + fi + cpf_reg="${LANES_PREFIX:+${LANES_PREFIX%/}/}"; cpf_logp="${LANES_LOG_PREFIX:+${LANES_LOG_PREFIX%/}/}" + cpf_bad="$(printf '%s\n' "$cpf_raw" | awk -F '\t' -v want="$cpf_n" -v reg="$cpf_reg" -v logp="$cpf_logp" \ + -v reg_path="$LANES_PATH" -v alias_path="$LANES_ALIASES_PATH" ' + function inside(p) { + return (reg != "" && index(p, reg) == 1) || (logp != "" && index(p, logp) == 1) || + index(p, "handoffs/") == 1 || p == reg_path || p == alias_path + } + function bytecode(p, n, part, i) { + if (p ~ /\.py[co]$/) return 1 + n = split(p, part, "/") + for (i = 1; i <= n; i++) + if (part[i] == "__pycache__" || part[i] == ".pytest_cache" || part[i] == ".mypy_cache" || + part[i] == ".ruff_cache" || part[i] == "node_modules" || part[i] == ".venv" || + part[i] == "venv" || part[i] == "site-packages") return 1 + return 0 + } + NF == 0 { next } + NF == 1 && $1 ~ /^[0-9a-f]+$/ { c = substr($1, 1, 12); seen++; next } + { split($1, f, " "); st = f[5]; mode = f[2] + if (!(NF == 2 && (st == "A" || st == "M") && (mode == "100644" || mode == "100755") && inside($2) && !bytecode($2))) + printf " %s %s %s %s\n", c, st, mode, $2 } + END { if (seen != want) exit 3 }')" || cpf_rc=$? + [ "$cpf_rc" = 0 ] || die "git could not read, or this helper could not classify, the local commits on $cpf_ref ahead of refs/remotes/origin/$LANES_BRANCH, so whether they are \`commit\`'s to publish is unknown; nothing was pushed (#194)" 2 + if [ -n "$cpf_odd$cpf_bad" ]; then + note "of the local commits on $cpf_ref ahead of origin/$LANES_BRANCH, these are not register or handoff writes (a merge or root commit, or a change that is not an added or modified regular file under ${LANES_PREFIX:-the register directory} or handoffs/):" + [ -z "$cpf_odd" ] || printf '%s\n' "$cpf_odd" >&2 + [ -z "$cpf_bad" ] || printf '%s\n' "$cpf_bad" >&2 + die "refusing to publish: \`commit\` pushes only register and handoff writes (#194), so nothing was pushed. A lane rename (Amendment 16) deletes and re-adds its log and is refused here too; the next register write from this checkout carries it. Anything else, whoever queued it publishes it; never reset it away. Read them: git -C $LANES_REPO log --stat refs/remotes/origin/$LANES_BRANCH..$cpf_ref" 2 + fi + CP_FENCE_TIP="$cpf_tip" + CP_FENCE_AHEAD="$cpf_n" +} + +# The publish's CP_AFTER_REBASE: `pull --rebase` has rewritten the queue onto +# what origin holds now, and may have taken in a commit made since the first +# read, so the fence reads it again and the push is pinned to what it read. +# THE PULL CAN EMPTY THE QUEUE (lane openRepoShape-2, #214 6243280936): origin +# may hold every queued commit already, by content under other shas, because +# another workstation made the same edit or a peer's write carried it. The +# rebase drops each one, and a push would send origin its own tip and print +# "pushed". So the publish ends here, exit 0, as the no-op it now is, and it +# says so. Only `commit` installs this hook, and this commit_push is its last +# act, so the exit is that return. +cp_publish_refence() { + cp_publish_fence + if [ "$CP_FENCE_AHEAD" = 0 ]; then + note "origin/${LANES_BRANCH} already holds every commit this publish listed: \`pull --rebase\` found each one there by content and dropped it, so none is left to push and no push was sent (#194)" + exit 0 + fi + CP_PUSH_SPEC="$CP_FENCE_TIP:refs/heads/$LANES_BRANCH" +} + +# commit_push "" [...] — the pathspecs default to the +# register alone, which is every caller that predates Amendment 7. A LANDING +# or LANDED writes TWO (the register and the lane's log) so that both halves +# of one act land in one commit and no reader ever sees half of it. +# AMENDMENT 15 — A CASE-ONLY RENAME IS STAGED IN THE INDEX AND COMMITTED FROM +# IT, because a PATH-LIMITED commit cannot record one at all on a +# case-INSENSITIVE filesystem — which is what this repository's macOS job runs +# on. `ensure_log` renames a lane's log to the register row's spelling and +# hands the OLD path in beside the new one. Three things are true there, and +# together they leave exactly one way through: +# +# * `git add -- ` under git's own `core.ignorecase=true` matches +# both pathspecs to the ONE index entry and stages a MODIFICATION under the +# old name, so the rename never reaches the commit. Measured on the macOS +# job of openRepoTools#41 at `48f2111`: fifteen red assertions, the first +# of them *"the rename landed in the WRITE's own commit"*, whose +# `git log -- ` came back EMPTY. +# * The same `add` under `core.ignorecase=false` is no better, and is worse: +# the OPERATING SYSTEM still resolves `lanes/log/repocase-1.md` to the file +# now named `repoCase-1.md`, so git stages the old entry as MODIFIED and +# the new path as a SECOND entry. One file on disk, two paths in the tree — +# and every checkout after it reports the one it cannot materialise as +# deleted, so the writes behind it are refused (2) for a dirty checkout +# they did not make. Measured at `e35f2a8` and `928908a`: eleven red +# assertions, all of them behind `lanes/log/repocase-1.md` reported dirty. +# * `git commit -- ` is `--only`: it builds the tree from HEAD and the +# WORKING TREE of those paths, disregarding what is staged. So an index +# that holds the rename exactly is thrown away by the commit anyway, and +# the old path — which the OS still resolves — comes back in the tree. +# +# So the old entry is dropped from the INDEX by its exact path, where no +# filesystem is consulted at all; the NEW path alone is added; and the commit +# is made from the index rather than from a pathspec. +# `update-index --force-remove` is the one git verb that removes an entry +# without asking the filesystem whether the file is still there, and it is a +# no-op on a path the index does not hold — so a log that was never committed +# renames just as quietly. The index commit is FAIL-CLOSED: anything staged +# that is not one of this write's own pathspecs refuses (6) instead of riding +# along, which is the guarantee the `--only` pathspec was there to give. +# +# `-c core.ignorecase=false` stays on every call that takes `CP_PATHS`, because +# a pathspec that means one thing to `add` and another to `diff` is the same +# defect one line along: with the old entry already gone it is what makes `add` +# record the new path in the spelling the code computed rather than the one the +# index used to hold. It narrows nothing else — these paths are this file's own, +# `lanes/LANES.md` and `lanes/log/.md`, spelled by the code that computes +# them. +CP_EXACT="core.ignorecase=false" +commit_push() { + msg="$1"; shift || : + if [ "$#" -gt 0 ]; then CP_PATHS=("$@"); else CP_PATHS=("$LANES_PATH"); fi + [ "$NO_GIT" = 1 ] && { note "LANES_NO_GIT=1 — not committing"; return 0; } + # THE OLD PATH IS A PATHSPEC FOR THE DIFFS AND NEVER FOR THE `add`: after the + # index entry is force-removed it matches neither the index nor a directory + # read that compares exactly, and `git add` FAILS on a pathspec that matches + # nothing at all. + cp_ren="${LOG_RENAMED_FROM:-}" + cp_add=(); cp_add_n=0 + for cp_p in ${CP_PATHS[@]+"${CP_PATHS[@]}"}; do + if [ -n "$cp_ren" ] && [ "$cp_p" = "$cp_ren" ]; then continue; fi + cp_add+=("$cp_p"); cp_add_n=$((cp_add_n + 1)) + done + if [ -n "$cp_ren" ]; then + git -C "$LANES_REPO" -c "$CP_EXACT" update-index --force-remove -- "$cp_ren" \ + || die "git update-index --force-remove $cp_ren failed — the log is already renamed on disk and git still holds the old path, so nothing was committed. Re-run; if it refuses again, \`git -C $LANES_REPO rm --cached -- $cp_ren\` is the same act by hand." 6 + fi + if [ "$cp_add_n" -gt 0 ]; then + cp_brc=0 + cp_byte="$(bytecode_in_pathspec "$LANES_REPO" ${cp_add[@]+"${cp_add[@]}"})" || cp_brc=$? + [ "$cp_brc" = 0 ] || die "git could not read what this commit would stage (a pathspec it cannot parse, or an index it cannot read), so whether it carries bytecode is unknown; nothing was staged or committed (opensoft/openRepoTools#170 G13)" 2 + [ -z "$cp_byte" ] || die "$(bytecode_refusal_text "$cp_byte")" 2 + git -C "$LANES_REPO" -c "$CP_EXACT" add -- ${cp_add[@]+"${cp_add[@]}"} || die "git add failed" 6 + fi + # #194 — NOTHING STAGED IS NOT NOTHING TO PUBLISH, FOR `commit` ALONE. A + # write the push loop below could not get out (a peer's uncommitted file + # blocking the rebase, six rejected pushes) leaves its edit as a LOCAL commit, + # and the RECOVERY printed for it is to re-run `commit` once the way is clear. + # Returning here sent that re-run home with exit 0 and the commit still local. + # So `commit`, the one caller that sets CP_PUBLISH_AHEAD, still takes the push + # loop (its lock, the dirty-elsewhere guard, the retries) whenever the branch + # holds commits `origin/$LANES_BRANCH` does not, as of the last fetch; no such + # ref reads as none. Every other write with nothing to stage stays the no-op it + # always was and reaches no network: a repeated `set-row-state` must not turn + # into a push of whatever this SHARED checkout has queued (the #214 review + # measured exactly that deleting `scripts/link-estates` on origin). + # + # AND `commit` PUBLISHES ONLY REGISTER AND HANDOFF WRITES, and only what it read: + # `cp_publish_fence` (above) reads the queue on the branch the push sends and + # refuses the whole publish (2) for anything that is not a register or + # handoff write. The push is pinned to the commit the fence read, and every + # `pull --rebase` reads it again (CP_AFTER_REBASE) and re-pins it. + cp_publish=0 + if git -C "$LANES_REPO" -c "$CP_EXACT" diff --cached --quiet -- "${CP_PATHS[@]}"; then + cp_ahead="$(git --no-replace-objects -C "$LANES_REPO" --no-pager log --oneline "refs/remotes/origin/$LANES_BRANCH..refs/heads/$LANES_BRANCH" 2>/dev/null || :)" + if [ -z "$cp_ahead" ]; then + note "nothing staged for ${CP_PATHS[*]} — no commit made" + return 0 + fi + cp_n="$(printf '%s\n' "$cp_ahead" | awk 'END { print NR }')" + if [ "$CP_PUBLISH_AHEAD" != 1 ]; then + note "nothing staged for ${CP_PATHS[*]} — no commit made; the $cp_n local commit(s) ahead of origin/$LANES_BRANCH stay local. \`lanes-edit.sh commit\` would publish all of them, so read \`git -C $LANES_REPO cherry -v origin/$LANES_BRANCH HEAD\` first: another lane's commits are its own to publish" + return 0 + fi + cp_publish_fence + note "nothing staged for ${CP_PATHS[*]} — no commit made; pushing the $cp_n local commit(s) origin/$LANES_BRANCH does not have, up to ${CP_FENCE_TIP:0:12}:" + printf '%s\n' "$cp_ahead" | head -n 10 >&2 || : + [ "$cp_n" -le 10 ] || note " … and $((cp_n - 10)) more" + CP_PUSH_SPEC="$CP_FENCE_TIP:refs/heads/$LANES_BRANCH" + CP_AFTER_REBASE=cp_publish_refence + cp_publish=1 + fi + if [ "$cp_publish" = 1 ]; then + : # nothing of this write's own to commit: straight on to the push + elif [ -n "$cp_ren" ]; then + cp_staged="$(git -C "$LANES_REPO" -c "$CP_EXACT" diff --cached --name-only)" + cp_extra="" + while IFS= read -r cp_s; do + [ -n "$cp_s" ] || continue + cp_known=0 + for cp_p in ${CP_PATHS[@]+"${CP_PATHS[@]}"}; do + if [ "$cp_s" = "$cp_p" ]; then cp_known=1; fi + done + if [ "$cp_known" = 0 ]; then cp_extra="$cp_extra $cp_s"; fi + done <&2 + note "skipping 'pull --rebase' (it refuses on any unstaged tracked change) and pushing straight out" + if git_net -C "$LANES_REPO" push -q origin "${CP_PUSH_SPEC:-$LANES_BRANCH}"; then + LANES_INDEX_NUDGE=1 + note "pushed origin/$LANES_BRANCH (attempt $attempt, no pull — see the warning above)" + return 0 + fi + [ "$GIT_TIMED_OUT" = 1 ] && git_timeout_die "git push origin $LANES_BRANCH" + note "push rejected and the pull is blocked by the files above (attempt $attempt)" + if [ "$attempt" -ge 6 ]; then + note "RECOVERY: their author commits those files (a handoff: handoff(@): )," + note " then re-run: LANES_LANE= lanes-edit.sh commit \"\" — your edit is already" + note " a local commit here. If $LANES_PATH is clean, that re-run makes no commit of its own and" + note " pushes the local commits this lists (#194), refusing (2) and pushing nothing unless every one" + note " is a register or handoff write: git -C $LANES_REPO log --oneline origin/$LANES_BRANCH..HEAD" + die "could not push origin/$LANES_BRANCH: behind the remote, and a peer's uncommitted file blocks the rebase. Nothing was lost — your commit is local." 3 + fi + elif git_net -C "$LANES_REPO" pull --rebase -q origin "$LANES_BRANCH"; then + # The rebase has just put this invocation's commit on top of whatever + # landed first. `claim` hooks in HERE, because that is the moment the + # race is decided: if a peer's claim is on this history, theirs landed. + if [ -n "${CP_AFTER_REBASE:-}" ]; then + "$CP_AFTER_REBASE" || return $? + fi + if git_net -C "$LANES_REPO" push -q origin "${CP_PUSH_SPEC:-$LANES_BRANCH}"; then + LANES_INDEX_NUDGE=1 + note "pushed origin/$LANES_BRANCH (attempt $attempt)" + return 0 + fi + [ "$GIT_TIMED_OUT" = 1 ] && git_timeout_die "git push origin $LANES_BRANCH" + note "push raced (attempt $attempt) — retrying" + else + # A TIMED-OUT PULL IS NOT A CONFLICT. Read as one it would send the writer + # to a recovery that does not apply, and `rebase --abort` would be the + # only true line in it. + [ "$GIT_TIMED_OUT" = 1 ] && git_timeout_die "git pull --rebase origin $LANES_BRANCH" + note "REBASE CONFLICT on origin/$LANES_BRANCH — conflicting lines follow:" + for cp in "${CP_PATHS[@]}"; do + grep -n -e '^<<<<<<<' -e '^=======' -e '^>>>>>>>' -- "$LANES_REPO/$cp" 2>/dev/null | head -n 40 >&2 || : + grep -n -A2 -e '^<<<<<<<' -- "$LANES_REPO/$cp" 2>/dev/null | head -n 40 >&2 || : + done + git -C "$LANES_REPO" rebase --abort 2>/dev/null || : + cp_sha="$(git -C "$LANES_REPO" rev-parse HEAD 2>/dev/null)" + note "rebase ABORTED — the worktree is clean and NOT mid-rebase. Your edit is safe in these local commits:" + git -C "$LANES_REPO" --no-pager log --oneline "origin/$LANES_BRANCH..HEAD" 2>/dev/null | head -n 10 >&2 || : + # #32 — AN ABORTED PULL IS NOT PROOF THIS COMMIT NEVER REACHED ORIGIN + # (the same rule RV-B3 took for the handoff stamp's own push, in + # lane-start). This checkout is shared with every lane on the + # workstation, so the very next write out of it pulls this dangling + # commit onto its own and pushes both together — three of the four + # "rebase conflict … nothing was pushed" lines seen on Eagle in one + # hour named a commit that was ALREADY on origin by the time anyone + # read them. LOOK before you reset or redo anything — by ANCESTRY + # (Copilot round 2 on #50, 5203033893): a log capped at a few entries + # can bury this commit below the window while it stays an ancestor, the + # moment four or more later writes land ahead of it. + # ROUND 3 (Copilot 5203261904): `fetch && merge-base ... && echo A || + # echo B` is left-associative — a FAILED fetch also falls to the `||` + # and prints the SAME "not-there" a genuine non-ancestor does, so a + # stale or unreachable origin would silently wave the reset/redo path + # through. Fetch is now its own line, checked before anything else. + # ROUND 4 (Copilot 5203455553): SHA ancestry is the wrong test — the + # very write this whole recovery exists to catch (a peer's own + # `commit_push` pulling THIS dangling commit and rebasing it onto a + # newer base, per the very next branch above) gives it a NEW sha, so + # `merge-base --is-ancestor $cp_sha …` answers "not-there" even once + # the CONTENT is published. `git cherry` compares by PATCH, not by + # sha, so a rebase that only replays the same change (no real + # conflict) is still found. Measured against a real bare repo: a + # commit rebased by a peer this way answers `not-there` under + # `merge-base --is-ancestor` and `-` (found, equivalent) under + # `git cherry` — verified for the genuinely-absent case too (`+`) and + # the plain same-sha case (no output at all, which the `-c '^+'` + # count below also reads as zero, i.e. already there). + note "RECOVERY (in that order):" + note " git -C $LANES_REPO fetch origin $LANES_BRANCH || echo FETCH-FAILED # if that printed FETCH-FAILED, STOP and retry — a stale or unreachable origin proves nothing either way" + note " git -C $LANES_REPO cherry origin/$LANES_BRANCH $cp_sha | grep -c '^+' # BY CONTENT, not by sha: a peer's rebase changes the hash but git cherry still finds the same patch" + note " if that printed 0, STOP — reset or redo now would write it a second time." + note " git -C $LANES_REPO rev-parse HEAD # if this is not $cp_sha, STOP: the checkout moved after this abort, and the lines below no longer describe it" + note " git -C $LANES_REPO cherry -v origin/$LANES_BRANCH HEAD # WHOSE: one '+' line per local commit origin lacks, which is what the reset below drops" + note " if any '+' line is not your own write, STOP and take it to the lane its subject names; a LANES(concurrent@…) or" + note " LANES(pre-existing@…) capture names no lane, so it is NOT yours. Never reset, stash or overwrite a peer's work:" + note " the reset below drops EVERY '+' commit in this checkout, theirs with yours, and origin holds no copy of any of them (#194)." + note " git -C $LANES_REPO diff origin/$LANES_BRANCH..HEAD -- ${CP_PATHS[*]} # only if it is not there: read back exactly what you wrote" + note " git -C $LANES_REPO reset --hard origin/$LANES_BRANCH # only if every '+' line is yours: drop the local commits (NOTE: also drops any" + note " # uncommitted peer edit in this checkout)" + note " then re-read LANES.md and redo the edit with lanes-edit.sh, on top of the peer's version." + die "rebase conflict on origin/$LANES_BRANCH — not pushed by this attempt; a later write from this checkout may already carry it, so look before you retry." 3 + fi + attempt=$((attempt + 1)) + sleep 3 + done + die "could not push origin/$LANES_BRANCH after 6 attempts; your commit is local — retry later" 6 +} + +# ====================================================== AMENDMENT 14 ======= +# +# THE DERIVED INDEX (lane-collision-protocol Amendment 14, ratified by Brett +# Heap 2026-10-05, verbatim "ratify 48"). The register's truth stays where it +# is; `lanes-index` keeps a DERIVED copy of it — SQLite on local disk, or QA +# Postgres where a workstation is configured for it — written behind the +# sources, read only by tooling that decides nothing, and never a gate. +# +# THIS FILE TOUCHES IT IN EXACTLY TWO PLACES, AND NEITHER IS ON AN ACT'S PATH. +# +# THE NUDGE (clause (d)). After a push has LANDED and the mutex is released — +# `cleanup`, on the way out, once `commit_push` has recorded a push that went +# through — ONE DETACHED `lanes-index sync`: stdin closed, stdout and stderr +# on /dev/null, descriptors 3 to 9 closed, started from a subshell that +# exits at once so this process never has a child to wait for, and its +# status never read. It carries no data: the indexer reads `origin/` +# as the push left it, never takes this file's mutex, and a slow, failing or +# absent indexer delays and fails nothing here. `LANES_INDEX=off` skips it, +# and so does a workstation with no `lanes-index` ON PATH — PATH alone, not +# the file beside this one, because a sibling in a clone is not an +# installation and the suite runs this file thousands of times from one: the +# absent case is one `command -v` and prints nothing. +# +# THE READ FLAG (clause (b)). `lanes ... --index` and `history ... --index`, +# and only when TYPED: `index_open` asks `lanes-index export` for the index's +# image of the register, and the eight PUBLISHED-READ primitives — the +# register, the archive, the alias table, the log list, a log's events, the +# events of them all — answer out of that image instead of `origin/`. +# Everything else the read does is unchanged, the LOCAL reads included (this +# checkout's own register and log files, this workstation's session records, +# tmux), which is what makes its answer byte-identical to the source read's +# where the index is current. Anything else — the indexer absent, the store +# missing, unreachable, wiped or of another schema, a configuration it +# refuses — is said in ONE line and the source read runs as it always did. +# +# NOTHING ELSE READS IT. No act, no hook, no guard, no writer and none of the +# reads an act makes for itself (`who`, `binding`, `live-holder`, `next-free`, +# `managed-projection`, `lane-reconcile`) has a path to `LANES_IDX_DIR`: it is +# assigned empty at start-up whatever the environment says, and set only by +# `index_open`, which only the two read arms call. +# +# THE INVENTORY'S NUDGE IS THE SAME ONE (opensoft/openRepoTools#161). The #97 +# inventory writers — `set-lane-state`, `set-lane-tree`, the lifecycle follow +# `write_event` makes after a `STARTED`/`RESUMED`/`ENDED`/`RETIRED`, and the +# rename that moves a lane's control root — write no commit and push nothing, +# so they leave `LANES_INDEX_NUDGE_INV` instead, and the same detached fork is +# made with `--source inventory`: the indexer reads this workstation's +# sidecars as they now stand, through this file's own `worktrees` read. A write +# that did both (a `STARTED` that landed and moved the snapshot) makes both +# forks; `lanes-index` runs one sync at a time per workstation, and a second +# that finds the lock held leaves the holder a mark naming its source. +index_nudge() { + in_reg="${LANES_INDEX_NUDGE:-0}"; in_inv="${LANES_INDEX_NUDGE_INV:-0}" + LANES_INDEX_NUDGE=0; LANES_INDEX_NUDGE_INV=0 + [ "${LANES_INDEX:-}" = off ] && return 0 + in_bin="$(command -v lanes-index 2>/dev/null || :)" + [ -n "$in_bin" ] || return 0 + if [ "$in_reg" = 1 ]; then + ( "$in_bin" sync /dev/null 2>&1 3>&- 4>&- 5>&- 6>&- 7>&- 8>&- 9>&- & ) >/dev/null 2>&1 + fi + if [ "$in_inv" = 1 ]; then + ( "$in_bin" sync --source inventory /dev/null 2>&1 3>&- 4>&- 5>&- 6>&- 7>&- 8>&- 9>&- & ) >/dev/null 2>&1 + fi + return 0 +} + +# THE READ FLAG'S ONE DOOR. 0 with `LANES_IDX_DIR` set and `read: index (...)` +# said; 1 with `read: sources (index )` said and NOTHING set, so the caller +# runs the source read exactly as it would have without the flag — and exits as +# that read would. Both lines go to stderr: stdout is the read's own, and a +# person diffing the two answers diffs the answer. +# +# THE LAG IS SAID, NEVER REFUSED (clause (b)): `` is how many commits this +# checkout's `origin/` carries past the indexed one, and `unknown` where +# that commit is not here to count from. +# +# `index_open worktrees` IS THE SAME DOOR FOR THE `worktrees` TABLE +# (opensoft/openRepoTools#161): `export --worktrees` writes every +# `inventory:` source the store holds, `LANES_WT_IDX_DIR` is set +# and `LANES_IDX_DIR` is NOT — so not one published read of the register is +# answered out of the index by it — and the line names each source with the +# time it was synced, because an inventory has no commit to count a lag in. +index_open() { # [worktrees] + io_kind="${1-register}" + LANES_IDX_DIR="" + LANES_WT_IDX_DIR="" + if [ "${LANES_INDEX:-}" = off ]; then + printf 'read: sources (index off: LANES_INDEX=off)\n' >&2 + return 1 + fi + io_bin="" + if [ -x "$SCRIPT_DIR/lanes-index" ]; then io_bin="$SCRIPT_DIR/lanes-index" + else io_bin="$(command -v lanes-index 2>/dev/null || :)" + fi + if [ -z "$io_bin" ]; then + printf 'read: sources (index missing: no lanes-index beside %s or on PATH)\n' "$SCRIPT_DIR/lanes-edit.sh" >&2 + return 1 + fi + io_dir="$(mktemp -d "${TMPDIR:-/tmp}/lanes-index-read.XXXXXX" 2>/dev/null || printf '')" + if [ -z "$io_dir" ]; then + printf 'read: sources (index unread: no temporary directory could be made)\n' >&2 + return 1 + fi + io_rc=0 + io_xa="" + [ "$io_kind" = worktrees ] && io_xa=--worktrees + if command -v timeout >/dev/null 2>&1; then + timeout -k 2 30 "$io_bin" export --out "$io_dir" ${io_xa:+"$io_xa"} /dev/null 2>"$io_dir/.stderr" || io_rc=$? + else + "$io_bin" export --out "$io_dir" ${io_xa:+"$io_xa"} /dev/null 2>"$io_dir/.stderr" || io_rc=$? + fi + if [ "$io_rc" != 0 ] || [ ! -f "$io_dir/meta" ]; then + io_why="" + [ -f "$io_dir/why" ] && io_why="$(head -n 1 -- "$io_dir/why" 2>/dev/null || :)" + case "$io_rc" in 124|137) io_why="unreachable: lanes-index export did not answer within 30 s" ;; esac + if [ -z "$io_why" ]; then + io_why="unread: lanes-index export exited $io_rc" + io_err="$(head -n 1 -- "$io_dir/.stderr" 2>/dev/null || :)" + [ -z "$io_err" ] || io_why="$io_why: $io_err" + fi + rm -rf -- "$io_dir" + printf 'read: sources (index %s)\n' "$io_why" >&2 + return 1 + fi + io_store="$(sed -n -e 's/^store=//p' "$io_dir/meta" | head -n 1)" + if [ "$io_kind" = worktrees ]; then + # A FIFTH FIELD IS THE LAST ERROR this workstation's own record of the + # source carries (N2 of the review of #289): a sync that refused a listing + # that was not whole left the table as it was, and `synced` alone did not + # say that a later sync had failed, or why. It is named as `status` names + # it, because a refused `reconcile`, a `--dry-run` included, records one + # too (review r2 of #289, NIT-1). + io_at="$(awk -F'\t' '$1 == "inventory" { printf "%s%s synced %s%s", (n++ ? "; " : ""), $2, $3, ($5 != "" ? " (last error: " $5 ")" : "") }' "$io_dir/meta")" + LANES_WT_IDX_DIR="$io_dir" + printf 'read: index (%s) at %s\n' "${io_store:-unknown}" "${io_at:-no inventory source}" >&2 + return 0 + fi + io_sha="$(sed -n -e 's/^sha=//p' "$io_dir/meta" | head -n 1)" + io_behind=unknown + if [ -n "$io_sha" ] && have_remote_ref; then + io_n="$(git -C "$LANES_REPO" rev-list --count "$io_sha..origin/$LANES_BRANCH" 2>/dev/null || :)" + case "$io_n" in ''|*[!0-9]*) : ;; *) io_behind="$io_n" ;; esac + fi + LANES_IDX_DIR="$io_dir" + # WHAT WAS READ BEFORE THE FLAG WAS HONOURED IS NOT WHAT IS READ AFTER IT: + # every published-read cache this process may already hold is dropped. + LANES_REGISTER_CACHE="" + [ -n "${SE_CACHE_FILE:-}" ] && rm -f -- "$SE_CACHE_FILE.register" + lane_alias_flush + state_events_flush + printf 'read: index (%s) at register@%s; %s commits behind\n' "${io_store:-unknown}" "${io_sha:0:12}" "$io_behind" >&2 + return 0 +} + +# Prints, to stdout, a comma-joined, de-duplicated list of the lane(s) whose +# row changed in the CURRENT unstaged diff of LANES.md — identified by the +# first backtick token on each changed (+/-) line — or "append" for a +# changed line that is not a `| ... |` row (e.g. a Rule 6 LANDING/LANDED +# line, which names no row of its own). +identify_changed_lanes() { + git -C "$LANES_REPO" --no-pager diff -- "${CP_PATHS[@]}" 2>/dev/null | awk ' + /^[+-][^+-]/ { + line = substr($0, 2) + lane = "append" + if (substr(line, 1, 1) == "|") { + p1 = index(line, "`") + if (p1 > 0) { + rest = substr(line, p1 + 1) + p2 = index(rest, "`") + if (p2 > 0) lane = substr(rest, 1, p2 - 1) + } + } + if (!(lane in seen)) { seen[lane] = 1; order[++n] = lane } + } + END { for (i = 1; i <= n; i++) printf "%s%s", (i > 1 ? "," : ""), order[i] } + ' +} + +# Prints the standard WARNING block (diff --stat + first 200 chars of every +# changed line) to stderr. Takes no action beyond warning. +warn_dirty() { + git -C "$LANES_REPO" --no-pager diff --stat -- "${CP_PATHS[@]}" >&2 + git -C "$LANES_REPO" --no-pager diff -- "${CP_PATHS[@]}" 2>/dev/null | awk '/^[+-][^+-]/ {print substr($0,1,200)}' >&2 +} + +# Called by every mutating subcommand BEFORE it makes its own edit. If +# LANES.md is already dirty at that point, that content is someone else's — +# a peer's hand edit, or a helper run interrupted before it could push — +# never this invocation's. Always warns. In the default --no-sweep mode it +# commits that content now, as its own attributed commit, so it can never +# land combined with this invocation's edit (the 0d84d34 / a1f2438 +# incidents: another lane's row edit landed inside an unrelated commit with +# no trace of whose it was). In --sweep mode it leaves the content staged +# for this invocation's own commit and sets PRE_DIRTY_LANES so the caller +# can annotate its commit subject. +# +# Sets PRE_DIRTY_LANES to the affected lane list in --sweep mode; empty +# otherwise (nothing left to annotate — it was already committed separately). +handle_preexisting() { + PRE_DIRTY_LANES="" + if [ "$#" -gt 0 ]; then CP_PATHS=("$@"); else CP_PATHS=("$LANES_PATH"); fi + [ "$NO_GIT" = 1 ] && return 0 + git -C "$LANES_REPO" diff --quiet -- "${CP_PATHS[@]}" 2>/dev/null && return 0 + lanes="$(identify_changed_lanes)"; lanes="${lanes:-unknown}" + note "WARNING: LANES.md already has uncommitted changes before this edit (row: $lanes) — not this invocation's" + warn_dirty + if [ "$SWEEP_MODE" = "sweep" ]; then + PRE_DIRTY_LANES="$lanes" + note "SWEEP_MODE=sweep — leaving it staged; it will land inside this invocation's own commit, annotated" + else + git -C "$LANES_REPO" add -- "${CP_PATHS[@]}" + git -C "$LANES_REPO" commit -q -m "LANES(pre-existing@$WS): capture an uncommitted registry edit (row $lanes)" -- "${CP_PATHS[@]}" || : + note "captured pre-existing edit (row $lanes) as its own commit" + fi + return 0 +} + +# R11 (Addendum 3, 2026-09-11) — a peer's uncommitted REGISTER edit is +# CAPTURED, not refused. `lanes/LANES.md` is dirty in this shared checkout for +# much of the day — the register takes ~500 commits a day and a half-written +# row is what one of them looks like a second before it lands — so refusing +# every `claim`, `log` and `release` on it would push lanes to stop using the +# tool, and the pre-existing capture already exists precisely to make that +# state safe to rebase over. So: capture FIRST, exactly as every register +# write has done since --no-sweep (the warning included), and let the guard +# re-test the checkout afterwards. +# +# Only when the register is NOT one of this write's own pathspecs: a LANDING +# or a LANDED commits it itself, and the ordinary handle_preexisting call +# covers it there, --sweep included. There is nothing to sweep a register edit +# INTO when this commit does not touch the register, so this capture is always +# its own commit whatever --sweep says. +# +# It is reached only AFTER write_event's first guard, so it never commits on +# behalf of a write that is about to refuse: a checkout dirty in anything ELSE +# is refused before the lock and before this runs, and a refusal that had +# already committed a peer's register edit would be a refusal that wrote. +capture_register_edit() { + case " $* " in *" $LANES_PATH "*) return 0 ;; esac + cre_mode="$SWEEP_MODE" + SWEEP_MODE="no-sweep" + handle_preexisting "$LANES_PATH" + SWEEP_MODE="$cre_mode" + return 0 +} + +# ======================================================== Amendment 7 ====== +# +# THE PER-LANE OBJECT LOG. +# +# lanes/log/.md — one file per lane, append-only, line 1 a header, +# every other line an EVENT. This helper is the only writer, for the same +# reason it is the register's only writer. One file per lane is also what +# makes two workstations safe: two lanes writing at once touch two files. +# +# — lane , session @, , [ → ][ — ] +# +# The verb is ONE token. The first four fields are separated by `, `. The +# OBJECT token contains no space and no comma; everything after it up to +# ` — ` is payload, whose sub-fields are separated by `; ` and whose refs +# are space-separated. +# +# STATE IS PER LANE. A lane's state on an object is that lane's LAST line +# naming it — the last such line IN THE FILE, never the largest UTC (R14); +# the lane HOLDS the object when that verb is in the OPEN set; the object is +# HELD when any lane holds it. There is no index file: a read fetches and +# greps, because 45 lanes' logs together are smaller than one of the +# register's rows. +# +# LANES.md is unchanged. Its rows stay its rows and its Rule 6 LANDING / +# LANDED lines stay where every lane already reads them as the merge hold — +# which is why `who --landing` reads THOSE and not the logs. A LANDING or +# LANDED writes both files in one commit, with two pathspecs. + +LANES_PREFIX="${LANES_PREFIX:-$(git -C "${LANES_DIR:-.}" rev-parse --show-prefix 2>/dev/null || :)}" +LANES_LOG_DIR="${LANES_LOG_DIR:-$LANES_DIR/log}" +LANES_LOG_PREFIX="${LANES_LOG_PREFIX:-${LANES_PREFIX}log/}" + +# THE ALIAS TABLE IS TWO LAYERS, in this order (Amendment 9(b), ruling 3): the +# per-wip OVERRIDE in the person's own workspace repository, then the +# organisation's table shipped by openRepoTools and installed beside this +# command. An override row replaces the shipped row for the same alias and adds +# rows the shipped table does not carry; an alias in NEITHER layer is still a +# refusal naming the fix, spell it `owner/repo` (Amendment 7(a), unchanged). +# +# The shipped copy sits BESIDE this file because `--install` places from one +# list into one directory at one mode — the alternative was a second +# destination and a second mode in two repositories, which is why the table +# carries an executable bit it has no use for. +LANES_REPOS_TSV="${LANES_REPOS_TSV:-${LANES_DIR:+$LANES_DIR/repos.tsv}}" +if [ -z "${LANES_REPOS_TSV_SHIPPED:-}" ]; then + if [ -n "${OPENREPOTOOLS_BIN_DIR:-}" ] && [ -f "$OPENREPOTOOLS_BIN_DIR/repos.tsv" ]; then + LANES_REPOS_TSV_SHIPPED="$OPENREPOTOOLS_BIN_DIR/repos.tsv" + else + LANES_REPOS_TSV_SHIPPED="$SCRIPT_DIR/repos.tsv" + fi +fi + +# AMENDMENT 16(e) — THE LANE ALIAS TABLE, `lanes/aliases.tsv`, one layer and +# not two. `repos.tsv` above has a shipped layer because a repository alias is +# an ORGANISATION's fact; a lane rename is one person's register moving, so the +# table lives beside the register it describes and openRepoTools ships none. +# ` `, one line per rename, appended by `rename-lane` and by +# nothing else — and read case-insensitively by `canon_lane`, which is the one +# seat every `` argument in this file already passes through. +LANES_ALIASES_TSV="${LANES_ALIASES_TSV:-${LANES_DIR:+$LANES_DIR/aliases.tsv}}" +LANES_ALIASES_PATH="${LANES_ALIASES_PATH:-${LANES_PREFIX}aliases.tsv}" +PROJECTS_ROOT="${PROJECTS_ROOT:-$HOME/projects}" +NO_GITHUB="${LANES_NO_GITHUB:-0}" +STALE_HOURS="${LANES_STALE_HOURS:-4}" # Rule 1's threshold, reused + +# The field separator for every machine-read line below. NOT a tab: a tab is +# IFS WHITESPACE, so bash's `read` collapses runs of them and one empty field +# (an event with no payload) shifts every field after it one to the left. +# \037 — US, "unit separator" — is not whitespace, so empty fields survive it. +US="$(printf '\037')" +# THE ROW SEPARATOR FOR THE IN-SHELL LOOKUP TABLES (A11 Addendum 4 ruling 12). +# GS, one below US, and for the same reason US was chosen over a tab: it is not +# IFS whitespace, so an empty field does not shift every field after it. +GS="$(printf '\036')" + +# ONE LINE OUT OF A TABLE THIS SHELL IS ALREADY HOLDING, WITHOUT A PROCESS. +# The listing's three tables — the published register's index, this checkout's, +# and one line of facts per lane — are a few dozen lines each and were read with +# `printf | awk` PER LANE, which is six processes a lane to look up strings that +# are already in memory. Fenced with `$GS` and keyed on the lane name +# lower-cased, the whole lookup is one parameter expansion. +# +# IT ASSIGNS A GLOBAL AND RETURNS, rather than printing: a function whose answer +# is taken with `$( … )` forks, which is the cost this exists to avoid. +# +# AND THE EXPANSION IS `%%key*`, NEVER `#*key` — THE SAME FIRST MATCH, IN +# LINEAR TIME (opensoft/openRepoTools#107). Bash removes a shortest prefix by +# trying the whole pattern against EVERY prefix of the string in turn, and a +# pattern that opens with `*` costs a scan of that prefix each time: `#*key` is +# QUADRATIC in the table. A longest suffix is found by trying the pattern only +# where its FIRST character matches, and here that is `$GS`, which occurs once +# per line — so `%%key*` touches each byte about once. Both name the FIRST +# occurrence of `$GS$US`: `#*key` is everything up to and including it, +# `%%key*` everything before it. Measured on the suite's own fixture register +# (194 rows, 162 object logs): the per-lane loop of one `lanes --prefix` read +# was 56.6 s of its 58.1 s, about 75 ms per lookup, three or more lookups per +# lane — which is what put `lane`'s pick past the pty driver's 60-second bound. +# The offset is in CHARACTERS on both sides of the `+` (`${#…}` and `${1:…}` +# count the same way in any one locale), so a multibyte table cuts where the +# old expansion cut. +LOOKUP_OUT="" +table_lookup() { # + local tl_key tl_head tl_rest + LOOKUP_OUT="" + tl_key="$GS$2$US" + tl_head="${1%%"$tl_key"*}" + [ "$tl_head" = "$1" ] && return 1 + tl_rest="${1:$(( ${#tl_head} + ${#tl_key} ))}" + LOOKUP_OUT="${tl_rest%%"$GS"*}" + return 0 +} + +utc_now() { date -u +%Y-%m-%dT%H:%M:%SZ; } + +# ---------------------------------------------------------------- the verbs +# +# A lane HOLDS an object while its own last line on it is OPEN. WITHDRAWN is +# open on purpose: withdrawing a landing leaves the PR held by the lane that +# withdrew it. The CLOSED set closes only the WRITING lane's hold — another +# lane's claim on the same object is untouched by it. +is_open_verb() { case "$1" in CLAIMED|TAKEOVER|OPENED|LANDING|WITHDRAWN) return 0 ;; esac; return 1; } +is_closed_verb() { case "$1" in RELEASED|CLAIM-LOST|CLOSED|LANDED) return 0 ;; esac; return 1; } +# AND `HANDOFF-REQUESTED` IS A LANE-KIND VERB THAT CHANGES NO STATE (Amendment +# 18(g)): *"this adds one lane-kind verb, `HANDOFF-REQUESTED`, which changes no +# object's state and which every last-line reader skips."* It is lane-kind +# because its object is `lane:` — which is what `is_lane_verb` is asked +# here, and the only thing it is asked (its one caller is the `log` arm's +# object check) — and it is in NEITHER state set, so it opens nothing and closes +# nothing. Every reader that decides a lane's STATE enumerates the five state +# verbs by name (`lane_row_facts`, `lane_payload_field`, `lane_binding_utc`, +# `lane-last`, `swapped_candidates`), so none of them sees it, and +# `lane_binding_scan` is the one read that does: to it a request is a fact ABOUT +# a binding and never a release of one. +is_lane_verb() { case "$1" in STARTED|PAUSED|RESUMED|ENDED|RETIRED|HANDOFF-REQUESTED) return 0 ;; esac; return 1; } +# AMENDMENT 13(b) — THE TWO NARRATIVE VERBS, AND THEY ARE OUTSIDE EVERY STATE +# THERE IS. `NOTED` is a status note and `RULED` a ruling recorded verbatim; +# both are lane-kind lines whose object is the lane itself, and NEITHER IS A +# TRANSITION OF ANYTHING. So they are their own set rather than members of +# `is_lane_verb`: every reader that computes a lane's state by the per-lane +# last-line rule takes the five lane verbs by name, and a sixth and seventh +# inside that predicate would have made the narrative move the lane — a `NOTED` +# after a swap's `PAUSED` would have made a paused lane read as neither paused +# nor running, which is the one thing `swapped` and `restart` are built on. +# The one reader that took the LAST lane-kind line whatever it was is +# `swapped_candidates`, and it skips these by name for exactly that reason. +# +# AMENDMENT 16 PUTS `RENAMED` HERE, AND THE SET IS WHAT IT WAS RATHER THAN WHAT +# IT IS CALLED: a LANE-KIND LINE THAT IS NOT A TRANSITION. Clause (c) says the +# rename's line "changes no object's state, every last-line reader skips it", +# which is Amendment 13(b)'s sentence about its own two in different words — and +# `swapped_candidates` is the proof that `is_lane_verb` is the wrong home: it +# takes a lane's last lane-kind line WHATEVER its verb is, so a `RENAMED` there +# would make a swapped lane read as neither paused nor running and `restart` +# would not find it. One predicate, three verbs, one property. +# +# `HANDOFF-REQUESTED` IS INSIDE `is_lane_verb` AND THESE THREE ARE NOT, and the +# difference is the object rather than the state: that predicate's ONE caller is +# the `log` arm's check that a lane verb's object is `lane:`, which the +# request needs and which Amendment 13 gives its two by their own arm, as +# Amendment 16 gives `RENAMED` by its. None of the four moves a lane, and none +# of the four is seen by a state reader. +is_note_verb() { case "$1" in NOTED|RULED|RENAMED) return 0 ;; esac; return 1; } +valid_verb() { + is_open_verb "$1" || is_closed_verb "$1" || is_lane_verb "$1" || is_note_verb "$1" +} +VERB_LIST="CLAIMED RELEASED TAKEOVER CLOSED | OPENED LANDING LANDED WITHDRAWN | STARTED PAUSED RESUMED ENDED RETIRED HANDOFF-REQUESTED | CLAIM-LOST | NOTED RULED RENAMED" + +check_lane_name() { + case "${1-}" in + "" | *[!A-Za-z0-9._-]* | .* | -*) + die "'${1-}' is not a lane name (letters, digits, . _ -, not opening with . or -)" 2 ;; + esac +} + +log_file_for() { printf '%s/%s.md\n' "$LANES_LOG_DIR" "$1"; } +log_path_for() { printf '%s%s.md\n' "$LANES_LOG_PREFIX" "$1"; } + +# AMENDMENT 15 — THE LOG FILE IS `lanes/log/.md`, AND A FILE OF +# ANOTHER CASE IS STILL THIS LANE'S LOG. +# +# The log's file name was lowercased from the start, which is exactly why the +# 2026-09-13 incident produced TWO ROWS AND ONE LOG: `openXfactory-2` and +# `openxfactory-2` had always shared `lanes/log/openxfactory-2.md`. The real +# register still carries `lanes/log/openxfactory-4.md` beside the row +# `openxfactory-4` — the same spelling, nothing to do — and the historical +# mismatch is the shape these two functions exist for. READERS find the file +# whatever its case; the first WRITE renames it to the canonical spelling, once, +# inside its own commit (`ensure_log` below). +# +# `ls` and one `awk`, not a `$(lc …)` per file: `lanes/log/` carries a file per +# lane of the estate and this is asked on the path a person is waiting on. +# +# AND THE `--` STAYS (Copilot round 3 on openRepoTools#41, DECLINED with a +# measurement). It was read as a macOS defect — *"BSD `ls` rejects `--`, and the +# suppressed error makes every case-insensitive log scan empty"* — which would +# mean no first write ever renames anything on the one platform this amendment's +# rename exists for. BSD `ls` ends its options at `--` through `getopt(3)`, as +# every POSIX utility does, and `tests-macos` has been GREEN on the two +# assertions that can only pass if this scan finds a file of another case there: +# the rename recorded inside the write's own commit, and `lane-start`'s own +# `repo repocase → repoCase` out of the twin scan at `lane-start:677`. The suite +# asserts the parse itself as well, on every platform. Dropping `--` would hand +# a directory whose name begins with `-` back to `ls` as flags and change +# nothing else. +# +# AND IT RETURNS 1 WHERE THE DIRECTORY IS THERE AND COULD NOT BE LISTED (#138 +# item 9). It was `ls … 2>/dev/null | awk`, whose status is the awk's, so an +# unreadable directory answered "no log of any case" — which `retire_rows`' scan +# took as a lane with no log, and its write loop then failed on that directory +# after the scan had passed. A missing directory is still no log, and 0. +log_files_named_ci() { # — every existing log file for it, whatever its case + lfn_ls="" + if [ -e "$LANES_LOG_DIR" ]; then + lfn_ls="$(ls -- "$LANES_LOG_DIR" 2>/dev/null)" || return 1 + fi + printf '%s\n' "$lfn_ls" | awk -v want="$1" -v d="$LANES_LOG_DIR" ' + BEGIN { w = tolower(want) ".md" } + tolower($0) == w { print d "/" $0 }' +} + +# The PUBLISHED path of a lane's log, found the same way — the canonical path +# where `origin/` has no file of another case, so a lane with no log at +# all still reads as the pre-cutover 8 rather than as a failure. +# +# TWO PATHS DIFFERING ONLY BY CASE ARE A REFUSAL AND NOT A CHOICE (Copilot round +# 4 on openRepoTools#41). The `exit` after the first match read a tree holding +# BOTH `lanes/log/repocase-1.md` and `lanes/log/repoCase-1.md` as though it held +# one, and every reader behind it — `lane_log_events`, `lane_log_exists`, +# `last-session`, the listing's per-lane facts — then consumed whichever `ls-tree` +# happened to name first and DROPPED the other file's lines without saying so. +# That is two logs for one lane, the state 15(d)'s hand merge exists for, and an +# append-only history half of which is invisible is worse than a refusal. Counted +# and REFUSED (2) naming both, in `canon_lane`'s own shape — it RETURNS rather +# than exits, because every caller takes it with `$( )`. +# +# AND THE WORKING TREE ANSWERS WHERE `origin` HAS NOTHING. The fallback was the +# canonical path outright, which is a path that need not exist: a lane whose log +# is still spelled the old way and has never been pushed has ONE file on disk and +# this named another. `claim`'s dirty-checkout exemption is computed from it, so +# the lane's own uncommitted log read as an unrelated dirty file and the claim was +# refused for it. The same case-insensitive scan every other reader uses answers +# that half (Copilot round 4). +log_path_ci() { # — 0 with the ONE path, 2 where two differ only by case + lpc_exact="$(log_path_for "$1")" + # AMENDMENT 14 — UNDER `--index` THE INDEX'S LOG LIST STANDS IN FOR + # `origin`'s tree, and nothing else in this function changes. + if [ -n "$LANES_IDX_DIR" ] || have_remote_ref; then + if [ -n "$LANES_IDX_DIR" ]; then + lpc_hits="$(awk -v want="$lpc_exact" 'BEGIN { w = tolower(want) } tolower($0) == w' "$LANES_IDX_DIR/logs" 2>/dev/null)" + else + lpc_hits="$(git -C "$LANES_REPO" ls-tree --name-only "origin/$LANES_BRANCH" -- "$LANES_LOG_PREFIX" 2>/dev/null \ + | awk -v want="$lpc_exact" 'BEGIN { w = tolower(want) } tolower($0) == w')" + fi + lpc_n="$(printf '%s' "$lpc_hits" | grep -c . || :)" + if [ "$lpc_n" -gt 1 ]; then + note "lane $1 has $lpc_n object logs on origin/$LANES_BRANCH whose names differ only by case: $(printf '%s\n' "$lpc_hits" | tr '\n' ' ')" + note "one lane is ONE lane under any case and its log is ONE file (Amendment 15), so no read of it is unambiguous and nothing here picks one of them. Merge them by hand into $lpc_exact, oldest lines first, remove the others in the same commit (Amendment 15(d)), and re-run." + return 2 + fi + [ "$lpc_n" = 1 ] && { printf '%s\n' "$lpc_hits"; return 0; } + fi + lpc_loc="$(log_files_named_ci "$1")" + lpc_ln="$(printf '%s' "$lpc_loc" | grep -c . || :)" + if [ "$lpc_ln" -gt 1 ]; then + note "lane $1 has $lpc_ln object logs in this checkout whose names differ only by case: $(printf '%s\n' "$lpc_loc" | tr '\n' ' ')" + note "one lane is ONE lane under any case and its log is ONE file (Amendment 15), so no read of it is unambiguous and nothing here picks one of them. Merge them by hand into $(log_file_for "$1"), oldest lines first, remove the others in the same commit (Amendment 15(d)), and re-run." + return 2 + fi + [ "$lpc_ln" = 1 ] && { printf '%s\n' "${LANES_LOG_PREFIX}${lpc_loc##*/}"; return 0; } + printf '%s\n' "$lpc_exact" +} + +# The repo-relative path `ensure_log` renamed a log AWAY from, for the ONE +# caller that has to put it in the same commit as the write. Empty on every +# other run, and reset by every `ensure_log`, so "renamed" is never sticky. +LOG_RENAMED_FROM="" + +ensure_log() { + lane="$1"; lf="$(log_file_for "$lane")" + LOG_RENAMED_FROM="" + [ -d "$LANES_LOG_DIR" ] || mkdir -p -- "$LANES_LOG_DIR" + el_hits="$(log_files_named_ci "$lane")" + el_n="$(printf '%s' "$el_hits" | grep -c . || :)" + if [ "$el_n" -gt 1 ]; then + die "lane $lane has $el_n object logs whose names differ only by case: $(printf '%s\n' "$el_hits" | tr '\n' ' ')— one lane is ONE lane under any case and its log is ONE file (Amendment 15). Merge them by hand into $lf, oldest lines first, remove the others in the same commit, and re-run. Nothing was written." 2 + fi + # A LOG THIS CHECKOUT HAS NOT PULLED IS STILL THIS LANE-S LOG, AND CREATING + # THE CANONICAL FILE BESIDE IT IS THE SPLIT THIS FUNCTION EXISTS TO PREVENT. + # `log_files_named_ci` reads the WORKING TREE, while every state reader here + # deliberately answers out of `origin/` (R19): on a checkout that is + # behind, a published `lanes/log/repocase-1.md` is invisible to the scan + # above, this write would create `repoCase-1.md`, and `commit_push`-s own + # rebase would then land BOTH. The refusal below is fail-closed and its cure + # is one command, where the cure for two published files is 15(d)-s hand + # merge (Copilot round 1 on openRepoTools#41). + # + # AND THE GUARD IS NOT ONLY FOR A CHECKOUT WITH NO FILE AT ALL (Copilot round 4 + # on openRepoTools#41). It ran under `el_n = 0`, so the state a rename leaves + # when its COMMIT does not land — the canonical file here, the old-cased path + # still in the remote tree — walked straight past it, and the next write staged + # the canonical path alone and left the published one where it was: two files + # for one lane again, by the path this function exists to close. The test is + # therefore on the PATHS and not on the count: a published path that is neither + # the canonical one NOR the one this checkout is about to rename FROM is a + # refusal, which leaves the ordinary rename (local and published agree on the + # old spelling) exactly as it was. + el_from="" + [ "$el_n" = 1 ] && el_from="$el_hits" + if have_remote_ref; then + el_pub="$(log_path_ci "$lane")" || die "lane $lane's object log is published twice (above) and nothing is written under a name that means two files. Merge them by hand (Amendment 15(d)) and re-run. Nothing was written." 2 + if [ "$el_pub" != "$(log_path_for "$lane")" ] && [ "${el_from##*/}" != "${el_pub##*/}" ]; then + el_here="and this checkout does not have it" + [ -n "$el_from" ] && el_here="while this checkout has ${LANES_LOG_PREFIX}${el_from##*/} instead — a case-only rename whose commit never landed" + die "lane ${lane}'s object log is published as $el_pub $el_here: the row spells the lane $lane, so the log is $(log_path_for "$lane") (Amendment 15), and writing one here now would leave TWO files for one lane. Pull first — \`git -C $LANES_REPO pull --rebase\` — and re-run; the rename then happens once, inside this write's own commit. Nothing was written." 2 + fi + fi + if [ -n "$el_from" ] && [ "$el_from" != "$lf" ]; then + # THE RENAME IS ONE ACT AND IT HAPPENS ONCE: after it the canonical name is + # the only one `log_files_named_ci` can find, so the next write takes the + # branch above and does nothing. THROUGH A TEMPORARY NAME, because on a + # case-INSENSITIVE filesystem — macOS, which this repository's CI runs — the + # two names are one file and `mv a A` answers "identical" rather than + # renaming; two `mv`s do the same job on both kinds of filesystem, and + # neither is `git mv`, whose own case-only rename is the thing that differs + # between platforms. The caller puts the old path in this write's pathspecs + # and `commit_push` drops its INDEX entry by that exact path before staging + # the new one, then commits the index rather than the pathspecs — the one + # sequence that records the rename on a case-insensitive filesystem as well + # as on this one, argued in full above `CP_EXACT`. + el_tmp="$lf.amendment15.$$" + # THE REFUSAL SAYS WHERE THE FILE IS, and the two halves fail differently: + # the first `mv` failing leaves the log exactly where it was, while the + # SECOND failing leaves it at `$el_tmp` — a name no reader of this + # directory looks for. A refusal that told a person to "move it by hand" + # without saying which path to move is a refusal they cannot act on, and + # this one costs a lane its whole history if it is acted on wrongly. + if ! mv -- "$el_from" "$el_tmp" 2>/dev/null; then + die "could not rename $el_from to $lf (Amendment 15: the register row's spelling names the lane's log). Nothing was written and the log is untouched at $el_from; rename it by hand and re-run." 5 + fi + if ! mv -- "$el_tmp" "$lf" 2>/dev/null; then + die "could not rename $el_tmp to $lf (Amendment 15: the register row's spelling names the lane's log). Nothing was written, and THIS LANE'S LOG IS NOW AT $el_tmp — rename it to $lf by hand, or back to $el_from, and re-run. It is not lost and no reader looks for it under that name." 5 + fi + LOG_RENAMED_FROM="${LANES_LOG_PREFIX}${el_from##*/}" + note "$el_from → $lf: the register row spells this lane $lane, and the row's spelling names its log (Amendment 15)" + fi + if [ ! -f "$lf" ]; then + printf '# lane %s — object log (lane-collision-protocol Amendment 7)\n' "$lane" > "$lf" + note "created $lf" + fi +} + +# ------------------------------------------------------- the alias table +# +# `lanes/repos.tsv`, `aliasowner/repo`. Consulted when the owner is +# omitted, and when a spelling the register really uses is not the canonical +# nameWithOwner (all four spellings of codexFactory resolve to +# `codeXfactory/codexFactory`, which is the redirect GitHub answers with). +# Matching is case-insensitive: the register spells one repo `OpsxFactory`, +# `opsXfactory` and `opsxfactory` in the same week. +alias_lookup() { + al_k="$1" + for al_tsv in "${LANES_REPOS_TSV:-}" "${LANES_REPOS_TSV_SHIPPED:-}"; do + [ -n "$al_tsv" ] && [ -f "$al_tsv" ] || continue + awk -F'\t' -v k="$al_k" ' + BEGIN { kl = tolower(k) } + /^[ \t]*#/ { next } + NF >= 2 { if (tolower($1) == kl) { print $2; found = 1; exit } } + END { exit(found ? 0 : 1) }' "$al_tsv" && return 0 + done + return 1 +} + +# canon_object [] — prints the canonical object key. +# THE KINDS IN SCOPE, and no others (a later amendment may add keys): +# owner/repo#n an issue or a PR +# owner/repo:openspec/changes/ an OpenSpec change directory +# #n the lane's OWN home repo +# lane: a lane, for the lane-kind lines only +# Human acts, realization groups, contract cuts, file surfaces and Amendment +# 1's substrates stay where they are today — comments on their governing +# records — and are an explicit non-goal here. +canon_object() { + co_raw="$1"; co_home="${2-}"; co_repo=""; co_rest=""; co_owner=""; co_hc="" + case "$co_raw" in + lane:*) + case "${co_raw#lane:}" in + "" | *[!A-Za-z0-9._-]*) note "'$co_raw' is not a lane object: lane:"; return 2 ;; + esac + # AMENDMENT 15 — A LANE OBJECT CARRIES THE ROW'S SPELLING TOO. `lane:` + # is the object of every lane-kind line (7(b)), so a `log PAUSED + # lane:openxfactory-2` on the lane `openXfactory-2` would write a key that + # does not match the lane's own earlier lines — in a file nothing rewrites, + # and against which `who lane:` is then asked. Canonicalised here, so + # the writers and the reader ask the same question of it. + co_cl="$(canon_lane "${co_raw#lane:}")" || return 2 + printf 'lane:%s\n' "$co_cl"; return 0 ;; + '#'*) + case "${co_raw#\#}" in + "" | *[!0-9]*) note "'$co_raw' is not an object key: after '#' comes the issue or PR number"; return 2 ;; + esac + if [ -z "$co_home" ]; then + note "'$co_raw' is shorthand for this lane's home repo, and no home is on record for it." + note " Spell it owner/repo$co_raw, or pass --home owner/repo (a pre-cutover lane has no STARTED line)." + return 2 + fi + if ! valid_nwo "$co_home"; then + note "'$co_home' is not a repository, so '$co_raw' cannot be expanded against it." + note " A home is owner/repo. This one came from the lane's STARTED line or from --home." + return 2 + fi + # R20 — THE HOME GOES THROUGH THE ALIAS TABLE TOO, on the way into a key. + # `home_of_lane` and `resolve_home` both resolve already; this is the last + # gate, so no caller can reach a key by a path that skipped it. A checkout + # whose origin still spells `opensoft/codexFactory` wrote `#5` as a key + # nothing could reconcile with `codeXfactory/codexFactory#5`, and two lanes + # held one issue with no collision detected. + co_hc="$(alias_lookup "$co_home" 2>/dev/null || :)" + [ -n "$co_hc" ] && co_home="$co_hc" + printf '%s%s\n' "$co_home" "$co_raw"; return 0 ;; + *:openspec/changes/*) + co_repo="${co_raw%%:openspec/changes/*}" + co_rest=":openspec/changes/${co_raw#*:openspec/changes/}" + case "${co_rest#:openspec/changes/}" in + "" | *[!A-Za-z0-9._-]*) note "'$co_raw' is not an object key: an OpenSpec change is owner/repo:openspec/changes/"; return 2 ;; + esac ;; + *'#'*) + co_repo="${co_raw%%#*}" + co_rest="#${co_raw#*#}" + case "${co_rest#\#}" in + "" | *[!0-9]*) note "'$co_raw' is not an object key: after '#' comes the issue or PR number"; return 2 ;; + esac ;; + *) + note "'$co_raw' is not an object key. In scope: owner/repo#, owner/repo:openspec/changes/, # for this lane's home repo, lane:." + return 2 ;; + esac + [ -n "$co_repo" ] || { note "'$co_raw' names no repository"; return 2; } + co_owner="$(alias_lookup "$co_repo" 2>/dev/null || :)" + if [ -z "$co_owner" ]; then + case "$co_repo" in + */*) co_owner="$co_repo" ;; # a spelled owner/repo is always accepted + *) + note "unknown repo alias '$co_repo' — spell it owner/repo (the canonical GitHub nameWithOwner), or add it to ${LANES_LOG_PREFIX%log/}repos.tsv" + return 2 ;; + esac + fi + case "$co_owner" in + */*/*|*/) note "the alias table maps '$co_repo' to '$co_owner', which is not owner/repo"; return 2 ;; + */*) : ;; + *) note "the alias table maps '$co_repo' to '$co_owner', which is not owner/repo"; return 2 ;; + esac + case "$co_owner" in *[!A-Za-z0-9./_-]*) note "'$co_owner' is not a usable owner/repo"; return 2 ;; esac + printf '%s%s\n' "$co_owner" "$co_rest" +} + +# owner/repo, and nothing else: exactly one slash, and only the characters +# GitHub allows in either half. `--home 'not a repo'` used to go straight into +# an object key, and the helper wrote `not a repo#42` — a line its OWN parser +# cannot read back, in a log nothing ever rewrites. +valid_nwo() { [[ "${1-}" =~ ^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$ ]]; } + +# A TRANSCRIPT UUID, and nothing else — the shape `claude --resume` takes +# exactly and the one every event line's `session` field carries (Amendment +# 7(b), Definitions sense 1). Not a PR-footer `session_01…`, not a session +# NAME, and not the literal `unknown`: `write_event` refuses all three. +valid_uuid() { [[ "${1-}" =~ ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$ ]]; } + +# The home repo for this invocation. `--home` is for a PRE-CUTOVER lane — one +# whose log has no STARTED line — and is REFUSED where the log already answers +# the question, so the flag and the log can never disagree. It is resolved +# through the alias table and then validated, like any other spelling. +# +# R30 (Addendum 7) — AND EVERY CALLER ASKS AFTER THE FETCH. The STARTED line it +# reads is `origin/`'s, like every other state read, so a home a peer +# recorded is invisible here until `log_sync` has run: asked before it, `--home` +# was ACCEPTED on a lane whose own log already answers the question — the one +# refusal this flag has — and the object key it then built was the second +# spelling of an issue another lane was already holding. `who` and `lane-end`'s +# `resolve-home` preflight fetched first already; `log`, `claim` and `release` +# now do too, so the preflight and the write can still never disagree. +# +# Called as `home="$(resolve_home "$lane" "$override")" || exit $?` — a `die` +# in here runs inside the command substitution, so the caller must pass the +# code on rather than carry on with an empty home. +resolve_home() { + rh_lane="${1-}"; rh_over="${2-}"; rh_log="" + [ -n "$rh_lane" ] && rh_log="$(home_of_lane "$rh_lane" 2>/dev/null || :)" + if [ -n "$rh_over" ]; then + if [ -n "$rh_log" ]; then + note "lane $rh_lane's own log already records its home: $rh_log (from its STARTED line)." + die "--home is for a pre-cutover lane, one whose log has no STARTED line. Drop it, or correct the lane's home by appending a new STARTED line through lane-start." 2 + fi + rh_res="$(alias_lookup "$rh_over" 2>/dev/null || :)"; rh_over="${rh_res:-$rh_over}" + valid_nwo "$rh_over" || die "--home takes owner/repo (the canonical GitHub nameWithOwner), or an alias in ${LANES_LOG_PREFIX%log/}repos.tsv: '${2-}' is neither" 2 + printf '%s\n' "$rh_over" + return 0 + fi + printf '%s\n' "$rh_log" +} + +is_lane_object() { case "$1" in lane:*) return 0 ;; esac; return 1; } +object_repo() { case "$1" in lane:*) printf '\n' ;; *:openspec/changes/*) printf '%s\n' "${1%%:openspec/changes/*}" ;; *) printf '%s\n' "${1%%#*}" ;; esac; } +object_number() { case "$1" in lane:*|*:openspec/changes/*) printf '\n' ;; *'#'*) printf '%s\n' "${1##*#}" ;; *) printf '\n' ;; esac; } +object_slug() { case "$1" in *:openspec/changes/*) printf '%s\n' "${1##*/}" ;; *'#'*) printf '%s\n' "${1##*#}" ;; *) printf '%s\n' "$1" ;; esac; } + +# ------------------------------------------------------- reading the logs +# +# One parser, used by everything. It prints US-separated fields, UTC first: +# utc lane verb uuid ws object ref payload text file line +# +# The last two are the line's ADDRESS — the file it was read from and its +# number IN THAT FILE (FNR, so it is the number the reader sees in the log and +# the number an `unreadable:` report names). That address is what every state +# read orders by (R14): the log is append-only, so a line further down the file +# is a line written later, whatever the two lines' UTC fields say. +# `match()` is used for every multi-byte separator: RSTART and RLENGTH are in +# the same units as each other whatever the locale, and a hard-coded byte +# offset for " — " is not. +# AMENDMENT 16(e) — A LINE'S LANE IS THE LANE OF THE FILE IT IS IN, and that is +# the whole of the rule. +# +# Clause (c) is explicit that a rename rewrites none of the lines above it: +# *"the lines above it — which still say `lane ` — are never rewritten"*. +# So after a rename a lane's log holds its whole history under two names, in one +# file, about one lane — the exact shape Amendment 15 met when one lane's log +# spelled it two ways, and the exact failure: `lane_objects`, `superseded_by`, +# `holders_of`, `lane_row_facts` and `first_landed_of` all key on this field, so +# read byte for byte HALF A RENAMED LANE'S HOLDS BECOME INVISIBLE — `who --lane` +# calls a held object free and `lane-end` ends a lane that holds one. +# +# THE FIRST ANSWER WAS AN ALIAS LOOKUP IN THIS PARSE, AND IT WAS THE WRONG ONE +# (Copilot round 1 on openRepoTools#81). A rename FREES the old name — no row +# carries it, so `lane_next_free` hands the position out and a NEW lane can be +# called it — and from that moment the field `lane ` is ambiguous: it is +# the renamed lane's history in one file and the new lane's present in another. +# No amount of resolving a NAME tells those apart, because the name is the same. +# +# THE FILE DOES. Amendment 7's first sentence is one file per lane, single +# writer, and Amendment 15 makes its name the row's own spelling — so +# `lanes/log/.md` IS the statement of which lane every line in it belongs +# to, it MOVES with the rename (clause (c)), and it needs no table to read. The +# field stays on the line as the spelling somebody typed; the FILE is what the +# readers are keyed on. That also settles, with nothing added, the two spellings +# of one lane Amendment 15 had to reason about line by line. +LOG_AWK=' +function trim(s) { sub(/^[ \t]+/, "", s); sub(/[ \t]+$/, "", s); return s } +# The lane a FILE belongs to: its base name without `.md`. `FN` is the +# repo-relative path `remote_log_events` hands in; `FILENAME` is awk-s own for a +# file read from disk. Computed once per file rather than per line. +function filelane( f, n, parts) { + f = (FN != "" ? FN : FILENAME) + if (f == "") return "" + n = split(f, parts, "/") + f = parts[n] + sub(/\.[Mm][Dd]$/, "", f) + return f +} +# A LINE IS NEVER DROPPED SILENTLY. This log is append-only and nothing in it +# is ever rewritten, so a line no parser can read is a hold no tool will +# mention again — `who` would call the object free, and it is not. +function bad(why, f) { + f = (FN != "" ? FN : FILENAME) + printf "unreadable: %s:%d (%s)\n", f, FNR, why > "/dev/stderr" + nbad++ +} +FNR == 1 { FL = "" } +{ + line = $0 + if (line ~ /^[ \t]*#/ || line ~ /^[ \t]*$/) next + if (match(line, / — /) == 0) { bad("no \" — \" after the verb"); next } + verb = trim(substr(line, 1, RSTART - 1)) + rest = substr(line, RSTART + RLENGTH) + if (index(verb, " ") > 0) { bad("the verb is one token: \"" verb "\""); next } + if (substr(rest, 1, 5) != "lane ") { bad("no \"lane \" field"); next } + rest = substr(rest, 6) + q = index(rest, ","); if (q == 0) { bad("no \",\" after the lane"); next } + lane = trim(substr(rest, 1, q - 1)); rest = trim(substr(rest, q + 1)) + if (substr(rest, 1, 8) != "session ") { bad("no \"session @\" field"); next } + rest = substr(rest, 9) + q = index(rest, ","); if (q == 0) { bad("no \",\" after the session"); next } + sess = trim(substr(rest, 1, q - 1)); rest = trim(substr(rest, q + 1)) + a = index(sess, "@") + uuid = (a ? substr(sess, 1, a - 1) : sess) + ws = (a ? substr(sess, a + 1) : "") + # The UTC is matched by SHAPE. Taking it up to the next comma would be + # wrong for any line whose object is followed by nothing at all. The + # seconds are optional: the register carries `…T20:31Z` lines from before + # this helper existed, and refusing to read one loses a hold. + if (match(rest, /^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9](:[0-9][0-9])?Z/) == 0) { bad("no YYYY-MM-DDTHH:MM[:SS]Z"); next } + utc = substr(rest, RSTART, RLENGTH) + rest = substr(rest, RSTART + RLENGTH) + if (substr(rest, 1, 1) != ",") { bad("no \",\" and object after the UTC"); next } + rest = trim(substr(rest, 2)) + # The object token contains no space and no comma, so it ends at the first + # space — which is what makes the payload unambiguous however it is spelled. + sp = index(rest, " ") + if (sp == 0) { obj = rest; rest = "" } + else { obj = substr(rest, 1, sp - 1); rest = substr(rest, sp + 1) } + ref = ""; payload = ""; txt = "" + # Every test below is a REGEX, never a substr() width: RSTART and RLENGTH + # are in whatever unit the locale counts in, and they agree with each other. + # A hard-coded 4 for "— " does not, and gawk counts characters. + if (rest != "") { + if (match(rest, /^— /)) { txt = trim(substr(rest, RSTART + RLENGTH)) } + else { + if (match(rest, / — /)) { txt = trim(substr(rest, RSTART + RLENGTH)); rest = trim(substr(rest, 1, RSTART - 1)) } + if (match(rest, /^→ /)) { ref = "→"; payload = trim(substr(rest, RSTART + RLENGTH)) } + else if (match(rest, /^← /)) { ref = "←"; payload = trim(substr(rest, RSTART + RLENGTH)) } + else { payload = trim(rest) } + } + } + if (FL == "") FL = filelane() + if (FL != "") { + # THE LANE-KIND OBJECT IS THE WRITING LANE AND NOTHING ELSE (Amendment + # 7(b)), so it follows the same rule: `lane:` in a renamed lane-s own + # log is that lane under the name it had, and `who lane:` asks + # `canon_object` -> `canon_lane` of the name it was given, which lands on + # the same answer from the other side. + lane = FL + if (substr(obj, 1, 5) == "lane:") obj = "lane:" FL + } + printf "%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s%c%d\n", utc, 31, lane, 31, verb, 31, uuid, 31, ws, 31, obj, 31, ref, 31, payload, 31, txt, 31, (FN != "" ? FN : FILENAME), 31, FNR +} +END { if (nbad > 0) printf "%d unreadable line(s) above — an append-only log is never rewritten, so a line no parser reads is a hold no tool will mention again\n", nbad > "/dev/stderr" }' + +parse_log_stream() { awk -v FN="${1:-}" "$LOG_AWK"; } + +log_files() { + for le_f in "$LANES_LOG_DIR"/*.md; do + [ -e "$le_f" ] || continue + case "${le_f##*/}" in README.md) continue ;; esac + printf '%s\n' "$le_f" + done +} + +log_events() { + le_files=() + if [ "$#" -gt 0 ]; then + le_files=("$@") + else + while IFS= read -r le_f; do [ -n "$le_f" ] && le_files+=("$le_f"); done <` to read from at all? Outside a repository, and +# under the LANES_NO_GIT=1 harness, there is not, and the working tree is all +# there is. +have_remote_ref() { + [ "$NO_GIT" = 1 ] && return 1 + git -C "$LANES_REPO" rev-parse --verify -q "origin/$LANES_BRANCH" >/dev/null 2>&1 +} + +# The same events, read from `origin/` instead of the working tree. +# EVERY state read goes through state_events() below, which reads THIS: what +# has LANDED is what other lanes can see, and a working tree can be anything — +# behind by a peer's whole day, or carrying a line that never lands. +remote_log_events() { + # AMENDMENT 14 — under `--index`, the index's events of every log, in the + # order and the grammar this function prints them in, and the warnings + # `LOG_AWK` would have printed for the lines it could not read. + if [ -n "$LANES_IDX_DIR" ]; then + cat -- "$LANES_IDX_DIR/warn" >&2 2>/dev/null || : + cat -- "$LANES_IDX_DIR/events" + return 0 + fi + [ "$NO_GIT" = 1 ] && { log_events; return 0; } + git -C "$LANES_REPO" rev-parse --verify -q "origin/$LANES_BRANCH" >/dev/null 2>&1 || { log_events; return 0; } + # A LOG THE TREE NAMES AND `show` CANNOT READ IS SAID, by path (#138 item + # 11). The parser's status is the pipeline's, so the failure left no trace: + # the lane simply had no lines, which the listing reads as DORMANT. The line + # reaches the person through `state_events`' warnings, and `lanes_rows` reads + # it back out of that file by its fixed prefix. + # AND A LIST OF THE LOGS THAT COULD NOT BE MADE IS SAID THE SAME WAY (the + # review of #289, SHOULD-1(a)). Piped straight into the loop, a failed + # `ls-tree` was no logs at all: every lane lost its events - its `dir` among + # them - in silence. `worktree_rows` reads this line back out of the same + # warnings, and because the events are built once per process, it speaks for + # the very read every lane's `dir` came from. + rl_list="" + if ! rl_list="$(git -C "$LANES_REPO" ls-tree --name-only "origin/$LANES_BRANCH" -- "$LANES_LOG_PREFIX" 2>/dev/null)"; then + note "unlisted logs: $LANES_LOG_PREFIX on origin/$LANES_BRANCH — git could not list them, so no log's lines are in this read" + return 0 + fi + printf '%s\n' "$rl_list" \ + | while IFS= read -r rf; do + [ -n "$rf" ] || continue + case "${rf##*/}" in README.md) continue ;; esac + git -C "$LANES_REPO" show "origin/$LANES_BRANCH:$rf" 2>/dev/null | parse_log_stream "$rf" + [ "${PIPESTATUS[0]}" = 0 ] || note "unreadable log: $rf — git could not read it, so none of its lines are in this read" + done +} + +# THE SOURCE OF EVERY STATE READ. Cached for the life of one invocation, +# because `who` on a held object asks for it eight or nine times (the state +# scan, the superseded filter once per holder, staleness twice, the crossing +# check) and reading it is 45 `git show`s. Any write flushes it: `claim` +# rescans after its rebase, and the ref has moved by then. +SE_CACHE_FILE="$(mktemp "${TMPDIR:-/tmp}/lanes-edit-events.XXXXXX" 2>/dev/null || printf '')" +# THE BUILD'S WARNINGS OUTLIVE THE BUILD, AND THAT IS NOT A CONVENIENCE. +# `LOG_AWK` writes `unreadable: :` and its count to stderr WHILE the +# stream is parsed — so they were emitted by whichever caller happened to build +# the cache first, and lost entirely when that caller was a command substitution +# with `2>/dev/null`. That was always true and never mattered, because the +# first builder in `who` was a call whose stderr reached the person. Ruling 12's +# one-pass listing moved the first build into exactly such a substitution — the +# `lr_facts` render — and the whole warning vanished from `who --lane`, caught +# by the two assertions that exist for it. +# +# So the build's stderr is CAPTURED beside the cache and replayed once per +# shell. `SE_WARNED` is deliberately a plain variable: a subshell that replays +# into `/dev/null` sets it only in ITSELF, so the parent still warns at its own +# first call — which is the call whose stderr a person is reading. An +# append-only log is never rewritten, so a line no parser reads is a hold no +# tool will mention again: this warning is the only notice there is. +SE_WARN_FILE="${SE_CACHE_FILE:+$SE_CACHE_FILE.warn}" +SE_WARNED=0 +state_events_warn() { + [ "$SE_WARNED" = 1 ] && return 0 + [ -n "$SE_WARN_FILE" ] && [ -s "$SE_WARN_FILE" ] || return 0 + SE_WARNED=1 + cat -- "$SE_WARN_FILE" >&2 + return 0 +} +state_events() { + if [ -z "$SE_CACHE_FILE" ]; then remote_log_events; return 0; fi + if [ ! -s "$SE_CACHE_FILE" ]; then + # BUILT ATOMICALLY, because `claim` asks for this from both ends of one + # pipeline: `state_events | lane_states_on | holders_of`, and holders_of + # calls superseded_by, which asks again while the first read is still + # writing. A half-written cache read as a whole one loses lines, and a + # lost line is a hold that has vanished. Write to a per-subshell name and + # rename: a reader then sees either the empty file (and builds its own) or + # the finished one, never half of it. + se_t="$SE_CACHE_FILE.${BASHPID:-$$}" + remote_log_events > "$se_t" 2> "$se_t.warn" + mv -f -- "$se_t.warn" "$SE_WARN_FILE" 2>/dev/null || rm -f -- "$se_t.warn" + mv -f -- "$se_t" "$SE_CACHE_FILE" 2>/dev/null || { state_events_warn; cat -- "$se_t"; rm -f -- "$se_t"; return 0; } + fi + state_events_warn + cat -- "$SE_CACHE_FILE" +} +state_events_flush() { + [ -n "$SE_CACHE_FILE" ] && : > "$SE_CACHE_FILE" + # The warnings belong to the stream that was parsed; a flush means it is + # parsed again, so they are said again. + [ -n "$SE_WARN_FILE" ] && : > "$SE_WARN_FILE" + SE_WARNED=0 + return 0 +} + +# One lane's own events, and whether that lane has a log at all — from +# `origin/` for the same reason. A lane whose log exists only in this +# working tree has not published anything, and a lane whose log exists only on +# `origin` is a lane this checkout has not pulled: the second is the case that +# matters and the one that used to read as "pre-cutover". +# +# AMENDMENT 15 — AND THE FILE IS FOUND WHATEVER ITS CASE. A lane whose log was +# written under another spelling has not lost its history the moment its row's +# spelling becomes canonical; the first write renames the file, and until then +# every reader finds it. +# +# BOTH HALVES ASK `log_path_ci`, AND A `head -n1` IS NOT AN ANSWER (Copilot round +# 4 on openRepoTools#41). The working-tree branch took the first of the +# case-insensitive matches exactly as the published lookup did, so two local +# files made a read-only caller decide a lane's resume, its profile and its state +# out of half its history — silently, while the WRITER treats that same state as +# ambiguous and refuses. One resolver now answers both, and its 2 is carried: +# `lane_log_exists` spends it rather than 1, so "there are two logs" is never +# read as "there is no log". +lane_log_events() { + ll_rel="$(log_path_ci "$1")" || return 2 + if [ -n "$LANES_IDX_DIR" ]; then + # A LOG THE INDEX DOES NOT HOLD IS A LOG `origin` DID NOT HOLD at the + # indexed commit: no lines, exactly as a `git show` of a missing path. + command grep -Fqx -- "$ll_rel" "$LANES_IDX_DIR/logs" 2>/dev/null || return 0 + awk -F"$US" -v p="$ll_rel" '$10 == p' "$LANES_IDX_DIR/events" + # THAT LOG'S WARNINGS AND THE COUNT THAT CLOSES THEM (opensoft/openRepoTools#166 + # item 3): the source read runs LOG_AWK over this one file, whose END says + # how many lines it could not read. The export writes that line after each + # log's own warnings, so it is the line straight after this log's last one. + awk -v p="unreadable: $ll_rel:" ' + index($0, p) == 1 { print; mine = 1; next } + mine && /^[0-9]+ unreadable line[(]s[)] above/ { print } + { mine = 0 }' "$LANES_IDX_DIR/warn" >&2 2>/dev/null || : + return 0 + elif have_remote_ref; then + git -C "$LANES_REPO" show "origin/$LANES_BRANCH:$ll_rel" 2>/dev/null | parse_log_stream "$ll_rel" + else + ll_f="$LANES_LOG_DIR/${ll_rel##*/}" + [ -f "$ll_f" ] || return 0 + log_events "$ll_f" + fi +} +lane_log_exists() { + lle_rel="$(log_path_ci "$1")" || return 2 + if [ -n "$LANES_IDX_DIR" ]; then + command grep -Fqx -- "$lle_rel" "$LANES_IDX_DIR/logs" 2>/dev/null + elif have_remote_ref; then + git -C "$LANES_REPO" cat-file -e "origin/$LANES_BRANCH:$lle_rel" 2>/dev/null + else + [ -f "$LANES_LOG_DIR/${lle_rel##*/}" ] + fi +} + +# The register, read the same way — `who --landing` is a state read about a +# merge hold other lanes are holding their merges for, so it must see what +# landed rather than what this checkout happens to have pulled. +# CACHED FOR THE LIFE OF ONE PROCESS, and Amendment 11's listing is the reason. +# The published register is a 1 MB file and this is a `git show` of it; every +# `row_of_lane`, `lane_named_ci`, `lane_of_session` and `lane_workstation` call +# makes one. A single lane's act makes a handful and nobody noticed — but +# `lanes` asks about EVERY lane in the register, so the same megabyte was being +# re-rendered dozens of times for one listing a person is waiting on. +# +# IT IS SAFE BECAUSE NOTHING INSIDE ONE INVOCATION MOVES IT. `origin/` +# is advanced by `log_sync`, which every subcommand runs BEFORE it reads, and by +# `commit_push`, which runs AFTER the last read of a write path — so the ref a +# process reads is fixed for as long as that process reads it. The one act that +# would break that assumption is a second `log_sync` mid-read, and there is +# none; `log_sync` clears this cache anyway, so a caller that adds one gets the +# fresh answer rather than a stale one. +# AND IN A FILE AS WELL AS A VARIABLE (A11 Addendum 4 ruling 12). The variable +# serves one shell; every caller of `row_of_lane`, `lane_workstation` and +# `session_ids_of_lane` reaches it through `$( … )`, which is a SUBSHELL, so the +# variable cache was rebuilt — a `git show` of 1.1 MB — by all four of the +# per-lane reads the listing makes, for every lane. The file survives the +# subshell that wrote it, so the megabyte is rendered once per process. +# +# AND THE READ SAYS WHETHER IT HAPPENED (opensoft/openRepoTools#67). +# `register_text_checked` is the read itself: 0 with the register on stdout, and +# 1 where the published `git show` or the working tree's `cat` FAILED — what it +# prints then is whatever that read printed, so `register_text` renders a failed +# read exactly as it always did, and it is not an answer. `register_text` is the +# same read with the status thrown away, as it always was, because its callers +# are pipelines whose `awk` answers for them and rewriting all of them is not +# this change. The three callers for which an empty register is a VERDICT ask +# the checked read through `session_ids_checked` below. +# +# A FAILED READ IS NEVER CACHED, in the variable or in the file. It used to be: +# the empty render went into both, so the first caller to meet a failed read — +# `canon_lane`, which `claim` and `duplicate-holder` both run first — left every +# later read in the process an empty register with no failure left to report, +# and a checked read behind it would have been reading that cache instead of the +# register. The next read asks again, and gets the same failure or the register. +LANES_REGISTER_CACHE="" +register_text_checked() { + # AMENDMENT 14 — under `--index`, the register's rows and its Rule 6 and + # Amendment 10 lines as the index holds them, in register order. Not cached: + # it is one local file, and the cache below belongs to the published read. + if [ -n "$LANES_IDX_DIR" ]; then cat -- "$LANES_IDX_DIR/register"; return; fi + if [ -n "$LANES_REGISTER_CACHE" ]; then printf '%s\n' "$LANES_REGISTER_CACHE"; return 0; fi + rt_c="${SE_CACHE_FILE:+$SE_CACHE_FILE.register}" + if [ -n "$rt_c" ] && [ -s "$rt_c" ]; then cat -- "$rt_c"; return; fi + rt_txt=""; rt_rc=0 + # WHETHER THE REGISTER IS PUBLISHED IS `register_published`'s answer, the + # tree's (#138 item 18, the review of #230): asked with `cat-file -e`, a + # missing or corrupt blob was "not published" and this checkout's copy was + # read in its place — an answer, where #67's rule above makes it a 1. + rt_prc=0; register_published || rt_prc=$? + case "$rt_prc" in + 0) rt_txt="$(git -C "$LANES_REPO" show "origin/$LANES_BRANCH:$LANES_PATH" 2>/dev/null)" || rt_rc=$? ;; + 8) rt_txt="$(cat -- "$LANES_FILE")" || rt_rc=$? ;; + *) rt_rc=1 ;; + esac + if [ "$rt_rc" != 0 ]; then + printf '%s\n' "$rt_txt" + return 1 + fi + LANES_REGISTER_CACHE="$rt_txt" + if [ -n "$rt_c" ]; then + printf '%s\n' "$LANES_REGISTER_CACHE" > "$rt_c.${BASHPID:-$$}" 2>/dev/null && + mv -f -- "$rt_c.${BASHPID:-$$}" "$rt_c" 2>/dev/null || + rm -f -- "$rt_c.${BASHPID:-$$}" + fi + printf '%s\n' "$LANES_REGISTER_CACHE" +} +register_text() { register_text_checked || :; } + +# IS THE REGISTER PUBLISHED? 0 yes, 8 no (or there is no `origin/`), 1 +# the tree could not be listed. THE TREE ANSWERS AND NEVER THE BLOB (#138 item +# 18, the review of #230): `cat-file -e` fails for a blob that is missing or +# corrupt exactly as for a path origin does not have, so a register origin has +# and git could not read was "not published", and `register_text` answered with +# this checkout's copy — the seam, `next-free` and `add-row` all read that as +# the published register. `retire_rows` asks a lane's log the same way (item 17). +# THE PATH IS AN ARGUMENT, the register's by default: `archive_text` asks it of +# the archive, which had the same `cat-file -e` and the same fallback. +register_published() { # [] + have_remote_ref || return 8 + rp_tree="" + rp_tree="$(git -C "$LANES_REPO" ls-tree --name-only "origin/$LANES_BRANCH" -- "${1:-$LANES_PATH}" 2>/dev/null)" || return 1 + [ -n "$rp_tree" ] || return 8 + return 0 +} + +# ------------------------- AMENDMENT 19(d): THE ARCHIVE IS PART OF THE READ +# +# `archive-rows ` moves a repository's RETIRED rows out of the register +# and into `lanes/archive/LANES-retired.md`, and the amendment is explicit about +# who follows them: *"every reader of the next free position and `lanes +# --closed` read the archive too"*. So the archive is read exactly as the +# register is — `origin/` first (R19), this checkout second — and its +# ABSENCE IS SILENCE: a register nobody has archived from has no such file, and +# that is the ordinary case rather than an error. +# +# It is NOT cached the way `register_text` is: this file is the small one (the +# rows nobody reads day to day), and a write that rescans it after its rebase +# (`add-row`'s `retired_identity_hits`) must read it as it now stands, which a +# cache kept for the process would not. ONE LISTING PINS IT, and only for its +# own reads: `worktree_rows` reads the archive once, and where that read +# succeeded, `PIN_ARCHIVE` hands its text to every read of the listing it then +# makes - so the archive the listing names lanes from IS the one it checked (the +# review of opensoft/openRepoTools#289, SHOULD-1(b): a read that failed only +# after the check left the archive's lanes out of a listing taken as whole). +LANES_ARCH_NAME="LANES-retired.md" +LANES_ARCH_PATH="${LANES_ARCH_PATH:-${LANES_PREFIX}archive/$LANES_ARCH_NAME}" +LANES_ARCH_FILE="${LANES_ARCH_FILE:-$LANES_DIR/archive/$LANES_ARCH_NAME}" +PIN_ARCHIVE=0 +PIN_ARCHIVE_TEXT="" +archive_text() { + if [ "$PIN_ARCHIVE" = 1 ]; then printf '%s' "$PIN_ARCHIVE_TEXT"; return 0; fi + # AMENDMENT 14 — under `--index`, the archive's rows where the indexed commit + # carried an archive; where it carried none, the same local fallback below. + if [ -n "$LANES_IDX_DIR" ] && [ -f "$LANES_IDX_DIR/archive" ]; then cat -- "$LANES_IDX_DIR/archive"; return 0; fi + # A published archive that cannot be rendered cannot be replaced with a + # possibly stale local copy: that copy may omit a retired position. WHETHER + # IT IS PUBLISHED IS THE TREE'S ANSWER (the re-review of #230): asked with + # `cat-file -e`, an archive blob git could not read was "not published", the + # local copy answered, and a retired position was offered and reissued. + if [ -z "$LANES_IDX_DIR" ]; then + at_prc=0; register_published "$LANES_ARCH_PATH" || at_prc=$? + case "$at_prc" in + 0) if git -C "$LANES_REPO" show "origin/$LANES_BRANCH:$LANES_ARCH_PATH" 2>/dev/null; then return 0; fi + note "the published $LANES_ARCH_PATH exists but could not be read — a local copy cannot prove it contains every published retired position" + return 1 ;; + 8) : ;; + *) note "the tree of origin/$LANES_BRANCH could not be listed, so whether $LANES_ARCH_PATH is published is not known — and a local copy cannot stand in for it" + return 1 ;; + esac + fi + # AND THE LOCAL COPY IS THE SAME RULE ONE RUNG DOWN: a file that is THERE and + # will not open is a read that FAILED, and its rows hold positions. Saying + # nothing here would put a retired `-` back on offer. + archive_local_text +} + +# THIS CHECKOUT'S ARCHIVE: its text, nothing where there is none, and 1 where +# the path is THERE AND IS NOT A REGULAR FILE (#138 item 7) as well as where it +# will not open. Asked with `-f` alone, a directory, a FIFO or a broken symlink +# read as no archive and its retired positions came back on offer; `cat` on the +# FIFO would have blocked besides. `archive_text`'s last rung and +# `retired_identity_hits`' second read are both this. +archive_local_text() { + if [ -f "$LANES_ARCH_FILE" ]; then + cat -- "$LANES_ARCH_FILE" 2>/dev/null || return 1 + elif [ -e "$LANES_ARCH_FILE" ] || [ -L "$LANES_ARCH_FILE" ]; then + note "$LANES_ARCH_PATH is there and is not a regular file, so the retired positions it should hold cannot be read" + return 1 + fi + return 0 +} + +# A retired name OR its numeric position is unavailable, even when a recut +# suffix changes the spelling. Inspect both published and unpushed archives. +# +# A LINE THE SCAN CANNOT TAKE APART IS A REFUSAL, NOT A NON-ROW (#122, Copilot +# round 6 on #93). The scan skipped every `|` line with no backticked token, and +# took the first backtick ANYWHERE in a line as its lane, so a retired row whose +# lane cell a hand edit or a bad merge had mangled — `| repoX-4 | harness `` +# | …` — dropped out of the answer and add-row reissued its position: 19(b)'s +# guarantee failing open. Every `|` line of the archive is now one of three: +# +# * THE RULE: `|`, `-`, `:` and blanks only, with at least one dash; +# * THE HEADER: its first cell is the word `lane`, as in the header +# `archive_rows` writes. It is NOT found as "the line above the rule": the +# live register carried two rows between its header and its rule on +# 2026-10-19, so a hand edit can part the two, and refusing a header for it +# would make add-row refuse on the path that creates every lane. Nor is it +# found by counting ` | `: the header carries six, exactly as a row does; +# * A ROW: its first backticked token lies wholly inside its FIRST cell. That +# is the token every reader here takes as the lane, `*(unnamed)* ``` +# included (three live rows are spelled that way). +# +# Any other `|` line is printed with its line number, and this returns 3: a row +# nobody can read may be the very lane being added. AND THE SCAN'S OWN STATUS +# IS READ. The scan's status used to be that of the `sort -u` behind it, so an +# awk that FAILED read as "no archived row matched". +# +# EACH LINE NUMBER NAMES ITS COPY (the review of #263, NIT 4). Both copies are +# scanned, and where the published archive and this checkout's differ, one bad +# line had two numbers and no word on which file either was in. +RETIRED_ROWS_AWK=' + function key(n, h, p) { + p = n; sub(/^.*-/, "", p); sub(/[A-Za-z]$/, "", p) + h = n; sub(/-[^-]*$/, "", h) + if (h == n || p !~ /^[0-9]+$/) return "" + return tolower(h) "-" (p + 0) + } + BEGIN { wk = key(want) } + substr($0, 1, 1) == "|" { + if ($0 ~ /^[|][-:| \t]*$/ && index($0, "-")) next + c = substr($0, 2); s = index(c, " | "); if (s) c = substr(c, 1, s - 1) + h = c; sub(/^[ \t]+/, "", h); sub(/[ \t|]+$/, "", h) + if (tolower(h) == "lane") next + p1 = index(c, "`"); p2 = p1 ? index(substr(c, p1 + 1), "`") : 0 + if (!p1 || p2 < 2) { printf "M%s%d%s%s\n", sep, NR, sep, $0; next } + t = substr(c, p1 + 1, p2 - 1) + if (tolower(t) == tolower(want) || (wk != "" && key(t) == wk)) printf "H%s%s\n", sep, t + }' +retired_identity_hits() { # ; stdout: matching retired spellings · 1 not read · 3 a line not a row + ri_lane="$1" + ri_pub="$(archive_text 2>/dev/null)" || return 1 + ri_local="" + ri_local="$(archive_local_text 2>/dev/null)" || return 1 + ri_scan="" + ri_scan="$(printf '%s\n' "$ri_pub" | awk -v want="$ri_lane" -v sep="$US" "$RETIRED_ROWS_AWK")" || return 1 + ri_scan2="" + ri_scan2="$(printf '%s\n' "$ri_local" | awk -v want="$ri_lane" -v sep="$US" "$RETIRED_ROWS_AWK")" || return 1 + # WHICH COPY `archive_text` ANSWERED WITH: the index's under `--index`, else + # origin's where the tree publishes one, else this checkout's (its own rungs, + # read the same way; a read that failed has already returned 1 above). + ri_from="this checkout" + if [ -n "$LANES_IDX_DIR" ]; then + [ -f "$LANES_IDX_DIR/archive" ] && ri_from="the index" + elif register_published "$LANES_ARCH_PATH" >/dev/null 2>&1; then + ri_from="origin/$LANES_BRANCH" + fi + ri_bad="" + ri_bad="$( { printf '%s\n' "$ri_scan" | awk -v sep="$US" -v w="$ri_from" 'substr($0, 1, 2) == "M" sep { print w sep substr($0, 3) }' + printf '%s\n' "$ri_scan2" | awk -v sep="$US" -v w="this checkout" 'substr($0, 1, 2) == "M" sep { print w sep substr($0, 3) }'; } | + awk -F"$US" '{ k = $2 FS $3 + if (!(k in w)) { o[++n] = k; w[k] = $1 } else if (w[k] != $1) w[k] = w[k] " and " $1 } + END { for (i = 1; i <= n; i++) { split(o[i], p, FS); print "line " p[1] " (" w[o[i]] "): " p[2] } }')" || return 1 + if [ -n "$ri_bad" ]; then + note "$LANES_ARCH_PATH carries a table line that is neither its header, its rule, nor a row whose first cell holds its lane in backticks (each named with the copy it is in):" + printf '%s\n' "$ri_bad" | sed -e 's/^/lanes-edit: /' >&2 + return 3 + fi + ri_hits="" + ri_hits="$(printf '%s\n%s\n' "$ri_scan" "$ri_scan2" | + awk -v sep="$US" 'substr($0, 1, 2) == "H" sep { print substr($0, 3) }')" || return 1 + [ -z "$ri_hits" ] || printf '%s\n' "$ri_hits" | LC_ALL=C sort -u +} + +# EVERY REFUSAL HERE TAKES ITS ROW BACK, not only the retired match (the review +# of #263, M1). This runs after `pull --rebase`, so the add-row is already a +# local commit on top of the peer's archive. A refusal that only returned left +# that commit at HEAD, and the next unrelated write from this checkout pushed +# it: measured, a peer's archive line this scan could not take apart during +# add-row's pull gave exit 1, then `set-row-state` published the row it had +# refused. A read that failed and a line that is not a row are refusals of the +# same row as a retired match is, so all three run the same compensation. +add_row_retirement_rescan() { + ar_rebased_rc=0 + ar_rebased_hits="$(retired_identity_hits "$ADD_ROW_LANE")" || ar_rebased_rc=$? + if [ "$ar_rebased_rc" != 0 ]; then + ar_why="the archive could not be read after rebase, or it carries a line that is not a row (above), so whether lane $ADD_ROW_LANE was retired meanwhile is not known" + ar_subject="cancel add-row whose retirement could not be checked after rebase" + ar_back=1 + elif [ -n "$ar_rebased_hits" ]; then + ar_why="lane $ADD_ROW_LANE was retired by a peer before this add-row could push (archive: $(printf '%s' "$ar_rebased_hits" | tr '\n' ' '))" + ar_subject="cancel add-row rejected by peer retirement" + ar_back=2 + else + return 0 + fi + # Leaving the rejected add-row at HEAD would let the next unrelated registry + # write push it. Remove ONLY this invocation's exact appended line and commit + # that compensation locally; any swept pre-existing edit stays intact. + # + # AND ONLY A ROW THIS CHECKOUT STILL ADDS IS ITS OWN TO TAKE BACK (the delta + # review of #263, D1). A peer that published the byte-identical row first + # makes `pull --rebase` DROP this add-row's commit as already upstream, and + # the one copy left in the register is then the peer's: the exact-line grep + # found it and deleted it, and the next write published that deletion + # (measured: the peer's row gone from origin). So the copy taken back is the + # one this checkout's register adds over origin/$LANES_BRANCH's, read from + # their diff by content — which is what a surviving add-row commit is, under + # whatever sha the rebase gave it, and whatever local commits sit beside it. + # None added: nothing of this add-row's is left, and nothing is taken back. + # One: that line, wherever an identical peer copy sits. More than one, or a + # diff that cannot be read: not this act's to guess, and said so. + # "origin already has the row" would be wrong the other way: an add-row + # commit that SURVIVED beside a peer's identical row at another place would + # be kept, and published by the next write as a second copy. + # + # AND THE LINE IS COUNTED WHATEVER CONTEXT THE DIFF CARRIES (the delta review + # of #263, S3). `-U0` does not hold on its own: a `GIT_DIFF_OPTS=-u3` in the + # environment overrides it outright, and a user's `diff.interHunkContext` + # fuses two nearby changes into one hunk with the lines between them as + # context. The parse counted only `+` lines, so a hunk carrying context put + # the row at the wrong line, the line check refused, nothing was taken back, + # and the next ordinary write published the row add-row had refused (M1 + # again; measured with each of the two). So both: this one diff runs with + # `GIT_DIFF_OPTS` unset and `diff.interHunkContext=0` (a `-c` on the command + # line outranks every config file and `GIT_CONFIG_*` in the environment), and + # the parse advances its new-file line on every line of a hunk but a removed + # one (`-`) or git's "\ No newline" note, so whatever context still arrives + # is counted where it stands. The `unset` is inside the command + # substitution's own subshell, and so touches nothing after it. + # + # AND IT IS READ AS TEXT (delta review 4 of #263, S4). Where git classes the + # register as binary, the diff is one line, "Binary files … differ", with no + # hunk to read: a `binary` or `-diff` attribute, published or local, a diff + # driver with `binary=true`, `core.attributesFile`, `GIT_ATTR_SOURCE`, + # `attr.tree`, a NUL byte in its first 8000 bytes, or a `core.bigFileThreshold` + # below its size (the live register is over 2 MB). add-row then said this + # checkout added no copy of the row, kept its commit, and the next write + # published the row (measured with each). `--text` gives the hunks whatever + # classes the register. + ar_diff="$(unset GIT_DIFF_OPTS; git --no-replace-objects --no-pager -C "$LANES_REPO" -c "$CP_EXACT" -c diff.interHunkContext=0 diff --no-color --no-ext-diff --no-textconv --text -U0 "refs/remotes/origin/$LANES_BRANCH" -- "$LANES_PATH" 2>/dev/null)" || { + note "$ar_why; and this checkout's register could not be compared with origin/$LANES_BRANCH's, so whether a copy of the rejected row here is this add-row's or a peer's is not known. Nothing was taken back: read \`git -C $LANES_REPO log -p origin/$LANES_BRANCH..HEAD -- $LANES_PATH\` and remove this add-row's row before any later push" + return 1 + } + ar_lines="$(printf '%s\n' "$ar_diff" | AR_ROW="$ADD_ROW_TEXT" LC_ALL=C awk ' + /^@@ / { h = $0; sub(/^@@ -[0-9,]+ [+]/, "", h); sub(/[ ,].*$/, "", h); n = h + 0; inh = 1; next } + !inh { next } + { c = substr($0, 1, 1) } + c == "-" || c == "\\" { next } + c == "+" && substr($0, 2) == ENVIRON["AR_ROW"] { print n } + { n++ } + ')" || { + note "$ar_why; and the diff of this checkout's register against origin/$LANES_BRANCH's could not be read, so nothing was taken back: remove this add-row's row before any later push" + return 1 + } + case "$ar_lines" in + '') + if git --no-replace-objects --no-pager -C "$LANES_REPO" show "refs/remotes/origin/$LANES_BRANCH:$LANES_PATH" 2>/dev/null | command grep -qFx -- "$ADD_ROW_TEXT"; then + note "$ar_why. origin/$LANES_BRANCH already carries this exact row, published by a peer, and the rebase dropped this add-row's commit as already upstream: this checkout adds no copy of it, so there is nothing of this add-row's to take back and the peer's row is left as it is." + else + note "$ar_why. This checkout's register carries no copy of the row that origin/$LANES_BRANCH's does not, so there is nothing of this add-row's to take back." + fi + return "$ar_back" ;; + *$'\n'*) + note "$ar_why; and this checkout's register adds more than one exact copy of the rejected row over origin/$LANES_BRANCH's, so which is this add-row's is not known and none was taken back: the local add-row commit must be repaired before any later push" + return 1 ;; + esac + ar_line="$ar_lines" + [ "$(sed -n "${ar_line}p" "$LANES_FILE" 2>/dev/null)" = "$ADD_ROW_TEXT" ] || { + note "$ar_why; and line $ar_line of $LANES_FILE, where the diff puts the rejected row, does not hold it exactly, so nothing was taken back: the local add-row commit must be repaired before any later push" + return 1 + } + # A REFUSAL OF THE TAKE-BACK ITSELF SAYS ADD-ROW'S TRUTH (the delta review of + # #263, NIT): `delete_lines`' own sentences are archive-rows' — "the rows are + # in the archive", "the archive may have been appended" — and false here. + REG_COMMITTED_HERE="this act HAS committed its row for lane $ADD_ROW_LANE, locally and unpushed" + DL_SAYS_UNCHANGED="no row was removed, so that row is still in it and in that commit. Remove it from $LANES_PATH and commit that before any other write in $LANES_REPO, because the next one would publish it" + DL_SAYS_AFTER_WRITE="Its row for lane $ADD_ROW_LANE was not taken back, and this act HAS committed it, locally and unpushed: with the register whole, remove that row from $LANES_PATH and commit that before any other write in $LANES_REPO, because the next one would publish it." + delete_lines "$ar_line" + REG_COMMITTED_HERE=""; DL_SAYS_UNCHANGED=""; DL_SAYS_AFTER_WRITE="" + # A REMOVAL THAT CANNOT BE COMMITTED SAYS SO (delta review 4 of #263, N3). + # These returned in silence: the removal was left written or staged under + # add-row's commit, and the next write's own commit carried it, under its + # own caption, with no one told. + ar_msg="LANES($ADD_ROW_LANE@$WS): $ar_subject" + ar_fix="add-row's commit still holds the row. Commit the removal before any other write in $LANES_REPO, so that write does not carry it under its own caption: \`git -C $LANES_REPO commit -m '$ar_msg' -- $LANES_PATH\`" + git -C "$LANES_REPO" -c "$CP_EXACT" add -- "$LANES_PATH" || { + note "$ar_why; the rejected row was removed from $LANES_FILE, but staging that removal failed, so it is only in the working tree, and $ar_fix" + return 1 + } + git -C "$LANES_REPO" -c "$CP_EXACT" commit -q -m "$ar_msg" -- "$LANES_PATH" || { + note "$ar_why; the rejected row was removed from $LANES_FILE and that removal is staged, but its compensating commit failed, so $ar_fix" + return 1 + } + note "$ar_why; the rejected row was removed in a compensating LOCAL commit, so no later write publishes it. Neither commit was pushed." + return "$ar_back" +} + +# Each lane's LAST line on , as +# utc lane verb uuid ws object ref payload text file line +# +# R14 — "LAST" IS THE LAST LINE IN THE FILE, and never the largest UTC. One +# lane's log is append-only and single-writer, so its line order IS that lane's +# write order; a clock is not. It was a max-UTC read here that made a LANDED +# invisible behind the LANDING it closed, on the day this workstation's clock +# was jumping ±25s. `pos()` is the line's address — its file and its line +# number, zero-padded so that one string comparison orders both. +# AMENDMENT 15 — KEYED ON THE LANE LOWER-CASED. The key decides how many rows +# come out of here, and the ROW is the whole line, so the spelling a reader sees +# is still the one the winning line carried. Keyed on the raw `$2`, a lane whose +# log spells it two ways emitted TWO rows for ONE lane — and `claim`-s rival +# test, which excludes its OWN row from this set, then met its own earlier +# CLAIMED as a stranger and refused the lane its own object (Copilot round 1 on +# openRepoTools#41). +PER_LANE_AWK=' +function pos(pf, pn) { return pf "\034" sprintf("%09d", pn) } +BEGIN { FS = sep } +$6 == o { k = tolower($2); p = pos($10, $11); if (!(k in u) || p >= u[k]) { u[k] = p; L[k] = $0 } } +END { for (l in u) print L[l] }' + +# Ordered by LANE NAME, deliberately. These rows are one line per lane, so +# nothing about their order is a fact about the object: which lane got there +# first is LANDING ORDER ON `main` (F13), which `first_landed_of` reads out of +# git history. This sort used to be on the UTC field, and sorting a set of +# lanes by their clocks is exactly the comparison R14 removes. +lane_states_on() { # [events-producer-output on stdin] + awk -v sep="$US" -v o="$1" "$PER_LANE_AWK" | LC_ALL=C sort -t"$US" -k2,2 +} + +# The lanes that HOLD — those whose own last line on it is open. +# Prints lane verb utc file line: the last two are the ADDRESS of that +# lane's own last line, which is what a staleness test needs in order to ask +# "has this lane written anything BELOW it in its own log" without a clock. +holders_of() { + hf_obj="$1" + while IFS="$US" read -r h_utc h_lane h_verb h_uuid h_ws h_o h_ref h_pay h_txt h_file h_line; do + [ -n "${h_verb:-}" ] || continue + is_open_verb "$h_verb" || continue + # A CLAIMED that another lane has since taken over is not a hold. + [ -z "$(superseded_by "$hf_obj" "$h_lane" "$h_verb")" ] || continue + printf '%s%s%s%s%s%s%s%s%s\n' "$h_lane" "$US" "$h_verb" "$US" "$h_utc" "$US" "$h_file" "$US" "$h_line" + done +} + +# A LANE NAME IS NOT A REGULAR EXPRESSION (Copilot round 4 on openRepoTools#41). +# Every filter of these US-delimited holder rows was `grep "^$lane$US"`, which +# hands a name straight to a matcher: `check_lane_name` admits `.`, so excluding +# `repo.a-1` also excludes the REAL rival `repoXa-1`, and `first_landed_of`'s +# `grep -q` could match a lane that is not in the set at all. A claim decided by +# that filter is a claim whose winner is whichever name happened to be a pattern +# — in a race whose whole point is that the arbiter is exact. +# +# So the comparison is `awk` on FIELD ONE, `tolower` on both sides, with no +# pattern anywhere: literal, case-insensitive (Amendment 15) and blind to `.`, +# `*`, `[` and `^`. `-v` carries one line, which a lane name is. +rows_not_named() { # — every row whose first field is NOT it + awk -v sep="$US" -v want="$1" 'BEGIN { FS = sep; w = tolower(want) } tolower($1) != w' +} +rows_named() { # — every row whose first field IS it + awk -v sep="$US" -v want="$1" 'BEGIN { FS = sep; w = tolower(want) } tolower($1) == w' +} + +# Every object this lane's OWN log mentions, with the lane's last verb on it. +# `lane-end`'s refusal and `who --lane` both read exactly this. +# Every object this lane's OWN log mentions, with the lane's last verb on it, +# plus — read from EVERY lane's log — whether another lane has since taken the +# object over. A lane closes only its own hold, so after someone else's +# TAKEOVER this lane's last line is still its CLAIMED; without the fifth field +# `lane-end` would refuse for ever and never say why. +# utc verb object ref+payload superseded-by(lane@utc, or empty) +lane_objects() { + # 8, not 1: "no log file" is an ANSWER. TWO LOGS IS NOT THAT ANSWER, and 2 is + # carried through rather than flattened into it (Copilot round 4): `who --lane` + # and `lane-end`'s refusal would otherwise report a lane whose history is split + # across two files as a pre-cutover lane with no log at all. + lo_ex=0 + lane_log_exists "$1" || lo_ex=$? + case "$lo_ex" in + 0) : ;; + 2) return 2 ;; + *) return 8 ;; + esac + # AMENDMENT 15 — THE LANE FIELD OF A LOG LINE IS MATCHED CASE-INSENSITIVELY, + # and the caller has already resolved `$1` to the row's spelling. The line's + # own spelling is whatever was TYPED on the day it was appended, and an + # append-only log is never rewritten: `lanes/log/openxfactory-2.md` carries + # `lane openXfactory-2` lines from 2026-09-02 and `lane openxfactory-2` lines + # from the 23:51:56Z incident, in one file, about one lane. Read byte for + # byte, half of that lane's claims are invisible to `who --lane` and to + # `lane-end`'s refusal — which is the amendment's own sentence, that a lane + # name is compared case-insensitively wherever a name is looked up, and the + # OBJECT LOG is one of the places it lists. + # + # `mel` IS COMPUTED ONCE IN `BEGIN`, not per line: this stream is every line + # of every lane's log on the estate. + state_events | awk -v sep="$US" -v me="$1" ' + function pos(pf, pn) { return pf "\034" sprintf("%09d", pn) } + BEGIN { FS = sep; mel = tolower(me) } + $6 ~ /^lane:/ { next } + tolower($2) == mel { + if (!($6 in ord)) { ord[$6] = ++n; byn[n] = $6 } + p = pos($10, $11) + if (!($6 in mp) || p >= mp[$6]) { mp[$6] = p; utc[$6] = $1; verb[$6] = $3; ref[$6] = $7; pay[$6] = $8 } + } + # EVERY OTHER LANE, ITS OWN LAST LINE on each object, by the same file-order + # rule this lane is read by (R14). The verb is kept, not only the TAKEOVERs, + # because what decides supersession is whether a TAKEOVER is still the last + # word of the lane that wrote it — see the END block. + # KEYED ON THE OTHER LANE LOWER-CASED TOO, and its SPELLING carried beside + # the key (Amendment 15): two spellings of one taker would otherwise be two + # takers, and the one whose last line is a stale CLAIMED could hide the + # other-s TAKEOVER. `on[]` keeps the spelling of the line that won the + # position test, so what is PRINTED is still a name somebody wrote. + # `ot[]` is the lane a TAKEOVER names as `← lane:`, lower-cased, and + # empty for any other line: the link a chain is followed by (#74, below). + tolower($2) != mel { + q = pos($10, $11); okey = $6 SUBSEP tolower($2) + if (!(okey in op) || q >= op[okey]) { op[okey] = q; ov[okey] = $3; ou[okey] = $1; on[okey] = $2 + ot[okey] = ($3 == "TAKEOVER" && $7 == "←" && substr($8, 1, 5) == "lane:") ? tolower(substr($8, 6)) : "" } + } + # SUPERSEDED, WITHOUT ORDERING TWO FILES AGAINST EACH OTHER (R14), AND ONLY + # WHILE THE TAKEOVER STILL STANDS (R18): another lane has a TAKEOVER on the + # object AS ITS OWN LAST LINE, and this lane has written nothing on it since + # — the last line here is still the open verb that TAKEOVER took. A + # TAKEOVER is never removed from an append-only log, so testing for one + # ANYWHERE in the file of the taker kept superseding these claims for ever: + # after that lane released the object and this one legitimately re-claimed + # it, `who` called the object FREE and a third lane was not refused. + # STALE UNTIL PR #61 (Copilot round 11): this paragraph itself said "a + # TAKEOVER displaces a CLAIMED and nothing else", singular, after the + # dead-lane exception of issue #30 had already widened what the awk + # fragment above tests. A TAKEOVER displaces CLAIMED (the ordinary + # stale-claim shape of decision 8(e)) or, per that dead-lane exception, a + # TAKEOVER, OPENED, LANDING or WITHDRAWN left by another lane (`claim + # --force` refuses every other verb) — that full set is the whole of the + # test; any later line of this lane is it speaking after the fact and is + # reported as it stands. The two lines sit in two different lanes, whose + # files share no clock, and this asks for none. + # A CHAIN IS FOLLOWED TO ITS LAST LINK (opensoft/openRepoTools#74), by the + # rule `superseded_by` below argues: when this lane-s own last line is a + # TAKEOVER, only another lane-s standing TAKEOVER that NAMES this lane + # (`← lane:`) displaces it, and not one this lane-s own + # TAKEOVER names back; any other open verb is displaced by any standing + # TAKEOVER, and the taker NAMED is one no other standing TAKEOVER names + # wherever there is one. Without it the true holder at the end of a chain + # was told here that it had been "taken over" by the lane it took the + # object from, and `lane-end` handed it the release that frees the object. + END { for (kk in ov) if (ov[kk] == "TAKEOVER" && ot[kk] != "") { + split(kk, aa, SUBSEP); if (ot[kk] != aa[2]) nmd[aa[1], ot[kk]] = 1 } + for (kk in ov) if (ov[kk] == "TAKEOVER") { + split(kk, aa, SUBSEP); oo = aa[1]; ll = aa[2] + if (!(oo in verb)) continue + if (verb[oo] == "TAKEOVER") { + mt = (ref[oo] == "←" && substr(pay[oo], 1, 5) == "lane:") ? tolower(substr(pay[oo], 6)) : "" + if (ot[kk] != mel || mt == ll) continue + r = 1 + } else r = (((oo, ll) in nmd) ? 0 : 1) + if (!(oo in tp) || r > tr[oo] || (r == tr[oo] && op[kk] >= tp[oo])) { tp[oo] = op[kk]; tr[oo] = r; tlane[oo] = on[kk]; tutc[oo] = ou[kk] } } + for (i = 1; i <= n; i++) { o = byn[i] + supv = ((o in tlane) && (verb[o] == "CLAIMED" || verb[o] == "TAKEOVER" || verb[o] == "OPENED" || verb[o] == "LANDING" || verb[o] == "WITHDRAWN")) + sup = supv ? tlane[o] "@" tutc[o] : "" + printf "%s%c%s%c%s%c%s%c%s\n", utc[o], 31, verb[o], 31, o, 31, (ref[o] ? ref[o] " " pay[o] : ""), 31, sup } }' +} + +# The lane and UTC of a TAKEOVER on that is STILL THAT LANE'S OWN LAST +# LINE on it — printed only when $3, our own last verb on the object, is one of +# the OPEN VERBS a takeover can displace: CLAIMED (decision 8(e)'s ordinary +# stale-claim shape), or TAKEOVER, OPENED, LANDING or WITHDRAWN (issue #30's +# dead-lane exception, `superseded_by`'s own case below). Empty when there is +# none. STALE UNTIL PR #61 (Copilot round 8): this line said "the CLAIMED a +# takeover displaces", singular, after the awk fragment just above it had +# already grown the full set — the code was never wrong, only this prose. +# +# R18 — "ITS OWN LAST LINE" IS THE WHOLE OF THE BOUND. Per-lane last-line +# semantics apply to the taker too: once the taker writes RELEASED, CLOSED or +# LANDED on the object, its TAKEOVER supersedes nothing and a later CLAIMED by +# the dispossessed lane holds. Matching any TAKEOVER anywhere in the taker's +# append-only file made a legitimate re-claim invisible for ever: `who` called +# a held object FREE, `claim` did not refuse the next lane — the single outcome +# Rule 1 exists to prevent — and `who --lane` and `lane-end` disagreed about the +# same object. +# +# NO TIMESTAMP IS COMPARED (R14): the two lines are in two lanes' files and +# there is no shared clock to order them by, so the question asked is the one +# file order can answer — is our own last line still the claim, and is a +# TAKEOVER still theirs. The UTC printed beside the lane is information for the +# reader, never a key. +# +# A CHAIN OF TAKEOVERS RESOLVES TO ITS LAST LINK (opensoft/openRepoTools#74). +# Issue #30's dead-lane exception lets a TAKEOVER displace an earlier TAKEOVER +# — A claims, B takes over from A, C takes over from B once B is dead — and +# every link that displaces a TAKEOVER names the lane it displaced as +# `← lane:`: `claim --force` writes that payload for every hold that is not +# a CLAIMED, and only a CLAIMED is ever taken with a comment URL instead. The +# test used to be "does SOME other lane's last line here read TAKEOVER", and it +# read B's TAKEOVER — itself displaced by C — as proof that C was displaced +# too: `who` reported ZERO holders of an object C held. So the question is now +# asked by what our own last line is: +# * a TAKEOVER is displaced ONLY by another lane's standing TAKEOVER that +# NAMES our lane. B is displaced by C, which names it; C by nothing, since +# no standing TAKEOVER names C. One lane holds the object: the last link. +# * any other open verb is displaced by any standing TAKEOVER, as it always +# was, and the taker NAMED is one that no other standing TAKEOVER names — +# the lane that holds the object now — wherever there is one. A's line +# says C, not B. Where every taker is named, the file-ordered position +# picks which one is named; A is displaced either way. +# Two lanes that each end on a TAKEOVER and do not name each other — two takers +# of one stale claim — are therefore BOTH holders, the visible conflict the +# README's "Known, deliberate" paragraph has always described; since PR #61 +# (issue #30) widened the gate, the old test had them displace each other and +# `who` called the object FREE. Two TAKEOVERs that name EACH OTHER (a lane revived and took back +# what had been taken from it) are both holders too: no file order says which +# was written last, and a conflict `who` shows is one a person can resolve. +superseded_by() { # + # ANY OPEN VERB, NOT ONLY CLAIMED (Copilot round 7, PR #61, issue #30): a + # dead lane's TAKEOVER — decision 8(e)'s stale-CLAIMED case is still the + # common one, but opensoft/openRepoTools#30 added a dead-lane TAKEOVER that + # displaces an OPENED, LANDING, WITHDRAWN or an earlier TAKEOVER too, exactly + # the verbs `is_open_verb` already lists. Gating this early return on + # `= CLAIMED` alone left every one of those un-superseded: `holders_of` + # counted the dead lane's own OPENED as a live hold beside the taker's + # TAKEOVER, and `who` reported two holders of one object — the very + # collision #30 exists to end. + case "${3-}" in + CLAIMED|TAKEOVER|OPENED|LANDING|WITHDRAWN) : ;; + *) return 0 ;; + esac + # AMENDMENT 15 — `tolower` ON BOTH SIDES, exactly as `lane_objects` above + # reads the same stream: the lane field of a log line carries the spelling + # that was typed on the day, and one lane's two spellings are one lane. The + # NAME is still the one the winning line carried, because this is printed. + # OUR OWN LAST LINE IS READ HERE TOO, not only the other lanes': the TAKEOVER + # it may be is what names the lane a chain was taken from (#74, above). `t[]` + # is the lane each last line names as `← lane:`, lower-cased, or empty; + # a TAKEOVER naming its own lane names nobody. + state_events | awk -v sep="$US" -v o="$1" -v me="$2" -v mv="$3" ' + function pos(pf, pn) { return pf "\034" sprintf("%09d", pn) } + BEGIN { FS = sep; mel = tolower(me) } + $6 == o { p = pos($10, $11); ll = tolower($2) + if (!(ll in q) || p >= q[ll]) { q[ll] = p; v[ll] = $3; u[ll] = $1; nm[ll] = $2 + t[ll] = ($3 == "TAKEOVER" && $7 == "←" && substr($8, 1, 5) == "lane:") ? tolower(substr($8, 6)) : "" } } + END { for (l in q) if (v[l] == "TAKEOVER" && t[l] != "" && t[l] != l) named[t[l]] = 1 + for (l in q) { + if (l == mel || v[l] != "TAKEOVER") continue + if (mv == "TAKEOVER") { + if (t[l] != mel || t[mel] == l) continue + r = 1 + } else r = ((l in named) ? 0 : 1) + if (!seen || r > br || (r == br && q[l] >= b)) { seen = 1; br = r; b = q[l]; bl = nm[l]; bu = u[l] } } + if (seen) print bl "@" bu }' +} + +# A lane's HOME repo, from the payload of its own STARTED (or RESUMED) line. +# `-` is a label, not a scope: this is the only thing that says where +# a lane actually lives. +# R20 — and the answer is CANONICAL. A STARTED line records whatever spelling +# that checkout's `origin` had on the day, and the register's own history proves +# those drift (`opensoft/codexFactory` is today `codeXfactory/codexFactory`). +# Every comparison of an object's repository against a home — canon_object's +# `#n`, cross_repo_warn, same_project, who's CROSS-REPO note — resolves BOTH +# sides, and resolving here is what makes that true of all of them at once. +home_of_lane() { + lane_log_exists "$1" || return 1 + hol_h="$(lane_log_events "$1" | awk -v sep="$US" ' + BEGIN { FS = sep } + $3 == "STARTED" || $3 == "RESUMED" { + if (match($8, /home [^ ;]+/)) h = substr($8, RSTART + 5, RLENGTH - 5) + } + END { if (h != "" && h != "unknown") print h; else exit 1 }')" || return 1 + [ -n "$hol_h" ] || return 1 + hol_c="$(alias_lookup "$hol_h" 2>/dev/null || :)" + printf '%s\n' "${hol_c:-$hol_h}" +} + +# `PIN_LOGS` IS THE ONE LISTING'S OWN LIST OF THE PUBLISHED LOGS, exactly as +# `PIN_ARCHIVE` is its archive: `worktree_rows` lists them once, and where that +# succeeded the listing names its lanes from that list and not from a second +# `ls-tree` that could fail after it (the review of #289, SHOULD-1(b)). +PIN_LOGS=0 +PIN_LOGS_TEXT="" +known_lanes() { + if [ -n "$LANES_IDX_DIR" ]; then + while IFS= read -r kl_f; do + [ -n "$kl_f" ] || continue + kl_n="${kl_f##*/}" + case "$kl_n" in README.md) continue ;; esac + printf '%s\n' "${kl_n%.md}" + done < "$LANES_IDX_DIR/logs" + return 0 + fi + if [ "$PIN_LOGS" = 1 ] || have_remote_ref; then + { if [ "$PIN_LOGS" = 1 ]; then printf '%s' "$PIN_LOGS_TEXT" + else git -C "$LANES_REPO" ls-tree --name-only "origin/$LANES_BRANCH" -- "$LANES_LOG_PREFIX" 2>/dev/null + fi; } \ + | while IFS= read -r kl_f; do + [ -n "$kl_f" ] || continue + kl_n="${kl_f##*/}" + case "$kl_n" in README.md) continue ;; esac + printf '%s\n' "${kl_n%.md}" + done + return 0 + fi + while IFS= read -r kl_f; do + [ -n "$kl_f" ] || continue + kl_n="${kl_f##*/}"; printf '%s\n' "${kl_n%.md}" + done <` IS GNU-ONLY, AND THIS FUNCTION IS WHAT STALENESS IS MADE +# OF (A9 Addendum 4, R-A9-11). BSD `date` — macOS's — answers `illegal option +# -- d`, and `2>/dev/null || printf ''` turned that refusal into an EMPTY +# ANSWER rather than an error: `age_of` printed `age unknown` beside every row, +# `older_than_minutes` and `older_than_threshold` returned false for every +# stamp, and the whole of `who`'s idle and stale reporting was silently off on +# a platform this repository's own CI runs. BSD spells the same question +# `-j -f `, so both are asked, GNU first because it is what +# every lane workstation runs. TWO FORMATS, because this estate writes two: +# `utc_now`, `lane-end`'s RELEASED and every log line carry SECONDS, and a +# row's `Started` cell carries MINUTES. GNU reads either from one call; BSD +# must be told which, so it is asked twice. A stamp none of the three can read +# is still the empty string every caller here already tests for. +epoch_of() { + date -u -d "$1" +%s 2>/dev/null || + date -u -j -f '%Y-%m-%dT%H:%M:%SZ' "$1" +%s 2>/dev/null || + date -u -j -f '%Y-%m-%dT%H:%MZ' "$1" +%s 2>/dev/null || + printf '' +} + +# `age_of []`. A CALLER WITH MANY STAMPS PASSES `now` +# ONCE (A11 Addendum 4 ruling 12): `date -u +%s` is a process, and asking the +# clock again for every row of a listing both costs one and lets the rows +# disagree about when "now" was. +age_of() { + ao_t="$(epoch_of "$1")" + if [ -z "$ao_t" ]; then printf 'age unknown'; return 0; fi + ao_now="${2-}"; [ -n "$ao_now" ] || ao_now="$(date -u +%s)" + ao_d=$(( ao_now - ao_t )); [ "$ao_d" -lt 0 ] && ao_d=0 + printf '%dh %02dm' "$((ao_d / 3600))" "$(((ao_d % 3600) / 60))" +} + +lc() { printf '%s' "${1-}" | tr 'A-Z' 'a-z'; } + +# `lc`'s ANSWER WITHOUT A PROCESS, for a loop that asks it of EVERY lane in the +# estate (opensoft/openRepoTools#107). `$(lc …)` is a subshell and a `tr`, and +# the listing's `--prefix` and `--repo` filters made two of them per lane per +# filter: measured on the suite's fixture register (194 rows, 162 logs), 3.2 s +# of one `lanes --prefix` read, for lanes it then filtered out. The mapping is +# `tr 'A-Z' 'a-z'`'s — the twenty-six ASCII capitals and nothing else — spelled +# as twenty-six literal substitutions, so no locale's idea of a range or of a +# case can widen it. It ASSIGNS `LOWER_OUT` and returns, for `table_lookup`'s +# reason: a function read through `$( … )` is the fork this exists to remove. +LOWER_OUT="" +lower_into() { # + LOWER_OUT="${1-}" + case "$LOWER_OUT" in *[ABCDEFGHIJKLMNOPQRSTUVWXYZ]*) : ;; *) return 0 ;; esac + LOWER_OUT="${LOWER_OUT//A/a}"; LOWER_OUT="${LOWER_OUT//B/b}"; LOWER_OUT="${LOWER_OUT//C/c}" + LOWER_OUT="${LOWER_OUT//D/d}"; LOWER_OUT="${LOWER_OUT//E/e}"; LOWER_OUT="${LOWER_OUT//F/f}" + LOWER_OUT="${LOWER_OUT//G/g}"; LOWER_OUT="${LOWER_OUT//H/h}"; LOWER_OUT="${LOWER_OUT//I/i}" + LOWER_OUT="${LOWER_OUT//J/j}"; LOWER_OUT="${LOWER_OUT//K/k}"; LOWER_OUT="${LOWER_OUT//L/l}" + LOWER_OUT="${LOWER_OUT//M/m}"; LOWER_OUT="${LOWER_OUT//N/n}"; LOWER_OUT="${LOWER_OUT//O/o}" + LOWER_OUT="${LOWER_OUT//P/p}"; LOWER_OUT="${LOWER_OUT//Q/q}"; LOWER_OUT="${LOWER_OUT//R/r}" + LOWER_OUT="${LOWER_OUT//S/s}"; LOWER_OUT="${LOWER_OUT//T/t}"; LOWER_OUT="${LOWER_OUT//U/u}" + LOWER_OUT="${LOWER_OUT//V/v}"; LOWER_OUT="${LOWER_OUT//W/w}"; LOWER_OUT="${LOWER_OUT//X/x}" + LOWER_OUT="${LOWER_OUT//Y/y}"; LOWER_OUT="${LOWER_OUT//Z/z}" + return 0 +} + +older_than_minutes() { # + om_t="$(epoch_of "$1")"; [ -n "$om_t" ] || return 1 + [ "$(( $(date -u +%s) - om_t ))" -gt "$(( $2 * 60 ))" ] +} + +older_than_threshold() { + st_t="$(epoch_of "$1")"; [ -n "$st_t" ] || return 1 + [ "$(( $(date -u +%s) - st_t ))" -gt "$((STALE_HOURS * 3600))" ] +} + +# An object is treated as a PR once some lane has written OPENED on it. That +# is the only offline evidence there is, and it is exactly the evidence Rule 1 +# cares about: a claim followed by a PR is not abandoned. +object_is_pr() { + op_o="$1" + state_events | awk -v sep="$US" -v o="$op_o" 'BEGIN{FS=sep} $6 == o && $3 == "OPENED" { f = 1 } END { exit(f ? 0 : 1) }' +} + +# Rule 1's staleness, made checkable. A lane's CLAIMED on an ISSUE is stale +# when it is older than four hours AND that lane has written no later OPENED +# whose `←` payload names the issue. A PR is never stale by this rule — Rule 6 +# governs PRs, with its own thirty minutes. +# "LATER" IS FURTHER DOWN THE SAME FILE (R14). The four hours above is a +# DURATION and stays on the clock, where ±25s is immaterial; this is an ORDER +# between two lines of one append-only log, and it is read off the log. +claim_is_stale() { # + cs_lane="$1"; cs_obj="$2"; cs_utc="$3"; cs_file="${4-}"; cs_line="${5-0}" + older_than_threshold "$cs_utc" || return 1 + object_is_pr "$cs_obj" && return 1 + state_events | awk -v sep="$US" -v l="$cs_lane" -v o="$cs_obj" -v f="$cs_file" -v ln="$cs_line" ' + BEGIN { FS = sep } + tolower($2) == tolower(l) && $3 == "OPENED" && $10 == f && ($11 + 0) > (ln + 0) { + # the `←` payload is space-separated issue keys + n = split($8, a, " ") + for (i = 1; i <= n; i++) if (a[i] == o) { found = 1 } + } + END { exit(found ? 1 : 0) }' +} + +# ------------------------------------------- issue #30: A DEAD LANE'S HOLD +# +# `claim_is_stale` answers Rule 1's own question — is THIS CLAIM old — and on +# purpose it refuses for anything that is not a CLAIMED issue: Rule 6 governs a +# PR's own thirty minutes, and an OPENED, LANDING or WITHDRAWN was never a +# claim to begin with. Neither test answers a DIFFERENT question Rule 1 never +# had a word for: the LANE holding the object is not coming back at all, +# whatever verb its last line on the object used. Measured 2026-09-13 +# (opensoft/openRepoTools#30): lane openRepoProject-1 went silent and was +# retired (`lane-end --retire`, Amendment 6(d)), leaving an OPENED PR and two +# CLAIMED issues behind — `claim --force` refused all three, the verb-check +# refusing the PR and the four-hour clock refusing the issues (a CLAIMED lane +# that later OPENED a PR naming it is deliberately never stale by Rule 1's own +# test, which is exactly backwards for a lane that is dead). The workaround +# was a `release` on the dead lane's behalf, by hand, object by object. +# +# DEAD, HERE, MEANS THE REGISTER SAYS SO, FIRST: the holder's own object log's +# last LANE-KIND line (Amendment 7(b)'s STARTED/PAUSED/RESUMED/ENDED/RETIRED — +# `lane_row_facts`' own "last lane-kind line wins in file order" rule, R14, +# read for one lane rather than for a whole listing) is ENDED or RETIRED. +# PAUSED IS DELIBERATELY NOT DEAD — a swap is a planned, expected stop +# (Amendment 8) and stealing a swapped lane's claims would be exactly the +# collision this protocol exists to prevent — and neither is a log with no +# lane-kind line yet, which cannot hold an object through this path at all +# (`state_events` reads nothing for it either). +# +# AND CONFIRMED, NEVER ASSUMED, SECOND: a register that says RETIRED is not +# proof by itself that nothing is still running under that name — Amendment +# 6(d)'s retire act writes no signal and kills no process, and +# opensoft/openRepoTools#39 is exactly a register saying one thing while a +# duplicate process says another. So the verdict is checked against +# `live_holder` — the ONE liveness implementation this file has, over the same +# published-union-local id set `lanes-edit.sh live-holder` already builds, and +# never a new one — and a lane a live record on THIS workstation still holds is +# refused exactly as an untaken CLAIMED is: "refuse where the holder is live" +# is not a special case here, it is this same rule. A `live_holder` read that +# FAILS is not "confirmed live" (fail closed for the log half, as every other +# reader of this stream does) — but nor is it "confirmed dead": a RETIRED +# verdict this workstation simply cannot check against any records at all is +# HELD BACK exactly as a live one is, because issue #30's fix must never be +# LESS safe than the check it sits beside. STALE UNTIL PR #61 (Copilot round +# 11): this paragraph used to say such a read "is not held back either", +# which described the opposite of the fail-closed rule the code below it +# already enforced — only an ACTUAL, CONFIRMED-EMPTY read (`live_holder` exit +# 8, never a bare rc 0 check) allows the takeover that every other outcome, +# read failures included, withholds. +# +# 0 dead-and-confirmed (`HOLDER_DEAD_VERB` names the verdict), 1 not — refuse +# as before. (This is `holder_is_dead`'s OWN return code, a different space +# from the three `live_holder` answers just above it.) +# +# A LINE WHOSE PAYLOAD OPENS `fork ` IS NEVER THE LANE'S OWN VERB (Copilot +# round 8, PR #61) — the same exclusion `lane_row_facts` already makes (above, +# "A FORK-S RETIRED IS NOT THE LANE-S OWN LAST VERB") and for the identical +# reason: the first build of ruling 8's retire act appended `RETIRED … lane: +# -> fork ; pid ; kind ` to the LANE's own log for a FORK it +# retired, and nothing writes one any more but these logs are append-only, so +# one written under that build is still there. Read as this lane's own last +# line, it says the LANE was retired — backwards for a lane that may be alive +# beside the fork it disowned, and exactly the state a PAUSED (swapped) lane +# would be in if a stray line like this landed after its own last STARTED or +# RESUMED: `claim --force` would read it as ENDED and take over holds a +# planned, expected stop was never meant to surrender — the very collision +# Amendment 8 exists to prevent. +# +# A LOG THAT YIELDED NO LANE-KIND VERDICT AT ALL IS ITS OWN ANSWER TOO +# (Copilot on 05d7889, PR #61). The read used to be one pipeline whose status +# was `awk`'s, so a log `lane_log_events` could not read — two files differing +# only by case on origin, a `git show` that failed, a log no longer there — +# came back as an EMPTY verdict with status 0 and set neither marker below: +# `claim_rescan_hook` then told the operator the log had "moved past the +# terminal line", which nobody had read. `HOLDER_NO_VERDICT` is that case, +# named: the read failed, or it produced no STARTED/PAUSED/RESUMED/ENDED/ +# RETIRED line to judge. It is still `return 1` — fail closed — and only the +# words a caller prints change. +# +# AND THE CONFIRMATION IS PRONOUNCED ONLY FROM INSIDE THE LANE'S LAST BINDING +# (Copilot on 8ce6c9d, PR #61, against Amendment 18(b) as #83 landed it): +# *"Liveness is pronounced only from INSIDE the binding's own `host` and +# `container`, where the pid namespace is the record's: from anywhere else a +# binding is UNKNOWN, never dead."* `live_holder` answering 8 says no session +# record on THIS workstation holds the lane — which proves nothing about a lane +# whose last `STARTED`/`RESUMED` was written on another host or in another +# container, so a terminal log there plus an empty read here would have handed +# its open holds to `--force` on a fact nobody could establish. The binding is +# read off the last such line before the terminal one, with clause (a)'s +# cutover rule (no `host`/`container`/`os` at all is a line from before it, +# matched on the line's own workstation), and judged by `binding_is_here` — +# the one locality rule this file has. Not here, the one exception clause (b) +# carves out still applies: a shared tmux server on which the binding's window +# is GONE is a dead binding (`binding_window_state`) — and then the local +# `live_holder` read below still has to come back empty, because a dead pane +# is not proof that nothing on this workstation still carries the lane +# (Copilot on a52abc6). Anything else is +# `HOLDER_BOUND_ELSEWHERE` (the binding's `host/container`), and refused like +# every other verdict this workstation could not establish. A log with no +# binding line at all keeps the local read, which is all there is to ask. +# +# AND THE IDS THE LOCAL READ IS ASKED ABOUT MUST HAVE BEEN READ +# (opensoft/openRepoTools#67). They are the row's, published-union-local, and +# an unreadable register used to yield the same EMPTY set as a lane with no +# row — which `live_holder` answers 8, so a terminal log on a register nobody +# could read was "confirmed dead" and its holds went to `--force`, even with a +# live session on this workstation still carrying the lane's id. That is +# `HOLDER_REGISTER_UNREADABLE` now, with `HOLDER_TERMINAL_UNKNOWN` beside it so +# every reader that already refuses a liveness read that failed refuses this one +# too; `claim` names it in its own words. +HOLDER_DEAD_VERB="" +HOLDER_LIVE_TERMINAL="" +HOLDER_TERMINAL_UNKNOWN="" +HOLDER_NO_VERDICT="" +HOLDER_BOUND_ELSEWHERE="" +HOLDER_REGISTER_UNREADABLE="" +HOLDER_DEAD_WHY="" +HOLDER_TERMINAL_SEEN="" +holder_is_dead() { # + hid_l="${1-}"; [ -n "$hid_l" ] || return 1 + HOLDER_DEAD_VERB="" + HOLDER_LIVE_TERMINAL="" + HOLDER_TERMINAL_UNKNOWN="" + HOLDER_NO_VERDICT="" + HOLDER_BOUND_ELSEWHERE="" + HOLDER_REGISTER_UNREADABLE="" + HOLDER_DEAD_WHY="no live session on this workstation" + HOLDER_TERMINAL_SEEN="" + hid_rc=0 + hid_ev="$(lane_log_events "$hid_l" 2>/dev/null)" || hid_rc=$? + if [ "$hid_rc" != 0 ]; then + HOLDER_NO_VERDICT=1 + return 1 + fi + hid_verb="$(printf '%s\n' "$hid_ev" | awk -F"$US" ' + ($3=="STARTED"||$3=="PAUSED"||$3=="RESUMED"||$3=="ENDED"||$3=="RETIRED") && substr($8,1,5)!="fork " { v=$3 } + END { print v }')" + case "$hid_verb" in + ENDED|RETIRED) : ;; + "") HOLDER_NO_VERDICT=1; return 1 ;; + *) return 1 ;; + esac + HOLDER_TERMINAL_SEEN="$hid_verb" + # AMENDMENT 18(b) — the last binding, and whether this place may pronounce + # on it (the paragraph above `HOLDER_DEAD_VERB`). + hid_bind="$(printf '%s\n' "$hid_ev" | awk -F"$US" ' + ($3=="STARTED"||$3=="RESUMED") && substr($8,1,5)!="fork " { ws=$5; pay=$8; seen=1 } + END { if (seen) printf "%s%c%s\n", ws, 31, pay }')" + if [ -n "$hid_bind" ]; then + hid_bws="${hid_bind%%"$US"*}"; hid_bpay="${hid_bind#*"$US"}" + hid_bhost="$(payload_subfield "$hid_bpay" host)" + hid_bcont="$(payload_subfield "$hid_bpay" container)" + hid_bos="$(payload_subfield "$hid_bpay" os)" + hid_bwin="$(payload_subfield "$hid_bpay" window all)" + hid_blegacy="" + [ -n "$hid_bhost$hid_bcont$hid_bos" ] || hid_blegacy=legacy + [ -n "$hid_bhost" ] || hid_bhost="$hid_bws" + [ -n "$hid_bcont" ] || hid_bcont=none + if ! binding_is_here "$hid_bhost" "$hid_bcont" "$hid_blegacy"; then + # THE WINDOW-GONE EXCEPTION ADMITS THE BINDING TO THE LOCAL READ BELOW, + # IT DOES NOT REPLACE IT (Copilot on a52abc6, PR #61): a pane gone from + # the shared tmux server says the BINDING is dead, not that nothing on + # this workstation still carries the lane — an orphaned background + # duplicate outlives its pane. So `live_holder` is still asked, and only + # its confirmed-empty 8 lets this answer dead; live or unreadable stays + # a refusal exactly as it is for a binding that is here. + if [ "$(binding_window_state "$hid_bhost" "$hid_bwin" "$hid_blegacy")" != gone ]; then + HOLDER_BOUND_ELSEWHERE="${hid_bhost:-unknown}/${hid_bcont}" + return 1 + fi + HOLDER_DEAD_WHY="its binding's window is gone from this host's tmux, Amendment 18(b), and no live session on this workstation" + fi + fi + # 8 IS AN ANSWER AND 1 IS NOT (#67, the paragraph above `HOLDER_DEAD_VERB`): + # a lane the register gives no transcript uuid goes on to `live_holder` with + # an empty set exactly as before; a register that could not be read stops here. + hid_ids=""; hid_irc=0 + hid_ids="$(session_ids_checked "$hid_l")" || hid_irc=$? + case "$hid_irc" in + 0|8) : ;; + *) HOLDER_REGISTER_UNREADABLE=1; HOLDER_TERMINAL_UNKNOWN="$hid_verb"; return 1 ;; + esac + # THREE ANSWERS, NEVER TWO CONFLATED (Copilot round 1, opensoft/openRepoTools#61): + # `live_holder` is 0 live, 8 read-and-confirmed-nothing, or any other code a + # records tree this workstation could not read at all — and THAT is not + # "confirmed dead" either, it is "not established", exactly as every other + # caller of this one liveness implementation already treats it. Only 8 may + # pass; 0 and every failure both refuse. + live_holder "$hid_l" "$hid_ids" >/dev/null 2>&1; hid_lrc=$? + [ "$hid_lrc" = 8 ] || { + # A CONFIRMED-LIVE TERMINAL LOG IS ITS OWN VERDICT, NOT "NOT ESTABLISHED" + # (Copilot round 13, PR #61): this function's OWN return value stays + # fail-closed exactly as above — only 8 ever lets it answer dead — but a + # caller that reads false here and falls back to Rule 1's ORDINARY + # stale-claim test has no way to tell "this log never terminated" apart + # from "this log terminated and a real session still answers for it", + # and the second is refused on liveness alone wherever else this file + # meets it (`repoK-3`'s own case, `lane-start`'s own refusal). Recorded + # here, for `hid_lrc = 0` (genuinely confirmed live). + # + # AND AN UNREADABLE RECORDS TREE IS NEITHER (Copilot's own "closer look" + # on c82577e, PR #61): `hid_lrc` outside {0, 8} means this workstation + # could not read whether a live session backs the lane up at all — the + # exact reading every OTHER caller of `live_holder` already refuses on + # (the comment three lines up), and silently letting `claim_is_stale` + # answer instead would treat "I could not check" as "checked and clear" + # for the one shape (a terminal log) this file already distrusts enough + # to check in the first place. Recorded so the caller can refuse in + # these words rather than in the confirmed-live ones, which would + # misstate why. + if [ "$hid_lrc" = 0 ]; then + HOLDER_LIVE_TERMINAL="$hid_verb" + else + HOLDER_TERMINAL_UNKNOWN="$hid_verb" + fi + return 1 + } + HOLDER_DEAD_VERB="$hid_verb" + return 0 +} + +# ------------------------------------------------------------- liveness +# +# ONE implementation, here, because `lane-start` and `who` must agree about +# what "live" means — `lane-start` asks for it with the `live-holder` +# subcommand rather than keeping a second copy that can drift. +# +# LIVE iff a session record ON THIS WORKSTATION carries one of the row's +# transcript uuids, its `status` is not one of {ended, exited, dead, stopped}, +# its pid is alive, and `/proc//stat` field 22 still equals the +# `procStart` the record wrote down. + +# Every session record on this workstation, one path per line. +# +# R22 — AND IT SAYS WHETHER IT COULD READ THEM. Returns 0 when every records +# tree that EXISTS was listed without error, and 1 when one existed and could +# not be — a permissions or IO fault, which is not the same answer as "no record +# holds this lane" and must never be reported as one. A tree that is simply +# absent is not a failure: a workstation may have only one of the two. +SESSION_FILES_ERR="" +session_files() { + sf_rc=0; sf_d=""; sf_err="" + SESSION_FILES_ERR="" + sf_err="$(mktemp "${TMPDIR:-/tmp}/lanes-edit-sf.XXXXXX" 2>/dev/null || printf '')" + if [ -z "$sf_err" ]; then + SESSION_FILES_ERR="could not create a temporary file under ${TMPDIR:-/tmp}" + return 1 + fi + # Team profiles sit two levels down (profiles////sessions/), + # so that one is a -path find and not a one-level glob. + for sf_d in "$HOME/.claude-profiles/profiles" "$HOME/.claude/sessions"; do + [ -e "$sf_d" ] || continue + case "$sf_d" in + */sessions) find "$sf_d" -maxdepth 1 -name '*.json' -type f 2>>"$sf_err" || sf_rc=1 ;; + *) find "$sf_d" -path '*/sessions/*.json' -type f 2>>"$sf_err" || sf_rc=1 ;; + esac + done + if [ -s "$sf_err" ]; then + SESSION_FILES_ERR="$(LC_ALL=C tr '\n' ';' < "$sf_err" | LC_ALL=C cut -c1-300)" + sf_rc=1 + fi + rm -f -- "$sf_err" + return "$sf_rc" +} + +jstr() { printf '%s' "$1" | grep -o "\"$2\":\"[^\"]*\"" | head -n1 | sed 's/^.*":"//; s/"$//'; } +jnum() { printf '%s' "$1" | grep -o "\"$2\":[0-9][0-9]*" | head -n1 | sed 's/^.*://'; } + +# ------------------------------------------------- A11 Addendum 4 ruling 12: +# ONE PASS OVER THE SESSION RECORDS, FOR THE WHOLE PROCESS +# +# *"Decision 6's `lanes` gets a stated bar — it answers in about a second on +# this estate — and the per-lane fan-out is what changes to meet it."* +# +# WHERE THE TIME WENT, measured on a copy of the live register (46 rows, 15 +# logs) before any of this was written: `lanes` took 14 m 30 s wall and ~23 +# CPU-minutes. Not the register, and not the logs — a `git show` of the 1.1 MB +# register is 11 ms and the fifteen logs are one cached pass. It was THIS: 564 +# session records on this workstation, each read with `cat` and then four or +# five `jstr`/`jnum` calls that are FOUR PROCESSES EACH (`printf | grep | head | +# sed`) — about twenty processes per record, eleven thousand per scan — and both +# scans were rebuilt FOR EVERY LANE, because `live_session_ids` and `fork_map` +# cached into a VARIABLE and every caller invoked them inside `$( … )`, which is +# a subshell whose variables die with it. +# +# So: the parse becomes ONE awk over every record file, and the caches become +# FILES, which a subshell's build leaves behind for its parent. +# +# `jstr` and `jnum` ARE REPRODUCED HERE RATHER THAN CALLED, and the reproduction +# is exact: `jstr` is the first `"key":"…"` whose value holds no `"`, `jnum` the +# first `"key":` followed immediately by a digit. Both are `grep -o … | head -n1` +# on the whole blob, so both take the FIRST occurrence and neither is anchored. +# A record is read the same way by either path, and `record_is_live` still makes +# the liveness decision in shell, on the fields this hands it. +SESSION_RECORD_AWK=' +function jstr(s, k, r, i, v) { + r = "\"" k "\":\"" + i = index(s, r); if (i == 0) return "" + v = substr(s, i + length(r)) + i = index(v, "\""); if (i == 0) return "" + return substr(v, 1, i - 1) +} +function jnum(s, k, r, i, v, rest) { + r = "\"" k "\":" + rest = s + while ((i = index(rest, r)) > 0) { + v = substr(rest, i + length(r)) + if (v ~ /^[0-9]/) { match(v, /^[0-9]+/); return substr(v, 1, RLENGTH) } + rest = substr(rest, i + length(r)) + } + return "" +} +function emit( ) { + if (f == "") return + printf "%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n", f, sep, + jstr(blob, "sessionId"), sep, jstr(blob, "tmux"), sep, jstr(blob, "name"), sep, + jnum(blob, "pid"), sep, jstr(blob, "kind"), sep, jstr(blob, "cwd"), sep, + jstr(blob, "status"), sep, jstr(blob, "procStart") +} +FNR == 1 { emit(); f = FILENAME; blob = "" } +{ blob = blob $0 } +END { emit() }' + +# A PER-PROCESS FILE CACHE. `$( … )` is a subshell, so a variable set by a +# builder called inside one is gone the moment it answers; a file is not. +# Named beside the events cache so `cleanup`'s `rm -f -- "$SE_CACHE_FILE".*` +# already takes them, and cleared by `log_sync` with everything else it moves. +# +# SPELLED AS A PARAMETER EXPANSION AND NOT A FUNCTION, because a function called +# as `$(cache_path register)` is a FORK — and this is reached on the per-lane +# path the ruling exists to take the forks out of. `${SE_CACHE_FILE:+…}` is the +# shell's own, costs nothing, and yields the empty string where there is no +# cache file at all, which is the one case every caller already tests for. + +# Every session record on this workstation, parsed once: +# +session_records() { + sr_c="${SE_CACHE_FILE:+$SE_CACHE_FILE.records}" + if [ -n "$sr_c" ] && [ -f "$sr_c" ]; then cat -- "$sr_c"; return 0; fi + # AND A TREE THAT COULD NOT BE READ IS NOT A WORKSTATION WITH NO SESSIONS + # (#26, the review of `37632b1`, `lanes-edit.sh:2008`). `session_files` sets + # `SESSION_FILES_ERR` and returns 1 for exactly that case — the three callers + # that read it DIRECTLY refuse on it, and say so where they do — and this one + # read it through `|| :` inside a `$( )`, which discards the status and the + # message with the subshell. The empty answer was then CACHED for the life of + # the process, so every consumer after it was told the same untrue thing. The + # status decides here and NOTHING IS WRITTEN to the cache on it: a cache of a + # failure is a failure nobody can see. + sr_files=""; sr_frc=0 + sr_files="$(session_files 2>/dev/null)" || sr_frc=$? + [ "$sr_frc" = 0 ] || return 1 + sr_t="" + [ -n "$sr_c" ] && sr_t="$sr_c.${BASHPID:-$$}" + if [ -z "$sr_files" ]; then + [ -n "$sr_t" ] && { : > "$sr_t"; mv -f -- "$sr_t" "$sr_c" 2>/dev/null || rm -f -- "$sr_t"; } + return 0 + fi + # One awk, however many files — `awk` takes them all on its command line and + # `FILENAME` keeps each record attributable. The same shape `log_events` uses + # for the lane logs, for the same reason. + sr_arr=() + while IFS= read -r sr_f; do [ -n "$sr_f" ] && sr_arr+=("$sr_f"); done < "$sr_t"; mv -f -- "$sr_t" "$sr_c" 2>/dev/null || rm -f -- "$sr_t"; } + return 0 + fi + if [ -n "$sr_t" ]; then + awk -v sep="$US" "$SESSION_RECORD_AWK" "${sr_arr[@]}" > "$sr_t" 2>/dev/null + mv -f -- "$sr_t" "$sr_c" 2>/dev/null || { cat -- "$sr_t"; rm -f -- "$sr_t"; return 0; } + cat -- "$sr_c" + else + awk -v sep="$US" "$SESSION_RECORD_AWK" "${sr_arr[@]}" 2>/dev/null + fi + return 0 +} + +pid_alive() { + local pid="$1" want="$2" statline rest + [ -n "$pid" ] || return 1 + kill -0 "$pid" 2>/dev/null || return 1 + [ -n "$want" ] || return 0 + [ -r "/proc/$pid/stat" ] || return 0 + # `read` AND NOT `$(cat …)`, WHICH IS A FORK PER RECORD (A11 Addendum 4 + # ruling 12). This runs once for every session record on the workstation — + # 564 of them here — and `lanes` asked about every record for every lane, so + # this one substitution was ~26,000 processes for one listing. A builtin read + # of a one-line file is the same answer. + statline="" + read -r statline < "/proc/$pid/stat" 2>/dev/null || statline="" + rest="${statline##*) }" + # shellcheck disable=SC2086 + set -- $rest + [ "$#" -ge 20 ] || return 0 + [ "${20}" = "$want" ] +} + +# A session record's `name` is EVIDENCE ABOUT ANOTHER LANE only when a person +# or a `--name` set it. The values real records carry on this estate are: +# +# derived the harness named the window after its working directory +# auto the harness named it without being told to +# user a person typed `/rename`, or `--name` was passed +# peer another session in the mesh set it +# +# EXPLICIT is {user, peer} — the two a person or `--name` produces. A record +# with any other value, or with none at all, says nothing either way about +# which lane it is, and is therefore NOT read as a denial. +# +# This is a fix, not a preference. On 2026-09-11 the orchestrator's own record +# read `name: openrepoproject-63, nameSource: derived` while it held lane +# openRepoProject-1 — pid alive, procStart matching, status busy — and the old +# filter skipped it on the name alone, so a dry run reported "no live session +# holds openRepoProject-1" and a second window would not have been refused. +# 274 of this estate's 341 records carry `derived`. +EXPLICIT_NAME_SOURCES="user peer" +name_is_explicit() { + case " $EXPLICIT_NAME_SOURCES " in *" ${1:-} "*) return 0 ;; esac + return 1 +} + +# The three tests every record answers, wherever it was found: a status that is +# not one of {ended, exited, dead, stopped}, a pid that is alive, and a +# `/proc//stat` field 22 still equal to the `procStart` the record wrote +# down — so a recycled pid cannot hold a name. `live_holder` adds the two that +# are about a LANE (the row's ids, and the nameSource rule); `window_session` +# adds the one that is about a WINDOW. One copy of the three, because two would +# drift and this is the check that decides whether a name may be taken. +record_is_live() { # + record_fields_are_live "$(jstr "$1" status)" "$(jnum "$1" pid)" "$(jstr "$1" procStart)" +} +# THE SAME THREE TESTS, ON FIELDS ALREADY IN HAND (ruling 12). `session_records` +# parses every record once; re-serialising its fields back into a blob so this +# could re-parse them would be the fork storm the one pass exists to remove. +# ONE copy of the three tests, because two would drift and this is the check +# that decides whether a name may be taken. +record_fields_are_live() { # + case "${1-}" in ended|exited|dead|stopped) return 1 ;; esac + pid_alive "${2-}" "${3-}" +} + +# ------------------------------------- AMENDMENT 8, ruling (g): WHOSE session +# +# Three facts about this estate's records, every one of them observed on +# 2026-09-12 while `lane-start` was refusing the very window that held the lane: +# +# 1. THE HARNESS EXPORTS `CLAUDE_CODE_SESSION_ID` into every shell a session +# runs — so a `lane-start` that a session runs already knows its own +# transcript id without asking the filesystem anything. That is the +# cheapest and the most certain test there is, and it comes first. +# 2. ONE SESSION WRITES MORE THAN ONE RECORD. Beside the interactive process +# in the pane the harness runs a companion: `kind: bg`, no `tmux`, no +# `nameSource`, its own pid, and THE SAME `sessionId`. Records that share a +# `sessionId` are one session, not a queue of rival holders, and there is +# no contest between them to win. +# 3. A RECORD MAY CARRY NO `tmux` AT ALL. The pane's interactive record +# usually has one, the companion never does, and the harness has been seen +# to write none for a process plainly in a window. "No target" is not "no +# window": it is a missing observation, and the process tree holds the +# answer the record failed to write down. +# +# What those three produced: `live_holder` returned the COMPANION — its +# `sessionId` matched the row, its pid was alive, and carrying no `nameSource` +# it survived the name test — reported its target as `none`, and `lane-start` +# read "not this window" and refused the session that was running the command: +# +# lane openRepoProject-1 is live in session c5701b54… (tmux none); +# take openRepoProject-2 or resume that window +# +# The orphaned idle holder from the PREVIOUS profile was a real find and was +# correctly retired under Amendment 6(d); this one was the same shape read +# wrongly. The difference between them is not recency and never was — it is +# whether the process is in THIS pane's tree. + +# A `kind: bg` record is a COMPANION: never a holder, never a rival, skipped by +# every read that asks who holds a lane or what is in a window. Only +# `interactive` records hold a lane; a record from a harness too old to say +# carries no `kind` at all and is read as interactive, because that is the only +# thing those harnesses ever wrote. +record_is_session() { # + record_fields_are_session "$(jstr "$1" kind)" +} +record_fields_are_session() { # + case "${1-}" in + ''|interactive) return 0 ;; + *) return 1 ;; + esac +} + +# THIS shell's own window and pane, asked of tmux and never guessed. Both are +# empty outside tmux, and an empty answer makes every test below fail SHUT — so +# a caller with no tmux behaves exactly as it did before Amendment 8. Cached +# because `who` asks about every lane in the register and this is two forks. +LANES_HERE_CTX=0 +LANES_THIS_WINDOW="" +LANES_PANE_PID="" +here_context() { + [ "$LANES_HERE_CTX" = 1 ] && return 0 + LANES_HERE_CTX=1 + [ -n "${TMUX:-}" ] || return 0 + command -v tmux >/dev/null 2>&1 || return 0 + LANES_THIS_WINDOW="$(tmux display-message -p '#{session_name}:#{window_id}' 2>/dev/null || :)" + LANES_PANE_PID="$(tmux display-message -p '#{pane_pid}' 2>/dev/null || :)" + case "$LANES_PANE_PID" in *[!0-9]*) LANES_PANE_PID="" ;; esac + return 0 +} + +# pid_under — is the ancestor itself, or below it? +# +# `/proc//stat` is ` () …`, and a comm may hold +# spaces and brackets, so the parse starts after the LAST `) ` — the same cut +# `pid_alive` makes for field 22. The walk stops at pid 1, at an entry it cannot +# read (a process it cannot see is not in this pane), and at 64 steps, so a +# /proc that lies about parentage cannot spin it. +pid_under() { # + pu_p="${1-}"; pu_anc="${2-}"; pu_i=0 + [ -n "$pu_p" ] && [ -n "$pu_anc" ] || return 1 + case "$pu_anc" in *[!0-9]*) return 1 ;; esac + while [ "$pu_i" -lt 64 ]; do + case "$pu_p" in ''|*[!0-9]*) return 1 ;; esac + [ "$pu_p" = "$pu_anc" ] && return 0 + [ "$pu_p" -gt 1 ] 2>/dev/null || return 1 + [ -r "/proc/$pu_p/stat" ] || return 1 + pu_rest="$(cat "/proc/$pu_p/stat" 2>/dev/null || :)" + [ -n "$pu_rest" ] || return 1 + pu_rest="${pu_rest##*) }" + pu_p="$(printf '%s' "$pu_rest" | cut -d' ' -f2)" + pu_i=$((pu_i + 1)) + done + return 1 +} + +# record_is_here — is this record THIS window's own session? The ruling's +# order, cheapest and most certain first: +# 1. its `sessionId` is the one the harness exported into this very shell; +# 2. its `tmux` target names this window — the FAST PATH, and only a fast +# path: a record without one is not thereby somewhere else; +# 3. its pid is this pane's process, or below it. +record_is_here() { # + here_context + rih_sid="$(jstr "$1" sessionId)" + if [ -n "${CLAUDE_CODE_SESSION_ID:-}" ] && [ -n "$rih_sid" ] \ + && [ "$rih_sid" = "$CLAUDE_CODE_SESSION_ID" ]; then return 0; fi + rih_t="$(jstr "$1" tmux)" + if [ -n "$rih_t" ] && [ -n "$LANES_THIS_WINDOW" ] \ + && [ "${rih_t%.*}" = "$LANES_THIS_WINDOW" ]; then return 0; fi + pid_under "$(jnum "$1" pid)" "$LANES_PANE_PID" +} + +# live_holder [] +# +# R22 — IT FAILS CLOSED AT THE SOURCE. Three answers, and they are distinct: +# 0 a live record holds the lane (the row is printed) +# 8 the records were READ, and none of them does +# 1 the records could not be read — a permissions or IO fault +# +# AND ON 0 IT SAYS WHOSE (Amendment 8, ruling (g)). The fifth field is the +# verdict — `here`, `elsewhere` or `orphan` — because the caller that has to act +# on it cannot work it out from the `tmux` column: a record with no target is +# not a record in no window, and `lane-start` refusing on that string is what +# refused this lane its own window. `here` beats `elsewhere` beats `orphan`, and +# a record with no target whose SESSION also wrote a windowed record is that +# same session seen twice, not a second holder — it is dropped, never ranked. +# `lane-start` renames a window on 8 and REFUSES on anything else, so collapsing +# a failed read into 8 is exactly how a running lane loses its address: the +# rename mints ` (2)` (AGENTS.md rule 7). The first version returned 1 for +# both, which is the same fault one layer up; hardening the CALLER left this +# source with no way to say "I could not read". +live_holder() { + local lane="$1" ids="${2-}" all="${3-}" pats=() f blob pid name status target sid base src + local lh_files lh_match lh_err kindv verdict c c_sid c_tgt c_name c_pid c_v + local lh_bg="" lh_windowed="" lh_here="" lh_here_tgt="" lh_else="" lh_orph="" lh_bres="" + local cands=() + SESSION_FILES_ERR="" + [ -n "$ids" ] || ids="$(session_ids_of_lane "$lane" 2>/dev/null || :)" + # A row with no transcript uuid in it is an ANSWER: nothing recorded can be + # live. It is not a failed read. + [ -n "$ids" ] || return 8 + for sid in $ids; do pats+=(-e "\"sessionId\":\"$sid\""); done + [ "${#pats[@]}" -gt 0 ] || return 8 + lh_files="$(mktemp "${TMPDIR:-/tmp}/lanes-edit-lf.XXXXXX" 2>/dev/null || printf '')" + lh_match="$(mktemp "${TMPDIR:-/tmp}/lanes-edit-lm.XXXXXX" 2>/dev/null || printf '')" + lh_err="$(mktemp "${TMPDIR:-/tmp}/lanes-edit-le.XXXXXX" 2>/dev/null || printf '')" + if [ -z "$lh_files" ] || [ -z "$lh_match" ] || [ -z "$lh_err" ]; then + rm -f -- "$lh_files" "$lh_match" "$lh_err" 2>/dev/null || : + SESSION_FILES_ERR="could not create a temporary file under ${TMPDIR:-/tmp}" + return 1 + fi + # NOT `$( )`: session_files sets SESSION_FILES_ERR, and a subshell would keep + # the reason for the failure to itself. + if ! session_files > "$lh_files"; then + rm -f -- "$lh_files" "$lh_match" "$lh_err" + return 1 + fi + if [ ! -s "$lh_files" ]; then + rm -f -- "$lh_files" "$lh_match" "$lh_err" + return 8 # this workstation keeps no records at all + fi + # `xargs -r` IS GNU-ONLY and was dead weight: the `[ ! -s ]` guard above + # returns before this line when there is no record to search at all, which + # is the only thing `-r` would have caught (A9 Addendum 4, R-A9-11). The + # `tr`s read arbitrary bytes — a path, and grep's own words about it — so + # they read them as bytes: BSD `tr` answers `Illegal byte sequence` for a + # multibyte character in a UTF-8 locale and prints NOTHING, which would turn + # a record that cannot be read into a reason nobody can read either. + LC_ALL=C tr '\n' '\0' < "$lh_files" | xargs -0 grep -l -F "${pats[@]}" > "$lh_match" 2>"$lh_err" || : + if [ -s "$lh_err" ]; then # a record that exists and cannot be read + SESSION_FILES_ERR="$(LC_ALL=C tr '\n' ';' < "$lh_err" | LC_ALL=C cut -c1-300)" + rm -f -- "$lh_files" "$lh_match" "$lh_err" + return 1 + fi + rm -f -- "$lh_files" "$lh_err" + # PASS 1 — every live record the row's ids match, classified. Not the first + # one found: the first one found is a directory order, and on 2026-09-12 the + # directory order put the companion in front of the session at the keyboard. + while IFS= read -r f; do + [ -n "$f" ] || continue + blob="$(cat -- "$f" 2>/dev/null || :)" + [ -n "$blob" ] || continue + record_is_live "$blob" || continue + sid="$(jstr "$blob" sessionId)" + pid="$(jnum "$blob" pid)" + name="$(jstr "$blob" name)" + src="$(jstr "$blob" nameSource)" + target="$(jstr "$blob" tmux)" + # A COMPANION IS NOT A HOLDER. It is reported, on stderr, so that a person + # who is looking at a `(tmux none)` record can see why it was not obeyed. + if ! record_is_session "$blob"; then + kindv="$(jstr "$blob" kind)" + lh_bg="${lh_bg}${lh_bg:+, }pid ${pid:-unknown} (kind ${kindv:-none}, session ${sid:-unknown})" + continue + fi + base="${name% (*)}" + # `tr`, not `${x,,}`: openRepoTools' CI parses every shipped bash file with + # macOS' /bin/bash 3.2, where `${x,,}` is a SYNTAX error and not a portable + # lowercase (.github/workflows/tests.yml — that job names this very + # construction as its example). Amendment 9's adoption act 3, obligation 4. + base_lc="$(printf '%s' "$base" | tr '[:upper:]' '[:lower:]')" + lane_lc="$(printf '%s' "$lane" | tr '[:upper:]' '[:lower:]')" + if [ -n "$base" ] && [ "$base_lc" != "$lane_lc" ] && name_is_explicit "$src"; then + # AMENDMENT 16(e) — A NAME THIS LANE USED TO HAVE IS THIS LANE. The skip + # above is Amendment 8's: a session a PERSON named for ANOTHER lane is not + # this one's holder. After a rename the lane's own session still carries + # its FORMER name — the `/rename` is what clause (f) is for and it lands at + # the lane's next prompt, not before — and read byte for byte that record + # is "another lane's", so the lane's own live session stopped being its + # holder the instant the row moved. That would refuse the rename's own + # window its `/rename`, and tell `who` the lane is NOT LIVE while it is. + # Resolved through the same seat every other name goes through; anything + # that resolves elsewhere is still skipped, which is Amendment 8's rule + # unchanged. + # AND THE RESOLVER'S OWN STATUS IS KEPT (Copilot round 4). Piped into + # `grep | head || :` it was thrown away, so an unreadable alias table + # answered EMPTY here, the record was skipped, and `live_holder` returned + # 8 — "no live session holds it" — about a lane that is running. That is + # the read `lane-start` renames a window over. + lh_brc=0 + lh_bres="$(rows_named_ci_alias "$base" 2>/dev/null)" || lh_brc=$? + if [ "$lh_brc" != 0 ]; then + SESSION_FILES_ERR="${LANES_ALIASES_PATH:-lanes/aliases.tsv} could not be read ($(lane_alias_err)), so whether the session named '$base' carries a FORMER name of lane $lane could not be established (Amendment 16(e))" + rm -f -- "$lh_match" + return 1 + fi + lh_bres="$(printf '%s\n' "$lh_bres" | grep . | head -n1 || :)" + if [ -z "$lh_bres" ] || [ "$(lc "$lh_bres")" != "$lane_lc" ]; then continue; fi + fi + if record_is_here "$blob"; then verdict=here + elif [ -n "$target" ]; then verdict=elsewhere + else verdict=orphan + fi + [ -n "$target" ] && lh_windowed="${lh_windowed}${sid} +" + cands+=("$(printf '%s%s%s%s%s%s%s%s%s' "$sid" "$US" "${target:-none}" "$US" "${name:-none}" "$US" "${pid:-unknown}" "$US" "$verdict")") + done < "$lh_match" + rm -f -- "$lh_match" + [ -n "$lh_bg" ] && note "lane $lane: companion records, which are never holders: $lh_bg" + + # The restart observer needs every process, while live-holder keeps its + # existing preferred-record contract. Multiple witnesses of one PID are + # one holder; two PIDs sharing a transcript are still two holders. + if [ "$all" = all ]; then + [ "${#cands[@]}" -gt 0 ] || return 8 + printf '%s\n' "${cands[@]}" | awk -F'\037' '!seen[$1 FS $4]++' + return 0 + fi + + # PASS 2 — the pick. `here` first, and among two records of one session the + # WINDOWED one is the better witness of it; then a genuine rival in another + # window; then an orphan, and only one whose session wrote no windowed record + # at all, because the other kind is this same session seen twice. + for c in ${cands[@]+"${cands[@]}"}; do + IFS="$US" read -r c_sid c_tgt c_name c_pid c_v <<<"$c" + case "$c_v" in + here) + if [ -z "$lh_here" ] || { [ "$lh_here_tgt" = none ] && [ "$c_tgt" != none ]; }; then + lh_here="$c"; lh_here_tgt="$c_tgt" + fi ;; + elsewhere) [ -n "$lh_else" ] || lh_else="$c" ;; + orphan) + printf '%s' "$lh_windowed" | grep -qx -F -- "$c_sid" && continue + [ -n "$lh_orph" ] || lh_orph="$c" ;; + esac + done + if [ -n "$lh_here" ]; then printf '%s\n' "$lh_here"; return 0 + elif [ -n "$lh_else" ]; then printf '%s\n' "$lh_else"; return 0 + elif [ -n "$lh_orph" ]; then printf '%s\n' "$lh_orph"; return 0 + fi + return 8 +} + +# -------------------------------- AMENDMENT 8(f), R-A8-6: the ORPHANED HOLDERS +# +# A row's session cell is a HISTORY, and its EARLIER ids are history rather than +# alternatives — but a live process can still be holding one, which is Amendment +# 6(d)'s orphan and, on this lane, the reason the `/resume` picker offered two +# transcripts of which neither was the lane. `live_holder` answers about the +# lane's holder, one record, picked; this answers about ALL the earlier ids, and +# it answers to be READ. +# +# IT NAMES THEM AND DOES NOTHING ELSE. Retiring is `kill `, printed by the +# caller and run by a person: ending somebody's process is not a boundary +# script's act — an idle background session is exactly the shape of thing that +# turns out to be somebody's long-running job — and clause (f) rules it the +# operator's, for the same reason clause (a)'s step 3 pushes nobody's work for +# them. +# +# IDLE means a LIVE record (Amendment 6's three tests: a status that is not +# ended, a pid that is alive, a `procStart` that still matches) which is NOT a +# session in a window: a `kind: bg` companion, or a record carrying no `tmux` +# target at all. A live INTERACTIVE record with a window is not an orphan, it is +# a rival, and `live_holder` is the read that answers about those. +# +# One line per record, ``. +# Exit 0 with rows, 8 with none, 1 where the records could not be read. +idle_holders() { # + ih_lane="${1-}"; ih_ids=""; ih_last=""; ih_earlier=""; ih_out="" + ih_files=""; ih_match=""; ih_err=""; ih_f=""; ih_blob="" + ih_sid=""; ih_pid=""; ih_kind=""; ih_tgt="" + SESSION_FILES_ERR="" + [ -n "$ih_lane" ] || return 8 + ih_ids="$(session_ids_of_lane "$ih_lane" 2>/dev/null || :)" + [ -n "$ih_ids" ] || return 8 + ih_last="$(printf '%s\n' "$ih_ids" | tail -n1)" + ih_earlier="$(printf '%s\n' "$ih_ids" | grep -vx -F -- "$ih_last" || :)" + [ -n "$ih_earlier" ] || return 8 + ih_files="$(mktemp "${TMPDIR:-/tmp}/lanes-edit-if.XXXXXX" 2>/dev/null || printf '')" + ih_match="$(mktemp "${TMPDIR:-/tmp}/lanes-edit-im.XXXXXX" 2>/dev/null || printf '')" + ih_err="$(mktemp "${TMPDIR:-/tmp}/lanes-edit-ie.XXXXXX" 2>/dev/null || printf '')" + if [ -z "$ih_files" ] || [ -z "$ih_match" ] || [ -z "$ih_err" ]; then + rm -f -- "$ih_files" "$ih_match" "$ih_err" 2>/dev/null || : + SESSION_FILES_ERR="could not create a temporary file under ${TMPDIR:-/tmp}" + return 1 + fi + if ! session_files > "$ih_files"; then + rm -f -- "$ih_files" "$ih_match" "$ih_err" + return 1 + fi + if [ ! -s "$ih_files" ]; then + rm -f -- "$ih_files" "$ih_match" "$ih_err" + return 8 + fi + ih_pats=() + for ih_sid in $ih_earlier; do ih_pats+=(-e "\"sessionId\":\"$ih_sid\""); done + # `xargs -r` and the locale, for the reason `live_holder` gives above. + LC_ALL=C tr '\n' '\0' < "$ih_files" | xargs -0 grep -l -F "${ih_pats[@]}" > "$ih_match" 2>"$ih_err" || : + if [ -s "$ih_err" ]; then + SESSION_FILES_ERR="$(LC_ALL=C tr '\n' ';' < "$ih_err" | LC_ALL=C cut -c1-300)" + rm -f -- "$ih_files" "$ih_match" "$ih_err" + return 1 + fi + rm -f -- "$ih_files" "$ih_err" + while IFS= read -r ih_f; do + [ -n "$ih_f" ] || continue + ih_blob="$(cat -- "$ih_f" 2>/dev/null || :)" + [ -n "$ih_blob" ] || continue + record_is_live "$ih_blob" || continue + ih_sid="$(jstr "$ih_blob" sessionId)" + ih_tgt="$(jstr "$ih_blob" tmux)" + ih_kind="$(jstr "$ih_blob" kind)" + # a session IN a window is not an orphan — it is a rival, and live_holder's + # question, not this one's. + if record_is_session "$ih_blob" && [ -n "$ih_tgt" ]; then continue; fi + ih_pid="$(jnum "$ih_blob" pid)" + ih_out="${ih_out}${ih_sid}\t${ih_pid:-unknown}\t${ih_kind:-none}\t$(record_profile "$ih_f") +" + done < "$ih_match" + rm -f -- "$ih_match" + [ -n "$ih_out" ] || return 8 + printf '%b' "$ih_out" + return 0 +} + +# ---------------------------------------------- the session in a tmux WINDOW +# +# AMENDMENT 8. `live_holder` asks "is any session this ROW names alive"; this +# asks "which live session is in THIS WINDOW", and the two answers differ in +# exactly the case Amendment 8 exists for. The harness mints a new transcript +# uuid without anybody acting — a `/clear` does it (Amendment 6, fact 4), and so +# did the 2026-09-12 usage reset that carried this lane's conversation into +# `4a91f1dc…` while its row still ended on `09dd34d1…`. That id is in no row, so +# `live_holder` cannot see it and answers 8, "this lane is parked", about the +# conversation sitting in the window it was asked about. Keyed on the WINDOW +# instead, the record is found, and `lane-start` appends its uuid to the cell +# before it stamps — which is what makes the next resume land in the right +# conversation. + +# The profile a record belongs to, read off its own path — never guessed from +# the environment, because the process asking may be in another profile: +# ~/.claude-profiles/profiles////sessions/.json +# ~/.claude/sessions/.json -> default +record_profile() { + rpf_d="${1%/*}"; rpf_d="${rpf_d%/sessions}"; rpf_n="${rpf_d##*/}" + case "$rpf_n" in .claude|claude|"") printf 'default\n' ;; *) printf '%s\n' "$rpf_n" ;; esac +} + +# window_session — the LIVE record whose own `tmux` field names +# that window. The target is `:`, which is what +# `tmux display-message -p '#{session_name}:#{window_id}'` prints and what the +# record's `tmux` field carries before its `.%` suffix. +# +# NO NAME TEST. `live_holder`'s fifth test skips a record explicitly named for +# another lane, because there the question is "does this record hold that lane". +# Here the question is "what is running in this window", and a window holds one +# interactive session whatever it is called: the record's name is REPORTED, so +# the caller can put it in front of a person, and decides nothing. +# +# R22 — three answers, never two of them conflated: 0 with the record, 8 when +# the records were READ and none is in that window, 1 when they could not be +# read at all. +# WHERE SEVERAL LIVE RECORDS NAME ONE WINDOW, IDENTITY DECIDES — NOT RECENCY +# (Amendment 8, ruling (g); this replaces the first version's "the most recently +# updated one wins", which was wrong in the case it was written for). +# +# tier 3 its `sessionId` is `$CLAUDE_CODE_SESSION_ID`, which the harness +# exported into this very shell — when the window asked about is this +# one. Nothing beats a session naming itself. +# tier 2 its pid is this pane's process or below it — again only for this +# window. This is what lets a record with NO `tmux` be found: the +# harness does not always write the target down, and a record without +# one is not thereby in no window. +# tier 1 its `tmux` field names the window. The fast path, and the only test +# available for a window that is not this one. +# +# `updatedAt` breaks a tie WITHIN a tier and nowhere else, so the answer never +# depends on directory order. It cannot be the rule itself: it is a LIVENESS +# HEARTBEAT, and the idle companion beside a working session heartbeats later +# than the session does — in the 2026-09-12 records the companion's `updatedAt` +# was 1789235975177 against the interactive record's 1789235958137, so "the +# newest wins" picks precisely the record that is not in the window. Two records +# of ONE session are not a contest to win at all: the windowed one represents +# the session, and `record_is_session` has already dropped the companion. +window_session() { + local target="$1" f blob sid tmuxv name pid upd best_upd best_out wsn_files + local tier best_tier ws_is_self ws_pane + SESSION_FILES_ERR="" + [ -n "$target" ] || return 8 + # Tiers 2 and 3 are about THIS pane, so they apply only when the window asked + # about is the one this process is in. Asked about somebody else's window, + # this read is exactly the `tmux`-field match it always was. + here_context + ws_is_self=0; ws_pane="" + if [ -n "$LANES_THIS_WINDOW" ] && [ "$LANES_THIS_WINDOW" = "$target" ]; then + ws_is_self=1; ws_pane="$LANES_PANE_PID" + fi + wsn_files="$(mktemp "${TMPDIR:-/tmp}/lanes-edit-ws.XXXXXX" 2>/dev/null || printf '')" + if [ -z "$wsn_files" ]; then + SESSION_FILES_ERR="could not create a temporary file under ${TMPDIR:-/tmp}" + return 1 + fi + # NOT `$( )`: session_files sets SESSION_FILES_ERR, and a subshell would keep + # the reason for the failure to itself. + if ! session_files > "$wsn_files"; then rm -f -- "$wsn_files"; return 1; fi + best_upd=-1; best_tier=0; best_out="" + while IFS= read -r f; do + [ -n "$f" ] || continue + blob="$(cat -- "$f" 2>/dev/null || :)" + [ -n "$blob" ] || continue + record_is_live "$blob" || continue + # A COMPANION IS NOT WHAT IS IN A WINDOW. `kind: bg` carries the interactive + # record's own `sessionId`, so admitting it here would let the SAME uuid be + # found by the wrong process — and would re-open the bug the moment a + # harness starts writing a target on to companions. + record_is_session "$blob" || continue + sid="$(jstr "$blob" sessionId)" + tmuxv="$(jstr "$blob" tmux)" + tier=0 + if [ "$ws_is_self" = 1 ] && [ -n "${CLAUDE_CODE_SESSION_ID:-}" ] \ + && [ -n "$sid" ] && [ "$sid" = "$CLAUDE_CODE_SESSION_ID" ]; then + tier=3 + elif [ -n "$ws_pane" ] && pid_under "$(jnum "$blob" pid)" "$ws_pane"; then + tier=2 + elif [ -n "$tmuxv" ] && [ "${tmuxv%.*}" = "$target" ]; then + tier=1 + else + continue + fi + upd="$(jnum "$blob" updatedAt)" + case "$upd" in ''|*[!0-9]*) upd=0 ;; esac + if [ "$tier" -lt "$best_tier" ]; then continue; fi + if [ "$tier" = "$best_tier" ] && [ "$upd" -le "$best_upd" ]; then continue; fi + best_tier="$tier"; best_upd="$upd" + name="$(jstr "$blob" name)" + pid="$(jnum "$blob" pid)" + best_out="$(printf '%s%s%s%s%s%s%s%s%s' "$sid" "$US" "${tmuxv:-$target}" "$US" "${name:-none}" "$US" "${pid:-unknown}" "$US" "$(record_profile "$f")")" + done < "$wsn_files" + rm -f -- "$wsn_files" + [ -n "$best_out" ] || return 8 + printf '%s\n' "$best_out" + return 0 +} + +# ------------------------------------------------------------ the row, read +# +# R19 — FROM `origin/`, LIKE EVERY OTHER STATE READ. These four reads +# (the row itself, its session cell, its handoff path and its workstation +# column) were the last ones taking the WORKING TREE, and `print_holder_detail` +# is built entirely out of them — so `who` routinely answered with a current log +# and a stale row: a holder recorded on the other workstation read `NOT LIVE` +# because a peer's UNCOMMITTED edit to column 3 said `Eagle`, and a row that +# exists only on `origin/main` was not seen at all, losing the resume uuid and +# the handoff path, which are the two things `who` exists to hand over. Nothing +# in `who` reads the working tree now. + +# AMENDMENT 15 — `tolower` ON BOTH SIDES, like every other lookup of a lane +# name in this file. A caller reaches these two through `canon_lane`, so the +# name arriving here is already the ROW's own spelling; the comparison is +# case-insensitive anyway, because a caller that did not canonicalise must not +# silently read "this lane has no row" about a lane that has one. +ROW_AWK=' + substr($0,1,1) == "|" { + p1 = index($0, "`"); if (p1 == 0) next + rest = substr($0, p1 + 1); p2 = index(rest, "`"); if (p2 == 0) next + if (tolower(substr(rest, 1, p2 - 1)) == tolower(lane)) print + }' +row_of_lane() { register_text | awk -v lane="$1" "$ROW_AWK"; } +# The same row as THIS CHECKOUT has it. One caller: the `live-holder` +# subcommand, which unions these ids with the published ones because liveness +# fails CLOSED — an id this checkout knows and `origin/main` does not yet is one +# more reason to refuse a rename, never a reason to allow one (AGENTS.md rule 7). +row_of_lane_local() { awk -v lane="$1" "$ROW_AWK" "$LANES_FILE"; } +row_cell() { printf '%s\n' "$1" | awk -F'|' -v i="$2" '{print $i}'; } + +# ====================================================== AMENDMENT 15 ======= +# +# THE RESOLVER. **A lane name is compared CASE-INSENSITIVELY wherever a name is +# looked up, and the spelling the register row carries is canonical** — it is +# what the window is named, what the session is named, what the log file is +# called, and what every line and stamp writes. A name typed in another case +# RESOLVES to it and is never written as typed. +# +# Every spelling the PUBLISHED register carries for a name, from +# `origin/` like every other state read (R19). `lane_named_ci` below is +# the same question asked for one answer and no refusal — it is the hook's read +# and the hook never refuses — so the two are one parse in two shapes rather +# than two rules. +# +# AND A THIRD SHAPE SINCE AMENDMENT 12: the prompt guard asks this one because +# it COUNTS. `canon_lane` below answers a caller that wants a name back and +# refuses two with `note` + 2 in this file's own voice; the guard has to print +# its triple FIRST and then say what is wrong, in its own shape, so it takes the +# spellings from here and makes the refusal itself. One parse, three readings, +# and no second rule about what a lane name is. +# +# AND IT RETURNS 1 WHERE THE PUBLISHED REGISTER COULD NOT BE READ (#138 item +# 18): the pipeline's status is the awk's, so a failed read was "no such row". +# It reads `register_text_checked` (#67), whose status `register_text` drops, +# and keeps both statuses; every caller that does not check them is unchanged. +rows_named_ci() { # + register_text_checked | awk -v want="$1" ' + substr($0,1,1) == "|" { + p1 = index($0, "`"); if (p1 == 0) next + rest = substr($0, p1 + 1); p2 = index(rest, "`"); if (p2 == 0) next + t = substr(rest, 1, p2 - 1) + if (tolower(t) == tolower(want)) print t + }' + [ "${PIPESTATUS[0]}${PIPESTATUS[1]}" = 00 ] +} + +# ====================================================== AMENDMENT 16 ======= +# +# THE LANE ALIAS TABLE — `lanes/aliases.tsv`, ` ` — AND THE +# ONE SEAT EVERY READER SHARES. +# +# Clause (e): *"Every reader that takes a lane name — `who`, `lanes`, +# `live-holder`, `history`, Rule 6 attribution, `lane-start`'s row lookup, the +# `SessionStart` block and Amendment 12's guard — resolves through it, +# case-insensitively (Amendment 15), before it reads."* THAT LIST IS NOT BUILT +# AS A LIST. Amendment 15 already put `canon_lane` in front of every one of +# those reads — each subcommand arm below spells +# `lane="$(canon_lane "$lane")" || exit 2`, and `lane-start`, `lane-end`, `lane` +# and `lane-handoff` each call the `canon-lane` subcommand — so the resolution +# is hooked THERE, once, and the guard's own two lookups take the same function +# one layer down. A list of readers is a list somebody has to keep complete. +# +# READ FROM `origin/` LIKE THE REGISTER (R19), falling back to this +# checkout's own file — `register_text`'s exact shape, for its exact reason: +# `rename-lane` lands the row and this table in ONE commit, so a reader taking +# one from the working tree and the other from `origin` could see an alias whose +# row has not arrived here, or a row whose alias has not. +LANES_ALIAS_CACHE="" +LANES_ALIAS_ERR="" +# THE REASON IS WRITTEN WHERE THE PARENT CAN READ IT, and that is not a +# nicety: every caller of `lane_alias_text` reaches it through a COMMAND +# SUBSTITUTION — `lane_alias_hop`, `lane_alias_target` and `lane_alias_keys` +# are all taken with `$( )`, and `rows_named_ci_alias` is taken with one by +# `canon_lane` — so a variable set here dies with the subshell, and every +# refusal below printed `(unknown error)`: fail-closed, and silent about what +# to fix. It goes in a file beside the events cache, which `cleanup` already +# sweeps (`rm -f -- "$SE_CACHE_FILE".*`), exactly as `SE_WARN_FILE` carries a +# warning raised inside the same kind of substitution. The variable is kept as +# the answer for a process that has no temporary file at all — `mktemp` can +# fail, and `SE_CACHE_FILE` is empty when it does. +lane_alias_fail() { # + LANES_ALIAS_ERR="${1-}" + laf_f="${SE_CACHE_FILE:+$SE_CACHE_FILE.aliaserr}" + [ -n "$laf_f" ] && printf '%s' "${1-}" > "$laf_f" 2>/dev/null + return 0 +} +# AND IT IS NOT ITS OWN FALLBACK. The file is the reason THIS process last +# failed with; the variable is the reason THIS SHELL last failed with; and +# where there is neither, the sentence still has to read as English, so the +# words are spelled out here rather than left to a caller's `${x:-…}`. +lane_alias_err() { + lae_f="${SE_CACHE_FILE:+$SE_CACHE_FILE.aliaserr}" + if [ -n "$lae_f" ] && [ -s "$lae_f" ]; then cat -- "$lae_f"; return 0; fi + printf '%s' "${LANES_ALIAS_ERR:-unknown error}" + return 0 +} +# A READ THAT FAILED IS NOT AN EMPTY TABLE (Copilot round 1 on openRepoTools#81). +# `cat … 2>/dev/null || :` made a permission or IO fault on `lanes/aliases.tsv` +# indistinguishable from an estate that has never renamed a lane — and the two +# have opposite consequences: the second means a name resolves to itself, while +# the first means a name whose row moved resolves to NOTHING, so a reader misses +# that lane's whole history and `rename-lane` validates its cycle test against a +# table it could not read. Clause (e) promises the old name resolves FOR EVER, so +# this fails CLOSED: 5, with the reason in `LANES_ALIAS_ERR`, which the writer +# turns into a refusal and every reader says out loud. +lane_alias_text() { + if [ -n "$LANES_ALIAS_CACHE" ]; then printf '%s\n' "$LANES_ALIAS_CACHE"; return 0; fi + lat_c="${SE_CACHE_FILE:+$SE_CACHE_FILE.aliases}" + # THE CACHE'S OWN READ IS CHECKED (Copilot round 5 on openRepoTools#81). The + # `return 0` under an unchecked `cat` was the fail-closed rule with a hole in + # it: a cache this process wrote and cannot now read would answer EMPTY with + # status 0, and a former lane name would resolve as new — which is the one + # outcome every other branch of this function exists to refuse. + if [ -n "$lat_c" ] && [ -s "$lat_c" ]; then + cat -- "$lat_c" || { + lane_alias_fail "the cached copy at $lat_c could not be read" + return 5 + } + return 0 + fi + # A FRESH READ BEGINS HERE, so the reason the LAST one failed with goes: the + # file outlives the subshell that wrote it on purpose, and an answer kept + # past the read it belongs to is the stale kind of honesty. + lat_t=""; LANES_ALIAS_ERR="" + lat_e="${SE_CACHE_FILE:+$SE_CACHE_FILE.aliaserr}" + [ -n "$lat_e" ] && rm -f -- "$lat_e" + # AMENDMENT 14 — under `--index`, the table as the indexed commit carried it; + # where it carried none, the same local fallbacks below. + if [ -n "$LANES_IDX_DIR" ] && [ -f "$LANES_IDX_DIR/aliases" ]; then + lat_t="$(cat -- "$LANES_IDX_DIR/aliases" 2>/dev/null)" || { + lane_alias_fail "the index's copy at $LANES_IDX_DIR/aliases could not be read" + return 5 + } + elif [ -z "$LANES_IDX_DIR" ] && have_remote_ref && git -C "$LANES_REPO" cat-file -e "origin/$LANES_BRANCH:$LANES_ALIASES_PATH" 2>/dev/null; then + lat_t="$(git -C "$LANES_REPO" show "origin/$LANES_BRANCH:$LANES_ALIASES_PATH" 2>/dev/null)" || { + lane_alias_fail "git show origin/$LANES_BRANCH:$LANES_ALIASES_PATH failed, and the object is there" + return 5 + } + elif [ -n "${LANES_ALIASES_TSV:-}" ] && [ -f "$LANES_ALIASES_TSV" ]; then + lat_t="$(cat -- "$LANES_ALIASES_TSV" 2>/dev/null)" || { + lane_alias_fail "$LANES_ALIASES_TSV is there and could not be read" + return 5 + } + elif [ -n "${LANES_ALIASES_TSV:-}" ] \ + && { [ -e "$LANES_ALIASES_TSV" ] || [ -L "$LANES_ALIASES_TSV" ]; }; then + # SOMETHING IS THERE AND IT IS NOT A TABLE (Copilot round 8 on + # openRepoTools#81). A directory, a FIFO, a socket or a DANGLING symlink at + # this path makes `-f` false, and the branch was simply skipped: the empty + # answer below was cached and handed back with status 0, so a former lane + # name read as NEW — and `lane-start` then appends a SECOND row for a lane + # that has been running all day, which is Amendment 15(a)'s duplicate + # arrived at through a READ. `-L` is asked beside `-e` because `-e` is FALSE + # on a dangling link, the same pair the handoff's destination test uses. + # + # AND THE READER'S RULE IS NARROWER THAN THE WRITER'S, deliberately. The + # writer refuses a LIVE symlink to a regular file as well, because it + # appends in place and a redirect follows one into whatever is at the far + # end; a reader that follows the same link gets the table's own bytes and is + # right to, so `-f` above answers it and says nothing. What is refused here + # is only what cannot be READ — which is why the two say different words. + if [ -L "$LANES_ALIASES_TSV" ]; then + lane_alias_fail "$LANES_ALIASES_TSV is a symlink whose target is not a regular file" + else + lane_alias_fail "$LANES_ALIASES_TSV exists and is not a regular file" + fi + return 5 + fi + # AND THE EMPTY ANSWER IS CACHED TOO, as one comment line in the table's own + # grammar. An estate that has never renamed a lane is the ordinary case, and + # without this the `cat-file -e` above would run again for every `canon_lane` + # of every command — which is the cost `table_lookup` one screen up exists to + # avoid, made per process instead of per lane. + LANES_ALIAS_CACHE="${lat_t:-# no lane aliases}" + if [ -n "$lat_c" ]; then + printf '%s\n' "$LANES_ALIAS_CACHE" > "$lat_c.${BASHPID:-$$}" 2>/dev/null && + mv -f -- "$lat_c.${BASHPID:-$$}" "$lat_c" 2>/dev/null || + rm -f -- "$lat_c.${BASHPID:-$$}" + fi + printf '%s\n' "$LANES_ALIAS_CACHE" +} + +# BOTH COPIES OF IT, and the flag that says the awk file has been asked for: +# the variable this shell holds, the file every subshell reads, and the path +# `LOG_AWK` was handed (ruling 12's rule for the register cache, which this one +# is a twin of). Called by `log_sync`, because a fetch moves the ref this is +# read from, and by `rename-lane` after its own commit, because the alias it +# just wrote is the one the comments below it are computed with. +lane_alias_flush() { + LANES_ALIAS_CACHE="" + LANES_ALIAS_ERR="" + laf_e="${SE_CACHE_FILE:+$SE_CACHE_FILE.aliaserr}" + [ -n "$laf_e" ] && rm -f -- "$laf_e" + laf_c="${SE_CACHE_FILE:+$SE_CACHE_FILE.aliases}" + [ -n "$laf_c" ] && rm -f -- "$laf_c" + return 0 +} + +# lane_alias_target [] — the END of that name's alias chain. +# 0 + the name the table names it (a chain `a→b`, `b→c` answers `c`) +# 1 + nothing the table does not name it +# 3 + nothing the table holds a CYCLE through it +# 4 + nothing the chain VISITS — `rename-lane`'s cycle test, +# which asks of the table as it WILL be: adding ` → +# ` closes a cycle exactly when the chain from `` +# reaches ``, and reaching it ANYWHERE counts, not only +# at the end (a chain `new → old → x` ends at `x` and still +# closes, because the new row is appended last and wins the +# key `old`). +# 5 + nothing the table could not be READ (fail closed; `LANES_ALIAS_ERR`) +# +# Case-insensitive on both sides (Amendment 15). THE LAST ROW FOR A KEY WINS: +# the file is append-ordered, and a name renamed away, minted again and renamed +# again has two rows of which the later is the answer a reader today needs. +# +# THE WALK IS BOUNDED BY THE TABLE AND NOT BY A NUMBER (Copilot round 1 on +# openRepoTools#81). It was `for (i = 0; i < 32; i++)`, which is a CAP on a +# valid chain as well as on a cycle: an estate that renamed one lane thirty-three +# times would have its earliest names resolve to an INTERMEDIATE one, which has +# no row, so `canon_lane` would answer a name nothing carries and clause (e)'s +# "for ever" would quietly end at hop 32. The `seen` set is what guarantees +# termination — every hop consumes one key of a finite map — so the bound is the +# number of keys plus one, which no honest chain can exceed and no cycle can +# reach without closing first. +lane_alias_target() { # [] + lat_out="$(lane_alias_text)" || return 5 + printf '%s\n' "$lat_out" | awk -F'\t' -v want="$1" -v stop="${2-}" ' + /^[ \t]*#/ { next } + NF >= 2 { + k = $1; v = $2 + gsub(/^[ \t]+|[ \t]+$/, "", k); gsub(/^[ \t]+|[ \t]+$/, "", v) + if (k == "" || v == "") next + if (!(tolower(k) in map)) nmap++ + map[tolower(k)] = v + } + END { + cur = want; ls = tolower(stop) + for (i = 0; i <= nmap; i++) { + lk = tolower(cur) + if (stop != "" && lk == ls) { hit = 1; break } + if (lk in seen) { cyc = 1; break } + if (!(lk in map)) break + seen[lk] = 1; cur = map[lk]; hops++ + } + if (hit) exit 4 + if (cyc) exit 3 + if (hops > 0) { print cur; exit 0 } + exit 1 + }' +} + +# ONE HOP, and the reason it exists apart from the walk above: "a ROW WINS OVER +# AN ALIAS" has to be asked at EVERY hop and not only at the start (Copilot round +# 1). After `A → B`, a lane legitimately minted under the name `A` again — the +# position `A` freed is one `lane_next_free` will hand out — makes `A` both a row +# and an alias key, and a chain `C → A` must then stop AT `A`, which is a lane, +# rather than carry on to `B`, which is a different one. Walking hop by hop in +# the shell is what lets the row test sit between the hops; the chains this +# estate writes are one or two long, and `register_text` is cached, so the cost +# is an awk per hop over a table of a few lines. +# 0 + the next name · 1 + nothing · 5 the table could not be read +lane_alias_hop() { # + lah_out="$(lane_alias_text)" || return 5 + printf '%s\n' "$lah_out" | awk -F'\t' -v want="$1" ' + /^[ \t]*#/ { next } + NF >= 2 { + k = $1; v = $2 + gsub(/^[ \t]+|[ \t]+$/, "", k); gsub(/^[ \t]+|[ \t]+$/, "", v) + if (k == "" || v == "") next + map[tolower(k)] = v + } + END { if (tolower(want) in map) { print map[tolower(want)]; exit 0 } exit 1 }' +} + +# lane_alias_keys — every key of the table, one per line, as written. The one +# caller is `rename-lane`, which refuses a `` that is already a key +# (Copilot round 1): a row under a former name TAKES PRECEDENCE over the alias, +# so minting one deliberately would end that former name's resolution — the one +# thing clause (e) promises never happens. +lane_alias_keys() { + lak_out="$(lane_alias_text)" || return 5 + printf '%s\n' "$lak_out" | awk -F'\t' ' + /^[ \t]*#/ { next } + NF >= 2 { k = $1; gsub(/^[ \t]+|[ \t]+$/, "", k); if (k != "") print k }' +} + +# Every ROW SPELLING that answers for : its own rows, and where it has +# none, the rows of the first name along its alias chain that HAS one. Used by +# `canon_lane` below and by the guard's window and session lookups, which are +# the two seats that read a row from a name without going through `canon_lane`. +# +# A ROW WINS OVER AN ALIAS, AT EVERY HOP AND NOT ONLY AT THE START (Copilot +# round 1 on openRepoTools#81). A name that is a lane today IS that lane — which +# is what makes renaming a lane BACK to a name readable — and the chain has to +# be walked with that test BETWEEN the hops, because an alias key can become a +# row again: `A → B` frees the name `A`, `lane_next_free` hands that position +# out, and a later `C → A` must then answer `A`, the lane, rather than running +# on to `B`, which is a different one. Taking only the END of the chain answered +# `B` and lost `C`'s own lane. +# +# The loop is bounded by a `seen` list rather than by a number, for +# `lane_alias_target`'s reason: every hop consumes one key of a finite table. +# 0 + the row spellings (possibly none) · 5 the alias table could not be READ +# +# AND THE 5 IS CARRIED, NOT SWALLOWED (Copilot round 3 on openRepoTools#81). It +# was `|| return 0`, which hands a caller an EMPTY answer — "no row under this +# name" — for a table nobody could read. Every caller then falls to its own +# not-a-lane branch: `canon_lane` answers the typed spelling, so `lane-start` +# reads a renamed lane as new and appends a SECOND row; the guard falls to +# `lane_shaped` and sends a running session to bind a row it already has. That +# is the fail-OPEN direction on the one promise clause (e) makes, so the status +# is propagated and each caller decides what to do with it. +rows_named_ci_alias() { # + rna_hits="$(rows_named_ci "$1" 2>/dev/null || :)" + if [ -n "$rna_hits" ]; then printf '%s\n' "$rna_hits"; return 0; fi + rna_cur="$1"; rna_seen="$US$(lc "$1")$US" + while :; do + rna_rc=0 + rna_next="$(lane_alias_hop "$rna_cur" 2>/dev/null)" || rna_rc=$? + [ "$rna_rc" = 5 ] && return 5 + [ "$rna_rc" = 0 ] && [ -n "$rna_next" ] || return 0 + case "$rna_seen" in *"$US$(lc "$rna_next")$US"*) return 0 ;; esac + rna_seen="$rna_seen$(lc "$rna_next")$US" + rna_hits="$(rows_named_ci "$rna_next" 2>/dev/null || :)" + if [ -n "$rna_hits" ]; then printf '%s\n' "$rna_hits"; return 0; fi + rna_cur="$rna_next" + done +} + +# canon_lane — the name every `` argument and `$LANES_LANE` is +# read through BEFORE anything is read or written under it. +# +# exactly one row matches, ignoring case its OWN spelling +# no row matches the typed spelling, unchanged — +# which is what `add-row` needs, and +# what makes a brand-new lane's +# first act possible at all +# two or more REFUSE (2), naming them all +# +# IT RETURNS AND NEVER EXITS, for `row_line`'s reason: every caller takes it +# with `$( )`, and an `exit` there would leave only the substitution's subshell +# while the caller carried on with an empty lane name. The callers spell it +# `lane="$(canon_lane "$lane")" || exit 2`. +# +# THE REFUSAL IS THE AMENDMENT'S OWN AND IT BELONGS TO EVERY WRITER, not only +# to `lane-start`, which has refused two rows for one name since Amendment 5: +# clause (b) says *"where the register already holds two rows that differ only +# by case, every writer REFUSES, naming both, until they are merged"*. Merging +# them is 15(d)'s act and a person's — the newer row's session id(s) appended to +# the older row's cell, in order, and the newer row removed in the same commit — +# because a tool that merged two rows of history on its own would be choosing +# which lane's record survives. +# +# AMENDMENT 16(e) — AND A NAME WITH NO ROW IS ASKED OF THE ALIAS TABLE BEFORE +# the typed spelling is handed back. This is clause (e)'s whole implementation +# and it is one function deep: a renamed lane's OLD name, from a line, a window, +# a session record or a person's typing, lands on the row it is now. The order +# is row first and alias second — a name that is a lane today is that lane — and +# the resolution SAYS SO on stderr, because every act under an old name is an +# act on a lane the caller did not name. +canon_lane() { # + cl_want="${1-}" + [ -n "$cl_want" ] || return 0 + cl_rc=0 + cl_hits="$(rows_named_ci_alias "$cl_want" 2>/dev/null)" || cl_rc=$? + # AN ALIAS TABLE THAT CANNOT BE READ IS A REFUSAL HERE TOO (Copilot round 3 + # on openRepoTools#81). This function's answer is what `lane-start` decides + # "is this lane new" by and what `register-row` reports, so carrying on with + # the typed spelling is not a read-only shrug: with a row under `` and an + # unreadable table, `lane-start ` reads the former name as absent + # and appends a SECOND row — the duplicate Amendment 15(a) exists to refuse. + # R22's rule governs: a read that could not be performed is never an answer. + if [ "$cl_rc" = 5 ]; then + note "${LANES_ALIASES_PATH:-lanes/aliases.tsv} COULD NOT BE READ ($(lane_alias_err)), so whether '$cl_want' is a FORMER name of some lane is NOT established — which is not the same as it not being one (Amendment 16(e))." + note "Nothing is read or written under a name this register cannot resolve: a rename's alias would be invisible, and a lane that has one would read as new. Fix the read — the table is ${LANES_ALIASES_TSV:-} here and ${LANES_ALIASES_PATH:-lanes/aliases.tsv} on origin/$LANES_BRANCH — and re-run." + # 66 AND NOT 2, BECAUSE 2 ALREADY MEANS SOMETHING TO FOUR CALLERS (Copilot + # round 4). `lane-start`, `lane-end`, `lane` and `lane-handoff` each read + # `canon-lane`'s 2 as EITHER Amendment 15(d)'s two-rows refusal — told by + # the words in its message — or the unknown-subcommand 2 of a helper that + # predates Amendment 15, which they carry on past with the name as typed. + # A third meaning on that number lands in the second branch, which is the + # fail-OPEN this refusal exists to close. 66 is EX_NOINPUT: an input file + # that did not exist or could not be read, which is exactly what happened, + # and a code none of the four recognises makes `lane` and `lane-handoff` + # refuse where they stand — the other two are taught it in this same commit. + return 66 + fi + cl_n="$(printf '%s' "$cl_hits" | grep -c . || :)" + if [ "$cl_n" -gt 1 ]; then + note "the register has $cl_n rows whose lane names differ only by case for '$cl_want': $(printf '%s' "$cl_hits" | tr '\n' ' ')" + note "a lane name is ONE name under any case (Amendment 15), so no read and no write under it is unambiguous. Merge them into one row (Amendment 15(d)): append the newer row's session id(s) to the older row's session cell, in order, remove the newer row in the SAME commit, and name both spellings in the commit message." + return 2 + fi + cl_out="$cl_want" + if [ "$cl_n" = 1 ]; then + cl_out="$cl_hits" + else + # NO ROW UNDER EITHER NAME. The alias still answers where the table names + # it — a lane whose row has since been archived keeps its log, and reading + # that log under the old name is the whole point of the table. + cl_al=""; cl_arc=0 + cl_al="$(lane_alias_target "$cl_want" 2>/dev/null)" || cl_arc=$? + if [ "$cl_arc" = 3 ]; then + note "${LANES_ALIASES_PATH:-lanes/aliases.tsv} resolves '$cl_want' in a CYCLE, so it names no lane at all: a rename chain that returns to its own start has no end to resolve to. \`rename-lane\` refuses to write one, so this table was edited by hand — take the offending row out of it. Carrying on with '$cl_want' exactly as typed." + elif [ "$cl_arc" = 5 ]; then + # UNREACHABLE BY THE PATH ABOVE, which already refused a 5 — kept because + # this arm is the second reader of the same table and a silent + # disagreement between two readers of one file is worth a line of code. + note "${LANES_ALIASES_PATH:-lanes/aliases.tsv} could not be read ($(lane_alias_err))." + return 66 + elif [ -n "$cl_al" ]; then + cl_out="$cl_al" + fi + fi + if [ "$(lc "$cl_out")" != "$(lc "$cl_want")" ]; then + note "'$cl_want' is a FORMER name of lane $cl_out (${LANES_ALIASES_PATH:-lanes/aliases.tsv}, Amendment 16(e)) — reading and writing $cl_out." + fi + printf '%s' "$cl_out" + return 0 +} + +uuids_in_cell() { grep -oiE '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}' | tr 'A-F' 'a-f' || :; } + +session_ids_of_lane() { + si_row="$(row_of_lane "$1")" + [ -n "$si_row" ] || return 1 + row_cell "$si_row" 3 | uuids_in_cell +} +session_ids_local_of_lane() { + sl_row="$(row_of_lane_local "$1")" + [ -n "$sl_row" ] || return 1 + row_cell "$sl_row" 3 | uuids_in_cell +} +# THE SAME UNION, AND IT SAYS WHETHER IT COULD READ IT (opensoft/openRepoTools#67). +# The pair above answer 1 for "this lane has no row" AND for "the register could +# not be read" — `row_of_lane` is `register_text | awk`, and `awk` answers 0 +# over an empty render — so a caller that unions them with `|| :` holds an +# EMPTY id set either way. For most of them that is harmless. For the three +# that take an empty set as a VERDICT it is fail-open: `holder_is_dead` hands it +# to `live_holder`, whose 8 then calls a lane dead that nobody could check, +# `duplicate_holder_pids` answers "no duplicate" without looking, and +# `lane_reconcile` pronounces a crash on that same 8 (#113 item 1). Those three +# ask this read instead, and the pair keep their contract for everyone else. +# +# 0 the published-union-local ids, one per line, published first, deduped +# 8 BOTH copies were read and neither gives this lane a transcript uuid: no +# row, or a row whose session cell holds none — an answer either way, the +# same one `live_holder` already gives an empty cell +# 1 the published register (or, with none published, the working tree's) or +# the working tree's own copy could not be read: NOT an empty set +session_ids_checked() { # + sc_pub=""; sc_loc="" + sc_pub="$(register_text_checked 2>/dev/null)" || return 1 + sc_loc="$(row_of_lane_local "$1" 2>/dev/null)" || return 1 + sc_ids="$(row_cell "$(printf '%s\n' "$sc_pub" | awk -v lane="$1" "$ROW_AWK") +$sc_loc" 3 | uuids_in_cell | awk 'NF && !seen[$0]++')" + [ -n "$sc_ids" ] || return 8 + printf '%s\n' "$sc_ids" +} +last_session_id_of_lane() { session_ids_of_lane "$1" 2>/dev/null | tail -n1; } +# The handoff path is the row's SIXTH column — awk field 7, because $1 is the +# empty string before the leading pipe. Counting back from NF was wrong for any +# row with a literal `|` inside a cell, and the live register has two: of 45 +# rows, 43 split into 9 fields, one into 10 and one into 11, and for the last +# of those NF-2 is the tail of the state cell (` re-cut `) rather than the +# handoff. `lane_workstation` below counts from the left for the same reason. +handoff_of_lane() { + hl_row="$(row_of_lane "$1")" + [ -n "$hl_row" ] || return 1 + row_cell "$hl_row" 7 | sed 's/^ *//; s/ *$//' +} + +short_ws() { printf '%s' "${1%%.*}" | tr 'A-Z' 'a-z'; } + +# Column 3 of the row is ` / / `. A lane recorded on +# ANOTHER workstation cannot be liveness-checked from here at all: the session +# records are local files. Saying NOT LIVE about it would be a claim this +# machine has no way to make. +lane_workstation() { + lw_row="$(row_of_lane "$1")" + [ -n "$lw_row" ] || return 1 + row_cell "$lw_row" 4 | sed 's/^ *//; s/ *$//; s| */.*||' | awk '{print $1}' +} +lane_is_elsewhere() { + lw="$(lane_workstation "$1" 2>/dev/null || :)" + [ -n "$lw" ] || return 1 + [ "$(short_ws "$lw")" != "$(short_ws "$WS")" ] +} + +# The session id an event line carries: what the caller says it is, else the +# lane's current one (Amendment 6(b): the LAST id in the cell), else NOTHING. +# +# R-A11 (e) — IT NO LONGER SUBSTITUTES THE LITERAL `unknown`. It did, and that +# literal is in the append-only log four times already, in two lanes +# (`lanes/log/codeXfactory-1.md` ×3, `lanes/log/openxfactory-4-opendox-extraction.md` +# ×1 on `origin/main`) — written by `log PAUSED` from a swap skill that had the +# uuid in hand and did not pass it, and by `release`. Amendment 7(b) makes that +# field a transcript uuid and ONLY that. Returning empty hands the decision to +# `write_event`, which refuses the write and names the act that supplies the +# uuid; the four lines already written stay exactly where they are (Amendment +# 7(b) forbids editing them, 7(i)'s cutover rule governs). +session_for() { + if [ -n "${LANES_SESSION:-}" ]; then printf '%s\n' "$LANES_SESSION"; return 0; fi + last_session_id_of_lane "$1" 2>/dev/null || : +} + +# ----------------------------------------------------- project.yaml legs +# +# openRepoShape's assembly-root manifest: a top-level `legs:` list of +# `- role: assembly|spec|code` / `repository: owner/repo` / `path:`. Two +# repositories are legs of ONE project when one manifest names them both. +# +# ONLY `legs[].repository` is read, and only as navigation. The manifest says +# of itself that it CONFERS NOTHING — `role:` in particular grants nothing and +# is never read here. +# +# `family.yaml`'s `members:` is deliberately NOT read, though its entries carry +# a `repository:` too. A family is broader than a project — `InkRouter` holds +# `IRRS` and `IRSS`, separate projects with separate lanes — and the ruling +# said legs. Two repos in one family ARE a crossing. +project_legs_file() { + [ -f "$1" ] || return 1 + awk ' + /^[A-Za-z_][A-Za-z0-9_]*:/ { inlegs = ($0 ~ /^legs:/); next } + !inlegs { next } + /^[ \t]*#/ { next } + /^[ \t]+repository:[ \t]*/ { + v = $0 + sub(/^[ \t]+repository:[ \t]*/, "", v) + sub(/[ \t]+$/, "", v) + gsub(/^"|"$/, "", v) + gsub(/^'"'"'|'"'"'$/, "", v) + if (v != "") print v + }' "$1" +} + +# ------------------------------------------- an assembly's legs, by path +# +# opensoft/openRepoTools#186, plan task T018 — WHERE A TRIAD'S LEGS ARE CHECKED +# OUT, for the lane tooling that has to look inside one: `lane-worktrees`' sweep, +# its daily report and its `add`, `lane-handoff`'s writer poll, and +# `lane-reconcile` below. A checkout IS AN ASSEMBLY when its own `project.yaml` +# declares a leg other than itself — the standard's own rule (openRepoShape's +# `templates/assembly-root/project.yaml`: a top-level `legs:` list of `- role:` / +# `repository:` / `path:`, the assembly's own leg at `path: "."`). A checkout +# with no such file, or one naming no leg but itself, is every single +# repository, and every reader asks it nothing more than it did before. +# +# THE READING IS `lane-start`'s RUNG 5, LINE FOR LINE, and never a second +# grammar: rung 5 resolves ONE leg's path for the home it is given, and this +# prints every leg the block declares, as ``. The seven +# lines that decide what a leg is are byte-identical to that reader's, and +# `tests/test_triad_lane_tooling.py` holds them so. As there, ONLY `repository:` +# and `path:` are read, and only as navigation: the manifest CONFERS NOTHING, +# and `role:` is never read. +project_leg_paths_file() { # + [ -f "$1" ] || return 1 + awk ' + /^[A-Za-z_][A-Za-z0-9_]*:/ { inlegs = ($0 ~ /^legs:/); repo = ""; path = ""; next } + !inlegs { next } + /^[ \t]*-[ \t]/ { repo = ""; path = "" } + /^[ \t]+repository:[ \t]*/ { v = $0; sub(/^[ \t]+repository:[ \t]*/, "", v) + sub(/[ \t]+$/, "", v); gsub(/^"|"$/, "", v); gsub(/^'"'"'|'"'"'$/, "", v); repo = v } + /^[ \t]+path:[ \t]*/ { v = $0; sub(/^[ \t]+path:[ \t]*/, "", v) + sub(/[ \t]+$/, "", v); gsub(/^"|"$/, "", v); gsub(/^'"'"'|'"'"'$/, "", v); path = v } + repo != "" && path != "" { print repo "\t" path; repo = ""; path = "" }' "$1" +} + +# THE LEGS OF ONE CHECKOUT, one a line: ``, the last being the declared path +# resolved against the checkout as rung 5 resolves it. The assembly's own `.` +# is left out: it IS the checkout. 0 with legs; 8 with none — no +# `project.yaml`, or one naming no leg but the checkout itself; 1 where the +# manifest is there and could not be read, which is never "no legs" (R22, +# Amendment 7(d)). +assembly_legs() { # + al_dir="${1-}"; al_dir="${al_dir%/}"; al_rows=""; al_out=""; al_tab="$(printf '\t')" + [ -n "$al_dir" ] || return 8 + al_m="$al_dir/project.yaml" + [ -e "$al_m" ] || [ -L "$al_m" ] || return 8 + { [ -f "$al_m" ] && [ -r "$al_m" ]; } || return 1 + al_rows="$(project_leg_paths_file "$al_m")" || return 1 + while IFS="$al_tab" read -r al_repo al_path; do + al_path="${al_path%/}" + case "$al_path" in + ''|.|./.) continue ;; + /*) al_abs="$al_path" ;; + ./*) al_abs="$al_dir/${al_path#./}" ;; + *) al_abs="$al_dir/$al_path" ;; + esac + al_out="$al_out$al_repo$al_tab$al_path$al_tab$al_abs +" + done </dev/null || :)" + printf '%s\n' "${cr_c:-$cr_v}" + done +} + +same_project() { + sp_home="$1"; sp_obj="$2"; sp_f=""; sp_legs="" + SAME_PROJECT_FILE="" + [ -n "$sp_home" ] && [ -n "$sp_obj" ] || return 1 + sp_c="$(alias_lookup "$sp_home" 2>/dev/null || :)"; sp_home="${sp_c:-$sp_home}" + sp_c="$(alias_lookup "$sp_obj" 2>/dev/null || :)"; sp_obj="${sp_c:-$sp_obj}" + [ "$sp_home" = "$sp_obj" ] && return 0 + for sp_f in ${LANES_LANE_DIR:+"$LANES_LANE_DIR/project.yaml"} \ + "$PROJECTS_ROOT"/*/project.yaml \ + "$PROJECTS_ROOT"/*/*/project.yaml; do + [ -f "$sp_f" ] || continue + sp_legs="$(project_legs_file "$sp_f" 2>/dev/null | canon_repo_list || :)" + [ -n "$sp_legs" ] || continue + printf '%s\n' "$sp_legs" | grep -qx -F -- "$sp_home" || continue + printf '%s\n' "$sp_legs" | grep -qx -F -- "$sp_obj" || continue + SAME_PROJECT_FILE="$sp_f" + return 0 + done + return 1 +} + +# Decision 2, ratified by Brett Heap 2026-09-11 ("yes just warn"): a crossing +# WARNS and proceeds. It never refuses — the estate crosses routinely +# (opsXfactory-3 landed 32 distinct PRs into opensoft/Omnigent-Install, every +# one of them foreign to its home), and a refusal here would be a new gate +# nobody asked for. +cross_repo_warn() { + cw_obj_repo="$1"; cw_home="$2"; cw_me="$3"; cw_found=0; cw_lane=""; cw_h=""; cw_id="" + [ -n "$cw_obj_repo" ] || return 0 + if [ -z "$cw_home" ]; then + note "NOTE: lane $cw_me has no home repo on record, so the cross-repo check did not run (pre-cutover lane: pass --home owner/repo)" + return 0 + fi + [ "$cw_obj_repo" = "$cw_home" ] && return 0 + if same_project "$cw_home" "$cw_obj_repo"; then + note "$cw_obj_repo and $cw_home are legs of one project.yaml — not a crossing (${SAME_PROJECT_FILE:-?})" + return 0 + fi + note "WARNING: CROSS-REPO — $cw_obj_repo is not lane $cw_me's home ($cw_home). Proceeding: Amendment 7 warns here, it never refuses." + while IFS= read -r cw_lane; do + [ -n "$cw_lane" ] || continue + [ "$cw_lane" = "$cw_me" ] && continue + # Both sides through the alias table (R20): home_of_lane resolves its + # answer, and the object's repository arrived canonical from canon_object, + # so this comparison is between two canonical spellings. It is still made + # case-insensitively, because the register spells one repository three ways + # in a week and only the TABLE's lookup is case-blind, not its output. + cw_h="$(home_of_lane "$cw_lane" 2>/dev/null || :)" + [ "$(lc "$cw_h")" = "$(lc "$cw_obj_repo")" ] || continue + cw_id="$(last_session_id_of_lane "$cw_lane" 2>/dev/null || :)" + if lane_is_elsewhere "$cw_lane"; then + note " lane homed on $cw_obj_repo, on another workstation ($(lane_workstation "$cw_lane")): @$cw_lane — last transcript uuid ${cw_id:-unknown}" + cw_found=1 + elif live_holder "$cw_lane" >/dev/null 2>&1; then + note " LIVE lane homed on $cw_obj_repo: @$cw_lane — last transcript uuid ${cw_id:-unknown} — claude --resume ${cw_id:-}" + cw_found=1 + fi + done < +# Appends to the lane's log and commits — and for a LANDING or a LANDED +# appends Rule 6's line to LANES.md in the SAME commit, two pathspecs, so the +# register and the log can never disagree about a merge hold. +write_event() { + we_lane="$1"; we_verb="$2"; we_obj="$3"; we_ref="$4"; we_pay="$5"; we_txt="$6"; we_utc="$7"; we_uuid="$8" + # R-A11 (e) — THE `session` FIELD IS A TRANSCRIPT UUID AND ONLY THAT, AND THE + # WRITER ITSELF IS WHERE THAT IS ENFORCED. Amendment 7(b) says so of the + # grammar; nothing checked it, and the literal `unknown` is in the append-only + # log four times already, in two lanes — three from `log PAUSED` (a swap skill + # holding the uuid and not passing it) and one from `release`. The log is + # append-only, so a line written wrong there is wrong for ever and no later + # line can correct it. Refused HERE rather than in the `log` arm because the + # same field is written by `claim` and `release` too, and one of the four came + # from `release`: this is the writer, so this is the gate. + # + # It is the FIRST test in the function, before the lock, before the capture + # and before the log file is created, so a refusal leaves the checkout exactly + # as it found it — and it names the act that supplies the uuid rather than the + # rule it broke, because the caller's next move is that act. + # + # This composes with `R-A8-2` rather than repeating it: `R-A8-2` stopped + # `lane-start` WRITING `unknown` (its title-fallback path defers the line + # instead); this stops the writer ACCEPTING it, from any caller. + if ! valid_uuid "$we_uuid"; then + we_bad="${we_uuid:-}" + case "$we_uuid" in + unknown) we_why="'unknown' is the one value this field must never carry: it is in this append-only log four times already, and no later line can correct any of them" ;; + session_*) we_why="'$we_bad' is a PR-footer id, which is neither resumable nor liveness-checkable (Amendment 6(b))" ;; + *) we_why="'$we_bad' is not a transcript uuid" ;; + esac + die "an event's session field is the TRANSCRIPT UUID and only that (Amendment 7(b)): $we_why. Nothing was written — not the $we_verb line, not the log file, not a commit. Name the session taking the act: LANES_SESSION=\"\$CLAUDE_CODE_SESSION_ID\" LANES_LANE=$we_lane lanes-edit.sh … If lane $we_lane has no transcript uuid recorded at all, the act that gives it one is Amendment 6(c)'s session-cell append: run 'lane-start --no-launch ' in the lane's own window first" 2 + fi + # THE WRITER REFUSES A FIELD THAT WOULD MAKE THE LINE UNREADABLE (R21). + # ` — ` divides a line into its three parts, and the grammar guarantees it + # occurs AT MOST TWICE — once after the verb, once before the free text — so + # that one parser reads every line. A payload or a free text carrying a third + # one breaks that guarantee in a file nothing ever rewrites; so does a + # newline, which `append_text_line` would notice only AFTER writing it. Both + # are refused here, before the lock and before anything is created, rather + # than hoped against. + case "$we_pay$we_txt" in + *" — "*) die "an event's payload and free text may not contain ' — ': that separator is what divides a line's verb from its fields and its fields from its free text, and a third one leaves the line ambiguous to its own parser. Use a semicolon or a colon instead: '$we_pay$we_txt'" 2 ;; + esac + if [ "${we_pay//[$'\n\r']/}" != "$we_pay" ] || [ "${we_txt//[$'\n\r']/}" != "$we_txt" ]; then + die "an event's payload and free text are ONE line: a newline in either would append several lines to an append-only log, and the proof that only one was added would fail after the write, not before it" 2 + fi + # AND A `, ` IN THE PAYLOAD, WHICH IS CLAUSE (c)'S OTHER SEPARATOR AND WAS IN + # NO WRITER AT ALL. ` — ` divides the verb from the fields and the fields from + # the free text; `, ` divides THE FIELDS FROM EACH OTHER — `lane , session + # @, , ` — and the payload is the tail of that fourth + # field, so a `, ` inside it reads back as a fifth field and a sixth that no + # reader knows. `lane-start` fences its `dir`, `window` and `profile` values + # one at a time (`:689-692`, `:728-731`, `:1574-1578`) and the `/lane-swap` + # skill now fences the same two; this is the backstop under all of them, in the + # writer, for the reason this file gives for putting the container guard at the + # dispatcher: *"nine copies of one rule is how eight of them would come to + # disagree"*. + # + # THE PAYLOAD AND NOT THE FREE TEXT. The free text is everything after the + # SECOND ` — `, where a parser has already finished splitting fields, so a + # comma there is ordinary prose and the estate's log is full of it. Refusing it + # would refuse lines this estate legitimately writes. + # + # AND NOT THE `"` EITHER, WHICH IS WHY THIS GUARD IS NARROWER THAN THE ONES + # ABOVE IT. Clause (c)'s own rule for a path containing a space is to WRITE IT + # QUOTED — `dir "/checkouts/b/my projects/x"`, which is what makes it one ref + # under 7(b)'s own grammar. (The amendment spells that example under a home + # directory; it is spelled with a neutral root here because + # `test_no_committed_file_names_a_host_absolute_path` refuses a `/home//` + # path in any tracked file, and a rule that holds for a real path holds for an + # example of one.) One ref under + # 7(b) — so `quote_subfield` puts a `"` into the payload deliberately and a `"` + # refusal here would refuse the very shape the clause mandates. The `"` belongs + # in the per-VALUE fences, where it is, and not in the whole-payload one. + # + # MEASURED BEFORE IT WAS WRITTEN, against every line this estate has: 111 + # payloads in `opensoft/brett-wip`'s 15 lane logs carry `, ` 0 times and `"` 0 + # times, while 76 carry `; ` — the sub-field separator, which this guard must + # therefore never touch. + case "$we_pay" in + *", "*) die "an event's payload may not contain ', ': that separator is what divides an event line's four fields from each other — 'lane , session @, , ' — and the payload is the tail of the fourth, so a ', ' inside it reads back as fields the log's own parser cannot account for. The log is append-only and no later line can correct it. Use a semicolon, which is the sub-field separator: '$we_pay'" 2 ;; + esac + # AND IT REFUSES A FREE TEXT THAT BEGINS WITH AN ARROW (R26, Addendum 6). + # `→` and `←` introduce the PAYLOAD, and the payload is its own argument. + # Quoted into the free-text slot — `log LANDED "→ "`, the shape a + # reader reaches for because that is how the finished line looks — it is + # written AFTER the ` — `, where the parser reads it as prose: the event + # carries no payload, `rule6_line` renders the register's Rule 6 line without + # `→ `, and the merge sha is lost in two files that are never rewritten. + # Nothing legitimate starts a sentence with an arrow, so the trap is closed + # here rather than left to be noticed afterwards. + case "$we_txt" in + '→'*|'←'*) + we_hint="LANES_LANE=$we_lane lanes-edit.sh log $we_verb $we_obj → " + case "$we_verb" in + RELEASED) we_hint="LANES_LANE=$we_lane lanes-edit.sh release $we_obj \"\" — a release takes a reason, not a payload" ;; + CLAIMED|TAKEOVER|CLAIM-LOST) we_hint="LANES_LANE=$we_lane lanes-edit.sh claim $we_obj" ;; + esac + die "an event's free text may not begin with '→' or '←': those arrows introduce the PAYLOAD, which is its own argument and comes BEFORE the free text. Quoted into the text slot it is written after the ' — ', where no reader and no parser looks for it — a LANDED that way loses its merge sha from both the log and the register's Rule 6 line, in two files nothing rewrites. Write it positionally, e.g. 'lanes-edit.sh log LANDED → '; for this call: $we_hint" 2 ;; + esac + # AMENDMENT 17(b) — the two sub-fields, checked in the writer for the same + # reason the session field is: from any caller, before the lock, before the + # log file is created, and on a log no later line can correct. + pause_subfields_check "$we_pay" + # AMENDMENT 18(a) — the binding's three sub-fields, checked where a caller + # wrote them and APPENDED where it did not, for the three verbs clause (a) + # names. The append is the LAST thing done to the payload, after every + # separator guard above has passed on what the caller gave: the writer's own + # values are fenced by `lanes_binding_value_ok` before they go in, so the + # guards cannot be re-run on them and do not need to be. + binding_subfields_check "$we_pay" + case "$we_verb" in + STARTED|RESUMED|PAUSED) + we_pay="$(binding_subfields_add "$we_pay")" + # A PAYLOAD THIS APPEND CREATED GETS THE ARROW THAT INTRODUCES ONE. A + # lane-kind line written with no payload at all — `log STARTED lane:X`, + # which this estate's older lines and several of its callers spell — now + # has one, and Amendment 7(b) introduces a payload with `→`. Without it + # the line would carry its sub-fields bare after the object: readable by + # `LOG_AWK`, which takes an unarrowed tail as the payload, and unlike + # every other lane-kind line in the estate. + [ -n "$we_ref" ] || [ -z "$we_pay" ] || we_ref='→' ;; + esac + we_line="$(event_line "$we_verb" "$we_lane" "$we_uuid" "$we_utc" "$we_obj" "$we_ref" "$we_pay" "$we_txt")" + we_paths=("$(log_path_for "$we_lane")") + we_r6="" + case "$we_verb" in + LANDING|LANDED) we_r6="$(rule6_line "$we_verb" "$we_lane" "$we_uuid" "$we_utc" "$we_obj" "$we_pay" 2>/dev/null || :)" ;; + esac + [ -n "$we_r6" ] && we_paths+=("$LANES_PATH") + # THE EXEMPTION IS THE PATH THE LOG IS ACTUALLY AT, WHICH NEED NOT BE THE + # CANONICAL ONE YET (Amendment 15; Copilot round 4 on openRepoTools#41). + # `$we_lane` is the ROW's spelling by the time it reaches here, while the file + # may still carry the spelling it was written under until THIS write renames + # it — so a lane with uncommitted lines in its own old-cased log met the test + # that exists to refuse somebody ELSE's uncommitted work, and could not write + # at all. Only the two exemptions take it: `we_paths` is what the capture and + # the commit are given and stays exactly what it was, with the old path joining + # it below as `LOG_RENAMED_FROM` once the rename has actually happened. + we_lp="$(log_path_ci "$we_lane")" || die "lane $we_lane's object log is published twice (above), and one lane is ONE lane under any case: its log is ONE file (Amendment 15). Merge them by hand (Amendment 15(d)) and re-run. Nothing was written." 2 + # R11 — the register is EXEMPT from this first test, because it is captured + # below rather than refused. Everything ELSE this checkout has dirty is + # refused HERE: before the lock, before the capture and before anything is + # created, so that a refusal leaves the checkout exactly as it found it. + refuse_dirty_checkout "write $we_verb" "${we_paths[@]}" "$we_lp" "$LANES_PATH" + # THE LIFECYCLE SNAPSHOT AS IT STANDS BEFORE THIS LINE EXISTS (openRepoTools#91, + # Copilot round 5 on #97). It is read HERE — before the lock, before the append + # and before the commit — because it is the pre-image the follow-up at the foot + # of this function compares against: a `RUNNING` written out of an event that + # landed an hour ago must not overwrite a `SWAPPING` that began since, and the + # only evidence of which came first is what the snapshot said when this write + # started. Only the four verbs that move the lifecycle pay for the read. + we_pre=""; we_seam="" + # THE SEAM, BEFORE THE LOCK AND BEFORE A BYTE (ruling 2026-10-04): EVERY + # lane-kind line — the four that move a lifecycle, a swap's `PAUSED`, and + # Amendment 18(g)'s `HANDOFF-REQUESTED` (Copilot round 3 on #97) — is a legacy + # act on the lane itself, and a managed-owned lane, or one whose ownership + # could not be read, refuses it here. Object-kind lines (a claim, a release) + # are about the object a lane holds and are not the lane's ownership. + is_lane_verb "$we_verb" && managed_seam_refuse "$we_lane" "a $we_verb line in its object log" + case "$we_verb" in + STARTED|RESUMED|ENDED|RETIRED) + # Past the seam the lane is legacy, and that verdict is what the lifecycle + # follow-up at this function's foot is handed. `PAUSED` and + # `HANDOFF-REQUESTED` move no lifecycle and are handed nothing. + we_seam=8 + we_pre="$(lane_state_preimage "$we_lane" "$we_pay")" ;; + esac + acquire_lock + capture_register_edit "${we_paths[@]}" + handle_preexisting "${we_paths[@]}" + # AMENDMENT 15 — `ensure_log` IS BELOW THE CAPTURE AND NOT ABOVE IT, and the + # order is load-bearing rather than tidy. It may now RENAME the lane's log to + # the row's own spelling, and the amendment says that rename lands "in that + # same commit" as the write — while `handle_preexisting` exists to commit + # whatever it finds dirty in this write's pathspecs FIRST, as somebody else's + # content. Run above it, the rename was exactly what that capture would + # commit: the one act of this write, taken out of it and attributed to a peer. + # Below it, the checkout is clean when the rename happens and the rename is + # this write's own. The old path joins the pathspecs so the deletion is + # committed beside the append. + ensure_log "$we_lane" + [ -n "$LOG_RENAMED_FROM" ] && we_paths+=("$LOG_RENAMED_FROM") + # THEN re-test, against the checkout the capture left behind. The capture is + # not assumed to have worked — handle_preexisting swallows a failed commit by + # design, it never fails the call — and a register still dirty at this point + # would send commit_push down Amendment 5(d)'s skip-the-pull branch, which is + # the branch that disables the rescan deciding a race. + refuse_dirty_checkout "write $we_verb" "${we_paths[@]}" "$we_lp" + append_text_line "$we_line" "$(log_file_for "$we_lane")" + if [ -n "$we_r6" ]; then + append_text_line "$we_r6" "$LANES_FILE" + note "Rule 6 line also appended to $LANES_FILE (one commit, ${#we_paths[@]} pathspecs)" + fi + we_msg="LOG($we_lane@$WS): $we_verb $we_obj" + [ -n "$PRE_DIRTY_LANES" ] && we_msg="$we_msg + sweeps uncommitted edit to row $PRE_DIRTY_LANES" + commit_push "$we_msg" "${we_paths[@]}" + we_rc=$? + state_events_flush + release_lock + # THE LIFECYCLE SNAPSHOT FOLLOWS THE LINE THAT WAS WRITTEN (openRepoTools#91), + # and it is here — in the writer, after the lock — for the reason + # `pause_subfields_check` is here: from ANY caller, over one implementation, + # rather than in each of the commands that write a lane-kind line. A + # `STARTED` or a `RESUMED` is the confirming act of a new owner and takes the + # lane to `RUNNING`; an `ENDED` or a `RETIRED` takes it to `CLOSED`; a + # `PAUSED` moves nothing, because the two-phase transition around it is + # `lane-handoff`'s and lands `SWAPPED` only once every mandatory write has. + # AFTER `release_lock`, because `acquire_lock` is a `mkdir` mutex and not a + # reentrant one — and the follow-up takes that same mutex for itself, around + # the read of the pre-image and the replacement of the snapshot together. It + # never fails the event and it is silent for a lane with no control root, which + # is every lane that has not started under Amendment 11(c) — the cutover rule + # of Amendment 7(i), not a failure. + lane_state_follow "$we_lane" "$we_verb" "$we_pay" "$we_uuid" "$we_pre" "$we_seam" + return "$we_rc" +} + +# A read fetches first — there is no index, so "current" means "after a fetch". +# +# AND WHERE IT DID NOT FETCH IT RECORDS WHY, so the one caller with a freshness +# line can correct it (#26, the fail-closed family one layer out, `lanes:411`). +# FOUR of the five ways out of here never reach the fetch at all — +# `LANES_NO_GIT=1`, `LANES_NO_FETCH=1`, a `$LANES_REPO` that is not a checkout, +# and an `origin/$LANES_BRANCH` `ls-remote` could not confirm, THE TIMEOUT AMONG +# THEM — and every one of them answered 0 in silence. `lanes --fetch` reads this +# file's stderr for one phrase and prints *"as of a fetch just now"* when it does +# not find it, so all four printed that sentence over a fetch that never ran. +# `43b6320` closed the LOUD path, where the fetch was attempted and failed; this +# is the quiet one. +# +# IT IS RECORDED HERE AND SAID IN THE `lanes` ARM, not printed here, because +# EVERY subcommand in this file runs this function and only the one with a +# `--fetch` flag has a freshness line to be wrong. A note on every path would put +# a paragraph in front of every launch on the workstation to fix a sentence that +# is printed in one place. +LOG_SYNC_FETCH="" # yes · fell-back · else WHY this run did not fetch +log_sync() { + # THE CACHE ABOVE IS THE REF AS IT STOOD; a fetch moves the ref, so it is + # dropped here rather than read past. Both copies of it: the variable this + # shell holds and the file every subshell reads (ruling 12). + LANES_REGISTER_CACHE="" + ls_rc="${SE_CACHE_FILE:+$SE_CACHE_FILE.register}"; [ -n "$ls_rc" ] && rm -f -- "$ls_rc" + # AND AMENDMENT 16's ALIAS TABLE, for the same reason and in the same breath: + # it is read from `origin/` beside the register and a fetch moves that + # ref. A rename lands both files in ONE commit, so a cache that kept one and + # dropped the other is exactly the disagreement the single commit prevents. + lane_alias_flush + LOG_SYNC_FETCH="" + [ "$NO_GIT" = 1 ] && { LOG_SYNC_FETCH="LANES_NO_GIT=1 is set, so nothing in this run touches git"; return 0; } + [ "${LANES_NO_FETCH:-0}" = 1 ] && { LOG_SYNC_FETCH="LANES_NO_FETCH=1 is set in this environment"; note "LANES_NO_FETCH=1 — not fetching; reading origin/$LANES_BRANCH as the ref already stands here"; return 0; } + git -C "$LANES_REPO" rev-parse --git-dir >/dev/null 2>&1 || { LOG_SYNC_FETCH="$LANES_REPO is not a git checkout"; return 0; } + if ! remote_has_branch; then + LOG_SYNC_FETCH="origin/$LANES_BRANCH could not be reached" + [ "$GIT_TIMED_OUT" = 1 ] && LOG_SYNC_FETCH="$LOG_SYNC_FETCH — ls-remote timed out after ${GIT_TIMEOUT}s" + return 0 + fi + if git_net -C "$LANES_REPO" fetch -q origin "$LANES_BRANCH" 2>/dev/null; then + LOG_SYNC_FETCH=yes + else + LOG_SYNC_FETCH=fell-back + note "fetch $([ "$GIT_TIMED_OUT" = 1 ] && printf 'timed out after %ss' "$GIT_TIMEOUT" || printf 'failed') — reading the logs as they stand locally" + fi + return 0 +} + +# ------------------------------------------------------------------- who +# +# Exit 0 found, 8 no record. + +print_holder_detail() { + ph_lane="$1"; ph_obj="$2"; ph_rc=0 + ph_home="$(home_of_lane "$ph_lane" 2>/dev/null || :)" + printf ' home %s\n' "${ph_home:-unknown (pre-cutover lane: no STARTED line)}" + ph_rowid="$(last_session_id_of_lane "$ph_lane" 2>/dev/null || :)" + if lane_is_elsewhere "$ph_lane"; then + # Session records are local files. This machine cannot see another + # workstation's, so it must not say NOT LIVE about one. + printf ' holder lane %s — UNKNOWN (records are local to %s; ask @%s or read its handoff)\n' \ + "$ph_lane" "$(lane_workstation "$ph_lane")" "$ph_lane" + else + # 0 / 8 / anything else, and never two of them conflated (R22): a read this + # workstation could not perform is UNKNOWN, exactly as another workstation's + # records are. NOT LIVE is a claim, and it is the claim that sends a reader + # to `claim --force` against a lane that is running. + ph_h="$(live_holder "$ph_lane" 2>/dev/null)"; ph_rc=$? + case "$ph_rc" in + 0) + IFS="$US" read -r ph_hid ph_target ph_hname ph_hpid ph_where <`, printed with the session and profile beside it so a person can + # check first, and run by that person (clause (f)). + # + # Silent where there are none, where the lane is on another workstation (its + # records are not local and this machine must not claim about them), and where + # the read itself failed — an unreadable record is not an assertion that a + # holder is absent, and `who`'s own `UNKNOWN` line has already said so. + if ! lane_is_elsewhere "$ph_lane"; then + ph_idle="$(idle_holders "$ph_lane" 2>/dev/null)" + # NOT a pipe: `printf ... | while read; do …; done` runs the loop on the + # STRIPPED command substitution with no trailing newline, so `read` hits + # EOF on the (only) line before it ever completes one, returns failure, + # and the loop body never runs at all — the one-holder case is exactly + # the common case, and a pipe here would print nothing, ever. A here-string + # always terminates the last line, which is why `lane-start`'s own reader + # of this same helper (above) uses one instead of a pipe. + if [ -n "$ph_idle" ]; then + while IFS="$(printf '\t')" read -r ph_isid ph_ipid ph_ikind ph_iprof; do + [ -n "$ph_isid" ] || continue + printf ' idle lane %s — an EARLIER session id of this row is still held: session %s, pid %s (kind %s, profile %s). History, not an alternative — retire it: kill %s\n' \ + "$ph_lane" "$ph_isid" "$ph_ipid" "${ph_ikind:-none}" "${ph_iprof:-unknown}" "$ph_ipid" + done <<<"$ph_idle" + fi + fi + printf ' address @%s · claude --resume %s\n' "$ph_lane" "${ph_rowid:-}" + ph_ho="$(handoff_of_lane "$ph_lane" 2>/dev/null || :)" + [ -n "$ph_ho" ] && printf ' handoff %s\n' "$ph_ho" + printf ' log %s\n' "$(log_path_for "$ph_lane")" + ph_objrepo="$(object_repo "$ph_obj")" + if [ -n "$ph_home" ] && [ -n "$ph_objrepo" ] && [ "$ph_objrepo" != "$ph_home" ] && ! same_project "$ph_home" "$ph_objrepo"; then + printf ' CROSS-REPO %s is not lane %s'"'"'s home (%s)\n' "$ph_objrepo" "$ph_lane" "$ph_home" + fi +} + +who_object() { + wo_obj="$1" + wo_states="$(state_events | lane_states_on "$wo_obj")" + if [ -z "$wo_states" ]; then + printf 'no record of %s in any lane log\n' "$wo_obj" + printf ' (a lane with no log file is pre-cutover: see its row'"'"'s state cell in LANES.md)\n' + return 8 + fi + printf 'object %s\n' "$wo_obj" + wo_held=0 + while IFS="$US" read -r s_utc s_lane s_verb s_uuid s_ws s_o s_ref s_pay s_txt s_file s_line; do + [ -n "${s_verb:-}" ] || continue + wo_sup="$(superseded_by "$wo_obj" "$s_lane" "$s_verb")" + if [ -n "$wo_sup" ]; then + printf 'super. lane %-22s %-9s %s (%s ago) — superseded by TAKEOVER (lane:%s) at %s\n' \ + "$s_lane" "$s_verb" "$s_utc" "$(age_of "$s_utc")" "${wo_sup%@*}" "${wo_sup#*@}" + printf ' this lane no longer holds it; it closes its own line with: lanes-edit.sh release %s "taken over by %s"\n' "$wo_obj" "${wo_sup%@*}" + elif is_open_verb "$s_verb"; then + printf 'HOLDS lane %-22s %-9s %s (%s ago)%s\n' "$s_lane" "$s_verb" "$s_utc" "$(age_of "$s_utc")" "${s_pay:+ ${s_ref:-} $s_pay}" + wo_held=1 + else + printf 'closed lane %-22s %-9s %s (%s ago)%s\n' "$s_lane" "$s_verb" "$s_utc" "$(age_of "$s_utc")" "${s_pay:+ ${s_ref:-} $s_pay}" + fi + # A line written with --no-github is not yet a Rule 1 claim: the comment a + # person outside this estate reads does not exist. + case "${s_txt:-}" in + no-github|'no-github;'*) printf ' local only — no GitHub claim comment\n' ;; + "") : ;; + *) printf ' %s\n' "$s_txt" ;; + esac + done </dev/null)" || wl_fkrc=$? + case "$wl_fkrc" in + 0 | 8) : ;; + *) printf 'UNKNOWN this workstation'"'"'s session records could not be read, so whether a live FORK of lane %s'"'"'s transcript is running is NOT established — which is not the same as none. See: lanes-edit.sh forks %s\n' "$wl_lane" "$wl_lane" ;; + esac + if [ -n "$wl_fk" ]; then + while IFS="$(printf '\t')" read -r wl_fid wl_fpid wl_fkind wl_fcwd; do + [ -n "${wl_fid:-}" ] || continue + printf 'DEFECT %s is a live FORK of this lane'"'"'s transcript (pid %s, %s, cwd %s) — never a holder, and it must not write the register. Retire it: lane-end %s --retire %s\n' \ + "$wl_fid" "$wl_fpid" "${wl_fkind:-interactive}" "${wl_fcwd:-unknown}" "$wl_lane" "$wl_fpid" + done < main` clause +# at all — 284 of 308 on the day this was measured — so keying a LANDED on the +# repository it names keyed 284 of them on the empty string, where they could +# never close the repository-qualified LANDING they belonged to: `who --landing` +# reported 201 phantom merge holds across five repositories, every one of them +# landed long ago, on a register whose genuinely open count was one. So the +# PAIRING is by (lane, PR) — the LANDED closes the most recent LANDING of that +# lane and PR that is still unmatched, and the pair’s repository is the +# LANDING’s — while the RESULT still keys on (lane, repository, PR), which is +# what keeps a LANDED on one repository from closing a LANDING on another. +# AND A LANDED THAT NAMES A REPOSITORY PREFERS A LANDING ON THAT REPOSITORY +# (R24, Addendum 6). Only a LANDED with NO `into main` clause takes the +# most recent unmatched LANDING regardless — it has said nothing about where it +# landed, so the LANDING is the only thing that can say. One that DOES name a +# repository takes the most recent unmatched LANDING naming the same one, and +# is reported as an `unpaired LANDED` — closing nothing — only when there is no +# such LANDING at all. Without the preference, a lane with two LANDINGs open on +# ONE PR number in two repositories that lands the EARLIER one, naming its +# repository, was unpaired and both holds stayed open until the second landed. +# The answer is identical everywhere else, including the (lane, repository, PR) +# result key: a LANDED on one repository still closes no LANDING on another. +# +# The repository is lower-cased IN THE KEY ONLY: the register spells one +# repository four ways in a week, and a LANDED spelled `OpsxFactory` must still +# close a LANDING spelled `opsXfactory`. +# +# AND BOTH SIDES GO THROUGH `lanes/repos.tsv` FIRST (R29, Addendum 7). Case is +# only half of it: the register writes `OpsxFactory` and `opensoft/OpsxFactory` +# for ONE repository — 23 Rule 6 lines against 70 at `8f9c04d` — and +# `codexFactory`, `codeXfactory/codexFactory` and `opensoft/codexFactory` for +# another. Compared literally, a LANDED spelled one way does not close the +# LANDING spelled the other: it reads as an `unpaired LANDED`, the hold stays +# open, and over-reporting a merge hold is the direction that stalls other +# lanes' merges. So every `into main` is resolved AS IT IS PARSED, which +# makes the pairing, R24's preference and the (lane, repository, PR) result key +# agree by construction — the key's repository is the canonical spelling, and +# an alias the table does not know keeps its own, case-blind like every other. +# +# WHAT THAT IS WORTH TODAY, measured read-only over `origin/main` at `6fa966b`: +# the VERDICT does not move — 1 open LANDING (lane browser-ui-repair's PR #401, +# genuinely in flight) and 0 unpaired LANDED, before this change and after it. +# No (lane, PR) pair in the register mixes its spellings YET, so this is a +# guard and not a repair, and it is worth saying so rather than claiming a hold +# it did not clear. What it does move there is the KEY: 17 result-key spellings +# collapse to the 11 repositories they name, and two LANDINGs a retry spelled +# two ways are one hold instead of two. +# +# The table is handed in through the ENVIRONMENT, as `LANES_RULE6_ALIASES`, +# one `\037` per line — because awk cannot read +# `repos.tsv` for itself here (this program's stdin is the register) and +# because `awk -v`, which is where it used to go, carries ONE LINE: see +# `who_landing` for what a many-line `-v` does on macOS's awk. +# +# BOTH LAYERS, SHIPPED FIRST (Amendment 9(b)). This is the second reader of the +# table — `alias_lookup` is the other — and it layers them the same way by +# reading the shipped file before the override, so the LAST assignment to an +# alias wins and an override row REPLACES the shipped row for that alias while +# adding rows the shipped table does not carry. One map, emitted in the order +# the aliases were first seen, so the output is stable. +rule6_aliases() { + r6_files=() + for r6_tsv in "${LANES_REPOS_TSV_SHIPPED:-}" "${LANES_REPOS_TSV:-}"; do + [ -n "$r6_tsv" ] && [ -f "$r6_tsv" ] || continue + r6_files+=("$r6_tsv") + done + [ "${#r6_files[@]}" -gt 0 ] || return 0 + awk -F'\t' ' + /^[ \t]*#/ { next } + NF >= 2 { + a = $1; b = $2 + gsub(/^[ \t]+|[ \t]+$/, "", a); gsub(/^[ \t]+|[ \t]+$/, "", b) + if (a != "" && b != "") { + k = tolower(a) + if (!(k in seen)) { seen[k] = 1; ord[++n] = k } + m[k] = b + } + } + END { for (i = 1; i <= n; i++) printf "%s\037%s\n", ord[i], m[ord[i]] }' "${r6_files[@]}" +} + +RULE6_AWK=' +function trim(s) { sub(/^[ \t]+/, "", s); sub(/[ \t]+$/, "", s); return s } +function canon(r, l) { l = tolower(r); return (l in A) ? A[l] : r } +BEGIN { + na = split(ENVIRON["LANES_RULE6_ALIASES"], ar, "\n") + for (ai = 1; ai <= na; ai++) { ap = index(ar[ai], "\037") + if (ap > 1) A[substr(ar[ai], 1, ap - 1)] = substr(ar[ai], ap + 1) } +} +/^(LANDING|LANDED) — / { + line = $0 + verb = substr(line, 1, index(line, " ") - 1) + lane = ""; pr = ""; repo = ""; utc = "" + if (match(line, /lane [A-Za-z0-9._-]+/)) lane = substr(line, RSTART + 5, RLENGTH - 5) + if (match(line, /PR #[0-9]+/)) pr = substr(line, RSTART + 4, RLENGTH - 4) + if (match(line, /into [A-Za-z0-9\/._-]+ main/)) repo = canon(substr(line, RSTART + 5, RLENGTH - 10)) + if (match(line, /[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9](:[0-9][0-9])?Z/)) utc = substr(line, RSTART, RLENGTH) + if (lane == "" || pr == "") next + g = lane "\037" pr + if (verb == "LANDING") { + k = g "\037" tolower(repo) + if (!(k in ST)) { gk[g, ++gn[g]] = k } + ST[k] = "LANDING"; U[k] = utc; L[k] = lane; P[k] = pr; R[k] = repo; O[k] = NR + next + } + best = ""; bord = -1; bestr = ""; bordr = -1 + for (i = 1; i <= gn[g]; i++) { kk = gk[g, i] + if (ST[kk] != "LANDING") continue + if (O[kk] > bord) { bord = O[kk]; best = kk } + if (repo != "" && tolower(repo) == tolower(R[kk]) && O[kk] > bordr) { bordr = O[kk]; bestr = kk } } + if (bestr != "") best = bestr # R24: a LANDED that NAMES a repository + if (best == "") next + if (repo != "" && tolower(repo) != tolower(R[best])) { + printf "UNPAIRED%c%s%c%s%c%s%c%s%c%s\n", 31, lane, 31, pr, 31, utc, 31, repo, 31, R[best] + next + } + ST[best] = "LANDED"; U[best] = utc; O[best] = NR +} +END { for (k in ST) printf "%s%c%s%c%s%c%s%c%s%c\n", ST[k], 31, L[k], 31, P[k], 31, U[k], 31, R[k], 31 }' + +# Rule 6's window, in minutes. A LANDING past it with no LANDED is still a +# line somebody wrote and is still listed — but it is marked, because reporting +# a 253-day-old LANDING as a live merge hold with nothing to say it is not one +# is how the estate ends up holding its merges for a lane that stopped. +LANDING_MINUTES="${LANES_LANDING_MINUTES:-30}" + +# The lane logs are SECONDARY here and are reported after the register: every +# lane writes its Rule 6 line into LANES.md, pre- and post-cutover alike, and +# that is what decides the hold. A lane's own LANDING/LANDED is evidence +# beside it, never instead of it. +who_landing_logs() { + wll_repo="$1"; wll_rows="" + wll_rows="$(state_events | awk -v sep="$US" -v repo="$wll_repo" ' + function pos(pf, pn) { return pf "\034" sprintf("%09d", pn) } + BEGIN { FS = sep } + $6 ~ /^lane:/ { next } + { + o = $6; r = o; sub(/#.*$/, "", r); sub(/:openspec\/changes\/.*$/, "", r) + if (tolower(r) != tolower(repo)) next + # The LAST line this lane wrote on the object, in FILE ORDER (R14). + # A LANDED is often written in the same second as the LANDING it closes, + # and on a workstation whose clock steps back it is stamped before it. + k = $2 sep o + p = pos($10, $11) + if (!(k in P) || p >= P[k]) { P[k] = p; u[k] = $1; V[k] = $3; L[k] = $2; O[k] = o } + } + END { for (k in P) if (V[k] == "LANDING" || V[k] == "LANDED") + printf "%s%c%s%c%s%c%s\n", V[k], 31, L[k], 31, O[k], 31, u[k] }' \ + | LC_ALL=C sort -t"$US" -k3,3 -k2,2)" + [ -n "$wll_rows" ] || return 0 + printf 'from lane logs (secondary):\n' + while IFS="$US" read -r wl_verb wl_lane wl_obj wl_utc; do + [ -n "${wl_verb:-}" ] || continue + printf ' %-8s %s lane %s, %s (%s ago)\n' "$wl_verb" "$wl_obj" "$wl_lane" "$wl_utc" "$(age_of "$wl_utc")" + done </dev/null || :)"; wd_c="${wd_c:-$wd_r}" + [ "$(lc "$wd_c")" = "$(lc "$wd_repo")" ] || continue + wd_stale="" + older_than_minutes "$wd_utc" "$LANDING_MINUTES" && wd_stale=" STALE (Rule 6: >${LANDING_MINUTES} min)" + printf 'LANDING %s#%s lane %s, %s (%s ago)%s\n' "$wd_repo" "$wd_pr" "$wd_lane" "$wd_utc" "$(age_of "$wd_utc")" "$wd_stale" + wd_n=$((wd_n + 1)) + done <` must read it as one. 8 is reserved for absence. + [ "$wd_n" = 0 ] && printf 'none open — no LANDING on %s is still open (read from LANES.md'"'"'s Rule 6 lines)\n' "$wd_repo" + # A LANDED that names THIS repository while the LANDING it would close is on + # another closes nothing (R17), and is said so rather than dropped: an + # append-only register is never rewritten, so a line no tool mentions again is + # a line nobody will ever reconcile. + while IFS="$US" read -r wd_verb wd_lane wd_pr wd_utc wd_r wd_other; do + [ "${wd_verb:-}" = UNPAIRED ] || continue + wd_c="$(alias_lookup "${wd_r:-}" 2>/dev/null || :)"; wd_c="${wd_c:-$wd_r}" + [ "$(lc "$wd_c")" = "$(lc "$wd_repo")" ] || continue + printf 'unpaired LANDED %s#%s lane %s, %s — the open LANDING for (lane %s, PR #%s) is on %s, so this closes nothing\n' \ + "$wd_repo" "$wd_pr" "$wd_lane" "$wd_utc" "$wd_lane" "$wd_pr" "${wd_other:-an unnamed repository}" + done <:; workstation `, and a lane is +# SWAPPED on a workstation when that PAUSED is its LAST lane-kind line. +# +# Both reads here are READ-ONLY and neither ever writes. `swapped` is what a +# launcher asks when the tmux window name is gone — a restart opens a NEW +# tmux session, which is precisely why the window name cannot carry the lane +# across one. `session-start` is the SessionStart hook's whole output. + +# The register's own spelling of a lane whose name matches $1 ignoring case, +# read from `origin/` like every other state read (R19). Rule 10's wire +# form is lowercase and a tmux window may carry either, while the row's token is +# camel (`openRepoProject-1`): an exact lookup alone loses the lane. +# +# AMENDMENT 16(e) — AND IT RESOLVES A FORMER NAME, through the same seat every +# other reader takes. Clause (e) names the `SessionStart` block among the +# readers that resolve, and this is the read behind it: a window still carrying +# the name a lane had before its rename would otherwise orient the new session +# to "no lane bound to this window" — which is the one thing that block exists +# not to say — while the lane's row, log and handoff are all a `lane-rename` +# away under another name. +# +# `rows_named_ci_alias` IS THAT SEAT AND THIS IS `head -n1` OF IT, which is +# exactly what the `exit` in the awk above was: one answer and no refusal. The +# hook never refuses, so where two rows differ only by case this still answers +# with the first of them and `canon_lane` — the read every WRITER goes through +# — is where that pair is refused. +# 0 + one spelling (or nothing) · 5 the alias table could not be READ +# The 5 is carried for `rows_named_ci_alias`-s reason: `session_start_block` is +# a hook and may not refuse, but it must not print "no lane bound to this +# window" about a window whose name it could not resolve. +lane_named_ci() { + lnc_rc=0 + lnc_out="$(rows_named_ci_alias "$1" 2>/dev/null)" || lnc_rc=$? + [ "$lnc_rc" = 5 ] && return 5 + printf '%s\n' "$lnc_out" | grep . | head -n1 + return 0 +} + +# The lane whose row's SESSION CELL names — the second resolution the +# hook has, for a window that carries no lane name. ONLY the session cell is +# read: state cells quote other lanes' ids all the time ("RESUMED by ", +# "handed off to "), and one of those is not this session's lane. +lane_of_session() { + los_id="$(lc "${1-}")" + [ -n "$los_id" ] || return 1 + register_text | awk -F'|' -v id="$los_id" ' + substr($0,1,1) != "|" { next } + { + if (index(tolower($3), id) == 0) next + p1 = index($2, "`"); if (p1 == 0) next + rest = substr($2, p1 + 1); p2 = index(rest, "`"); if (p2 == 0) next + print substr(rest, 1, p2 - 1); exit + }' +} + +# ============================================================================ +# AMENDMENT 11 — THE RECORD'S SUB-FIELDS, AND THE READS BUILT ON THEM +# ============================================================================ +# +# Amendment 11 clause (c) gives the lane's `STARTED`/`RESUMED` lines and the +# swap record two new payload sub-fields, `dir ` and `profile `, +# beside Amendment 8(b)'s `window`, which gains a second ref. Clause (h) turns +# the reads of them into subcommands, for the reason Amendment 7(d) already +# gives `live-holder` and `lane-objects`: EACH READ EXISTS SO THAT SEVERAL +# CALLERS SHARE ONE IMPLEMENTATION. `window-lane` has three (the launcher's +# precedence 3, `/restart`'s step 2(c), the `/lane-swap` skill's step 1); +# `session-lane` has two (`/restart`'s step 2(b) and the SessionStart hook); +# `lane-dir` has four. A rule implemented once cannot be implemented three +# ways, which is exactly how the launcher, the skill and `/restart` would come +# to disagree about which lane a window is. + +# ONE PARSER OF A PAYLOAD'S SUB-FIELDS, AND ONE UNQUOTER. +# +# Amendment 7(b)'s grammar: sub-fields are separated by `; `, and SEVERAL REFS +# INSIDE ONE SUB-FIELD ARE SEPARATED BY SPACES — which is what the `window` +# sub-field's `: <@id>` relies on. So an unquoted +# `dir $HOME/my projects/x` (unquoted) parses as two refs and hands back a truncated +# path, and clause (c)'s rule is that the WRITER QUOTES a value containing a +# space and EVERY READER takes a value opening with `"` as running to its +# closing `"`, stripping both. +# +# Two modes, because the grammar has two kinds of value: +# (default) ONE REF — the value up to its first space, or the whole of a +# quoted value. `dir` and `profile` are read this way. +# all EVERY REF — the whole sub-field, which is what `window` is: +# two refs that a caller splits itself. +payload_subfield() { # [all] + awk -v pay="$1" -v want="$2" -v mode="${3-}" ' + BEGIN { + want = want " " + n = split(pay, sf, "; ") + for (i = 1; i <= n; i++) { + if (substr(sf[i], 1, length(want)) != want) continue + v = substr(sf[i], length(want) + 1) + sub(/^[ \t]+/, "", v); sub(/[ \t]+$/, "", v) + if (substr(v, 1, 1) == "\"") { + q = index(substr(v, 2), "\"") + if (q > 0) { print substr(v, 2, q - 1); exit } + } + if (mode != "all") { sub(/ .*$/, "", v) } + print v; exit + } + }' +} + +# ---------------------------------------- AMENDMENT 17(b): THE TWO SUB-FIELDS +# +# `agent ` and `transcript `, VALIDATED BY THE WRITER. Amendment +# 17(b) gives the `PAUSED` payload both; nothing else in this file could check +# them, because a payload is free text to `write_event` — and this log is +# APPEND-ONLY, so a sub-field written wrong is wrong for ever and no later line +# corrects it. The check is the same shape `valid_uuid` gives the session field +# under clause (e): the WRITER is the gate, from any caller. +# +# WHAT EACH ADMITS, and why the pattern is the rule rather than a list: +# agent A MANIFEST KEY — letters, digits, `.`, `_`, `-`. It is what +# `lane-start --agent ` reads back to choose a launcher, so +# a value carrying a space or a `;` is a value that would come +# back as two sub-fields or as an argument nobody meant. The +# pattern is also how this sub-field gets SPEC rev 6 §5's `; ` +# rule without a token of its own — the same argument clause (c)'s +# `profile` takes. +# transcript THE AGENT'S OWN RESUMABLE ID, or the literal `none` — which is +# an ANSWER ("this agent has no resumable id") and not a gap. +# Claude's is a uuid; another agent's is whatever that agent +# prints, so the shape is the same manifest key rather than +# `valid_uuid`, which would refuse every agent but one. +# +# A PAYLOAD CARRYING NEITHER IS VALID AND STAYS VALID. Every record written +# before this amendment carries neither, and Amendment 7(i)'s cutover rule is +# that a reader finding none says so rather than assuming one. The check fires +# only on a sub-field that is THERE. +# THE TWO ARE WRITTEN TOGETHER OR NOT AT ALL, AND AN EMPTY ONE IS NOT AN +# ABSENT ONE (Copilot rounds 1 and 2 on openRepoTools#47). The first shape of +# this gate entered on either sub-field and then accepted each empty result +# independently, which let a HALF record through: `agent codex` with no +# transcript, or `transcript ` with no agent, both of which `lane-start` +# reads one field of and defaults the other — launching Claude on a codex id, +# or codex on none. And a sub-field written EMPTY (`; agent ; …`) parsed +# identically to one that was never there, so a malformed line was indexed as a +# pre-amendment one for ever, in a log nothing rewrites. +# +# PRESENCE IS READ OFF THE SUB-FIELDS, never off the whole line: `dir +# /srv/agent-work` carries the letters and is not the field. +pause_subfields_check() { # + psc_pay="${1-}" + case "$psc_pay" in *agent*|*transcript*) : ;; *) return 0 ;; esac + psc_has_a=0; psc_has_t=0 + psc_rest="$psc_pay" + while : ; do + psc_one="${psc_rest%%; *}" + case "$psc_one" in + agent | 'agent '*) psc_has_a=1 ;; + transcript | 'transcript '*) psc_has_t=1 ;; + esac + case "$psc_rest" in + *'; '*) psc_rest="${psc_rest#*; }" ;; + *) break ;; + esac + done + # A PAYLOAD CARRYING NEITHER IS VALID AND STAYS VALID: every record written + # before this amendment carries neither, and Amendment 7(i)'s cutover rule is + # that a reader finding none says so rather than assuming one. + if [ "$psc_has_a" = 0 ] && [ "$psc_has_t" = 0 ]; then return 0; fi + # EACH FIELD THAT IS THERE IS READ WITH `all`, WHICH IS THE WHOLE SUB-FIELD + # AND NOT ITS FIRST REF. The default mode ends a value at its first space — + # the rule `dir` and `profile` are read by — so `agent not a key` would come + # back as `not`, a perfectly good manifest key, and the check would pass the + # very value it exists to refuse. A gate reads what was written, never what a + # reader would make of it. THE VALUE IS JUDGED BEFORE THE PAIR, so a payload + # that is both malformed and half-written is refused for the malformation, + # which is the thing the writer of it can see in what they typed. + if [ "$psc_has_a" = 1 ]; then + psc_a="$(payload_subfield "$psc_pay" agent all)" + case "$psc_a" in + '') + die "the record's \`agent\` sub-field is THERE and EMPTY, which is not the same as absent: no reader can tell it from a pre-amendment record, so every one of them would default to \`claude\` for ever (Amendment 7(i)'s cutover rule is about a field that was never written, not one written blank). Write the agent, or write neither sub-field. Nothing was written" 2 ;; + *[!A-Za-z0-9._-]*) + die "the record's \`agent\` sub-field is a manifest key — letters, digits, '.', '_', '-' — and '$psc_a' is not one (Amendment 17(b)). Nothing was written: this log is append-only, and \`lane-start --agent\` launches on what it reads back from this field" 2 ;; + esac + fi + if [ "$psc_has_t" = 1 ]; then + psc_t="$(payload_subfield "$psc_pay" transcript all)" + case "$psc_t" in + '') + die "the record's \`transcript\` sub-field is THERE and EMPTY. The word for an agent with no resumable id is \`none\`, which is an ANSWER; blank is a gap no reader can tell from a pre-amendment record. Nothing was written" 2 ;; + *[!A-Za-z0-9._-]*) + die "the record's \`transcript\` sub-field is the agent's own resumable id, or the word 'none' — '$psc_t' is neither (Amendment 17(b)). Nothing was written" 2 ;; + esac + fi + # AND THE PAIR. `lane-start` reads ONE of these fields to choose a launcher + # and the OTHER to choose what it hands that launcher, so a record carrying + # one of them makes it default the other: Claude launched on a codex id, or + # codex launched on none, out of a line nothing rewrites. + if [ "$psc_has_a" != "$psc_has_t" ]; then + psc_only=transcript + [ "$psc_has_a" = 1 ] && psc_only=agent + die "Amendment 17(b)'s two sub-fields are written TOGETHER or not at all, and this payload carries only \`$psc_only\`. A half record is worse than none: \`lane-start\` reads the field that is there and DEFAULTS the one that is not, so it would launch the wrong agent, or the right one on an id that is not its. Write both (\`agent ; transcript \`), or neither. Nothing was written — this log is append-only" 2 + fi + return 0 +} + +# ------------------------- AMENDMENT 18(a): THE BINDING'S THREE SUB-FIELDS +# +# WRITTEN BY THE WRITER, ONCE, FOR EVERY CALLER — the argument this file already +# makes for putting the container refusal at the dispatcher: *"nine copies of one +# rule is how eight of them would come to disagree."* `lane-start` writes +# `STARTED`/`RESUMED`, `lane-handoff` writes `PAUSED`, and clause (e)'s forced +# `PAUSED` is written here; all three go through `write_event`, so the three +# facts are appended HERE and no boundary script carries a copy of the probe. +# +# THE THREE VERBS ARE CLAUSE (a)'s THREE, AND `ENDED`/`RETIRED` ARE NOT AMONG +# THEM. Clause (a) is the RULE and it names `STARTED`, `RESUMED` and `PAUSED`; +# clause (b) reads the binding out of `STARTED`/`RESUMED` alone and a `PAUSED` +# releases it. Amendment 18's Adoption list adds `lane-end`'s two "for the +# record", and they are left out deliberately: Amendment 7(b) says *"`PAUSED`, +# `RESUMED`, `ENDED` and `RETIRED` take no payload"*, Amendment 11 clause (c) +# narrows that for `RESUMED` as **edit 1 of six** and says in the same breath +# that *"`ENDED` and `RETIRED` stay payload-free"*, and `lane-end` already +# refuses to write one for exactly that reason (its own block argues it at +# length: a payload there is a SEVENTH edit to in-force text where the count is +# six and the six are ratified, `R-A11-15`). A verb that RELEASES a binding has +# no binding to describe, so nothing is lost by the omission and a ratified +# count is not quietly broken by it. +# +# APPENDED AND NEVER SUBSTITUTED: a payload that already carries one of the +# three is the caller's own and is left exactly as it is, so a test seam, a +# replay and a future writer that fills them in itself all keep their value. +# They go LAST, after Amendment 11(c)'s and Amendment 17(b)'s, on the same +# cutover argument those took: a reader written before this clause stops at the +# sub-field it knows, and one that finds none says so (Amendment 7(i)). +# +# A VALUE THAT WOULD MAKE THE LINE UNREADABLE COSTS ITS OWN SUB-FIELD AND NEVER +# THE LINE (`R-A11-11`'s posture): the drop is printed, and the binding still +# names whichever of the three it could write. +binding_subfields_add() { # ; prints the payload with the three appended + bsa_pay="${1-}" + bsa_drop="" + # READ LIVE AT THE WRITE, which is what this clause says and what the + # 2026-09-15T12:17Z measurement means: a container's `hostname` names THAT + # container for as long as it exists and names nothing afterwards. The globals + # are a process-start convenience for the reads; the line about to be appended + # to an append-only log takes the probe again. + lanes_binding_probe + for bsa_f in host os container; do + case "$bsa_f" in + host) bsa_v="$LANES_HOST_NAME" ;; + os) bsa_v="$LANES_OS_NAME" ;; + container) bsa_v="$LANES_CONTAINER_NAME" ;; + esac + # Already there: the caller's, untouched. + [ -n "$(payload_subfield "$bsa_pay" "$bsa_f" all)" ] && continue + case "$bsa_pay" in "$bsa_f "*) continue ;; esac + if ! lanes_binding_value_ok "$bsa_v"; then + bsa_drop="$bsa_drop $bsa_f=${bsa_v:-}" + continue + fi + # AND `os` IS ONE OF FOUR WORDS WHEREVER IT COMES FROM (Copilot round 5 on + # openRepoTools#83). `binding_subfields_check` refuses a caller-written `os` + # that is none of them; this path takes the LAUNCHER'S export, which is + # nobody's to validate but this writer's — `LANES_OS=plan9` would otherwise + # be persisted on every binding line as a value the same file refuses when a + # caller supplies it, in a log nothing rewrites. Dropped rather than + # refused, like every other value here: `host` and `container` are what + # clause (b) reads, and a lane-kind line is never lost over a field no + # reader decides anything by. + if [ "$bsa_f" = os ]; then + case "$bsa_v" in + linux|macos|wsl|windows) : ;; + *) bsa_drop="$bsa_drop os=$bsa_v"; continue ;; + esac + fi + bsa_pay="${bsa_pay:+$bsa_pay; }$bsa_f $bsa_v" + done + [ -z "$bsa_drop" ] || note "DROPPED binding sub-field (the line is still written, Amendment 18(a)):$bsa_drop — a value carrying a space, ',', ';', '\"' or ' — ' is a line this log's own parser could never read again, and an \`os\` that is none of linux, macos, wsl, windows is a value this file's own writer refuses when a caller supplies it" + printf '%s' "$bsa_pay" +} + +# AND THE VALUES A CALLER WRITES ITSELF ARE CHECKED, for the reason +# `pause_subfields_check` gives for Amendment 17(b)'s two: a payload is free +# text to `write_event`, this log is append-only, and `binding` launches — and +# refuses — on what it reads back. The check fires only on a sub-field that is +# THERE, so every line written before this clause stays valid (Amendment 7(i)). +binding_subfields_check() { # + bsc_pay="${1-}" + case "$bsc_pay" in *host*|*os*|*container*) : ;; *) return 0 ;; esac + for bsc_f in host os container; do + bsc_has=0 + bsc_rest="$bsc_pay" + while : ; do + bsc_one="${bsc_rest%%; *}" + case "$bsc_one" in "$bsc_f" | "$bsc_f "*) bsc_has=1 ;; esac + case "$bsc_rest" in + *'; '*) bsc_rest="${bsc_rest#*; }" ;; + *) break ;; + esac + done + [ "$bsc_has" = 1 ] || continue + bsc_v="$(payload_subfield "$bsc_pay" "$bsc_f" all)" + case "$bsc_v" in + '') + die "the record's \`$bsc_f\` sub-field is THERE and EMPTY, which is not the same as absent: no reader can tell it from a line written before Amendment 18(a), so every one of them would read this lane's binding as the window on the row's workstation for ever. Write the value, or leave the sub-field out and the writer fills it in. Nothing was written" 2 ;; + *[!A-Za-z0-9._:-]*) + die "the record's \`$bsc_f\` sub-field is one ref of Amendment 7(b)'s grammar — letters, digits, '.', '_', '-', ':' — and '$bsc_v' is not one (Amendment 18(a)). A space there is a SECOND ref and a ';' is a second sub-field, in a log nothing rewrites. Nothing was written" 2 ;; + esac + if [ "$bsc_f" = os ]; then + case "$bsc_v" in + linux|macos|wsl|windows) : ;; + *) die "the record's \`os\` sub-field is one of linux, macos, wsl, windows (Amendment 18(a)) — '$bsc_v' is none of them. The probe writes the first three and only a launcher on the Windows host itself writes the fourth. Nothing was written" 2 ;; + esac + fi + done + return 0 +} + +# The sub-field of the lane's LAST lane-kind line that carries one, IN +# FILE ORDER — which is the order every other state read in this file uses, and +# for the reason `swapped_lanes` states below: a lane's log is append-only and +# single-writer, so a line further down the file is a line written later +# whatever the two UTC fields say. +# +# THE LAST LINE CARRYING ONE, NOT THE LAST LINE. A lane started under Amendment +# 11 and then PAUSED for a reason that is not a swap has a last line with no +# payload at all, and its directory has not stopped being true. Amendment 7(i)'s +# cutover rule is the same shape: a line written before this clause carries +# none, and a reader that finds none SAYS SO rather than assuming one. +# THE SIX FACTS A LISTING ROW NEEDS, FROM ONE PASS OVER ONE LANE'S EVENTS. +# `` on one line. +# It is `payload_subfield`'s two rules and `home_of_lane`'s one, written once in +# awk instead of a dozen forks per lane — and the rules are restated here rather +# than referred to because a reader comparing the two must be able to see both: +# * the LAST lane-kind line that carries a sub-field wins, in FILE ORDER; +# * a value opening with `"` runs to its closing `"`, quotes stripped, and any +# other value ends at its first space — except `window`, which is two +# space-separated refs in ONE sub-field and is taken whole. +lane_row_facts() { # events on stdin, ONE LINE PER LANE + awk -v sep="$US" ' + function field(pay, want, whole, n, i, sf, v, q) { + want = want " " + n = split(pay, sf, "; ") + for (i = 1; i <= n; i++) { + if (substr(sf[i], 1, length(want)) != want) continue + v = substr(sf[i], length(want) + 1) + sub(/^[ \t]+/, "", v); sub(/[ \t]+$/, "", v) + if (substr(v, 1, 1) == "\"") { + q = index(substr(v, 2), "\"") + if (q > 0) return substr(v, 2, q - 1) + } + if (!whole) sub(/ .*$/, "", v) + return v + } + return "" + } + function pos(pf2, pn) { return pf2 "\034" sprintf("%09d", pn) } + BEGIN { FS = sep } + $3 == "STARTED" || $3 == "PAUSED" || $3 == "RESUMED" || $3 == "ENDED" || $3 == "RETIRED" { + # AMENDMENT 15 — KEYED ON THE LANE LOWER-CASED, WITH ITS SPELLING BESIDE + # IT. Every consumer of this table already looks a lane up by its + # lower-cased name (`lanes_rows`-s `table_lookup`, which reads the FIRST + # line with that key), and the key used to be the spelling the LINE + # carried: a log holding both spellings of one lane — which is what + # `lanes/log/openxfactory-2.md` holds — emitted TWO lines under one key, + # and the listing took the first and lost the other-s state, dir, + # profile, window, home and session. `disp` is the first spelling seen, + # for the second column; `lanes_rows` prints the register-s spelling over + # it anyway, and this is what a lane with a log and no row shows as. + l = tolower($2) + if (!(l in seen)) { seen[l] = ++n; byn[n] = l } + if (!(l in disp)) disp[l] = $2 + # A FORK-S RETIRED IS NOT THE LANE-S OWN LAST VERB (decision 8(c): a fork + # is never the lane; A11 Addendum 4 ruling 8). Read as the lane-s own line + # it would say the LANE was retired — the opposite of what happened, since + # the lane may well be live beside the fork it disowned. So a line whose + # payload opens `fork ` is skipped HERE, for the state fields only. + # NOTHING WRITES ONE ANY MORE, and this comment said otherwise (#26, the + # review of `29d3417`). The first build of ruling 8-s act appended + # `RETIRED … lane: -> fork ; pid ; kind `; that line is a + # seventh edit to in-force text and Amendment 7(b) gives `RETIRED` no + # payload, so `lane-end --retire` PROVES the fork and prints 6(d) and + # writes nothing at all (`lane_forks`-s own block argues it in full). The + # skip stays because these logs are APPEND-ONLY and never rewritten: a log + # that took one of those lines while that build was live still carries it. + # + # R14 IS NOT WEAKENED BY THIS. R14 decides WHICH of a lane-s own lines is + # last; this decides which lines are the lane-s own. A line about + # something that is never the lane was never in that set. + if (substr($8, 1, 5) == "fork ") next + # FILE ORDER decides which line is a lane-s LAST (R14), exactly as + # `swapped_candidates` decides it: a lane-s log is append-only and + # single-writer, so a line further down the file is a line written later + # whatever the two UTC fields say. + p = pos($10, $11) + if (!(l in mp) || p >= mp[l]) { mp[l] = p; verb[l] = $3; utc[l] = $1; ws[l] = $5 } + v = field($8, "dir", 0); if (v != "") d[l] = v + v = field($8, "profile", 0); if (v != "") pf[l] = v + v = field($8, "window", 1); if (v != "") w[l] = v + if ($3 == "STARTED" || $3 == "RESUMED") { + v = field($8, "home", 0); if (v != "" && v != "unknown") h[l] = v + # AMENDMENT 18(b) — WHERE THIS BINDING IS, out of the same pass, and + # taken from the BINDING LINE rather than from the last line carrying a + # sub-field: a `PAUSED` releases a binding and its own host is where the + # release was written, not where the lane was. Lower-cased here so the + # comparison one layer up costs no process (`lc` is a printf and a tr, + # and this listing asks it of every lane). + bh[l] = tolower(field($8, "host", 0)); if (bh[l] == "") bh[l] = tolower($5) + bc[l] = tolower(field($8, "container", 0)); if (bc[l] == "") bc[l] = "none" + # A line written before clause (a) carries NONE OF THE THREE, and its + # binding is *"the window on the row-s workstation"* — which has no + # container in it. All three, and not the host alone: this writer drops + # an offending sub-field on its own and keeps the line, so a modern line + # missing only its host is modern and is matched on the container it + # does carry (Copilot round 2). Said here so the reader one layer up + # matches it exactly as `binding` does. + bl[l] = (field($8, "host", 0) == "" && field($8, "container", 0) == "" && \ + field($8, "os", 0) == "" ? "legacy" : "") + } + # Clause (d) rule 3-s second source, out of the same pass: the session + # field of the lane-s last PAUSED or RESUMED, which is the resume target + # where the published cell names none. + if (($3 == "PAUSED" || $3 == "RESUMED") && $4 ~ /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/) sid[l] = tolower($4) + next + } + # THE OBJECTS EACH LANE HOLDS, from the same pass. A lane HOLDS an object + # when its own LAST line on that object carries an OPEN verb — Amendment + # 7(b)-s partition, and the one `lane-end` refuses on. + # + # IT CARRIES NO TAKEN-OVER ANNOTATION, AND THAT IS A DELIBERATE NARROWING. + # `lane_objects` adds one by asking `superseded_by` per object, which is a + # full pass over this stream per object per lane: on the suite-s own + # register that turned a listing into eighteen minutes and counting. A + # listing says WHAT A LANE HOLDS; `who --lane ` is the authority that + # says whether somebody has taken it over, and the listing points at it. + $6 !~ /^lane:/ { + l = tolower($2); k = l "\034" $6 # Amendment 15, as above + p = pos($10, $11) + if (!(k in omp) || p >= omp[k]) { omp[k] = p; overb[k] = $3; oobj[k] = $6; olane[k] = l + if (!(k in okseen)) { okseen[k] = ++okn; okbyn[okn] = k } } + if (!(l in seen)) { seen[l] = ++n; byn[n] = l } + if (!(l in disp)) disp[l] = $2 + } + END { + for (i = 1; i <= okn; i++) { + k = okbyn[i] + if (overb[k] != "CLAIMED" && overb[k] != "TAKEOVER" && overb[k] != "OPENED" && overb[k] != "LANDING" && overb[k] != "WITHDRAWN") continue + l = olane[k] + if (l in have) obj[l] = obj[l] "; " overb[k] " " oobj[k] + else { obj[l] = overb[k] " " oobj[k]; have[l] = 1 } + } + for (i = 1; i <= n; i++) { + l = byn[i] + # KEYED ON THE LANE LOWER-CASED, like the register index beside it and + # for the same reason: the listing joins these two tables on the lane + # name, and this file matches a lane name case-insensitively everywhere + # else (`lane_named_ci`). + printf "%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s\n", l, 31, disp[l], 31, verb[l], 31, utc[l], 31, ws[l], 31, d[l], 31, pf[l], 31, w[l], 31, h[l], 31, sid[l], 31, obj[l], 31, bh[l], 31, bc[l], 31, bl[l] + } + }' +} + +# 0 with the sub-field · 8 the log was read and carries none · 1 THE LOG COULD +# NOT BE READ, which is not the same fact and never was (#26, the fail-closed +# family one layer out, `lanes-edit.sh:3525`). +# +# THE READ WAS INSIDE THE HERE-DOCUMENT THAT FEEDS THE LOOP, and a command +# substitution's status THERE is not carried anywhere — not, as the review had +# it, carried as `awk`'s; it is discarded outright, because a here-document body +# is text and nothing tests it. So a `lane_log_events` that failed arrived as no +# lines at all and left through the `return 8` below, and 8 is the one code every +# caller of this function is entitled to read as *"this lane has not started +# under Amendment 11 yet"* — the pre-cutover answer that sends `restart`, +# `lane-start` and both skills to the rungs beneath a record they never +# established was readable. The read is its own step now and its status decides. +lane_payload_field() { # [all] + lpf_lines=""; lpf_rc=0 + lpf_lines="$(lane_log_events "$1")" || lpf_rc=$? + [ "$lpf_rc" = 0 ] || return 1 + # The scan is over EVERY lane-kind payload, newest last, and the answer is + # the last one that actually carries the sub-field. + lpf_v="" + while IFS= read -r lpf_p; do + [ -n "$lpf_p" ] || continue + lpf_this="$(payload_subfield "$lpf_p" "$2" "${3-}")" + [ -n "$lpf_this" ] && lpf_v="$lpf_this" + done < + [ -n "${1-}" ] || return 1 + command -v tmux >/dev/null 2>&1 || return 1 + tmux display-message -p -t "$1" "$2" 2>/dev/null | head -n1 +} + +# THE LANE BOUND TO A WINDOW OF THE ASKING WORKSTATION (Amendment 11 clause +# (h), `R-A11-8`/RV-T7 for the scoping and `R-A11-8`/RV-T6 for the agreement +# rule). Three callers, ONE implementation: +# +# * the launcher's precedence 3 (clause (b) row 3), +# * `/restart`'s step 2(c) (clause (f)), +# * the `/lane-swap` skill's step 1 (Amendment 8(a) step 1, extended). +# +# TWO RUNGS, first answer wins: +# 1. the window's own NAME, where the register has a row for it. That is +# clause (b)'s precedence 2 read through the same door, so a caller that +# asks this read a ref gets the same answer the launcher would. +# 2. this workstation's swap records, matched on the ref. +# +# SCOPED TO THE ASKING WORKSTATION, IN THE CONTRACT AND NOT ONLY IN `Open`. A +# `:` is a local fact about one machine, and `claude-x:0` +# written on Raven collides with `claude-y:0` on Eagle far more easily than an +# `<@id>` will. `swapped` takes `[]` for exactly that reason and this read +# takes it for the same one: records written by another workstation are NOT +# CONSIDERED. +# +# THE AGREEMENT RULE, AND THIS READ OWNS IT. Existing-now is not enough on its +# own: a record naming `claude-y:0 @97`, met from the window that has since +# taken `claude-y:0` as `@200`, passes the existing-now test on its ref and +# would bind the lane to a stranger's pane with no question — which is the +# failure the liveness fence exists to stop, arriving through the LIVE ref +# instead of the dead one. So: +# +# a record that carries an `<@id>` is matched on its `:` ONLY +# WHERE THE WINDOW NOW HOLDING THAT REF REPORTS THAT SAME ID; a record with +# no id is matched on the ref alone. +# +# It is stated once, here, and not restated in each of the read's three +# callers: three implementations of one rule is how they would come to +# disagree. The launcher PR withdrew its own copy of this clause on the same +# ground. +# +# 0 with the lane, 8 with none, 64 a usage error of its own. +window_lane() { # + wl_ws="$(short_ws "${1:-$WS}")"; wl_ref="${2-}" + [ -n "$wl_ref" ] || return 64 + # A WORKSTATION THAT IS NOT THIS ONE HAS NO WINDOW THIS PROCESS CAN SEE, and + # the read says so rather than pretending. The window's NAME and the liveness + # fence are both facts about the tmux server running HERE: asked about Raven, + # a local `display-message` would answer about an Eagle window that happens to + # share the ref — which is the collision the scoping exists to stop, made by + # the fence itself. So a foreign workstation is answered from its RECORDS + # alone, unfenced, and that is the cross-machine answer Amendment 7's open + # item is about: this process cannot tell whether Raven's window still exists. + wl_local=1 + [ "$wl_ws" = "$(short_ws "$WS")" ] || wl_local=0 + if [ "$wl_local" = 1 ]; then + # RUNG 1 — the window's own name. Read from tmux, so a ref that names no + # window answers nothing here either. + wl_name="$(tmux_window_field "$wl_ref" '#{window_name}' 2>/dev/null || :)" + if [ -n "$wl_name" ]; then + wl_row="$(lane_named_ci "$wl_name" 2>/dev/null || :)" + if [ -n "$wl_row" ]; then printf '%s\n' "$wl_row"; return 0; fi + fi + fi + # RUNG 2 — that workstation's swap records. `swapped_candidates` is the one + # reader of a `PAUSED … swap;` line in this file, so the record's shape is + # parsed once however many reads are built on it. + wl_now_id="" + if [ "$wl_local" = 1 ]; then + wl_now_id="$(tmux_window_field "$wl_ref" '#{window_id}' 2>/dev/null || :)" + [ -n "$wl_now_id" ] || return 8 # the ref names no window HERE, now + fi + # THE FIELD LIST IS `swapped_candidates`' OWN, IN FULL, and it gains Amendment + # 17(b)'s two: `read` puts every field it has no variable for into the LAST + # one, so a short list would have quietly moved the pickaxe key — which is not + # read here — into `wl_p` and the agent into it too. Named in full, the reader + # and the writer of this row cannot drift apart. + while IFS="$US" read -r wl_l wl_u wl_w wl_d wl_p wl_a wl_t wl_key; do + [ -n "${wl_l:-}" ] || continue + [ -n "${wl_w:-}" ] && [ "$wl_w" != unknown ] || continue + # The sub-field's refs: `:` first, `<@id>` second. + wl_rec_ref="${wl_w%% *}" + wl_rec_id="" + case "$wl_w" in *' '@*) wl_rec_id="${wl_w##* }" ;; esac + case "$wl_ref" in + @*) + # Asked by id. The record must carry that id, and the id must resolve — + # which `wl_now_id` has already proved, since tmux answered for it. + [ -n "$wl_rec_id" ] && [ "$wl_rec_id" = "$wl_ref" ] || continue + ;; + *) + # Asked by `:`. The record must name that ref, AND — + # where the record carries an id and this workstation can see the window + # — the window now holding the ref must report that same id. + [ "$wl_rec_ref" = "$wl_ref" ] || continue + if [ "$wl_local" = 1 ] && [ -n "$wl_rec_id" ] && [ "$wl_rec_id" != "$wl_now_id" ]; then continue; fi + ;; + esac + # AMENDMENT 15 — AND THE ANSWER IS THE ROW'S SPELLING, as rung 1's already + # is. `$wl_l` is the lane as its own `PAUSED … swap;` line spells it, which + # is whatever the lane was PAUSED under; this read's three callers hand what + # it prints to `tmux rename-window`, to `--name` and to `lane `, so + # a record written before the row's spelling settled would rename a window + # to the wrong one. A register holding the 15(d) pair keeps the record's own + # spelling rather than refusing: this read is a rung in front of a launch and + # its contract is 0, 8 or 64 — the refusal belongs to the writer it leads to. + wl_can="$(canon_lane "$wl_l" 2>/dev/null || :)" + printf '%s\n' "${wl_can:-$wl_l}" + return 0 + done <` exactly as every other +# state read is. Clause (e) is what makes this source trustworthy, by +# refusing `unknown` in that field: a log that may carry the literal there +# is a log that cannot be read this way, and the two clauses are one act. +# +# A uuid whose transcript is not in the lane's directory IS STILL A UUID, and +# the caller says so rather than resuming a title into a picker. +# +# 0 with the uuid, 8 where neither source names one. +last_session_of() { # + lso_l="${1-}"; [ -n "$lso_l" ] || return 64 + lso_id="$(session_ids_of_lane "$lso_l" 2>/dev/null | tail -n1 || :)" + if [ -n "$lso_id" ]; then printf '%s\n' "$lso_id"; return 0; fi + lso_id="$(lane_log_events "$lso_l" 2>/dev/null | awk -F"$US" ' + ($3 == "PAUSED" || $3 == "RESUMED") && $4 ~ /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/ { id = $4 } + END { if (id != "") print tolower(id) }')" + [ -n "$lso_id" ] || return 8 + printf '%s\n' "$lso_id" +} + +# ------------------------- decision 8(c) and 8(e): A FORK IS NEVER A HOLDER +# +# Evidence 6, 2026-09-13: an abandoned launch of a lane left behind a DAEMON +# FORK of its transcript — `--fork-session`, a NEW session id, `kind: bg`, no +# tmux, a cwd of `/workspace` — which went on orchestrating the same plan, +# relaunched writers on the same three branches, wrote `RESUMED` and `PAUSED` +# lines into the lane's log, and messaged the interactive session claiming to +# be the holder while citing a dead pid. +# +# Amendment 8 ruling (g) already skips a `kind: bg` companion, and that is not +# enough: a fork is a SESSION OF ITS OWN with an id no row carries, so the +# thing that makes it recognisable is neither its kind nor its id but ITS +# TRANSCRIPT'S TITLE. A `--fork-session` copies the parent's `custom-title` +# record, so the fork's transcript says `openRepoProject-1` while its id says +# something the lane's row has never heard of. That pair — THE LANE'S TITLE +# UNDER AN ID THE LANE DOES NOT RECORD — is the defect, and it is what this +# read finds. +# +# IT NAMES THEM AND DOES NOTHING ELSE, exactly as `idle_holders` does and for +# the same reason clause (f) of Amendment 8 gives. THE ACT IT NAMES IS +# `lane-end --retire ` (clause (k) rule (e), A11 Addendum 4 +# ruling 8) and never `kill `: that act is the DOOR to Amendment 6(d), it +# writes nothing and *"neither kills a process"*. So this read goes on naming a +# fork until 6(d) is actually taken on it — the retitle, or the process gone — +# which is what is TRUE; and stopping the process stays a person's act that no +# surface here prints as the one. +# +# One line per fork, ``. +# 0 with rows, 8 with none, 1 where the records could not be read. +# Every LIVE record on this workstation whose transcript carries a custom +# title, as +# `<US><sessionId><US><lc sessionId><US><pid><US><kind><US><cwd>`. +# Built ONCE per process: `who` asks about every lane in the register, and one +# find per record per lane would be a read nobody would run. +# +# CACHED IN A FILE for the reason `live_session_ids` gives, and this one was the +# more expensive of the two: `transcript_title` falls back to a `find` over the +# whole profiles tree, so a rebuild per lane was a filesystem walk per lane. +# +# THE LOWER-CASED TITLE AND ID ARE CARRIED rather than computed by the reader: +# `lc` is `printf | tr`, TWO PROCESSES, and `lane_forks` ran it on every entry of +# this map for every lane it was asked about — fifty lanes times however many +# live records, for two comparisons a `case` can make. +fork_map() { + fm_c="${SE_CACHE_FILE:+$SE_CACHE_FILE.forks}" + if [ -n "$fm_c" ] && [ -f "$fm_c" ]; then cat -- "$fm_c"; return 0; fi + # THE READ IS ITS OWN STEP AND ITS STATUS DECIDES, because the loop below is + # fed by a HERE-DOCUMENT and a here-document body is TEXT: the status of a + # command substitution inside it is discarded outright (#26, the review of + # `37632b1`; the same shape `f368a75` took out of `lane_payload_field`). + fm_recs=""; fm_rc=0 + fm_recs="$(session_records)" || fm_rc=$? + [ "$fm_rc" = 0 ] || return 1 + fm_out="" + while IFS="$US" read -r fm_f fm_sid fm_tmux fm_name fm_pid fm_kind fm_cwd fm_status fm_start; do + [ -n "${fm_sid:-}" ] || continue + record_fields_are_live "$fm_status" "$fm_pid" "$fm_start" || continue + fm_t="$(transcript_title "$fm_sid" "$fm_f" "$fm_cwd")" + [ -n "$fm_t" ] || continue + fm_out="${fm_out}$(lc "$fm_t")${US}${fm_t}${US}${fm_sid}${US}$(lc "$fm_sid")${US}${fm_pid}${US}${fm_kind}${US}${fm_cwd} +" + done <<EOF +$fm_recs +EOF + if [ -n "$fm_c" ]; then + printf '%s' "$fm_out" > "$fm_c.${BASHPID:-$$}" 2>/dev/null && + mv -f -- "$fm_c.${BASHPID:-$$}" "$fm_c" 2>/dev/null || + rm -f -- "$fm_c.${BASHPID:-$$}" + fi + printf '%s' "$fm_out" +} + +# The `customTitle` of a transcript, by its uuid. A `/rename` writes a +# `{"type":"custom-title",…}` record INTO the transcript and the LAST one wins, +# which is the same reading `lane-start`'s own `titled_transcript` makes. +# `<lane> (2)` is the same lane: that suffix is what a rename into a title +# something else still holds mints. +transcript_title() { # <uuid> [<the record's file>] [<the record's cwd>] + tt_id="${1-}"; [ -n "$tt_id" ] || return 1 + tt_f="" + # THE CHEAP CANDIDATES FIRST, AND THE WALK ONLY WHERE THEY MISS. The harness + # keeps one transcript directory per working directory, named by that + # directory with every character that is not a letter or a digit replaced by + # `-`; the record itself carries both the profile directory it was written in + # (`<profile>/sessions/<pid>.json`) and the `cwd`. Two `[ -f ]` tests answer + # for every ordinary session, and the `find` is what catches a transcript the + # harness moved — which is the case Evidence 6's fork was in, its transcript + # under `state/` rather than under the profile. + if [ -n "${3-}" ]; then + tt_slug="$(printf '%s' "$3" | sed 's/[^A-Za-z0-9]/-/g')" + for tt_c in \ + "$(dirname -- "$(dirname -- "${2:-/nonexistent/x}")")/projects/$tt_slug/$tt_id.jsonl" \ + "${CLAUDE_CONFIG_DIR:-$HOME/.claude}/projects/$tt_slug/$tt_id.jsonl"; do + [ -f "$tt_c" ] && { tt_f="$tt_c"; break; } + done + fi + if [ -z "$tt_f" ]; then + for tt_root in "${CLAUDE_PROFILES_HOME:-$HOME/.claude-profiles}" "${CLAUDE_CONFIG_DIR:-$HOME/.claude}"; do + [ -d "$tt_root" ] || continue + tt_f="$(find "$tt_root" -maxdepth 8 -path '*/projects/*' -name "$tt_id.jsonl" -type f 2>/dev/null | head -n1)" + [ -n "$tt_f" ] && break + done + fi + [ -n "$tt_f" ] || return 1 + tt_last="$(grep -e '^{"type":"custom-title"' -- "$tt_f" 2>/dev/null | tail -n1 || :)" + [ -n "$tt_last" ] || return 1 + tt_v="$(printf '%s' "$tt_last" | sed 's/.*"customTitle":"//; s/".*//')" + [ -n "$tt_v" ] || return 1 + printf '%s\n' "${tt_v% (*)}" +} + +# `lane_forks <lane> [<ids fence>]` +# +# THE TWO SETS AS ONE SPACE-FENCED STRING EACH, tested with `case` (A11 +# Addendum 4 ruling 12). The `grep -qx` this replaces was a process per map +# entry per lane, and `lc` on the entry's title was two more; a `case` is the +# shell's own. +# +# AND A CALLER THAT ALREADY HAS THEM PASSES THEM. `lanes` asks this about every +# lane, and computing the row's ids here meant TWO renders of the published +# register plus one of the working tree's, per lane — the very reads the listing +# has already made in one pass. A caller with one lane in hand (`forks`, `who`) +# passes nothing and this computes them, so the read is unchanged for everybody +# else. The fences are `" a b c "`, lower-cased, spaces at both ends. +lane_forks() { # <lane> [<ids fence>] + lf_l="${1-}"; [ -n "$lf_l" ] || return 64 + lf_ll="$(lc "$lf_l")" + if [ "$#" -ge 2 ]; then + lf_ids="$2" + else + lf_ids=" $( { session_ids_of_lane "$lf_l" 2>/dev/null || : + session_ids_local_of_lane "$lf_l" 2>/dev/null || :; } | awk 'NF && !seen[$0]++' | tr '\n' ' ')" + fi + # AND THE MAP IS READ BEFORE THE LOOP, so that a session tree which could not + # be read leaves here as **1** and not as the **8** that means "no fork of it + # is live" (#26, the review of `37632b1`). The `forks` arm has carried the + # refusal for that 1 since it was written — *"That is NOT 'no fork of it is + # live'"* — and it was UNREACHABLE, because the status died in the + # here-document below. A fork is a DEFECT under ratified decision 8(e); the + # one thing worse than reporting one is reporting none without looking. + lf_map=""; lf_mrc=0 + lf_map="$(fork_map)" || lf_mrc=$? + [ "$lf_mrc" = 0 ] || return 1 + lf_out="" + while IFS="$US" read -r lf_tl lf_t lf_sid lf_sidl lf_pid lf_kind lf_cwd; do + [ -n "${lf_tl:-}" ] || continue + [ "$lf_tl" = "$lf_ll" ] || continue + # AN ID THE ROW RECORDS IS THE LANE ITSELF, never a fork of it. + case "$lf_ids" in *" $lf_sid "*) continue ;; esac + # AND THERE IS NO THIRD TEST, BECAUSE RETIRING WRITES NOTHING. The first + # build of ruling 8's act appended `RETIRED … -> fork <sid>` to the lane's + # log and this read filtered on it; that line is a SEVENTH edit to in-force + # text — Amendment 7(b) gives `RETIRED` no payload and A11 clause (c) keeps + # it that way — so it is gone (`lane-end`'s own block argues it in full). + # `lane-end --retire <pid|uuid>` is the DOOR to Amendment 6(d) and performs + # none of it, which is clause (k) rule (e)'s own posture, so a fork stays a + # fork here until the operator's retitle or its process is gone. This read + # keeps saying what is TRUE rather than what has been acknowledged. + lf_out="${lf_out}${lf_sid} ${lf_pid} ${lf_kind:-interactive} ${lf_cwd} +" + done <<EOF +$lf_map +EOF + [ -n "$lf_out" ] || return 8 + printf '%s' "$lf_out" +} + +# ------------------------------------------- issue #39: DUPLICATE HOLDERS +# +# `lane_forks` answers one question — a LIVE session recorded under an id the +# row does NOT carry, wearing the lane's own transcript title — and it answers +# it well: Evidence 6's `--fork-session` daemon had a fresh id nothing had +# heard of. Measured 2026-09-14 (opensoft/openRepoTools#39): a cross-profile +# resume leaves a SECOND kind of stray behind that `lane_forks` cannot see at +# all — a `bg-pty-host` running `claude --session-id <X> --fork-session +# --resume <parent>.jsonl` under a background pty host, where a LATER +# `lane-start --no-launch` went on to bind `<X>` itself as the row's own +# session. Once that happens the fork's id IS an id the row carries, +# `lane_forks`' own exclusion (`case "$lf_ids" in *" $lf_sid "*) continue`) +# fires exactly as designed, and the daemon goes invisible to it — while a +# second live process now holds the one transcript Amendment 18(h) says +# exactly one process may hold. `lane-end --retire <pid>` refused it outright, +# and the retirement was a bare `kill -TERM`, outside every tool this estate +# has. +# +# THE PROCESS TABLE, NOT A SESSION RECORD'S `sessionId` FIELD, because this +# question is not about what a record CLAIMS its id is — the fork's own record +# may say `<X>`, which is exactly the id the row now also carries and exactly +# why `lane_forks` cannot use it — it is about the ARGV a live process was +# actually started with: a `--fork-session` invocation whose `--resume` path +# ends in one of THIS LANE's own transcript ids. Every id the row has ever +# carried is checked, not only the last (Amendment 6(b): a chained cell's +# earlier link is still this lane's transcript). +# +# `pgrep -f` FIRST, THEN `ps -o pid=,ppid=,args= -p` PER CANDIDATE, both forms +# already used elsewhere in this tree for the same reason: GNU and BSD/macOS +# agree on `-f` (match the full argument list) and on `-o field=` (each `=` +# suppresses that field's own header, so the frame needs no trimming) where +# they do not agree on a fixed-column `ps aux`. Scoping the `ps` call to one +# candidate pid at a time, rather than walking the whole table once, is what +# lets the exact form stay `-p <pid>` instead of a table-wide parse this file +# would then own two implementations of. +# +# THE ROW'S OWN LIVE HOLDER IS EXCLUDED, never reported and never touched, +# over the SAME implementation `live-holder` already calls (`live_holder`, +# over the published-union-local id set) — never a new liveness primitive. In +# the ordinary case this exclusion never fires: a lane's real interactive +# session is never started WITH `--fork-session` in its own argv, so nothing +# this read finds can coincide with it. It stays in because a fence that is +# usually a no-op is exactly what a fence should be, and `lane-end` asks the +# same question again, in words, before it sends a single signal. +# +# One line per surviving match: `<parent pid><US><child pids, or empty><US> +# <the matched uuid>` — `$US`, never a TAB. A CONFIRMED CHILD OF THE CI RUN ON +# PR #61: with a real, honest, DOCUMENTED-empty child slot (the line just +# above — "the child slot stays empty" is not a race-only rarity, it is this +# read's ordinary answer for a parent with no confirmable fork-session child), +# a bare TAB is one of bash `read`'s own IFS-WHITESPACE characters, so +# `IFS=$'\t' read -r a b c` on `"<parent>\t\t<uuid>"` — TWO adjacent tabs +# either side of the empty middle field — COLLAPSES them into ONE delimiter +# exactly as it collapses repeated spaces, silently shifting the uuid into +# `b` and leaving `c` empty. Measured: `tests-no-submodule` on e4f9054, +# `test_the_lane_helper_suite_passes` read the empty child as a parent still +# "STILL ALIVE" (its own argv check comparing against `$dh_uuid_lc=""` could +# match nothing) and the uuid as a pid — `pid <uuid> (child): gone`. `$US` is +# not IFS whitespace, so `read` never merges it with itself; both consumers in +# `lane-end` read this format with `IFS=$'\037'` for the same reason +# `live-holder`'s own multi-field line already does. +# 0 with rows, 8 with none, 1 where `pgrep` is missing, the register or +# this workstation's session records could not be read — a read that failed is +# never "nothing is a duplicate". +duplicate_holder_pids() { # <lane> + dhp_l="${1-}"; [ -n "$dhp_l" ] || return 64 + command -v pgrep >/dev/null 2>&1 || return 1 + command -v ps >/dev/null 2>&1 || return 1 + # THE IDS ARE THE WHOLE SEARCH, SO A REGISTER THAT COULD NOT BE READ IS 1 + # (opensoft/openRepoTools#67). Its empty render used to be the same empty set + # as a lane with no row, and this returned 8 — "no duplicate holder is live" — + # without asking the process table anything at all. + dhp_ids=""; dhp_irc=0 + dhp_ids="$(session_ids_checked "$dhp_l")" || dhp_irc=$? + case "$dhp_irc" in + 0) : ;; + 8) return 8 ;; + *) SESSION_FILES_ERR="the register (origin/$LANES_BRANCH:$LANES_PATH, or $LANES_FILE) could not be read, so lane $dhp_l's session ids are not known and no process could be matched against them" + return 1 ;; + esac + dhp_legit="" + # NOT `$( … )` (Copilot round 2, PR #61): `live_holder` communicates a read + # failure by setting `SESSION_FILES_ERR` in ITS CALLER's shell, exactly as + # `session_files` documents and `window_session` already relies on — a + # command substitution runs in a SUBSHELL, so that assignment would die with + # it and the dispatcher's `${SESSION_FILES_ERR:-unknown error}` would print + # "unknown error" always. The tmp file is what lets this call stay direct + # and still hand the printed record back to the code after it. + dhp_lh_f="$(mktemp "${TMPDIR:-/tmp}/lanes-edit-dhp.XXXXXX" 2>/dev/null || printf '')" + if [ -z "$dhp_lh_f" ]; then + SESSION_FILES_ERR="could not create a temporary file under ${TMPDIR:-/tmp}" + return 1 + fi + live_holder "$dhp_l" "$dhp_ids" > "$dhp_lh_f" 2>/dev/null; dhp_lrc=$? + case "$dhp_lrc" in + 0) dhp_legit="$(awk -F"$US" '{print $4}' "$dhp_lh_f")" ;; + 8) : ;; + *) rm -f -- "$dhp_lh_f"; return 1 ;; + esac + rm -f -- "$dhp_lh_f" + # `pgrep -f` ITSELF, THREE-WAY (Copilot round 2): 1 is its OWN "no process + # matched" — the ordinary, honest 8 — and anything else (2 usage, 3 a fatal + # error reading the process table) is a READ THAT FAILED, never "none is a + # duplicate". + dhp_cand=""; dhp_pgrc=0 + dhp_cand="$(pgrep -f 'fork-session' 2>/dev/null)" || dhp_pgrc=$? + case "$dhp_pgrc" in + 0) : ;; + 1) return 8 ;; + *) return 1 ;; + esac + [ -n "$dhp_cand" ] || return 8 + # AMENDMENT 8 RULING (g)'s COMPANION IS NEVER A DUPLICATE, FROM THIS SURFACE + # EITHER (Copilot on 05d7889, PR #61). `live_holder` above answers the + # INTERACTIVE holder only — it passes over a `kind: bg` record by design — + # so `dhp_legit` fenced the session at the keyboard but not the harness's + # own companion beside it: a `kind: bg` record carrying the SAME id in the + # SAME profile as an interactive record of it, "one session, not a queue of + # rival holders". `lane-end`'s session-record path already refuses that pid + # by name; this process-table path runs FIRST, so a companion whose argv + # carried `--fork-session --resume <this lane's id>.jsonl` would have been + # handed to it as a duplicate and TERMed — one half of the live session that + # IS the lane. The companion set is built here with the very rule + # `lane-end` applies (`transcript_holders`' own `companion` verdict, or a + # `bg` row in a profile that also holds a non-`bg` row of the same id, which + # is how that verdict reads from outside the lane's own window), and a + # candidate that is one — or a wrapper whose child is one — is never a row. + # A records tree `transcript_holders` could not read is a read that FAILED, + # exactly as `live_holder`'s is above: 1, never "no companion". + dhp_comp=" " + dhp_th_f="$(mktemp "${TMPDIR:-/tmp}/lanes-edit-dht.XXXXXX" 2>/dev/null || printf '')" + if [ -z "$dhp_th_f" ]; then + SESSION_FILES_ERR="could not create a temporary file under ${TMPDIR:-/tmp}" + return 1 + fi + for dhp_tid in $dhp_ids; do + transcript_holders "$dhp_tid" > "$dhp_th_f" 2>/dev/null; dhp_thrc=$? + case "$dhp_thrc" in + 0) : ;; + 8) continue ;; + *) rm -f -- "$dhp_th_f"; return 1 ;; + esac + dhp_int_profs=" " + while IFS="$US" read -r dt_pid dt_kind dt_tgt dt_prof dt_where dt_v dt_file; do + [ -n "${dt_pid:-}" ] || continue + [ "$dt_kind" = bg ] && continue + case "$dhp_int_profs" in *" $dt_prof "*) : ;; *) dhp_int_profs="${dhp_int_profs}${dt_prof} " ;; esac + done < "$dhp_th_f" + while IFS="$US" read -r dt_pid dt_kind dt_tgt dt_prof dt_where dt_v dt_file; do + [ -n "${dt_pid:-}" ] || continue + [ "$dt_kind" = bg ] || continue + dt_is_comp=0 + if [ "$dt_v" = companion ]; then + dt_is_comp=1 + else + case "$dhp_int_profs" in *" $dt_prof "*) dt_is_comp=1 ;; esac + fi + [ "$dt_is_comp" = 1 ] && dhp_comp="${dhp_comp}${dt_pid} " + done < "$dhp_th_f" + done + rm -f -- "$dhp_th_f" + # A CANDIDATE'S OWN PARENT, WHEN IT IS ALSO A CANDIDATE, IS NEVER TREATED AS + # A SECOND PARENT (Copilot round 2): `--fork-session`'s argv is inherited by + # the child `claude` process as often as the bg-pty-host wrapper that + # started it, so `pgrep -f` routinely returns BOTH — and reading the child + # on its own turn, with no ppid fence, reported it as a headless parent of + # its own (no child of ITS OWN to find), doubling one duplicate into two + # rows and leaving `--retire <the real parent's pid>` unreachable if the + # child's spurious row was taken instead. + dhp_cand_fence=" $(printf '%s' "$dhp_cand" | tr '\n' ' ') " + dhp_out="" + while IFS= read -r dhp_pid; do + [ -n "$dhp_pid" ] || continue + [ -n "$dhp_legit" ] && [ "$dhp_pid" = "$dhp_legit" ] && continue + case "$dhp_comp" in *" $dhp_pid "*) continue ;; esac + dhp_psrc=0 + dhp_line="$(ps -o pid=,ppid=,args= -p "$dhp_pid" 2>/dev/null)" || dhp_psrc=$? + # A `ps -p` MISS IS NOT A READ FAILURE, but a nonzero status alongside + # OUTPUT would be (Copilot round 5/6, PR #61: "a failed ps lookup is read + # as no candidate") — `ps -p <gone pid>` fails with EMPTY output, which is + # the ordinary, honest "it already exited" race this whole scan expects; + # a command that failed and still printed something is the one case + # this file's fail-closed rule everywhere else applies to. + if [ -z "$dhp_line" ]; then continue; fi + [ "$dhp_psrc" = 0 ] || return 1 + read -r dhp_pid_chk dhp_ppid dhp_args <<DHPLINE +$dhp_line +DHPLINE + # `--fork-session ` WITH ITS OWN TRAILING SPACE (Copilot round 11, PR + # #61): a bare substring also matches `--fork-session-helper` or any + # other flag that merely STARTS WITH this text, which is never the + # process this scan means — the real invocation always has a boundary + # (a space, then `--resume`) right after this flag, so requiring it + # rules the false one out the same way the `--resume ` half already + # rules out `--resume-file` beside it. + case "$dhp_args" in *"--fork-session "*"--resume "*) : ;; *) continue ;; esac + case "$dhp_cand_fence" in *" $dhp_ppid "*) continue ;; esac + dhp_args_lc="$(printf '%s' "$dhp_args" | tr 'A-F' 'a-f')" + # THE ACTUAL `--resume` VALUE, NOT A GLOB THAT CAN SPAN OTHER ARGUMENTS + # (Copilot round 5, PR #61): `*"--resume"*"/$id.jsonl"*` also matches + # `--resume /other.jsonl --label /<id>.jsonl`, since `*` between them + # freely crosses argument boundaries. What was actually resumed is the + # value right after `--resume `, and that is the only thing compared — + # read WHOLE, spaces and all, by `dhp_resume_value` below this function + # (opensoft/openRepoTools#76: cutting it at the first space never matched + # a directory that has one). + dhp_resume_value "$dhp_args_lc"; dhp_resume="$dhp_rv" + for dhp_id in $dhp_ids; do + dhp_id_lc="$(printf '%s' "$dhp_id" | tr 'A-F' 'a-f')" + # AN EXACT PATH COMPONENT, NOT AN ARBITRARY SUBSTRING (Copilot round 4, + # PR #61): a bare substring also matches `other-<id>.jsonl` (no leading + # `/`, so it is not THIS transcript's basename) and `<id>.jsonl.bak` — + # `/<id>.jsonl` must be the resume token's own trailing path component. + dhp_matched=0 + case "$dhp_resume" in */"$dhp_id_lc.jsonl") dhp_matched=1 ;; esac + if [ "$dhp_matched" = 1 ]; then + # THE CHILD, PREFERRING ONE THAT IS ITSELF A `--fork-session` MATCH + # (the real `claude` leaf) over whichever child the process table + # happens to list first. `pgrep -P`'s OWN status, three-way, same as + # the top-level `pgrep -f` above (Copilot round 4): 1 is its own + # "no children", honestly empty; anything else is a read that + # FAILED, and this candidate is skipped rather than reported with a + # child slot that only LOOKS empty on purpose. + dhp_child=""; dhp_kids=""; dhp_kidrc=0 + dhp_kids="$(pgrep -P "$dhp_pid" 2>/dev/null)" || dhp_kidrc=$? + case "$dhp_kidrc" in + 0 | 1) : ;; + *) return 1 ;; + esac + # AN ARBITRARY CHILD IS NEVER GUESSED (Copilot round 6, PR #61): a + # bg-pty-host can have children that are not the `claude` process it + # wraps at all — a shell, a pty helper — and reporting the FIRST one + # `pgrep -P` happens to list, when none of them is itself a + # `--fork-session` candidate, could hand an unrelated process to + # `lane-end --retire`'s TERM. Only a child THIS SAME SCAN also + # confirmed as a fork-session candidate is ever named; otherwise the + # child slot stays empty; the parent is still reported and retirable + # on its own. + # + # EVERY FENCED CANDIDATE MUST PROVE IT RESUMES THIS SAME TRANSCRIPT + # BEFORE IT IS NAMED, and a `ps -p` MISS IS NOT THE SAME VERDICT AS A + # CONFIRMED MISMATCH (Copilot round 8 AND round 9, PR #61: the first + # pass here trusted a SOLE fenced candidate on the fence alone, + # which round 9 found true a wrapper with exactly one child for a + # DIFFERENT transcript could exploit). Both facts are proven in one + # pass, never two: + # * a candidate whose `ps -p` reads and whose `--resume` value + # matches `$dhp_id_lc` exactly is VERIFIED — named, however many + # other candidates there are, and so is EVERY other child that + # verifies (opensoft/openRepoTools#86, below); + # * a candidate whose `ps -p` reads but whose `--resume` does NOT + # match is a CONFIRMED MISMATCH — a different transcript's fork, + # and it is never named, however few other candidates there are; + # * a candidate whose `ps -p` MISSES (empty output — the ordinary + # "already gone by the time this scan asks" race, not a + # confirmed anything) is neither: it is held as a FALLBACK, and + # named only if it is the SOLE fallback with no verified + # candidate elsewhere. This is what keeps `lane-end`'s own race + # case working — a child already unreadable by the time + # discovery runs is still named here, for the pre-kill recheck + # a step later to catch honestly — while a wrapper's one child + # for another transcript, which DOES read, is never mistaken + # for it. + # Two or more unresolved fallbacks are left unnamed rather than + # guessed between; the parent is still reported and retirable on + # its own in every one of these shapes. + # + # EVERY VERIFIED CHILD, NOT THE FIRST (opensoft/openRepoTools#86, + # Copilot on 11bf0f0, PR #61): this loop used to `break` on the first + # child that verified, and the record had one child slot, so a + # wrapper with two children both resuming this transcript had the + # second left out of the report `lane-end --retire` acts on — which + # then TERMed the parent and the one child it was told about, + # reported RETIRED, and left the other still holding the transcript. + # The loop now runs to the end, and the slot carries every verified + # child, space-separated, in the order `pgrep -P` listed them. A + # pid never contains a space and `$US` is the record's only field + # separator, so `lane-end`'s `IFS=$'\037' read` still takes the + # whole list as one field. + dhp_verified=""; dhp_fallback=""; dhp_fallback_n=0 + for dhp_c in $dhp_kids; do + case "$dhp_cand_fence" in *" $dhp_c "*) : ;; *) continue ;; esac + dhp_c_line=""; dhp_c_psrc=0 + dhp_c_line="$(ps -o args= -p "$dhp_c" 2>/dev/null)" || dhp_c_psrc=$? + if [ -z "$dhp_c_line" ]; then + dhp_fallback_n=$((dhp_fallback_n + 1)) + [ -n "$dhp_fallback" ] || dhp_fallback="$dhp_c" + continue + fi + [ "$dhp_c_psrc" = 0 ] || return 1 + dhp_c_args_lc="$(printf '%s' "$dhp_c_line" | tr 'A-F' 'a-f')" + # `--fork-session ` WITH ITS OWN TRAILING SPACE (Copilot round 11, + # PR #61) — same fix, same reason as the parent's own check above. + case "$dhp_c_args_lc" in *"--fork-session "*"--resume "*) : ;; *) continue ;; esac + dhp_resume_value "$dhp_c_args_lc"; dhp_c_resume="$dhp_rv" + case "$dhp_c_resume" in + */"$dhp_id_lc.jsonl") dhp_verified="${dhp_verified}${dhp_verified:+ }${dhp_c}" ;; + esac + done + if [ -n "$dhp_verified" ]; then + dhp_child="$dhp_verified" + elif [ "$dhp_fallback_n" = 1 ]; then + dhp_child="$dhp_fallback" + fi + # A WRAPPER WHOSE CHILD IS THE COMPANION IS THE COMPANION'S OWN HOST + # (Copilot on 05d7889, PR #61, with the companion set above): the + # harness's record may carry the `claude` leaf's pid rather than the + # `bg-pty-host` wrapper's, so EVERY child `pgrep -P` listed is asked + # — named or not — and a match drops the whole pair. Terming the + # wrapper ends the companion with it. + dhp_is_comp_host=0 + for dhp_c in $dhp_kids; do + case "$dhp_comp" in *" $dhp_c "*) dhp_is_comp_host=1; break ;; esac + done + if [ "$dhp_is_comp_host" = 0 ]; then + dhp_out="${dhp_out}${dhp_pid}${US}${dhp_child}${US}${dhp_id} +" + fi + break + fi + done + done <<EOF +$dhp_cand +EOF + [ -n "$dhp_out" ] || return 8 + printf '%s' "$dhp_out" +} + +# THE `--resume` VALUE, READ WHOLE (opensoft/openRepoTools#76), for both of +# `duplicate_holder_pids`' matches above. It sets `dhp_rv` in the caller's own +# shell, never through `$( … )`, which would fork once per candidate, to the +# value after the FIRST `--resume ` in a flattened, already-lowercased argv, +# or to empty where there is no value it can name. +# +# `ps -o args=` JOINS THE ARGV WITH SPACES AND QUOTES NOTHING, so where one +# argument ends is gone from the line this reads. Measured with procps on +# Linux: `--resume "/home/Jane Doe/.claude/projects/p/<id>.jsonl" +# --output-format stream-json` reads back as `--resume /home/Jane +# Doe/.claude/projects/p/<id>.jsonl --output-format stream-json`. The cut this +# replaced, `${v%% *}`, took `/home/jane` from that and matched nothing, so a +# duplicate resumed from a home, profile or project directory with a space in +# it was never found, and `lane-end`'s pre-kill recheck, which made the same +# cut, would have withheld the TERM it is there to send. +# +# THE VALUE ENDS AT THE FIRST `.jsonl` THAT ENDS AN ARGUMENT, one followed by +# a space or by the end of the line, because the transcript path a harness +# resumes ends exactly there. That keeps both of PR #61's earlier guarantees: +# Copilot round 5's `--resume /other.jsonl --label /<id>.jsonl` still reads +# `/other.jsonl` and never this transcript, and round 4's `<id>.jsonl.bak` +# is still not `<id>.jsonl`, because its `.jsonl` ends no argument. +# +# A WORD OPENING WITH `--` INSIDE IT IS A LATER OPTION, NOT A DIRECTORY, and a +# value that holds one is EMPTY. `--resume <a bare session id> --x +# /<id>.jsonl` has no `.jsonl` of its own to stop at, so the first one that +# ends an argument is the later option's, and naming the process from it +# would hand `lane-end --retire` a TERM for something that resumed another +# session. +# +# A VALUE WITH A SPACE IN IT MUST BE ONE ABSOLUTE PATH, starting with `/` and +# holding no ` /`, or it is EMPTY (Brett Heap's ruling of 2026-10-18 on PR +# #205, "Add the condition first (Recommended)"). A value that does not itself +# end in `.jsonl` runs on to the next `.jsonl` that ends an argument, so a +# later plain word ending in `/<id>.jsonl` was read as its tail, where the cut +# at the first space never read it at all. Five shapes did that: a bare +# session id followed by a prompt that names the transcript (`--resume <id> +# read /p/<id>.jsonl and summarise`, and `claude -p … --resume <id> summarise +# /p/<id>.jsonl`), an empty argument before the path (`--resume '' +# /p/<id>.jsonl`, which `ps` prints with two spaces), a `<id>.jsonl.bak` +# followed by a word that names the transcript (`--resume /p/<id>.jsonl.bak +# note /q/<id>.jsonl`), and a shell whose `-c` string resumes `$ID` and then +# tails the transcript. Each of them starts with something other than `/`, or +# reaches the later path through a space and a `/`, and a transcript path does +# neither, whatever spaces its home, profile or project directory holds, save +# a directory whose name ENDS in a space before its `/`, which puts a ` /` +# inside the path, so it is refused (see the known limits below). A value with +# no space in it is untouched by this, and reads as the cut read it. +# +# KNOWN LIMITS, and they are the flattening's rather than this read's. A +# directory whose own name holds `.jsonl ` or ` --`, or ends in a space before +# its `/`, is cut short or refused, which only ever misses. The one shape this +# read can still mistake is narrower now: a value that starts with `/` but +# does not itself end in `.jsonl`, followed by a later word that names +# `<id>.jsonl` and does not begin with `/` (`--resume /p/<id>.jsonl.bak note +# q/<id>.jsonl`, and likewise a word opening `~/`, `$HOME/`, `file:///`, +# `path=/` or `(/`), which reaches it through no ` /`. Linux's +# `/proc/<pid>/cmdline` keeps the argument boundaries and BSD/macOS has +# nothing like it, so one portable reading of `ps`, the same on every +# platform and under the suite's own fake `ps`, is kept over two that could +# disagree. `lane-end` carries the same rule for its pre-kill recheck +# (`dh_resume_value`), and the two must stay the same rule. +dhp_resume_value() { # <flattened argv, lowercased> — sets dhp_rv + dhp_rv="" + case "${1-}" in *"--resume "*) : ;; *) return 0 ;; esac + dhp_rv_rest="${1#*--resume }" + while :; do + case "$dhp_rv_rest" in *.jsonl*) : ;; *) dhp_rv=""; return 0 ;; esac + dhp_rv="${dhp_rv}${dhp_rv_rest%%.jsonl*}.jsonl" + dhp_rv_rest="${dhp_rv_rest#*.jsonl}" + case "$dhp_rv_rest" in "" | " "*) break ;; esac + done + case "$dhp_rv" in *" --"*) dhp_rv="" ;; esac + case "$dhp_rv" in *" "*) + case "$dhp_rv" in /*) : ;; *) dhp_rv="" ;; esac + case "$dhp_rv" in *" /"*) dhp_rv="" ;; esac + esac + return 0 +} + +# ------------------------------- decisions 6 and 7: THE LANE LISTING READ +# +# ONE READ, TWO LISTINGS. Decision 6 ratified the estate-wide `lanes`; decision +# 7 ratified `restart`'s per-repo listing and `/restart`'s. All three are the +# same rows with a different filter, so the filter is an argument here rather +# than three implementations in three commands — the rule clause (h) already +# gives `window-lane` and `session-lane`. +# +# READ-ONLY, out of `origin/<branch>` like every Amendment 7 read, and +# `LANES_NO_FETCH=1` is honoured by the one `log_sync` its caller makes. It +# never writes and never launches anything. +# +# lanes_rows [--repo <owner/repo>] [--dir <path>] [--ws <ws>] [--all] +# +# `--repo` and `--dir` are decision 7's per-repo scope and they are an OR, not +# an AND: "rows whose register `home` is this checkout's `origin`, OR whose +# recorded `dir` is this checkout". That second half is a second use for clause +# (c)'s `dir` and an argument for recording it, because a lane's home +# repository and the checkout it sits in are not the same fact. +# +# Tab-separated, one line per lane, and the COLUMNS ARE THE DATA rather than a +# rendering: `restart` and `lanes` lay them out, and a third caller that wants +# a different shape does not need a fourth read. +# +# <lane> <state> <workstation> <profile> <window> <last uuid> <dir> +# <objects> <age> <restart line> <home> <forks> +# +# THE FIRST TEN ARE CLAUSE (j)'s TEN, IN CLAUSE (j)'s ORDER (A11 Addendum 4 +# ruling 7): *"`lanes` and `restart` each render the subset of clause (j)'s ten +# columns their surface needs while the read carries all ten."* Column 10 — the +# restart line — used to be computed by each renderer, which is two +# implementations of one column; it is the read's now, so the two surfaces +# cannot disagree about which lane may be restarted or about what to type. +# +# `<home>` and `<forks>` are the read's own additions after the ten. +# `<forks>` is decision 8(e): the count of LIVE forks of this lane's transcript +# — a defect to retire, shown by both listings and never counted as a holder. +# +# Newest activity first, by the UTC of the lane's last lane-kind line. That is +# a clock and it decides nothing but the ORDER OF A LISTING, which is the one +# place a clock is allowed to: `swapped` ranks by landing order because a +# launcher BINDS from its first row, and nothing binds from this one. +# Every LIVE session id on this workstation with the window it is in, as +# `<sessionId><US><tmux target><US><name><US><pid>`. ONE pass over the records +# for the whole listing: `live_holder` answers about one lane and re-reads +# every record to do it, which for a 48-row register is 48 scans of the same +# directory. +# +# CACHED IN A FILE AND NOT IN A VARIABLE (A11 Addendum 4 ruling 12). Every +# caller invokes this inside `$( … )`, which is a SUBSHELL — so the variable the +# build set died with the build and the next lane rebuilt it, 564 records at a +# time, 46 times for one listing. A file survives the subshell that wrote it. +live_session_ids() { + lsi_c="${SE_CACHE_FILE:+$SE_CACHE_FILE.live}" + if [ -n "$lsi_c" ] && [ -f "$lsi_c" ]; then cat -- "$lsi_c"; return 0; fi + # ITS OWN STEP, FOR THE HERE-DOCUMENT'S SAKE, exactly as in `fork_map`: a + # session tree that could not be read is not a workstation with nothing live + # on it, and this answer decides the STATE column of every row a listing + # prints (#26, the review of `37632b1`). + lsi_recs=""; lsi_rc=0 + lsi_recs="$(session_records)" || lsi_rc=$? + [ "$lsi_rc" = 0 ] || return 1 + lsi_out="" + while IFS="$US" read -r lsi_f lsi_sid lsi_tmux lsi_name lsi_pid lsi_kind lsi_cwd lsi_status lsi_start; do + [ -n "${lsi_sid:-}" ] || continue + record_fields_are_session "$lsi_kind" || continue + record_fields_are_live "$lsi_status" "$lsi_pid" "$lsi_start" || continue + lsi_out="${lsi_out}${lsi_sid}${US}${lsi_tmux}${US}${lsi_name}${US}${lsi_pid} +" + done <<EOF +$lsi_recs +EOF + if [ -n "$lsi_c" ]; then + printf '%s' "$lsi_out" > "$lsi_c.${BASHPID:-$$}" 2>/dev/null && + mv -f -- "$lsi_c.${BASHPID:-$$}" "$lsi_c" 2>/dev/null || + rm -f -- "$lsi_c.${BASHPID:-$$}" + fi + printf '%s' "$lsi_out" +} + +# Every lane the register has a row for — the union with `known_lanes` is what +# a listing shows, because a lane may have a row and no log (pre-cutover) or a +# log and a row that has been closed. +register_lanes() { + { register_text; archive_text; } | awk ' + substr($0,1,1) == "|" { + p1 = index($0, "`"); if (p1 == 0) next + rest = substr($0, p1 + 1); p2 = index(rest, "`"); if (p2 == 0) next + print substr(rest, 1, p2 - 1) + }' +} + +# ONE PASS OVER THE REGISTER FOR THE WHOLE LISTING (A11 Addendum 4 ruling 12). +# `<lane><US><workstation><US><session ids, lower-cased, space separated>` +# +# The four facts the listing wants from a row — is there a row, whose +# workstation, which ids, which is last — were four separate reads per lane, +# each of them `register_text | awk` and each therefore a render of the +# published 1.1 MB register. This is the same three answers from one pass, and +# the parsing is the SAME parsing: `ROW_AWK`'s first-backticked-token rule for +# the name, `row_cell`'s "field k+1 because $1 is the empty string before the +# leading pipe" for the cells, `lane_workstation`'s strip-at-the-first-slash for +# the workstation, and `uuids_in_cell`'s shape match — restated here in awk +# because a reader comparing the two must be able to see both. +LANES_REGISTER_INDEX_AWK=' + # THE STATE CELL IS THE SEVENTH, AND SIX ` | ` SEPARATORS ARE THE PROOF — + # `row_split_state_cell` in awk, for the same reason the three reads above + # are restated here: this pass already holds the row, and a second read of + # the same megabyte to ask what the cell says would cost the listing what + # ruling 12 spent this function to save. The rule is that files: split from + # the left, six separators or it is not knowable WHICH text is the state + # cell, and then the last piece is it. More than six returns EMPTY rather + # than a guess — the writer refuses that row outright, and a reader that + # picked one of the two readings would be filing a lane by the wrong text. + function cell_state(row, body, rest, i, cnt) { + sub(/[ \t]+$/, "", row) + if (substr(row, 1, 1) != "|") return "" + if (substr(row, length(row), 1) != "|") return "" + body = substr(row, 1, length(row) - 1) + rest = body; cnt = 0 + while (cnt < 6) { + i = index(rest, " | ") + if (i == 0) return "" + rest = substr(rest, i + 3) + cnt++ + } + if (index(rest, " | ") > 0) return "" + return rest + } + function trim(t) { sub(/^[ \t]+/, "", t); sub(/[ \t]+$/, "", t); return t } + substr($0, 1, 1) != "|" { next } + { + p1 = index($0, "`"); if (p1 == 0) next + rest = substr($0, p1 + 1); p2 = index(rest, "`"); if (p2 == 0) next + lane = substr(rest, 1, p2 - 1) + n = split($0, c, "|") + ses = (n >= 3 ? c[3] : "") + ws = (n >= 4 ? c[4] : "") + # COLUMN 4, `started (UTC)`, AS THE ROW SPELLS IT. The live register + # writes that column three ways — `2026-09-02`, `2026-09-04 ~15:30Z` and + # `2026-09-13T17:41Z` — and this carries the text, not an instant: the + # sweep prints it for a person to read, and `mig_started_utc` is the one + # place that turns it into a UTC. + started = (n >= 5 ? trim(c[5]) : "") + gsub(/\t/, " ", started) + sub(/^[ \t]+/, "", ws); sub(/[ \t]+$/, "", ws) + sub(/ *\/.*$/, "", ws) + sub(/[ \t].*$/, "", ws) + # `short_ws` IS `printf | tr`, TWO PROCESSES, and the listing ran it per + # lane to decide the workstation filter. It is one `sub` and a `tolower` + # here, in the pass that already has the value. + wss = tolower(ws); sub(/\..*$/, "", wss) + ids = ""; s2 = tolower(ses) + while (match(s2, /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/)) { + ids = ids substr(s2, RSTART, RLENGTH) " " + s2 = substr(s2, RSTART + RLENGTH) + } + sub(/ $/, "", ids) + # THE STATE CELL: ITS HEAD, AND THE WORDS A SWEEP MUST NOT PASS OVER + # SILENTLY (Amendment 19(b) and (c)). The head is what `lanes --closed` + # shows for a dormant row and what its `RETIRED` line carries as + # `was:`, so the row-s own last words survive the sweep that closes it; + # the flags are read from the WHOLE cell and not from the head, because + # the five words that matter — the work was unpushed, lost, a loss, owed, + # or the cell still says LIVE — sit at the end of cells thousands of + # characters long on the register this was written for. + # CUT BACK TO A SPACE: `substr` counts bytes in some awks and characters + # in others, and a cut mid-character would put half a `—` into a log line + # that is append-only. Dropping the last (possibly torn) word costs a word + # and can never do that. + # + # AND THESE TWO ARE A TABLE OF THEIR OWN (`--cells`), NEVER THE ONE THE + # LISTING SCANS PER LANE — ruling 12 again, measured. `table_lookup` walks + # the whole table for every lane, so a free-text field of up to 280 + # characters per row is paid for N times: on a register of 132 rows one + # `lanes --prefix <repo>` went from 14 s to 42 s with `head` and `flags` + # in this table, which is what put the pick past the 60-second terminal + # case in CI. The four short facts every row needs stay here; the two long + # ones are asked for BELOW THE NARROWING FILTER and only for a row with no + # object log, which is the only row that has anything to say with them + # (Amendment 19(a)). + if (!cells) { + print tolower(lane) sep lane sep ws sep wss sep ids sep started + next + } + cell = cell_state($0) + # An invalid column boundary is NOT an empty state cell. Leave this row + # out of the cells index so the caller keeps it unclassified and visible. + if (cell == "") next + gsub(/\t/, " ", cell) + cell = trim(cell) + head = cell + if (length(head) > 280) { + head = substr(head, 1, 280) + sub(/[^ ]*$/, "", head) + head = trim(head) + if (head == "") head = substr(cell, 1, 200) + head = head " ..." + } + lcell = tolower(cell) + flags = "" + if (lcell ~ /(^|[^a-z])unpushed([^a-z]|$)/) flags = flags "unpushed," + if (lcell ~ /(^|[^a-z])lost([^a-z]|$)/) flags = flags "lost," + if (lcell ~ /(^|[^a-z])loss([^a-z]|$)/) flags = flags "loss," + if (lcell ~ /(^|[^a-z])owe[sd]([^a-z]|$)/) flags = flags "owes," + if (lcell ~ /(^|[^a-z])live([^a-z]|$)/) flags = flags "LIVE," + sub(/,$/, "", flags) + # KEYED ON THE LANE NAME LOWER-CASED, because `lane_named_ci` is the rule + # everywhere else in this file: the register spells one lane three ways in + # a week, and the names this listing joins on come from the LOG files. + # (No apostrophe in this comment: the whole program is a single-quoted + # shell string, and one would end it.) + print tolower(lane) sep head sep flags + }' +# `--local` READS THIS CHECKOUT'S REGISTER instead of the published one, which +# is `session_ids_local_of_lane`'s source and is unioned with the published ids +# for the same fail-closed reason that read gives: an id this checkout knows and +# `origin/main` does not yet is one more reason to refuse, never to allow. +# `--cells` IS THE OTHER HALF OF THE SAME PASS: `<lane>` and the state cell-s +# head and flag words, and nothing else. It is a separate call because it is a +# separate COST — see the awk above — and the listing asks for it only where a +# row has no object log to speak for it. +lanes_register_index() { # [--local] [--cells] + lri_local=0; lri_cells=0 + while [ $# -gt 0 ]; do + case "$1" in + --local) lri_local=1; shift ;; + --cells) lri_cells=1; shift ;; + *) break ;; + esac + done + if [ "$lri_local" = 1 ]; then + { cat -- "$LANES_FILE" 2>/dev/null || : + [ -f "$LANES_ARCH_FILE" ] && { cat -- "$LANES_ARCH_FILE" 2>/dev/null || :; } + } | awk -v sep="$US" -v cells="$lri_cells" "$LANES_REGISTER_INDEX_AWK" 2>/dev/null + else + { register_text; archive_text; } | awk -v sep="$US" -v cells="$lri_cells" "$LANES_REGISTER_INDEX_AWK" + fi +} + +# SCOPE, AFTER A11 Addendum 4 RULING 6 (ratified "a11 addendum 4 yes", ruling 6 +# = NO to the workstation-scoped default): +# +# default EVERY lane the register and the logs know — clause (j) as +# written. It used to be this workstation's, and that was never in +# the contract: `window-lane` is scoped and the contract says so at +# length (`R-A11-8`/RV-T7); this read is not. "List the lanes" on a +# two-workstation estate means both. +# --here this workstation only. The old default, kept as an OPTION. +# --ws <n> a named workstation only, which implies the same narrowing. +# --all no narrowing of any kind: it CLEARS `--repo`, `--dir`, `--prefix` +# and `--here`, so a caller that has narrowed can undo it in one +# word. That is what the settlement means by "`--all` forces the +# every-lane listing". +# +# `--prefix <repo>` is the LABEL fallback and nothing more: a lane whose log +# records NEITHER a home NOR a directory cannot be filed by either, and its +# name's `<repo>-` prefix is the only thing left. Amendment 7 calls that prefix +# a label rather than a fact, so it is used ONLY where the two facts are absent +# — never to override a home that disagrees with it, which is the case +# `openRepoTools#28` says must be SAID rather than filed twice. +lanes_rows() { + lr_repo=""; lr_dir=""; lr_ws="$WS"; lr_here=0; lr_all=0; lr_one=""; lr_prefix="" + lr_closed=0 + while [ $# -gt 0 ]; do + case "$1" in + --repo) lr_repo="${2-}"; shift 2 || return 64 ;; + --dir) lr_dir="${2-}"; shift 2 || return 64 ;; + --prefix) lr_prefix="${2-}"; shift 2 || return 64 ;; + --ws) lr_ws="${2-}"; lr_here=1; shift 2 || return 64 ;; + --lane) lr_one="${2-}"; shift 2 || return 64 ;; + --here) lr_here=1; shift ;; + --all) lr_all=1; shift ;; + # AMENDMENT 19(b) — `--closed` ADDS the CLOSED and the DORMANT rows, and + # it COMBINES with everything rather than replacing it: with `--all` it is + # every repository-s closed lanes, with `--here` this workstation-s. So it + # is deliberately NOT cleared by the `--all` reset below, which exists to + # undo a NARROWING; this flag widens. + --closed) lr_closed=1; shift ;; + *) return 64 ;; + esac + done + # `--all` LAST AND ABSOLUTE, whatever order the flags arrived in — AND THAT + # INCLUDES `--lane`, which this reset used to leave standing (#26, the review + # of `c3ebcfe`). `--lane <name>` is the narrowest selector there is: the block + # below it sets `lr_names` to that one name and clears the other four filters + # for itself, so `lanes --all --lane X` answered about ONE lane under the flag + # that means every lane. The sentence above it has said "absolute" since it was + # written; this is the code catching up with it, and it is the same defect the + # wrapper's own `here_repo` had one file up (`lanes:143`, taken at `2f44da0`). + if [ "$lr_all" = 1 ]; then lr_repo=""; lr_dir=""; lr_prefix=""; lr_here=0; lr_one=""; fi + [ -n "$lr_dir" ] && lr_dir="$(cd -- "$lr_dir" 2>/dev/null && pwd -P || printf '%s' "$lr_dir")" + # ONE LANE, WITHOUT SCANNING THE ESTATE. `lane <name>` needs one row's + # `profile` and nothing else, and building the whole listing for it would walk + # every log, every row and every live session record on the workstation to + # answer a question about one lane. Same rows, same columns, same code. + # EACH NAME CARRIES ITS OWN LOWER-CASED KEY, emitted by the pass that already + # computes it for the de-duplication: the three lookups below join on that key + # and `lc` is two processes (ruling 12). + if [ -n "$lr_one" ]; then + lr_names="$(printf '%s\n' "$lr_one" | awk -v sep="$US" 'NF { print tolower($0) sep $0 }')" + lr_here=0; lr_repo=""; lr_dir=""; lr_prefix="" + else + # THE REGISTER FIRST, AND THAT IS AMENDMENT 15 (it was the logs first). + # The de-duplication has always been on the name LOWER-CASED, so for a lane + # both sources know it is the FIRST source that decides which spelling the + # listing prints — and the amendment says the register row's spelling is the + # canonical one. Read the other way round, a lane whose log file predates + # its row's spelling was listed under the file name, and column 10's + # line that binds the lane offered that spelling back to the reader. + lr_names="$( { register_lanes 2>/dev/null || :; known_lanes 2>/dev/null || :; } | awk -v sep="$US" 'NF && !seen[tolower($0)]++ { print tolower($0) sep $0 }')" + fi + [ -n "$lr_names" ] || return 8 + # ONE PASS OVER EVERY LANE'S EVENTS, NOT ONE READ PER LANE PER FIELD. + # `lanes` asks about every lane the register and the logs know, and this loop + # used to make a `git show` of each lane's log — and then a fork per sub-field + # on top. Measured on the live register: 24 s for a listing that shows ONE + # row, because the cost was the 74 lanes it filtered OUT. `state_events` is + # the stream every other state read in this file is built on, it is already + # cached for the life of the process, and `lane_row_facts` turns it into one + # line per lane carrying the six facts a row needs — `payload_subfield`'s two + # rules and `home_of_lane`'s one, applied in the same awk that parses. + # `--lane` READS ONE LOG, NOT THE ESTATE'S. `lane <name>` asks for one + # lane's profile and nothing else, and `state_events` is a `git show` per log + # file — nine seconds on the live register. The same parser over the same + # grammar either way, so the two answers cannot differ. + if [ -n "$lr_one" ]; then + lr_facts="$(lane_log_events "$lr_one" 2>/dev/null | lane_row_facts)" + else + lr_facts="$(state_events 2>/dev/null | lane_row_facts)" + fi + # AND A PUBLISHED LOG THAT COULD NOT BE READ IS NOT A LANE WITH NO LOG (#138 + # item 11). A lane absent from the facts is DORMANT below, and a log whose + # `git show` failed gave no lines; `remote_log_events` names each such log, + # and those lanes are fenced out of the class here. Without the warnings file + # (no temporary file could be made) no read can be told from a failed one, so + # no row is classed dormant at all. + lr_unread=" "; lr_unread_ok=1; lr_unread_paths="" + if [ -z "$lr_one" ] && [ -z "$LANES_IDX_DIR" ]; then + if [ -n "$SE_WARN_FILE" ]; then + lr_unread_paths="$(sed -n -e 's/^lanes-edit: unreadable log: \(.*\) — git could not read it.*$/\1/p' "$SE_WARN_FILE" 2>/dev/null)" + lr_unread=" $(printf '%s\n' "$lr_unread_paths" | awk 'NF { n = $0; sub(/^.*\//, "", n); sub(/\.md$/, "", n); print tolower(n) }' | tr '\n' ' ')" + else + lr_unread_ok=0 + fi + fi + [ -z "$lr_unread_paths" ] || + note "these published logs could not be read, so no lane of theirs is classed DORMANT: $(printf '%s\n' "$lr_unread_paths" | tr '\n' ' ')" + [ "$lr_unread_ok" = 1 ] || + note "no temporary file could be made for the read's warnings, so whether any published log failed to read is not known, and no row is classed DORMANT here." + # AND A REGISTER THAT COULD NOT BE READ IS SAID, ONCE (the re-review of #230). + # Every row above came out of `register_text`, which drops the status + # `register_text_checked` keeps (#67), and a published register git cannot + # read renders as no text, so those rows simply vanished — and the sweep + # counted none of them. The class is withheld, which `lane-end` refuses on. A + # read that succeeds fills the cache every later read here takes, so the + # check costs one render. + lr_reg_ok=1 + register_text_checked >/dev/null 2>&1 || lr_reg_ok=0 + [ "$lr_reg_ok" = 1 ] || + note "the register ($LANES_PATH, published or this checkout's) could not be read, so its rows are not in this listing, and no row is classed DORMANT here." + # THE REGISTER AND THE LIVE RECORDS, EACH READ ONCE FOR THE WHOLE LISTING + # (ruling 12). Both were per-lane before, and `live_session_ids` was rebuilt + # from 564 session records for every one of them. + # THE THREE TABLES, FENCED FOR AN IN-SHELL LOOKUP (ruling 12). `tr` turns each + # newline into `$GS` once, and `table_lookup` then finds any lane's line with + # one parameter expansion — instead of `printf | awk` per lane per table, + # which for fifty lanes was a hundred and fifty processes spent reading + # strings this shell was already holding. + # AN ARCHIVE THAT CANNOT BE READ IS SAID, NOT SWALLOWED (Copilot round 2 on + # #93). The two pipelines below end in `awk`, whose status is its own, so a + # failed `archive_text` inside them is invisible — and what goes missing is + # the CLOSED rows the archive holds. A listing may not refuse (it sits in + # front of a launch), so it says it, exactly as it says a session-record read + # that failed; the POSITION is the half that must not guess, and + # `lane_next_free` refuses there rather than offering one over a partial read. + if ! archive_text >/dev/null 2>&1; then + note "$LANES_ARCH_PATH exists and could not be read, so the RETIRED rows it holds are not in this listing — and \`next-free\` will refuse a position rather than offer one over a partial read." + fi + lr_index="$GS$(lanes_register_index 2>/dev/null | tr '\n' "$GS" || :)" + # THE CELLS ARE BUILT ON FIRST USE AND NOT BEFORE (see `lanes_register_index + # --cells`): a listing whose every row has an object log never asks for them, + # and the two passes that build them are two `awk`s over a register this + # function has already rendered once. + lr_cells=""; lr_lcells=""; lr_cells_built=0 + lr_local_index="$GS$(lanes_register_index --local 2>/dev/null | tr '\n' "$GS" || :)" + lr_facts_t="$GS$(printf '%s\n' "$lr_facts" | tr '\n' "$GS")" + # THE LIVE SCAN, AND WHAT A LISTING DOES WHEN IT FAILS (#26, the review of + # `37632b1`). NOT a refusal: this listing is the read a person makes IN FRONT + # OF A LAUNCH, and `43b6320`'s rule for the fetch is the rule here — it + # answers, and says what it could not establish. What it must never do is + # print a lane's log verb as its STATE in silence, because a lane that is + # LIVE then shows as IDLE or PAUSED and the row offers the `restart` line that + # would start a second session on it. The collision itself is still refused + # one surface along: `lane-start`'s own `live_holder` reads these same records + # DIRECTLY and exits 1 where they cannot be read. + lr_live_rows=""; lr_live_rc=0 + lr_live_rows="$(live_session_ids 2>/dev/null)" || lr_live_rc=$? + lr_fork_rc=0 + lr_live_fence=" $(printf '%s\n' "$lr_live_rows" | awk -F"$US" 'NF { print tolower($1) }' | tr '\n' ' ')" + lr_ws_short="$(short_ws "$lr_ws")" + lr_now="$(date -u +%s)" + # AMENDMENT 18(b), FOR THE PARTITION — computed ONCE for the whole listing, + # because `lc` is two processes and this is asked of every lane. The row + # carries the BINDING-s host and container (lower-cased by the awk above) and + # this is what they are compared against. + LANES_HOST_LC="$(lc "$LANES_HOST_NAME")" + LANES_WS_LC="$(lc "$WS")" + LANES_CONTAINER_LC="$(lc "$LANES_CONTAINER_NAME")" + # AND THE TWO NARROWING FILTERS' OWN SIDES, for the same reason: `--repo` and + # `--prefix` do not change from one lane to the next, and the loop below asked + # `lc` for both of them again for every lane in the estate (#107). The lane's + # side is per lane and goes through `lower_into`, which is `lc` without a fork. + lr_repo_lc=""; [ -z "$lr_repo" ] || lr_repo_lc="$(lc "$lr_repo")" + lr_prefix_lc=""; [ -z "$lr_prefix" ] || lr_prefix_lc="$(lc "$lr_prefix")" + # ONLY A LANE THE FORK MAP NAMES CAN HAVE A FORK (ruling 12). `lane_forks` + # stays the ONE implementation of what a fork is and what disqualifies one; + # this simply declines to ask it about the forty-five lanes of this estate + # that no live transcript is titled for, each of which cost a subshell, a + # `cat` of the map and a `grep` to be told nothing. + lr_fork_map="" + lr_fork_map="$(fork_map 2>/dev/null)" || lr_fork_rc=$? + lr_fork_titles=" $(printf '%s\n' "$lr_fork_map" | awk -F"$US" 'NF { print $1 }' | tr '\n' ' ')" + # THE LOG FILES THIS CHECKOUT HAS, LOWER-CASED, AS ONE FENCE (Copilot round 4 + # on #93). `state_events` reads the PUBLISHED logs (R19), so a log committed + # here and not yet pushed is not in the facts pass at all — and DORMANT is + # "no object log", which that lane has. The sweep reads the local log for + # exactly this reason since round 3, and the read and the writer may not + # disagree about the amendment's own condition. One `ls` for the whole + # listing, matched with a `case` per lane, and lower-cased because a lane name + # is ONE name under any case (Amendment 15). + # AND A DIRECTORY THAT IS THERE AND CANNOT BE LISTED IS NOT ONE WITH NO LOG IN + # IT (#138 item 4): the fence would be empty and a lane whose only log is here + # classed DORMANT. It is said, and no row is classed dormant over it below. + lr_logfiles=""; lr_logs_rc=0 + if [ -e "$LANES_LOG_DIR" ]; then + lr_logfiles="$(ls -- "$LANES_LOG_DIR" 2>/dev/null)" || lr_logs_rc=1 + fi + lr_logfiles=" $(printf '%s\n' "$lr_logfiles" | awk '{ print tolower($0) }' | tr '\n' ' ')" + [ "$lr_logs_rc" = 0 ] || + note "$LANES_LOG_DIR exists and could not be listed, so whether a row has a log this checkout has and origin has not is not known, and no row is classed DORMANT here. Fix the read and re-run before sweeping." + if [ "$lr_live_rc" != 0 ] || [ "$lr_fork_rc" != 0 ]; then + note "this workstation's session records could not be read, so the STATE column below is the LOG's verb alone: a lane that is live may show as IDLE or PAUSED here, and no fork of any lane is established either way. Fix the read and re-run before acting on a restart line." + fi + lr_out="" + while IFS="$US" read -r lr_ll lr_l; do + [ -n "$lr_l" ] || continue + lr_verb=""; lr_utc=""; lr_w=""; lr_d=""; lr_pf=""; lr_win=""; lr_home=""; lr_logsid=""; lr_obj="" + # DOES THIS LANE HAVE AN OBJECT LOG AT ALL? `lane_row_facts` emits a line + # for every lane whose log carries one of Amendment 7-s five lane verbs, so + # this lookup — which the listing makes anyway — is the answer, and + # Amendment 19(a)-s DORMANT is built on it below. + lr_lanekind=0 + lr_bhost=""; lr_bcont=""; lr_blegacy="" + if table_lookup "$lr_facts_t" "$lr_ll"; then + lr_lanekind=1 + IFS="$US" read -r lr_fl lr_verb lr_utc lr_w lr_d lr_pf lr_win lr_home lr_logsid lr_obj \ + lr_bhost lr_bcont lr_blegacy <<EOF2 +$LOOKUP_OUT +EOF2 + fi + # THE ROW'S THREE FACTS, OUT OF THE ONE PASS: is there a row at all, whose + # workstation it names, and which transcript uuids its session cell carries. + # AND ITS `started` CELL (Amendment 19(b)), which `--closed` prints for a + # CLOSED row as well as a dormant one and which is a date rather than free + # text. Its state cell's HEAD and FLAGS are NOT here — they are the one + # table this loop does not walk per lane, and they are fetched below the + # narrowing filter for the rows that have no log to speak for them. + lr_ixl=""; lr_rw=""; lr_rws=""; lr_ids_sp=""; lr_start=""; lr_was=""; lr_flags="" + if table_lookup "$lr_index" "$lr_ll"; then + IFS="$US" read -r lr_ixl lr_rw lr_rws lr_ids_sp lr_start <<EOF2 +$LOOKUP_OUT +EOF2 + fi + lr_lixl=""; lr_lrw=""; lr_lrws=""; lr_lids_sp=""; lr_lstart=""; lr_lwas=""; lr_lflags="" + if table_lookup "$lr_local_index" "$lr_ll"; then + IFS="$US" read -r lr_lixl lr_lrw lr_lrws lr_lids_sp lr_lstart <<EOF2 +$LOOKUP_OUT +EOF2 + fi + # THE PUBLISHED ROW-S WORDS WIN AND THIS CHECKOUT-S ANSWER ONLY FILLS IN + # (R19): a row this checkout has added and not yet pushed has no published + # text at all, and showing nothing about it would hide the newest row on the + # workstation that made it. + [ -n "$lr_start" ] || lr_start="$lr_lstart" + # THE REGISTER'S OWN WORKSTATION COLUMN WINS where the row has one: it is + # what every other read in this file compares, and a lane may have a row + # here and its last log line from another machine. + [ -n "$lr_rw" ] && lr_w="$lr_rw" + if [ "$lr_here" = 1 ] && [ -n "$lr_w" ]; then + lr_wcmp="$lr_rws"; [ -n "$lr_wcmp" ] || lr_wcmp="$(short_ws "$lr_w")" + [ "$lr_wcmp" = "$lr_ws_short" ] || continue + fi + lr_row="$lr_ixl" + if [ -n "$lr_home" ]; then + lr_hc="$(alias_lookup "$lr_home" 2>/dev/null || :)" + [ -n "$lr_hc" ] && lr_home="$lr_hc" + fi + if [ -n "$lr_repo" ] || [ -n "$lr_dir" ] || [ -n "$lr_prefix" ]; then + lr_keep=0 + if [ -n "$lr_repo" ] && [ -n "$lr_home" ]; then + lower_into "$lr_home" + [ "$LOWER_OUT" = "$lr_repo_lc" ] && lr_keep=1 + fi + [ -n "$lr_dir" ] && [ -n "$lr_d" ] && [ "$lr_d" = "$lr_dir" ] && lr_keep=1 + # THE LABEL, AS A THIRD OR-TERM. Amendment 7 calls a lane name's + # `<repo>-` prefix a LABEL rather than a fact, and the home is what FILES + # a lane — but a listing is asked "which lanes are this repository's", and + # two populations answer that and are missed by home and `dir` alike: + # * a lane with a ROW AND NO LOG, which this estate has, whose home and + # directory are simply not recorded anywhere yet; + # * a lane a person NAMED for this repository whose log records a + # different home — the disagreement `openRepoTools#28` says to SAY + # rather than resolve, and still a position `lane-start <repo> <n>` + # cannot hand out twice. + # It never overrides a home: a lane matched only by its label is LISTED, + # not re-homed. + if [ "$lr_keep" = 0 ] && [ -n "$lr_prefix" ]; then + lower_into "$lr_l" + case "$LOWER_OUT" in "$lr_prefix_lc"-*) lr_keep=1 ;; esac + fi + [ "$lr_keep" = 1 ] || continue + fi + # FAILING THE CELL, THE LANE'S OWN LOG — clause (d) rule 3, out of the same + # one pass rather than a second read of the same stream. + lr_sid="${lr_ids_sp##* }" + [ -n "$lr_sid" ] || lr_sid="$lr_logsid" + # THE STATE. A live record naming one of the lane-s ids beats the log-s + # own last verb, because a lane whose session is running is LIVE whatever + # its last written line says; otherwise the verb answers. + # + # A `case` OVER A SPACE-FENCED STRING, AND NOT A `grep` PER RECORD (ruling + # 12): this ran `printf | grep -qx` once for every live record for every + # lane. The fence is built once above; the lookup of the WINDOW is an awk, + # and it only happens for a lane that is actually live. + # THE IDS OF BOTH ROWS, AND THAT IS FAIL-CLOSED (Copilot round 1 on #93). + # The published cell is R19's source for everything else here, but a lane + # whose `append-session-id` has landed in THIS checkout and not yet been + # pushed has its current transcript in the local row alone — and + # `live_session_ids` can see that very session running. Read from the + # published cell only, such a lane is not LIVE, which under Amendment 19(a) + # makes it DORMANT: hidden from the listing and offered to the sweep while + # somebody is working in it. Both sets are asked, and either one naming a + # live record is LIVE. + lr_state="" + lr_live_win="" + for lr_one_id in $lr_ids_sp $lr_lids_sp; do + case "$lr_live_fence" in + *" $lr_one_id "*) + lr_state=LIVE + lr_live_win="$(printf '%s\n' "$lr_live_rows" | awk -F"$US" -v i="$lr_one_id" 'tolower($1) == i { print $2; exit }')" + break ;; + esac + done + if [ -n "$lr_live_win" ]; then + lr_win="$lr_live_win" + elif [ -n "$lr_win" ]; then + # SPEC rev 4 §15 column 5: the window is marked `gone` where the ref no + # longer resolves. After a tmux server restart that is EVERY recorded + # window on the workstation — measured on Eagle at 15:5xZ on 2026-09-13, + # 0 of 5 — and a column that showed a dead ref as though it were live is + # the column a person would try to attach to. + lr_wref="${lr_win%% *}" + [ -n "$(tmux_window_field "$lr_wref" '#{window_id}' 2>/dev/null || :)" ] || lr_win="$lr_win (gone)" + fi + if [ -z "$lr_state" ]; then + case "$lr_verb" in + PAUSED) lr_state=PAUSED ;; + ENDED) lr_state=ENDED ;; + RETIRED) lr_state=RETIRED ;; + STARTED|RESUMED) lr_state=IDLE ;; + *) lr_state="$([ -n "$lr_row" ] && printf 'NO LOG' || printf 'UNKNOWN')" ;; + esac + fi + # THE STATE CELL-S HEAD AND FLAGS, FOR THE ROWS THEY ARE ABOUT — a row with + # NO OBJECT LOG (Amendment 19(a)). It is the only row whose cell is all the + # listing has: one with a log has the log, and `lanes` prints neither field + # for it. The lookup is HERE, below the narrowing filter, because a row this + # listing is not showing is a row it may not pay for — and it walks a table + # of its own rather than the one above, which every lane in the estate walks + # once (ruling 12: the measurement is in `LANES_REGISTER_INDEX_AWK`). + # + # AND A ROW THE CELLS PASS DID NOT SEE IS NOT A ROW WITH NO CELL. The two + # passes read ONE register text, so every row in the table above is in this + # one; a row in the first and not the second is a read that answered + # differently the second time, and an EMPTY cell read as an answer would + # make `mig_cell_is_phrase` false and class the row DORMANT — hiding a row + # whose cell may say PAUSED and offering it to the sweep, which is the one + # thing 13(a) is in this rule for. `lr_cellrow` carries whether the pass saw + # it, and the class below is not decided without it (Amendment 7(d), the + # same posture round 3 gave the liveness read). It is the PUBLISHED pass + # that carries it, because the published row is the only one the class is + # ever decided on — `lr_row` is `lr_ixl` and a row this checkout alone has + # is in no class either way. + lr_cellrow=0 + if [ "$lr_lanekind" = 0 ] && [ -n "$lr_ixl$lr_lixl" ]; then + if [ "$lr_cells_built" = 0 ]; then + lr_cells="$GS$(lanes_register_index --cells 2>/dev/null | tr '\n' "$GS" || :)" + lr_lcells="$GS$(lanes_register_index --local --cells 2>/dev/null | tr '\n' "$GS" || :)" + lr_cells_built=1 + fi + if table_lookup "$lr_cells" "$lr_ll"; then + lr_cellrow=1 + IFS="$US" read -r lr_was lr_flags <<EOF2 +$LOOKUP_OUT +EOF2 + fi + if table_lookup "$lr_lcells" "$lr_ll"; then + IFS="$US" read -r lr_lwas lr_lflags <<EOF2 +$LOOKUP_OUT +EOF2 + fi + [ -n "$lr_was" ] || lr_was="$lr_lwas" + [ -n "$lr_flags" ] || lr_flags="$lr_lflags" + fi + # ------- AMENDMENT 19(a): THE TWO STATES BELOW PARKED, AND WHO IS IN THEM + # + # CLOSED is a lane whose own log has FINISHED — its last lane-kind line is + # `ENDED` or `RETIRED`, which is exactly what the block above has just put + # in `lr_state`. DORMANT is a row with NO OBJECT LOG and no live session + # here: the fourteen rows of openxFactory that ran before Amendment 7 gave + # every lane a log, that no `lane-end` can close because it wants a live + # session or a log to write into, and that sat at the top of every `lanes` + # while the next free position was read past them. + # + # "NO OBJECT LOG" IS ASKED OF THE FACTS TABLE AND NOT OF THE FILESYSTEM: + # `lr_lanekind` is that lookup, made once at the top of this loop, where a + # `git cat-file` per lane would have the listing pay for the whole estate to + # answer about the rows it is going to hide. + # + # AND THE REGISTER-S OWN CLAIM IS HONOURED (Amendment 13(a): the row says + # where a lane IS, in one line). A cell that is the phrase and whose state + # word is neither `ENDED`, `RETIRED` nor the migration-s `MIGRATED` says the + # lane is somewhere — PAUSED, LANDING, HANDED OFF — and hiding that row + # would hide a lane a person can still pick up, which is the opposite of + # what this amendment is for. It is the one way a row with no log is NOT + # dormant, and `mig_cell_is_phrase` is the same test the migration makes of + # the same cell rather than a second reading of it. + lr_class="" + case "$lr_state" in + ENDED|RETIRED) lr_class=closed ;; + LIVE) : ;; + *) + # AND NEVER OVER A LIVENESS READ THAT FAILED (Copilot round 3 on #93). + # DORMANT is "no object log AND no live session on this workstation"; + # where the session records could not be read, the second half was never + # established, and hiding the row on it would hide a lane somebody may + # be working in. The listing already SAYS the read failed (one screen + # up); this is what it does about it — leaves the class unset, so the + # row stays listed and the sweep is never offered it. + if [ -n "$lr_row" ] && [ "$lr_lanekind" = 0 ] && [ "$lr_live_rc" = 0 ] && + [ "$lr_cellrow" = 1 ] && [ "$lr_logs_rc" = 0 ] && [ "$lr_unread_ok" = 1 ] && + [ "$lr_reg_ok" = 1 ]; then + lr_class=dormant + # A LOG THIS CHECKOUT HAS AND `origin` HAS NOT IS STILL AN OBJECT LOG, + # AND SO IS ONE `origin` HAS AND GIT COULD NOT READ (item 11). + case "$lr_logfiles" in + *" $lr_ll.md "*) lr_class="" ;; + esac + case "$lr_unread" in + *" $lr_ll "*) lr_class="" ;; + esac + if mig_cell_is_phrase "$lr_was"; then + case "${lr_was%% · *}" in + ENDED|RETIRED|MIGRATED) : ;; + *) lr_class="" ;; + esac + fi + fi ;; + esac + # NEITHER IS LISTED BY DEFAULT (clause (b)) and `--closed` adds them back. + # `--lane <name>` IS NEVER FILTERED: it is the narrowest selector there is + # and its caller has NAMED the lane, so a closed lane asked about by name + # answers about itself instead of reading as a lane that does not exist — + # which is what `lane <name>`, `lane-start` and the handoff would all have + # been told by an empty answer. + if [ -n "$lr_class" ] && [ "$lr_closed" = 0 ] && [ -z "$lr_one" ]; then continue; fi + # THE ROW'S OWN STATE, WHERE THE LOG HAS NONE TO GIVE (#89, out of the + # suppressed comments of Copilot's review of #82). Amendment 13(a) makes the + # state cell the lane's CURRENT STATE, and `migrate-state-cells` leaves + # exactly that behind: the phrase in the cell and, in the log, NOTED lines + # and no lane-kind line at all. So the STATE above said `NO LOG` over a cell + # saying `PAUSED`, and the one column the amendment exists to make + # authoritative was the one column this listing did not consult. Where the + # log gave no answer and `mig_cell_is_phrase` proves the cell is the phrase + # — the same test the migration and the class above make of the same cell — + # the STATE is the cell's word with ` (row)` after it. + # + # ` (row)` IS PART OF THE WORD, AND THAT IS THE POINT: the word is SHOWN and + # never bound. A row with no lane-kind line records no directory, no profile + # and no binding, so there is nothing for `lane` to resume — and every + # reader that keys on the log's own `PAUSED` (column 10 below, `lane_groups`, + # the `bind it:` line of `lanes`) passes this word by without a change of + # its own. `lane_groups` files it `rowonly`, and `lane` refuses that group by + # name rather than launching on a word no log wrote. + # + # FOUR WORDS STAY `NO LOG`. `ENDED`, `RETIRED` and the migration's + # `MIGRATED` are the cells of Amendment 19(a)'s DORMANT rows, which 19(b) + # shows as `NO LOG` with that cell's head on a line of its own. And `LIVE` is + # the one case that is NOT symmetric: a cell cannot prove a session is + # running, only a live record can, and the read above has already been + # asked — a row it did not find live whose cell still says `LIVE` is the row + # column 17 flags, and a STATE column saying so would tell a person a lane + # is running that nothing has proved is. + # + # BELOW THE CLASS, ON PURPOSE: the cell is read only for a row with no object + # log and only below the narrowing filter (ruling 12), and the class is the + # LOG's question, decided on the log's answer before this changes the word. + if [ "$lr_state" = 'NO LOG' ] && mig_cell_is_phrase "$lr_was"; then + case "${lr_was%% · *}" in + LIVE | ENDED | RETIRED | MIGRATED) : ;; + *) lr_state="${lr_was%% · *} (row)" ;; + esac + fi + [ -n "$lr_obj" ] || lr_obj="none open" + lr_age="$([ -n "$lr_utc" ] && age_of "$lr_utc" "$lr_now" || printf 'age unknown')" + # THE TWO SETS `lane_forks` WOULD OTHERWISE RE-READ THE REGISTER FOR, handed + # to it out of the one pass this loop already made (ruling 12) — and asked + # at all only where a live transcript carries this lane's title. + lr_fk=0 + case "$lr_fork_titles" in + *" $lr_ll "*) + lr_fk="$(lane_forks "$lr_l" " $lr_ids_sp $lr_lids_sp " 2>/dev/null | grep -c . || :)" + case "$lr_fk" in ''|*[!0-9]*) lr_fk=0 ;; esac ;; + esac + # `none` AND NEVER A DASH, because three of these columns are `none` on + # this estate until adoption act 7 cuts each lane over — `profile`, + # `directory` and the `<@id>` half of `window` all come from records written + # under clause (c), and 0 of the 5 swap records on Eagle carry any of them. + # A word a reader can act on beats a glyph they have to interpret. + # COLUMN 10 — THE LINE THAT BINDS THE LANE — IS THE READ'S AND NOT A + # RENDERER'S (A11 Addendum 4 ruling 7). Clause (j) gives TEN columns in + # order and this carried nine; `lanes` computed the tenth and `restart` + # computed a different tenth, which is two implementations of one column and + # is how they would come to disagree about which lane may be restarted. + # + # THE WORD IS `lane <name>` (Amendment 18 Addendum 2, ratified + # 2026-09-14T16:50:32Z verbatim "ratify"): `restart` is no longer a command + # a person is given, and `lane <name>` is the same act — the launcher's + # path, the lane's own recorded directory and profile, asking nothing — + # plus the pick, the attach and the elsewhere branch. A column naming a word + # that is not on the person's PATH is a column they cannot type. + # + # A PAUSED LANE ONLY (clause (j) column 10, F-X20), and a PAUSED lane whose + # record carries NO `profile` gets the form that works today with the + # profile named as the one token the operator must supply — because a wrong + # profile is a launch into another account and nothing here may guess one, + # while a line that cannot be typed is worse than a column that says + # `none`. Every other state gets `none`: a lane whose last act was its last + # is not a lane a person restarts. + # + # AND A **LIVE** LANE'S ONE ACT IS THE ATTACH, FILLED IN (Amendment 18 + # clause (i), refined on the question Brett Heap asked 2026-09-14T13:47Z — + # verbatim *"how do i start claude with that profile and that lane? do i use + # lane command?"*, about a lane live in a DETACHED tmux session, where the + # listing named the session and no act). A live lane is never started a + # second time: clause (h) is one live process per transcript, and a + # `lane-start` or a `pclaude` on a running lane is exactly the second one. + # So the column carries `tmux switch-client` inside tmux and `tmux attach` + # outside it — the same two acts `lane`'s LIVE HERE branch performs, which + # is why the CHOICE between them is made here, in the read both surfaces + # share, and not in a renderer. + # + # THE TARGET IS `<session>:<@id>` WHERE THE RECORD KNOWS AN ID, and the + # session alone where it does not. Measured on this estate 2026-09-14 (tmux + # 3.4, private socket): `attach -t dst:@2` attached AND made `@2` current in + # ONE act, while `attach -t <session>` lands on whatever that session has + # since made current — another lane, which is the one thing the + # id-AND-session fence exists to stop. A bare session is still what a record + # with no `@id` can offer, and it is offered as that. + lr_restart=none + if [ "$lr_state" = PAUSED ]; then + if [ -z "$lr_pf" ] || [ "$lr_pf" = none ]; then + lr_restart="pclaude --lane $lr_l <profile>" + else + lr_restart="lane $lr_l" + fi + elif [ "$lr_state" = LIVE ]; then + # THE WINDOW COLUMN HAS TWO SHAPES AND BOTH REACH HERE. A LIVE row takes + # it from the live session record, whose `tmux` field is + # `<session>:<@id>.<%pane>`; every other row takes it from the log, whose + # `window` sub-field is Amendment 11(c)'s TWO space-separated refs, + # `<session>:<index> <@id>`. Reading one for the other is how this column + # would offer `tmux attach -t <session>:<index>` — an index another window + # can be given between the read and the act, which is exactly what the + # id-AND-session rule exists to stop. + lr_wref="${lr_win%% *}" + lr_attid="" + case "$lr_win" in *' @'*) lr_attid="${lr_win##* }" ;; esac + if [ -z "$lr_attid" ]; then + lr_wtmp="${lr_wref%%.*}" + case "${lr_wtmp#*:}" in @[0-9]*) lr_attid="${lr_wtmp#*:}" ;; esac + fi + lr_att="${lr_wref%%:*}" + [ -z "$lr_attid" ] || lr_att="$lr_att:$lr_attid" + case "${lr_win:-none}" in + none | *'(gone)'*) : ;; + *) + if [ -n "${TMUX:-}" ]; then lr_restart="tmux switch-client -t $lr_att" + else lr_restart="tmux attach -t $lr_att" + fi ;; + esac + fi + # COLUMN 13 — WHETHER THIS PLACE MAY PRONOUNCE ON THAT BINDING, and it is + # the READ-s answer and not a renderer-s (Copilot round 1 on this PR; the + # rule A11 Addendum 4 ruling 7 gave column 10). `lane-groups` filed an + # `IDLE` row as AVAILABLE on the workstation column alone — and an IDLE row + # is a binding THIS host could not see a live record for, which across a + # container seam is exactly the lane that IS running: two benches on one + # host share the profile directory, so the pick offered another container-s + # live lane and the launch made a second process on it. `here` is Amendment + # 18(b)-s only place liveness may be pronounced from; a pre-clause line is + # matched on the host alone, which is clause (a)-s cutover sentence; and + # `none` is a lane with no binding line at all, which changes nothing about + # how it was filed before this column existed (it was EMPTY until Amendment + # 19-s four columns came after it — see below for why it cannot be now). + # AND ONLY WHERE THERE IS A BINDING TO BE LOCAL TO. The binding fields come + # from the last `STARTED`/`RESUMED` whatever released it since, so a PARKED + # lane still carries the host and container of the place that last ran it — + # and a lane parked in another container is AVAILABLE here, because parking + # IS the handoff (asserted since Amendment 18 Addendum 1). Column 13 means + # *the locality of a binding that stands*, and is `none` where none does. + lr_local="" + case "$lr_verb" in STARTED|RESUMED) : ;; *) lr_bhost="" ;; esac + if [ -n "$lr_bhost" ]; then + lr_local=elsewhere + # THE RULE IS `binding_is_here`-s AND NOT A SECOND COPY OF IT (Copilot + # round 2 on openRepoTools#83 read the two and found them already + # diverging). The `_lc` form is the same function with the two `lc` forks + # taken off the front, because the awk above has lower-cased these values + # already and this is asked of every lane in the listing. + binding_is_here_lc "$lr_bhost" "$lr_bcont" "$lr_blegacy" && lr_local=here + fi + # COLUMNS 14 TO 17 ARE AMENDMENT 19-S, AND THEY GO AFTER AMENDMENT 18(b)-S + # 13 for the reason `swapped_lanes` gives its sixth and seventh: the first + # field before the first tab is the contract every reader of this output + # takes, and each of the others is read by its own index. 14 is the CLASS — + # `closed`, `dormant` or `none` — so that the sweep and the listing + # partition the rows ONE way; 15 the row-s `started` cell, 16 its state + # cell-s head and 17 the flag words found in the whole of that cell. + # + # AND NO COLUMN IS EMPTY, 13 INCLUDED, because three readers take this row + # with `IFS=<tab> read`, and a tab is IFS WHITESPACE: two in a row are ONE + # separator, so an empty 13 would hand 14 to the variable named for 13 and + # every field after it to the one before. A row with no standing binding + # says `none` there, which `lane_groups` files exactly as it filed empty — + # only `elsewhere` changes the group. + lr_out="${lr_out}${lr_utc:-0000}${US}${lr_l} ${lr_state} ${lr_w:-unknown} ${lr_pf:-none} ${lr_win:-none} ${lr_sid:-none} ${lr_d:-none} ${lr_obj:-none} ${lr_age} ${lr_restart} ${lr_home:-none} ${lr_fk} ${lr_local:-none} ${lr_class:-none} ${lr_start:-unknown} ${lr_was:-none} ${lr_flags:-none} +" + done <<EOF +$lr_names +EOF + [ -n "$lr_out" ] || return 8 + printf '%s' "$lr_out" | LC_ALL=C sort -t"$US" -k1,1r | awk -F"$US" 'NF >= 2 { print $2 }' +} + +# --------------------- AMENDMENT 18 ADDENDUM 1: THE PICK'S TWO READS --------- +# +# `lane` (Addendum 1 (i-1), ratified 2026-09-14T14:05:54Z verbatim "ratify the +# addendum") renders THE SAME ROWS `lanes` renders — in three groups, with a +# number in front of each. Neither the grouping nor the next free position is +# that word's own: both are computed HERE, over the rows `lanes_rows` printed, +# because two surfaces computing one answer is how they come to disagree. That +# is the rule clause (h) already gives `window-lane` and `session-lane`, and the +# one A11 Addendum 4 ruling 7 gave column 10 after `lanes` and `restart` had +# each computed a restart line of its own. +# +# ROWS ON STDIN, like `sibling-filter` one screen down: the caller has already +# made the read and paid for it, and a subcommand that read the register a +# second time would double the cost of every pick to answer a question about +# the rows already in its hand. Neither of these two reads the register, the +# logs, the session records or the network at all. + +# THE PARTITION, AND IT IS THE STATE COLUMN'S (clause (i-2)): +# +# available PARKED — a lane nobody holds — or A BINDING THIS HOST PROVES +# DEAD: a lane whose last verb was STARTED or RESUMED, on this +# workstation, with no live session record naming any of its ids. +# `lanes_rows` has already made that proof, and it is the whole +# difference between its `LIVE` and its `IDLE`. +# live LIVE: a live session record on this workstation names one of the +# row's ids. The act is the ATTACH and never a second process. +# elsewhere a binding this host CANNOT prove dead, because the row is +# another workstation's: the session records are local files, so +# saying NOT LIVE about Raven from Eagle would be a claim this +# machine has no way to make. Clause (c)'s handoff question. +# rowonly NOT A PICK: a STATE `lanes_rows` read out of the row's own +# 13(a) cell, `<WORD> (row)`, because the log has no lane-kind +# line to give one (#89). Shown by `lanes`, never numbered by +# `lane`, and refused by name — there is no log to resume from. +# +# CLOSED AND DORMANT LANES LEAVE THE PICK (Amendment 19). A lane whose last act +# was its last is not a lane a person picks, and a pick that offered one would +# be offering to reopen something closed on purpose. `ENDED` and `RETIRED` are +# that set in today's vocabulary and `CLOSED`/`DORMANT` are the words the rows +# take under #42; both are named here, so the pick is right under either and +# the word does not have to move when the read does. They are still ROWS in +# `lanes`, which is the READ — this is a pick. +lane_groups() { # <workstation> ; rows on stdin + awk -F'\t' -v me="$(short_ws "${1:-$WS}")" ' + NF >= 3 { + st = $2 + # THE CLASS FIRST, AND THAT IS AMENDMENT 19 ARRIVING IN COLUMN 14 — 13 is + # Amendment 18(b)-s, which landed first (Copilot round 2 on #93). A DORMANT row-s STATE is `NO LOG`, which is in no list + # below, so the state test alone let one through wherever the rows come + # from a read that does not hide them — `lanes --closed`, and `lane + # <name>`-s own `--lane` read, which is never filtered because its caller + # named the lane. The class is the read-s answer to exactly this question. + cls = (NF >= 14 ? $14 : "") + if (cls == "closed" || cls == "dormant") next + if (st == "ENDED" || st == "RETIRED" || st == "CLOSED" || st == "DORMANT") next + # A STATE READ OUT OF THE ROW-S OWN CELL IS SHOWN AND NEVER PICKED (#89). + # `lanes_rows` prints `<WORD> (row)` for a row whose log has no lane-kind + # line and whose cell is Amendment 13(a)-s phrase, and such a row records + # no directory, no profile and no binding: there is no log to resume it + # from. It is in none of the three groups, so the pick never numbers it, + # and `rowonly` is the group `lane <name>` refuses by name. Asked BEFORE + # the workstation, because a row with no log on this workstation was + # filed AVAILABLE on that column alone. + if (st ~ / \(row\)$/) { print "rowonly" "\t" $0; next } + w = tolower($3); sub(/\..*$/, "", w) + # COLUMN 13 IS THE READ-S OWN ANSWER to *"may this place pronounce on that + # binding"* (Amendment 18(b)), and an `IDLE` row is exactly the row that + # needs it: IDLE means THIS host saw no live record for the lane-s ids, + # and across a container seam that is the lane that IS running — two + # benches on one host share the profile directory, so the pid the record + # names is in the other one-s namespace. Filed on the workstation column + # alone, such a row was offered as AVAILABLE and the launch made a second + # process on a live lane (Copilot round 1 on openRepoTools#83). + # + # AN EMPTY OR `none` COLUMN 13 IS A ROW WITH NO BINDING LINE AT ALL — a lane + # with a row and no log, or a `lanes-edit.sh` predating this column (the + # read says `none` since Amendment 19 put columns after it) — and it is + # filed exactly as it was before the column existed, which is Amendment + # 7(i)-s cutover rule for a field a reader may simply not have. + loc = (NF >= 13 ? $13 : "") + # AND IT IS ASKED BEFORE THE STATE, INCLUDING OF A `LIVE` ROW (Copilot + # round 2 on openRepoTools#83). `LIVE` is a live session record HERE + # naming one of the row-s ids — and a record written in another container + # is readable here while the pid it names is in another namespace, so a + # `kill -0` that answers is answering about some other process. Clause (b) + # gives that binding to the place it is in: from here it is UNKNOWN, the + # act is clause (c)-s request, and the attach stays available to a person + # because `lane`-s elsewhere branch names it wherever that window is live + # on this tmux server. Column 13 is `none` where no binding stands, so a + # PARKED lane of another container is untouched by this and is AVAILABLE, + # because parking IS the handoff. + if (loc == "elsewhere") g = "elsewhere" + else if (st == "LIVE") g = "live" + else if (st == "PAUSED") g = "available" + else if (w == me) g = "available" + else g = "elsewhere" + print g "\t" $0 + }' +} + +# THE NEXT FREE POSITION, over those same rows: clause (i-1)'s `f` answer, and +# the footer `lanes` has printed since Brett Heap's settlement of +# 2026-09-13T20:38:11Z. It is the LOWEST one NO ROW HOLDS and never the highest +# plus one, because handing out 12 while 3 has never been used grows a column +# nobody reads — and `lane-start` refuses a position that is taken, so this is a +# suggestion with a guard behind it and never an assertion. +# +# A POSITION A LANE HAS HELD IS RESERVED, ENDED AND RETIRED ROWS INCLUDED +# (Copilot round 7 on #45, `lanes-edit.sh:4839`, where this paragraph said +# positions "come back as lanes end" and the code has never done that). EVERY +# row on stdin is taken, whatever its state, and that is deliberate: a lane's +# identity is its name, its object log is `lanes/log/<lane>.md` and it is +# APPEND-ONLY, so a second lane at a retired position would write its life into +# the first one's file and every read of that log — who holds what, when it was +# claimed, which session paused it — would answer for two lanes at once. The +# register's row is the same story in one line. Positions are cheap; identities +# are not. +# +# A POSITION IS DIGITS WITH AN OPTIONAL TRAILING LETTER, which is +# `lane-start`'s own rule: `5a` and `5` are one position taken twice, because a +# lane may be re-cut and a re-cut position is not free, and it is the only +# reading under which `openxfactory-4-opendox-extraction` has no position at +# all. The comparison is case-insensitive on both sides, like every other lookup +# of a lane name in this file (Amendment 15). +# EVERY ROW OF THE REGISTER AND OF THE ARCHIVE, AS BARE NAMES — the rows the +# listing HIDES since Amendment 19(b), and the rows `archive-rows` has moved out +# of the register altogether under 19(d). Both are read out of THIS CHECKOUT-s +# files and neither is fetched: the rows on stdin already carry the published +# register (the caller has just rendered it), and this union can only move the +# position UP, which is the direction a position may safely move. `next-free` +# is exempt from the workspace guard, so no workspace at all is silence here. +# THE PUBLISHED ONES, WITH THIS CHECKOUT'S AS THE FALLBACK (Copilot round 1 on +# #93). Reading only the local files missed a row that is on `origin/<branch>` +# and not yet pulled here: hidden from the stdin rows by clause (b) and absent +# from this union, its position came back on offer — which is the one thing +# 19(b) exists to prevent. `register_text` and `archive_text` are the same two +# reads the listing makes, in R19's order. +# +# AND A SOURCE THAT EXISTS AND CANNOT BE READ IS A REFUSAL, not an empty set: a +# position is handed out ONCE, and a read that failed is never an answer +# (Amendment 7(d)). +lane_position_rows() { # 0 with the names · 1 where a source exists and could not be read + [ -n "${LANES_FILE:-}" ] || return 0 + # THE PUBLISHED REGISTER FIRST AND THE WORKING TREE SECOND — `register_text`'s + # own rule, asked for rather than restated (Copilot round 3 on #93). Gated on + # the working-tree FILE existing, this read skipped the published register + # entirely on a checkout that has none, and `next-free` then counted only the + # stdin rows and the archive. + # + # AND AN EMPTY ANSWER WHERE A SOURCE EXISTS IS A READ THAT FAILED (round 2): + # `register_text` ends in a `printf` and answers 0 whatever its `git show` or + # its `cat` did, so the status says nothing; what cannot happen is a source + # with bytes in it rendering as nothing. + # AND ANY PATH THERE IS A SOURCE (#138 item 5). Under `[ -s ]` a zero-byte + # register — what a rewrite that failed leaves — and a broken symlink were + # skipped where origin has no register, and `next-free` counted the stdin + # rows and the archive alone. Counted as a source, either renders empty, and + # the check below refuses it. + if [ -f "$LANES_FILE" ] && [ ! -r "$LANES_FILE" ]; then return 1; fi + lpr_have=0 + if [ -e "$LANES_FILE" ] || [ -L "$LANES_FILE" ]; then lpr_have=1; fi + # AND THE PUBLISHED ONE IS THE TREE'S ANSWER, with `register_text`'s 1 kept + # (#138 item 18, the review of #230): a published register whose blob git + # cannot read is a source that failed, not one that is absent. + lpr_prc=0; register_published || lpr_prc=$? + case "$lpr_prc" in + 0) lpr_have=1 ;; + 8) : ;; + *) return 1 ;; + esac + lpr_reg="" + if [ "$lpr_have" = 1 ]; then + lpr_reg="$(register_text_checked 2>/dev/null)" || return 1 + [ -n "$lpr_reg" ] || return 1 + fi + lpr_arc="" + lpr_arc="$(archive_text 2>/dev/null)" || return 1 + printf '%s\n%s\n' "$lpr_reg" "$lpr_arc" | awk ' + substr($0,1,1) == "|" { + p1 = index($0, "`"); if (p1 == 0) next + r = substr($0, p1 + 1); p2 = index(r, "`"); if (p2 == 0) next + print substr(r, 1, p2 - 1) + }' 2>/dev/null || return 1 + return 0 +} + +lane_next_free() { # <repo> ; rows on stdin + [ -n "${1-}" ] || return 64 + lnf_more="" + if ! lnf_more="$(lane_position_rows)"; then + note "the register or the archive of retired rows exists and could not be read, so the rows this position must avoid are not all known. A position is handed out ONCE and a read that failed is not an answer (Amendment 7(d)), so none is offered." + return 1 + fi + { cat; printf '%s\n' "$lnf_more"; } | awk -F'\t' -v r="$1" ' + BEGIN { rl = tolower(r) } + $1 != "" { + # THE WHOLE NAME BEFORE THE POSITION IS COMPARED, NOT A PREFIX (Copilot + # round 7 on #45, `lanes-edit.sh:4853`). `substr(l, 1, length(rl))` reads + # `repo-foo-1` as a lane of `repo`, so a repository whose name is another + # name plus a hyphen took positions out of its neighbour: `next-free repo` + # would skip 1 because `repo-foo-1` exists, and hand out a number for a + # reason nobody could see in the listing. `head` is everything before the + # LAST hyphen and has to equal the repository exactly. + p = $1; sub(/^.*-/, "", p) + head = $1; sub(/-[^-]*$/, "", head) + if (head == $1) next + if (tolower(head) != rl) next + sub(/[A-Za-z]$/, "", p) + if (p !~ /^[0-9]+$/) next + taken[p + 0] = 1 + } + END { i = 1; while (i in taken) i++; print i }' +} + +# swapped_lanes [<workstation>] — one row per swapped lane, tab-separated: +# <lane> <UTC> <window> <dir> <profile> <agent> <transcript> +# +# THE FIRST FIELD IS THE REGISTER ROW'S SPELLING OF THE LANE (Amendment 15), the +# way `window-lane`'s answer is. The record is read under the lane's LOG FILE +# name, and a log written before Amendment 15 is still `lanes/log/<lower>.md` +# beside a row that spells the lane in mixed case (`lanes/log/openxfactory-4.md` +# and `openXfactory-4`), so the raw name is the wrong one to print. A caller of +# this output hands that field to `tmux rename-window`, to `--name`, to +# `lane <name>` and to a read of the register, and each of them wants the row's +# spelling. The log's own spelling is kept for the two things that read the LOG +# — its path and the pickaxe key — and is never printed. +# +# THE LAST TWO ARE AMENDMENT 17(b)'s, and they are added at the END for the +# reason the fourth and fifth were: the FIRST FIELD BEFORE THE FIRST TAB is the +# contract every reader of this output takes (the launcher, the `handoff` +# skill's step 1, `lane-start`'s directory rung 2 and `restart`'s, each with the +# same comment saying so), and each of the others is read by its own index. A +# record written before an amendment carries its fields EMPTY rather than +# guessed — Amendment 7(i)'s cutover rule, which is what makes a sixth and a +# seventh safe to add at all. +# +# WHICH LINE IS A LANE'S "LAST" IS FILE ORDER (R14), like every other state read +# here: a lane's log is append-only and single-writer, so a line further down +# the file is a line written later whatever the two UTC fields say — and this is +# the read a restart resolves its lane from, so letting a clock decide it would +# be the same fault Amendment 7 removed everywhere else. +# +# THE ROWS ARE ORDERED BY LANDING ORDER ON `origin/<branch>`, MOST RECENTLY +# LANDED FIRST — the position of the commit that ADDED each lane's PAUSED line, +# and never the UTC in it. File order does not reach across two lanes' files, +# and two lanes' UTCs are two clocks: they may be two workstations' (Amendment 7 +# gives them no shared order at all) or one workstation's mid-jump — this one +# was observed stepping ±25 s in bursts, and a log commit landed whose content +# carried a UTC 26 s after its own committer date. Git's push serialization is +# the one order both lanes really share, and it is the same arbiter clause (f) +# already uses to decide a race. The UTC stays in the output as INFORMATION, and +# decides nothing. +# +# The rank is the DAG distance from the tip (`rev-list --count <sha>..origin`), +# not a committer date, so it is history order and not a clock either. Swapped +# lanes are few — one per window a swap paused — so one pickaxe per candidate is +# the cheap read. A candidate whose adding commit cannot be found (no remote ref +# here, or the harness's LANES_NO_GIT=1) ranks last, and those fall back to UTC +# order among themselves: an order that is merely unhelpful, never wrong. +swapped_candidates() { + sw_want="$(short_ws "${1:-$WS}")" + state_events | awk -v sep="$US" -v want="$sw_want" ' + function pos(pf, pn) { return pf "\034" sprintf("%09d", pn) } + BEGIN { FS = sep } + $6 !~ /^lane:/ { next } + # AMENDMENT 13(b) — AND THE TWO NARRATIVE VERBS ARE NOT LANE-KIND STATE. + # AMENDMENT 16 ADDS THE THIRD, and it is the one reader that has to be told + # (Copilot round 6 on openRepoTools#81). `RENAMED` joined `is_note_verb` — + # lane-kind, and not a transition — but this awk names the verbs it skips + # rather than asking the predicate, so a lane whose LAST line was its rename + # stopped reading as PAUSED: `swapped` would not list it and `restart` would + # not find the lane it is meant to bring back. + # This read takes a lane-s LAST lane-kind line whatever its verb is and then + # asks whether it is a `PAUSED` carrying a swap payload; it is the ONE state + # reader in this file that does not name the five verbs it wants. `NOTED` + # and `RULED` are written into exactly the same lines and change nothing + # about where a lane is, so a lane that noted anything after its swap would + # have vanished from `swapped` — and `restart` reads `swapped` to find the + # lane whose window name a new tmux session has lost. Skipped by name, here + # and nowhere else, because every other reader already takes a whitelist. + $3 == "NOTED" || $3 == "RULED" || $3 == "RENAMED" { next } + # AMENDMENT 15 — LOWER-CASED KEY, ORIGINAL SPELLING BESIDE IT. Which line is + # a lane-s LAST is what decides whether that lane is SWAPPED at all, and + # keyed on the raw `$2` a `PAUSED … swap;` under one spelling followed by a + # `RESUMED` under the other left the PAUSED alive as a candidate: `restart` + # would relaunch a lane that is not paused, and `window-lane` would bind a + # window ref the lane has since left (Copilot round 1 on openRepoTools#41). + { k = tolower($2); p = pos($10, $11) + if (!(k in mp) || p >= mp[k]) { + mp[k] = p; verb[k] = $3; utc[k] = $1; pay[k] = $8; uuid[k] = $4; ws[k] = $5; obj[k] = $6; nm[k] = $2 } } + END { + for (l in mp) { + if (verb[l] != "PAUSED") continue + if (substr(pay[l], 1, 5) != "swap;") continue + w = ""; wst = ""; d = ""; pf = ""; ag = ""; tr = "" + n = split(pay[l], sf, "; ") + for (i = 1; i <= n; i++) { + if (substr(sf[i], 1, 7) == "window ") w = substr(sf[i], 8) + if (substr(sf[i], 1, 12) == "workstation ") wst = substr(sf[i], 13) + # AMENDMENT 11 clause (c): two sub-fields added to the three + # A8(b):202 gives this line. + # A `dir` whose path carries a space is written QUOTED, so the quotes + # are stripped here — one unquoter, in the one parser of this line. + if (substr(sf[i], 1, 4) == "dir ") d = substr(sf[i], 5) + if (substr(sf[i], 1, 8) == "profile ") pf = substr(sf[i], 9) + # AMENDMENT 17(b): two more, and a record written before that + # amendment carries neither — which is EMPTY here, never a guess + # (the cutover rule of Amendment 7(i); no apostrophe in this comment, + # because this awk program is single-quoted in the shell). + if (substr(sf[i], 1, 6) == "agent ") ag = substr(sf[i], 7) + if (substr(sf[i], 1, 11) == "transcript ") tr = substr(sf[i], 12) + } + sub(/[ \t]+$/, "", w); sub(/[ \t]+$/, "", wst); sub(/\..*$/, "", wst) + sub(/^[ \t]+/, "", d); sub(/[ \t]+$/, "", d) + sub(/^[ \t]+/, "", pf); sub(/[ \t]+$/, "", pf) + sub(/^[ \t]+/, "", ag); sub(/[ \t]+$/, "", ag) + sub(/^[ \t]+/, "", tr); sub(/[ \t]+$/, "", tr) + if (substr(d, 1, 1) == "\"") { q = index(substr(d, 2), "\""); if (q > 0) d = substr(d, 2, q - 1) } + else { sub(/ .*$/, "", d) } + sub(/ .*$/, "", pf) + sub(/ .*$/, "", ag) + sub(/ .*$/, "", tr) + if (tolower(wst) != want) continue + # The LAST field is the PICKAXE KEY: the head of the line as it was + # written, up to and including its object, which is unique to it and + # which `git log -S` can find without a regex. + # `nm[l]` AND NEVER `l` (Amendment 15, `8345d2f`): the key is the lane + # folded to one case and `nm` is the lane as the event stream spells + # it, which is the base name of the lane LOG FILE (Amendment 16(c) keys + # every line to its file). That is NOT the register row spelling + # wherever the file does not carry it: a log written before Amendment 15 + # is still `lanes/log/openxfactory-4.md` beside the row `openXfactory-4`. + # It stays the spelling of the log itself, for the pickaxe key below and for + # `log_path_for`; the row spelling is for `swapped_lanes` to print as + # the first field, and `window-lane` canonicalises its answer the same + # way. (No apostrophe in this comment: this awk program is single-quoted.) + printf "%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s — lane %s, session %s@%s, %s, %s\n", + nm[l], 31, utc[l], 31, (w == "" ? "unknown" : w), 31, + (d == "" ? "" : d), 31, (pf == "" ? "" : pf), 31, + (ag == "" ? "" : ag), 31, (tr == "" ? "" : tr), 31, + verb[l], nm[l], uuid[l], ws[l], utc[l], obj[l] + } + }' +} + +swapped_lanes() { + sw_rows="$(swapped_candidates "${1:-$WS}")" + [ -n "$sw_rows" ] || return 0 + while IFS="$US" read -r sw_l sw_u sw_w sw_d sw_p sw_a sw_t sw_key; do + [ -n "${sw_l:-}" ] || continue + # THE ROW'S SPELLING FOR THE FIRST FIELD, THE LOG'S FOR THE LOG (see above). + # `canon_lane` refuses a register holding the 15(d) pair and a table of + # former names it cannot read; this read keeps the log's own spelling then, + # for `window-lane`'s reason: it is informational and its contract is rows + # or 8, and the refusal belongs to the writer the lane leads to. + sw_can="$(canon_lane "$sw_l" 2>/dev/null || :)" + sw_rank=999999999 + if have_remote_ref; then + sw_sha="$(git -C "$LANES_REPO" log -1 --format=%H -S"$sw_key" "origin/$LANES_BRANCH" -- "$(log_path_for "$sw_l")" 2>/dev/null || :)" + if [ -n "$sw_sha" ]; then + sw_c="$(git -C "$LANES_REPO" rev-list --count "$sw_sha..origin/$LANES_BRANCH" 2>/dev/null || :)" + case "$sw_c" in ''|*[!0-9]*) : ;; *) sw_rank="$sw_c" ;; esac + fi + fi + printf '%09d%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n' "$sw_rank" "$US" "${sw_can:-$sw_l}" "$US" "$sw_u" "$US" "$sw_w" \ + "$US" "${sw_d:-}" "$US" "${sw_p:-}" "$US" "${sw_a:-}" "$US" "${sw_t:-}" + done <<EOF +$sw_rows +EOF +} + +# The lane's open objects on ONE line, for the hook's block. `who --lane` prints +# a line per object and a heading; a hook has one line's worth of a reader's +# attention, and the objects are what the next act needs to know. +lane_open_summary() { + los_l="$1"; los_out="" + if ! lane_log_exists "$los_l"; then + printf 'no log for %s (pre-cutover lane) — see its row'"'"'s state cell\n' "$los_l" + return 0 + fi + while IFS="$US" read -r lo_utc lo_verb lo_obj lo_ref lo_sup; do + [ -n "${lo_verb:-}" ] || continue + is_open_verb "$lo_verb" || continue + los_out="${los_out}${los_out:+; }$lo_verb $lo_obj${lo_sup:+ (taken over by lane:${lo_sup%@*})}" + done <<EOF +$(lane_objects "$los_l" 2>/dev/null || :) +EOF + printf '%s\n' "${los_out:-none open}" +} + +# HOW OLD THE ANSWER IS (Amendment 8, R-A8-1). The hook never fetches, so every +# line of its block is the checkout as it last stood. `.git/FETCH_HEAD` is +# rewritten by every fetch and by nothing else, so its mtime is when this +# checkout last heard from `origin` — and a block that says "4d ago" is a block +# a reader knows not to trust about another workstation's lane. Never a network +# call and never a failure: an unreadable one answers `unknown`. +fetch_age() { + fa_dir="$(git -C "$LANES_REPO" rev-parse --git-dir 2>/dev/null || :)" + [ -n "$fa_dir" ] || { printf 'unknown\n'; return 0; } + case "$fa_dir" in /*) : ;; *) fa_dir="$LANES_REPO/$fa_dir" ;; esac + [ -f "$fa_dir/FETCH_HEAD" ] || { printf 'never\n'; return 0; } + fa_t="$(stat -c %Y -- "$fa_dir/FETCH_HEAD" 2>/dev/null || stat -f %m -- "$fa_dir/FETCH_HEAD" 2>/dev/null || :)" + case "$fa_t" in ''|*[!0-9]*) printf 'unknown\n'; return 0 ;; esac + fa_s=$(( $(date -u +%s) - fa_t )) + [ "$fa_s" -lt 0 ] && fa_s=0 + if [ "$fa_s" -lt 90 ]; then printf '%ss ago\n' "$fa_s" + elif [ "$fa_s" -lt 5400 ]; then printf '%sm ago\n' "$((fa_s / 60))" + elif [ "$fa_s" -lt 172800 ]; then printf '%sh ago\n' "$((fa_s / 3600))" + else printf '%sd ago\n' "$((fa_s / 86400))" + fi +} + +# The last line of every block the hook prints, whichever branch wrote the rest, +# in the words clause (e) gives it: "every block ends with the line +# `as of <n>m ago (no fetch)`". It is the whole of what makes an unfetched read +# honest — a reader sees how stale the answer is instead of trusting a freshness +# nobody verified. +ssb_tail() { + printf 'as of %s (no fetch)\n' "$(fetch_age)" + return 0 +} + +# `lane-start`'s arguments FOR THIS LANE, filled in (Amendment 8, R-A8-7). The +# block used to print the literal `<repo> <n>` with the lane in hand, so every +# reader translated `openRepoProject-1` into `openRepoProject 1` by hand, on +# every mismatch, for ever. A lane is `<repo>-<position across>` (THE LANE +# RULE), so the split is on the LAST `-` — and ONLY when what follows it is a +# number: a lane named before that rule (`browser-ui-repair`) is started through +# `--dir`, and splitting it would print `browser-ui repair`, which is a command +# that does the wrong thing rather than one that does nothing. +lane_start_args() { + lsa_l="${1-}"; lsa_n="${lsa_l##*-}" + case "$lsa_l" in *-*) : ;; *) printf -- '--dir <path> %s\n' "$lsa_l"; return 0 ;; esac + case "$lsa_n" in ''|*[!0-9]*) printf -- '--dir <path> %s\n' "$lsa_l"; return 0 ;; esac + printf '%s %s\n' "${lsa_l%-*}" "$lsa_n" +} + +# Has Rule 3's stamp for THIS session already been written? (Amendment 8, +# R-A8-7: the block told every resume to "stamp the handoff RESUMED" when +# `lane-start` had just written it — one manufactured decision per resume.) A +# local file read and nothing else: the row's handoff cell, resolved the way the +# row spells it, grepped for this session's own line. It is ASKED rather than +# assumed from the ids matching, because a window started by a bare `claude` +# rather than by `lane-start` has no stamp and does still owe one. +handoff_stamped_by() { # <handoff cell> <session id> + hsb_cell="${1-}"; hsb_id="${2-}"; hsb_f="" + [ -n "$hsb_cell" ] && [ -n "$hsb_id" ] || return 1 + case "$hsb_cell" in + '~/'*) hsb_f="$HOME/${hsb_cell#'~/'}" ;; + /*) hsb_f="$hsb_cell" ;; + *) [ -n "${LANES_REPO:-}" ] && hsb_f="$LANES_REPO/$hsb_cell" ;; + esac + [ -n "$hsb_f" ] && [ -r "$hsb_f" ] || return 1 + grep -qF -e "RESUMED by $hsb_id" -- "$hsb_f" 2>/dev/null +} + +# DOES THE ROW'S NEWEST STAMP NAME A UUID, OR `unknown`? (Amendment 8(e), "the +# first cure carries one condition".) A real `lane-start` is the wrong-lineage +# remedy BECAUSE the cell's last id names a transcript the lane's directory has. +# Where the last launch took clause (d)'s title fallback, that id names a +# transcript this directory does not have — which is why the fallback was +# reached — and the row says so in its own words: the stamp that run wrote +# carries the literal `unknown`. A relaunch would take the same fallback again, +# so the cure there is the recording act instead. +# +# The row is read, never the directory: the hook is handed no lane checkout and +# the working directory confers no lane. `0` when the newest stamp says +# `unknown`, `1` otherwise — including a row with no stamp at all, where a +# relaunch is the ordinary remedy. +row_stamp_is_unknown() { # <lane> + rsu_lane="${1-}"; rsu_n=""; rsu_row=""; rsu_last="" + [ -n "$rsu_lane" ] || return 1 + rsu_n="$(row_line "$rsu_lane" 2>/dev/null)" || return 1 + case "$rsu_n" in ''|*[!0-9]*) return 1 ;; esac + rsu_row="$(sed -n -e "${rsu_n}p" "$LANES_FILE" 2>/dev/null || :)" + [ -n "$rsu_row" ] || return 1 + rsu_last="$(printf '%s' "$rsu_row" | grep -o '[A-Z][A-Z]* by [^ |]*' | tail -n1 || :)" + case "$rsu_last" in *" by unknown") return 0 ;; esac + return 1 +} + +# session_start_block <hook json> <tmux window name> — the whole of what the +# SessionStart hook prints. It NEVER writes and its caller ALWAYS exits 0. +# +# `source` is one of startup, resume, clear, compact, fork. A COMPACT prints +# NOTHING: the same conversation carries on in the same window under the same +# id, and a block there would announce a lane's identity into the middle of a +# session that already has it. Everything else — a fork included, which is a new +# attachment to the lane's conversation — gets the block, and an unknown or +# missing source is treated as a startup rather than dropped. +# +# `cwd` is in the payload and is deliberately NOT read as a lane: THE WORKING +# DIRECTORY CONFERS NO LANE (Amendment 6(a)) — two lanes share one all day, and +# every nested checkout in the xFactory estate shares its parent's. The WINDOW +# and the REGISTER decide, in that order. +session_start_block() { + ssb_json="${1-}"; ssb_win="${2-}" + ssb_id="$(lc "$(jstr "$ssb_json" session_id)")" + ssb_src="$(jstr "$ssb_json" source)" + case "$ssb_src" in compact) return 0 ;; esac + + # AMENDMENT 15 — THE WINDOW NAME, THE SESSION NAME AND THE ROW KEY ARE + # COMPARED CASE-INSENSITIVELY, AND EVERY LINE BELOW PRINTS THE ROW'S OWN + # SPELLING. Both reads already answer with the register's spelling — + # `lane_named_ci` lowercases both sides by name, and `lane_of_session` prints + # the row's token — so `$ssb_lane` is canonical from here down, which is what + # makes `lane_start_args` below hand a reader the commands filled in with the + # spelling their window and their session are about to be named. + # AMENDMENT 12'S GUARD AND LOCK PLUG IN HERE, and since #25 they ARE built — + # `ssb_name_line` immediately below is clause (f), and the lock it types is + # the same `guard_type` the `UserPromptSubmit` guard uses. A session whose + # name differs from `$ssb_lane` only by case is renamed to the ROW's spelling + # like any other drift, which is what makes this line and Amendment 15 one + # rule rather than two. + ssb_lane=""; ssb_alias_unread="" + if [ -n "$ssb_win" ]; then + # AMENDMENT 16(e) — AND A TABLE THIS READ COULD NOT OPEN IS SAID, NOT + # SWALLOWED (Copilot round 3 on openRepoTools#81). This hook never refuses, + # so an unreadable `lanes/aliases.tsv` cannot stop the block — but printing + # "no lane bound to this window" about a window whose name might be a + # FORMER one is the block orienting a session wrongly, which is the one + # thing it exists not to do. It says so instead, and the line below it is + # then read as what it is. + ssb_rc=0 + ssb_lane="$(lane_named_ci "$ssb_win" 2>/dev/null)" || ssb_rc=$? + [ "$ssb_rc" = 5 ] && { ssb_lane=""; ssb_alias_unread=1; } + fi + [ -n "$ssb_lane" ] || [ -z "$ssb_id" ] || ssb_lane="$(lane_of_session "$ssb_id" 2>/dev/null || :)" + [ -n "$ssb_alias_unread" ] && [ -z "$ssb_lane" ] && \ + printf 'WARNING: %s could not be read, so a window named for a lane RENAMED since could not be resolved to it (Amendment 16(e)) — this block may be about to say no lane binds a window that one does\n' "${LANES_ALIASES_PATH:-lanes/aliases.tsv}" + # AMENDMENT 12 CLAUSE (f) AND AMENDMENT 18(h)'s READ — the name line and the + # duplicate line, printed HERE rather than inside each of the three branches + # below, because both are facts about this session and not about which of them + # applies. `|| :` for the reason the whole block has one: this hook never + # fails and always exits 0 (R-A8-1). + # THE SUBSHELL IS THE `|| :` MADE TRUE OF MORE THAN A RETURN — see + # `ssb_name_line`'s own header. It is the one line of this block that reads + # every profile's session records, so it is the one most able to meet + # something this hook may not die on. + ( ssb_name_line "$ssb_id" "$ssb_lane" ) || : + if [ -z "$ssb_lane" ]; then + # THE ONE PLACE THE PLACEHOLDER IS RIGHT: no lane is known here, so there is + # nothing to fill in. It is also the estate's ONE no-lane notice — the + # launcher prints its own on stderr before the launch, and Amendment 8's + # resume-choice table says one of the two goes; this is the one the session + # itself can read. + # THE ONE BRANCH THAT KEEPS ITS PLACEHOLDERS — no lane is known here, so + # there is nothing to fill in. Except where the WINDOW NAME itself parses as + # `<repo>-<n>`: the register has no such row, but the operator's own two + # arguments are right there in the name, and printing them beats printing a + # blank for them to fill. It is also the estate's ONE no-lane notice — + # clause (c) step 4 stands down wherever this hook can speak. + if [ -n "$ssb_win" ] && [ "$(lane_start_args "$ssb_win")" != "--dir <path> $ssb_win" ]; then + printf 'no lane bound to this window — run: lane-start %s\n' "$(lane_start_args "$ssb_win")" + else + printf 'no lane bound to this window — run: lane-start <repo> <n>\n' + fi + ssb_tail + return 0 + fi + + ssb_args="$(lane_start_args "$ssb_lane")" + ssb_cur="$(last_session_id_of_lane "$ssb_lane" 2>/dev/null || :)" + if [ -n "$ssb_id" ] && [ -n "$ssb_cur" ] && [ "$ssb_id" != "$ssb_cur" ]; then + # THE BRANCH IS THE ID'S POSITION IN THE SESSION CELL, NOT ITS PRESENCE. + # The cell is a history written oldest first and the LAST id is the lane + # (Amendment 6(b)), so there are exactly three places an id can be, and + # each is cured by a different act: + # + # * the cell's LAST id — this session IS the lane. Handled below. + # * IN the cell but not last — a SUPERSEDED transcript of this lane. That + # is the 2026-09-11 wrong-lineage resume, caught at the first instant it + # can be caught, and the cure is a real `lane-start`, which resumes the + # id the row ends on. The conversation in this window is not the lane's, + # so the session is exited rather than carried on with. + # * in NO cell — the harness minted a new transcript with nobody acting (a + # /clear, a usage reset, a profile switch), or an operator's title- + # fallback pick landed on a transcript no row carries. The lane is right + # and the row is simply behind, so the cure is the recording act and no + # relaunch: `lane-start --no-launch`, which reads the live record in + # this window and appends that uuid to the cell. + # + # THE TWO CURES ARE NOT INTERCHANGEABLE. A reader who runs `--no-launch` on + # a superseded transcript records the WRONG conversation as the lane's, in + # the cell the next restart resumes from — the failure this block exists to + # catch, performed by its own remedy. + # + # AND NO CURE SENDS A READER BACK THROUGH THE PICKER (clause (f)): where the + # row's newest stamp says `unknown`, the cell's last id names a transcript + # the lane's directory does not have, a relaunch would take the same title + # fallback again, and the recording act is the cure there too. No branch + # names `/resume` or the picker, because neither is a lane surface. + # + # EVERY COMMAND IS PRINTED FILLED IN (F-B6): the hook holds the lane, and a + # reader trying to get back to work should not have to translate + # `openRepoProject-1` into `openRepoProject 1` by hand at that moment. + if printf '%s\n' "$(session_ids_of_lane "$ssb_lane" 2>/dev/null || :)" | grep -qx -F -- "$ssb_id"; then + if row_stamp_is_unknown "$ssb_lane"; then + printf 'WARNING: this is a superseded transcript of lane %s; the live one is %s, which the row records as `unknown` — a relaunch would record nothing either, so run: lane-start --no-launch %s\n' \ + "$ssb_lane" "$ssb_cur" "$ssb_args" + else + printf 'WARNING: this is a superseded transcript of lane %s; the live one is %s; you resumed %s — exit this session and run: lane-start %s\n' \ + "$ssb_lane" "$ssb_cur" "$ssb_id" "$ssb_args" + fi + else + printf 'WARNING: this window is lane %s whose current session is %s; this session %s is in no row — the harness minted a new transcript — run: lane-start --no-launch %s\n' \ + "$ssb_lane" "$ssb_cur" "$ssb_id" "$ssb_args" + fi + ssb_tail + return 0 + fi + + ssb_ho="$(handoff_of_lane "$ssb_lane" 2>/dev/null || :)" + # AMENDMENT 11 CLAUSE (h) — THE BOUND LINE GAINS THE WINDOW, and gains + # nothing else: `session-start` keeps all three of its safety properties, it + # never writes, it never touches the network and it always exits 0 (R-A8-1), + # and this is a field the block has already read out of the lane's own log. + # It is here because the window is what clause (b)'s precedence 3 and clause + # (f)'s step 2(c) bind from, and a reader who cannot see what the record says + # the window is cannot tell a lane that will bind with no question from one + # that will not. + ssb_win="$(lane_payload_field "$ssb_lane" window all 2>/dev/null || :)" + printf 'LANE %s — handoff %s — row session %s%s\n' \ + "$ssb_lane" "${ssb_ho:-none recorded}" "${ssb_cur:-none recorded}" \ + "${ssb_win:+ — window $ssb_win}" + # DECISION 8(e) — A LIVE FORK OF THIS LANE'S TRANSCRIPT IS SHOWN AS A DEFECT + # TO RETIRE. Evidence 6: an abandoned launch left a `--fork-session` daemon + # orchestrating the same plan, relaunching writers on the same branches and + # writing this lane's log under an id no row carries, while telling the + # interactive session it was the holder. A session that starts into a lane + # somebody else's fork is still running needs to know before it acts, and the + # retirement is a person's act (Amendment 8(f)), so the line NAMES and does + # nothing. + ssb_fk=""; ssb_fkrc=0 + ssb_fk="$(lane_forks "$ssb_lane" 2>/dev/null)" || ssb_fkrc=$? + # AND THE SAME HERE, for the same reason: this block is the first thing a + # session that starts into a lane reads, and "no fork" is a fact it acts on. + case "$ssb_fkrc" in + 0 | 8) : ;; + *) printf 'UNKNOWN: this workstation'"'"'s session records could not be read, so whether a live FORK of this lane'"'"'s transcript is running is NOT established — which is not the same as none. See: lanes-edit.sh forks %s\n' "$ssb_lane" ;; + esac + if [ -n "$ssb_fk" ]; then + while IFS='\t' read -r ssb_fid ssb_fpid ssb_fkind ssb_fcwd; do + [ -n "${ssb_fid:-}" ] || continue + printf 'DEFECT: %s is a live FORK of this lane'"'"'s transcript (pid %s, %s, cwd %s) — it is not the holder and must not write the register. Retire it: lane-end %s --retire %s\n' \ + "$ssb_fid" "$ssb_fpid" "${ssb_fkind:-interactive}" "${ssb_fcwd:-unknown}" "$ssb_lane" "$ssb_fpid" + done <<EOF +$ssb_fk +EOF + fi + # THE BLOCK STOPS ASKING FOR A STAMP `lane-start` HAS ALREADY WRITTEN (R-A8-7, + # resume-choice row 9: one manufactured decision per resume). It is DERIVED, + # not assumed from the ids matching — a window started by a bare `claude` + # rather than through the launcher has no stamp and does still owe one — so + # the handoff the ROW names is read and grepped for THIS session's own line. + # Where the row names no handoff at all the line says that instead. + if [ -z "$ssb_ho" ]; then + printf 'the row records no handoff path — there is none to stamp or to follow\n' + elif handoff_stamped_by "$ssb_ho" "$ssb_id"; then + printf 'handoff already stamped by lane-start — follow its top block\n' + else + printf 'stamp the handoff RESUMED (Rule 3) and follow its top block\n' + fi + printf 'open: %s\n' "$(lane_open_summary "$ssb_lane")" + ssb_tail + return 0 +} + +# ============================================================================ +# AMENDMENT 12 — THE NAME GUARD AND THE LOCK, WITH AMENDMENT 18(h)'S ONE READ +# ============================================================================ +# +# **A LANE SESSION WORKS ONLY WHILE THREE NAMES ARE ONE** — the tmux WINDOW it +# runs in, the SESSION's own name, and the register ROW whose session cell ends +# on this transcript — **and otherwise the prompt is REFUSED** (exit 2), with +# the triple as it stands and the ONE command that cures it, filled in. Ratified +# 2026-09-13T18:20:44Z, "Ratify revision 2", with M1 "Type /rename into the +# pane"; `brettheap/new-workstation#22`/#23, opensoft/openRepoTools#25. +# +# WHY THE RULE NEEDED AN ENFORCEMENT. Amendment 2 has said since 2026-09-05 that +# a lane is its window's name and its session's name; nothing refused anything +# for eight days, and between 2026-09-10 and 2026-09-12 this very lane ran as +# `openRepoTools-3`, `-4`, … `-14` — a fresh title per `/resume`, in a window +# still named `claude`, in profiles that changed at every usage reset — and no +# row was ever written. `session_start_block` above says which lane a window is +# and "ALWAYS exits 0"; `window_session` "decides nothing". This is the surface +# that decides. +# +# THE LOCK (clause (h), Brett Heap's D5). Under the projects root the session +# name is not the person's to set freely; it is the lane's. The tooling sets it +# at every launch (`lane-start --name "$LANE"`, clause (c)) and again whenever it +# drifts — by TYPING `/rename <lane>` into the session's own tmux pane, which is +# the only mechanism a running session has (M1, "Type /rename into the pane"): +# the docs name `--name` at launch, `/rename`, and `Ctrl+R` in the picker, and +# nothing else — no hook output field, no environment variable, no settings key. +# A PERSON'S rename to another lane's name is not drift but an INSTRUCTION, and +# it is OFFERED back before it is obeyed: yes moves this window to that lane, no +# renames the session back. +# +# FAIL CLOSED (clause (d)). A mismatch refuses; so does an INDETERMINATE read — +# session records unreadable, tmux not answering, the register unreadable — +# naming the read, because a triple that cannot be verified is not a triple that +# agrees. Profile-only launches carrying exactly `CLAUDE_NO_LANE=1` are exempt +# from this guard. `claude --safe-mode` disables every hook, deliberate and +# visible in the prompt box; a session started that way is not a lane session +# and may not write the register or claim an object. +# +# WHAT IT COSTS, AND THE ONE WAY IT FAILS OPEN. Measured on Eagle 2026-09-14 +# against 329 session records and a 1.3 MB register: the register read is ~2 s +# wall and the `grep -l` over every profile's records ~0.4 s, so a refusal lands +# inside the ratified `timeout 5`. A hook that EXCEEDS its timeout is killed, and +# a killed hook does not exit 2 — so the timeout is the one path on which this +# guard fails open. It is the amendment's own number and is left at it; the +# cheap tests are made first so that the two reads happen only where they decide +# something. +# +# IT NEVER FETCHES. `session-start`'s R-A8-1 argument applies here several times +# over — that hook runs once per session and this one runs at EVERY PROMPT — so +# the row is read from `origin/<branch>` AS THIS CHECKOUT LAST HAD IT (R19, the +# same `register_text` every other state read takes) and the network is never +# opened. "The register not fetchable" (clause (d)) is therefore the READ +# failing, and that refuses. + +# A LANE NAME IS `<repo>-<position>` (THE LANE RULE), and this is the predicate +# for it: `check_lane_name`'s character fence, plus a LAST `-` followed by +# digits. It agrees with `lane_start_args` by construction — that function +# prints `--dir <path> <lane>` for exactly the names this refuses — and the two +# exist separately because one answers a question and the other builds a command +# line. A name the register has a row for is a lane whatever its shape +# (`browser-ui-repair` is one); this asks only whether the two arguments of +# `lane-start` can be read OUT of a name nobody has a row for yet, which is what +# rows 1 and 6 of the table below need. +lane_shaped() { # <name> + lsh_n="${1-}" + case "$lsh_n" in ''|*[!A-Za-z0-9._-]*|.*|-*) return 1 ;; esac + case "$lsh_n" in *-*) : ;; *) return 1 ;; esac + lsh_pos="${lsh_n##*-}" + case "$lsh_pos" in ''|*[!0-9]*) return 1 ;; esac + return 0 +} + +# CLAUSE (e)'s SCOPE, AND IT IS ASKED OF BOTH SPELLINGS OF A PATH. The guard +# applies to every session whose `cwd` is under the projects root and is silent +# elsewhere (D1, "Projects root only"). On a launcher-configured workstation +# `~/projects` is a SYMLINK — every profile's is one link to +# `~/.claude-profiles/state/opensoft/projects` — and the harness reports a `cwd` +# that has already been resolved through it, so a literal prefix test answers +# "outside the projects root" about every estate session there is. Both the +# typed path and its `pwd -P` are compared, and a match on either is inside: +# the direction that errs toward the guard APPLYING is the safe one, because +# the other direction is the guard never firing at all. +under_projects_root() { # <cwd> <projects root> + upr_c="${1-}"; upr_r="${2-}" + [ -n "$upr_c" ] && [ -n "$upr_r" ] || return 1 + case "$upr_c/" in "$upr_r"/*) return 0 ;; esac + upr_cr="$(cd -- "$upr_c" 2>/dev/null && pwd -P)" || upr_cr="" + upr_rr="$(cd -- "$upr_r" 2>/dev/null && pwd -P)" || upr_rr="" + [ -n "$upr_cr" ] && [ -n "$upr_rr" ] || return 1 + case "$upr_cr/" in "$upr_rr"/*) return 0 ;; esac + return 1 +} + +# THE WINDOW A RECORD NAMES, UNDER AMENDMENT 11(h)'s AGREEMENT RULE. A record's +# `tmux` is `<session>:<@id>.<%pane>`, and tmux REUSES window ids once a window +# is gone — measured 2026-09-14, when a stale record's `@1` resolved to a window +# of another session. So the id alone is not the window: the id must resolve +# HERE and the session it resolves in must be the one the record wrote down. +# 0 the window exists and agrees +# 1 the id resolves nowhere here, or resolves in another tmux session — and +# the SERVER answered, so this is a refutation and not a silence +# 2 tmux did not answer at all: its server is down or unreachable from here, +# so the window is UNKNOWN, not gone (openRepoTools#73, item 1) +# 8 there is nothing to test — no target on the record, no `@id` in it, or no +# tmux to ask (a record with no window is not thereby a record nowhere) +# +# THE 2 NEEDS A SECOND QUESTION, AND IT IS ASKED ONLY WHERE THE FIRST CAME BACK +# EMPTY. `tmux_window_field` answers empty for a window this server refuted and +# for a server that never answered, and this function used to call both 1 — +# which `transcript_holders` writes as `(gone)`, and which `lane-end --retire` +# reads as "not the lane's own session". So with tmux installed and its server +# silent, `--retire <the lane's own pid>` was accepted and printed Amendment +# 6(d)'s retitle for the conversation that IS the lane (measured on f87fd5a: +# `/rename repoGD-1 · retired …`, exit 0). `tmux_server_answers` tells the two +# apart, and a window nobody could ask about keeps `(not asked)`'s posture: it +# protects the process in it. +record_window_state() { # <the record's tmux field> + rws_t="${1-}" + [ -n "$rws_t" ] && [ "$rws_t" != none ] || return 8 + rws_ref="${rws_t%.*}" + rws_id="${rws_ref##*:}" + rws_sess="${rws_ref%:*}" + case "$rws_id" in @*) : ;; *) return 8 ;; esac + command -v tmux >/dev/null 2>&1 || return 8 + rws_now="$(tmux_window_field "$rws_id" '#{session_name}' 2>/dev/null || :)" + if [ -z "$rws_now" ]; then + tmux_server_answers || return 2 + return 1 + fi + [ "$rws_now" = "$rws_sess" ] || return 1 + return 0 +} + +# DOES A TMUX SERVER ANSWER HERE AT ALL? Asked UNTARGETED, so it names no window +# and no window's absence can refute it: with no `-t`, tmux answers for the +# client this shell is in, or outside tmux for a session of its own choosing, +# and with no server it prints nothing and exits 1 (`no server running on …`). +# Measured on this estate 2026-10-13 against tmux 3.4 on a private socket: no +# server → empty, exit 1; a server up, asked from outside it → the session's +# name, exit 0; and a TARGETED read of an `@id` that server does not have → +# empty, exit 0 — the very answer a silent server also gives, which is why this +# is a separate question and not a status code read off the first one. +tmux_server_answers() { + command -v tmux >/dev/null 2>&1 || return 1 + [ -n "$(tmux display-message -p '#{session_name}' 2>/dev/null | head -n1)" ] +} + +# ------------------------------------- AMENDMENT 18(h): ONE LIVE PROCESS +# +# *"A transcript (one session id) is held by ONE live process. The harness can +# fork one (`--fork-session`, minting a new id in a background pty host) or +# resume one twice, and the tooling refuses to build on either."* Ratified +# 2026-09-14T13:15:18Z as revision 4 of Amendment 18; +# `brettheap/new-workstation#34`, opensoft/openRepoTools#39. +# +# MEASURED FOUR TIMES ON 2026-09-14, the fourth at 18:14Z: a `bg` record in ONE +# profile's `sessions/` and an interactive record in ANOTHER's, both live, both +# carrying one `sessionId` — which is why this sweeps EVERY profile's directory +# and not the asking session's. On a launcher-configured workstation every +# profile's `projects/` is one shared directory, so a transcript needs no move +# to be resumed under another profile and a duplicate is one `--resume` away. +# +# THREE CALLERS, ONE IMPLEMENTATION, for the reason clause (h) already gives +# `window-lane`: `lane-start` refuses to bind or resume an id another process +# holds, `lane-end --retire <pid>` retires that process, and the prompt guard +# refuses every prompt inside it. A rule implemented three times is a rule three +# surfaces come to disagree about. +# +# IT IS BUILT ON A `grep -l`, NOT ON `session_records`. This runs at every prompt +# under a five-second timeout, and the one-pass parse is a per-process CACHE that +# the first caller pays for in full — 329 records here. The question asked is +# about ONE id the harness has already handed the hook, so the cheap shape is the +# one `live_holder` uses: one grep for the id, then a parse of the one or two +# files that match. Measured at ~0.4 s against those 329. +# +# <pid><US><kind><US><tmux|none><US><profile><US><where><US><verdict><US><file> +# +# `where` is for a person to read — `window <session>:<@id>`, the same with +# ` (gone)` where the agreement rule above refuses it, ` (no answer)` where tmux +# did not answer at all and ` (not asked)` where there was nothing to ask — or +# `bg`. Only `(gone)` is a window this server REFUTED (openRepoTools#73). +# +# THE VERDICT IS THE WHOLE OF THE JUDGEMENT, and it has four values because +# THREE IN-FORCE RULES MEET HERE AND NONE OF THEM MAY BE OVERTURNED BY THIS ONE: +# +# here the record is THIS window's own process — its `tmux` names this +# window, or its pid is this pane's or below it: `record_is_here`'s +# TIERS 2 AND 3, and its tier 1 is left out because it cannot +# discriminate here. That tier asks whether the record's +# `sessionId` is `$CLAUDE_CODE_SESSION_ID`, and every candidate in +# this set carries the very id being tested — so on the asking +# session's own transcript it would answer `here` for the +# duplicate too, which is the one reading this function exists to +# prevent. +# companion not this window's, in the SAME profile's `sessions/` as this +# window's own record of this id, AND NOT A SESSION RECORD. +# AMENDMENT 8, RULING (g) names exactly one such thing: *"Beside +# the interactive process in the pane the harness runs a companion: +# `kind: bg`, no `tmux`, no `nameSource`, its own pid, and THE SAME +# `sessionId` … Records that share a `sessionId` are one session, +# not a queue of rival holders, and there is no contest between +# them to win."* The harness writes a session's own records under +# that session's own `$CLAUDE_CONFIG_DIR`, so same-profile is what +# "the harness's own second record of one session" looks like — +# and the `kind` is what tells that record apart from a SECOND +# INTERACTIVE PROCESS in the same directory, which is one +# transcript resumed twice and is 18(h)'s own case rather than the +# harness's companion. The profile alone read a second `--resume` +# UNDER ONE PROFILE as benign (Copilot round 1 on this PR), and +# that is the cheapest way there is to make two live processes on +# one transcript: no move, no swap, one command. +# THE KIND IS `bg` AND NOTHING ELSE IS READ AS ONE. `not a session +# record` was the first spelling of this test and it was too wide +# by exactly the kinds nobody has ruled on: this suite's own +# interactive fork carries `kind: user` +# (`tests/test_lane_helpers.sh`, Amendment 11 clause (k)), and any +# kind a later harness invents would have arrived here as the +# harness's benign companion (Copilot round 2 on this PR). Ruling +# (g) names ONE shape to pass over, so that shape is what this +# matches; every other live record on this id — known kind or not, +# and a record too old to carry a `kind` at all, which pass 1 +# writes down as `interactive` — is a duplicate, which is the +# closed direction. +# AND WHERE THIS WINDOW CARRIES NO RECORD OF THE TRANSCRIPT, THE +# LANE'S LIVE WINDOW STANDS IN FOR IT (openRepoTools#73, item 2). +# The relation is the HARNESS's, between two records of one +# session, and nothing about it depends on who asks — but it was +# read relative to the ASKING process, so `lane-end --retire` typed +# in a bare shell or in another lane's window found nothing +# `here`, every holder came back `unrelated`, and the companion +# was never called one. The record a session's companion sits +# beside is the interactive record in a window this server +# RESOLVES AND AGREES WITH (rc 0 above) — the record `lane-end` +# already calls "the lane's session" — so a `kind: bg` record in +# that record's profile is `companion` from any window. ONLY ONE +# PROFILE MAY ANSWER: two live windows in two profiles on one +# transcript is 18(h)'s own case with no way to tell which is the +# lane's, and there every row stays `unrelated`, as before. The +# anchor row itself is not this window's and stays `unrelated`. +# duplicate EVERY OTHER live record carrying this id: a session record in +# another window of this same profile, or any record at all in +# ANOTHER profile's `sessions/` beside this window's own. That is +# AMENDMENT 18(h)'s second live process. The MEASURED shape was the +# second one — four times on 2026-09-14, the last at 18:14Z, the +# second record sat in another profile's directory, and 18(h) says +# why, *"on a launcher-configured workstation every profile's +# `projects/` is one shared directory … which is also why a +# duplicate is one `--resume` away"* — but the rule it states is +# one live PROCESS per transcript, not one per profile. +# unrelated THIS WINDOW CARRIES NO RECORD OF THIS TRANSCRIPT AT ALL, so this +# read says nothing about the processes that do — beyond the one +# relation that is not this window's to have, the companion above +# (#73). That is not timidity: `live_holder` answers "is any +# session this row names alive" and Amendment 8(f) rules an +# ORPHAN reported and never refused, while `lane_forks` answers +# about a fork. A rule that counted every live record here would +# overturn both from a read that was not asked about either. ONE +# CALLER TAKES IT AS A BLOCKER ANYWAY AND SAYS SO WHERE IT DOES: +# `lane-start`'s `dup_check`, asked about the ONE id a run is +# about to resume, where an `unrelated` holder is a second live +# process on the very file that run is about to open (Amendment +# 18(h), *"never launches a second resume of it"*). That is a +# narrower question than this verdict answers, so the narrowing +# lives at that call site and not in this table. +# +# 0 with rows, 8 with none, 1 where the records could not be read, 64 no uuid. +transcript_holders() { # <session uuid> + th_id="${1-}"; [ -n "$th_id" ] || return 64 + th_files=""; th_match=""; th_err=""; th_f=""; th_blob="" + th_pid=""; th_kind=""; th_tgt=""; th_where=""; th_verdict=""; th_out="" + # `th_here_prof` AND `th_here` AMONG THEM, and the omission was not cosmetic: + # this file runs under `set -u` (line 292), pass 2's `[ -z "$th_here_prof" ]` + # is reached for the FIRST record that is not this window's, and an unset + # variable there exits the shell with `unbound variable` — a 1 every caller + # reads as "the records could not be read" and refuses on. It cost the suite's + # `the same lane live in THIS window is not a collision`, which asks + # `lane-start` for an exit 0 and got `dup_check`'s fail-closed 1. + th_here=""; th_here_prof=""; th_prof=""; th_wrc=0; th_final="" + # THE LANE'S LIVE WINDOW, for the companion verdict where this window has no + # record of the transcript (#73): the profile of the session record whose + # window this server resolves and agrees with, and whether a SECOND profile + # answered too, which leaves no single one to read it from. + th_live_win=no; th_win_prof=""; th_win_two=no + SESSION_FILES_ERR="" + here_context + th_files="$(mktemp "${TMPDIR:-/tmp}/lanes-edit-tf.XXXXXX" 2>/dev/null || printf '')" + th_match="$(mktemp "${TMPDIR:-/tmp}/lanes-edit-tm.XXXXXX" 2>/dev/null || printf '')" + th_err="$(mktemp "${TMPDIR:-/tmp}/lanes-edit-te.XXXXXX" 2>/dev/null || printf '')" + if [ -z "$th_files" ] || [ -z "$th_match" ] || [ -z "$th_err" ]; then + rm -f -- "$th_files" "$th_match" "$th_err" 2>/dev/null || : + SESSION_FILES_ERR="could not create a temporary file under ${TMPDIR:-/tmp}" + return 1 + fi + # NOT `$( )`: session_files sets SESSION_FILES_ERR, and a subshell would keep + # the reason for the failure to itself. + if ! session_files > "$th_files"; then + rm -f -- "$th_files" "$th_match" "$th_err" + return 1 + fi + if [ ! -s "$th_files" ]; then + rm -f -- "$th_files" "$th_match" "$th_err" + return 8 + fi + # The locale and the NUL separator for the reason `live_holder` states above: + # these are arbitrary bytes and BSD `tr` prints nothing at all for a multibyte + # character in a UTF-8 locale. + LC_ALL=C tr '\n' '\0' < "$th_files" | xargs -0 grep -l -F -e "\"sessionId\":\"$th_id\"" > "$th_match" 2>"$th_err" || : + if [ -s "$th_err" ]; then + SESSION_FILES_ERR="$(LC_ALL=C tr '\n' ';' < "$th_err" | LC_ALL=C cut -c1-300)" + rm -f -- "$th_files" "$th_match" "$th_err" + return 1 + fi + rm -f -- "$th_files" "$th_err" + while IFS= read -r th_f; do + [ -n "$th_f" ] || continue + th_blob="$(cat -- "$th_f" 2>/dev/null || :)" + [ -n "$th_blob" ] || continue + # The id is matched EXACTLY and not by the grep alone: a record naming this + # uuid inside some other field would otherwise be counted as a holder. + [ "$(lc "$(jstr "$th_blob" sessionId)")" = "$(lc "$th_id")" ] || continue + record_is_live "$th_blob" || continue + th_pid="$(jnum "$th_blob" pid)" + th_kind="$(jstr "$th_blob" kind)" + th_tgt="$(jstr "$th_blob" tmux)" + th_where=bg; th_live_win=no + if record_fields_are_session "$th_kind" && [ -n "$th_tgt" ]; then + th_wrc=0 + record_window_state "$th_tgt" || th_wrc=$? + case "$th_wrc" in + 0) th_where="window ${th_tgt%.*}"; th_live_win=yes ;; + 1) th_where="window ${th_tgt%.*} (gone)" ;; + 2) th_where="window ${th_tgt%.*} (no answer)" ;; + *) th_where="window ${th_tgt%.*} (not asked)" ;; + esac + elif record_fields_are_session "$th_kind"; then + th_where="no window" + fi + th_here=no + if [ -n "$th_tgt" ] && [ -n "$LANES_THIS_WINDOW" ] && [ "${th_tgt%.*}" = "$LANES_THIS_WINDOW" ]; then + th_here=yes + elif pid_under "$th_pid" "$LANES_PANE_PID"; then + th_here=yes + fi + th_prof="$(record_profile "$th_f")" + [ "$th_here" = yes ] && [ -z "$th_here_prof" ] && th_here_prof="$th_prof" + if [ "$th_live_win" = yes ]; then + if [ -z "$th_win_prof" ]; then th_win_prof="$th_prof" + elif [ "$th_win_prof" != "$th_prof" ]; then th_win_two=yes + fi + fi + th_out="${th_out}${th_pid:-unknown}${US}${th_kind:-interactive}${US}${th_tgt:-none}${US}${th_prof}${US}${th_where}${US}${th_here}${US}${th_f} +" + done < "$th_match" + rm -f -- "$th_match" + [ -n "$th_out" ] || return 8 + [ "$th_win_two" = yes ] && th_win_prof="" + # PASS 2 — THE VERDICT, WHICH NEEDS THE WHOLE SET AND SO CANNOT BE MADE ABOVE. + th_final="" + while IFS="$US" read -r tv_pid tv_kind tv_tgt tv_prof tv_where tv_here tv_file; do + [ -n "${tv_pid:-}" ] || continue + if [ "$tv_here" = yes ]; then + tv_v=here + elif [ -z "$th_here_prof" ]; then + # NOTHING HERE, SO THE LANE'S LIVE WINDOW ANSWERS FOR THE ONE RELATION + # THAT IS NOT THE ASKER'S (#73): the harness's `bg` companion beside it. + # Everything else stays `unrelated`, which is what every caller already + # reads this state as. + if [ -n "$th_win_prof" ] && [ "$tv_prof" = "$th_win_prof" ] && [ "$tv_kind" = bg ]; then + tv_v=companion + else + tv_v=unrelated + fi + elif [ "$tv_prof" = "$th_here_prof" ] && [ "$tv_kind" = bg ]; then + tv_v=companion + else + tv_v=duplicate + fi + th_final="${th_final}${tv_pid}${US}${tv_kind}${US}${tv_tgt}${US}${tv_prof}${US}${tv_where}${US}${tv_v}${US}${tv_file} +" + done <<EOF +$th_out +EOF + printf '%s' "$th_final" + return 0 +} + +# ===================== AMENDMENT 18(b) — THE BINDING, READ ================== +# +# **A LANE HAS ONE BINDING**: the `host`, `container` and `window` of its last +# lane-kind line that is `STARTED` or `RESUMED` with no `PAUSED`, `ENDED` or +# `RETIRED` after it. A lane whose last lane-kind line is one of those three, or +# that has none, is FREE. Ratified 2026-09-14T13:15:18Z as revision 4. +# +# ONE SCAN ANSWERS FOUR QUESTIONS, because three surfaces ask them of the same +# stream and a second pass is a second answer: the `binding` read (clause (c)'s +# refusal), the prompt guard's clause (d) — *"a `HANDOFF-REQUESTED` newer than +# its own binding and not yet answered"* — its clause (e) — *"a `PAUSED` newer +# than the binding that this session did not write"* — and `request-handoff`'s +# wait, which ends when the release arrives. +# +# IT IS FILE ORDER AND NEVER A CLOCK (R14). A lane's log is append-only and +# single-writer, so a line further down the file is a line written later +# whatever the two UTC fields say — and "newer than the binding" here means +# BELOW it in the file, which is the only order two lines of one lane really +# share. The UTC is carried out as information, for the sentence a person reads. +# +# A FORK'S LINE IS NOT THE LANE'S (decision 8(c), A11 Addendum 4 ruling 8), so a +# payload opening `fork ` is skipped exactly as `lane_row_facts` skips it: a +# `RETIRED` about a fork would read as the LANE being retired, which is the +# opposite of what happened. +# +# A LINE WRITTEN BEFORE AMENDMENT 18(a) CARRIES NONE OF THE THREE SUB-FIELDS AND +# STAYS VALID: its binding is *"the window on the row's workstation, which is +# what they read today"*. So `host` falls back to the line's own `@<ws>` — which +# is the Rule 10 workstation, and is also what a container with no export writes +# into `host` deliberately — and `container` falls back to `none`. Amendment +# 7(i)'s cutover rule, with the fallback the clause itself names. +# +# 1 state bound · requested · released · free +# 2 host 3 container 4 window 5 utc 6 session 7 os +# 8 request utc 9 request session 10 request payload +# 11 release verb 12 release utc 13 release session 14 release payload +# 15 legacy `legacy` where the binding line predates clause (a) +# 16 foreign release verb 17 utc 18 session 19 payload — the release +# ANOTHER session wrote after the session named in argument 2 wrote +# its own last lane-kind line, which is clause (e)-s test and which +# survives a later binding by a third place +# +# 0 with the line, 1 where the LOG COULD NOT BE READ — which is not the same +# fact as "this lane has no binding" and never was (#26, the fail-closed family). +lane_binding_scan() { # <lane> [<this session uuid>] + lbs_lines=""; lbs_rc=0 + lbs_lines="$(lane_log_events "$1")" || lbs_rc=$? + [ "$lbs_rc" = 0 ] || return 1 + printf '%s\n' "$lbs_lines" | awk -v sep="$US" -v me="$(lc "${2-}")" ' + function field(pay, want, whole, n, i, sf, v, q) { + want = want " " + n = split(pay, sf, "; ") + for (i = 1; i <= n; i++) { + if (substr(sf[i], 1, length(want)) != want) continue + v = substr(sf[i], length(want) + 1) + sub(/^[ \t]+/, "", v); sub(/[ \t]+$/, "", v) + if (substr(v, 1, 1) == "\"") { + q = index(substr(v, 2), "\"") + if (q > 0) return substr(v, 2, q - 1) + } + if (!whole) sub(/ .*$/, "", v) + return v + } + return "" + } + BEGIN { FS = sep; state = "free" } + # THIS SESSION-S OWN LAST LANE-KIND LINE, wherever it is, and the release + # another session wrote AFTER it — clause (e), which says EVERY prompt from + # then on and not merely the prompt before the next binding (Copilot round 1 + # on this PR). Tracked beside the binding and never out of it: when a third + # place binds the lane after a forced release, the binding fields below move + # on to that new line while this pair stays exactly where it was, which is + # what makes the refusal persist as the clause says it must. + me != "" && tolower($4) == me && \ + ($3 == "STARTED" || $3 == "RESUMED" || $3 == "PAUSED" || $3 == "ENDED" || $3 == "RETIRED") { me_pos = NR; me_verb = $3 } + me != "" && tolower($4) != me && ($3 == "PAUSED" || $3 == "ENDED" || $3 == "RETIRED") { + if (substr($8, 1, 5) != "fork ") { + f_pos = NR; f_verb = $3; f_utc = $1; f_sess = $4; f_pay = $8 + # A release that NAMES this session is evidence on its own, whether or + # not this session ever wrote a line of its own: clause (e)-s `on behalf + # of <bound uuid>` is written by a place that read the binding, and the + # session it names may have been bound by a `lane-start` whose own + # STARTED was deferred for want of a uuid (Amendment 8(d), R-A8-2). + if (index(tolower($8), "on behalf of " me) > 0) { + ob_pos = NR; ob_verb = $3; ob_utc = $1; ob_sess = $4; ob_pay = $8 + } + } + } + $3 == "STARTED" || $3 == "RESUMED" { + if (substr($8, 1, 5) == "fork ") next + state = "bound"; seen = 1 + b_utc = $1; b_sess = $4; b_ws = $5; b_pay = $8 + r_utc = ""; r_sess = ""; r_pay = "" + x_verb = ""; x_utc = ""; x_sess = ""; x_pay = "" + next + } + $3 == "HANDOFF-REQUESTED" { + if (state != "bound" && state != "requested") next + state = "requested" + r_utc = $1; r_sess = $4; r_pay = $8 + next + } + $3 == "PAUSED" || $3 == "ENDED" || $3 == "RETIRED" { + if (substr($8, 1, 5) == "fork ") next + if (!seen) { state = "free"; next } + state = "released" + x_verb = $3; x_utc = $1; x_sess = $4; x_pay = $8 + r_utc = ""; r_sess = ""; r_pay = "" + next + } + END { + host = field(b_pay, "host", 0); if (host == "") host = b_ws + cont = field(b_pay, "container", 0); if (cont == "") cont = "none" + win = field(b_pay, "window", 1) + os = field(b_pay, "os", 0) + # CLAUSE (a) CUTOVER RULE, CARRIED AS A FIELD OF ITS OWN: *"A line + # written before this amendment carries none of the three and stays + # valid; readers treat its binding as THE WINDOW ON THE ROW-S + # WORKSTATION, which is what they read today."* What they read today has + # no container in it — so a pre-amendment binding must not be filed under + # ANOTHER container merely because the asker is in one, which on an estate + # whose every line predates this clause would refuse every lane start + # inside every bench. The fallback values above are still what the read + # PRINTS (`none` is the answer a reader acts on); this field says which of + # them were read and which were supplied. + # (No apostrophe anywhere in this comment: the whole program is a + # single-quoted shell string, and one would end it — the same rule + # `LANES_REGISTER_INDEX_AWK` states for its own.) + # LEGACY IS ALL THREE ABSENT, NOT `host` ALONE (Copilot round 2 on + # openRepoTools#83). The writer drops an offending sub-field on its own + # and keeps the line — `R-A11-11`-s posture — so a MODERN line can carry a + # container and an os and no host, and calling that one pre-amendment + # would ignore the container it does carry and let another container past + # the fence. All three absent is the only shape that is really a line from + # before this clause; anything less fails CLOSED, matched on host AND + # container like every other modern line. + legacy = (field(b_pay, "host", 0) == "" && field(b_pay, "container", 0) == "" && \ + field(b_pay, "os", 0) == "" ? "legacy" : "") + if (state == "free" || state == "released") { host = ""; cont = ""; win = ""; os = ""; legacy = "" } + # A release by another session counts only where it came AFTER this + # session-s own last line. One that came before it is a lane this session + # has bound or handed off since, and the clause is about being released + # from UNDER a session, not about anything that ever happened to the lane. + # A release by another session counts only where it came AFTER this + # session-s own last line, and only where this session HAS one: a uuid + # that appears nowhere in this log has been released from nothing, and + # every fresh transcript in a lane-s window would otherwise be refused for + # ever by the PAUSED its predecessor wrote. The exception is a release + # that names this session outright, which is evidence with no line of its + # own needed. + if (ob_pos > me_pos) { + f_verb = ob_verb; f_utc = ob_utc; f_sess = ob_sess; f_pay = ob_pay + } else if (me_pos == 0 || f_pos <= me_pos) { + f_verb = ""; f_utc = ""; f_sess = ""; f_pay = "" + } + # AND A SESSION THAT RELEASED THE LANE ITSELF WAS TAKEN FROM NOTHING. + # Clause (e) is about a binding released from UNDER a session that still + # holds it; where this session-s own last lane-kind line is a PAUSED, an + # ENDED or a RETIRED, it gave the lane up, and the next place-s release of + # it is ordinary history. A session in that state that is somehow still + # running is the (b) table-s superseded-transcript row, which says the + # right thing about it and names the right cure. + if (me_verb == "PAUSED" || me_verb == "ENDED" || me_verb == "RETIRED") { + f_verb = ""; f_utc = ""; f_sess = ""; f_pay = "" + } + printf "%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s\n", \ + state, 31, host, 31, cont, 31, win, 31, b_utc, 31, b_sess, 31, os, 31, \ + r_utc, 31, r_sess, 31, r_pay, 31, x_verb, 31, x_utc, 31, x_sess, 31, x_pay, 31, legacy, 31, \ + f_verb, 31, f_utc, 31, f_sess, 31, f_pay + }' + return 0 +} + +# IS THAT BINDING THIS PLACE'S? Clause (b): *"Liveness is pronounced only from +# INSIDE the binding's own `host` and `container`, where the pid namespace is +# the record's: from anywhere else a binding is UNKNOWN, never dead, whatever +# `kill -0` says."* So the comparison is made ONCE, here, and every surface that +# refuses on it reads the same answer. +# +# A MODERN RECORD MATCHES ON BOTH, AND ON THE HOST'S OWN NAME (Copilot round 2 +# on openRepoTools#83). The `$WS` fallback below is clause (a)'s CUTOVER +# affordance and nothing else: a line written before this amendment carries no +# `host`, and its binding is *"the window on the row's workstation"* — so the +# workstation's name is all such a line has to be matched on, and the container +# it never carried is not asked for. A line that DOES carry the three is matched +# on what it says: the machine's own hostname AND the container. Allowing `$WS` +# there let a record whose `host` is another machine read as `here` wherever the +# two names happened to coincide — and `lane-start` then skips the fence, which +# is the one refusal this clause exists to make. +# +# CLAUSE (a)'s OWN FALLBACK STILL WORKS THROUGH IT: a writer inside a container +# with no `$LANES_HOST` writes the Rule 10 workstation name into `host`, and a +# reader in that same container computes the same name the same way, so the two +# agree without this function having to guess which of the two names it is +# looking at. +# +# TWO FORMS, ONE RULE. `binding_is_here` takes the record's values as they were +# written; `binding_is_here_lc` takes them already lower-cased, for the listing, +# which asks this of every lane and may not spend two processes a lane on `lc`. +# The rule is in the second and the first is two `lc`s in front of it. +LANES_HOST_LC=""; LANES_WS_LC=""; LANES_CONTAINER_LC="" +# THE HOST HALF ON ITS OWN, because clause (b)'s two rules need different +# halves of it: the pid namespace is the host AND the container, while the tmux +# server one host's launcher mounts into every container it starts is THE HOST. +# Both take the same legacy affordance, and taking it in one place is what stops +# them drifting — which is exactly what the review found when only one of them +# had it (Copilot round 4 on openRepoTools#83). +binding_host_is_here_lc() { # <host, lower-cased> [legacy] + [ -n "$LANES_HOST_LC" ] || LANES_HOST_LC="$(lc "$LANES_HOST_NAME")" + [ -n "$LANES_WS_LC" ] || LANES_WS_LC="$(lc "$WS")" + [ "${1-}" = "$LANES_HOST_LC" ] && return 0 + # THE WORKSTATION NAME IS A PRE-AMENDMENT LINE'S ONLY HANDLE, and nothing + # else's: a line that carries the three says which machine it is on, and + # accepting a second name for this one lets another machine's binding read as + # local wherever the two strings coincide. + [ "${2-}" = legacy ] && [ "${1-}" = "$LANES_WS_LC" ] && return 0 + return 1 +} +binding_is_here_lc() { # <host, lower-cased> <container, lower-cased> [legacy] + binding_host_is_here_lc "${1-}" "${3-}" || return 1 + [ "${3-}" = legacy ] && return 0 + [ -n "$LANES_CONTAINER_LC" ] || LANES_CONTAINER_LC="$(lc "$LANES_CONTAINER_NAME")" + [ "${2-}" = "$LANES_CONTAINER_LC" ] || return 1 + return 0 +} +binding_is_here() { # <host> <container> [legacy] + binding_is_here_lc "$(lc "${1-}")" "$(lc "${2-}")" "${3-}" +} + +# IS THIS THE SAME BINDING AS THE ONE THAT WAS READ? Five fields and not two +# (Copilot round 7 on openRepoTools#83). A binding is `host`, `container` and +# `window` — that is clause (b)'s own definition — and the UTC and session are +# what tell one of them from the next at the same place. Compared on the UTC and +# the session alone, a lane released and REBOUND within the same second by a +# process carrying the same transcript id reads as unchanged, and the act that +# follows the comparison (a forced `PAUSED`, or carrying on into a bind) lands +# on a holder that arrived after the read. The log has a one-second UTC and this +# estate resumes one transcript from several places, so neither field is +# distinguishing on its own. +# +# TEN ARGUMENTS IN TWO GROUPS OF FIVE, in the order `binding` prints them. +binding_identity_same() { # <h1> <c1> <w1> <u1> <s1> <h2> <c2> <w2> <u2> <s2> + [ "${1-}" = "${6-}" ] || return 1 + [ "${2-}" = "${7-}" ] || return 1 + [ "${3-}" = "${8-}" ] || return 1 + [ "${4-}" = "${9-}" ] || return 1 + [ "${5-}" = "${10-}" ] || return 1 + return 0 +} + +# THE ONE EXCEPTION CLAUSE (b) CARVES OUT, AND ITS FENCE. *"Where the asker and +# the binding share a tmux server (the launcher mounts one socket into every +# container it starts on a host) and the binding's window no longer exists +# there, the binding is DEAD — the pane a session must live in is gone."* +# +# THE SHARED SERVER IS THE **HOST**, NOT THE CONTAINER: that is the whole point +# of the exception, because two benches on one machine see one tmux and neither +# can see the other's pids. So the window is asked about wherever the `host` +# matches, container or no container, and never where it does not — a window id +# from another MACHINE resolving here would be a coincidence, and matching it is +# how a lane binds to a stranger's pane. +# +# THE ID *AND* THE SESSION, which is Amendment 11(h)'s agreement rule and the +# 2026-09-14 measurement behind it: tmux reuses window ids once a window is +# gone, and a stale record's `@1` resolved to a window of another session. +# +# live the window is there and its session agrees +# gone the id resolves nowhere here, or resolves in another session +# unknown not this host, no `@id` in the record, or no tmux to ask — and +# UNKNOWN IS NEVER DEAD, which is the clause's own word +binding_window_state() { # <host> <window sub-field> [legacy] + bws_host="${1-}"; bws_win="${2-}" + # THE SHARED SERVER IS THE HOST, AND THE HOST IS MATCHED BY THE ONE RULE + # `binding_is_here` USES (Copilot round 4 on openRepoTools#83). This test + # accepted the Rule 10 workstation name for EVERY record, so a MODERN line + # naming another machine could be judged `gone` here — and `gone` is the one + # answer that makes a binding elsewhere read DEAD and hands `lane-start` and + # `lane` the takeover path. A takeover of another machine's lane, out of a + # name that happened to coincide, is the collision this clause exists to stop, + # reached through its own exception. + binding_host_is_here_lc "$(lc "$bws_host")" "${3-}" || { printf 'unknown\n'; return 0; } + [ -n "$bws_win" ] || { printf 'unknown\n'; return 0; } + # `<session>:<index> <@id>` — two space-separated refs in ONE sub-field + # (Amendment 11(c)). The id is the second; a record that carries only the ref + # cannot be tested by the agreement rule at all. + bws_ref="${bws_win%% *}" + bws_id="${bws_win##* }" + case "$bws_id" in @[0-9]*) : ;; *) printf 'unknown\n'; return 0 ;; esac + command -v tmux >/dev/null 2>&1 || { printf 'unknown\n'; return 0; } + bws_now="$(tmux_window_field "$bws_id" '#{session_name}' 2>/dev/null || :)" + # `gone` IS THE ID RESOLVING NOWHERE, AND NOTHING ELSE (Copilot round 6 on + # openRepoTools#83). An id that resolves in ANOTHER session is two different + # facts wearing one answer: tmux reuses ids, so it may be a stranger's + # window — and `lane <name>` MOVES a live lane's window into the asking + # session (Addendum 1 (i-2)), which leaves the record naming the session it + # came from while the very same window, with the very same id, is alive one + # session along. Answered `gone`, that move would make a RUNNING lane read as + # a dead binding, and `gone` is the one answer that hands `lane-start` and + # `lane` the takeover path: a second process on a lane whose window a person + # had just pulled in front of themselves. + # + # So the two are separated and only the first is DEAD. The second is + # `unknown` — not this place's to pronounce, which is clause (b)'s own posture + # everywhere else — and it costs the takeover path exactly the case where an + # id has been reused, which was never a proof of death either. The RECORD + # going stale under a move is a real gap and it is filed, not papered over + # here: `lane` writes nothing to the register by design (Addendum 1), so + # keeping that field current is an act somebody has to rule on + # (opensoft/openRepoTools#95). + # + # AND AN EMPTY ANSWER IS TWO FACTS, OF WHICH ONLY ONE IS DEAD (Copilot round 9 + # on openRepoTools#83). `bws_now` comes back EMPTY both where the id resolves + # nowhere and where there is NO SERVER TO ASK AT ALL — a container the host's + # socket was never mounted into, a server not started yet, a `$TMUX_TMPDIR` + # that differs, a socket this user cannot read. AND THE STATUS IS NOT THE + # DISCRIMINATOR: measured on tmux 3.4, an id that resolves nowhere on a server + # that IS there answers `0` with an empty stdout, while no server at all + # answers 1 with an empty stdout and `error connecting to … (No such file or + # directory)` on stderr — which `tmux_window_field` sends to `/dev/null` and + # this read discards with `|| :`. `command -v tmux` catches only the + # workstation that has no tmux BINARY, and the two are not the same + # workstation. Read as `gone`, the second one makes + # EVERY binding of every other container on this host read DEAD — the one + # answer that hands `lane-start` and `lane` the takeover path — which is this + # clause's own collision reached through its own exception, on the very estate + # the exception was written for. The contract three lines above already says + # *"no tmux to ask"* is `unknown`; this is the code saying it too. + # + # SO THE SERVER IS ASKED A QUESTION THAT DOES NOT MENTION THE ID, and only a + # server that ANSWERS may pronounce. One extra fork, and only on the read that + # was about to say DEAD. + if [ -z "$bws_now" ]; then + tmux list-windows -a -F '#{window_id}' >/dev/null 2>&1 || { printf 'unknown\n'; return 0; } + printf 'gone\n'; return 0 + fi + [ "$bws_now" = "${bws_ref%%:*}" ] || { printf 'unknown\n'; return 0; } + printf 'live\n' + return 0 +} + +# ============ AMENDMENT 18(c)/(d)/(e) — THE SECOND PLACE ASKS =============== +# +# *"`lane-start <repo> <n>` and `restart <lane>` run from a place that is not the +# binding — a different `host`, `container` or `window` — REFUSE to bind. … A +# `y`, or the flag `--request-handoff` from a caller with no terminal, is THE +# REQUEST, and it is written before anything else is tried … Then, WHERE THE +# BOUND PANE IS ON THIS TMUX SERVER, the requester also types `/handoff --exit +# requested by <uuid>@<host>/<container>` into that pane … The requester then +# WAITS … When one arrives the lane is free and the requester binds as it would +# have."* +# +# THE MECHANISM IS HERE AND THE QUESTION IS AT THE DOOR. `lane-start` and `lane` +# each ASK in their own words — one is a launch that has already been typed, the +# other a pick out of a listing — and both then call THIS, so the line that is +# written, the pane that is typed into, the interval that is polled and the +# refusal that ends an empty wait are one implementation. That is the rule +# clause (h) gives `window-lane` and the one A11 Addendum 4 ruling 7 gave column +# 10 after two surfaces had each computed a restart line of their own. +# +# THE ORDER IS THE CLAUSE'S AND IT IS LOAD-BEARING: the line is written and +# PUSHED FIRST, so that a bound session anywhere can read it from `origin`, and +# only then is the pane typed into — which is an optimisation for the same-host +# case and never the request itself. A request that could not be written is not +# a request, and nothing is typed on the strength of one. +# +# $LANES_POLL_SECONDS the poll interval (default 15) — the one seam, and it +# is the suite's: a case that must watch a wait end +# cannot spend fifteen seconds per poll doing it. + +# THE REQUESTER'S OWN TRANSCRIPT UUID, which the line's `session` field is and +# which Amendment 7(b) admits nothing else into (clause (e), enforced in +# `write_event`). Four sources, first answer wins: the flag, `$LANES_SESSION`, +# the harness's own `$CLAUDE_CODE_SESSION_ID`, and the live record of THIS +# window. A caller with none of them is REFUSED rather than given a placeholder: +# the literal `unknown` is in this estate's append-only log four times already +# and no later line corrects any of them. +requester_uuid() { # [<--session value>] + ru_v="${1-}" + [ -n "$ru_v" ] || ru_v="${LANES_SESSION:-}" + [ -n "$ru_v" ] || ru_v="${CLAUDE_CODE_SESSION_ID:-}" + if [ -z "$ru_v" ]; then + here_context + if [ -n "$LANES_THIS_WINDOW" ]; then + ru_rec="$(window_session "$LANES_THIS_WINDOW" 2>/dev/null || :)" + [ -n "$ru_rec" ] && ru_v="${ru_rec%%"$US"*}" + fi + fi + valid_uuid "$ru_v" || return 8 + printf '%s\n' "$(lc "$ru_v")" +} + +# THIS WINDOW'S OWN `@id`, for the one comparison clause (c) needs before it +# writes anything: a request to hand off the window you are standing in is not a +# request, it is a loop. `here_context` gives `<session>:<@id>`; a record's +# `window` sub-field is `<session>:<index> <@id>`, so the ids are what compare. +binding_is_this_window() { # <window sub-field> + bitw_id="${1##* }" + case "$bitw_id" in @[0-9]*) : ;; *) return 1 ;; esac + here_context + [ -n "$LANES_THIS_WINDOW" ] || return 1 + [ "${LANES_THIS_WINDOW##*:}" = "$bitw_id" ] || return 1 + return 0 +} + +# THE FACTS A PERSON NEEDS TO DECIDE, in one place, so the question `lane-start` +# asks, the question `lane` asks and the refusal that ends an empty wait all +# name the same things (clause (e): *"the binding (`host`, `container`, +# `window`, the line and its `UTC`), the request and its `UTC`, whether the pane +# was reachable and typed into, and the one word that overrides"*). +binding_facts() { # <lane> <host> <container> <window> <utc> <session> <window state> + printf 'lane %s is bound to window %s in container %s on host %s (session %s, last line %s); this tmux server says that window is %s\n' \ + "$1" "${4:-none}" "${3:-none}" "${2:-unknown}" "${6:-unknown}" "${5:-unknown}" "${7:-unknown}" +} + +# The UTC of the lane's last `STARTED` or `RESUMED` — Amendment 18(b)'s BINDING, +# read from the lane's own log out of `origin/<branch>` like every other state +# read. Clause (h) rule 2 compares a record's `nameSince` against it: a rename +# OLDER than the binding is a title this window inherited, not an instruction +# somebody has just given. 0 with the stamp, 8 where the log names none, 1 where +# it could not be read. +lane_binding_utc() { # <lane> + lbu_lines=""; lbu_rc=0 + lbu_lines="$(lane_log_events "$1")" || lbu_rc=$? + [ "$lbu_rc" = 0 ] || return 1 + lbu_v="$(printf '%s\n' "$lbu_lines" | awk -F"$US" '$3 == "STARTED" || $3 == "RESUMED" { v = $1 } END { if (v != "") print v }')" + [ -n "$lbu_v" ] || return 8 + printf '%s\n' "$lbu_v" +} + +# ------------------------------------------------- (h)'s ONE ACT ON A PANE +# +# M1, ratified: *"the guard and the `SessionStart` hook rename by TYPING +# `/rename <lane>` into the session's own tmux pane with `tmux send-keys`: the +# only path that exists, run from inside the pane, only after the prompt has +# been refused and only while the pane's current command is `claude`."* +# +# THE PANE'S CURRENT COMMAND IS ASKED FIRST, and a pane that is running anything +# else is NOT typed into: `/rename openRepoTools-3` typed at a shell is a command +# that does not exist, and typed into an editor it is text somebody did not +# write. +# +# `claude` AND NOTHING ELSE, which is M1's own word — *"only while the pane's +# current command is `claude`"*. This test read `claude|node` for one round, on +# the reasoning that the harness is a node program and this format reports the +# process rather than the wrapper; MEASURED on Eagle 2026-09-14T23:4xZ, across +# the twelve panes tmux had, it is not: eleven lane panes report `claude`, two +# report `bash` (a pane whose session is under a launcher wrapper) and one +# `zsh`, and no pane reports `node` at all. So `node` bought nothing here and +# would have let a stray Node REPL in a pane take `/rename <lane>` as input +# (Copilot round 4 on this PR). A pane this refuses is not a lock that failed: +# the caller prints the line for the person to type, which is the cure — and on +# this estate today the `bash` panes are exactly where they will read it. +# +# 0 typed +# 1 no tmux, or `send-keys` itself refused +# 8 the pane's current command could not be read — fail closed, type nothing +# 9 the pane is running something else +guard_type() { # <pane target> <the line to type> + gt_pane="${1-}"; gt_text="${2-}" + [ -n "$gt_text" ] || return 1 + command -v tmux >/dev/null 2>&1 || return 1 + # THE RECORD'S PANE, ELSE THIS ONE — AND THIS ONE IS THE RIGHT FALLBACK + # BECAUSE OF WHERE THIS CODE RUNS. The pane comes from the live record's + # `tmux` field, and the harness has been seen to write NO `tmux` at all for a + # process plainly in a window (Amendment 8, ruling (g)'s third fact) — a + # record `transcript_holders` and `record_is_here` still place HERE, by the + # pane's own process tree. With an empty target the lock used to print "tmux + # would not take the keys" and type nothing, for a session whose name it could + # have fixed (Copilot round 2 on this PR). Both callers of this function run + # INSIDE the session's own pane — a `UserPromptSubmit` hook and a + # `SessionStart` hook do — so `#{pane_id}` with no `-t` is that session's + # pane, asked of tmux rather than guessed, and M1's condition below is still + # asked of whatever pane this resolves to. + [ -n "$gt_pane" ] || gt_pane="$(tmux display-message -p '#{pane_id}' 2>/dev/null || :)" + [ -n "$gt_pane" ] || return 1 + gt_cmd="$(tmux_window_field "$gt_pane" '#{pane_current_command}' 2>/dev/null || :)" + [ -n "$gt_cmd" ] || return 8 + case "$gt_cmd" in claude) : ;; *) return 9 ;; esac + tmux send-keys -t "$gt_pane" "$gt_text" Enter 2>/dev/null || return 1 + return 0 +} + +# THE PENDING OFFER, held per session id and expiring with the session (clause +# (h) rule 2). It is a file and not a variable because the next prompt is a +# different process: `$CLAUDE_CONFIG_DIR/lanes/offers/<uuid>`, the harness's own +# per-profile configuration directory, which is where a fact about one session +# belongs and is not the register. +guard_offer_file() { # <session uuid> + printf '%s/lanes/offers/%s\n' "${CLAUDE_CONFIG_DIR:-$HOME/.claude}" "${1-}" +} + +# `lane-start`, found the way every word in this toolset finds its siblings: +# beside this file first — `--install` places them in one directory — then on +# PATH. One resolution, so a workstation with two copies never reads one and +# runs the other. `$LANES_LANE_START` is the seam the suite sets. +# +# NAMED AS A SIBLING OF THIS FILE AND NOT OF ANY PARTICULAR WORD, because +# Amendment 18 Addendum 2 (in force 2026-09-14T16:50:32Z) takes `restart` off a +# person's PATH altogether — "i think we can drop restart as a cli command and +# keep it inside a claude session with /restart … lane does all the things a +# user wants" — and opensoft/openRepoTools#43 removes the file. A comment that +# pointed at it for its resolution order would name a file that is going. +guard_lane_start() { + if [ -n "${LANES_LANE_START:-}" ]; then printf '%s\n' "$LANES_LANE_START"; return 0; fi + if [ -x "$SCRIPT_DIR/lane-start" ]; then printf '%s\n' "$SCRIPT_DIR/lane-start"; return 0; fi + command -v lane-start 2>/dev/null || printf '' +} + +# ------------------------------------------------------- the triple, printed +# +# EVERY REFUSAL PRINTS THE THREE NAMES AS THEY STAND, and prints them ONCE +# however many things are wrong. What a person sees is the state and then the +# one command, which is F-B6's rule — filled in, never `<repo> <n>`. +G_WINREF=""; G_WINNAME=""; G_ID=""; G_NAME=""; G_SRC=""; G_PID=""; G_PROF="" +G_ROW=""; G_LANE=""; G_SES_LANE="" +# AMENDMENT 16(f) — the former name this window still carried, and whether the +# guard managed to rename the window to the lane's current one. +G_WIN_WAS=""; G_WIN_FIXED=0 +GUARD_TRIPLE_DONE=0 +GUARD_RENAME_SAID=0 +# SAID ONCE, WHEREVER THE RUN ENDS. The guard's own rename of a window is the +# one act it takes that is not a refusal, so it is announced on the agreeing +# path too — a lock that silently did something is a lock nobody knows about, +# which is the rule `guard_lock_rename` already states for the typing. +guard_window_renamed_note() { + [ -n "$G_WIN_WAS" ] || return 0 + [ "$GUARD_RENAME_SAID" = 0 ] || return 0 + GUARD_RENAME_SAID=1 + if [ "$G_WIN_FIXED" = 1 ]; then + note "THIS WINDOW WAS NAMED '$G_WIN_WAS', WHICH IS A FORMER NAME OF LANE $G_LANE (${LANES_ALIASES_PATH:-lanes/aliases.tsv}, Amendment 16(e)) — so it has been renamed to $G_LANE for you (Amendment 16(f): a rename run from another window leaves this one to fix at its next prompt, and a window's name is one tmux call, not a typed one)." + else + note "THIS WINDOW IS NAMED '$G_WIN_WAS', WHICH IS A FORMER NAME OF LANE $G_LANE (${LANES_ALIASES_PATH:-lanes/aliases.tsv}, Amendment 16(e)), and tmux would not rename it. Rename it yourself: tmux rename-window -t ${G_WINREF:-<this window>} $G_LANE" + fi + return 0 +} +# +# THE HEADING IS AN ARGUMENT BECAUSE ONE CALLER DOES NOT REFUSE. An explicitly +# allowed mismatch (choice 1 below) prints the same three names and then lets +# the prompt through, and a line reading "THE NAME GUARD REFUSES THIS PROMPT" +# over a prompt it has just allowed is the guard lying about its own act. Every +# other caller passes nothing and gets the refusal heading unchanged. +guard_triple() { # [<heading>] + [ "$GUARD_TRIPLE_DONE" = 0 ] || return 0 + GUARD_TRIPLE_DONE=1 + gt_s="${G_ID:-unknown} '${G_NAME:-none}'" + [ -n "$G_SRC" ] && gt_s="$gt_s (nameSource $G_SRC)" + [ -n "$G_PID" ] && gt_s="$gt_s pid $G_PID" + [ -n "$G_PROF" ] && gt_s="$gt_s profile $G_PROF" + gt_w="${G_WINREF:-not in tmux} '${G_WINNAME:-none}'" + [ -n "$G_WIN_WAS" ] && gt_w="$gt_w — a former name of $G_LANE (Amendment 16(e))" + note "${1:-THE NAME GUARD REFUSES THIS PROMPT (lane-collision-protocol Amendment 12). The three names:}" + note " window $gt_w" + note " session $gt_s" + note " row ${G_ROW:-not read}" + guard_window_renamed_note + return 0 +} + +# SAFE-MODE RECOVERY, NAMED WHERE A PERSON COULD BE STUCK (clause (d)). +# Profile-only launches are exempt through `CLAUDE_NO_LANE=1` at dispatch. +# Claude's `--safe-mode` disables every hook and is visible in the prompt box; a +# session started that way is not a lane session and may not write the register +# or claim an object. It is printed by the INDETERMINATE refusals — the reads +# that could not be made — and not by the mismatches, which have a cure of their +# own one line above. +guard_bypass() { + printf '%s' "If this workstation cannot answer at all, \`claude --safe-mode\` runs with every hook off — and a session started that way is NOT a lane session: it may not write the register or claim an object." +} + +# <why> [<the one command, filled in>] — the shape of every row of the (b) +# table: the triple, one sentence saying what is wrong, and one line to type. +guard_refuse() { + guard_triple + note "$1" + [ -n "${2-}" ] && note "run: $2" + return 2 +} + +# ============================== `guard` ============================== +# +# THE (b) TABLE, ONE ROW PER STATE AND ONE CURE EACH, in the amendment's own +# order. Every message prints the register's own spelling of the lane +# (Amendment 15) and every command is filled in — or, for a lane named before +# Rule 4, which leaves its checkout unknown, SAYS it cannot be +# (`guard_refuse_start`, openRepoTools#73). +# +# the window is not a lane, the session name parses as `<repo>-<n>` +# -> `lane-start --no-launch <repo> <n>` THE 2026-09-10 CASE +# the window is not a lane, and neither is the session name +# -> `lane-start <repo> <n>` for the lane this work is — the guard cannot +# name it +# the window is a lane, this uuid is the row's LAST id, the session name is +# not a lane name (untitled, a fallback, `<lane> (N)`, any word that does not +# parse) -> THE LOCK RENAMES IT, and says so +# … the session name is ANOTHER lane's and a PERSON set it after the binding +# -> THE OFFER (D5) +# the window is a lane, this uuid is IN the cell but not last +# -> Amendment 8's cure: exit, `lane-start <repo> <n>` +# the window is a lane, this uuid is in NO row +# -> Amendment 8's cure: `lane-start --no-launch <repo> <n>` +# the window is a lane whose name matches TWO rows, or the register cannot be +# read -> refuse naming the read +# not inside tmux at all -> refuse (D2): a lane runs in a tmux window +# named for it +# +# AND THE AGREEING CASE IS SILENT AND COSTS NOTHING, which is the property that +# makes a hook at every prompt bearable at all. +guard_run() { # <the hook's JSON, on stdin already read> + gr_json="${1-}" + + # ---- (e) SCOPE, and the two exemptions are the cheapest tests there are. + # + # A SUBAGENT IS EXEMPT: subagents do not submit prompts, and the lane that + # runs them has already passed this guard. The hook input carries `agent_id` + # for one and nothing else does. + [ -z "$(jstr "$gr_json" agent_id)" ] || return 0 + # OUTSIDE THE PROJECTS ROOT THE GUARD IS SILENT (D1). A name there is a title + # and nothing more. INPUT THAT NAMES NO `cwd` AT ALL is not "outside": it is a + # read that did not happen, and clause (d) refuses those. + gr_cwd="$(jstr "$gr_json" cwd)" + if [ -z "$gr_cwd" ]; then + guard_refuse "the hook input carried no \`cwd\`, so whether this session is under the projects root — the whole of clause (e)'s scope — could not be read, and an indeterminate read refuses (Amendment 12(d)). $(guard_bypass)" + return 2 + fi + under_projects_root "$gr_cwd" "${PROJECTS_ROOT:-$HOME/projects}" || return 0 + + G_ID="$(lc "$(jstr "$gr_json" session_id)")" + gr_prompt="$(jstr "$gr_json" prompt)" + + # ---- THE WORKSPACE. Every other subcommand dies 1 here (the dispatcher's + # own guard, which this verb is exempt from); this one refuses with 2, + # because 1 does not block a prompt and clause (d) is fail CLOSED: a register + # that cannot be located is not a register that agrees. + if [ -z "$LANES_REPO" ] || [ -z "$LANES_DIR" ] || [ ! -f "$LANES_FILE" ]; then + guard_refuse "the ROW cannot be read, so the triple cannot be verified — and a triple that cannot be verified is not a triple that agrees (Amendment 12(d)). $(lanes_workspace_why) $(guard_bypass)" + return 2 + fi + + # ---- (b)'s LAST ROW: NOT INSIDE TMUX AT ALL (D2, "Refuse"). + here_context + if [ -z "$LANES_THIS_WINDOW" ]; then + if [ -z "${TMUX:-}" ]; then + guard_refuse "this session is not in a tmux window at all, and a lane RUNS in a tmux window named for it (Rule 4, Amendment 2). Open one and start the lane there." "lane-start <repo> <n> (in a tmux window)" + else + guard_refuse "tmux did not answer \`display-message -p '#{session_name}:#{window_id}'\`, so the WINDOW half of the triple could not be read — and an indeterminate read refuses (Amendment 12(d)). $(guard_bypass)" + fi + return 2 + fi + G_WINREF="$LANES_THIS_WINDOW" + G_WINNAME="$(tmux display-message -p '#W' 2>/dev/null || :)" + if [ -z "$G_WINNAME" ]; then + guard_refuse "tmux did not answer \`display-message -p '#W'\` for $G_WINREF, so the WINDOW's name could not be read — and an indeterminate read refuses (Amendment 12(d)). $(guard_bypass)" + return 2 + fi + + # ---- THE LIVE RECORD FOR THIS SESSION, AND AMENDMENT 18(h)'s COUNT, IN ONE + # READ. The hook is handed its own `session_id` by the harness, so the + # question asked is "which live processes carry THIS transcript", which is + # both halves at once and is the cheap shape (`transcript_holders` states the + # measurement). `window_session` asks the other question — "what is live in + # this window" — by parsing every record on the workstation, and at 11.8 s + # against 329 of them on 2026-09-14 it cannot run inside a five-second hook. + # + # NOT `$( )`: `transcript_holders` sets `SESSION_FILES_ERR`, and a subshell + # would keep the reason for the failure to itself. + gr_tmp="$(mktemp "${TMPDIR:-/tmp}/lanes-edit-gd.XXXXXX" 2>/dev/null || printf '')" + if [ -z "$gr_tmp" ]; then + guard_refuse "no temporary file could be made under ${TMPDIR:-/tmp}, so this workstation's session records could not be read (Amendment 12(d)). $(guard_bypass)" + return 2 + fi + gr_rc=0 + transcript_holders "$G_ID" > "$gr_tmp" || gr_rc=$? + if [ "$gr_rc" != 0 ] && [ "$gr_rc" != 8 ]; then + rm -f -- "$gr_tmp" + guard_refuse "this workstation's session records could not be read (${SESSION_FILES_ERR:-unknown error}), so the SESSION's own name could not be read — and an indeterminate read refuses (Amendment 12(d)). $(guard_bypass)" + return 2 + fi + gr_here=""; gr_here_tgt=""; gr_others="" + while IFS="$US" read -r gh_pid gh_kind gh_tgt gh_prof gh_where gh_verdict gh_file; do + [ -n "${gh_pid:-}" ] || continue + # A COMPANION IS NEITHER — not this window's record and not a second + # process — so it is passed over in silence, which is Amendment 8 ruling + # (g)'s own posture. Two records of ONE session in ONE pane are that + # session seen twice, and the WINDOWED one is the better witness of it. + case "$gh_verdict" in + here) + if [ -z "$gr_here" ] || { [ "$gr_here_tgt" = none ] && [ "$gh_tgt" != none ]; }; then + gr_here="$gh_pid$US$gh_kind$US$gh_tgt$US$gh_prof$US$gh_file"; gr_here_tgt="$gh_tgt" + fi ;; + duplicate) + gr_others="${gr_others}${gr_others:+, }pid $gh_pid ($gh_where, kind $gh_kind, profile $gh_prof)" ;; + esac + done < "$gr_tmp" + rm -f -- "$gr_tmp" + if [ -z "$gr_here" ]; then + guard_refuse "no live session record in THIS window ($G_WINREF) carries this session id, so the SESSION's own name could not be read — and an indeterminate read refuses (Amendment 12(d)). The records were read; none of them is this window's. $(guard_bypass)" + return 2 + fi + IFS="$US" read -r G_PID gr_kind gr_tgt G_PROF gr_file <<<"$gr_here" + gr_blob="$(cat -- "$gr_file" 2>/dev/null || :)" + G_NAME="$(jstr "$gr_blob" name)" + G_SRC="$(jstr "$gr_blob" nameSource)" + # THE PANE ONLY FROM A TARGET THAT NAMES THIS WINDOW. `here` is true by the + # record's target OR by the pane's own process tree, and tmux REUSES window + # ids — so a record that is here BY ANCESTRY can carry a target another + # window now answers to, and `/rename` typed into it would land in somebody + # else's pane. M1's gate cannot catch that one: the other pane is running + # `claude` too (Copilot round 3 on this PR). Where the record's target does + # not name this window the pane is left EMPTY, and `guard_type` asks tmux for + # the pane this hook is running in, which is the session's own. + gr_pane="" + if [ -n "$gr_tgt" ] && [ -n "$LANES_THIS_WINDOW" ] && [ "${gr_tgt%.*}" = "$LANES_THIS_WINDOW" ]; then + case "$gr_tgt" in *.%*) gr_pane="${gr_tgt##*.}" ;; esac + fi + + # ---- THE REGISTER'S TEXT, TESTED POSITIVELY, ONCE, BEFORE THE ROW IS READ + # (openRepoTools#60). `register_text` prefers `origin/<branch>` and falls back + # to this checkout's file, and where both come back empty — a file this + # checkout cannot open, with no published copy — it answers EMPTY TEXT AND 0, + # because it ends in a `printf`. Every read below then finds no rows, and the + # table refused by its LAST arm, "whose row does not name this uuid at all", + # with a cure that cannot mend a read that did not happen. A status on + # `rows_named_ci` is not the place: its status is its awk's, which says nothing + # about the text, and it is shared with `canon_lane` and Amendment 15's + # callers. The awk below has one job, and its status IS the answer. + # HERE, AND NOT BESIDE THE WORKSPACE TEST WHERE #60 PROPOSED IT: there neither + # the window nor the session has been read yet, so the triple this refusal + # prints said `not in tmux` about a session that is. Here it names both, and + # `row not read`, which is the one thing that is not known. + # IT COSTS ONE `cat` AND ONE `awk`, ~6 ms on a 1.3 MB register: the text is + # cached beside `$SE_CACHE_FILE` for the life of this process, so this is the + # render the first read below would have made, moved here — `GIT_TRACE` counts + # one `git show` of the register per prompt with this test and without it. It + # is streamed and not captured: `$( )` of the same megabyte measured ~30 ms. + if ! register_text 2>/dev/null | awk 'NF { t = 1 } END { exit !t }'; then + guard_refuse "the register's TEXT could not be read — neither \`origin/$LANES_BRANCH:$LANES_PATH\` nor $LANES_FILE rendered a line — so the ROW cannot be read and the triple cannot be verified. A register that could not be read is not a register with no row for this lane, and an indeterminate read refuses (Amendment 12(d)). $(guard_bypass)" + return 2 + fi + + # ---- THE ROW, from `origin/<branch>` as this checkout last had it (R19), and + # every comparison case-insensitive with the register's spelling printed + # (Amendment 15). + # AMENDMENT 16(e) — BOTH LOOKUPS RESOLVE AN ALIAS. A rename run from another + # window leaves this one named for the lane as it was (clause (f) says so in + # as many words), and read byte for byte that window names no row at all: the + # guard would send a running lane to `lane-start --no-launch` for a row it + # already has, under a name the register no longer carries. `rows_named_ci_alias` + # is `rows_named_ci` with the table behind it, so the row this window's name + # answers for is the row the lane is in today. + # AND A TABLE THIS READ COULD NOT OPEN REFUSES THE PROMPT (Copilot round 3 on + # openRepoTools#81). `|| :` made an unreadable `lanes/aliases.tsv` look like + # "this name is no lane", and the `lane_shaped` fallback below then bound the + # window's own former spelling — sending a running lane to `lane-start + # --no-launch` for a row it already has. Clause (d) is fail CLOSED and this is + # exactly its shape: a triple that cannot be verified is not a triple that + # agrees. + # `gr_warc` AND NOT `gr_arc`, WHICH THIS FUNCTION NOW USES FOR THE ANSWER'S + # STATUS (#87). Both are set before every read of them, so nothing leaked; + # one name for two questions in one function is the kind of thing that only + # stays harmless until somebody moves a block. It pairs with `gr_sarc`, the + # session-name read below. + gr_warc=0 + gr_hits="$(rows_named_ci_alias "$G_WINNAME" 2>/dev/null)" || gr_warc=$? + if [ "$gr_warc" = 5 ]; then + guard_refuse "${LANES_ALIASES_PATH:-lanes/aliases.tsv} could not be read ($(lane_alias_err)), so whether this window's name '$G_WINNAME' is a FORMER name of a lane could not be established — and an indeterminate read refuses (Amendment 12(d), Amendment 16(e)). $(guard_bypass)" + return 2 + fi + gr_n="$(printf '%s' "$gr_hits" | grep -c . || :)" + if [ "$gr_n" -gt 1 ]; then + guard_refuse "the register holds $gr_n rows whose lane names differ only by case for this window's name '$G_WINNAME': $(printf '%s' "$gr_hits" | tr '\n' ' '). A lane name is ONE name under any case (Amendment 15), so no read under it is unambiguous and a register that cannot be read is not a register that agrees (Amendment 12(b))." "merge them into one row (Amendment 15(d)) — append the newer row's session id(s) to the older row's session cell, in order, and remove the newer row in the SAME commit" + return 2 + fi + if [ "$gr_n" = 1 ]; then G_LANE="$gr_hits" + elif lane_shaped "$G_WINNAME"; then G_LANE="$G_WINNAME" + fi + + # ---- AMENDMENT 16(f) — AND THE WINDOW IS RENAMED HERE, not merely reported. + # The two halves of the triple are fixed by different acts for a reason: a + # running session's NAME can only be changed from inside it, which is why + # (h)1's lock TYPES `/rename`, while a WINDOW's name is one tmux call any + # client can make — `lane-start:1849` makes exactly this one. So where this + # window still carries a former name of its lane, the guard renames it and + # says so, rather than refusing a prompt over a difference it can close + # itself. It costs nothing where no lane was ever renamed: `G_WIN_WAS` is set + # only when the alias table answered above. + # + # UNTARGETED, LIKE `lane-start:1849` AND `lane-handoff:517`. This hook runs + # INSIDE the session's own pane, so tmux's current window IS the one being + # named, and a `-t` here would be a second spelling of a window this file + # already has three of (Amendment 11(c)) — one more place for two of them to + # disagree. `rename-window` also turns automatic-rename OFF for the window, + # which is what makes the new name survive the next command that runs in it. + gr_wl="$(lc "$G_WINNAME")" + if [ -n "$G_LANE" ] && [ "$gr_wl" != "$(lc "$G_LANE")" ]; then + G_WIN_WAS="$G_WINNAME" + if tmux rename-window "$G_LANE" 2>/dev/null; then + G_WIN_FIXED=1 + fi + fi + + gr_sarc=0 + gr_snhits="$(rows_named_ci_alias "$G_NAME" 2>/dev/null)" || gr_sarc=$? + if [ "$gr_sarc" = 5 ]; then + guard_refuse "${LANES_ALIASES_PATH:-lanes/aliases.tsv} could not be read ($(lane_alias_err)), so whether this session's name '${G_NAME:-none}' is a FORMER name of a lane could not be established — and an indeterminate read refuses (Amendment 12(d), Amendment 16(e)). $(guard_bypass)" + return 2 + fi + gr_snn="$(printf '%s' "$gr_snhits" | grep -c . || :)" + if [ "$gr_snn" -gt 1 ]; then + guard_refuse "the register holds $gr_snn rows whose lane names differ only by case for this session's name '$G_NAME': $(printf '%s' "$gr_snhits" | tr '\n' ' '). A lane name is ONE name under any case (Amendment 15)." "merge them into one row (Amendment 15(d))" + return 2 + fi + if [ "$gr_snn" = 1 ]; then G_SES_LANE="$gr_snhits" + elif lane_shaped "$G_NAME"; then G_SES_LANE="$G_NAME" + fi + + gr_ids=""; gr_last="" + if [ -n "$G_LANE" ]; then + gr_ids="$(session_ids_of_lane "$G_LANE" 2>/dev/null || :)" + gr_last="$(printf '%s\n' "$gr_ids" | grep . | tail -n1 || :)" + if [ -n "$(row_of_lane "$G_LANE" 2>/dev/null || :)" ]; then + G_ROW="\`$G_LANE\` — last session ${gr_last:-none recorded}" + else + G_ROW="the register has no row for \`$G_LANE\`" + fi + else + G_ROW="this window names no lane, so no row is keyed by it" + fi + + # ---- AMENDMENT 18(h) — ONE LIVE PROCESS PER TRANSCRIPT, ASKED BEFORE THE + # PENDING OFFER IS ANSWERED. Clause (h) refuses *"every prompt in a process + # that shares its session id with another live one"*, and THE ANSWER TO THIS + # GUARD'S OWN QUESTION IS A PROMPT: a `2` consumed here runs `lane-start`, + # writes a register row and appends a uuid to a cell, out of a process that + # may not be writing anything at all — and the offer is held per SESSION ID, + # so the second process answers the first one's question. The offer is KEPT + # while the duplicate stands and is answered at the first prompt after the + # other process is retired (Copilot round 1 on this PR). + if [ -n "$gr_others" ]; then + guard_triple + note "ANOTHER LIVE PROCESS CARRIES THIS SESSION ID ($G_ID): $gr_others." + note "A transcript is held by ONE live process (Amendment 18(h), ratified 2026-09-14): two of them append to one file, each overwriting what the other wrote, and the row records an id that two processes answer for. Measured four times on 2026-09-14, the last at 18:14Z — a harness \`--fork-session\` in a background pty host beside the interactive resume, its record in ANOTHER profile's sessions/ directory." + if [ -n "$G_LANE" ]; then + note "retire the other one — it proves the process is this lane's duplicate and prints Amendment 6(d)'s act for it, and it ends, writes and kills nothing:" + note "run: lane-end $G_LANE --retire <pid>" + else + note "retire the other one: lane-end <lane> --retire <pid>. This window names no lane, so which lane it is is yours to name." + fi + return 2 + fi + + # ---- THE PENDING OFFER, ANSWERED BEFORE THE TABLE BELOW IS CONSULTED + # (clause (h) rule 2). The answer prompt is the person's reply to a question + # this guard asked, it is consumed here and never reaches the model, and the + # triple still disagrees BECAUSE of the rename being answered — so this + # cannot wait behind the table below. It DOES wait behind 18(h)'s count + # above, for the reason stated there. + # + # AND AN `allow` FILE IS NOT A PENDING QUESTION, so it is not answered here: + # it is a STANDING ANSWER to one the person has already settled, and it is + # honoured at the row of the table that states the mismatch it allows — never + # in front of the table, where it would also silence the SUPERSEDED and the + # not-in-any-row refusals, which are states nobody allowed and which the + # amendment keeps closed (the requirement's own words: unreadable, ambiguous, + # duplicate or superseded identity still refuses). + gr_off="$(guard_offer_file "$G_ID")" + gr_mode="" + [ -f "$gr_off" ] && gr_mode="$(sed -n -e 's/^mode=//p' "$gr_off" 2>/dev/null | head -n1)" + if [ -f "$gr_off" ] && [ "$gr_mode" != allow ]; then + # 3 IS "THE OFFER WAS STALE AND HAS BEEN DROPPED", and it is the one answer + # that does not consume the prompt: the table below judges it, which asks + # the question again where the mismatch still stands and refuses where the + # state has become one the amendment keeps closed. + gr_arc=0 + guard_answer "$gr_off" "$gr_prompt" "$gr_pane" || gr_arc=$? + [ "$gr_arc" = 3 ] || return 2 + gr_mode="" + fi + + # ---- AMENDMENT 18 CLAUSES (d) AND (e), THE BOUND SESSION'S TWO ANSWERS. + # Both are reads of THIS lane's own object log, made at this point for the + # reason (h)'s count above is made here: the lane is known, nothing has been + # judged yet, and a refusal here costs the prompt and nothing else. + # + # (d) a `HANDOFF-REQUESTED` newer than this session's binding and not yet + # answered by a `PAUSED` of its own -> refuse this ONE prompt, name who + # asked and from where, and type `/handoff --exit requested by …` into + # this pane ((h)1's mechanism, which `guard_type` already is). *"The + # person at the bound pane sees the refusal and the handoff run; nothing + # they typed is lost, because the refused prompt is theirs to type again + # in the new place."* + # (e) a `PAUSED` newer than the binding that THIS session did not write -> + # refuse EVERY prompt from then on, naming the line and who forced it, + # until the person here hands off or ends the session. *"Two places + # never both write a lane in silence; the worst a `--force` can do is + # make the old place stop, loudly."* + # + # BOTH ARE GATED ON THE BINDING BEING THIS SESSION'S, and the gate has two + # disjuncts because a lane's transcript changes under it: the binding's + # `session` field is this uuid, OR the binding's WINDOW is this window — which + # is the `/clear`, the usage reset and the profile switch, where the harness + # minted a new id and the row has not caught up. Without the second, a request + # aimed at a lane that had been cleared would be answered by nobody; without + # the first, a session in a window that merely carries the name would answer + # for somebody else's binding. + # + # WHAT IT COSTS, MEASURED: `lanes-edit.sh binding openRepoTools-3` against this +# estate's live register is **0.17 s** wall (2026-09-15), because it is one +# `git show` of ONE lane's log and one awk — not the register read the triple +# above already paid for. The guard's own budget is the amendment's `timeout 5`, +# and the two reads it makes before this one measured ~2 s and ~0.4 s. +# +# A READ THAT FAILED IS NOT A LANE WITH NOTHING PENDING — but it is not a + # refusal either, and that is a narrowing this guard makes deliberately. + # Clause (d) is fail-closed about the READS THAT BUILD THE TRIPLE; these two + # decide whether ANOTHER PLACE has asked for the lane, and a log that cannot + # be read there costs at worst a request answered one prompt later, while + # refusing on it would block every prompt of every lane on a workstation whose + # `origin` is briefly unreadable. It is said rather than swallowed. + # + # AND ONLY WHERE THIS WINDOW NAMES A LANE. With no lane there is no log to + # read and no binding to be asked for; the row below this block is the one + # that refuses a window naming none, and it says the right thing about it. + gr_bind=""; gr_bind_rc=0 + [ -n "$G_LANE" ] && { gr_bind="$(lane_binding_scan "$G_LANE" "$G_ID")" || gr_bind_rc=$?; } + if [ -z "$G_LANE" ]; then : + elif [ "$gr_bind_rc" != 0 ]; then + note "lane $G_LANE's object log could not be read, so whether another place has asked for this lane (Amendment 18(d)) or forced it away (18(e)) is NOT known this prompt. The prompt is not refused for it — the three names above agree — but a request would be answered one prompt late." + else + IFS="$US" read -r gb_state gb_host gb_cont gb_win gb_utc gb_sess gb_os gb_rutc gb_rsess gb_rpay \ + gb_xverb gb_xutc gb_xsess gb_xpay gb_legacy gb_fverb gb_futc gb_fsess gb_fpay <<EOF +$gr_bind +EOF + gb_mine=0 + [ -n "$gb_sess" ] && [ "$(lc "$gb_sess")" = "$G_ID" ] && gb_mine=1 + # THE WINDOW DISJUNCT IS A LOCAL TEST AND IS GATED LIKE ONE (Copilot round 4 + # on openRepoTools#83). It exists for the `/clear`, the usage reset and the + # profile switch, where the harness minted a new id and the binding's window + # is still this one — but a tmux `@id` names a window on ONE server and tmux + # reissues them from `@0`, so compared alone it could make THIS session the + # answerer for a binding on another host, or for a stale one whose id has + # since been given to somebody else: the guard would then type `/handoff + # --exit` into this pane and refuse this prompt for a request nobody made of + # it. Three tests, not one: the binding is in this host and container, its + # window RESOLVES here with its own session (Amendment 11(h)'s agreement + # rule, which is what `live` means), and only then is the id compared. + if [ "$gb_mine" = 0 ] && [ -n "$gb_win" ] \ + && binding_is_here "$gb_host" "$gb_cont" "$gb_legacy" \ + && [ "$(binding_window_state "$gb_host" "$gb_win" "$gb_legacy")" = live ] \ + && binding_is_this_window "$gb_win"; then + gb_mine=1 + fi + if [ "$gb_mine" = 1 ] && [ "$gb_state" = requested ]; then + # `by host <h>` IS ONE SUB-FIELD WHOSE NAME IS `by host`, which is how + # clause (c) spells the request's payload — `→ by host <h>; container + # <c>; window <w>; wait <n>s`. Read as `host` it matches nothing, because + # `payload_subfield` anchors on the START of a sub-field and this one + # opens `by `. The clause's spelling is the grammar here, not a typo in + # it, and the reader is what bends. + gb_by="$(payload_subfield "$gb_rpay" "by host")" + gb_bc="$(payload_subfield "$gb_rpay" container)" + gb_bw="$(payload_subfield "$gb_rpay" window all)" + gb_line="/handoff --exit requested by ${gb_rsess:-a session this line does not name}@${gb_by:-unknown}/${gb_bc:-none}" + gb_trc=0 + guard_type "$gr_pane" "$gb_line" || gb_trc=$? + guard_triple + note "A HANDOFF WAS REQUESTED for lane $G_LANE at ${gb_rutc:-an instant this line does not name} by ${gb_rsess:-a session this line does not name} from container ${gb_bc:-none} on host ${gb_by:-unknown}${gb_bw:+, window $gb_bw} — handing off (Amendment 18(d))." + gb_wait="$(payload_subfield "$gb_rpay" wait)" + note "A lane has ONE binding: that place cannot bind this lane until this one releases it, and it is WAITING on this session${gb_wait:+, for $gb_wait}. The handoff writes the PAUSED record, refreshes the handoff file with a fresh Rule 3 top block, and then ENDS this session, because a handoff to another place is a handoff and not a restart (Amendment 17(a) under \`--exit\`)." + case "$gb_trc" in + 0) note " \`$gb_line\` has been typed into this pane — it runs at this prompt's place, and THIS prompt is refused so the handoff goes first. Nothing you typed is lost: type it again in the new place." ;; + 9) note " this pane is running something other than \`claude\`, so nothing was typed into it (Amendment 12's M1 types only into a pane running claude). Run it yourself: $gb_line" ;; + 8) note " this pane's current command could not be read, so nothing was typed into it — fail closed. Run it yourself: $gb_line" ;; + *) note " tmux would not take the keys, so nothing was typed. Run it yourself: $gb_line" ;; + esac + note "If this lane is NOT going anywhere, the answer is still an act and not a silence: tell that place, and they can stop waiting." + return 2 + fi + # CLAUSE (e) IS ASKED OF THIS SESSION-S OWN TRACK, not of the latest + # binding (Copilot round 1 on this PR). Read off the binding, the refusal + # stopped the moment a THIRD place bound the lane — the scan-s `x_*` fields + # move on to the new line — and the clause says the refusal is EVERY prompt + # from then on, until the person here hands off or ends the session. Fields + # 16-19 are that track: the release another session wrote after this one-s + # own last lane-kind line, wherever the lane has been since. + if [ -n "$gb_fverb" ] && [ -n "$gb_fsess" ]; then + guard_triple + note "THIS LANE'S BINDING WAS RELEASED BY SOMEBODY ELSE (Amendment 18(e)). Lane $G_LANE's log carries a \`$gb_fverb\` at ${gb_futc:-an instant this line does not name}, written by session $gb_fsess — not by this one — after this session's own last line:" + note " ${gb_fpay:-(no payload)}" + note "Another place forced the lane away and has bound it, or is binding it now. TWO PLACES NEVER BOTH WRITE A LANE: every prompt in this session is refused from here on, and this is not a state a rename or a relaunch clears." + note "The exits, and both are yours: hand this session off properly, which records what it holds and ends it —" + note " lane-handoff --exit \"released from under me by $gb_fsess\"" + note "— or end the session. To take the lane BACK, do it from a place that can bind it, after this one has stopped." + return 2 + fi + fi + + # ---- (b) ROWS 1 AND 2: THE WINDOW IS NOT A LANE. + if [ -z "$G_LANE" ]; then + if [ -n "$G_SES_LANE" ]; then + guard_refuse_start "this window is named '$G_WINNAME', which is no lane, while the SESSION is named for lane $G_SES_LANE — so nothing binds this conversation to a row, no surface would refuse a second window taking the same lane, and the handoff this session writes is one only this profile can find. THAT IS THE 2026-09-10 CASE, which ran for three days." "$G_SES_LANE" --no-launch + else + guard_refuse "neither this window ('$G_WINNAME') nor this session ('${G_NAME:-none}') names a lane, so the guard cannot name one either: WHICH lane this work is is yours to say, and a guard that guessed would bind a window to a row nobody chose." "lane-start <repo> <n> (for the lane this work is)" + fi + return 2 + fi + + # ---- THE WINDOW IS A LANE. Where the uuid sits in the row's cell decides + # which of the next four rows applies, and the cell is a HISTORY written + # oldest first whose LAST id is the lane (Amendment 6(b)). + if [ -n "$gr_last" ] && [ "$G_ID" = "$gr_last" ]; then + # ---- THE DRIFTS THAT ARE NOT DECISIONS, AND AMENDMENT 16 ADDS THE SECOND. + # openRepoTools#87 left the LOCK exactly one case — a session name differing + # from the row's only by CASE, which is the same lane under Amendment 15 — + # and made every other readable mismatch a three-choice OFFER, because a + # person who renames a session to ANOTHER lane's name is choosing something + # and a guard may not choose for them. A FORMER NAME OF THIS VERY LANE IS + # NOT SUCH A CHOICE: clause (e) makes it resolve to this row for ever, so a + # session still named `repoRen-1` on a lane the register now spells + # `repoRen-7` is this lane under the name it was renamed away from — drift + # left behind by a rename run in ANOTHER window, which is precisely the + # state clause (f) exists to finish. Offering three ways to repair it would + # ask a person to decide what the rename already decided, and two of the + # three answers would be wrong: `1` would make the old name permanent and + # `2` would move the lane BACK to the name it was renamed away from. + # + # `$G_SES_LANE` IS THE TEST BECAUSE IT IS ALREADY THE RESOLVED ANSWER: it is + # `rows_named_ci_alias "$G_NAME"` above, so it is this lane exactly when the + # session's name is this lane's under any case or any former spelling. + if [ "$(lc "$G_NAME")" = "$(lc "$G_LANE")" ] \ + || { [ -n "$G_SES_LANE" ] && [ "$(lc "$G_SES_LANE")" = "$(lc "$G_LANE")" ]; }; then + # THE THREE AGREE. Under Amendment 15 they agree under any case — and the + # ROW's spelling is the one the session carries, so a name that differs + # only by case is renamed to it rather than refused for ever. + # AND AN ALLOWANCE DIES WITH THE MISMATCH IT ALLOWED: the names agreeing + # again is one of the two names having CHANGED, which is the requirement's + # own condition for it no longer applying. Leaving the file would let a + # rename back to the allowed spelling pass silently on a decision the + # person made about a state they have since left. + [ -f "$gr_off" ] && [ "$gr_mode" = allow ] && rm -f -- "$gr_off" + # AMENDMENT 16(f): the window may still have carried a former name a + # moment ago, in which case it has just been renamed and that is said + # here — the one thing this guard does that is not a refusal. + [ "$G_NAME" = "$G_LANE" ] && { guard_window_renamed_note; return 0; } + if [ "$(lc "$G_NAME")" = "$(lc "$G_LANE")" ]; then + guard_lock_rename "$gr_pane" "spells the lane '$G_NAME' where the register's row spells it '$G_LANE', and a lane name is ONE name under any case whose canonical spelling is the row's (Amendment 15)" + else + guard_lock_rename "$gr_pane" "is '$G_NAME', which is a FORMER name of lane $G_LANE (${LANES_ALIASES_PATH:-lanes/aliases.tsv}, Amendment 16(e)) — the same lane under the name it was renamed away from, and not a lane anybody is moving to" + fi + return 2 + fi + # ---- THE MISMATCH, AND THE ONE STATE THAT PASSES THROUGH IT. The + # allowance is honoured HERE and nowhere earlier: this is the row of the + # table it was given for — a readable current lane whose uuid is the row's + # LAST id and whose session name is not the lane's — so a superseded + # transcript, a uuid in no row, an ambiguous register and an unreadable + # read have all been refused above it, allowance or no allowance. + if [ "$gr_mode" = allow ] && guard_allow_active "$gr_off"; then + guard_triple "THE NAME GUARD ALLOWS THIS PROMPT ON AN EXPLICIT CHOICE (lane-collision-protocol Amendment 12). The three names:" + note "WARNING: this lane/session name mismatch was explicitly allowed for this transcript. It will remain allowed only while the lane and session names stay unchanged." + return 0 + fi + # AN ALLOWANCE THAT NO LONGER FITS IS DROPPED RATHER THAN CARRIED: either + # name having changed is exactly what invalidates it, and the person is + # asked again below. + [ "$gr_mode" = allow ] && rm -f -- "$gr_off" + guard_offer "$gr_off" "$gr_pane" + return 2 + fi + + if [ -n "$gr_ids" ] && printf '%s\n' "$gr_ids" | grep -qx -F -- "$G_ID"; then + guard_refuse_start "this is a SUPERSEDED transcript of lane $G_LANE: the row's session cell carries $G_ID but ENDS on $gr_last, so the conversation in this window is not the lane's and renaming it would not make it one. Exit this session and start the lane, which resumes the id the row ends on." "$G_LANE" + return 2 + fi + + guard_refuse_start "this window is lane $G_LANE, whose row ${gr_last:+ends on $gr_last and }does not name $G_ID at all — the harness minted a new transcript with nobody acting (a /clear, a usage reset, a profile switch). The lane is right and the ROW is behind, so the cure is the recording act and no relaunch: it reads the live record in this window and appends that uuid to the cell." "$G_LANE" --no-launch + return 2 +} + +# (h) rule 2's third test: is the rename NEWER than this window's binding? +# Amendment 18(b) makes the binding the lane's last `STARTED`/`RESUMED`, and +# `nameSince` is an epoch in MILLISECONDS (measured on this estate's records, +# 2026-09-14). A rename OLDER than the binding is a title this window inherited +# and not an instruction somebody has just given, so it is drift and the lock +# renames it back. A record with NO `nameSince` — an older harness — cannot be +# told apart either way and is drift too, which is (h)1's default and the +# closed direction. A lane whose log records no binding at all cannot make a +# rename older than one, so there the rename is the instruction. +# AND A LOG THAT COULD NOT BE READ IS A THIRD ANSWER, NOT EITHER OF THE TWO +# (openRepoTools#60). `lane_binding_utc` answers 1 for it — `log_path_ci` +# refuses two logs differing only by case (Amendment 15) — and this test folded +# that 1 into the 8, so the `SessionStart` hook, its one caller since #87 made +# the guard's answer the offer, told a person their rename was newer than a +# binding nobody read. Read as "not newer" it would type over a person's own +# `/rename`, which (h) rule 4 forbids, so the caller is told and names the read. +# 0 newer · 1 not newer, or no `nameSince` · 5 the lane's log could not be read +guard_rename_is_newer() { # <lane> <nameSince, epoch ms> + grn_lane="${1-}"; grn_since="${2-}" + case "$grn_since" in ''|*[!0-9]*) return 1 ;; esac + grn_rc=0 + grn_utc="$(lane_binding_utc "$grn_lane" 2>/dev/null)" || grn_rc=$? + [ "$grn_rc" = 0 ] || [ "$grn_rc" = 8 ] || return 5 + [ -n "$grn_utc" ] || return 0 + grn_e="$(epoch_of "$grn_utc")" + [ -n "$grn_e" ] || return 0 + [ "$grn_since" -gt "$((grn_e * 1000))" ] +} + +# ------------------------------------------------------ (h)1: THE LOCK RENAMES +# +# The guard refuses THIS ONE PROMPT so the rename lands first, types +# `/rename <lane>` into this pane, and says so. M1's conditions are +# `guard_type`'s; every outcome but a successful typing prints the line for the +# person to type themselves, because a lock that silently did nothing is a lock +# nobody knows is broken. +guard_lock_rename() { # <pane> <what is wrong with the name, as a clause> + glr_pane="${1-}"; glr_why="${2-}" + glr_rc=0 + guard_type "$glr_pane" "/rename $G_LANE" || glr_rc=$? + guard_triple + note "the session name $glr_why, and under the projects root the session name is not the person's to set freely — it is the LANE's (Amendment 12(h), THE LOCK)." + case "$glr_rc" in + 0) note "SO IT HAS BEEN RENAMED FOR YOU: \`/rename $G_LANE\` was typed into this pane ($glr_pane), which is the only path a running session's name has (M1). This one prompt is refused so the rename lands first — send it again." ;; + 8) note "the pane's current command could not be read, so NOTHING was typed: a \`/rename\` typed at a shell is a command that does not exist and typed into an editor is text nobody wrote. Type it yourself: /rename $G_LANE" ;; + 9) note "this pane is not running claude, so NOTHING was typed, for the reason above. Type it in the lane's own pane: /rename $G_LANE" ;; + *) note "tmux would not take the keys, so NOTHING was typed. Type it yourself: /rename $G_LANE" ;; + esac + # THE ' (N)' SUFFIX IS NOT READ HERE ANY MORE, and it is not lost. Two names + # reach this lock and NEITHER CAN CARRY ONE: a name differing from the lane's + # only by CASE, which has no room for a suffix, and a FORMER name of this lane + # (Amendment 16(e)), which is a KEY of the alias table — and `repoRen-1 (2)` + # is not that key, so a suffixed former name resolves to nothing and goes to + # the offer with every other wider mismatch. `guard_offer` prints ratified + # decision D4's reading of the suffix, where the state that has one arrives. + return 2 +} + +# F-B6 PRINTS EVERY COMMAND FILLED IN, AND THERE IS ONE LANE NAME THAT CANNOT +# BE. `lane_start_args` answers `<repo> <n>` for a lane named under Rule 4's +# `<repo>-<n>` form and `--dir <path> <lane>` for one named before it — and that +# `<path>` is a PLACEHOLDER, because nothing in the register, the window or this +# session says where such a lane's checkout is. Printing it in a diagnostic is +# honest; RUNNING it is not. `lane-start --no-launch --dir '<path>' legacy-ui` +# refuses on a directory that does not exist, and the offer that ran it would +# ask the same question at every prompt afterwards (Copilot round 1 on this PR). +# So the offer SAYS what it cannot fill in and choice `2` refuses instead of +# running it, with the offer kept so that `1` and `3` still answer it. +guard_args_filled() { # <lane> + gaf_a="$(lane_start_args "$1")" + case "$gaf_a" in *'<path>'*) return 1 ;; esac + return 0 +} + +# AND THE TABLE'S OWN CURES SAY IT TOO (openRepoTools#73, item 3). The offer was +# fixed and the diagnostic beside it was not: rows 1, 5 and 6 of the (b) table +# printed `$(lane_start_args …)` straight, so a lane named before Rule 4 got +# `run: lane-start --no-launch --dir <path> legacy-ui` — a `<path>` placeholder +# in the one line a person is told to type, which F-B6 says is printed filled +# in. Filled in where it can be; where it cannot, the reason is the OFFER's +# sentence, the act is the offer's own line, and the checkout is the person's to +# supply, because nothing this guard can read says which one it is. +guard_refuse_start() { # <why> <lane> [--no-launch] + grs_why="${1-}"; grs_lane="${2-}"; grs_flag="${3-}" + if guard_args_filled "$grs_lane"; then + guard_refuse "$grs_why" "lane-start ${grs_flag:+$grs_flag }$(lane_start_args "$grs_lane")" + return 2 + fi + guard_refuse "$grs_why Lane $grs_lane is named before Rule 4's \`<repo>-<n>\` form, so the command below cannot be filled in here: \`lane-start\` needs that lane's DIRECTORY and nothing in the register, the window or this session says which one it is — the checkout is yours to supply." "lane-start ${grs_flag:+$grs_flag }--dir <that lane's checkout> $grs_lane" + return 2 +} + +# ------------------------------------------------------------ (h)2: THE OFFER +# +# *"if the user does a rename, then we should offer to move to that lane or +# create a new lane if we do not have one as that name"* (D5, verbatim). The +# one thing the guard never does silently is decide, with nobody acting, which +# of two disagreeing LANES a window belongs to. +guard_offer() { # <offer file> <pane> + go_f="${1-}"; go_pane="${2-}" + mkdir -p -- "${go_f%/*}" 2>/dev/null || : + { printf 'mode=name-drift\n' + printf 'from=%s\n' "$G_LANE" + printf 'to=%s\n' "$G_SES_LANE" + printf 'session=%s\n' "$G_NAME" + printf 'uuid=%s\n' "$G_ID" + printf 'utc=%s\n' "$(utc_now)" + printf 'window=%s\n' "$G_WINREF" + printf 'pane=%s\n' "$go_pane" + } > "$go_f" 2>/dev/null || : + guard_triple + note "WARNING: the lane and Claude session names disagree. This prompt is paused until you choose how to repair or explicitly allow this lane." + note "1) explicitly allow this lane for this transcript (future prompts warn but do not block while both names stay unchanged)" + if [ -n "$G_SES_LANE" ]; then + go_row="$(row_of_lane "$G_SES_LANE" 2>/dev/null || :)" + if [ -n "$go_row" ]; then + go_last="$(last_session_id_of_lane "$G_SES_LANE" 2>/dev/null || :)" + note "2) adjust the lane to session $G_SES_LANE (existing lane; last session ${go_last:-none recorded})" + else + note "2) adjust the lane to session $G_SES_LANE (create or move to this lane)" + fi + note "3) adjust the session to lane $G_LANE (types \`/rename $G_LANE\` into this pane)" + else + note "2) adjust the lane to session — unavailable because '${G_NAME:-none}' is not a lane name the tooling can safely derive" + note "3) adjust the session to lane $G_LANE (types \`/rename $G_LANE\` into this pane)" + fi + # RATIFIED DECISION D4, WHERE THE STATE IT READS NOW ARRIVES. A `<lane> (N)` + # title is a mismatch and the SUFFIX IS EVIDENCE about another process, so it + # is said beside the choices rather than left for the person to notice. + go_base="${G_NAME% (*)}" + if [ -n "$go_base" ] && [ "$(lc "$go_base")" = "$(lc "$G_LANE")" ] && [ "$go_base" != "$G_NAME" ]; then + note "AND THE ' (N)' SUFFIX IS EVIDENCE: it is exactly what a rename into a title something else still holds mints, so another holder of '$G_LANE' was live when this session was named (Amendment 6(d), ratified decision D4). Naming them is a read of its own, kept off this hook's path because it costs about three seconds: \`lanes-edit.sh forks $G_LANE\`. Retiring one is \`lane-end $G_LANE --retire <pid>\`, which proves it is a fork, prints Amendment 6(d)'s act filled in, and ends, writes and kills nothing." + fi + note "Reply \`1\`, \`2\` or \`3\`. The answer is the NEXT prompt, it is consumed here and never reaches the model; anything else asks again." + [ -f "$go_f" ] || note "(the offer could not be written to $go_f, so the answer will be read as a fresh prompt and this question asked again — which is the safe direction)" + return 2 +} + +# A choice of 1 is deliberately sticky only for the exact readable identity it +# allowed. A renamed session, a different lane binding, or a new transcript +# must come back through the numbered offer. +guard_allow_active() { # <offer file> + gaa_f="${1-}" + [ "$(sed -n -e 's/^mode=//p' "$gaa_f" 2>/dev/null | head -n1)" = allow ] || return 1 + [ "$(sed -n -e 's/^from=//p' "$gaa_f" 2>/dev/null | head -n1)" = "$G_LANE" ] || return 1 + [ "$(sed -n -e 's/^session=//p' "$gaa_f" 2>/dev/null | head -n1)" = "$G_NAME" ] || return 1 + [ "$(sed -n -e 's/^uuid=//p' "$gaa_f" 2>/dev/null | head -n1)" = "$G_ID" ] || return 1 + return 0 +} + +# ------------ THE UUID IN THE NEW LANE'S CELL, WHICH `lane-start --bind` WRITES +# +# CLAUSE (h) RULE 2 NAMES THE END STATE AND RULE 3 REPEATS IT: after choice 2, +# *"window X, session X, ROW X STAMPED WITH THIS UUID"*. `lane-start --no-launch` +# used to perform every other part of that and NOT this one, by a fence that is +# right and stays: its step 3b VETO 1 — Amendment 11 clause (d) rule 1 — never +# takes a uuid that belongs to ANOTHER ROW, and after a rename this uuid belongs +# to `$ga_from`'s. +# +# MEASURED, AND IT WAS A LOOP AND NOT A BLEMISH. In the suite: choice `2` moved +# the window to `repoGD-2`, whose row then read `STARTED by 7a01ae69…` while this +# session was `aaaa0012-1111…`. The NEXT prompt therefore found a lane window +# whose row did not name this transcript — the last row of the (b) table — and +# refused with `lane-start --no-launch repoGD 2`, which vetoed for the same +# reason and changed nothing. So the guard made that last write itself, after +# `lane-start` returned — by which time `lane-start` had taken the destination +# row's ordinary RESUME path and stamped the row, the lane's log and the handoff +# with the id THE ROW ALREADY HAD, under `--no-launch`, about a conversation +# nobody was in (openRepoTools#70). +# +# THE WRITE IS `lane-start`'s NOW, IN ITS BINDING MODE. `--bind <this uuid>` is +# veto 1 answered by the person's `2` — clause (h) rule 4's limit is that the +# lock never moves a uuid between rows WITHOUT the person's yes, and this is the +# yes — so the cell is extended first and every stamp names THIS uuid, in one +# act, anchored on the PUBLISHED last id as `lane-start` always anchors, and +# where a cell records no uuid on the `none recorded` or `pending — set by the +# session's first act` text such a cell carries instead, which is this guard's +# former anchor rule moved there. +# +# SO THIS IS A READ, AND IT WRITES NOTHING. It says the end state rule 3 names +# is there, or prints the act that puts it there where `lane-start` could not: +# a checkout whose copy of the row is older than the published one, or a cell +# carrying no uuid and neither text. THE OLD WRITE IS NOT KEPT BEHIND IT AS A +# FALLBACK, because it would rescue neither: its anchor is `lane-start`'s, so a +# stale copy of the row refuses it exactly as it refused `lane-start` (whose own +# next write to that same row line has by then met the same difference as a +# rebase conflict), and a cell with neither text has nothing to anchor on. What +# it would add is a second append after a write whose push timed out, read +# against a published ref that never moved — the uuid in the cell twice. +# +# 0 the cell ends on this uuid +# 1 it does not, and the act that fixes it has been printed +guard_bound_check() { # <the lane moved to> + gbc_to="${1-}" + # THE CACHED REGISTER IS THE ONE FROM BEFORE `lane-start` RAN, and this is the + # one place in the file that reads it AFTER a writer has moved it: a row + # `lane-start` has just CREATED is not in it at all, and the answer would then + # be "no uuid" on the one path that most needs the true one. Both copies are + # dropped — the variable this shell holds and the file every subshell reads + # (A11 Addendum 4 ruling 12) — exactly as `log_sync` drops them after a fetch, + # and for the same reason: the ref has moved under them. + LANES_REGISTER_CACHE="" + gbc_rc="${SE_CACHE_FILE:+$SE_CACHE_FILE.register}"; [ -n "$gbc_rc" ] && rm -f -- "$gbc_rc" + gbc_last="$(last_session_id_of_lane "$gbc_to" 2>/dev/null || :)" + if [ "$(lc "$gbc_last")" = "$(lc "$G_ID")" ]; then + note "…and $gbc_to's session cell now ends on $G_ID, written by lane-start's binding mode — which is what the next \`lane-start $gbc_to\` resumes." + return 0 + fi + note "…but $gbc_to's session cell does NOT end on $G_ID (it ends on ${gbc_last:-no transcript uuid at all}; lane-start's own words are above). Stamp it as this session's first act, which is Amendment 6(c)'s own remedy:" + note " LANES_LANE=$gbc_to lanes-edit.sh append-session-id $gbc_to \"<the session cell's last id>\" \"→ harness $G_ID (transcript uuid; profile ${G_PROF:-unknown})\"" + return 1 +} + +# The answer, and it is the whole of clause (h) rule 2's second half. +guard_answer() { # <offer file> <the prompt> <pane> + ga_f="${1-}"; ga_p="${2-}"; ga_pane="${3-}" + ga_mode="$(sed -n -e 's/^mode=//p' "$ga_f" 2>/dev/null | head -n1)" + ga_from="$(sed -n -e 's/^from=//p' "$ga_f" 2>/dev/null | head -n1)" + ga_to="$(sed -n -e 's/^to=//p' "$ga_f" 2>/dev/null | head -n1)" + ga_session="$(sed -n -e 's/^session=//p' "$ga_f" 2>/dev/null | head -n1)" + ga_ans="$(printf '%s' "$ga_p" | tr 'A-Z' 'a-z' | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')" + # THE OFFER IS READABLE WHEN IT NAMES ITS MODE AND THE LANE IT WAS MADE FOR, + # AND `session=` IS NOT PART OF THAT TEST. A session record carrying NO `name` + # at all is the (b) table's own untitled row and it reaches this offer with an + # empty name, so requiring one here made that state's offer UNANSWERABLE: the + # question was asked, the answer was dropped as unreadable, the next prompt + # asked it again, and choice 3 — the one that would have fixed it — could + # never be reached. An empty session name is a FACT about the session, and it + # is printed as `none` wherever this speaks. + if [ "$ga_mode" != name-drift ] || [ -z "$ga_from" ]; then + rm -f -- "$ga_f" + guard_refuse "the pending offer at $ga_f could not be read, so it has been dropped rather than answered on a guess. Send your prompt again and the question will be asked afresh." + return 2 + fi + # AND THE QUESTION BEING ANSWERED MUST STILL BE THE QUESTION THAT WAS ASKED + # (Copilot round 1 on openRepoTools#87). The file is keyed by TRANSCRIPT, and + # a prompt is a later moment: between the offer and its answer the window can + # be renamed to another lane and the session renamed by hand, and every one of + # the three choices then acts on a state nobody was shown — `2` moves to a + # destination derived from a session name that has gone, `3` types `/rename` + # for a lane this window no longer is, and `1` records an allowance for a pair + # that does not exist. So the stored identity is compared with the live one, + # and a stale offer is DROPPED rather than answered: this prompt is not + # consumed, it is judged by the table below, which asks again where the + # mismatch still stands and refuses where the state has become one of the + # unsafe ones. 3 is that status, and `guard_run` is its only caller. + if [ "$ga_from" != "$G_LANE" ] || [ "$ga_session" != "$G_NAME" ]; then + rm -f -- "$ga_f" + note "the pending question was about lane $ga_from and session '${ga_session:-none}', and this window is now lane ${G_LANE:-none} with session '${G_NAME:-none}' — so the offer has been DROPPED rather than answered on a state you were never shown. Nothing was renamed or written. This prompt is judged afresh below." + return 3 + fi + case "$ga_ans" in + 1) + if ! { printf 'mode=allow\n' + printf 'from=%s\n' "$ga_from" + printf 'to=%s\n' "$ga_to" + printf 'session=%s\n' "$ga_session" + printf 'uuid=%s\n' "$G_ID" + printf 'utc=%s\n' "$(utc_now)" + } > "$ga_f" 2>/dev/null; then + guard_refuse "the explicit allow could not be recorded at $ga_f, so the mismatch remains unapproved. Nothing was renamed or written; answer 1 again after the session state is writable." + return 2 + fi + guard_triple + note "ALLOWED: this lane/session name mismatch is explicitly allowed for this transcript. This answer is consumed; send your work again. Future prompts will warn without blocking while the lane remains $ga_from and the session remains '${ga_session:-none}'." + return 2 ;; + 2) + if [ -z "$ga_to" ]; then + guard_refuse "choice 2 is unavailable because the session name '${ga_session:-none}' is not a lane name the tooling can safely derive. Nothing was renamed or written; the offer is kept. Choose 1 or 3." + return 2 + fi + if ! guard_args_filled "$ga_to"; then + guard_refuse "lane $ga_to is named before Rule 4's \`<repo>-<n>\` form, so choice 2 cannot be filled in here: \`lane-start\` needs that lane's DIRECTORY and nothing in the register, the window or this session says which one it is. NOTHING has been renamed, moved or written, and the offer is KEPT." "lane-start --no-launch --dir <that lane's checkout> $ga_to" + return 2 + fi + ga_start="$(guard_lane_start)" + if [ -z "$ga_start" ] || [ ! -x "$ga_start" ]; then + guard_refuse "there is no \`lane-start\` beside this file or on PATH, so this window has NOT moved to $ga_to and NOTHING has been written. The offer is kept: answer \`2\` again once it is installed (\`openRepoTools --install\`)." + return 2 + fi + # THE WINDOW IS RENAMED FIRST, AND THAT ORDER IS LOAD-BEARING. Clause (h) + # rule 2 lists the acts in it — *"window renamed, row created or this uuid + # appended to its cell"* — and `lane-start` will not do the second while the + # first is undone: its step 3b VETO 2 refuses to take the session live in a + # window NAMED FOR ANOTHER LANE (Amendment 11 clause (d) rule 1, veto 2, + # `R-A11-12`), which after choice 2 is exactly what this window is. Without + # the rename the binding mode below REFUSES, because `--bind` answers veto 1 + # and never veto 2 (openRepoTools#70) — and before it existed the lane was + # started and stamped with the person's transcript left OUT of its session + # cell, the one thing the next resume follows. The veto is right and stays: + # what changes is that the person has just said this window is the other + # lane. + if command -v tmux >/dev/null 2>&1; then + tmux rename-window "$ga_to" 2>/dev/null || + note "the window could not be renamed to $ga_to, so lane-start may refuse to take this session as that lane's (its step 3b veto 2)." + fi + ga_rc=0 + # ITS STDOUT IS THE COMMAND IT WOULD HAVE LAUNCHED, and a hook's stdout is + # not what a person reads: everything this act says goes to stderr, where + # the blocking reason is shown. + # UNQUOTED ON PURPOSE: `lane_start_args` prints TWO words, `<repo> <n>` — + # or `--dir <path> <lane>` for a lane named before the `<repo>-<n>` rule. + # AND IN ITS BINDING MODE (openRepoTools#70): `--bind` names THIS + # transcript, so the destination's cell is appended with it and the row's + # stamp, its log line and its handoff's Rule 3 stamp all name it — never + # the id that row would otherwise have resumed, which nobody is in. The + # flag is the guard's alone, so it is in this call and in no command this + # file prints for a person to type. + # shellcheck disable=SC2046 + "$ga_start" --no-launch --bind "$G_ID" $(lane_start_args "$ga_to") >&2 || ga_rc=$? + if [ "$ga_rc" != 0 ]; then + guard_refuse "\`lane-start --no-launch $(lane_start_args "$ga_to")\`, run in its binding mode for this transcript, exited $ga_rc (its own words are above), so this window has NOT moved and $ga_from has NOT been marked MOVED. The offer is KEPT, so answer \`2\` again once that refusal is settled, or choose \`3\` to rename the session back to $ga_from." + return 2 + fi + rm -f -- "$ga_f" + guard_triple + note "MOVED: this window is now lane $ga_to — renamed, and stamped. The prompt that answered the question is consumed; send your work again." + guard_bound_check "$ga_to" || : + if [ -n "$(row_of_lane "$ga_from" 2>/dev/null || :)" ]; then + # AMENDMENT 13(a) — THE STATE IS SET, NOT APPENDED. This window has just + # moved to another lane, so the lane it LEFT is not running in it any + # more: `PAUSED` is where that lane now is, and the line says where it + # went. It used to be an `append-row-status` of `MOVED → <lane>`, which + # left the cell saying two things at once — whatever state it opened with, + # and this. + # THE LINE IS BOUNDED (Copilot round 5 on openRepoTools#82). A lane name is + # bounded in its CHARACTERS by `check_lane_name` and not in its length, and + # this line carried it twice: a long enough name makes `set-row-state` + # refuse the very write that records where the work went — after the window + # has already been renamed and moved. The name is said ONCE, and cut where + # even once does not fit, so the act always records something true. + ga_line="this window moved to lane $ga_to on the person's choice 2 at the guard" + if [ "${#ga_line}" -gt 230 ]; then + ga_line="${ga_line:0:230}" + case "$ga_line" in *' '*) ga_line="${ga_line% *}" ;; esac + ga_line="$ga_line ..." + fi + if "$RESOLVED" set-row-state "$ga_from" "PAUSED · $ga_line" >&2; then + note "…and $ga_from's row now reads PAUSED, naming the move to $ga_to." + else + note "…but $ga_from's row could NOT be marked (its writer's words are above). Run: lanes-edit.sh set-row-state $ga_from \"PAUSED · $ga_line\"" + fi + else + note "…and the register has no row for $ga_from, so there is nothing to mark MOVED there." + fi + return 2 ;; + 3) + ga_trc=0 + guard_type "$ga_pane" "/rename $ga_from" || ga_trc=$? + guard_triple + case "$ga_trc" in + 0) rm -f -- "$ga_f"; note "ADJUSTED SESSION TO LANE $ga_from: \`/rename $ga_from\` was typed into this pane ($ga_pane). The prompt that answered the question is consumed; send your work again." ;; + *) note "the rename could NOT be typed into this pane, so the session is still named '${ga_session:-none}'. NOTHING was written; the offer is kept. Type it yourself: /rename $ga_from" ;; + esac + return 2 ;; + *) + guard_triple + note "that is not an answer to the pending question, so it has been refused rather than acted on: this window is lane $ga_from and this session is named '${ga_session:-none}'." + note "1) allow this lane for this transcript 2) adjust the lane to session ${ga_to:-${ga_session:-none}} 3) adjust the session to lane $ga_from (types \`/rename $ga_from\`)" + # THE SAME SENTENCE THE OFFER ENDS ON, because a question asked again is + # asked in the words it was asked in: a person who is being re-asked has + # just typed something else, and two spellings of one question is how they + # come to believe the second one takes different answers. + note "Reply \`1\`, \`2\` or \`3\`. The answer is the NEXT prompt, it is consumed here and never reaches the model; anything else asks again." + return 2 ;; + esac +} + + +# ------------------------------- CLAUSE (f): THE `SessionStart` BLOCK'S LINE +# +# *"Where the record's name differs from the window's lane it prints +# `session name '<x>' was not the lane '<y>' — renamed` and types the rename +# ((h)1), so the first prompt already finds the three agreeing. It stays +# read-only against the register and non-blocking, as Amendment 8 made it; the +# refusal is the `UserPromptSubmit` hook's."* +# +# AND AMENDMENT 18(h)'s READ BESIDE IT, SAID AND NOT ACTED ON: where another +# live process carries this session id, the block NAMES it and the retire act. +# The guard refuses on that; this hook refuses nothing and never will — a hook +# that fails is a hook that breaks the session it was meant to orient (R-A8-1), +# and typing into its own pane writes nothing anywhere, which is why (h)1 gives +# it that one act and no other. +# +# EVERY PATH RETURNS 0. A read that failed prints nothing rather than guessing: +# the guard is the surface that refuses on an indeterminate read, and doing it +# twice, in the hook that may not, would be the same failure one layer up. +ssb_name_line() { # <session uuid> <lane, or empty> + snl_id="${1-}"; snl_lane="${2-}" + [ -n "$snl_id" ] || return 0 + snl_tmp="$(mktemp "${TMPDIR:-/tmp}/lanes-edit-sn.XXXXXX" 2>/dev/null || printf '')" + [ -n "$snl_tmp" ] || return 0 + snl_rc=0 + # IN A SUBSHELL, AND THAT IS R-A8-1 AND NOT TIDINESS. *"This hook never fails + # and always exits 0"*; `|| snl_rc=$?` catches a RETURN and catches nothing + # else, because a fatal inside a function called in this shell — an unbound + # variable under `set -u`, a `die` on a path nobody expected to reach one — + # exits the shell itself, `|| :` at the call site and all. Measured: with + # `th_here_prof` unset, `lanes-edit.sh session-start` exited 1 and printed no + # block at all, which is precisely the hook breaking the session it was + # written to orient. Nothing here needs state from the call — the rows come + # back through a file — so the subshell costs nothing and bounds it. + ( transcript_holders "$snl_id" ) > "$snl_tmp" 2>/dev/null || snl_rc=$? + if [ "$snl_rc" != 0 ]; then rm -f -- "$snl_tmp"; return 0; fi + snl_file=""; snl_tgt=none; snl_others="" + while IFS="$US" read -r sn_pid sn_kind sn_tgt sn_prof sn_where sn_verdict sn_file; do + [ -n "${sn_pid:-}" ] || continue + # The same three-way reading the guard makes, and for the same reasons. + case "$sn_verdict" in + here) + if [ -z "$snl_file" ] || { [ "$snl_tgt" = none ] && [ "$sn_tgt" != none ]; }; then + snl_file="$sn_file"; snl_tgt="$sn_tgt" + fi ;; + duplicate) + snl_others="${snl_others}${snl_others:+, }pid $sn_pid ($sn_where, kind $sn_kind, profile $sn_prof)" ;; + esac + done < "$snl_tmp" + rm -f -- "$snl_tmp" + if [ -n "$snl_others" ]; then + printf 'DEFECT: another live process carries this session id (%s): %s — a transcript is held by ONE live process (Amendment 18(h)), and two of them append to one file. Retire it: lane-end %s --retire <pid>\n' \ + "$snl_id" "$snl_others" "${snl_lane:-<lane>}" + fi + [ -n "$snl_lane" ] && [ -n "$snl_file" ] || return 0 + snl_blob="$(cat -- "$snl_file" 2>/dev/null || :)" + snl_name="$(jstr "$snl_blob" name)" + [ -n "$snl_name" ] || snl_name=none + [ "$snl_name" = "$snl_lane" ] && return 0 + # THE SAME FENCE AS THE GUARD'S, for the same reason and in the same words: + # a record that is here by ancestry can carry another window's target, and + # this hook types into a pane. `here_context` is asked HERE because the read + # above it runs in a subshell, which is where its answer would otherwise have + # stayed. + # A PERSON'S RENAME TO ANOTHER LANE IS THE GUARD'S TO OFFER, NOT THIS HOOK'S + # TO UNDO. Clause (f) types the rename for (h)1's case — DRIFT, a name that is + # no lane's — while (h) rule 2 makes a record whose `nameSource` is `user`, + # whose name is another lane's, and whose `nameSince` is later than this + # window's binding an INSTRUCTION, answered `1`, `2` or `3` at the next prompt. + # This hook runs on every startup, resume, clear and fork, so typing over such + # a name would erase the person's choice before the guard could put the + # question (Copilot round 4 on this PR): a rename, then a `/clear`, and the + # offer never happens. It is SAID here and left to the prompt that follows. + snl_src="$(jstr "$snl_blob" nameSource)" + snl_since="$(jnum "$snl_blob" nameSince)" + snl_nrc=1 + if [ "${snl_src:-}" = user ] && [ "$(lc "$snl_name")" != "$(lc "$snl_lane")" ] \ + && { [ -n "$(rows_named_ci "$snl_name" 2>/dev/null || :)" ] || lane_shaped "$snl_name"; }; then + snl_nrc=0 + guard_rename_is_newer "$snl_lane" "$snl_since" || snl_nrc=$? + fi + case "$snl_nrc" in + 0) + printf "session name '%s' is a lane name YOU set, newer than this window's binding to '%s' — the name guard offers the move at your next prompt (Amendment 12(h) rule 2); nothing was renamed here\n" \ + "$snl_name" "$snl_lane" + return 0 ;; + # A BINDING NOBODY COULD READ IS NEITHER ANSWER (openRepoTools#60): not + # "newer", which is a claim about a log this hook did not read, and not + # drift, which would type over the person's own rename. The read is named + # and the name left alone; this hook refuses nothing, so that is all it does. + 5) + printf "session name '%s' is a lane name YOU set, and lane %s's object log could not be read, so whether you set it after this window's binding is NOT known — nothing was renamed here, and the name guard puts it to you at your next prompt (Amendment 12(h) rule 4)\n" \ + "$snl_name" "$snl_lane" + return 0 ;; + esac + here_context + snl_pane="" + if [ -n "$snl_tgt" ] && [ "$snl_tgt" != none ] && [ -n "$LANES_THIS_WINDOW" ] \ + && [ "${snl_tgt%.*}" = "$LANES_THIS_WINDOW" ]; then + case "$snl_tgt" in *.%*) snl_pane="${snl_tgt##*.}" ;; esac + fi + snl_trc=0 + guard_type "$snl_pane" "/rename $snl_lane" || snl_trc=$? + if [ "$snl_trc" = 0 ]; then + printf "session name '%s' was not the lane '%s' — renamed\n" "$snl_name" "$snl_lane" + else + printf "session name '%s' is not the lane '%s' — run: /rename %s\n" "$snl_name" "$snl_lane" "$snl_lane" + fi + return 0 +} + +# ----------------------------------------------------------------- GitHub +# +# Rule 1 is one act: the three reads, the local line, and the comment that +# another person reads. The LOG is authoritative for a claim made through +# `claim` — a log line IS a live claim for Rule 1 purposes — and the GitHub +# comment is the copy that a person outside this estate can see. +# --no-github skips every call here, which is what the tests and an offline +# lane run with. + +# THE SIBLING READS NAME THE OBJECT, NOT ITS DIGITS (Amendment 8). Rule 1's +# reads 2 and 3 searched for the bare slug as a SUBSTRING, and a number is a +# substring of almost everything. Measured live on 2026-09-12 against the +# governing repository, `gh pr list --search 15` answered with PR #16 and PR +# #10 — GitHub had matched the digits inside "**15 of the register's 41 rows**" +# — and `ls-remote | grep 15` answered with a branch whose 40-character sha +# merely contains them, all under the heading "existing work on this object". +# A sibling that does not NAME the object is not evidence about it, and evidence +# that is not evidence is how a lane talks itself out of a claim it should make. +# +# TWO READS, TWO TESTS, because the two inputs are not the same kind of text. +# pr `gh pr list`'s rows, which are prose. A number in prose is a +# number; a REFERENCE is `#<n>`, so the hash is required — and its +# LEFT side is not bounded, because the canonical spelling of the +# thing being looked for is `owner/repo#15` and the character before +# the `#` is a letter. A row whose FIRST field is the number itself +# is kept too: that is the PR the object IS. +# branch `ls-remote`'s refs, which are names. `issue-15-fix` names the +# object and carries no hash, so the bare number as a whole token is +# the test — after the leading sha is stripped, so a branch is matched +# by its name and never by the digits of the commit it points at. +# An OpenSpec change directory has a word for a slug and takes the whole-token +# test in both modes. +# +# AND READ 2 FILTERS OVER THE BODY. `gh pr list`'s columns are number, title, +# branch and state; the reference that makes a PR a sibling is almost always in +# its BODY, which is what GitHub's own search matched and what the columns do +# not carry. Filtering the columns alone dropped PR #16 — the PR for this very +# issue, whose body says `brettheap/new-workstation#15` twice — while a filter +# with the hash optional kept #10 instead. So the body is fetched, flattened to +# one line, used for the test, and cut off again before anything is printed: +# under-reporting a sibling is the direction that lets a lane claim what +# somebody is already working on, and it is the one direction Rule 1 cannot +# afford. +ere_quote() { printf '%s' "${1-}" | sed -E 's/[][(){}.^$*+?|\\/]/\\&/g'; } +sibling_filter() { # <object> [pr|branch]; candidate lines on stdin + sfl_slug="$(object_slug "$1")" + sfl_num="$(object_number "$1")" + sfl_mode="${2:-pr}" + if [ -z "$sfl_slug" ]; then cat; return 0; fi + sfl_q="$(ere_quote "$sfl_slug")" + if [ -n "$sfl_num" ] && [ "$sfl_mode" = pr ]; then + # `#<n>` anywhere, or the row's own number column. + awk -v sep="$(printf '\t')" -v n="$sfl_slug" -v re="#$sfl_q([^0-9A-Za-z]|$)" ' + { if ($0 ~ re) { print; next } + split($0, f, sep); if (f[1] == n) print }' + return 0 + fi + sed -E 's/^[0-9a-fA-F]{40}[[:space:]]+//' \ + | grep -E -- "(^|[^0-9A-Za-z])$sfl_q([^0-9A-Za-z]|\$)" || : +} + +gh_reads() { + gr_obj="$1"; gr_repo="$(object_repo "$gr_obj")"; gr_n="$(object_number "$gr_obj")"; gr_slug="$(object_slug "$gr_obj")" + gr_term="${gr_n:+#$gr_n}"; gr_term="${gr_term:-$gr_slug}" + if [ "$NO_GITHUB" = 1 ]; then + printf '1. existing claims on the object: not read (--no-github)\n' + printf '2. gh pr list --state all --search: not read (--no-github)\n' + printf '3. git ls-remote --heads: not read (--no-github)\n' + return 0 + fi + command -v gh >/dev/null 2>&1 || { note "gh is not on PATH — rerun with --no-github, or install it"; return 1; } + printf '1. existing `CLAIMED —` comments on %s:\n' "$gr_obj" + if [ -n "$gr_n" ]; then + gr_c="$( { gh issue view "$gr_n" --repo "$gr_repo" --comments 2>/dev/null || gh pr view "$gr_n" --repo "$gr_repo" --comments 2>/dev/null; } | grep -n -e 'CLAIMED —' -e 'TAKEOVER —' -e 'RELEASED —' || : )" + else + gr_c="" + fi + printf '%s\n' "${gr_c:- none}" + printf '2. `gh pr list --repo %s --state all --search "%s"`, kept where the row or its body names `%s`:\n' "$gr_repo" "$gr_term" "${gr_n:+#}$gr_slug" + # The body is fetched for the TEST and cut off before the print. `--json` + # needs a gh that has it; where it does not, the four columns are filtered on + # their own, which is strictly less recall and never a wrong answer. + gr_raw="$(gh pr list --repo "$gr_repo" --state all --search "$gr_term" --limit 20 \ + --json number,title,headRefName,state,body \ + -q '.[] | [.number, .title, .headRefName, .state, (.body // "" | gsub("[\r\n]+"; " "))] | @tsv' 2>/dev/null || :)" + [ -n "$gr_raw" ] || gr_raw="$(gh pr list --repo "$gr_repo" --state all --search "$gr_term" --limit 20 2>/dev/null || :)" + gr_p="$(printf '%s\n' "$gr_raw" | sibling_filter "$gr_obj" pr | cut -f1-4 || :)" + printf '%s\n' "${gr_p:- none}" + printf '3. `git ls-remote --heads git@github.com:%s` branches naming `%s` as a whole token:\n' "$gr_repo" "$gr_slug" + gr_b="$(git ls-remote --heads "git@github.com:$gr_repo.git" 2>/dev/null | sibling_filter "$gr_obj" branch || :)" + printf '%s\n' "${gr_b:- none}" + return 0 +} + +gh_comment() { + gc_obj="$1"; gc_body="$2"; gc_repo="$(object_repo "$gc_obj")"; gc_n="$(object_number "$gc_obj")" + [ "$NO_GITHUB" = 1 ] && return 1 + [ -n "$gc_n" ] || { note "$gc_obj is a change directory, not an issue or a PR — no GitHub comment to post"; return 1; } + command -v gh >/dev/null 2>&1 || return 1 + gc_url="$(printf '%s' "$gc_body" | gh issue comment "$gc_n" --repo "$gc_repo" --body-file - 2>/dev/null \ + || printf '%s' "$gc_body" | gh pr comment "$gc_n" --repo "$gc_repo" --body-file - 2>/dev/null || :)" + gc_url="$(printf '%s\n' "$gc_url" | grep -o 'https://[^ ]*' | tail -n1 || :)" + [ -n "$gc_url" ] || return 1 + printf '%s\n' "$gc_url" +} + +# The hook `commit_push` calls after every `pull --rebase`, before it pushes. +# If another lane's CLAIMED or TAKEOVER on this object is on the rebased +# history, THEIRS LANDED FIRST and this claim has lost. Git's push +# serialization is the arbiter across workstations; the local `mkdir` mutex +# only serializes one workstation, and never decides a race. +# Of the rival lanes in <holders>, the one whose line on <object> LANDED +# first. Landing order is the arbiter and a timestamp is not: two +# workstations' clocks are not a shared order, which is the whole reason this +# amendment decides the race by which CLAIMED reaches `main` first. The +# pickaxe lists the commits that added a line naming the object, oldest first; +# the first of them that touched a rival's log names the winner. +first_landed_of() { # <object> <holder rows> + fl_obj="$1"; fl_holders="$2" + fl_first="$(printf '%s\n' "$fl_holders" | head -n1 | cut -d"$US" -f1)" + [ "$(printf '%s\n' "$fl_holders" | grep -c .)" -gt 1 ] || { printf '%s\n' "$fl_first"; return 0; } + have_remote_ref || { printf '%s\n' "$fl_first"; return 0; } + while IFS= read -r fl_sha; do + [ -n "$fl_sha" ] || continue + while IFS= read -r fl_f; do + [ -n "$fl_f" ] || continue + fl_lane="${fl_f##*/}"; fl_lane="${fl_lane%.md}" + # THE JOIN IS FILE NAME → HOLDER ROW, AND THE TWO NEED NOT SPELL THE LANE + # ALIKE (Copilot round 4). The file carries the row's canonical spelling + # from the moment the first write renames it (Amendment 15); the holder row + # carries whatever the winning LINE was typed with, which an append-only + # log never rewrites. Byte for byte this join missed the winner and the + # rescan fell back to the sorted-first holder — a CLAIM-LOST naming the + # wrong lane. Literal and case-insensitive, both defects at once. + if [ -n "$(printf '%s\n' "$fl_holders" | rows_named "$fl_lane")" ]; then printf '%s\n' "$fl_lane"; return 0; fi + done <<EOF +$(git -C "$LANES_REPO" show --name-only --format= "$fl_sha" -- "$LANES_LOG_PREFIX" 2>/dev/null) +EOF + done <<EOF +$(git -C "$LANES_REPO" log --reverse --format=%H -S"$fl_obj" "origin/$LANES_BRANCH" -- "$LANES_LOG_PREFIX" 2>/dev/null) +EOF + printf '%s\n' "$fl_first" +} + +claim_rescan_hook() { + CLAIM_WINNER="" + # The pull has just moved `origin/<branch>`, and OUR commit is not on it — + # so everything this read can see landed before ours, which is the whole + # test. Flush the cache first: the ref moved a moment ago. + state_events_flush + # ISSUE #30's OWN RACE (Copilot round 12, PR #61): the dead-lane verdict was + # read ONCE, before this claim's first pull, and nothing about $CLAIM_OBJ has + # to change for that verdict to go stale — a RESUMED line is the LANE's own + # log, never an event on the object the scan below reads, so that scan alone + # can never catch a source lane waking back up. Re-run the SAME check the + # takeover was granted on, on every rebase this loop makes, and abandon + # exactly as a landed rival does the moment it no longer answers dead. A + # stale-claim takeover carries no such verdict to revalidate — `claim_is_stale`'s + # age does not run backwards — so this runs only where `CLAIM_SKIP_DEAD` says + # the skip was issue #30's. + if [ -n "$CLAIM_SKIP_DEAD" ] && [ -n "$CLAIM_SKIP" ] && ! holder_is_dead "$CLAIM_SKIP"; then + # THREE DIFFERENT ANSWERS, NEVER ONE SENTENCE (Copilot's own "closer + # look" on 21b8e82, PR #61): `holder_is_dead` returning false a SECOND + # time is not one fact. `HOLDER_LIVE_TERMINAL` set is a CONFIRMED + # revival; `HOLDER_TERMINAL_UNKNOWN` set is a read that failed — fail- + # closed for ownership, same as the grant itself demanded, but "I could + # not check" is not "it came back", and saying so would misreport a read + # failure as a fact this file never established; NEITHER set means the + # log's own last lane-kind line has moved past ENDED/RETIRED entirely — + # a resume in every sense but the word. Distinguished so the note says + # which actually happened here. + # + # AND A FOURTH, `HOLDER_NO_VERDICT` (Copilot on 05d7889, PR #61): the + # log itself could not be read, or yielded no lane-kind line at all. That + # is not "moved past the terminal line" — nothing was read to move — so + # it takes the could-not-reconfirm words, and `CLAIM_ABANDON_REVIVED` + # carries which kind of abort this was to the note and the CLAIM-LOST + # line `claim` writes after this hook returns, so neither says "alive + # again" about a lane nobody saw come back. + CLAIM_ABANDON_REVIVED=1 + if [ -n "$HOLDER_LIVE_TERMINAL" ]; then + note "lane $CLAIM_SKIP is no longer confirmed dead — its own log ends $HOLDER_LIVE_TERMINAL, but a live session on this workstation now backs it up" + elif [ -n "$HOLDER_TERMINAL_UNKNOWN" ]; then + CLAIM_ABANDON_REVIVED="" + note "lane $CLAIM_SKIP's dead-lane verdict could not be reconfirmed — this workstation could not read whether a live session backs it up before this takeover's push landed. That is NOT 'still dead', so the takeover is abandoned rather than assumed safe" + elif [ -n "$HOLDER_BOUND_ELSEWHERE" ]; then + # AMENDMENT 18(b) (Copilot on 8ce6c9d, PR #61): the log the takeover + # was granted on now names a last binding on another host or container, + # whose liveness this place cannot pronounce — not a revival seen. + CLAIM_ABANDON_REVIVED="" + note "lane $CLAIM_SKIP's dead-lane verdict could not be reconfirmed — its last binding is now on $HOLDER_BOUND_ELSEWHERE (host/container), and from here that binding is UNKNOWN, never dead (Amendment 18(b)). The takeover is abandoned rather than assumed safe" + elif [ -n "$HOLDER_NO_VERDICT" ]; then + CLAIM_ABANDON_REVIVED="" + note "lane $CLAIM_SKIP's dead-lane verdict could not be reconfirmed — its own object log could not be read, or yielded no lane-kind line at all, before this takeover's push landed. That is NOT 'still dead' and NOT 'it resumed' either: nothing was read. The takeover is abandoned rather than assumed safe" + else + note "lane $CLAIM_SKIP is no longer confirmed dead — its own log has moved past the terminal line this takeover was granted on, a resume in every sense but the word" + fi + CLAIM_WINNER="$CLAIM_SKIP" + # A DISTINCT EXIT CODE, NOT A REUSE OF 7 (Copilot's own "closer look" on + # 21b8e82, PR #61): 7 is documented, elsewhere and before this PR + # (`lanes-edit.sh`'s own exit-code table, `docs/README-lanes.md`), as + # CLAIM-LOST — another lane's claim landing on main first — and + # automation reading that code for THIS abort would chase a remote race + # that never happened. 9 is this file's own public code, unused before + # now; the event this writes is still CLAIM-LOST (this attempt did not + # succeed, which is what that verb has always meant), but the PROCESS + # exit is not the SAME claim as a landed rival's. + return 9 + fi + # CASE-INSENSITIVE ON BOTH EXCLUSIONS (Amendment 15), for the reason `claim`-s + # own pre-check carries it: these two remove THIS lane and the lane it is + # taking over from the set of rivals, and the row each removes carries whatever + # spelling the winning line used. Byte for byte, a lane whose earlier CLAIMED + # says `repohold-1` under the row `repoHold-1` loses the race to ITSELF and + # writes a CLAIM-LOST naming itself as the winner — measured, exit 7. + # AND LITERAL, not `grep -iv` (Copilot round 4): a name is not a pattern, and a + # rival removed because a `.` in THIS lane's name matched its spelling is a + # race this read reports as won when it was lost. + crh="$(state_events | lane_states_on "$CLAIM_OBJ" | holders_of "$CLAIM_OBJ" \ + | rows_not_named "$CLAIM_LANE" | { [ -n "$CLAIM_SKIP" ] && rows_not_named "$CLAIM_SKIP" || cat; } || :)" + [ -n "$crh" ] || return 0 + CLAIM_WINNER="$(first_landed_of "$CLAIM_OBJ" "$crh")" + IFS="$US" read -r crh_lane crh_verb crh_utc crh_rest <<EOF +$(printf '%s\n' "$crh" | rows_named "$CLAIM_WINNER" | head -n1) +EOF + note "another lane's claim landed on main before this one: @$CLAIM_WINNER ($crh_verb, $crh_utc)" + return 7 +} + +# The URL of the stale claim a TAKEOVER supersedes — Rule 1's takeover comment +# must name it. Read from GitHub, because that is where the comment is. +gh_stale_claim_url() { + gs_obj="$1"; gs_lane="$2"; gs_repo="$(object_repo "$gs_obj")"; gs_n="$(object_number "$gs_obj")" + [ "$NO_GITHUB" = 1 ] && return 1 + [ -n "$gs_n" ] || return 1 + command -v gh >/dev/null 2>&1 || return 1 + gh issue view "$gs_n" --repo "$gs_repo" --json comments \ + -q '.comments[] | select(.body | test("CLAIMED — lane '"$gs_lane"'")) | .url' 2>/dev/null | tail -n1 +} + +# ------------------------------- AMENDMENT 13(e): THE MIGRATION, ONE ACT ----- +# +# `migrate-state-cells` empties every `state` cell of its diary INTO the lane's +# own log, once, on Brett Heap's word (ratified decision O3: after the writer +# changes are installed on both workstations — a cell must stop growing before +# it is emptied). It is a DRY RUN unless `--yes` is passed, and it REFUSES to +# run at all when no cell holds a ` · ` entry, so a second run is a no-op that +# says so. +# +# NOTHING IS DELETED. The appended narrative exists in git history AND in +# `lanes/archive/LANES-pre-amendment-13-<UTC>.md`, written in this same commit, +# AND in the logs — three times over, which is the posture Amendment 3 took +# after the 2026-09-08 loss. +# +# WHAT A ROW BECOMES. Its cell is split on ` · ` into entries, in cell order +# (the cell grew by appending, so that is oldest first). Each entry becomes one +# line in `lanes/log/<lane>.md`: `RULED` where the entry begins with RULING, +# RULINGS or RATIFIED, else `NOTED`; the entry's own leading timestamp becomes +# the line's UTC field rather than being repeated inside its text, and every +# other character of the entry is carried verbatim — including the ` — ` these +# entries are full of, which the log's parser reads as prose because a +# lane-kind line's free text is introduced by the ` — ` right after its object. +# The cell is then REPLACED by the state derived from the LAST entry's leading +# verb where that verb is one of clause (a)'s, else by `MIGRATED`. +# +# THE FOUR FIELDS THAT ARE NOT IN THE ENTRY come from the row: the UTC of an +# entry that carries none is the row's `started` (a date-only `started` is read +# as midnight UTC that day, and the register's older minute-precision form is +# accepted as Amendment 7(b) already accepts it); the session is the LAST uuid +# of the row's session cell; the workstation is the first `/`-separated part of +# the row's own column. +# +# AND A ROW THAT CANNOT BE MIGRATED IS SKIPPED AND NAMED, never guessed at and +# never half-written. Its cell keeps its history, so a re-run after the row is +# fixed by hand migrates exactly that row. Five reasons, all of them visible in +# the dry run: an ambiguous row (more than six ` | ` separators — see +# `row_split_state_cell`); a row whose session cell holds NO transcript uuid, so +# the line could only name `unknown` in the one field this log must never carry +# it in; two rows whose lane names differ only by case (Amendment 15(d)'s hand +# merge); a lane whose object log is two files, or is published under a +# spelling this checkout does not have; and a name that is not a lane name. +# Measured against the live register on 2026-09-15 (52 rows): 20 rows migrate, +# 1 has no uuid, 2 are ambiguous, and 29 hold no ` · ` entry at all and are +# already one phrase. +# +# THE WORKSTATION IS A TOKEN OR IT IS `unknown`. Twelve of the live register's +# rows carry `<workstation? — owner fills>` in that column, and that placeholder +# holds a ` — `: written into the `session <uuid>@<ws>` field it would put a +# THIRD ` — ` in the line, ahead of the object, and the log's own parser would +# read the verb and the fields out of the wrong halves for ever. So the column +# is read up to its first ` / `, and anything that is not one plain token +# (letters, digits, `.`, `_`, `-`) is recorded as `unknown` — which is inert +# here: no reader computes a lane's state, its window or its workstation from a +# narrative line (Amendment 13(b)). + +# THESE FOUR ASSIGN A GLOBAL AND RETURN, rather than printing — the idiom +# `table_lookup` states one screen up, for the same reason: *"a function whose +# answer is taken with `$( … )` forks, which is the cost this exists to avoid"*. +# They are asked once PER ENTRY, and the live register holds 2,206 entries +# across its twenty diary cells. Measured on a copy of it, 2026-09-15: the +# printing form took 94 seconds of a dry run, five forks an entry; this one +# takes eleven. +MIG_LEAD_UTC="" +MIG_LEAD="" +MIG_TRIM="" + +# Spaces off BOTH ends, forking nothing — `rstrip_spaces` and its mirror in one +# place, for the one caller that runs them thousands of times in a row. +mig_trim() { # <text> — sets MIG_TRIM + MIG_TRIM="${1-}" + while [ "${MIG_TRIM# }" != "$MIG_TRIM" ]; do MIG_TRIM="${MIG_TRIM# }"; done + while [ "${MIG_TRIM% }" != "$MIG_TRIM" ]; do MIG_TRIM="${MIG_TRIM% }"; done +} + +# The entry's own leading timestamp, or empty. Matched at the very start of the +# entry and nowhere else: a UTC in the middle of a sentence is prose. +mig_lead_utc() { # <entry> — sets MIG_LEAD_UTC + MIG_LEAD_UTC="" + case "${1-}" in + [0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9]Z*) MIG_LEAD_UTC="${1:0:20}" ;; + [0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]Z*) MIG_LEAD_UTC="${1:0:17}" ;; + esac +} + +# The row's `started` cell as an instant the log's grammar can read: the UTC it +# already is, else midnight on the date it opens with, else empty — the live +# register spells that column `2026-09-02`, `2026-09-04 ~15:30Z` and +# `2026-09-13T17:41Z` in different rows. +mig_started_utc() { # <the started cell> + mig_trim "${1-}" + mig_lead_utc "$MIG_TRIM" + [ -n "$MIG_LEAD_UTC" ] && { printf '%s' "$MIG_LEAD_UTC"; return 0; } + case "$MIG_TRIM" in + [0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]*) printf '%sT00:00Z' "${MIG_TRIM:0:10}" ;; + esac +} + +# Everything a leading state word or timestamp can hide behind, stripped: the +# register writes `**LIVE**`, `> RULING …` and `` `PAUSED` `` in the same column. +mig_strip_lead() { # <text> — sets MIG_LEAD + MIG_LEAD="${1-}" + while :; do + case "$MIG_LEAD" in + ' '*|'*'*|'_'*|'`'*|'>'*|'#'*) MIG_LEAD="${MIG_LEAD#?}" ;; + *) break ;; + esac + done + mig_lead_utc "$MIG_LEAD" + [ -n "$MIG_LEAD_UTC" ] && { MIG_LEAD="${MIG_LEAD#"$MIG_LEAD_UTC"}"; MIG_LEAD="${MIG_LEAD# }"; } + return 0 +} + +# Clause (e)'s test: does this entry RECORD A RULING? Case-folded, because the +# register spells it `RULING`, `Ruling` and `RULINGS` in the same week. +# A CHARACTER CLASS PER LETTER, which is how a `case` matches without regard to +# case in POSIX shell — and it forks nothing, where the `tr` it replaces forked +# once per entry. `RULINGS` is `RULING*` already. +mig_is_ruling() { # <entry> + mig_strip_lead "${1:0:64}" + case "$MIG_LEAD" in + [Rr][Uu][Ll][Ii][Nn][Gg]* | [Rr][Aa][Tt][Ii][Ff][Ii][Ee][Dd]*) return 0 ;; + esac + return 1 +} + +# The current state the last entry names, or empty. The word must END where the +# state word ends — `LIVELY` is not `LIVE` — and `LANDING #<n>` keeps its number, +# because Rule 6's reading of this cell is unchanged by Amendment 13 and is now +# the whole of what the cell says at that moment. +mig_lead_state() { # <entry> + mig_strip_lead "${1:0:64}" + mls="$MIG_LEAD" + case "$mls" in + 'LANDING #'*) + mls_n="${mls#LANDING #}" + mls_d="" + while :; do + case "$mls_n" in + [0-9]*) mls_d="$mls_d${mls_n:0:1}"; mls_n="${mls_n:1}" ;; + *) break ;; + esac + done + # THE NUMBER ENDS WHERE THE WORD ENDS, exactly as `state_word_is_valid` + # and the five states below bound theirs. Without the test `LANDING #123abc` + # derived the state `LANDING #123` — a merge hold Rule 6 would read, out of + # an entry that names no PR at all (Copilot round 1 on openRepoTools#82). + case "$mls_n" in + '' | [!A-Za-z0-9]*) [ -n "$mls_d" ] && printf 'LANDING #%s' "$mls_d" ;; + esac + return 0 ;; + 'HANDED OFF' | 'HANDED OFF'[!A-Za-z0-9]*) printf 'HANDED OFF'; return 0 ;; + LIVE | LIVE[!A-Za-z0-9]*) printf 'LIVE'; return 0 ;; + PAUSED | PAUSED[!A-Za-z0-9]*) printf 'PAUSED'; return 0 ;; + LANDED | LANDED[!A-Za-z0-9]*) printf 'LANDED'; return 0 ;; + ENDED | ENDED[!A-Za-z0-9]*) printf 'ENDED'; return 0 ;; + RETIRED | RETIRED[!A-Za-z0-9]*) printf 'RETIRED'; return 0 ;; + esac + return 0 +} + +# IS THIS CELL ALREADY CLAUSE (a)'s PHRASE? `<STATE> · <UTC> · <one line>` — +# exactly three parts, the first one of the seven states (or the migration's own +# `MIGRATED`) and the second an instant. +# +# WITHOUT THIS THE MIGRATION READS ITS OWN OUTPUT AS A DIARY. The phrase it +# writes carries two ` · ` of its own, so "the cell holds a ` · ` entry" is true +# of every row the moment it has been migrated, and clause (e)'s refusal — +# *"it REFUSES to run when no cell holds a ` · ` entry, so a second run is a +# no-op that says so"* — could never fire on a register that had just been +# migrated. Measured: the second run re-split every migrated cell into three +# entries and would have appended them to the logs again. +mig_cell_is_phrase() { # <cell> + mcp="${1-}" + case "$mcp" in *' · '*) : ;; *) return 1 ;; esac + mcp_a="${mcp%% · *}"; mcp_r="${mcp#* · }" + case "$mcp_r" in *' · '*) : ;; *) return 1 ;; esac + mcp_b="${mcp_r%% · *}"; mcp_c="${mcp_r#* · }" + case "$mcp_c" in *' · '*) return 1 ;; esac # a fourth part is not the phrase + [ -n "$mcp_c" ] || return 1 + case "$mcp_a" in + MIGRATED) : ;; + *) state_word_is_valid "$mcp_a" || return 1 ;; + esac + mig_lead_utc "$mcp_b" + [ -n "$mcp_b" ] && [ "$MIG_LEAD_UTC" = "$mcp_b" ] || return 1 + return 0 +} + +# The workstation field of a migrated line — see the paragraph above. +mig_row_ws() { # <the workstation column> + mrw="${1%% / *}" + mrw="$(rstrip_spaces "$mrw")" + case "$mrw" in + '' | *[!A-Za-z0-9._-]*) printf 'unknown' ;; + *) printf '%s' "$mrw" ;; + esac +} + +# A BLOCK OF LINES APPENDED WITH THE SAME PROOF `append_text_line` MAKES FOR +# ONE. A lane's whole migrated history is appended in a single act — the alt is +# one call per entry, and on the live register that is hundreds of full copies +# of a log and hundreds of `1 line appended to …` notes for what is one write. +# The proof is the stronger of the two `append_text_line` states: the file +# afterwards must be exactly its old bytes followed by exactly this block. +append_text_block() { # <target> <block, lines separated by newlines> + atb_t="$1"; atb_b="$2" + [ -n "$atb_b" ] || return 0 + ATB_TMPD="$(mktemp -d)" + atb_pre="$ATB_TMPD/pre" + cat -- "$atb_t" > "$atb_pre" + atb_before="$(wc -l < "$atb_pre" | tr -d ' ')" + atb_n="$(printf '%s\n' "$atb_b" | wc -l | tr -d ' ')" + printf '%s\n' "$atb_b" >> "$atb_t" # >> FOLLOWS the symlink + atb_after="$(wc -l < "$atb_t" | tr -d ' ')" + [ "$atb_after" -eq "$((atb_before + atb_n))" ] || + die "append changed line count by $((atb_after - atb_before)) where $atb_n lines were appended; inspect $atb_t" 5 + { cat -- "$atb_pre"; printf '%s\n' "$atb_b"; } | cmp -s -- "$atb_t" - || + die "append rewrote existing bytes; inspect $atb_t" 5 + # AND THE COPY GOES, because it is a whole log and there is one per lane: the + # live register's migration makes twenty of them in a run, and a dry run makes + # them while reporting that nothing was written (Copilot round 1 on + # openRepoTools#82). It is removed HERE, where the proof has just passed, and + # a `die` above leaves it for the same reason every other `mktemp -d` in this + # file leaves one: a refused write is evidence. + rm -rf -- "$ATB_TMPD" + note "$atb_n lines appended to $atb_t" +} + +# The act itself. `<1>` writes; `<0>` is the dry run, which reads exactly the +# same things, reports exactly the same rows, and touches nothing. +migrate_state_cells() { # <1 = the act, 0 = the dry run> + msc_do="${1:-0}" + msc_utc="$(utc_now)" + msc_tmp="$(mktemp -d)" + mkdir -p "$msc_tmp/block" + : > "$msc_tmp/report"; : > "$msc_tmp/skips"; : > "$msc_tmp/cells"; : > "$msc_tmp/targets" + msc_arch_rel="${LANES_PREFIX}archive/LANES-pre-amendment-13-$msc_utc.md" + msc_arch="$LANES_DIR/archive/LANES-pre-amendment-13-$msc_utc.md" + + # THE FETCH FIRST (R30), AND A CHECKOUT THAT IS BEHIND IS REFUSED. This one + # act rewrites every row of the register and appends to every lane's log in a + # single commit; made against a register that is not the published one, each + # of those rewrites is a conflict for `commit_push`'s rebase to resolve, and + # the one it cannot resolve costs the whole migration its atomicity. + log_sync + if [ "$NO_GIT" != 1 ] && have_remote_ref; then + msc_behind="$(git -C "$LANES_REPO" rev-list --count "HEAD..origin/$LANES_BRANCH" 2>/dev/null || printf '')" + case "$msc_behind" in + '' | 0) : ;; + *) die "this checkout is $msc_behind commit(s) behind origin/$LANES_BRANCH. The migration rewrites EVERY row and every lane's log in ONE commit, so it is made against the published register or not at all. Pull first — \`git -C $LANES_REPO pull --rebase\` — and re-run. Nothing was written." 2 ;; + esac + fi + refuse_dirty_checkout "migrate-state-cells" "$LANES_PATH" + + # THE MUTEX COMES BEFORE THE SCAN, NOT BETWEEN THE SCAN AND THE WRITE (Copilot + # round 2 on openRepoTools#82). This act reads every row's LINE NUMBER and its + # cell, and then rewrites those lines BY NUMBER: a peer's `add-row` or + # `replace-in-row` landing in this checkout between the two moves the lines + # under it, and `replace_line` then rewrites the wrong row — its one-line proof + # holds for the line it was given, not for the row a person meant. So the scan + # and the write happen inside ONE hold of the lock. + # + # THE DRY RUN TAKES NO LOCK AT ALL. It writes nothing, so a row that moves + # under it costs a report one line of accuracy and nothing else — and a read + # that holds the estate's one register mutex for the seconds this scan takes + # is a read that blocks every lane's write to say what it would have done. + [ "$msc_do" = 1 ] && acquire_lock + + # TWO ROWS FOR ONE LANE UNDER TWO CASES ARE 15(d)'s HAND MERGE, and both of + # them are skipped rather than migrated into one log under a name that means + # two rows. + msc_dups="$(awk ' + substr($0,1,1) == "|" { + p1 = index($0, "`"); if (p1 == 0) next + r = substr($0, p1 + 1); p2 = index(r, "`"); if (p2 == 0) next + print tolower(substr(r, 1, p2 - 1)) + }' "$LANES_FILE" | LC_ALL=C sort | LC_ALL=C uniq -d)" + + msc_rows=0; msc_ok=0; msc_lines=0; msc_noted=0; msc_ruled=0; msc_skipped=0 + msc_phrase=0; msc_plain=0; msc_before=0; msc_after=0 + + while IFS="$(printf '\t')" read -r msc_n msc_lane; do + [ -n "${msc_n:-}" ] || continue + msc_rows=$((msc_rows + 1)) + msc_why="" + case "$msc_lane" in + '' | *[!A-Za-z0-9._-]* | .* | -*) msc_why="'$msc_lane' is not a lane name (letters, digits, . _ -), so it names no log this writer would create" ;; + esac + if [ -z "$msc_why" ] && [ -n "$msc_dups" ]; then + msc_low="$(lc "$msc_lane")" + while IFS= read -r msc_d; do + [ -n "$msc_d" ] || continue + [ "$msc_d" = "$msc_low" ] && msc_why="the register holds more than one row whose lane name is $msc_lane under some case — one lane is ONE lane (Amendment 15), and the two are merged by hand into one row (15(d)) before either is migrated" + done <<EOF +$msc_dups +EOF + fi + msc_row="$(sed -n -e "${msc_n}p" "$LANES_FILE")" + if [ -z "$msc_why" ]; then + msc_rc=0; row_split_state_cell "$msc_row" || msc_rc=$? + case "$msc_rc" in + 0) : ;; + 2) msc_why="its row carries $(row_sep_count "$msc_row") ' | ' separators where a seven-column row carries 6, so which text is the state cell is not knowable from the row (escape the literal pipe inside a cell as \\| by hand, commit it, and re-run)" ;; + *) msc_why="its row does not open with '|' and end with '|'" ;; + esac + fi + if [ -z "$msc_why" ]; then + mig_trim "$RSS_CELL"; msc_cell="$MIG_TRIM" + msc_head="$RSS_HEAD"; msc_tail="$RSS_TAIL" + # TWO WAYS A CELL HOLDS NO HISTORY, AND THEY ARE NOT THE SAME FACT + # (Copilot round 1 on openRepoTools#82). A cell that is already + # `<STATE> · <UTC> · <one line>` is in clause (a)'s shape and there is + # nothing to do. A cell holding ONE WORD — `ACTIVE`, `LIVE`, the bare + # states this register is full of — has no diary to move either, so this + # act leaves it alone, but it is NOT in the shape: the next + # `set-row-state` on that lane puts it there, and reporting the two as one + # number would say the register was compliant when a third of it is not. + case "$msc_cell" in + *' · '*) : ;; + *) msc_plain=$((msc_plain + 1)); continue ;; + esac + if mig_cell_is_phrase "$msc_cell"; then msc_phrase=$((msc_phrase + 1)); continue; fi + # THE SEAM (Brett Heap's ruling of 2026-10-04; Copilot round 2 on + # openRepoTools#97). This act rewrites a row's state cell and appends to + # its lane's log, so a lane the managed ledger has enrolled is not a row it + # may take — and the historical shorthand `MANAGED OWNER · <token>` holds + # ONE ` · `, so `mig_cell_is_phrase` does not recognise it and, unasked, + # the row was planned as a diary and rewritten to `MIGRATED · …`. + # ONE SUCH ROW REFUSES THE WHOLE MIGRATION, exactly as one refuses the + # whole of Amendment 19's sweep: clause (e) makes this act ONE commit, and + # a register migrated but for its managed rows is not that commit. Asked + # HERE and not at the top of the loop: a row skipped above (15(d)'s + # duplicate pair, a row that is not seven columns, one word, the phrase) is + # never rewritten and has nothing to refuse, and asking first would turn + # today's skips into refusals. Both modes ask, because the dry run reports + # exactly what the act would do. `die` releases the lock the act holds. + # The seam reads this checkout's row as well as the published one, and + # this checkout's row is the one the migration rewrites. + managed_seam_refuse "$msc_lane" "migrate-state-cells (the WHOLE migration, which Amendment 13(e) makes one commit)" + fi + if [ -z "$msc_why" ]; then + # The row's own columns, walked from the LEFT out of the head this split + # already proved reassembles: 3 is `<workstation> / <env> / <user>` and 4 + # is `started (UTC)`. + msc_h="${msc_head#| }" + msc_h="${msc_h#* | }" # past the lane cell + msc_h="${msc_h#* | }" # past the session cell + msc_c3="${msc_h%% | *}" # workstation / env / user + msc_c4="${msc_h#* | }"; msc_c4="${msc_c4%% | *}" # started (UTC) + msc_ws="$(mig_row_ws "$msc_c3")" + msc_started="$(mig_started_utc "$msc_c4")" + [ -n "$msc_started" ] || msc_started="$msc_utc" + msc_uuid="" + if row_split_session_cell "$msc_row"; then + msc_uuid="$(printf '%s\n' "$RSC_CELL" | uuids_in_cell | tail -n1)" + fi + [ -n "$msc_uuid" ] || + msc_why="its session cell holds no transcript uuid, and the session field of an event line is a transcript uuid and only that (Amendment 7(b)) — a migrated line naming 'unknown' there is wrong for ever in an append-only file. Read the cell and set the row by hand instead: lanes-edit.sh set-row-state $msc_lane \"<STATE> · <one line>\"" + fi + if [ -z "$msc_why" ]; then + # The lane's log, found whatever its case, and never created beside one + # this checkout has not pulled (Amendment 15, `ensure_log`'s own guard). + msc_pub=""; msc_prc=0 + msc_pub="$(log_path_ci "$msc_lane")" || msc_prc=$? + if [ "$msc_prc" != 0 ]; then + msc_why="its object log is published twice under names that differ only by case (above) — 15(d)'s hand merge" + else + msc_loc="$(log_files_named_ci "$msc_lane")" + msc_ln="$(printf '%s' "$msc_loc" | grep -c . || :)" + if [ "$msc_ln" -gt 1 ]; then + msc_why="this checkout holds $msc_ln object logs for it whose names differ only by case — 15(d)'s hand merge" + elif [ "$msc_ln" = 1 ]; then + msc_lf="$msc_loc"; msc_rel="${LANES_LOG_PREFIX}${msc_loc##*/}" + if [ "${msc_rel##*/}" != "${msc_pub##*/}" ]; then + msc_why="its object log is published as $msc_pub while this checkout has ${msc_rel##*/} — a case-only rename whose commit never landed. Pull first, or merge them (15(d))" + elif [ "$NO_GIT" != 1 ] && ! git -C "$LANES_REPO" ls-files --error-unmatch -- "$msc_rel" >/dev/null 2>&1; then + # AN UNTRACKED LOG IS SOMEBODY'S UNCOMMITTED WORK, AND THIS ACT WOULD + # COMMIT IT (Copilot round 2 on openRepoTools#82). A log that is + # TRACKED and dirty is already refused for the whole run by + # `refuse_dirty_checkout` above, which exempts the register alone and + # reads staged and unstaged alike; an untracked file is in neither of + # those lists, so appending to it here would put a peer's first lines + # into this migration's one commit under this migration's message. + # The row is skipped and the file named, exactly as the other five + # reasons are, and its cell keeps every character. + msc_why="its object log ${msc_rel} exists here but is NOT TRACKED — somebody's uncommitted work, which this act would commit inside the migration's own commit. Commit it first (\`git -C $LANES_REPO commit -m \"<what it is>\" -- $msc_rel\`) and re-run" + fi + else + msc_rel="$msc_pub"; msc_lf="$LANES_LOG_DIR/${msc_pub##*/}" + fi + fi + fi + if [ -n "$msc_why" ]; then + msc_skipped=$((msc_skipped + 1)) + printf ' %-26s %s\n' "$msc_lane" "$msc_why" >> "$msc_tmp/skips" + continue + fi + + # THE ENTRIES, IN CELL ORDER — which is oldest first, because the cell grew + # by appending. + # + # SPLIT BY `awk`, IN ONE PASS, and not by `${cell#* · }` in a loop. That + # expansion is the shortest-prefix form: bash walks every prefix length in + # turn, so its cost is quadratic in the DISTANCE TO THE MATCH — cheap while + # the entries are short and ruinous for one long entry near the end of a + # 94,341-character cell. Measured on this bash, 2026-09-15: six of those + # expansions over a 95,000-character string with no match at all take 16 + # seconds. One pass of `awk` is linear in the cell whatever the entries look + # like. A register row is ONE LINE, so an entry can hold no newline and a + # line of this stream is exactly an entry. + : > "$msc_tmp/block/$msc_n" + msc_en=0; msc_last="" + while IFS= read -r msc_e; do + mig_trim "$msc_e"; msc_e="$MIG_TRIM" + if [ -n "$msc_e" ]; then + msc_last="$msc_e" + mig_lead_utc "$msc_e"; msc_eutc="$MIG_LEAD_UTC" + msc_text="$msc_e" + if [ -n "$msc_eutc" ]; then + msc_t2="${msc_e#"$msc_eutc"}"; mig_trim "$msc_t2"; msc_t2="$MIG_TRIM" + # AN ENTRY THAT IS NOTHING BUT A TIMESTAMP KEEPS IT AS ITS TEXT: a + # line whose free text is empty is a line with a dangling ` — `, and + # this log is never rewritten. + [ -n "$msc_t2" ] && msc_text="$msc_t2" + else + msc_eutc="$msc_started" + fi + if mig_is_ruling "$msc_e"; then msc_verb=RULED; msc_ruled=$((msc_ruled + 1)) + else msc_verb=NOTED; msc_noted=$((msc_noted + 1)); fi + printf '%s — lane %s, session %s@%s, %s, lane:%s — %s\n' \ + "$msc_verb" "$msc_lane" "$msc_uuid" "$msc_ws" "$msc_eutc" "$msc_lane" "$msc_text" >> "$msc_tmp/block/$msc_n" + msc_en=$((msc_en + 1)); msc_lines=$((msc_lines + 1)) + fi + done <<EOF +$(printf '%s\n' "$msc_cell" | awk '{ gsub(/ · /, "\n"); print }') +EOF + if [ "$msc_en" = 0 ]; then + msc_plain=$((msc_plain + 1)); rm -f -- "$msc_tmp/block/$msc_n"; continue + fi + + # THE CELL IT BECOMES — clause (e): the state the LAST entry's leading verb + # names, where that verb is one of clause (a)'s, else `MIGRATED`. + msc_state="$(mig_lead_state "$msc_last")" + [ -n "$msc_state" ] || msc_state=MIGRATED + # THE CAP IS THE CAP HERE TOO (Copilot round 5 on openRepoTools#82). This + # builds the cell directly rather than through `set-row-state`, so nothing + # else enforces ratified decision O1's 240 characters on the line — and the + # line carries a PATH whose length is the lane's name: `check_lane_name` + # bounds a name's characters and not its length, so a lane named with 216 of + # them would be migrated to a cell the writer itself would refuse. Cut back + # to the last space, for the reason the three commands' `cut_to_line` gives: + # `${s:0:n}` counts bytes wherever the locale is not a UTF-8 one. + msc_line="history in $msc_rel" + if [ "${#msc_line}" -gt 230 ]; then + msc_line="${msc_line:0:230}" + case "$msc_line" in *' '*) msc_line="${msc_line% *}" ;; esac + msc_line="$msc_line ..." + fi + msc_new="$msc_state · $msc_utc · $msc_line" + printf '%s%s%s%s%s%s%s\n' "$msc_n" "$US" "$msc_new" "$US" "$msc_head" "$US" "$msc_tail" >> "$msc_tmp/cells" + printf '%s%s%s%s%s\n' "$msc_n" "$US" "$msc_lf" "$US" "$msc_rel" >> "$msc_tmp/targets" + printf ' %-26s %4s entries %7s chars → %s\n' \ + "$msc_lane" "$msc_en" "${#msc_cell}" "$msc_new" >> "$msc_tmp/report" + msc_ok=$((msc_ok + 1)) + msc_before=$((msc_before + ${#msc_cell})); msc_after=$((msc_after + ${#msc_new})) + done <<EOF +$(awk 'substr($0,1,1) == "|" { + p1 = index($0, "`"); if (p1 == 0) next + r = substr($0, p1 + 1); p2 = index(r, "`"); if (p2 == 0) next + printf "%d\t%s\n", NR, substr(r, 1, p2 - 1) + }' "$LANES_FILE") +EOF + + # ------------------------------------------------------------- the report + printf 'migrate-state-cells — %s (lane-collision-protocol Amendment 13(e))\n' \ + "$( [ "$msc_do" = 1 ] && printf 'THE ACT' || printf 'DRY RUN, nothing is written' )" + printf ' register : %s\n' "$LANES_FILE" + printf ' archive : %s\n' "$msc_arch_rel" + printf ' rows : %s read · %s to migrate · %s already the phrase · %s one word, no history · %s skipped\n' \ + "$msc_rows" "$msc_ok" "$msc_phrase" "$msc_plain" "$msc_skipped" + if [ "$msc_ok" -gt 0 ]; then + printf '\n lane entries cell now → the phrase it becomes\n' + cat -- "$msc_tmp/report" + fi + if [ "$msc_skipped" -gt 0 ]; then + printf '\n SKIPPED — nothing is written for these rows and their cells keep every\n' + printf ' character, so a re-run after each is settled migrates exactly it:\n' + cat -- "$msc_tmp/skips" + fi + if [ "$msc_plain" -gt 0 ]; then + printf '\n %s row(s) hold ONE WORD and no history (`ACTIVE`, `LIVE`, …). This act leaves\n' "$msc_plain" + printf ' them exactly as they are — there is no diary in them to move — and they are NOT\n' + printf ' yet `<STATE> · <UTC> · <one line>`: the next set-row-state on each writes it.\n' + fi + printf '\n log lines: %s (%s NOTED, %s RULED) into %s log(s)\n' "$msc_lines" "$msc_noted" "$msc_ruled" "$msc_ok" + printf ' state cells: %s characters → %s\n' "$msc_before" "$msc_after" + + # THE REFUSAL CLAUSE (e) ASKS FOR, and it is the same answer in both modes: + # a register whose cells hold no ` · ` entry has already been migrated (or + # never needed it), and a second run is a no-op that says so. + if [ "$msc_ok" = 0 ]; then + msc_left="" + [ "$msc_skipped" -gt 0 ] && msc_left=" The $msc_skipped row(s) listed above still hold theirs and are the ones this act cannot take; each is settled by the line beside it, and a re-run then migrates exactly those." + rm -rf -- "$msc_tmp" + die "no cell holds a ' · ' entry this act can migrate: $msc_phrase row(s) are already in Amendment 13(a)'s shape and $msc_plain hold ONE WORD and no history, which this act leaves alone — the next \`set-row-state\` on each of those lanes writes it as the phrase.$msc_left The migration is ONE act and this was not it — nothing was written." 2 + fi + if [ "$msc_do" != 1 ]; then + printf '\n DRY RUN — nothing was written. Make it the one act with: lanes-edit.sh migrate-state-cells --yes\n' + printf ' (Amendment 13(e): one commit carrying the archive, the logs and the register.)\n' + rm -rf -- "$msc_tmp" + return 0 + fi + + # --------------------------------------------------------------- the write + # + # THE LOCK IS ALREADY HELD — it was taken BEFORE the scan, so the line numbers + # rewritten below are the ones this invocation read (Copilot round 2 on + # openRepoTools#82). + # + # AND A PEER'S REGISTER EDIT IS CAPTURED HERE, AFTER EVERY REFUSAL AND SKIP OF + # THE SCAN AND BEFORE THE FIRST BYTE IS WRITTEN (openRepoTools#157 item 4b). + # Captured before the scan, a refusal in it — the seam's, or the "nothing to + # migrate" one — left a `LANES(pre-existing@…)` commit behind: a refusal that + # wrote, which `capture_register_edit` names as the one thing it must never + # be. The capture commits the file's bytes and changes none of them, so what + # the scan read is what is committed, as it was. `retire_rows` and + # `archive_rows` capture at their writes for the same reason. + handle_preexisting "$LANES_PATH" + # + # EVERYTHING BELOW IS ONE COMMIT OR NONE. The archive, the appended logs and + # the rewritten rows are made on disk first and published by the single + # `commit_push` at the end, so a refusal in the middle of them — a log whose + # append could not be proved, a row whose rewrite moved more than one line — + # leaves this checkout DIRTY and the register unpublished, which is what + # `git status` then shows and `git checkout -- lanes` undoes whole. Nothing is + # half-published, because the commit is the only thing that publishes; and a + # re-run on a checkout still holding that half is REFUSED by + # `refuse_dirty_checkout` above rather than made twice. + mkdir -p -- "$LANES_DIR/archive" || die "could not create $LANES_DIR/archive — the archive is written BEFORE anything else changes, so nothing has been" 6 + # A `>` REDIRECT, WHICH FOLLOWS A SYMLINK, and the source read whole first: + # this copy is the file's state before this act and it is one of the three + # places clause (e) keeps it. + cat -- "$LANES_FILE" > "$msc_arch" || die "could not write the archive $msc_arch — nothing else has been touched" 6 + cmp -s -- "$LANES_FILE" "$msc_arch" || die "the archive $msc_arch is not byte for byte the register it was copied from; nothing else has been touched" 5 + note "archive written: $msc_arch_rel" + reg_wrote "$msc_arch_rel (the register as it was)" + + msc_paths=("$LANES_PATH" "$msc_arch_rel") + while IFS="$US" read -r msc_n msc_lf msc_rel; do + [ -n "${msc_n:-}" ] || continue + if [ ! -f "$msc_lf" ]; then + mkdir -p -- "$LANES_LOG_DIR" + msc_base="${msc_lf##*/}" + printf '# lane %s — object log (lane-collision-protocol Amendment 7)\n' "${msc_base%.md}" > "$msc_lf" + note "created $msc_lf" + fi + append_text_block "$msc_lf" "$(cat -- "$msc_tmp/block/$msc_n")" + msc_paths+=("$msc_rel") + done <<EOF +$(cat -- "$msc_tmp/targets") +EOF + [ "${#msc_paths[@]}" -le 2 ] || reg_wrote "$(( ${#msc_paths[@]} - 2 )) lanes' logs under $LANES_LOG_PREFIX (their migrated lines)" + + msc_rows=0 + while IFS="$US" read -r msc_n msc_new msc_head msc_tail; do + [ -n "${msc_n:-}" ] || continue + replace_line "$msc_n" "$msc_head$msc_new $msc_tail" + msc_rows=$((msc_rows + 1)) + [ "$msc_rows" != 1 ] || reg_wrote "$LANES_PATH (the state cells rewritten before this one)" + done <<EOF +$(cat -- "$msc_tmp/cells") +EOF + + msc_msg="LANES(migrate@$WS): Amendment 13(e) — $msc_ok state cells become one phrase; $msc_lines lines ($msc_noted NOTED, $msc_ruled RULED) into the lanes' own logs; pre-migration register archived" + commit_push "$msc_msg" "${msc_paths[@]}" + msc_rc=$? + release_lock + # THE STAGING GOES ON THE WAY OUT, on both paths: this directory holds a block + # of log lines per migrated lane, and on the live register that is 2,206 lines + # (Copilot round 1 on openRepoTools#82). A `die` on the way here keeps it, like + # every other refused write in this file. + rm -rf -- "$msc_tmp" + return "$msc_rc" +} + +# ------------------------------------- the restart intent (openRepoTools#94) +# +# WHY THIS IS A FILE AND NOT AN ENVIRONMENT VARIABLE, measured on Eagle +# 2026-09-15T20:59Z and filed as `opensoft/openRepoTools#94`. `/ctx` respawned +# its own pane with `LANE_START_FRESH=1 … lane openRepoTools-3` and what came +# up was `claude --name openRepoTools-3 --resume <the uuid it had just paused>`. +# `lane-start` was not at fault — its `(( ! fresh ))` gates were in the +# installed copy and are in this tree — and neither was `lane`, which `exec`s. +# The launcher is: `claude-profile` re-creates the child through tmux, and its +# own comment states the rule this estate now has to build around — +# +# "`tmux new-session` hands the command the SERVER's environment, not this +# client's, so a variable the operator exported in their own shell reaches +# the child only if it is written into the command string" +# +# — which is why it threads six values explicitly and why a seventh nobody +# thought to thread is simply GONE. The defect capture's session name, +# `claude-max-001-20260915205926-456327`, is that launcher's own +# `claude-<profile>-<timestamp>-<pid>` pattern, so this is what happened and not +# what might have. An ENVIRONMENT seam cannot cross a boundary another +# repository owns. A FILE can: the intent is written under the lane's own +# control root before the old process is killed, and every launch after it +# reads the same bytes whatever the environment did. +# +# THE CONTROL ROOT follows the same layout as the diagnostic lifecycle from +# openRepoTools#97. The restart helpers have their own namespace: their strict +# validation and private atomic writer must not be replaced by the diagnostic +# helpers. The intent sits beside lane-state.yaml without sharing its authority. + +LANE_RESTART_SCHEMA=1 + +# THE CONTROL ROOT — explicit override, retained intent, then creation rungs. +# 0 with a path, 8 with no rung, 1 for unknown or competing locations. +lane_restart_control_root() { # <lane> [<payload>] [<checkout hint>] + lcr_lane="${1-}"; lcr_pay="${2-}"; lcr_dir=""; lcr_par="" + lcr_record_root=""; lcr_projects_root=""; lcr_existing="" + [ -n "$lcr_lane" ] || return 8 + if [ -n "${LANES_LANE_STATE_ROOT:-}" ]; then + printf '%s/%s\n' "${LANES_LANE_STATE_ROOT%/}" "$lcr_lane" + return 0 + fi + [ -n "$lcr_pay" ] && lcr_dir="$(payload_subfield "$lcr_pay" dir)" + if [ -z "$lcr_dir" ]; then + lcr_dir="$(lane_payload_field "$lcr_lane" dir 2>/dev/null || :)" + fi + case "$lcr_dir" in + /*) lcr_par="${lcr_dir%/*}" ;; + *) lcr_par="" ;; + esac + if [ -n "$lcr_par" ]; then + lcr_record_root="$lcr_par/.lane-state/$lcr_lane" + lane_restart_root_ok "$lcr_record_root" || return 1 + [ -d "$lcr_par" ] || lcr_record_root="" + fi + if [ -n "${PROJECTS_ROOT:-}" ]; then + lcr_projects_root="${PROJECTS_ROOT%/}/.lane-state/$lcr_lane" + lane_restart_root_ok "$lcr_projects_root" || return 1 + [ -d "$PROJECTS_ROOT" ] || lcr_projects_root="" + fi + # PAUSED may first record a nested checkout after reservation. Existing + # intent authority stays at its physical location; validity is the reader's + # gate, never a reason to bypass an occupied path. Unknown ancestry refuses. + # Only directory aliases share an atomic replacement entry; separate leaf + # symlinks/hardlinks would split into two records on the next replacement. + for lcr_candidate in "$lcr_record_root" "$lcr_projects_root"; do + [ -n "$lcr_candidate" ] || continue + lcr_file="$lcr_candidate/restart-intent.yaml" + if [ -e "$lcr_file" ] || [ -L "$lcr_file" ]; then + if [ -n "$lcr_existing" ] && [ "$lcr_candidate" != "$lcr_existing" ] && + [ ! "$lcr_candidate" -ef "$lcr_existing" ]; then + note "lane $lcr_lane has distinct restart-intent locations in $lcr_existing and $lcr_candidate; reconcile these records before continuing. Nothing was written." + return 1 + fi + [ -n "$lcr_existing" ] || lcr_existing="$lcr_candidate" + fi + done + if [ -n "$lcr_existing" ]; then + printf '%s\n' "$lcr_existing" + return 0 + fi + if [ -n "$lcr_record_root" ]; then + printf '%s\n' "$lcr_record_root" + return 0 + fi + if [ -n "$lcr_projects_root" ]; then + printf '%s\n' "$lcr_projects_root" + return 0 + fi + # A checkout hint is a last resort, so reads cannot hide an intent that + # writers/status already placed under the established root rungs. + case "${3-}" in + /*) lcr_par="${3%/*}" + if [ -n "$lcr_par" ] && [ -d "$lcr_par" ]; then + printf '%s/.lane-state/%s\n' "$lcr_par" "$lcr_lane" + return 0 + fi ;; + esac + return 8 +} + +# ONE FIELD OUT OF ONE OF THESE FILES. They are flat `key: value` lines and +# nothing else — no nesting, no lists — so one `awk` reads every one of them +# and a malformed file answers empty rather than half a value. +lane_restart_sidecar_field() { # <file> <key> + [ -r "${1-}" ] || return 1 + awk -v k="${2-}" ' + BEGIN { k = k ": " } + substr($0, 1, length(k)) == k { + v = substr($0, length(k) + 1) + print v; exit }' "$1" +} + +# Diagnostic prose is bounded and flattened; launch identity is never normalized. +lane_restart_sidecar_value() { # <diagnostic value> + printf '%s' "${1-}" | LC_ALL=C tr '[:cntrl:]' ' ' +} + +lane_restart_value_ok() { # exact values must survive flat and tabular readers + # POSIX class matching also works in Bash 3.2; its ANSI-C range did not. + local LC_ALL=C + case "${1-}" in *[[:cntrl:]]*) return 1 ;; esac + return 0 +} + +# THE ATOMIC REPLACE. Written beside the target and renamed over it, so a +# reader never sees half a snapshot and a full disk leaves the old one intact. +lane_restart_sidecar_put() { # <file> ; the whole body on stdin + lsp_f="${1-}"; lsp_d="${lsp_f%/*}" + [ -n "$lsp_f" ] || return 1 + mkdir -p -- "$lsp_d" 2>/dev/null || return 1 + [ ! -d "$lsp_f" ] || return 1 + lsp_t="$(umask 077; mktemp "$lsp_d/.restart-intent.XXXXXX" 2>/dev/null)" || return 1 + [ -n "$lsp_t" ] || return 1 + cat > "$lsp_t" 2>/dev/null || { rm -f -- "$lsp_t" 2>/dev/null; return 1; } + lsp_bad="$(lane_restart_missing "$lsp_t" "$2")" || { rm -f -- "$lsp_t"; return 1; } + [ -z "$lsp_bad" ] || { rm -f -- "$lsp_t"; return 1; } + mv -- "$lsp_t" "$lsp_f" 2>/dev/null || { rm -f -- "$lsp_t" 2>/dev/null; return 1; } + return 0 +} + +# AN OPERATION ID: unique to one transition, and shaped like the manifest key +# every other sub-field of this estate is — letters, digits, `.`, `_`, `-` — so +# that it can be carried in a payload, a filename and a commit subject without +# a quoting rule of its own. There is no `uuidgen` on every workstation this +# runs on, and a timestamp with the pid and two `$RANDOM`s behind it is unique +# among the handfuls of transitions one lane takes in a day. +lane_restart_op_id() { + printf 'op-%s-%s-%s%s\n' "$(date -u +%Y%m%dT%H%M%SZ)" "$$" "$RANDOM" "$RANDOM" +} + +# THE FOUR STATES OF A RESTART, AND NOTHING ELSE IS ONE. +# pending the intent is written and the old process may still be alive; the +# pane has not been replaced, or has been and the supervisor has +# not claimed it yet. +# starting a supervisor has claimed this exact operation and launched. +# failed the launch did not reach readiness; the supervisor is still in +# the pane with the diagnostic and the retry. +# ready readiness was positively confirmed. A `ready` intent is HISTORY +# and authorises no launch, which is what makes an ordinary +# `lane <name>` after a successful `/ctx` an ordinary resume. +lane_restart_word_ok() { # <word> + case "${1-}" in preparing|pending|starting|failed|ready) return 0 ;; esac + return 1 +} + +# THE HANDOFF'S DIGEST. `shasum -a 256` is on macOS, `sha256sum` on Linux, and +# a workstation with neither answers `none` — which is an ANSWER and not a gap: +# the digest then cannot be COMPARED, and every reader below treats a `none` +# digest as *not checked here* rather than as *unchanged*. Never `cksum`: a +# 32-bit checksum is not a change detector for a file a person edits. +lane_handoff_digest() { # <file> + [ -r "${1-}" ] || { printf 'none\n'; return 0; } + if command -v sha256sum >/dev/null 2>&1; then + sha256sum -- "$1" 2>/dev/null | awk '{print $1; exit}' + elif command -v shasum >/dev/null 2>&1; then + shasum -a 256 -- "$1" 2>/dev/null | awk '{print $1; exit}' + else + printf 'none\n' + fi +} + +# THE INTENT, READ. `<key><TAB><value>` lines, which is what every caller here +# parses with one `awk`. 0 with the fields, 8 where the lane has no intent at +# all (the ordinary lane, and not a failure), 1 where the control root could +# not be derived. +# All schema-1 keys are mandatory; prepared_digest is an optional extension. +# One read validates presence and duplicate keys without per-field subprocesses. +lane_restart_missing() { # <file> <canonical lane> + awk -v lane="$2" ' + BEGIN { + n=split("schema lane state generation operation mode agent profile dir pane window handoff digest old_transcript new_transcript attempt workstation created updated reason", keys, " ") + for (i=1;i<=n;i++) allowed[keys[i]]=1 + allowed["prepared_digest"]=1 + } + { + if ($0 ~ /[[:cntrl:]]/ || $0 !~ /^[A-Za-z_]+: /) {bad["record"]=1; next} + k=$0; sub(/:.*/, "", k) + if (!(k in allowed)) {bad["unknown-key"]=1; next} + v=substr($0,length(k)+3) + seen[k]++; values[k]=v; if (v!="") good[k]=1 + } + END { + for (i=1;i<=n;i++) if (seen[keys[i]]!=1 || !good[keys[i]]) bad[keys[i]]=1 + if (values["lane"]!=lane) bad["lane"]=1 + if (values["generation"] !~ /^[0-9]+$/) bad["generation"]=1 + if (values["attempt"] !~ /^[0-9]+$/) bad["attempt"]=1 + n=split("operation mode agent profile old_transcript new_transcript", keys, " ") + for (i=1;i<=n;i++) if (values[keys[i]] !~ /^[A-Za-z0-9._-]+$/) bad[keys[i]]=1 + n=split("dir handoff", keys, " ") + for (i=1;i<=n;i++) if (values[keys[i]]!="none" && values[keys[i]] !~ /^\//) bad[keys[i]]=1 + n=split("digest prepared_digest", keys, " ") + for (i=1;i<=n;i++) if ((seen[keys[i]] && seen[keys[i]]!=1) || + (seen[keys[i]] && values[keys[i]]!="none" && (length(values[keys[i]])!=64 || values[keys[i]] !~ /^[0-9a-fA-F]+$/))) bad[keys[i]]=1 + for (k in bad) {printf "%s%s", sep, k; sep=" "} + } + ' "$1" +} + +lane_restart_root_ok() { # missing directories are allowed; unusable existing ancestors are not + lrro_path="$1" + while [ -n "$lrro_path" ]; do + if [ -e "$lrro_path" ] || [ -L "$lrro_path" ]; then + [ -d "$lrro_path" ] && [ -r "$lrro_path" ] && [ -x "$lrro_path" ] || return 1 + fi + lrro_parent="$(dirname -- "$lrro_path")" || return 1 + [ "$lrro_parent" != "$lrro_path" ] || break + lrro_path="$lrro_parent" + done + return 0 +} + +lane_restart_read() { # <lane> [<resolved checkout hint>] + lrr_lane="${1-}"; lrr_root=""; lrr_rc=0 + lrr_root="$(lane_restart_control_root "$lrr_lane" "" "${2-}")" || lrr_rc=$? + [ "$lrr_rc" = 0 ] || return 1 + lane_restart_root_ok "$lrr_root" || return 1 + lrr_f="$lrr_root/restart-intent.yaml" + [ -e "$lrr_f" ] || [ -L "$lrr_f" ] || return 8 + [ -f "$lrr_f" ] && [ -r "$lrr_f" ] || return 1 + lrr_schema="$(lane_restart_sidecar_field "$lrr_f" schema)" || return 1 + # AN UNKNOWN SCHEMA FAILS CLOSED, exactly as `lane-state` does for the same + # reason: a newer tooling's intent read by an older reader must not be + # reported as a launch this reader knows how to make. + case "$lrr_schema" in + "$LANE_RESTART_SCHEMA") : ;; + *) printf 'state\tUNKNOWN-SCHEMA\n'; printf 'schema\t%s\n' "${lrr_schema:-<none>}" + printf 'file\t%s\n' "$lrr_f"; return 0 ;; + esac + # AN ACTIVE INTENT MISSING A FACT A LAUNCH IS FENCED ON IS NOT A READABLE ONE + # (Copilot round 2 on openRepoTools#121). The schema check above is the whole + # of what this read used to verify, so a `pending` record carrying an + # operation and a mode and nothing else came back with empty values — and + # empty is exactly what every comparison downstream treats as *cannot + # compare*: `pane_agrees` returns agreement on an empty side, the digest check + # skips, and the launch goes ahead with none of the three checks those fields + # exist for. That is a silent launch from a record nobody wrote. + # + # PRESENT AND NOT EMPTY, WHICH IS NOT THE SAME AS *NOT `none`*. `none` IS an + # answer here — a workstation with neither `sha256sum` nor `shasum` records + # `digest: none`, and the writer writes `none` for every empty field on every + # transition — so what is checked is that the KEY IS THERE AT ALL, which is + # true of everything this tooling has ever written and false of a record that + # was truncated or edited by hand. + # + # `failed` ALSO NEEDS THE LAUNCH FACTS: it authorizes a supervised retry. + # Incomplete records remain readable diagnostics, never launch authority. + lrr_state="$(lane_restart_sidecar_field "$lrr_f" state)" || return 1 + if ! lane_restart_word_ok "$lrr_state"; then + printf 'state\tUNKNOWN-STATE\nfile\t%s\n' "$lrr_f" + return 0 + fi + lrr_missing="$(lane_restart_missing "$lrr_f" "$lrr_lane")" || return 1 + if [ -n "$lrr_missing" ]; then + printf 'state\tINCOMPLETE\nintended_state\t%s\nmissing\t%s\nfile\t%s\n' "$lrr_state" "$lrr_missing" "$lrr_f" + return 0 + fi + for lrr_num in generation attempt; do + lrr_value="$(lane_restart_sidecar_field "$lrr_f" "$lrr_num")" || return 1 + case "$lrr_value" in ''|*[!0-9]*) + printf 'state\tINCOMPLETE\nmissing\t%s\nfile\t%s\n' "$lrr_num" "$lrr_f" + return 0 ;; + esac + done + for lrr_k in state generation operation mode lane agent profile dir pane window \ + handoff digest prepared_digest old_transcript new_transcript attempt workstation \ + created updated reason; do + printf '%s\t%s\n' "$lrr_k" "$(lane_restart_sidecar_field "$lrr_f" "$lrr_k")" + done + printf 'file\t%s\n' "$lrr_f" + return 0 +} + +# One field of it, for the callers that want exactly one. +lane_restart_of() { # <lane> <key> + lro_out=""; lro_rc=0 + lro_out="$(lane_restart_read "${1-}")" || lro_rc=$? + [ "$lro_rc" = 0 ] || return "$lro_rc" + printf '%s\n' "$lro_out" | awk -F'\t' -v k="${2-}" '$1 == k { print $2; exit }' +} + +# THE INTENT, WRITTEN — the ONE writer, and every caller reaches it through +# `set-restart-intent`. An empty field is written as `none`, which is an ANSWER +# and not a gap, on the same argument Amendment 17(b) gives its `transcript` +# sub-field. +# +# THERE IS NO CREDENTIAL FIELD AND THERE IS NO PLACE FOR ONE. The fields are a +# lane, a generation, an operation, two transcript ids, an agent, a PROFILE +# NAME (a manifest key, never a token), a directory, a pane, a handoff path, +# its digest, an attempt count and a bounded reason. A caller that had a secret +# in hand would have nowhere here to put it. +lane_restart_put() { # <root> <lane> <state> <gen> <op> <mode> <agent> <profile> <dir> <pane> <window> <handoff> <digest> <old> <new> <attempt> <reason> <created> + lrw_root="$1"; lrw_lane="$2"; lrw_state="$3"; lrw_gen="$4"; lrw_op="$5" + lrw_mode="$6"; lrw_agent="$7"; lrw_prof="$8"; lrw_dir="$9"; shift 9 + lrw_pane="$1"; lrw_win="$2"; lrw_hf="$3"; lrw_dig="$4"; lrw_old="$5" + lrw_new="$6"; lrw_att="$7"; lrw_reason="$8"; lrw_created="$9"; lrw_prepared="${10-}" + for lrw_value in "$lrw_lane" "$lrw_state" "$lrw_gen" "$lrw_op" "$lrw_mode" \ + "$lrw_agent" "$lrw_prof" "$lrw_dir" "$lrw_pane" "$lrw_win" "$lrw_hf" \ + "$lrw_dig" "$lrw_old" "$lrw_new" "$lrw_att" "$lrw_created" "$lrw_prepared" "${WS:-none}"; do + lane_restart_value_ok "$lrw_value" || return 1 + done + # BOUNDED DIAGNOSTICS (design decision 3). A launcher that died printing a + # megabyte of stderr must not turn the lane's own control file into that + # megabyte, and the field is one LINE by construction. + lrw_reason="$(lane_restart_sidecar_value "$lrw_reason")" + if [ "${#lrw_reason}" -gt 400 ]; then + lrw_reason="$(printf '%s' "$lrw_reason" | cut -c1-400)… (truncated)" + fi + { printf 'schema: %s\n' "$LANE_RESTART_SCHEMA" + printf 'lane: %s\n' "$lrw_lane" + printf 'state: %s\n' "$lrw_state" + printf 'generation: %s\n' "${lrw_gen:-0}" + printf 'operation: %s\n' "${lrw_op:-none}" + printf 'mode: %s\n' "${lrw_mode:-fresh-from-handoff}" + printf 'agent: %s\n' "${lrw_agent:-none}" + printf 'profile: %s\n' "${lrw_prof:-none}" + printf 'dir: %s\n' "${lrw_dir:-none}" + printf 'pane: %s\n' "${lrw_pane:-none}" + printf 'window: %s\n' "${lrw_win:-none}" + printf 'handoff: %s\n' "${lrw_hf:-none}" + printf 'digest: %s\n' "${lrw_dig:-none}" + printf 'prepared_digest: %s\n' "${lrw_prepared:-none}" + printf 'old_transcript: %s\n' "${lrw_old:-none}" + printf 'new_transcript: %s\n' "${lrw_new:-none}" + printf 'attempt: %s\n' "${lrw_att:-0}" + printf 'workstation: %s\n' "${WS:-none}" + printf 'created: %s\n' "${lrw_created:-$(utc_now)}" + printf 'updated: %s\n' "$(utc_now)" + printf 'reason: %s\n' "${lrw_reason:-none}" + } | lane_restart_sidecar_put "$lrw_root/restart-intent.yaml" "$lrw_lane" +} + +# ------------------- AMENDMENT 19(c): THE SWEEP, ONE COMMIT OR NONE --------- +# +# `lane-end --retire-dormant <repo>` is the word a person types, the dry run +# they read and the `--yes` they answer with; THIS is the write underneath it. +# It is a verb of its own because the sweep touches many rows and many logs and +# is ONE commit — the shape `migrate-state-cells` has one screen up, for the +# same reason: a half-published sweep is a register whose rows and whose logs +# disagree about which lanes are finished. +# +# WHAT IT WRITES PER LANE, and clause (c) spells it out character by character: +# `lanes/log/<lane>.md` gains ONE line — +# RETIRED — lane <lane>, session <uuid>@<ws>, <UTC>, lane:<lane> +# → retired-dormant by lane <writer>; reason <why>; was: <the cell's head> +# and the row's state cell becomes `RETIRED · <UTC> · <why>; was: <head>`. +# +# THE PAYLOAD ON A `RETIRED` IS THIS AMENDMENT'S OWN. Amendment 7(b) gives +# `RETIRED` no payload and Amendment 11 clause (c) keeps it that way — which is +# why `lane-end`'s fork retire is a DOOR that writes nothing at all. Amendment +# 19 is later, ratified as drafted, and spells this line out in full: the row's +# own last words are carried into the log so that nothing the row said is lost +# when the row stops saying it. That is the whole of the exception, and it is +# this line and no other. +# +# THE CELL IS AMENDMENT 13(a)'s PHRASE, NOT CLAUSE (c)'s LITERAL TEXT. Clause +# (c) writes the cell as `RETIRED <UTC> · <why> · was: <head>` — four parts +# where 13(a)'s cell has three, and a first word of `RETIRED <UTC>`, which is a +# state no reader of Rule 6 or of the listing knows. The phrase that carries the +# same four facts under the grammar every other writer obeys is +# `RETIRED · <UTC> · <why>; was: <head>`, and it goes through `row_state_check` +# — the gate `set-row-state` uses — so the 240-character cap, the `|` and the +# second ` · ` are refused here exactly as they are there. The `|` a legacy cell +# may carry is replaced by `/` in the ROW (it would forge a cell boundary) and +# kept VERBATIM in the log line, which is not a table. +# +# THE THREE REFUSALS ARE CLAUSE (c)'s: a lane a live session holds on this +# workstation, a row whose log already carries a lane-kind line other than +# `ENDED`/`RETIRED` (a parked lane is not dormant), and — in `lane-end`, which +# is the word that finds them — a repository with no dormant row at all. +# ANY ONE OF THEM REFUSES THE WHOLE RUN, before a byte is written: this is one +# commit, so it is one decision. +retire_rows() { # <lane>… [--reason "<why>"] [--writer <lane>] + rr_reason=""; rr_writer="${LANES_LANE:-}"; rr_lanes="" + while [ $# -gt 0 ]; do + case "$1" in + # A FLAG IS NOT A VALUE (Copilot round 1 on #93). `--reason --writer x` + # took `--writer` as the reason and swept with it, and the writer the + # caller named was never read — a malformed line that RAN. A value + # beginning with `-` is refused and the `=` spelling named for the reason + # that legitimately starts with one. + --reason) case "${2-}" in '' | -*) die "--reason needs the words that say why, and '${2-}' is a flag — so the reason was left out. Spell a reason that really begins with a dash as --reason=<why>." 2 ;; esac + rr_reason="$2"; shift 2 ;; + --reason=*) rr_reason="${1#--reason=}"; [ -n "$rr_reason" ] || die "--reason needs the words that say why" 2; shift ;; + --writer) case "${2-}" in '' | -*) die "--writer needs the lane doing the sweeping, and '${2-}' is a flag — so the lane was left out." 2 ;; esac + rr_writer="$2"; shift 2 ;; + --writer=*) rr_writer="${1#--writer=}"; [ -n "$rr_writer" ] || die "--writer needs the lane doing the sweeping" 2; shift ;; + --) shift ;; + -*) die "unknown option '$1' for retire-rows (usage: retire-rows <lane>… [--reason \"<why>\"] [--writer <lane>])" 2 ;; + *) check_lane_name "$1"; rr_lanes="$rr_lanes $1"; shift ;; + esac + done + [ -n "$rr_lanes" ] || + die "usage: retire-rows <lane>… [--reason \"<why>\"] [--writer <lane>] + The lanes are DORMANT rows — a row with no object log and no live session + (Amendment 19(a)). The word that FINDS them, shows the dry run and asks for + the person's --yes is: lane-end --retire-dormant <repo>" 2 + [ -n "$rr_reason" ] || rr_reason="dormant row swept under Amendment 19(c)" + [ -n "$rr_writer" ] || + die "retire-rows needs the lane doing the sweeping: LANES_LANE=<lane> lanes-edit.sh retire-rows … (or --writer <lane>). Every line it writes carries that lane's own transcript uuid in its session field, and a session field that is anything else is wrong for ever in an append-only log (Amendment 7(b))." 2 + check_lane_name "$rr_writer" + # THE REASON IS CHECKED ONCE, HERE, AND NEVER PER ROW. It goes into every cell + # this sweep rewrites, so a `|` or a second ` · ` in it is a refusal of the + # ARGUMENT, named as one — rather than `row_state_check` dying half-way down + # the scan with a message about a cell the caller never wrote. The cap is + # lower than the cell's own, because the row's last words go in beside it. + case "$rr_reason" in + *'|'*) die "--reason may not contain '|': it would forge a cell boundary in every row this sweep rewrites. Got: '$rr_reason'" 2 ;; + *' · '*) die "--reason may not contain ' · ': that separator is what divides the state cell's three parts (Amendment 13(a)), and a second one reads back as a fourth part. Use a semicolon. Got: '$rr_reason'" 2 ;; + esac + if [ "${rr_reason//[$'\n\r']/}" != "$rr_reason" ]; then + die "--reason is ONE line: a newline in it would split a row in two and every row after it would be read as a lane" 2 + fi + if [ "${rr_reason//$US/}" != "$rr_reason" ]; then + die "--reason may not contain the internal field separator: it would corrupt the sweep plan before any row is written" 2 + fi + [ "${#rr_reason}" -le 180 ] || + die "--reason is ${#rr_reason} characters. The cell's whole line is capped at $ROW_STATE_CAP (Amendment 13, ratified decision O1) and the row's OWN last words go in beside it, so a reason longer than 180 leaves nothing of them. Shorten it — the long version belongs in the lane's log." 2 + + # R30 — THE FETCH FIRST, AND A CHECKOUT THAT IS BEHIND IS REFUSED, for the + # reason the migration gives: this act rewrites several rows and appends to + # several logs in ONE commit, and made against a register that is not the + # published one each of those is a conflict for `commit_push`'s rebase. + log_sync + if [ "$NO_GIT" != 1 ] && [ "$LOG_SYNC_FETCH" != yes ]; then + die "retire-rows requires a successful fresh fetch before rewriting several rows; $LOG_SYNC_FETCH. The local origin/$LANES_BRANCH ref may be stale. Nothing was written." 1 + fi + rr_writer="$(canon_lane "$rr_writer")" || exit 2 + # THE WRITER'S TRANSCRIPT IS THIS CHECKOUT'S ROW'S LAST ID, and the published + # row's only where this checkout has none (Copilot round 18 on #93, #138 item + # 8). `session_for` reads `$LANES_SESSION` or the PUBLISHED row, and the + # documented call sets only `LANES_LANE`: a writer whose newest transcript is + # stamped here and not yet pushed signed every append-only RETIRED line with an + # older id. A checkout behind origin is refused below, so this row is never + # the older of the two — the same reason refusal 1 reads both rows' ids. + rr_uuid="${LANES_SESSION:-}" + [ -n "$rr_uuid" ] || rr_uuid="$(session_ids_local_of_lane "$rr_writer" 2>/dev/null | tail -n1)" + [ -n "$rr_uuid" ] || rr_uuid="$(session_for "$rr_writer" 2>/dev/null || :)" + valid_uuid "$rr_uuid" || + die "the sweeping lane $rr_writer has no transcript uuid to write: \$LANES_SESSION is unset and its row's session cell holds none. Amendment 7(b) gives the session field a transcript uuid and ONLY that, and this log is append-only, so nothing is written. Run it from the lane's own session, or pass the id: LANES_SESSION=<uuid> LANES_LANE=$rr_writer lanes-edit.sh retire-rows …" 2 + # All path cleanliness and ref fences run under the same writer lock as the + # scan. A peer can otherwise alter a target log while this act waits. + acquire_lock + if [ "$NO_GIT" != 1 ] && have_remote_ref; then + rr_behind="$(git -C "$LANES_REPO" rev-list --count "HEAD..origin/$LANES_BRANCH" 2>/dev/null || printf '')" + case "$rr_behind" in + '' | 0) : ;; + *) die "this checkout is $rr_behind commit(s) behind origin/$LANES_BRANCH. The sweep is ONE commit over several rows and several logs, so it is made against the published register or not at all. Pull first — \`git -C $LANES_REPO pull --rebase\` — and re-run. Nothing was written." 2 ;; + esac + fi + refuse_dirty_checkout "retire-rows" "$LANES_PATH" + + # THE MUTEX COMES BEFORE THE SCAN, not between the scan and the write: this + # act reads every row's LINE NUMBER and rewrites those lines by number, and a + # peer's `add-row` landing in between moves them under it (the finding + # `migrate-state-cells` took in round 2 of openRepoTools#82). It is held from + # `acquire_lock` above; a peer's register edit is captured at the write, after + # every refusal of the scan (#157 item 4b, `migrate_state_cells`' reason). + + # THE LIVE READ IS FAIL-CLOSED, AND IT IS TAKEN INSIDE THE LOCK (Copilot round + # 2 on #93). `lanes_rows` degrades to the log's verb when this workstation's + # session records cannot be read, because a LISTING may not refuse; a WRITE + # that retired a row out from under the session still writing it is the other + # kind of mistake entirely — and a snapshot taken BEFORE the mutex is a + # snapshot a lane can go live behind: `lane-start` appends its id to the row + # under this same lock, so the scan would read that new id and compare it with + # a fence that predates it. + rr_live=""; rr_live_rc=0 + rr_live="$(live_session_ids 2>/dev/null)" || rr_live_rc=$? + [ "$rr_live_rc" = 0 ] || + die "this workstation's session records could not be read, so whether any of these lanes is LIVE HERE is not known — and clause (c) refuses a lane a live session holds. A read that failed is not 'nothing is live' (Amendment 7(d)). Nothing was written." 1 + rr_fence=" $(printf '%s\n' "$rr_live" | awk -F"$US" 'NF { print tolower($1) }' | tr '\n' ' ')" + + rr_utc="$(utc_now)" + rr_tmp="$(mktemp -d)" + : > "$rr_tmp/plan"; : > "$rr_tmp/report" + rr_n=0; rr_names="" + rr_follow="" + rr_seen="" + for rr_lane in $rr_lanes; do + rr_l="$(canon_lane "$rr_lane")" || exit 2 # Amendment 15 + # THE SEAM (ruling 2026-10-04). The sweep is ONE commit, so one managed or + # unknown lane in it refuses all of it, here in the scan, before any line or + # cell is written; `die` releases the lock this sweep holds. + managed_seam_refuse "$rr_l" "retire-rows (Amendment 19's sweep)" + # A LANE NAMED TWICE IS A REFUSAL AND NOT A SECOND LINE. The log is + # append-only: a duplicate in the argument list would put the same `RETIRED` + # line into it twice, in one commit, and no later line could take it back. + # Compared on the RESOLVED name, so the two spellings of one lane are one + # lane here as they are everywhere else (Amendment 15). + case " $rr_seen " in + *" $rr_l "*) die "lane $rr_l is named twice in this sweep. Its log is append-only, so a second pass over it would write the same RETIRED line again and nothing could take it back. Name each lane once. Nothing was written." 2 ;; + esac + rr_seen="$rr_seen $rr_l" + rr_ln="$(row_line "$rr_l")" || exit 2 # one row, exactly + rr_row="$(sed -n -e "${rr_ln}p" "$LANES_FILE")" + if [ "${rr_row//$US/}" != "$rr_row" ]; then + die "lane $rr_l's row contains the internal sweep-plan field separator, so it cannot be serialized safely. Nothing was written." 2 + fi + rr_rc=0; row_split_state_cell "$rr_row" || rr_rc=$? + case "$rr_rc" in + 0) : ;; + 2) die "lane $rr_l's row (line $rr_ln) carries $(row_sep_count "$rr_row") ' | ' separators where a seven-column row carries 6, so WHICH TEXT IS THE STATE CELL is not knowable from the row — and this act both READS that cell (the words it carries into the log) and REWRITES it. Escape the literal pipe inside that cell as \| by hand, commit it, and re-run. Nothing was written." 2 ;; + *) die "lane $rr_l's row (line $rr_ln) does not open with '|' and end with '|', so it is not a row this writer can take apart. Nothing was written." 2 ;; + esac + mig_trim "$RSS_CELL"; rr_cell="$MIG_TRIM" + rr_head="$rr_cell" + if [ "${#rr_head}" -gt 240 ]; then + # THE CAP IS CLAUSE (c)'s 240, CUT BACK TO A SPACE — `cut_to_line`'s rule + # and the migration's: `${s:0:n}` counts bytes wherever the locale is not + # a UTF-8 one, and these cells are full of `·`, `—` and `→`. + rr_head="${rr_head:0:236}" # 236 + " ..." is the 240 clause (c) gives + case "$rr_head" in *' '*) rr_head="${rr_head% *}" ;; esac + rr_head="$rr_head ..." + fi + + # (c) REFUSAL 1 — a live session here. + # BOTH ROWS' IDS, for the reason `lanes_rows` gives one screen up: an id + # this checkout has committed and not yet pushed is on no published cell, + # and this is the FAIL-CLOSED half of the same question (Copilot round 1 on + # #93). + rr_ids="$(session_ids_of_lane "$rr_l" 2>/dev/null || :) +$(session_ids_local_of_lane "$rr_l" 2>/dev/null || :)" + for rr_id in $rr_ids; do + case "$rr_fence" in + *" $rr_id "*) die "lane $rr_l has a LIVE session on this workstation (transcript $rr_id), so it is not a dormant row: clause (c) refuses a lane a live session holds, and retiring it would take the row out from under the conversation that IS the lane. End it the ordinary way when it is done — lane-end $rr_l. Nothing was written." 2 ;; + esac + done + + # (c) REFUSAL 2 — a log that says the lane is somewhere. + # + # THE PUBLISHED LOG IS PROVED READABLE FIRST (Copilot round 3 on #93). + # `lane_log_events` ends in `git show … | parse_log_stream` and this file + # sets no `pipefail`, so a `git show` that FAILED is masked by the parser + # exiting 0 over empty input — and the lane then reads as having no + # lane-kind line at all, which is the one answer that lets the sweep + # through. The object is asked for by name instead, and then `show` with its + # own status. + # WHETHER THE PATH IS PUBLISHED IS THE TREE'S ANSWER, NOT THE BLOB'S + # (Copilot round 21 on #93, #138 item 17). It was `cat-file -e`, which + # fails for a blob that is missing or corrupt exactly as for a path that is + # not there, so a log the tree names and git cannot read was "no published + # log" and the sweep went on. `ls-tree` reads the tree alone. + rr_pubp="" + rr_pubp="$(log_path_ci "$rr_l")" || + die "lane $rr_l's object log is published twice under names that differ only by case (above) — 15(d)'s hand merge. Nothing was written." 2 + if [ "$NO_GIT" != 1 ] && have_remote_ref; then + rr_intree="" + rr_intree="$(git -C "$LANES_REPO" ls-tree --name-only "origin/$LANES_BRANCH" -- "$rr_pubp" 2>/dev/null)" || + die "the tree of origin/$LANES_BRANCH could not be listed, so whether lane $rr_l has a published object log is not known — and that is NOT 'it has none' (Amendment 7(d)). Nothing was written." 1 + if [ -n "$rr_intree" ]; then + git -C "$LANES_REPO" show "origin/$LANES_BRANCH:$rr_pubp" >/dev/null 2>&1 || + die "lane $rr_l's published object log ($rr_pubp) exists on origin/$LANES_BRANCH and could not be read, so whether it carries a lane-kind line is not known — and that is NOT 'it has none' (Amendment 7(d)). Nothing was written." 1 + fi + fi + rr_ev=""; rr_erc=0 + rr_ev="$(lane_log_events "$rr_l" 2>/dev/null)" || rr_erc=$? + [ "$rr_erc" = 0 ] || + die "lane $rr_l's object log could not be read (exit $rr_erc), so whether it carries a lane-kind line is not known — and that is NOT 'this lane has no log' (Amendment 7(d)). Nothing was written." 1 + # AND THIS CHECKOUT'S OWN COPY OF THAT LOG (Copilot round 2 on #93), for the + # reason the session ids are read from both rows: `lane_log_events` answers + # out of `origin/<branch>` (R19), and a log line committed here and not yet + # pushed is on no origin at all. The `behind` guard above refuses a checkout + # that is behind; one that is AHEAD is legitimate, and there a `STARTED` + # that exists only here would be invisible — the lane reading as dormant + # while its own log says it is running. + # AND THE LOCAL ONE IS READ WITH THE SAME POSTURE (round 3): converted to an + # empty stream with `|| :`, a TRACKED log that exists here and will not open + # read as a lane with no lane-kind line — and the untracked-file guard below + # does not catch a tracked one. + rr_lev="" + rr_lf="$(log_file_for "$rr_l")" + # A LOG PATH THAT IS A SYMLINK, OR THERE AND NOT A REGULAR FILE, IS REFUSED + # BEFORE IT IS READ (Copilot round 18 on #93, #138 item 12). The write + # appends with `>>`, which follows a link: a tracked link here put the + # RETIRED line in whatever file it named, outside the repository, while the + # commit recorded only the link. + if [ -L "$rr_lf" ] || { [ -e "$rr_lf" ] && [ ! -f "$rr_lf" ]; }; then + die "lane $rr_l's object log $(log_path_for "$rr_l") is a symlink, or is there and not a regular file, in this checkout. This sweep appends to it with '>>', which writes through a link to whatever file it names while the commit records only the link. Put the log itself there as a regular file, commit that, and re-run. Nothing was written." 2 + fi + if [ -f "$rr_lf" ]; then + [ -r "$rr_lf" ] || + die "lane $rr_l's object log $rr_lf exists in this checkout and could not be read, so whether it carries a lane-kind line is not known — and that is NOT 'it has none' (Amendment 7(d)). Nothing was written." 1 + rr_lev="$(log_events "$rr_lf" 2>/dev/null)" || + die "lane $rr_l's object log $rr_lf could not be parsed, so whether it carries a lane-kind line is not known (Amendment 7(d)). Nothing was written." 1 + fi + rr_open="$(printf '%s\n%s\n' "$rr_ev" "$rr_lev" | awk -F"$US" '$3 == "STARTED" || $3 == "PAUSED" || $3 == "RESUMED" || $3 == "ENDED" || $3 == "RETIRED" { v = $3 } END { if (v != "") print v }')" + rr_pub_open="$(printf '%s\n' "$rr_ev" | awk -F"$US" '$3 == "STARTED" || $3 == "PAUSED" || $3 == "RESUMED" || $3 == "ENDED" || $3 == "RETIRED" { v = $3 } END { if (v != "") print v }')" + # THE RULE IS CLAUSE (c)'s AND STAYS: a log that CARRIES a lane-kind line is + # refused. THE SENTENCE FOLLOWS THE LAST ONE (#120 item 3, Copilot round 5 on + # #93). A log whose last lane-kind line is ENDED or RETIRED is a lane already + # CLOSED (19(a)), and `lane-end` is not its exit: it is told it is closed, + # already hidden, and — for RETIRED alone, the only cell `archive-rows` + # moves — which act takes the row out of the register. + # + # AND "CLOSED" IS SAID ONLY OF A CLOSING LINE ORIGIN CARRIES (the review of + # #263, S2). An earlier sweep that stopped part-way leaves its RETIRED line + # in this checkout's log and nowhere else; a re-run told the lane it was + # CLOSED, "nothing more is owed", about a row never retired and a line never + # published. That line is still refused, and is named as this checkout's. + case "$rr_open" in + '') : ;; + ENDED | RETIRED) + rr_art=a; [ "$rr_open" != ENDED ] || rr_art=an + [ "$rr_pub_open" = "$rr_open" ] || + die "lane $rr_l's object log in THIS CHECKOUT ends on $rr_art $rr_open line, and origin/$LANES_BRANCH's copy does not: it is a write made here and never published, by an earlier act that stopped part-way or a commit whose push has not landed (\`git -C $LANES_REPO status\` and \`git -C $LANES_REPO log origin/$LANES_BRANCH..HEAD -- $(log_path_for "$rr_l")\` say which). It is refused either way, since a second closing line would be one more line in an append-only log, and the lane is not called CLOSED, since nothing published says so. Publish that line or undo it, then re-run. Nothing was written." 2 + case "$rr_open" in + RETIRED) + die "lane $rr_l's object log ends on a RETIRED line, so the lane is already CLOSED and RETIRED (Amendment 19(a)), not a dormant row: \`lanes\` already hides it (19(b)), and its log is append-only, so it is not retired a second time. Its row leaves the register by \`lanes-edit.sh archive-rows ${rr_l%-*}\` (19(d)), which moves that repository's rows whose state cell says RETIRED. Nothing was written." 2 ;; + *) + die "lane $rr_l's object log ends on an ENDED line, so the lane is already CLOSED (Amendment 19(a)): it was ended, and a closed lane is not a dormant row. \`lanes\` already hides it (19(b)), and its log is append-only, so a RETIRED line after its ENDED would be one more line for a lane that is already finished. Nothing more is owed: its row stays in the register as the record (Rule 9), and \`archive-rows\` is not its exit, since it moves only rows whose state cell says RETIRED. Nothing was written." 2 ;; + esac ;; + *) + die "lane $rr_l's object log carries a $rr_open line as its last lane-kind line, so it is not a dormant row: a running or parked lane is a lane a person can still pick up. End it as itself when its work is done: lane-end $rr_l. Nothing was written." 2 ;; + esac + + # (c) REFUSAL 3 — THE ROW ITSELF SAYING THE LANE IS SOMEWHERE, which is the + # same test the listing makes and is re-proved here rather than trusted + # (Copilot round 1 on #93). Amendment 13(a) makes the state cell the lane's + # CURRENT STATE: a cell that is the phrase and names anything but `ENDED`, + # `RETIRED` or the migration's `MIGRATED` is a row `lanes` does not hide + # either, and the writer and the read must not disagree about which rows are + # dormant — that is the defect clause (h) and A11 Addendum 4 ruling 7 both + # exist to prevent. + # + # A CELL THAT ALREADY SAYS `RETIRED` IS NOT A SECOND RETIREMENT (Copilot + # round 20 on #93). Refused here, it was a row the listing classes DORMANT + # and the preview names — and one refusal stops the whole sweep. The row a + # migration leaves is exactly that: the phrase in the cell, NOTED lines in + # the log. A second retirement is a second RETIRED LINE in an append-only + # log, and refusal 2 just above refuses that, from the log. + if mig_cell_is_phrase "$rr_cell"; then + case "${rr_cell%% · *}" in + ENDED | RETIRED | MIGRATED) : ;; + *) die "lane $rr_l's row says ${rr_cell%% · *}: its state cell is Amendment 13(a)'s phrase — '$rr_cell' — and that cell is the lane's CURRENT STATE, so this is not a dormant row and \`lanes\` does not hide it either. A lane the register says is somewhere is ended as itself (lane-end $rr_l) or its cell is corrected first (set-row-state). Nothing was written." 2 ;; + esac + fi + + # AMENDMENT 15 — the log this write appends to is the row's own spelling, + # and a case-only rename is a write of its own rather than one this sweep + # smuggles into a commit that names something else. Both halves of + # `ensure_log`'s question are asked HERE, in the scan, so the refusal comes + # before any byte is written rather than half-way through the run. + # AND A LOG DIRECTORY THAT CANNOT BE LISTED IS A REFUSAL HERE (#138 item 9), + # not a lane with no log that `ensure_log` then fails on inside the loop. + rr_loc="$(log_files_named_ci "$rr_l")" || + die "the log directory $LANES_LOG_DIR exists and could not be listed, so whether lane $rr_l has a log of any case in this checkout is not known — and that is NOT 'it has none' (Amendment 7(d)). Nothing was written." 1 + rr_ln2="$(printf '%s' "$rr_loc" | grep -c . || :)" + [ "$rr_ln2" -le 1 ] || + die "lane $rr_l has $rr_ln2 object logs in this checkout whose names differ only by case: $(printf '%s\n' "$rr_loc" | tr '\n' ' ')— one lane is ONE lane under any case (Amendment 15) and no read of it is unambiguous. Merge them by hand into $(log_file_for "$rr_l") (15(d)) and re-run. Nothing was written." 2 + if [ "$rr_ln2" = 1 ] && [ "$rr_loc" != "$(log_file_for "$rr_l")" ]; then + die "lane $rr_l's object log is here as ${rr_loc##*/} while the row spells the lane $rr_l, so the first write to it RENAMES the file (Amendment 15) — and this sweep is one commit over several lanes, which is not the commit that rename belongs in. Take it first with a write of that lane's own (\`LANES_LANE=$rr_l lanes-edit.sh log NOTED lane:$rr_l \"<what it was>\"\`), then re-run. Nothing was written." 2 + fi + # AN UNTRACKED LOG IS SOMEBODY'S UNCOMMITTED WORK, AND THIS ACT WOULD + # COMMIT IT — the finding `migrate-state-cells` took in round 2 of + # openRepoTools#82, and this sweep has the same shape. A TRACKED log that is + # dirty is already refused for the whole run by `refuse_dirty_checkout` + # above, which exempts the register alone; an untracked file is in neither + # of its lists, so appending here would put a peer's first lines into this + # sweep's one commit under this sweep's message. (A dormant row usually has + # no log at all — but a migrated one has a log of NOTED lines, and that is + # the file this meets.) + if [ "$rr_ln2" = 1 ] && [ "$NO_GIT" != 1 ] && + ! git -C "$LANES_REPO" ls-files --error-unmatch -- "$(log_path_for "$rr_l")" >/dev/null 2>&1; then + die "lane $rr_l's object log $(log_path_for "$rr_l") exists in this checkout but is NOT TRACKED — somebody's uncommitted work, which this sweep would commit inside its own commit and under its own message. Commit it first (\`git -C $LANES_REPO commit -m \"<what it is>\" -- $(log_path_for "$rr_l")\`) and re-run. Nothing was written." 2 + fi + # THE PUBLISHED PATH IS THE ONE THE READABILITY PROBE ALREADY RESOLVED — + # `log_path_ci` is a `ls-tree` of the whole log directory and this loop runs + # per lane, so asking it twice for one lane is a second read of the same + # tree for the same answer. + # + # AND THE QUESTION IS `ensure_log`'S OWN, NOT A PARAPHRASE OF IT (#120 item + # 2, Copilot round 5 on #93). The scan asked it only where this checkout had + # NO log, and beside that compared a BASENAME with a repo-relative PATH, a + # clause that could never be equal. So the state a case-only rename leaves + # when its commit has not been pushed — the row's spelling here, committed; + # the old spelling still in origin's tree; a checkout merely AHEAD, which the + # `behind` guard rightly lets through — passed the scan, and `ensure_log` + # refused it INSIDE THE WRITE LOOP, after the lanes before it in this one + # commit had had their logs created and appended. It is asked here as + # `ensure_log` asks it, in its words, because it is the same refusal; the + # refusal of a local file of another case above means `rr_from`, where + # there is one, is the row's own spelling. + rr_pub="$rr_pubp" + rr_from="" + [ "$rr_ln2" = 1 ] && rr_from="$rr_loc" + if [ "$rr_pub" != "$(log_path_for "$rr_l")" ] && [ "${rr_from##*/}" != "${rr_pub##*/}" ]; then + rr_here="and this checkout does not have it" + [ -n "$rr_from" ] && rr_here="while this checkout has ${LANES_LOG_PREFIX}${rr_from##*/} instead — a case-only rename whose commit never landed" + die "lane ${rr_l}'s object log is published as $rr_pub $rr_here: the row spells the lane $rr_l, so the log is $(log_path_for "$rr_l") (Amendment 15), and writing one here now would leave TWO files for one lane. Pull first — \`git -C $LANES_REPO pull --rebase\` — and re-run. Nothing was written." 2 + fi + + # THE LINE AND THE CELL, BOTH BUILT AND BOTH CHECKED BEFORE ANYTHING IS + # WRITTEN. `row_state_check` dies on a cap, a `|` or a second ` · `, so it + # is asked HERE — in the scan — and never with the register half-rewritten. + rr_pay="retired-dormant by lane $rr_writer; reason $rr_reason; was: $rr_head" + event_line RETIRED "$rr_l" "$rr_uuid" "$rr_utc" "lane:$rr_l" '→' "$rr_pay" > "$rr_tmp/line.$rr_ln" + rr_wasrow="$(printf '%s' "$rr_head" | tr '|' '/')" + rr_wasrow="${rr_wasrow// · /; }" + rr_line="$rr_reason; was: $rr_wasrow" + if [ "${#rr_line}" -gt "$ROW_STATE_CAP" ]; then + rr_line="${rr_line:0:$((ROW_STATE_CAP - 4))}" + case "$rr_line" in *' '*) rr_line="${rr_line% *}" ;; esac + rr_line="$rr_line ..." + fi + row_state_check "RETIRED · $rr_line" + rr_new="RETIRED · $rr_utc · $ROW_STATE_LINE" + printf '%s%s%s%s%s%s%s%s%s\n' "$rr_ln" "$US" "$rr_l" "$US" "$rr_new" "$US" "$RSS_HEAD" "$US" "$RSS_TAIL" >> "$rr_tmp/plan" + printf ' %-26s %s\n' "$rr_l" "$rr_new" >> "$rr_tmp/report" + rr_names="$rr_names $rr_l" + # THE LIFECYCLE PRE-IMAGE, TAKEN UNDER THE LOCK THIS SWEEP ALREADY HOLDS + # (openRepoTools#91). These `RETIRED` lines are appended by this function + # and never by `write_event`, so the follow-up that moves a lane's snapshot + # to `CLOSED` for every other `RETIRED` would never run for them, and a + # swept lane would keep whatever its snapshot last said. The pre-image is + # what the follow-up compares against, exactly as `write_event` takes it. + rr_follow="$rr_follow$rr_l$US$(lane_state_preimage "$rr_l" "")${US}8 +" + rr_n=$((rr_n + 1)) + done + + # --------------------------------------------------------------- the write + # + # THE LOGS FIRST AND THE ROWS SECOND, and all of it published by the single + # `commit_push` at the end: a refusal in the middle leaves this checkout dirty + # and the register unpublished, which `git status` shows and + # `git checkout -- lanes` undoes whole. Nothing is half-published, because the + # commit is the only thing that publishes. A peer's register edit is + # committed as its own first, as `migrate_state_cells` says at its write. + handle_preexisting "$LANES_PATH" + rr_paths=("$LANES_PATH") + while IFS="$US" read -r rr_ln rr_l rr_new rr_head2 rr_tail; do + [ -n "${rr_ln:-}" ] || continue + ensure_log "$rr_l" + append_text_block "$(log_file_for "$rr_l")" "$(cat -- "$rr_tmp/line.$rr_ln")" + rr_paths+=("$(log_path_for "$rr_l")") + reg_wrote "$(log_path_for "$rr_l") (its RETIRED line)" + done <<EOF +$(cat -- "$rr_tmp/plan") +EOF + while IFS="$US" read -r rr_ln rr_l rr_new rr_head2 rr_tail; do + [ -n "${rr_ln:-}" ] || continue + replace_line "$rr_ln" "$rr_head2$rr_new $rr_tail" + reg_wrote "$LANES_PATH (the row of $rr_l)" + done <<EOF +$(cat -- "$rr_tmp/plan") +EOF + + printf 'retire-rows — %s lane(s) RETIRED (lane-collision-protocol Amendment 19(c))\n' "$rr_n" + printf ' writer : lane %s, session %s@%s\n' "$rr_writer" "$rr_uuid" "$WS" + printf ' reason : %s\n' "$rr_reason" + printf '\n lane the cell it becomes\n' + cat -- "$rr_tmp/report" + rm -rf -- "$rr_tmp" + + rr_msg="LANES(retire-dormant@$WS): Amendment 19(c) — $rr_n dormant row(s) RETIRED by lane $rr_writer;$rr_names; reason $rr_reason" + commit_push "$rr_msg" "${rr_paths[@]}" + rr_crc=$? + release_lock + # AND EACH SWEPT LANE'S SNAPSHOT FOLLOWS ITS LINE, after the lock, for the + # reason `write_event` gives at its own foot: the follow-up takes the mutex + # for itself and never fails the act whose lines have already landed. + while IFS="$US" read -r rr_fl rr_fpre rr_fseam; do + [ -n "${rr_fl:-}" ] || continue + lane_state_follow "$rr_fl" RETIRED "" "$rr_uuid" "$rr_fpre" "$rr_fseam" + done <<RR_FOLLOW +$rr_follow +RR_FOLLOW + return "$rr_crc" +} + +# ------------------- AMENDMENT 19(d): THE ARCHIVE, A SECOND ACT ON A SECOND +# WORD +# +# `archive-rows <repo>` MOVES every `RETIRED` row of `<repo>` out of +# `lanes/LANES.md` and into `lanes/archive/LANES-retired.md`, in ONE commit +# whose message names each lane moved. Rule 9 holds either way — a row is one +# `git show` away — so this is for a register a person wants SHORTER and is +# never a requirement, and nothing reads a row differently for having moved: +# `register_lanes`, `lanes_register_index` and `lane_position_rows` all read +# the archive beside the register, which is the amendment's own sentence +# (*"every reader of the next free position and `lanes --closed` read the +# archive too"*). A retired `<repo>-<n>` is never reissued. +# +# WHICH ROWS: the lane name's head — everything before its LAST hyphen — is the +# repository, compared without regard to case, which is `lane_next_free`'s rule +# for the same question and not a second one; and the state cell names `RETIRED` +# by `mig_lead_state`, the one reader of a cell's leading state word, so a +# legacy cell and Amendment 13's phrase are read by the same code. +archive_rows() { # <repo> <1 = the act, 0 = the dry run> + ar_repo="$1"; ar_do="${2:-0}" + ar_rl="$(lc "$ar_repo")" + log_sync + if [ "$ar_do" = 1 ]; then + if [ "$NO_GIT" != 1 ] && [ "$LOG_SYNC_FETCH" != yes ]; then + die "archive-rows requires a successful fresh fetch before moving rows; $LOG_SYNC_FETCH. The local origin/$LANES_BRANCH ref may be stale. Nothing was written." 1 + fi + if [ "$NO_GIT" != 1 ] && have_remote_ref; then + ar_behind="$(git -C "$LANES_REPO" rev-list --count "HEAD..origin/$LANES_BRANCH" 2>/dev/null || printf '')" + case "$ar_behind" in + '' | 0) : ;; + *) die "this checkout is $ar_behind commit(s) behind origin/$LANES_BRANCH. The move is ONE commit carrying the register and the archive, so it is made against the published register or not at all. Pull first — \`git -C $LANES_REPO pull --rebase\` — and re-run. Nothing was written." 2 ;; + esac + fi + acquire_lock + # The cleanliness fence belongs INSIDE the writer lock. Another writer + # could otherwise create or edit the archive while this act waits for it. + # THE ARCHIVE IS NOT EXEMPT (Copilot round 4 on #93). It was, because this + # act writes it — but `handle_preexisting` captures the REGISTER alone, so a + # tracked edit somebody else left in the archive rode into this commit under + # this act's message. And it is what makes a half-done move safe: if the + # append lands and `delete_lines` or the commit does not, the archive is + # dirty and the next run REFUSES by name instead of appending the same rows + # a second time. + refuse_dirty_checkout "archive-rows" "$LANES_PATH" + # THE SAME RULE FOR THE ARCHIVE ITSELF: an untracked one is a file this act + # did not create, and appending to it would commit somebody else's lines + # inside this move (openRepoTools#82, round 2). An archive this act creates + # is untracked for the seconds between the write and the commit, which is + # why the test is made HERE — before anything is written. + if [ -f "$LANES_ARCH_FILE" ] && [ "$NO_GIT" != 1 ] && + ! git -C "$LANES_REPO" ls-files --error-unmatch -- "$LANES_ARCH_PATH" >/dev/null 2>&1; then + die "$LANES_ARCH_PATH exists in this checkout but is NOT TRACKED — somebody's uncommitted work, which this move would commit inside its own commit. Commit it first (\`git -C $LANES_REPO commit -m \"<what it is>\" -- $LANES_ARCH_PATH\`) and re-run. Nothing was written." 2 + fi + # AN ARCHIVE THAT IS A SYMLINK, OR THERE AND NOT A REGULAR FILE, IS REFUSED + # (Copilot on #93's `afd5481`, #138 item 10). The rows are appended with + # `>>`, which follows a link: a tracked link here put them in whatever file + # it named, outside the repository, while the commit published the link and + # their removal from the register — the rows left the repository entirely. + if [ -L "$LANES_DIR/archive" ] || [ -L "$LANES_ARCH_FILE" ] || + { [ -e "$LANES_ARCH_FILE" ] && [ ! -f "$LANES_ARCH_FILE" ]; }; then + die "$LANES_ARCH_PATH, or its directory, is a symlink — or the archive is there and not a regular file. This move appends the rows with '>>', which writes through a link to whatever file it names while the commit records the link and removes the rows from the register. Put the archive itself there as a regular file, commit it, and re-run. Nothing was written." 2 + fi + # A PUBLISHED ARCHIVE THIS CHECKOUT DOES NOT HAVE IS REFUSED (Copilot on #93's + # `d0310f6`, #138 item 2). Out of a sparse checkout, or marked skip-worktree, + # the file is absent here and in nobody's dirty list, so the move created a + # NEW archive of only its own rows, whose commit would drop every position the + # published one reserves (Amendment 19(b)). Refused rather than seeded from + # origin: git (2.43, measured) will not stage a skip-worktree path, so a seeded + # archive fails at the commit after the rows have left the register here. + if [ "$NO_GIT" != 1 ] && have_remote_ref && [ ! -e "$LANES_ARCH_FILE" ] && [ ! -L "$LANES_ARCH_FILE" ]; then + ar_pubarch="" + ar_pubarch="$(git -C "$LANES_REPO" ls-tree --name-only "origin/$LANES_BRANCH" -- "$LANES_ARCH_PATH" 2>/dev/null)" || + die "the tree of origin/$LANES_BRANCH could not be listed, so whether $LANES_ARCH_PATH is published is not known — and a move that creates one beside a published one drops every position it reserves (Amendment 7(d)). Nothing was written." 1 + [ -z "$ar_pubarch" ] || + die "$LANES_ARCH_PATH is published on origin/$LANES_BRANCH and this checkout does not have it (it is outside a sparse checkout, or marked skip-worktree). A move made here would create a new archive holding only these rows, and its commit would drop every retired position the published one reserves (Amendment 19(b)). Bring it into this checkout — \`git -C $LANES_REPO sparse-checkout add ${LANES_ARCH_PATH%/*}\`, or for a skip-worktree path \`git -C $LANES_REPO update-index --no-skip-worktree $LANES_ARCH_PATH\` and \`git -C $LANES_REPO checkout -- $LANES_ARCH_PATH\` — and re-run. Nothing was written." 2 + fi + fi + + # THE REGISTER IS READ WITH ITS OWN STATUS (Copilot round 4 on #93). Inside + # the here-document below, a failed `awk` — an unreadable register — is + # discarded, the loop gets no rows, and the act reports "no row of <repo> has + # the state RETIRED" about a file it never read. An unreadable source is never + # an empty set (Amendment 7(d)). + ar_scan="" + ar_scan="$(awk 'substr($0,1,1) == "|" { + p1 = index($0, "`"); if (p1 == 0) next + r = substr($0, p1 + 1); p2 = index(r, "`"); if (p2 == 0) next + printf "%d\t%s\n", NR, substr(r, 1, p2 - 1) + }' "$LANES_FILE")" || + die "the register $LANES_FILE could not be read, so which of $ar_repo's rows are RETIRED is not known — and that is not 'none of them are' (Amendment 7(d)). Nothing was written." 1 + + ar_tmp="$(mktemp -d)" + : > "$ar_tmp/rows"; : > "$ar_tmp/nums"; : > "$ar_tmp/names" + ar_n=0 + while IFS="$(printf '\t')" read -r ar_num ar_lane; do + [ -n "${ar_num:-}" ] || continue + case "$(lc "$ar_lane")" in + "$ar_rl"-*) : ;; + *) continue ;; + esac + ar_head="$ar_lane"; ar_head="${ar_head%-*}" + [ "$(lc "$ar_head")" = "$ar_rl" ] || continue + ar_row="$(sed -n -e "${ar_num}p" "$LANES_FILE")" + # A ROW OF THIS REPOSITORY THAT CANNOT BE TAKEN APART IS A REFUSAL, NOT A + # SKIP (Copilot round 1 on #93). This act says it moves EVERY `RETIRED` row + # of `<repo>`; a row whose ` | ` count hides which text is the state cell + # may BE one, and moving the others while saying nothing about it is a + # partial act reported as a whole one. + ar_src=0; row_split_state_cell "$ar_row" || ar_src=$? + if [ "$ar_src" != 0 ]; then + rm -rf -- "$ar_tmp" + die "lane $ar_lane is $ar_repo's and its row (line $ar_num) carries $(row_sep_count "$ar_row") ' | ' separators where a seven-column row carries 6, so whether its state is RETIRED is not knowable from the row — and this act moves EVERY retired row of a repository or none of them. Escape the literal pipe inside that cell as \| by hand, commit it (\`LANES_LANE=$ar_lane lanes-edit.sh commit \"escape a literal pipe in row $ar_lane\"\`), and re-run. Nothing was written." 2 + fi + mig_trim "$RSS_CELL" + [ "$(mig_lead_state "$MIG_TRIM")" = RETIRED ] || continue + # THE SEAM (Copilot round 3 on #97). This act takes a row out of the + # register, and a RETIRED row may carry the managed ledger's marker. One + # managed or unknown row refuses the WHOLE move, as one refuses the whole + # of the sweep, because the move is one commit. Asked in a subshell so this + # function removes its own staging directory before it exits, as each + # refusal above does; `die` there has already said why. + ar_mrc=0 + ( managed_seam_refuse "$ar_lane" "archive-rows $ar_repo (the WHOLE move, which Amendment 19(d) makes one commit)" ) || ar_mrc=$? + if [ "$ar_mrc" != 0 ]; then + rm -rf -- "$ar_tmp" + exit "$ar_mrc" + fi + printf '%s\n' "$ar_row" >> "$ar_tmp/rows" + printf '%s\n' "$ar_num" >> "$ar_tmp/nums" + printf '%s\n' "$ar_lane" >> "$ar_tmp/names" + ar_n=$((ar_n + 1)) + done <<EOF +$ar_scan +EOF + + printf 'archive-rows %s — %s (lane-collision-protocol Amendment 19(d))\n' \ + "$ar_repo" "$( [ "$ar_do" = 1 ] && printf 'THE ACT' || printf 'DRY RUN, nothing is written' )" + printf ' register : %s\n' "$LANES_FILE" + printf ' archive : %s\n' "$LANES_ARCH_PATH" + printf ' rows : %s RETIRED row(s) of %s\n' "$ar_n" "$ar_repo" + if [ "$ar_n" -gt 0 ]; then + printf '\n' + awk '{ print " " $0 }' "$ar_tmp/names" + fi + if [ "$ar_n" = 0 ]; then + rm -rf -- "$ar_tmp" + die "no row of $ar_repo has the state RETIRED, so there is nothing to archive — this act moves finished rows and never anything else. \`lanes --closed --prefix $ar_repo\` shows what that repository's rows say; \`lane-end --retire-dormant $ar_repo\` is what RETIRES its dormant ones. Nothing was written." 2 + fi + if [ "$ar_do" != 1 ]; then + printf '\n DRY RUN — nothing was written. Make it the one act with: lanes-edit.sh archive-rows %s --yes\n' "$ar_repo" + rm -rf -- "$ar_tmp" + return 0 + fi + # A stopped earlier run may have appended to the archive before it removed + # the register rows. Never append those identities a second time, even if + # that partial archive was subsequently committed during recovery. + ar_existing="" + if [ -f "$LANES_ARCH_FILE" ]; then + ar_existing="$(awk -F'`' '/^\|/ && NF >= 3 { print $2 }' "$LANES_ARCH_FILE")" || + die "could not read $LANES_ARCH_FILE to check for already archived lanes. Nothing was written." 1 + fi + while IFS= read -r ar_lane; do + [ -n "$ar_lane" ] || continue + if printf '%s\n' "$ar_existing" | command grep -qixF -- "$ar_lane"; then + die "lane $ar_lane is already in $LANES_ARCH_PATH while still present in the register. Resolve that partial archive move before retrying; nothing was written." 2 + fi + done < "$ar_tmp/names" + + # THE ARCHIVE IS WRITTEN FIRST AND THE ROWS REMOVED SECOND, for the reason + # `delete_lines` gives: a refusal between the two leaves a copy in the archive + # and the register whole, and never a row in neither file. A peer's register + # edit is committed as its own first, after every refusal above (#157 item + # 4b, `migrate_state_cells`' reason). + handle_preexisting "$LANES_PATH" + mkdir -p -- "$LANES_DIR/archive" || + die "could not create $LANES_DIR/archive — the archive is written before anything is removed, so nothing has been" 6 + if [ ! -f "$LANES_ARCH_FILE" ]; then + { + printf '# LANES-retired.md — rows RETIRED out of `lanes/LANES.md`\n\n' + printf 'lane-collision-protocol Amendment 19(d). These lanes are finished. Their\n' + printf 'positions are NEVER REISSUED: every reader of the next free position and\n' + printf '`lanes --closed` read this file beside the register.\n\n' + printf '| lane | session id | workstation / env / user | started (UTC) | objects owned | handoff path | state |\n' + printf '|---|---|---|---|---|---|---|\n' + } > "$LANES_ARCH_FILE" || + die "could not write $LANES_ARCH_FILE — nothing has been removed from the register" 6 + note "created $LANES_ARCH_FILE" + reg_wrote "$LANES_ARCH_PATH (created)" + fi + append_text_block "$LANES_ARCH_FILE" "$(cat -- "$ar_tmp/rows")" + reg_wrote "$LANES_ARCH_PATH ($ar_n row(s) appended)" + delete_lines "$(cat -- "$ar_tmp/nums")" + + ar_msg="LANES(archive@$WS): Amendment 19(d) — $ar_n RETIRED row(s) of $ar_repo moved to $LANES_ARCH_PATH: $(tr '\n' ' ' < "$ar_tmp/names")" + rm -rf -- "$ar_tmp" + commit_push "$ar_msg" "$LANES_PATH" "$LANES_ARCH_PATH" + ar_crc=$? + release_lock + return "$ar_crc" +} + +# ============================================================================ +# THE SEAM: A MANAGED-OWNED LANE IS NOT THIS TOOLING'S +# ============================================================================ +# +# Brett Heap's ruling of 2026-10-04, verbatim: "managed ledger owns enrolled +# lanes; #97 owns legacy — rework both". A lane the managed ledger has enrolled +# carries a MANAGED-OWNER MARKER in its register row's state cell, written by +# that ledger's own writer; every lane without one is a LEGACY lane, and the +# legacy lane tooling in this file — the lifecycle below, the object log's +# lane-kind lines, the sweep, the row writers — answers for legacy lanes only. +# +# THE RULE, which is the ported reader's own ("no malformed marker may be +# downgraded to absence"): +# * a VALID marker is a managed lane: every legacy write refuses it with 2, +# names the owner, and writes nothing; +# * managed-owner vocabulary that does NOT parse — a malformed marker, a row +# that is not seven columns, an empty owner — or a register that could not +# be read is UNKNOWN: refused with 1, and nothing is written; +# * no vocabulary at all is a legacy lane, and everything here runs exactly +# as it did. +# +# PROVENANCE. The block between the two markers below is +# `3c26041:lanes-edit.sh:776-898` — the projection reader of branch +# `001-separate-swap-ctx-handoff` (its T019) — ported VERBATIM: not one byte of +# it differs, so that when that branch's T024 lands, the merge of the two is +# "keep either", and this file's `lane_is_managed_owned` becomes that branch's +# `managed_legacy_check`. The proof is an empty diff: +# diff <(git show 3c26041:lanes-edit.sh | sed -n 776,898p) \ +# <(sed -n '/^# --- BEGIN ported from 3c26041/,/^# --- END ported from 3c26041/p' lanes-edit.sh | sed '1d;$d') +# Its four dependencies — `row_split_state_cell`, `rstrip_spaces`, `lc` and +# `row_of_lane` — are byte-identical in this file and in that one. +# --- BEGIN ported from 3c26041:lanes-edit.sh:776-898 --- +MANAGED_PROJECTION_MODE="" +MANAGED_PROJECTION_DAEMON="" +MANAGED_PROJECTION_GENERATION="" +MANAGED_PROJECTION_LANE="" + +managed_projection_component_valid() { # <path-safe component> + local mpc_value="${1-}" + case "$mpc_value" in + '' | .* | -* | *[!A-Za-z0-9._-]*) return 1 ;; + esac + [ "${#mpc_value}" -le 128 ] || return 1 + return 0 +} + +managed_projection_generation_valid() { # <positive decimal integer> + local mpg_value="${1-}" + case "$mpg_value" in + '' | *[!0-9]* | 0) return 1 ;; + esac + while [ "${mpg_value#0}" != "$mpg_value" ]; do + mpg_value="${mpg_value#0}" + done + [ -n "$mpg_value" ] || return 1 + MANAGED_PROJECTION_GENERATION="$mpg_value" + return 0 +} + +managed_projection_hint() { # <row>; 0 means a managed marker is visible + printf '%s\n' "${1-}" | awk ' + { s = tolower($0) + if (s ~ /managed[ _-](owner|binding)/ || + s ~ /mode[ _-]*=[ _-]*managed/ || + s ~ /managed[ _-]*:/) found = 1 + } + END { exit(found ? 0 : 8) }' +} + +managed_projection_parse_row() { # <row>; 0 valid marker, 8 absent, other unknown + local mppr_row="${1-}" mppr_split mppr_cell mppr_text mppr_line mppr_fields mppr_hint mppr_row_lane + MANAGED_PROJECTION_MODE="" + MANAGED_PROJECTION_DAEMON="" + MANAGED_PROJECTION_GENERATION="" + MANAGED_PROJECTION_LANE="" + mppr_hint=8 + if managed_projection_hint "$mppr_row"; then + mppr_hint=0 + else + mppr_hint=$? + fi + mppr_split=0 + row_split_state_cell "$mppr_row" || mppr_split=$? + case "$mppr_split" in + 0) : ;; + 2) [ "$mppr_hint" = 0 ] && return 1; return 8 ;; + *) [ "$mppr_hint" = 0 ] && return 1; return 8 ;; + esac + # A row without any managed-owner vocabulary is an ordinary legacy row and + # is the confirmed-absent projection result. Once that vocabulary appears, + # however, every table/state delimiter and every owner field is evidence that + # must parse; no malformed marker may be downgraded to absence. The split + # above intentionally runs first so projection writers retain RSS_HEAD and + # RSS_TAIL when replacing an ordinary row. + [ "$mppr_hint" = 0 ] || { [ "$mppr_hint" = 8 ] && return 8; return 1; } + mppr_cell="$(rstrip_spaces "$RSS_CELL")" + case "$mppr_cell" in + 'MANAGED OWNER · '* | 'managed owner · '*) + # Keep the historical shorthand, but never treat an empty owner token + # as a valid durable binding. + mppr_text="${mppr_cell#* · }" + case "$mppr_text" in + '' | *[!A-Za-z0-9._-]*) return 1 ;; + esac + return 0 + ;; + *' · '*) mppr_text="${mppr_cell#* · }" ;; + *) return 1 ;; + esac + case "$mppr_text" in + *' · '*) mppr_line="${mppr_text#* · }" ;; + *) + return 1 ;; + esac + case "$mppr_line" in + managed-owner\ *) : ;; + *) return 1 ;; + esac + mppr_fields="$(printf '%s\n' "$mppr_line" | sed -n \ + 's/^managed-owner mode=\([^[:space:]]*\) daemon=\([^[:space:]]*\) generation=\([^[:space:]]*\) bound-lane=\([^[:space:]]*\)$/\1|\2|\3|\4/p')" + [ -n "$mppr_fields" ] || return 1 + IFS='|' read -r MANAGED_PROJECTION_MODE \ + MANAGED_PROJECTION_DAEMON MANAGED_PROJECTION_GENERATION \ + MANAGED_PROJECTION_LANE <<EOF +$mppr_fields +EOF + [ "$MANAGED_PROJECTION_MODE" = managed ] || return 1 + managed_projection_component_valid "$MANAGED_PROJECTION_DAEMON" || return 1 + managed_projection_generation_valid "$MANAGED_PROJECTION_GENERATION" || return 1 + managed_projection_component_valid "$MANAGED_PROJECTION_LANE" || return 1 + mppr_row_lane="$(printf '%s\n' "$RSS_HEAD" | awk -F'|' '{ cell=$2; sub(/^[[:space:]]+/, "", cell); sub(/[[:space:]]+$/, "", cell); sub(/^`/, "", cell); sub(/`$/, "", cell); print cell }')" + managed_projection_component_valid "$mppr_row_lane" || return 1 + [ "$(lc "$mppr_row_lane")" = "$(lc "$MANAGED_PROJECTION_LANE")" ] || return 1 + return 0 +} + +managed_projection_read() { # <canonical lane>; 0 marker, 8 absent, other unknown + local mpr_lane="${1-}" mpr_row mpr_rc + if mpr_row="$(row_of_lane "$mpr_lane" 2>/dev/null)"; then + : + else + mpr_rc=$? + return "${mpr_rc:-1}" + fi + # `row_of_lane` is an awk pipeline and therefore exits 0 even when it + # printed no row. An empty result is the published register's confirmed + # absence (8), not an unreadable projection; callers need this distinction + # so a new legacy lane remains compatible when the optional helper is absent. + [ -n "$mpr_row" ] || return 8 + managed_projection_parse_row "$mpr_row" +} + +managed_projection_check() { # <canonical lane>; 0 conflict, 8 absent, other unknown + managed_projection_read "${1-}" +} +# --- END ported from 3c26041:lanes-edit.sh:776-898 --- + +# THE ONE READ EVERY CALLER ASKS: 0 with the owner on stdout, 8 a legacy lane, +# 1 UNKNOWN. It wraps `managed_projection_read` and maps every other status of +# it to 1, and it closes the one gap the ported reader leaves open on purpose: +# `row_of_lane` is an awk pipeline over `register_text`, which answers an EMPTY +# register — not a failure — where the published one could not be rendered, so +# the reader would call every lane legacy. An empty register is not a register +# with no managed lane in it, and it is 1 here (Amendment 7(d)). +# THE OWNER is the marker's `daemon=` for the full form and its token for the +# historical `MANAGED OWNER · <token>` shorthand, read from the same state cell +# the reader has just validated. +lane_is_managed_owned() { # <canonical lane> + limo_lane="${1-}"; limo_rc=0 + [ -n "$limo_lane" ] || return 1 + limo_reg="$(register_text)" + [ -n "$limo_reg" ] || return 1 + managed_projection_read "$limo_lane" || limo_rc=$? + case "$limo_rc" in + 0) + if [ -n "$MANAGED_PROJECTION_DAEMON" ]; then + printf '%s\n' "$MANAGED_PROJECTION_DAEMON" + else + limo_cell="$(rstrip_spaces "$RSS_CELL")" + printf '%s\n' "${limo_cell#* · }" + fi + return 0 ;; + 8) return 8 ;; + *) return 1 ;; + esac +} + +# THE REFUSAL, in one place, so every legacy act says the same two sentences. +# Returns 0 for a legacy lane; never returns otherwise. Called BEFORE the act +# writes anything — before its lock where it takes one, and where the lock is +# already held (the sweeps), before its first write — so a refusal changes +# nothing; `die` releases a held lock on the way out. +# +# AND THIS CHECKOUT'S ROW, NOT ONLY THE PUBLISHED ONE (Copilot round 2 and 3 on +# openRepoTools#97). The read above is the published register's (R19), and every +# legacy row writer rewrites the row in THIS checkout: one ahead of origin, or +# holding an edit `handle_preexisting` is about to capture, can carry managed-owner +# vocabulary the published row does not. Two copies that disagree on ownership +# are UNKNOWN, never legacy (Amendment 7(d)). A checkout with no register file +# has no row here to rewrite, and the published read has already answered. +managed_seam_refuse() { # <canonical lane> <the act> + msr_lane="${1-}"; msr_act="${2-this act}"; msr_rc=0; msr_owner="" + msr_owner="$(lane_is_managed_owned "$msr_lane")" || msr_rc=$? + case "$msr_rc" in + 0) die "lane $msr_lane is owned by the managed ledger (owner ${msr_owner:-unnamed}, from the managed-owner marker in its register row), and $msr_act is a legacy lane act: Brett Heap's ruling of 2026-10-04 — \"managed ledger owns enrolled lanes; #97 owns legacy\". Nothing was written. Act on this lane through the managed ledger." 2 ;; + 8) : ;; + *) die "whether the managed ledger owns lane $msr_lane is UNKNOWN: its register row carries managed-owner vocabulary that does not parse as a marker, or the register could not be read — and an ownership nobody could establish is never read as 'legacy' (Amendment 7(d)). $msr_act was refused and nothing was written. Read it: lanes-edit.sh managed-projection $msr_lane" 1 ;; + esac + managed_local_hint "$msr_lane" || + die "whether the managed ledger owns lane $msr_lane is UNKNOWN: its row in this checkout's register file, $LANES_FILE, carries managed-owner vocabulary (or could not be read) where the published register's, origin/$LANES_BRANCH, does not, and a legacy act rewrites THAT file's row — an ownership the two copies disagree on is never read as 'legacy' (Amendment 7(d)). $msr_act was refused and nothing was written. $(managed_local_remedy)" 1 + return 0 +} + +# THIS CHECKOUT'S HALF OF THAT READ, which `managed-projection` asks too +# (opensoft/openRepoTools#157 item 4a): the gates of `lane-start`, `lane-handoff` +# and `lane-end` ask that read, and a gate that passed a marker only this copy +# carries let a launch go on until a later writer refused. 0 where this +# checkout's row carries no managed-owner vocabulary, or there is no register +# file here; 1 where it carries some or could not be read. VOCABULARY ONLY, and +# not the row's shape (item 4d): a row with none cannot be a marker, so it is +# legacy in either copy, and the writer that rewrites it refuses a shape it +# cannot split on its own. +managed_local_hint() { # <canonical lane> + mlh_hint=8; mlh_loc="" + [ -f "$LANES_FILE" ] || return 0 + mlh_loc="$(row_of_lane_local "${1-}" 2>/dev/null)" || mlh_hint=1 + if [ "$mlh_hint" = 8 ] && [ -n "$mlh_loc" ]; then + mlh_hint=0; managed_projection_hint "$mlh_loc" || mlh_hint=$? + fi + [ "$mlh_hint" = 8 ] +} + +# WHAT A PERSON DOES ABOUT IT, in the words both refusals above print. The file +# named is the one `managed_local_hint` READ, which is not always in +# `$LANES_REPO`: a caller that points `LANES_REPO` at a runtime clone and sets +# no `LANES_WORKSPACE_ROOT` reads the published register in that clone and this +# file in workspace.yaml's tree. And the two copies can disagree in either +# direction: a change here that origin has not got, or a change on origin +# (the ledger removing its marker) that this checkout has not pulled. +managed_local_remedy() { + printf 'That file is AHEAD of origin — the row changed there and not pushed, or not committed at all: publish that change or undo it — or BEHIND it — origin has dropped the vocabulary since that checkout last moved: fast-forward it. Which one: git -C %s fetch && git -C %s status --short --branch -- %s' \ + "${LANES_FILE%/*}" "${LANES_FILE%/*}" "${LANES_FILE##*/}" +} + +# ============================================================================ +# THE CRASH-CONSISTENT LANE LIFECYCLE AND THE WORKTREE INVENTORY +# (openspec/changes/add-crash-consistent-lane-worktree-recovery, +# opensoft/openRepoTools#91) +# ============================================================================ +# +# **A LANE IS `RUNNING`, `SWAPPING`, `SWAPPED` OR `CLOSED`, and which of those +# it is, with no live holder, is what says where it stopped.** A session can +# run out of tokens BEFORE the handoff, AFTER it began and before it finished, +# or after it finished — and until this section those three left the same +# evidence: a lane whose last lane-kind line was a `STARTED`/`RESUMED` (which +# is also what a lane that is running looks like) or a `PAUSED` (which is also +# what a clean swap looks like). The two crash kinds had no word. +# +# WHAT IS NEW AND WHAT IS NOT. Nothing about the append-only log changes: its +# five STATE verbs are Amendment 7's and this section adds no lane-kind verb at +# all (Amendment 18(g)'s `HANDOFF-REQUESTED` is the sixth lane-kind verb, and it +# changes no state), so `swapped_candidates`, `lane_row_facts`, +# `lane_payload_field`, `lane-last`, `who` and `lane-end` read exactly what they +# read before. What is added is a +# SNAPSHOT beside that history — one small file per lane, replaced atomically +# under this file's own mutex — carrying the state word, a monotonic +# GENERATION, the OPERATION ID of the transition in flight, and the owner. The +# log stays the provenance; the snapshot is the cheap current-state read that +# an append-only file cannot give a compare-and-swap. +# +# WHERE IT LIVES, AND WHY IT IS NOT IN THE REGISTER AND NOT IN A WORKTREE. +# * NOT IN THE REGISTER. `lanes/LANES.md` is one file shared by every lane on +# every workstation and every write of it is a commit, a pull --rebase and +# a push (Amendment 5). A transition is taken three times per handoff and +# must be able to happen with no network at all. +# * NOT INSIDE A GIT WORKTREE. Orchestration metadata written into a checkout +# dirties it, is committed by accident, and disappears with the very +# directory whose loss it is meant to explain. +# * SO: a LOCAL control root beside the lane's own checkouts, derived in this +# order and never from the caller's current directory — +# 1. `$LANES_LANE_STATE_ROOT/<lane>`, the explicit override and the +# suite's seam; +# 2. `<parent of the lane's recorded `dir`>/.lane-state/<lane>` — the +# same parent the lane's own `.lane-worktrees/<lane>` root sits in, +# and `dir` is Amendment 11(c)'s recorded field, not a guess; +# 3. `$PROJECTS_ROOT/.lane-state/<lane>`, for a lane whose record names +# no directory yet. +# No answer is 8, "this lane has no control root", exactly as `lane-dir` +# answers 8 for a lane that has not started under Amendment 11 — and the +# pre-cutover lane is the ordinary case, not a failure (Amendment 7(i)). +# +# IT IS WRITTEN WHERE `R-A11-14` STOPS THE REGISTER AND THE OBJECT LOG. That +# rule refuses a record FILED UNDER A WORKSTATION where no workstation is +# configured, because such a record is unfindable by every restart of every +# workstation. The snapshot is filed under nothing: it is local to the machine +# that wrote it, it is never committed and it never leaves. So a container with +# no `$LANES_WORKSTATION` still keeps a lifecycle it can recover itself from, +# and these two writers are deliberately NOT in the dispatcher's workstation +# guard above. +# +# THE FENCE. Every transition carries `generation` (monotonic) and +# `operation` (unique to one handoff). `set-lane-state --expect` names the +# state, and optionally the generation and the operation, the caller believes +# it is moving from; the write happens only where all three still match, and +# otherwise NOTHING is written and the exit is 7 — the estate's "another act +# got there first", which is what `claim` already spends it on. That is the +# whole of what stops a `/handoff` that stalled for an hour from marking a lane +# `SWAPPED` after somebody has recovered and resumed it. +# +# WHO WRITES `RUNNING`. The confirming act, and never the SessionStart hook: +# `session-start` NEVER WRITES, never touches the network and ALWAYS EXITS 0 +# (Amendment 8, R-A8-1), which is what makes it safe in front of every session +# on the workstation. The act that actually proves lane, transcript, agent, +# directory and binding is `lane-start` (with or without `--no-launch`), and +# the proof it leaves is its `STARTED`/`RESUMED` line — so the snapshot follows +# THAT line, in `write_event`, from any caller. `ENDED`/`RETIRED` become +# `CLOSED` by the same rule. A `PAUSED` moves nothing: the two-phase transition +# around it belongs to `lane-handoff`, which takes `SWAPPING` before it polls +# anything and `SWAPPED` only after every mandatory write has landed. + +LANE_STATE_SCHEMA=1 + +# The four words, and nothing else is one. +lane_state_word_ok() { # <word> + case "${1-}" in RUNNING|SWAPPING|SWAPPED|CLOSED) return 0 ;; esac + return 1 +} + +# THE CONTROL ROOT — the three rungs above, in order. 0 with the path (which +# need not exist yet), 8 where no rung answers. +lane_control_root() { # <lane> [<a payload that may carry `dir`>] + lcr_lane="${1-}"; lcr_pay="${2-}"; lcr_dir=""; lcr_par="" + [ -n "$lcr_lane" ] || return 8 + if [ -n "${LANES_LANE_STATE_ROOT:-}" ]; then + printf '%s/%s\n' "${LANES_LANE_STATE_ROOT%/}" "$lcr_lane" + return 0 + fi + [ -n "$lcr_pay" ] && lcr_dir="$(payload_subfield "$lcr_pay" dir)" + if [ -z "$lcr_dir" ]; then + lcr_dir="$(lane_payload_field "$lcr_lane" dir 2>/dev/null || :)" + fi + case "$lcr_dir" in + /*) lcr_par="${lcr_dir%/*}" ;; + *) lcr_par="" ;; + esac + if [ -n "$lcr_par" ] && [ -d "$lcr_par" ]; then + printf '%s/.lane-state/%s\n' "$lcr_par" "$lcr_lane" + return 0 + fi + if [ -n "${PROJECTS_ROOT:-}" ] && [ -d "$PROJECTS_ROOT" ]; then + printf '%s/.lane-state/%s\n' "${PROJECTS_ROOT%/}" "$lcr_lane" + return 0 + fi + return 8 +} + +# ONE FIELD OUT OF ONE OF THESE FILES. They are flat `key: value` lines and +# nothing else — no nesting, no lists — so one `awk` reads every one of them +# and a malformed file answers empty rather than half a value. +lane_sidecar_field() { # <file> <key> + [ -r "${1-}" ] || return 1 + awk -v k="${2-}" ' + BEGIN { k = k ": " } + substr($0, 1, length(k)) == k { + v = substr($0, length(k) + 1) + sub(/^[ \t]+/, "", v); sub(/[ \t]+$/, "", v) + print v; exit }' "$1" +} + +# THE SCHEMA EVERY WRITER ASKS ABOUT BEFORE IT REPLACES ANYTHING (Copilot round +# 5 on openRepoTools#97). `lane_state_read` fails closed for a snapshot version +# it does not know — but a READER failing closed protects nobody if the WRITER +# beside it reads the raw fields and renames a file of its own over the top: an +# older helper meeting a `schema: 999` snapshot would then destroy a record it +# could not even read, and no later reader can undo that. So every writer of a +# sidecar in this section asks this first. +# +# ABSENT IS FINE — the first snapshot of a lane destroys nothing — and the +# CURRENT version is fine. Everything else, INCLUDING A FILE THAT EXISTS AND +# CANNOT BE READ, is refused: a schema nobody could read is not a schema this +# helper knows (R22, Amendment 7(d)). +# AND A DANGLING SYMLINK IS NOT ABSENT (Copilot on 64dfd97, PR #97): `-e` is +# false for one, so this guard used to wave every writer through to rename its +# own file over a record `lane_state_read` itself calls present-and-unreadable. +# `[ -L ]` beside `[ -e ]`, exactly as the reader asks it. +# +# AND THE RECORD, NOT ONLY ITS VERSION LINE (opensoft/openRepoTools#115). This +# asked one question, so a file whose first line is `schema: 1` and which holds +# nothing else passed it — a record of the current version that is not valid at +# that version — and both sides took it for one: the readers emitted empty +# fields for it and the writers renamed their own file over it, the act this +# guard exists to refuse. A file cut short is not exotic: `lane_sidecar_put`'s +# `cat` can be, and the rename makes a COMPLETE file atomic, not an incomplete +# one impossible. So a record of the current schema passes only when it is +# WHOLE: every key its writer writes is there and is not empty, the keys a +# reader decides with have their shapes, and a tree record claims the id its +# file name gives it. Both writers have written exactly these keys since #97 +# landed (`lane_state_put`, `lane_tree_put`), so no record a released helper +# wrote fails it. A malformed record of the KNOWN schema takes the refusal an +# unknown schema takes: every writer refuses it (1), the snapshot's reader +# answers 10, and the inventory's names it `<malformed>`. +# +# WHICH KIND OF RECORD IT IS COMES FROM WHERE IT IS FILED — `<root>/lane-state.yaml` +# for the snapshot, `<root>/trees/<id>.yaml` for a tree — and the second argument +# names that place for a file that is not there yet (`lane_sidecar_put`'s +# temporary file). THE SNAPSHOT'S ARM COMES FIRST (review r1 of #252): a `case` +# pattern's `*` matches `/`, so `*/trees/*.yaml` also matches +# `/x/trees/state/<lane>/lane-state.yaml`, and under a control root with any +# directory named `trees` above it every snapshot was asked a tree's keys, +# refused, and never written. A tree's file is never named `lane-state.yaml`: +# its id is `c<cksum>-…` (`tree_id_for`). `LSS_WHY` says why a record failed, in words a caller puts +# in its own message; it is set in the caller's shell, so call this directly +# and never inside `$( )`. The awk reads the id through the ENVIRONMENT, because +# `awk -v` processes escapes in a value. +lane_sidecar_schema_ok() { # <file> [<the path it is filed as>] + LSS_WHY="" + [ -e "${1-}" ] || [ -L "${1-}" ] || return 0 + if [ ! -r "$1" ]; then + LSS_WHY="it is there and could not be read" + return 1 + fi + lss_v="$(lane_sidecar_field "$1" schema 2>/dev/null || :)" + if [ "$lss_v" != "$LANE_STATE_SCHEMA" ]; then + LSS_WHY="it is of a schema this helper does not write (it writes schema $LANE_STATE_SCHEMA)" + return 1 + fi + lss_as="${2:-$1}"; lss_kind=""; lss_id="" + case "$lss_as" in + */lane-state.yaml) lss_kind=snapshot ;; + */trees/*.yaml) lss_kind=tree; lss_id="${lss_as##*/}"; lss_id="${lss_id%.yaml}" ;; + esac + [ -n "$lss_kind" ] || return 0 + lss_rc=0 + LSS_WHY="$(LSS_KIND="$lss_kind" LSS_ID="$lss_id" awk ' + { i = index($0, ": ") + if (i > 1) { k = substr($0, 1, i - 1); v = substr($0, i + 2) + sub(/^[ \t]+/, "", v); sub(/[ \t]+$/, "", v) + if (!(k in val)) val[k] = v } } + END { + kind = ENVIRON["LSS_KIND"] + if (kind == "snapshot") + n = split("lane state generation operation owner agent profile workstation kind updated", req, " ") + else + n = split("lane tree path checkout branch head upstream dirty unpushed writer generation operation observed", req, " ") + miss = "" + for (j = 1; j <= n; j++) + if (!(req[j] in val) || val[req[j]] == "") miss = miss (miss == "" ? "" : ", ") req[j] + if (miss != "") { print "it is not a whole record: it carries no " miss; exit } + if (val["generation"] !~ /^[0-9]+$/) { print "its generation \"" val["generation"] "\" is not a number"; exit } + if (kind == "snapshot") { + if (val["state"] !~ /^(RUNNING|SWAPPING|SWAPPED|CLOSED)$/) { + print "its state \"" val["state"] "\" is none of RUNNING, SWAPPING, SWAPPED and CLOSED"; exit } + } else { + if (val["tree"] != ENVIRON["LSS_ID"]) { + print "it claims to be tree " val["tree"] " and is filed as " ENVIRON["LSS_ID"]; exit } + if (substr(val["path"], 1, 1) != "/") { print "its path \"" val["path"] "\" is not absolute"; exit } + if (val["dirty"] !~ /^[0-9]+$/) { print "its dirty count \"" val["dirty"] "\" is not a number"; exit } + if (val["unpushed"] !~ /^([0-9]+|unknown)$/) { + print "its unpushed count \"" val["unpushed"] "\" is neither a number nor unknown"; exit } + } + }' "$1" 2>/dev/null)" || lss_rc=$? + if [ "$lss_rc" != 0 ]; then + LSS_WHY="it could not be read through (awk exited $lss_rc)" + return 1 + fi + [ -z "$LSS_WHY" ] +} + +# THE SNAPSHOT AS IT STOOD, IN ONE STRING — the pre-image a fenced write +# compares against. `<state>/<generation>/<operation>`, and `none/0/none` for a +# lane that has no snapshot at all, so that "there was nothing here" and "there +# was something here" are two different answers rather than one empty string. +lane_state_fingerprint() { # <file> + [ -e "${1-}" ] || { printf 'none/0/none\n'; return 0; } + printf '%s/%s/%s\n' \ + "$(lane_sidecar_field "$1" state 2>/dev/null || :)" \ + "$(lane_sidecar_field "$1" generation 2>/dev/null || :)" \ + "$(lane_sidecar_field "$1" operation 2>/dev/null || :)" +} + +# A VALUE IS ONE LINE OF `key: value`, so a newline or a leading space in one +# would make the file unreadable by the reader above. Both are flattened here +# rather than refused, because a value this can spoil is a branch name or a +# path and losing the WHOLE record over one is the worse trade. +lane_sidecar_value() { # <value> + lsv="${1-}" + lsv="${lsv//$'\r'/ }" + lsv="${lsv//$'\n'/ }" + printf '%s' "$lsv" +} + +# THE ATOMIC REPLACE. Written beside the target and renamed over it, so a +# reader never sees half a snapshot and a full disk leaves the old one intact. +# +# AND ONLY A WHOLE RECORD IS RENAMED INTO PLACE (opensoft/openRepoTools#115). +# The rename makes a complete file atomic and nothing more: a `cat` whose input +# was cut short — the writer killed between two of its lines — still exits 0, +# and the half record it wrote was renamed over the whole one. The temporary +# file is asked the question every reader and writer of the record asks, under +# the name it is about to take, and a record that fails it is removed instead. +lane_sidecar_put() { # <file> ; the whole body on stdin + lsp_f="${1-}"; lsp_d="${lsp_f%/*}" + [ -n "$lsp_f" ] || return 1 + mkdir -p -- "$lsp_d" 2>/dev/null || return 1 + lsp_t="$lsp_f.tmp.$$" + cat > "$lsp_t" 2>/dev/null || { rm -f -- "$lsp_t" 2>/dev/null; return 1; } + if ! lane_sidecar_schema_ok "$lsp_t" "$lsp_f"; then + rm -f -- "$lsp_t" 2>/dev/null + note "the record for $lsp_f was NOT written: what was about to replace it is not a whole record ($LSS_WHY), and a half record is never renamed over a whole one." + return 1 + fi + mv -- "$lsp_t" "$lsp_f" 2>/dev/null || { rm -f -- "$lsp_t" 2>/dev/null; return 1; } + return 0 +} + +# AN OPERATION ID: unique to one transition, and shaped like the manifest key +# every other sub-field of this estate is — letters, digits, `.`, `_`, `-` — so +# that it can be carried in a payload, a filename and a commit subject without +# a quoting rule of its own. There is no `uuidgen` on every workstation this +# runs on, and a timestamp with the pid and two `$RANDOM`s behind it is unique +# among the handfuls of transitions one lane takes in a day. +lane_op_id() { + printf 'op-%s-%s-%s%s\n' "$(date -u +%Y%m%dT%H%M%SZ)" "$$" "$RANDOM" "$RANDOM" +} + +# THE SNAPSHOT, READ. `<key><TAB><value>` lines, which is what every caller +# here parses with one `awk`. 0 with the fields, 8 where the lane has no +# snapshot at all (the pre-cutover lane, and not a failure), 10 where a snapshot +# IS there and could not be read — or is of this schema and not a whole record +# (#115) — 1 where the control root could not be derived. +# +# THE 10 IS THE POINT OF THIS ROUND (Copilot round 6 on openRepoTools#97, where +# it was 9 — main's #61 has since spent 9 on `claim`, so this one moved). A bare +# `[ -r ] || return 8` answered *this lane has no snapshot* for a file that +# exists and cannot be opened, and `lane_reconcile` maps every non-zero read to +# `NONE` — so a permission or an I/O error came out of the report as `no-state`, +# the verdict that tells a launcher this lane was never migrated and there is +# nothing to recover. That is fail-OPEN on a crash pronouncement, which is the +# whole class this capability exists to close: a read that failed is never an +# answer (R22, Amendment 7(d)), and the two cases are told apart here so that +# every caller above can tell them apart too. +# +# `[ -L ]` BESIDE `[ -e ]`, because a DANGLING SYMLINK is `-e` false: the name +# is there and the bytes are not, which is exactly *present and unreadable* and +# would otherwise fall through to the 8. +# +# THE PAYLOAD IS `lane_control_root`'s, AND OPTIONAL: a caller that already +# holds the lane's `dir` hands it here, and the lane's log is not read again +# to find it (review r2 of #289, SHOULD-A). A caller that names the lane +# alone finds the root exactly as before. +lane_state_read() { # <lane> [<a payload that may carry `dir`>] + lsr_lane="${1-}"; lsr_root=""; lsr_rc=0 + lsr_root="$(lane_control_root "$lsr_lane" "${2-}")" || lsr_rc=$? + [ "$lsr_rc" = 0 ] || return 1 + lsr_f="$lsr_root/lane-state.yaml" + if [ ! -r "$lsr_f" ]; then + if [ -e "$lsr_f" ] || [ -L "$lsr_f" ]; then return 10; fi + return 8 + fi + # AN UNKNOWN SCHEMA FAILS CLOSED (design decision: "conservative fail-closed + # behaviour for unknown versions"), through the ONE test every writer of these + # files takes too. A newer tooling's snapshot read by an older reader must not + # be reported as a lane in a state this reader knows — and must not be + # replaced by one either, which is what `lane_sidecar_schema_ok` is for. + # A RECORD OF THIS SCHEMA THAT IS NOT A WHOLE ONE is 10 (#115): it is there + # and nothing can be read out of it as a snapshot, which is what 10 says. Its + # fields used to come out EMPTY, and an empty state reached the verdict table + # as a word nobody wrote. + if ! lane_sidecar_schema_ok "$lsr_f"; then + lsr_schema="$(lane_sidecar_field "$lsr_f" schema 2>/dev/null || :)" + [ "$lsr_schema" != "$LANE_STATE_SCHEMA" ] || return 10 + printf 'state\tUNKNOWN-SCHEMA\n'; printf 'schema\t%s\n' "${lsr_schema:-<none>}" + printf 'file\t%s\n' "$lsr_f"; return 0 + fi + for lsr_k in state generation operation owner agent profile workstation kind updated lane; do + printf '%s\t%s\n' "$lsr_k" "$(lane_sidecar_field "$lsr_f" "$lsr_k")" + done + printf 'file\t%s\n' "$lsr_f" + return 0 +} + +# One field of it, for the callers that want exactly one. +lane_state_of() { # <lane> <key> + lso_out=""; lso_rc=0 + lso_out="$(lane_state_read "${1-}")" || lso_rc=$? + [ "$lso_rc" = 0 ] || return "$lso_rc" + printf '%s\n' "$lso_out" | awk -F'\t' -v k="${2-}" '$1 == k { print $2; exit }' +} + +# THE SNAPSHOT, WRITTEN — the ONE writer, and every caller reaches it through +# `set-lane-state`. `lsw_*` are its fields; an empty one is written as `none`, +# which is an ANSWER and not a gap, on the same argument Amendment 17(b) gives +# its `transcript` sub-field. +lane_state_put() { # <root> <lane> <state> <gen> <op> <owner> <agent> <profile> <ws> <kind> + lsw_root="$1"; lsw_lane="$2"; lsw_state="$3"; lsw_gen="$4"; lsw_op="$5" + lsw_owner="$6"; lsw_agent="$7"; lsw_prof="$8"; lsw_ws="$9"; shift 9; lsw_kind="${1-}" + { printf 'schema: %s\n' "$LANE_STATE_SCHEMA" + printf 'lane: %s\n' "$(lane_sidecar_value "$lsw_lane")" + printf 'state: %s\n' "$lsw_state" + printf 'generation: %s\n' "$lsw_gen" + printf 'operation: %s\n' "${lsw_op:-none}" + printf 'owner: %s\n' "${lsw_owner:-none}" + printf 'agent: %s\n' "${lsw_agent:-none}" + printf 'profile: %s\n' "${lsw_prof:-none}" + printf 'workstation: %s\n' "${lsw_ws:-none}" + printf 'kind: %s\n' "${lsw_kind:-none}" + printf 'updated: %s\n' "$(utc_now)" + } | lane_sidecar_put "$lsw_root/lane-state.yaml" +} + +# THE SNAPSHOT AS IT STOOD BEFORE THE LINE WAS WRITTEN. `write_event` takes this +# BEFORE it appends anything and hands it to the follow-up below, which is the +# only way that follow-up can tell *I am the newest act on this lane* from *I am +# a delayed act whose lane has moved on since*. A lane with no control root +# answers the same `none/0/none` a lane with no snapshot does: nothing to +# compare, and nothing to overwrite either. +lane_state_preimage() { # <lane> <payload> + lsp_root=""; lsp_prc=0 + lsp_root="$(lane_control_root "${1-}" "${2-}")" || lsp_prc=$? + [ "$lsp_prc" = 0 ] || { printf 'none/0/none\n'; return 0; } + lane_state_fingerprint "$lsp_root/lane-state.yaml" +} + +# THE LINE THAT WAS WRITTEN IS WHAT MOVES THE SNAPSHOT, and this is where the +# two are kept from disagreeing: it is called by `write_event`, from any +# caller, after the log line has landed. It NEVER fails the event: a lane with +# no control root is silent, because a lane that has not started under Amendment +# 11 has no directory to derive one from and that is the ordinary pre-cutover +# case. +# +# IT IS SERIALIZED AND IT IS FENCED (Copilot round 5 on openRepoTools#97). What +# a confirmed `STARTED`/`RESUMED` is entitled to overwrite is the state THIS +# WRITE SAW — advancing the generation over a `SWAPPING` it superseded is the +# whole point of writing it — and what it is never entitled to overwrite is a +# state that arrived AFTER it. The two are the same act read at different +# moments, so they are told apart the only way they can be: the snapshot is read +# under the same mutex `set-lane-state` takes, and compared with the pre-image +# `write_event` took before this event's own line landed. Unequal means another +# act moved the lane while this one was being written — a recovery, a handoff, +# an `ENDED` from elsewhere — and a delayed `RUNNING` or `CLOSED` written over +# it would be exactly the overwrite the generation exists to refuse. Nothing is +# written then, and the lane is NAMED so a person can read it. +# +# THE MUTEX IS TAKEN WITHOUT DYING FOR IT. `write_event` has already released it +# and its line is already committed: a `die` here would abort a caller whose +# work is on disk, so a mutex nobody could take within 20s costs the snapshot +# and says so, never the event. +# +# AND IT WRITES ONLY FOR A LEGACY LANE, ON EVIDENCE IT WAS HANDED (ruling +# 2026-10-04, design decision 21). Three things must all hold before the +# snapshot moves — `RUNNING` for a `STARTED`/`RESUMED`, `CLOSED` for an +# `ENDED`/`RETIRED`: +# * the verb is one of those four; +# * the caller's seam read said 8 — this lane carries no managed-owner +# marker and no vocabulary of one — because a managed lane's lifecycle is +# the managed ledger's and an unknown one is nobody's to write; +# * a pre-image was taken before the line was written and the snapshot still +# matches it under the mutex. +# A missing verdict or a missing pre-image is NOT a pass: it writes nothing, +# because a caller that did not ask is not a caller that was told "legacy". +lane_state_follow() { # <lane> <verb> <payload> <uuid> <pre-image> <seam verdict> + lsf_lane="${1-}"; lsf_verb="${2-}"; lsf_pay="${3-}"; lsf_uuid="${4-}"; lsf_pre="${5-}" + lsf_seam="${6-}" + lsf_new="" + case "$lsf_verb" in + STARTED|RESUMED) lsf_new=RUNNING ;; + ENDED|RETIRED) lsf_new=CLOSED ;; + *) return 0 ;; + esac + [ "$lsf_seam" = 8 ] || return 0 + [ -n "$lsf_pre" ] || return 0 + lsf_root=""; lsf_rc=0 + lsf_root="$(lane_control_root "$lsf_lane" "$lsf_pay")" || lsf_rc=$? + [ "$lsf_rc" = 0 ] || return 0 + lsf_f="$lsf_root/lane-state.yaml" + lsf_own=0 + if [ "$LOCK_HELD" != 1 ]; then + if lock_try 20; then + lsf_own=1 + else + note "the lane lifecycle snapshot for $lsf_lane was NOT moved to $lsf_new: $LOCK is held by another lanes-edit run and this follow-up will not wait behind an event that has already landed. The $lsf_verb line itself is written; the snapshot is one act behind until the next transition, and \`lanes-edit.sh lane-reconcile $lsf_lane\` says what it holds." + return 0 + fi + fi + # A SNAPSHOT THIS HELPER CANNOT READ IS ONE IT MUST NOT REPLACE. + if ! lane_sidecar_schema_ok "$lsf_f"; then + if [ "$lsf_own" = 1 ]; then release_lock; fi + note "the lane lifecycle snapshot at $lsf_f is not a record this helper can read ($LSS_WHY), so the $lsf_verb line landed and NOTHING was written over that file: a record this helper cannot read is one it cannot safely replace. Upgrade this workstation's lanes-edit.sh if a newer tooling wrote it, or read the file by hand." + return 0 + fi + lsf_seen="$(lane_state_fingerprint "$lsf_f")" + if [ "$lsf_seen" != "$lsf_pre" ]; then + if [ "$lsf_own" = 1 ]; then release_lock; fi + note "the lane lifecycle moved under this $lsf_verb: lane $lsf_lane read '$lsf_pre' (state/generation/operation) when this write began and reads '$lsf_seen' now, so the snapshot is LEFT AS IT IS and no $lsf_new was written over it. Another act got there first — a recovery, or a second handoff — and a delayed write is precisely what the generation exists to refuse. The $lsf_verb line itself landed: read the lane with \`lanes-edit.sh lane-reconcile $lsf_lane\` before relaunching anything." + return 0 + fi + lsf_gen="$(lane_sidecar_field "$lsf_f" generation 2>/dev/null || :)" + case "$lsf_gen" in ''|*[!0-9]*) lsf_gen=0 ;; esac + lsf_gen=$((lsf_gen + 1)) + lsf_agent="$(payload_subfield "$lsf_pay" agent)" + lsf_prof="$(payload_subfield "$lsf_pay" profile)" + if lane_state_put "$lsf_root" "$lsf_lane" "$lsf_new" "$lsf_gen" "$(lane_op_id)" \ + "$lsf_uuid" "${lsf_agent:-}" "${lsf_prof:-}" "$WS" ""; then + if [ "$lsf_own" = 1 ]; then release_lock; fi + LANES_INDEX_NUDGE_INV=1 # opensoft/openRepoTools#161: the table follows it + return 0 + fi + if [ "$lsf_own" = 1 ]; then release_lock; fi + note "the lane lifecycle snapshot at $lsf_f could NOT be written (the $lsf_verb line itself landed). Crash recovery for lane $lsf_lane is incomplete until it can be: see \`lanes-edit.sh lane-reconcile $lsf_lane\`" + return 0 +} + +# A RENAMED LANE KEEPS ITS LIFECYCLE (Amendment 16, openRepoTools#91). The +# control root is keyed by the lane's NAME — `<parent>/.lane-state/<lane>` on +# every rung — and `rename-lane` moves the row, the log, the handoff and the +# alias table but knew nothing of this directory, so a renamed lane's snapshot +# and inventory were left under a name every reader now resolves away from, and +# its next reconciliation read `no-state`: the one answer a launcher goes past. +# The directory is MOVED, never copied (two snapshots of one lane would be two +# answers), only after the rename's commit returned 0, and never over anything +# already at the new name, which is reported for a person rather than merged. +# The diagnostic files' `lane:` line keeps the old name until the next write; +# their readers do not key on it. Completed restart history is different: its +# strict reader keys on the lane and its launch facts describe the old name. +# Keep that history at the old root and move only the diagnostic files beside +# it. The new canonical lane has no inherited restart operation. +lane_state_rename() { # <the old name's control root> <new lane> + lsn_old="${1-}"; lsn_new="${2-}" + [ -n "$lsn_old" ] && [ -n "$lsn_new" ] || return 0 + [ -e "$lsn_old" ] || [ -L "$lsn_old" ] || return 0 + lsn_to="${lsn_old%/*}/$lsn_new" + [ "$lsn_to" != "$lsn_old" ] || return 0 + # A RENAME BY CASE ALONE is the same directory on a case-insensitive file + # system (macOS's default), where the target "exists" because it is the + # source; it goes through a temporary name so it lands on every file system. + if [ "$(lc "${lsn_old##*/}")" = "$(lc "$lsn_new")" ]; then + lsn_tmp="$lsn_old.rename.$$" + if mv -- "$lsn_old" "$lsn_tmp" 2>/dev/null && mv -- "$lsn_tmp" "$lsn_to" 2>/dev/null; then + LANES_INDEX_NUDGE_INV=1 + note "the lane lifecycle snapshot and inventory moved with the rename: $lsn_old → $lsn_to" + else + note "the lane lifecycle snapshot and inventory could NOT be moved from $lsn_old to $lsn_to (the rename itself has landed). Move it by hand; until then \`lanes-edit.sh lane-reconcile $lsn_new\` reads no snapshot for this lane." + fi + return 0 + fi + if [ -e "$lsn_to" ] || [ -L "$lsn_to" ]; then + note "the lane lifecycle snapshot and inventory were NOT moved: $lsn_old is the old name's and $lsn_to already exists for the new one, and two records of one lane are not merged here. Read both and keep one by hand; the rename itself has landed." + return 0 + fi + if [ -e "$lsn_old/restart-intent.yaml" ] || [ -L "$lsn_old/restart-intent.yaml" ]; then + # rename-lane has already refused unfinished or unreadable restart records + # under the mutex. Preserve the completed record byte for byte, as before + # the diagnostic lifecycle was added; do not reinterpret it as a new lane. + if ! (umask 077; mkdir -- "$lsn_to") 2>/dev/null; then + note "the diagnostic control root could NOT be made at $lsn_to (the rename itself has landed). Completed restart history remains at $lsn_old." + return 0 + fi + # The inventory moves here as well, even when only part of it does, so the + # worktrees table follows it (opensoft/openRepoTools#161). A sync with + # nothing changed writes nothing. + LANES_INDEX_NUDGE_INV=1 + for lsn_part in lane-state.yaml trees; do + if [ -e "$lsn_old/$lsn_part" ] || [ -L "$lsn_old/$lsn_part" ]; then + if ! mv -- "$lsn_old/$lsn_part" "$lsn_to/$lsn_part" 2>/dev/null; then + note "the diagnostic $lsn_part could NOT be moved to $lsn_to (the rename itself has landed). Read both roots before reconciliation. Completed restart history remains at $lsn_old." + return 0 + fi + fi + done + note "the lane lifecycle snapshot and inventory moved to $lsn_to; completed restart history remains at $lsn_old" + return 0 + fi + if mv -- "$lsn_old" "$lsn_to" 2>/dev/null; then + LANES_INDEX_NUDGE_INV=1 + note "the lane lifecycle snapshot and inventory moved with the rename: $lsn_old → $lsn_to" + else + note "the lane lifecycle snapshot and inventory could NOT be moved from $lsn_old to $lsn_to (the rename itself has landed). Move it by hand; until then \`lanes-edit.sh lane-reconcile $lsn_new\` reads no snapshot for this lane." + fi + return 0 +} + +# ------------------------------------------------- the worktree inventory +# +# A TREE ID IS DERIVED FROM ITS PATH AND FROM NOTHING ELSE, so that a branch +# renamed under a writer does not rename the record of the tree it is on: a +# `cksum` of the WHOLE absolute path, then the path with every character outside +# the manifest-key set folded to `-`, which a reader recognises. The fold alone +# is NOT one name per path (Codex on ec9847e, PR #97): `…/a+b` and `…/a-b` fold +# to the same name, and recording the second would replace the first tree's +# sidecar and lose its last observation without a word. The checksum in front +# of EVERY id is what keeps two paths two records; the fold is for a person. +tree_id_for() { # <absolute worktree path> + tif_p="$(printf '%s' "${1-}" | tr -c 'A-Za-z0-9._-' '-' | tr -s '-')" + while [ "${tif_p#-}" != "$tif_p" ]; do tif_p="${tif_p#-}"; done + while [ "${tif_p%-}" != "$tif_p" ]; do tif_p="${tif_p%-}"; done + tif_c="$(printf '%s' "${1-}" | cksum | awk '{print $1}')" + # AND IT CAN NEVER OUTGROW A FILE NAME. A path deep enough to make this + # longer than the 255 bytes most filesystems take is a tree whose sidecar + # could not be created at all — silently, since the failure would be the + # shell's `>` and not this function's. The tail is what a reader recognises, + # so the head is what is dropped. + if [ "${#tif_p}" -gt 180 ]; then + tif_p="$(printf '%s' "$tif_p" | tail -c 180)" + fi + printf 'c%s-%s\n' "$tif_c" "$tif_p" +} + +# ONE TREE'S SIDECAR. Every field is an OBSERVATION and none of them is truth +# about git: `lane-reconcile` recomputes all of them and reports the +# difference, which is the whole of design decision 6. +lane_tree_put() { # <root> <lane> <path> <checkout> <branch> <head> <upstream> <dirty> <unpushed> <writer> <gen> <op> + ltp_root="$1"; ltp_lane="$2"; ltp_path="$3"; ltp_co="$4"; ltp_branch="$5" + ltp_head="$6"; ltp_up="$7"; ltp_dirty="$8"; ltp_unp="$9"; shift 9 + ltp_writer="${1-}"; ltp_gen="${2-}"; ltp_op="${3-}" + ltp_id="$(tree_id_for "$ltp_path")" + [ -n "$ltp_id" ] || return 1 + { printf 'schema: %s\n' "$LANE_STATE_SCHEMA" + printf 'lane: %s\n' "$(lane_sidecar_value "$ltp_lane")" + printf 'tree: %s\n' "$ltp_id" + printf 'path: %s\n' "$(lane_sidecar_value "$ltp_path")" + printf 'checkout: %s\n' "$(lane_sidecar_value "${ltp_co:-unknown}")" + printf 'branch: %s\n' "$(lane_sidecar_value "${ltp_branch:-unknown}")" + printf 'head: %s\n' "$(lane_sidecar_value "${ltp_head:-unknown}")" + printf 'upstream: %s\n' "$(lane_sidecar_value "${ltp_up:-none}")" + printf 'dirty: %s\n' "${ltp_dirty:-0}" + printf 'unpushed: %s\n' "${ltp_unp:-0}" + printf 'writer: %s\n' "${ltp_writer:-none}" + printf 'generation: %s\n' "${ltp_gen:-0}" + printf 'operation: %s\n' "${ltp_op:-none}" + printf 'observed: %s\n' "$(utc_now)" + } | lane_sidecar_put "$ltp_root/trees/$ltp_id.yaml" +} + +# EVERY RECORDED TREE, ONE PER LINE, US-separated: +# <id><US><path><US><branch><US><head><US><upstream><US><dirty><US><unpushed><US><writer><US><observed><US><checkout><US><generation><US><operation><US><schema> +# 0 with rows, 8 with none, 1 where no control root could be derived, 10 where +# the `trees` directory is there and cannot be listed. +# +# THAT 10 IS NOT AN 8 (#157 item 4e). A directory this process may not read or +# search yields an empty glob, which read as a lane that recorded no tree — the +# unreadable sidecar's rule above, one level up. `worktree_rows` already tells +# the two apart before it asks; `lane-trees` and its callers now can too. +# +# THE LAST THREE ARE NEW AND THEY ARE AT THE END (Copilot round 5 on +# openRepoTools#97): the fence the observation was RECORDED UNDER, and the +# schema the sidecar itself carries. A reader written against the ten fields +# that were here first still reads those ten. The fence is here because it was +# written into the file and read by nothing — so a poll filed by an operation a +# recovery has since superseded looked exactly like the current one. +# +# AND A SIDECAR THIS READER DOES NOT KNOW IS SAID, NEVER PARSED. Until this +# round every `*.yaml` under `trees/` was read field by field whatever it +# claimed to be, which is the fail-closed contract `lane_state_read` keeps for +# the snapshot broken for the inventory beside it: a record written by a newer +# tooling would have been reported as an ordinary observation of a tree, in +# fields this reader was guessing at. Its id, its path and its schema are +# printed — the three a person needs to find it — and every other field is +# EMPTY, which `lane_reconcile` reports as `unknown-schema` rather than +# recomputing against. A record of THIS schema that is not a whole one is the +# same row with the schema `<malformed>` (#115), and `lane_reconcile` reports +# it as `malformed-sidecar`. +# +# An optional payload carrying the lane's `dir` is `lane_control_root`'s, as +# `lane_state_read` takes it (review r2 of #289, SHOULD-A). +lane_trees_list() { # <lane> [<a payload that may carry `dir`>] + ltl_root=""; ltl_rc=0; ltl_n=0 + ltl_root="$(lane_control_root "${1-}" "${2-}")" || ltl_rc=$? + [ "$ltl_rc" = 0 ] || return 1 + [ -d "$ltl_root/trees" ] || return 8 + [ -r "$ltl_root/trees" ] && [ -x "$ltl_root/trees" ] || return 10 + for ltl_f in "$ltl_root"/trees/*.yaml; do + [ -e "$ltl_f" ] || [ -L "$ltl_f" ] || continue + ltl_n=$((ltl_n + 1)) + # A SIDECAR THAT IS THERE AND CANNOT BE READ IS NOT AN ABSENT ONE (Codex on + # ec9847e, PR #97). It was skipped, so a permission or an I/O error — or a + # dangling link — made the only record of a tree's location and its dirty + # state vanish, and a lane whose one sidecar it was read as having no + # inventory at all. It is a row of its own, named by its file and carrying + # no field, which `lane_reconcile` reports as `unreadable-sidecar`. + if [ ! -r "$ltl_f" ]; then + ltl_id="${ltl_f##*/}"; ltl_id="${ltl_id%.yaml}" + printf '%s\n' "$ltl_id$US$US$US$US$US$US$US$US$US$US$US$US<unreadable>" + continue + fi + ltl_s="$(lane_sidecar_field "$ltl_f" schema 2>/dev/null || :)" + ltl_id="$(lane_sidecar_field "$ltl_f" tree 2>/dev/null || :)" + ltl_p="$(lane_sidecar_field "$ltl_f" path 2>/dev/null || :)" + if [ "$ltl_s" != "$LANE_STATE_SCHEMA" ]; then + # The file name is the id where the record cannot be trusted to name it: + # a row with no id at all is one `lane_reconcile` skips, and a sidecar + # nobody can account for is the opposite of what this round is about. + [ -n "$ltl_id" ] || { ltl_id="${ltl_f##*/}"; ltl_id="${ltl_id%.yaml}"; } + printf '%s\n' "$ltl_id$US$ltl_p$US$US$US$US$US$US$US$US$US$US$US${ltl_s:-<none>}" + continue + fi + # AND A RECORD OF THIS SCHEMA THAT IS NOT A WHOLE ONE IS SAID, NEVER READ + # (#115). A truncated `schema: 1` file came out as a row of empty fields — + # an EMPTY ID, which `lane_reconcile` skipped outright, and an empty dirty + # and unpushed, which it read as 0 and 0: a vanished tree that held work + # reported `missing`, clean and published. Its id is its FILE NAME, because + # the one it claims is not to be trusted, the path it records is kept so + # the tree is still named once, and every other field is empty under the + # schema `<malformed>`. + if ! lane_sidecar_schema_ok "$ltl_f"; then + ltl_id="${ltl_f##*/}"; ltl_id="${ltl_id%.yaml}" + printf '%s\n' "$ltl_id$US$ltl_p$US$US$US$US$US$US$US$US$US$US$US<malformed>" + continue + fi + printf '%s\n' "$ltl_id$US$ltl_p\ +$US$(lane_sidecar_field "$ltl_f" branch)\ +$US$(lane_sidecar_field "$ltl_f" head)\ +$US$(lane_sidecar_field "$ltl_f" upstream)\ +$US$(lane_sidecar_field "$ltl_f" dirty)\ +$US$(lane_sidecar_field "$ltl_f" unpushed)\ +$US$(lane_sidecar_field "$ltl_f" writer)\ +$US$(lane_sidecar_field "$ltl_f" observed)\ +$US$(lane_sidecar_field "$ltl_f" checkout)\ +$US$(lane_sidecar_field "$ltl_f" generation)\ +$US$(lane_sidecar_field "$ltl_f" operation)\ +$US$ltl_s" + done + [ "$ltl_n" -gt 0 ] || return 8 + return 0 +} + +# ------------------------------------------------ resume-time reconciliation +# +# IT REPORTS AND IT RESETS NOTHING. AGENTS.md rule 1 is the estate's: *"`park` +# CREATES NOTHING and `resume` RESETS NOTHING"*, and never a `git reset`, a +# `git stash`, a `git checkout -f` or a `worktree add --force` to make the next +# run succeed. So this read runs `git status`, `git log @{u}..`, `git rev-parse` +# and `git worktree list --porcelain` and NOTHING ELSE, names the act a person +# takes, and leaves every tree exactly as it found it — a missing tree included, +# whose rebuild is the estate's own `resume <Name>` and is a person's to run. + +# ONE PATH, ONE SPELLING — the physical one, or the path itself where it cannot +# be resolved (a path that is gone still has to be comparable). +# +# THE REPORT READS THREE SOURCES AND THEY DO NOT AGREE ABOUT SPELLING. A sidecar +# holds the path the poll was given, `git worktree list --porcelain` answers with +# the PHYSICAL path, and the on-disk sweep walks the recorded `dir`. Every estate +# with a `projects` symlink reaches its checkouts through it — and on macOS +# `$TMPDIR` and `$HOME` are under `/var`, which IS a symlink to `/private/var`, +# which is how four cases of this section went red on that runner alone at +# `612ba5c` (`expected [dirty], got [dirty unmanaged]`): every tree was reported +# TWICE, once as the tree it is and once as a tree nobody manages. `612ba5c` +# resolved the lane's OWN checkout for exactly this reason and left the trees +# under it unresolved. `cd -P` is the portable resolver, for the reason +# `lane-start`'s `real_of` gives: `readlink -f` is not in the stock macOS +# userland. +lane_real_path() { # <path> + lrp_p="${1-}" + [ -n "$lrp_p" ] || return 0 + lrp_r="$( CDPATH=''; cd -P -- "$lrp_p" 2>/dev/null && pwd -P )" || lrp_r="" + printf '%s\n' "${lrp_r:-$lrp_p}" +} + +# THE LANE'S TWO WORKTREE ROOTS — the same two `lane-handoff` polls, and they +# are here rather than there so the poll and the reconciliation cannot come to +# disagree about where a lane keeps its writers. Where the lane's checkout is an +# ASSEMBLY (T018) both also read its paired root, `<assembly>/worktrees/ +# <feature>/<each leg's path>`, which is two levels deep and per feature, so it +# is read beside these two (`lane_reconcile`, step 4) rather than as a third. +lane_worktree_roots() { # <lane> <the lane's checkout> + lwr_lane="${1-}"; lwr_dir="${2-}" + [ -n "$lwr_dir" ] || return 0 + printf '%s/.claude/worktrees\n' "$lwr_dir" + printf '%s/.lane-worktrees/%s\n' "${lwr_dir%/*}" "$lwr_lane" + return 0 +} + +# What git says about one tree, NOW — +# `<branch><US><head><US><upstream><US><dirty><US><unpushed>` — and it is the ONE +# implementation of that sentence: `lane-reconcile` recomputes with it, +# `set-lane-tree` records through it and `lane-handoff` polls its writers with +# it, over the `lane-tree-now` arm below, so the WRITERS section a person reads +# and the sidecar a recovery reads can never be two different readings. +# +# 0 the five fields +# 1 there is no directory at that path +# 2 the path is there and git does not answer in it at all +# 3 GIT ANSWERED AND ONE OF THE READS FAILED, and NOTHING is printed +# +# THE 3 IS THE WHOLE POINT OF THIS ROUND (Copilot round 5 on openRepoTools#97). +# Every read below used to end in `|| printf 'unknown'`, `|| printf 'none'` or +# an empty count that became `0` — so a repository whose object store is +# unreadable, whose index is locked or whose HEAD is corrupt produced a RECORD +# THAT LOOKED CLEAN AND PUBLISHED, and a later reconciliation comparing against +# it would call a tree holding work `missing` rather than `possible-loss`. A +# read that failed is never an answer (R22, Amendment 7(d)), so it is no longer +# converted into one: the caller is told the observation could not be made. +# +# TWO THINGS ARE ANSWERS AND NOT FAILURES, and they are named rather than +# guessed. A branch with NO COMMIT YET has `unborn` for a head — HEAD is a +# symbolic ref to a branch that does not exist, which is an ordinary state and +# not a broken repository. And a branch with NO UPSTREAM CONFIGURED has `none`, +# which is exactly the distinction the inventory records an upstream for. A +# branch whose upstream IS configured and whose remote-tracking ref is not here +# — the ordinary state of a branch whose remote was deleted after its merge — is +# the third: the configured spelling is recorded, and the count against a ref +# this checkout does not have is `unknown` rather than the `0` that reads as +# *everything is published*. +lane_tree_now() { # <path> + ltn_p="${1-}" + [ -d "$ltn_p" ] || return 1 + git -C "$ltn_p" rev-parse --git-dir >/dev/null 2>&1 || return 2 + ltn_raw=""; ltn_b=""; ltn_h=""; ltn_u=none; ltn_d=""; ltn_n=0 + ltn_s=""; ltn_up=""; ltn_cfg=""; ltn_rem=""; ltn_crc=0 + # THE BRANCH, AND THE UNBORN ONE `rev-parse` CANNOT ANSWER FOR. A branch with + # no commit yet is HEAD as a symbolic ref to a ref that does not exist, which + # `rev-parse --abbrev-ref` refuses exactly as it refuses a corrupt HEAD — + # `symbolic-ref` is what tells the two apart, and it is asked only where the + # first read failed, so an ordinary tree costs one git process as before. + if ltn_raw="$(git -C "$ltn_p" rev-parse --abbrev-ref HEAD 2>/dev/null)" && [ -n "$ltn_raw" ]; then + : + elif ltn_raw="$(git -C "$ltn_p" symbolic-ref --short -q HEAD 2>/dev/null)" && [ -n "$ltn_raw" ]; then + : + else + return 3 + fi + ltn_b="$ltn_raw"; [ "$ltn_b" = HEAD ] && ltn_b=detached + if ltn_h="$(git -C "$ltn_p" rev-parse --verify --quiet HEAD 2>/dev/null)"; then + [ -n "$ltn_h" ] || return 3 + elif git -C "$ltn_p" symbolic-ref -q HEAD >/dev/null 2>&1; then + ltn_h=unborn + else + return 3 + fi + ltn_s="$(git -C "$ltn_p" status --short 2>/dev/null)" || return 3 + ltn_d="$(printf '%s\n' "$ltn_s" | awk 'NF { n = n + 1 } END { print n + 0 }')" + if ltn_up="$(git -C "$ltn_p" rev-parse --abbrev-ref '@{u}' 2>/dev/null)" && [ -n "$ltn_up" ]; then + ltn_u="$ltn_up" + ltn_n="$(git -C "$ltn_p" rev-list --count '@{u}..HEAD' 2>/dev/null)" || return 3 + case "$ltn_n" in ''|*[!0-9]*) return 3 ;; esac + elif [ "$ltn_b" != detached ]; then + # `git config --get` is 0 for found and 1 for NOT FOUND; anything else is + # the read itself failing, and that is a 3 like any other. + ltn_cfg="$(git -C "$ltn_p" config --get "branch.$ltn_raw.merge" 2>/dev/null)" || ltn_crc=$? + case "$ltn_crc" in 0|1) : ;; *) return 3 ;; esac + if [ -n "$ltn_cfg" ]; then + # AND THE REMOTE BESIDE IT IS ASKED THE SAME WAY (opensoft/openRepoTools + # #113 item 3). It ended in `|| :`, so a read that FAILED became an empty + # remote and `${ltn_rem:-.}` then FABRICATED the local upstream + # `./<merge>`, which was filed as an observation. Only a remote that is + # NOT CONFIGURED (1) keeps the `.` this read has always written for it. + ltn_rrc=0 + ltn_rem="$(git -C "$ltn_p" config --get "branch.$ltn_raw.remote" 2>/dev/null)" || ltn_rrc=$? + case "$ltn_rrc" in 0|1) : ;; *) return 3 ;; esac + ltn_u="${ltn_rem:-.}/${ltn_cfg#refs/heads/}" + ltn_n=unknown + fi + fi + printf '%s%s%s%s%s%s%s%s%s\n' "$ltn_b" "$US" "$ltn_h" "$US" "${ltn_u:-none}" "$US" \ + "${ltn_d:-0}" "$US" "$ltn_n" + return 0 +} + +# NO REPOSITORY AT ALL IS AN ABSENCE, and nothing else is: `lane-worktrees`' +# `no_repository`, the rule #170 G5 settled, so the two readers of one lane's +# checkout cannot disagree about it. A directory with a `.git` of its own IS a +# repository however broken — git answers "not a git repository" for a gitdir +# it cannot read too — and only git's own "not a git repository" for a +# directory with none is the answer "there is nothing registered here". That +# message is read in the C locale, as `lane-worktrees`' `git_env` reads it: a +# translated git would otherwise say it in words this match never finds, and the +# two readers would disagree (review r1 of #252). +lane_no_repository() { # <dir> + lnr_d="${1-}"; lnr_err="" + if [ -e "$lnr_d/.git" ] || [ -L "$lnr_d/.git" ]; then return 1; fi + if lnr_err="$(LC_ALL=C git -C "$lnr_d" rev-parse --git-dir 2>&1 >/dev/null </dev/null)"; then return 1; fi + case "$(printf '%s' "$lnr_err" | tr '[:upper:]' '[:lower:]')" in + *"not a git repository"*) return 0 ;; + esac + return 1 +} + +lane_reconcile() { # <lane> + lrc_lane="${1-}" + # 0. THE SEAM (ruling 2026-10-04): a managed-owned lane's lifecycle is the + # managed ledger's, so this legacy reconciliation reads nothing of it and + # pronounces nothing on it — no crash, no clearance, no closure. A lane whose + # ownership could not be read gets the same silence, as `indeterminate`. + lrc_mrc=0; lrc_mown="" + lrc_mown="$(lane_is_managed_owned "$lrc_lane")" || lrc_mrc=$? + case "$lrc_mrc" in + 0) + printf 'MANAGED%s%s\n' "$US" "${lrc_mown:-unnamed}" + printf 'VERDICT%smanaged-owned%slane %s is owned by the managed ledger (owner %s): its lifecycle and its worktrees are that ledger'"'"'s, and this legacy reconciliation pronounces nothing on them (ruling 2026-10-04: "managed ledger owns enrolled lanes; #97 owns legacy")\n' \ + "$US" "$US" "$lrc_lane" "${lrc_mown:-unnamed}" + return 0 ;; + 8) : ;; + *) + printf 'MANAGED%sunknown\n' "$US" + printf 'VERDICT%sindeterminate%swhether the managed ledger owns lane %s is UNKNOWN — its register row carries managed-owner vocabulary that does not parse, or the register could not be read — so nothing is pronounced on it (Amendment 7(d)). Read it: lanes-edit.sh managed-projection %s\n' \ + "$US" "$US" "$lrc_lane" "$lrc_lane" + return 0 ;; + esac + lrc_root=""; lrc_rc=0 + lrc_root="$(lane_control_root "$lrc_lane")" || lrc_rc=$? + if [ "$lrc_rc" != 0 ]; then + note "lane $lrc_lane has no control root: its record names no directory (Amendment 11(c)) and \$PROJECTS_ROOT is not a directory here, so there is nothing to reconcile against. This is the pre-cutover answer, not a failure — the lane's next start or handoff creates one." + return 8 + fi + + # 1. THE SNAPSHOT. + lrc_state=""; lrc_gen=""; lrc_op=""; lrc_owner=""; lrc_upd="" + lrc_snap=""; lrc_srrc=0 + lrc_snap="$(lane_state_read "$lrc_lane")" || lrc_srrc=$? + if [ "$lrc_srrc" = 0 ]; then + lrc_state="$(printf '%s\n' "$lrc_snap" | awk -F'\t' '$1 == "state" { print $2; exit }')" + lrc_gen="$(printf '%s\n' "$lrc_snap" | awk -F'\t' '$1 == "generation" { print $2; exit }')" + lrc_op="$(printf '%s\n' "$lrc_snap" | awk -F'\t' '$1 == "operation" { print $2; exit }')" + lrc_owner="$(printf '%s\n' "$lrc_snap" | awk -F'\t' '$1 == "owner" { print $2; exit }')" + lrc_upd="$(printf '%s\n' "$lrc_snap" | awk -F'\t' '$1 == "updated" { print $2; exit }')" + elif [ "$lrc_srrc" = 8 ]; then + lrc_state=NONE + else + # A SNAPSHOT THAT IS THERE AND COULD NOT BE READ IS NOT A LANE THAT HAS + # NONE (Copilot round 6 on openRepoTools#97). Every non-zero read used to + # land on `NONE` here, and `NONE` is the verdict `no-state` — *this lane + # never started under this capability, there is nothing to recover* — which + # a launcher answers by going straight on. That is fail-OPEN on a crash + # pronouncement, the one class this capability exists to close. A read + # nobody got is `indeterminate` below, exactly as an unreadable HOLDER is. + lrc_state=UNREADABLE + # AND ONE THAT OPENS AND IS NOT A WHOLE RECORD IS SAID AS SUCH (#115). It + # used to come out as fields that were EMPTY, and its empty state word was + # `unknown-state` by the `*)` arm below — failing safe by accident rather + # than by a check. The 10 is the same; the word says which of the two. + lrc_swhy="" + if [ "$lrc_srrc" = 10 ] && [ -r "$lrc_root/lane-state.yaml" ] \ + && ! lane_sidecar_schema_ok "$lrc_root/lane-state.yaml"; then + lrc_state=MALFORMED; lrc_swhy="$LSS_WHY" + fi + fi + printf 'ROOT%s%s\n' "$US" "$lrc_root" + printf 'STATE%s%s%sgeneration %s%soperation %s%sowner %s%supdated %s\n' \ + "$US" "$lrc_state" "$US" "${lrc_gen:-0}" "$US" "${lrc_op:-none}" "$US" \ + "${lrc_owner:-none}" "$US" "${lrc_upd:-never}" + + # 2. THE HOLDER. `live_holder`'s three answers are the contract every other + # caller here reads: 0 a holder, 8 none, anything else THE RECORDS COULD NOT + # BE READ — which is never "no holder" (R22, Amendment 7(d)). A holder that + # could not be established fails CLOSED: the verdict is `indeterminate` and + # no crash is pronounced on a read nobody got. + # AND THE SAME DISTINCTION ONE READ EARLIER (#113 item 1): the ids the row + # records. Both reads ended in `|| :`, so a register nobody could read came + # out as an EMPTY id set, `live_holder` answered 8 for it — this lane records + # no session, nothing can be live — and a crash was pronounced on a liveness + # question nobody answered. `session_ids_checked` is #67's read of the same + # published-union-local ids, and it tells the two apart: 8, no row or a row + # naming no session, goes on to `live_holder` exactly as before; 1, either + # copy of the register unread, never reaches it. + lrc_ids=""; lrc_irc=0; lrc_hwhy="" + lrc_ids="$(session_ids_checked "$lrc_lane")" || lrc_irc=$? + lrc_hold=""; lrc_hrc=0 + if [ "$lrc_irc" != 0 ] && [ "$lrc_irc" != 8 ]; then + lrc_hrc=1 + lrc_hwhy="lane $lrc_lane's register row could not be read — the published register, or this checkout's copy of it at $LANES_FILE — so which sessions it records is NOT established, and an id set nobody read is never an empty one" + else + lrc_hold="$(live_holder "$lrc_lane" "$lrc_ids" 2>/dev/null)" || lrc_hrc=$? + fi + case "$lrc_hrc" in + 0) printf 'HOLDER%slive%s%s\n' "$US" "$US" "$(printf '%s' "$lrc_hold" | tr "$US" ' ')" ;; + 8) printf 'HOLDER%snone\n' "$US" ;; + *) printf 'HOLDER%sunknown%s%s\n' "$US" "$US" "${lrc_hwhy:-${SESSION_FILES_ERR:-the session records of this workstation could not be read}}" ;; + esac + + # 2b. THE BINDING (Amendment 18(b)): *"Liveness is pronounced only from + # INSIDE the binding's own `host` and `container`, where the pid namespace is + # the record's: from anywhere else a binding is UNKNOWN, never dead."* The + # holder read above is THIS workstation's session records, so it says nothing + # about a lane whose last STARTED/RESUMED was written on another host or in + # another container — and this workstation's snapshot is this workstation's + # alone (design decision 10). Read through the same scan and the same + # locality rule `binding` and `holder_is_dead` use, with clause (b)'s one + # exception: a binding whose window is GONE from a shared tmux server is a + # dead binding, and then the local read above decides, as it does there. + # here the binding is this place's, or the lane's lines predate it + # free no binding is open (released, or never started) + # gone bound elsewhere on this host's tmux, and its window is gone + # elsewhere bound in a place this one cannot pronounce on + # unknown the object log could not be read for it (Amendment 7(d)) + lrc_bwhere=free; lrc_bat="" + lrc_bout=""; lrc_brc=0 + lrc_bout="$(lane_binding_scan "$lrc_lane")" || lrc_brc=$? + if [ "$lrc_brc" != 0 ]; then + lrc_bwhere=unknown + else + IFS="$US" read -r lrc_bst lrc_bhost lrc_bcont lrc_bwin lrc_butc lrc_bsess lrc_bos \ + lrc_brutc lrc_brsess lrc_brpay lrc_bxverb lrc_bxutc lrc_bxsess lrc_bxpay lrc_blegacy \ + lrc_bfverb lrc_bfutc lrc_bfsess lrc_bfpay <<LRC_BIND +$lrc_bout +LRC_BIND + case "$lrc_bst" in + bound|requested) + lrc_bat="${lrc_bhost:-unknown}/${lrc_bcont:-none}" + if binding_is_here "$lrc_bhost" "$lrc_bcont" "$lrc_blegacy"; then + lrc_bwhere=here + elif [ "$(binding_window_state "$lrc_bhost" "$lrc_bwin" "$lrc_blegacy")" = gone ]; then + lrc_bwhere=gone + else + lrc_bwhere=elsewhere + fi ;; + esac + fi + printf 'BINDING%s%s%s%s\n' "$US" "$lrc_bwhere" "$US" "${lrc_bat:-none}" + + # 3. THE TREES — the inventory, recomputed. A stored value is a COMPARISON + # POINT and never current truth. + # THE COORDINATOR DIRECTORY, AND A LOG NOBODY COULD READ IS NOT A LANE WITH + # NONE (Copilot on 64dfd97, PR #97). `lane_payload_field` answers 8 for a log + # that carries no `dir` and 1 for a log that could not be read; collapsed into + # one empty string, the second skipped both sweeps below — the registrations + # `git worktree list` holds and the trees on disk — and a SWAPPED lane with no + # holder then read as resumable over paths nobody inspected. The 1 is kept, + # and the verdict below is `indeterminate` for it. + lrc_dir=""; lrc_drc=0 + lrc_dir="$(lane_payload_field "$lrc_lane" dir 2>/dev/null)" || lrc_drc=$? + [ "$lrc_drc" = 0 ] || lrc_dir="" + lrc_seen=""; lrc_n=0; lrc_recover=0; lrc_dirty=0 + # AN INVENTORY NOBODY COULD LIST IS NOT AN EMPTY ONE (#113, the unreadable + # sidecar's rule one level up). `lane_trees_list` answers 10 for a `trees` + # directory that is there and cannot be listed (#157 item 4e), and this read + # ended in `|| :`, so every tree the lane recorded vanished from the report and + # its verdict could still be `resumable`. `lrc_unread` gathers what the + # inventory and the sweeps below could not read, and the verdict says so. + lrc_unread=""; lrc_tl=""; lrc_tlrc=0 + lrc_tl="$(lane_trees_list "$lrc_lane" 2>/dev/null)" || lrc_tlrc=$? + case "$lrc_tlrc" in + 0|8) : ;; + 10) lrc_unread="its worktree inventory directory $lrc_root/trees is there and could not be listed" ;; + *) lrc_unread="its worktree inventory could not be read (exit $lrc_tlrc)" ;; + esac + while IFS="$US" read -r lrc_id lrc_p lrc_b lrc_h lrc_u lrc_d lrc_np lrc_w lrc_ob lrc_co lrc_tg lrc_to lrc_sch; do + [ -n "${lrc_id:-}" ] || continue + lrc_n=$((lrc_n + 1)) + # BOTH SPELLINGS JOIN THE SEEN SET, because the two sweeps below compare + # against it with git's physical answer and with the recorded `dir`'s own, + # and a tree named under one spelling and skipped under neither is a tree + # reported twice. + [ -n "${lrc_p:-}" ] && lrc_seen="$lrc_seen $lrc_p $(lane_real_path "$lrc_p") " + # A SIDECAR THIS READER DOES NOT KNOW IS REPORTED AND NEVER RECOMPUTED + # AGAINST. `lane_trees_list` empties every field of one, because a value + # read out of a record whose shape this reader is guessing at is worse than + # no value: comparing git's answer to it would print a difference that means + # nothing. It counts as wanting recovery, because a person has to say what + # wrote it. + if [ "${lrc_sch:-}" = "<unreadable>" ]; then + printf 'TREE%s%s%sunreadable-sidecar%s%s%sits sidecar is there and could not be read, so the tree it records — where it is, and whether it held uncommitted or unpublished work — is NOT known, and nothing is assumed about it; read %s/trees/%s.yaml by hand before relaunching a writer\n' \ + "$US" "$lrc_id" "$US" "$US" "<no path read>" "$US" "$lrc_root" "$lrc_id" + lrc_recover=$((lrc_recover + 1)) + continue + fi + # A RECORD OF THIS SCHEMA THAT IS NOT A WHOLE ONE (#115) is reported as the + # unreadable one is: nothing is read out of it, it counts toward recovery, + # and the line says what is missing from it and names the file. + if [ "${lrc_sch:-}" = "<malformed>" ]; then + lrc_mwhy="the record could not be read again to say why" + if lane_sidecar_schema_ok "$lrc_root/trees/$lrc_id.yaml"; then :; else lrc_mwhy="$LSS_WHY"; fi + printf 'TREE%s%s%smalformed-sidecar%s%s%sits sidecar is of this schema and %s, so the tree it records — where it is, and whether it held uncommitted or unpublished work — is NOT known, nothing is assumed about it, and no writer replaces it; read %s/trees/%s.yaml by hand before relaunching a writer\n' \ + "$US" "$lrc_id" "$US" "$US" "${lrc_p:-<no path read>}" "$US" "$lrc_mwhy" "$lrc_root" "$lrc_id" + lrc_recover=$((lrc_recover + 1)) + continue + fi + if [ "${lrc_sch:-}" != "$LANE_STATE_SCHEMA" ]; then + printf 'TREE%s%s%sunknown-schema%s%s%sits sidecar records schema %s and this reader writes %s, so none of its fields is read and nothing is compared against them; the tree itself is untouched\n' \ + "$US" "$lrc_id" "$US" "$US" "${lrc_p:-<no path recorded>}" "$US" "${lrc_sch:-<none>}" "$LANE_STATE_SCHEMA" + lrc_recover=$((lrc_recover + 1)) + continue + fi + lrc_now=""; lrc_nrc=0 + lrc_now="$(lane_tree_now "$lrc_p")" || lrc_nrc=$? + if [ "$lrc_nrc" = 3 ]; then + # GIT ANSWERS THERE AND ONE OF ITS READS FAILED. Nothing is assumed: not + # clean, not dirty, not published. The tree is left exactly as it is and + # the person is sent to it. + printf 'TREE%s%s%sunreadable%s%s%sgit answers in this path and one of the reads an observation is made of failed, so NOTHING is assumed about it — it was branch %s head %s with %s dirty and %s unpushed at %s; read it by hand (git -C %s status) before relaunching a writer onto it\n' \ + "$US" "$lrc_id" "$US" "$US" "$lrc_p" "$US" "$lrc_b" "$lrc_h" "${lrc_d:-0}" "${lrc_np:-0}" "$lrc_ob" "$lrc_p" + lrc_recover=$((lrc_recover + 1)) + continue + fi + if [ "$lrc_nrc" = 1 ]; then + # THE PATH IS GONE. Whether that is a tidy removal or a loss is decided + # by what the sidecar last SAW there, and metadata can reconstruct no + # file's contents: a tree that held uncommitted or unpublished work is + # POSSIBLE LOSS and is never claimed to be rebuildable. + case "${lrc_d:-0}${lrc_np:-0}" in + 00) printf 'TREE%s%s%smissing%s%s%swas branch %s head %s; clean and published at %s; the estate parked record and `resume <Name>` are the only rebuild\n' \ + "$US" "$lrc_id" "$US" "$US" "$lrc_p" "$US" "$lrc_b" "$lrc_h" "$lrc_ob" ;; + *) printf 'TREE%s%s%spossible-loss%s%s%swas branch %s head %s with %s dirty and %s unpushed at %s; NOTHING here can reconstruct uncommitted files — do not recreate this path\n' \ + "$US" "$lrc_id" "$US" "$US" "$lrc_p" "$US" "$lrc_b" "$lrc_h" "$lrc_d" "$lrc_np" "$lrc_ob" ;; + esac + lrc_recover=$((lrc_recover + 1)) + continue + fi + if [ "$lrc_nrc" = 2 ]; then + printf 'TREE%s%s%snot-a-checkout%s%s%sthe path exists and git does not answer in it; it is left exactly as it is\n' \ + "$US" "$lrc_id" "$US" "$US" "$lrc_p" "$US" + lrc_recover=$((lrc_recover + 1)) + continue + fi + lrc_nb="$(printf '%s' "$lrc_now" | awk -F"$US" '{print $1}')" + lrc_nh="$(printf '%s' "$lrc_now" | awk -F"$US" '{print $2}')" + lrc_nu="$(printf '%s' "$lrc_now" | awk -F"$US" '{print $3}')" + lrc_nd="$(printf '%s' "$lrc_now" | awk -F"$US" '{print $4}')" + lrc_nn="$(printf '%s' "$lrc_now" | awk -F"$US" '{print $5}')" + lrc_class=ok + [ "${lrc_nd:-0}" -gt 0 ] && lrc_class=dirty + # `unpushed` IS A COUNT OR IT IS THE WORD `unknown`, and the word is what a + # branch whose configured upstream is not in this checkout answers. It is + # never compared as a number, and it counts as work that may not be + # published rather than as nothing to publish. + case "${lrc_nn:-0}" in + ''|0) : ;; + *[!0-9]*) + if [ "$lrc_class" = dirty ]; then lrc_class=dirty+unpushed-unknown; else lrc_class=unpushed-unknown; fi ;; + *) + if [ "$lrc_class" = dirty ]; then lrc_class=dirty+unpushed; else lrc_class=unpushed; fi ;; + esac + [ "$lrc_class" = ok ] || lrc_dirty=$((lrc_dirty + 1)) + lrc_moved="" + [ "$lrc_nb" = "$lrc_b" ] || lrc_moved="$lrc_moved; branch was $lrc_b and is $lrc_nb" + [ "$lrc_nh" = "$lrc_h" ] || lrc_moved="$lrc_moved; head was $lrc_h and is $lrc_nh" + [ "${lrc_nu:-none}" = "${lrc_u:-none}" ] || lrc_moved="$lrc_moved; upstream was ${lrc_u:-none} and is ${lrc_nu:-none}" + # AND WHICH TRANSITION TOOK THE OBSERVATION, where it is not this lane's + # current one. The pair was written into every sidecar and read by nothing + # until this round, so a poll filed by an operation a recovery has since + # superseded read exactly like the current one. + if [ -n "${lrc_tg:-}" ] && [ "$lrc_tg" != 0 ] && [ "$lrc_tg" != "${lrc_gen:-0}" ]; then + lrc_moved="$lrc_moved; observed under generation $lrc_tg (operation ${lrc_to:-none}) and this lane is at generation ${lrc_gen:-0}" + fi + printf 'TREE%s%s%s%s%s%s%sbranch %s head %s upstream %s %s dirty %s unpushed; observed %s at %s%s\n' \ + "$US" "$lrc_id" "$US" "$lrc_class" "$US" "$lrc_p" "$US" \ + "$lrc_nb" "$lrc_nh" "${lrc_nu:-none}" "${lrc_nd:-0}" "${lrc_nn:-0}" \ + "${lrc_d:-0}/${lrc_np:-0}" "$lrc_ob" "$lrc_moved" + done <<EOF +$lrc_tl +EOF + + # 4. WHAT IS THERE AND IS IN NO SIDECAR — from git's own registrations and + # from the two lane roots on disk. It is REPORTED and never adopted, deleted + # or overwritten: which lane a tree belongs to is a person's to say. + lrc_unmanaged=0 + # A TRIAD (opensoft/openRepoTools#186, plan task T018). WHERE THE LANE'S + # CHECKOUT IS AN ASSEMBLY — its own `project.yaml` declares a leg other than + # itself, read by `assembly_legs`, the one reader every lane tool asks — what + # its LEGS hold is read too: the worktrees git registers in each leg's + # repository, which `git worktree list` in the assembly never names, and the + # paired feature trees `<assembly>/worktrees/<feature>/<each leg's path>`. + # Both are reported exactly as the checkout's own registrations and the lane + # roots are, and adopted, deleted or overwritten no more. A checkout with no + # `project.yaml` is asked nothing, so its report is what it always was; a + # manifest, a leg's registrations or the paired root that could not be read + # leaves paths nobody read, and the verdict below says so. + lrc_legs=""; lrc_lgrc=8; lrc_legwhy=""; lrc_tab="$(printf '\t')" + if [ -n "$lrc_dir" ] && [ -d "$lrc_dir" ] && { [ -e "$lrc_dir/project.yaml" ] || [ -L "$lrc_dir/project.yaml" ]; }; then + lrc_lgrc=0 + lrc_legs="$(assembly_legs "$lrc_dir")" || lrc_lgrc=$? + fi + if [ -n "$lrc_dir" ] && [ -d "$lrc_dir" ]; then + # THE CHECKOUT'S OWN ROW IS NOT AN UNMANAGED TREE, AND git ANSWERS WITH THE + # PHYSICAL PATH. A recorded `dir` reached through a symlink — which is how + # every estate with a `projects` link spells it — would otherwise not match + # the first row of `worktree list` and the lane's own checkout would be + # reported as a tree nobody manages. `cd -P` is the portable resolver here + # for the reason `lane-start`'s `real_of` gives: `readlink -f` is not in the + # stock macOS userland. + lrc_dirp="$(lane_real_path "$lrc_dir")" + # THE REGISTRATIONS ARE A READ, AND ITS STATUS IS KEPT (#113 item 4). It + # ended in `|| :`, so a checkout whose registrations could not be read was + # one with none: every stale registration and every unmanaged tree in it + # was omitted, the verdict could still read `resumable`, and the estate's + # own `resume` then failed on the registration the report never named. A + # directory that is NO repository at all registers nothing, and that alone + # is an absence (`lane_no_repository`, `lane-worktrees`' rule). + lrc_wlo=""; lrc_wlrc=0 + lrc_wlo="$(git -C "$lrc_dir" worktree list --porcelain 2>/dev/null </dev/null)" || lrc_wlrc=$? + if [ "$lrc_wlrc" != 0 ] && lane_no_repository "$lrc_dir"; then lrc_wlrc=0; lrc_wlo=""; fi + if [ "$lrc_wlrc" != 0 ]; then + lrc_unread="${lrc_unread:+$lrc_unread; }the worktree registrations of $lrc_dir could not be read (git worktree list exited $lrc_wlrc)" + fi + while IFS= read -r lrc_wl; do + case "$lrc_wl" in worktree\ *) : ;; *) continue ;; esac + lrc_wp="${lrc_wl#worktree }" + [ "$lrc_wp" = "$lrc_dir" ] && continue + [ -n "$lrc_dirp" ] && [ "$lrc_wp" = "$lrc_dirp" ] && continue + # AND THE SIDECARS ARE ASKED UNDER BOTH SPELLINGS, for the same reason. + lrc_wpr="$(lane_real_path "$lrc_wp")" + case "$lrc_seen" in *" $lrc_wp "*|*" $lrc_wpr "*) continue ;; esac + if [ -d "$lrc_wp" ]; then + printf 'TREE%s%s%sunmanaged%s%s%sgit registers it in %s and no sidecar of this lane names it; it is left exactly as it is\n' \ + "$US" "$(tree_id_for "$lrc_wp")" "$US" "$US" "$lrc_wp" "$US" "$lrc_dir" + else + printf 'TREE%s%s%sstale-registration%s%s%sgit registers it in %s and the directory is gone; `git -C %s worktree prune` is a person'\''s act\n' \ + "$US" "$(tree_id_for "$lrc_wp")" "$US" "$US" "$lrc_wp" "$US" "$lrc_dir" "$lrc_dir" + fi + # NAMED ONCE. The on-disk sweep below walks the same two roots git + # registers these in, so a path reported here joins the seen set — under + # both spellings, because that sweep walks the recorded `dir` and this one + # answered with the physical path — or a reader is told about one tree + # twice under two different reasons. + lrc_seen="$lrc_seen $lrc_wp $lrc_wpr " + lrc_unmanaged=$((lrc_unmanaged + 1)) + done <<EOF +$lrc_wlo +EOF + fi + # T018: EVERY LEG'S REGISTRATIONS, beside the checkout's own. A leg that is + # not checked out here is an empty directory of the assembly's, where git + # answers the ASSEMBLY — it registers nothing of its own, so it is passed + # over. A leg's main worktree is listed FIRST and spelled as its git + # directory under the assembly's `.git/modules/`, so it is skipped by place, + # not by name. + # A LEG WITH A `.git` OF ITS OWN THAT GIT CANNOT READ is no absent leg: it is + # a read that failed, never an absent or a clean one (Amendment 7(d)), and + # passed over it was a leg this reconciliation said nothing of while the + # sweep counted it. So it is the sweep's rule (`probe_leg`: git's toplevel + # there is not the leg, and a `.git` stands in it) and the sweep's word: a + # TREE row `unreadable`, which requires recovery, as the sweep's `leg` row is + # `unreadable` and counted. It is NO `indeterminate`: the sweep counts that + # leg and goes on (exit 3), and a verdict it refuses on would hide the count. + # SO IS A LEG DIRECTORY THIS ACCOUNT CANNOT SEARCH (#255, openRepoShape-2's + # SHOULD on #246): whether a `.git` stands in it cannot be tested, and the + # `.git` test fails there exactly as for a leg that is not checked out, so it + # was passed over in silence. It is the same `unreadable` row, in the words + # of the sweep's `probe_leg` and `lane-handoff`; a leg directory that is not + # there at all is still passed over (`-d`). + if [ "$lrc_lgrc" = 0 ]; then + while IFS="$lrc_tab" read -r lrc_lrepo lrc_ldecl lrc_labs; do + [ -n "$lrc_labs" ] && [ -d "$lrc_labs" ] || continue + lrc_ltop="$(git -C "$lrc_labs" rev-parse --show-toplevel 2>/dev/null </dev/null || :)" + if [ -z "$lrc_ltop" ] || [ "$(lane_real_path "$lrc_ltop")" != "$(lane_real_path "$lrc_labs")" ]; then + if [ -e "$lrc_labs/.git" ] || [ -L "$lrc_labs/.git" ]; then + lrc_lwhat="it has a .git of its own and git could not read it" + elif [ ! -x "$lrc_labs" ]; then + lrc_lwhat="its directory cannot be searched, so whether it has a .git of its own could not be tested, and git could not read it" + else + continue + fi + lrc_lr="$(lane_real_path "$lrc_labs")" + case "$lrc_seen" in *" $lrc_labs "*|*" $lrc_lr "*) continue ;; esac + if [ -n "$lrc_ltop" ]; then + lrc_lerr="git answers $lrc_ltop there" + else + lrc_lerr="$(git -C "$lrc_labs" rev-parse --show-toplevel 2>&1 >/dev/null </dev/null \ + | awk 'NF { sub(/^[ \t]+/, ""); sub(/[ \t]+$/, ""); print; exit }' | tr -d '\037')" + lrc_lerr="${lrc_lerr:-no answer}" + fi + printf 'TREE%s%s%sunreadable%s%s%sthe %s leg of %s/project.yaml%s: git could not be read through it (%s: %s), so NOTHING is assumed about it — not its own state, nor the worktrees it registers, which were not listed; a read that failed is never a clean leg (Amendment 7(d)) — read it by hand (git -C %s status) before relaunching a writer onto a tree of its repository\n' \ + "$US" "$(tree_id_for "$lrc_labs")" "$US" "$US" "$lrc_labs" "$US" "$lrc_ldecl" "$lrc_dir" \ + "${lrc_lrepo:+ ($lrc_lrepo)}" "$lrc_lwhat" "$lrc_lerr" "$lrc_labs" + lrc_seen="$lrc_seen $lrc_labs $lrc_lr " + lrc_recover=$((lrc_recover + 1)) + continue + fi + lrc_lwl=""; lrc_lwrc=0 + lrc_lwl="$(git -C "$lrc_labs" worktree list --porcelain 2>/dev/null </dev/null)" || lrc_lwrc=$? + if [ "$lrc_lwrc" != 0 ]; then + lrc_legwhy="${lrc_legwhy:+$lrc_legwhy; }the worktrees git registers in $lrc_labs, the $lrc_ldecl leg, could not be listed (git worktree list exited $lrc_lwrc)" + continue + fi + lrc_first=1 + while IFS= read -r lrc_wl; do + case "$lrc_wl" in worktree\ *) : ;; *) continue ;; esac + if [ "$lrc_first" = 1 ]; then lrc_first=0; continue; fi + lrc_wp="${lrc_wl#worktree }" + lrc_wpr="$(lane_real_path "$lrc_wp")" + case "$lrc_seen" in *" $lrc_wp "*|*" $lrc_wpr "*) continue ;; esac + if [ -d "$lrc_wp" ]; then + printf 'TREE%s%s%sunmanaged%s%s%sgit registers it in %s, the %s leg of %s/project.yaml (%s), and no sidecar of this lane names it; it is left exactly as it is\n' \ + "$US" "$(tree_id_for "$lrc_wp")" "$US" "$US" "$lrc_wp" "$US" "$lrc_labs" "$lrc_ldecl" "$lrc_dir" "$lrc_lrepo" + else + printf 'TREE%s%s%sstale-registration%s%s%sgit registers it in %s, the %s leg of %s/project.yaml (%s), and the directory is gone; `git -C %s worktree prune` is a person'\''s act\n' \ + "$US" "$(tree_id_for "$lrc_wp")" "$US" "$US" "$lrc_wp" "$US" "$lrc_labs" "$lrc_ldecl" "$lrc_dir" "$lrc_lrepo" "$lrc_labs" + fi + lrc_seen="$lrc_seen $lrc_wp $lrc_wpr " + lrc_unmanaged=$((lrc_unmanaged + 1)) + done <<LRC_LEG_TREES +$lrc_lwl +LRC_LEG_TREES + done <<LRC_LEGS +$lrc_legs +LRC_LEGS + fi + while IFS= read -r lrc_wr; do + [ -n "$lrc_wr" ] || continue + [ -d "$lrc_wr" ] || continue + # A ROOT THAT CANNOT BE LISTED hides every tree in it — the glob comes back + # as itself and reads as an empty root — so it is a read nobody made (#113 + # item 4, the on-disk half of the same sweep). + if [ ! -r "$lrc_wr" ] || [ ! -x "$lrc_wr" ]; then + lrc_unread="${lrc_unread:+$lrc_unread; }the lane's worktree root $lrc_wr could not be listed" + continue + fi + for lrc_c in "$lrc_wr"/*; do + [ -d "$lrc_c" ] || continue + lrc_cr="$(lane_real_path "$lrc_c")" + case "$lrc_seen" in *" $lrc_c "*|*" $lrc_cr "*) continue ;; esac + git -C "$lrc_c" rev-parse --git-dir >/dev/null 2>&1 || continue + printf 'TREE%s%s%sunmanaged%s%s%sit sits under this lane'\''s worktree root and no sidecar names it; it is left exactly as it is\n' \ + "$US" "$(tree_id_for "$lrc_c")" "$US" "$US" "$lrc_c" "$US" + lrc_seen="$lrc_seen $lrc_c $lrc_cr " + lrc_unmanaged=$((lrc_unmanaged + 1)) + done + done <<EOF +$(lane_worktree_roots "$lrc_lane" "$lrc_dir") +EOF + # T018: THE PAIRED ROOT. A feature directory, and each declared leg's path + # under it, that holds a `.git` of its own and that nothing above named — a + # registration lost, or a clone where a worktree belongs. Anything else under + # it is the assembly's own working tree, where git answers too, so a `.git` + # is what makes a checkout here. A directory that cannot be listed is a read + # nobody made, never an empty one. + if [ "$lrc_lgrc" = 0 ] && [ -d "$lrc_dir/worktrees" ]; then + if [ ! -r "$lrc_dir/worktrees" ] || [ ! -x "$lrc_dir/worktrees" ]; then + lrc_legwhy="${lrc_legwhy:+$lrc_legwhy; }the assembly's paired root $lrc_dir/worktrees could not be listed" + else + for lrc_f in "$lrc_dir"/worktrees/*; do + [ -d "$lrc_f" ] && [ ! -L "$lrc_f" ] || continue + if [ ! -r "$lrc_f" ] || [ ! -x "$lrc_f" ]; then + lrc_legwhy="${lrc_legwhy:+$lrc_legwhy; }the assembly's feature directory $lrc_f could not be listed" + continue + fi + # THE FEATURE DIRECTORY ITSELF, then each declared leg's path under + # it — a relative one, as the standard writes them. The directory is + # passed through the ENVIRONMENT: `awk -v` reads escapes in a value, + # so a name holding `\` would come out as another path. + lrc_cands="$lrc_f +$(printf '%s\n' "$lrc_legs" | LRC_F="$lrc_f" awk -F'\t' '$2 != "" && $2 !~ /^\// { p = $2; sub(/^\.\//, "", p); print ENVIRON["LRC_F"] "/" p }')" + while IFS= read -r lrc_c; do + [ -n "$lrc_c" ] && [ -d "$lrc_c" ] && [ ! -L "$lrc_c" ] || continue + lrc_cr="$(lane_real_path "$lrc_c")" + case "$lrc_seen" in *" $lrc_c "*|*" $lrc_cr "*) continue ;; esac + # A LEG'S DIRECTORY THAT CANNOT BE SEARCHED hides whether a `.git` + # stands in it: a read nobody made, never an empty directory. + if [ ! -x "$lrc_c" ]; then + lrc_legwhy="${lrc_legwhy:+$lrc_legwhy; }the assembly's paired tree directory $lrc_c could not be searched" + continue + fi + { [ -e "$lrc_c/.git" ] || [ -L "$lrc_c/.git" ]; } || continue + printf 'TREE%s%s%sunmanaged%s%s%sit sits in the assembly'\''s paired feature trees (%s/worktrees) and no sidecar of this lane names it; it is left exactly as it is\n' \ + "$US" "$(tree_id_for "$lrc_c")" "$US" "$US" "$lrc_c" "$US" "$lrc_dir" + lrc_seen="$lrc_seen $lrc_c $lrc_cr " + lrc_unmanaged=$((lrc_unmanaged + 1)) + done <<LRC_PAIRED +$lrc_cands +LRC_PAIRED + done + fi + fi + + # 5. THE VERDICT — the lifecycle word crossed with the holder, which is the + # whole of what tells the two crash kinds apart. + lrc_v=""; lrc_why="" + if [ "$lrc_hrc" != 0 ] && [ "$lrc_hrc" != 8 ]; then + lrc_v=indeterminate + [ -n "$lrc_hwhy" ] || lrc_hwhy="this workstation's session records could not be read" + lrc_why="$lrc_hwhy, so whether a holder is live is NOT established — which is not the same as none" + else + case "$lrc_state$lrc_hrc" in + RUNNING8) lrc_v=ungraceful-stop; lrc_why="the lane is recorded RUNNING and no verified holder is live: the session stopped before any handoff began, so nothing was polled, refreshed or recorded — inspect every tree below before relaunching a writer" ;; + RUNNING0) lrc_v=running; lrc_why="a verified holder is live and the lane is RUNNING: do not launch a second coordinator or a second writer onto any tree below" ;; + SWAPPING8) lrc_v=interrupted-swap; lrc_why="the lane is recorded SWAPPING and no verified holder is live: operation ${lrc_op:-none} began and did not finish, so the handoff, the row and the record may each be half done — every tree below is preserved for recovery" ;; + SWAPPING0) lrc_v=swap-in-progress; lrc_why="operation ${lrc_op:-none} is running in a live holder: do not compete with it" ;; + SWAPPED8) lrc_v=resumable; lrc_why="the swap completed and no holder is live: the lane may be resumed once the trees below are read" ;; + SWAPPED0) lrc_v=inconsistent; lrc_why="the lane is recorded SWAPPED and a holder is LIVE: a swapped lane has no holder, so one of the two is wrong and neither is overwritten here" ;; + CLOSED8) lrc_v=closed; lrc_why="the lane is closed" ;; + CLOSED0) lrc_v=inconsistent; lrc_why="the lane is recorded CLOSED and a holder is LIVE" ;; + UNREADABLE*) lrc_v=indeterminate; lrc_why="this lane's lifecycle snapshot at $lrc_root/lane-state.yaml IS THERE and could not be read, so where its session stopped is NOT established — which is not the same as a lane that has none, and is no clearance to relaunch anything (R22, Amendment 7(d): a read that failed is never an answer). Read that file by hand; if you know what wrote it, move it aside and this lane's next transition writes a fresh one" ;; + MALFORMED*) lrc_v=indeterminate; lrc_why="this lane's lifecycle snapshot at $lrc_root/lane-state.yaml is of this schema and ${lrc_swhy:-is not a whole record} — truncated, or edited by hand — so where its session stopped is NOT established, and no writer replaces it, exactly as none replaces a schema it does not write (#115). Read that file by hand; if you know what wrote it, move it aside and this lane's next transition writes a fresh one" ;; + NONE*) lrc_v=no-state; lrc_why="this lane has no lifecycle snapshot: it has not started or handed off under this capability, so its crash kind cannot be told from its record (Amendment 7(i)'s cutover rule — nothing is backfilled)" ;; + *) lrc_v=unknown-state; lrc_why="the snapshot holds the state word '$lrc_state', which this reader does not know; nothing is assumed about it" ;; + esac + if [ "$lrc_v" = closed ] && [ "$lrc_dirty" -gt 0 ]; then + lrc_v=closure-inconsistent + lrc_why="the lane is recorded CLOSED and $lrc_dirty tree(s) below are dirty or unpushed: no cleanup is made here" + fi + fi + # AND A LANE BOUND ELSEWHERE IS NEVER PRONOUNCED ON FROM HERE (Amendment + # 18(b), step 2b above). Every verdict this function can reach out of a local + # snapshot and a local holder read — a crash, a clearance, a closure, or + # "nothing to recover" — is a pronouncement on liveness, and from outside the + # binding that is UNKNOWN, never dead. So all of them become `indeterminate`. + case "$lrc_bwhere" in + elsewhere) + lrc_v=indeterminate + lrc_why="lane $lrc_lane is bound on $lrc_bat, and liveness is pronounced only from inside that binding (Amendment 18(b)): from here it is UNKNOWN, never dead, so no crash, no clearance and no closure is pronounced — and this workstation's snapshot is this workstation's alone (design decision 10). Read the lane from that place, or ask it to hand off: lane-start --request-handoff" ;; + unknown) + lrc_v=indeterminate + lrc_why="lane $lrc_lane's object log could not be read, so where it is bound is NOT established — and liveness may be pronounced only from inside the binding (Amendment 18(b)). A read that failed is never an answer (Amendment 7(d))" ;; + esac + # AND NO CLEARANCE OVER PATHS NOBODY READ (#113). The inventory, the + # registrations or a lane root that could not be read leaves trees this + # report never saw — so whatever the snapshot and the holder say, the verdict + # is not one a launcher may go past. + if [ -n "$lrc_unread" ] && [ "$lrc_v" != indeterminate ]; then + lrc_v=indeterminate + lrc_why="not all of lane $lrc_lane's worktrees could be read ($lrc_unread), so trees this report never saw may hold work, and no clearance is pronounced over paths nobody read (R22, Amendment 7(d))" + fi + if [ "$lrc_drc" != 0 ] && [ "$lrc_drc" != 8 ] && [ "$lrc_v" != indeterminate ]; then + lrc_v=indeterminate + lrc_why="lane $lrc_lane's object log could not be read, so its coordinator directory is NOT established and neither the worktrees git registers there nor the trees on disk under its roots were inspected — no clearance is pronounced over paths nobody read (Amendment 7(d))" + fi + # T018: AN ASSEMBLY WHOSE LEGS COULD NOT BE READ is one whose leg + # registrations and paired trees nobody inspected — the same paths-nobody-read + # as an unreadable object log, and the same answer. It is said in the words + # `lane-worktrees`' sweep refuses with (`the legs of the assembly <dir> could + # not be read`), because the sweep reads this verdict FIRST and refuses on + # it: one fact, one spelling, whichever reader a person meets. + if [ "$lrc_lgrc" != 0 ] && [ "$lrc_lgrc" != 8 ] && [ "$lrc_v" != indeterminate ]; then + lrc_v=indeterminate + lrc_why="the legs of the assembly $lrc_dir could not be read (its project.yaml is there and unreadable), so which legs it declares — and the worktrees they register and the paired feature trees under $lrc_dir/worktrees — is NOT established, and no clearance is pronounced over paths nobody read (T018, Amendment 7(d))" + fi + if [ -n "$lrc_legwhy" ] && [ "$lrc_v" != indeterminate ]; then + lrc_v=indeterminate + lrc_why="lane $lrc_lane's checkout $lrc_dir is an assembly and not all of what its legs hold could be read ($lrc_legwhy), so no clearance is pronounced over paths nobody read (T018, Amendment 7(d))" + fi + printf 'TREES%s%s inventoried%s%s dirty or unpushed%s%s require recovery%s%s unmanaged or stale\n' \ + "$US" "$lrc_n" "$US" "$lrc_dirty" "$US" "$lrc_recover" "$US" "$lrc_unmanaged" + printf 'VERDICT%s%s%s%s\n' "$US" "$lrc_v" "$US" "$lrc_why" + return 0 +} + +# ------------------------------------- every inventoried worktree, as rows +# +# opensoft/openRepoTools#161 — THE INVENTORY OF EVERY LANE ON THIS WORKSTATION, +# ONE ROW PER TREE, and the one implementation of that sentence: `lanes +# --worktrees` renders what this prints and `lanes-index sync --source +# inventory` copies it into the derived index's `worktrees` table, so the +# listing a person reads and the table another workstation queries cannot come +# to disagree about what a lane left. US-separated, sixteen fields: +# +# TREE <workstation> <lane> <owner> <path> <branch> <base> <lifecycle> +# <generation> <operation> <writer_live> <last_seen_utc> <last_commit> +# <dirty> <unpushed> <provenance> +# UNREAD <workstation> <lane> <why> +# PARTIAL <workstation> <why> +# +# IT READS WHAT #97 WROTE AND NOTHING THAT IT DID NOT. The lanes are the +# listing's own (`lanes_rows --all --closed`, so a closed or dormant lane's +# leftovers are not hidden), and so is `writer_live` — the listing's LIVE, out +# of this workstation's session records, and EMPTY where those could not be +# read or the lane is bound elsewhere (Amendment 7(d) and 18(b): never "no" on a +# read nobody could make). The trees are `lane_trees_list`'s sidecars and +# NO DIRECTORY IS WALKED for a tree no sidecar names: that is +# `lane-reconcile`'s act, and it is an act. `owner` is `lane_is_managed_owned`'s +# answer — the read `managed-projection` makes — as `legacy`, `managed <owner>` +# or `unknown`, and `lifecycle` is the snapshot's own word for a LEGACY lane +# only: a managed or unknown lane's lifecycle is not this tooling's to +# pronounce on (ruling 2026-10-04), and neither is one whose snapshot is +# missing, unreadable or of another schema, so those are `INDETERMINATE`. +# `generation` and `operation` are the snapshot's; `provenance` is the +# generation the TREE'S OWN record was filed under, which is behind +# `generation` exactly when the observation predates the lane's current +# transition. +# +# EVERY FIELD IS THE LAST OBSERVATION, NEVER RECOMPUTED: `branch`, `dirty`, +# `unpushed` and `last_seen_utc` are what the sidecar says the handoff saw. +# Two git reads are made per tree the inventory names, both of the RECORDED +# head and neither of the working tree: `last_commit` (`<sha> <subject>`) and +# `base`, its merge-base with `origin/main`, else `main`, else `origin/HEAD` +# — in the tree, or in its recorded checkout once the tree is gone. A detached +# head is `detached <sha>`; a record that could not be read is `unreadable +# sidecar`, one of another schema `unknown schema <n>`, and one of this schema +# that is not whole `malformed sidecar` (#115). Each keeps the path the record +# names where it names one, else the record's id (its file name) stands +# there. A kept path is the record's own word, so it may be relative or +# not a tree at all; only a whole record's path is known absolute. A count that is +# `unknown` is empty — an INTEGER column has no word for it. +# +# AND THE LISTING ITSELF IS SAID TO BE WHOLE OR NOT (opensoft/openRepoTools#173 +# item c1, Copilot's fourth review of #171). Its lanes are the names three +# reads give — the register's rows, the archive's rows and the object logs' +# file names — and each lane's trees are found under the control root its +# log's `dir` places. `lanes_rows` is a listing a person reads in front of a +# launch, so it may not refuse: where one of those reads fails it SAYS so on +# stderr (the log listing not even that) and lists what the others gave. Taken +# as whole, that made a lane whose only row is in an archive that could not be +# read a lane with no trees — and `lanes-index sync` removed its rows; with all +# three unread the listing was EMPTY and this said 8, "none", and the sync +# removed every row. So for the whole listing — a named lane is read by its +# name, which no listing gives — each of those reads is asked here too, and a +# failed one is ONE `PARTIAL` line: the rows beside it are every tree this read +# reached, a lane it could not name is NOT a lane with no worktrees (R22, +# Amendment 7(d)), and the indexer writes nothing over it. The register, the +# archive and the list of the logs are asked BEFORE the listing, and a read +# that succeeds is the very text the listing then reads - the register's out of +# its cache, the other two pinned for the listing alone (`PIN_ARCHIVE`, +# `PIN_LOGS`), so no read that fails after the check can thin a listing taken +# as whole (the review of #289, SHOULD-1). The logs themselves are asked AFTER +# it, out of the warnings the events' own read of them left (`state_events`, +# built once per process): a log it could not read, and a list of the logs it +# could not make, which is the read every lane's `dir` comes from - and the +# lane's root, its trees and its snapshot are all found under that one `dir`, +# not under a second read of its log (review r2 of #289, SHOULD-A); where +# those warnings could not be kept, whether a log failed is not known, which +# is said the same way. With no `origin`, the log directory is asked as the +# trees' is below, and its files are still read twice: docs/README-lanes.md +# says what that leaves. An empty listing over a failed read is that line +# alone, and never 8. +# +# The rows are sorted bytewise, which is the order the index's copy is written +# in too: the two reads of one inventory are the same bytes. +# 0 rows, with a PARTIAL line where the listing was not whole · 8 none · +# 1 the lane listing could not be read +worktree_rows() { # [<canonical lane>] + wr_one="${1-}"; wr_out="" + wr_live_ok=1 + live_session_ids >/dev/null 2>&1 || wr_live_ok=0 + wr_partial="" + wr_unlisted="the object logs under origin/$LANES_BRANCH:$LANES_LOG_PREFIX could not be listed" + if [ -z "$wr_one" ]; then + register_text_checked >/dev/null 2>&1 || + wr_partial="the register $LANES_PATH could not be read" + # THE ARCHIVE AND THE LOG LIST ARE PINNED, NOT ONLY ASKED (SHOULD-1(b)): + # each read that succeeds here is the text every read of the listing below + # is handed, as the register's is its cache. `x` keeps the text's last + # newline through the substitution. + wr_pin="" + if wr_pin="$(archive_text 2>/dev/null && printf x)"; then + PIN_ARCHIVE_TEXT="${wr_pin%x}"; PIN_ARCHIVE=1 + else + wr_partial="${wr_partial:+$wr_partial; }the archive $LANES_ARCH_PATH could not be read" + fi + # `known_lanes`' OWN TWO READS, which print what they could and answer 0 + # either way, because the listing unions them with the register. WITH NO + # `origin`, A DIRECTORY THAT IS THERE IS ASKED AS THE TREES' IS BELOW: `ls` + # lists an `r--` one, whose files no glob can then open (N1 of the review). + if have_remote_ref; then + wr_pin="" + if wr_pin="$(git -C "$LANES_REPO" ls-tree --name-only "origin/$LANES_BRANCH" -- "$LANES_LOG_PREFIX" 2>/dev/null && printf x)"; then + PIN_LOGS_TEXT="${wr_pin%x}"; PIN_LOGS=1 + else + wr_partial="${wr_partial:+$wr_partial; }$wr_unlisted" + fi + elif [ -e "$LANES_LOG_DIR" ] || [ -L "$LANES_LOG_DIR" ]; then + if [ ! -d "$LANES_LOG_DIR" ] || [ ! -r "$LANES_LOG_DIR" ] || [ ! -x "$LANES_LOG_DIR" ]; then + wr_partial="${wr_partial:+$wr_partial; }the log directory $LANES_LOG_DIR is there and could not be listed" + fi + fi + fi + wr_lanes=""; wr_lrc=0 + if [ -n "$wr_one" ]; then + wr_lanes="$(lanes_rows --lane "$wr_one" --closed)" || wr_lrc=$? + else + wr_lanes="$(lanes_rows --all --closed)" || wr_lrc=$? + fi + PIN_ARCHIVE=0; PIN_ARCHIVE_TEXT=""; PIN_LOGS=0; PIN_LOGS_TEXT="" + case "$wr_lrc" in + 0) : ;; + 8) [ -n "$wr_partial" ] || return 8 ;; + *) return 1 ;; + esac + if [ -z "$wr_one" ] && [ "$wr_lrc" = 0 ]; then + wr_ulogs=""; wr_urc=0; wr_ulist="" + if [ -n "$SE_WARN_FILE" ] && [ -f "$SE_WARN_FILE" ]; then + wr_ulogs="$(sed -n -e 's/^lanes-edit: unreadable log: \(.*\) — git could not read it.*$/\1/p' "$SE_WARN_FILE" 2>/dev/null)" || wr_urc=1 + # THE EVENTS' OWN LIST OF THE LOGS (SHOULD-1(a)): where it failed, no + # lane has the `dir` its trees are found under. + wr_ulist="$(sed -n -e '/^lanes-edit: unlisted logs: /p' "$SE_WARN_FILE" 2>/dev/null)" || wr_urc=1 + else + wr_urc=1 + fi + if [ "$wr_urc" != 0 ]; then + wr_partial="${wr_partial:+$wr_partial; }whether every object log could be read is not known, because the warnings of their read could not be kept" + else + if [ -n "$wr_ulist" ]; then + case "; $wr_partial; " in + *"; $wr_unlisted; "*) : ;; + *) wr_partial="${wr_partial:+$wr_partial; }$wr_unlisted" ;; + esac + fi + if [ -n "$wr_ulogs" ]; then + wr_partial="${wr_partial:+$wr_partial; }these object logs could not be read: $(printf '%s\n' "$wr_ulogs" | tr '\n' ' ' | sed -e 's/ $//')" + fi + fi + fi + wr_tab="$(printf '\t')" + while IFS="$wr_tab" read -r wr_l wr_st wr_w wr_pf wr_win wr_sid wr_dir wr_obj wr_age wr_restart wr_home wr_fk wr_loc wr_rest; do + [ -n "${wr_l:-}" ] || continue + # ONE CONTROL-ROOT READ FOR A LANE WITH NO TREES, which is nearly every lane + # in the estate: the sidecars are listed only where a `trees` directory is. + # The listing's column 7 IS `lane_payload_field <lane> dir` — the same last + # lane-kind payload carrying `dir`, out of the same published logs, `none` + # where there is none — so it is handed to `lane_control_root` as the + # payload it takes, rather than having each of sixty lanes' logs read a + # second time to find what the listing has just said (measured on Eagle's + # 61 lanes: 7.9 s for the whole read with the second reading, 2.7 s + # without it). `none` is not absolute, so it falls to the same third rung + # an absent `dir` does. + # AND THE SAME PAYLOAD TO THE TWO READS BELOW (review r2 of #289, + # SHOULD-A). `lane_trees_list` and `lane_state_read` worked the root out + # again with no `dir`, reading the lane's log a second and a third time, + # and a `git show` that failed there was thrown away: the root fell to the + # third rung, where no `trees` is, and a lane whose trees this loop had + # just found read as a lane with none. The listing's `dir` is now the root + # of all three, so the read that could fail is not made. + wr_pay="dir ${wr_dir:-none}" + wr_root=""; wr_rrc=0 + wr_root="$(lane_control_root "$wr_l" "$wr_pay" 2>/dev/null)" || wr_rrc=$? + [ "$wr_rrc" = 0 ] || continue + [ -d "$wr_root/trees" ] || continue + # A DIRECTORY THAT IS THERE AND CANNOT BE LISTED IS NOT AN EMPTY ONE, and + # the trees it holds are not trees this lane no longer has (R22). + if [ ! -r "$wr_root/trees" ] || [ ! -x "$wr_root/trees" ]; then + wr_out="${wr_out}UNREAD$US$WS$US$wr_l${US}its trees directory $wr_root/trees is there and could not be listed +" + continue + fi + wr_trees=""; wr_trc=0 + wr_trees="$(lane_trees_list "$wr_l" "$wr_pay" 2>/dev/null)" || wr_trc=$? + # 8 IS A `trees` DIRECTORY WITH NO RECORD IN IT; ANYTHING ELSE, with the + # directory already found above, is a read that did not happen - and its + # rows are not rows this lane no longer has (Copilot round 2 on #171). + case "$wr_trc" in + 0) : ;; + 8) continue ;; + *) + wr_out="${wr_out}UNREAD$US$WS$US$wr_l${US}its trees directory $wr_root/trees is there and lane-trees could not read it (exit $wr_trc) +" + continue ;; + esac + # LIVENESS IS PRONOUNCED ONLY FROM INSIDE THE BINDING (Amendment 18(b)). A + # live record here naming one of the lane's ids is `1` and no such record is + # `0` - but only where this workstation could read its records AND the + # lane's latest binding is not on another host (the listing's column 13). + # Either of those says UNKNOWN, the empty field, and it wins over the + # listing's LIVE too (Copilot round 1 on #171): a still-running local + # session of an older binding says nothing about the writer the lane's + # binding elsewhere has now. + wr_live=0 + [ "$wr_st" = LIVE ] && wr_live=1 + [ "${wr_loc:-none}" = elsewhere ] && wr_live="" + [ "$wr_live_ok" = 1 ] || wr_live="" + wr_own=""; wr_orc=0 + wr_own="$(lane_is_managed_owned "$wr_l" 2>/dev/null)" || wr_orc=$? + wr_own="$(printf '%s\n' "$wr_own" | head -n 1)" + case "$wr_orc" in + 0) if [ -n "$wr_own" ]; then wr_owner="managed $wr_own"; else wr_owner=unknown; fi ;; + 8) wr_owner=legacy ;; + *) wr_owner=unknown ;; + esac + wr_life=INDETERMINATE; wr_gen=""; wr_op="" + wr_snap=""; wr_src=0 + wr_snap="$(lane_state_read "$wr_l" "$wr_pay" 2>/dev/null)" || wr_src=$? + if [ "$wr_src" = 0 ]; then + wr_s="$(printf '%s\n' "$wr_snap" | awk -F'\t' '$1 == "state" { print $2; exit }')" + if [ "$wr_s" != UNKNOWN-SCHEMA ]; then + wr_gen="$(printf '%s\n' "$wr_snap" | awk -F'\t' '$1 == "generation" { print $2; exit }')" + wr_op="$(printf '%s\n' "$wr_snap" | awk -F'\t' '$1 == "operation" { print $2; exit }')" + case "$wr_gen" in ''|*[!0-9]*) wr_gen="" ;; esac + case "$wr_s" in RUNNING|SWAPPING|SWAPPED|CLOSED) wr_life="$wr_s" ;; esac + fi + fi + [ "$wr_owner" = legacy ] || wr_life=INDETERMINATE + while IFS="$US" read -r t_id t_p t_b t_h t_u t_d t_n t_w t_ob t_co t_g t_o t_s; do + [ -n "${t_id:-}" ] || continue + t_base=""; t_last="" + if [ "${t_s:-}" = "<unreadable>" ]; then + t_branch="unreadable sidecar"; [ -n "${t_p:-}" ] || t_p="$t_id" + t_d=""; t_n=""; t_g=""; t_ob="" + elif [ "${t_s:-}" = "<malformed>" ]; then + t_branch="malformed sidecar"; [ -n "${t_p:-}" ] || t_p="$t_id" + t_d=""; t_n=""; t_g=""; t_ob="" + elif [ "${t_s:-}" != "$LANE_STATE_SCHEMA" ]; then + t_branch="unknown schema ${t_s:-<none>}"; [ -n "${t_p:-}" ] || t_p="$t_id" + t_d=""; t_n=""; t_g=""; t_ob="" + else + if [ "$t_b" = detached ]; then t_branch="detached $t_h"; else t_branch="$t_b"; fi + case "$t_h" in + ''|*[!0-9a-f]*) : ;; + *) + if [ "${#t_h}" -eq 40 ]; then + t_gd="" + if [ -d "$t_p" ]; then t_gd="$t_p"; elif [ -d "${t_co:-}" ]; then t_gd="$t_co"; fi + if [ -n "$t_gd" ]; then + t_last="$(git -C "$t_gd" show -s --format='%H %s' "$t_h^{commit}" 2>/dev/null | head -n 1 | tr -d '\037')" + [ -n "$t_last" ] || t_last="$t_h" + for t_ref in refs/remotes/origin/main refs/heads/main refs/remotes/origin/HEAD; do + if git -C "$t_gd" rev-parse --verify -q "$t_ref^{commit}" >/dev/null 2>&1; then + t_base="$(git -C "$t_gd" merge-base "$t_h" "$t_ref" 2>/dev/null || :)" + break + fi + done + else + t_last="$t_h" + fi + fi ;; + esac + case "$t_d" in ''|*[!0-9]*) t_d="" ;; esac + case "$t_n" in ''|*[!0-9]*) t_n="" ;; esac + case "$t_g" in ''|*[!0-9]*) t_g="" ;; esac + fi + wr_out="${wr_out}TREE$US$WS$US$wr_l$US$wr_owner$US$t_p$US$t_branch$US$t_base$US$wr_life$US$wr_gen$US$wr_op$US$wr_live$US$t_ob$US$t_last$US$t_d$US$t_n$US$t_g +" + done <<WR_TREES +$wr_trees +WR_TREES + done <<WR_LANES +$wr_lanes +WR_LANES + [ -z "$wr_partial" ] || wr_out="${wr_out}PARTIAL$US$WS$US$wr_partial +" + [ -n "$wr_out" ] || return 8 + printf '%s' "$wr_out" | LC_ALL=C sort + return 0 +} + +# ---------------------------------------------------------------- subcommands + +cmd="${1-}" +# The usage block is this file's own header: print from line 3 until the first +# line that is not a comment. (It used to be a hard-coded `3,59p`, which went +# stale the moment the header grew — as it did under Amendment 5.) +[ -n "$cmd" ] || { sed -n -e '1,2d' -e '/^#/!q' -e 's/^# \{0,1\}//' -e p "$RESOLVED"; exit 2; } +shift || : +# `session-start` is EXEMPT. It is a hook: it never writes, and it must exit 0 +# even where there is no register to read at all — a hook that dies is a hook +# that breaks the session it was meant to orient. +# EVERY WRITER REFUSES WHERE THIS CONTAINER HAS NO CONFIGURED WORKSTATION +# (Amendment 11, decision 8(d), `R-A11-14`). ONE GUARD AT THE DISPATCHER rather +# than one per writer: `WS` is built into every event line's `session <uuid>@<ws>` +# and into every commit subject this file writes, so a container id reaches the +# append-only log through any of the TEN subcommands listed below (nine until +# Amendment 18 added `request-handoff`), and ten copies of one rule is how nine +# of them would come to disagree. The READS are untouched — a read in +# front of every launch may not refuse, and one that answers nothing for a +# workstation nobody configured is telling the truth. +case "$cmd" in + # `request-handoff` JOINS THE LIST BECAUSE IT WRITES (Amendment 18(c)/(e)). It + # reaches `write_event` directly rather than through `log`, so the dispatcher + # guard is the only place that stops it filing a `HANDOFF-REQUESTED` or a + # forced `PAUSED` under a container id — and one field further along than the + # `session <uuid>@<ws>` this guard has always protected, clause (a)'s own + # `host` falls back to THE RULE 10 WORKSTATION NAME, which in this state is + # that same container id. One guard, every writer, exactly as the paragraph + # below says — and Amendment 13's `set-row-state` and `migrate-state-cells` + # are in it for the same reason. + # AND `rename-lane` JOINS IT FOR THE SAME REASON (Amendment 16). Its four + # moves are one commit and one of them is a `RENAMED` line carrying + # `session <uuid>@<ws>`, so an unconfigured container would put its own id + # into the register, the log AND `lanes/aliases.tsv` in a single write. + # AND AMENDMENT 19-S TWO WRITES, `retire-rows` and `archive-rows`, for the + # same reason: each is ONE commit over several rows and logs, and every + # `RETIRED` line it appends carries `session <uuid>@<ws>`. + replace-in-row|append-session-id|append-line|add-row|set-row-state|migrate-state-cells|retire-rows|archive-rows|commit|log|claim|release|request-handoff|rename-lane) + ws_why="$(lanes_workstation_why "$WS_SOURCE")" + [ -z "$ws_why" ] || die "$ws_why" 2 ;; +esac + +# `guard` JOINS THAT EXEMPTION AND REFUSES FOR ITSELF (Amendment 12(d)). It is +# a hook too, and a blocking one: `die … 1` here would print the workspace +# refusal and let the prompt THROUGH, because only exit 2 blocks a +# `UserPromptSubmit`. So the verb takes the same reads itself and answers them +# with a 2 — fail CLOSED, which is the clause. +case "$cmd" in + # THE TWO FILTERS OF AMENDMENT 18 ADDENDUM 1 READ THEIR ROWS FROM STDIN and + # touch no workspace at all, so a workspace this workstation has not pointed + # at yet is not a reason to refuse them — the same exemption `session-start` + # has had since it was written, and the same one `guard` joined under + # Amendment 12(d), each for its own reason. + # AND THE RETIRED VERB IS EXEMPT TOO (Copilot round 4 on openRepoTools#82, + # suppressed comment `lanes-edit.sh:7525`). `append-row-status` is out of the + # WRITER list above and says so of itself — *"it refuses before the + # workstation guard and before the register is even looked for"* — but this + # second guard caught it all the same: on a machine with no configured + # workspace the caller got the workspace refusal (exit 1) instead of the + # RETIREMENT refusal (exit 2) naming the two acts that replace it. A + # compatibility refusal that only fires where the register is already + # reachable is not one. + # AND `project-legs` (T018) READS ONE `project.yaml` and nothing of the + # workspace, so `lane-worktrees`' daily report can ask it on a + # workstation where no register is configured. + session-start|guard|lane-groups|next-free|append-row-status|project-legs) : ;; + *) + if [ -z "$LANES_REPO" ] || [ -z "$LANES_DIR" ]; then + die "$(lanes_workspace_why)" 1 + fi + [ -f "$LANES_FILE" ] || die "registry not found: $LANES_FILE + $LANES_REPO is the workspace repository $(lanes_ws_yaml) names, and it + carries no lanes/LANES.md. A repository seeded by \`openRepoTools wip init\` + has one; re-run it (it is idempotent) or pull that checkout." 1 + ;; +esac + +case "$cmd" in + verify-row) + lane="${1-}"; [ -n "$lane" ] || die "usage: verify-row <lane>" 2 + lane="$(canon_lane "$lane")" || exit 2 + n="$(row_line "$lane")" || exit 2 + row="$(sed -n -e "${n}p" "$LANES_FILE")" + # Bash substrings, not `cut -c` and `rev`: `${#row}` counts CHARACTERS, + # and a register row is full of `·` `—` `→`, so a byte-counting `cut` + # disagrees with the length printed one field earlier — and BSD `rev` and + # `cut` answer `Illegal byte sequence` on the same row rather than + # disagreeing. The same rule `lane-end:566` states (R-A9-11). + # `${row: -200}` on a row SHORTER than 200 answers the empty string, where + # `rev | cut | rev` answered the whole row — so the short case is asked + # for explicitly rather than left to the expansion. + row_tail="$row"; [ "${#row}" -gt 200 ] && row_tail="${row: -200}" + printf 'lane : %s\nline : %s\nlength : %s chars\nfirst200: %s\nlast200 : %s\n' \ + "$lane" "$n" "${#row}" "${row:0:200}" "$row_tail" + ;; + + # AMENDMENT 13(a) — RETIRED, AND THE REFUSAL IS THE WHOLE OF IT. + # + # This verb appended to the `state` cell and never replaced it, which is how a + # column defined as the lane's CURRENT STATE came to hold a diary: 96,228 + # characters in one row, 7,016 in this lane's own after a single day, in a + # table nobody can read in the table. The cell can never grow again because + # the act that grew it is gone — not because every caller remembered. + # + # IT REFUSES BEFORE THE WORKSTATION GUARD AND BEFORE THE REGISTER IS EVEN + # LOOKED FOR (it is out of the dispatcher's writer list above), so a caller on + # a machine that has neither still learns what to run instead. Two acts + # replace it, and they are two because the cell held two things: the STATE, + # which is one phrase a person reads, and the NARRATIVE, which is history and + # belongs in the lane's own append-only log. + append-row-status) + die "append-row-status is RETIRED (lane-collision-protocol Amendment 13(a), in force 2026-09-13T21:08:36Z). The state cell is ONE PHRASE — '<STATE> · <UTC> · <one line>' — and every write REPLACES it, so that the column that says where a lane IS can never grow into a diary again. + the STATE: LANES_LANE=${1:-<lane>} lanes-edit.sh set-row-state ${1:-<lane>} \"<STATE> · <one line>\" + ($ROW_STATES; the line at most $ROW_STATE_CAP characters) + the NARRATIVE: LANES_LANE=${1:-<lane>} lanes-edit.sh log NOTED lane:${1:-<lane>} \"<what the lane did, found, launched, left>\" + a RULING: LANES_LANE=${1:-<lane>} lanes-edit.sh log RULED lane:${1:-<lane>} [→ <object>] \"<Brett Heap's words, verbatim>\" + read it back: lanes-edit.sh history ${1:-<lane>} [--since <UTC>] +Nothing was written." 2 + ;; + + # AMENDMENT 13(a) — THE ONE WRITER OF THE STATE CELL. It stamps the UTC itself + # and REPLACES the cell, so what the column holds after this call is exactly + # `<STATE> · <UTC> · <one line>` and nothing of what it held before. The + # history is not lost by that: it is in git, and — after `migrate-state-cells` + # — in the lane's own log, which is the file built to hold it. + set-row-state) + lane="${1-}"; phrase="${2-}" + [ -n "$lane" ] && [ -n "$phrase" ] || die "usage: set-row-state <lane> \"<STATE> · <one line>\" (STATE: $ROW_STATES)" 2 + [ "$#" -le 2 ] || die "set-row-state takes TWO arguments: the lane, and the phrase as ONE quoted string — set-row-state <lane> \"<STATE> · <one line>\". Got $# ; the shell has split the phrase, so quote it." 2 + # EVERY TEST OF THE PHRASE IS MADE FIRST — before the resolver, before the + # lock and before the row is read — so a refusal leaves this checkout, the + # mutex and the register exactly as it found them. + row_state_check "$phrase" + # AMENDMENT 15 — the row's own spelling, which is what the commit subject + # and every message below then carry. + lane="$(canon_lane "$lane")" || exit 2 + # THE CELL THIS REPLACES MAY BE THE MANAGED LEDGER'S MARKER (ruling + # 2026-10-04), and replacing it would take the lane out of the ledger's + # hands without the ledger: refused before the lock, nothing written. + managed_seam_refuse "$lane" "set-row-state" + acquire_lock; handle_preexisting + n="$(row_line "$lane")" || exit 2 + row="$(sed -n -e "${n}p" "$LANES_FILE")" + srs_rc=0; row_split_state_cell "$row" || srs_rc=$? + case "$srs_rc" in + 0) : ;; + 2) die "lane $lane's row (line $n) carries $(row_sep_count "$row") ' | ' separators where a seven-column row carries 6, so WHICH TEXT IS THE STATE CELL is not knowable from the row: read from the left this write lands on one cell, read from the right on another, and one of those readings overwrites the row's handoff path. Nothing was written. A Markdown table carries a literal pipe ESCAPED — \`\\|\` — so find the unescaped ' | ' inside a cell of that row, escape it by hand with an allowed tool, commit it (\`LANES_LANE=$lane lanes-edit.sh commit \"escape a literal pipe in row $lane\"\`), and re-run." 2 ;; + *) die "lane $lane's row (line $n) does not open with '|' and end with '|', so it is not a row this writer can take apart. Nothing was written." 2 ;; + esac + srs_new="$ROW_STATE · $(utc_now) · $ROW_STATE_LINE" + srs_was="$(rstrip_spaces "$RSS_CELL")" + replace_line "$n" "$RSS_HEAD$srs_new $RSS_TAIL" + # WHAT IT SAYS IS WHAT HAPPENED, and the two are not the same act. A state + # phrase stamped twice inside one second is byte-identical — `utc_now` is + # seconds — so the row already reads exactly this, nothing is written, and + # "REPLACED" beside `replace_line`'s own "nothing rewritten" would be two + # lines of one output contradicting each other. + if [ "${REPLACE_LINE_NOOP:-0}" = 1 ]; then + note "state cell UNCHANGED: it already reads exactly this ${#srs_new} chars, to the second" + else + note "state cell REPLACED: ${#srs_was} chars → ${#srs_new} chars" + fi + # THE WHOLE LINE IN THE SUBJECT, as `append-row-status` put its whole text + # there: the line is capped at 240 characters by the act above, and a + # subject cut at 72 loses exactly the tail that says what happened. + msg="LANES($lane@$WS): state · $ROW_STATE · $ROW_STATE_LINE" + [ -n "$PRE_DIRTY_LANES" ] && msg="$msg + sweeps uncommitted edit to row $PRE_DIRTY_LANES" + commit_push "$msg" + ;; + + replace-in-row) + lane="${1-}"; old="${2-}"; new="${3-}"; why="${4-}" + [ -n "$lane" ] && [ -n "$old" ] || die "usage: replace-in-row <lane> \"<old>\" \"<new>\" [\"<why>\"]" 2 + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + # THE SEAM (ruling 2026-10-04): a managed lane's row is the ledger's, and + # no legacy edit may write the marker's vocabulary into any row. + managed_seam_refuse "$lane" "replace-in-row" + if managed_projection_hint "$new"; then + die "the replacement text carries managed-owner vocabulary ('managed owner', 'managed binding', 'mode=managed' or 'managed:'), and only the managed ledger's own writer writes a managed-owner marker, and a legacy writer that wrote its vocabulary into a row would forge that lane's ownership (ruling 2026-10-04: \"managed ledger owns enrolled lanes; #97 owns legacy\"). Nothing was written." 2 + fi + acquire_lock; handle_preexisting + n="$(row_line "$lane")" || exit 2 + row="$(sed -n -e "${n}p" "$LANES_FILE")" + c="$(count_occurrences "$row" "$old")" || exit 2 + [ "$c" = 1 ] || die "'$old' occurs $c times in lane $lane's row (line $n); exactly 1 required" 2 + # NOT `${row/"$old"/"$new"}` (A9 Addendum 4, R-A9-11). Bash 4.3 and later + # read the quotes there as "this half is a literal, not a pattern"; BASH + # 3.2 KEEPS THE ONES AROUND THE REPLACEMENT AS CHARACTERS, so on macOS + # every `replace-in-row` wrote its new text WRAPPED IN DOUBLE QUOTES. The + # macOS job read `| "RETIRED 2026-09-13T20:39:04Z" · …` where the register + # wanted `| RETIRED 2026-…`, and nothing else noticed: the write succeeded, + # the commit landed, and the row was quietly wrong. (The pattern half is + # unaffected — 3.2 does remove those quotes, which is how the replacement + # got made at all.) Prefix and suffix instead, so `$new` never enters the + # pattern machinery: `%%` leaves the shortest prefix and `#` the text after + # the first match, and `count_occurrences` above has already proved there + # is exactly one. + ri_pre="${row%%"$old"*}"; ri_post="${row#*"$old"}" + replace_line "$n" "$ri_pre$new$ri_post" + msg="LANES($lane@$WS): ${why:-replace-in-row}" + [ -n "$PRE_DIRTY_LANES" ] && msg="$msg + sweeps uncommitted edit to row $PRE_DIRTY_LANES" + commit_push "$msg" + ;; + + # AMENDMENT 8, R-A8-4 — THE UUID APPEND IS CELL-SCOPED. + # + # `replace-in-row` refuses unless its anchor occurs exactly once in the WHOLE + # ROW, and the anchor for a session-cell append is a transcript uuid — which + # the 6(c) stamp writes into the STATE cell again on every launch (`RESUMED by + # <uuid> … launching claude --resume <uuid>` — twice more per launched start). + # Measured against `origin/main` on 2026-09-12, `openRepoProject-1`'s own row + # carries its current uuid THREE times and its previous one three times, so + # the single most load-bearing new act in Amendment 8(d) — recording the + # transcript the harness minted — could not run on the lane the amendment was + # written for. + # + # So the anchor is matched INSIDE THE SESSION CELL and nowhere else, and must + # occur exactly once THERE. `replace-in-row`'s whole-row rule is unchanged and + # is still right for what it is for: a state cell says the same thing in two + # places all the time, and a blind replace there would rewrite the wrong one. + # + # AND THE TEXT IS APPENDED AT THE END OF THE CELL, NOT AT THE ANCHOR. This is + # the second half of the same finding and it is not cosmetic: the cell spells + # its ids `harness `<uuid>`` — inside backticks — so a replace AT a bare-uuid + # anchor writes `harness `<uuid> → harness <new>`` and puts the new id inside + # the old one's code span. The anchor's job is to prove that the cell this + # checkout holds is the published one the caller read (Amendment 6(b): the + # cell is a HISTORY, oldest first, and the last id is the lane's current + # session); the APPEND's job is to add a lineage after all of them. Those are + # two different positions, and conflating them corrupted the cell. + # + # Anything that is not an append — a cell that must really be rewritten — is + # `replace-in-row`'s business, in front of a person. + append-session-id) + lane="${1-}"; old="${2-}"; add="${3-}"; why="${4-}" + [ -n "$lane" ] && [ -n "$old" ] && [ -n "$add" ] \ + || die "usage: append-session-id <lane> \"<anchor in the session cell>\" \"<text to append to the cell>\" [\"<why>\"]" 2 + case "$add" in + *"|"*) die "append-session-id's appended text may not contain '|': it would forge a cell boundary in the row. Got '$add'." 2 ;; + esac + if managed_projection_hint "$add"; then + die "append-session-id's appended text carries managed-owner vocabulary ('managed owner', 'managed binding', 'mode=managed' or 'managed:'), and only the managed ledger's own writer writes it into a row. Nothing was written." 2 + fi + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + managed_seam_refuse "$lane" "append-session-id" # Copilot round 3 on #97 + acquire_lock; handle_preexisting + n="$(row_line "$lane")" || exit 2 + row="$(sed -n -e "${n}p" "$LANES_FILE")" + row_split_session_cell "$row" || die "lane $lane's row (line $n) does not have three '|' before its session cell ends; refusing to touch it" 2 + c="$(count_occurrences "$RSC_CELL" "$old")" || exit 2 + if [ "$c" != 1 ]; then + whole="$(count_occurrences "$row" "$old" || printf '?')" + die "'$old' occurs $c time(s) in lane $lane's SESSION CELL (line $n); exactly 1 required there. The row as a whole carries it $whole time(s) — that difference is exactly why this act is cell-scoped and not replace-in-row." 2 + fi + replace_line "$n" "$RSC_HEAD$(rstrip_spaces "$RSC_CELL") $add $RSC_TAIL" + msg="LANES($lane@$WS): ${why:-append-session-id}" + [ -n "$PRE_DIRTY_LANES" ] && msg="$msg + sweeps uncommitted edit to row $PRE_DIRTY_LANES" + commit_push "$msg" + ;; + + append-line) + text="${1-}"; [ -n "$text" ] || die "usage: append-line \"<text>\"" 2 + # ONE LINE, REFUSED A NEWLINE BEFORE THE LOCK (opensoft/openRepoTools#85). + # `append_text_line` refuses it too, and before it writes — but that is + # after `acquire_lock` and `handle_preexisting`, which can COMMIT a peer's + # uncommitted register edit before this act's own write. A refusal that has + # already committed something is a refusal that wrote, so the verb asks + # first, exactly where `write_event` asks for `log`: the checkout is left + # as this command found it. `lane-handoff`'s file-level PAUSED line is the + # caller that met it, with a `why` carrying a newline. + if [ "${text//[$'\n\r']/}" != "$text" ]; then + die "append-line appends ONE line to the register, and this text carries a newline or a carriage return: it would append several, and the proof that only one was added would fail after the write, leaving the register modified and uncommitted. Nothing was written, and the lock was not taken. Spell the break '; ' and re-run." 2 + fi + # NO MARKER BY THE BACK DOOR (Copilot round 3 on #97): `add-row` refuses a + # row in the marker's vocabulary, and this appends any line at all to the + # register — a row-shaped one included. + if managed_projection_hint "$text"; then + die "the line carries managed-owner vocabulary ('managed owner', 'managed binding', 'mode=managed' or 'managed:'), and only the managed ledger's own writer writes it into the register. Nothing was written." 2 + fi + lane_tag="${LANES_LANE:-}" + [ -z "$lane_tag" ] || lane_tag="$(canon_lane "$lane_tag")" || exit 2 + if [ -z "$lane_tag" ]; then + cand="$(lane_from_text "$text")" + # AMENDMENT 15 — `row_lane_ci` ALONE, and the exact branch that used to + # sit above it is the same question asked twice now that `row_line` + # compares case-insensitively too. It answers with the ROW's spelling + # rather than the LINE's, which is what Rule 10's wire form needs: the + # line says `Lane: openxfactory-2` in lowercase and the row's token is + # `openXfactory-2`. It is still the register that decides — a candidate no + # row matches prints nothing, so "…names no lane at all" is never + # attributed to a lane called "at". + # + # AND THE 15(d) PAIR IS A REFUSAL HERE TOO, not an absence. `row_lane_ci` + # answers EMPTY for two rows exactly as it does for none, and an empty + # `lane_tag` is a commit attributed to nobody — a writer carrying on over + # the one register state the amendment says every writer refuses (Copilot + # round 1 on openRepoTools#41). `canon_lane` is asked for its STATUS only; + # which of "no row" and "one row" it is stays `row_lane_ci`-s answer. + # + # AMENDMENT 16(e) — AND THE NAME THE LINE CARRIES MAY BE A FORMER ONE. + # Rule 6 attribution is named in clause (e)'s own list of readers, and a + # line that says `lane <old>` is one lane's line whatever the register + # calls that lane today: `canon_lane` resolves it, and `row_lane_ci` still + # has the last word about whether any row answers at all, which is what + # keeps "…names no lane at all" from being attributed to a lane called + # "at". + if [ -n "$cand" ]; then + cand_c="$(canon_lane "$cand")" || exit 2 + lane_tag="$(row_lane_ci "${cand_c:-$cand}")" + fi + fi + acquire_lock; handle_preexisting + append_text_line "$text" + msg="LANES(${lane_tag:-unknown}@$WS): append line — ${text:0:72}" + [ -n "$PRE_DIRTY_LANES" ] && msg="$msg + sweeps uncommitted edit to row $PRE_DIRTY_LANES" + commit_push "$msg" + ;; + + add-row) + row="${1-}"; [ -n "$row" ] || die "usage: add-row \"<full | row |>\"" 2 + case "$row" in + "| "*) : ;; + *) die "a row must start with '| '" 2 ;; + esac + case "$(rstrip_spaces "$row")" in + *"|") : ;; + *) die "a row must end with '|'" 2 ;; + esac + pipes="$(count_occurrences "$row" "|")" || exit 2 + [ "$pipes" -ge 8 ] || die "a 7-column row needs at least 8 '|' characters, found $pipes" 2 + if managed_projection_hint "$row"; then + die "the new row carries managed-owner vocabulary ('managed owner', 'managed binding', 'mode=managed' or 'managed:'), and only the managed ledger's own writer writes a managed-owner marker, and a legacy writer that wrote its vocabulary into a row would forge that lane's ownership (ruling 2026-10-04: \"managed ledger owns enrolled lanes; #97 owns legacy\"). Nothing was written." 2 + fi + lane_new="$(printf '%s' "$row" | cut -d'`' -f2)" + # AMENDMENT 15(a) — A ROW UNDER ANY CASE IS A ROW, AND THE REFUSAL NAMES IT. + # This is the act the 2026-09-13 incident got past: `lane-start openxfactory + # 2` found no row for `openXfactory-2` and appended a second one for a lane + # that already had one. `row_line`'s exactly-one test cannot be the whole + # gate here, because two rows differing only by case make it fail for the + # OTHER reason and a failed `row_line` used to read as "no row, go ahead". + # + # AND THE PUBLISHED ROWS ARE ASKED TOO — R19, AND R30's FETCH IN FRONT OF IT + # (Copilot round 4 on openRepoTools#41). The scan was of `$LANES_FILE` alone, + # which a fetch does not move: on a checkout that is behind, a row `origin` + # already carries as `repoCase-1` is invisible here, this appends + # `repocase-1`, and `commit_push`'s own rebase then publishes the pair — the + # exact duplicate 15(a) makes this command refuse, arrived at through the one + # file the check never read. BOTH sets are asked and either is the refusal: + # the local scan stays because a row added here and not yet pushed is on no + # `origin` at all, and the published scan is the one the incident needed. + if [ -n "$lane_new" ]; then + log_sync + # AND THE ARCHIVE IS ASKED AS WELL (Amendment 19(b) and (d)). A row + # `archive-rows` has moved into `lanes/archive/LANES-retired.md` is still + # that lane's row: its object log is `lanes/log/<lane>.md` and that file is + # APPEND-ONLY, so a second lane under the same name would write its life + # into the first one's file and every read of that log — who held what, + # when it was claimed, which session paused it — would answer for two + # lanes at once. `next-free` never OFFERS such a position, because it + # counts the archive too; this is what refuses one that is typed by hand, + # which is the whole of "a retired `<repo>-<n>` is never reissued". + # BOTH COPIES OF THE ARCHIVE (Copilot round 1 on #93): `archive_text` + # answers with the PUBLISHED file wherever there is one, so a move + # committed here and not yet pushed was invisible to this check and its + # name came back on offer. The local file is read beside it, exactly as + # the row scan below reads `rows_named_ci_local` beside `rows_named_ci`. + # + # AND A READ THAT FAILED IS A REFUSAL, not an empty archive (round 2): the + # whole point of this check is that a retired identity is never reissued, + # and "I could not read the file that says which ones are retired" is not + # "none of them are" (Amendment 7(d)). NOR IS A LINE IT COULD NOT TAKE + # APART (#122): that row may be this lane's own, so it is the same refusal + # and the same 1, naming the line. + ar_arch_rc=0 + ar_arch="$(retired_identity_hits "$lane_new")" || ar_arch_rc=$? + case "$ar_arch_rc" in + 0) : ;; + 3) die "$LANES_ARCH_PATH carries a line this scan cannot take apart (above), so whether '$lane_new' is a name this estate has RETIRED is not known: a row this scan cannot take apart may be that lane's own, and a retired position is never reissued (Amendment 19(b)). A row that could not be read is not a row that is not there (Amendment 7(d)). Put the lane back in backticks in that row's first cell, or remove the line if it is no row; commit the archive (\`git -C $LANES_REPO commit -m \"<what it was>\" -- $LANES_ARCH_PATH\`), publish it where the line is on origin (\`LANES_LANE=<lane> lanes-edit.sh commit \"<what it was>\"\`), and re-run. Nothing was written." 1 ;; + *) die "$LANES_ARCH_PATH exists and could not be read or scanned, so whether '$lane_new' is a name this estate has RETIRED is not known — and a retired position is never reissued (Amendment 19(b)). A read that failed is not 'it is not retired' (Amendment 7(d)). Fix the read and re-run; nothing was written." 1 ;; + esac + if [ -n "$ar_arch" ]; then + die "lane '$lane_new' is RETIRED: its row is in $LANES_ARCH_PATH, spelled $(printf '%s\n' "$ar_arch" | tr '\n' ' ')— and a retired position is NEVER REISSUED (Amendment 19(b)). That lane's object log is $(log_path_for "$lane_new") and it is append-only, so a second lane under this name would write its life into the first one's file and every read of that log would answer for two lanes at once. Take a free position instead — \`lanes --prefix <repo>\` prints the next one and the line that takes it. Nothing was written." 2 + fi + ar_hits="$(rows_named_ci_local "$lane_new")" + # THE PUBLISHED ROWS ARE READ WITH THEIR STATUS (Copilot round 21 on #93, + # #138 item 18). Through `|| :` a register origin has and git could not + # read was "no row there", and a row this checkout had not pulled was + # appended a second time — and landed, wherever the rebase did not clash. + ar_pub="" + ar_pub="$(rows_named_ci "$lane_new" 2>/dev/null)" || + die "the published register on origin/$LANES_BRANCH could not be read, so whether '$lane_new' already has a row there is not known — and that is NOT 'it has none' (Amendment 7(d)): a row this checkout has not pulled would be added a second time. Fix the read and re-run; nothing was written." 1 + ar_all="$(printf '%s\n%s\n' "$ar_hits" "$ar_pub" | grep -v '^$' | LC_ALL=C sort -u || :)" + ar_n="$(printf '%s' "$ar_all" | grep -c . || :)" + ar_ln="$(printf '%s' "$ar_hits" | grep -c . || :)" + if [ "$ar_n" -gt 0 ]; then + # A LANE THE MANAGED LEDGER OWNS IS SAID TO BE ONE (Copilot round 3 on + # #97) before the duplicate refusal below, which would refuse it anyway + # without naming the owner. A new lane has no row and is never asked. + managed_seam_refuse "$lane_new" "add-row" + ar_more="" + [ "$ar_n" -gt 1 ] && ar_more=" Those $ar_n rows differ only by case and are themselves the refusal: merge them into one row first (Amendment 15(d))." + ar_where="Use set-row-state / replace-in-row on the row that is there." + [ "$ar_ln" = 0 ] && ar_where="That row is on origin/$LANES_BRANCH and this checkout has not pulled it, so adding one here would make two the moment this push rebases. Pull first — \`git -C $LANES_REPO pull --rebase\` — then use set-row-state / replace-in-row on the row that is there." + die "lane '$lane_new' already has a row, spelled $(printf '%s\n' "$ar_all" | tr '\n' ' ')— a lane name is ONE name under any case (Amendment 15(a)), so a row under another case IS that lane's row and this would be a second one. $ar_where$ar_more" 2 + fi + fi + acquire_lock; handle_preexisting + append_text_line "$row" + msg="LANES(${lane_new:-${LANES_LANE:-unknown}}@$WS): add row" + [ -n "$PRE_DIRTY_LANES" ] && msg="$msg + sweeps uncommitted edit to row $PRE_DIRTY_LANES" + ADD_ROW_LANE="$lane_new" + ADD_ROW_TEXT="$row" + CP_AFTER_REBASE=add_row_retirement_rescan + commit_push "$msg" + ar_push_rc=$? + CP_AFTER_REBASE="" + exit "$ar_push_rc" + ;; + + commit) + msg="${1-}"; [ -n "$msg" ] || die "usage: commit \"<message>\"" 2 + # AMENDMENT 15 — `$LANES_LANE` passes through the resolver like every + # `<lane>` argument does: it is the attribution in this commit's subject and + # the name the "touches other rows" test compares against. + [ -z "${LANES_LANE:-}" ] || LANES_LANE="$(canon_lane "$LANES_LANE")" || exit 2 + acquire_lock + # `commit` has no edit of its own to separate from a pre-existing one — + # its whole job is to wrap whatever is already dirty (a hand edit made + # with an allowed tool). The best it can do is warn when that dirty + # content ALSO touches a ROW other than the caller's own $LANES_LANE, + # and say so in the commit subject (0d84d34: a hermes-wallet-exercise + # `commit` call silently absorbed an unrelated openXfactory-2 row edit). + # "append" (a plain line with no row of its own, e.g. this call's own + # Rule 6 LANDING/LANDED line) is excluded from "other" — it is the + # normal, expected shape of exactly what `commit` is for, and flagging + # it would warn on every ordinary use. + if [ "$NO_GIT" != 1 ] && ! git -C "$LANES_REPO" diff --quiet -- "${CP_PATHS[@]}" 2>/dev/null; then + touched="$(identify_changed_lanes)" + other="$(printf '%s\n' "$touched" | tr ',' '\n' | grep -v -x -e "${LANES_LANE:-}" -e '' -e 'append' | paste -sd, - 2>/dev/null || :)" + if [ -n "$other" ]; then + note "WARNING: uncommitted LANES.md changes touch row(s) other than this lane (${LANES_LANE:-unknown}): $other" + warn_dirty + msg="$msg + sweeps uncommitted edit to row $other" + fi + fi + # #194 — the one write that, with nothing to stage, publishes the local + # commits ahead of origin: it is the RECOVERY's re-run. See commit_push. + CP_PUBLISH_AHEAD=1 + commit_push "LANES(${LANES_LANE:-unknown}@$WS): $msg" + ;; + + # AMENDMENT 19(c) — THE SWEEP'S WRITE. `lane-end --retire-dormant <repo>` is + # the word that finds the dormant rows, shows the dry run and takes the + # person's `--yes`; this is the one commit under it, and it re-proves every + # refusal for itself rather than trusting the caller's list. + retire-rows) + retire_rows ${1+"$@"} + ;; + + # AMENDMENT 19(d) — THE ARCHIVE. A DRY RUN unless `--yes` is passed, like the + # migration beside it, and one commit naming each lane moved when it is. + archive-rows) + ar_repo=""; ar_yes=0 + while [ $# -gt 0 ]; do + case "$1" in + --yes) ar_yes=1; shift ;; + --dry-run) ar_yes=0; shift ;; + --) shift ;; + -*) die "unknown option '$1' for archive-rows (usage: archive-rows <repo> [--yes])" 2 ;; + *) [ -z "$ar_repo" ] || die "archive-rows takes ONE repository: archive-rows <repo> [--yes]" 2 + ar_repo="$1"; shift ;; + esac + done + [ -n "$ar_repo" ] || die "usage: archive-rows <repo> [--yes] — without --yes it is a DRY RUN that writes nothing" 2 + archive_rows "$ar_repo" "$ar_yes" + ;; + + # ====================================================== AMENDMENT 16 ======= + # + # `rename-lane <old> <new> ["<why>"] [--verbatim] [--no-github]` — A LANE IS + # RENAMED IN ONE COMMIT, REFUSED OR WHOLE, AND ITS OLD NAME RESOLVES FOR EVER. + # + # Ratified 2026-09-14T09:24:35Z, verbatim *"Ratify as drafted (Recommended)"*, + # on Brett Heap's request of the same day, verbatim *"we need the ability to + # rename a lane"*. `lane-rename <old> <new>` on PATH is the word a person + # types; THIS is its write. The two are one act only because the word also + # renames the tmux window and types `/rename <new>` into the pane — neither of + # which a register writer may do for a session it is not (Amendment 16(f), and + # Amendment 12(h)'s M1 for why the typing is the only path a running session's + # name has). + # + # FOUR MOVES, ONE COMMIT (clauses (b)–(e)): the row's key cell, the object + # log, the handoff, and `lanes/aliases.tsv`. They are one commit because ANY + # TWO OF THEM APART IS A STATE NO READER CAN READ — a row under `<new>` whose + # log is still `<old>.md` is a lane whose history `who --lane` cannot find, and + # an alias without the row it points at is a name that resolves to nothing. So + # every refusal in clause (a) is made BEFORE THE FIRST BYTE IS WRITTEN, and + # each one of them says "Nothing was written": this command moves four files + # and a half-done rename is not something a second run can finish. + # + # AND THE `git mv` OF CLAUSES (c) AND (d) IS A PLAIN `mv` PLUS A PATHSPEC. + # `git mv` is one command and it also STAGES, which is the one thing this file + # never does: `commit_push` commits from its PATHSPECS precisely so that a + # peer's uncommitted work in this shared checkout can never be swept into a + # lane's commit (Amendment 5(d), and the sweep that made `--no-sweep` the + # default). Both paths go in as pathspecs of the one commit and git records + # the rename from the content, as it always does. `ensure_log`'s two-step + # `mv` is not needed either: a case-ONLY rename is refused below, so the two + # names are two files on every filesystem this ships to. + rename-lane) + rl_old=""; rl_new=""; rl_why=""; rl_verbatim=0 + while [ $# -gt 0 ]; do + case "$1" in + --verbatim) rl_verbatim=1; shift ;; + --no-github) NO_GITHUB=1; shift ;; + --why) rl_why="${2-}"; [ -n "$rl_why" ] || die "--why needs a reason" 2; shift 2 ;; + --why=*) rl_why="${1#--why=}"; [ -n "$rl_why" ] || die "--why needs a reason" 2; shift ;; + --) shift ;; + -*) die "unknown option '$1' for rename-lane" 2 ;; + *) + if [ -z "$rl_old" ]; then rl_old="$1" + elif [ -z "$rl_new" ]; then rl_new="$1" + elif [ -z "$rl_why" ]; then rl_why="$1" + else die "rename-lane takes <old> <new> [\"<why>\"] — '$1' is one argument too many" 2 + fi + shift ;; + esac + done + [ -n "$rl_old" ] && [ -n "$rl_new" ] \ + || die "usage: rename-lane <old> <new> [\"<why>\"] [--verbatim] [--no-github]" 2 + check_lane_name "$rl_old" + check_lane_name "$rl_new" + if managed_projection_hint "$rl_new"; then + die "the new name '$rl_new' carries managed-owner vocabulary ('managed-owner' or 'managed-binding'), so the row it is written into would read as a malformed managed-owner marker — ownership UNKNOWN for every act. Choose another name. Nothing was written." 2 + fi + # THE REASON IS FREE TEXT ON AN APPEND-ONLY LINE, so it takes the writer's + # own two rules before anything else is read (`write_event` states both): a + # third ` — ` leaves the line ambiguous to its own parser, and a newline + # appends lines to a file whose proof counts exactly one. + case "$rl_why" in + *" — "*) die "the reason may not contain ' — ': that separator divides an event line's verb from its fields and its fields from its free text, and a third one leaves the line ambiguous to its own parser, in a file nothing ever rewrites. Use a semicolon or a colon: '$rl_why'" 2 ;; + esac + if [ "${rl_why//[$'\n\r']/}" != "$rl_why" ]; then + die "the reason is ONE line: a newline in it would append several lines to an append-only log, and the proof that only one was added would fail after the write rather than before it" 2 + fi + rl_utc="$(utc_now)" + [ -n "$rl_why" ] || rl_why="renamed with lane-rename (lane-collision-protocol Amendment 16)" + + # ---- (a) THE REFUSALS. The fetch first, because every read below is of + # `origin/<branch>` (R19, R30) — a rename computed from a checkout that is + # behind is a rename whose push rebases into two rows. + log_sync + # AND THE OLD NAME GOES THROUGH THE RESOLVER LIKE ANY OTHER, WHICH MAKES + # RENAMING UNDER AN ANCIENT NAME WORK: `canon_lane` answers with the row's + # own spelling, and with clause (e) behind it a name this lane was called + # two renames ago renames the lane it is now. + rl_crc=0 + rl_old="$(canon_lane "$rl_old")" || rl_crc=$? + # ONE CONDITION, ONE CODE (Copilot round 6 on openRepoTools#81). `canon_lane` + # answers 66 for an alias table it could not read so that `canon-lane`'s four + # callers can tell it from a refusal — but a flat `|| exit 2` here made THIS + # writer answer 2 or 1 for the same fault depending on whether the typed name + # happened to have a row of its own, because a name with one never reaches + # the table at all. Translated to this command's own 1, which is what its + # other two alias-read refusals already spend and what the amendment's + # fail-closed rule is about. + case "$rl_crc" in + 0) : ;; + 66) die "${LANES_ALIASES_PATH:-lanes/aliases.tsv} could not be read ($(lane_alias_err)), and a rename whose alias table cannot be read is a rename whose old name may stop resolving — which is the one thing clause (e) promises for ever, so this fails closed. Nothing was written." 1 ;; + *) exit 2 ;; + esac + # THE OLD NAME'S LIFECYCLE CONTROL ROOT, read while the old name still has + # its log (openRepoTools#91; `lane_state_rename` moves it after the commit). + rl_lsr_old="$(lane_control_root "$rl_old" 2>/dev/null)" || rl_lsr_old="" + # THE SEAM (ruling 2026-10-04). A managed lane's marker names its lane as + # `bound-lane=`, so renaming the row under it would turn a valid marker into + # an unparseable one; the rename is the ledger's, and refused before the lock. + managed_seam_refuse "$rl_old" "rename-lane" + + # ---- THE MUTEX IS TAKEN BEFORE THE CHECKS, NOT BETWEEN THEM AND THE WRITE + # (Copilot round 6 on openRepoTools#81). Every refusal below reads a row, a + # log path, the alias table and a handoff, and every one of them is a + # question about what is NOT there — so two renames on one workstation could + # both answer "the target is free", and the second would move its log over + # the first's and rewrite a row it read before the first commit. The lock is + # this workstation's serialiser and it costs nothing to take it early: it is + # not a write, every refusal below still writes nothing, and `cleanup` + # releases it on every path out, the two signals included. + # + # ACROSS WORKSTATIONS the arbiter is the same one Rule 1's claim has: + # whichever commit lands on `main` first. `commit_push`'s rebase brings the + # other's row and log in, and the loser's next attempt meets its own + # refusals — a row under `<new>`, a published log — with nothing written. + acquire_lock + + # Refuse a spelling-only rename before probing both roots: on a + # case-insensitive filesystem they are the same intent, whose stored lane + # carries the canonical spelling rather than the requested new spelling. + if [ "$(lc "$rl_old")" = "$(lc "$rl_new")" ]; then + die "'$rl_old' and '$rl_new' are ONE name under any case (Amendment 15), so this is not a rename at all: it is a change to the row's own SPELLING, which every reader already resolves to and which Amendment 15(d) makes a hand act — the newer row's session id(s) appended to the older row's cell, in one commit. Nothing was written." 2 + fi + + # Rename and restart publication share this mutex. An unfinished operation + # owns its name and canonical inputs, including recovery from failed. + for rl_check in "$rl_old" "$rl_new"; do + rl_root_rc=0 + lane_restart_control_root "$rl_check" >/dev/null || rl_root_rc=$? + [ "$rl_root_rc" != 8 ] || continue # no root any writer could have used + [ "$rl_root_rc" = 0 ] || die "restart control root could not be read. Nothing was written." 1 + rl_restart=""; rl_restart_rc=0 + rl_restart="$(lane_restart_read "$rl_check")" || rl_restart_rc=$? + case "$rl_restart_rc" in + 8) continue ;; + 0) rl_restart_state="$(printf '%s\n' "$rl_restart" | awk -F'\t' '$1=="state" {print $2; exit}')" + [ "$rl_restart_state" = ready ] || die "lane $rl_check has restart intent $rl_restart_state; finish its supervised recovery before renaming. Nothing was written." 2 ;; + *) die "lane $rl_check restart intent could not be read. Nothing was written." 1 ;; + esac + done + + rl_oh="$(rows_named_ci "$rl_old" 2>/dev/null || :)" + rl_on="$(printf '%s' "$rl_oh" | grep -c . || :)" + rl_lh="$(rows_named_ci_local "$rl_old" 2>/dev/null || :)" + rl_ln="$(printf '%s' "$rl_lh" | grep -c . || :)" + if [ "$rl_on" -gt 1 ] || [ "$rl_ln" -gt 1 ]; then + die "the register holds rows whose lane names differ only by case for '$rl_old': $(printf '%s\n%s\n' "$rl_oh" "$rl_lh" | grep -v '^$' | LC_ALL=C sort -u | tr '\n' ' ')— a lane name is ONE name under any case (Amendment 15), so there is no ONE row to rename. Merge them first (Amendment 15(d)): append the newer row's session id(s) to the older row's session cell, in order, and remove the newer row in the SAME commit. Nothing was written." 2 + fi + if [ "$rl_ln" = 0 ]; then + if [ "$rl_on" = 1 ]; then + die "lane $rl_old's row is on origin/$LANES_BRANCH and this checkout has not pulled it, so the row this rename must rewrite is not here — and a rename that appended a second row would be the very duplicate Amendment 15(a) refuses. Pull first — \`git -C $LANES_REPO pull --rebase\` — and re-run. Nothing was written." 2 + fi + die "the register has no row for lane '$rl_old', in any case (Amendment 15(a)) and through no alias (Amendment 16(e)). A rename moves a row that exists; \`lanes --all\` lists the ones that do. Nothing was written." 2 + fi + + # A ROW UNDER `<new>` IN ANY CASE, asked of BOTH the published register and + # this copy of it — `add-row`'s own pair of scans, for its own reason: a row + # `origin` already carries is invisible to a local scan, and this push would + # rebase the two together. + rl_nh="$(printf '%s\n%s\n' "$(rows_named_ci "$rl_new" 2>/dev/null || :)" "$(rows_named_ci_local "$rl_new" 2>/dev/null || :)" | grep -v '^$' | LC_ALL=C sort -u || :)" + if [ -n "$rl_nh" ]; then + die "lane '$rl_new' already has a row, spelled $(printf '%s\n' "$rl_nh" | tr '\n' ' ')— a lane name is ONE name under any case (Amendment 15(a)), so renaming into it would make TWO rows for one name, which is the state every writer in this file refuses until 15(d)'s merge. Nothing was written." 2 + fi + + # `<new>` IS `<repo>-<n>` UNLESS `--verbatim` NAMES IT. Rule 4's form is + # what `lanes --prefix`, the next free position and `lane-start <repo> <n>` + # are all computed from, so a lane renamed out of it loses every one of + # them; Amendment 11's `--dir` lanes are the deliberate exception the flag + # exists for. + if [ "$rl_verbatim" = 0 ] && ! lane_shaped "$rl_new"; then + die "'$rl_new' is not of the form <repo>-<n> (Rule 4), and a lane renamed out of that form loses the next free position, the \`lane-start <repo> <n>\` that takes it and the whole of \`lanes --prefix\`. A lane deliberately named otherwise — Amendment 11's \`--dir\` lanes are the ones there are — is renamed with --verbatim. Nothing was written." 2 + fi + + # A `<new>` THAT IS ALREADY AN ALIAS KEY IS REFUSED (Copilot round 1 on + # openRepoTools#81). A row wins over an alias at every hop — that is what + # makes a name that is a lane today BE that lane — so minting a row under a + # name some other lane was renamed AWAY from would end that lane's old name + # resolving, which is the one thing clause (e) promises never happens. The + # refusal is here, at the one writer that can do it deliberately; a row + # minted under a freed name by `lane-start` is a different act and the + # readers handle it by the row-wins rule itself. + rl_krc=0 + rl_keys="$(lane_alias_keys 2>/dev/null)" || rl_krc=$? + if [ "$rl_krc" = 5 ]; then + die "${LANES_ALIASES_PATH:-lanes/aliases.tsv} could not be read ($(lane_alias_err)), and a rename whose alias table cannot be read is a rename whose old name may stop resolving — which is the one thing clause (e) promises for ever, so this fails closed. Nothing was written." 1 + fi + rl_kmatch="$(printf '%s\n' "$rl_keys" | awk -v w="$rl_new" 'BEGIN { lw = tolower(w) } NF && tolower($0) == lw { print; exit }')" + if [ -n "$rl_kmatch" ]; then + die "'$rl_new' is already a FORMER name in ${LANES_ALIASES_PATH:-lanes/aliases.tsv} (spelled '$rl_kmatch'), and a row under it would take precedence over that alias — which would end a lane's old name resolving, the one thing Amendment 16(e) promises for ever. Pick a name no lane has ever been called. Nothing was written." 2 + fi + + # A CYCLE, ASKED OF THE TABLE AS IT WILL BE (clause (e)). Adding `<old> → + # <new>` closes one exactly when the chain from `<new>` reaches `<old>`, + # anywhere along it — the new row is appended last and wins the key. + rl_arc=0 + lane_alias_target "$rl_new" "$rl_old" >/dev/null 2>&1 || rl_arc=$? + case "$rl_arc" in + 0 | 1) : ;; + 3) die "${LANES_ALIASES_PATH:-lanes/aliases.tsv} already resolves '$rl_new' in a CYCLE, so nothing can be added through it until that row is taken out by hand. \`rename-lane\` writes no cycle, so this table was hand-edited. Nothing was written." 2 ;; + 4) die "renaming $rl_old to $rl_new would close a CYCLE in ${LANES_ALIASES_PATH:-lanes/aliases.tsv}: '$rl_new' already resolves back through '$rl_old', and a chain that returns to its own start has no end for a reader to resolve to (Amendment 16(e)). Nothing was written." 2 ;; + *) die "${LANES_ALIASES_PATH:-lanes/aliases.tsv} could not be read ($(lane_alias_err)), and a rename whose alias table cannot be read is a rename whose old name may stop resolving — which is the one thing clause (e) promises for ever, so this fails closed. Nothing was written." 1 ;; + esac + + # THE SESSION FIELD OF THE `RENAMED` LINE IS A TRANSCRIPT UUID AND ONLY + # THAT (Amendment 7(b), R-A11 (e)) — asked HERE, with the other refusals, + # rather than by `write_event`, because this write does not go through + # `write_event`: its line lands in the same commit as three file moves. + rl_uuid="$(session_for "$rl_old")" + if ! valid_uuid "$rl_uuid"; then + die "an event's session field is the TRANSCRIPT UUID and only that (Amendment 7(b)), and this rename's RENAMED line has none: '${rl_uuid:-<empty>}'. Name the session taking the act: LANES_SESSION=\"\$CLAUDE_CODE_SESSION_ID\" lanes-edit.sh rename-lane $rl_old $rl_new. Nothing was written." 2 + fi + + # A LIVE SESSION HOLDING `<old>` IN ANOTHER WINDOW. + # + # THE WINDOW THIS COMMAND RUNS IN IS EXEMPT, AND IT IS THE ORDINARY CASE: a + # lane renames ITSELF, from its own pane, which is the whole of clause (f). + # `live_holder`'s fifth field is the verdict that tells the two apart — + # `here`, `elsewhere`, `orphan` — and it is the same read `lane-start` + # refuses a name over. The id SET is the published row's union this + # checkout's (R25), for that rule's reason: liveness fails CLOSED here, so + # an id `origin` has not seen yet is one more reason to refuse. + rl_ids="$( { session_ids_of_lane "$rl_old" 2>/dev/null || : + session_ids_local_of_lane "$rl_old" 2>/dev/null || :; } | awk 'NF && !seen[$0]++')" + rl_lhv=""; rl_lhrc=0 + rl_lhv="$(live_holder "$rl_old" "$rl_ids" 2>/dev/null)" || rl_lhrc=$? + case "$rl_lhrc" in + 8) : ;; + 0) + IFS="$US" read -r rl_hsid rl_htgt rl_hname rl_hpid rl_hverdict <<EOF +$rl_lhv +EOF + if [ "${rl_hverdict:-}" != here ]; then + die "a LIVE session holds lane $rl_old and it is not this window's: session $rl_hsid, pid $rl_hpid, named '${rl_hname:-none}', window ${rl_htgt:-none} (${rl_hverdict:-unknown}). Clause (a) refuses that, and clause (f) is why: the session's own NAME is locked to the lane (Amendment 12(h)) and only the session itself can change it, so a rename made from anywhere else leaves a running conversation named for a lane the register no longer has. Run \`lane-rename $rl_old $rl_new\` in THAT window, or hand the lane off first (\`lane-handoff\`) and rename it once it is paused. Nothing was written." 2 + fi ;; + *) die "could not read this workstation's session records for lane $rl_old: ${SESSION_FILES_ERR:-unknown error}. That is NOT 'no live session holds it' — clause (a) refuses on a LIVE holder, so a read that could not be made fails closed (R22). Fix the records or the permissions and re-run. Nothing was written." 1 ;; + esac + + # ---- THE FOUR PATHS, ALL COMPUTED BEFORE ANYTHING MOVES. + rl_log_new_rel="$(log_path_for "$rl_new")" + rl_log_new="$(log_file_for "$rl_new")" + # THE TARGET LOG IS LOOKED FOR UNDER ANY CASE, here and on `origin` + # (Copilot round 1 on openRepoTools#81). The exact-path test missed an + # orphan `lanes/log/<NEW>.md` of another spelling on a case-SENSITIVE + # filesystem — Linux and WSL2, where this estate runs — and a rename into it + # would leave two case-variant histories for one lane, which is the state + # Amendment 15(d) makes a hand merge. `log_files_named_ci` and the published + # `ls-tree` scan are the same two reads every other case question here uses. + rl_nlocal="$(log_files_named_ci "$rl_new")" + if [ -n "$rl_nlocal" ]; then + die "lane '$rl_new' has no row and this checkout already carries $(printf '%s\n' "$rl_nlocal" | tr '\n' ' ')— an object log under that name, in some case. That file is not this rename's to write into, and appending one lane's history to another's is the one thing an append-only log cannot be walked back from. Nothing was written." 2 + fi + if have_remote_ref; then + rl_npub="$(git -C "$LANES_REPO" ls-tree --name-only "origin/$LANES_BRANCH" -- "$LANES_LOG_PREFIX" 2>/dev/null \ + | awk -v want="$rl_log_new_rel" 'BEGIN { w = tolower(want) } tolower($0) == w')" + if [ -n "$rl_npub" ]; then + die "$(printf '%s\n' "$rl_npub" | tr '\n' ' ')is published on origin/$LANES_BRANCH while lane '$rl_new' has no row — renaming into it would merge two lanes' histories into one append-only file. Nothing was written." 2 + fi + fi + rl_lfhits="$(log_files_named_ci "$rl_old")" + rl_lfn="$(printf '%s' "$rl_lfhits" | grep -c . || :)" + if [ "$rl_lfn" -gt 1 ]; then + die "lane $rl_old has $rl_lfn object logs whose names differ only by case: $(printf '%s\n' "$rl_lfhits" | tr '\n' ' ')— one lane is ONE lane under any case and its log is ONE file (Amendment 15). Merge them by hand into $(log_file_for "$rl_old"), oldest lines first, remove the others in the same commit (15(d)), and re-run. Nothing was written." 2 + fi + rl_log_old=""; rl_log_old_rel="" + if [ "$rl_lfn" = 1 ]; then + rl_log_old="$rl_lfhits"; rl_log_old_rel="${LANES_LOG_PREFIX}${rl_log_old##*/}" + # A SYMLINK IS NOT THIS LANE'S LOG (Copilot round 4 on openRepoTools#81). + # `ls` lists one like any other file, `mv` moves the LINK, and + # `append_text_line`'s `>>` then writes the RENAMED line THROUGH it — into + # whatever is at the far end, which may be outside this repository + # altogether, while the commit records only the link. The same rule + # `openRepoTools --install` states for every target it places: `cp` + # follows a symlink, so a symlink is a refusal and not a file. + if [ -L "$rl_log_old" ]; then + die "lane $rl_old's object log at $rl_log_old is a SYMLINK. An append-only log is written in place — the RENAMED line would go through the link into whatever is at the far end, and the commit would record the link — so this rename is not made over one. Replace it with the file itself and re-run. Nothing was written." 2 + fi + # AND A REGULAR FILE, NOT MERELY NOT-A-SYMLINK (Copilot round 5). `ls` + # lists a FIFO like any other name, and the snapshot's `cat` of one BLOCKS + # — for ever, holding this lane's mutex — where a refusal costs a second. + if [ ! -f "$rl_log_old" ]; then + die "lane $rl_old's object log at $rl_log_old is not a regular file. An append-only log is read whole for the rollback copy and appended to in place, and neither can be done to that — a FIFO there would block this write, and its lock, indefinitely. Nothing was written." 2 + fi + # AND GIT MUST ALREADY KNOW IT (Copilot round 6 on openRepoTools#81). + # `refuse_dirty_checkout` reads `tracked_dirty`, which reports no untracked + # file, so a peer's uncommitted `lanes/log/<old>.md` walked past it — and + # this rename would MOVE that file to a path it always stages, committing + # somebody else's lines under its own message. Round 3 kept the old path + # out of the pathspecs when it was untracked, which stopped `git add` + # failing and did nothing about the content. + if [ "$NO_GIT" != 1 ] \ + && ! git -C "$LANES_REPO" ls-files --error-unmatch -- "$rl_log_old_rel" >/dev/null 2>&1; then + die "lane $rl_old's object log at $rl_log_old_rel exists here and git does not track it, so its lines have never been committed by anyone — and this rename would move them to $rl_log_new_rel and commit them under its own message. Whoever wrote them commits them first: \`git -C $LANES_REPO add -- $rl_log_old_rel && git -C $LANES_REPO commit -m \"handoff(<lane>@<workstation>): <what>\"\`. Nothing was written." 2 + fi + fi + if have_remote_ref; then + rl_pub="$(log_path_ci "$rl_old")" || die "lane $rl_old's object log is published twice (above), and one lane is ONE lane under any case: its log is ONE file (Amendment 15). Merge them by hand (15(d)) and re-run. Nothing was written." 2 + if [ "$rl_pub" != "$rl_log_old_rel" ] && git -C "$LANES_REPO" cat-file -e "origin/$LANES_BRANCH:$rl_pub" 2>/dev/null; then + die "lane $rl_old's object log is published as $rl_pub while this checkout has ${rl_log_old_rel:-no log for it at all}: a rename made from here would move one file and leave the other, which is two logs for one lane by the path \`ensure_log\` exists to close. Pull first — \`git -C $LANES_REPO pull --rebase\` — and re-run. Nothing was written." 2 + fi + fi + + # AND THE ALIAS TABLE `origin` CARRIES AND THIS CHECKOUT DOES NOT (Copilot + # round 3 on openRepoTools#81). The READ prefers `origin/<branch>`, while + # the APPEND is to the file on disk — so on a checkout that is behind, this + # would create a fresh table holding ONE mapping, and the commit would + # either drop every alias already published or meet an add/add conflict in + # its own rebase. Every name renamed before today would stop resolving, + # which is the one thing clause (e) promises never happens. The cure is the + # one the row and the log guards above already name. + # AND THE ALIAS TABLE IS A FILE, NOT A LINK (Copilot round 4). The append is + # a `>>`, which follows one: a live link would put this estate's permanent + # alias into an arbitrary target and a dangling one would create it, while + # git staged only the link path. + if [ -L "$LANES_ALIASES_TSV" ]; then + die "$LANES_ALIASES_PATH is a SYMLINK at $LANES_ALIASES_TSV. The alias row is appended in place and a redirect follows a link, so it would be written at the far end while this commit recorded the link — and the alias is the one thing that makes a renamed lane's old name resolve for ever (Amendment 16(e)). Replace it with the file itself and re-run. Nothing was written." 2 + fi + if [ -e "$LANES_ALIASES_TSV" ] && [ ! -f "$LANES_ALIASES_TSV" ]; then + die "$LANES_ALIASES_PATH at $LANES_ALIASES_TSV is not a regular file. The alias row is appended in place and the table is read whole for the rollback copy — a FIFO there would block this write, and its lock, indefinitely. Nothing was written." 2 + fi + # AN EXISTING UNTRACKED TABLE IS SOMEBODY'S HAND EDIT (Copilot round 5 on + # openRepoTools#81). `refuse_dirty_checkout` reads `tracked_dirty`, which + # deliberately omits untracked files — so before this estate's FIRST rename + # an untracked `lanes/aliases.tsv` walked past the guard and its contents + # were appended to and committed inside this lane's rename. The only writer + # of that file is this command, and this command commits what it writes, so + # an untracked one was written by hand or left by a run that died. + if [ "$NO_GIT" != 1 ] && [ -f "$LANES_ALIASES_TSV" ] \ + && ! git -C "$LANES_REPO" ls-files --error-unmatch -- "$LANES_ALIASES_PATH" >/dev/null 2>&1; then + die "$LANES_ALIASES_PATH exists here and git does not track it, so it was written by hand or left behind by a run that died — and appending this rename's alias to it would commit somebody else's lines inside this lane's commit. \`rename-lane\` is the only writer of that file and it commits what it writes. Commit it or remove it, and re-run. Nothing was written." 2 + fi + # AND A TABLE WHOSE LAST BYTE IS NOT A NEWLINE IS REFUSED (Copilot round 5). + # `append_text_line`'s `>>` would put this rename's record on the END of the + # previous line — and its own proof passes, because the bytes it builds to + # compare are concatenated the same way. The TSV parser then never sees the + # new alias at all: the rename would commit and the old name would not + # resolve, which is the one thing clause (e) promises. Refused rather than + # repaired, because appending a newline to a file this command did not write + # is an edit to somebody else's lines. + if [ -f "$LANES_ALIASES_TSV" ] && [ -s "$LANES_ALIASES_TSV" ] \ + && [ "$(tail -c 1 -- "$LANES_ALIASES_TSV" | od -An -c | tr -d ' ')" != '\n' ]; then + die "$LANES_ALIASES_PATH does not end with a newline, so appending this rename's record would join it to the last line and the table's own parser would never see the new alias — the rename would land and '$rl_old' would stop resolving (Amendment 16(e)). Put a newline at its end and re-run. Nothing was written." 2 + fi + if have_remote_ref && [ ! -f "$LANES_ALIASES_TSV" ] \ + && git -C "$LANES_REPO" cat-file -e "origin/$LANES_BRANCH:$LANES_ALIASES_PATH" 2>/dev/null; then + die "$LANES_ALIASES_PATH is published on origin/$LANES_BRANCH and this checkout does not have it, so appending here would write a table holding only this one rename and drop every alias already published — every name renamed before today would stop resolving (Amendment 16(e)). Pull first — \`git -C $LANES_REPO pull --rebase\` — and re-run. Nothing was written." 2 + fi + + # THE ROW, AND ITS TWO CELLS. Read before the lock because nothing between + # here and the write changes a byte of it — `capture_register_edit` and + # `handle_preexisting` commit what is already there, they do not edit it. + rl_n="$(row_line "$rl_old")" || exit 2 + rl_row="$(sed -n -e "${rl_n}p" "$LANES_FILE")" + case "$rl_row" in *"|"*) : ;; *) die "lane $rl_old's row (line $rl_n) has no '|' at all; refusing to touch it. Nothing was written." 2 ;; esac + rl_rest="${rl_row#*|}" + case "$rl_rest" in *"|"*) : ;; *) die "lane $rl_old's row (line $rl_n) has one cell and no second '|'; refusing to touch it. Nothing was written." 2 ;; esac + rl_head="${rl_row%%|*}|" + rl_cell="${rl_rest%%|*}" + rl_tail="|${rl_rest#*|}" + [ "$rl_head$rl_cell$rl_tail" = "$rl_row" ] || die "lane $rl_old's row (line $rl_n) does not reassemble from its first cell; refusing to touch it. Nothing was written." 2 + rl_tok="\`$rl_old\`" + case "$rl_cell" in + *"$rl_tok"*) : ;; + *) die "lane $rl_old's row (line $rl_n) does not spell its lane \`$rl_old\` in its first cell, so there is no key cell to rewrite. Nothing was written." 2 ;; + esac + # (b) THE KEY CELL. Prefix and suffix, never `${cell/"$old"/"$new"}`: BASH + # 3.2 keeps the quotes around the REPLACEMENT half as characters, which is + # what once wrote a whole register cell wrapped in double quotes on the + # macOS job (`replace-in-row` states the measurement). + rl_cpre="${rl_cell%%"$rl_tok"*}" + rl_cpost="${rl_cell#*"$rl_tok"}" + rl_newcell="$(rstrip_spaces "$rl_cpre\`$rl_new\`$rl_cpost") *(ex \`$rl_old\`, renamed $rl_utc)* " + rl_newrow="$rl_head$rl_newcell$rl_tail" + + # (d) THE HANDOFF CELL IS COUNTED FROM THE LEFT — awk field 7, the SIXTH + # cell — and never back from NF: the live register carries rows with a + # literal `|` inside a later cell, and counting back from the end puts the + # handoff two cells out on exactly those rows (`handoff_of_lane` says so at + # length). Six pipes consumed, then the cell, then the rest. + rl_pre=""; rl_rem="$rl_newrow"; rl_i=0 + while [ "$rl_i" -lt 6 ]; do + case "$rl_rem" in *"|"*) : ;; *) break ;; esac + rl_pre="$rl_pre${rl_rem%%|*}|"; rl_rem="${rl_rem#*|}"; rl_i=$((rl_i + 1)) + done + rl_hc=""; rl_hpost=""; rl_hsplit=0 + if [ "$rl_i" = 6 ]; then + case "$rl_rem" in + *"|"*) rl_hc="${rl_rem%%|*}"; rl_hpost="|${rl_rem#*|}"; rl_hsplit=1 ;; + esac + fi + [ "$rl_hsplit" = 1 ] && [ "$rl_pre$rl_hc$rl_hpost" = "$rl_newrow" ] || { + rl_hsplit=0 + note "lane $rl_old's row has fewer than seven '|' before its handoff column, so that column is left exactly as it is (Amendment 16(d) moves the file the row NAMES; this row names none in the place the header puts it)" + } + rl_hcell="" + [ "$rl_hsplit" = 1 ] && rl_hcell="$(printf '%s' "$rl_hc" | sed 's/^ *//; s/ *$//')" + rl_hpath_new="$rl_hcell"; rl_hmove=0 + if [ -n "$rl_hcell" ]; then + rl_hbase="${rl_hcell##*/}" + rl_hdir="${rl_hcell%"$rl_hbase"}" + # `session-handoff-<date>-lane-<old>.md` → the same date with + # `lane-<new>` (clause (d)). ANY OTHER SHAPE IS LEFT WHERE IT IS: a + # handoff not named for its lane has no `lane-<name>` in it to rename, + # and inventing one would move a file the row points at to a path the + # row's own history never named. Matched case-insensitively and cut by + # LENGTH, because `${x%$suffix}` cannot match a suffix of another case. + rl_hsuf="-lane-$rl_old.md" + # BOTH SIDES LOWER-CASED INTO VARIABLES FIRST, and the `case` reads them: + # a command substitution inside a case PATTERN is the shape bash 3.2 — + # the bash the macOS job parses every shipped file with — mis-parses at + # the first `)`, which is the rule `tests/test_repo_hygiene.py` holds for + # every file here. + rl_hb_lc="$(lc "$rl_hbase")" + rl_hs_lc="$(lc "$rl_hsuf")" + case "$rl_hb_lc" in + *"$rl_hs_lc") + rl_hkeep=$(( ${#rl_hbase} - ${#rl_hsuf} )) + if [ "$rl_hkeep" -gt 0 ]; then + rl_hpath_new="$rl_hdir${rl_hbase:0:$rl_hkeep}-lane-$rl_new.md" + rl_hmove=1 + fi ;; + esac + fi + rl_hfile=""; rl_hfile_new=""; rl_h_rel=""; rl_h_rel_new="" + if [ -n "$rl_hcell" ]; then + case "$rl_hcell" in + '~/'*) rl_hfile="$HOME/${rl_hcell#'~/'}"; rl_hfile_new="$HOME/${rl_hpath_new#'~/'}" ;; + /*) rl_hfile="$rl_hcell"; rl_hfile_new="$rl_hpath_new" ;; + *) rl_hfile="${LANES_REPO:+$LANES_REPO/}$rl_hcell"; rl_hfile_new="${LANES_REPO:+$LANES_REPO/}$rl_hpath_new" ;; + esac + # THE CONTAINMENT TEST IS PHYSICAL (Copilot round 5 on openRepoTools#81). + # A string prefix accepts `handoffs/../../outside/x.md` and accepts a path + # whose PARENT is a symlink out of the checkout — both of which resolve + # outside it, so the file would be moved and stamped before git refused + # the pathspec. The directory's own `cd -P` is the resolution + # `lane-start:2941` already makes for this very path, and for the same + # reason it gives: `readlink -f` is not in the stock macOS userland. + # + # THE QUESTION IS PUT TO THE NEAREST ANCESTOR THAT EXISTS, which is the + # rule `openRepoTools --install` already states for its own targets. A row + # names a handoff before anything writes one — `lane-start` puts the path + # in the row at the lane's first launch and `lane-handoff` creates the file + # (and its estate directory) at the first swap — so `cd -P` of the leaf + # directory fails for every lane that has not swapped yet, and taking that + # failure as "outside the workspace" refused the ordinary case. + if [ -n "${LANES_REPO:-}" ]; then + rl_repo_real="$( CDPATH=''; cd -P -- "$LANES_REPO" 2>/dev/null && pwd -P )" || rl_repo_real="$LANES_REPO" + rl_anc="$(dirname -- "$rl_hfile")"; rl_suffix=""; rl_hdir_real=""; rl_walk=0 + while [ "$rl_walk" -lt 64 ]; do + if [ -d "$rl_anc" ]; then + rl_hdir_real="$( CDPATH=''; cd -P -- "$rl_anc" 2>/dev/null && pwd -P )" || rl_hdir_real="" + break + fi + case "$rl_anc" in */*) : ;; *) break ;; esac + rl_suffix="${rl_anc##*/}${rl_suffix:+/$rl_suffix}" + rl_anc="${rl_anc%/*}" + [ -n "$rl_anc" ] || rl_anc=/ + rl_walk=$((rl_walk + 1)) + done + # A `..` AMONG THE COMPONENTS THAT DO NOT EXIST RESOLVES TO NOTHING, so + # it is refused rather than guessed at: the physical answer is only the + # ancestor's, and the suffix is taken literally. + case "/$rl_suffix/" in *"/../"*) rl_hdir_real="" ;; esac + if [ -n "$rl_hdir_real" ]; then + [ -n "$rl_suffix" ] && rl_hdir_real="$rl_hdir_real/$rl_suffix" + case "$rl_hdir_real/" in + "$rl_repo_real"/*) + rl_hreal="$rl_hdir_real/$(basename -- "$rl_hfile")" + rl_h_rel="${rl_hreal#"$rl_repo_real"/}" + rl_h_rel_new="${rl_h_rel%/*}/$(basename -- "$rl_hpath_new")" + case "$rl_h_rel" in */*) : ;; *) rl_h_rel_new="$(basename -- "$rl_hpath_new")" ;; esac ;; + esac + fi + fi + # A HANDOFF OUTSIDE THE WORKSPACE REPOSITORY IS A REFUSAL, NOT A NOTE + # (Copilot round 1 on openRepoTools#81). It used to be moved and stamped + # and then left OUT of the commit, because a git commit cannot carry a + # file outside its own checkout — so "four moves, one commit" was not true + # of that row, and a failure afterwards had nothing to roll the outside + # file back from. The register's handoff column is repo-relative + # everywhere this estate writes it (`handoffs/<estate>/…`, the path + # `lane-start` computes), so a row naming one elsewhere is a hand edit, + # and the exit is to put the file where the row's own convention puts it. + if [ -z "$rl_h_rel" ]; then + die "lane $rl_old's row names the handoff '$rl_hcell', which resolves to $rl_hfile — outside the workspace repository ${LANES_REPO:-<unknown>}. A rename is FOUR MOVES IN ONE COMMIT (Amendment 16), and a commit cannot carry a file outside its own checkout, so this one would be three moves and a note. Move that handoff under $LANES_REPO — \`handoffs/<estate>/session-handoff-<date>-lane-$rl_old.md\` is the path \`lane-start\` computes — point the row's handoff column at it, and re-run. Nothing was written." 2 + fi + # `-L` BESIDE `-e`, because `-e` IS FALSE ON A DANGLING LINK (Copilot + # round 5) — and `mv` would then replace that link, destroying a path this + # rename does not own, exactly as the source-side tests already say. + [ "$rl_hmove" = 1 ] && { [ -e "$rl_hfile_new" ] || [ -L "$rl_hfile_new" ]; } && \ + die "the handoff would move to $rl_hfile_new and something is already there. That path belongs to lane $rl_new's own handoff and is not this rename's to overwrite. Move it aside and re-run. Nothing was written." 2 + fi + # THE HANDOFF IS A PATHSPEC OF THIS COMMIT ONLY WHERE THERE IS A FILE TO + # COMMIT. `git add` FAILS on a pathspec matching nothing at all, and a row + # that names a handoff nobody ever wrote is ordinary — every lane has one + # until its first swap. A row that names one which cannot be READ is a + # different thing and is refused below, with the log already snapshotted. + # AND A PATH THAT EXISTS AND IS NOT A REGULAR FILE IS A REFUSAL, not a + # missing handoff (Copilot round 3 on openRepoTools#81). `-f` alone read a + # directory, a FIFO and a DANGLING SYMLINK as "the row names a handoff + # nobody wrote", so the rename committed the other three and left that path + # where it was. `-e` is false on a dangling link, which is why `-L` is asked + # beside it — the same pair `unplaceable_kind` in `openRepoTools` asks, for + # the same reason: `cat` through a dangling link CREATES the far end. + # A SYMLINK IS TESTED BEFORE `-f`, because `-f` is TRUE through one to a + # regular file (Copilot round 4 on openRepoTools#81) — and Rule 3's stamp is + # written with a redirect, which FOLLOWS it: the stamp would land in the + # link's target, possibly outside this repository, while the commit recorded + # the link and the rollback restored the wrong bytes. + if [ -n "$rl_hcell" ] && [ -L "$rl_hfile" ]; then + die "lane $rl_old's row names the handoff '$rl_hcell' and $rl_hfile is a SYMLINK. Rule 3's stamp is written in place and a redirect follows a link, so the stamp would land at the far end while this commit recorded the link (Amendment 16(d)). Point the row's column at the file itself and re-run. Nothing was written." 2 + fi + if [ -n "$rl_hcell" ] && [ ! -f "$rl_hfile" ] && [ -e "$rl_hfile" ]; then + die "lane $rl_old's row names the handoff '$rl_hcell' and $rl_hfile is not a regular file. A rename moves and STAMPS the handoff the row names (Amendment 16(d)), and neither can be done to that; nor is it the absent handoff an un-swapped lane has, which is passed over. Put a handoff there, or point the row's column at one, and re-run. Nothing was written." 2 + fi + rl_h_touch=0 + [ -n "$rl_h_rel" ] && [ -f "$rl_hfile" ] && rl_h_touch=1 + # AND AN UNTRACKED HANDOFF IS SOMEBODY'S UNCOMMITTED WORK (Copilot round 6). + # It is a pathspec of this commit the moment it exists, and `tracked_dirty` + # never reports it, so another lane's half-written handoff would be stamped + # and committed under this rename's message — which is the one thing + # `--no-sweep` was made the default for. + if [ "$rl_h_touch" = 1 ] && [ "$NO_GIT" != 1 ] \ + && ! git -C "$LANES_REPO" ls-files --error-unmatch -- "$rl_h_rel" >/dev/null 2>&1; then + die "the handoff at $rl_h_rel exists here and git does not track it, so its lines have never been committed by anyone — and this rename would stamp it, move it and commit it under its own message. Whoever wrote it commits it first: \`git -C $LANES_REPO add -- $rl_h_rel && git -C $LANES_REPO commit -m \"handoff(<lane>@<workstation>): <what>\"\`. Nothing was written." 2 + fi + + # ---- NOTHING ABOVE HAS WRITTEN A BYTE. The four moves follow, in one + # commit, in the order the amendment lists them. + rl_paths=("$LANES_PATH" "$rl_log_new_rel" "$LANES_ALIASES_PATH") + # THE OLD LOG IS A PATHSPEC ONLY WHERE GIT KNOWS IT (Copilot round 3 on + # openRepoTools#81). A TRACKED path that has been moved away still matches + # in the index and `git add` stages its deletion; an UNTRACKED one — the log + # an earlier write created and never committed — matches nothing once it is + # gone, and `git add` FAILS on a pathspec that matches nothing at all, + # which would end this write inside `commit_push` with all four moves on + # disk. Nothing in the index refers to it, so there is nothing to stage. + if [ -n "$rl_log_old_rel" ] && [ "$rl_log_old_rel" != "$rl_log_new_rel" ] \ + && { [ "$NO_GIT" = 1 ] || git -C "$LANES_REPO" ls-files --error-unmatch -- "$rl_log_old_rel" >/dev/null 2>&1; }; then + rl_paths+=("$rl_log_old_rel") + fi + if [ "$rl_h_touch" = 1 ]; then + rl_paths+=("$rl_h_rel_new") + [ "$rl_hmove" = 1 ] && rl_paths+=("$rl_h_rel") + fi + # THE ALIAS TABLE IS NOT EXEMPT FROM THE DIRTY-CHECKOUT REFUSAL (Copilot + # round 4 on openRepoTools#81). Every pathspec handed here is exempted, and + # `lanes/aliases.tsv` has ONE writer — this command — so a dirty one is not + # the ordinary mid-write state `lanes/LANES.md` is in half the day and there + # is no capture for it: exempted and uncaptured, a peer's half-finished + # rename would be appended to and swept into this lane's commit. So it is + # left OUT of the exemption list and the generic refusal names it. + rl_exempt=() + for rl_p in ${rl_paths[@]+"${rl_paths[@]}"}; do + [ "$rl_p" = "$LANES_ALIASES_PATH" ] && continue + rl_exempt+=("$rl_p") + done + refuse_dirty_checkout "rename lane $rl_old" ${rl_exempt[@]+"${rl_exempt[@]}"} "$LANES_PATH" + # THE CAPTURE IS GIVEN THE REGISTER AND NOTHING ELSE (Copilot round 3 on + # openRepoTools#81). `handle_preexisting` runs `git add -- <paths>` on the + # branch that captures a peer's uncommitted edit, and most of this write's + # pathspecs DO NOT EXIST YET — the new log, the alias table, the handoff's + # new name — so that `git add` would fail, the capture would not happen, and + # a peer's half-written row would be swept into this rename's commit. The + # register is the only file that can be dirty here at all: every OTHER + # tracked change was refused one line up, which is the same reasoning + # `capture_register_edit` states for its own single pathspec. + handle_preexisting "$LANES_PATH" + + # ---- THE SNAPSHOT, BEFORE THE FIRST BYTE. Every exit path from here to the + # commit restores it (`rename_undo`, hooked into `cleanup`), because the + # four moves are one act and a filesystem can refuse the third of them. + RL_SNAP="$(mktemp -d)" || die "no temporary directory could be made under ${TMPDIR:-/tmp}, and this write is not made without somewhere to put the copy that undoes it. Nothing was written." 1 + [ -n "$rl_log_old" ] && { cat -- "$rl_log_old" > "$RL_SNAP/log" || die "lane $rl_old's object log at $rl_log_old could not be read, so there is no copy to roll back to and this rename is not started. Nothing was written." 5; } + [ "$rl_h_touch" = 1 ] && { cat -- "$rl_hfile" > "$RL_SNAP/handoff" || die "the handoff at $rl_hfile is named by the row and could not be READ, so it can be neither stamped nor rolled back — and a rename that moved it unstamped is three moves and a half (Amendment 16(d)). Fix the permission, or point the row's column at a handoff that is there, and re-run. Nothing was written." 5; } + RL_ALIAS="$LANES_ALIASES_TSV"; RL_ALIAS_EXISTED=0 + if [ -f "$LANES_ALIASES_TSV" ]; then + RL_ALIAS_EXISTED=1 + cat -- "$LANES_ALIASES_TSV" > "$RL_SNAP/aliases" || die "$LANES_ALIASES_PATH is there and could not be read, so there is no copy to roll back to. Nothing was written." 5 + fi + # AND THE REGISTER IS IN THE SNAPSHOT TOO (Copilot round 4 on + # openRepoTools#81). `replace_line` cannot half-write it — it proves the new + # file before it writes a byte — but the row IS written before + # `commit_push`, and `commit_push` can die before it commits anything. The + # undo then put the other three back and left the row renamed: a split + # rename, which is the state this whole mechanism exists to prevent. + RL_REG="$LANES_FILE" + cat -- "$LANES_FILE" > "$RL_SNAP/register" || die "the register at $LANES_FILE could not be read, so there is no copy to roll back to. Nothing was written." 5 + RL_LOG_OLD="$rl_log_old"; RL_LOG_NEW="$rl_log_new" + RL_H_OLD=""; RL_H_NEW="" + RL_PATHS_FOR_UNDO=("${rl_paths[@]}") + RL_ACTIVE=1 + + # (c) THE LOG — moved, then appended to. The lines above the new one still + # say `lane <old>` and are NEVER rewritten (clause (c)): this file is + # append-only and those lines are what happened. `LOG_AWK` resolves the + # field on the way in, so every reader sees one lane. + if [ -n "$rl_log_old" ]; then + mv -- "$rl_log_old" "$rl_log_new" || die "could not rename $rl_log_old to $rl_log_new." 5 + note "$rl_log_old_rel → $rl_log_new_rel" + else + [ -d "$LANES_LOG_DIR" ] || mkdir -p -- "$LANES_LOG_DIR" + printf '# lane %s — object log (lane-collision-protocol Amendment 7)\n' "$rl_new" > "$rl_log_new" + note "created $rl_log_new_rel — lane $rl_old has no object log (a pre-cutover lane, Amendment 7(i)), so this RENAMED is its first line" + fi + rl_line="$(event_line RENAMED "$rl_new" "$rl_uuid" "$rl_utc" "lane:$rl_new" "←" "lane:$rl_old" "$rl_why")" + append_text_line "$rl_line" "$rl_log_new" + + # (d) THE HANDOFF — moved to the same date with `lane-<new>`, and stamped + # under its header block (Rule 3). THE FILE IS SPLICED AND NEVER REWRITTEN + # WHOLE, with the proof `lane-start` makes for its own `RESUMED by` stamp: + # one line in at the ruled position, and taking that line back out again + # gives the file back byte for byte. A handoff is the one document this + # protocol cannot afford to lose, and the act that dropped two lanes' rows + # on 2026-09-08 was a file written whole from what somebody remembered. + rl_hstamp="RENAMED from $rl_old by $rl_uuid (lane $rl_new) at $rl_utc" + rl_hdone=0 + if [ -z "$rl_hcell" ]; then + note "the row names no handoff, so there is none to move or stamp (Amendment 16(d))" + elif [ ! -f "$rl_hfile" ]; then + note "the handoff the row names is not at $rl_hfile, so nothing was moved or stamped and the row's handoff column is left exactly as it is. If it turns up, rename it — $rl_hcell → $rl_hpath_new — and stamp it: $rl_hstamp" + else + if [ "$rl_hmove" = 1 ]; then + RL_H_OLD="$rl_hfile"; RL_H_NEW="$rl_hfile_new" + mv -- "$rl_hfile" "$rl_hfile_new" || die "could not rename $rl_hfile to $rl_hfile_new." 5 + note "$rl_hcell → $rl_hpath_new" + rl_hdone=1 + else + rl_hfile_new="$rl_hfile" + RL_H_OLD="$rl_hfile"; RL_H_NEW="$rl_hfile" + note "the handoff $rl_hcell is not named \`…-lane-$rl_old.md\`, so it has no lane in its name to rename; it is stamped where it is (Amendment 16(d))" + fi + # A STAMP THAT CANNOT BE WRITTEN IS A REFUSAL (Copilot round 1 on + # openRepoTools#81). It used to be a `note`, and the rename went on to + # commit — leaving a handoff MOVED and UNSTAMPED, which is clause (d) done + # by half, in the one document Rule 3 says the next session reads first. + # The redirect is checked for the same reason: this file runs `set -u` and + # not `set -e`, so an unwritable handoff would otherwise reach the + # "stamped" note having written nothing. + rl_hat="$(awk 'NR > 1 && /^[[:space:]]*$/ { print NR; exit }' "$rl_hfile_new" 2>/dev/null || :)" + [ -n "$rl_hat" ] || rl_hat=1 + rl_htmpd="$(mktemp -d)" || die "no temporary directory could be made under ${TMPDIR:-/tmp} for the handoff's Rule 3 stamp." 1 + cat -- "$rl_hfile_new" > "$rl_htmpd/pre" 2>/dev/null || { rm -rf -- "$rl_htmpd"; die "the handoff at $rl_hfile_new could not be read, so Rule 3's stamp cannot be written and this rename is not made without it." 5; } + { head -n "$rl_hat" -- "$rl_htmpd/pre" + printf '%s\n' "$rl_hstamp" + tail -n "+$((rl_hat + 1))" -- "$rl_htmpd/pre" + } > "$rl_htmpd/out" + if [ "$(sed -n -e "$((rl_hat + 1))p" "$rl_htmpd/out")" != "$rl_hstamp" ] || + ! { head -n "$rl_hat" -- "$rl_htmpd/out"; tail -n "+$((rl_hat + 2))" -- "$rl_htmpd/out"; } | cmp -s - "$rl_htmpd/pre" + then + rm -rf -- "$rl_htmpd" + die "the handoff at $rl_hfile_new cannot take Rule 3's stamp without rewriting a byte of it, and a handoff written whole from anything but its own bytes is the act that lost two lanes' rows on 2026-09-08. The line it wants under its header block is: $rl_hstamp" 5 + fi + # AND THE STAMPED COPY REPLACES THE HANDOFF BY RENAME, NEVER THROUGH A + # REDIRECT INTO IT (opensoft/openRepoTools#158). `>` truncated the handoff + # before the first stamped byte was written, so a writer killed inside + # that `cat` — or a machine that lost power there — left a handoff cut + # short, and no undo reached it: `rename_undo` is a trap and SIGKILL runs + # none, so every later read took the short file for the handoff. The + # bytes now go to an exclusive temporary file BESIDE the handoff, in the + # physical directory it resolves to, with its mode (`cp -p` first), and + # `mv -f` replaces it in one rename: a reader sees the handoff whole + # before the stamp or whole after it. These are `publish-handoff`'s + # mechanics, inlined because that verb takes the lock this write already + # holds. The leaf is never a link — refused above, before the first byte + # — so replacing it rather than writing through it is the same file. + # `cleanup` removes the temporary on every handled exit; one a crash + # leaves is `<handoff>.rename.XXXXXX`, which no reader of `*.md` takes + # for a handoff. THIS MAKES THE STAMP ATOMIC, NOT THE RENAME: a crash + # between two of the four moves still leaves them apart. + rl_hpub="$( CDPATH=''; cd -P -- "$(dirname -- "$rl_hfile_new")" && pwd -P )" || { rm -rf -- "$rl_htmpd"; die "the directory of the handoff at $rl_hfile_new could not be resolved, so Rule 3's stamp cannot be published beside it and this rename is not made without it." 5; } + rl_hpub="$rl_hpub/$(basename -- "$rl_hfile_new")" + rl_htmp="$(mktemp "$rl_hpub.rename.XXXXXX")" || { rl_htmp=""; rm -rf -- "$rl_htmpd"; die "no temporary file could be made beside the handoff at $rl_hfile_new, and Rule 3's stamp is not written into a handoff in place. This rename is not made without it." 5; } + if ! cp -p -- "$rl_hpub" "$rl_htmp" || ! cat -- "$rl_htmpd/out" > "$rl_htmp" || ! mv -f -- "$rl_htmp" "$rl_hpub"; then + rm -f -- "$rl_htmp"; rl_htmp=""; rm -rf -- "$rl_htmpd" + die "the handoff at $rl_hfile_new could not be written, so Rule 3's stamp is not there and this rename is not made without it." 5 + fi + rl_htmp="" + rm -rf -- "$rl_htmpd" + note "handoff stamped at line $((rl_hat + 1)) of $rl_hpath_new: $rl_hstamp" + fi + # The row's handoff column follows the file, and only where the file + # actually moved: a column pointed at a path nothing moved to is a column + # that names a file that is not there. + if [ "$rl_hdone" = 1 ] && [ "$rl_hsplit" = 1 ]; then + rl_hc_pre="${rl_hc%%"$rl_hcell"*}"; rl_hc_post="${rl_hc#*"$rl_hcell"}" + rl_newrow="$rl_pre$rl_hc_pre$rl_hpath_new$rl_hc_post$rl_hpost" + fi + + # (e) THE ALIAS TABLE — the one write that makes the old name keep working, + # for ever and in every reader (clause (e)). + if [ ! -f "$LANES_ALIASES_TSV" ]; then + { printf '# lanes/aliases.tsv — lane-collision-protocol Amendment 16(e)\n' + printf '# <old lane>\t<new lane>\t<UTC of the rename>\n' + printf '# Appended by `lanes-edit.sh rename-lane` and by nothing else. Every reader of a\n' + printf '# lane name resolves through it, case-insensitively; a chain resolves to its end,\n' + printf '# stopping at any name that is a ROW again; a cycle is refused at write time; the\n' + printf '# LAST row for a key wins.\n' + } > "$LANES_ALIASES_TSV" || die "$LANES_ALIASES_PATH could not be created, and a rename without its alias row is a lane whose old name stops resolving (Amendment 16(e))." 5 + note "created $LANES_ALIASES_PATH" + fi + append_text_line "$(printf '%s\t%s\t%s' "$rl_old" "$rl_new" "$rl_utc")" "$LANES_ALIASES_TSV" + + # (b) THE ROW, LAST — so that a refusal anywhere above leaves the register + # itself untouched and `row_line` still finds the lane under its old name. + replace_line "$rl_n" "$rl_newrow" + + # EVERY ONE OF THE FOUR IS ON DISK — AND THE UNDO STAYS ARMED THROUGH THE + # COMMIT (Copilot round 3 on openRepoTools#81). It was cleared here, and + # `commit_push` can die on `update-index`, `git add` or `git commit` BEFORE + # any commit exists: the four files would then be left moved and modified + # with nothing to show for them, which is the half-renamed state this whole + # mechanism exists to prevent. + # + # WHAT DECIDES IS WHETHER A COMMIT WAS MADE, not where the failure happened. + # `rename_undo` compares HEAD against the sha taken here: unchanged means no + # commit carries this work and the four are restored; moved means the commit + # exists, the work is IN it, and `commit_push` owns the recovery from there + # — its exit 3 says so in its own words, and undoing a committed rename + # behind its back would be a second, inverse change nobody asked for. + RL_HEAD_BEFORE="$(git -C "$LANES_REPO" rev-parse HEAD 2>/dev/null || printf '')" + rl_msg="LANES($rl_new@$WS): RENAMED lane $rl_old → $rl_new (Amendment 16) — the row, $rl_log_new_rel, the handoff and $LANES_ALIASES_PATH in one commit" + [ -n "$PRE_DIRTY_LANES" ] && rl_msg="$rl_msg + sweeps uncommitted edit to row $PRE_DIRTY_LANES" + commit_push "$rl_msg" "${rl_paths[@]}" + rl_rc=$? + # `commit_push` RETURNED, so either it committed or it had nothing staged; + # every other outcome exits from inside it and is the trap's business. + RL_ACTIVE=0 + state_events_flush + lane_alias_flush + [ "$rl_rc" != 0 ] || lane_state_rename "$rl_lsr_old" "$rl_new" + release_lock + [ "$rl_rc" = 0 ] || exit "$rl_rc" + + rl_sha="$(git -C "$LANES_REPO" rev-parse HEAD 2>/dev/null || printf '')" + note "lane $rl_old is lane $rl_new (${rl_sha:-no sha}); '$rl_old' resolves to it for ever through $LANES_ALIASES_PATH" + + # (g) ONE COMMENT PER OBJECT THE LANE HOLDS — Amendment 7(b)'s partition, + # the same set `lane-end` refuses on and `who --lane` reports. Posted only + # AFTER the commit has landed and citing its sha, exactly as `claim`'s + # comment is, and skipped entirely by `--no-github`. + if [ "$NO_GITHUB" != 1 ]; then + rl_body="$(printf 'Lane %s renamed %s at %s (lane-collision-protocol Amendment 16). Lane: %s (%s)\n\nRecorded in `%s` at `%s`. `%s` resolves `%s` to `%s` for every reader of a lane name, so every earlier comment, line and branch naming the old lane still finds it.\n' \ + "$rl_old" "$rl_new" "$rl_utc" "$(lc "$rl_new")" "$rl_new" \ + "$rl_log_new_rel" "${rl_sha:-unknown}" "${LANES_ALIASES_PATH:-lanes/aliases.tsv}" "$rl_old" "$rl_new")" + rl_posted=0; rl_missed="" + while IFS="$US" read -r rl_outc rl_overb rl_oobj rl_oref rl_osup; do + [ -n "${rl_overb:-}" ] || continue + is_open_verb "$rl_overb" || continue + rl_url="$(gh_comment "$rl_oobj" "$rl_body" 2>/dev/null || :)" + if [ -n "$rl_url" ]; then + note "comment posted on $rl_oobj: $rl_url"; rl_posted=$((rl_posted + 1)) + else + rl_missed="$rl_missed $rl_oobj" + fi + done <<EOF +$(lane_objects "$rl_new" 2>/dev/null || :) +EOF + [ "$rl_posted" = 0 ] && [ -z "$rl_missed" ] && note "lane $rl_new holds nothing open, so there is no object to comment on (Amendment 16(g))" + [ -n "$rl_missed" ] && note "WARNING: the rename comment could not be posted on:$rl_missed. The commit IS the rename and it has landed; post them by hand so that a reader outside this estate can see it." + fi + note "THE WINDOW AND THE SESSION ARE NOT THIS WRITE'S (Amendment 16(f)): in the lane's own window, \`tmux rename-window $rl_new\` and \`/rename $rl_new\` typed into its pane. \`lane-rename\` does both when it is run there; from anywhere else the name guard renames the window at this lane's next prompt and types the \`/rename\` itself." + ;; + + # AMENDMENT 13(e) — THE MIGRATION. A DRY RUN unless `--yes` is passed, and one + # act on Brett Heap's word when it is (ratified decision O3). Everything it + # does is argued above `migrate_state_cells`. + migrate-state-cells) + msc_yes=0 + while [ $# -gt 0 ]; do + case "$1" in + --yes) msc_yes=1; shift ;; + --) shift ;; + *) die "usage: migrate-state-cells [--yes] — without --yes it is a DRY RUN that writes nothing; '$1' is neither" 2 ;; + esac + done + migrate_state_cells "$msc_yes" + ;; + + log) + lane="${LANES_LANE:-}" + [ -n "$lane" ] || die "log needs the lane: LANES_LANE=<lane> lanes-edit.sh log <VERB> <object> …" 2 + check_lane_name "$lane" + verb=""; obj_raw=""; ref=""; payload=""; text=""; home_override=""; utc_override="" + while [ $# -gt 0 ]; do + case "$1" in + --no-github) NO_GITHUB=1; shift ;; + # AMENDMENT 17, adoption act 7 — THE LATE RECORD'S OWN DATE, AND + # NOTHING ELSE USES IT. A `PAUSED` written after the fact for a swap + # that never ran names the moment the OLD SESSION ENDED, not the moment + # the shell writing it ran: `lane-handoff --late --at <UTC>` is the one + # caller, and its own rule is that the line may only be written where it + # is still the lane's last one (this log is append-only and FILE ORDER + # is what every state read means by "last"). The shape is checked here + # because a UTC field this parser cannot read is a line no reader can + # date — and the log is never rewritten. + --utc) utc_override="${2-}"; [ -n "$utc_override" ] || die "--utc needs a UTC instant" 2; shift 2 ;; + --utc=*) utc_override="${1#--utc=}"; [ -n "$utc_override" ] || die "--utc needs a UTC instant" 2; shift ;; + --home) home_override="${2-}"; [ -n "$home_override" ] || die "--home needs owner/repo" 2; shift 2 ;; + --home=*) home_override="${1#--home=}"; [ -n "$home_override" ] || die "--home needs owner/repo" 2; shift ;; + --text) text="${2-}"; shift 2 ;; + --text=*) text="${1#--text=}"; shift ;; + --) shift ;; + '→'|'->') ref="→"; payload="${2-}"; [ -n "$payload" ] || die "'$1' needs a payload after it" 2; shift 2 ;; + '←'|'<-') ref="←"; payload="${2-}"; [ -n "$payload" ] || die "'$1' needs a payload after it" 2; shift 2 ;; + -*) die "unknown option '$1' for log" 2 ;; + *) + if [ -z "$verb" ]; then verb="$1" + elif [ -z "$obj_raw" ]; then obj_raw="$1" + elif [ -z "$text" ]; then text="$1" + else die "log takes <VERB> <object> [→|← <payload>] [\"<free text>\"] — '$1' is one argument too many" 2 + fi + shift ;; + esac + done + [ -n "$verb" ] && [ -n "$obj_raw" ] || die "usage: log <VERB> <object> [→|← <payload>] [\"<free text>\"] ($VERB_LIST)" 2 + valid_verb "$verb" || die "'$verb' is not one of the Amendment 7 verbs ($VERB_LIST)" 2 + # The four verbs that have a subcommand of their own are NOT written by + # hand. `log CLAIMED` skipped the pre-check, the race and the rescan and + # `who` reported the result identically to a real claim; `log TAKEOVER` + # skipped the staleness test that is the only thing making a takeover + # legitimate. Refusing them here costs nothing that is actually needed. + case "$verb" in + CLAIMED) + die "a CLAIMED is not written by hand: it is Rule 1's act, and 'log' skips the pre-check, the race and the rescan. Use: LANES_LANE=$lane lanes-edit.sh claim $obj_raw" 2 ;; + TAKEOVER) + die "a TAKEOVER is not written by hand: it is only legitimate against a claim that is STALE, and that is the test 'log' does not make. Use: LANES_LANE=$lane lanes-edit.sh claim $obj_raw --force" 2 ;; + RELEASED) + die "a RELEASED is not written by hand: 'release' also posts the Rule 1 comment. Use: LANES_LANE=$lane lanes-edit.sh release $obj_raw \"<why>\"" 2 ;; + CLAIM-LOST) + die "a CLAIM-LOST is written by 'claim' when it loses the race for an object, and by nothing else — there is no hand-written form of losing a race" 2 ;; + HANDOFF-REQUESTED) + die "a HANDOFF-REQUESTED is not written by hand: it is clause (c)'s act, and 'log' skips the binding read that says there is anything to request, the pane it types into and the wait that follows. Use: $SELF request-handoff $lane" 2 ;; + # AMENDMENT 16 — AND A `RENAMED` IS NOT WRITTEN BY HAND EITHER, for the + # reason the amendment itself was drafted for: two lanes renamed + # themselves on 2026-09-14 by appending exactly this line and nothing + # else, and *"the lines are honest and they are all there is: the rows + # still carry the old keys, the logs and handoffs the old names"*. The + # line is one of four moves that are one commit, and `log` makes the + # other three of them not at all. + RENAMED) + die "a RENAMED is not written by hand: it is one of the FOUR moves of a rename — the row's key, this log's own name, the handoff and lanes/aliases.tsv — which land in ONE commit, refused or whole (Amendment 16). A line on its own is the 2026-09-14 hand rename this amendment exists to replace: honest, and all there is. Use: lane-rename ${obj_raw#lane:} <new name>" 2 ;; + esac + # R30 — THE FETCH COMES FIRST. `log` had no `log_sync` of its own at all: + # it read the STARTED line that REFUSES `--home` out of an `origin/<branch>` + # nothing here had moved, and the pull inside `commit_push` comes far too + # late to be that read. + log_sync + # AMENDMENT 15 — AFTER THE FETCH AND BEFORE EVERY READ AND WRITE BELOW IT. + # The resolver reads the PUBLISHED register (R19), so it is asked once + # `log_sync` has moved the ref — and what it answers is the lane this line + # is WRITTEN with, the file it is written to, and the commit subject. + lane="$(canon_lane "$lane")" || exit 2 + home="$(resolve_home "$lane" "$home_override")" || exit $? + obj="$(canon_object "$obj_raw" "$home")" || exit 2 + # AMENDMENT 13(b) — THE TWO NARRATIVE VERBS, AND WHAT EACH OF THEM TAKES. + # `NOTED` is a status note about the lane; `RULED` is a ruling recorded + # VERBATIM, with the object it bears on as its payload where there is one. + # Both are lane-kind lines in Amendment 7's own `STARTED`/`RESUMED` form — + # object `lane:<lane>`, one token — and neither is a transition, so no + # reader's state moves because one was written. They are the cell's old + # diary, in the file built to hold it. + if is_note_verb "$verb"; then + is_lane_object "$obj" || + die "'$verb' is a lane-kind line (Amendment 13(b)): its object is the LANE itself, lane:$lane, and not $obj. The object a ruling BEARS ON is its payload: LANES_LANE=$lane lanes-edit.sh log RULED lane:$lane → $obj \"<the words, verbatim>\"" 2 + # AND IT IS THIS LANE, NOT ANOTHER (Copilot round 5 on openRepoTools#82). + # `is_lane_object` reads the `lane:` prefix and nothing more, so + # `LANES_LANE=repoA … log NOTED lane:repoB` wrote a line into repoA's log + # whose object named repoB — a note about a lane in a file that is not its + # log, and `history repoB` would never show it. Clause (b) is explicit + # that these are "lane-kind lines whose object is the lane itself". + # COMPARED CASE-INSENSITIVELY, because `$lane` is already the row's own + # spelling and a caller may have typed another (Amendment 15). + [ "$(lc "${obj#lane:}")" = "$(lc "$lane")" ] || + die "'$verb' is a line about THIS lane, and its object is this lane: lane:$lane, not $obj (Amendment 13(b)). A note is written into the log of the lane it names, so an object naming another lane is a note nobody reading that lane's history would ever see. To say something about another lane, write it in the text; to record a ruling about an OBJECT, that object is the payload: LANES_LANE=$lane lanes-edit.sh log RULED lane:$lane → <object> \"<the words>\"" 2 + if [ -z "$text" ]; then + case "$verb" in + RULED) die "a RULED with no words is not a ruling. The text is the ruling, VERBATIM — it is what Amendment 13(b) put this verb in the log for: LANES_LANE=$lane lanes-edit.sh log RULED lane:$lane${payload:+ → $payload} \"<Brett Heap's words, verbatim>\"" 2 ;; + *) die "a NOTED with no text is a note with nothing in it. The text is what the line is FOR — it is the narrative the state cell used to carry (Amendment 13(a)): LANES_LANE=$lane lanes-edit.sh log NOTED lane:$lane \"<what the lane did, found, launched, left>\"" 2 ;; + esac + fi + case "$verb" in + NOTED) + [ -z "$payload" ] || + die "NOTED takes no payload: it is a note about the lane, and Amendment 13(b) gives it the object and the free text alone. Put it in the text — or, if it is a ruling about an object, write it as one: LANES_LANE=$lane lanes-edit.sh log RULED lane:$lane → $payload \"<the words>\"" 2 ;; + RULED) + if [ -n "$payload" ]; then + # `→` AND NOT `←`, because clause (b) spells the form `lane:<lane>[ → + # <object>]` and the arrow is the only thing that says which way the + # ruling points. AND THE OBJECT IS CANONICALISED like every other + # object this file writes (R20): a ruling recorded against `#29` in a + # lane whose home is `opensoft/openRepoTools` is a ruling about + # `opensoft/openRepoTools#29`, and one recorded against a legacy org + # spelling is a second key for one issue — which is the defect + # Amendment 7(a)'s alias table exists for. + [ "$ref" = '→' ] || + die "RULED's payload is the object the ruling bears on and it is introduced by → (Amendment 13(b)): 'log RULED lane:$lane → <object> \"<the words>\"'. '←' points the other way and means nothing here." 2 + payload="$(canon_object "$payload" "$home")" || exit 2 + fi ;; + esac + elif is_lane_verb "$verb"; then + is_lane_object "$obj" || die "'$verb' is a lane verb: its object is lane:<name>, not $obj" 2 + else + ! is_lane_object "$obj" || die "'$verb' is an object verb: lane:<name> is not one of its objects" 2 + fi + log_utc="$(utc_now)" + if [ -n "$utc_override" ]; then + # `--utc` IS THE LATE `PAUSED`'s SEAM AND HAS NO OTHER CALLER (Amendment + # 17, adoption act 7; Copilot round 2 on openRepoTools#47). The parser + # above takes the option for every verb and only its SHAPE was checked + # here, so a `STARTED` or a `RESUMED` could be dated by hand — and this + # log is append-only with FILE ORDER deciding which line is a lane's + # last, so a hand-dated line changes what every state read reports about + # a lane that is running. The one line that legitimately carries its own + # date is the record a swap never left, and `lane-handoff --late` has its + # own rule for when even that may be written. + [ "$verb" = PAUSED ] || die "--utc dates the LATE PAUSED that a swap never left (Amendment 17, adoption act 7) and nothing else — '$verb' is not one. Every other line is dated by the clock of the act that wrote it, because this log is append-only and a line dated by hand is a line whose order no reader can trust. Write it without --utc." 2 + case "$utc_override" in + [0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9]Z) log_utc="$utc_override" ;; + *) die "--utc takes a UTC instant spelled as this log spells it, YYYY-MM-DDTHH:MM:SSZ — '$utc_override' is not one, and a line nothing can date is a line no reader can order" 2 ;; + esac + fi + write_event "$lane" "$verb" "$obj" "$ref" "$payload" "$text" "$log_utc" "$(session_for "$lane")" + ;; + + claim) + lane="${LANES_LANE:-}" + [ -n "$lane" ] || die "claim needs the lane: LANES_LANE=<lane> lanes-edit.sh claim <object>" 2 + check_lane_name "$lane" + obj_raw=""; force=0; home_override="" + while [ $# -gt 0 ]; do + case "$1" in + --force) force=1; shift ;; + --no-github) NO_GITHUB=1; shift ;; + --home) home_override="${2-}"; [ -n "$home_override" ] || die "--home needs owner/repo" 2; shift 2 ;; + --home=*) home_override="${1#--home=}"; [ -n "$home_override" ] || die "--home needs owner/repo" 2; shift ;; + --) shift ;; + -*) die "unknown option '$1' for claim" 2 ;; + *) [ -z "$obj_raw" ] || die "claim takes exactly one object" 2; obj_raw="$1"; shift ;; + esac + done + [ -n "$obj_raw" ] || die "usage: claim <object> [--force] [--no-github] [--home owner/repo]" 2 + + # THE RACE IS DECIDED BY WHICH CLAIM LANDS ON main FIRST, and a rebase is + # what makes that decidable. Amendment 5(d) SKIPS the rebase when a peer + # has left uncommitted changes to other files in this shared checkout — a + # sensible default for a row edit, and unacceptable for a claim, which + # would then race unprotected. Refuse, and name the files — BEFORE the + # reads and before anything is written, and against exactly the pathspec + # this claim will write (the lane's log; a CLAIMED is not a LANDING). + # The register is exempt HERE and only here: write_event captures a peer's + # uncommitted `lanes/LANES.md` as its own commit and re-tests the checkout + # afterwards (R11), so a claim is not refused for the one file this + # checkout is dirty in most of the day. + # AND THE EXEMPTION IS A PATH, SO ITS AMBIGUITY IS THIS CLAIM'S (Copilot + # round 4): two logs differing only by case are a refusal, not a pathspec. + claim_log="$(log_path_ci "$lane")" || exit 2 + refuse_dirty_checkout claim "$claim_log" "$LANES_PATH" + + # 1. FETCH FIRST OF ALL — then resolve `--home` against the lane's STARTED + # line (R30), canonicalise the object, and pre-check against what has + # actually LANDED on main. Never against a working tree, which can be + # anything, and never against a log this checkout has not pulled: a home + # a peer recorded is on `origin/<branch>` and nowhere else here. + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + home="$(resolve_home "$lane" "$home_override")" || exit $? + obj="$(canon_object "$obj_raw" "$home")" || exit 2 + ! is_lane_object "$obj" || die "a lane is not a claimable object" 2 + takeover_payload=""; takeover_note=""; takeover_from=""; takeover_reason_phrase=""; takeover_dead="" + # CASE-INSENSITIVE, FOR THE SAME REASON THE KEY ABOVE IS LOWER-CASED + # (Amendment 15). This is the lane REMOVING ITSELF from the holders of the + # object it is about to claim, and the row it removes carries whatever + # spelling the winning line used. Byte for byte, a lane whose own earlier + # CLAIMED says `repohold-1` under the row `repoHold-1` is refused its own + # object. AND LITERAL rather than `grep -iv` (Copilot round 4): `repo.-1` + # excluding the rival `repoX-1` is a claim taken over a hold that is open. + held="$(state_events | lane_states_on "$obj" | holders_of "$obj" | rows_not_named "$lane" || :)" + if [ -n "$held" ]; then + who_object "$obj" || : + IFS="$US" read -r h_lane h_verb h_utc h_file h_line <<EOF +$(printf '%s\n' "$held" | head -n1) +EOF + if [ "$force" = 0 ]; then + die "lane $h_lane holds $obj ($h_verb, $h_utc). Rule 1: the lane stops and reports; it does not author a successor. If that claim is stale (CLAIMED on an issue, older than ${STALE_HOURS}h with no OPENED naming it), take it over with --force." 2 + fi + if [ "$(printf '%s\n' "$held" | grep -c .)" != 1 ]; then + die "--force takes over ONE stale claim, and $obj is held by $(printf '%s\n' "$held" | grep -c .) lanes" 2 + fi + # ISSUE #30 — a holder whose LANE is dead is takeable WHATEVER ITS VERB, + # bypassing both gates below: neither one was ever about the lane being + # gone, and a dead lane's OPENED PR has no CLAIMED to be stale in the + # first place. `holder_is_dead` is checked first and, alone, decides + # this branch; it is refused (as today) below wherever it says no. + if holder_is_dead "$h_lane"; then + takeover_from="$h_lane" + takeover_dead=1 + takeover_note="lane $h_lane is dead (log ends $HOLDER_DEAD_VERB, $HOLDER_DEAD_WHY, issue #30)" + # A DIFFERENT PHRASE FOR THE PUBLIC COMMENT (Copilot round 3, PR #61): + # the formatter below used to say every takeover was "of the stale + # claim" unconditionally, which is simply false for this branch — the + # object may be an OPENED PR that was never a CLAIMED issue to begin + # with, and even a CLAIMED one is takeable here whatever its age. The + # audit comment a person outside this estate reads must not misstate + # why. + takeover_reason_phrase=" (takeover of a dead lane's hold: $takeover_note)" + else + # AMENDMENT 18(b) — A TERMINAL LOG WHOSE LAST BINDING IS ANOTHER PLACE'S + # IS UNKNOWN, NEVER DEAD (Copilot on 8ce6c9d, PR #61), and it is + # refused here, ahead of the verb test and of Rule 1's age-only test, + # for the reason `HOLDER_TERMINAL_UNKNOWN` is below: this workstation + # could not establish that nothing still runs under that name, and the + # log is exactly the shape issue #30 distrusts enough to check. + if [ -n "$HOLDER_BOUND_ELSEWHERE" ]; then + die "--force refused: lane $h_lane's own log ends $HOLDER_TERMINAL_SEEN, but its last binding is on $HOLDER_BOUND_ELSEWHERE (host/container), and liveness is pronounced only from inside a binding's own host and container — from here it is UNKNOWN, never dead (Amendment 18(b)). Run this takeover from that host and container, or have the lane's holds released there. Rule 1: the lane stops and reports; it does not author a successor." 2 + fi + # OPENSOFT/OPENREPOTOOLS#67 — AND A REGISTER THAT COULD NOT BE READ IS + # REFUSED HERE TOO, ahead of the verb test, in its own words: the verb + # refusal below would blame a live session nobody looked for, and the + # `HOLDER_TERMINAL_UNKNOWN` one would put the failure on this + # workstation's session records, when what could not be read was the + # register — the row naming the ids to look for. + if [ -n "$HOLDER_REGISTER_UNREADABLE" ]; then + die "--force refused: lane $h_lane's own log ends $HOLDER_TERMINAL_SEEN, but the register (origin/$LANES_BRANCH:$LANES_PATH, or $LANES_FILE) could not be read, so the session ids lane $h_lane holds are not known and whether a live session on this workstation still backs it up was never checked. That is NOT 'it has no session ids' — an unreadable register never confirms a lane dead (issue #67). Fix the read and re-run. Rule 1: the lane stops and reports; it does not author a successor." 2 + fi + if [ "$h_verb" != CLAIMED ]; then + # NAMES ITS OWN VERB, NOT ONLY THE THREE THAT USED TO BE POSSIBLE + # HERE (Copilot round 8, PR #61): before issue #30, `$h_verb` could + # only be OPENED, LANDING or WITHDRAWN by the time this branch is + # reached (a live lane's own TAKEOVER on an object it still holds + # falls through the `!= CLAIMED` test the same way) — but a dead + # lane's own un-superseded TAKEOVER (an earlier stale-claim takeover + # this lane never followed with a CLOSED/RELEASED/LANDED) reaches + # here too when THIS lane is confirmed alive, and the enumeration + # left it unnamed. + die "--force takes over a stale CLAIMED and nothing else: $obj is $h_verb by lane $h_lane. An open TAKEOVER, OPENED, LANDING or WITHDRAWN is not a stale claim, and lane $h_lane's own log does not end on ENDED or RETIRED either (or a live session on this workstation still holds it)." 2 + fi + # A LIVE TERMINAL HOLDER IS REFUSED HERE, NOT ASKED WHETHER ITS CLAIM + # IS OLD (Copilot round 13, PR #61): `claim_is_stale` answers a claim's + # own AGE and has never known anything about the lane behind it — so a + # CLAIMED left by a lane whose own log says ENDED/RETIRED while a real + # session on this workstation still backs it up would read as an + # ORDINARY stale claim once old enough, and be taken over, which is + # exactly the collision issue #30 exists to stop (repoK-3's own shape, + # reached here only because ITS object happened to be OPENED rather + # than CLAIMED). `HOLDER_LIVE_TERMINAL` is the immediately-preceding + # `holder_is_dead` call's own tri-state answer for this lane; refused + # in these words rather than folded into the stale-claim message + # below, which is not why this one is refused. + if [ -n "$HOLDER_LIVE_TERMINAL" ]; then + die "--force refused: lane $h_lane's own log ends $HOLDER_LIVE_TERMINAL, but a live session on this workstation still backs it up — refused exactly as any other live holder's claim on $obj is. Rule 1: the lane stops and reports; it does not author a successor." 2 + fi + # AND AN UNREADABLE RECORDS TREE IS REFUSED THE SAME WAY, NEVER ASKED + # claim_is_stale's QUESTION INSTEAD (Copilot's own "closer look" on + # c82577e, PR #61): "I could not check whether a live session backs + # this terminal log up" is not "checked and clear" — every OTHER + # caller of `live_holder` already refuses on a read this workstation + # could not make, and a terminal log is exactly the shape this branch + # exists to distrust; falling through to an age-only test here would + # let a workstation with no session records at all force a takeover + # `holder_is_dead` itself never established was safe. + if [ -n "$HOLDER_TERMINAL_UNKNOWN" ]; then + die "--force refused: lane $h_lane's own log ends $HOLDER_TERMINAL_UNKNOWN, and this workstation could not read whether a live session still backs it up. That is NOT 'no live session holds it' — refused for the same reason an unreadable read refuses the dead-lane path (issue #30), never assumed safe. Rule 1: the lane stops and reports; it does not author a successor." 2 + fi + if ! claim_is_stale "$h_lane" "$obj" "$h_utc" "$h_file" "$h_line"; then + die "--force refused: lane $h_lane's claim on $obj is $(age_of "$h_utc") old (threshold ${STALE_HOURS}h), or it is a PR, or that lane has since OPENED a PR naming it. Rule 1 makes a claim takeable only when it is stale, and lane $h_lane's own log does not end on ENDED or RETIRED either (or a live session on this workstation still holds it)." 2 + fi + takeover_from="$h_lane" + takeover_note="stale claim by lane $h_lane, posted $h_utc, no PR after ${STALE_HOURS}h" + takeover_reason_phrase=" (takeover of the stale claim held by lane $takeover_from)" + fi + # THE LOOKUP NAMES A "CLAIMED —" COMMENT, SO IT ONLY ANSWERS FOR ONE + # (Copilot round 12, PR #61): a dead lane's OPENED/LANDING/WITHDRAWN/ + # TAKEOVER hold can carry an EARLIER claimed comment of its own, from + # before that lane progressed past it, and `gh_stale_claim_url` would + # happily hand back that superseded comment's URL — citing a claim that + # is not the hold this TAKEOVER displaces. Only a currently-CLAIMED hold + # is that comment's own hold; every other dead-lane verb takes the lane + # fallback, exactly as `--no-github` already does. + if [ "$NO_GITHUB" = 1 ] || [ "$h_verb" != CLAIMED ]; then + takeover_payload="lane:$h_lane" + else + takeover_payload="$(gh_stale_claim_url "$obj" "$h_lane")" + [ -n "$takeover_payload" ] || takeover_payload="lane:$h_lane" + fi + fi + + # 2. Rule 1's three reads, printed. + reads="$(gh_reads "$obj")" || exit 1 + printf '%s\n' "$reads" + + # 3. decision 2 — a crossing warns and proceeds. + cross_repo_warn "$(object_repo "$obj")" "$home" "$lane" + + # 4. append, commit, push. CP_AFTER_REBASE runs on every rebase inside the + # push loop: if another lane's claim is on the rebased history, theirs + # landed first and this one has lost. + uuid="$(session_for "$lane")" + utc="$(utc_now)" + CLAIM_OBJ="$obj"; CLAIM_LANE="$lane"; CLAIM_SKIP="$takeover_from"; CLAIM_SKIP_DEAD="$takeover_dead" + CLAIM_ABANDON_REVIVED="" + CP_AFTER_REBASE=claim_rescan_hook + # A line written with --no-github is NOT a Rule 1 claim until its GitHub + # comment exists, and it says so on its face rather than in a habit. + ng=""; [ "$NO_GITHUB" = 1 ] && ng="no-github" + if [ -n "$takeover_from" ]; then + write_event "$lane" TAKEOVER "$obj" "←" "$takeover_payload" "${ng:+$ng; }$takeover_note" "$utc" "$uuid" + else + write_event "$lane" CLAIMED "$obj" "" "" "$ng" "$utc" "$uuid" + fi + wrc=$? + CP_AFTER_REBASE="" + CLAIM_SKIP_DEAD="" + + # 5. lost: Rule 1 says the lane STOPS AND REPORTS. The claim is abandoned, + # never queued — Rule 7's queueing is for substrates, which this + # amendment does not touch. TWO CAUSES, TWO EXIT CODES (Copilot's own + # "closer look" on 21b8e82, PR #61): 7 is the documented, pre-existing + # CLAIM-LOST — a rival's claim landed on main first; 9 is issue #30's + # own dead-lane verdict failing to reconfirm before this takeover's + # push landed. Both write the same CLAIM-LOST event (this attempt did + # not succeed, in either cause), but automation reading the PROCESS + # exit must be able to tell them apart, so the exit is never coerced + # to 7 for the second. + if [ "$wrc" = 7 ] || [ "$wrc" = 9 ]; then + # "ALIVE AGAIN" ONLY WHERE IT WAS SEEN (Copilot on 05d7889, PR #61): + # `claim_rescan_hook` sets `CLAIM_ABANDON_REVIVED` for a confirmed + # revival — a live session now backs the lane, or its log moved past + # the terminal line — and leaves it empty where the verdict simply + # could not be reconfirmed (an unreadable log, or an unreadable + # records tree). The exit is 9 either way; only the words differ. + if [ "$wrc" = 9 ] && [ -n "$CLAIM_ABANDON_REVIVED" ]; then + note "TAKEOVER ABANDONED — lane $CLAIM_WINNER is alive again. Rule 1: stop and report; do not author a successor." + write_event "$lane" CLAIM-LOST "$obj" "→" "lane:$CLAIM_WINNER" "abandoned: $CLAIM_WINNER is no longer dead, takeover withdrawn before landing" "$(utc_now)" "$uuid" + elif [ "$wrc" = 9 ]; then + note "TAKEOVER ABANDONED — lane $CLAIM_WINNER's dead-lane verdict could not be reconfirmed before this push landed (above). Rule 1: stop and report; do not author a successor." + write_event "$lane" CLAIM-LOST "$obj" "→" "lane:$CLAIM_WINNER" "abandoned: the dead verdict on $CLAIM_WINNER could not be reconfirmed; takeover withdrawn before landing" "$(utc_now)" "$uuid" + else + note "CLAIM LOST — lane $CLAIM_WINNER's claim on $obj landed on main first. Rule 1: stop and report; do not author a successor." + write_event "$lane" CLAIM-LOST "$obj" "→" "lane:$CLAIM_WINNER" "abandoned: $CLAIM_WINNER landed its claim first" "$(utc_now)" "$uuid" + fi + who_object "$obj" || : + exit "$wrc" + fi + [ "$wrc" = 0 ] || exit "$wrc" + + # 6. the comment, AFTER the push, citing the commit that carries the line. + sha="$(git -C "$LANES_REPO" rev-parse HEAD 2>/dev/null || printf '')" + if [ "$NO_GITHUB" != 1 ]; then + body="$(printf '%s — lane %s, session %s@%s, %s, for %s\n\nLogged in `%s` at `%s`%s.\n\nThe three reads (lane-collision-protocol Rule 1):\n\n```text\n%s\n```\n' \ + "${takeover_from:+TAKEOVER}${takeover_from:-CLAIMED}" "$lane" "$uuid" "$WS" "$utc" "$obj" \ + "$(log_path_for "$lane")" "${sha:-unknown}" "$takeover_reason_phrase" "$reads")" + url="$(gh_comment "$obj" "$body" 2>/dev/null || :)" + if [ -n "$url" ]; then + note "comment posted: $url" + else + note "WARNING: the GitHub comment could not be posted. The log line IS the claim and it has landed; post the comment by hand so that a reader outside this estate can see it." + fi + fi + note "lane $lane now holds $obj (${sha:-no sha})" + ;; + + release) + lane="${LANES_LANE:-}" + [ -n "$lane" ] || die "release needs the lane: LANES_LANE=<lane> lanes-edit.sh release <object>" 2 + check_lane_name "$lane" + obj_raw=""; why=""; home_override="" + while [ $# -gt 0 ]; do + case "$1" in + --no-github) NO_GITHUB=1; shift ;; + --home) home_override="${2-}"; [ -n "$home_override" ] || die "--home needs owner/repo" 2; shift 2 ;; + --home=*) home_override="${1#--home=}"; [ -n "$home_override" ] || die "--home needs owner/repo" 2; shift ;; + --) shift ;; + -*) die "unknown option '$1' for release" 2 ;; + *) + if [ -z "$obj_raw" ]; then obj_raw="$1" + elif [ -z "$why" ]; then why="$1" + else die "release takes <object> [\"<why>\"]" 2 + fi + shift ;; + esac + done + [ -n "$obj_raw" ] || die "usage: release <object> [\"<why>\"] [--no-github] [--home owner/repo]" 2 + log_sync # R30 — the fetch, then --home and the STARTED line + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + home="$(resolve_home "$lane" "$home_override")" || exit $? + obj="$(canon_object "$obj_raw" "$home")" || exit 2 + ! is_lane_object "$obj" || die "a lane is not a releasable object" 2 + mine="$(state_events | lane_states_on "$obj" | awk -v sep="$US" -v lane="$lane" 'BEGIN{FS=sep} tolower($2) == tolower(lane)' || :)" + if [ -z "$mine" ]; then + note "NOTE: this lane has no line on $obj — releasing anyway, and the log will show that it did." + else + IFS="$US" read -r m_utc m_lane m_verb m_rest <<EOF +$mine +EOF + is_open_verb "$m_verb" || note "NOTE: this lane's last line on $obj is $m_verb, which is not an open state — releasing anyway." + fi + uuid="$(session_for "$lane")" + utc="$(utc_now)" + write_event "$lane" RELEASED "$obj" "" "" "$why" "$utc" "$uuid" || exit $? + if [ "$NO_GITHUB" != 1 ]; then + url="$(gh_comment "$obj" "$(printf 'RELEASED — lane %s, session %s@%s, %s, for %s%s\n' \ + "$lane" "$uuid" "$WS" "$utc" "$obj" "${why:+ — $why}")" 2>/dev/null || :)" + [ -n "$url" ] && note "release comment posted: $url" + fi + note "lane $lane released $obj" + ;; + + who) + mode="object"; arg=""; home_override="" + while [ $# -gt 0 ]; do + case "$1" in + --lane) mode="lane"; arg="${2-}"; [ -n "$arg" ] || die "--lane needs a lane name" 2; shift 2 ;; + --lane=*) mode="lane"; arg="${1#--lane=}"; [ -n "$arg" ] || die "--lane needs a lane name" 2; shift ;; + --landing) mode="landing"; arg="${2-}"; [ -n "$arg" ] || die "--landing needs owner/repo" 2; shift 2 ;; + --landing=*) mode="landing"; arg="${1#--landing=}"; [ -n "$arg" ] || die "--landing needs owner/repo" 2; shift ;; + --home) home_override="${2-}"; [ -n "$home_override" ] || die "--home needs owner/repo" 2; shift 2 ;; + --home=*) home_override="${1#--home=}"; [ -n "$home_override" ] || die "--home needs owner/repo" 2; shift ;; + --no-fetch) LANES_NO_FETCH=1; shift ;; + --) shift ;; + -*) die "unknown option '$1' for who" 2 ;; + *) [ -z "$arg" ] || die "who takes one argument" 2; arg="$1"; shift ;; + esac + done + [ -n "$arg" ] || die "usage: who <object> | who --lane <lane> | who --landing owner/repo" 2 + log_sync + case "$mode" in + lane) arg="$(canon_lane "$arg")" || exit 2 # Amendment 15 + who_lane "$arg" || exit $? ;; + landing) + wl_repo="$(alias_lookup "$arg" 2>/dev/null || :)"; wl_repo="${wl_repo:-$arg}" + case "$wl_repo" in */*) : ;; *) die "--landing needs owner/repo (or an alias in ${LANES_LOG_PREFIX%log/}repos.tsv); '$arg' is neither" 2 ;; esac + who_landing "$wl_repo" || exit $? ;; + *) + home="$(resolve_home "${LANES_LANE:-}" "$home_override")" || exit $? + obj="$(canon_object "$arg" "$home")" || exit 2 + who_object "$obj" || exit $? ;; + esac + ;; + + # ------------------------------------------- Amendment 8: swap and restart + + # Read-only. Exit 0 with rows, 8 with none — 8 is "no record" here exactly as + # it is everywhere else, so a launcher may gate on it. + # `swapped` EXITS 64 ON A USAGE ERROR OF ITS OWN, never the dispatcher's 2 + # (clause (c); F-B8, F-W4). The launcher gates its whole Amendment 8 degrade + # on this subcommand's 2 meaning ONE thing — "this `lanes-edit.sh` predates + # Amendment 8 and has no `swapped`" — and the dispatcher's unknown-subcommand + # 2 is exactly that. A caller's own bug must not be indistinguishable from an + # old helper at the one place the degrade is decided, so it gets a code of its + # own: 0 rows, 8 none swapped, 64 a bad call, 2 no such subcommand. + swapped) + sw_arg="" + while [ $# -gt 0 ]; do + case "$1" in + --) shift ;; + -*) die "unknown option '$1' for swapped (usage: swapped [<workstation>])" 64 ;; + *) [ -z "$sw_arg" ] || die "swapped takes at most one workstation: swapped [<workstation>]" 64 + sw_arg="$1"; shift ;; + esac + done + log_sync + # SEVEN FIELDS SINCE AMENDMENT 17(b), and the `NF >= 4` gate is unchanged: + # it is the shape test for a row that got as far as carrying a window, not a + # count of the fields a row has. `$7` and `$8` are the agent and its + # transcript, EMPTY for every record written before that amendment. + sw_out="$(swapped_lanes "${sw_arg:-$WS}" \ + | LC_ALL=C sort -t"$US" -k1,1 -k3,3r -k2,2 \ + | awk -v sep="$US" 'BEGIN { FS = sep; OFS = "\t" } NF >= 4 { print $2, $3, $4, $5, $6, $7, $8 }')" + if [ -z "$sw_out" ]; then + note "no lane on ${sw_arg:-$WS} is swapped — no lane's LAST lane-kind line is a PAUSED whose payload begins 'swap;' and names that workstation" + exit 8 + fi + printf '%s\n' "$sw_out" + ;; + + # The SessionStart hook. IT NEVER WRITES, IT NEVER TOUCHES THE NETWORK, AND + # IT ALWAYS EXITS 0 — the three properties that make it safe to put in front + # of every session on this workstation. Its stdin is the hook's JSON; with a + # terminal on stdin nobody piped one, and it is read as empty rather than + # waited for, because a hook that blocks is worse than a hook that says + # nothing. + # + # AMENDMENT 8, R-A8-1 — THERE IS NO `log_sync` HERE, AND THERE MUST NOT BE. + # This branch used to fetch: `log_sync` runs `remote_has_branch` (an + # `ls-remote`) and then a `fetch`, two network round-trips bounded at 60 s + # EACH, in front of every session start on the workstation — writing + # `.git/FETCH_HEAD`, objects and `refs/remotes/origin/main`, and advancing + # `origin/main` under any `lane-start` running at the same time. Amendment 7's + # "a read fetches first" governs STATE decisions (a claim, a refusal, who + # holds what); this is an informational block printed at every session start, + # and it must be fast and offline-safe instead. It reads the checkout AS LAST + # FETCHED and says how old that is, so a reader can tell a current answer from + # a stale one. `git_net` is the only door to the network in this file, and + # nothing on this path opens it. + session-start) + if [ -t 0 ]; then ss_json=""; else ss_json="$(cat 2>/dev/null || :)"; fi + ss_win="" + command -v tmux >/dev/null 2>&1 && ss_win="$(tmux display-message -p '#W' 2>/dev/null || :)" + session_start_block "$ss_json" "$ss_win" || : + exit 0 + ;; + + # AMENDMENT 12 — THE `UserPromptSubmit` HOOK. The ONE surface in this file + # that refuses a person's work, and the only one whose exit code is read by + # the harness rather than by a script: 2 BLOCKS the prompt and its stderr is + # what the person sees (code.claude.com/docs/en/hooks). Every other code lets + # the prompt through, which is why every refusal below is a 2 and why this + # verb is exempt from the dispatcher's `die … 1` above. + # + # AN ARGUMENT IS A USAGE REFUSAL AND NOT A SHRUG: a hook configured with a + # stray word is a hook nobody has checked, and passing the prompt through on + # one is exactly the silence Amendment 12 exists to end. + guard) + [ "$#" -eq 0 ] || die "usage: guard (the UserPromptSubmit hook; the hook's JSON on stdin)" 2 + if [ -t 0 ]; then g_json=""; else g_json="$(cat 2>/dev/null || :)"; fi + # IN A SUBSHELL, AND EVERY CODE BUT 0 IS A 2. This is clause (d) — *"fail + # CLOSED"* — made true of the guard's OWN failures and not only of the + # reads it makes, and it is here because the alternative was measured: + # `transcript_holders` left `th_here_prof` unset, `set -u` (line 292) took + # the whole shell down at the first record that was not this window's, and + # `lanes-edit.sh guard` exited 1. A 1 does not block a `UserPromptSubmit` + # — only 2 does — so the one defect this guard cannot have, a guard that + # lets a prompt through in silence, is exactly what a fatal inside it + # produced. The subshell contains it: `guard_run`'s effects are on the + # filesystem (the offer file, `lane-start`, the register) and on stderr, + # all of which cross it, and the only thing lost is shell state nothing + # reads afterwards. + # + # A `die` reached from one of the reads it makes is caught the same way, + # which is why the arm maps EVERY unexpected code rather than listing the + # ones known today. + g_rc=0 + ( guard_run "$g_json" ) || g_rc=$? + case "$g_rc" in + 0 | 2) exit "$g_rc" ;; + *) note "THE NAME GUARD ITSELF FAILED (exit $g_rc), so the three names were not verified — and a triple that cannot be verified is not a triple that agrees (Amendment 12(d)). This prompt is refused rather than let through, because only a 2 blocks one and a guard that fails open is the silence this amendment exists to end. $(guard_bypass)" + exit 2 ;; + esac + ;; + + # --- internal reads, for lane-start and lane-end ------------------------- + # Not part of the protocol's surface: they exist so that the two boundary + # scripts share ONE implementation of liveness and ONE parser of the log, + # instead of carrying copies that drift apart. + # Both answer with 8 for "there is no such record", the same 8 `who` uses, + # and with anything else ONLY when they failed. `lane-start` and `lane-end` + # treat 0 and 8 as answers and every other code as a refusal, because the + # first version of this returned 1 for both and both scripts read 1 as "no + # holder" / "pre-cutover lane" — a broken helper turned a refusal into a + # silent pass, which is the one thing a boundary act must never do. + # 0 prints `<uuid> <tmux> <name> <pid> <here|elsewhere|orphan>`, US-separated. + # The fifth field is Amendment 8 ruling (g)'s: the caller must not have to + # infer whose session it is from the `tmux` column, because a record with no + # target is not a record in no window, and reading it as one is what refused + # this lane the window it was running in. + # AMENDMENT 8(f), R-A8-6 — the row's EARLIER ids, and who is still holding + # them. Read-only, no fetch of its own (the caller has just made one), and it + # runs nothing: `lane-end <lane> --retire <pid|uuid>` is printed by the caller + # and typed by a person (clause (k) rule (e)). + # 0 with rows, 8 with none, 1 where the records could not be read — the same + # three answers `live-holder` gives, so a caller reads them the same way. + idle-holders) + lane="${1-}"; [ -n "$lane" ] || die "usage: idle-holders <lane>" 2 + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + idle_holders "$lane"; ih_rc=$? + case "$ih_rc" in + 0) : ;; + 8) exit 8 ;; + *) die "could not read this workstation's session records for lane $lane: ${SESSION_FILES_ERR:-unknown error}." 1 ;; + esac + ;; + + live-holder|lane-holders) + lane="${1-}"; [ -n "$lane" ] || die "usage: live-holder <lane>" 2 + # A READ FETCHES FIRST, like every other read here. This one did not, and + # "the published row" then meant whatever `origin/<branch>` happened to say + # when this checkout last pulled: a session started from another clone on + # this workstation stamps its uuid on the row, and until something unrelated + # fetched, the rename gate could not see it and answered 8 — a rename into a + # name that is held, which is what mints `<lane> (2)`. The fetch can only + # ADD ids, and an id is only ever a reason to refuse. + log_sync + # The id SET is the published row's union the working tree's (R25): this is + # the boundary read that decides whether a window may take a name, and an id + # only ever adds a reason to refuse. + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + lh_ids="$( { session_ids_of_lane "$lane" 2>/dev/null || : + session_ids_local_of_lane "$lane" 2>/dev/null || :; } | awk 'NF && !seen[$0]++')" + # DECISION 8(e) — A `--fork-session` OF THIS LANE'S TRANSCRIPT IS NEVER A + # HOLDER, AND SAYING SO IS PART OF THE ANSWER. `live_holder` already + # answers only about ids the ROW carries, so a fork — which has a new id + # and the lane's title — cannot be returned by it and could pass unseen. + # Amendment 8 ruling (g) skipped a `kind: bg` companion; Evidence 6's fork + # was one AND was orchestrating, so the rule is extended to forks BY ID. + # The note is on stderr, so the 0/8 contract this read's two callers gate + # on is untouched. + lh_fk=""; lh_fkrc=0 + lh_fk="$(lane_forks "$lane" 2>/dev/null)" || lh_fkrc=$? + # ON STDERR, like the DEFECT line below it, so the 0/8 contract this read's + # two callers gate on is untouched — and said at all, because a fork check + # that could not be made is not a lane with no fork (#26, `37632b1`). + case "$lh_fkrc" in + 0 | 8) : ;; + *) note "this workstation's session records could not be read, so whether a live FORK of lane $lane's transcript is running is NOT established — which is not the same as none. See: lanes-edit.sh forks $lane" ;; + esac + if [ -n "$lh_fk" ]; then + while IFS="$(printf '\t')" read -r lh_fid lh_fpid lh_fkind lh_fcwd; do + [ -n "${lh_fid:-}" ] || continue + note "DEFECT: $lh_fid is a live FORK of lane $lane's transcript (pid $lh_fpid, ${lh_fkind:-interactive}, cwd ${lh_fcwd:-unknown}) — it is NOT a holder of this lane and must not write the register. Retire it: lane-end $lane --retire $lh_fpid" + done <<EOF +$lh_fk +EOF + fi + lh_all=""; [ "$cmd" != lane-holders ] || lh_all=all + live_holder "$lane" "$lh_ids" "$lh_all"; lh_rc=$? + case "$lh_rc" in + 0) : ;; + 8) exit 8 ;; + *) die "could not read this workstation's session records for lane $lane: ${SESSION_FILES_ERR:-unknown error}. That is NOT 'no live session holds it' — fix the records or the permissions and re-run." 1 ;; + esac + ;; + + # AMENDMENT 8 — which LIVE session is in a tmux WINDOW, keyed on the window + # and not on a lane's recorded ids. `lane-start` asks it about the window it + # is run in, because the harness mints a new transcript uuid with nobody + # acting and that id is in no row for `live-holder` to find. 0 with + # `<uuid> <tmux> <name> <pid> <profile>` (US-separated), 8 when the records + # were read and no live one is in that window, 1 when they could not be read. + window-session) + wsub="${1-}"; [ -n "$wsub" ] || die "usage: window-session <tmux session>:<window id>" 2 + window_session "$wsub"; wsub_rc=$? + case "$wsub_rc" in + 0) : ;; + 8) exit 8 ;; + *) die "could not read this workstation's session records for window $wsub: ${SESSION_FILES_ERR:-unknown error}. That is NOT 'no live session is in that window'." 1 ;; + esac + ;; + + # ------------------------- AMENDMENT 18(h): ONE LIVE PROCESS PER TRANSCRIPT + # + # THREE CALLERS AND ONE IMPLEMENTATION — `lane-start` before it binds or + # resumes an id, `lane-end --retire <pid>` when the duplicate's id is the + # ROW'S OWN (opensoft/openRepoTools#39), and the prompt `guard`. It answers + # about ONE transcript and says, per live process, where it is and whether it + # is THIS window's: + # + # <pid><TAB-as-US><kind><US><tmux|none><US><profile><US><where><US><here|other><US><record file> + # + # 0 with rows, 8 with none, 1 where the records could not be read, 64 usage. + # The 1 is the fail-closed one: a caller that read it as 8 would bind a + # transcript two processes hold, which is the whole defect. + transcript-holders) + thub="${1-}"; [ -n "$thub" ] || die "usage: transcript-holders <session uuid>" 64 + transcript_holders "$thub"; thub_rc=$? + case "$thub_rc" in + 0) : ;; + 8) exit 8 ;; + 64) die "usage: transcript-holders <session uuid>" 64 ;; + *) die "could not read this workstation's session records for session $thub: ${SESSION_FILES_ERR:-unknown error}. That is NOT 'no other live process carries it', and a caller that read it as one would bind a transcript two processes hold." 1 ;; + esac + ;; + + # ---------------------- AMENDMENT 18(b): THE BINDING, AS A READ + # + # `binding <lane>` — WHERE THIS LANE IS, and whether this place may pronounce + # on it. Eight tab-separated fields; the FIRST FOUR are the contract + # opensoft/openRepoTools#38 act 2 states and the rest are grown at the end, + # this file's rule for a read that gains a field (`swapped_lanes`'s sixth and + # seventh say why): + # + # <host> <container> <window> <utc> <session> <os> <here|elsewhere> <window state> + # + # here / elsewhere whether THIS process is inside the binding's own host + # and container — the only place liveness may be + # pronounced from (clause (b)). From `elsewhere` a + # binding is UNKNOWN and never dead, whatever `kill -0` + # says, because a pid does not cross a pid namespace. + # window state `live`, `gone` or `unknown`. `gone` is clause (b)'s one + # exception and is answered only where the HOST matches, + # because that is what makes the tmux server shared; it + # is the takeover path (opensoft/openRepoTools#30) and + # the one way a binding reads dead from another container. + # + # 0 BOUND · 8 FREE (the last lane-kind line released it, or there is none) · + # 1 the log could not be read, which is never "this lane is free" (Amendment + # 7(d)) · 64 a usage error of its own. + binding) + lane="${1-}"; [ -n "$lane" ] || die "usage: binding <lane>" 64 + [ "$#" -le 1 ] || die "binding takes one lane: binding <lane>" 64 + check_lane_name "$lane" + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + bd_out=""; bd_rc=0 + bd_out="$(lane_binding_scan "$lane")" || bd_rc=$? + [ "$bd_rc" = 0 ] || die "binding could not read lane $lane's object log (exit $bd_rc). That is NOT 'this lane is free' — a read that failed is never an answer (Amendment 7(d)), and a caller that took it as one would start a second session on a lane another place is holding." 1 + # EVERY FIELD IS NAMED, and the last name is the last field: `read` puts + # what is left into its final variable, so a name short of the emit is a + # variable carrying four more fields glued on by `$US` — and `bd_legacy` + # then reads `legacy` plus four separators, which is not `legacy`, and the + # cutover rule below silently stops firing. Measured by the suite, on + # `lane-start --dry-run repoA11 7`: a pre-amendment binding on this very + # workstation read as another container's. + IFS="$US" read -r bd_state bd_host bd_cont bd_win bd_utc bd_sess bd_os \ + bd_rutc bd_rsess bd_rpay bd_xverb bd_xutc bd_xsess bd_xpay bd_legacy \ + bd_fverb bd_futc bd_fsess bd_fpay <<EOF +$bd_out +EOF + case "$bd_state" in + bound|requested) : ;; + *) exit 8 ;; + esac + bd_where=elsewhere + binding_is_here "$bd_host" "$bd_cont" "$bd_legacy" && bd_where=here + printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' \ + "${bd_host:-unknown}" "${bd_cont:-none}" "${bd_win:-none}" "${bd_utc:-unknown}" \ + "${bd_sess:-unknown}" "${bd_os:-unknown}" "$bd_where" "$(binding_window_state "$bd_host" "$bd_win" "$bd_legacy")" + ;; + + # ------------- AMENDMENT 18(c)/(e): ASK THE BINDING TO HAND OFF, THEN WAIT + # + # request-handoff <lane> [--wait <s>] [--session <uuid>] [--no-wait] + # [--force "<why>"] [--dry-run] + # + # THE WHOLE OF CLAUSE (c)'s MECHANISM, in the order the clause states it: the + # line is written and PUSHED first, so a bound session anywhere reads it from + # `origin`; then — and only where the bound pane is on THIS tmux server — + # `/handoff --exit requested by <uuid>@<host>/<container>` is typed into it + # (Amendment 12's M1, the one mechanism a running session has); then the + # requester WAITS for a `PAUSED`, `ENDED` or `RETIRED` newer than its request. + # + # `--force` IS CLAUSE (e) AND IS A SECOND INVOCATION, NEVER AUTOMATIC: it + # writes the release ON THE BOUND SESSION'S BEHALF, in the REQUESTER'S OWN + # session field — *"so it is not impersonation (the retired-lane release of + # 2026-09-13, opensoft/openRepoTools#30, is the precedent)"* — and asks for + # nothing. It takes a WHY, because the bound session, if it is alive after all, + # is going to read that sentence at its next prompt and refuse every prompt + # from then on. + # + # EXIT CODES, this file's family: 0 THE LANE IS FREE — bind it · 2 the wait + # ended with nothing, or the request was refused · 8 the lane was already free + # · 1 a read failed, which is never "the lane is free" · 64 usage. + request-handoff) + lane="${1-}"; [ -n "$lane" ] || die "usage: request-handoff <lane> [--wait <s>] [--session <uuid>] [--force \"<why>\"] [--dry-run]" 64 + shift + rh_wait=300; rh_sess=""; rh_force=0; rh_dry=0; rh_why="" + while [ $# -gt 0 ]; do + case "$1" in + --wait) rh_wait="${2-}"; [ -n "$rh_wait" ] || die "--wait needs a number of seconds" 64; shift 2 ;; + --wait=*) rh_wait="${1#--wait=}"; [ -n "$rh_wait" ] || die "--wait needs a number of seconds" 64; shift ;; + --no-wait) rh_wait=0; shift ;; + --session) rh_sess="${2-}"; [ -n "$rh_sess" ] || die "--session needs a transcript uuid" 64; shift 2 ;; + --session=*) rh_sess="${1#--session=}"; [ -n "$rh_sess" ] || die "--session needs a transcript uuid" 64; shift ;; + --force) rh_force=1; shift ;; + --dry-run) rh_dry=1; shift ;; + --) shift; while [ $# -gt 0 ]; do rh_why="${rh_why:+$rh_why }$1"; shift; done ;; + -*) die "unknown option '$1' for request-handoff" 64 ;; + *) rh_why="${rh_why:+$rh_why }$1"; shift ;; + esac + done + case "$rh_wait" in ''|*[!0-9]*) die "--wait takes a whole number of seconds; '$rh_wait' is not one" 64 ;; esac + # A WHY BELONGS TO `--force` AND TO NOTHING ELSE, so one given without it is + # REFUSED rather than ignored: a request carries the asker's host, container + # and window and no sentence, and words silently dropped are words a person + # believes they wrote into an append-only log. + if [ -n "$rh_why" ] && [ "$rh_force" = 0 ]; then + die "request-handoff takes no free text: clause (c)'s request line says WHO is asking and from WHERE — \`by host <h>; container <c>; window <w>; wait <n>s\` — and carries no sentence. A why is what \`--force\` writes, because that one is read by the session it takes the lane from: + $SELF request-handoff $lane --force \"$rh_why\"" 64 + fi + check_lane_name "$lane" + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + # THE SEAM (Copilot round 3 on #97): asking a lane's session to hand off is + # a handoff act on that lane, refused for a managed one before the binding + # is read — so `--dry-run` refuses too, rather than planning an act that + # could not be taken. + managed_seam_refuse "$lane" "request-handoff (Amendment 18(c))" + rh_out=""; rh_rc=0 + rh_out="$(lane_binding_scan "$lane")" || rh_rc=$? + [ "$rh_rc" = 0 ] || die "request-handoff could not read lane $lane's object log (exit $rh_rc). That is NOT 'this lane is free' (Amendment 7(d)), and nothing was written." 1 + IFS="$US" read -r rh_state rh_host rh_cont rh_win rh_utc rh_bsess rh_os \ + rh_rutc rh_rsess rh_rpay rh_xverb rh_xutc rh_xsess rh_xpay rh_legacy \ + rh_fverb rh_futc rh_fsess rh_fpay <<EOF +$rh_out +EOF + case "$rh_state" in + bound|requested) : ;; + *) note "lane $lane is FREE — its last lane-kind line is ${rh_xverb:-none at all}${rh_xutc:+ at $rh_xutc}, so there is no binding to ask and nothing was written. Bind it."; exit 8 ;; + esac + rh_wstate="$(binding_window_state "$rh_host" "$rh_win" "$rh_legacy")" + # WHERE the binding is decides what a reader is TOLD, not whether the + # request is allowed. Clause (c) makes a different `host`, `container` OR + # WINDOW a refusal to bind, so a binding in this very host and container — + # a second window of it — is asked for exactly as another machine's is, and + # the one place a request has nothing to ask is the window it is made from. + rh_here=elsewhere + binding_is_here "$rh_host" "$rh_cont" "$rh_legacy" && rh_here=here + # AND THAT ONE PLACE IS TESTED ONLY WHERE THE BINDING IS LOCAL (Copilot + # round 1 on this PR). A tmux `@id` names a window ON ONE TMUX SERVER and + # tmux reissues them from `@0` when a server is replaced, so `@3` here and + # `@3` on another machine are not one window — and comparing the ids alone + # would refuse a request from a second HOST whose current window happened to + # carry the bound window's number, which is the one refusal that leaves a + # lane unaskable. The identity test is made after locality is proved, never + # instead of it. + if [ "$rh_here" = here ] && binding_is_this_window "$rh_win"; then + die "lane $lane's binding IS this window ($rh_win) on this host and in this container: a handoff request is what a SECOND place makes of the first, and there is nothing here to ask. Nothing was written." 2 + fi + + # ---- CLAUSE (e): `--force`, THE SECOND INVOCATION. + if [ "$rh_force" = 1 ]; then + [ -n "$rh_why" ] || die "--force takes a WHY, and it is not decoration: it is written into the lane's append-only log and it is the sentence the bound session reads at its next prompt, when it refuses every prompt from then on and names who forced it (Amendment 18(e)). Say what happened: + $SELF request-handoff $lane --force \"<why>\"" 2 + rh_uuid="$(requester_uuid "$rh_sess")" || rh_uuid="" + [ -n "$rh_uuid" ] || die "--force writes a \`PAUSED\` in THE REQUESTER'S OWN session field — that is what makes it a release on behalf of the bound session rather than an impersonation of it (Amendment 18(e); the 2026-09-13 retired-lane release, opensoft/openRepoTools#30, is the precedent) — and no transcript uuid is knowable here. Name it: --session <uuid>, or run this from inside the session that wants the lane. Nothing was written." 2 + # THE PERSON TYPED A SENTENCE, NOT A GRAMMAR — so the three separators + # this line is built out of are folded rather than refused: `, ` divides + # an event line's four FIELDS, ` — ` divides the verb from the fields and + # the fields from the free text, and `; ` divides one SUB-FIELD from the + # next. A middle dot is none of them, and it is the separator this + # estate's own register rows already use. + # + # AND THE WHY IS WRITTEN AS A NAMED SUB-FIELD, `why <text>`, which clause + # (e) does not spell and which the log needs. The clause's `; <why the + # person gave>` is a sub-field with no name, and every reader here matches + # a sub-field by the word it OPENS with: a why beginning `host is + # unreachable` would be read as this line's `host`, refused by the + # writer's own check, and the person would be told about a field they did + # not write. Named, it can collide with nothing, the words are still + # exactly the ones they typed, and `why` is a name no reader in this file + # parses. + rh_why_clean="$(printf '%s' "$rh_why" | sed 's/ — / · /g; s/, / · /g; s/; / · /g')" + # THE BINDING IS READ AGAIN IMMEDIATELY BEFORE THE APPEND (Copilot round 1 + # on this PR). This release names the session it acts for — `on behalf of + # <bound uuid>` — out of a scan made before the uuid was resolved and the + # why was checked. If the original holder released in between and a third + # place bound the lane, an unconditional append would release THE NEW + # HOLDER while naming the old one: the one act this clause exists to make + # loud, made silently against somebody who never had a chance to answer. + # The window is not closed by this — an append is not a lock, and nothing + # in the ratified text gives a lane one — but the scan is now the last + # thing before the write rather than the first thing in the run, and a + # binding that moved is a refusal naming what it moved to. + rh_re=""; rh_re_rc=0 + rh_re="$(lane_binding_scan "$lane")" || rh_re_rc=$? + [ "$rh_re_rc" = 0 ] || die "lane $lane's object log could not be re-read immediately before the forced release (exit $rh_re_rc), and a \`PAUSED\` written on an answer nobody got could release a binding that is not the one this run read. Nothing was written." 1 + IFS="$US" read -r rh2_state rh2_host rh2_cont rh2_win rh2_utc rh2_sess rh2_rest <<EOF +$rh_re +EOF + if ! binding_identity_same "$rh_host" "$rh_cont" "$rh_win" "$rh_utc" "$rh_bsess" \ + "$rh2_host" "$rh2_cont" "$rh2_win" "$rh2_utc" "$rh2_sess"; then + die "lane $lane's binding CHANGED while this run was preparing to force it. It was window $rh_win in container $rh_cont on host $rh_host (session ${rh_bsess:-unknown}, $rh_utc); it is now ${rh2_state:-free}${rh2_win:+, window $rh2_win in container ${rh2_cont:-none} on host ${rh2_host:-unknown} (session ${rh2_sess:-unknown}, $rh2_utc)}. Nothing was written: a forced release names the session it acts for, and this one would have named a session that no longer holds the lane while releasing one that does. Read it and decide again: + $SELF binding $lane" 2 + fi + rh_fpay="on behalf of ${rh_bsess:-unknown}; forced by $rh_uuid@$LANES_HOST_NAME/$LANES_CONTAINER_NAME; why $rh_why_clean" + if [ "$rh_dry" = 1 ]; then + note "PLAN: $SELF log PAUSED lane:$lane → \"$rh_fpay\" (as session $rh_uuid)" + note "PLAN: then bind — the lane reads free from that line on" + exit 0 + fi + write_event "$lane" PAUSED "lane:$lane" '→' "$rh_fpay" "forced release" "$(utc_now)" "$rh_uuid" || exit $? + note "FORCED: lane $lane's binding is released on behalf of ${rh_bsess:-the bound session}. $(binding_facts "$lane" "$rh_host" "$rh_cont" "$rh_win" "$rh_utc" "$rh_bsess" "$rh_wstate")" + note "If that session is alive after all it will read this line at its next prompt and refuse EVERY prompt from then on, naming it and naming you, until the person there hands off or ends it (Amendment 18(e)). Two places never both write a lane in silence." + exit 0 + fi + + # ---- CLAUSE (c): THE REQUEST, WRITTEN BEFORE ANYTHING ELSE IS TRIED. + rh_uuid="$(requester_uuid "$rh_sess")" || rh_uuid="" + [ -n "$rh_uuid" ] || die "clause (c)'s request line carries the REQUESTER'S transcript uuid in its session field, and Amendment 7(b) admits nothing else there — not a placeholder, and never the literal 'unknown', which is in this estate's append-only log four times already with no later line able to correct any of them. No uuid is knowable here: this shell has no \$CLAUDE_CODE_SESSION_ID and no live session record names this window. Ask from inside the session that wants the lane, or name it: + $SELF request-handoff $lane --session <uuid> + Nothing was written." 2 + rh_mywin="$(tmux display-message -p '#{session_name}:#{window_index}' 2>/dev/null || :)" + rh_myid="$(tmux display-message -p '#{window_id}' 2>/dev/null || :)" + case "$rh_myid" in @[0-9]*) rh_mywin="$rh_mywin $rh_myid" ;; esac + [ -n "$rh_mywin" ] || rh_mywin=none + rh_pay="by host $LANES_HOST_NAME; container $LANES_CONTAINER_NAME; window $rh_mywin; wait ${rh_wait}s" + rh_type="/handoff --exit requested by $rh_uuid@$LANES_HOST_NAME/$LANES_CONTAINER_NAME" + if [ "$rh_dry" = 1 ]; then + note "PLAN: $(binding_facts "$lane" "$rh_host" "$rh_cont" "$rh_win" "$rh_utc" "$rh_bsess" "$rh_wstate") ($rh_here)" + note "PLAN: $SELF log HANDOFF-REQUESTED lane:$lane → \"$rh_pay\" (as session $rh_uuid), committed and pushed FIRST" + if [ "$rh_wstate" = live ]; then + note "PLAN: tmux send-keys into ${rh_win##* } — $rh_type" + else + note "PLAN: nothing is typed into a pane — this tmux server says the bound window is $rh_wstate, and the request travels through the pushed log alone" + fi + note "PLAN: then poll the published log every ${LANES_POLL_SECONDS:-15}s for ${rh_wait}s for a PAUSED, ENDED or RETIRED newer than the request; an empty wait REFUSES and names --force" + exit 0 + fi + rh_wrote="$(utc_now)" + write_event "$lane" HANDOFF-REQUESTED "lane:$lane" '→' "$rh_pay" "" "$rh_wrote" "$rh_uuid" || exit $? + note "REQUESTED: $(binding_facts "$lane" "$rh_host" "$rh_cont" "$rh_win" "$rh_utc" "$rh_bsess" "$rh_wstate")" + + # ---- AND ONLY NOW THE PANE, WHERE IT IS ON THIS TMUX SERVER (Amendment + # 12's M1). It is an OPTIMISATION of the same-host case and never the + # request: a session that never reads it answers at its hook's next read of + # the pushed line instead. + rh_typed=no + if [ "$rh_wstate" = live ]; then + rh_trc=0 + guard_type "${rh_win##* }" "$rh_type" || rh_trc=$? + case "$rh_trc" in + 0) rh_typed=yes; note "typed into ${rh_win##* }: $rh_type" ;; + 9) note "the bound pane is running something other than \`claude\`, so nothing was typed into it (M1's own condition): the request is in the pushed log and is read at that session's next prompt." ;; + 8) note "the bound pane's current command could not be read, so nothing was typed into it — fail closed (M1). The request is in the pushed log." ;; + *) note "tmux would not take the keys for ${rh_win##* }, so nothing was typed. The request is in the pushed log and is read at that session's next prompt." ;; + esac + else + note "the bound window is $rh_wstate from here, so no pane was typed into: the request travels through the pushed log, which is why it is written first." + fi + + # ---- THE WAIT (clause (c)), AND ITS EMPTY END (clause (e)). + rh_poll="${LANES_POLL_SECONDS:-15}" + case "$rh_poll" in ''|*[!0-9]*|0) rh_poll=15 ;; esac + rh_deadline=$(( $(date -u +%s) + rh_wait )) + [ "$rh_wait" = 0 ] || note "waiting up to ${rh_wait}s for lane $lane to be released (polling the published log every ${rh_poll}s) …" + while : ; do + rh_left=$(( rh_deadline - $(date -u +%s) )) + if [ "$rh_left" -le 0 ]; then break; fi + # THE SLEEP IS BOUNDED BY WHAT IS LEFT OF THE WAIT (Copilot round 1 on + # this PR). `--wait <s>` is an UPPER BOUND a person named, and a fixed + # fifteen-second poll overruns it whenever the two disagree: `--wait 1` + # slept fifteen and then answered. What the poll interval decides is how + # OFTEN the log is asked, never how long the caller is held. + rh_nap="$rh_poll" + [ "$rh_nap" -gt "$rh_left" ] && rh_nap="$rh_left" + sleep "$rh_nap" + log_sync + rh_out=""; rh_rc=0 + rh_out="$(lane_binding_scan "$lane")" || rh_rc=$? + [ "$rh_rc" = 0 ] || { note "the lane's log could not be read on this poll — waiting on"; continue; } + IFS="$US" read -r rh_state2 rh_host2 rh_cont2 rh_win2 rh_utc2 rh_bsess2 rh_os2 rh_rest2 <<EOF +$rh_out +EOF + case "$rh_state2" in + released|free) + note "lane $lane is FREE — the binding was released while this request waited. Bind it." + exit 0 ;; + bound|requested) + if ! binding_identity_same "$rh_host" "$rh_cont" "$rh_win" "$rh_utc" "$rh_bsess" \ + "$rh_host2" "$rh_cont2" "$rh_win2" "$rh_utc2" "$rh_bsess2"; then + die "lane $lane was released and BOUND AGAIN while this request waited — its binding is now window ${rh_win2:-none} in container ${rh_cont2:-none} on host ${rh_host2:-unknown} (session ${rh_bsess2:-unknown}, $rh_utc2). The request this run wrote is answered and the lane is somebody else's: ask again, or take it up with that place." 2 + fi ;; + esac + done + note "THE WAIT ENDED WITH NOTHING. $(binding_facts "$lane" "$rh_host" "$rh_cont" "$rh_win" "$rh_utc" "$rh_bsess" "$rh_wstate")" + note " the request: $rh_wrote → $rh_pay, as session $rh_uuid" + note " the pane: ${rh_typed} (this tmux server says that window is $rh_wstate)" + die "no PAUSED, ENDED or RETIRED newer than that request arrived in ${rh_wait}s, so lane $lane is still bound and NOTHING here has bound it (Amendment 18(e)). A working session is never interrupted — a hook fires at a prompt boundary, and a session inside a long turn answers when that turn ends. Wait longer, or override, which is a SECOND invocation and never automatic: + $SELF request-handoff $lane --wait 900 + $SELF request-handoff $lane --force \"<why you are taking it>\"" 2 + ;; + + # ------------------------------ AMENDMENT 11, clause (h): the new reads + # + # ALL READ-ONLY; all answer out of `origin/<branch>` as every Amendment 7 + # read does; all honour `LANES_NO_FETCH=1`, because each one sits in front of + # a launch and a launcher must not sit on the network to open a terminal; and + # all follow Amendment 7(d)'s fail-closed convention — 0 an answer, 8 NO + # ANSWER, 64 a usage error of their own, and anything else a failed read that + # a caller must not read as "nothing to report". + # + # WITH ONE EXCEPTION, AND IT IS THE ONE EVERY UN-UPGRADED WORKSTATION IS IN: + # a `lanes-edit.sh` that has never heard of one of these exits **2** for an + # unknown subcommand, exactly as a pre-Amendment-8 one did for `swapped`. + # That is A HELPER PREDATING THE AMENDMENT THAT ADDED THE READ — expected and + # silent — and a caller falls to its next rung there rather than refusing. + # The two kinds of 2 are told apart by the helper's own WORDS and not by its + # status: the `*)` arm below says "unknown subcommand" and no other refusal + # here does. + + # ADOPTION ACT 0 SHIPS `session-lane`, AND IT IS BELOW RATHER THAN HERE. + # `opensoft/brett-wip#5` @`3719d97` added it and `openRepoTools#24` — MERGED as +# `d4b5710` on this repository's `main`, which is the sha act 3 is cited by from +# here on rather than a branch name — ported that + # commit into this copy, so this branch carries NO second implementation of it + # (A11 Addendum 3, CF-T11: act 0 ships FOUR items, and that is the fourth). + # `3719d97` IS THE MERGE COMMIT. Act 0 merged 2026-09-13T19:14:37Z, squashed, + # so the draft head `95e7a4c` this comment used to cite is not an ancestor of + # `origin/main` at all (F-X18, A11 Addendum 4 ruling 13). + # `/restart`'s step 2(b) and `lane-start`'s step 3b both call the ported arm. + + # The lane bound to a window OF THE ASKING WORKSTATION. Three callers share + # this one implementation — the launcher's precedence 3, `/restart`'s step + # 2(c), and the `/lane-swap` skill's step 1 — and it owns the `<@id>`-versus- + # ref agreement rule for all three (A11 Addendum 2, `R-A11-8`). + # + # The optional workstation comes FIRST, exactly as `swapped [<ws>]` takes it, + # and is told from the ref by shape: a ref is an `@id` or carries a `:`, and + # a workstation name is neither. + window-lane) + wl_a=""; wl_b="" + while [ $# -gt 0 ]; do + case "$1" in + --) shift ;; + -*) die "unknown option '$1' for window-lane (usage: window-lane [<workstation>] <@id>|<session>:<index>)" 64 ;; + *) if [ -z "$wl_a" ]; then wl_a="$1" + elif [ -z "$wl_b" ]; then wl_b="$1" + else die "window-lane takes at most a workstation and one window ref" 64 + fi + shift ;; + esac + done + if [ -n "$wl_b" ]; then wl_in_ws="$wl_a"; wl_in_ref="$wl_b" + else wl_in_ws="$WS"; wl_in_ref="$wl_a" + fi + [ -n "$wl_in_ref" ] || die "usage: window-lane [<workstation>] <@id>|<session>:<index>" 64 + case "$wl_in_ref" in + @*|*:*) : ;; + *) die "'$wl_in_ref' is neither an <@id> nor a <session>:<index>. A workstation is given FIRST: window-lane [<workstation>] <ref>" 64 ;; + esac + log_sync + window_lane "$wl_in_ws" "$wl_in_ref"; wl_rc=$? + case "$wl_rc" in + 0) : ;; + 8) exit 8 ;; + 64) die "usage: window-lane [<workstation>] <@id>|<session>:<index>" 64 ;; + *) die "window-lane could not read this workstation's records for $wl_in_ref (exit $wl_rc). That is NOT 'no lane is bound to that window'." 1 ;; + esac + ;; + + # The lane's RECORDED DIRECTORY: the `dir ` sub-field of its log's LAST + # lane-kind line carrying one, in file order, unquoted where it was written + # quoted (Amendment 11 clause (c)). Four callers: `lane-start`'s directory + # precedence rung 3, the launcher's `--dir` default, `/restart`'s step 3 and + # `restart`'s own. + # + # 8 IS THE ANSWER FOR EVERY LANE THAT HAS NOT STARTED UNDER THIS AMENDMENT, + # and it is not a failure: adoption act 7 cuts each lane over at its own next + # start, nothing is backfilled (Amendment 7(i)), and the default + # `$PROJECTS_ROOT/<repo>` carries it until then, which is what it has always + # done. + lane-dir) + lane="${1-}"; [ -n "$lane" ] || die "usage: lane-dir <lane>" 64 + [ "$#" -le 1 ] || die "lane-dir takes one lane: lane-dir <lane>" 64 + check_lane_name "$lane" + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + # THE READER'S STATUS DECIDES, AS IT DOES IN EVERY OTHER ARM OF THIS CLAUSE + # (#26, the fail-closed family one layer out). `window-session`, `last-session`, + # `forks` and `window-lane` all carry this `case`; these two carried + # `|| :` and then read the EMPTINESS of the output, so a log that could not + # be read left here as **8** — the pre-cutover answer, which is the one + # answer every caller of this read treats as *"fall to the next rung"*. + ld_out="$(lane_payload_field "$lane" dir)"; ld_rc=$? + case "$ld_rc" in + 0) : ;; + 8) exit 8 ;; + *) die "lane-dir could not read lane $lane's log (exit $ld_rc). That is NOT 'this lane has no recorded directory', and a caller that read it that way would resolve the directory from the rungs beneath a record it never read (Amendment 7(d))." 1 ;; + esac + [ -n "$ld_out" ] || exit 8 + printf '%s\n' "$ld_out" + ;; + + # THE LANE'S RECORDED PROFILE — `lane-dir`'s sibling, and the same read one + # sub-field along: the `profile ` of its log's LAST lane-kind line carrying + # one, unquoted where it was written quoted. + # + # IT IS AN ADDITION TO SPEC §11's TABLE AND IS NAMED AS ONE. `lane <name>` + # needs exactly two facts about a lane it is not standing in — its directory + # and its profile — and the directory already had a read of its own. Without + # this the profile came out of the `lanes` listing, which must consult + # `state_events` for the held-objects column and so reads EVERY log on the + # workstation: measured at seventeen seconds on the live register, to answer + # one question about one lane, on the path a person types to get back to work. + # One `git show` instead, through the same `lane_payload_field` `lane-dir` + # uses, so the two cannot disagree about which line is a lane's last. + # + # 8 IS THE ANSWER FOR EVERY LANE THAT HAS NOT STARTED UNDER THIS AMENDMENT, + # and `restart` refuses on it rather than guessing: a wrong profile is a + # launch into another account. + lane-profile) + lane="${1-}"; [ -n "$lane" ] || die "usage: lane-profile <lane>" 64 + [ "$#" -le 1 ] || die "lane-profile takes one lane: lane-profile <lane>" 64 + check_lane_name "$lane" + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + lp_out="$(lane_payload_field "$lane" profile)"; lp_rc=$? + case "$lp_rc" in + 0) : ;; + 8) exit 8 ;; + *) die "lane-profile could not read lane $lane's log (exit $lp_rc). That is NOT 'this lane's record names no profile', and a wrong profile is a launch into another account (Amendment 7(d))." 1 ;; + esac + [ -n "$lp_out" ] || exit 8 + printf '%s\n' "$lp_out" + ;; + + # ------------------------------------------- AMENDMENT 17(b): the two reads + # + # `lane-agent` and `lane-transcript` are `lane-dir`'s siblings, one sub-field + # along and through the same `lane_payload_field`, so the four cannot disagree + # about which line is a lane's last. ONE CALLER EACH TODAY and that is the + # point of the read existing rather than being inlined: `lane-start` reads the + # agent to know WHICH LAUNCHER to use with no `--agent`, and reads the + # transcript to know the id to append to the row's session cell in that + # agent's own spelling (`Codex <id>`), which is the one id a launch of a + # non-Claude agent has in hand. + # + # 8 IS THE ANSWER FOR EVERY RECORD WRITTEN BEFORE THIS AMENDMENT, and it is + # not a failure: Amendment 7(i) cuts each lane over at its own next handoff, + # nothing is backfilled, and `lane-start`'s default of `claude` carries it + # until then — which is what it has always done. + lane-agent) + lane="${1-}"; [ -n "$lane" ] || die "usage: lane-agent <lane>" 64 + [ "$#" -le 1 ] || die "lane-agent takes one lane: lane-agent <lane>" 64 + check_lane_name "$lane" + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15: one name under any case + la_out="$(lane_payload_field "$lane" agent)"; la_rc=$? + case "$la_rc" in + 0) : ;; + 8) exit 8 ;; + *) die "lane-agent could not read lane $lane's log (exit $la_rc). That is NOT 'this lane's record names no agent', and a caller that read it that way would launch the default agent over a lane another one paused (Amendment 7(d))." 1 ;; + esac + [ -n "$la_out" ] || exit 8 + printf '%s\n' "$la_out" + ;; + + lane-transcript) + lane="${1-}"; [ -n "$lane" ] || die "usage: lane-transcript <lane>" 64 + [ "$#" -le 1 ] || die "lane-transcript takes one lane: lane-transcript <lane>" 64 + check_lane_name "$lane" + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15: one name under any case + lt_out="$(lane_payload_field "$lane" transcript)"; lt_rc=$? + case "$lt_rc" in + 0) : ;; + 8) exit 8 ;; + *) die "lane-transcript could not read lane $lane's log (exit $lt_rc). That is NOT 'this lane's record names no transcript' (Amendment 7(d))." 1 ;; + esac + [ -n "$lt_out" ] || exit 8 + printf '%s\n' "$lt_out" + ;; + + # AMENDMENT 13(b) — THE DIARY THE CELL USED TO BE, IN THE FILE BUILT TO HOLD + # IT. A lane's `NOTED` and `RULED` lines in order — FILE order, which is the + # order that lane wrote them (R14), and never a sort on the UTC field: two + # workstations share no clock and this one has been measured jumping ±25s. + # `--since` is the one filter, and it compares the two instants after padding + # the register's older minute-precision form to seconds, so a line stamped + # `…T20:31Z` is on the right side of a `--since …T20:30:00Z`. + # + # 8 IS "THIS LANE HAS WRITTEN NO NARRATIVE", which a lane that has never taken + # a note and a lane with no log at all both are; a read that could not be made + # is never 8 (R22) and leaves through the die above it. + # AMENDMENT 13's DIARY, and since AMENDMENT 14 ACROSS LANES TOO. + # + # history <lane> one lane's `NOTED` and `RULED` lines, in + # FILE ORDER — the diary the state cell used + # to be. Unchanged. + # history --all every lane's, as ONE timeline: by UTC, and + # by file and line where two share a minute. + # history --repo <owner/repo> the lanes whose HOME is that repository — + # the `home` of their last `STARTED`/`RESUMED`, + # through the alias table, exactly as `lanes + # --repo` files them — on one timeline. + # --since <UTC> with any of the three. + # --index read the DERIVED INDEX instead of the + # published logs (Amendment 14(b)), only when + # typed: stderr says `read: index (<store>) at + # register@<sha12>; <k> commits behind`, or + # `read: sources (index <why>)` and the + # sources answer. Where the index answers it + # does not fetch: it reads no network at all, + # and the lag is said against this checkout. + # + # `history` over two lanes was refused, exit 64, on 2026-10-05 (Amendment 14, + # "Why" 3); `--all` and `--repo` are that question, and they read the + # SOURCES — the same one pass over every published log `who` makes — with or + # without the flag. + history) + lane=""; hi_since=""; hi_all=0; hi_repo=""; hi_index=0 + hi_usage="history <lane> | --all | --repo <owner/repo> [--since <UTC>] [--index]" + while [ $# -gt 0 ]; do + case "$1" in + --since) hi_since="${2-}"; [ -n "$hi_since" ] || die "--since needs a UTC instant" 64; shift 2 ;; + --since=*) hi_since="${1#--since=}"; [ -n "$hi_since" ] || die "--since needs a UTC instant" 64; shift ;; + --all) hi_all=1; shift ;; + --repo) hi_repo="${2-}"; [ -n "$hi_repo" ] || die "--repo needs a repository ($hi_usage)" 64; shift 2 ;; + --repo=*) hi_repo="${1#--repo=}"; [ -n "$hi_repo" ] || die "--repo needs a repository ($hi_usage)" 64; shift ;; + --index) hi_index=1; shift ;; + --) shift ;; + -*) die "unknown option '$1' for history ($hi_usage)" 64 ;; + *) [ -z "$lane" ] || die "history takes ONE lane, or --all, or --repo <owner/repo>: $hi_usage" 64; lane="$1"; shift ;; + esac + done + hi_sel=0 + [ -n "$lane" ] && hi_sel=$((hi_sel + 1)) + [ "$hi_all" = 1 ] && hi_sel=$((hi_sel + 1)) + [ -n "$hi_repo" ] && hi_sel=$((hi_sel + 1)) + [ "$hi_sel" = 1 ] || die "usage: $hi_usage — ONE of a lane, --all or --repo" 64 + [ -z "$lane" ] || check_lane_name "$lane" + case "$hi_since" in + '') : ;; + [0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]Z | [0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9]Z) : ;; + *) die "--since takes a UTC instant spelled as this log spells it, YYYY-MM-DDTHH:MM[:SS]Z — '$hi_since' is not one" 64 ;; + esac + # THE INDEX FIRST, and where it answers there is no fetch: the read is the + # index's, and a network round trip in front of it is the cost the flag is + # for avoiding. Where it does not answer, the source read below is exactly + # the one this arm always made, the fetch included. + if [ "$hi_index" = 1 ] && index_open; then LANES_NO_FETCH=1; fi + log_sync + if [ -n "$lane" ]; then + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + hi_lines=""; hi_rc=0 + hi_lines="$(lane_log_events "$lane")" || hi_rc=$? + case "$hi_rc" in + 0) : ;; + 2) exit 2 ;; + *) die "history could not read lane $lane's log (exit $hi_rc). That is NOT 'this lane has written no narrative' — a read that failed is never an answer (Amendment 7(d))." 1 ;; + esac + hi_out="$(printf '%s\n' "$hi_lines" | awk -F"$US" -v since="$hi_since" ' + function pad(u) { return (length(u) == 17) ? substr(u, 1, 16) ":00Z" : u } + $3 == "NOTED" || $3 == "RULED" { + if (since != "" && pad($1) < pad(since)) next + printf "%-20s %-5s %s%s\n", $1, $3, ($8 != "" ? $8 " — " : ""), $9 + }')" + [ -n "$hi_out" ] || exit 8 + printf '%s\n' "$hi_out" + else + hi_ev="$(state_events)" + # `--repo`: THE LANES WHOSE HOME IS IT, keyed as every other table in + # this file is — the log's own lane, lower-cased — and a home compared + # through the alias table on BOTH sides, so `openRepoTools` and + # `opensoft/openRepoTools` are one repository here as they are to + # `lanes --repo`. A lane with no recorded home is in no repository's. + hi_filter=0; hi_keep="" + if [ -n "$hi_repo" ]; then + hi_filter=1 + hi_want="$(alias_lookup "$hi_repo" 2>/dev/null || :)"; [ -n "$hi_want" ] || hi_want="$hi_repo" + lower_into "$hi_want"; hi_want_lc="$LOWER_OUT" + while IFS="$US" read -r hi_l _hi_disp _hi_v _hi_u _hi_w _hi_d _hi_p _hi_win hi_h _hi_rest; do + [ -n "${hi_l:-}" ] && [ -n "${hi_h:-}" ] || continue + hi_hc="$(alias_lookup "$hi_h" 2>/dev/null || :)"; [ -n "$hi_hc" ] || hi_hc="$hi_h" + lower_into "$hi_hc" + [ "$LOWER_OUT" = "$hi_want_lc" ] && hi_keep="$hi_keep $hi_l" + done <<EOF +$(printf '%s\n' "$hi_ev" | lane_row_facts) +EOF + fi + # ONE TIMELINE: the UTC padded as the single-lane read pads it, then the + # file and the line — the log's own order where two lines share a stamp. + # The key is cut away after the sort; the lane is the LOG's (Amendment + # 16(e): a line's lane is the lane of the file it is in). + hi_out="$(printf '%s\n' "$hi_ev" | awk -F"$US" -v since="$hi_since" -v filter="$hi_filter" -v keep="$hi_keep" ' + function pad(u) { return (length(u) == 17) ? substr(u, 1, 16) ":00Z" : u } + BEGIN { n = split(keep, kk, " "); for (i = 1; i <= n; i++) K[kk[i]] = 1 } + $3 == "NOTED" || $3 == "RULED" { + if (since != "" && pad($1) < pad(since)) next + if (filter == 1 && !(tolower($2) in K)) next + printf "%s\034%s\034%09d\037%-20s %-26s %-5s %s%s\n", pad($1), $10, $11, $1, $2, $3, ($8 != "" ? $8 " — " : ""), $9 + }' | LC_ALL=C sort | awk -v s="$US" '{ i = index($0, s); print substr($0, i + 1) }')" + [ -n "$hi_out" ] || exit 8 + printf '%s\n' "$hi_out" + fi + ;; + + # THE LANE'S LAST LANE-KIND LINE, in FILE ORDER — `<verb><TAB><utc><TAB><session><TAB><payload>`. + # One caller: `lane-handoff --late`, which may only write the record a swap + # never left where that line is still a `STARTED` or a `RESUMED` older than + # the instant the late line claims. This log is APPEND-ONLY and file order is + # what every state read means by "last", so a `PAUSED` appended after the + # relaunch's `RESUMED` would make a lane that is RUNNING read as paused — and + # this read is how that is refused instead of written. + # + # IT IS THE LANE'S OWN LINES AND NOT A FORK'S, which is `lane_row_facts`' rule + # one function along (decision 8(c): a fork is never the lane). + lane-last) + lane="${1-}"; [ -n "$lane" ] || die "usage: lane-last <lane>" 64 + [ "$#" -le 1 ] || die "lane-last takes one lane: lane-last <lane>" 64 + check_lane_name "$lane" + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15: one name under any case + ll_lines=""; ll_rc=0 + ll_lines="$(lane_log_events "$lane")" || ll_rc=$? + [ "$ll_rc" = 0 ] || die "lane-last could not read lane $lane's log (exit $ll_rc). That is NOT 'this lane has no lane-kind line' (Amendment 7(d))." 1 + ll_out="$(printf '%s\n' "$ll_lines" | awk -F"$US" -v OFS=' ' ' + $3 == "STARTED" || $3 == "PAUSED" || $3 == "RESUMED" || $3 == "ENDED" || $3 == "RETIRED" { + if (substr($8, 1, 5) == "fork ") next + v = $3; u = $1; s = $4; p = $8 + } + END { if (v != "") print v, u, s, p }')" + [ -n "$ll_out" ] || exit 8 + printf '%s\n' "$ll_out" + ;; + + # THE WORKSPACE REPOSITORY'S PATH — the one resolver, printed. Amendment 9(a) + # is explicit that a second way to find one thing is a second answer, and + # `lane-handoff` needs this path to resolve the handoff cell of a row whose + # spelling is repository-relative. Every other reader of it is in this file. + workspace-root) + [ "$#" = 0 ] || die "workspace-root takes no arguments" 64 + wr_out="$(lanes_workspace_root 2>/dev/null || :)" + [ -n "$wr_out" ] || die "$(lanes_workspace_why)" 1 + printf '%s\n' "$wr_out" + ;; + + # The lane's RESUME TARGET, read robustly (Amendment 11 clause (d) rules 3 + # and 4): the last uuid in the published row's session cell WHATEVER SHAPE + # THAT CELL IS IN, and failing that the session field of the lane's last + # `PAUSED` or `RESUMED` line. Never a title, and never an exit — a caller + # that gets 8 has learnt that no uuid is knowable from either source, which + # is the ONLY state in which Amendment 8(d)'s title fallback is reachable. + last-session) + lane="${1-}"; [ -n "$lane" ] || die "usage: last-session <lane>" 64 + [ "$#" -le 1 ] || die "last-session takes one lane: last-session <lane>" 64 + check_lane_name "$lane" + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + last_session_of "$lane"; ls_rc=$? + case "$ls_rc" in + 0) : ;; + 8) exit 8 ;; + *) die "last-session could not read the register or the log for $lane (exit $ls_rc)" 1 ;; + esac + ;; + + # DECISION 8(c) AND 8(e) — the live FORKS of this lane's transcript, which + # are a defect to retire and never a holder. Evidence 6: an abandoned launch + # left a `--fork-session` daemon orchestrating the same plan and writing this + # lane's log under an id no row carries. It NAMES them and does nothing else: + # the act is `lane-end <lane> --retire <pid|uuid>` (clause (k) rule (e)), + # printed by the caller and typed by a person, for the reason Amendment 8(f) + # gives — and it writes a record rather than killing anything. + # 0 with rows, 8 with none, 1 where the records could not be read. + forks) + lane="${1-}"; [ -n "$lane" ] || die "usage: forks <lane>" 64 + [ "$#" -le 1 ] || die "forks takes one lane: forks <lane>" 64 + check_lane_name "$lane" + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + lane_forks "$lane"; fk_rc=$? + case "$fk_rc" in + 0) : ;; + 8) exit 8 ;; + 64) die "usage: forks <lane>" 64 ;; + *) die "could not read this workstation's session records for lane $lane: ${SESSION_FILES_ERR:-unknown error}. That is NOT 'no fork of it is live'." 1 ;; + esac + ;; + + # ISSUE #39 — a live `--fork-session` DUPLICATE of this lane's OWN + # transcript, found in the process table rather than in a session record's + # `sessionId` field (which is exactly why `forks` cannot see it once the id + # is bound to the row: `lane-end <lane> --retire <pid>` is the caller, for a + # duplicate `lane_forks` was designed to stay silent about). + # 0 with rows, 8 with none, 1 where `pgrep` is missing, or the register or + # the records could not be read. + duplicate-holder) + lane="${1-}"; [ -n "$lane" ] || die "usage: duplicate-holder <lane>" 64 + [ "$#" -le 1 ] || die "duplicate-holder takes one lane: duplicate-holder <lane>" 64 + check_lane_name "$lane" + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + duplicate_holder_pids "$lane"; dh_rc=$? + case "$dh_rc" in + 0) : ;; + 8) exit 8 ;; + 64) die "usage: duplicate-holder <lane>" 64 ;; + *) die "could not read the register, this workstation's process table or its session records for lane $lane: ${SESSION_FILES_ERR:-unknown error}. That is NOT 'no duplicate holder is live'." 1 ;; + esac + ;; + + # DECISION 8(d) — THE WORKSTATION'S NAME, AND WHERE IT CAME FROM. One + # implementation, so `restart`, `lanes` and every other caller name the + # workstation the same way the register's own writer does rather than each + # running `hostname` and disagreeing with it. Prints `<name><TAB><source>`, + # where the source is one of the THREE `lanes_workstation_pair` emits — + # `seam`, `hostname` or `container-unset` (`:371-383`) — and on that last one + # the sentence that says what to export goes to stderr, because a read must + # still answer. + # + # THE TWO NAMES THAT WERE HERE DO NOT EXIST. `config` and + # `hostname-in-container` are the vocabulary of the rung `R-A11-14` REMOVED: + # a `workstation:` key in `workspace.yaml`, refused as a second place for the + # truth to be wrong beside the variable the launcher already sets (`:337-339`). + # `lanes:190` matched the second of them and could therefore never print, which + # is how a dead branch went unnoticed (F-X1). SPEC rev 6's §11 row still lists + # all four; that is the text's to correct, and the code's own emitters are the + # authority for this comment. + # Always 0: a workstation name that could refuse would be a refusal in front + # of every launch on this machine. + # THE WORKSTATION'S NAME AND ITS SOURCE — and, since Amendment 18(a), the + # THREE FACTS BENEATH IT and theirs. Eight tab-separated fields: + # + # <workstation> <source> <host> <source> <os> <source> <container> <source> + # + # GROWN AT THE END, which is this file's rule for every read that gains a + # field (`swapped_lanes`'s sixth and seventh say why): the FIRST TWO are the + # contract `lanes`, `lane` and `lane-handoff` already take with `cut -f1` and + # `cut -f2`, and a reader that has never heard of the rest is unaffected by + # them. Each source is one of `seam` (the launcher exported it), `hostname` + # (probed), `workstation` (a container with no export, writing the Rule 10 + # name for its host), `kernel` (the `uname`/`/proc/version` probe) or + # `outside` (no container). The workstation's own refusal sentence is printed + # on stderr exactly as before, and this read still ANSWERS: a read in front of + # every launch may not refuse. + workstation) + [ "$#" -eq 0 ] || die "workstation takes no arguments" 64 + ws_why="$(lanes_workstation_why "$WS_SOURCE")" + [ -n "$ws_why" ] && note "$ws_why" + printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' \ + "$WS" "$WS_SOURCE" \ + "$LANES_HOST_NAME" "$LANES_HOST_SOURCE" \ + "$LANES_OS_NAME" "$LANES_OS_SOURCE" \ + "$LANES_CONTAINER_NAME" "$LANES_CONTAINER_SOURCE" + ;; + + # HOW OLD THE CHECKOUT'S ANSWER IS (`R-A8-1`'s rule, given its own read). + # `.git/FETCH_HEAD` is rewritten by every fetch and by nothing else, so its + # mtime is when this checkout last heard from `origin` — and a listing that + # says "4d ago" is a listing a reader knows not to trust about another + # workstation's lane. Never a network call and never a failure: an unreadable + # one answers `unknown`. Always 0. + fetch-age) + [ "$#" -eq 0 ] || die "fetch-age takes no arguments" 64 + fetch_age + ;; + + # DECISIONS 6 AND 7 — THE LANE LISTING, as data. `lanes` renders the + # estate-wide one and `restart` the per-repo one from these same rows, which + # is why the filter is an argument rather than three implementations. + # 0 with rows, 8 with none, 64 a usage error of its own. + lanes) + lns_args=(); lns_fetch=0; lns_index=0 + while [ $# -gt 0 ]; do + case "$1" in + --repo|--dir|--ws|--lane|--prefix) [ -n "${2-}" ] || die "$1 needs a value (usage: lanes [--repo <owner/repo>] [--dir <path>] [--prefix <repo>] [--ws <workstation>] [--lane <lane>] [--here] [--all] [--closed] [--fetch] [--index])" 64 + lns_args+=("$1" "$2"); shift 2 ;; + --all|--here|--closed) lns_args+=("$1"); shift ;; + --fetch) lns_fetch=1; shift ;; + # AMENDMENT 14(b) — THE DERIVED INDEX, ONLY WHEN TYPED. It replaces the + # PUBLISHED reads of the register and the logs and nothing else; the + # live session records, tmux and this checkout's own files are read + # exactly as they are without it, so the rows are the same rows. + --index) lns_index=1; shift ;; + --) shift ;; + *) die "unknown argument '$1' for lanes (usage: lanes [--repo <owner/repo>] [--dir <path>] [--prefix <repo>] [--ws <workstation>] [--here] [--all] [--closed] [--fetch] [--index])" 64 ;; + esac + done + # THE ONE READ IN THIS FILE WHOSE DEFAULT IS LOCAL (SPEC rev 4 §15). Every + # other read here sits in front of a LAUNCH, where a stale answer binds the + # wrong lane; this one sits in front of a PERSON, who is waiting on it. So + # `LANES_NO_FETCH=1` is its default rather than an override — still honoured + # where it is already set — and `--fetch` is how a caller asks for the + # network. `fetch-age` is the read beside it, so a listing can say how old + # its answer is, exactly as Amendment 8(e)'s hook does under `R-A8-1`. + [ "$lns_fetch" = 1 ] || LANES_NO_FETCH=1 + log_sync + # A FETCH THAT DID NOT HAPPEN IS NOT A FETCH, AND IT IS SAID IN THE ONE + # PHRASE THE CALLER ALREADY READS (#26, `lanes:411`). `log_sync` leaves four + # ways out of itself that never reach the fetch and were silent on all four; + # `lanes --fetch` matches its stderr for *"reading the logs as they stand + # locally"* and prints *"as of a fetch just now"* where it does not find it. + # So the phrase is the helper's, once, and the reason is named beside it. + # + # ONLY UNDER `--fetch`. Without it this read's default is LOCAL by design + # (SPEC rev 4 §15) and the notice would be a line saying it did what it was + # asked — which is why the wrapper renders the fetch path's stderr and not + # the local path's. + if [ "$lns_fetch" = 1 ] && [ "$LOG_SYNC_FETCH" != yes ] && [ "$LOG_SYNC_FETCH" != fell-back ]; then + note "--fetch was asked for and NO FETCH WAS MADE: $LOG_SYNC_FETCH — reading the logs as they stand locally" + fi + # AFTER the fetch, so `<k> commits behind` is counted against the + # `origin/<branch>` this run has just brought up to date where it asked to. + if [ "$lns_index" = 1 ]; then index_open || :; fi + # AMENDMENT 15 — `--lane <name>` IS A `<lane>` ARGUMENT AND GOES THROUGH THE + # RESOLVER. The filter inside `lanes_rows` has always joined on the name + # lower-cased, so the ROWS came back either way; what a typed spelling used + # to do was put itself in column 1 and in column 10's `lane <name>` line. + # `${lns_args[@]+"${lns_args[@]}"}` AND NOT `${#lns_args[@]}` OR AN INDEX: + # this file is parsed under macOS bash 3.2 in CI, where an EMPTY array under + # `set -u` is the expansion this idiom exists for — it is the same one the + # `lanes_rows` call below already uses, and a bare `lanes` with no flags is + # exactly the empty case. The rebuild also stops assuming the value sits at + # `i + 1`; it takes the word AFTER `--lane`, which is what the parser above + # guarantees there is one of. + # `--all` IS ABSOLUTE AND IT CLEARS `--lane` (the reset inside `lanes_rows` + # says so in terms), so a `--lane` it is about to throw away must not be + # resolved — and must not REFUSE. `lanes --all --lane <the 15(d) pair>` is + # the every-lane listing, in either flag order, and exiting 2 on a selector + # this run ignores would hide every lane for a name nothing was asked about + # (Copilot round 1 on openRepoTools#41). + lns_all=0 + for lns_a in ${lns_args[@]+"${lns_args[@]}"}; do + case "$lns_a" in --all) lns_all=1 ;; esac + done + lns_new=(); lns_take=0 + for lns_a in ${lns_args[@]+"${lns_args[@]}"}; do + if [ "$lns_take" = 1 ]; then + lns_take=0 + if [ "$lns_all" = 0 ]; then + lns_one="$(canon_lane "$lns_a")" || exit 2 + else + lns_one="$lns_a" + fi + lns_new+=("$lns_one") + continue + fi + case "$lns_a" in --lane) lns_take=1 ;; esac + lns_new+=("$lns_a") + done + lns_args=(${lns_new[@]+"${lns_new[@]}"}) + lns_out="$(lanes_rows ${lns_args[@]+"${lns_args[@]}"})"; lns_rc=$? + case "$lns_rc" in + 0) : ;; + 8) exit 8 ;; + 64) die "usage: lanes [--repo <owner/repo>] [--dir <path>] [--prefix <repo>] [--ws <workstation>] [--here] [--all] [--closed] [--fetch] [--index]" 64 ;; + *) die "the lane listing could not be read (exit $lns_rc)" 1 ;; + esac + [ -n "$lns_out" ] || exit 8 + printf '%s\n' "$lns_out" + ;; + + # AMENDMENT 18 ADDENDUM 1 — THE PICK'S TWO READS, over the rows the `lanes` + # arm above has just printed. Both take those rows on STDIN and neither reads + # the register: the caller has paid for that read and a second one would + # double the cost of every pick. `lane` is the only caller of the first and + # `lane` and `lanes` are both callers of the second, which is the point — two + # surfaces computing one partition, or one next free position, is how they + # come to disagree. + # 0 with the answer · 64 a usage error of its own. + lane-groups) + [ "$#" -le 1 ] || die "lane-groups takes one optional workstation: lane-groups [<workstation>] (the rows on stdin)" 64 + lane_groups "${1-}" + ;; + + next-free) + [ -n "${1-}" ] || die "usage: next-free <repo> (the rows on stdin)" 64 + [ "$#" -le 1 ] || die "next-free takes one repository: next-free <repo> (the rows on stdin)" 64 + lane_next_free "$1" + ;; + + # AMENDMENT 8 — Rule 1's sibling reads, filtered to lines that NAME the + # object. `gh_reads` pipes both of its searches through this; it is a + # subcommand so that the filter can be held to account directly, and so a + # person can run a search of their own through the same test. + sibling-filter) + sfsub=""; sfsub_mode=pr + while [ $# -gt 0 ]; do + case "$1" in + --branch) sfsub_mode=branch; shift ;; + --pr) sfsub_mode=pr; shift ;; + --) shift ;; + -*) die "unknown option '$1' for sibling-filter" 2 ;; + *) [ -z "$sfsub" ] || die "sibling-filter takes one object" 2; sfsub="$1"; shift ;; + esac + done + [ -n "$sfsub" ] || die "usage: sibling-filter <object> [--branch] (candidate lines on stdin)" 2 + sfsub_home="$(resolve_home "${LANES_LANE:-}" "" 2>/dev/null || :)" + sfsub_obj="$(canon_object "$sfsub" "$sfsub_home")" || exit 2 + sibling_filter "$sfsub_obj" "$sfsub_mode" + ;; + + # R20 — a lane's HOME goes through `repos.tsv` like every other spelling, and + # `lane-start` has no alias table of its own. 0 with the canonical + # nameWithOwner, 8 when the table has no row for it (the caller records the + # spelling it derived, and warns), 2 when the table maps it to something that + # is not owner/repo. + resolve-repo) + rr="${1-}"; [ -n "$rr" ] || die "usage: resolve-repo <owner/repo|alias>" 2 + rr_c="$(alias_lookup "$rr" 2>/dev/null || :)" + [ -n "$rr_c" ] || { printf '%s\n' "$rr"; exit 8; } + valid_nwo "$rr_c" || die "the alias table maps '$rr' to '$rr_c', which is not owner/repo" 2 + printf '%s\n' "$rr_c" + ;; + + lane-objects) + lane="${1-}"; [ -n "$lane" ] || die "usage: lane-objects <lane>" 2 + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + lane_objects "$lane" || exit $? + ;; + + # The lane's ROW as it has LANDED — fetched, and read from + # `origin/<branch>:lanes/LANES.md` like every other state read (R19). 0 with + # the row, 8 when the published register has none. `lane-end`'s pre-cutover + # fallback and `lane-start`'s "is this lane new" test both used to read the + # working tree, which a fetch does not move: a peer's LANDING appended to the + # state cell, or a peer's whole row, was invisible to both, so `lane-end` + # wrote NOTHING IN FLIGHT over a live merge hold and `lane-start` added a + # SECOND row for a lane that already had one — and two rows is a register no + # helper can edit (`row_line` requires exactly one). + register-row) + lane="${1-}"; [ -n "$lane" ] || die "usage: register-row <lane>" 2 + check_lane_name "$lane" + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + rr_row="$(row_of_lane "$lane")" + [ -n "$rr_row" ] || exit 8 + printf '%s\n' "$rr_row" + ;; + + # This checkout's row can be ahead of origin after a local transcript stamp. + # The live attach checks both copies; an unreadable local row is not absence. + register-row-local) + lane="${1-}"; [ -n "$lane" ] || die "usage: register-row-local <lane>" 2 + check_lane_name "$lane" + rr_row="$(row_of_lane_local "$lane")" || die "could not read local register row for $lane" 1 + [ -n "$rr_row" ] || exit 8 + case "$rr_row" in *$'\n'*) die "more than one local row names $lane" 2 ;; esac + printf '%s\n' "$rr_row" + ;; + + # 0 with archived spellings, 8 absent, 1 when either archive cannot be read + # or carries a line that is not a row (#122, named above the refusal). + retired-identity) + lane="${1-}"; [ -n "$lane" ] || die "usage: retired-identity <lane>" 2 + check_lane_name "$lane" + log_sync + rr_hits="$(retired_identity_hits "$lane")" || die "could not read the lane archive, or it carries a line that is not a row (above)" 1 + [ -n "$rr_hits" ] || exit 8 + printf '%s\n' "$rr_hits" + ;; + + # R-A11-7 — THE HOOK'S OWN uuid → lane READ, EXPOSED. `lane_of_session` has + # answered "which lane's row's SESSION CELL names this uuid" since Amendment + # 8(e), for a window that carries no lane name; nothing else could reach it. + # `lane-start` step 3b needs the same answer to keep R-A11-1's fence — a live + # session that belongs to ANOTHER row is never taken — so it is one read with + # two callers rather than a second implementation of the same question. + # + # ONLY the session cell is read, exactly as the hook reads it: state cells + # quote other lanes' ids all the time (`RESUMED by <id>`, `handed off to + # <id>`), and one of those is not that session's lane. + # + # Read-only. 0 with the lane, 8 when no row's session cell names it — + # Amendment 7(d)'s fail-closed convention, so a caller can tell *none* from + # *could not read* — and 64 on a usage error of its own. + # + # 64 AND NOT 2 (A11 Addendum 4 ruling 1, ratified "a11 addendum 4 yes"). + # Adoption act 0 wrote this read with a usage `2` (`3719d97:lanes/lanes-edit.sh`) + # and SPEC rev 6 §11 recorded the landed code; clause (h)'s own table said + # `64 usage` for every read in it, and the contract contradicted itself. The + # ruling settles it the other way: *"`session-lane`'s usage code is 64 like + # every other read in clause (h); adoption act 0 item (4), which says 2, is + # the line corrected."* + # + # IT MATTERS BECAUSE `2` HERE ALREADY MEANS SOMETHING ELSE. A helper that has + # never heard of `session-lane` exits 2 from the `*)` arm, and that is what + # every workstation answers until act 3's install reaches it. A caller that + # cannot tell that 2 from a usage 2 cannot tell *"install the helper"* from + # *"fix your call"* — and both of `session-lane`'s callers fail CLOSED on + # anything but 0 or 8, so the distinction is the whole of what they can report. + session-lane) + sl_id="${1-}"; [ -n "$sl_id" ] || die "usage: session-lane <transcript-uuid>" 64 + [ "$#" -le 1 ] || die "session-lane takes one transcript uuid: session-lane <transcript-uuid>" 64 + log_sync + sl_lane="$(lane_of_session "$sl_id")" + [ -n "$sl_lane" ] || exit 8 + printf '%s\n' "$sl_lane" + ;; + + # AMENDMENT 15 — THE RESOLVER, EXPOSED, because `lane-start`, `lane-end`, + # `lanes` and `restart` all take a `<lane>` argument and the amendment gives + # them all the SAME resolver. An implementation of "which row is this name's" + # in each command is how they would come to disagree about it — which is the + # whole reason clause (h) turned `window-lane` and `session-lane` into + # subcommands. + # + # Read-only, out of `origin/<branch>` like every other state read (R19). + # 0 the canonical spelling — the row's own where a row matches ignoring + # case, and the TYPED spelling where none does, because a lane with no + # row is a lane `add-row` is about to create and the typed name is all + # there is. + # 2 the refusal: two or more rows differ only by case (15(d)). It is 2 and + # not 8 because it is a REFUSAL and not an absence — and `lane-start` + # already spends 2 on exactly this fact for two rows of one spelling. + # 64 a usage error of its own, as every read in clause (h)'s table does. + # A caller that meets 2 from a helper predating this amendment is meeting the + # `*)` arm's unknown-subcommand 2, told apart by the helper's own WORDS as + # every other read here is; the four callers fall through to the typed + # spelling there, and each has its own refusal for a register that really does + # hold two such rows. + canon-lane) + cl_in="${1-}"; [ -n "$cl_in" ] || die "usage: canon-lane <lane>" 64 + [ "$#" -le 1 ] || die "canon-lane takes one lane: canon-lane <lane>" 64 + check_lane_name "$cl_in" + log_sync + # THE CODE IS CARRIED, not flattened to 2: 66 is the alias table that could + # not be read and its four callers tell it from 2 by that number alone. + cl_res="$(canon_lane "$cl_in")" || exit $? + printf '%s\n' "$cl_res" + ;; + + # `--home`'s validation, WITHOUT a write — the same `resolve_home` the writers + # call, so a preflight and the write can never disagree. 0 with the canonical + # home, 8 when the lane has none and none was given, 2 when the option is + # refused (the lane's log already records its home) or is not owner/repo. + # `lane-end` forwards `--home` to its own ENDED line, which is written AFTER + # the row has been closed: without this the refusal arrived too late to + # refuse anything, and left a closed row with no ENDED line behind it. + resolve-home) + lane="${1-}"; [ -n "$lane" ] || die "usage: resolve-home <lane> [<owner/repo|alias>]" 2 + check_lane_name "$lane" + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + rh_out="$(resolve_home "$lane" "${2-}")" || exit $? + [ -n "$rh_out" ] || exit 8 + printf '%s\n' "$rh_out" + ;; + + # ---------- openRepoTools#94: the restart intent the supervisor launches from + # + # BOTH ANSWER OUT OF THE LOCAL CONTROL ROOT. The writer reads the register's + # managed-ownership projection before mutation; neither writes the register, + # the object log or reaches the network. The WRITER is deliberately absent from the + # dispatcher's workstation guard above — `R-A11-14` is about a record FILED + # UNDER A WORKSTATION, and this one is filed under nothing and never leaves + # the machine that wrote it — and it takes the same 64-for-usage contract + # every read Amendment 11 added takes, because it sits in front of a launch + # exactly as those do. + # + # 0 done + # 1 no control root could be derived, or it could not be written + # 2 a refusal of the arguments + # 7 THE FENCE DID NOT MATCH — another act got there first, which is what + # this file already spends 7 on (`claim`'s CLAIM-LOST, `set-lane-state`). + # Nothing was written and the current intent is printed. + # 8 there is no intent for this lane + # 64 a usage error of this subcommand's own + + restart-intent) + lane="${1-}"; [ -n "$lane" ] || die "usage: restart-intent <lane> [--dir <absolute checkout>]" 64 + shift; lri_dir="" + if [ "$#" -gt 0 ]; then + [ "$#" = 2 ] && [ "$1" = --dir ] || die "usage: restart-intent <lane> [--dir <absolute checkout>]" 64 + case "$2" in /*) lri_dir="$2" ;; *) die "--dir takes an absolute checkout" 64 ;; esac + fi + check_lane_name "$lane" + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + lri_out=""; lri_rc=0 + lri_out="$(lane_restart_read "$lane" "$lri_dir")" || lri_rc=$? + case "$lri_rc" in + 0) : ;; + 8) exit 8 ;; + *) die "lane $lane has no lifecycle control root, so it can carry no restart intent: its record names no directory (Amendment 11(c)) and \$PROJECTS_ROOT is not a directory here. That is NOT 'this lane has no restart in flight' — a read that could not be made is never an answer (Amendment 7(d))." 1 ;; + esac + printf '%s\n' "$lri_out" + ;; + + publish-handoff) + lane="${1-}"; pbh_target="${2-}"; pbh_source="${3-}" + [ "$#" -ge 3 ] || die "usage: publish-handoff <lane> <target> <prepared-file> --expect-digest <sha> [--operation <id> --generation <n> --attempt <n> --state <state> --transcript <id>]" 64 + shift 3; check_lane_name "$lane"; lane="$(canon_lane "$lane")" || exit 2 + pbh_digest=""; pbh_op=""; pbh_gen=""; pbh_attempt=""; pbh_state=""; pbh_sid="" + while [ "$#" -gt 0 ]; do + [ "$#" -ge 2 ] && [ -n "${2-}" ] || die "$1 needs a value" 64 + case "$1" in + --expect-digest) pbh_digest="$2" ;; + --operation) pbh_op="$2" ;; + --generation) pbh_gen="$2" ;; + --attempt) pbh_attempt="$2" ;; + --state) pbh_state="$2" ;; + --transcript) pbh_sid="$2" ;; + *) die "unknown publish-handoff flag $1" 64 ;; + esac + shift 2 + done + [ "${#pbh_digest}" = 64 ] || die "publication requires the complete prior SHA-256" 64 + case "$pbh_digest" in *[!0-9a-fA-F]*) die "publication requires SHA-256" 64 ;; esac + [ -f "$pbh_source" ] && [ -r "$pbh_source" ] && [ -s "$pbh_source" ] || die "the prepared handoff is unreadable or empty" 1 + acquire_lock + managed_seam_refuse "$lane" "publish-handoff" + pbh_links=0 + while [ -L "$pbh_target" ]; do + pbh_links=$((pbh_links+1)); [ "$pbh_links" -lt 40 ] || die "the handoff link chain cannot be resolved" 2 + pbh_link="$(readlink "$pbh_target")" || die "the handoff link could not be read" 1 + case "$pbh_link" in /*) pbh_target="$pbh_link" ;; *) pbh_target="$(dirname -- "$pbh_target")/$pbh_link" ;; esac + done + pbh_parent="$( CDPATH=''; cd -P -- "$(dirname -- "$pbh_target")" && pwd -P )" || die "the handoff parent is missing" 1 + pbh_target="$pbh_parent/$(basename -- "$pbh_target")" + [ -f "$pbh_target" ] && [ -r "$pbh_target" ] || die "the handoff target is unreadable" 1 + pbh_irc=0; pbh_intent="$(lane_restart_read "$lane")" || pbh_irc=$? + case "$pbh_irc" in 0|8) : ;; *) release_lock; die "restart ownership could not be read; no handoff was published" 1 ;; esac + pbh_current="$(printf '%s\n' "$pbh_intent" | awk -F'\t' '$1=="state" {print $2; exit}')" + case "$pbh_current" in UNKNOWN-*|INCOMPLETE) release_lock; die "restart ownership is malformed; no handoff was published" 2 ;; esac + if [ -n "$pbh_op" ]; then + [ -n "$pbh_gen" ] && [ -n "$pbh_attempt" ] && [ -n "$pbh_state" ] && [ -n "$pbh_sid" ] || { release_lock; die "operation publication needs generation, attempt, state and transcript fences" 64; } + pbh_actual="$(printf '%s\n' "$pbh_intent" | awk -F'\t' ' + $1=="operation" {o=$2} $1=="generation" {g=$2} $1=="attempt" {a=$2} $1=="state" {s=$2} $1=="new_transcript" {t=$2} + END {printf "%s|%s|%s|%s|%s",o,g,a,s,t}')" + [ "$pbh_actual" = "$pbh_op|$pbh_gen|$pbh_attempt|$pbh_state|$pbh_sid" ] || { release_lock; die "this handoff publisher lost restart ownership; nothing was published" 7; } + pbh_bound="$(printf '%s\n' "$pbh_intent" | awk -F'\t' '$1=="handoff" {print $2; exit}')" + [ -n "$pbh_bound" ] && [ "$pbh_bound" != none ] && [ "$pbh_bound" -ef "$pbh_target" ] || + { release_lock; die "the publication target is not the operation-bound handoff; nothing was published" 2; } + else + case "$pbh_current" in preparing|pending|starting) release_lock; die "an active restart owns this handoff; nothing was published" 7 ;; esac + fi + [ "$(lane_handoff_digest "$pbh_target")" = "$pbh_digest" ] || { release_lock; die "the handoff changed before publication; nothing was published" 7; } + pbh_tmp="$(mktemp "$pbh_target.resume.XXXXXX")" || { release_lock; die "the publication temporary file could not be made" 1; } + if ! cp -p -- "$pbh_target" "$pbh_tmp" || ! cat -- "$pbh_source" > "$pbh_tmp" || ! mv -f -- "$pbh_tmp" "$pbh_target"; then + rm -f -- "$pbh_tmp"; release_lock; die "the handoff could not be published atomically" 1 + fi + release_lock + printf '%s\n' "$pbh_target" + ;; + + legacy-restart-check) + lane="${1-}"; check_lane_name "$lane" + lane="$(canon_lane "$lane")" || exit 2 + managed_seam_refuse "$lane" "legacy-restart-check" + # Use the managed service's affirmative read when that installation exists. + # Exit 8 means confirmed absence; every unknown/error answer refuses. + lrc_managed="${SELF%/*}/lane-managed" + if [ -e "$lrc_managed" ] || [ -L "$lrc_managed" ]; then + [ -f "$lrc_managed" ] && [ -r "$lrc_managed" ] && [ -x "$lrc_managed" ] || + die "the installed managed ownership reader is unusable. Legacy restart refuses without writing or launching." 1 + lrc_rc=0 + LANES_NO_FETCH=1 "$lrc_managed" legacy-check --lane "$lane" >/dev/null || lrc_rc=$? + case "$lrc_rc" in + 8) exit 0 ;; + 0) die "lane $lane is managed. Legacy /ctx restart refuses; use the managed service. Its JSON ledger is the sole authority." 2 ;; + *) die "managed ownership for lane $lane could not be confirmed. Legacy restart refuses without writing or launching." 1 ;; + esac + fi + # A missing executable cannot mean missing enrollment. Probe only the + # private workspace's Git common directory, never this code checkout. + lrc_common="$(git -C "$LANES_REPO" rev-parse --git-common-dir)" || + die "the workspace Git common directory could not be read. Legacy restart refuses." 1 + case "$lrc_common" in /*) : ;; *) lrc_common="$LANES_REPO/$lrc_common" ;; esac + lrc_root="$lrc_common/openrepotools-managed" + if [ -e "$lrc_root" ] || [ -L "$lrc_root" ]; then + [ -d "$lrc_root" ] && [ -r "$lrc_root" ] && [ -x "$lrc_root" ] && [ ! -L "$lrc_root" ] || + die "managed ownership storage is unreadable or unsafe. Legacy restart refuses." 1 + lrc_key="$(lc "$lane")" + for lrc_host in "$lrc_root"/*; do + [ -e "$lrc_host" ] || [ -L "$lrc_host" ] || continue + [ -d "$lrc_host" ] && [ -r "$lrc_host" ] && [ -x "$lrc_host" ] && [ ! -L "$lrc_host" ] || + die "managed host ownership storage is unreadable or unsafe. Legacy restart refuses." 1 + if [ -e "$lrc_host/$lrc_key" ] || [ -L "$lrc_host/$lrc_key" ]; then + die "lane $lane has managed ownership storage. Legacy /ctx restart refuses; install/use its managed service to read the JSON authority." 2 + fi + done + fi + ;; + + set-restart-intent) + lane="${1-}"; [ -n "$lane" ] || die "usage: set-restart-intent <lane> <preparing|pending|starting|failed|ready> [--expect <STATE[|STATE…]|none>] [--expect-generation <n>] [--expect-operation <id>] [--operation <id>] [--generation <n>] [--mode <word>] [--agent <name>] [--profile <name>] [--dir <path>] [--pane <ref>] [--window <ref>] [--handoff <path>] [--digest <sha|none>] [--old-transcript <id>] [--new-transcript <id>] [--attempt <n>] [--bump-attempt] [--reason <text>]" 64 + shift + sri_state="${1-}"; [ -n "$sri_state" ] || die "set-restart-intent needs the state to move to: preparing, pending, starting, failed or ready" 64 + shift + sri_exp=""; sri_expg=""; sri_expo=""; sri_expa=""; sri_expn=""; sri_op=""; sri_gen=""; sri_mode="" + sri_agent=""; sri_prof=""; sri_dir=""; sri_pane=""; sri_win=""; sri_hf="" + sri_dig=""; sri_prepared=""; sri_old=""; sri_new=""; sri_att=""; sri_bump=0; sri_reason="" + # THE TWO SPELLINGS OF ONE FLAG GIVE ONE ANSWER (#26, the review of + # `c3ebcfe`, and `lane-start` carries the same paragraph at its own + # arguments). `--flag ""` refused an empty value here and `--flag=` took + # one, so the `=` spelling of an empty operation, generation, attempt or + # expectation read as ABSENT — and every rung below the flag then ran on a + # value the operator DID give: an `--expect=` would have fenced on nothing, + # an `--expect-operation=` would have claimed an operation it was not + # entitled to. The six that refuse an empty value refuse it in both + # spellings; the ones below that take `[ "$#" -ge 2 ]` deliberately ACCEPT + # an empty value in both, because `none` is an answer for those fields. + while [ $# -gt 0 ]; do + case "$1" in + --expect) sri_exp="${2-}"; [ -n "$sri_exp" ] || die "--expect needs a state word, 'none', or a '|'-separated set of them" 64; shift 2 ;; + --expect=*) sri_exp="${1#--expect=}"; [ -n "$sri_exp" ] || die "--expect needs a state word, 'none', or a '|'-separated set of them" 64; shift ;; + --expect-generation) sri_expg="${2-}"; [ -n "$sri_expg" ] || die "--expect-generation needs a number" 64; shift 2 ;; + --expect-generation=*) sri_expg="${1#--expect-generation=}"; [ -n "$sri_expg" ] || die "--expect-generation needs a number" 64; shift ;; + --expect-attempt) sri_expa="${2-}"; [ -n "$sri_expa" ] || die "--expect-attempt needs a number" 64; shift 2 ;; + --expect-attempt=*) sri_expa="${1#--expect-attempt=}"; [ -n "$sri_expa" ] || die "--expect-attempt needs a number" 64; shift ;; + --prepared-digest) sri_prepared="${2-}"; [ -n "$sri_prepared" ] || die "--prepared-digest needs a checksum" 64; shift 2 ;; + --prepared-digest=*) sri_prepared="${1#--prepared-digest=}"; [ -n "$sri_prepared" ] || die "--prepared-digest needs a checksum" 64; shift ;; + --expect-new-transcript) sri_expn="${2-}"; [ -n "$sri_expn" ] || die "--expect-new-transcript needs an id or none" 64; shift 2 ;; + --expect-new-transcript=*) sri_expn="${1#--expect-new-transcript=}"; [ -n "$sri_expn" ] || die "--expect-new-transcript needs an id or none" 64; shift ;; + --expect-operation) sri_expo="${2-}"; [ -n "$sri_expo" ] || die "--expect-operation needs an operation id" 64; shift 2 ;; + --expect-operation=*) sri_expo="${1#--expect-operation=}"; [ -n "$sri_expo" ] || die "--expect-operation needs an operation id" 64; shift ;; + --operation) sri_op="${2-}"; [ -n "$sri_op" ] || die "--operation needs an operation id" 64; shift 2 ;; + --operation=*) sri_op="${1#--operation=}"; [ -n "$sri_op" ] || die "--operation needs an operation id" 64; shift ;; + --generation) sri_gen="${2-}"; [ -n "$sri_gen" ] || die "--generation needs a number" 64; shift 2 ;; + --generation=*) sri_gen="${1#--generation=}"; [ -n "$sri_gen" ] || die "--generation needs a number" 64; shift ;; + --mode) sri_mode="${2-}"; [ "$#" -ge 2 ] || die "--mode needs a value" 64; shift 2 ;; + --mode=*) sri_mode="${1#--mode=}"; shift ;; + --agent) sri_agent="${2-}"; [ "$#" -ge 2 ] || die "--agent needs a value" 64; shift 2 ;; + --agent=*) sri_agent="${1#--agent=}"; shift ;; + --profile) sri_prof="${2-}"; [ "$#" -ge 2 ] || die "--profile needs a value" 64; shift 2 ;; + --profile=*) sri_prof="${1#--profile=}"; shift ;; + --dir) sri_dir="${2-}"; [ "$#" -ge 2 ] || die "--dir needs a value" 64; shift 2 ;; + --dir=*) sri_dir="${1#--dir=}"; shift ;; + --pane) sri_pane="${2-}"; [ "$#" -ge 2 ] || die "--pane needs a value" 64; shift 2 ;; + --pane=*) sri_pane="${1#--pane=}"; shift ;; + --window) sri_win="${2-}"; [ "$#" -ge 2 ] || die "--window needs a value" 64; shift 2 ;; + --window=*) sri_win="${1#--window=}"; shift ;; + --handoff) sri_hf="${2-}"; [ "$#" -ge 2 ] || die "--handoff needs a value" 64; shift 2 ;; + --handoff=*) sri_hf="${1#--handoff=}"; shift ;; + --digest) sri_dig="${2-}"; [ "$#" -ge 2 ] || die "--digest needs a value" 64; shift 2 ;; + --digest=*) sri_dig="${1#--digest=}"; shift ;; + --old-transcript) sri_old="${2-}"; [ "$#" -ge 2 ] || die "--old-transcript needs a value" 64; shift 2 ;; + --old-transcript=*) sri_old="${1#--old-transcript=}"; shift ;; + --new-transcript) sri_new="${2-}"; [ "$#" -ge 2 ] || die "--new-transcript needs a value" 64; shift 2 ;; + --new-transcript=*) sri_new="${1#--new-transcript=}"; shift ;; + --attempt) sri_att="${2-}"; [ -n "$sri_att" ] || die "--attempt needs a number" 64; shift 2 ;; + --attempt=*) sri_att="${1#--attempt=}"; [ -n "$sri_att" ] || die "--attempt needs a number" 64; shift ;; + --bump-attempt) sri_bump=1; shift ;; + --reason) sri_reason="${2-}"; [ "$#" -ge 2 ] || die "--reason needs a value" 64; shift 2 ;; + --reason=*) sri_reason="${1#--reason=}"; shift ;; + --) shift ;; + *) die "unknown option '$1' for set-restart-intent" 64 ;; + esac + done + lane_restart_word_ok "$sri_state" || + die "'$sri_state' is not a restart-intent state: preparing, pending, starting, failed and ready are the supported states" 64 + # THE FOUR VALUES THAT ARE KEYS AND NOT PROSE. An operation id, a launch + # mode, an agent and a profile are MANIFEST KEYS everywhere else in this + # estate — letters, digits, `.`, `_`, `-` — and each of them is compared + # for equality by a later reader (`--expect-operation`, the supervisor's + # own fence, `lane-start --agent`). A value carrying a space, a `;` or a + # newline is a value no such comparison can be trusted with, and this file + # is written one `key: value` line at a time. + for sri_k in "operation=$sri_op" "mode=$sri_mode" "agent=$sri_agent" "profile=$sri_prof" \ + "expect-operation=$sri_expo"; do + sri_kv="${sri_k#*=}" + [ -n "$sri_kv" ] || continue + case "$sri_kv" in + *[!A-Za-z0-9._-]*) die "--${sri_k%%=*} takes a manifest key — letters, digits, '.', '_' and '-' — because a later reader compares it for equality and this record is one line per field. Got '$sri_kv'." 64 ;; + esac + done + case "$sri_gen$sri_att$sri_expa" in *[!0-9]*) die "--generation and --attempt take numbers" 64 ;; esac + case "$sri_expg" in + '') : ;; + *[!0-9]*) die "--expect-generation takes a number; '$sri_expg' is not one" 64 ;; + esac + # A DIRECTORY IN THIS RECORD IS ABSOLUTE OR IT IS NOTHING, and the same for + # the handoff: the reader of this file is a DIFFERENT PROCESS IN A + # DIFFERENT DIRECTORY — the supervisor in a respawned pane — and a relative + # path resolved against its cwd is a path to somewhere else. `~` is the + # writing shell's and is never expanded here. + case "$sri_dir" in ''|/*) : ;; *) die "--dir takes an ABSOLUTE path: this record is read by the supervisor in a pane whose working directory is not this one, and a relative path there names a different place. Got '$sri_dir'." 64 ;; esac + case "$sri_hf" in ''|/*) : ;; *) die "--handoff takes an ABSOLUTE path, for the same reason --dir does: the launch that reads it back stands somewhere else. Got '$sri_hf'." 64 ;; esac + for sri_exact in "$sri_dir" "$sri_pane" "$sri_win" "$sri_hf" "$sri_old" "$sri_new" "$sri_dig" "$sri_prepared"; do + lane_restart_value_ok "$sri_exact" || die "restart launch facts cannot contain control characters. Nothing was written." 64 + done + check_lane_name "$lane" + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + # Select the physical intent under the CAS mutex: a waiting writer must + # see a reservation another writer established before releasing the lock. + acquire_lock + managed_seam_refuse "$lane" "set-restart-intent" + sri_root=""; sri_rrc=0 + sri_root="$(lane_restart_control_root "$lane")" || sri_rrc=$? + [ "$sri_rrc" = 0 ] || { + release_lock + die "lane $lane's restart control root is unavailable, unreadable or ambiguous. Nothing was written. Inspect its recorded directory and projects-root intents, or configure LANES_LANE_STATE_ROOT explicitly." 1 + } + sri_f="$sri_root/restart-intent.yaml" + # A SCHEMA THIS WRITER DOES NOT KNOW IS NOT ITS RECORD TO REPLACE (Copilot + # round 1 on openRepoTools#121). The READ side already fails closed on one — + # it answers `UNKNOWN-SCHEMA` rather than reporting a launch it cannot + # understand — and the WRITE side walked straight past it: the fields it + # knows were copied forward, the ones it does not were dropped, and the file + # came out stamped `schema: 1`. A newer tooling's intent would have been + # silently rewritten as an older one's, which is the read-side protection + # undone by the other half of the same command. This is checked INSIDE the + # lock, with the fence, because the file may be replaced between a read and + # a write, and it refuses with 2 — not 7 — because 7 is *another act got + # there first, re-read and decide* and this is *this copy of the tooling + # must not touch this file at all*. + if [ -e "$sri_f" ] || [ -L "$sri_f" ]; then + if [ ! -f "$sri_f" ] || [ ! -r "$sri_f" ]; then + release_lock + die "lane $lane has an existing unreadable restart intent. Nothing was written: a failed read is not an absent operation." 1 + fi + sri_missing="$(lane_restart_missing "$sri_f" "$lane")" || { release_lock; die "the restart record could not be read. Nothing was written." 1; } + [ -z "$sri_missing" ] || { release_lock; die "the existing restart record is malformed (missing, duplicate or invalid fields: $sri_missing). Nothing was written." 2; } + sri_nows="$(lane_restart_sidecar_field "$sri_f" schema)" || { release_lock; die "the restart schema could not be read. Nothing was written." 1; } + if [ "$sri_nows" != "$LANE_RESTART_SCHEMA" ]; then + release_lock + die "lane $lane's restart intent is schema '$sri_nows' and this \`lanes-edit.sh\` writes schema $LANE_RESTART_SCHEMA. Nothing was written: taking a transition over it would copy forward the fields this version knows, drop the ones it does not, and stamp the file as an older schema — which is a newer tooling's record quietly replaced by an older one. Read it with a helper that knows that schema, or remove $sri_f once you know no restart is in flight." 2 + fi + fi + sri_now=""; sri_nowg=""; sri_nowo=""; sri_nowa=""; sri_nown="" + if [ -r "$sri_f" ]; then + sri_now="$(lane_restart_sidecar_field "$sri_f" state)" + sri_nowg="$(lane_restart_sidecar_field "$sri_f" generation)" + sri_nowo="$(lane_restart_sidecar_field "$sri_f" operation)" + sri_nowa="$(lane_restart_sidecar_field "$sri_f" attempt)" + sri_nown="$(lane_restart_sidecar_field "$sri_f" new_transcript)" + fi + if [ -r "$sri_f" ]; then + lane_restart_word_ok "$sri_now" || { release_lock; die "the existing restart state is malformed. Nothing was written." 2; } + case "$sri_nowg:$sri_nowa" in *[!0-9:]*|:*|*:) release_lock; die "the existing restart generation or attempt is malformed. Nothing was written." 2 ;; esac + fi + sri_fence="" + # `--expect` TAKES A SET, because the states a caller is entitled to write + # over are usually more than one and asking for them in two calls is a + # second read-then-write with a window between. `pending` is created over + # `none|ready|failed` and never over `pending|starting`, which is the + # spec's *an ordinary `/ctx` does not supersede an operation in flight* + # expressed as one argument. + if [ -n "$sri_exp" ]; then + sri_match=0 + sri_rest="$sri_exp" + while [ -n "$sri_rest" ]; do + case "$sri_rest" in + *'|'*) sri_one="${sri_rest%%|*}"; sri_rest="${sri_rest#*|}" ;; + *) sri_one="$sri_rest"; sri_rest="" ;; + esac + [ "$sri_one" = none ] || lane_restart_word_ok "$sri_one" || + { release_lock; die "--expect takes restart-intent states or 'none'; '$sri_one' is neither" 64; } + [ "$sri_one" = "${sri_now:-none}" ] && sri_match=1 + done + [ "$sri_match" = 1 ] || sri_fence="the intent is ${sri_now:-none} and --expect named $sri_exp" + fi + [ -z "$sri_expg" ] || [ "$sri_expg" = "${sri_nowg:-0}" ] || sri_fence="${sri_fence:+$sri_fence; }generation is ${sri_nowg:-0} and --expect-generation named $sri_expg" + [ -z "$sri_expo" ] || [ "$sri_expo" = "${sri_nowo:-none}" ] || sri_fence="${sri_fence:+$sri_fence; }operation is ${sri_nowo:-none} and --expect-operation named $sri_expo" + [ -z "$sri_expa" ] || [ "$sri_expa" = "${sri_nowa:-0}" ] || sri_fence="${sri_fence:+$sri_fence; }attempt is ${sri_nowa:-0} and --expect-attempt named $sri_expa" + [ -z "$sri_expn" ] || [ "$sri_expn" = "${sri_nown:-none}" ] || sri_fence="${sri_fence:+$sri_fence; }prepared transcript is ${sri_nown:-none} and --expect-new-transcript named $sri_expn" + if [ -n "$sri_fence" ]; then + release_lock + printf 'state\t%s\ngeneration\t%s\noperation\t%s\nattempt\t%s\n' \ + "${sri_now:-none}" "${sri_nowg:-0}" "${sri_nowo:-none}" "${sri_nowa:-0}" + die "lane $lane's restart intent did not move to $sri_state: $sri_fence. Another act got there first — a second /ctx, a supervisor that claimed this operation, or a resume that finished it — and nothing was written. Re-read it (lanes-edit.sh restart-intent $lane) before deciding what this process should do; a stale supervisor must never overwrite a newer operation." 7 + fi + case "$sri_nowg" in ''|*[!0-9]*) sri_nowg=0 ;; esac + case "$sri_nowa" in ''|*[!0-9]*) sri_nowa=0 ;; esac + # A TRANSITION THAT DOES NOT NAME A FIELD KEEPS IT, and does not blank it — + # the same rule `set-lane-state` takes, and for the same reason: a + # `starting` written by the supervisor is about the STATE, and blanking the + # handoff digest out of that call would lose the one fact every later + # launch and retry is fenced on. + sri_keep() { # <key> <value the caller gave> + [ -n "${2-}" ] && { printf '%s' "$2"; return 0; } + lane_restart_sidecar_field "$sri_f" "$1" 2>/dev/null || : + } + sri_gen="$(sri_keep generation "$sri_gen")"; [ -n "$sri_gen" ] || sri_gen="$sri_nowg" + sri_op="$(sri_keep operation "$sri_op")"; [ -n "$sri_op" ] || sri_op="$(lane_restart_op_id)" + sri_prepared="$(sri_keep prepared_digest "$sri_prepared")" + sri_mode="$(sri_keep mode "$sri_mode")" + sri_agent="$(sri_keep agent "$sri_agent")" + sri_prof="$(sri_keep profile "$sri_prof")" + sri_dir="$(sri_keep dir "$sri_dir")" + sri_pane="$(sri_keep pane "$sri_pane")" + sri_win="$(sri_keep window "$sri_win")" + sri_hf="$(sri_keep handoff "$sri_hf")" + # …EXCEPT WHERE THE OPERATION ITSELF HAS CHANGED, and then five of these + # fields are not this act's facts at all. `old_transcript`, + # `new_transcript`, `attempt`, `reason` and `created` are scoped to ONE + # operation: the transcript that restart paused, the transcript its launch + # was preparing, how many times THAT launch was tried, why THAT one failed, + # and when THAT intent was made. Carrying them into the next operation is + # how a brand-new `/ctx` comes out reading `attempt 3` and `reason "the + # launcher exited 127"` from a restart that is over — and two of them are + # worse than cosmetic, because the supervisor's readiness predicate is + # built on exactly this pair: + # + # * an inherited `new_transcript` is a uuid THIS launch will never mint, + # so readiness can only run to its deadline and report indeterminate; + # * an inherited `old_transcript` is the wrong uuid to be distinct FROM, + # and that check is the one that catches openRepoTools#94 itself — a + # replacement that came up resuming the transcript this `/ctx` paused. + # Comparing it against some earlier restart's transcript would let the + # measured defect through the very predicate written to catch it. + # + # A caller that names one of the five still wins; this only decides what an + # UNNAMED field falls back to, and `none` is an answer where another + # operation's value is a lie. + sri_newop=0 + [ "$sri_op" = "${sri_nowo:-none}" ] || sri_newop=1 + if [ "$sri_newop" = 1 ]; then sri_prepared=none; fi + if [ "$sri_newop" != 1 ]; then + sri_old="$(sri_keep old_transcript "$sri_old")" + sri_new="$(sri_keep new_transcript "$sri_new")" + sri_reason="$(sri_keep reason "$sri_reason")" + fi + # THE DIGEST IS COMPUTED HERE WHERE THE CALLER NAMED A HANDOFF AND NO + # DIGEST, so that there is ONE implementation of *what this handoff was + # when the intent was made* and a caller cannot accidentally record a + # digest of something else. + if [ -z "$sri_dig" ]; then + case "$sri_hf" in + /*) if [ "$sri_state" = pending ] && [ -r "$sri_hf" ]; then + sri_dig="$(lane_handoff_digest "$sri_hf")" + else + sri_dig="$(lane_restart_sidecar_field "$sri_f" digest 2>/dev/null || :)" + fi ;; + *) sri_dig="$(lane_restart_sidecar_field "$sri_f" digest 2>/dev/null || :)" ;; + esac + fi + # THE ATTEMPT COUNT. `--bump-attempt` is the retry's own act and is the one + # thing that may not be inferred: a supervisor claiming a NEW operation + # starts at 1, and a retry of the SAME one increments. + if [ -n "$sri_att" ]; then + : + elif [ "$sri_bump" = 1 ]; then + sri_att=$((sri_nowa + 1)) + elif [ "$sri_newop" = 1 ]; then + sri_att=0 + else + sri_att="$sri_nowa" + fi + # AND `created` IS THIS OPERATION'S OWN, for the same reason: it is read as + # *when this restart was taken*, and a new operation inheriting the last + # one's timestamp says a `/ctx` happened at a moment it did not. + if [ "$sri_newop" = 1 ]; then + sri_created="" + else + sri_created="$(lane_restart_sidecar_field "$sri_f" created 2>/dev/null || :)" + fi + if lane_restart_put "$sri_root" "$lane" "$sri_state" "$sri_gen" "$sri_op" \ + "$sri_mode" "$sri_agent" "$sri_prof" "$sri_dir" "$sri_pane" "$sri_win" \ + "$sri_hf" "$sri_dig" "$sri_old" "$sri_new" "$sri_att" "$sri_reason" \ + "$sri_created" "$sri_prepared"; then + release_lock + printf 'state\t%s\ngeneration\t%s\noperation\t%s\nattempt\t%s\ndigest\t%s\nfile\t%s\n' \ + "$sri_state" "$sri_gen" "$sri_op" "$sri_att" "${sri_dig:-none}" "$sri_f" + else + release_lock + die "lane $lane's restart intent could not be written under $sri_root (the shell's own error is above). Nothing was changed: the intent is replaced atomically, so the one that was there is the one that is there." 1 + fi + ;; + + # ---------- THE SEAM: is this lane the managed ledger's? (ruling 2026-10-04) + # + # 0 a valid managed-owner marker: the owner is printed + # 8 no marker and no managed-owner vocabulary, in the published row or + # this checkout's: a legacy lane + # 1 vocabulary that does not parse, vocabulary only this checkout's row + # carries (#157 item 4a, as `managed_seam_refuse` reads it), or a + # register that could not be read: ownership UNKNOWN, which a caller + # refuses on exactly as it refuses 0 + # 64 usage + managed-projection) + lane="${1-}"; [ -n "$lane" ] || die "usage: managed-projection <lane>" 64 + [ "$#" -le 1 ] || die "managed-projection takes one lane: managed-projection <lane>" 64 + check_lane_name "$lane" + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + mpj_out=""; mpj_rc=0 + mpj_out="$(lane_is_managed_owned "$lane")" || mpj_rc=$? + case "$mpj_rc" in + 0) printf '%s\n' "$mpj_out" ;; + 8) + managed_local_hint "$lane" || + die "lane $lane's row in this checkout's register file, $LANES_FILE, carries managed-owner vocabulary (or could not be read) where the published register's, origin/$LANES_BRANCH, does not: the two copies disagree on whether the managed ledger owns it, so that is UNKNOWN, and it is never read as 'legacy' (Amendment 7(d)) — every legacy writer refuses it for the same reason. $(managed_local_remedy)" 1 + exit 8 ;; + *) die "lane $lane's register row carries managed-owner vocabulary that does not parse as a marker, or the register could not be read: whether the managed ledger owns it is UNKNOWN, and that is never read as 'legacy' (Amendment 7(d))." 1 ;; + esac + ;; + + # ---------- openRepoTools#91: the lifecycle, the inventory, the reconcile + # + # ALL FIVE ANSWER OUT OF THE LOCAL CONTROL ROOT and none of them touches the + # register, the object log or the network. The two WRITERS are deliberately + # absent from the dispatcher's workstation guard above (`R-A11-14` is about a + # record FILED UNDER A WORKSTATION; this one is filed under nothing and never + # leaves the machine that wrote it), and they take the same 64-for-usage + # contract every read Amendment 11 added takes, because they sit in front of + # a launch exactly as those do. + # + # 0 done + # 1 no control root could be derived, or it could not be written; or a + # WRITER met a record there it cannot read — of a schema it does not + # write, or of its own and not a whole record (#115) — and replaced + # nothing; or `lane-tree-now` met a git read that failed + # 2 a refusal of the arguments + # 7 THE FENCE DID NOT MATCH — another act got there first, which is what + # this file already spends 7 on (`claim`'s CLAIM-LOST). Nothing was + # written and the current state is printed. `set-lane-tree` spends it + # too where the lane is `SWAPPED`: the operation its fence names is + # finished (#114). + # 8 there is no such record (no snapshot, no tree) + # 10 THE RECORD IS THERE AND COULD NOT BE READ, which is never 8 (Copilot + # round 6 on #97). 8 tells a launcher *this lane was never migrated, go + # on*; 10 tells it *this lane may be mid-crash and nobody could look*. + # (It was 9 until main's #61 spent 9 on `claim`'s abandoned takeover.) + # A snapshot of this schema that is not a whole record is 10 as well + # (#115): nothing can be read out of it as a snapshot. + # 64 a usage error of this subcommand's own — for `set-lane-tree`, a + # partial observation, a `--dirty`/`--unpushed` that is not a count + # (`unknown` is one for `--unpushed`), or a field that is only blanks + + lane-state) + lane="${1-}"; [ -n "$lane" ] || die "usage: lane-state <lane>" 64 + [ "$#" -le 1 ] || die "lane-state takes one lane: lane-state <lane>" 64 + check_lane_name "$lane" + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + lst_out=""; lst_rc=0 + lst_out="$(lane_state_read "$lane")" || lst_rc=$? + case "$lst_rc" in + 0) : ;; + 8) exit 8 ;; + 10) + # WHICH OF THE TWO 10s (#115): a record that opens and is not a whole + # one of this schema is said as that, for the person who reads it. + lst_f="$(lane_control_root "$lane" 2>/dev/null || printf '<no control root>')/lane-state.yaml" + lst_what="it could not be read" + if [ -r "$lst_f" ] && ! lane_sidecar_schema_ok "$lst_f"; then lst_what="it is of this schema and $LSS_WHY, so nothing can be read out of it as a snapshot"; fi + die "lane $lane HAS a lifecycle snapshot at its control root and $lst_what. That is NOT 'this lane has no snapshot' — 8 says that, and a launcher answers an 8 by going on, which over an unreadable record would be a launch made in ignorance of a crash nobody could look at (R22, Amendment 7(d)). Read it by hand: $lst_f" 10 ;; + *) die "lane $lane has no lifecycle control root: its record names no directory (Amendment 11(c)) and \$PROJECTS_ROOT is not a directory here. That is NOT 'this lane is in no state' — a read that could not be made is never an answer (Amendment 7(d))." 1 ;; + esac + printf '%s\n' "$lst_out" + ;; + + set-lane-state) + lane="${1-}"; [ -n "$lane" ] || die "usage: set-lane-state <lane> <RUNNING|SWAPPING|SWAPPED|CLOSED> [--expect <STATE|none>] [--expect-generation <n>] [--expect-operation <id>] [--operation <id>] [--owner <uuid>] [--agent <name>] [--profile <name>] [--kind <word>]" 64 + shift + sls_state="${1-}"; [ -n "$sls_state" ] || die "set-lane-state needs the state to move to: RUNNING, SWAPPING, SWAPPED or CLOSED" 64 + shift + sls_exp=""; sls_expg=""; sls_expo=""; sls_op=""; sls_owner=""; sls_agent=""; sls_prof=""; sls_kind="" + while [ $# -gt 0 ]; do + case "$1" in + --expect) sls_exp="${2-}"; [ -n "$sls_exp" ] || die "--expect needs a state word, or 'none'" 64; shift 2 ;; + --expect=*) sls_exp="${1#--expect=}"; [ -n "$sls_exp" ] || die "--expect needs a value" 64; shift ;; + --expect-generation) sls_expg="${2-}"; [ -n "$sls_expg" ] || die "--expect-generation needs a number" 64; shift 2 ;; + --expect-generation=*) sls_expg="${1#--expect-generation=}"; [ -n "$sls_expg" ] || die "--expect-generation needs a value" 64; shift ;; + --expect-operation) sls_expo="${2-}"; [ -n "$sls_expo" ] || die "--expect-operation needs an operation id" 64; shift 2 ;; + --expect-operation=*) sls_expo="${1#--expect-operation=}"; [ -n "$sls_expo" ] || die "--expect-operation needs a value" 64; shift ;; + --operation) sls_op="${2-}"; [ -n "$sls_op" ] || die "--operation needs an operation id" 64; shift 2 ;; + --operation=*) sls_op="${1#--operation=}"; [ -n "$sls_op" ] || die "--operation needs a value" 64; shift ;; + --owner) sls_owner="${2-}"; [ "$#" -ge 2 ] && [ -n "$sls_owner" ] || die "--owner needs a value" 64; shift 2 ;; + --owner=*) sls_owner="${1#--owner=}"; [ -n "$sls_owner" ] || die "--owner needs a value" 64; shift ;; + --agent) sls_agent="${2-}"; [ "$#" -ge 2 ] && [ -n "$sls_agent" ] || die "--agent needs a value" 64; shift 2 ;; + --agent=*) sls_agent="${1#--agent=}"; [ -n "$sls_agent" ] || die "--agent needs a value" 64; shift ;; + --profile) sls_prof="${2-}"; [ "$#" -ge 2 ] && [ -n "$sls_prof" ] || die "--profile needs a value" 64; shift 2 ;; + --profile=*) sls_prof="${1#--profile=}"; [ -n "$sls_prof" ] || die "--profile needs a value" 64; shift ;; + --kind) sls_kind="${2-}"; [ "$#" -ge 2 ] && [ -n "$sls_kind" ] || die "--kind needs a value" 64; shift 2 ;; + --kind=*) sls_kind="${1#--kind=}"; [ -n "$sls_kind" ] || die "--kind needs a value" 64; shift ;; + --) shift ;; + *) die "unknown option '$1' for set-lane-state" 64 ;; + esac + done + lane_state_word_ok "$sls_state" || die "'$sls_state' is not a lane lifecycle state: RUNNING, SWAPPING, SWAPPED and CLOSED are the four, and a fifth word in this file would be a state no reader of it knows" 64 + [ -z "$sls_exp" ] || [ "$sls_exp" = none ] || lane_state_word_ok "$sls_exp" || + die "--expect takes one of the four states, or 'none' for a lane that has no snapshot yet; '$sls_exp' is neither" 64 + case "$sls_expg" in + '') : ;; + *[!0-9]*) die "--expect-generation takes a number; '$sls_expg' is not one" 64 ;; + esac + check_lane_name "$lane" + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + managed_seam_refuse "$lane" "set-lane-state" # ruling 2026-10-04 + sls_root=""; sls_rrc=0 + sls_root="$(lane_control_root "$lane")" || sls_rrc=$? + [ "$sls_rrc" = 0 ] || + die "lane $lane has no lifecycle control root, so there is nowhere to record that it is $sls_state: its record names no directory (Amendment 11(c)) and \$PROJECTS_ROOT is not a directory here. Set \$LANES_LANE_STATE_ROOT, or start the lane through lane-start so that its record carries a dir." 1 + # THE FENCE, read under the same mutex the write takes, so that two + # transitions cannot both read the state before either writes it. + acquire_lock + # AND THE SCHEMA IS ASKED ABOUT BEFORE ANY TRANSITION FIELD IS READ OR + # WRITTEN (Copilot round 5 on #97). `lane_state_read` fails closed for a + # version it does not know; this writer used to walk past that check into + # the raw fields and rename its own file over the top, so an older helper + # meeting a newer tooling's snapshot destroyed a record it could not read — + # the one act no later reader can undo. It is a 1 and not a 7: 7 says a race + # was lost and invites the caller to re-read and try again, and no re-read + # makes this file readable by this helper. + if ! lane_sidecar_schema_ok "$sls_root/lane-state.yaml"; then + sls_sch="$(lane_sidecar_field "$sls_root/lane-state.yaml" schema 2>/dev/null || :)" + release_lock + die "lane $lane's lifecycle snapshot at $sls_root/lane-state.yaml records schema ${sls_sch:-<none>} and is not a record this helper can read: $LSS_WHY. NOTHING was read out of it and nothing was written over it: a record this helper cannot read is one it cannot safely replace, whether its schema is one this helper does not write or its own and the record is not whole (#115). Upgrade this workstation's lanes-edit.sh if a newer tooling wrote it; if you know what wrote that file, move it aside by hand and re-run." 1 + fi + sls_now=""; sls_nowg=""; sls_nowo="" + if [ -r "$sls_root/lane-state.yaml" ]; then + sls_now="$(lane_sidecar_field "$sls_root/lane-state.yaml" state)" + sls_nowg="$(lane_sidecar_field "$sls_root/lane-state.yaml" generation)" + sls_nowo="$(lane_sidecar_field "$sls_root/lane-state.yaml" operation)" + fi + sls_fence="" + [ -z "$sls_exp" ] || [ "$sls_exp" = "${sls_now:-none}" ] || sls_fence="state is ${sls_now:-none} and --expect named $sls_exp" + [ -z "$sls_expg" ] || [ "$sls_expg" = "${sls_nowg:-0}" ] || sls_fence="${sls_fence:+$sls_fence; }generation is ${sls_nowg:-0} and --expect-generation named $sls_expg" + [ -z "$sls_expo" ] || [ "$sls_expo" = "${sls_nowo:-none}" ] || sls_fence="${sls_fence:+$sls_fence; }operation is ${sls_nowo:-none} and --expect-operation named $sls_expo" + if [ -n "$sls_fence" ]; then + release_lock + printf 'state\t%s\ngeneration\t%s\noperation\t%s\n' "${sls_now:-none}" "${sls_nowg:-0}" "${sls_nowo:-none}" + die "lane $lane did not move to $sls_state: $sls_fence. Another act got there first — a resume that advanced the generation, or a second handoff — and nothing was written. Re-read the state (lanes-edit.sh lane-state $lane) before deciding what this process should do; a stale finalizer must never overwrite a newer owner." 7 + fi + case "$sls_nowg" in ''|*[!0-9]*) sls_nowg=0 ;; esac + # A TRANSITION THAT DOES NOT NAME A FIELD KEEPS IT, and does not blank it. + # `SWAPPED` is the same operation's commit point and `CLOSED` the end of a + # lane that was owned by somebody: writing `owner none` there would lose + # the one fact a later reconciliation compares a live holder against, out of + # a call that was only ever about the state word. + [ -n "$sls_owner" ] || sls_owner="$(lane_sidecar_field "$sls_root/lane-state.yaml" owner 2>/dev/null || :)" + [ -n "$sls_agent" ] || sls_agent="$(lane_sidecar_field "$sls_root/lane-state.yaml" agent 2>/dev/null || :)" + [ -n "$sls_prof" ] || sls_prof="$(lane_sidecar_field "$sls_root/lane-state.yaml" profile 2>/dev/null || :)" + [ -n "$sls_kind" ] || sls_kind="$(lane_sidecar_field "$sls_root/lane-state.yaml" kind 2>/dev/null || :)" + # WHICH TRANSITION ADVANCES THE GENERATION. A new owner or a new operation + # does (`RUNNING`, `SWAPPING`, `CLOSED`); the FINISH of an operation + # already in flight does not, because `SWAPPED` is the same operation + # reaching its commit point and a fence that moved under it would refuse + # the very finalizer that is entitled to write. + case "$sls_state" in + SWAPPED) sls_gen="$sls_nowg"; [ -n "$sls_op" ] || sls_op="${sls_nowo:-none}" ;; + *) sls_gen=$((sls_nowg + 1)); [ -n "$sls_op" ] || sls_op="$(lane_op_id)" ;; + esac + if lane_state_put "$sls_root" "$lane" "$sls_state" "$sls_gen" "$sls_op" \ + "$sls_owner" "$sls_agent" "$sls_prof" "$WS" "$sls_kind"; then + release_lock + LANES_INDEX_NUDGE_INV=1 # opensoft/openRepoTools#161: `cleanup` nudges the indexer + printf 'state\t%s\ngeneration\t%s\noperation\t%s\n' "$sls_state" "$sls_gen" "$sls_op" + else + release_lock + die "lane $lane's lifecycle snapshot could not be written under $sls_root (the shell's own error is above). Nothing was changed: the snapshot is replaced atomically, so the one that was there is the one that is there." 1 + fi + ;; + + lane-trees) + lane="${1-}"; [ -n "$lane" ] || die "usage: lane-trees <lane>" 64 + [ "$#" -le 1 ] || die "lane-trees takes one lane: lane-trees <lane>" 64 + check_lane_name "$lane" + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + ltr_out=""; ltr_rc=0 + ltr_out="$(lane_trees_list "$lane")" || ltr_rc=$? + case "$ltr_rc" in + 0) : ;; + 8) exit 8 ;; + 10) die "lane $lane's worktree inventory directory $(lane_control_root "$lane" 2>/dev/null || printf '<no control root>')/trees is there and could not be listed. That is NOT 'this lane recorded no tree' — 8 says that, and a reader that goes on over it relaunches writers onto trees nobody looked at (R22, Amendment 7(d)). Read it by hand." 10 ;; + *) die "lane $lane has no lifecycle control root, so its worktree inventory could not be read. That is NOT 'this lane owns no worktree' (Amendment 7(d))." 1 ;; + esac + printf '%s\n' "$ltr_out" + ;; + + set-lane-tree) + lane="${1-}"; [ -n "$lane" ] || die "usage: set-lane-tree <lane> <worktree path> [--checkout <dir>] [--branch <b>] [--head <sha>] [--upstream <ref>] [--dirty <n>] [--unpushed <n>] [--writer <uuid>] [--generation <n>] [--operation <id>]" 64 + shift + slt_path="${1-}"; [ -n "$slt_path" ] || die "set-lane-tree needs the worktree's path" 64 + shift + case "$slt_path" in /*) : ;; *) die "set-lane-tree takes an ABSOLUTE path: a relative one has no meaning to any later reader of this record, which is a different process in a different directory" 64 ;; esac + slt_co=""; slt_b=""; slt_h=""; slt_u=""; slt_d=""; slt_n=""; slt_w=""; slt_g=""; slt_op="" + while [ $# -gt 0 ]; do + case "$1" in + --checkout) slt_co="${2-}"; [ "$#" -ge 2 ] && [ -n "$slt_co" ] || die "--checkout needs a value" 64; shift 2 ;; + --checkout=*) slt_co="${1#--checkout=}"; [ -n "$slt_co" ] || die "--checkout needs a value" 64; shift ;; + --branch) slt_b="${2-}"; [ "$#" -ge 2 ] && [ -n "$slt_b" ] || die "--branch needs a value" 64; shift 2 ;; + --branch=*) slt_b="${1#--branch=}"; [ -n "$slt_b" ] || die "--branch needs a value" 64; shift ;; + --head) slt_h="${2-}"; [ "$#" -ge 2 ] && [ -n "$slt_h" ] || die "--head needs a value" 64; shift 2 ;; + --head=*) slt_h="${1#--head=}"; [ -n "$slt_h" ] || die "--head needs a value" 64; shift ;; + --upstream) slt_u="${2-}"; [ "$#" -ge 2 ] && [ -n "$slt_u" ] || die "--upstream needs a value" 64; shift 2 ;; + --upstream=*) slt_u="${1#--upstream=}"; [ -n "$slt_u" ] || die "--upstream needs a value" 64; shift ;; + --dirty) slt_d="${2-}"; [ "$#" -ge 2 ] && [ -n "$slt_d" ] || die "--dirty needs a value" 64; shift 2 ;; + --dirty=*) slt_d="${1#--dirty=}"; [ -n "$slt_d" ] || die "--dirty needs a value" 64; shift ;; + --unpushed) slt_n="${2-}"; [ "$#" -ge 2 ] && [ -n "$slt_n" ] || die "--unpushed needs a value" 64; shift 2 ;; + --unpushed=*) slt_n="${1#--unpushed=}"; [ -n "$slt_n" ] || die "--unpushed needs a value" 64; shift ;; + --writer) slt_w="${2-}"; [ "$#" -ge 2 ] && [ -n "$slt_w" ] || die "--writer needs a value" 64; shift 2 ;; + --writer=*) slt_w="${1#--writer=}"; [ -n "$slt_w" ] || die "--writer needs a value" 64; shift ;; + --generation) slt_g="${2-}"; [ "$#" -ge 2 ] && [ -n "$slt_g" ] || die "--generation needs a value" 64; shift 2 ;; + --generation=*) slt_g="${1#--generation=}"; [ -n "$slt_g" ] || die "--generation needs a value" 64; shift ;; + --operation) slt_op="${2-}"; [ "$#" -ge 2 ] && [ -n "$slt_op" ] || die "--operation needs a value" 64; shift 2 ;; + --operation=*) slt_op="${1#--operation=}"; [ -n "$slt_op" ] || die "--operation needs a value" 64; shift ;; + --) shift ;; + *) die "unknown option '$1' for set-lane-tree" 64 ;; + esac + done + check_lane_name "$lane" + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + managed_seam_refuse "$lane" "set-lane-tree" # ruling 2026-10-04 + slt_root=""; slt_rrc=0 + slt_root="$(lane_control_root "$lane")" || slt_rrc=$? + [ "$slt_rrc" = 0 ] || + die "lane $lane has no lifecycle control root, so its worktree inventory has nowhere to go: its record names no directory (Amendment 11(c)) and \$PROJECTS_ROOT is not a directory here." 1 + # WHAT THE CALLER SAW BEATS WHAT THIS PROCESS SEES, because a poll and a + # record written from it are ONE observation and a second reading of the + # same tree a moment later is a different one. Where the caller passed + # nothing, the tree is read HERE through the same `lane_tree_now` + # `lane-reconcile` recomputes with, so the two cannot disagree. + # + # AND AN OBSERVATION NOBODY COULD MAKE IS NOT COMPLETED WITH CLEAN-LOOKING + # VALUES (Copilot round 5 on #97). Until this round a `lane_tree_now` that + # failed left every field empty and `lane_tree_put`'s defaults wrote them as + # `unknown` / `none` / `0` — a record saying *branch unknown, nothing dirty, + # nothing unpushed* for a tree this process never read, which a later + # reconciliation would compare against and call published. + if [ -z "$slt_b$slt_h$slt_u$slt_d$slt_n" ]; then + slt_now=""; slt_nrc=0 + slt_now="$(lane_tree_now "$slt_path")" || slt_nrc=$? + case "$slt_nrc" in + 0) + slt_b="$(printf '%s' "$slt_now" | awk -F"$US" '{print $1}')" + slt_h="$(printf '%s' "$slt_now" | awk -F"$US" '{print $2}')" + slt_u="$(printf '%s' "$slt_now" | awk -F"$US" '{print $3}')" + slt_d="$(printf '%s' "$slt_now" | awk -F"$US" '{print $4}')" + slt_n="$(printf '%s' "$slt_now" | awk -F"$US" '{print $5}')" ;; + 1) die "no worktree was recorded for lane $lane: there is no directory at $slt_path and this command was given no observation of its own to file. A record of a tree nobody read would say 'branch unknown, 0 dirty, 0 unpushed', which a later reconciliation reads as clean and published. Pass what you saw (--branch/--head/--upstream/--dirty/--unpushed), or record the tree while it is there." 1 ;; + 2) die "no worktree was recorded for lane $lane: $slt_path exists and git does not answer in it, so there is no observation to file and this command invents none. The path itself was not touched." 1 ;; + *) die "no worktree was recorded for lane $lane: git answers in $slt_path and one of the reads an observation is made of FAILED, so nothing was written — a branch, a head, a status or an upstream that could not be read is never recorded as a clean tree (Amendment 7(d)). Read it by hand: git -C $slt_path status" 1 ;; + esac + # AND A CALLER'S OBSERVATION IS TAKEN WHOLE OR NOT AT ALL (Codex on ec9847e, + # PR #97). One flag alone used to skip the reading above and let the rest + # reach the record as `unknown`, `none` and — the dangerous two — `dirty 0` + # and `unpushed 0`, which a later reconciliation of a vanished tree reads as + # clean and published although nobody observed either. + elif [ -z "$slt_b" ] || [ -z "$slt_h" ] || [ -z "$slt_u" ] || [ -z "$slt_d" ] || [ -z "$slt_n" ]; then + die "set-lane-tree takes the caller's observation WHOLE — --branch, --head, --upstream, --dirty and --unpushed together — or none of them, when the tree is read here. A partial one would be filed with values nobody observed, and 'dirty 0, unpushed 0' is the record a later reconciliation reads as clean and published. Nothing was written." 64 + fi + # AND IN THE SHAPES A RECORD IS READ BACK IN (#115). The two counts are what + # a reconciliation decides with, and a record carrying one that is neither a + # count nor `unknown` is one no reader may use and no writer may replace — + # so it is refused here, before anything is written, rather than filed. + case "$slt_d" in + ''|*[!0-9]*) die "set-lane-tree's --dirty takes a count of the tree's dirty paths, and '$slt_d' is not one: a record carrying it could be neither read nor replaced. Nothing was written." 64 ;; + esac + case "$slt_n" in + unknown) : ;; + ''|*[!0-9]*) die "set-lane-tree's --unpushed takes a count of commits, or 'unknown' where the upstream is configured and its remote-tracking ref is not here; '$slt_n' is neither, and a record carrying it could be neither read nor replaced. Nothing was written." 64 ;; + esac + # AND NO FIELD THAT IS ONLY BLANKS (review r1 of #252). A reader trims a + # value, so `--branch ' '` files a record with no branch — one the rename + # below refused only after the lock, with exit 1 and "the shell's own error + # is above". It is the caller's usage, said as one, before anything is taken. + for slt_fv in "branch=$slt_b" "head=$slt_h" "upstream=$slt_u" "checkout=$slt_co" "writer=$slt_w"; do + case "${slt_fv#*=}" in + ''|*[![:space:]]*) : ;; + *) die "set-lane-tree's --${slt_fv%%=*} is only blanks: a reader trims a value, so the record would carry no ${slt_fv%%=*} and could be neither read nor replaced. Nothing was written." 64 ;; + esac + done + # THE FENCE, AND IT IS THE LANE'S OWN (Copilot round 5 on #97). A caller + # that names the generation and the operation it is recording under is + # saying *this observation belongs to that transition* — and until this + # round the pair was serialized into the sidecar and compared with nothing, + # so a handoff that stalled while a recovery advanced the lane filed its + # superseded poll straight over the current inventory. The pair is compared + # with the lane's own snapshot under the SAME mutex the transition takes, + # and the write happens inside that mutex, so a transition cannot land + # between the compare and the record. A caller that names NEITHER is making + # an observation of its own — a person, or the read above — and has no fence + # to fail. + # + # AND THE MUTEX IS TAKEN WHETHER OR NOT THERE IS A FENCE TO CHECK (Copilot + # round 6 on #97). It used to be taken only for a FENCED write, which left + # the unfenced ones — a person's `set-lane-tree`, a caller that named no + # transition — racing every other writer of the same sidecar: the atomic + # rename below stops a reader seeing half a file and stops nothing else, so + # an unfenced observation could land after a newer fenced one and replace + # it, and the inventory would then hold a reading older than the transition + # recorded beside it. One mutex over every write of these files, and the + # generation/operation comparison stays what it was for the callers that + # name one. + # + # IT IS TAKEN HERE AND NOT ABOVE THE OBSERVATION, because the observation + # runs `git status` and `git rev-list` in somebody's checkout and this lock + # is the whole workstation's (design decision 14, and the same argument that + # keeps `lane-reconcile` out of it): what must be serialized is the compare + # and the write, not the reading of a repository. + acquire_lock + if [ -n "$slt_g" ] || [ -n "$slt_op" ]; then + if ! lane_sidecar_schema_ok "$slt_root/lane-state.yaml"; then + release_lock + die "the worktree $slt_path was NOT recorded for lane $lane: its lifecycle snapshot is not a record this helper can read ($LSS_WHY), so the generation and operation this observation names cannot be compared with anything. Nothing was written. Upgrade this workstation's lanes-edit.sh if a newer tooling wrote it, or read the snapshot by hand." 1 + fi + slt_ng=""; slt_no=""; slt_ns="" + if [ -r "$slt_root/lane-state.yaml" ]; then + slt_ns="$(lane_sidecar_field "$slt_root/lane-state.yaml" state)" + slt_ng="$(lane_sidecar_field "$slt_root/lane-state.yaml" generation)" + slt_no="$(lane_sidecar_field "$slt_root/lane-state.yaml" operation)" + fi + slt_fence="" + [ -z "$slt_g" ] || [ "$slt_g" = "${slt_ng:-0}" ] || slt_fence="generation is ${slt_ng:-0} and --generation named $slt_g" + [ -z "$slt_op" ] || [ "$slt_op" = "${slt_no:-none}" ] || slt_fence="${slt_fence:+$slt_fence; }operation is ${slt_no:-none} and --operation named $slt_op" + # AND THE OPERATION MUST STILL BE OPEN (opensoft/openRepoTools#114 item 1). + # `SWAPPING -> SWAPPED` keeps the generation AND the operation by design — + # it is the same operation reaching its commit point, and a fence that + # moved under it would refuse the very finalizer entitled to write — so the + # two values alone accepted a poll from that operation AFTER it was + # finalized: a reading taken before the commit point, filed over the + # inventory the commit point closed, and nothing downstream could tell. Every + # other transition advances the generation, so `SWAPPED` is the one state in + # which a matching pair names a FINISHED operation. An observation of the + # lane's own, under no transition, is an unfenced `set-lane-tree`. + [ "$slt_ns" != SWAPPED ] || slt_fence="${slt_fence:+$slt_fence; }the lane is SWAPPED: operation ${slt_no:-none} reached its commit point and its inventory is closed" + if [ -n "$slt_fence" ]; then + release_lock + die "the worktree $slt_path was NOT recorded for lane $lane: $slt_fence. The lane moved while this observation was being made — a recovery advanced it, a second handoff did, or the operation it names was finalized — so filing this poll now would put a superseded reading where the current one belongs, and nothing downstream could tell. Nothing was written and the tree itself was not touched. Re-read the lane (lanes-edit.sh lane-reconcile $lane) before recording anything under this operation; an observation filed under no transition is set-lane-tree without --generation and --operation." 7 + fi + fi + # AND THE SIDECAR THAT IS THERE IS NOT WALKED OVER EITHER, for the same + # reason the snapshot is not: a record written by a newer tooling is one + # this helper cannot read, so it is not one this helper may replace. + if ! lane_sidecar_schema_ok "$slt_root/trees/$(tree_id_for "$slt_path").yaml"; then + release_lock + die "the worktree $slt_path was NOT recorded for lane $lane: its sidecar under $slt_root/trees is not a record this helper can read ($LSS_WHY), and a record it cannot read is one it cannot safely replace. Nothing was written. Upgrade this workstation's lanes-edit.sh if a newer tooling wrote it; if you know what wrote that file, move it aside by hand and re-run." 1 + fi + if lane_tree_put "$slt_root" "$lane" "$slt_path" "$slt_co" "$slt_b" "$slt_h" \ + "$slt_u" "$slt_d" "$slt_n" "$slt_w" "$slt_g" "$slt_op"; then + release_lock + LANES_INDEX_NUDGE_INV=1 # opensoft/openRepoTools#161: `cleanup` nudges the indexer + printf '%s\n' "$(tree_id_for "$slt_path")" + else + release_lock + die "the sidecar for $slt_path could not be written under $slt_root/trees (the shell's own error is above). The tree itself was not touched: this command reads worktrees and writes only its own record of them." 1 + fi + ;; + + # THE OBSERVATION, FROM THE ONE IMPLEMENTATION OF IT (Copilot round 5 on #97). + # `lane-handoff` polls the worktrees this reconciliation recomputes, and until + # this arm it made that observation ITSELF — a second implementation with its + # own error handling, in which a failed upstream lookup became `none` and a + # failed `log @{u}..` became `0`. One function answers both now: the handoff + # records what this prints, for its WRITERS section and for the sidecar alike, + # and `lane-reconcile` recomputes with the same code. It touches no lane, no + # register and no lock — it reads one path with git. + # + # 0 <branch><US><head><US><upstream><US><dirty><US><unpushed> + # 8 no checkout there: the path is gone, or git does not answer in it + # 1 git ANSWERED there and one of the reads FAILED, so nothing is printed + # 64 a usage error of this subcommand's own + lane-tree-now) + ltna="${1-}"; [ -n "$ltna" ] || die "usage: lane-tree-now <worktree path>" 64 + [ "$#" -le 1 ] || die "lane-tree-now takes one path: lane-tree-now <worktree path>" 64 + case "$ltna" in /*) : ;; *) die "lane-tree-now takes an ABSOLUTE path: a relative one means whatever the calling process's directory happens to be, and that is never the tree being asked about" 64 ;; esac + ltna_out=""; ltna_rc=0 + ltna_out="$(lane_tree_now "$ltna")" || ltna_rc=$? + case "$ltna_rc" in + 0) printf '%s\n' "$ltna_out" ;; + 1|2) exit 8 ;; + *) die "git answers in $ltna and one of the reads an observation is made of FAILED, so NOTHING is printed: a branch, a head, a status or an upstream that could not be read is never reported as a clean tree (R22, Amendment 7(d)). Read it by hand: git -C $ltna status" 1 ;; + esac + ;; + + # opensoft/openRepoTools#186, plan task T018 — THE LEGS A CHECKOUT'S + # `project.yaml` DECLARES, by path: `assembly_legs` above, which is the one + # reader every lane tool asks (`lane-worktrees`' sweep, report and `add`, and + # `lane-handoff`'s writer poll), so no two of them can read a triad two ways. + # It reads one file and touches no workspace, so it answers on a workstation + # with no register configured too (the dispatcher exempts it). + # + # 0 <repository><TAB><path as declared><TAB><where it is checked out>, a leg a line + # 8 no legs: no project.yaml there, or one naming no leg but the checkout itself + # 1 a project.yaml is there and could not be read — which is never "no legs" + # 64 a usage error of this subcommand's own + project-legs) + pla="${1-}"; [ -n "$pla" ] || die "usage: project-legs <checkout>" 64 + [ "$#" -le 1 ] || die "project-legs takes one directory: project-legs <checkout>" 64 + case "$pla" in /*) : ;; *) die "project-legs takes an ABSOLUTE path: a relative one means whatever the calling process's directory happens to be, and that is never the checkout being asked about" 64 ;; esac + pla_out=""; pla_rc=0 + pla_out="$(assembly_legs "$pla")" || pla_rc=$? + case "$pla_rc" in + 0) printf '%s\n' "$pla_out" ;; + 8) exit 8 ;; + *) die "${pla%/}/project.yaml is there and could not be read, so which legs that checkout declares is NOT known — which is not the same as none (R22, Amendment 7(d))" 1 ;; + esac + ;; + + lane-reconcile) + lane="${1-}"; [ -n "$lane" ] || die "usage: lane-reconcile <lane>" 64 + [ "$#" -le 1 ] || die "lane-reconcile takes one lane: lane-reconcile <lane>" 64 + check_lane_name "$lane" + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + lane_reconcile "$lane"; lrec_rc=$? + case "$lrec_rc" in + 0) : ;; + 8) exit 8 ;; + *) die "lane $lane could not be reconciled (exit $lrec_rc)" 1 ;; + esac + ;; + + # ---------- opensoft/openRepoTools#161: every inventoried worktree, as rows + # + # `worktree_rows` above, for one lane or every lane on this workstation, and + # the READ the `worktrees` table answers when `--index` is TYPED (Amendment + # 14(b)): `index_open worktrees` asks `lanes-index export --worktrees` for + # every `inventory:<Workstation>` source the store holds — this + # workstation's and any other that syncs into the same Postgres, which is the + # point of the table — and stderr says which was read: `read: index (<store>) + # at inventory:<ws> synced <UTC>` (and `(last error: <UTC> <why>)` after a + # source this workstation recorded one for, as `status` shows it), or + # `read: sources (index <why>)` and the sidecars answer, exactly as without + # the flag. NO ACT READS THIS: not + # `lane-reconcile`, not `lane-start`, not `lane-end`, not a sweep — each of + # them reads the sidecars and the disk, and this is a listing. + # + # Local by default, as `lanes` is: `--fetch` refreshes the register first. + # 0 rows (`--all`: with one PARTIAL line where the lane listing they were + # read through was not whole, #173) · 8 none · 2 a lane name refused + # (Amendment 15) · 64 usage · 1 a read failed + worktrees) + wt_lane=""; wt_all=0; wt_index=0; wt_fetch=0 + wt_usage="worktrees [<lane> | --all] [--index] [--fetch]" + while [ $# -gt 0 ]; do + case "$1" in + --all) wt_all=1; shift ;; + --index) wt_index=1; shift ;; + --fetch) wt_fetch=1; shift ;; + --) shift ;; + -*) die "unknown option '$1' for worktrees ($wt_usage)" 64 ;; + *) [ -z "$wt_lane" ] || die "worktrees takes ONE lane, or --all: $wt_usage" 64; wt_lane="$1"; shift ;; + esac + done + [ "$wt_all" = 0 ] || [ -z "$wt_lane" ] || die "worktrees takes ONE lane OR --all, not both: $wt_usage" 64 + [ -z "$wt_lane" ] || check_lane_name "$wt_lane" + [ "$wt_fetch" = 1 ] || LANES_NO_FETCH=1 + log_sync + if [ -n "$wt_lane" ]; then + wt_lane="$(canon_lane "$wt_lane")" || exit 2 # Amendment 15 + fi + if [ "$wt_index" = 1 ] && index_open worktrees; then + wt_out="$(awk -F"$US" -v l="$(lc "$wt_lane")" 'l == "" || tolower($3) == l' "$LANES_WT_IDX_DIR/worktrees" 2>/dev/null)" + [ -n "$wt_out" ] || exit 8 + printf '%s\n' "$wt_out" + else + wt_out=""; wt_rc=0 + wt_out="$(worktree_rows "$wt_lane")" || wt_rc=$? + case "$wt_rc" in + 0) : ;; + 8) exit 8 ;; + *) die "the lane listing the inventory is read through could not be read (exit $wt_rc). That is NOT 'no worktree is inventoried' (Amendment 7(d))." 1 ;; + esac + printf '%s\n' "$wt_out" + fi + ;; + + # opensoft/openRepoTools#162 — WHAT A HAND COMMIT OF A HANDOFF'S ATTACHMENTS + # WOULD STAGE THAT IS BYTECODE, asked BEFORE the commit. `commit_push` + # refuses such a pathspec for every write this file makes; attachments are + # committed by hand, so this is the same question for a person to ask first. + # 0 nothing in those paths would stage bytecode, a cache or an environment + # 2 something would: the paths on stdout, the offer on stderr - or git + # could not read what they would stage, which is never "clean" (#170 G13) + # 64 usage + pathspec-check) + [ "$#" -gt 0 ] || die "usage: pathspec-check <path>... (relative to the workspace repository $LANES_REPO)" 64 + pck_rc=0 + pck_out="$(bytecode_in_pathspec "$LANES_REPO" "$@")" || pck_rc=$? + if [ "$pck_rc" != 0 ]; then + note "git could not read what that pathspec would stage (a pathspec it cannot parse, or an index it cannot read), so whether it holds bytecode is unknown, and an unknown is never reported clean (opensoft/openRepoTools#170 G13)" + exit 2 + fi + if [ -n "$pck_out" ]; then + printf '%s\n' "$pck_out" + note "$(bytecode_refusal_text "$pck_out")" + exit 2 + fi + ;; + + *) + die "unknown subcommand '$cmd' (verify-row|set-row-state|append-row-status|replace-in-row|append-session-id|append-line|add-row|retire-rows|archive-rows|migrate-state-cells|commit|rename-lane|log|claim|release|who|history|swapped|session-start|guard|idle-holders|live-holder|window-session|transcript-holders|binding|request-handoff|session-lane|window-lane|lane-dir|lane-profile|lane-agent|lane-transcript|lane-last|workspace-root|last-session|forks|duplicate-holder|workstation|fetch-age|lanes|lane-groups|next-free|sibling-filter|resolve-repo|lane-objects|register-row|register-row-local|retired-identity|canon-lane|resolve-home|managed-projection|lane-state|set-lane-state|lane-trees|set-lane-tree|lane-tree-now|project-legs|lane-reconcile|lane-holders|legacy-restart-check|publish-handoff|restart-intent|set-restart-intent|worktrees|pathspec-check)" 2 + ;; +esac diff --git a/tests/sql_register_landed/T210 b/tests/sql_register_landed/T210 new file mode 100644 index 00000000..e69de29b diff --git a/tests/sql_register_landed/T240 b/tests/sql_register_landed/T240 new file mode 100644 index 00000000..e69de29b diff --git a/tests/sql_register_landed/T241 b/tests/sql_register_landed/T241 new file mode 100644 index 00000000..e69de29b diff --git a/tests/sql_register_landed/T270 b/tests/sql_register_landed/T270 new file mode 100644 index 00000000..e69de29b diff --git a/tests/sql_register_landed/T271 b/tests/sql_register_landed/T271 new file mode 100644 index 00000000..e69de29b diff --git a/tests/sql_register_landed/T273 b/tests/sql_register_landed/T273 new file mode 100644 index 00000000..e69de29b diff --git a/tests/test_sql_register_divergence.py b/tests/test_sql_register_divergence.py new file mode 100644 index 00000000..d22bb16e --- /dev/null +++ b/tests/test_sql_register_divergence.py @@ -0,0 +1,1619 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Feature 007's test 6, a stray commit and its two ways out, with AT-MIR's +gating case and the model of the server-side gate (L2-G2; L2-G5's AT-MIR +gating case; AT-6; AT-MIR; T271; FR-047, FR-048, FR-059; US6) +(opensoft/openRepoTools#165). + +T271 writes this module: 11 tests, 10 from AT-6 (9) and AT-MIR (1), and one +new since v3f, R-F10-34's, which holds lane 3's two strays for T324, +R-F13c-10's third id and, new in B15, lane 3's L2-8 fourth, +`[stray-no-longer-applies]`. Lane 3's T324 runs the whole module by its +word, `sql_register_divergence`. + +THE V1.1.0 WRITER (PC-12; the test plan's open point 5). +`tests/fixtures/lanes-edit-v1.1.0/lanes-edit.sh` is `lanes-edit.sh` byte for +byte as code `2a057a6d` (tag `v1.1.0`) holds it: blob `d28ed8f2`, 1139720 +bytes. CI checks out at depth 1 with no tags, so the copy is the only way the +suite runs the real old writer. Its digest is recorded twice: in +`tests/fixtures/lanes-edit-v1.1.0/SHA256SUMS`, in `sha256sum`'s form, and in +this module's `V110_SHA256`, beside its git blob id and size. Every case that +runs it calls `v1_1_0_writer()` first, which checks all four, so a drift in +the fixture fails loudly instead of testing something else (AT-6, +"Flakiness"). The copy is never run from its own directory's neighbours: no +`lanes-index` and no `repos.tsv` sit beside it, and the stale clone's `PATH` +masks `lanes-index`, so it makes no index nudge. + +THE ESTATE (AT-6, "Fixture"), `Estate`, built inside each case so that a +step a lane has not built fails the case at its own assertion: + +- the fixture register at C: a files-mode workspace on a bare origin + (`Workspace`), its seed `SEED`, and a files-mode `log NOTED` on top as the + operator lane, so C's tip is bytes `lanes-edit.sh` wrote, as test 7's + fixture register is built; +- imported on `pg` by `lanes-index import --at <C>` (lane 1's T115), as the + operator lane through its checkout; +- the cutover by AT-LR006's route (TP:4610-4615): `commit_write` with a + `cutover` entry, as REGISTER-WRITER, then the marker commit, `lanes/STORE` + with D21's fields and `Register-Seq: 1`, pushed to the bare origin as a + fast-forward of C, then `record_marker`, so the switch reads `primary` + with the marker `present`. Neither T116 nor T327 is in T271's Order, so the + estate runs neither `cutover` nor its push; +- each primary write is a `commit_write` call of a `write` entry, as + REGISTER-WRITER (AT-LR006's "one write"), that appends a line of no kind to + `lanes/LANES.md`, so it carries no structured row; and each render a fork + would start is `lanes-index render --checkout <c>` run by the case, as a + fork runs it (TP:1160-1167), in the operator lane's checkout. Lane 4's + writes on primary and their fork (T415, T416) are not in T271's Order. + +The commands run from the operator lane's checkout, `LANES_LANE=repoA-2`, by +T203's flipped copy of `lanes-index` (`RENDER_GIT_HALF = True`), which the +renderer and the two ways out need on `lanes_register`; `import --at` runs the +shipped `lanes-index`, as test 7's does. Their configuration names the +session cluster's socket as its superuser, as test 7's does. + +THE STALE WORKSTATION (AT-6, "Fixture"), `StaleWorkstation`: a clone of +origin with a home, a workspace pointer and a lane of its own (`repoW-1`), no +`lanes-index` configuration, and the v1.1.0 writer. Its `log NOTED` pushes a +commit changing `lanes/log/repoW-1.md`; it knows no marker. + +THE WAITS (open point 8). The stop is read after the renderer's exit: the +case runs the render itself, in the foreground, so its exit is the wait. +Where the lag must reach 0, the case polls `lanes-index status` every 100 ms +until it prints a lag of 0, with a 30 s ceiling, after a render of its own; +a render a way out forks itself is the same render lock's, so the case's own +render then marks a rerun and the poll waits for both. + +THE GATE MODEL (AT-6, "Options", Q21(b)): `GATE_HOOK`, a pre-receive hook in +the bare origin, refuses a push whose commits change a path of the render +set or `lanes/STORE` (`lanes/LANES.md`, `lanes/log/<lane>.md`, +`lanes/aliases.tsv`, anything under `lanes/archive/`, and `lanes/STORE`), and +lets every other path through, `lanes/repos.tsv` and `lanes/log/README.md` +among them. It is a model: the suite cannot reach GitHub. Its two tests need +no engine. + +WHAT EACH FAILS UNTIL (T271's Order, B15 tasks:2487): it waits for T205, +and its tests fail until L1-A6, L1-A15, T322, T324 and T326 land. Case by +case: the estate needs lane 1's T107 (`commit_write`, `record_marker`, +`record_mirror_state`; L1-A6) and T115 (`import --at`, L1-A13), and each +case reads `status` (T117, L1-A15) and runs the renderer's pass (lane 3's +T321 to T323). Then: + +- the stop, the row's two ids and the three commits outside the render set + fail until those alone; +- `test_status_prints_diverged_at_the_stray_sha_and_reconcile_imports_nothing` + also fails until T325, whose re-render gives `reconcile` the renderer's 1 + for a recorded `diverged at`, where T117's check alone, like `--dry-run`, + exits 0 (lane 3, #165 6809045090, L2-6); +- the two ways out, the strays and the `Register-Seq` above the head fail + until T324 too; +- `test_rollback_works_after_each_way_out` and the `Register-Seq` case's last + part fail until T326 (the rollback's render and push); +- `[stray-revives-a-pair]` fails until T324's refusal and T107's + `one_live_claim`; `[stray-no-longer-applies]` also fails until T324's + `import --single` refusal (lane 3, #165 6809045090, L2-8); the other two + strays' oracle needs T115's `import --at`; +- the gate model's seven ids wait for nothing: they test the model and the + pinned copy, and pass now. + +COPIED, NOT SHARED (lane 2's rule for wave 12: no module imports another's +helpers). From `test_sql_register_import.py` (line W3a at T211m, `c9989b5`): +`Workspace`, the fixture register's `config` and `import_at`, +`flipped_indexer`, `_rows`, `_renders`, `RENDER_SET`, `REGISTER_SEQ` and +`LAG_0`. From `test_sql_register_landing_expired.py` (line LX at T253e, +`e9b949e`): `_masked_path`, with its mirrors. From +`test_sql_register_schema.py` (line W3b at T221j, `0154c91`): `STRUCTURED` +and `structured`, T221's step-6 comparison, and the commit call's form. From +`test_sql_register_rollback.py` (line RB at T273b, `35b616ff`): test 8's first +oracle, `_assert_rolled_back`, and `_said`. + +READINGS, NOT FOUND IN A CONTRACT: + +- "A later primary write still commits to SQL" is a `commit_write` of a + `write` entry that returns the next seq while `diverged at` is recorded. +- "SQL writes refused", in test 8's first oracle, is `commit_write`'s LR002 + for a `write` entry once the switch reads `files`, with the head unmoved. +- "Its line edits equal the stray commit's diff": the v1.1.0 writer's stray + appends lines to one log, so the entry's edits are one `append` per added + line, in order, on that path. +- A revert's message "names" the stray where it holds the stray's first 7 + hex digits, git's shortest abbreviation, or more; its `git_commit` is the + full sha (design.md's kinds paragraph). +- "Its render commit puts SQL's state back over the stray" is read over the + render commits that follow the stray up to the revert's seq: a write that + lands between the stray and the revert is rendered first and already puts + the stray's path back (design.md's prototype note on the import), so on + each path the stray changed, the tip after the resume equals the stray's + parent. +- "The pending seqs reach origin in order": the `Register-Seq` values of the + commits after the stray, oldest first, are each seq from `m+1` to the head, + once each. +- "Between renders": the `repos.tsv` and `handoffs/` commits land after a + render of their own estate's first write; the cutover's `lanes/STORE` + commit is origin's tip when the first render starts. +- The negative and the row-only cases' "status shows no divergence" is + `status`'s `divergence: none recorded` line, where the row is empty. +- `[stray-revives-a-pair]`'s "writes nothing" also leaves `mirror_state` + recording the stray. +- `[stray-no-longer-applies]`'s "a primary write changes a line after the + stray commit changed it": the stray retitles `lanes/LANES.md`'s first + line, its heading, a line of no kind, by hand; then a `commit_write` of a + `write` entry replaces the same line in SQL with other text, by its old + text's digest. So the stray's one edit, a `replace` at line 1, finds there + a line its parent never held. +- Its "sends no commit call" is read through a `psql` first on the import's + `PATH` that logs each call's stdin, where `lanes-index` sends each request: + no request holds `commit_write(`, and at least one was sent, since the + refusal reads SQL's images. Its "naming the edit" is stderr naming the + edit's path and that its edits "no longer apply" (TP:1292). Its "writes + nothing" is the head, the journal's count, the four structured tables and + SQL's images as they were, `mirror_state` still recording the stray, and + origin's tip still the stray. +- The ways out run "on a person's word from the operator lane's checkout" + (TP:1276-1277), where that person's git names an author: the checkout's + own `user.name` and `user.email` name `AUTHOR`, set once C is made. A way + out removes every inherited `GIT_*` variable before it asks git (D12), so + the module's `GIT_AUTHOR_*` variables, which still sign the estate's own + commits, cannot name it; T324 as built refuses with 2 where git names no + author there. +- The stale clone's `sleep` is a stub that returns at once, so the v1.1.0 + writer's six push attempts, three seconds apart, take no time; what it + does at each attempt is unchanged. + +RULED BY LANE 3 (#165 6809045090; its RULINGS-batch-e-analysis-20261111.md, +L2-6 to L2-8; B15 folds them): + +- L2-6: AT-6's stop stands (TP:1285): `reconcile` exits non-zero on a + diverged mirror once T325 lands. T325 re-renders what the mirror lacks + through T322's pass, and the pass's recorded stop, `diverged at` among + them, is the renderer's 1 (exit-codes.md section 3.4's `reconcile` 1 + row). T117's check alone, like `reconcile --dry-run`, exits 0 whatever it + found. So the status case asserts 1, the code the contract names, and + fails until T325. +- L2-7: T117 is right. With `m` above the head there is no lag (Y:2850): + until a revert names `R`, its `Register-Seq` counts, so `m` = `h`+10 is + past `n` = `h`+1, and `status` prints the lag as "none, and the mirror's + <m> is past n <n>" (TP:1319 at B15: "no lag: its `m` is past `n` + (Y:2850), as `status` says"). The `Register-Seq` case asserts that line, + naming `h`+10 and `h`+1. The plain stray's "a lag of at least 1" + (TP:1284) stands: that stray carries no `Register-Seq`. +- L2-8: AT-6's "case of its own", the import's refusal where the stray's + edits no longer apply to SQL's images (TP:1292-1293), is + `[stray-no-longer-applies]`, a fourth id of the strays' function beside + `[stray-revives-a-pair]`, whose LR005 is the other refusal: `import + --single` refuses with 2 before any commit call, naming `render --revert + <sha>` as the way out (PC-4; T324 `9a664ef`:16115-16117), writes nothing, + and leaves the tables unchanged (B15 tasks:2486). It fails until T324's + refusal. +""" + +from __future__ import annotations + +import atexit +import base64 +import hashlib +import json +import os +import re +import shlex +import shutil +import subprocess +import sys +import tempfile +import time +import uuid +from pathlib import Path + +import pytest + +from conftest import REPO, WINDOWS_SKIP +from pgcluster import Database + +pytestmark = [WINDOWS_SKIP, pytest.mark.skipif( + shutil.which("bash") is None or shutil.which("git") is None, + reason="the lane tooling is bash over git")] + +# ------------------------------------------------------------------ the landing gate +#: THE LANDING GATE'S TABLE (T280; task sets version 12b's rule 11, +#: opensoft/openRepoTools#165 6877673742), read by `tests/sql_register_gate.py`. +#: Where the gate is active, an id whose tasks have not all landed is skipped, +#: and the skip names them; an id waits for the `"*"` row and its own. T281 +#: removes this block in the last set. It is T271's Order (tasks:2489 at lane +#: 3's commit 17, 204145ae), as lane 2's plan GP-24 keys it (sha256 16d738b9): +#: +#: - `"*"`: the module's tests fail until L1-A6 (T107, T108), L1-A15 (T117), +#: T322, T324 and T326. The gate model's seven ids need none of them (their +#: docstrings: "waits for nothing"), but the Order names the module's tests +#: whole, so `"*"` holds them too; +#: - the status case also fails until T325 (lane 3's L2-6): its own row; +#: - `[stray-no-longer-applies]`'s T324, and `[stray-revives-a-pair]`'s T324 +#: and T107, are in `"*"` already. The two other strays' T115 (L1-A13) has +#: no row: it lands in an earlier set than T326, so a row would hold no id +#: longer. +SQL_REGISTER_GATE_TABLE = { + "*": ("T107", "T108", "T117", "T322", "T324", "T326"), + "test_status_prints_diverged_at_the_stray_sha_and_reconcile_imports_nothing": ("T325",), +} + +LANES_EDIT = REPO / "lanes-edit.sh" +INDEXER = REPO / "lanes-index" + +# ------------------------------------------------------------------ the v1.1.0 writer +#: PC-12's copy and its pin (see the module's docstring). +FIXTURE_DIR = Path(__file__).resolve().parent / "fixtures" / "lanes-edit-v1.1.0" +V110 = FIXTURE_DIR / "lanes-edit.sh" +V110_SUMS = FIXTURE_DIR / "SHA256SUMS" +V110_COMMIT = "2a057a6d84e58c8acb4bda20d2b7b667b552c3fe" +V110_BLOB = "d28ed8f2d18adcabc4483eaf2a9424410e288cc6" +V110_SHA256 = "b68d0cbac35ac3bbac9e70790cafe63538821be582ca28cec0f7ec0f5c4745d2" +V110_SIZE = 1139720 + + +def v1_1_0_writer() -> Path: + """The pinned v1.1.0 `lanes-edit.sh`, once its bytes are proved: its + size, its sha256 against this module's pin and against `SHA256SUMS`, and + its git blob id against the tag's. Any drift fails here, loudly.""" + assert V110.is_file(), f"PC-12's copy of the v1.1.0 writer is missing: {V110}" + data = V110.read_bytes() + sums = V110_SUMS.read_text(encoding="ascii") if V110_SUMS.is_file() else None + assert sums == f"{V110_SHA256} lanes-edit.sh\n", ( + f"{V110_SUMS} does not record the pinned digest {V110_SHA256} (PC-12): {sums!r}") + got = (len(data), hashlib.sha256(data).hexdigest(), + hashlib.sha1(b"blob %d\0" % len(data) + data).hexdigest()) + assert got == (V110_SIZE, V110_SHA256, V110_BLOB), ( + f"{V110} is not lanes-edit.sh as v1.1.0 ({V110_COMMIT[:8]}) holds it: size, sha256 and " + f"blob {got}, pinned {(V110_SIZE, V110_SHA256, V110_BLOB)}. The fixture drifted, so " + f"test 6 would test something else (PC-12; open point 5)") + return V110 + + +# ------------------------------------------------------------------ the register +EM, DOT, ARROW = chr(0x2014), chr(0xB7), chr(0x2192) + +#: The register's schema, `register_schema=`'s default, and the writer's group. +SCHEMA = "lanes_register" +WRITER = "lanes_register_writer" +#: The operator lane (lane 1's T115: "It runs with `LANES_LANE=<operator +#: lane>`, through that lane's checkout"), its workstation and git's author. +OPERATOR = "repoA-2" +WS = "Eagle" +AUTHOR_NAME, AUTHOR_EMAIL = "T271 operator", "t271@example.invalid" +AUTHOR = f"{AUTHOR_NAME} <{AUTHOR_EMAIL}>" +#: The label the configuration's `register_label=` and `lanes/STORE` carry. +LABEL = "t271" +#: The stale workstation's lane and name. +STALE_LANE = "repoW-1" +STALE_WS = "Stale" + +ARGS_SHA256 = "a" * 64 +NOT_AFTER = "2100-01-01T00:00:00Z" +STORE_UTC = "2026-11-11T10:00:00Z" + +UUID_A2 = "aaaaaaaa-0003-4000-8000-00000000a003" +UUID_D1 = "dddddddd-0002-4000-8000-00000000d002" +UUID_I1 = "11111111-0001-4000-8000-000000001001" +UUID_W1 = "eeeeeeee-0002-4000-8000-00000000e002" +UUID_X1 = "cccccccc-0001-4000-8000-00000000c001" +UUID_Y1 = "cccccccc-0002-4000-8000-00000000c002" +UUID_Z1 = "eeeeeeee-0001-4000-8000-00000000e001" + +#: The object two lanes held, one after the other: repoX-1 claimed and +#: released it, then repoY-1 claimed it. One claim is live at C, so the +#: import marks no pair `exempt`. +PAIR_OBJECT = "opensoft/repoQ#1" + + +def _row(lane: str, uid: str, state: str) -> str: + return (f"| `{lane}` | harness `{uid}` | Eagle / test / brett | 2026-10-01T00:00Z | none | " + f"handoffs/{lane}.md | {state} |") + + +def _started(lane: str, uid: str, home: str, utc: str = "2026-10-01T00:00:00Z") -> str: + return (f"STARTED {EM} lane {lane}, session {uid}@Eagle, {utc}, lane:{lane} {ARROW} home " + f"{home}; dir /work/{lane}") + + +def _line(verb: str, lane: str, uid: str, utc: str, obj: str, text: str) -> str: + return f"{verb} {EM} lane {lane}, session {uid}@Eagle, {utc}, {obj} {EM} {text}" + + +def _log(lane: str, *lines: str) -> str: + return "\n".join([f"# lane {lane} {EM} object log (lane-collision-protocol Amendment 7)", + *lines, ""]) + + +#: The row the first stray deletes, with no archive copy. +ROW_D = _row("repoD-1", UUID_D1, f"PAUSED {DOT} 2026-10-02T00:00:00Z {DOT} a row a stray deletes") +#: The release the third stray deletes, which revives repoX-1's claim. +RELEASED_X = _line("RELEASED", "repoX-1", UUID_X1, "2026-10-01T03:00:00Z", PAIR_OBJECT, + "handed back") +#: The line the second stray inserts before its log's end. +INSERTED_I = _line("NOTED", "repoI-1", UUID_I1, "2026-10-03T00:00:00Z", "lane:repoI-1", + "a line a person inserted by hand") +#: `lanes/LANES.md`'s first line, a heading of no kind. The fourth stray +#: retitles it by hand, then a primary write retitles it in SQL (L2-8). +TITLE = f"# LANES.md {EM} test 6's register" +TITLE_BY_HAND = TITLE + ", retitled by hand" +TITLE_IN_SQL = TITLE + ", retitled by a primary write" + +#: C's files, before the `lanes-edit.sh` write on top. `lanes/repos.tsv` and +#: `lanes/log/README.md` are outside the render set (Q18 (A)). +SEED = { + "lanes/LANES.md": "\n".join([ + TITLE, + "", + "| lane | session id | workstation / env / user | started (UTC) | objects owned | " + "handoff path | state |", + "|---|---|---|---|---|---|---|", + _row("repoA-2", UUID_A2, f"LIVE {DOT} 2026-10-01T02:00:00Z {DOT} the operator lane"), + _row("repoW-1", UUID_W1, f"LIVE {DOT} 2026-10-02T00:00:00Z {DOT} the stale workstation"), + _row("repoX-1", UUID_X1, f"LIVE {DOT} 2026-10-01T00:00:00Z {DOT} it released repoQ#1"), + _row("repoY-1", UUID_Y1, f"LIVE {DOT} 2026-10-01T00:00:00Z {DOT} it holds repoQ#1"), + ROW_D, + _row("repoI-1", UUID_I1, f"LIVE {DOT} 2026-10-01T00:00:00Z {DOT} a log with claims"), + "", + ]), + "lanes/log/README.md": "# the object logs\n", + "lanes/repos.tsv": "# alias\towner/repo\nrepoE\topensoft/repoE\n", + "lanes/aliases.tsv": "# old\tnew\tutc\nrepoOld-1\trepoA-2\t2026-09-30T00:00:00Z\n", + "lanes/archive/LANES-retired.md": "\n".join([ + "# retired rows (Amendment 19(d))", "", + _row("repoZ-1", UUID_Z1, f"RETIRED {DOT} 2026-09-02T00:00:00Z {DOT} retired"), ""]), + "lanes/log/repoA-2.md": _log("repoA-2", _started("repoA-2", UUID_A2, "opensoft/repoA")), + "lanes/log/repoW-1.md": _log("repoW-1", _started("repoW-1", UUID_W1, "opensoft/repoW")), + "lanes/log/repoX-1.md": _log( + "repoX-1", _started("repoX-1", UUID_X1, "opensoft/repoQ"), + _line("CLAIMED", "repoX-1", UUID_X1, "2026-10-01T01:00:00Z", PAIR_OBJECT, "mine"), + RELEASED_X), + "lanes/log/repoY-1.md": _log( + "repoY-1", _started("repoY-1", UUID_Y1, "opensoft/repoQ"), + _line("CLAIMED", "repoY-1", UUID_Y1, "2026-10-01T04:00:00Z", PAIR_OBJECT, + "after repoX-1 let it go")), + "lanes/log/repoI-1.md": _log( + "repoI-1", _started("repoI-1", UUID_I1, "opensoft/repoI"), + _line("CLAIMED", "repoI-1", UUID_I1, "2026-10-01T01:00:00Z", "opensoft/repoI#1", "one"), + _line("CLAIMED", "repoI-1", UUID_I1, "2026-10-01T01:10:00Z", "opensoft/repoI#2", "two"), + _line("OPENED", "repoI-1", UUID_I1, "2026-10-01T01:20:00Z", "opensoft/repoI#3", + "three")), +} + +#: The render set (Q18 (A); CLI4.10 section 3.6): `lanes/LANES.md`, +#: `lanes/aliases.tsv`, each `lanes/log/<lane>.md` but the README, and the +#: archive. `lanes/STORE` is the marker, never rendered. +RENDER_SET = re.compile(r"^lanes/(LANES\.md|aliases\.tsv|archive/[^/]+\.md" + r"|log/(?!README\.md$)[^/]+\.md)$") +#: The trailer each mirror commit and the marker commit carry (section 1.3). +REGISTER_SEQ = re.compile(r"^Register-Seq: ([0-9]+)$", re.M) +#: `status`'s lag line (lane 1's T117): at 0, and as a number of seqs. +LAG_0 = re.compile(r"^\s*lag:\s+0 seq", re.M) +LAG_N = re.compile(r"^\s*lag:\s+([0-9]+) seq", re.M) +#: ... and with `m` above `n` at `primary`, no lag (R2's N6; Y:2850; lane 3's +#: L2-7): "none, and the mirror's <m> is past n <n>". +LAG_PAST_N = re.compile(r"^\s*lag:\s+none\b[^\n]*?\b([0-9]+) is past n ([0-9]+)", re.M) +NO_DIVERGENCE = re.compile(r"^\s*divergence:\s+none recorded", re.M) + + +def _said(proc) -> str: + return (f"exit {proc.returncode}\n--- stdout ---\n{(proc.stdout or '')[-3000:]}" + f"\n--- stderr ---\n{(proc.stderr or '')[-3000:]}") + + +def _sha256(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +# ------------------------------------------------------------------ the PATH mask +#: `_masked_path`'s mirrors, by each directory's real path (None where the +#: directory holds no masked name), and the one temporary root they share. +_PATH_MIRRORS: dict = {} +_PATH_MIRROR_ROOT: list = [] + + +def _masked_path() -> str: + """The caller's PATH with every directory kept in its place, and each one + that holds a `psql`, a `lanes-index` or a name that starts `pg_` swapped + for a private mirror of it: a directory of links, one to each of its + entries by its absolute path, those names left out. An installed + indexer, a real `psql` or one of the `pg_` client wrappers shipped beside + it is never what a case runs, but the tools beside them are: on a GitHub + runner `postgresql-16`'s client puts `psql` in `/usr/bin` with `git` and + `bash` (and `/bin` is a link to it), so dropping the directory would drop + `git` and `bash` too (lane 1's census, #165 6807454856). A directory that + holds none of those names passes through unchanged. Each mirror is made + once per process, under one `mkdtemp` that an `atexit` handler removes. + The estate's commands reach the session cluster's `psql` through a + directory of their own, first on their `PATH`.""" + parts = [] + for part in os.environ.get("PATH", "").split(os.pathsep): + if not part: + continue + real = os.path.realpath(part) + if real not in _PATH_MIRRORS: + try: + names = os.listdir(real) + except OSError: + names = [] + masked = {name for name in names + if name in ("psql", "lanes-index") or name.startswith("pg_")} + mirror = None + if masked: + if not _PATH_MIRROR_ROOT: + _PATH_MIRROR_ROOT.append(tempfile.mkdtemp(prefix="l2-pathmask-")) + atexit.register(shutil.rmtree, _PATH_MIRROR_ROOT[0], ignore_errors=True) + mirror = os.path.join(_PATH_MIRROR_ROOT[0], str(len(_PATH_MIRRORS))) + os.mkdir(mirror) + for name in names: + if name not in masked: + os.symlink(os.path.join(real, name), os.path.join(mirror, name)) + _PATH_MIRRORS[real] = mirror + parts.append(_PATH_MIRRORS[real] or part) + return os.pathsep.join(parts) + + +def _script(path: Path, text: str) -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + path.chmod(0o755) + return path + + +def _logging_psql(directory: Path, real: str, log: Path) -> Path: + """A directory for the front of one command's `PATH`, holding a `psql` + that appends `--- psql <its argv>` and then its stdin to `log` as it + streams them, through `tee`, to the real `psql` at `real`, whose exit it + keeps. `lanes-index` sends each request as one `psql` call with its SQL on + stdin, so `log` holds every request the command sent.""" + _script(directory / "psql", "#!/bin/sh\n" + f"printf '%s\\n' \"--- psql $*\" >> {shlex.quote(str(log))}\n" + f"tee -a {shlex.quote(str(log))} | {shlex.quote(str(real))} \"$@\"\n") + return directory + + +# ------------------------------------------------------------------ the workspace +class Workspace: + """A whole files-mode workspace in `root`: a bare origin, its clone, the + pointer file that joins them (Amendment 23 S5's view of the clone), a + fake `tmux`, and the environment every command here runs in. With + `files`, a new origin is made and `files` committed and pushed by git + alone; with `origin`, that origin is cloned as it stands.""" + + def __init__(self, root: Path, files: dict | None = None, *, origin: Path | None = None, + lane: str = OPERATOR, workstation: str = WS): + self.root = root + self.home = root / "home" + self.agents = self.home / ".agents" + self.origin = origin or root / "origin.git" + self.wip = self.home / "projects" / "wip" + self.fakebin = root / "fakebin" + self.conf = root / "conf" + for d in (self.home, self.agents, self.fakebin, self.conf, root / "state", + root / "config", root / "tmp"): + d.mkdir(parents=True, exist_ok=True) + _script(self.fakebin / "tmux", "#!/bin/sh\nexit 1\n") + env = {k: v for k, v in os.environ.items() + if not k.startswith(("LANES_", "CLAUDE_", "WORKBENCHES_", "TMUX", "XDG_", "PG", + "AGENT_PROTOCOL_ROOT", "PROJECTS_", "GIT_"))} + env.update( + HOME=str(self.home), AGENT_PROTOCOL_ROOT=str(self.agents), TMPDIR=str(root / "tmp"), + XDG_STATE_HOME=str(root / "state"), XDG_CONFIG_HOME=str(root / "config"), + CLAUDE_CONFIG_DIR=str(self.home / ".claude"), LANES_WORKSTATION=workstation, + LANES_HOST="eagle", LANES_OS="linux", LANES_CONTAINER="none", + LANES_IN_CONTAINER="0", LANES_NO_GITHUB="1", LANES_EDIT=str(LANES_EDIT), + GIT_AUTHOR_NAME="lanes-index tests", GIT_AUTHOR_EMAIL="test@example.invalid", + GIT_COMMITTER_NAME="lanes-index tests", GIT_COMMITTER_EMAIL="test@example.invalid", + PATH=str(self.fakebin) + os.pathsep + _masked_path()) + self.env = env + if origin is None: + subprocess.run(["git", "init", "-q", "--bare", "-b", "main", str(self.origin)], + check=True, env=self.env, capture_output=True) + subprocess.run(["git", "clone", "-q", str(self.origin), str(self.wip)], + check=True, env=self.env, capture_output=True) + if files: + self.commit(files, "seed the register") + self.ws = root / "ro" / "wip" + self.ws.mkdir(parents=True) + (self.ws / ".git").write_text(f"gitdir: {os.path.realpath(self.wip / '.git')}\n", + encoding="utf-8") + (self.ws / "lanes").symlink_to(self.wip / "lanes") + (self.agents / "workspace.yaml").write_text( + f"repository: {self.origin}\npath: {self.ws}\n", encoding="utf-8") + self.env["LANES_REPO"] = str(self.wip) + self.lane = lane + + def git(self, *args: str, input_bytes: bytes | None = None, check: bool = True) -> str: + proc = subprocess.run(["git", *args], cwd=str(self.wip), capture_output=True, + input=input_bytes, env=self.env, check=False) + assert not check or proc.returncode == 0, ( + f"git {' '.join(args)}: {proc.stderr.decode(errors='replace')}") + return proc.stdout.decode("utf-8", "replace") + + def commit(self, files: dict, message: str, *, push: bool = True) -> str: + """Commit `files` ({path: str or bytes, or None to remove}) through + git alone, push it unless told not to, and return the commit.""" + for path, text in files.items(): + if text is None: + self.git("rm", "-q", "--cached", "--", path) + continue + data = text.encode("utf-8") if isinstance(text, str) else text + sha = self.git("hash-object", "-w", "--stdin", input_bytes=data).strip() + self.git("-c", "core.ignorecase=false", "update-index", "--add", "--cacheinfo", + f"100644,{sha},{path}") + self.git("-c", "core.ignorecase=false", "commit", "-q", "-m", message) + if push: + self.git("push", "-q", "origin", "main") + self.git("-c", "core.ignorecase=false", "checkout", "-q", "-f", "HEAD") + return self.git("rev-parse", "HEAD").strip() + + def run(self, *argv, env: dict | None = None, timeout: float = 120, + cwd: Path | None = None) -> subprocess.CompletedProcess: + child = dict(self.env) + for key, value in (env or {}).items(): + if value is None: + child.pop(key, None) + else: + child[key] = value + return subprocess.run([str(a) for a in argv], capture_output=True, text=True, + env=child, timeout=timeout, cwd=str(cwd or self.root), + stdin=subprocess.DEVNULL) + + def edit(self, *args, env: dict | None = None, **kw) -> subprocess.CompletedProcess: + return self.run("bash", LANES_EDIT, *args, env=env, **kw) + + def tip(self) -> str: + return self.git("rev-parse", "origin/main").strip() + + def tree(self, sha: str, path: str = "lanes") -> str: + return self.git("rev-parse", f"{sha}:{path}").strip() + + # ------------------------------------------------------------ the bare origin + def origin_git(self, *args: str) -> str: + """git in the bare origin itself, so no clone's refs move.""" + proc = subprocess.run(["git", f"--git-dir={self.origin}", *args], capture_output=True, + env=self.env, check=False, stdin=subprocess.DEVNULL) + assert proc.returncode == 0, f"git {' '.join(args)}: {proc.stderr.decode(errors='replace')}" + return proc.stdout.decode("utf-8", "replace") + + def origin_tip(self) -> str: + return self.origin_git("rev-parse", "refs/heads/main").strip() + + def origin_blob(self, rev: str, path: str) -> bytes | None: + proc = subprocess.run(["git", f"--git-dir={self.origin}", "cat-file", "blob", + f"{rev}:{path}"], capture_output=True, env=self.env, + check=False, stdin=subprocess.DEVNULL) + return proc.stdout if proc.returncode == 0 else None + + def origin_changed(self, sha: str) -> list: + """The paths `sha` changes against its first parent.""" + out = self.origin_git("diff-tree", "--root", "--no-commit-id", "-r", "--no-renames", + "--name-only", "-z", sha) + return sorted(p for p in out.split("\0") if p) + + def origin_parent(self, sha: str) -> str: + return self.origin_git("rev-parse", f"{sha}^").strip() + + def commits_after(self, since: str) -> list: + """The commits on origin's `main` after `since`, oldest first, each + with its `Register-Seq` values.""" + commits = self.origin_git("rev-list", "--reverse", f"{since}..refs/heads/main").split() + return [(sha, [int(s) for s in REGISTER_SEQ.findall( + self.origin_git("log", "-1", "--format=%B", sha))]) for sha in commits] + + def origin_render_set(self, rev: str) -> dict: + """The render set at `rev` on origin, {path: bytes}.""" + paths = self.origin_git("ls-tree", "-r", "--name-only", "-z", rev, "--", "lanes/") + return {p: self.origin_blob(rev, p) for p in paths.split("\0") if p and RENDER_SET.match(p)} + + +class StaleWorkstation(Workspace): + """THE STALE WORKSTATION (AT-6, "Fixture"): a clone of `origin` with no + `lanes-index` configuration, its own home and pointer, lane `STALE_LANE`, + and the pinned v1.1.0 writer. `lanes-index` and `psql` are masked off its + `PATH`, and its `sleep` returns at once (the module's readings).""" + + def __init__(self, root: Path, origin: Path): + super().__init__(root, origin=origin, lane=STALE_LANE, workstation=STALE_WS) + _script(self.fakebin / "sleep", "#!/bin/sh\nexit 0\n") + self.env.update(LANES_LANE=STALE_LANE, GIT_AUTHOR_NAME="A stale workstation", + GIT_COMMITTER_NAME="A stale workstation") + self.env.pop("LANES_EDIT", None) + self.writer = v1_1_0_writer() + + def v110(self, *args, env: dict | None = None) -> subprocess.CompletedProcess: + """The v1.1.0 `lanes-edit.sh`, run by `bash` in the stale clone.""" + return self.run("bash", self.writer, *args, env=env, cwd=self.wip, timeout=300) + + def note(self, text: str) -> subprocess.CompletedProcess: + """`log NOTED`, AT-6's stale write: a commit changing the lane's log.""" + return self.v110("log", "NOTED", f"lane:{STALE_LANE}", text) + + def local_commit(self, path: str, text: str, message: str) -> str: + """A person's commit in the stale clone, appending `text` to `path`, + not pushed.""" + target = self.wip / path + target.write_text(target.read_text(encoding="utf-8") + text, encoding="utf-8") + self.git("add", "--", path) + self.git("commit", "-q", "-m", message) + return self.git("rev-parse", "HEAD").strip() + + +# ------------------------------------------------------------------ the gate model +#: AT-6'S MODEL OF Q21(b)'s PUSH RULESET (Brett's scope, "Render set + +#: STORE", lane 3's 6721583757), a pre-receive hook in the bare origin: it +#: refuses a push whose commits change a path of the render set or +#: `lanes/STORE`, and lets every other path through. Each push is one JSON +#: line of its log. +GATE_HOOK = r'''#!/usr/bin/env -S python3 -I +# T271's model of the server-side gate (test plan, AT-6, "Options"): a model, +# since the suite cannot reach GitHub. +import json, re, subprocess, sys +LOG = LOG_PATH +GUARDED = re.compile(r"^lanes/(LANES\.md|aliases\.tsv|STORE|archive/.+" + r"|log/(?!README\.md$)[^/]+\.md)$") +ZERO = "0" * 40 + + +def git(*args): + return subprocess.run(["git", *args], capture_output=True, text=True, + check=True).stdout + + +def changed(old, new): + revs = git("rev-list", new if old == ZERO else f"{old}..{new}").split() + paths = set() + for rev in revs: + out = git("diff-tree", "--root", "--no-commit-id", "-r", "-m", "--no-renames", + "--name-only", "-z", rev) + paths.update(p for p in out.split("\0") if p) + return sorted(paths) + + +def main(): + pushes, refused = [], [] + for line in sys.stdin: + old, new, ref = line.split() + if new == ZERO: + continue + paths = changed(old, new) + hits = [p for p in paths if GUARDED.match(p)] + pushes.append({"ref": ref, "old": old, "new": new, "paths": paths, "guarded": hits}) + refused += hits + with open(LOG, "a", encoding="utf-8") as handle: + handle.write(json.dumps({"outcome": "refused" if refused else "accepted", + "pushes": pushes}) + "\n") + if refused: + sys.stderr.write("t271 gate model: a push to the render set or lanes/STORE is " + "refused: " + ", ".join(sorted(set(refused))) + "\n") + return 1 + return 0 + + +sys.exit(main()) +''' + + +class GatedOrigin(Workspace): + """The gate model's register: the seed and a files-mode write, then + `lanes/STORE` as the cutover's marker commit leaves it, on a bare origin + that `GATE_HOOK` guards. No database: the model needs none.""" + + def __init__(self, root: Path): + super().__init__(root, SEED) + proc = self.edit("log", "NOTED", f"lane:{OPERATOR}", "test 6's register, at C", + env={"LANES_LANE": OPERATOR}) + assert proc.returncode == 0, f"lanes-edit.sh log NOTED: {_said(proc)}" + self.c = self.tip() + self.marker = self.commit({"lanes/STORE": _store_text(LABEL, self.c, self.tree(self.c))}, + "cutover: lanes/STORE, the marker\n\nRegister-Seq: 1") + self.gate_log = root / "gate.log" + _script(self.origin / "hooks" / "pre-receive", + GATE_HOOK.replace("LOG_PATH", repr(str(self.gate_log)))) + + def gate_records(self) -> list: + if not self.gate_log.exists(): + return [] + return [json.loads(line) for line in self.gate_log.read_text(encoding="utf-8").splitlines() + if line] + + +# ------------------------------------------------------------------ the estate +def flipped_indexer(directory: Path) -> Path: + """T203's flipped copy, `RENDER_GIT_HALF = True`, in `directory`, with + `lanes-edit.sh` and `repos.tsv` beside it (the copy rule, CLI4.5 section + 6), so that the renderer and the two ways out take `lanes_register`.""" + from sql_register_helpers import RENDER_GIT_HALF_LINE, flipped_copy + assert len(RENDER_GIT_HALF_LINE.findall(INDEXER.read_bytes())) == 1, ( + f"{INDEXER} holds no single `RENDER_GIT_HALF = ...` line, Q6(c)'s build constant " + f"(L1-A4, lane 1's T105), so no copy can be flipped") + copy = flipped_copy(INDEXER, directory, True) + for name in ("lanes-edit.sh", "repos.tsv"): + if (REPO / name).exists(): + shutil.copy2(REPO / name, copy.parent / name) + return copy + + +def _store_text(label: str, c: str, tree: str) -> str: + """`lanes/STORE` with D21's fields, one per line.""" + return "\n".join(_store_lines(label, c, tree)) + "\n" + + +def _store_lines(label: str, c: str, tree: str) -> list: + return ["store=primary", f"database={label}", f"import={c}", f"lanes-tree={tree}", + f"utc={STORE_UTC}"] + + +def _entry(kind: str, verb: str, message: str, **parts) -> dict: + """One `commit_write` entry (section 1.3): the journal object, + `not_after`, and `parts`.""" + journal = {"kind": kind, "verb": verb, "lane": OPERATOR, "workstation": WS, + "author": AUTHOR, "message": message} + journal.update(parts.pop("journal", {})) + return {"journal": journal, "not_after": NOT_AFTER, **parts} + + +#: The four structured tables, each row keyed by its line's `(path, line_no)` +#: in place of a line id, without the columns a write stamps: the written seq, +#: the mode and the workstation (T221's step-6 comparison; lane 2's reading, +#: NOTES question 33). +STRUCTURED = { + "lanes": f"SELECT to_jsonb(t) - 'row_line_id' - 'last_seq' - 'last_mode' - 'workstation' || " + f"jsonb_build_object('path', d.path, 'line_no', d.line_no) FROM {SCHEMA}.lanes t " + f"LEFT JOIN {SCHEMA}.doc_lines d ON d.line_id = t.row_line_id", + "log_lines": f"SELECT to_jsonb(t) - 'line_id' - 'seq' - 'mode' - 'workstation' || " + f"jsonb_build_object('path', d.path, 'line_no', d.line_no) FROM " + f"{SCHEMA}.log_lines t LEFT JOIN {SCHEMA}.doc_lines d ON d.line_id = t.line_id", + "register_lines": f"SELECT to_jsonb(t) - 'line_id' - 'seq' - 'mode' - 'workstation' || " + f"jsonb_build_object('path', d.path, 'line_no', d.line_no) FROM " + f"{SCHEMA}.register_lines t LEFT JOIN {SCHEMA}.doc_lines d " + f"ON d.line_id = t.line_id", + "object_holds": f"SELECT to_jsonb(t) - 'seq' - 'mode' FROM {SCHEMA}.object_holds t", +} + + +def _psql(db, script: str, role: str | None = None) -> subprocess.CompletedProcess: + """One `psql` as the fixture's superuser, as `role` where one is named, + with the commit call's settings, so a refusal's first stderr line is + `ERROR: <SQLSTATE>: <message>`.""" + head = "\\set VERBOSITY verbose\n\\set SHOW_CONTEXT never\nSET client_encoding = 'UTF8';\n" + if role: + head += f"SET ROLE {role};\n" + return subprocess.run([db.psql_bin, "-X", "-q", "-A", "-t", "-v", "ON_ERROR_STOP=1"], + input=head + script, capture_output=True, encoding="utf-8", + errors="replace", env=db.env(appname="t271"), timeout=120, check=False) + + +def _sql(db, script: str, role: str | None = None) -> str: + proc = _psql(db, script, role) + assert proc.returncode == 0, (f"psql{' as ' + role if role else ''} exited " + f"{proc.returncode}: {proc.stderr.strip()}\n{script}") + return proc.stdout.strip() + + +def _rows(db, query: str) -> list: + """`query`'s rows as JSON objects, read in the register's schema, by + `jsonb_agg`, whose text is one line.""" + return json.loads(_sql(db, f"SET search_path TO {SCHEMA};\n" + f"SELECT coalesce(jsonb_agg(t), '[]'::jsonb) FROM ({query}) t;") + .splitlines()[-1]) + + +def structured(db) -> dict: + """The four structured tables of `db`, as `STRUCTURED` reads them, each a + sorted list.""" + return {table: json.loads(_sql(db, f"SELECT coalesce(jsonb_agg(r ORDER BY r::text), '[]') " + f"FROM ({query}) AS q(r);")) + for table, query in STRUCTURED.items()} + + +def _renders(db) -> dict: + """SQL's own render (lane 1's T107, `render_file`) of every path in + `files`, {path: bytes}.""" + return {r["path"]: base64.b64decode(r["b64"]) for r in _rows( + db, "SELECT path, encode(render_file(path), 'base64') AS b64 FROM files ORDER BY path")} + + +class Estate(Workspace): + """TEST 6'S PRIMARY ESTATE (AT-6, "Fixture"), as the module's docstring + sets it out: the fixture register at C imported on `pg`, and the cutover + by AT-LR006's route, its marker commit on the bare origin. Until a step's + task lands, the case fails at that step's own assertion, naming it.""" + + def __init__(self, root: Path, pg): + super().__init__(root, SEED) + proc = self.edit("log", "NOTED", f"lane:{OPERATOR}", "test 6's register, at C", + env={"LANES_LANE": OPERATOR}) + assert proc.returncode == 0, f"lanes-edit.sh log NOTED: {_said(proc)}" + self.c = self.tip() + # The operator lane's git author, in its checkout's own configuration: + # a way out names its entry's author as git does there, with every + # inherited `GIT_*` variable removed first (D12), so this module's + # `GIT_AUTHOR_*` never reach it (the module's readings). + self.git("config", "user.name", AUTHOR_NAME) + self.git("config", "user.email", AUTHOR_EMAIL) + self.pg = pg + self.bin = root / "bin" + self.bin.mkdir() + (self.bin / "psql").symlink_to(pg.psql_bin) + self.env["PATH"] = str(self.bin) + os.pathsep + self.env["PATH"] + self.copy = flipped_indexer(root / "flip") + self.index_conf = self.config(pg, "index") + self.primary_conf = self.config(pg, "primary") + self.persons = 0 + imported = self.import_at(self.c) + assert imported.returncode == 0, ( + f"test 6's import at C failed (lane 1's T115, `import --at`):\n{_said(imported)}") + assert self.head() == 0, f"after the import the head is {self.head()}, not 0" + self.marker = self._cutover() + + # ------------------------------------------------------------ the configuration + def config(self, pg, mode: str, name: str = "") -> Path: + """The operator's configuration (CLI4.10 section 2.5): `mode`, the + register's two URLs on the cluster's Unix socket, a private password + file each, `register_label=` and `register_schema=`. Mode 0600.""" + passfile = self.conf / "pgpass" + if not passfile.exists(): + passfile.write_text("", encoding="utf-8") + passfile.chmod(0o600) + path = self.conf / f"lanes-index-{name or mode}.conf" + path.write_text("\n".join([ + f"mode={mode}", f"register_url={pg.url()}", f"register_passfile={passfile}", + f"reader_url={pg.url()}", f"reader_passfile={passfile}", + f"register_label={LABEL}", f"register_schema={SCHEMA}", ""]), encoding="utf-8") + path.chmod(0o600) + return path + + # ------------------------------------------------------------ the SQL side + def rows(self, query: str) -> list: + return _rows(self.pg, query) + + def head(self) -> int: + return self.rows("SELECT seq FROM register_head")[0]["seq"] + + def switch(self) -> dict: + return self.rows("SELECT * FROM register_switch")[0] + + def mirror(self) -> dict: + return self.rows("SELECT * FROM mirror_state")[0] + + def count(self) -> int: + return self.rows("SELECT count(*) AS n FROM journal")[0]["n"] + + def entry(self, seq: int) -> dict: + found = self.rows(f"SELECT seq, kind, verb, message, git_commit, operator FROM journal " + f"WHERE seq = {seq}") + assert len(found) == 1, f"the journal holds no entry at seq {seq}: {found}" + return found[0] + + def edits(self, seq: int) -> list: + return [(r["op"], r["path"], r["new_text"]) for r in self.rows( + f"SELECT ord, op, path, new_text FROM journal_edits WHERE seq = {seq} ORDER BY ord")] + + def renders(self) -> dict: + return _renders(self.pg) + + def commit_call(self, base: int, body: dict) -> subprocess.CompletedProcess: + """The commit call as a writer sends it (section 1.3's step 3; + AT-LR006's fixture): one SERIALIZABLE transaction around + `commit_write`, as REGISTER-WRITER.""" + version = self.rows("SELECT version FROM schema_version")[0]["version"] + generation = self.switch()["generation"] + literal = json.dumps(body, ensure_ascii=True).replace("'", "''") + return _psql(self.pg, f"BEGIN ISOLATION LEVEL SERIALIZABLE;\n" + f"SELECT {SCHEMA}.commit_write({base}, '{uuid.uuid4()}'::uuid, " + f"{version}, '{generation}'::uuid, '{literal}'::jsonb);\nCOMMIT;\n", + WRITER) + + def committed(self, base: int, body: dict, what: str) -> int: + proc = self.commit_call(base, body) + assert proc.returncode == 0, (f"{what}: commit_write refused it (lane 1's T107):\n" + f"{proc.stderr.strip()}") + return int(proc.stdout.strip().splitlines()[-1]) + + def _cutover(self) -> str: + """AT-LR006's route from the import: the `cutover` entry, its marker + commit pushed as a fast-forward of C, then `record_marker`.""" + lines = _store_lines(LABEL, self.c, self.tree(self.c)) + text = "\n".join(lines) + "\n" + edits = [{"ord": 1, "op": "create", "path": "lanes/STORE"}] + edits += [{"ord": n, "op": "append", "path": "lanes/STORE", "new_text": line} + for n, line in enumerate(lines, start=2)] + cut = self.committed(0, _entry( + "cutover", "cutover", "t271: the cutover", edits=edits, + files=[{"path": "lanes/STORE", "present": True, + "sha256": _sha256(text.encode("utf-8")), "final_newline": True}]), + "the cutover entry") + marker = self.commit({"lanes/STORE": text}, + f"cutover: lanes/STORE, the marker\n\nRegister-Seq: {cut}") + assert self.origin_parent(marker) == self.c, "the marker commit is a fast-forward of C" + version = self.rows("SELECT version FROM schema_version")[0]["version"] + answer = _sql(self.pg, f"SELECT {SCHEMA}.record_marker({version}, {cut}, '{marker}', " + f"'{WS}');", WRITER) + assert answer == "present", f"record_marker answered {answer!r}, not present" + switch = self.switch() + assert (switch["mode"], switch["marker_state"], self.head()) == ("primary", "present", 1), ( + f"AT-LR006's route left the switch {switch} and the head {self.head()}, not primary, " + f"present and 1") + return marker + + def write_body(self, text: str) -> dict: + """A write that appends `text`, a line of no kind, to + `lanes/LANES.md`: no structured row.""" + after = self.renders()["lanes/LANES.md"] + (text + "\n").encode("utf-8") + return _entry("write", "log", f"LANES({OPERATOR}@{WS}): {text}", + journal={"args_sha256": ARGS_SHA256}, + edits=[{"ord": 1, "op": "append", "path": "lanes/LANES.md", + "new_text": text}], + files=[{"path": "lanes/LANES.md", "present": True, + "sha256": _sha256(after), "final_newline": True}]) + + def write(self, text: str) -> int: + """A primary write (the module's docstring): its seq.""" + base = self.head() + seq = self.committed(base, self.write_body(text), f"a primary write, {text!r}") + assert seq == base + 1, f"the write took seq {seq}, not {base + 1}" + return seq + + def replace_line(self, path: str, line_no: int, text: str) -> int: + """A primary write that replaces line `line_no` of `path`, a line of + no kind, with `text`: one `replace` edit, naming the line by its old + text's digest (section 1.3), and no structured row. Its seq.""" + image = self.renders()[path] + lines = image.decode("utf-8").split("\n") + assert image.endswith(b"\n") and 1 <= line_no < len(lines), (path, line_no, lines) + old, lines[line_no - 1] = lines[line_no - 1], text + after = "\n".join(lines).encode("utf-8") + base = self.head() + seq = self.committed(base, _entry( + "write", "log", f"LANES({OPERATOR}@{WS}): t271: {path} line {line_no} replaced", + journal={"args_sha256": ARGS_SHA256}, + edits=[{"ord": 1, "op": "replace", "path": path, "line_no": line_no, + "old_sha256": _sha256(old.encode("utf-8")), "new_text": text}], + files=[{"path": path, "present": True, "sha256": _sha256(after), + "final_newline": True}]), + f"a primary write replacing line {line_no} of {path}") + assert seq == base + 1, f"the write took seq {seq}, not {base + 1}" + return seq + + def record(self, sha: str | None, error: str | None = None, + ws: str = "ws-t271") -> subprocess.CompletedProcess: + return _psql(self.pg, f"SELECT {SCHEMA}.record_mirror_state('{ws}', " + f"{'NULL' if sha is None else repr(sha)}, " + f"{'NULL' if error is None else repr(error)});", WRITER) + + # ------------------------------------------------------------ lanes-index + def index(self, *args, conf: Path | None = None, env: dict | None = None, + timeout: float = 300) -> subprocess.CompletedProcess: + """The flipped copy, as the operator lane through its checkout.""" + child = {"LANES_INDEX_CONFIG": str(conf or self.primary_conf), "LANES_LANE": OPERATOR, + "LANES_INDEX": None, "LANES_EDIT": str(self.copy.parent / "lanes-edit.sh")} + child.update(env or {}) + return self.run(sys.executable, self.copy, *args, cwd=self.wip, timeout=timeout, + env=child) + + def import_at(self, sha: str, *, conf: Path | None = None, + cwd: Path | None = None, env: dict | None = None) -> subprocess.CompletedProcess: + """`lanes-index import --at <sha>`, the shipped one, as the operator + lane through its checkout (test 7's form).""" + child = {"LANES_INDEX_CONFIG": str(conf or self.index_conf), "LANES_LANE": OPERATOR, + "LANES_INDEX": None} + child.update(env or {}) + return self.run(sys.executable, INDEXER, "import", "--at", sha, cwd=cwd or self.wip, + timeout=400, env=child) + + def render(self) -> subprocess.CompletedProcess: + """The render a primary write forks, `render --checkout <c>`, run in + the foreground: its exit is the wait for it.""" + return self.index("render", "--checkout", str(self.wip)) + + def status(self) -> subprocess.CompletedProcess: + """`lanes-index status`, after a fetch in the checkout: `status` + never fetches, and reads `m` on `origin/main` as last fetched.""" + self.git("fetch", "-q", "origin", check=False) + return self.index("status", conf=self.index_conf) + + def wait_lag_0(self, ceiling: float = 30.0) -> subprocess.CompletedProcess: + """Open point 8's first wait: `status` every 100 ms until its lag is + 0, under `ceiling`. Returns the last `status`.""" + end = time.monotonic() + ceiling + while True: + proc = self.status() + if LAG_0.search(proc.stdout) or time.monotonic() > end: + return proc + time.sleep(0.1) + + def reconcile(self) -> subprocess.CompletedProcess: + return self.index("reconcile") + + def import_single(self, sha: str) -> subprocess.CompletedProcess: + """The single-write import, on a person's word (T324).""" + return self.index("import", "--single", sha) + + def revert(self, sha: str) -> subprocess.CompletedProcess: + """The renderer's revert, on a person's word (T324).""" + return self.index("render", "--revert", sha) + + def rollback(self) -> subprocess.CompletedProcess: + return self.index("rollback") + + # ------------------------------------------------------------ other hands + def stale(self) -> StaleWorkstation: + return StaleWorkstation(self.root / "stale", self.origin) + + def push_as_person(self, files: dict, message: str) -> str: + """A person's commit of `files` ({path: str}), from a clone of their + own, pushed to origin's `main`. Returns it.""" + self.persons += 1 + clone = self.root / f"person-{self.persons}" + subprocess.run(["git", "clone", "-q", str(self.origin), str(clone)], check=True, + env=self.env, capture_output=True, stdin=subprocess.DEVNULL) + for path, text in files.items(): + target = clone / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(text.encode("utf-8")) + for argv in (["add", "--", *files], ["commit", "-q", "-m", message], + ["push", "-q", "origin", "HEAD:main"]): + subprocess.run(["git", "-C", str(clone), *argv], check=True, env=self.env, + capture_output=True, stdin=subprocess.DEVNULL) + sha = self.origin_tip() + assert subprocess.run(["git", "-C", str(clone), "rev-parse", "HEAD"], capture_output=True, + text=True, env=self.env).stdout.strip() == sha + return sha + + def origin_text(self, path: str) -> str: + return self.origin_blob(self.origin_tip(), path).decode("utf-8") + + +# ------------------------------------------------------------------ the oracles +def _lag(text: str) -> int | None: + m = LAG_N.search(text) + return int(m.group(1)) if m else None + + +def _stop(est: Estate) -> tuple: + """AT-6's stray and stop: the stale workstation's `log NOTED`, then a + primary write and its render. Returns (the stray, the write's seq, the + render).""" + before = est.origin_tip() + stale = est.stale() + proc = stale.note("a note the v1.1.0 writer pushes to a primary estate") + assert proc.returncode == 0, ( + f"the v1.1.0 writer's log NOTED did not push (it knows no marker, so on an estate " + f"with no gate it pushes):\n{_said(proc)}") + stray = est.origin_tip() + assert stray != before and est.origin_parent(stray) == before, ( + f"origin's tip {stray} is not one commit on {before}") + assert est.origin_changed(stray) == [f"lanes/log/{STALE_LANE}.md"], ( + f"the stale write changes {est.origin_changed(stray)}, not its lane's log alone") + k = est.write("t271: a primary write after the stray") + return stray, k, est.render() + + +def _assert_stopped(est: Estate, stray: str, render) -> None: + """The stop, read after the renderer's exit: no render commit, origin's + tip still the stray, and `diverged at` recorded (D16).""" + assert est.origin_tip() == stray, ( + f"origin's tip moved past the stray {stray} to {est.origin_tip()}: the render pushed " + f"over a commit it did not make (lane 3's T322)\n{_said(render)}") + diverged = est.mirror()["diverged_sha"] + assert diverged == stray, ( + f"mirror_state.diverged_sha is {diverged!r}, not the stray {stray} (D16; lane 3's T322)" + f"\n{_said(render)}") + + +def _assert_status_diverged(est: Estate, sha: str, past: tuple | None = None) -> None: + """`status` prints `diverged at <sha>` with the full sha, and the lag: + for a plain stray, a lag of at least 1 (TP:1284); with `past`, `(m, n)` + for a `Register-Seq` above the head, no lag, `m` past `n`, as `status` + says (TP:1319 at B15; lane 3's L2-7).""" + proc = est.status() + assert f"diverged at {sha}" in proc.stdout, ( + f"status does not print `diverged at {sha}` with the full sha (lane 1's T117):\n" + f"{_said(proc)}") + if past is not None: + found = LAG_PAST_N.search(proc.stdout) + assert found and _lag(proc.stdout) is None and ( + int(found.group(1)), int(found.group(2))) == past, ( + f"status does not print no lag, the mirror's {past[0]} past n {past[1]} " + f"(TP:1319; Y:2850; lane 3's L2-7):\n{_said(proc)}") + return + lag = _lag(proc.stdout) + assert lag is not None and lag >= 1, ( + f"status does not print a lag of at least 1 seq (AT-6's stop):\n{_said(proc)}") + + +def _resume(est: Estate, since: str, first: int) -> None: + """THE RESUME (AT-6, each way out): the renderer renders every pending + seq onto origin's tip in order; `status` then shows a lag of 0 and no + divergence; origin's rendered paths equal a full render from SQL, byte + for byte; and `reconcile` exits 0.""" + render = est.render() + proc = est.wait_lag_0() + assert LAG_0.search(proc.stdout), ( + f"after the way out, status shows no lag of 0 within 30 s (the renderer did not " + f"resume):\n{_said(proc)}\nthe render: {_said(render)}") + assert NO_DIVERGENCE.search(proc.stdout) and "diverged at" not in proc.stdout, ( + f"status still shows a divergence:\n{_said(proc)}") + seqs = [s for _sha, found in est.commits_after(since) for s in found] + assert seqs == list(range(first, est.head() + 1)), ( + f"the seqs pushed after {since[:12]} are {seqs}, not {first} to {est.head()} in order") + tip = est.origin_tip() + from_sql = {p: b for p, b in est.renders().items() if RENDER_SET.match(p)} + on_origin = est.origin_render_set(tip) + assert on_origin == from_sql, ( + f"origin's rendered paths at {tip[:12]} differ from a full render from SQL: " + f"{sorted(set(on_origin) ^ set(from_sql))} or " + f"{sorted(p for p in on_origin if p in from_sql and on_origin[p] != from_sql[p])}") + rec = est.reconcile() + assert rec.returncode == 0, f"reconcile does not pass after the way out:\n{_said(rec)}" + + +def _way_out(est: Estate, stray: str, way: str) -> int: + """`import --single <stray>` or `render --revert <stray>`, on a person's + word: one journal entry naming the stray, and `diverged at` cleared. + Returns the entry's seq.""" + n, count = est.head(), est.count() + proc = est.import_single(stray) if way == "import" else est.revert(stray) + verb = "import --single" if way == "import" else "render --revert" + assert proc.returncode == 0, f"lanes-index {verb} {stray} (lane 3's T324):\n{_said(proc)}" + assert (est.head(), est.count()) == (n + 1, count + 1), ( + f"{verb} did not add exactly one journal entry: the head {n} -> {est.head()}, the " + f"count {count} -> {est.count()}") + got = est.entry(n + 1) + kind = "stray-import" if way == "import" else "stray-revert" + assert (got["kind"], got["git_commit"]) == (kind, stray), ( + f"seq {n + 1} is {got}, not a {kind} entry naming {stray} (design.md's kinds)") + mirror = est.mirror() + assert mirror["diverged_sha"] is None, ( + f"after {verb} mirror_state still records diverged at {mirror['diverged_sha']} (D16)") + return n + 1 + + +def _assert_rolled_back(est: Estate, proc) -> None: + """TEST 8'S FIRST ORACLE (test 8 (a)): exit 0; the switch at `files` + with the marker `absent`; origin's last commit removes `lanes/STORE` + alone and carries the rollback entry's seq, the journal's last; origin's + rendered paths equal a full render from SQL, byte for byte; and SQL + writes refused: a `write` entry is LR002, and the head does not move.""" + assert proc.returncode == 0, f"the rollback did not end 0 (lane 3's T326):\n{_said(proc)}" + switch = est.switch() + assert (switch["mode"], switch["marker_state"]) == ("files", "absent"), ( + f"the switch is {switch['mode']}/{switch['marker_state']}, not files/absent") + last = est.rows("SELECT seq, kind, operator FROM journal ORDER BY seq DESC LIMIT 1")[0] + assert (last["kind"], last["operator"]) == ("rollback", True), f"the last entry is {last}" + tip = est.origin_tip() + assert REGISTER_SEQ.findall(est.origin_git("log", "-1", "--format=%B", tip)) == [ + str(last["seq"])], f"origin's last commit does not carry Register-Seq: {last['seq']}" + changed = est.origin_git("diff-tree", "--no-commit-id", "--name-status", "-r", f"{tip}^", tip) + assert changed.split("\n") == ["D\tlanes/STORE", ""], ( + f"origin's last commit does not remove lanes/STORE alone: {changed!r}") + from_sql = {p: b for p, b in est.renders().items() if RENDER_SET.match(p)} + assert est.origin_render_set(tip) == from_sql, ( + "origin's rendered paths differ from a full render from SQL after the rollback") + head = est.head() + refused = est.commit_call(head, est.write_body("t271: a write after the rollback")) + assert refused.returncode != 0 and "LR002" in refused.stderr, ( + f"a write after the rollback was not refused with LR002:\n{_said(refused)}") + assert est.head() == head + + +# =================================================================== the gate model +GUARDED = { + "lanes-md": "lanes/LANES.md", + "log-lane": f"lanes/log/{STALE_LANE}.md", + "aliases-tsv": "lanes/aliases.tsv", + "archive": "lanes/archive/LANES-retired.md", + "store": "lanes/STORE", +} +UNGUARDED = {"repos-tsv": "lanes/repos.tsv", "log-readme": "lanes/log/README.md"} + + +@pytest.mark.parametrize("path", list(GUARDED)) +def test_a_server_side_gate_refuses_the_stale_writers_push(tmp_path, path): + """A MODEL (AT-6, "Options", Q21(b)): with `GATE_HOOK` in the bare + origin, the v1.1.0 writer's push to each guarded path is refused. Its + exit is v1.1.0's 6 (six rejected pushes, "your commit is local"), the + hook's log names the path, and origin's `main` does not move. + + `[lanes-md]` is a hand edit the writer commits (`commit`); `[log-lane]` + is `log NOTED`; `[aliases-tsv]`, `[archive]` and `[store]` are a + person's local commit that the writer publishes (`commit`, #194's + publish of the commits ahead, which takes any added or modified file + under `lanes/`). Needs no engine, and waits for nothing.""" + reg = GatedOrigin(tmp_path / "e") + stale = StaleWorkstation(tmp_path / "stale", reg.origin) + target = GUARDED[path] + before = reg.origin_tip() + if path == "lanes-md": + page = stale.wip / target + page.write_text(page.read_text(encoding="utf-8") + "a hand edit of the register\n", + encoding="utf-8") + proc = stale.v110("commit", "t271: a hand edit of LANES.md") + elif path == "log-lane": + proc = stale.note("a note the gate refuses") + else: + stale.local_commit(target, "a line a person added\n", f"t271: an edit of {target}") + proc = stale.v110("commit", f"t271: publish the edit of {target}") + assert proc.returncode == 6, ( + f"the v1.1.0 writer's push to {target} did not end with its six-attempt refusal, " + f"6:\n{_said(proc)}") + records = reg.gate_records() + assert records and all(r["outcome"] == "refused" for r in records), records + assert {p for r in records for push in r["pushes"] for p in push["guarded"]} == {target}, ( + f"the gate model refused {records}, not {target} alone") + assert reg.origin_tip() == before, "origin's main moved under a refused push" + + +@pytest.mark.parametrize("path", list(UNGUARDED)) +def test_the_gate_model_lets_a_push_to_an_unguarded_path_through(tmp_path, path): + """A MODEL (AT-6, "Options"): a person's push of an edit to + `lanes/repos.tsv` or `lanes/log/README.md`, from the stale workstation's + clone, is accepted ("A person's `repos.tsv` edit is not gated"): origin's + `main` is that commit, and the hook's log says it was let through. Needs + no engine, and waits for nothing.""" + reg = GatedOrigin(tmp_path / "e") + stale = StaleWorkstation(tmp_path / "stale", reg.origin) + target = UNGUARDED[path] + sha = stale.local_commit(target, "a line a person added\n", f"t271: an edit of {target}") + stale.git("push", "-q", "origin", "main") + assert reg.origin_tip() == sha, "the push to an unguarded path did not land" + records = reg.gate_records() + assert [r["outcome"] for r in records] == ["accepted"], records + assert records[0]["pushes"][0]["paths"] == [target], records + + +# =================================================================== the stop +def test_the_v1_1_0_writer_pushing_to_a_primary_estate_stops_the_renderer(pg, tmp_path): + """AT-6, the stop: the stale workstation's `log NOTED`, by the pinned + v1.1.0 writer, lands on origin over a primary estate; the next primary + write's render makes no commit, origin's tip is still the stray, and + `mirror_state.diverged_sha` records it (D16). A later primary write + still commits to SQL, since the mirror is write-behind. Fails until + T107, T115, T117 and lane 3's T321 to T323 land.""" + est = Estate(tmp_path / "e", pg) + stray, k, render = _stop(est) + _assert_stopped(est, stray, render) + assert est.commits_after(stray) == [], "the render pushed a commit after the stray" + later = est.write("t271: a later write, while the mirror is diverged") + assert later == k + 1 and est.head() == later + assert est.mirror()["diverged_sha"] == stray + + +def test_status_prints_diverged_at_the_stray_sha_and_reconcile_imports_nothing(pg, tmp_path): + """AT-6, the stop: after the renderer's exit, `status` prints `diverged + at <the stray's full sha>` and a lag of at least 1; `reconcile` exits + non-zero, the journal's count is unchanged, and `status` still prints + `diverged at` after it. The non-zero is 1: T325's re-render runs T322's + pass, whose recorded stop is the renderer's 1 (exit-codes.md section + 3.4's `reconcile` 1 row; lane 3's L2-6). Fails until T107, T115, T117 + and T321 to T323 land, and also until T325, where T117's check alone + exits 0 (B15 tasks:2487).""" + est = Estate(tmp_path / "e", pg) + stray, _k, render = _stop(est) + _assert_stopped(est, stray, render) + _assert_status_diverged(est, stray) + count, head = est.count(), est.head() + rec = est.reconcile() + assert (est.count(), est.head()) == (count, head), "reconcile wrote to the journal" + assert rec.returncode == 1, ( + f"reconcile on a diverged mirror does not exit 1, the renderer's code for a recorded " + f"`diverged at` (AT-6: non-zero; exit-codes.md section 3.4; lane 3's T325, without " + f"which T117's check alone exits 0; L2-6):\n{_said(rec)}") + after = est.status() + assert f"diverged at {stray}" in after.stdout, ( + f"status no longer prints `diverged at {stray}` after reconcile:\n{_said(after)}") + + +# =================================================================== the ways out +def test_the_single_write_import_resumes_the_renderer_and_reconcile_passes(pg, tmp_path): + """AT-6, the single-write import: `lanes-index import --single <stray>` + adds exactly one journal entry, a `stray-import` naming the stray, whose + line edits equal the stray commit's diff; `mirror_state` no longer + records `diverged at`; the renderer resumes and the pending seqs reach + origin in order; `status` shows a lag of 0 and no divergence; origin's + rendered paths equal a full render; and `reconcile` exits 0. Fails until + T324 (and T107, T115, T117, T321 to T323).""" + est = Estate(tmp_path / "e", pg) + stray, _k, render = _stop(est) + _assert_stopped(est, stray, render) + path = f"lanes/log/{STALE_LANE}.md" + old = est.origin_blob(f"{stray}^", path).decode("utf-8").split("\n") + new = est.origin_blob(stray, path).decode("utf-8").split("\n") + assert new[:len(old) - 1] == old[:-1] and old[-1] == new[-1] == "", "the stray only appends" + added = new[len(old) - 1:-1] + seq = _way_out(est, stray, "import") + assert est.edits(seq) == [("append", path, line) for line in added], ( + f"the import's edits {est.edits(seq)} are not the stray's diff, {added} appended to " + f"{path}") + _resume(est, stray, 2) + assert all(line.encode("utf-8") in est.renders()[path] for line in added) + + +def test_the_renderers_revert_resumes_it_and_reconcile_passes(pg, tmp_path): + """AT-6, the renderer's revert: `lanes-index render --revert <stray>` + journals one `stray-revert` entry with no edits, whose message names the + stray (D16); `diverged at` clears; the resume as for the import; and the + render puts SQL's state back over the stray: on each path the stray + changed, origin's tip equals the stray's parent (the module's readings). + Fails until T324 (and T107, T115, T117, T321 to T323).""" + est = Estate(tmp_path / "e", pg) + stray, _k, render = _stop(est) + _assert_stopped(est, stray, render) + seq = _way_out(est, stray, "revert") + assert est.edits(seq) == [], f"the revert's entry has edits: {est.edits(seq)}" + assert stray[:7] in (est.entry(seq)["message"] or ""), ( + f"the revert's message does not name the stray: {est.entry(seq)['message']!r}") + _resume(est, stray, 2) + tip = est.origin_tip() + for path in est.origin_changed(stray): + assert est.origin_blob(tip, path) == est.origin_blob(f"{stray}^", path), ( + f"{path} at origin's tip is not SQL's state from before the stray") + + +@pytest.mark.parametrize("way", ["import", "revert"]) +def test_rollback_works_after_each_way_out(pg, tmp_path, way): + """AT-6, after each way out and the resume: a rollback, with the + database up, ends with the files byte-identical, the marker gone and SQL + writes refused (test 8's first oracle). Fails until T324 and T326 (and + T107, T115, T117, T321 to T323).""" + est = Estate(tmp_path / "e", pg) + stray, _k, render = _stop(est) + _assert_stopped(est, stray, render) + _way_out(est, stray, way) + _resume(est, stray, 2) + _assert_rolled_back(est, est.rollback()) + + +# =================================================================== the negative cases +OUTSIDE = ["cutover-store", "repos-tsv", "handoff"] + + +@pytest.mark.parametrize("commit", OUTSIDE) +def test_commits_outside_the_render_set_do_not_stop_the_renderer(pg, tmp_path, commit): + """AT-6's negative cases (P366-374): the cutover's own `lanes/STORE` + commit, a person's `lanes/repos.tsv` edit, and a person's commit under + `handoffs/`, each between renders, do not stop the renderer: the next + render renders onto that tip, and `status` shows a lag of 0 and no + divergence. Fails until T107, T115, T117 and T321 to T323 land.""" + est = Estate(tmp_path / "e", pg) + if commit == "cutover-store": + tip = est.origin_tip() + assert tip == est.marker and est.origin_changed(tip) == ["lanes/STORE"] + else: + est.write("t271: a write rendered before the commit") + settled = est.render(), est.wait_lag_0() + assert LAG_0.search(settled[1].stdout), ( + f"the first write was not rendered:\n{_said(settled[0])}\n{_said(settled[1])}") + if commit == "repos-tsv": + files = {"lanes/repos.tsv": est.origin_text("lanes/repos.tsv") + + "repoQ\topensoft/repoQ\n"} + else: + files = {f"handoffs/{OPERATOR}.md": "# a handoff, between renders\n"} + tip = est.push_as_person(files, f"t271: a person's {commit} commit") + assert est.origin_changed(tip) == sorted(files) + k = est.write("t271: the write after the commit") + render = est.render() + proc = est.wait_lag_0() + assert LAG_0.search(proc.stdout) and NO_DIVERGENCE.search(proc.stdout), ( + f"after the {commit} commit the render stopped or lags:\n{_said(proc)}\n{_said(render)}") + gained = est.commits_after(tip) + assert gained and gained[-1][1] == [k], f"origin gained {gained} after {tip[:12]}, not seq {k}" + assert est.origin_parent(gained[0][0]) == tip, "the render did not render onto that tip" + assert est.mirror()["diverged_sha"] is None + + +# =================================================================== R2's N6 at primary +def test_a_register_seq_above_the_head_stops_the_renderer_at_primary_and_the_revert_resumes_it( + pg, tmp_path): + """AT-6, a `Register-Seq` above the head (R2's N6), at `primary`: a + person's commit of a file under `handoffs/` carrying `Register-Seq: + <h+10>` in its final trailer block, then a write at `h+1` and its + render. The pass records a divergence at that commit and pushes nothing; + `status` prints `diverged at` its full sha and no lag, its `m` (`h`+10) + past `n` (`h`+1), as `status` says (TP:1319 at B15; Y:2850; lane 3's + L2-7); `render --revert <sha>` journals one entry with no + edits naming it, and `diverged at` clears; the renderer then finds `m` + at the last render commit before it and renders on, on top of it, to the + revert's own seq; origin equals a full render, `reconcile` exits 0, and a + rollback afterwards works. Fails until T324 and T326 (and T107, T115, + T117, T321 to T323).""" + est = Estate(tmp_path / "e", pg) + est.write("t271: a write rendered before the forged trailer") + est.render() + assert LAG_0.search(est.wait_lag_0().stdout), "the first write was not rendered" + h = est.head() + forged = est.push_as_person({f"handoffs/{OPERATOR}.md": "# a handoff, its trailer copied\n"}, + f"t271: a handoff carrying a copied trailer\n\n" + f"Register-Seq: {h + 10}") + assert est.origin_changed(forged) == [f"handoffs/{OPERATOR}.md"] + est.write("t271: a write after the forged trailer") + render = est.render() + _assert_stopped(est, forged, render) + _assert_status_diverged(est, forged, past=(h + 10, h + 1)) + seq = _way_out(est, forged, "revert") + assert est.edits(seq) == [], f"the revert's entry has edits: {est.edits(seq)}" + assert forged[:7] in (est.entry(seq)["message"] or "") + _resume(est, forged, h + 1) + assert est.origin_parent(est.commits_after(forged)[0][0]) == forged, ( + "the renderer did not render on top of the commit it passed over") + _assert_rolled_back(est, est.rollback()) + + +# =================================================================== AT-MIR's gating case +@pytest.mark.parametrize("case", ["row-only", "git-only"]) +def test_the_mirror_state_row_never_gates_alone(pg, tmp_path, case): + """AT-MIR, the row never gates alone (G; D16): `[row-only]`, with + `mirror_state` recording a divergence by `record_mirror_state` and git + holding no stray, the next render renders and `status` shows a lag of + 0; `[git-only]`, with a stray on origin and the row empty, the renderer + still stops (test 6's oracle). Fails until T107, T115, T117 and T321 to + T323 land.""" + est = Estate(tmp_path / "e", pg) + if case == "row-only": + recorded = est.record("1" * 40) + assert recorded.returncode == 0, f"record_mirror_state: {_said(recorded)}" + assert est.mirror()["diverged_sha"] == "1" * 40 + tip = est.origin_tip() + k = est.write("t271: a write with the row set") + render = est.render() + proc = est.wait_lag_0() + assert LAG_0.search(proc.stdout), ( + f"with the row set and no stray, the render did not render:\n{_said(proc)}\n" + f"{_said(render)}") + gained = est.commits_after(tip) + assert [s for _sha, found in gained for s in found] == [k], gained + return + assert est.mirror()["diverged_sha"] is None, "the row is not empty before the stray" + stray, _k, render = _stop(est) + _assert_stopped(est, stray, render) + _assert_status_diverged(est, stray) + + +# =================================================================== T324's strays +def _stray_files(est: Estate, stray: str) -> tuple: + """The stray's files, from origin's tip: `[stray-deletes-a-row]` deletes + repoD-1's row with no archive copy; `[stray-inserts-before-the-end]` + inserts a line in repoI-1's log after its `STARTED`, above its claims; + `[stray-revives-a-pair]` deletes repoX-1's `RELEASED`, so its `CLAIMED` + on `PAIR_OBJECT` is live beside repoY-1's; `[stray-no-longer-applies]` + retitles `lanes/LANES.md`'s heading by hand.""" + if stray == "stray-deletes-a-row": + path, old, new = "lanes/LANES.md", ROW_D + "\n", "" + elif stray == "stray-inserts-before-the-end": + path = "lanes/log/repoI-1.md" + old = _started("repoI-1", UUID_I1, "opensoft/repoI") + "\n" + new = old + INSERTED_I + "\n" + elif stray == "stray-no-longer-applies": + path, old, new = "lanes/LANES.md", TITLE + "\n", TITLE_BY_HAND + "\n" + else: + path, old, new = "lanes/log/repoX-1.md", RELEASED_X + "\n", "" + text = est.origin_text(path) + assert text.count(old) == 1, f"{path} does not hold the line the stray changes once" + return path, {path: text.replace(old, new)} + + +def _assert_no_longer_applies(est: Estate, sha: str, path: str) -> None: + """L2-8'S REFUSAL (TP:1292-1293; B15 tasks:2486): `import --single <sha>`, + where the stray's edits no longer apply to SQL's images, refuses with 2 + on stderr, naming the edit's path, that its edits no longer apply, and + `render --revert <sha>` as the way out (PC-4); it sends no commit call; + and it writes nothing (the module's readings).""" + before = (est.head(), est.count(), structured(est.pg), est.renders()) + log = est.root / "psql-calls.log" + front = _logging_psql(est.root / "psql-log-bin", est.pg.psql_bin, log) + proc = est.index("import", "--single", sha, + env={"PATH": str(front) + os.pathsep + est.env["PATH"]}) + assert proc.returncode == 2 and all(w in proc.stderr for w in ( + "no longer apply", path, f"render --revert {sha}")), ( + f"import --single of a stray whose edits no longer apply to SQL's images is not " + f"refused with 2 on stderr, naming {path}, that they no longer apply, and " + f"`render --revert {sha}` (lane 3's T324; L2-8):\n{_said(proc)}") + calls = (log.read_text(encoding="utf-8", errors="replace").split("--- psql ")[1:] + if log.exists() else []) + requests = [call for call in calls if not call.startswith("--version")] + assert requests, ( + "the refused import sent no request through the psql first on its PATH, so the log " + "cannot show that it sent no commit call") + sent = [call for call in requests if "commit_write(" in call] + assert not sent, ( + f"the refused import sent {len(sent)} commit call(s): it refuses before any (TP:1292; " + f"B15 tasks:2486):\n{sent[0][:1500]}") + assert (est.head(), est.count(), structured(est.pg), est.renders()) == before, ( + "the refused import changed the head, the journal, the structured tables or SQL's " + "images") + assert est.mirror()["diverged_sha"] == sha, "the refused import cleared the divergence" + assert est.origin_tip() == sha, "the refused import moved origin's main" + + +@pytest.mark.parametrize("stray", ["stray-deletes-a-row", "stray-inserts-before-the-end", + "stray-revives-a-pair", "stray-no-longer-applies"]) +def test_a_strays_single_write_import_leaves_the_tables_equal_to_the_imports_derivation( + pg, tmp_path, stray): + """T324'S STRAYS (R-F10-34; lane 3, #165 6755386771; ERR-48) and a stray + that revives a pair (R-F13c-10; lane 3's batch 5, #165 6778890211): a + person's stray commit on origin's `lanes`; the next write's render stops + `diverged at <sha>`. + + `[stray-deletes-a-row]` and `[stray-inserts-before-the-end]`: `lanes-index + import --single <sha>` loads it through `register commit` and exits 0; + the renderer resumes and `reconcile` passes; and the four structured + tables equal what `import --at` of the same mirror leaves in a second + clone's database, compared as T221's step-6 cases compare them, without + the columns a write stamps, which ERR-48's re-stamped later lines are. + The insert's holds below its line each point at their own line. + + `[stray-revives-a-pair]`: two claims on one object are live after it, + neither `exempt`, since only an import sets `exempt`; `import --single` + refuses with 2, LR005 `one-live-claim` and `held-by=`, writes nothing, + and leaves the four tables as they were. Its way out is the revert, + which `test_the_renderers_revert_resumes_it_and_reconcile_passes` covers. + + `[stray-no-longer-applies]` (lane 3, #165 6809045090, L2-8; AT-6, + TP:1292-1293; B15 tasks:2486): a primary write changes a line after the + stray commit changed it, so the stray's edits no longer apply to SQL's + images; `import --single` refuses with 2, naming the edit and `render + --revert <sha>` as the way out (PC-4), sends no commit call, writes + nothing, and leaves the four tables as they were. + + Fail until T324 (and T107, T115, T117, T321 to T323); the oracle, until + T115's `import --at`; `[stray-revives-a-pair]`, until T324's refusal and + T107's `one_live_claim`; `[stray-no-longer-applies]`, until T324's + `import --single` refusal.""" + est = Estate(tmp_path / "e", pg) + if stray == "stray-revives-a-pair": + holds = {(h["lane_key"], h["verb"], h["exempt"]) for h in est.rows( + f"SELECT lane_key, verb, exempt FROM object_holds " + f"WHERE lower(object) = lower('{PAIR_OBJECT}')")} + assert holds == {("repox-1", "RELEASED", False), ("repoy-1", "CLAIMED", False)}, ( + f"the control: at C repoX-1 has released {PAIR_OBJECT} and repoY-1 holds it, " + f"neither exempt: {holds}") + path, files = _stray_files(est, stray) + sha = est.push_as_person(files, f"t271: a stray edit of {path}, by hand") + assert est.origin_changed(sha) == [path] + if stray == "stray-no-longer-applies": + est.replace_line(path, 1, TITLE_IN_SQL) + else: + est.write("t271: a primary write after the stray") + render = est.render() + _assert_stopped(est, sha, render) + if stray == "stray-no-longer-applies": + _assert_no_longer_applies(est, sha, path) + return + if stray == "stray-revives-a-pair": + before, head, count = structured(est.pg), est.head(), est.count() + proc = est.import_single(sha) + said = proc.stdout + proc.stderr + assert proc.returncode == 2 and all(w in said for w in ("LR005", "one-live-claim", + "held-by=")), ( + f"import --single of a stray that revives a pair is not refused with 2, LR005 " + f"one-live-claim and held-by= (lane 3's T324):\n{_said(proc)}") + assert (est.head(), est.count()) == (head, count), "the refused import wrote an entry" + assert structured(est.pg) == before, "the refused import changed the structured tables" + assert est.mirror()["diverged_sha"] == sha, "the refused import cleared the divergence" + return + _way_out(est, sha, "import") + _resume(est, sha, 2) + got = structured(est.pg) + tip = est.origin_tip() + second = Workspace(tmp_path / "oracle", origin=est.origin) + oracle_db = Database(est.pg.cluster, est.pg.cluster.new_database()) + try: + conf = est.config(oracle_db, "index", name="oracle") + proc = est.import_at(tip, conf=conf, cwd=second.wip, + env={"LANES_REPO": str(second.wip), "HOME": str(second.home), + "AGENT_PROTOCOL_ROOT": str(second.agents)}) + assert proc.returncode == 0, ( + f"the oracle's import --at {tip[:12]} of the mirror failed (lane 1's T115):\n" + f"{_said(proc)}") + want = structured(oracle_db) + finally: + est.pg.cluster.drop_database(oracle_db.name) + for table in STRUCTURED: + assert got[table] == want[table], ( + f"{stray}: {table} is not the import's derivation of the mirror:\n" + f"got {json.dumps(got[table], indent=1)[:3000]}\n" + f"want {json.dumps(want[table], indent=1)[:3000]}") + if stray == "stray-inserts-before-the-end": + lines = {(r["path"], r["line_no"]): r for r in got["log_lines"]} + for hold in got["object_holds"]: + if hold["file"] == path: + line = lines[(hold["file"], hold["ordinal"])] + assert (line["object"], line["verb"]) == (hold["object"], hold["verb"]), ( + hold, line) diff --git a/tests/test_sql_register_render.py b/tests/test_sql_register_render.py new file mode 100644 index 00000000..3e89fadd --- /dev/null +++ b/tests/test_sql_register_render.py @@ -0,0 +1,2837 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Feature 007's test 1 (AT-1, L2-N1; opensoft/openRepoTools#165): the mirror +byte-identical to a full render from SQL after a write. + +THIS MODULE TODAY holds test 1's phase-N part, lane 2's T210: + + * `test_a_storage_layer_entry_renders_byte_identical_to_a_full_render[<entry>]` + (N, RE): the storage layer's write entry, called as the projection writer + will call it, then the pure renderer; + * `test_the_render_of_one_entry_and_of_a_full_render_is_timed_and_recorded` + (N, RE; M6): the pure renderer timed, never asserted; + * `test_sync_source_register_does_nothing_on_primary_and_says_so` (FP, no + engine); + +and the image cache's own cases, lane 2's T210e (B10 tasks:972's +`PENDING-L2`), each named with `image_cache` so that lane 1's T302 selects +them with `-k 'sql_register_render and image_cache'`, with no engine: see +"the image cache (T302's API)" below; + +and the render read's one case with `start`, lane 2's T210f (B10 tasks:1003; +lane 1's T301 cache-forward, #165 6767347563): with `start`, +`register_render_read` returns the images, `{path: bytes}`, and not the rows. +No engine, no image cache: see "the render read's `start`" below; + +and test 1's phase-W part, lane 2's T240: each verb through `lanes-edit.sh` +on `mode=primary` with the pure renderer writing a scratch mirror, its +files-mode twin, `rename-lane`'s transaction then its move, a caller's UTC +kept, and no register `sync` nudge on primary (see "phase W: T240" below); + +and test 1's phase-G part, lane 2's T270's one case here: the mirror read +from the bare origin's `main` after the forked render (see "phase G: T270" +below). + +THE STORAGE-LAYER ENTRY (design S4; the delta spec's "The managed seam stays +the ledger's"). The managed projection writer arrives with the 001 feature's +T024; this change provides the entry it will call and tests it with a fake +writer. Its storage layer is `lanes-index`, the one database client (D2), and +one attempt of S1's loop is two calls (contract section 1): + + 1. `lanes-index register snapshot --write-id new --lane <l> --verb <v> + --args-sha256 <h> --tree <attempt>/tree --checkout <c>` (section 3.2), + which mints the write id and builds the scratch tree at `n`; + 2. the verb's edit in the scratch tree, then the attempt directory, as the + seam writes it (section 3.3's table: `snapshot`, `changes.tsv`, + `images/`, `tree/`, `msg`, `author`, `files`, `not_after`); + 3. `lanes-index register commit --write-id <w> --generation <g> --lane <l> + --verb <v> --args-sha256 <h> --workstation <ws> <attempt>` (section 3.3). + +The fake writer, `projection_entry`, does exactly that, and abandons on any +end of the snapshot but 0 (section 3.3, "The caller's map"). Its cases are +the managed projection itself, which rewrites a row's state cell to carry a +managed-owner marker (`lanes-edit.sh`'s ported reader at 3c26041), and two +other entries of S1's writes, a log line and a `LANES.md` take, so that the +renderer is checked on a row, a line of `LANES.md` and a log. + +THE REGISTER, "against an import": a files-mode repository at commit C, +holding AT-1's fixture register (three lanes, one archived; aliases; a lane +with `HOLD`, `LANDING` and `LANDED` lines; a log with `WORD` lines whose UTC +carries milliseconds), loaded by AT-LR006's route (the test plan at +4610-4615): as `lanes_register_writer`, `commit_write` with an `import` entry +of C's render set, then a `cutover` entry, then `record_marker`, so the +switch is `primary` with the marker `present`. No `lanes-index import` or +`cutover` runs (those are L1-A13's and group C's). + +THE PURE RENDERER is lane 3's T301, as lane 1 built it (#165 6754569755): +`lanes-index render --images --at <k> --out <dir>` (contract section 3.6), +which writes the render set's images at seq `k` from the journal alone. The +full render from SQL is `render_file` (lane 1's T107) of every path in +`files`. + +REAL ENGINE. The entry's cases ask for `pg` (`tests/pgcluster.py`), one +database cloned from the template that T227 builds by the bootstrap; on T205's +empty template they fail, since the schema is not there, and without +PostgreSQL 16 they skip with T205's banner. They fail until L1-A6 (T107 and +T108), L1-A9 (T111, `register snapshot`), L1-A10 (T112, `register commit`) +and T301 land. `lanes-index` runs as T203's flipped copy, `RENDER_GIT_HALF = +True`, so `mode=primary` loads (open point 3), and connects as two logins of +this module's own, members of the writer and the reader groups, by the +cluster's trust. + +`sync --source register` NEEDS NO ENGINE: on primary it makes no `psql` +call, writes nothing and says it does nothing on primary (L1-A15, lane 1's +T117). It runs with T203's register fake first on `PATH`, whose log, with no +call that carries a request in it, is the oracle for "no `psql` call"; the +fake answers T106's `psql --version` probe itself since T203b. +""" + +from __future__ import annotations + +import atexit +import base64 +import hashlib +import json +import os +import re +import shlex +import shutil +import stat +import subprocess +import sys +import tempfile +import time +import uuid +from pathlib import Path +from urllib.parse import quote + +import pytest + +from conftest import REPO, WINDOWS_SKIP +from sql_register_helpers import (LANES_INDEX, PSQL_SHIM, PSQL_SHIM_CONTROL, PSQL_SHIM_LOG, + REGISTER_FAKE_PSQL, RENDER_GIT_HALF_LINE, contract_stub, + flipped_copy) + +pytestmark = [WINDOWS_SKIP, pytest.mark.skipif( + shutil.which("bash") is None or shutil.which("git") is None, + reason="the lane tooling is bash over git")] + +#: THE LANDING GATE'S TABLE (T280; `tests/sql_register_gate.py` reads it, and +#: T281 removes it in the last set): the tasks each id of this module waits +#: for, by T210's, T240's and T270's Orders (tasks.md at 204145ae), keyed by +#: function. Lane 2's plan GP-24 wrote it (task sets 12b's rule 11). +SQL_REGISTER_GATE_TABLE = { + "test_a_caller_composed_utc_and_log_paused_utc_stay_as_written": ("T414", "T415", "T416", "T421", "T422"), # T240; tasks:2313 + "test_a_storage_layer_entry_renders_byte_identical_to_a_full_render": ("T105", "T107", "T108", "T111", "T112", "T227", "T301"), # T210; tasks:1951 + "test_each_write_leaves_the_mirror_byte_identical_to_a_full_render": ("T414", "T415", "T416", "T421", "T422"), # T240; tasks:2313 + "test_each_write_matches_its_files_mode_twin_byte_for_byte": ("T414", "T415", "T416", "T421", "T422"), # T240; tasks:2313 + "test_each_write_reads_back_primary_as_the_mode_that_wrote_it_last": ("T414", "T415", "T416", "T421", "T422"), # T240; tasks:2313 + "test_on_primary_a_write_does_not_nudge_a_register_sync": ("T414", "T415", "T416", "T421", "T422"), # T240; tasks:2313 + "test_rename_lane_commits_the_transaction_only_where_its_handoffs_path_has_no_cache_part_on_primary": ("T414", "T415", "T416", "T421", "T422"), # T240; tasks:2313 + "test_rename_lane_commits_the_transaction_then_a_rerun_makes_only_the_move": ("T414", "T415", "T416", "T421", "T422"), # T240; tasks:2313 + "test_rename_lane_commits_the_transaction_then_its_move_on_primary_takes_no_bytecode_to_to": ("T414", "T415", "T416", "T421", "T422"), # T240; tasks:2313 + "test_sync_source_register_does_nothing_on_primary_and_says_so": ("T105", "T107", "T108", "T111", "T112", "T227", "T301"), # T210; tasks:1951 + "test_the_image_cache_collects_all_but_the_last_three_manifests_past_the_floor": ("T302",), # T210; tasks:1951 + "test_the_image_cache_follows_no_symlink_at_its_lock_or_its_head": ("T302",), # T210; tasks:1951 + "test_the_image_cache_puts_and_gets_an_object_only_by_its_digest": ("T302",), # T210; tasks:1951 + "test_the_image_cache_records_manifests_and_a_head_that_moves_only_forward": ("T302",), # T210; tasks:1951 + "test_the_image_cache_skips_a_busy_or_odd_lock_and_never_waits": ("T302",), # T210; tasks:1951 + "test_the_mirror_on_origin_equals_a_full_render_after_each_write": ("T320", "T321", "T322", "T323", "T325", "T415", "T416"), # T270; tasks:2479 + "test_the_render_of_one_entry_and_of_a_full_render_is_timed_and_recorded": ("T105", "T107", "T108", "T111", "T112", "T227", "T301"), # T210; tasks:1951 + "test_the_render_read_with_start_returns_the_images_and_a_bad_start_costs_one_full_read": ("T301",), # T210; tasks:1951 +} + +LANES_EDIT = REPO / "lanes-edit.sh" + +#: The register's schema, `register_schema=`'s default (contract section 2.5). +SCHEMA = "lanes_register" +WRITER, READER = "lanes_register_writer", "lanes_register_reader" +#: The logins `lanes-index` connects as in this module's real-engine cases. +#: Made once per cluster, members of the writer and the reader groups, with +#: no password. +LOGIN_WRITER, LOGIN_READER = "t210_register_writer", "t210_register_reader" + +#: What the fake writer stamps: the workstation (`--workstation`, and each +#: line's `session <uuid>@<ws>`), the author, and the operator lane. +WS = "Eagle" +AUTHOR = "T210 fake writer <t210@example.invalid>" +OPERATOR = "repoA-2" +MARKER_COMMIT = "e" * 40 +STORE_UTC = "2026-11-09T10:00:00Z" + +#: The register's punctuation, spelled by code point so no raw character +#: enters this file: the em dash, the middle dot of a state cell, the arrow +#: of a `LANDED` line. +EM, DOT, ARROW = chr(0x2014), chr(0x00B7), chr(0x2192) + +SID_A1 = "aaaaaaaa-0001-4000-8000-00000000a001" +SID_A2 = "aaaaaaaa-0003-4000-8000-00000000a003" +SID_Z1 = "eeeeeeee-0001-4000-8000-00000000e001" +TIP = "0123456789abcdef0123456789abcdef01234567" + +#: The render set (Q18 (A); contract section 3.6): `lanes/LANES.md`, +#: `lanes/aliases.tsv`, each `lanes/log/<lane>.md` but the README, and the +#: archive. `lanes/STORE` is the operator entries' alone, never a write's. +RENDER_SET = re.compile(r"^lanes/(LANES\.md|aliases\.tsv|archive/[^/]+\.md" + r"|log/(?!README\.md$)[^/]+\.md)$") +STORE_PATH = "lanes/STORE" +UTC_RE = re.compile(r"^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$") + + +def _row(lane: str, sid: str, state: str, started: str = "2026-10-01T00:00Z") -> str: + return (f"| `{lane}` | harness `{sid}` | Eagle / test / brett | {started} | none " + f"| handoffs/{lane}.md | {state} |") + + +#: AT-1's fixture register at C ("Fixture"): three lanes, one of them +#: archived; `aliases.tsv` entries; a lane with `HOLD`, `LANDING` and +#: `LANDED` lines; a log with `WORD` lines whose UTC carries milliseconds +#: (Q4(d)(i)). `lanes/repos.tsv` and `lanes/log/README.md` are outside the +#: render set, and `register snapshot --tree` takes them from the checkout. +SEED = { + "lanes/LANES.md": "\n".join([ + f"# LANES.md {EM} test 1's fixture register", + "", + "| lane | session id | workstation / env / user | started (UTC) | objects owned " + "| handoff path | state |", + "|---|---|---|---|---|---|---|", + _row("repoA-1", SID_A1, f"LIVE {DOT} 2026-10-01T01:00:00Z {DOT} working"), + _row("repoA-2", SID_A2, f"PAUSED {DOT} 2026-10-01T02:00:00Z {DOT} parked"), + "", + f"HOLD {EM} lane repoA-1 (Eagle), window w, 2026-10-01T03:00:00Z: opensoft/repoA main " + f"{TIP} for a frozen window", + f"LANDING {EM} lane repoA-1, session {SID_A1}@Eagle, 2026-10-01T03:10:00Z, PR #7 into " + f"opensoft/repoA main", + f"LANDED {EM} lane repoA-1, session {SID_A1}@Eagle, 2026-10-01T03:15:00Z, PR #7 into " + f"opensoft/repoA main {ARROW} abc1234", + ""]), + "lanes/aliases.tsv": "# old\tnew\tutc\nrepoOld-1\trepoA-2\t2026-09-30T00:00:00Z\n", + "lanes/archive/LANES-retired.md": "\n".join([ + "# retired rows (Amendment 19(d))", "", + _row("repoZ-1", SID_Z1, f"RETIRED {DOT} 2026-09-02T00:00:00Z {DOT} retired"), + ""]), + "lanes/log/repoA-1.md": "\n".join([ + f"# lane repoA-1 {EM} object log (lane-collision-protocol Amendment 7)", + f"STARTED {EM} lane repoA-1, session {SID_A1}@Eagle, 2026-10-01T00:00:00Z, " + f"lane:repoA-1 {ARROW} home opensoft/repoA; dir /work/repoA1", + ""]), + "lanes/log/repoA-2.md": "\n".join([ + f"# lane repoA-2 {EM} object log (lane-collision-protocol Amendment 7)", + f"STARTED {EM} lane repoA-2, session {SID_A2}@Eagle, 2026-10-01T02:00:00Z, " + f"lane:repoA-2 {ARROW} home opensoft/repoA; dir /work/repoA2", + f"NOTED {EM} lane repoA-2, session {SID_A2}@Eagle, 2026-10-01T02:10:00.123Z, " + f"lane:repoA-2 {EM} a stamp with milliseconds", + f"NOTED {EM} lane repoA-2, session {SID_A2}@Eagle, 2026-10-01T02:11:00.456Z, " + f"lane:repoA-2 {EM} another", + ""]), + "lanes/log/README.md": "# the object logs\n", + "lanes/repos.tsv": "# alias\towner/repo\nrepoA\topensoft/repoA\n", +} + + +# ------------------------------------------------------------------ the estate +def git(cwd: Path, *args: str, env: dict | None = None) -> str: + proc = subprocess.run(["git", *args], cwd=str(cwd), capture_output=True, text=True, + env=env, check=False) + assert proc.returncode == 0, f"git {' '.join(args)} in {cwd}: {proc.stderr}{proc.stdout}" + return proc.stdout + + +def git_env(home: Path) -> dict: + """A git with no person's configuration in it, and an identity of its own.""" + env = {k: v for k, v in os.environ.items() + if not k.startswith(("GIT_", "PG", "LANES_", "TMUX"))} + env.update(HOME=str(home), GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull, + GIT_AUTHOR_NAME="T210 estate", GIT_AUTHOR_EMAIL="t210@example.invalid", + GIT_COMMITTER_NAME="T210 estate", GIT_COMMITTER_EMAIL="t210@example.invalid", + LC_ALL="C") + return env + + +class Estate: + """A bare origin and the lane's checkout at C: SEED (or `files`) committed + and pushed to `main`. `register snapshot --checkout` reads + `lanes/repos.tsv` and `lanes/log/README.md` from its `origin/main`.""" + + def __init__(self, root: Path, files: dict = None): + self.root = root + self.home = root / "home" + self.home.mkdir(parents=True, exist_ok=True) + self.env = git_env(self.home) + self.origin = root / "origin.git" + self.checkout = root / "checkout" + git(root, "init", "-q", "--bare", "-b", "main", str(self.origin), env=self.env) + git(root, "clone", "-q", str(self.origin), str(self.checkout), env=self.env) + self.files = dict(files if files is not None else SEED) + for path, text in self.files.items(): + target = self.checkout / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(text.encode("utf-8")) + git(self.checkout, "add", "-A", env=self.env) + git(self.checkout, "commit", "-q", "-m", "C: the fixture register", env=self.env) + git(self.checkout, "push", "-q", "origin", "main", env=self.env) + self.c = git(self.checkout, "rev-parse", "HEAD", env=self.env).strip() + self.lanes_tree = git(self.checkout, "rev-parse", f"{self.c}:lanes", env=self.env).strip() + + def render_set(self) -> dict: + """C's render set, {path: bytes}.""" + return {p: t.encode("utf-8") for p, t in self.files.items() if RENDER_SET.match(p)} + + def state(self) -> tuple: + """What a write through the storage layer never changes in the + checkout: HEAD, `status --porcelain=v1 -uall`, the index's digest and + `origin/main`.""" + index = self.checkout / ".git" / "index" + return (git(self.checkout, "rev-parse", "HEAD", env=self.env), + git(self.checkout, "status", "--porcelain=v1", "-uall", env=self.env), + hashlib.sha256(index.read_bytes()).hexdigest() if index.exists() else "-", + git(self.checkout, "rev-parse", "origin/main", env=self.env)) + + +# ------------------------------------------------------------------ the SQL side +def psql(db, script: str, role: str = None) -> subprocess.CompletedProcess: + """One `psql` as the fixture's superuser, as `role` where one is named, + with the commit call's settings, so a refusal's first stderr line is + `ERROR: <SQLSTATE>: <message>`.""" + head = "\\set VERBOSITY verbose\n\\set SHOW_CONTEXT never\nSET client_encoding = 'UTF8';\n" + if role: + head += f"SET ROLE {role};\n" + return subprocess.run([db.psql_bin, "-X", "-q", "-A", "-t", "-v", "ON_ERROR_STOP=1"], + input=head + script, capture_output=True, encoding="utf-8", + errors="replace", env=db.env(appname="t210"), timeout=120, check=False) + + +def sql(db, script: str, role: str = None) -> str: + proc = psql(db, script, role) + assert proc.returncode == 0, (f"psql{' as ' + role if role else ''} exited " + f"{proc.returncode}: {proc.stderr.strip()}\n{script}") + return proc.stdout.strip() + + +def rows(db, query: str) -> list: + """`query`'s rows as JSON objects, read in the register's schema.""" + out = sql(db, f"SET search_path TO {SCHEMA};\n" + f"SELECT coalesce(jsonb_agg(q), '[]'::jsonb) FROM ({query}) q;") + return json.loads(out.splitlines()[-1]) + + +def head(db) -> int: + return rows(db, "SELECT seq FROM register_head")[0]["seq"] + + +def db_clock(db) -> int: + """The database's clock, floored to whole seconds, as epoch seconds.""" + return rows(db, "SELECT floor(extract(epoch FROM clock_timestamp()))::bigint AS s")[0]["s"] + + +def full_render(db) -> dict: + """The full render from SQL: `render_file` (lane 1's T107) of every path + in `files`, {path: bytes}.""" + return {r["path"]: base64.b64decode(r["b64"]) for r in rows( + db, "SELECT path, encode(render_file(path), 'base64') AS b64 FROM files ORDER BY path")} + + +def _lines(data: bytes) -> list: + text = data.decode("utf-8") + assert text.endswith("\n"), "every fixture file ends with a newline" + return text[:-1].split("\n") + + +def _entry(kind: str, verb: str, journal: dict = None, **parts) -> dict: + body = {"kind": kind, "verb": verb, "lane": OPERATOR, "workstation": WS, "author": AUTHOR, + "message": f"t210: {kind}"} + body.update(journal or {}) + return {"journal": body, "not_after": "2100-01-01T00:00:00Z", **parts} + + +def _creates(files: dict) -> tuple: + """Each of `files` ({path: bytes}) created, then its lines appended, and + each path's digest as it renders: the edits and the `files` rows.""" + edits, ordinal = [], 0 + for path in sorted(files): + ordinal += 1 + edits.append({"ord": ordinal, "op": "create", "path": path}) + for text in _lines(files[path]): + ordinal += 1 + edits.append({"ord": ordinal, "op": "append", "path": path, "new_text": text}) + return edits, [{"path": p, "present": True, "sha256": hashlib.sha256(files[p]).hexdigest(), + "final_newline": True} for p in sorted(files)] + + +def _commit_call(db, base: int, body: dict) -> int: + """The commit call as the writer sends it, as `lanes_register_writer` + (section 1.3's step 3; AT-LR006's fixture), and the seq it committed.""" + gen = rows(db, "SELECT generation FROM register_switch")[0]["generation"] + version = rows(db, "SELECT version FROM schema_version")[0]["version"] + literal = json.dumps(body, ensure_ascii=True).replace("'", "''") + out = sql(db, f"BEGIN ISOLATION LEVEL SERIALIZABLE;\n" + f"SELECT {SCHEMA}.commit_write({base}, '{uuid.uuid4()}'::uuid, {version}, " + f"'{gen}'::uuid, '{literal}'::jsonb);\nCOMMIT;", WRITER) + return int(out.splitlines()[-1]) + + +def import_to_primary(db, estate: Estate, marker_on_origin: bool = False) -> int: + """AT-LR006's route (TP:4610-4615) over C: an `import` entry of C's render + set, a `cutover` entry, then `record_marker`, by the documented functions + as `lanes_register_writer`. Returns the import's seq. + + `record_marker` records a made-up sha, `MARKER_COMMIT`, and origin stays + at C, for every estate but part G's: only part G's `PrimaryWrites` sets + `marker_on_origin` (T270's line, tasks:2477; lane 2, #165 6866688575; + lane 3, #165 6866808028). There the cutover's marker commit is put on + origin's `main` before `record_marker`, which records it by its sha + (`_marker_commit_on_origin`). It cannot come after: `record_marker` runs + once a cutover, and refuses LR002 once the marker is `present`.""" + edits, files = _creates(estate.render_set()) + imported = _commit_call(db, head(db), _entry( + "import", "import", {"git_commit": estate.c, "git_tree": estate.lanes_tree}, + edits=edits, files=files)) + store = "".join(f"{line}\n" for line in ( + "store=primary", "database=t210", f"import={estate.c}", + f"lanes-tree={estate.lanes_tree}", f"utc={STORE_UTC}")).encode("utf-8") + edits, files = _creates({STORE_PATH: store}) + cut = _commit_call(db, imported, _entry("cutover", "cutover", edits=edits, files=files)) + marker_sha = MARKER_COMMIT + if marker_on_origin: + rendered = rows(db, f"SELECT encode(render_file('{STORE_PATH}'), 'base64') AS b64") + assert base64.b64decode(rendered[0]["b64"]) == store, ( + f"SQL renders {STORE_PATH} otherwise than the cutover entry's bytes") + marker_sha = _marker_commit_on_origin(estate, store, cut) + version = rows(db, "SELECT version FROM schema_version")[0]["version"] + marker = sql(db, f"SELECT {SCHEMA}.record_marker({version}, {cut}, '{marker_sha}', " + f"'{WS}');", WRITER) + assert marker.splitlines()[-1] == "present", f"record_marker answered {marker!r}" + assert rows(db, "SELECT mode, marker_state FROM register_switch") == \ + [{"mode": "primary", "marker_state": "present"}] + if marker_on_origin: + assert rows(db, "SELECT marker_commit FROM register_switch") == \ + [{"marker_commit": marker_sha}], "record_marker did not record the marker commit" + return imported + + +def _marker_commit_on_origin(estate: Estate, store: bytes, cut: int) -> str: + """The cutover's marker commit, put on the bare origin's `main` as a + cutover's own push puts it (Y:2812-2814), and its sha: C's tree plus + `STORE_PATH` holding `store`, the cutover entry's bytes, on parent C, with + `Register-Seq: <cut>` alone in its message's last paragraph. It is made in + the origin through an index of its own, as RG's `commit_in_origin` makes + one (`fdab9267:tests/test_sql_register_renderer_git.py:573-586`), and + `main` moves to it from C, so no clone's refs move; the lane checkouts + that `PrimaryWrites` clones after this are at it.""" + git_dir = f"--git-dir={estate.origin}" + env = dict(estate.env, GIT_INDEX_FILE=str(estate.root / "marker.index")) + blob_file = estate.root / "marker-STORE" + blob_file.write_bytes(store) + git(estate.root, git_dir, "read-tree", estate.c, env=env) + blob = git(estate.root, git_dir, "hash-object", "-w", str(blob_file), env=env).strip() + git(estate.root, git_dir, "update-index", "--add", "--cacheinfo", + f"100644,{blob},{STORE_PATH}", env=env) + tree = git(estate.root, git_dir, "write-tree", env=env).strip() + commit = git(estate.root, git_dir, "commit-tree", tree, "-p", estate.c, + "-m", "t270: the cutover, by AT-LR006's route", + "-m", f"Register-Seq: {cut}", env=estate.env).strip() + git(estate.root, git_dir, "update-ref", "refs/heads/main", commit, estate.c, + env=estate.env) + trailer = git(estate.root, git_dir, "log", "-1", + "--format=%(trailers:key=Register-Seq,valueonly)", commit, + env=estate.env).strip() + assert trailer == str(cut), f"the marker commit's Register-Seq reads {trailer!r}, not {cut}" + return commit + + +# ------------------------------------------------------------------ lanes-index +def require_the_constant() -> None: + """The flipped copy needs Q6(c)'s constant (lane 1's T105, L1-A4): an + assertion, so a case without it fails by saying so.""" + assert len(RENDER_GIT_HALF_LINE.findall(LANES_INDEX.read_bytes())) == 1, ( + f"{LANES_INDEX} holds no single `RENDER_GIT_HALF = ...` line, Q6(c)'s build constant " + f"(L1-A4, lane 1's T105), so no copy can be flipped to load mode=primary") + + +def flipped(tmp_path: Path, name: str = "bin") -> Path: + """T203's flipped copy, `RENDER_GIT_HALF = True`, so `mode=primary` loads, + with `lanes-edit.sh` beside it (the copy rule, CLI4.5 section 6).""" + require_the_constant() + copy = flipped_copy(LANES_INDEX, tmp_path / name, True) + shutil.copy2(str(LANES_EDIT), str(copy.parent / "lanes-edit.sh")) + return copy + + +def ensure_logins(db) -> None: + """The writer's and the reader's login, once per cluster (roles are + cluster-wide), members of their groups, with no password.""" + for login, group in ((LOGIN_WRITER, WRITER), (LOGIN_READER, READER)): + sql(db, f"DO $l$ BEGIN CREATE ROLE {login} LOGIN IN ROLE {group}; " + f"EXCEPTION WHEN duplicate_object THEN NULL; END $l$;") + + +def primary_config(path: Path, register_url: str, reader_url: str, + passfile: Path | None = None) -> Path: + """A 0600 `lanes-index.conf` with `mode=primary` and the register's two + URLs (contract section 2.5), outside every work tree.""" + lines = ["mode=primary", f"register_url={register_url}", f"reader_url={reader_url}"] + if passfile is not None: + lines += [f"register_passfile={passfile}", f"reader_passfile={passfile}"] + path.write_text("\n".join(lines) + "\n", encoding="utf-8") + path.chmod(0o600) + return path + + +def index_env(tmp_path: Path, conf: Path, home: Path, **extra) -> dict: + """The environment `lanes-index` runs in: no inherited `PG*`, `LANES_*`, + `GIT_*` or `TMUX*` (#160's run-wide `LANES_INDEX=off` among them), this + case's configuration, state directory and git identity.""" + env = {k: v for k, v in os.environ.items() + if not k.startswith(("PG", "LANES_", "GIT_", "TMUX"))} + env.update(git_env(home)) + env.update(LANES_INDEX_CONFIG=str(conf), XDG_STATE_HOME=str(tmp_path / "state"), LC_ALL="C") + env.update(extra) + return env + + +def run_index(copy: Path, args, env: dict, cwd: Path = None) -> subprocess.CompletedProcess: + return subprocess.run([sys.executable, str(copy), *[str(a) for a in args]], + capture_output=True, encoding="utf-8", errors="replace", env=env, + timeout=120, cwd=str(cwd) if cwd else None, check=False, + stdin=subprocess.DEVNULL) + + +def keys(stdout: str) -> dict: + """A `key=value` output's keys, each its first value (section 3.2).""" + found = {} + for line in stdout.splitlines(): + key, sep, value = line.partition("=") + if sep and key not in found: + found[key] = value + return found + + +def utc_of(epoch: int) -> str: + return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(epoch)) + + +def epoch_of(utc: str) -> int: + import calendar + return calendar.timegm(time.strptime(utc, "%Y-%m-%dT%H:%M:%SZ")) + + +# ------------------------------------------------------------------ the fake writer +def _edit_managed_projection(tree: Path, utc: str) -> str: + """S4's projection: repoA-1's row's state cell carries a managed-owner + marker, in the form `lanes-edit.sh`'s ported reader parses (3c26041's + T019): `<STATE> . <utc> . managed-owner mode=... daemon=... generation=... + bound-lane=<lane>`. Returns the new line.""" + path = tree / "lanes" / "LANES.md" + text = path.read_text(encoding="utf-8") + old = _row("repoA-1", SID_A1, f"LIVE {DOT} 2026-10-01T01:00:00Z {DOT} working") + new = _row("repoA-1", SID_A1, f"LIVE {DOT} {utc} {DOT} managed-owner mode=managed " + f"daemon=t210d generation=7 bound-lane=repoA-1") + assert text.count(old + "\n") == 1, "the fixture row is in the scratch tree once" + path.write_text(text.replace(old + "\n", new + "\n"), encoding="utf-8") + return new + + +def _edit_log_noted(tree: Path, utc: str) -> str: + """`log NOTED`'s line, appended to repoA-1's log.""" + line = (f"NOTED {EM} lane repoA-1, session {SID_A1}@{WS}, {utc}, lane:repoA-1 {EM} " + f"test 1's part N") + path = tree / "lanes" / "log" / "repoA-1.md" + path.write_bytes(path.read_bytes() + line.encode("utf-8") + b"\n") + return line + + +def _edit_append_hold(tree: Path, utc: str) -> str: + """`append-line`'s take: a `HOLD` on a repository nobody holds.""" + line = (f"HOLD {EM} lane repoA-2 ({WS}), window w, {utc}: opensoft/repoB main {TIP} " + f"for a check") + path = tree / "lanes" / "LANES.md" + path.write_bytes(path.read_bytes() + line.encode("utf-8") + b"\n") + return line + + +#: The entries the fake writer drives: {id: (lane, verb, the edit, the path +#: it touches)}. The managed projection is S4's own verb (design S4: "run +#: through S1's attempt loop as the verb `managed-projection`"). +ENTRIES = { + "managed-projection": ("repoA-1", "managed-projection", _edit_managed_projection, + "lanes/LANES.md"), + "log-noted": ("repoA-1", "log", _edit_log_noted, "lanes/log/repoA-1.md"), + "append-line-hold": ("repoA-2", "append-line", _edit_append_hold, "lanes/LANES.md"), +} + + +def _canonical_rows(changes: list, images: dict) -> str: + """Section 3.2's canonical rows for every path in `changes.tsv`, sorted by + path bytewise, each LF-ended: `<path>` TAB `1` TAB `<sha256>`, or `0` and + `-` for a path the write removes.""" + out = [] + for path in sorted({c[1] for c in changes}, key=lambda p: p.encode("utf-8")): + if path in images: + out.append(f"{path}\t1\t{hashlib.sha256(images[path]).hexdigest()}\n") + else: + out.append(f"{path}\t0\t-\n") + return "".join(out) + + +def projection_entry(copy: Path, env: dict, checkout: Path, root: Path, entry: str, + message: str) -> dict: + """The storage layer's write entry, driven by a fake writer as the + projection writer will call it (design S4; contract sections 3.2 and 3.3): + `register snapshot --write-id new ... --tree <root>/attempt/tree + --checkout <checkout>`; on 0 alone, the edit, the attempt directory and + `register commit`. Returns what each call answered, the entry's code + (the snapshot's where it did not answer 0, else the commit's), the + attempt directory, the message and the line the edit wrote.""" + lane, verb, edit, _path = ENTRIES[entry] + args_sha256 = hashlib.sha256(json.dumps([lane, verb, message]).encode("utf-8")).hexdigest() + attempt = root / "attempt" + out = {"snapshot": None, "commit": None, "code": None, "attempt": attempt, + "message": message, "line": None, "fields": {}, "args_sha256": args_sha256} + # THE ATTEMPT DIRECTORY EXISTS BEFORE THE FIRST SNAPSHOT, as the seam's + # does (contract section 3.3: its digest, run nonce and attempt "are + # known before the first snapshot"); `--tree` names an empty `tree/` in it. + attempt.mkdir(parents=True, exist_ok=True) + snap = run_index(copy, ["register", "snapshot", "--write-id", "new", "--lane", lane, + "--verb", verb, "--args-sha256", args_sha256, + "--tree", attempt / "tree", "--checkout", checkout], env) + out["snapshot"] = snap + if snap.returncode != 0: + out["code"] = snap.returncode + return out + fields = keys(snap.stdout) + out["fields"] = fields + tree = attempt / "tree" + (attempt / "snapshot").write_text(snap.stdout, encoding="utf-8") + out["line"] = edit(tree, utc_of(int(fields["clock"]))) + git(tree, "add", "-A", "--", "lanes", env=env) + changes = [] + for raw in git(tree, "diff", "--cached", "--no-renames", "--raw", "--no-abbrev", "HEAD", + env=env).splitlines(): + meta, path = raw.split("\t", 1) + parts = meta.split() + changes.append((parts[4], path, parts[2], parts[3])) + assert changes, "the edit staged a change" + (attempt / "changes.tsv").write_text( + "".join(f"{s}\t{p}\t{o}\t{n}\n" for s, p, o, n in changes), encoding="utf-8") + images = {} + for status, path, _old, _new in changes: + if status in ("A", "M"): + images[path] = (tree / path).read_bytes() + target = attempt / "images" / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(images[path]) + (attempt / "files").write_text(_canonical_rows(changes, images), encoding="utf-8") + (attempt / "msg").write_text(message, encoding="utf-8") + (attempt / "author").write_text(AUTHOR + "\n", encoding="utf-8") + (attempt / "not_after").write_text(fields["not_after"] + "\n", encoding="utf-8") + commit = run_index(copy, ["register", "commit", "--write-id", fields["write_id"], + "--generation", fields["generation"], "--lane", lane, + "--verb", verb, "--args-sha256", args_sha256, + "--workstation", WS, attempt], env) + out["commit"] = commit + out["code"] = commit.returncode + return out + + +def render_images(copy: Path, env: dict, k: int, out_dir: Path) -> tuple: + """The pure renderer, T301: `render --images --at <k> --out <dir>` + (contract section 3.6). Returns the call and {path: bytes} of every file + it wrote under `out_dir`.""" + proc = run_index(copy, ["render", "--images", "--at", k, "--out", out_dir], env) + written = {} + if out_dir.is_dir(): + for path in sorted(out_dir.rglob("*")): + if path.is_file(): + written[path.relative_to(out_dir).as_posix()] = path.read_bytes() + return proc, written + + +def _rendered_only(files: dict) -> dict: + return {p: b for p, b in files.items() if RENDER_SET.match(p)} + + +class PrimaryRegister: + """C imported and brought to `primary`, a flipped copy, and the + configuration that reaches the test's database as this module's logins.""" + + def __init__(self, pg, tmp_path: Path): + self.pg = pg + self.estate = Estate(tmp_path / "estate") + self.imported = import_to_primary(pg, self.estate) + ensure_logins(pg) + self.copy = flipped(tmp_path) + (tmp_path / "conf").mkdir() + conf = primary_config(tmp_path / "conf" / "lanes-index.conf", pg.url(LOGIN_WRITER), + pg.url(LOGIN_READER)) + self.env = index_env(tmp_path, conf, self.estate.home) + + +# ============================================================ part N (real engine) + +@pytest.mark.parametrize("entry", list(ENTRIES)) +def test_a_storage_layer_entry_renders_byte_identical_to_a_full_render(pg, tmp_path, entry): + """AT-1's part N: the storage layer's write entry, called as the + projection writer will call it, commits one entry; then the pure + renderer's images at that seq equal the full render from SQL, path set + and bytes, over the four paths, and it writes nothing outside them. The + journal gains exactly one entry, at the old head plus one, carrying the + write's message byte for byte and its write id, unique in the journal; + every row the entry touched reads `primary` as the mode that wrote it + last; the new line's UTC is the database's, in whole seconds, between the + clock read before the write and after it. The checkout is unchanged.""" + reg = PrimaryRegister(pg, tmp_path) + before_head = head(pg) + before_ids = {r["write_id"] for r in rows(pg, "SELECT write_id FROM journal")} + checkout_before = reg.estate.state() + message = f"lanes-edit.sh {ENTRIES[entry][1]}: test 1's part N, {entry}" + clock_before = db_clock(pg) + done = projection_entry(reg.copy, reg.env, reg.estate.checkout, tmp_path, entry, message) + clock_after = db_clock(pg) + assert done["snapshot"].returncode == 0, ( + f"register snapshot exited {done['snapshot'].returncode}: {done['snapshot'].stderr}") + assert done["code"] == 0, f"register commit exited {done['code']}: {done['commit'].stderr}" + seq = before_head + 1 + assert done["commit"].stdout == f"committed {seq}\n", done["commit"].stdout + + # THE JOURNAL: one entry, at the old head plus one, with the message and + # the write id the snapshot minted, unique in the journal. + new = rows(pg, f"SELECT seq, write_id, kind, verb, lane, message FROM journal " + f"WHERE seq > {before_head} ORDER BY seq") + lane, verb, _edit, path = ENTRIES[entry] + assert new == [{"seq": seq, "write_id": done["fields"]["write_id"], "kind": "write", + "verb": verb, "lane": lane, "message": message}], new + assert done["fields"]["write_id"] not in before_ids + assert rows(pg, f"SELECT count(*) AS n FROM journal " + f"WHERE write_id = '{done['fields']['write_id']}'") == [{"n": 1}] + + # THE ROWS: every row the entry wrote reads `primary` as its last writer's. + touched = rows(pg, f"SELECT 'doc_lines' AS t, written_mode AS m FROM doc_lines " + f"WHERE written_seq = {seq} " + f"UNION ALL SELECT 'lanes', last_mode FROM lanes WHERE last_seq = {seq} " + f"UNION ALL SELECT 'log_lines', mode FROM log_lines WHERE seq = {seq} " + f"UNION ALL SELECT 'register_lines', mode FROM register_lines " + f"WHERE seq = {seq} " + f"UNION ALL SELECT 'object_holds', mode FROM object_holds WHERE seq = {seq}") + assert touched and {r["m"] for r in touched} == {"primary"}, touched + + # THE UTC: the database's clock in whole seconds (S6, D13). + utc = utc_of(int(done["fields"]["clock"])) + assert UTC_RE.match(utc) and utc in done["line"] + assert clock_before <= epoch_of(utc) <= clock_after, (clock_before, utc, clock_after) + + # THE MIRROR: the pure renderer at seq equals the full render from SQL. + proc, images = render_images(reg.copy, reg.env, seq, tmp_path / "mirror") + assert proc.returncode == 0, f"render --images exited {proc.returncode}: {proc.stderr}" + assert all(RENDER_SET.match(p) or p == STORE_PATH for p in images), ( + f"the renderer wrote outside its four paths: {sorted(images)}") + full = _rendered_only(full_render(pg)) + assert sorted(_rendered_only(images)) == sorted(full), "the path sets are equal" + for name in full: + assert _rendered_only(images)[name] == full[name], f"{name}'s bytes differ" + assert done["line"].encode("utf-8") + b"\n" in full[path] + assert images[path] == (done["attempt"] / "images" / path).read_bytes(), ( + "the image the writer sent is the one rendered") + assert reg.estate.state() == checkout_before, "the lane checkout is unchanged" + + +def _stats(samples: list) -> dict: + """Section 5.3's statistics: median and p95 by nearest rank, min-max, n.""" + ordered = sorted(samples) + rank = lambda p: ordered[max(0, -(-p * len(ordered) // 100) - 1)] # noqa: E731 + return {"median": rank(50), "p95": rank(95), "min": ordered[0], "max": ordered[-1], + "n": len(ordered)} + + +def test_the_render_of_one_entry_and_of_a_full_render_is_timed_and_recorded(pg, tmp_path): + """M6 (section 5.1): the pure renderer's time, exec to exit, cold once + and ten warm, for a full render of the fixture register (its images at + the import's seq) and for one journal entry's image (its images at the + seq of one entry the storage layer committed on top), each recorded with + section 5.3's statistics and its n in the job's log and + `$GITHUB_STEP_SUMMARY` where it is set; never asserted. The correctness + alongside: every run answers 0; the full render equals C's files byte for + byte; the one entry's render equals the full render from SQL for the + same paths, so a measurement that rendered wrongly fails, whatever its + time.""" + reg = PrimaryRegister(pg, tmp_path) + done = projection_entry(reg.copy, reg.env, reg.estate.checkout, tmp_path, "log-noted", + "lanes-edit.sh log: test 1's measured entry") + assert done["code"] == 0, (done["snapshot"].stderr, done["commit"] and done["commit"].stderr) + seq = int(done["commit"].stdout.split()[1]) + path = ENTRIES["log-noted"][3] + sql_render = _rendered_only(full_render(reg.pg)) + figures = {} + for label, k in (("full render, the fixture register", reg.imported), + ("one entry's image", seq)): + times = [] + for n in range(11): + out_dir = tmp_path / "timed" / f"{k}-{n}" + start = time.monotonic_ns() + proc, images = render_images(reg.copy, reg.env, k, out_dir) + times.append((time.monotonic_ns() - start) / 1e6) + assert proc.returncode == 0, f"render --images --at {k}: {proc.stderr}" + if k == reg.imported: + assert _rendered_only(images) == reg.estate.render_set(), ( + "the full render is C's render set, byte for byte") + else: + assert images[path] == sql_render[path], ( + "the one entry's render equals the full render from SQL") + figures[label] = (times[0], _stats(times[1:])) + lines = [] + for label, (cold, warm) in figures.items(): + lines.append(f"| M6 | fixture cluster, Unix socket | `render --images`, {label} | " + f"cold {cold:.1f} ms | median {warm['median']:.1f} ms, p95 " + f"{warm['p95']:.1f} ms, {warm['min']:.1f}-{warm['max']:.1f} ms, " + f"n={warm['n']} |") + print("\n" + "\n".join(lines)) + summary = os.environ.get("GITHUB_STEP_SUMMARY") + if summary: + with open(summary, "a", encoding="utf-8") as handle: + handle.write("\n".join(lines) + "\n") + + +# ============================================================ `sync --source register` (FP) + +def fake_psql_dir(directory: Path, answers: list = None) -> dict: + """T203's register fake, written to `directory` as `psql`, which a case + puts first on `PATH`. Since T203b it answers `psql --version` itself, + `psql (PostgreSQL) 16.4` (`PSQL_VERSION_LINE`), the probe lane 1's T106 + makes once per process on a register path, and logs that probe as its + own kind (`"kind": "version"`, no `call`). Returns the variables the fake + reads: its log, and its answers where `answers` teaches any (T203's + docstring).""" + directory.mkdir(parents=True, exist_ok=True) + (directory / "psql").write_text(REGISTER_FAKE_PSQL, encoding="utf-8") + (directory / "psql").chmod(0o755) + env = {"FAKE_PSQL_LOG": str(directory / "psql.log")} + if answers is not None: + (directory / "answers.json").write_text(json.dumps(answers), encoding="utf-8") + env["FAKE_PSQL_ANSWERS"] = str(directory / "answers.json") + return env + + +def fake_calls(fake: dict) -> list: + """The fake's log, one object per call that carried a request: the + entries with no `kind`. A `psql --version` probe (T203b's `"kind": + "version"`) sends nothing, so it is left out, as T210's own wrapper + left it out before T203b.""" + log = Path(fake["FAKE_PSQL_LOG"]) + if not log.exists(): + return [] + entries = [json.loads(line) for line in log.read_text(encoding="utf-8").splitlines() if line] + return [e for e in entries if e.get("kind") != "version"] + + +#: What `_masked_path` keeps off a case's `PATH`: an installed `lanes-index`, +#: a real `psql`, and every `pg_` client that `postgresql-16` puts beside it. +_MASKED_NAMES = ("psql", "lanes-index") +_MASKED_PREFIX = "pg_" +#: `_masked_path`'s mirrors, built once per process: each masked directory's +#: real path, to its mirror under the one `l2-pathmask-` directory. +_PATH_MIRRORS: dict = {} +_PATH_MIRROR_ROOT: list = [] + + +def _masked_path() -> str: + """The caller's PATH with every directory kept, in its place, and each one + that holds a masked name swapped for a mirror of it without them. A real + `psql` or `pg_` client, or an installed `lanes-index`, is never what a + case runs; but dropping the directory that holds one drops what sits + beside it. On a GitHub runner, `postgresql-16`'s client package puts + `psql` in `/usr/bin` together with `git` and `bash`, and `/bin` links + there, so a filter that drops the directory leaves a case no `git` or + `bash` to run. The mirror is a directory of symlinks, one per entry, each + to the original entry's absolute path, the masked names left out. It is + built once per process, keyed by the directory's real path, under one + temporary directory that an `atexit` handler removes. A directory that + holds no masked name passes through unchanged, so where no `PATH` + directory holds one, the PATH is what the old filter gave; empty entries + are left out, as that filter left them.""" + kept = [] + for part in os.environ.get("PATH", "").split(os.pathsep): + if not part: + continue + real = os.path.realpath(part) + if real not in _PATH_MIRRORS: + try: + names = os.listdir(real) + except OSError: + names = [] + if not any(_is_masked(name) for name in names): + kept.append(part) + continue + _PATH_MIRRORS[real] = _path_mirror(real, names) + kept.append(_PATH_MIRRORS[real]) + return os.pathsep.join(kept) + + +def _is_masked(name: str) -> bool: + return name in _MASKED_NAMES or name.startswith(_MASKED_PREFIX) + + +def _path_mirror(real: str, names: list) -> str: + """`real`'s mirror: a new directory under the one `l2-pathmask-` + directory, holding a symlink to each entry of `real` but the masked.""" + if not _PATH_MIRROR_ROOT: + root = tempfile.mkdtemp(prefix="l2-pathmask-") + atexit.register(shutil.rmtree, root, ignore_errors=True) + _PATH_MIRROR_ROOT.append(root) + mirror = tempfile.mkdtemp(prefix=(os.path.basename(real) or "root") + "-", + dir=_PATH_MIRROR_ROOT[0]) + for name in names: + if not _is_masked(name): + os.symlink(os.path.join(real, name), os.path.join(mirror, name)) + return mirror + + +def workspace(root: Path, fakebin: Path) -> tuple: + """A files-mode workspace on a bare origin, at C (SEED), whose + `workspace.yaml` names that origin as its `repository:` and the checkout + as its `path:`, as `test_sql_register_import.py`'s `Workspace` names + them, with a fake `tmux` and `fakebin` first on `PATH`, in the + environment that `Workspace` sets. Returns (the estate, the environment, + the register source `sync --source` must name: `register:` and the + repository as `lanes-index`'s `source_of` normalizes it, its `.git` + dropped).""" + estate = Estate(root) + agents = estate.home / ".agents" + agents.mkdir(parents=True, exist_ok=True) + (agents / "workspace.yaml").write_text( + f"repository: {estate.origin}\npath: {estate.checkout}\n", encoding="utf-8") + source = "register:" + re.sub(r"\.git$", "", str(estate.origin)) + fakebin.mkdir(parents=True, exist_ok=True) + (fakebin / "tmux").write_text("#!/bin/sh\nexit 1\n", encoding="utf-8") + (fakebin / "tmux").chmod(0o755) + for d in ("state", "config", "tmp"): + (root / d).mkdir(parents=True, exist_ok=True) + env = dict(estate.env) + env.update(AGENT_PROTOCOL_ROOT=str(agents), TMPDIR=str(root / "tmp"), + XDG_STATE_HOME=str(root / "state"), XDG_CONFIG_HOME=str(root / "config"), + CLAUDE_CONFIG_DIR=str(estate.home / ".claude"), LANES_WORKSTATION=WS, + LANES_HOST="eagle", LANES_OS="linux", LANES_CONTAINER="none", + LANES_IN_CONTAINER="0", LANES_NO_GITHUB="1", LANES_REPO=str(estate.checkout), + PATH=str(fakebin) + os.pathsep + _masked_path()) + return estate, env, source + + +def test_sync_source_register_does_nothing_on_primary_and_says_so(tmp_path): + """`lanes-index sync --source register:<owner/repo>` on a `mode=primary` + workstation, this workstation's own source, makes no `psql` call, writes + nothing (the checkout's HEAD, status, index and `origin/main` as they + were, and nothing in `lanes-index`'s state directory but its sync lock: + no index store, no status record), exits 0, and its output says it does + nothing on primary (AT-1's + FP case; lane 1's T117, "`cmd_sync` with a `register:<owner/repo>` + source does nothing on primary, and says so"; the delta's "The post-write + nudge does not re-index the mirror into its own source"). #160's + run-wide `LANES_INDEX=off` is unset, or it would say nothing of + primary.""" + fakebin = tmp_path / "fakebin" + fake = fake_psql_dir(fakebin) + estate, env, source = workspace(tmp_path / "ws", fakebin) + copy = flipped(tmp_path) + sock = tmp_path / "sock" + sock.mkdir() + passfile = tmp_path / "conf" / "pgpass" + passfile.parent.mkdir() + passfile.write_text("", encoding="utf-8") + passfile.chmod(0o600) + host = quote(sock.as_posix(), safe="") + conf = primary_config(tmp_path / "conf" / "lanes-index.conf", + f"postgresql://lanes_w_t210@{host}:5432/lanes_t210", + f"postgresql://lanes_r_t210@{host}:5432/lanes_t210", passfile) + env.update(fake, LANES_INDEX_CONFIG=str(conf)) + env.pop("LANES_INDEX", None) + state_root = Path(env["XDG_STATE_HOME"]) + before, state_before = estate.state(), _files_under(state_root) + proc = run_index(copy, ["sync", "--source", source], env, cwd=estate.checkout) + said = proc.stdout + proc.stderr + assert proc.returncode == 0, f"sync exited {proc.returncode}: {said}" + assert fake_calls(fake) == [], f"sync made a psql call on primary: {fake_calls(fake)}" + assert "primary" in said, f"sync's output does not say it does nothing on primary: {said!r}" + assert estate.state() == before, "sync wrote to the checkout" + state_after = _files_under(state_root) + written = sorted(p for p, digest in state_after.items() if state_before.get(p) != digest) + assert all(SYNC_LOCK_FILES.match(p) for p in written), ( + f"sync wrote under {state_root} on primary, beyond its lock: {written}") + + +#: What a sync may leave in `lanes-index`'s state directory, +#: `$XDG_STATE_HOME/openRepoTools/`, when it does nothing: its one-at-a-time +#: lock and the lock's rerun marks (`SyncLock`, 14(d) and #161). An index +#: store (`lanes-index.sqlite`) or a status record is a write. +SYNC_LOCK_FILES = re.compile(r"^openRepoTools/lanes-index\.(lock|rerun(-[a-z]+)?)$") + + +def _files_under(root: Path) -> dict: + """Every file under `root`, {relative path: sha256}.""" + if not root.is_dir(): + return {} + return {p.relative_to(root).as_posix(): hashlib.sha256(p.read_bytes()).hexdigest() + for p in sorted(root.rglob("*")) if p.is_file()} + + +# ============================================================ the image cache (T302's API) +# +# THE IMAGE CACHE'S OWN TEST (lane 2's T210e; B10 tasks:972's `PENDING-L2`; +# F10-OWED items 26 and 34): lane 1's T302 adds the cache to `lanes-index`, +# under its state directory, `register-images/` (design Y:4963; PC-1), with +# the five functions and two constants of lane 3's ruling (#165 6746004829, +# extended by 6755051914) and lane 1's formats (#165 6755106847, "The +# formats, for lane 2's test"), as its fix round left them (6755799745; lane +# 3's delta check, 6755954683). T302's first run selects these cases with +# `-k 'sql_register_render and image_cache'`. They need no engine: each loads +# `lanes-index` as a module, with `XDG_STATE_HOME` under the case's own +# directory, and calls the API in process. They fail until T302 lands, by the +# assertion `image_cache_module` makes; the last one fails until lane 1's +# follow-up commit too (6755954683, doubts 1 and 2). + +#: The API lane 3's ruling fixes: five functions and two constants. +IMAGE_CACHE_API = ("image_cache_get", "image_cache_put", "image_cache_head", + "image_cache_record", "image_cache_collect") +IMAGE_CACHE_CONSTANTS = {"IMAGE_CACHE_KEEP": 3, "IMAGE_CACHE_FLOOR_SECONDS": 600} +#: A temp file as lane 1's format names it: `.<name>.tmp-<pid>-<8 hex>`. +IMAGE_CACHE_TEMP = re.compile(r"^\..+\.tmp-[0-9]+-[0-9a-f]{8}$") +#: Older than collection's floor, with room: an hour before now. +IMAGE_CACHE_OLD = 3600 + + +class ImageCache: + """`lanes-index` loaded as a module whose state directory is `state` + (`XDG_STATE_HOME`), with the cache's paths.""" + + def __init__(self, module, state: Path): + self.m = module + self.root = state / "openRepoTools" / "register-images" + self.objects = self.root / "objects" + self.seq = self.root / "seq" + self.head_file = self.root / "head" + self.lock = self.root / "lock" + + def object(self, digest: str) -> Path: + return self.objects / digest + + def age(self, path: Path, seconds: int = IMAGE_CACHE_OLD) -> None: + """Sets `path`'s mtime `seconds` before now, past the floor.""" + then = time.time() - seconds + os.utime(path, (then, then), follow_symlinks=False) + + def temps(self) -> list: + """Every temp file of lane 1's form left anywhere in the cache.""" + if not self.root.is_dir(): + return [] + return sorted(p.relative_to(self.root).as_posix() for p in self.root.rglob(".*") + if IMAGE_CACHE_TEMP.match(p.name)) + + +def image_cache_module(tmp_path: Path, monkeypatch) -> ImageCache: + """`lanes-index` as a module, under its own name so nothing else in the + run shares it, with `XDG_STATE_HOME` set to `<tmp_path>/state`, where + `state_dir()` puts `openRepoTools/register-images/`. Asserts the API is + there: lane 1's T302, B10 tasks:972 (the case's red until it lands).""" + from importlib.machinery import SourceFileLoader + import importlib.util + loader = SourceFileLoader(f"lanes_index_image_cache_{uuid.uuid4().hex}", str(LANES_INDEX)) + spec = importlib.util.spec_from_loader(loader.name, loader) + module = importlib.util.module_from_spec(spec) + loader.exec_module(module) + missing = [name for name in (*IMAGE_CACHE_API, *IMAGE_CACHE_CONSTANTS) + if not hasattr(module, name)] + assert not missing, ( + f"{LANES_INDEX} has no image cache API, {missing} missing: lane 1's T302 (B10 " + f"tasks:972; #165 6755106847) has not landed") + state = tmp_path / "state" + monkeypatch.setenv("XDG_STATE_HOME", str(state)) + return ImageCache(module, state) + + +def _mode(path: Path) -> int: + return stat.S_IMODE(os.lstat(path).st_mode) + + +def _digest(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def test_the_image_cache_puts_and_gets_an_object_only_by_its_digest(tmp_path, monkeypatch): + """`image_cache_put(data)` returns `data`'s sha256 as 64 lowercase hex and + writes `objects/<digest>` under `$XDG_STATE_HOME/openRepoTools/ + register-images/`, the file 0600 and each directory 0700, by a temp file + and a rename that leaves no temp file; a `bytearray` is taken as bytes, + and anything else raises `TypeError` before the cache is touched, the + one error that escapes. `image_cache_get(digest)` returns the bytes only + when they hash to `digest`: a missing object, a digest that is not 64 + lowercase hex, a name outside `objects/`, an object whose bytes changed + and a symlink at the object's name are each a miss (None), and `put` + replaces the bad object and leaves a link's target alone. A second `put` + of an object already whole rewrites nothing and sets its mtime to now, + so the floor keeps it (lane 1's readings 1 and 2; fix round NIT-3 and + NIT-4).""" + cache = image_cache_module(tmp_path, monkeypatch) + m = cache.m + with pytest.raises(TypeError): + m.image_cache_put("lanes/LANES.md as text, not bytes") + assert not (tmp_path / "state").exists(), "put touched the cache before its TypeError" + + data = f"# LANES.md {EM} the image cache's own test\n".encode("utf-8") + digest = m.image_cache_put(data) + assert digest == _digest(data) and re.fullmatch(r"[0-9a-f]{64}", digest), digest + assert cache.object(digest).read_bytes() == data + assert _mode(cache.object(digest)) == 0o600, oct(_mode(cache.object(digest))) + for directory in (tmp_path / "state" / "openRepoTools", cache.root, cache.objects): + assert _mode(directory) == 0o700, f"{directory} is {oct(_mode(directory))}, not 0700" + assert m.image_cache_get(digest) == data + assert m.image_cache_put(bytearray(data)) == digest + assert cache.temps() == [], f"a temp file was left: {cache.temps()}" + + # MISSES: an object that is not there, and digests out of form. + other = _digest(b"never put\n") + assert m.image_cache_get(other) is None + for bad in (digest.upper(), digest[:63], digest + "0", "", "../head", None, 7): + assert m.image_cache_get(bad) is None, f"get({bad!r}) was not a miss" + + # A WHOLE OBJECT IS NOT WRITTEN AGAIN; ITS MTIME COMES TO NOW. + inode = os.lstat(cache.object(digest)).st_ino + cache.age(cache.object(digest)) + assert m.image_cache_put(data) == digest + assert os.lstat(cache.object(digest)).st_ino == inode, "a whole object was rewritten" + assert time.time() - os.lstat(cache.object(digest)).st_mtime < 60, ( + "put of a whole object left its old mtime, so the floor would not keep it") + + # AN OBJECT WHOSE BYTES CHANGED IS A MISS, AND PUT REPLACES IT. + cache.object(digest).write_bytes(b"torn") + assert m.image_cache_get(digest) is None, "get returned bytes that do not hash to the name" + assert m.image_cache_put(data) == digest + assert m.image_cache_get(digest) == data and cache.object(digest).read_bytes() == data + + # A SYMLINK AT THE OBJECT'S NAME IS A MISS, AND PUT REPLACES IT (NIT-4). + outside = tmp_path / "outside" + outside.write_bytes(data) + cache.object(digest).unlink() + cache.object(digest).symlink_to(outside) + assert m.image_cache_get(digest) is None, "get followed a symlink at an object's name" + assert m.image_cache_put(data) == digest + assert not cache.object(digest).is_symlink() and cache.object(digest).read_bytes() == data + assert outside.read_bytes() == data, "put changed a link's target" + assert cache.temps() == [], f"a temp file was left: {cache.temps()}" + + +def test_the_image_cache_records_manifests_and_a_head_that_moves_only_forward(tmp_path, + monkeypatch): + """`image_cache_record(n, manifest)` writes `seq/<n>`, one `<path>` TAB + `<digest>` line per path, each LF-ended, sorted by path bytewise, an + empty manifest an empty file, 0600; a second record of one `n` merges + into the first, a path in both taking the second's digest. `head` is + `<n>` and an LF, read with or without the LF and never with a leading + zero, and moves only forward; a missing `head`, or one with no seq, is + written as the larger of `n` and the highest seq `seq/` lists (NIT-2). + `image_cache_head()` answers (seq, manifest), or None. A record whose `n` + is not a whole number from 0 to 2**63 - 1, or whose manifest is not a + dict of paths with no control character to digests, is skipped, and no + call raises (lane 1's readings 6 and 7).""" + cache = image_cache_module(tmp_path, monkeypatch) + m = cache.m + assert m.image_cache_head() is None + accented = "lanes/log/repo" + chr(0x00E9) + "-1.md" + d1, d2, d3 = (_digest(f"image {k}\n".encode("ascii")) for k in (1, 2, 3)) + m.image_cache_record(5, {"lanes/log/repoA-1.md": d2, accented: d3, "lanes/LANES.md": d1}) + expected = [("lanes/LANES.md", d1), ("lanes/log/repoA-1.md", d2), (accented, d3)] + assert (cache.seq / "5").read_bytes() == "".join( + f"{p}\t{d}\n" for p, d in expected).encode("utf-8"), "the manifest's form or order" + assert cache.head_file.read_bytes() == b"5\n" + assert _mode(cache.seq / "5") == 0o600 and _mode(cache.head_file) == 0o600 + assert _mode(cache.seq) == 0o700 + assert m.image_cache_head() == (5, dict(expected)) + + # THE HEAD NEVER MOVES BACK. + m.image_cache_record(3, {"lanes/LANES.md": d2}) + assert (cache.seq / "3").read_bytes() == f"lanes/LANES.md\t{d2}\n".encode("ascii") + assert cache.head_file.read_bytes() == b"5\n", "a lower record moved the head back" + + # A SECOND RECORD OF ONE SEQ MERGES, ITS OWN DIGEST WINNING. + m.image_cache_record(5, {"lanes/LANES.md": d3, "lanes/aliases.tsv": d1}) + assert m.image_cache_head() == (5, {"lanes/LANES.md": d3, "lanes/aliases.tsv": d1, + "lanes/log/repoA-1.md": d2, accented: d3}) + + # AN EMPTY MANIFEST IS AN EMPTY FILE; THE HEAD READS WITH OR WITHOUT ITS LF. + m.image_cache_record(7, {}) + assert (cache.seq / "7").read_bytes() == b"" and cache.head_file.read_bytes() == b"7\n" + assert m.image_cache_head() == (7, {}) + cache.head_file.write_bytes(b"7") + assert m.image_cache_head() == (7, {}), "a head with no LF is not read" + for bad in (b"07\n", b"7\n\n", b" 7\n", b"seven\n", b""): + cache.head_file.write_bytes(bad) + assert m.image_cache_head() is None, f"a head of {bad!r} was read" + + # A HEAD WITH NO SEQ, OR NONE, IS WRITTEN AS THE LARGER OF n AND seq/'s HIGHEST. + cache.head_file.write_bytes(b"seven\n") + m.image_cache_record(4, {"lanes/LANES.md": d1}) + assert cache.head_file.read_bytes() == b"7\n", "a junk head was not repaired to 7" + cache.head_file.unlink() + m.image_cache_record(2, {"lanes/LANES.md": d1}) + assert cache.head_file.read_bytes() == b"7\n", "a missing head moved back to 2" + + # RECORDS OUT OF FORM ARE SKIPPED, AND RAISE NOTHING. + before = sorted(p.name for p in cache.seq.iterdir()) + for n, manifest in ((-1, {}), (True, {}), (2 ** 63, {}), ("9", {}), (9.0, {}), + (9, {"lanes/LANES.md": d1.upper()}), (9, {"lanes/a\tb.md": d1}), + (9, {"lanes/a\nb.md": d1}), (9, {"lanes/a" + chr(0) + ".md": d1}), + (9, {"": d1}), (9, [("lanes/LANES.md", d1)]), (9, None)): + m.image_cache_record(n, manifest) + assert sorted(p.name for p in cache.seq.iterdir()) == before, ( + "a record out of form wrote a manifest") + assert cache.head_file.read_bytes() == b"7\n" + assert m.image_cache_record(2 ** 63 - 1, {}) is None + assert cache.head_file.read_bytes() == str(2 ** 63 - 1).encode("ascii") + b"\n" + assert cache.temps() == [], f"a temp file was left: {cache.temps()}" + + +def test_the_image_cache_collects_all_but_the_last_three_manifests_past_the_floor( + tmp_path, monkeypatch): + """Collection keeps the manifests of the `IMAGE_CACHE_KEEP` = 3 highest + seqs and removes every older one; it removes an object named in none of + them only when its mtime is over `IMAGE_CACHE_FLOOR_SECONDS` = 600 old, + so an old object a kept manifest names, and a young one none names, both + stay. It removes a temp file of the form `.<name>.tmp-<pid>-<8 hex>` + only past the same floor, and no other name. Where one of the kept + manifests is out of form, it removes no object (lane 1's readings 3, 4 + and 5). `image_cache_record` collects too, under the same lock.""" + cache = image_cache_module(tmp_path, monkeypatch) + m = cache.m + for name, value in IMAGE_CACHE_CONSTANTS.items(): + assert getattr(m, name) == value, f"{name} is {getattr(m, name)!r}, not {value}" + data = [f"image {k}\n".encode("ascii") for k in range(1, 8)] + o = [m.image_cache_put(d) for d in data] + for k in range(1, 6): + m.image_cache_record(k, {"lanes/LANES.md": o[k - 1]}) + assert sorted(p.name for p in cache.seq.iterdir()) == ["3", "4", "5"], ( + "record kept a manifest older than the last three") + + for k in (0, 1, 2, 3, 6): + cache.age(cache.object(o[k])) + temps = {"objects/.x.tmp-41-0123abcd": True, "objects/.y.tmp-42-89abcdef": False, + ".head.tmp-43-deadbeef": True, "seq/.5.tmp-44-cafef00d": True} + strays = ("objects/notes.txt", "objects/" + "A" * 64, "objects/.x.tmp-45-XYZ") + for rel, old in temps.items(): + (cache.root / rel).write_bytes(b"part") + if old: + cache.age(cache.root / rel) + for rel in strays: + (cache.root / rel).write_bytes(b"stray") + cache.age(cache.root / rel) + + m.image_cache_collect() + kept = {k for k in range(7) if cache.object(o[k]).exists()} + assert kept == {2, 3, 4, 5}, ( + f"objects kept: {sorted(kept)}, not images 3 and 4 (old, named by seqs 3 and 4), 5 " + f"(named by the head) and 6 (named by none, younger than the floor)") + assert sorted(p.name for p in cache.seq.iterdir() if not p.name.startswith(".")) == \ + ["3", "4", "5"] + for rel, old in temps.items(): + assert (cache.root / rel).exists() is not old, ( + f"{rel}: a temp file {'over' if old else 'under'} the floor was " + f"{'kept' if old else 'removed'}") + for rel in strays: + assert (cache.root / rel).exists(), f"collection removed {rel}, not a name it writes" + assert m.image_cache_head() == (5, {"lanes/LANES.md": o[4]}) + + # A KEPT MANIFEST OUT OF FORM: NO OBJECT IS REMOVED. + cache.age(cache.object(o[5])) + (cache.seq / "4").write_bytes(b"lanes/LANES.md") + m.image_cache_collect() + assert cache.object(o[5]).exists(), ( + "collection removed an object while a kept manifest could not be read") + + +def test_the_image_cache_skips_a_busy_or_odd_lock_and_never_waits(tmp_path, monkeypatch): + """Recording and collection take `register-images/lock` with `LOCK_EX | + LOCK_NB`, tried once: while another holder has it, `image_cache_record` + writes nothing and `image_cache_collect` removes nothing, and neither + waits. A `lock` that is not a regular file, a FIFO with no reader here, + counts as busy, and the call returns at once with nothing changed + (lane 1's fix round, SHOULD-1). The lock file is 0600.""" + import fcntl + import threading + cache = image_cache_module(tmp_path, monkeypatch) + m = cache.m + d1, d2 = (m.image_cache_put(f"image {k}\n".encode("ascii")) for k in (1, 2)) + m.image_cache_record(1, {"lanes/LANES.md": d1}) + assert _mode(cache.lock) == 0o600, oct(_mode(cache.lock)) + loose = m.image_cache_put(b"named by no manifest\n") + cache.age(cache.object(loose)) + + held = os.open(str(cache.lock), os.O_WRONLY | os.O_APPEND) + try: + fcntl.flock(held, fcntl.LOCK_EX | fcntl.LOCK_NB) + start = time.monotonic() + m.image_cache_record(2, {"lanes/LANES.md": d2}) + m.image_cache_collect() + assert time.monotonic() - start < 5, "a call waited for the held lock" + assert not (cache.seq / "2").exists(), "record wrote while the lock was held" + assert cache.head_file.read_bytes() == b"1\n" + assert cache.object(loose).exists(), "collect removed an object while the lock was held" + finally: + os.close(held) + + m.image_cache_collect() + assert not cache.object(loose).exists(), "collect did nothing once the lock was free" + m.image_cache_record(2, {"lanes/LANES.md": d2}) + assert cache.head_file.read_bytes() == b"2\n" + + # A FIFO AT THE LOCK'S NAME: BUSY, AT ONCE, WHETHER OR NOT IT BLOCKS ITS OPEN. + os.replace(str(cache.lock), str(cache.root / "lock.aside")) + os.mkfifo(str(cache.lock), 0o600) + loose = m.image_cache_put(b"named by no manifest, again\n") + cache.age(cache.object(loose)) + worker = threading.Thread(target=lambda: (m.image_cache_record(3, {"lanes/LANES.md": d1}), + m.image_cache_collect()), daemon=True) + worker.start() + worker.join(10) + assert not worker.is_alive(), "record or collect blocked on a FIFO at the lock's name" + assert not (cache.seq / "3").exists() and cache.head_file.read_bytes() == b"2\n" + assert cache.object(loose).exists(), "collect ran through a FIFO lock" + assert stat.S_ISFIFO(os.lstat(cache.lock).st_mode) + + +def test_the_image_cache_follows_no_symlink_at_its_lock_or_its_head(tmp_path, monkeypatch): + """Lane 1's follow-up to T302's fix round (lane 3's delta check, #165 + 6755954683, doubts 1 and 2): the lock is opened with `O_NOFOLLOW`, so a + symlink planted at `register-images/lock` is a skip, its target neither + changed nor created; and `record` treats a symlinked `head` as a missing + one, so it replaces the link with a regular `head` and leaves the link's + target alone. Until that commit lands, this case fails by its own + assertion, where the rest of the image cache's cases pass.""" + cache = image_cache_module(tmp_path, monkeypatch) + m = cache.m + d1 = m.image_cache_put(b"image 1\n") + m.image_cache_record(1, {"lanes/LANES.md": d1}) + + # A SYMLINKED HEAD: RECORD REPLACES THE LINK, NOT ITS TARGET. + target = tmp_path / "elsewhere-head" + target.write_bytes(b"1\n") + cache.head_file.unlink() + cache.head_file.symlink_to(target) + m.image_cache_record(2, {"lanes/LANES.md": d1}) + assert target.read_bytes() == b"1\n", "record wrote through a symlinked head" + assert not cache.head_file.is_symlink() and cache.head_file.read_bytes() == b"2\n", ( + "record left a symlinked head in place (lane 3's 6755954683, doubt 2's fix: ELOOP as " + "FileNotFoundError), so image_cache_head() stays unreadable") + + # A SYMLINKED LOCK, DANGLING: A SKIP, AND ITS TARGET IS NOT CREATED. + planted = tmp_path / "elsewhere" / "lock-target" + planted.parent.mkdir() + os.replace(str(cache.lock), str(cache.root / "lock.aside")) + cache.lock.symlink_to(planted) + m.image_cache_record(3, {"lanes/LANES.md": d1}) + assert not planted.exists(), ( + "the lock's open followed a symlink and created its target (lane 3's 6755954683, " + "doubt 1: O_NOFOLLOW on the lock)") + assert not (cache.seq / "3").exists(), "record ran under a symlinked lock" + + +# ======================================== the render read's `start` (T301's cache-forward) +# +# LANE 1'S CACHE-FORWARD COMMIT (T301's `e4d28a505af8`, tag `l1-007-T301-cf1`; +# #165 6767347563; the cache signature lane 3 accepted in 6755051914, B10 +# tasks:996-1003). B10 gives T210 "one case with `start`, so that both arms are +# covered", and lane 1's doubt 1 says what it expects: with `start`, +# `register_render_read` returns THE IMAGES, `{path: bytes}`, and not the rows; +# without it, still `(journal, edits, files)`. T210f (line W4b, wave 6) is this +# case. It needs no engine: the read runs in process against a stand-in store +# that answers each SELECT the code sends from an in-memory sqlite database, as +# lane 1's own hand checks do ("sqlite stood in for PostgreSQL"), and fails +# until the cache-forward commit lands, by the assertion `render_read_module` +# makes. +# +# What the case reads from lane 1's code rather than from a contract, since +# section 3.6 fixes only the CLI: `register_render_read(store, k, *, start=None, +# row="render")`, `register_render_queries(k, *, since=None)`, +# `register_cache_state(images)`, `register_images(journal, edits, files, *, +# start=None)`, `RenderRefused`, and the store's one method the read calls, +# `_query_many(queries, snapshot=True, row=...)`, whose answer is a list of +# result sets of rows of text fields (`t`/`f` for a boolean, None for NULL). + +#: The paths of the journal below: the render set's files, and `lanes/STORE`, +#: which is journaled and is never an image. +LANES_MD, ALPHA_LOG, BETA_LOG, GAMMA_LOG = ("lanes/LANES.md", "lanes/log/alpha.md", + "lanes/log/beta.md", "lanes/log/gamma.md") +ALIASES_TSV, ARCHIVE_MD = "lanes/aliases.tsv", "lanes/archive/old.md" +#: The files whose row says `final_newline` false: an image with no last LF. +NO_LAST_LF = frozenset({ALIASES_TSV}) + +#: AT-1's journal in miniature, as `commit_write` leaves it (design section 1.3.1): an +#: import, then writes. An entry is `(kind, edits, no_last_lf)`; an edit is +#: `("create", path)`, `("append", path, text)`, `("replace", path, n, text)`, +#: `("delete", path, n)` or `("remove", path)`. Seq 2 touches `lanes/STORE`; +#: seq 3 replaces a line, seq 4 deletes one, seq 5 removes a file, and +#: `lanes/archive/old.md` is never touched after the import. +RENDER_JOURNAL = [ + ("import", [("create", LANES_MD), ("append", LANES_MD, "# LANES"), + ("append", LANES_MD, "| alpha | held |"), + ("create", ALPHA_LOG), ("append", ALPHA_LOG, "alpha 1"), + ("append", ALPHA_LOG, f"alpha 2 {EM} two"), + ("create", ALIASES_TSV), ("append", ALIASES_TSV, "old\talpha"), + ("create", ARCHIVE_MD), ("append", ARCHIVE_MD, "archived")], NO_LAST_LF), + ("write", [("append", LANES_MD, "| beta | free |")], ()), + ("write", [("append", ALPHA_LOG, "alpha 3"), ("create", BETA_LOG), + ("append", BETA_LOG, "beta 1"), ("create", STORE_PATH)], ()), + ("write", [("replace", ALPHA_LOG, 1, "alpha 1 (edited)")], ()), + ("write", [("delete", ALPHA_LOG, 2), ("append", ALIASES_TSV, "new\tbeta")], NO_LAST_LF), + ("write", [("remove", BETA_LOG), ("append", LANES_MD, "| gamma | free |")], ()), +] +#: The same register after a re-import at seq 4 (before a confirmed cutover): +#: the root is replaced, so alpha and beta are gone and the seqs 0 to 3 of the +#: old root are history a cache may still hold. +RENDER_REIMPORT = RENDER_JOURNAL[:4] + [ + ("import", [("create", LANES_MD), ("append", LANES_MD, "# LANES (re-imported)"), + ("create", GAMMA_LOG), ("append", GAMMA_LOG, "gamma 1"), + ("create", ALIASES_TSV), ("append", ALIASES_TSV, "old\tgamma")], NO_LAST_LF), + ("write", [("append", GAMMA_LOG, "gamma 2")], ()), +] + + +def _render_image_bytes(lines: list, final_newline: bool) -> bytes: + """One file's bytes as `render_file` builds them (design Y:1297), spelled + out here so that the case's oracle is not the code's own function.""" + return ("\n".join(lines) + ("\n" if final_newline and lines else "")).encode("utf-8") + + +class RenderJournal: + """`entries` replayed by this test's own model, which gives what the + register would hold: the rows of `journal`, `journal_edits` and + `journal_files`, and for each seq the render set's images and its state, + `{path: (lines, final_newline)}`, as the cache's read-back should give.""" + + def __init__(self, entries: list): + self.rows = {"journal": [], "journal_edits": [], "journal_files": []} + self.images_at, self.state_at = [], [] + state: dict = {} + for seq, (kind, edits, no_last_lf) in enumerate(entries): + self.rows["journal"].append((seq, kind)) + if kind == "import": + state.clear() + touched = [] + for ordinal, edit in enumerate(edits, 1): + op, path = edit[0], edit[1] + if path not in touched: + touched.append(path) + lines = state[path][0] if path in state else None + row = (None, None, None) + if op == "create": + state[path] = [[], True] + elif op == "append": + row = (len(lines) + 1, None, edit[2]) + lines.append(edit[2]) + elif op == "replace": + row = (edit[2], _digest(lines[edit[2] - 1].encode("utf-8")), edit[3]) + lines[edit[2] - 1] = edit[3] + elif op == "delete": + row = (edit[2], _digest(lines[edit[2] - 1].encode("utf-8")), None) + del lines[edit[2] - 1] + else: + del state[path] + self.rows["journal_edits"].append((seq, ordinal, op, path, *row, None)) + for path in touched: + if path not in state: + self.rows["journal_files"].append((seq, path, "f", None, None)) + continue + if path in no_last_lf: + state[path][1] = False + lines, final_newline = state[path] + self.rows["journal_files"].append( + (seq, path, "t", _digest(_render_image_bytes(lines, final_newline)), + "t" if final_newline else "f")) + self.images_at.append({p: _render_image_bytes(*v) for p, v in state.items() + if RENDER_SET.match(p)}) + self.state_at.append({p: (list(v[0]), v[1]) for p, v in state.items() + if RENDER_SET.match(p)}) + self.last = len(entries) - 1 + + +class RenderRegister: + """The stand-in store: `register_render_read` calls `store._query_many( + queries, snapshot=True, row=...)`, and this answers each SELECT it is + given from an in-memory sqlite database holding `journal`'s rows. It + records each call in `requests`, as `(queries, snapshot, row)`. With + `raises` set, a call records itself and raises that, as a dead connection + does. Line R's `_register_render_rows` also passes `first_request_at=` + (`lanes-index:2434-2435` at `refs/l1/V-round4`), the bound's clock for + `register snapshot`'s second request (#165 6780364102), which the stand-in + takes and does not use.""" + + DDL = ( + "CREATE TABLE schema_version (id INTEGER PRIMARY KEY, version INTEGER, " + "writers_from INTEGER, readers_from INTEGER)", + "CREATE TABLE register_head (id INTEGER PRIMARY KEY, seq INTEGER)", + "CREATE TABLE journal (seq INTEGER PRIMARY KEY, kind TEXT)", + "CREATE TABLE journal_edits (seq INTEGER, ord INTEGER, op TEXT, path TEXT, " + "line_no INTEGER, old_sha256 TEXT, new_text TEXT, to_path TEXT)", + "CREATE TABLE journal_files (seq INTEGER, path TEXT, present TEXT, sha256 TEXT, " + "final_newline TEXT)", + ) + + def __init__(self, module, journal: RenderJournal): + import sqlite3 + self.db = sqlite3.connect(":memory:") + for statement in self.DDL: + self.db.execute(statement) + self.db.execute("INSERT INTO schema_version VALUES (1, ?, 1, 1)", + (module.REGISTER_SCHEMA_VERSION,)) + self.db.execute("INSERT INTO register_head VALUES (1, ?)", (journal.last,)) + for table, rows in journal.rows.items(): + self.db.executemany(f"INSERT INTO {table} VALUES ({', '.join('?' * len(rows[0]))})", + rows) + self.requests: list = [] + self.raises = None + + def _query_many(self, queries, snapshot=False, *, row=None, timer=None, + first_request_at=None): + self.requests.append((list(queries), snapshot, row)) + if self.raises is not None: + raise self.raises + return [[[None if value is None else str(value) for value in fetched] + for fetched in self.db.execute(query).fetchall()] for query in queries] + + +def render_read_module(): + """`lanes-index` as a module, under its own name so nothing else in the run + shares it. Asserts lane 1's cache-forward commit is there: the case's red + until `register_render_read`, `register_images` and `register_render_queries` + take their `start` and `since`, and `register_cache_state` reads images + back (#165 6755040818, 6767347563).""" + from importlib.machinery import SourceFileLoader + import importlib.util + import inspect + loader = SourceFileLoader(f"lanes_index_render_read_{uuid.uuid4().hex}", str(LANES_INDEX)) + spec = importlib.util.spec_from_loader(loader.name, loader) + module = importlib.util.module_from_spec(spec) + loader.exec_module(module) + missing = [name for name in ("register_render_read", "register_render_queries", + "register_images", "register_cache_state", "RenderRefused", + "PsqlFailed", "REGISTER_SCHEMA_VERSION") + if not hasattr(module, name)] + assert not missing, ( + f"{LANES_INDEX} has no render read, {missing} missing: lane 1's T301, with its " + f"cache-forward commit (`e4d28a505af8`, #165 6767347563), has not landed") + wanting = [f"{name}'s {keyword}" for name, keyword in ( + ("register_render_read", "start"), ("register_images", "start"), + ("register_render_queries", "since")) + if keyword not in inspect.signature(getattr(module, name)).parameters] + assert not wanting, ( + f"{LANES_INDEX} takes no {wanting}: lane 1's T301 cache-forward commit " + f"(`e4d28a505af8`, #165 6767347563) has not landed") + return module + + +def test_the_render_read_with_start_returns_the_images_and_a_bad_start_costs_one_full_read(): + """T210's case with `start` (B10 tasks:1003; lane 1, #165 6767347563, doubt + 1: "**Lane 2:** T210's `start` case should expect images"). Both arms of + `register_render_read`, against a register built by this test's own model + of `commit_write`: + + WITHOUT `start` it returns `(journal, edits, files)`, the rows from the + latest import to `k`, which `register_images` builds into the images, in + one request. + + WITH `start=(c, state)`, `state` being `register_cache_state` of the + images at `c`, it returns THE IMAGES AT `k`, a `dict` of `bytes` and not + the rows, equal to the model's for every `c` from 0 to `k`: in ONE request, + which reads only the entries after `c` (`register_render_queries(k, + since=c)`), and `start` is left as it was. + + A START IT CANNOT TRUST IS A MISS, NOT AN ERROR, AND THE COUNT SAYS + WHICH KIND (lane 1, #165 6769176187, for the cache-forward commit + `e4d28a5`): a `start` of another form, or a `c` above `k`, is refused + before any request and costs exactly ONE, the full read; a cached image + of an untouched path that is wrong (a cache from a reused seq), a cached + image that an edit does not apply on, and a path the cache lacks are + found after the read since `c` and cost exactly TWO, that read and then + the full one. Each returns the right images, the full read last. An + import among entries `c+1` to `k` sets `start` aside, so even a wrong + cache is no miss there, one request. Only the full read's failure ends in + `RenderRefused`, after the two requests; a dead connection (`PsqlFailed`) + is raised as it is, after one, and is never tried twice. And + `register_cache_state` misses (None) on an image that is empty, is not + UTF-8 or is not bytes, so an estate with an empty file in its render set + always replays in full.""" + pytest.importorskip("sqlite3") + import copy + m = render_read_module() + journal = RenderJournal(RENDER_JOURNAL) + register = RenderRegister(m, journal) + last = journal.last + + def read(k, **kwargs): + """One call and the requests it made. A `RenderRefused` is no answer, and + fails the expectation that asked.""" + before = len(register.requests) + try: + answer = m.register_render_read(register, k, **kwargs) + except m.RenderRefused as refusal: + raise AssertionError(f"read(k={k}) ended in RenderRefused: {refusal}") from None + return answer, register.requests[before:] + + def kinds(k, sent): + """The requests as `full` or `since`, for a failure's message.""" + return ["full" if queries == m.register_render_queries(k) else "since" + for queries, _snapshot, _row in sent] + + def full(k, row="render"): + return (m.register_render_queries(k), True, row) + + def since(k, c, row="render"): + return (m.register_render_queries(k, since=c), True, row) + + # THE READ WITHOUT `start` GIVES THE ROWS, IN ONE REQUEST, AND THE ROWS BUILD THE IMAGES. + for k in range(last + 1): + rows, sent = read(k) + assert isinstance(rows, tuple) and len(rows) == 3, ( + f"read(k={k}) without start returned {type(rows).__name__}, not " + f"(journal, edits, files)") + assert sent == [full(k)], f"read({k}) sent {kinds(k, sent)}" + assert rows[0][0] == (0, "import") and rows[0][-1][0] == k, rows[0] + assert m.register_images(*rows) == journal.images_at[k], f"the images at seq {k}" + + # THE CACHE'S READ-BACK: THE STATE THE MODEL HOLDS, FOR EVERY SEQ. + for c in range(last + 1): + assert m.register_cache_state(journal.images_at[c]) == journal.state_at[c], ( + f"register_cache_state of the images at seq {c}") + + # WITH `start`: THE IMAGES AT `k`, FOR EVERY `c` UP TO `k`, IN ONE REQUEST SINCE `c`. + for c in range(last + 1): + start = (c, m.register_cache_state(journal.images_at[c])) + frozen = copy.deepcopy(start) + for k in range(c, last + 1): + images, sent = read(k, start=start) + assert isinstance(images, dict) and not isinstance(images, tuple), ( + f"read(k={k}, start at {c}) returned {type(images).__name__}: with `start` " + f"it returns the images, {{path: bytes}}, and not the rows") + assert all(isinstance(p, str) and isinstance(b, bytes) for p, b in images.items()) + assert images == journal.images_at[k], f"the images at seq {k} from a cache at {c}" + assert sent == [since(k, c)], ( + f"read(k={k}, start at {c}) sent {kinds(k, sent)}, not one request since {c}") + assert start == frozen, "register_render_read changed `start`" + + # A START IT CANNOT TRUST IS A MISS: THE RIGHT IMAGES, AND A FULL READ LAST. + k, c = last, 2 + good = dict(journal.images_at[c]) + wrong_untouched = {**good, ARCHIVE_MD: b"another root's archive\n"} + wrong_edit_base = {**good, ALPHA_LOG: b"not alpha's first line\nalpha 2\nalpha 3\n"} + lacks_untouched = {p: b for p, b in good.items() if p != ARCHIVE_MD} + for what, images in (("a wrong image of an untouched path (a cache from a reused seq)", + wrong_untouched), + ("an image the seq-3 replace does not apply on", wrong_edit_base), + ("a cache that lacks an untouched path", lacks_untouched)): + state = m.register_cache_state(images) + assert state is not None, f"register_cache_state refused {what}" + answer, sent = read(k, start=(c, state)) + assert answer == journal.images_at[k], f"the images after {what}" + assert sent == [since(k, c), full(k)], ( + f"{what}: a failed proof or edit costs exactly two requests, the first since " + f"seq {c} and the second the full read; sent {kinds(k, sent)}") + ok_state = m.register_cache_state(good) + for what, start, at in (("a `c` above `k`", (5, m.register_cache_state(journal.images_at[5])), + 3), + ("a `c` that is not an int", ("2", ok_state), last), + ("a `c` that is a bool", (True, ok_state), last), + ("a state that is not a dict", (2, "not a state"), last), + ("a state of the wrong value form", (2, {LANES_MD: "text"}), last), + ("a start of one item", (2,), last), + ("a start that is not a pair", [], last)): + answer, sent = read(at, start=start) + assert isinstance(answer, dict) and answer == journal.images_at[at], ( + f"the images after {what}") + assert sent == [full(at)], ( + f"{what}: a start of another form, or a `c` above `k`, is refused before any " + f"request and costs exactly one, the full read; sent {kinds(at, sent)}") + + # AN IMPORT AMONG ENTRIES `c+1` TO `k` SETS `start` ASIDE: EVEN A WRONG CACHE IS NO MISS. + again = RenderJournal(RENDER_REIMPORT) + reimport = RenderRegister(m, again) + old_root = m.register_cache_state(journal.images_at[2]) + for caches, cached in (("the old root's images", old_root), + ("images the seq-3 replace does not apply on, which is never " + "applied", m.register_cache_state(wrong_edit_base))): + for c, k in ((2, 5), (2, 4), (3, 5)): + before = len(reimport.requests) + answer = m.register_render_read(reimport, k, start=(c, cached)) + assert answer == again.images_at[k], f"the images at seq {k} past the re-import" + assert reimport.requests[before:] == [(m.register_render_queries(k, since=c), True, + "render")], ( + f"a start at {c}, {caches}, was set aside by the re-import at 4, and cost " + f"one request") + # A CACHE AT OR AFTER THE IMPORT IS BROUGHT FORWARD AS ANY IS. + new_root = m.register_cache_state(again.images_at[4]) + before = len(reimport.requests) + assert m.register_render_read(reimport, 5, start=(4, new_root)) == again.images_at[5] + assert reimport.requests[before:] == [(m.register_render_queries(5, since=4), True, "render")] + + # ONLY THE FULL READ'S FAILURE ENDS IN `RenderRefused`: k=3 is before the latest import. + before = len(reimport.requests) + with pytest.raises(m.RenderRefused): + m.register_render_read(reimport, 3, start=(2, old_root)) + assert reimport.requests[before:] == [ + (m.register_render_queries(3, since=2), True, "render"), + (m.register_render_queries(3), True, "render")], ( + "a refused k, with a start, is two requests and then the refusal") + + # A DEAD CONNECTION IS RAISED AS IT IS, AFTER ONE REQUEST, AND NEVER TRIED TWICE. + register.raises = m.PsqlFailed("unreachable", "the database did not answer") + before = len(register.requests) + with pytest.raises(m.PsqlFailed): + m.register_render_read(register, last, start=(2, ok_state)) + assert register.requests[before:] == [since(last, 2)], "a dead connection was tried twice" + register.raises = None + + # THE CACHE'S READ-BACK MISSES ON AN IMAGE IT CANNOT READ BACK: THE ESTATE REPLAYS IN FULL. + images = journal.images_at[last] + assert m.register_cache_state(images) == journal.state_at[last] + for what, bad in (("an empty image", {**images, "lanes/log/empty.md": b""}), + ("an image that is not UTF-8", {**images, ALPHA_LOG: b"\xff\xfe\n"}), + ("an image that is not bytes", {**images, ALPHA_LOG: "alpha\n"}), + ("images that are not a dict", list(images.items()))): + assert m.register_cache_state(bad) is None, f"register_cache_state took {what}" + + +# ============================================================ phase W: T240 +# +# TEST 1'S PHASE-W PART (lane 2's T240; AT-1, the test plan's lines 537-645; +# FR-018, FR-027, FR-042, FR-059): each of S1's writes through `lanes-edit.sh` +# on a `mode=primary` workstation, from T203's flipped copy (`RENDER_GIT_HALF = +# True`, test 14's second state) with `lanes-edit.sh` beside it, over test 1's +# imported register (`import_to_primary`, AT-LR006's route), then the pure +# renderer writing a scratch mirror, `render --images --at <seq> --out <dir>`. +# +# THE VERBS (`W_VERBS`) are the thirteen of P192-196, `log` once per verb of +# its grammar: the fourteen arms of `lanes-edit.sh`'s write dispatch but +# `commit`, whose direct write is 2 (D10), with the argument lists the writes +# module's `WRITE_VERBS` gives them (T241), and `log` once for each verb of +# `VERB_LIST` that `log` writes by hand. That is twelve: `log` refuses CLAIMED, +# TAKEOVER, RELEASED, CLAIM-LOST, HANDOFF-REQUESTED and RENAMED, which their own +# verbs write. The lists are copied here, never imported: the writes module +# imports this one. Every verb runs from the same starting state, C with the +# verb's prep (`W_PREPS`), and each case gets a database of its own. Each +# argument list exits 0 and makes one commit in files mode on line R's +# V-round4 (line W1-12's probe). +# +# THE TWIN (AT-1, "Part W adds an FM twin"): a files-mode clone of W's origin +# at C, with its own origin and its own `$HOME`, makes the same verb. The +# mirror's render set equals the twin's origin's, path set and bytes, with +# every UTC masked in both, in a line or in a path (`migrate-state-cells`' +# archive is named by its UTC): open point 4 leaves the mask in place until a +# test can fix the database's clock. The journal entry's message is the twin's +# commit message, but `rename-lane`'s, which on primary is the message the +# design names under Q13(a) (lane 3's ruling (A), #165 6859179515). +# +# GB SECTION 4.3'S CASES (R29), each an assertion of a named test: D12, the +# fake `git`'s log holding no `fetch` on primary that the verb itself makes, +# for any verb, the renderer the write forks left out by the process above +# the call (lane 3, #165 6859073786), in the mirror case; `rename-lane`'s +# `register seq` and its tail under Q13(a), the +# transaction first and then the move, in +# `test_rename_lane_commits_the_transaction_then_a_rerun_makes_only_the_move`; +# and `start-record` in both modes, its twin run once more under +# `LANES_ROUTE_WRITES=1`, as the twin case's `[start-record]`. +# +# THE MOVE ON PRIMARY (lane 3's batch c, #165 6807881675, Q55 and Q56, B15 +# texts (2) to (4) for F13d:502, :497 and :496): `rename-lane` renames one +# regular file inside its own folder and commits those two paths alone, so a +# folder's tracked bytecode never rides it (#162); a handoff whose own path has +# a cache, bytecode or environment part refuses 2 before the seam (Y:5138; +# REV422c N1). The rerun is `LANES_LANE=<new> lanes-edit.sh rename-lane <old> +# <new>` (batch c Q71 and Q74, #165 6808141050). +# +# THEY FAIL UNTIL lane 4's L4-B4 (T414's seam), L4-B8 (T422, `rename-lane`'s +# tail and its seq) and L4-B13 (T415's author, T416's fork, `<c>` and the +# nudge) land, each by its own assertion here: line R's `lanes-edit.sh` writes +# the files whatever `mode=` says. `[start-record]` fails until L4-B9 (T427) +# too, and the two `rename-lane` cases B15 adds until lane 4's T422. + +#: The lanes these writes are for, each with its own checkout `<c>`, +#: `<W>-lanes/<lane>` (B14 tasks:1142's T415 bullets; R17): repoA-1 and +#: repoA-2, as `LANES_LANE` or a verb's `<lane>`, and repoA-3, `add-row`'s new +#: row and `rename-lane`'s new name (the writes module's `WRITE_LANES`). +W_LANES = ("repoA-1", "repoA-2", "repoA-3") + +#: The writer's password in the 0600 `register_passfile=` (AT-1's fixture), +#: which the cluster's trust never asks for and no output may carry. +W_SECRET = "t240-never-printed-5d2a" + + +def _w_with_row(lane: str, sid: str, cell: str, log: str = None) -> dict: + """A prep: test 1's SEED with one more row in `LANES.md`'s table, after + repoA-2's, and the lane's log (its header, then `log`'s lines). Copied + from the writes module's `_with_row`.""" + lanes = SEED["lanes/LANES.md"] + anchor = next(line for line in lanes.split("\n") if line.startswith("| `repoA-2` |")) + row = (f"| `{lane}` | harness `{sid}` | Eagle / test / brett | 2026-09-01T00:00Z | none " + f"| handoffs/{lane}.md | {cell} |") + header = f"# lane {lane} {EM} object log (lane-collision-protocol Amendment 7)\n" + return {"lanes/LANES.md": lanes.replace(anchor + "\n", anchor + "\n" + row + "\n", 1), + f"lanes/log/{lane}.md": header + (log or "")} + + +def _w_with_handoffs(handoffs: dict, extra: dict = None) -> dict: + """A prep: test 1's SEED with each lane of `handoffs`, {lane: (path, + bytes)}, naming the handoff at `path` in its row's handoff column, and that + handoff committed there; and `extra`, {path: bytes}, committed beside + them.""" + lanes = SEED["lanes/LANES.md"] + files: dict = {} + for lane, (path, data) in handoffs.items(): + old = next(line for line in lanes.split("\n") if line.startswith(f"| `{lane}` |")) + assert old.count(f"| handoffs/{lane}.md |") == 1, old + lanes = lanes.replace(old, old.replace(f"| handoffs/{lane}.md |", f"| {path} |"), 1) + files[path] = data + files["lanes/LANES.md"] = lanes + files.update(extra or {}) + return files + + +#: The starting state three verbs need, or they refuse for want of work (2), +#: as the writes module's `PREPS` gives it: `archive-rows <repo>` moves a +#: repository's RETIRED rows, `retire-rows` takes a dormant row, and +#: `migrate-state-cells` migrates a diary cell. +W_PREPS = { + "archive-rows": _w_with_row( + "repoZ-2", "eeeeeeee-0002-4000-8000-00000000e002", + f"RETIRED {DOT} 2026-09-03T00:00:00Z {DOT} retired", + f"RETIRED {EM} lane repoZ-2, session eeeeeeee-0002-4000-8000-00000000e002@Eagle, " + f"2026-09-03T00:00:00Z, lane:repoZ-2 {EM} retired\n"), + "retire-rows": _w_with_row("repoA-4", "aaaaaaaa-0005-4000-8000-00000000a005", + f"MIGRATED {DOT} 2026-09-01T00:00:00Z {DOT} migrated"), + "migrate-state-cells": _w_with_row("repoA-5", "aaaaaaaa-0006-4000-8000-00000000a006", + f"parked 2026-09-01 {DOT} picked up 2026-09-02"), +} + +#: The session `request-handoff --force` writes its `PAUSED` for, as the +#: writes module's `SID_REQUESTER`. +W_SID_REQUESTER = "bbbbbbbb-0007-4000-8000-00000000b007" + +#: A lane's binding payload, for `log STARTED` and `log RESUMED`. +W_BINDING = "home opensoft/repoA; dir /work/repoA2" + +#: S1's writes but `commit`, `log` once per verb of its grammar: {id: (its +#: arguments, the lane it writes as)}. The forms are `lanes-edit.sh`'s usage +#: lines at a2073eae; `log`'s are its arm's, at line R's V-round4. +#: THE LANE IT WRITES AS is the lane the write is for, D12's writing lane, +#: whose checkout `<c>` T415's `pw_checkout` takes through `write_lane_of` +#: (lane 3, #165 6869860086; lane 4, #165 6869806372): for `add-row` the new +#: row's, repoA-3, and for `request-handoff` its target's, repoA-1, as +#: `lane-start` and `lane` set `LANES_LANE` for those two verbs. For every +#: other verb the two lanes are one already. +W_VERBS = { + "add-row": (["add-row", f"| `repoA-3` | harness `aaaaaaaa-0004-4000-8000-00000000a004` | " + f"Eagle / test / brett | 2026-11-10T00:00Z | none | handoffs/repoA-3.md | " + f"LIVE {DOT} 2026-11-10T00:00:00Z {DOT} test 1 |"], "repoA-3"), + "append-line": (["append-line", f"HOLD {EM} lane repoA-2 ({WS}), window w, " + f"2026-11-10T00:00:00Z: opensoft/repoB main {TIP} for test 1"], "repoA-2"), + "append-session-id": (["append-session-id", "repoA-2", f"harness `{SID_A2}`", + " (test 1)"], "repoA-2"), + "archive-rows": (["archive-rows", "repoZ", "--yes"], "repoA-2"), + "claim": (["claim", "opensoft/repoA#9", "--no-github"], "repoA-2"), + "log-closed": (["log", "CLOSED", "opensoft/repoA#9", "closed for test 1"], "repoA-2"), + "log-opened": (["log", "OPENED", "opensoft/repoA#8", "test 1's PR"], "repoA-2"), + "log-landing": (["log", "LANDING", "opensoft/repoA#8", "test 1"], "repoA-2"), + "log-landed": (["log", "LANDED", "opensoft/repoA#8", ARROW, "abc1234"], "repoA-2"), + "log-withdrawn": (["log", "WITHDRAWN", "opensoft/repoA#8", "test 1"], "repoA-2"), + "log-started": (["log", "STARTED", "lane:repoA-2", ARROW, W_BINDING], "repoA-2"), + "log-paused": (["log", "PAUSED", "lane:repoA-1", "parked for test 1"], "repoA-1"), + "log-resumed": (["log", "RESUMED", "lane:repoA-2", ARROW, W_BINDING], "repoA-2"), + "log-ended": (["log", "ENDED", "lane:repoA-1", "ended for test 1"], "repoA-1"), + "log-retired": (["log", "RETIRED", "lane:repoA-1", "retired for test 1"], "repoA-1"), + "log-noted": (["log", "NOTED", "lane:repoA-2", "test 1's note"], "repoA-2"), + "log-ruled": (["log", "RULED", "lane:repoA-2", ARROW, "opensoft/repoA#9", + "the words, verbatim"], "repoA-2"), + "migrate-state-cells": (["migrate-state-cells", "--yes"], "repoA-2"), + "release": (["release", "opensoft/repoA#7", "test 1", "--no-github"], "repoA-1"), + "rename-lane": (["rename-lane", "repoA-2", "repoA-3", "test 1", "--no-github"], "repoA-2"), + "replace-in-row": (["replace-in-row", "repoA-2", "parked", "parked for test 1"], "repoA-2"), + "request-handoff": (["request-handoff", "repoA-1", "--force", "test 1", "--session", + W_SID_REQUESTER], "repoA-1"), + "retire-rows": (["retire-rows", "repoA-4", "--reason", "test 1"], "repoA-2"), + "set-row-state": (["set-row-state", "repoA-2", f"PAUSED {DOT} test 1"], "repoA-2"), +} + +#: The twin's verbs: `W_VERBS`, and GB section 4.3's `start-record`, lane 4's +#: T427 verb (L4-B9), as a resume of repoA-2, which `LANES_SESSION` names by +#: its transcript uuid and `LANES_LANE` by the row's own spelling (B14 +#: tasks:1325-1333): {id: (its arguments, the lane, what the run adds to the +#: environment)}. +TWIN_VERBS = {**{verb: (argv, lane, {}) for verb, (argv, lane) in W_VERBS.items()}, + "start-record": (["start-record", "repoA-2", "RESUMED", "--state", + f"LIVE {DOT} resumed for test 1", "--log", "lane:repoA-2", + ARROW, W_BINDING], "repoA-2", {"LANES_SESSION": SID_A2})} + + +def _logging_git(path: Path, log: Path, real: str = None) -> None: + """A `git` at `path` that appends each call to `log`, then runs the real + `git` (or `real`) with its arguments (D12's oracle: GB section 4.3, "the + fake `git`'s log"). A call is one record, written by one `printf`, so a + forked renderer's calls and the verb's never interleave: the pid above + the call; where any argument is `fetch` or `pull`, that process's command + line, as open point 8's wrapper reads it (`ps -ww -o command=`; TP:8799-8800, + test 5's wrapper in `test_sql_register_renderer_git.py`), and the + directory the call runs in; then its arguments. Each field is ended by a + US (0x1f) and the record by an RS (0x1e) and a LF.""" + real = real or shutil.which("git") + assert real, "no git on PATH" + path.write_text("#!/bin/sh\n" + "u='\x1f' above=$PPID command= here=\n" + "for a in \"$@\"; do case $a in fetch|pull)\n" + " command=$(ps -ww -o command= -p \"$above\" 2>/dev/null" + " | tr '\\n\\036\\037' ' ')\n" + " here=$PWD; break ;; esac; done\n" + "record=\"$above$u$command$u$here$u\"\n" + "for a in \"$@\"; do record=\"$record$a$u\"; done\n" + f"printf '%s\\036\\n' \"$record\" >> {shlex.quote(str(log))}\n" + f"exec {shlex.quote(real)} \"$@\"\n", encoding="utf-8") + path.chmod(0o755) + + +#: `git`'s own options that take the next argument as their value. +_GIT_VALUE_OPTIONS = frozenset({"-C", "-c", "--git-dir", "--work-tree", "--namespace", + "--exec-path", "--super-prefix", "--config-env"}) + + +def _render_checkout(command: str): + """The `<c>` of a `lanes-index render --checkout <c>` command line, the + renderer a write forks (`pw_render_fork`, T416), or None for any other + process.""" + words = command.split() + for i in range(len(words) - 3): + if (words[i].rsplit("/", 1)[-1] == "lanes-index" + and words[i + 1:i + 3] == ["render", "--checkout"]): + return words[i + 3] + return None + + +def _git_calls(log: Path) -> list: + """`_logging_git`'s log: each call as a dict, its subcommand (`sub`, the + first argument that is not one of `git`'s own options or such an + option's value), its arguments (`args`), the pid above it (`above`), and, + for a `fetch` or a `pull`, the `<c>` of the `lanes-index render + --checkout` process above it, or None (`render`), and the real path of + the repository it ran in, its directory moved by each `-C` (`where`).""" + if not log.exists(): + return [] + calls = [] + for record in log.read_bytes().decode("utf-8", "replace").split("\x1e\n"): + if not record: + continue + above, command, here, *args = record.split("\x1f")[:-1] + i = 0 + where = here + while i < len(args) and args[i].startswith("-"): + if args[i] == "-C" and i + 1 < len(args): + where = os.path.join(where, args[i + 1]) + i += 2 if args[i] in _GIT_VALUE_OPTIONS else 1 + calls.append({"sub": args[i] if i < len(args) else "", "args": args, "above": above, + "render": _render_checkout(command), + "where": os.path.realpath(where) if here else ""}) + return calls + + +def _d12_control(root: Path, checkout: str) -> None: + """D12's control: the render pass's own fetch argv (`lanes-index`'s + `render_pass`, step 1), in `checkout`, logged by `_logging_git` with + `true` for `git`, so nothing is fetched. Once from this test, which is + no renderer: kept, as a fetch of the verb's would be. Once from a + stand-in whose command line is `lanes-index render --checkout + <checkout>`: left out, with its `<c>`. The same argv both times, so the + two are told apart by the process above the call alone.""" + root.mkdir(parents=True, exist_ok=True) + log, shim, stand_in = root / "git-calls.log", root / "git", root / "lanes-index" + _logging_git(shim, log, real=shutil.which("true")) + stand_in.write_text("#!/bin/sh\nshift 4\n\"$D12_SHIM\" \"$@\"\nexit $?\n", + encoding="utf-8") + stand_in.chmod(0o755) + argv = ["-C", checkout, "-c", "gc.auto=0", "-c", "maintenance.auto=false", "fetch", + "--no-tags", "--no-write-fetch-head", "--no-recurse-submodules", "-q", "origin", + "+refs/heads/main:refs/remotes/origin/main"] + env = dict(os.environ, D12_SHIM=str(shim)) + for command in ([str(shim), *argv], + [str(stand_in), "render", "--checkout", checkout, "--", *argv]): + done = subprocess.run(command, cwd=str(root), env=env, capture_output=True, + timeout=60, check=False) + assert done.returncode == 0, f"the D12 control's {command[0]}: {done.stderr!r}" + got = [(call["sub"], call["args"], call["render"], call["where"]) + for call in _git_calls(log)] + assert got == [("fetch", argv, None, checkout), ("fetch", argv, checkout, checkout)], ( + f"the D12 control: the renderer's fetch argv run by no renderer must be kept, " + f"and under a `lanes-index render --checkout` left out: {got}") + + +def _git_bytes(cwd: Path, env: dict, *args: str) -> bytes: + proc = subprocess.run(["git", *args], cwd=str(cwd), capture_output=True, env=env, + check=False) + assert proc.returncode == 0, f"git {' '.join(args)} in {cwd}: {proc.stderr!r}" + return proc.stdout + + +def _origin_render_set(origin: Path, env: dict, ref: str = "main") -> dict: + """The render set on a bare repository's `ref`, read by object: {path: + bytes}.""" + names = _git_bytes(origin, env, "ls-tree", "-r", "-z", "--name-only", ref, "--", "lanes") + return {name: _git_bytes(origin, env, "cat-file", "blob", f"{ref}:{name}") + for name in names.decode("utf-8").split("\0") if name and RENDER_SET.match(name)} + + +def _origin_paths(origin: Path, env: dict, ref: str = "main", where: str = ".") -> dict: + """Every path under `where` on a bare repository's `ref`, to its blob.""" + out = _git_bytes(origin, env, "ls-tree", "-r", "-z", ref, "--", where).decode("utf-8") + found = {} + for entry in out.split("\0"): + if entry: + meta, path = entry.split("\t", 1) + found[path] = meta.split()[2] + return found + + +def _raw_message(origin: Path, env: dict, ref: str = "main") -> str: + """A commit's message as git stores it, every byte after the header.""" + raw = _git_bytes(origin, env, "cat-file", "commit", ref) + return raw.split(b"\n\n", 1)[1].decode("utf-8") if b"\n\n" in raw else "" + + +#: A UTC in any form a register file spells it: whole minutes (a row's +#: `started` cell), whole seconds, or with a fraction (Q4(d)(i)). +_UTC_ANY = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}(?::[0-9]{2}(?:\.[0-9]+)?)?Z") +_UTC_ANY_BYTES = re.compile(_UTC_ANY.pattern.encode("ascii")) + + +def _utc_masked(files: dict) -> dict: + """`files`, {path: bytes}, with every UTC masked, in each path and in + each file's bytes (AT-1's twin oracle; open point 4).""" + return {_UTC_ANY.sub("<utc>", path): _UTC_ANY_BYTES.sub(b"<utc>", data) + for path, data in files.items()} + + +def _first_difference(ours: bytes, theirs: bytes) -> str: + a = ours.decode("utf-8", "replace").split("\n") + b = theirs.decode("utf-8", "replace").split("\n") + for n, (x, y) in enumerate(zip(a, b), 1): + if x != y: + return f"line {n}: {x!r} != {y!r}" + return f"{len(a)} lines != {len(b)} lines" + + +def _assert_same_files(ours: dict, theirs: dict, what: str) -> None: + assert sorted(ours) == sorted(theirs), ( + f"{what}: the path sets differ: only ours {sorted(set(ours) - set(theirs))}, only " + f"theirs {sorted(set(theirs) - set(ours))}") + for name in sorted(ours): + assert ours[name] == theirs[name], ( + f"{what}: {name}'s bytes differ, {_first_difference(ours[name], theirs[name])}") + + +def _stamped_utcs(before: dict, after: dict, argv: list) -> list: + """Each UTC in whole seconds or finer that a write put on a line of the + render set, (path, line, utc): one not already anywhere in the register + before it, and not one the caller typed. A UTC in whole minutes is a row's + `started` cell, never a write's clock. For `migrate-state-cells` alone + (`argv[0]`), nor is a minute already in the register with `:00` added, + which that verb writes on primary for an entry's minute-only time or its + row's `started` cell; no other verb adds it (design.md:5114 at + `8e8d1b49`; `44f487d1:lanes-edit.sh:23907-23922`, its arm's `msc_eutc`; + lane 3, #165 6859073786). Any other verb's `:00` UTC is still checked + against the clock, though its minute was in the register.""" + old = set(_UTC_ANY.findall("\n".join(d.decode("utf-8", "replace") for d in before.values()))) + typed = set(_UTC_ANY.findall(" ".join(argv))) + minute_kept = argv[0] == "migrate-state-cells" + found = [] + for path, data in sorted(after.items()): + lines_before = set(before.get(path, b"").decode("utf-8", "replace").split("\n")) + for line in data.decode("utf-8", "replace").split("\n"): + if line in lines_before: + continue + for utc in _UTC_ANY.findall(line): + if (utc.count(":") == 2 and utc not in old and utc not in typed + and not (minute_kept and utc.endswith(":00Z") + and utc[:-4] + "Z" in old)): + found.append((path, line, utc)) + return found + + +class PrimaryWrites: + """AT-1's part-W workstation over the test's database, a copy of the + writes module's `RegisterWorkstation` (that module imports this one): the + files-mode workspace of the sync case (`workspace`) at C, the case's prep + committed and pushed first; C imported and brought to `primary` with the + marker `present` (`import_to_primary`, AT-LR006's route); T203's flipped + copy with `lanes-edit.sh` beside it; a 0600 `lanes-index.conf` with + `mode=primary`, both URLs naming the cluster's socket as this module's + logins, and a 0600 `register_passfile=`; `<c>` for each of `W_LANES`, a + clone of origin; and first on `PATH`, T203's `psql` shim, which hands each + call to the cluster's `psql` and logs it, and `_logging_git`. + `marker_on_origin`, which only part G sets, puts the cutover's marker + commit on origin's `main` before `record_marker` (`import_to_primary`), + so each `<c>` is cloned at it; every other case keeps a made-up marker + sha and an origin at C (T270's line, tasks:2477).""" + + def __init__(self, pg, tmp_path: Path, prep: dict = None, + marker_on_origin: bool = False): + self.pg = pg + self.fakebin = tmp_path / "fakebin" + self.fakebin.mkdir(parents=True, exist_ok=True) + (self.fakebin / "psql").write_text(PSQL_SHIM, encoding="utf-8") + (self.fakebin / "psql").chmod(0o755) + (self.fakebin / PSQL_SHIM_CONTROL).write_text(json.dumps({"psql": pg.psql_bin}), + encoding="utf-8") + self.git_log = tmp_path / "git-calls.log" + _logging_git(self.fakebin / "git", self.git_log) + self.estate, self.env, _source = workspace(tmp_path / "ws", self.fakebin) + if prep: + self._prep(prep) + ensure_logins(pg) + self.copy = flipped(tmp_path) + self.lanes_edit = self.copy.parent / "lanes-edit.sh" + conf_dir = tmp_path / "conf" + conf_dir.mkdir() + passfile = conf_dir / "pgpass" + passfile.write_text(f"*:*:*:{LOGIN_WRITER}:{W_SECRET}\n", encoding="utf-8") + passfile.chmod(0o600) + self.conf = primary_config(conf_dir / "lanes-index.conf", pg.url(LOGIN_WRITER), + pg.url(LOGIN_READER), passfile) + self.env.update(LANES_INDEX_CONFIG=str(self.conf)) + self.env.pop("LANES_INDEX", None) + #: The environment the pure renderer and `status` run in. + self.index = index_env(tmp_path, self.conf, self.estate.home) + self.imported = import_to_primary(pg, self.estate, marker_on_origin) + for lane in W_LANES: + self.make_lane_checkout(lane) + + def _prep(self, files: dict) -> None: + """`files` ({path: text or bytes}) written over the checkout, + committed and pushed, so the case starts from them; C is that + commit.""" + estate = self.estate + for path, data in files.items(): + target = estate.checkout / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data if isinstance(data, bytes) else data.encode("utf-8")) + git(estate.checkout, "add", "-A", env=estate.env) + git(estate.checkout, "commit", "-q", "-m", "C': the case's starting state", + env=estate.env) + git(estate.checkout, "push", "-q", "origin", "main", env=estate.env) + estate.files.update({p: d for p, d in files.items() if isinstance(d, str)}) + estate.c = git(estate.checkout, "rev-parse", "HEAD", env=estate.env).strip() + estate.lanes_tree = git(estate.checkout, "rev-parse", f"{estate.c}:lanes", + env=estate.env).strip() + + def lane_checkout(self, lane: str) -> Path: + """`<c>`, `<W>-lanes/<lane>`, W being the real path of + `workspace.yaml`'s `path:` (Amendment 23 S1).""" + real = Path(os.path.realpath(self.estate.checkout)) + return real.parent / f"{real.name}-lanes" / lane + + def make_lane_checkout(self, lane: str) -> Path: + target = self.lane_checkout(lane) + target.parent.mkdir(parents=True, exist_ok=True) + git(target.parent, "clone", "-q", str(self.estate.origin), str(target), + env=self.estate.env) + return target + + def checkouts(self) -> list: + """W's checkout and each lane's `<c>`.""" + return [self.estate.checkout, *(self.lane_checkout(lane) for lane in W_LANES)] + + def run(self, argv: list, lane: str, **extra) -> subprocess.CompletedProcess: + """`lanes-edit.sh <argv>` in W's checkout, as lane `lane`.""" + env = dict(self.env, LANES_LANE=lane, **extra) + return subprocess.run(["bash", str(self.lanes_edit), *argv], capture_output=True, + encoding="utf-8", errors="replace", env=env, timeout=120, + cwd=str(self.estate.checkout), check=False, + stdin=subprocess.DEVNULL) + + def shim_calls(self) -> list: + log = self.fakebin / PSQL_SHIM_LOG + if not log.exists(): + return [] + entries = [json.loads(x) for x in log.read_text(encoding="utf-8").splitlines() if x] + return [e for e in entries if e.get("kind") != "version"] + + def commit_calls(self) -> list: + return [c for c in self.shim_calls() if "commit_write(" in (c.get("stdin") or "")] + + def git_calls(self) -> list: + return _git_calls(self.git_log) + + +class FilesTwin: + """AT-1's twin: a files-mode clone of W's origin at C, "under its own + `$HOME`", with an origin of its own, a bare clone of W's, so its push + moves nothing the primary case reads, and the environment `workspace` + sets, with no `lanes-index.conf`: `lanes-edit.sh` beside the flipped copy + asks its mode, and `files` answers. Made before the primary write, so it + is at C whatever a forked render pushes to W's origin. A `routed` twin + runs under `LANES_ROUTE_WRITES=1` with `LANES_REPO` unset, so each write + goes through its lane's own checkout, `<W>-lanes/<lane>`, made on first + use: an explicit `LANES_REPO` naming W is refused there (Amendment 23 S2, + S5; `f9e1449c:lanes-edit.sh:28132-28160`; lane 3, #165 6859073786). The + lane is named by `LANES_LANE`, as `run` sets it.""" + + def __init__(self, root: Path, estate: Estate, lanes_edit: Path, routed: bool = False): + self.root = root + self.home = root / "home" + self.home.mkdir(parents=True, exist_ok=True) + self.git_env = git_env(self.home) + self.origin = root / "origin.git" + self.checkout = root / "checkout" + git(root, "clone", "-q", "--bare", str(estate.origin), str(self.origin), + env=self.git_env) + git(root, "clone", "-q", str(self.origin), str(self.checkout), env=self.git_env) + self.c = git(self.origin, "rev-parse", "main", env=self.git_env).strip() + assert self.c == estate.c, "the twin is not at C" + agents = self.home / ".agents" + agents.mkdir(parents=True, exist_ok=True) + (agents / "workspace.yaml").write_text( + f"repository: {self.origin}\npath: {self.checkout}\n", encoding="utf-8") + fakebin = root / "fakebin" + fakebin.mkdir(parents=True, exist_ok=True) + (fakebin / "tmux").write_text("#!/bin/sh\nexit 1\n", encoding="utf-8") + (fakebin / "tmux").chmod(0o755) + for d in ("state", "config", "tmp"): + (root / d).mkdir(parents=True, exist_ok=True) + self.env = dict(self.git_env) + self.env.update(AGENT_PROTOCOL_ROOT=str(agents), TMPDIR=str(root / "tmp"), + XDG_STATE_HOME=str(root / "state"), + XDG_CONFIG_HOME=str(root / "config"), + CLAUDE_CONFIG_DIR=str(self.home / ".claude"), LANES_WORKSTATION=WS, + LANES_HOST="eagle", LANES_OS="linux", LANES_CONTAINER="none", + LANES_IN_CONTAINER="0", LANES_NO_GITHUB="1", + LANES_REPO=str(self.checkout), + PATH=str(fakebin) + os.pathsep + _masked_path()) + self.env.pop("LANES_INDEX", None) + self.env.pop("LANES_INDEX_CONFIG", None) + if routed: + self.env.pop("LANES_REPO") + self.env.update(LANES_ROUTE_WRITES="1") + self.lanes_edit = lanes_edit + + def run(self, argv: list, lane: str, **extra) -> subprocess.CompletedProcess: + env = dict(self.env, LANES_LANE=lane, **extra) + return subprocess.run(["bash", str(self.lanes_edit), *argv], capture_output=True, + encoding="utf-8", errors="replace", env=env, timeout=120, + cwd=str(self.checkout), check=False, stdin=subprocess.DEVNULL) + + def commits(self) -> list: + """The commits the twin pushed since C, oldest first.""" + out = git(self.origin, "rev-list", "--reverse", f"{self.c}..main", env=self.git_env) + return out.split() + + def render_set(self) -> dict: + return _origin_render_set(self.origin, self.git_env) + + def message(self) -> str: + return _raw_message(self.origin, self.git_env) + + +#: Files mode's `rename-lane` subject, "... the row, <log>, the handoff and +#: <aliases> in one commit" (`f9e1449c:lanes-edit.sh:30289`). +_RENAME_FILES_SUBJECT = re.compile( + r"^(LANES\(\S+\): RENAMED lane .+ the row, )(\S+), the handoff and (\S+) in one commit$", + re.M) + + +def _primary_message(verb: str, message: str) -> str: + """The journal message a primary write of `verb` composes, from its + files-mode twin's commit `message`: the same, but `rename-lane`'s, whose + handoff is not in the entry (Q13(a)), so T422 composes "... the row, + <log> and <aliases> in one register write; the handoff's move and stamp + follow in the lane's checkout (Q13(a))" (`f9e1449c:lanes-edit.sh:30293-30294`), + the message the design names (lane 3's ruling (A), #165 6859179515).""" + if verb != "rename-lane": + return message + named, n = _RENAME_FILES_SUBJECT.subn( + r"\1\2 and \3 in one register write; the handoff's move and stamp follow in " + r"the lane's checkout (Q13(a))", message, count=1) + assert n == 1, f"rename-lane: the twin's message has no files-mode subject: {message!r}" + return named + + +def _journal_since(db, seq: int) -> list: + return rows(db, f"SELECT seq, write_id, kind, verb, lane, message FROM journal " + f"WHERE seq > {seq} ORDER BY seq") + + +def _one_entry(db, before: int, proc: subprocess.CompletedProcess, what: str) -> dict: + """A write on primary that exited 0, and its one journal entry, at the old + head plus one.""" + assert proc.returncode == 0, ( + f"{what} on primary exited {proc.returncode} (L4-B4, L4-B8, L4-B13): " + f"{proc.stderr[-800:]}") + new = _journal_since(db, before) + assert len(new) == 1 and new[0]["seq"] == before + 1, ( + f"{what} on primary added {len(new)} journal entries after seq {before}, not one at " + f"{before + 1}: line R's lanes-edit.sh writes the files whatever mode= says (L4-B4, " + f"T414's seam): {new}") + return new[0] + + +def _rows_written_at(db, seq: int) -> list: + """Every register row whose last writer is the entry at `seq`, with the + mode it records: part N's five tables.""" + return rows(db, f"SELECT 'doc_lines' AS t, written_mode AS m FROM doc_lines " + f"WHERE written_seq = {seq} " + f"UNION ALL SELECT 'lanes', last_mode FROM lanes WHERE last_seq = {seq} " + f"UNION ALL SELECT 'log_lines', mode FROM log_lines WHERE seq = {seq} " + f"UNION ALL SELECT 'register_lines', mode FROM register_lines " + f"WHERE seq = {seq} " + f"UNION ALL SELECT 'object_holds', mode FROM object_holds WHERE seq = {seq}") + + +def _mirror(ws: PrimaryWrites, seq: int, out_dir: Path) -> dict: + """The pure renderer's scratch mirror at `seq`, its render set: {path: + bytes}. It writes nothing outside its four paths (and `lanes/STORE`).""" + proc, images = render_images(ws.copy, ws.index, seq, out_dir) + assert proc.returncode == 0, f"render --images --at {seq} exited {proc.returncode}: " \ + f"{proc.stderr}" + assert all(RENDER_SET.match(p) or p == STORE_PATH for p in images), ( + f"the renderer wrote outside its four paths: {sorted(images)}") + return _rendered_only(images) + + +@pytest.mark.parametrize("verb", list(W_VERBS)) +def test_each_write_leaves_the_mirror_byte_identical_to_a_full_render(pg, tmp_path, verb): + """AT-1's part W, the mirror: `lanes-edit.sh <verb>` on primary exits 0; + the journal gains exactly one entry, at the old head plus one, with a + `write_id` unique in the journal; the pure renderer's scratch mirror at + that seq equals the full render from SQL (`render_file` of every path in + `files`), path set and bytes, over `lanes/LANES.md`, `lanes/log/*.md`, + `lanes/aliases.tsv` and `lanes/archive/**`, and holds nothing outside + them; the write changed a rendered file; each UTC the write put on a line + is the database's, in whole seconds, between its clock read before the + write and after it (S6; D13). And D12 (GB section 4.3): the fake `git`'s + log holds no `fetch` (nor a `pull`) on primary that the verb itself + makes, for any verb. The renderer the write forks fetches origin, as each + pass does (Y:2839; AT-C8, TP:3187-3188), so a call with a `lanes-index + render --checkout` process above it is left out, by that process, never + by the call's argv, since the pass's read-back fetch has the same argv; + each one left out ran in the writing lane's checkout (lane 3, #165 + 6859073786). A control shows the test tells them apart by process. Fails + until L4-B4, L4-B8 and L4-B13.""" + argv, lane = W_VERBS[verb] + ws = PrimaryWrites(pg, tmp_path, W_PREPS.get(verb)) + before_head = head(pg) + before_ids = {r["write_id"] for r in rows(pg, "SELECT write_id FROM journal")} + before = _rendered_only(full_render(pg)) + clock_before = db_clock(pg) + proc = ws.run(argv, lane) + clock_after = db_clock(pg) + entry = _one_entry(pg, before_head, proc, verb) + seq = entry["seq"] + assert entry["write_id"] and entry["write_id"] not in before_ids, entry + assert rows(pg, f"SELECT count(*) AS n FROM journal " + f"WHERE write_id = '{entry['write_id']}'") == [{"n": 1}] + + # THE MIRROR: the scratch mirror at seq is the full render from SQL. + mirror = _mirror(ws, seq, tmp_path / "mirror") + full = _rendered_only(full_render(pg)) + _assert_same_files(mirror, full, f"{verb}: the mirror at seq {seq} and the full render") + assert mirror != before, f"{verb} changed no rendered file" + + # THE UTC: the database's clock, in whole seconds. + for path, line, utc in _stamped_utcs(before, mirror, argv): + assert UTC_RE.match(utc), f"{verb} wrote {utc!r}, not whole seconds, in {path}: {line!r}" + assert clock_before <= epoch_of(utc) <= clock_after, ( + f"{verb} wrote {utc} in {path}, outside the database's clock " + f"[{utc_of(clock_before)}, {utc_of(clock_after)}]: {line!r}") + + # D12: NO FETCH ON PRIMARY BY THE VERB ITSELF. The forked renderer's own + # fetches are left out by the process above them, each in the writing + # lane's checkout. + fetches = [call for call in ws.git_calls() if call["sub"] in ("fetch", "pull")] + own = [call["args"] for call in fetches if call["render"] is None] + assert own == [], f"{verb} fetched on primary (D12): {own}" + checkout = os.path.realpath(ws.lane_checkout(lane)) + astray = [call for call in fetches + if os.path.realpath(call["render"]) != checkout or call["where"] != checkout] + assert astray == [], ( + f"{verb}: its forked renderer fetched outside the writing lane's checkout " + f"{checkout} (D12): {astray}") + _d12_control(tmp_path / "d12-control", checkout) + + +@pytest.mark.parametrize("verb", list(TWIN_VERBS)) +def test_each_write_matches_its_files_mode_twin_byte_for_byte(pg, tmp_path, verb): + """AT-1's part W, the twin: `lanes-edit.sh <verb>` on primary exits 0 with + one journal entry; its files-mode twin, a clone of W's origin at C under + its own `$HOME`, makes the same verb, exits 0 and pushes one commit; the + scratch mirror at the entry's seq equals the render set on the twin's + origin, path set and bytes, every UTC masked in both (open point 4); and + the entry's message is the twin's commit message, byte for byte, or but + for the one LF git ends a stored message with; for `rename-lane`, the + message the design names under Q13(a), `_primary_message`'s. GB section 4.3's + `start-record` (lane 4's T427, L4-B9) is `[start-record]`, a resume of + repoA-2 in both modes, whose twin runs once more, in a second clone at C, + under `LANES_ROUTE_WRITES=1` with `LANES_REPO` unset, through the lane's + own checkout (Amendment 23 S2, S5), with the same render set and message. Fails + until L4-B4, L4-B8 and L4-B13; `[start-record]` until L4-B9 too.""" + argv, lane, extra = TWIN_VERBS[verb] + ws = PrimaryWrites(pg, tmp_path, W_PREPS.get(verb)) + twin = FilesTwin(tmp_path / "twin", ws.estate, ws.lanes_edit) + routed = (FilesTwin(tmp_path / "twin-routed", ws.estate, ws.lanes_edit, routed=True) + if verb == "start-record" else None) + before_head = head(pg) + proc = ws.run(argv, lane, **extra) + entry = _one_entry(pg, before_head, proc, verb) + mirror = _mirror(ws, entry["seq"], tmp_path / "mirror") + + for label, files_twin in (("the twin", twin), ("the routed twin", routed)): + if files_twin is None: + continue + done = files_twin.run(argv, lane, **extra) + assert done.returncode == 0, ( + f"{label}'s {verb} in files mode exited {done.returncode}: {done.stderr[-800:]}") + assert len(files_twin.commits()) == 1, ( + f"{label}'s {verb} pushed {len(files_twin.commits())} commits, not one") + _assert_same_files(_utc_masked(mirror), _utc_masked(files_twin.render_set()), + f"{verb}: the mirror and {label}'s files, every UTC masked") + message = _primary_message(verb, files_twin.message()) + bare = message[:-1] if message.endswith("\n") else message + assert entry["message"] in (message, bare), ( + f"{verb}: the journal's message {entry['message']!r} is not {label}'s commit " + f"message, as primary composes it, {message!r}") + + +@pytest.mark.parametrize("verb", list(W_VERBS)) +def test_each_write_reads_back_primary_as_the_mode_that_wrote_it_last(pg, tmp_path, verb): + """AT-1's part W, the rows (P183-188): after `lanes-edit.sh <verb>` on + primary exits 0 with one journal entry, every register row that entry + wrote last (`doc_lines`, `lanes`, `log_lines`, `register_lines` and + `object_holds`, by its seq) reads `primary` as the mode that wrote it, + and there is at least one. Fails until L4-B4, L4-B8 and L4-B13.""" + argv, lane = W_VERBS[verb] + ws = PrimaryWrites(pg, tmp_path, W_PREPS.get(verb)) + before_head = head(pg) + proc = ws.run(argv, lane) + entry = _one_entry(pg, before_head, proc, verb) + touched = _rows_written_at(pg, entry["seq"]) + assert touched, f"{verb}'s entry at seq {entry['seq']} wrote no register row" + assert {r["m"] for r in touched} == {"primary"}, ( + f"{verb}'s rows do not all read primary as the mode that wrote them last: {touched}") + + +#: AT-1's `rename-lane` handoffs: a handoff named for its lane, under its +#: estate's folder, as `lane-start` computes it, and where the rename moves it. +RL_HANDOFF = "handoffs/eagle/session-handoff-2026-10-01-lane-repoA-2.md" +RL_MOVED = "handoffs/eagle/session-handoff-2026-10-01-lane-repoA-3.md" +#: A handoff Rule 3's stamp can go into: a header line, a blank line, a body. +RL_TEXT = b"# handoff of lane repoA-2\n\nwhat the lane left\n" +#: A handoff that cannot take the stamp without a byte of it rewritten: one +#: line and no LF, so the stamp would join its only line. +RL_UNSTAMPABLE = ("handoffs/eagle/session-handoff-2026-10-01-lane-repoA-1.md", + b"# handoff of lane repoA-1, with no LF") +#: The rename's arguments, its old lane and its new. +RL_ARGV = ["rename-lane", "repoA-2", "repoA-3", "test 1", "--no-github"] + + +def _rl_stamped(old: bytes, new: bytes) -> bool: + """`new` is `old` with exactly one line put in, which names both lanes: + Rule 3's stamp (Amendment 16(d)).""" + a, b = old.split(b"\n"), new.split(b"\n") + return len(b) == len(a) + 1 and any( + b[:i] + b[i + 1:] == a and b"repoA-2" in b[i] and b"repoA-3" in b[i] + for i in range(len(b))) + + +def test_rename_lane_commits_the_transaction_then_a_rerun_makes_only_the_move(pg, tmp_path): + """AT-1's part W, Brett's row 18 (comment 6721583757), with GB section + 4.3's `rename-lane` cases (R29): on primary the transaction comes first, + and the handoff's move and Rule 3 stamp follow it as the verb's + after-COMMIT tail (Q13(a); Y:5092; B14 tasks:1270-1279). + + A HANDOFF THAT CANNOT BE STAMPED refuses before anything is sent (Y:5138): + repoA-1's, one line with no LF; its rename exits non-zero with no commit + call, the journal and origin as they were. + + THEN repoA-2's, with the move made to fail after the commit (its folder in + repoA-2's `<c>` read-only): the rename exits 0 with one WARNING, the move + owed; it prints `register seq <s>`, the entry's seq; the journal holds the + rename once; the handoff paths left the change set (no `handoffs/` path + among the entry's files), and the row's handoff column names the new path + in the transaction; origin still holds the handoff at its old path. A + rerun, `LANES_LANE=repoA-3 lanes-edit.sh rename-lane repoA-2 repoA-3` + (batch c Q71 and Q74), exits 0, adds no journal entry, and makes the move: + origin holds the handoff at the new path, stamped, and not at the old. + Fails until L4-B8 (lane 4's T422), L4-B4 and L4-B13.""" + prep = _w_with_handoffs({"repoA-2": (RL_HANDOFF, RL_TEXT), "repoA-1": RL_UNSTAMPABLE}) + ws = PrimaryWrites(pg, tmp_path, prep) + origin, env = ws.estate.origin, ws.estate.env + + # A HANDOFF THAT CANNOT BE STAMPED: refused before anything is sent. + before_head, refs = head(pg), _origin_paths(origin, env) + refused = ws.run(["rename-lane", "repoA-1", "repoA-9", "test 1", "--no-github"], "repoA-1") + assert refused.returncode != 0, ( + f"a rename of a handoff that cannot take Rule 3's stamp exited 0 (Y:5138): " + f"{refused.stderr[-800:]}") + assert ws.commit_calls() == [], f"the refusal sent a commit call: {ws.commit_calls()}" + assert head(pg) == before_head and _origin_paths(origin, env) == refs + + # THE MOVE MADE TO FAIL AFTER THE COMMIT. + folder = ws.lane_checkout("repoA-2") / Path(RL_HANDOFF).parent + folder.chmod(0o555) + try: + if os.access(str(folder), os.W_OK): + pytest.skip("this user writes into a read-only directory, so the move cannot be " + "made to fail") + first = ws.run(RL_ARGV, "repoA-2") + finally: + folder.chmod(0o755) + entry = _one_entry(pg, before_head, first, "rename-lane, its move made to fail") + said = first.stdout + first.stderr + assert re.search(rf"\bregister seq {entry['seq']}\b", said), ( + f"rename-lane on primary did not print `register seq {entry['seq']}`: {said[-800:]}") + assert first.stderr.count("WARNING") == 1, ( + f"a failed move ends 0 with ONE WARNING, the move owed: {first.stderr[-1200:]}") + entry_files = rows(pg, f"SELECT path FROM journal_files WHERE seq = {entry['seq']}") + assert not [r for r in entry_files if r["path"].startswith("handoffs/")], ( + f"the handoff paths did not leave the change set: {entry_files}") + lanes_md = _rendered_only(full_render(pg))["lanes/LANES.md"].decode("utf-8") + row = next((line for line in lanes_md.split("\n") if line.startswith("| `repoA-3`")), "") + assert f"| {RL_MOVED} |" in row, f"the row's handoff column is not the new path: {row!r}" + paths = _origin_paths(origin, env) + assert RL_HANDOFF in paths and RL_MOVED not in paths, ( + "the failed move reached origin, or the handoff left its old path") + + # THE RERUN: no entry, only the move. + again = ws.run(RL_ARGV, "repoA-3") + assert again.returncode == 0, f"the rerun exited {again.returncode}: {again.stderr[-800:]}" + assert _journal_since(pg, entry["seq"]) == [], "the rerun added a journal entry" + paths = _origin_paths(origin, env) + assert RL_MOVED in paths and RL_HANDOFF not in paths, ( + f"the rerun did not make the move on origin: " + f"{sorted(p for p in paths if p.startswith('handoffs/'))}") + moved = _git_bytes(origin, env, "cat-file", "blob", f"main:{RL_MOVED}") + assert _rl_stamped(RL_TEXT, moved), f"the moved handoff is not stamped: {moved!r}" + + +def test_a_caller_composed_utc_and_log_paused_utc_stay_as_written(pg, tmp_path): + """AT-1's part W: a UTC the caller wrote into the line, `append-line`'s + `HOLD` line, and `log PAUSED --utc`'s, Amendment 17's late PAUSED, are + stored and rendered byte for byte, never replaced by the database's + clock: after each write on primary (exit 0, one journal entry), the line + is in `doc_lines`, in the full render from SQL and in the scratch mirror + at the entry's seq, carrying the caller's UTC, which is not the + database's clock. Fails until L4-B4, L4-B8 and L4-B13.""" + ws = PrimaryWrites(pg, tmp_path) + hold = (f"HOLD {EM} lane repoA-2 ({WS}), window w, 2026-11-02T03:04:05Z: " + f"opensoft/repoB main {TIP} for test 1's own UTC") + late = "2026-11-01T09:08:07Z" + paused = re.compile(rf"^PAUSED {EM} lane repoA-1, session [^,]+@{WS}, {late}, lane:repoA-1" + rf"(?: |$)") + for what, argv, lane, path, utc, wanted in ( + ("append-line's HOLD", ["append-line", hold], "repoA-2", "lanes/LANES.md", + "2026-11-02T03:04:05Z", lambda line: line == hold), + ("log PAUSED --utc", ["log", "PAUSED", "lane:repoA-1", "--utc", late, + "parked late for test 1"], "repoA-1", "lanes/log/repoA-1.md", + late, lambda line: bool(paused.match(line)))): + assert abs(db_clock(pg) - epoch_of(utc)) > 3600, "the caller's UTC is the clock's" + before_head = head(pg) + proc = ws.run(argv, lane) + entry = _one_entry(pg, before_head, proc, what) + stored = [r["text"] for r in rows(pg, f"SELECT text FROM doc_lines WHERE path = '{path}' " + f"AND written_seq = {entry['seq']}")] + assert any(wanted(text) for text in stored), ( + f"{what}: no line the write stored carries the caller's UTC as written: {stored}") + for label, files in (("the full render", _rendered_only(full_render(pg))), + ("the mirror", _mirror(ws, entry["seq"], + tmp_path / f"mirror-{entry['seq']}"))): + lines = files[path].decode("utf-8").split("\n") + assert any(wanted(line) for line in lines), ( + f"{what}: {label}'s {path} holds no line with the caller's UTC as written") + + +def test_on_primary_a_write_does_not_nudge_a_register_sync(tmp_path): + """AT-1's FP case (the delta's "The post-write nudge does not re-index the + mirror into its own source"; FR-027; T416, "The nudge: `index_nudge`'s + register `sync` is suppressed on primary. Its inventory nudge stays"): a + `log RESUMED` on a `mode=primary` workstation whose `lanes-index` is the + contract's stub (T207), beside a copy of `lanes-edit.sh`, `repos.tsv` and + `lane-start` (CLI4.5 section 6's copy rule) and first on `PATH`, where + `index_nudge` finds it, its register holding C's render set. The write + exits 0 and is a primary write (the stub's log holds its `register + commit`); then the stub's log holds no register `sync` (`sync` with no + `--source`, or one naming the register), and holds the inventory's, + `sync --source inventory`, which a `RESUMED`'s lifecycle follow leaves + (`LANES_LANE_STATE_ROOT` gives it a control root). The nudges are + detached forks, so the case waits for the inventory's, 30 s at most, and + one second more. No engine. Fails until L4-B13 (T416's nudge) and L4-B4: + on line R's V-round4 the write runs files mode, exits 0 and makes no + `register commit`.""" + code = tmp_path / "code" + code.mkdir() + for name in ("lanes-edit.sh", "repos.tsv", "lane-start"): + shutil.copy2(str(REPO / name), str(code / name)) + fakebin = tmp_path / "fakebin" + estate, env, _source = workspace(tmp_path / "ws", fakebin) + contract_stub(code, register={p: t for p, t in estate.files.items() if RENDER_SET.match(p)}) + argv_log = code / "lanes-index.argv" + dead = tmp_path / "dead" + dead.mkdir() + host = quote(dead.as_posix(), safe="") + (tmp_path / "conf").mkdir() + conf = primary_config(tmp_path / "conf" / "lanes-index.conf", + f"postgresql://{LOGIN_WRITER}@{host}:5432/lanes_t240", + f"postgresql://{LOGIN_READER}@{host}:5432/lanes_t240") + env.update(LANES_INDEX_CONFIG=str(conf), LANES_LANE="repoA-2", + LANES_LANE_STATE_ROOT=str(tmp_path / "lane-state"), + PATH=str(code) + os.pathsep + env["PATH"]) + env.pop("LANES_INDEX", None) + real = Path(os.path.realpath(estate.checkout)) + lane_c = real.parent / f"{real.name}-lanes" / "repoA-2" + lane_c.parent.mkdir(parents=True, exist_ok=True) + git(lane_c.parent, "clone", "-q", str(estate.origin), str(lane_c), env=estate.env) + + proc = subprocess.run(["bash", str(code / "lanes-edit.sh"), *W_VERBS["log-resumed"][0]], + capture_output=True, encoding="utf-8", errors="replace", env=env, + timeout=120, cwd=str(estate.checkout), check=False, + stdin=subprocess.DEVNULL) + assert proc.returncode == 0, ( + f"log RESUMED on primary exited {proc.returncode} (L4-B4, L4-B13): " + f"{proc.stderr[-800:]}") + + def calls() -> list: + if not argv_log.exists(): + return [] + return [json.loads(x) for x in argv_log.read_text(encoding="utf-8").splitlines() if x] + + assert any(c[:2] == ["register", "commit"] for c in calls()), ( + f"the write made no `register commit`, so it was no primary write: {calls()}") + inventory = ["sync", "--source", "inventory"] + deadline = time.monotonic() + 30 + while inventory not in calls() and time.monotonic() < deadline: + time.sleep(0.1) + time.sleep(1) + syncs = [c for c in calls() if c and c[0] == "sync"] + register_syncs = [c for c in syncs if c != inventory] + assert register_syncs == [], ( + f"a primary write nudged a register sync, which re-indexes the mirror into its own " + f"source (T416): {register_syncs}") + assert inventory in syncs, f"the inventory's nudge did not run: {calls()}" + + +def test_rename_lane_commits_the_transaction_then_its_move_on_primary_takes_no_bytecode_to_to( + pg, tmp_path): + """The move's bytecode on primary (R-F13c-23; lane 3's batch 8, Q32, as + lane 3's batch c corrects it, #165 6807881675, Q55 and Q56; #162; B15 text + (2) for F13d:502): `rename-lane` on primary moves a handoff whose folder + also tracks a pre-#162 `__pycache__` file and a tool-cache path + (`.mypy_cache`). The rename exits 0 with one journal entry; the move + renames that one handoff inside its folder, and its commit, the one commit + on origin that changes a path under `handoffs/`, holds only the handoff's + D at `<from>` and A at `<to>`; the folder's other tracked paths stay in + `<c>`'s index and on origin as they were; no note names them; and T420's + backstop passes the push (origin holds the move). The files-mode twin + moves as today: its rename exits 0, and its origin holds the handoff at + `<to>` alone, with the folder's other paths kept. Fails until lane 4's + T422 lands, with L4-B4 and L4-B13.""" + bytecode = {"handoffs/eagle/__pycache__/notes.cpython-312.pyc": b"\x00pyc, before #162", + "handoffs/eagle/.mypy_cache/3.12/notes.meta.json": b"{}\n"} + ws = PrimaryWrites(pg, tmp_path, _w_with_handoffs({"repoA-2": (RL_HANDOFF, RL_TEXT)}, + bytecode)) + twin = FilesTwin(tmp_path / "twin", ws.estate, ws.lanes_edit) + origin, env = ws.estate.origin, ws.estate.env + lane_c = ws.lane_checkout("repoA-2") + base = git(origin, "rev-parse", "main", env=env).strip() + kept_on_origin = {p: b for p, b in _origin_paths(origin, env).items() if p in bytecode} + kept_in_c = git(lane_c, "ls-files", "-s", "--", *bytecode, env=env) + assert len(kept_on_origin) == 2 and len(kept_in_c.splitlines()) == 2 + + before_head = head(pg) + proc = ws.run(RL_ARGV, "repoA-2") + _one_entry(pg, before_head, proc, "rename-lane over a folder that tracks bytecode") + moves = git(origin, "log", "--format=%H", f"{base}..main", "--", "handoffs", + env=env).split() + assert len(moves) == 1, f"{len(moves)} commits on origin change handoffs/, not one: {moves}" + changed = git(origin, "diff-tree", "--no-commit-id", "-r", "--no-renames", "--name-status", + moves[0], env=env).split("\n") + assert sorted(x for x in changed if x) == sorted([f"D\t{RL_HANDOFF}", f"A\t{RL_MOVED}"]), ( + f"the move's commit holds more than the handoff's D and A: {changed}") + assert {p: b for p, b in _origin_paths(origin, env).items() if p in bytecode} == \ + kept_on_origin, "the folder's other tracked paths changed on origin" + assert git(lane_c, "ls-files", "-s", "--", *bytecode, env=env) == kept_in_c, ( + "the folder's other tracked paths left <c>'s index") + said = proc.stdout + proc.stderr + assert "__pycache__" not in said and ".mypy_cache" not in said, ( + f"a note names the folder's bytecode or tool-cache paths: {said[-800:]}") + + done = twin.run(RL_ARGV, "repoA-2") + assert done.returncode == 0, f"the files-mode twin's rename exited {done.returncode}: " \ + f"{done.stderr[-800:]}" + theirs = _origin_paths(twin.origin, twin.git_env) + assert RL_MOVED in theirs and RL_HANDOFF not in theirs, "the twin did not move the handoff" + assert {p: b for p, b in theirs.items() if p in bytecode} == kept_on_origin, ( + "the twin's move changed the folder's other tracked paths") + + +#: N1's handoff paths (REV422c N1; batch c Q56): a row whose handoff is at a +#: path with a `venv/` part, and one whose handoff is at a path with a +#: `__pycache__/` part, each named for its lane: {lane: (path, its new name)}. +RL_CACHE_PARTS = { + "repoA-2": ("handoffs/venv/session-handoff-2026-10-01-lane-repoA-2.md", "repoA-3", "venv"), + "repoA-1": ("handoffs/eagle/__pycache__/session-handoff-2026-10-01-lane-repoA-1.md", + "repoA-9", "__pycache__"), +} + + +def test_rename_lane_commits_the_transaction_only_where_its_handoffs_path_has_no_cache_part_on_primary( # noqa: E501 + pg, tmp_path): + """N1's refusal (REV422c N1; lane 3's batch c, #165 6807881675, Q56; B15 + text (2) for F13d:502; Y:5138, "a handoff that cannot be stamped refuses + before anything is sent"): on primary, a row whose handoff is at a path + with a `venv/` part, and one whose handoff is at a path with a + `__pycache__/` part (each tracked in the lane's `<c>`, committed there + before #162), each refuse 2 before the seam: stderr names the part; the + run sent the register a read, the attempt's snapshot, so the refusal is + primary's, made in the attempt's child before the seam (files mode's own + #162 refusal of the same move sends nothing, and exits 2 as well); no + commit call is sent; no register line is written (the journal's head and + the rendered files as they were); and no move is made (origin, and the + handoff in `<c>`, as they were). Fails until lane 4's T422 lands, with + L4-B4 and L4-B13: it passes on T422 `eda2411` over line R's V-round4.""" + prep = _w_with_handoffs({lane: (path, f"# handoff of lane {lane}\n\nbody\n".encode("ascii")) + for lane, (path, _new, _part) in RL_CACHE_PARTS.items()}) + ws = PrimaryWrites(pg, tmp_path, prep) + origin, env = ws.estate.origin, ws.estate.env + for lane, (path, new, part) in RL_CACHE_PARTS.items(): + before_head, before_files = head(pg), _rendered_only(full_render(pg)) + paths = _origin_paths(origin, env) + handoff = ws.lane_checkout(lane) / path + held = handoff.read_bytes() + sent_before = len(ws.shim_calls()) + proc = ws.run(["rename-lane", lane, new, "test 1", "--no-github"], lane) + sent = ws.shim_calls()[sent_before:] + assert proc.returncode == 2, ( + f"rename-lane {lane} on primary, its handoff at {path}, exited {proc.returncode}, " + f"not 2 (N1; lane 4's T422): {proc.stderr[-800:]}") + assert part in proc.stderr, f"the refusal does not name {part!r}: {proc.stderr!r}" + assert sent, ( + f"rename-lane {lane} sent the register nothing, so its 2 is not primary's refusal " + f"after the attempt's snapshot (N1; lane 4's T422; L4-B4): {proc.stderr[-800:]}") + assert not [c for c in sent if "commit_write(" in (c.get("stdin") or "")], ( + f"the refusal sent a commit call: {sent}") + assert head(pg) == before_head and _rendered_only(full_render(pg)) == before_files, ( + "the refusal wrote a register line") + assert _origin_paths(origin, env) == paths and handoff.read_bytes() == held, ( + "the refusal moved the handoff") + + +# ============================================================ phase G: T270 +# +# TEST 1'S PHASE-G PART (lane 2's T270, its one case in this module; AT-1, the +# test plan's line 606; the rest of T270 is test 5 and C8, in +# `test_sql_register_renderer_git.py`): the same verbs as part W, on the same +# workstation, with the mirror read from the bare origin's `main`, by object, +# after the renderer the write forks (T416's `render --checkout <c>`, lane 3's +# T320 to T323) has pushed it. The wait is open point 8's first: `lanes-index +# status`, every 100 ms, 30 s at most, until its lag is 0 (`lag: 0 +# seq(s)`, lane 1's `status_register`). `status` reads `m` from `origin/<b>` as +# last fetched in W's checkout, `workspace-root`'s answer, `workspace.yaml`'s +# `path:`, whatever `LANES_REPO` names (`7893339348a5:lanes-index:20357`, +# `:1400-1412`; `7893339348a5:lanes-edit.sh:1411-1416`), and fetches nothing +# (`_register_mirror`); the render pushes from the writing lane's `<c>`. So +# each poll comes after the harness's own fetch of W, `git -C <W> fetch -q +# origin main`, with plain git, never through `_logging_git`: lane 3's ruling +# (a), #165 6833830078, as RG's `wait_lag_0` (T270e) and the drill's have it. +# It fails until T320 to T323, T325 and L4-B13 land. +# +# ITS ESTATE, AND NO OTHER, PUTS THE CUTOVER'S MARKER COMMIT ON W'S ORIGIN +# (T270's line, tasks:2477; lane 2, #165 6866688575; lane 3, #165 +# 6866808028): `PrimaryWrites(marker_on_origin=True)`, C plus `lanes/STORE` +# with the cutover entry's bytes, `Register-Seq: <cut>` in the last paragraph, +# made before `record_marker` and recorded by it. On a made-up sha and an +# origin at C the forked render finds no `m`, and renders and pushes nothing +# (Y:2845-2847), and `status`'s lag is unknown at every poll. With the commit +# `m` is the cut and the lag 0 before the write, which commits seq cut + 1 +# before the poll starts, so a lag of 0 can then only be the render's push, +# and a lag that `status` cannot read for want of `m` fails at once. + +#: `status`'s lag line when the mirror has caught up (`status_register`). +STATUS_LAG_ZERO = re.compile(r"^\s*lag:\s+0 seq\(s\)", re.M) +#: `status`'s lag line when no `Register-Seq` is found (`status_register`). +STATUS_LAG_NO_M = re.compile(r"^\s*lag:\s+unknown, since the mirror's m cannot be read", re.M) + + +def _checkout_state(checkout: Path, env: dict) -> tuple: + """A checkout's HEAD, its index's digest and `status --porcelain=v1 -uall`.""" + index = checkout / ".git" / "index" + return (git(checkout, "rev-parse", "HEAD", env=env), + hashlib.sha256(index.read_bytes()).hexdigest() if index.exists() else "-", + git(checkout, "status", "--porcelain=v1", "-uall", env=env)) + + +def _status_after_fetching_w(ws: PrimaryWrites) -> subprocess.CompletedProcess: + """`status` in W's checkout, after the harness's own fetch of W, with plain + git (the estate's environment, no `_logging_git` on its `PATH`).""" + git(ws.estate.checkout, "fetch", "-q", "origin", "main", env=ws.estate.env) + return run_index(ws.copy, ["status"], ws.env, cwd=ws.estate.checkout) + + +def _wait_for_the_render(ws: PrimaryWrites, ceiling: float = 30.0) -> None: + """Open point 8's first wait: a bounded poll of `status`, each after a + fetch of W, until its lag is 0. Origin carries `m` from the marker commit + on, so a lag unknown for want of `m` fails at once.""" + deadline = time.monotonic() + ceiling + last = "" + while True: + proc = _status_after_fetching_w(ws) + if STATUS_LAG_ZERO.search(proc.stdout): + return + last = f"exit {proc.returncode}: {proc.stdout[-700:]}{proc.stderr[-300:]}" + assert not STATUS_LAG_NO_M.search(proc.stdout), ( + f"status found no Register-Seq on W's origin/main, though origin carries the " + f"marker commit; status said {last}") + assert time.monotonic() < deadline, ( + f"the forked render did not bring the lag to 0 within {ceiling:.0f} s (T320 to " + f"T323, L4-B13); status said {last}") + time.sleep(0.1) + + +@pytest.mark.parametrize("verb", list(W_VERBS)) +def test_the_mirror_on_origin_equals_a_full_render_after_each_write(pg, tmp_path, verb): + """AT-1's part G: `lanes-edit.sh <verb>` on primary exits 0 with one + journal entry; once the forked render has brought `status`'s lag to 0 + (open point 8), origin has gained exactly one commit, whose + `Register-Seq:` trailer, in its message's last paragraph in `Key: value` + form, is the entry's seq, so `git log + --format='%(trailers:key=Register-Seq,valueonly)'` reads it (AT-F11); the + render set on origin's `main`, read by object, equals the full render from + SQL, path set and bytes; and W's checkout and each lane's `<c>` keep their + HEAD, index and working tree (Q27(a), the private-index form). Origin + starts at the cutover's marker commit on C, the sha `record_marker` + recorded, where `status`, after a fetch of W, reads a lag of 0 before the + write, and the render commit's parent is that marker commit + (tasks:2477). Fails until T320 to T323, T325 and L4-B13, with L4-B4 and + L4-B8.""" + argv, lane = W_VERBS[verb] + ws = PrimaryWrites(pg, tmp_path, W_PREPS.get(verb), marker_on_origin=True) + origin, env = ws.estate.origin, ws.estate.env + base = git(origin, "rev-parse", "main", env=env).strip() + recorded = rows(pg, "SELECT marker_commit FROM register_switch")[0]["marker_commit"] + assert base == recorded and git(origin, "rev-parse", f"{base}^", env=env).strip() == \ + ws.estate.c, (f"origin's main is {base}, not the marker commit {recorded} on C " + f"{ws.estate.c}") + status = _status_after_fetching_w(ws) + assert STATUS_LAG_ZERO.search(status.stdout), ( + f"before the write, status after a fetch of W did not read a lag of 0 from the " + f"marker commit: exit {status.returncode}: {status.stdout[-700:]}" + f"{status.stderr[-300:]}") + checkouts = {str(c): _checkout_state(c, env) for c in ws.checkouts()} + before_head = head(pg) + proc = ws.run(argv, lane) + entry = _one_entry(pg, before_head, proc, verb) + _wait_for_the_render(ws) + + gained = git(origin, "rev-list", f"{base}..main", env=env).split() + assert len(gained) == 1, f"origin gained {len(gained)} commits, not one: {gained}" + assert git(origin, "rev-parse", f"{gained[0]}^", env=env).strip() == base, ( + "the render commit's parent is not the marker commit") + trailer = git(origin, "log", "-1", "--format=%(trailers:key=Register-Seq,valueonly)", + gained[0], env=env).strip() + assert trailer == str(entry["seq"]), ( + f"the render commit's Register-Seq trailer reads {trailer!r}, not {entry['seq']}") + _assert_same_files(_origin_render_set(origin, env), _rendered_only(full_render(pg)), + f"{verb}: origin's main and the full render") + assert {str(c): _checkout_state(c, env) for c in ws.checkouts()} == checkouts, ( + "the render changed a lane checkout's HEAD, index or working tree") diff --git a/tests/test_sql_register_renderer_git.py b/tests/test_sql_register_renderer_git.py new file mode 100644 index 00000000..d03ba26f --- /dev/null +++ b/tests/test_sql_register_renderer_git.py @@ -0,0 +1,2052 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Feature 007's test 5 and AT-C8: the renderer's git half and its push +(L2-G1; L2-G5's C8; AT-5; AT-C8; T270; FR-044, FR-045, FR-046, FR-059) +(opensoft/openRepoTools#165). + +T270 writes 25 tests: AT-5's 23 and AT-C8's one are here (TP:1016-1246, +TP:3173-3196, at the test plan `8702b70a`). Its 25th, test 1's part G, +`test_the_mirror_on_origin_equals_a_full_render_after_each_write`, is in +`test_sql_register_render.py`, which line W4b owns; it is not here. + +THE ESTATE (AT-5, "Fixture"; AT-C8, "Fixture"). Each case's database is +`pg_imported` (T227b): test 7's register imported at seq 0, the switch at +`files`. Its origin is a bare copy of the session's `imported_register` +origin, at C, so a case that pushes pushes to its own. The estate goes to +`primary` by AT-LR006's route (TP:4610-4615), as T304's own test does: a +`cutover` entry at seq 1 through `commit_write`, as REGISTER-WRITER, which +creates `lanes/STORE` with D21's fields; the marker commit, C plus that +`lanes/STORE` (SQL's own `render_file` of it), with `Register-Seq: 1`, +pushed to origin's `main` by hand; then `record_marker`. That is the open +point 27 form, "AT-5's `files` case pushes the marker commit by hand and +needs only the renderer's side", taken for `primary` too, so no case here +waits for lane 3's T327 (the cutover's own push). `n`, the head after the +cutover, is 1. Lane checkouts are clones of that origin, each with its own +`$HOME`, `workspace.yaml` naming a view of it, and `LANES_REPO` at it (test +7's `Workspace` form). That view is W. A lane whose writes fork the +renderer also has its own register checkout `<c>`, `<W>-lanes/<lane>/`, +made by `lanes-edit.sh lane-checkout <lane> --create`, since on primary +each write goes through it whatever `LANES_REPO` says, and its fork +renders there (T270e; `RenderEstate.own_checkout`). + +ENTRIES "WRITTEN THROUGH THE WRITE PATH" (TP:1055-1056) come two ways: +- by `commit_write` as REGISTER-WRITER, the write path's SQL half (T107), + where the case then starts the renderer itself, as a fork starts it, + `lanes-index render --checkout <c>` in a session of its own. Each of + these cases tests the renderer, never the writer or the fork; +- by `lanes-edit.sh log NOTED` on `primary` through T203's flipped copy, + whose fork starts the renderer (lane 4's T415 and T416, L4-B13), where + the oracle is about writers and forks (the writer- and fork-side cases, + at the end). + +TEST 5'S `git` WRAPPER (TP:1059-1082; open point 8, TP:8792-8812) is first +on the `PATH` of every `lanes-index` and `lanes-edit.sh` run here. It logs +each call as a JSON line: its subcommand, argv, pid, the pid above it (the +renderer) with that process's start time as `ps -o lstart=` gives it, the +repository it runs in, the time, and the environment's +`GIT_SSH_COMMAND`, `GIT_CONFIG_GLOBAL`, `GIT_CONFIG_NOSYSTEM`, +`SSH_AUTH_SOCK`, `LANES_NO_FETCH` and `GIT_INDEX_FILE`. Its arms, each on +one subcommand, and on one repository where `where` names it: `hold` on a +FIFO (re-armed per call, `times` bounding it); `kill`, SIGKILL to the +renderer's process group, after leaving `<GIT_INDEX_FILE>.lock` where +`index_lock` asks, as git inside `read-tree` leaves it; `fail`, exit 1; +`reject`, git's non-fast-forward refusal with exit 1, N times, then +disarmed; `stall`, a sleep before the real git. `render_only` limits an +arm to the calls of a `lanes-index render --checkout`, by the command line +of the process above the call (`ps -ww -o command=`), which the log keeps +as `render`, true or false. `redirect` sends a +`fetch` or `push` of a GitHub URL to the bare origin in its place. +Section 3.2's `psql` shim is beside it, handing every call to the +engine's own `psql` by its path. + +THE PATH: every directory of the caller's `PATH` is kept, in its place; one +that holds a `psql`, a `lanes-index` or a `pg_` name is swapped for a +private mirror without them (`_masked_path`, lane 2's mask policy, as LX's +T253e has it). The case's own `psql` is the shim, in the estate's `bin`. + +THE WAITS. A case that starts the renderer itself waits for its exit. A +render forked by a write is waited for by open point 8's two waits, and no +other: a poll of `status` every 100 ms until its lag is 0, under 30 s, +each poll after the harness's own fetch of the W `status` reads; or, +where the lag must stay above 0, a wait for every renderer pid the wrapper +logged after the write to exit. + +WHAT EACH FAILS UNTIL. Every case fails until lane 3's T320 to T323 (the +push, the lock and its handshake, the pass, its bounds); line R holds them +at `refs/l1/V-round4`. `test_six_lost_races_leave_the_last_write_for_the_ +next_write_or_reconcile`, which T325's verify selects by `reconcile`, also +fails until T325, at its own assertion: until then `reconcile` on `primary` +is T117's read-only check. The cases whose writes fork the renderer, at the end, +also fail until lane 4's T415 and T416 (L4-B13). Every case is RE: without +PostgreSQL 16 it skips with T205's banner. + +COPIED, NEVER SHARED (lane 2's rule for wave 12): `_masked_path` from line +LX's T253e (`tests/test_sql_register_landing_expired.py`); `_rows`, the +`Workspace` form of a lane checkout, and T203's flipped copy with +`lanes-edit.sh` beside it (`flipped_indexer`) from line W3a's +`tests/test_sql_register_import.py`; the cutover entry and the commit call +from line RB's `tests/test_sql_register_rollback.py`; `_open_when_held` +from the same; `_stats` from the import module. + +READINGS, NOT FOUND IN A CONTRACT: +- AT-LR006'S ROUTE to `primary`, and the marker commit pushed by hand, as + above. +- "WRITTEN THROUGH THE WRITE PATH" is read as the commit call alone where + the oracle is the renderer's, so those cases start the renderer + themselves. The six-lost-races case is one: the renderer that loses six + races is started as a fork starts it, for its one write. +- `reconcile` "in the given checkout" (B14 tasks:1531) is read as + `lanes-index reconcile` run in the lane's checkout, its workspace root, + with the `mode=primary` configuration, and no `--checkout`. +- AT DEPTH 0 "no `--skip`" (TP:1198-1199) is read as no page after the + first: the walk's one `log` call may say `--skip 0`, as line R's does. +- THE COMMIT'S MESSAGE: "each message equals its journal entry's" is read + through T322's form: the entry's message, then `Register-Seq: <k>`, in its + final trailer block where its last paragraph is one, or as a new last + paragraph after one blank line. +""" + +from __future__ import annotations + +import atexit +import hashlib +import json +import os +import re +import shlex +import shutil +import signal +import subprocess +import sys +import tempfile +import time +import uuid +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from conftest import REPO, WINDOWS_SKIP +from sql_register_helpers import PSQL_SHIM, PSQL_SHIM_CONTROL, PSQL_SHIM_LOG, flipped_copy + +pytestmark = [WINDOWS_SKIP, pytest.mark.skipif( + shutil.which("bash") is None or shutil.which("git") is None, + reason="the lane tooling is bash over git")] + +#: THE LANDING GATE'S TABLE (T280's reader, `tests/sql_register_gate.py`; T281 +#: removes it in the last set). Every id here waits for T270's own fails-until, +#: T320 to T323, T325 and L4-B13, which is lane 4's T415 (the author) and T416 +#: (the fork), and for T227, whose T227b makes `pg_imported` and +#: `pg_cluster.imported_register`, on which every case builds its estate +#: (`_estate`; lane 3, #165 6877365776, point 2). Lane 2's plan GP-24. +SQL_REGISTER_GATE_TABLE = { + "*": ("T227", "T320", "T321", "T322", "T323", "T325", "T415", "T416"), # every id: the tasks all its rows share +} + +LANES_EDIT = REPO / "lanes-edit.sh" +INDEXER = REPO / "lanes-index" + +#: The register's schema, and the role the commit call runs as. +SCHEMA = "lanes_register" +WRITER_ROLE = "lanes_register_writer" + +#: Test 7's operator lane, and the two lanes whose checkouts race: `repoW-1` +#: and `repoD-1` are LIVE rows of test 7's register. `OPERATOR` is T227b's +#: `TEST7_OPERATOR` in `tests/pgcluster.py`, written out here: a name imported +#: from there at module level fails this module's collection wherever T227 has +#: not landed, and no landing gate skips a collection error (lane 3, #165 +#: 6877365776, point 2). Each case checks that the two agree +#: (`_operator_is_test7s`). +OPERATOR = "repoA-2" +L1, L2 = "repoW-1", "repoD-1" +WS = "Eagle" +AUTHOR = "T270 writer <t270@example.invalid>" +OPERATOR_AUTHOR = "T270 operator <t270-operator@example.invalid>" +NOT_AFTER = "2100-01-01T00:00:00Z" +ARGS_SHA256 = "a" * 64 +STORE_UTC = "2026-11-11T10:00:00Z" +#: The file the commit-call entries append to. +APPENDED = "lanes/LANES.md" + +#: A commit's `Register-Seq` trailer, `status`'s lag at `primary`, and its +#: divergence and failed-pass lines (lane 1's T117; line R). +REGISTER_SEQ = re.compile(r"^Register-Seq: ([0-9]+)$", re.M) +LAG = re.compile(r"^\s*lag:\s+([0-9]+) seq", re.M) +DIVERGED = re.compile(r"diverged at ([0-9a-f]{40})") +FAILED_PASS = re.compile(r"^\s*renderer:\s+its last failed pass", re.M) + +#: Open point 8's ceiling and poll. +CEILING, POLL = 30.0, 0.1 + +#: The GitHub repository the deploy-key case names, by HTTPS and by SSH. +GITHUB_REPO = "opensoft/t270-mirror" +GITHUB_HTTPS = f"https://github.com/{GITHUB_REPO}.git" +GITHUB_SSH = f"ssh://git@github.com/{GITHUB_REPO}.git" + +#: The environment no case inherits. +DROPPED = ("LANES_", "CLAUDE_", "WORKBENCHES_", "TMUX", "XDG_", "PG", "AGENT_PROTOCOL_ROOT", + "PROJECTS_", "GIT_", "SSH_", "FAKE_PSQL", "RULE6_", "OPENREPOTOOLS_") + +#: The subcommands that would rewrite history, which no render may run. +REWRITES = ("rebase", "pull", "cherry-pick", "am", "reset", "merge", "commit") + + +# ------------------------------------------------------------------ the PATH mask +#: `_masked_path`'s mirrors, by each directory's real path (None where the +#: directory holds no masked name), and the one temporary root they share. +#: Copied from line LX's T253e. +_PATH_MIRRORS: dict = {} +_PATH_MIRROR_ROOT: list = [] + + +def _masked_path() -> str: + """The caller's PATH with every directory kept in its place, and each one + that holds a `psql`, a `lanes-index` or a name that starts `pg_` swapped + for a private mirror of it: a directory of links, one to each of its + entries by its absolute path, those names left out. An installed + indexer, a real `psql` or one of the `pg_` client wrappers shipped beside + it is never what a case runs, but the tools beside them are: on a GitHub + runner `postgresql-16`'s client puts `psql` in `/usr/bin` with `git` and + `bash` (and `/bin` is a link to it), so dropping the directory dropped + `git` and `bash` too (lane 1's census, #165 6807454856). A directory that + holds none of those names passes through unchanged. Each mirror is made + once per process, under one `mkdtemp` that an `atexit` handler removes.""" + parts = [] + for part in os.environ.get("PATH", "").split(os.pathsep): + if not part: + continue + real = os.path.realpath(part) + if real not in _PATH_MIRRORS: + try: + names = os.listdir(real) + except OSError: + names = [] + masked = {name for name in names + if name in ("psql", "lanes-index") or name.startswith("pg_")} + mirror = None + if masked: + if not _PATH_MIRROR_ROOT: + _PATH_MIRROR_ROOT.append(tempfile.mkdtemp(prefix="l2-pathmask-")) + atexit.register(shutil.rmtree, _PATH_MIRROR_ROOT[0], ignore_errors=True) + mirror = os.path.join(_PATH_MIRROR_ROOT[0], str(len(_PATH_MIRRORS))) + os.mkdir(mirror) + for name in names: + if name not in masked: + os.symlink(os.path.join(real, name), os.path.join(mirror, name)) + _PATH_MIRRORS[real] = mirror + parts.append(_PATH_MIRRORS[real] or part) + return os.pathsep.join(parts) + + +# ------------------------------------------------------------------ small helpers +def _script(path: Path, text: str) -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + path.chmod(0o755) + return path + + +def _private(path: Path, text: str) -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + path.chmod(0o600) + return path + + +def _said(proc) -> str: + return (f"exit {proc.returncode}\n--- stdout ---\n{(proc.stdout or '')[-3000:]}" + f"\n--- stderr ---\n{(proc.stderr or '')[-3000:]}") + + +def _jsonl(path: Path) -> list: + if not path.exists(): + return [] + return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line] + + +def _sha256(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def _stats(samples: list) -> dict: + """Section 5.3's statistics: median and p95 by nearest rank, min-max, n. + Copied from the import module.""" + ordered = sorted(samples) + rank = lambda p: ordered[max(0, -(-p * len(ordered) // 100) - 1)] # noqa: E731 + return {"median": rank(50), "p95": rank(95), "min": ordered[0], "max": ordered[-1], + "n": len(ordered)} + + +def _open_when_held(fifo: Path, proc: subprocess.Popen, seconds: float = 120): + """The FIFO's write end, opened once a reader holds a call on it; None + where `proc` ends, or the time runs out, first. Closing it releases the + call. Copied from line RB's rollback module.""" + deadline = time.monotonic() + seconds + while time.monotonic() < deadline and proc.poll() is None: + try: + return os.open(str(fifo), os.O_WRONLY | os.O_NONBLOCK) + except OSError: + time.sleep(0.05) + return None + + +def _lock_is_free(path: Path) -> bool: + """A non-blocking `flock` on `path` succeeds (D14; [L4-4]).""" + import fcntl + fd = os.open(str(path), os.O_RDWR | os.O_CREAT, 0o600) + try: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + except OSError: + return False + else: + fcntl.flock(fd, fcntl.LOCK_UN) + return True + finally: + os.close(fd) + + +def _flipped(directory: Path) -> Path: + """T203's flipped copy, `RENDER_GIT_HALF = True`, with `lanes-edit.sh` + and `repos.tsv` beside it (the copy rule, CLI4.5 section 6), so a + `mode=primary` configuration loads and a render runs. Copied from line + W3a's `flipped_indexer`.""" + copy = flipped_copy(INDEXER, directory, True) + for name in ("lanes-edit.sh", "repos.tsv"): + if (REPO / name).exists(): + shutil.copy2(REPO / name, copy.parent / name) + return copy + + +# ------------------------------------------------------------------ the wrapper +GIT_WRAPPER = r'''#!/usr/bin/env -S python3 -I +# TEST 5'S `git` WRAPPER (TP:1059-1082; open point 8, TP:8792-8812), first on +# the renderer's PATH, standard library only. Each call is one JSON line of +# git-wrapper.log beside it; git-wrapper.json beside it holds `git` (the real +# git, by its path), `arms` and `redirect`. +import fcntl, json, os, signal, subprocess, sys, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +CONTROL = os.path.join(HERE, "git-wrapper.json") +LOG = os.path.join(HERE, "git-wrapper.log") +STATE = os.path.join(HERE, "git-wrapper.state") +WITH_VALUE = {"-C", "-c", "--git-dir", "--work-tree", "--namespace", "--exec-path", + "--config-env"} +ENV_KEYS = ("GIT_SSH_COMMAND", "GIT_CONFIG_GLOBAL", "GIT_CONFIG_NOSYSTEM", "SSH_AUTH_SOCK", + "LANES_NO_FETCH", "GIT_INDEX_FILE") +NETWORK = ("fetch", "push", "ls-remote", "pull") + + +def subcommand(args): + i = 0 + while i < len(args): + if args[i] in WITH_VALUE: + i += 2 + elif args[i].startswith("-"): + i += 1 + else: + return args[i] + return "" + + +def where(args): + """The repository the call runs in: its cwd, moved by each `-C`.""" + found = os.getcwd() + i = 0 + while i < len(args): + if args[i] == "-C" and i + 1 < len(args): + found = os.path.join(found, args[i + 1]) + i += 2 + elif args[i] in WITH_VALUE: + i += 2 + elif args[i].startswith("-"): + i += 1 + else: + break + return os.path.realpath(found) + + +def started(pid): + try: + out = subprocess.run(["ps", "-o", "lstart=", "-p", str(pid)], capture_output=True, + text=True, timeout=10).stdout + except (OSError, subprocess.SubprocessError): + return "" + return " ".join(out.split()) + + +def is_render(pid): + """Whether the process above the call is a `lanes-index render + --checkout`, by its command line; only that answer is kept.""" + try: + out = subprocess.run(["ps", "-ww", "-o", "command=", "-p", str(pid)], + capture_output=True, text=True, timeout=10).stdout + except (OSError, subprocess.SubprocessError): + return False + return " render --checkout " in " %s " % " ".join(out.split()) + + +def log(record): + with open(LOG, "a", encoding="utf-8") as handle: + fcntl.flock(handle, fcntl.LOCK_EX) + handle.write(json.dumps(record) + "\n") + handle.flush() + + +def take(index, times): + """Whether arm `index` takes this call: a count per arm, under a lock; + `times` below 0 takes every call.""" + with open(STATE, "a+", encoding="utf-8") as handle: + fcntl.flock(handle, fcntl.LOCK_EX) + handle.seek(0) + text = handle.read() + counts = json.loads(text) if text.strip() else {} + used = counts.get(str(index), 0) + if times >= 0 and used >= times: + return False + counts[str(index)] = used + 1 + handle.seek(0) + handle.truncate() + handle.write(json.dumps(counts)) + return True + + +def applies(arm, sub, args, here, render): + if arm.get("sub") != sub: + return False + if arm.get("where") and os.path.realpath(arm["where"]) != here: + return False + if arm.get("has") and arm["has"] not in args: + return False + if arm.get("render_only") and not render: + return False + return True + + +def main(): + args = sys.argv[1:] + with open(CONTROL, encoding="utf-8") as handle: + control = json.load(handle) + sub = subcommand(args) + here = where(args) + parent = os.getppid() + record = {"sub": sub, "argv": args, "pid": os.getpid(), "renderer": parent, + "renderer_start": started(parent), "render": is_render(parent), "where": here, + "env": {key: os.environ.get(key) for key in ENV_KEYS}, "t0": time.time()} + for index, arm in enumerate(control.get("arms", [])): + if (not applies(arm, sub, args, here, record["render"]) + or not take(index, arm.get("times", -1))): + continue + do = arm["do"] + if do == "hold": + log(dict(record, outcome="held")) + with open(arm["fifo"], "rb") as fifo: + fifo.read() + elif do == "stall": + log(dict(record, outcome="stalled")) + time.sleep(float(arm.get("seconds", 5))) + elif do == "fail": + log(dict(record, outcome="failed", rc=1)) + sys.stderr.write("fatal: the test's git wrapper fails this %s\n" % sub) + return 1 + elif do == "reject": + log(dict(record, outcome="rejected", rc=1)) + refspec = next((a for a in reversed(args) if ":" in a and not a.startswith("-")), + "HEAD") + dest = args[args.index(refspec) - 1] if refspec in args else "origin" + if "--porcelain" in args: + sys.stdout.write("To %s\n!\t%s\t[rejected] (non-fast-forward)\nDone\n" + % (dest, refspec)) + sys.stderr.write(" ! [rejected] %s (non-fast-forward)\nerror: failed to " + "push some refs to '%s'\nhint: Updates were rejected because " + "the remote contains work that you do not have locally.\n" + % (refspec, dest)) + return 1 + elif do == "kill": + index_file = os.environ.get("GIT_INDEX_FILE") + if arm.get("index_lock") and index_file: + open(index_file + ".lock", "a").close() + log(dict(record, outcome="killed")) + # The renderer's own group where it leads one (a detached fork, or + # a case's render in a session of its own); else the renderer + # alone. Each git call runs in a group of its own (`_run_bounded`), + # so this call, which stands for git, then ends itself. + if os.getpgid(parent) == parent: + os.killpg(parent, signal.SIGKILL) + else: + os.kill(parent, signal.SIGKILL) + os.kill(os.getpid(), signal.SIGKILL) + return 137 + command = [control["git"]] + redirect = control.get("redirect") or {} + if sub in NETWORK: + for url, path in sorted(redirect.items()): + command += ["-c", "url.%s.insteadOf=%s" % (path, url)] + args = [redirect.get(arg, arg) for arg in args] + ran = time.time() + rc = subprocess.run(command + args).returncode + log(dict(record, outcome="ran", rc=rc, ran=ran, t1=time.time())) + return rc + + +sys.exit(main()) +''' + +#: Test 4's start barrier (TP:886-888): the launcher blocks on the FIFO it is +#: given until the test opens and closes it, then becomes the command. +LAUNCH = r'''#!/usr/bin/env -S python3 -I +import os, sys +with open(sys.argv[1], "rb") as fifo: + fifo.read() +os.execv(sys.argv[2], sys.argv[2:]) +''' + + +def _rows(db, sql: str) -> list: + """`sql`'s rows as JSON objects, read in the register's schema, by + `jsonb_agg`, whose text is one line. Copied from the import module.""" + out = db.psql(f"SET search_path TO {SCHEMA};\n" + f"SELECT coalesce(jsonb_agg(t), '[]'::jsonb) FROM ({sql}) t;\n").stdout + return json.loads(out.strip().splitlines()[-1]) + + +# ------------------------------------------------------------------ the estate +class RenderEstate: + """TEST 5'S ESTATE: see the module's docstring. `stage` is `primary` (the + default), `imported` (seq 0, the switch at `files`) or `empty` (no + journal, on `pg`). At `primary`, `marker` is `pushed`, or `recorded` for + a marker commit `record_marker` names that is not on origin's `main`.""" + + def __init__(self, root: Path, db, cluster, *, stage: str = "primary", + marker: str = "pushed"): + assert stage in ("primary", "imported", "empty"), stage + source = cluster.imported_register + if source is None: + pytest.fail(f"no imported register on the session cluster: " + f"{cluster.imported_problem}", pytrace=False) + self.root, self.db, self.stage = root, db, stage + root.mkdir(parents=True, exist_ok=True) + masked = _masked_path() + self.real_git = shutil.which("git", path=masked) + assert self.real_git, "no git on PATH" + self.bin, self.fakebin = root / "bin", root / "fakebin" + _script(self.bin / "git", GIT_WRAPPER) + _script(self.bin / "psql", PSQL_SHIM) + _script(self.bin / "launch", LAUNCH) + _script(self.fakebin / "tmux", "#!/bin/sh\nexit 1\n") + self.copy = _flipped(root / "flip") + env = {k: v for k, v in os.environ.items() if not k.startswith(DROPPED)} + env.update(TMPDIR=str(root / "tmp"), LANES_WORKSTATION=WS, LANES_HOST="eagle", + LANES_OS="linux", LANES_CONTAINER="none", LANES_IN_CONTAINER="0", + LANES_NO_GITHUB="1", LANES_EDIT=str(self.copy.parent / "lanes-edit.sh"), + GIT_AUTHOR_NAME="T270 estate", GIT_AUTHOR_EMAIL="t270@example.invalid", + GIT_COMMITTER_NAME="T270 estate", GIT_COMMITTER_EMAIL="t270@example.invalid", + PATH=os.pathsep.join([str(self.bin), str(self.fakebin), masked])) + (root / "tmp").mkdir(exist_ok=True) + self.env = env + #: The test's own git calls: the real git, no wrapper on PATH. + self.plain_env = dict(env, PATH=os.pathsep.join([str(self.fakebin), masked])) + self.arm() + self.c = source.c + self.origin = root / "origin.git" + self.git(None, "clone", "-q", "--bare", str(source.origin), str(self.origin)) + assert self.origin_tip() == self.c, "the imported register's origin is not at C" + self.label = self.switch()["database_label"] + self.conf_dir = root / "conf" + self.passfile = _private(self.conf_dir / "empty.pgpass", "") + self.index_conf = self.config("index", "index") + self.primary_conf = self.config("primary", "primary") + self.checkouts: dict = {} + head = self.head() + if stage == "empty": + assert head == -1, f"`pg`'s journal is not empty: head {head}" + else: + assert head == 0 and self.switch()["mode"] == "files", ( + f"`pg_imported` is not test 7's register at seq 0 at files: head {head}, " + f"switch {self.switch()}") + self.n = head + self.marker = None + if stage == "primary": + self._to_primary(marker) + + # ------------------------------------------------------------ git + def git(self, cwd, *args: str, env: dict | None = None, data: bytes | None = None) -> str: + proc = subprocess.run([self.real_git, *args], cwd=str(cwd) if cwd else None, + env=env or self.plain_env, input=data, capture_output=True, + timeout=300, check=False) + assert proc.returncode == 0, (f"git {' '.join(args[:4])}: " + f"{proc.stderr.decode('utf-8', 'replace')[-800:]}") + return proc.stdout.decode("utf-8", "replace") + + def origin_git(self, *args: str, env: dict | None = None, data: bytes | None = None, + origin: Path | None = None) -> str: + """git in a bare origin itself, so no clone's refs move.""" + return self.git(None, f"--git-dir={origin or self.origin}", *args, env=env, data=data) + + def origin_tip(self, origin: Path | None = None) -> str: + return self.origin_git("rev-parse", "refs/heads/main", origin=origin).strip() + + def commit_in_origin(self, parent: str, files: dict, message: str, + origin: Path | None = None) -> str: + """A commit on `parent` with `files` ({path: bytes}) changed, made in + the bare origin through an index of its own; no ref moves.""" + index = self.root / f"build-{uuid.uuid4().hex[:8]}.index" + env = dict(self.plain_env, GIT_INDEX_FILE=str(index)) + self.origin_git("read-tree", parent, env=env, origin=origin) + for path, data in files.items(): + blob = self.origin_git("hash-object", "-w", "--stdin", data=data, origin=origin).strip() + self.origin_git("update-index", "--add", "--cacheinfo", f"100644,{blob},{path}", + env=env, origin=origin) + tree = self.origin_git("write-tree", env=env, origin=origin).strip() + return self.origin_git("commit-tree", tree, "-p", parent, data=message.encode("utf-8"), + origin=origin).strip() + + def push_by_hand(self, commit: str, origin: Path | None = None) -> None: + """Origin's `main` moved to `commit`, a fast-forward, as a push makes it.""" + old = self.origin_tip(origin) + self.origin_git("merge-base", "--is-ancestor", old, commit, origin=origin) + self.origin_git("update-ref", "refs/heads/main", commit, old, origin=origin) + + def second_origin(self, name: str) -> Path: + """A bare copy of origin as it stands.""" + path = self.root / f"{name}.git" + self.git(None, "clone", "-q", "--bare", str(self.origin), str(path)) + return path + + def commits_after(self, old: str, origin: Path | None = None) -> list: + """[(sha, its Register-Seq values, its raw message)] on origin's + `main`'s first-parent line after `old`, oldest first.""" + out = self.origin_git("rev-list", "--reverse", "--first-parent", + f"{old}..refs/heads/main", origin=origin) + found = [] + for sha in out.split(): + raw = self.origin_git("cat-file", "commit", sha, origin=origin) + message = raw.split("\n\n", 1)[1] if "\n\n" in raw else "" + found.append((sha, [int(s) for s in REGISTER_SEQ.findall(message)], message)) + return found + + def identity(self, sha: str, origin: Path | None = None) -> dict: + out = self.origin_git("log", "-1", "--format=%an <%ae>%x00%at%x00%cn <%ce>%x00%ct", sha, + origin=origin).rstrip("\n").split("\0") + return {"author": out[0], "author_epoch": int(out[1]), "committer": out[2], + "committer_epoch": int(out[3])} + + def form_c(self, sha: str, origin: Path | None = None) -> str: + """Form C on one commit, with the walk's pins (Y:2843-2847).""" + out = self.origin_git("-c", "trailer.separators=:", "-c", "core.commentChar=#", + "log", "-n", "1", + "--format=%(trailers:key=Register-Seq,valueonly)", sha, + origin=origin) + return next((line.strip() for line in out.split("\n") if line.strip()), "") + + # ------------------------------------------------------------ the database + def rows(self, sql: str) -> list: + return _rows(self.db, sql) + + def sql(self, script: str, role: str | None = None) -> subprocess.CompletedProcess: + head = f"SET search_path TO {SCHEMA};\n" + (f"SET ROLE {role};\n" if role else "") + return self.db.psql(head + script, check=False) + + def head(self) -> int: + return self.rows("SELECT seq FROM register_head")[0]["seq"] + + def window(self) -> int: + return self.rows("SELECT version FROM schema_version")[0]["version"] + + def switch(self) -> dict: + return self.rows("SELECT * FROM register_switch")[0] + + def mirror(self) -> dict: + return self.rows("SELECT * FROM mirror_state")[0] + + def journal(self, after: int = -1) -> list: + return self.rows(f"SELECT seq, kind, message, author, " + f"extract(epoch FROM utc)::bigint AS epoch FROM journal " + f"WHERE seq > {after} ORDER BY seq") + + def render_sql(self, path: str) -> bytes: + """SQL's own render of `path` at the head (lane 1's T107).""" + quoted = path.replace("'", "''") + rows = self.rows(f"SELECT encode(render_file('{quoted}'), 'hex') AS hex") + return bytes.fromhex(rows[0]["hex"]) + + def commit_entries(self, bodies: list) -> list: + """THE COMMIT CALL, as a writer sends it (section 1.3's step 3): one + SERIALIZABLE transaction around `commit_write` per entry, as + REGISTER-WRITER, in one `psql`. Returns the entries' seqs.""" + head, window = self.head(), self.window() + generation = self.switch()["generation"] + script = [] + for n, body in enumerate(bodies): + literal = json.dumps(body, ensure_ascii=True).replace("'", "''") + script += ["BEGIN ISOLATION LEVEL SERIALIZABLE;", + f"SELECT commit_write({head + n}, '{uuid.uuid4()}'::uuid, {window}, " + f"'{generation}'::uuid, '{literal}'::jsonb);", "COMMIT;"] + proc = self.sql("\n".join(script) + "\n", WRITER_ROLE) + assert proc.returncode == 0, f"commit_write refused an entry: {proc.stderr[-1500:]}" + seqs = [int(word) for word in proc.stdout.split()] + assert seqs == list(range(head + 1, head + 1 + len(bodies))), ( + f"the commit calls answered {seqs}, not {head + 1} to {head + len(bodies)}") + return seqs + + def write_sql(self, texts: list, *, lane: str = L1, messages: list | None = None) -> list: + """One write entry per text, each appending it to `APPENDED`, through + the commit call alone (no fork). Returns their seqs.""" + data = self.render_sql(APPENDED) + assert data.endswith(b"\n"), f"SQL's {APPENDED} does not end with a newline" + bodies = [] + for n, text in enumerate(texts): + data += text.encode("utf-8") + b"\n" + bodies.append({ + "journal": {"kind": "write", "verb": "log", "lane": lane, "workstation": WS, + "author": AUTHOR, "args_sha256": ARGS_SHA256, + "message": messages[n] if messages else f"t270: {text}"}, + "not_after": NOT_AFTER, + "edits": [{"ord": 1, "op": "append", "path": APPENDED, "new_text": text}], + "files": [{"path": APPENDED, "present": True, "sha256": _sha256(data), + "final_newline": True}]}) + return self.commit_entries(bodies) + + def _to_primary(self, marker: str) -> None: + """AT-LR006'S ROUTE (TP:4610-4615): the cutover entry at seq 1, the + marker commit pushed by hand (or only recorded), `record_marker`.""" + tree = self.origin_git("rev-parse", f"{self.c}:lanes").strip() + lines = ("store=primary", f"database={self.label}", f"import={self.c}", + f"lanes-tree={tree}", f"utc={STORE_UTC}") + data = ("\n".join(lines) + "\n").encode("utf-8") + message = "t270: the cutover, by AT-LR006's route" + edits = [{"ord": 1, "op": "create", "path": "lanes/STORE"}] + edits += [{"ord": n, "op": "append", "path": "lanes/STORE", "new_text": line} + for n, line in enumerate(lines, start=2)] + (cut,) = self.commit_entries([{ + "journal": {"kind": "cutover", "verb": "cutover", "lane": OPERATOR, + "workstation": WS, "author": OPERATOR_AUTHOR, "message": message}, + "not_after": NOT_AFTER, "edits": edits, + "files": [{"path": "lanes/STORE", "present": True, "sha256": _sha256(data), + "final_newline": True}]}]) + assert cut == 1, f"the cutover entry took seq {cut}, not 1" + assert self.render_sql("lanes/STORE") == data, "SQL renders lanes/STORE otherwise" + self.marker = self.commit_in_origin(self.c, {"lanes/STORE": data}, + f"{message}\n\nRegister-Seq: {cut}\n") + if marker == "pushed": + self.push_by_hand(self.marker) + proc = self.sql(f"SELECT record_marker({self.window()}, {cut}, '{self.marker}', " + f"'{WS}');", WRITER_ROLE) + assert proc.returncode == 0 and proc.stdout.strip() == "present", ( + f"record_marker answered {proc.stdout.strip()!r}: {proc.stderr[-800:]}") + switch = self.switch() + assert (switch["mode"], switch["marker_state"]) == ("primary", "present"), switch + self.n = cut + + # ------------------------------------------------------------ configuration + def config(self, name: str, mode: str, extra=()) -> Path: + """A 0600 `lanes-index.conf` outside every work tree: `mode`, the two + URLs on the cluster's socket as its own user, an empty password file, + the switch's label and the schema, and `extra` lines.""" + lines = [f"mode={mode}", f"register_url={self.db.url()}", + f"register_passfile={self.passfile}", f"reader_url={self.db.url()}", + f"reader_passfile={self.passfile}", f"register_label={self.label}", + f"register_schema={SCHEMA}", *extra] + return _private(self.conf_dir / name / "lanes-index.conf", "\n".join(lines) + "\n") + + # ------------------------------------------------------------ lane checkouts + def checkout(self, name: str, lane: str = L1, *, origin: Path | None = None, + repository: str | None = None, own: bool = False) -> SimpleNamespace: + """A lane's register checkout, a clone of `origin`, in test 7's + `Workspace` form: its own `$HOME`, W a view of the clone that + `workspace.yaml` names (with `repository:` `repository`, origin's + path by default), and `LANES_REPO` at the clone. With `own`, for a + lane whose writes fork the renderer, also the lane's own register + checkout `<c>` (`own_checkout`), as `.own`.""" + root = self.root / name + home = root / "home" + agents = home / ".agents" + agents.mkdir(parents=True) + clone = home / "projects" / "wip" + self.git(None, "clone", "-q", str(origin or self.origin), str(clone)) + view = root / "ro" / "wip" + view.mkdir(parents=True) + (view / ".git").write_text(f"gitdir: {os.path.realpath(clone / '.git')}\n", + encoding="utf-8") + (view / "lanes").symlink_to(clone / "lanes") + (agents / "workspace.yaml").write_text( + f"repository: {repository or (origin or self.origin)}\npath: {view}\n", + encoding="utf-8") + for d in ("state", "config", "tmp"): + (root / d).mkdir() + env = dict(self.env, HOME=str(home), AGENT_PROTOCOL_ROOT=str(agents), + XDG_STATE_HOME=str(root / "state"), XDG_CONFIG_HOME=str(root / "config"), + TMPDIR=str(root / "tmp"), CLAUDE_CONFIG_DIR=str(home / ".claude"), + LANES_REPO=str(clone), LANES_LANE=lane) + lane_checkout = SimpleNamespace(name=name, lane=lane, root=root, home=home, clone=clone, + git_dir=clone / ".git", env=env, w=view, own=None) + if own: + lane_checkout.own = self.own_checkout(lane_checkout) + self.checkouts[name] = lane_checkout + return lane_checkout + + def own_checkout(self, lc) -> SimpleNamespace: + """THE LANE'S OWN REGISTER CHECKOUT ON PRIMARY, `<c>`, `<W>-lanes/<lane>/` + (T270e), made by `lanes-edit.sh lane-checkout <lane> --create` through the + flipped copy, as line G's T254s makes it for each primary lane. The estate makes + `<c>` itself, because `lane-start` makes it only under `LANES_ROUTE_WRITES=1` + with neither `LANES_REPO` nor `LANES_FILE` set (lane 3, #165 6841265575; + `dfc4ce4c:lane-start:1209-1210`). + + WHY: on primary, T415's `pw_checkout` takes each write's checkout from + `lane_checkout_path`, `<W>-lanes/<lane>`, and `LANES_REPO` never enters it + (lane 4, #165 6840794493: `a38af255:lanes-edit.sh:6273`, `:20738`, `:1673-1674`). + Where it is not there, the write refuses 2 and nothing is sent. The write's fork + then renders there, `render --checkout "$PW_C"` (`pw_render_fork`). So the + render's calls, lock and marks are `<c>`'s. The clone is a fetch, so + `LANES_NO_FETCH` is left out. Returns `<c>`'s `clone` and `git_dir`.""" + proc = subprocess.run(["bash", str(self.copy.parent / "lanes-edit.sh"), "lane-checkout", + lc.lane, "--create"], cwd=str(lc.clone), + env=self.lane_env(lc, None, {"LANES_NO_FETCH": None}), + capture_output=True, text=True, timeout=300, + stdin=subprocess.DEVNULL, check=False) + assert proc.returncode == 0, f"lane-checkout {lc.lane} --create:\n{_said(proc)}" + c = Path(proc.stdout.strip().splitlines()[-1]) + expected = Path(os.path.realpath(lc.w) + "-lanes") / lc.lane + assert c == expected and c.is_dir(), ( + f"lane-checkout {lc.lane} --create made {c}, not {expected}:\n{_said(proc)}") + git_dir = Path(self.git(c, "rev-parse", "--absolute-git-dir").strip()) + return SimpleNamespace(clone=c, git_dir=git_dir) + + def snapshot(self, lc) -> dict: + """The checkout's HEAD, index digest and `status --porcelain`, the + index read first and `status` run with no optional lock, so this + read never rewrites the index it digests.""" + index = _sha256((lc.git_dir / "index").read_bytes()) + return {"head": self.git(lc.clone, "rev-parse", "HEAD").strip(), "index": index, + "status": self.git(lc.clone, "--no-optional-locks", "status", "--porcelain")} + + # ------------------------------------------------------------ the wrapper and the shim + def arm(self, arms=(), redirect: dict | None = None, shim_arms=()) -> None: + """The wrapper's arms and the shim's, each log and count started + afresh.""" + for name in ("git-wrapper.log", "git-wrapper.state", PSQL_SHIM_LOG, "psql-shim.ends"): + (self.bin / name).write_text("", encoding="utf-8") + (self.bin / "psql-shim.state").write_text("{}", encoding="utf-8") + control = {"git": self.real_git, "arms": list(arms), "redirect": redirect or {}} + (self.bin / "git-wrapper.json").write_text(json.dumps(control), encoding="utf-8") + (self.bin / PSQL_SHIM_CONTROL).write_text( + json.dumps({"psql": self.db.psql_bin, "arms": list(shim_arms)}), encoding="utf-8") + + def calls(self, sub: str | None = None, lc=None) -> list: + """The wrapper's log, in order: each call that ran, or that an arm + took, once (its `ran` line, else its arm's line).""" + entries = _jsonl(self.bin / "git-wrapper.log") + ran = {e["pid"] for e in entries if e.get("outcome") == "ran"} + kept = [e for e in entries if e.get("outcome") == "ran" or e["pid"] not in ran] + if sub is not None: + kept = [e for e in kept if e["sub"] == sub] + if lc is not None: + kept = [e for e in kept if e["where"] == os.path.realpath(lc.clone)] + return kept + + # ------------------------------------------------------------ the commands + def lane_env(self, lc, conf: Path | None, env: dict | None) -> dict: + child = dict(lc.env, LANES_INDEX_CONFIG=str(conf or self.primary_conf)) + for key, value in (env or {}).items(): + if value is None: + child.pop(key, None) + else: + child[key] = value + return child + + def render_argv(self, lc) -> list: + return [sys.executable, str(self.copy), "render", "--checkout", str(lc.clone)] + + def render(self, lc, *, conf: Path | None = None, env: dict | None = None, + timeout: float = 300) -> subprocess.CompletedProcess: + """`lanes-index render --checkout <c>`, as a fork starts it: in a + session of its own, through the flipped copy, with the `mode=primary` + configuration. Waited for to its exit.""" + return subprocess.run(self.render_argv(lc), cwd=str(lc.clone), + env=self.lane_env(lc, conf, env), capture_output=True, text=True, + timeout=timeout, stdin=subprocess.DEVNULL, start_new_session=True, + check=False) + + def popen_render(self, lc, *, conf: Path | None = None, env: dict | None = None, + argv: list | None = None) -> subprocess.Popen: + return subprocess.Popen(argv or self.render_argv(lc), cwd=str(lc.clone), + env=self.lane_env(lc, conf, env), text=True, + stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, start_new_session=True) + + def index(self, lc, *args: str, conf: Path | None = None, env: dict | None = None, + timeout: float = 300) -> subprocess.CompletedProcess: + """Another `lanes-index` command in the lane's checkout.""" + return subprocess.run([sys.executable, str(self.copy), *args], cwd=str(lc.clone), + env=self.lane_env(lc, conf or self.index_conf, env), + capture_output=True, text=True, timeout=timeout, + stdin=subprocess.DEVNULL, check=False) + + def status(self, lc) -> subprocess.CompletedProcess: + """`lanes-index status` in the lane's checkout: its lag is `n` less + the `m` origin's `main` carried as last fetched there.""" + return self.index(lc, "status") + + def lag(self, lc) -> int | None: + found = LAG.search(self.status(lc).stdout) + return int(found.group(1)) if found else None + + def race(self, checkouts: list, *, conf: Path | None = None) -> list: + """Test 4's barrier (TP:886-888, TP:1083): one renderer per checkout, + each launched blocking on a FIFO of its own, released together once + all are waiting. Returns each one's (returncode, stdout, stderr).""" + procs, fifos = [], [] + for lc in checkouts: + fifo = self.root / f"barrier-{lc.name}.fifo" + os.mkfifo(str(fifo), 0o600) + fifos.append(fifo) + procs.append(self.popen_render(lc, conf=conf, argv=[ + sys.executable, "-I", str(self.bin / "launch"), str(fifo), *self.render_argv(lc)])) + fds = [] + try: + for fifo, proc in zip(fifos, procs): + fd = _open_when_held(fifo, proc) + assert fd is not None, f"a launcher never waited on {fifo}" + fds.append(fd) + finally: + for fd in fds: + os.close(fd) + ended = [] + for proc in procs: + out, err = proc.communicate(timeout=300) + ended.append(SimpleNamespace(returncode=proc.returncode, stdout=out, stderr=err)) + return ended + + # ------------------------------------------------------------ writes that fork + def rearm(self, arms=()) -> None: + """The wrapper's arms changed, its log and counts kept.""" + control = json.loads((self.bin / "git-wrapper.json").read_text(encoding="utf-8")) + control["arms"] = list(arms) + (self.bin / "git-wrapper.json").write_text(json.dumps(control), encoding="utf-8") + + def edit(self, lc, *args: str, env: dict | None = None, + timeout: float = 300) -> subprocess.CompletedProcess: + """`lanes-edit.sh <args>` in the lane's checkout, as its lane, through + the flipped copy's `lanes-edit.sh`, with the `mode=primary` + configuration: a write on `primary`, which forks the renderer (lane + 4's T415 and T416).""" + return subprocess.run(["bash", str(self.copy.parent / "lanes-edit.sh"), *args], + cwd=str(lc.clone), env=self.lane_env(lc, None, env), + capture_output=True, text=True, timeout=timeout, + stdin=subprocess.DEVNULL, check=False) + + def write(self, lc, text: str, env: dict | None = None, + timeout: float = 300) -> subprocess.CompletedProcess: + """One `log NOTED lane:<L> <text>` from the lane's checkout.""" + return self.edit(lc, "log", "NOTED", f"lane:{lc.lane}", text, env=env, timeout=timeout) + + def entries(self) -> int: + """The wrapper log's length, the mark a wait starts after.""" + return len(_jsonl(self.bin / "git-wrapper.log")) + + def render_calls(self, after: int = 0) -> list: + """The calls a `lanes-index render --checkout` made, logged after the + mark `after`, each once.""" + entries = _jsonl(self.bin / "git-wrapper.log")[after:] + ran = {e["pid"] for e in entries if e.get("outcome") == "ran"} + return [e for e in entries if e.get("render") + and (e.get("outcome") == "ran" or e["pid"] not in ran)] + + def wait_lag_0(self, lc, what: str) -> None: + """OPEN POINT 8'S FIRST WAIT: `status` every 100 ms until its lag is + 0, under 30 s, each poll after the harness's fetch of the W `status` + reads (T270e; lane 3's ruling (a), #165 6833830078): + `git -C <W> fetch -q origin main`, with plain git, never through the + wrapper. `status` reads `m` on W's `origin/main` as last fetched and + never fetches, no write on primary fetches (D12), and the + render pushes from the lane's `<c>`. The fetch is the harness's own + act, not a write's, as the drill's `wait_lag_0` has it (DR's + T276f).""" + deadline = time.monotonic() + CEILING + while True: + self.git(lc.w, "fetch", "-q", "origin", "main") + if self.lag(lc) == 0: + return + if time.monotonic() > deadline: + shown = self.status(lc) + pytest.fail(f"{what}: the lag, each read after a fetch of W, is not 0 within " + f"{CEILING:g} s:\n{shown.stdout}" + f"{shown.stderr[-800:]}", pytrace=False) + time.sleep(POLL) + + def wait_renders_exit(self, after: int, what: str) -> list: + """OPEN POINT 8'S SECOND WAIT: under 30 s, a render's call logged + after the mark `after` (every pass begins with a fetch), then the + exit of every renderer pid logged after it, a re-fork's included: + `os.pidfd_open` where it exists, else `os.kill(pid, 0)` beside the + start time logged, a pid whose start time no longer matches counting + as exited. Returns the renderer pids.""" + deadline = time.monotonic() + CEILING + while not self.render_calls(after): + if time.monotonic() > deadline: + pytest.fail(f"{what}: no render's call was logged within {CEILING:g} s", + pytrace=False) + time.sleep(POLL) + seen: dict = {} + while True: + for call in self.render_calls(after): + seen.setdefault(call["renderer"], call["renderer_start"]) + live = [pid for pid, start in seen.items() if not _exited(pid, start)] + if not live: + again = {c["renderer"] for c in self.render_calls(after)} + if again <= set(seen): + return sorted(seen) + continue + if time.monotonic() > deadline: + pytest.fail(f"{what}: renderer pids {live} did not exit within {CEILING:g} s", + pytrace=False) + time.sleep(POLL) + + +def _exited(pid: int, start: str) -> bool: + """Whether `pid`, which started at `start` (`ps -o lstart=`), is gone.""" + if hasattr(os, "pidfd_open"): + try: + fd = os.pidfd_open(pid) + except ProcessLookupError: + return True + except OSError: + fd = None + if fd is not None: + import select + try: + poller = select.poll() + poller.register(fd, select.POLLIN) + if poller.poll(0): + return True + finally: + os.close(fd) + else: + try: + os.kill(pid, 0) + except ProcessLookupError: + return True + except PermissionError: + pass + now = subprocess.run(["ps", "-o", "lstart=", "-p", str(pid)], capture_output=True, + text=True, check=False).stdout + return " ".join(now.split()) != start + + +def _until(predicate, seconds: float) -> bool: + """`predicate()` polled every 100 ms until it holds, or `seconds` pass; + its last answer.""" + deadline = time.monotonic() + seconds + while not predicate(): + if time.monotonic() > deadline: + return bool(predicate()) + time.sleep(POLL) + return True + + +def _held_fd(fifo: Path, what: str, seconds: float = 120) -> int: + """The FIFO's write end, once the wrapper or the shim holds a call on + it; the case fails, naming `what`, where none does in time.""" + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + try: + return os.open(str(fifo), os.O_WRONLY | os.O_NONBLOCK) + except OSError: + time.sleep(0.05) + pytest.fail(f"{what}: nothing was held on {fifo.name} within {seconds:g} s", pytrace=False) + + +def _held_pushes(est: RenderEstate) -> int: + """The render pushes the wrapper has held so far, each counted by its + own `held` line in the raw `git-wrapper.log`. Not `render_calls()`, + which drops a pid's `held` line once its push has run.""" + return sum(1 for c in _jsonl(est.bin / "git-wrapper.log") + if c.get("render") and c["sub"] == "push" and c.get("outcome") == "held") + + +def _kth_held_fd(est: RenderEstate, fifo: Path, k: int, what: str, + seconds: float = 120) -> int: + """`_held_fd`, opened only once the raw log holds the `k`-th held + render push. A pass starts only after the previous push's wrapper has + exited, so the open lands on the `k`-th push, never on one just + released whose wrapper has not yet seen EOF (lane 3's #38, #165 + 6859801732).""" + if not _until(lambda: _held_pushes(est) >= k, seconds): + pytest.fail(f"{what}: the wrapper's log holds {_held_pushes(est)} held render pushes, " + f"not {k}, within {seconds:g} s", pytrace=False) + return _held_fd(fifo, what, seconds) + + +def _wrote(proc, what: str) -> None: + assert proc.returncode == 0, ( + f"{what} on primary did not exit 0 (lane 4's T415 and T416, L4-B13):\n{_said(proc)}") + + +#: Test 7's seed's session of `L1`'s row (pgcluster's `_test7_seed`). +UUID_L1 = "eeeeeeee-0002-4000-8000-00000000e002" + + +def _operator_is_test7s() -> None: + """THE OPERATOR'S ONE VALUE: `OPERATOR` equals T227b's `TEST7_OPERATOR`. + The name is imported here, when a case runs, and never at module level, + so the module collects where T227 has not landed. Every case here waits + for T227 anyway, since its estate is built on `pg_imported` and + `pg_cluster.imported_register`, both T227's. So on a tree without the + name each case fails here, naming T227, and on a tree whose value + differs each case fails here, before it asks for the engine.""" + try: + from pgcluster import TEST7_OPERATOR + except ImportError as exc: + pytest.fail(f"tests/pgcluster.py has no TEST7_OPERATOR ({exc}): every case " + f"here waits for T227, whose T227b adds it with `pg_imported`", + pytrace=False) + assert OPERATOR == TEST7_OPERATOR, ( + f"this module's OPERATOR {OPERATOR!r} is not pgcluster's TEST7_OPERATOR " + f"{TEST7_OPERATOR!r} (T227b): change the copy here to match") + + +def _estate(request, tmp_path: Path, **kw) -> RenderEstate: + """A `RenderEstate` on `pg_imported`, or `pg` where `stage` is `empty`, + once `OPERATOR` is checked against T227b's (`_operator_is_test7s`).""" + _operator_is_test7s() + stage = kw.get("stage", "primary") + db = request.getfixturevalue("pg" if stage == "empty" else "pg_imported") + cluster = request.getfixturevalue("pg_cluster") + return RenderEstate(tmp_path / "estate", db, cluster, **kw) + + +def _assert_rendered(est: RenderEstate, old: str, seqs: list, origin: Path | None = None) -> list: + """THE RACE'S ORACLE (TP:1092-1099): origin's `main` gains exactly one + commit per seq after `old`, carrying `seqs` in order with none repeated, + each message the journal entry's with its `Register-Seq` (T322's form), + and author, committer and both dates the journal's (D15). Returns the + commits.""" + gained = est.commits_after(old, origin) + assert [s for _sha, carried, _m in gained for s in carried] == seqs, ( + f"origin's main gained {[(sha[:12], carried) for sha, carried, _m in gained]}, not one " + f"commit for each of {seqs} in order") + assert len(gained) == len(seqs), f"origin's main gained {len(gained)} commits for {seqs}" + journal = {row["seq"]: row for row in est.journal(min(seqs) - 1)} + for sha, (k,), message in gained: + entry = journal[k] + assert message.rstrip("\n") == _with_trailer(entry["message"], k), ( + f"the commit for seq {k} carries {message!r}, not the journal's message " + f"{entry['message']!r} with Register-Seq: {k} (T322's form)") + ident = est.identity(sha, origin) + assert ident == {"author": entry["author"], "author_epoch": entry["epoch"], + "committer": entry["author"], "committer_epoch": entry["epoch"]}, ( + f"the commit for seq {k} has {ident}, not the journal's author {entry['author']} " + f"as author and committer, both at {entry['epoch']} (D15)") + return [sha for sha, _c, _m in gained] + + +#: A line of a trailer block, `Token: value` (F29; B14 tasks:1504). +TRAILER_LINE = re.compile(r"[A-Za-z0-9-]+: .*") + + +def _with_trailer(message: str, k: int) -> str: + """T322'S FORM (B14 tasks:1504), with no final LF: the entry's message, + its blank last lines dropped, then `Register-Seq: <k>` as the last line + of its final trailer block, where it has two paragraphs or more and every + line of the last is `Token: value`; otherwise as a new last paragraph + after one blank line.""" + lines = message.split("\n") + while lines and not lines[-1].strip(" \t"): + lines.pop() + paragraphs, current = [], [] + for line in lines: + if line.strip(" \t"): + current.append(line) + elif current: + paragraphs.append(current) + current = [] + paragraphs.append(current) + block = len(paragraphs) >= 2 and all(TRAILER_LINE.fullmatch(line) for line in paragraphs[-1]) + return "\n".join(lines) + ("\n" if block else "\n\n") + f"Register-Seq: {k}" + + +def _no_rewrite(est: RenderEstate) -> None: + """The wrapper's log shows no `rebase`, no `pull --rebase` and no other + command that moves a HEAD (TP:1099; P314-318).""" + bad = [c["argv"] for c in est.calls() if c["sub"] in REWRITES] + assert not bad, f"a render ran a command that rewrites or moves a HEAD: {bad}" + + +def _push_tip(call: dict) -> str: + """The commit a push call names, from its `<tip>:refs/heads/main`.""" + spec = next((a for a in reversed(call["argv"]) if a.endswith(":refs/heads/main")), "") + return spec.split(":", 1)[0].lstrip("+") + + +# =================================================================== AT-5: the race +def test_two_renderers_racing_push_one_commit_per_seq_in_order(request, tmp_path): + """AT-5's race (TP:1092-1099): `n+1` to `n+5` committed, then two + renderers, in `L1`'s and `L2`'s checkouts of one bare origin, started + through test 4's barrier. Origin's `main` gains exactly five commits, + carrying `n+1` to `n+5` in order with none repeated, each message and + identity the journal's; both renderers exit 0; and the wrapper's log + shows no `rebase` and no `pull --rebase`. Fails until T320 to T322.""" + est = _estate(request, tmp_path) + one, two = est.checkout("L1", L1), est.checkout("L2", L2) + seqs = est.write_sql([f"race entry {i}" for i in range(1, 6)]) + assert seqs == list(range(est.n + 1, est.n + 6)), seqs + old = est.origin_tip() + est.arm() + ended = est.race([one, two]) + for lc, proc in zip((one, two), ended): + assert proc.returncode == 0, f"{lc.name}'s renderer:\n{_said(proc)}" + _assert_rendered(est, old, seqs) + _no_rewrite(est) + + +def _held_and_rendered(est: RenderEstate, one, two, seqs: list) -> tuple: + """`two`'s renderer held at its first push, `one`'s run to its end, then + `two` released: returns (the commit `two` had built for its push, + origin's commits for `seqs`, `two`'s exit).""" + fifo = est.root / f"hold-{two.name}.fifo" + os.mkfifo(str(fifo), 0o600) + old = est.origin_tip() + est.arm([{"sub": "push", "do": "hold", "fifo": str(fifo), "where": str(two.clone), + "times": 1}]) + held = est.popen_render(two) + fd = _open_when_held(fifo, held) + try: + assert fd is not None, (f"{two.name}'s renderer never reached its push:\n" + f"{held.communicate(timeout=60)}") + proc = est.render(one) + assert proc.returncode == 0, f"{one.name}'s renderer:\n{_said(proc)}" + finally: + if fd is not None: + os.close(fd) + out, err = held.communicate(timeout=300) + first = next(c for c in est.calls("push", two)) + commits = _assert_rendered(est, old, seqs) + return _push_tip(first), commits, SimpleNamespace(returncode=held.returncode, stdout=out, + stderr=err) + + +def test_renderers_make_identical_commits_for_one_seq(request, tmp_path): + """AT-5's identical commits (TP:1100-1102; P1363-1367): with `n+1` + committed, `L2`'s renderer is held at its push while `L1`'s renders and + pushes; the commit `L2` built for `n+1`, the one its push names, is the + sha `L1` pushed, its author and committer the journal's identity, both + dated by the entry's commit UTC (D15). Released, `L2` exits 0. Fails + until T320 to T322.""" + est = _estate(request, tmp_path) + one, two = est.checkout("L1", L1), est.checkout("L2", L2) + seqs = est.write_sql(["one seq, two renderers"]) + built, commits, two_ended = _held_and_rendered(est, one, two, seqs) + assert built == commits[0], (f"L2's renderer built {built} for seq {seqs[0]}, and L1's " + f"pushed {commits[0]}: two renderers made different commits") + assert two_ended.returncode == 0, f"L2's renderer after the release:\n{_said(two_ended)}" + + +# =================================================================== AT-5: the kill +def test_a_renderer_killed_by_sigkill_leaves_the_checkout_able_to_render_at_once(request, + tmp_path): + """[L4-4] (TP:1107-1109): the wrapper sends SIGKILL to the renderer's + process group just before its push. Then a non-blocking `flock` on + `lanes-render.lock` succeeds at once, no lock directory is left, and, + with no hand removal, the next render pushes every missing seq in order. + Fails until T320 to T322.""" + est = _estate(request, tmp_path) + one = est.checkout("L1", L1) + seqs = est.write_sql(["killed before its push, 1", "killed before its push, 2"]) + old = est.origin_tip() + est.arm([{"sub": "push", "do": "kill", "where": str(one.clone), "times": 1}]) + killed = est.render(one) + assert killed.returncode == -signal.SIGKILL, ( + f"the renderer was not killed at its push:\n{_said(killed)}") + assert est.origin_tip() == old, "the killed renderer pushed" + lock = one.git_dir / "lanes-render.lock" + assert not lock.is_dir(), "a lock directory is left behind" + assert not [p.name for p in one.git_dir.iterdir() + if p.is_dir() and p.name.startswith("lanes-render")], "a lock directory is left" + assert _lock_is_free(lock), "the SIGKILL did not release lanes-render.lock (D14; [L4-4])" + est.arm() + proc = est.render(one) + assert proc.returncode == 0, f"the next render, with no hand removal:\n{_said(proc)}" + _assert_rendered(est, old, seqs) + + +def test_a_renderer_killed_inside_read_tree_does_not_block_the_next_render(request, tmp_path): + """AT-5 (TP:1065-1067, :1223-1224): the wrapper leaves + `lanes-render.index.lock` behind, as git inside `read-tree` does, and + sends SIGKILL to the renderer's process group. The lock is free at once, + and the next render clears the stale `.lock` under the lock and pushes + every missing seq in order. Fails until T320 to T322.""" + est = _estate(request, tmp_path) + one = est.checkout("L1", L1) + seqs = est.write_sql(["killed inside read-tree"]) + old = est.origin_tip() + est.arm([{"sub": "read-tree", "do": "kill", "index_lock": True, "where": str(one.clone), + "times": 1}]) + killed = est.render(one) + assert killed.returncode == -signal.SIGKILL, ( + f"the renderer was not killed inside read-tree:\n{_said(killed)}") + stale = one.git_dir / "lanes-render.index.lock" + assert stale.exists(), (f"no {stale.name} was left: the build ran no read-tree under " + f"GIT_INDEX_FILE {one.git_dir / 'lanes-render.index'}") + assert _lock_is_free(one.git_dir / "lanes-render.lock"), "the render lock is still held" + est.arm() + proc = est.render(one) + assert proc.returncode == 0, f"the next render after the stale index lock:\n{_said(proc)}" + _assert_rendered(est, old, seqs) + assert not stale.exists(), f"{stale.name} is still there after the next render" + + +# =================================================================== AT-5: the lost race +def test_a_lost_push_race_never_rebases_a_render(request, tmp_path): + """P314-318 (TP:1034, :1181): `L1`'s renderer is held at its first push + while another clone pushes a handoff commit, so the push is rejected as a + non-fast-forward. The renderer fetches, builds again on the new tip, and + pushes: origin's `main` is the handoff commit and then one commit per + seq, in order; the wrapper's log shows two pushes with a fetch between, + and no `rebase`, `pull` or other command that moves a HEAD; and `L1`'s + HEAD, index and status are as before. Fails until T320 to T322.""" + est = _estate(request, tmp_path) + one = est.checkout("L1", L1) + seqs = est.write_sql(["a lost race, 1", "a lost race, 2"]) + before = est.snapshot(one) + fifo = est.root / "hold.fifo" + os.mkfifo(str(fifo), 0o600) + est.arm([{"sub": "push", "do": "hold", "fifo": str(fifo), "where": str(one.clone), + "times": 1}]) + held = est.popen_render(one) + fd = _open_when_held(fifo, held) + try: + assert fd is not None, f"the renderer never reached its push:\n{held.communicate()}" + handoff = est.commit_in_origin(est.origin_tip(), { + f"handoffs/{L2}.md": b"# a handoff pushed while the render was held\n"}, + "a handoff commit, pushed during the render's push") + est.push_by_hand(handoff) + finally: + if fd is not None: + os.close(fd) + out, err = held.communicate(timeout=300) + assert held.returncode == 0, _said(SimpleNamespace(returncode=held.returncode, stdout=out, + stderr=err)) + _assert_rendered(est, handoff, seqs) + pushes = est.calls("push", one) + assert [p.get("rc") for p in pushes] == [1, 0], ( + f"not one rejected push then one that landed: {[(p['outcome'], p.get('rc')) for p in pushes]}") + calls = est.calls(lc=one) + first, second = (calls.index(p) for p in pushes) + assert any(c["sub"] == "fetch" for c in calls[first + 1:second]), ( + "the renderer pushed again with no fetch after the rejection") + _no_rewrite(est) + assert est.snapshot(one) == before, "the render moved L1's HEAD, index or status" + + +# =================================================================== AT-5: the push (T320) +def test_the_render_push_alone_carries_the_deploy_key(request, tmp_path): + """D23 (TP:1182-1193): with `render_key=` set, origin named by a GitHub + HTTPS URL, a global `url.*.insteadOf` rewriting SSH URLs to HTTPS and + `SSH_AUTH_SOCK` in the case's own environment, the wrapper records the + push and makes it to the bare origin in its place. The push names + `ssh://git@github.com/<owner>/<repo>.git` and `<tip>:refs/heads/main`, + with `--no-verify` and no force; its environment alone carries + `GIT_SSH_COMMAND` with `-i` the key file, `IdentitiesOnly=yes` and + `BatchMode=yes`, `GIT_CONFIG_GLOBAL=/dev/null` and + `GIT_CONFIG_NOSYSTEM=1`, and no `SSH_AUTH_SOCK`; the checkout's + configuration is unchanged, with no `pushurl`; and the read-back fetches + `origin`. Fails until T320 to T322.""" + est = _estate(request, tmp_path) + one = est.checkout("L1", L1, repository=GITHUB_HTTPS) + est.git(one.clone, "remote", "set-url", "origin", GITHUB_HTTPS) + (one.home / ".gitconfig").write_text( + '[url "https://github.com/"]\n\tinsteadOf = ssh://git@github.com/\n', encoding="utf-8") + key = _private(one.root / "keys" / "render_key", "not a key: the git wrapper makes the push\n") + conf = est.config("deploy-key", "primary", [f"render_key={key}"]) + local_before = est.git(one.clone, "config", "--local", "--list") + seqs = est.write_sql(["pushed with the deploy key"]) + old = est.origin_tip() + est.arm(redirect={GITHUB_HTTPS: str(est.origin), GITHUB_SSH: str(est.origin)}) + proc = est.render(one, conf=conf, env={"SSH_AUTH_SOCK": str(one.root / "agent.sock")}) + assert proc.returncode == 0, f"the render with render_key=:\n{_said(proc)}" + _assert_rendered(est, old, seqs) + calls = est.calls(lc=one) + pushes = [c for c in calls if c["sub"] == "push"] + assert len(pushes) == 1, f"not one push: {[p['argv'] for p in pushes]}" + push = pushes[0] + argv = push["argv"] + assert GITHUB_SSH in argv, f"the push does not name {GITHUB_SSH}: {argv}" + assert any(a.endswith(":refs/heads/main") and not a.startswith("+") for a in argv), argv + assert "--no-verify" in argv and not {"-f", "--force", "--force-with-lease"} & set(argv), argv + ssh = push["env"]["GIT_SSH_COMMAND"] or "" + words = shlex.split(ssh) + assert "-i" in words and words[words.index("-i") + 1] == str(key), ( + f"GIT_SSH_COMMAND does not name the key file with -i: {ssh!r}") + for option in ("IdentitiesOnly=yes", "BatchMode=yes"): + assert option in ssh, f"GIT_SSH_COMMAND lacks {option}: {ssh!r}" + assert (push["env"]["GIT_CONFIG_GLOBAL"], push["env"]["GIT_CONFIG_NOSYSTEM"]) == ( + os.devnull, "1"), push["env"] + assert push["env"]["SSH_AUTH_SOCK"] is None, "the push inherited SSH_AUTH_SOCK" + others = [c for c in calls if c is not push] + assert not [c["argv"] for c in others if c["env"]["GIT_SSH_COMMAND"]], ( + "another git call than the push carried GIT_SSH_COMMAND") + assert not [c["argv"] for c in others if str(key) in json.dumps(c["argv"])], ( + "another git call named the key file") + local_after = est.git(one.clone, "config", "--local", "--list") + assert local_after == local_before, f"the checkout's configuration changed:\n{local_after}" + assert "pushurl" not in local_after.lower(), local_after + after = calls[calls.index(push) + 1:] + assert any(c["sub"] == "fetch" and "origin" in c["argv"] for c in after), ( + "the read-back fetched no `origin` after the push") + + +def test_a_non_github_origin_with_render_key_is_refused_with_2(request, tmp_path): + """D23 (TP:1194; B14 tasks:1472): with `render_key=` set and the + checkout's origin a plain path, no GitHub repository, `render --checkout` + exits 2, names the origin as not a GitHub repository, makes no push, and + origin's `main` does not move. Fails until T320 to T322.""" + est = _estate(request, tmp_path) + one = est.checkout("L1", L1) + key = _private(one.root / "keys" / "render_key", "not a key\n") + conf = est.config("deploy-key", "primary", [f"render_key={key}"]) + est.write_sql(["refused: the origin is no GitHub repository"]) + old = est.origin_tip() + est.arm() + proc = est.render(one, conf=conf) + assert proc.returncode == 2, f"a non-GitHub origin with render_key= is not refused 2:\n{_said(proc)}" + assert "not a GitHub repository" in proc.stderr, _said(proc) + assert est.calls("push") == [], f"a push was made: {[c['argv'] for c in est.calls('push')]}" + assert est.origin_tip() == old, "origin's main moved" + + +def test_without_render_key_the_push_goes_to_origin(request, tmp_path): + """Q21(b)(A) (TP:1195; B14 tasks:1473-1477): without `render_key=` the + push names `origin` as it stands, `<tip>:refs/heads/main`, never forced, + with no `GIT_SSH_COMMAND`; origin gains the seq; and the checkout's + configuration is unchanged. Fails until T320 to T322.""" + est = _estate(request, tmp_path) + one = est.checkout("L1", L1) + local_before = est.git(one.clone, "config", "--local", "--list") + seqs = est.write_sql(["pushed to origin as it stands"]) + old = est.origin_tip() + est.arm() + proc = est.render(one) + assert proc.returncode == 0, f"the render without render_key=:\n{_said(proc)}" + commits = _assert_rendered(est, old, seqs) + pushes = est.calls("push", one) + assert len(pushes) == 1, f"not one push: {[p['argv'] for p in pushes]}" + argv = pushes[0]["argv"] + assert argv[argv.index(next(a for a in argv if a.endswith(":refs/heads/main"))) - 1] == "origin", ( + f"the push does not name `origin`: {argv}") + assert _push_tip(pushes[0]) == commits[-1], argv + assert not {"-f", "--force", "--force-with-lease"} & set(argv) and not any( + a.startswith("+") for a in argv), argv + assert pushes[0]["env"]["GIT_SSH_COMMAND"] is None, pushes[0]["env"] + assert est.git(one.clone, "config", "--local", "--list") == local_before + + +# =================================================================== AT-5: the pass and form C +def _deepen(est: RenderEstate, depth: int) -> str: + """`depth` commits under `handoffs/` on origin's `main`, none in the + render set, by one `git fast-import`. Returns the new tip.""" + old = est.origin_tip() + stream = [] + for n in range(1, depth + 1): + message = f"t270: handoff commit {n} of {depth}\n".encode() + content = f"# handoff {n}\n".encode() + stream.append(b"commit refs/heads/main\n") + stream.append(f"mark :{n}\n".encode()) + stream.append(f"committer T270 estate <t270@example.invalid> {1762858800 + n} +0000\n" + .encode()) + stream.append(b"data %d\n" % len(message) + message) + stream.append(f"from {old if n == 1 else ':' + str(n - 1)}\n".encode()) + stream.append(b"M 100644 inline handoffs/t270-depth.md\n") + stream.append(b"data %d\n" % len(content) + content) + est.origin_git("fast-import", "--quiet", data=b"".join(stream)) + tip = est.origin_tip() + assert est.origin_git("rev-list", "--count", f"{old}..{tip}").strip() == str(depth) + return tip + + +def _walks(est: RenderEstate, lc) -> list: + """The wrapper's `log --first-parent` calls in the checkout: form C's + walk, as (`-n`, `--skip`, whether it says `--grep`).""" + found = [] + for call in est.calls("log", lc): + argv = call["argv"] + if "--first-parent" not in argv or any(a.startswith("--raw") for a in argv): + continue + n = argv[argv.index("-n") + 1] if "-n" in argv else None + skip = argv[argv.index("--skip") + 1] if "--skip" in argv else None + found.append((n, skip, any(a.startswith("--grep") for a in argv))) + return found + + +@pytest.mark.parametrize("depth", ["depth-0", "depth-250"]) +def test_the_renderer_finds_m_by_paging_form_c(request, tmp_path, depth): + """Lane 4's section (TP:1040-1043, :1196-1203): at depth 0 the newest + render commit is the tip, and the renderer finds it in one page, the + wrapper's log showing each pass's walk as one page of `-n 200`, no page + after the first and no `--grep`; T323's holder runs a second pass after + a pass that made progress, F15, and that pass walks its first page + again from the new tip. At depth 250 it is 250 first-parent commits below the + tip: the renderer pages with `--skip` and finds it, the log showing + `-n 200`, the `--skip 200` page and no `--grep`. Either way it renders + the seq after it on top of the tip. Fails until T320 to T322.""" + est = _estate(request, tmp_path) + one = est.checkout("L1", L1) + tip = _deepen(est, 250) if depth == "depth-250" else est.origin_tip() + seqs = est.write_sql([f"found at {depth}"]) + est.arm() + proc = est.render(one) + assert proc.returncode == 0, f"the render at {depth}:\n{_said(proc)}" + _assert_rendered(est, tip, seqs) + walks = _walks(est, one) + assert walks and all(n == "200" for n, _skip, _grep in walks), ( + f"form C's walk is not in pages of 200: {walks}") + assert not any(grep for _n, _skip, grep in walks), f"form C's walk used --grep: {walks}" + if depth == "depth-0": + assert all(skip in (None, "0") for _n, skip, _g in walks), ( + f"at depth 0 a pass's walk took more than its first page: {walks}") + else: + assert [skip or "0" for _n, skip, _g in walks[:2]] == ["0", "200"], ( + f"at depth 250 the walk did not page on with --skip 200: {walks}") + + +@pytest.mark.parametrize("why", ["none", "out-of-time"]) +def test_with_no_register_seq_found_the_renderer_pushes_nothing_and_records_why(request, + tmp_path, why): + """Lane 4's section (TP:1040-1043, :1204-1206): `[none]`, origin's + `main` is C, no commit of which carries a `Register-Seq` (the marker + commit is recorded and not on origin); `[out-of-time]`, the wrapper + stalls the walk's `log` past `LANES_GIT_TIMEOUT`, set to 2 s. The + renderer pushes nothing and exits non-zero; `mirror_state.last_error` + and its time are set through `record_mirror_state`, `diverged_sha` stays + NULL; `status` shows the failed pass; and origin is unchanged. Fails + until T320 to T322.""" + est = _estate(request, tmp_path, marker="pushed" if why == "out-of-time" else "recorded") + one = est.checkout("L1", L1) + est.write_sql([f"no Register-Seq found: {why}"]) + old = est.origin_tip() + env = None + if why == "out-of-time": + est.arm([{"sub": "log", "do": "stall", "has": "--first-parent", "seconds": 6, + "where": str(one.clone)}]) + env = {"LANES_GIT_TIMEOUT": "2"} + else: + assert old == est.c and est.form_c(old) == "", "origin's main carries a Register-Seq" + est.arm() + proc = est.render(one, env=env, timeout=120) + assert proc.returncode != 0, f"the renderer found no m and still ended 0:\n{_said(proc)}" + assert est.calls("push") == [], f"it pushed: {[c['argv'] for c in est.calls('push')]}" + assert est.origin_tip() == old, "origin's main moved" + mirror = est.mirror() + assert mirror["last_error"] and mirror["last_error_utc"], ( + f"no failed pass is recorded in mirror_state: {mirror}\n{_said(proc)}") + assert mirror["diverged_sha"] is None, f"a divergence was recorded: {mirror}" + shown = est.status(one) + assert FAILED_PASS.search(shown.stdout), f"status does not show the failed pass:\n{_said(shown)}" + + +def test_a_pass_renders_at_most_64_seqs(request, tmp_path): + """PC-3 (TP:1044-1045, :1207-1209): a backlog of 70 seqs reaches origin + as `m+1` to `m+64` in one pass, one push, and the rest in the next; and + the commits are those of any other batching: a second origin, rendered + in batches of 10 and then 60, carries the same 70 shas. Fails until + T320 to T323.""" + est = _estate(request, tmp_path) + other_origin = est.second_origin("origin-batched") + one = est.checkout("L1", L1) + batched = est.checkout("L2", L2, origin=other_origin) + old = est.origin_tip() + m = est.n + first = est.write_sql([f"backlog entry {i}" for i in range(1, 11)]) + est.arm() + proc = est.render(batched) + assert proc.returncode == 0, f"the batched render of 10:\n{_said(proc)}" + rest = est.write_sql([f"backlog entry {i}" for i in range(11, 71)]) + seqs = first + rest + assert seqs == list(range(m + 1, m + 71)), seqs + est.arm() + proc = est.render(one) + assert proc.returncode == 0, f"the render of a backlog of 70:\n{_said(proc)}" + commits = _assert_rendered(est, old, seqs) + tips = [_push_tip(p) for p in est.calls("push", one)] + assert tips == [commits[63], commits[69]], ( + f"the pushes named {tips}, not seq {m + 64}'s commit, then seq {m + 70}'s: a pass " + f"renders at most 64 seqs") + est.arm() + proc = est.render(batched) + assert proc.returncode == 0, f"the batched render of 60:\n{_said(proc)}" + assert _assert_rendered(est, old, seqs, other_origin) == commits, ( + "batches of 10 and 60 made other commits than batches of 64 and 6") + + +@pytest.mark.parametrize("shape", ["subject-only", "trailer-block", "prose"]) +def test_form_c_reads_the_trailer_from_each_message_shape(request, tmp_path, shape): + """Lane 4's section (TP:1225-1226): a journal message of each shape, a + subject alone, a body ending in a trailer block, and a body ending in + prose. Two checkouts give one sha for it (`L2` held at its push while + `L1` renders), and form C reads `<k>` from it. The trailer joins the + final trailer block, or is a new last paragraph after one blank line + (T322). Fails until T320 to T322.""" + message = { + "subject-only": "t270: a subject alone", + "trailer-block": (f"t270: a subject\n\nA body line.\n\nLane: {L1}\n" + f"Co-Authored-By: T270 <t270@example.invalid>"), + "prose": ("t270: a subject\n\nA body that ends in prose, a paragraph with no " + "trailer in it."), + }[shape] + est = _estate(request, tmp_path) + one, two = est.checkout("L1", L1), est.checkout("L2", L2) + old = est.origin_tip() + (k,) = est.write_sql([f"form C, {shape}"], messages=[message]) + fifo = est.root / "hold.fifo" + os.mkfifo(str(fifo), 0o600) + est.arm([{"sub": "push", "do": "hold", "fifo": str(fifo), "where": str(two.clone), + "times": 1}]) + held = est.popen_render(two) + fd = _open_when_held(fifo, held) + try: + assert fd is not None, f"L2's renderer never reached its push:\n{held.communicate()}" + proc = est.render(one) + assert proc.returncode == 0, f"L1's renderer:\n{_said(proc)}" + finally: + if fd is not None: + os.close(fd) + held.communicate(timeout=300) + assert held.returncode == 0, "L2's renderer after the release" + gained = est.commits_after(old) + assert [carried for _s, carried, _m in gained] == [[k]], gained + sha, _carried, raw = gained[0] + assert _push_tip(est.calls("push", two)[0]) == sha, "two checkouts gave two shas" + assert est.form_c(sha) == str(k), f"form C reads {est.form_c(sha)!r} from {sha}, not {k}" + joined = "\n" if shape == "trailer-block" else "\n\n" + assert raw.rstrip("\n") == f"{message}{joined}Register-Seq: {k}", ( + f"the {shape} message is not the journal's with Register-Seq: {k} " + f"{'in its trailer block' if shape == 'trailer-block' else 'as a new paragraph'}: {raw!r}") + + +@pytest.mark.parametrize("case", ["marker-first-head-minus-1", "marker-first-head-0", "forged"]) +def test_a_register_seq_above_the_head_with_the_switch_at_files_is_no_divergence_and_renders_nothing( + request, tmp_path, case): + """R2's N6, at `files` (TP:1150-1167, :1227-1228): the switch reads + `files`, and origin's `main` carries a commit whose last `Register-Seq` + is above the head `h`: the marker commit `S` with `Register-Seq: 1`, + pushed ahead of the import (`h` -1, on `pg`) or after it (`h` 0); or a + forged commit under `handoffs/` carrying `Register-Seq: <h+10>`. A pass + run by `render --checkout <c>`, as a fork runs it, records no + divergence (`diverged_sha` NULL, no `diverged at` in `status`), pushes + nothing, and exits 0. Fails until T320 to T322.""" + est = _estate(request, tmp_path, stage="empty" if case.endswith("minus-1") else "imported") + h = est.head() + if case == "forged": + top = est.commit_in_origin(est.c, {f"handoffs/{L1}.md": b"# a forged commit\n"}, + f"a forged handoff commit\n\nRegister-Seq: {h + 10}\n") + else: + top = est.commit_in_origin(est.c, {"lanes/STORE": b"store=primary\n"}, + "t270: the marker commit, pushed first\n\nRegister-Seq: 1\n") + est.push_by_hand(top) + one = est.checkout("L1", L1) + est.arm() + proc = est.render(one) + assert proc.returncode == 0, f"the pass at files:\n{_said(proc)}" + assert est.calls("push") == [] and est.origin_tip() == top, "the pass at files pushed" + assert est.mirror()["diverged_sha"] is None, f"a divergence was recorded: {est.mirror()}" + shown = est.status(one) + assert not DIVERGED.search(shown.stdout), f"status prints a divergence:\n{shown.stdout}" + assert est.head() == h and est.switch()["mode"] == "files" + + +def test_a_render_commit_with_a_private_index_and_its_push_are_timed_and_recorded(request, + tmp_path): + """M6, section 5.1 (TP:1229-1235): the render commit made through the + private index, and its push to the local origin, each timed from the + wrapper's log, which tells the commit (`commit-tree`) from the push, over + five renders of one seq each; recorded with section 5.3's statistics and + their n, never asserted. Correctness alongside: each `write-tree` ran + under `GIT_INDEX_FILE` `lanes-render.index`, and origin gains each commit + with its `Register-Seq`. Fails until T320 to T322.""" + est = _estate(request, tmp_path) + one = est.checkout("L1", L1) + commits, pushes = [], [] + for n in range(1, 6): + old = est.origin_tip() + seqs = est.write_sql([f"timed render {n}"]) + est.arm() + proc = est.render(one) + assert proc.returncode == 0, f"timed render {n}:\n{_said(proc)}" + _assert_rendered(est, old, seqs) + trees = est.calls("write-tree", one) + assert trees and all((c["env"]["GIT_INDEX_FILE"] or "").endswith("lanes-render.index") + for c in trees), ( + f"a write-tree ran without the private index: {[c['env'] for c in trees]}") + commits += [(c["t1"] - c["ran"]) * 1000 for c in est.calls("commit-tree", one)] + pushes += [(c["t1"] - c["ran"]) * 1000 for c in est.calls("push", one)] + assert commits and pushes + for what, samples in (("render commit, private index", commits), ("its push", pushes)): + stats = _stats(samples) + row = (f"| M6 | fixture cluster, local bare origin | {what} | median " + f"{stats['median']:.1f} ms, p95 {stats['p95']:.1f} ms, " + f"{stats['min']:.1f}-{stats['max']:.1f} ms, n={stats['n']} |") + print("\n" + row) + summary = os.environ.get("GITHUB_STEP_SUMMARY") + if summary: + with open(summary, "a", encoding="utf-8") as handle: + handle.write(row + "\n") + + +# =================================================================== AT-5: six lost races (T323, T325) +def test_six_lost_races_leave_the_last_write_for_the_next_write_or_reconcile(request, + tmp_path): + """Lane 4's known gap (TP:1044-1045, :1074-1080, :1216-1218): the wrapper + rejects six pushes in a row as non-fast-forwards. The renderer makes six + push attempts in all, a fetch before each new one, and ends non-zero; + origin is unchanged and `status` shows a lag of 1. Then `reconcile`, + run in the lane's checkout with the `mode=primary` configuration, + renders it: origin carries the seq, and the lag is 0. Fails until T320 + to T323, and T325 (the re-render), at its own assertion.""" + est = _estate(request, tmp_path) + one = est.checkout("L1", L1) + seqs = est.write_sql(["the last write, six races lost"]) + old = est.origin_tip() + est.arm([{"sub": "push", "do": "reject", "where": str(one.clone), "times": 6}]) + proc = est.render(one) + assert proc.returncode != 0, f"the renderer that lost six races ended 0:\n{_said(proc)}" + assert est.origin_tip() == old, "origin moved" + calls = est.calls(lc=one) + pushes = [i for i, c in enumerate(calls) if c["sub"] == "push"] + assert len(pushes) == 6 and all(calls[i]["outcome"] == "rejected" for i in pushes), ( + f"not six rejected pushes: {[(c['sub'], c['outcome']) for c in calls]}") + for before, after in zip(pushes, pushes[1:]): + assert any(c["sub"] == "fetch" for c in calls[before + 1:after]), ( + "a push was retried with no fetch after its rejection") + assert est.lag(one) == 1, f"status does not show a lag of 1:\n{est.status(one).stdout}" + proc = est.index(one, "reconcile", conf=est.primary_conf) + assert proc.returncode == 0, f"reconcile:\n{_said(proc)}" + assert est.commits_after(old) and est.commits_after(old)[-1][1] == seqs, ( + f"reconcile did not render seq {seqs[0]} (T325: it re-renders what the mirror lacks, " + f"through T322's pass): origin carries {est.commits_after(old)}\n{_said(proc)}") + _assert_rendered(est, old, seqs) + assert est.lag(one) == 0, f"the lag is not 0 after reconcile:\n{est.status(one).stdout}" + + +# =================================================================== writes that fork +#: THE WRITER- AND FORK-SIDE CASES: each write is `lanes-edit.sh log NOTED` +#: (or lane-start's stamp) on `primary` from a lane's checkout, through the +#: flipped copy, and its fork starts the renderer in the lane's own register +#: checkout `<c>` (`own=True`, T270e), whose calls, lock and marks each case +#: reads. Each fails until lane 4's T415 and T416 (L4-B13), with T320 to +#: T323. Every wait for a forked render is open point 8's. + + +def test_a_renderer_killed_between_commit_and_push_blocks_nothing(request, tmp_path): + """AT-5's kill (TP:1103-1115; P319-346; concern 3, ADV-C6): `L1`'s write + forks a render that the wrapper kills by SIGKILL just before its push. + Read after the renderer's exit (open point 8's second wait): `L1`'s + HEAD, index digest and `status --porcelain` are as before the render. + Then, with no other command between, `L1`'s next write forks a render + that pushes every missing seq in order, and `L1`'s next handoff commit, + lane-handoff's commit block, exits 0 and is pushed. A second kill, then + a write, then lane-start's stamp (`append-session-id`), which exits 0 + and is rendered. Fails until L4-B13 and T320 to T322.""" + est = _estate(request, tmp_path) + one = est.checkout("L1", L1, own=True) + old = est.origin_tip() + before = est.snapshot(one.own) + est.arm([{"sub": "push", "do": "kill", "render_only": True, "where": str(one.own.clone), + "times": 1}]) + mark = est.entries() + _wrote(est.write(one, "a write whose render is killed before its push"), "log NOTED") + est.wait_renders_exit(mark, "the killed render") + assert [c for c in est.render_calls(mark) if c["outcome"] == "killed"], ( + "the wrapper killed no render at its push") + assert est.snapshot(one.own) == before, "the killed render moved L1's HEAD, index or status" + assert _lock_is_free(one.own.git_dir / "lanes-render.lock"), "the render lock is still held" + # The next write, then lane-handoff's commit block, with nothing between. + est.rearm() + _wrote(est.write(one, "the next write after the kill"), "the next log NOTED") + est.wait_lag_0(one, "the next write's render") + _assert_rendered(est, old, list(range(est.n + 1, est.head() + 1))) + handoff = f"handoffs/{L1}.md" + (one.own.clone / "handoffs").mkdir(exist_ok=True) + (one.own.clone / handoff).write_text("# a handoff, after the killed render\n", + encoding="utf-8") + env = dict(est.plain_env, HOME=str(one.home)) + for argv in (["add", "--", handoff], + ["commit", "-q", "-m", f"handoff({L1}@{WS}): PAUSED, t270", "-m", + f"Lane: {L1}", "--", handoff], + ["pull", "--rebase", "-q", "origin", "main"], ["push", "-q", "origin", "main"]): + est.git(one.own.clone, *argv, env=env) + assert handoff in est.origin_git("ls-tree", "-r", "--name-only", "refs/heads/main", + "handoffs/").split(), "the handoff commit was not pushed" + # The second case: a kill, a write, then lane-start's stamp. It arms the + # kill afresh with `est.arm()`, which starts the wrapper's log and its + # counts again: `rearm()` keeps each arm's count of uses, and the first + # case's kill used arm 0's one (`times: 1`), so a re-armed kill never + # fired and the second case passed with no kill (RV20, finding 2). + est.arm([{"sub": "push", "do": "kill", "render_only": True, "where": str(one.own.clone), + "times": 1}]) + mark = est.entries() + _wrote(est.write(one, "a second write whose render is killed"), "log NOTED") + est.wait_renders_exit(mark, "the second killed render") + assert [c for c in est.render_calls(mark) if c["outcome"] == "killed"], ( + f"the wrapper killed no render at the second case's push: " + f"{[(c['sub'], c['outcome']) for c in est.render_calls(mark)]}") + est.rearm() + _wrote(est.write(one, "the write after the second kill"), "log NOTED") + stamp = est.edit(one, "append-session-id", L1, f"harness `{UUID_L1}`", " (t270)") + _wrote(stamp, "lane-start's stamp, append-session-id") + est.wait_lag_0(one, "the stamp's render") + + +def _held_burst(est: RenderEstate, one) -> SimpleNamespace: + """AT-5's HELD RENDERER (TP:1116-1125): `L1`'s render held at its push + (the hold re-armed for each push) while four more writes from `L1` each + exit 0; then the hold is disarmed and released, and both of open point + 8's waits run. Returns what the case reads.""" + fifo = est.root / "held.fifo" + os.mkfifo(str(fifo), 0o600) + old = est.origin_tip() + est.arm([{"sub": "push", "do": "hold", "render_only": True, "fifo": str(fifo), + "where": str(one.own.clone)}]) + mark = est.entries() + _wrote(est.write(one, "the first write of a burst"), "log NOTED") + fd = _held_fd(fifo, "the first write's render, at its push") + rerun = one.own.git_dir / "lanes-render.rerun" + try: + holder = {c["renderer"] for c in est.render_calls(mark) if c["outcome"] == "held"} + waited = [] + for n in range(2, 6): + start = time.monotonic() + _wrote(est.write(one, f"write {n} of a burst, while the render is held", + timeout=120), f"write {n}") + waited.append(time.monotonic() - start) + + def forks() -> dict: + return {c["renderer"]: c["renderer_start"] for c in est.render_calls(mark) + if c["renderer"] not in holder} + # A detached fork may start after its write returns: wait, the hold + # standing, until the four have run a git call and exited, or 30 s. + _until(lambda: len(forks()) >= 4 and all(_exited(p, s) for p, s in forks().items()), + CEILING) + forks_live = [pid for pid, start in forks().items() if not _exited(pid, start)] + marked = rerun.exists() + est.rearm() + finally: + os.close(fd) + est.wait_lag_0(one, "the burst's last write") + est.wait_renders_exit(mark, "the burst's renders") + assert _lock_is_free(one.own.git_dir / "lanes-render.lock"), "the render lock is still held" + pushes = [c for c in est.render_calls(mark) if c["sub"] == "push" and c["outcome"] == "ran"] + return SimpleNamespace(old=old, holder=holder, marked=marked, forks=forks(), + forks_live=forks_live, waited=waited, pushes=pushes, + rerun_left=rerun.exists()) + + +def test_a_held_renderer_delays_no_writer_beyond_the_fork(request, tmp_path): + """AT-5's held renderer (TP:1116-1120, :1240-1241): with `L1`'s render + held at its push, four more writes from `L1` each exit 0 while it is + held, so no fork waited; each fork that found the lock held left + `lanes-render.rerun` in the checkout's git directory and had exited + while the hold still stood (D14). Fails until L4-B13 and T320 to T322.""" + est = _estate(request, tmp_path) + one = est.checkout("L1", L1, own=True) + seen = _held_burst(est, one) + assert len(seen.holder) == 1, f"not one held render: {seen.holder}" + assert seen.marked, "no fork that found the lock held left lanes-render.rerun" + assert seen.forks, "no fork of the four writes ran `render --checkout`" + assert not seen.forks_live, ( + f"forks {seen.forks_live} that found the lock held had not exited while it was held") + + +def test_a_burst_from_one_lane_gives_at_most_two_renders(request, tmp_path): + """[L4-3], qualified (TP:1028-1030, :1121-1125, :1242): the held + renderer's burst of five writes. Once the lag is 0 and every renderer + has exited, at most two renders made commits, the wrapper's log + counting their pushes, and origin carries the burst's last seq, each + seq once, in order. Fails until L4-B13 and T320 to T323.""" + est = _estate(request, tmp_path) + one = est.checkout("L1", L1, own=True) + seen = _held_burst(est, one) + assert 1 <= len(seen.pushes) <= 2, ( + f"{len(seen.pushes)} pushes for a burst that arrived within one pass, not at most two: " + f"{[_push_tip(p)[:12] for p in seen.pushes]}") + _assert_rendered(est, seen.old, list(range(est.n + 1, est.head() + 1))) + + +def test_the_last_write_of_a_burst_is_rendered_with_no_later_write(request, tmp_path): + """S2 (TP:1031): five writes from `L1` in a row, no hold, and no later + write. Within open point 8's waits the lag reaches 0 and every renderer + exits; origin carries every seq of the burst, its last included, in + order. Fails until L4-B13 and T320 to T323.""" + est = _estate(request, tmp_path) + one = est.checkout("L1", L1, own=True) + old = est.origin_tip() + est.arm() + for n in range(1, 6): + _wrote(est.write(one, f"burst write {n}, with no later write"), f"write {n}") + est.wait_lag_0(one, "the burst's last write") + est.wait_renders_exit(0, "the burst's renders") + _assert_rendered(est, old, list(range(est.n + 1, est.head() + 1))) + + +@pytest.mark.parametrize("fail", ["fetch", "push"]) +def test_a_failed_render_shows_its_lag_and_the_next_render_catches_up(request, tmp_path, fail): + """AT-5's failed render (TP:1134-1149): every render's `fetch` (or + `push`) fails. After the write, open point 8's second wait: SQL holds + the seq and `status` shows a lag of 1; `last_error` and its time are set + by the failed pass, and `diverged_sha` stays NULL; in the push case each + push follows a fetch, six pushes at most; and after the renderer's exit + no pass follows it, no render's `fetch` or `push` until the next write. + Released, the next write's render leaves both seqs on origin in order, + and a lag of 0. Fails until L4-B13 and T320 to T323.""" + est = _estate(request, tmp_path) + one = est.checkout("L1", L1, own=True) + old = est.origin_tip() + est.arm([{"sub": fail, "do": "fail", "render_only": True, "where": str(one.own.clone)}]) + mark = est.entries() + _wrote(est.write(one, f"a write whose render's {fail} fails"), "log NOTED") + est.wait_renders_exit(mark, f"the render whose {fail} fails") + k = est.head() + assert k == est.n + 1 and est.origin_tip() == old, "the failed render pushed" + assert est.lag(one) == 1, f"status does not show a lag of 1:\n{est.status(one).stdout}" + mirror = est.mirror() + assert mirror["last_error"] and mirror["last_error_utc"], ( + f"the failed pass recorded nothing: {mirror}") + assert mirror["diverged_sha"] is None, f"a divergence was recorded: {mirror}" + calls = est.render_calls(mark) + if fail == "push": + pushes = [i for i, c in enumerate(calls) if c["sub"] == "push"] + assert 1 <= len(pushes) <= 6, f"{len(pushes)} pushes, not one to six" + for i in pushes: + assert any(c["sub"] == "fetch" for c in calls[:i]), "a push with no fetch before it" + ended = est.entries() + est.rearm() + assert not [c for c in est.render_calls(ended) if c["sub"] in ("fetch", "push")], ( + "a pass followed the failed one (F15: a pass that pushed nothing ends the renderer)") + _wrote(est.write(one, "the next write, after the release"), "the next log NOTED") + est.wait_lag_0(one, "the next write's render") + _assert_rendered(est, old, [k, k + 1]) + + +def test_a_renderer_hands_over_once_after_16_passes(request, tmp_path): + """PC-3's handover (TP:1046-1049, :1210-1215): a stream of 17 writes + from `L1`, one per pass, each made while that pass is held at its push + (the hold re-arms for each push). Each write waits for that pass's push + in the wrapper's raw log, so no two writes share a pass. No renderer + process makes more than 16 passes (a pass begins with its fetch), a + second process follows once, and the last write reaches origin. Fails + until L4-B13 and T320 to T323.""" + est = _estate(request, tmp_path) + one = est.checkout("L1", L1, own=True) + old = est.origin_tip() + fifo = est.root / "pass.fifo" + os.mkfifo(str(fifo), 0o600) + est.arm([{"sub": "push", "do": "hold", "render_only": True, "fifo": str(fifo), + "where": str(one.own.clone)}]) + _wrote(est.write(one, "stream write 1"), "write 1") + # Write n waits for pass n-1's push, the (n-1)-th held line in the raw + # log (lane 3's #38, #165 6859801732). `_held_fd` alone could reopen the + # FIFO onto the push just released, before its wrapper saw EOF: that + # push stayed held through write n, and the next pass rendered two seqs. + for n in range(2, 18): + fd = _kth_held_fd(est, fifo, n - 1, f"pass {n - 1}'s push") + try: + _wrote(est.write(one, f"stream write {n}", timeout=120), f"write {n}") + finally: + os.close(fd) + fd = _kth_held_fd(est, fifo, 17, "the last pass's push") + est.rearm() + os.close(fd) + est.wait_lag_0(one, "the stream's last write") + est.wait_renders_exit(0, "the stream's renders") + # Each pass renders one write and pushes it once (nothing rejects here), + # so a renderer's pushes count its passes that made progress. + passes: dict = {} + for call in est.render_calls(0): + if call["sub"] == "push" and call["outcome"] == "ran": + passes[call["renderer"]] = passes.get(call["renderer"], 0) + 1 + assert sum(passes.values()) == 17, ( + f"the 17 writes did not go out in 17 render pushes, one per pass: {passes}") + assert passes and max(passes.values()) <= 16, f"a renderer made more than 16 passes: {passes}" + assert len(passes) == 2, ( + f"{len(passes)} renderer processes pushed, not the first and one that follows it: " + f"{passes}") + _assert_rendered(est, old, list(range(est.n + 1, est.n + 18))) + + +def test_no_rerun_mark_is_left_and_the_last_write_is_rendered_after_a_burst(request, tmp_path): + """D14's handshake (TP:1219-1221): after each of two bursts of 10 forks + from `L1`, both halves of the `flock` handshake leave no + `lanes-render.rerun`, and origin carries the last seq. Fails until + L4-B13 and T320 to T323.""" + est = _estate(request, tmp_path) + one = est.checkout("L1", L1, own=True) + old = est.origin_tip() + est.arm() + for burst in (1, 2): + mark = est.entries() + for n in range(1, 11): + _wrote(est.write(one, f"burst {burst}, fork {n}"), f"burst {burst}, write {n}") + est.wait_lag_0(one, f"burst {burst}") + est.wait_renders_exit(mark, f"burst {burst}'s renders") + assert not (one.own.git_dir / "lanes-render.rerun").exists(), ( + f"burst {burst} left lanes-render.rerun") + assert est.commits_after(old)[-1][1] == [est.head()], ( + f"origin does not carry burst {burst}'s last seq {est.head()}") + _assert_rendered(est, old, list(range(est.n + 1, est.head() + 1))) + + +def test_a_write_that_commits_as_the_render_lets_go_is_rendered_with_no_later_write(request, + tmp_path): + """Commit I's "A write that commits as the render lets go" (TP:1084-1090, + :1126-1133; S2's two halves of `SyncLock`'s handshake): `L1`'s first + write forks a render, and the `psql` shim holds that render's second + pass, one-shot, once the real `psql` has returned its read of the head, + which holds no entry after `m`. A second write from `L1` commits and + exits 0; its fork finds the lock held, leaves `lanes-render.rerun`, and + exits. The case releases the shim and makes no later write: the second + write's seq reaches origin, `status` shows a lag of 0, and no + `lanes-render.rerun` is left. Fails until L4-B13 and T320 to T323.""" + est = _estate(request, tmp_path) + one = est.checkout("L1", L1, own=True) + old = est.origin_tip() + fifo = est.root / "lets-go.fifo" + os.mkfifo(str(fifo), 0o600) + est.arm(shim_arms=[{"mode": "timer", "fifo": str(fifo), + "match": "FROM register_head h, register_switch s", "call": 2}]) + mark = est.entries() + _wrote(est.write(one, "the first write; its render lets go"), "write 1") + fd = _held_fd(fifo, "the render's second pass, after its read of the head") + try: + _wrote(est.write(one, "the write that commits as the render lets go", timeout=120), + "write 2") + assert _until(lambda: (one.own.git_dir / "lanes-render.rerun").exists(), CEILING), ( + "the second write's fork found the lock held and left no lanes-render.rerun") + finally: + os.close(fd) + est.wait_lag_0(one, "the write that commits as the render lets go") + est.wait_renders_exit(mark, "the renders") + _assert_rendered(est, old, [est.n + 1, est.n + 2]) + assert not (one.own.git_dir / "lanes-render.rerun").exists(), "lanes-render.rerun is left" + + +# =================================================================== AT-C8 +def test_a_render_forked_from_a_no_fetch_verb_still_renders(request, tmp_path): + """AT-C8 (C172-184; TP:3173-3196): `log NOTED` run with + `LANES_NO_FETCH=1` from `L1`'s checkout on a primary estate. Its render + commit reaches origin and `status` reports a lag of 0 (open point 8's + first wait); the wrapper's log shows the renderer's own fetch, made with + the variable absent from its environment, and no render's call made + with it set (D12). Fails until L4-B13 and T320 to T322.""" + est = _estate(request, tmp_path) + one = est.checkout("L1", L1, own=True) + old = est.origin_tip() + est.arm() + _wrote(est.write(one, "a write under LANES_NO_FETCH=1", env={"LANES_NO_FETCH": "1"}), + "log NOTED under LANES_NO_FETCH=1") + est.wait_lag_0(one, "the no-fetch write's render") + est.wait_renders_exit(0, "the no-fetch write's render") + _assert_rendered(est, old, [est.n + 1]) + renders = est.render_calls(0) + fetches = [c for c in renders if c["sub"] == "fetch"] + assert fetches and all(c["env"]["LANES_NO_FETCH"] is None for c in fetches), ( + f"the renderer made no fetch of its own with LANES_NO_FETCH absent: " + f"{[(c['argv'], c['env']['LANES_NO_FETCH']) for c in fetches]}") + assert not [c["argv"] for c in renders if c["env"]["LANES_NO_FETCH"] is not None], ( + "a render's git call inherited LANES_NO_FETCH") diff --git a/tests/test_sql_register_rollback.py b/tests/test_sql_register_rollback.py new file mode 100644 index 00000000..4fb9b367 --- /dev/null +++ b/tests/test_sql_register_rollback.py @@ -0,0 +1,2134 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Feature 007's test 8, section 4.2 and AT-F1: the rollback (L2-G4; L2-G5's +AT-F1; AT-8; T273; FR-051, FR-052, FR-059; also US6) (opensoft/openRepoTools#165). + +T273 writes this module: 21 tests, 20 from AT-8 (11), AT-F1 (7) and section +4.2 (2), and T304's own (R-F10-34), and T273d a 22nd: AT-F2's rollback rerun +after a 3 with a files-mode write between (lane 3's #165 6814260122), not yet +in B15's T273 text. T304's own test, +`test_rollback_steps_0_and_1_run_only_against_a_scratch_schema` (NOTES +question 6; B10 tasks:1011-1024; `PLACEMENT.md` section 4), is phase 1's, +and lane 3's T304 selects it with its word `sql_register_rollback and +scratch`: those six ids and nothing else. No other name or id in this module +holds that word. The other 20 (T273b) are after it, with their own notes. + +T304'S OWN TEST: steps 0 and 1 of `lanes-index rollback` (lane 3's T304), run +by the shipped `lanes-index` with Q6(c)'s constant unset (`RENDER_GIT_HALF = +False`), as the operator lane, `LANES_LANE=<operator lane>` (B10 tasks:1015), +with this workstation's name and git's author set, on a database of the +session cluster that `lanes-index bootstrap` made for a scratch +`register_schema=` (T109's DEC-23 rendering), brought to `primary` with the +marker `present` by AT-LR006's route (TP:4610-4615). A scratch schema is any +`register_schema=` but the default `lanes_register` (Y:2323; lane 2's +reading). Its ids: + + * `[diverged-refuses-2]`: with `mirror_state.diverged_sha` set, it exits 2, + and the switch, the marker and the head do not move (B10 tasks:1016); + * `[step-1-one-transaction]`: one transaction leaves the switch at `files`, + the head at `k+1`, an operator entry removing `lanes/STORE` last, and the + marker `removing` (tasks:1017). The case asserts the database's state, not + the exit after step 1, which T326's steps follow; + * `[outage-declared-with-mirror-seq]`: its start declares the outage, + marked as from a rollback, through `outage declare --rollback --mirror-seq + <k>` (tasks:1020; T121); + * `[lost-turn-rechecks-step-0]`: a second session holds the head row past + `rollback`'s `lock_timeout`, so step 1 meets 55P03, and records a + divergence meanwhile; once released, the rollback goes back to step 0 with + the head read afresh and exits 2, with the switch and the marker unchanged + (tasks:1018, :1016); + * `[database-unreachable-69]`: 69, with neither the switch nor the marker + changed (tasks:1021); + * `[not-a-scratch-schema-2]`: with `register_schema=` unset and the constant + unset, 2 (tasks:1023; `exit-codes.md` :145 at `23e4494`; Y:4872). + +D7's 75 (tasks:1019) and the rerun's step 2 (tasks:1022) stay with the phase +G cases (T273b). Each id fails until T107, T109's rendering, T121 and T304 +land (L1-A6, L1-A7, L1-A18; R-F10-34). Every id is RE: it asks for the +session cluster, and without PostgreSQL 16 it skips with T205's banner. + +READINGS, NOT FOUND IN A CONTRACT: +- AT-LR006'S ROUTE is the documented functions as REGISTER-WRITER, by direct + calls, as T231's cases reach `primary`: `commit_write` with an `import` + entry at seq 0, then a `cutover` entry at 1, then `record_marker`, then one + write at 2, so the rollback's `k` (2) is neither the import's seq nor the + cutover's. +- "ONE TRANSACTION" is read as: of every `psql` call the rollback makes, one + alone carries a function that writes (`commit_write`, `record_marker`, + `switch_to_files`, `record_mirror_state`), and that call is step 1's one + request, `BEGIN ISOLATION LEVEL SERIALIZABLE`, the `commit_write` call, + then `COMMIT` (section 3.2's shim logs each call as sent). The database + then holds what that one call leaves. +- THE SECOND SESSION of `[lost-turn-rechecks-step-0]` is the fixture's + superuser holding `register_head`'s row `FOR UPDATE`. The divergence is + recorded in that same session, as REGISTER-WRITER by `record_mirror_state`, + so its `COMMIT` records it and releases the row at once. The shim holds the + rollback's second read (the second call carrying `diverged_sha`) until + then, so the read after the lost turn is the one that finds the divergence, + whatever the machine's speed. +- "THE DATABASE UNREACHABLE" is a configuration whose URLs name the cluster's + socket directory at a port where no server listens. The database itself, + read by the test, shows the switch, the marker and the head unchanged. +- THE CONSTANT: the shipped `lanes-index` must carry `RENDER_GIT_HALF = + False`. Each id says so where it does not (lane 3's T328 sets it True), since + the scratch-schema rule holds only while it is unset. Once T328 has set it, + with one `RENDER_GIT_HALF = True` line, each id skips before its setup, + saying why (`CONSTANT_SET`; tasks:2511). Anything else fails. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import re +import shutil +import signal +import subprocess +import sys +import time +import uuid +from pathlib import Path +from types import SimpleNamespace +from urllib.parse import quote + +import pytest + +from conftest import WINDOWS_SKIP +from pgcluster import SUPERUSER, Database +from sql_register_helpers import (LANES_INDEX, PSQL_SHIM, PSQL_SHIM_CONTROL, PSQL_SHIM_LOG, + REGISTER_FAKE_PSQL, RENDER_GIT_HALF_LINE, flipped_copy, + guard_strip_env) + +pytestmark = [WINDOWS_SKIP] + +#: THE LANDING GATE'S TABLE (T280; `tests/sql_register_gate.py` reads it): the +#: tasks each id waits for, from T273's Order (tasks:2512 at 204145ae). In a +#: gated run an id is skipped while any of its tasks has no marker in +#: `tests/sql_register_landed/`. T281 removes it with the gate. +SQL_REGISTER_GATE_TABLE = { + "test_a_cutover_and_a_rollback_leave_exactly_two_operator_entries": ("T121", "T304", "T326"), # T273; tasks:2512 + "test_a_files_mode_claim_after_rollback_leaves_one_holder": ("T121", "T304", "T326"), # T273; tasks:2512 + "test_a_missed_primary_writer_is_refused_after_rollback": ("T111", "T121", "T304", "T326", "T327", "T415", "T416", "T420"), # T273; tasks:2512 + "test_a_missed_writer_is_refused_once_the_partitioned_rollback_completes": ("T111", "T121", "T304", "T326", "T327", "T415", "T416", "T420"), # T273; tasks:2512 + "test_a_reimport_after_a_rollback_continues_the_journal": ("T121", "T304", "T326"), # T273; tasks:2512 + "test_a_rerun_after_an_unconfirmed_removal_and_a_files_mode_write_ends_0_with_the_marker_absent": ("T121", "T304", "T326"), # T273; tasks:2512 + "test_a_rollback_entry_over_a_recorded_divergence_is_lr012": ("T107", "T109"), # T273; tasks:2512 + "test_a_rollback_finds_a_stray_not_yet_recorded_records_it_and_exits_2": ("T121", "T304", "T326"), # T273; tasks:2512 + "test_a_rollback_goes_back_to_its_check_on_each_lost_turn_code": ("T326",), # T273; tasks:2512 + "test_a_rollback_goes_back_to_its_check_past_a_last_error_and_refuses_a_divergence_recorded_meanwhile": ("T121", "T304", "T326"), # T273; tasks:2512 + "test_a_rollback_rerun_resumes_after_its_own_entry": ("T121", "T304", "T326"), # T273; tasks:2512 + "test_a_rollback_retries_a_lost_turn_on_a_fresh_k_through_its_check": ("T121", "T304", "T326"), # T273; tasks:2512 + "test_a_write_that_committed_before_the_rollback_is_found_by_its_rerun_after_it": ("T121", "T304", "T326", "T327", "T415", "T416", "T417"), # T273; tasks:2512 + "test_rollback_exits_2_on_lr012_naming_the_divergence_and_both_ways_out": ("T107", "T109", "T121", "T304"), # T273; tasks:2512 + "test_rollback_from_a_partitioned_clone_is_refused_and_removes_no_marker": ("T121", "T304", "T326"), # T273; tasks:2512 + "test_rollback_leaves_files_byte_identical_marker_gone_and_sql_writes_refused": ("T121", "T304", "T326"), # T273; tasks:2512 + "test_rollback_refuses_to_start_while_the_mirror_is_diverged": ("T121", "T304", "T326"), # T273; tasks:2512 + "test_rollback_steps_0_and_1_run_only_against_a_scratch_schema": ("T107", "T109", "T121", "T304"), # T273; tasks:2512 + "test_rollback_with_the_database_stopped_is_refused_and_changes_neither_switch_nor_marker": ("T121", "T304", "T326"), # T273; tasks:2512 + "test_the_marker_removal_entry_is_written_with_the_switch_in_step_1": ("T121", "T304", "T326"), # T273; tasks:2512 + "test_the_rollback_oracle_fails_on_a_last_fetched_tip_writer": ("T121", "T304", "T326"), # T273; tasks:2512 + "test_the_rollback_oracle_fails_on_a_switch_reset_when_the_database_returns": ("T121", "T304", "T326"), # T273; tasks:2512 +} + +#: The scratch schema the cases bootstrap: any `register_schema=` but the +#: default (Y:2323; lane 2's reading, NOTES question 6). +SCRATCH = "t273_scratch" +DEFAULT_SCHEMA = "lanes_register" +WRITER, READER = "lanes_register_writer", "lanes_register_reader" + +#: The logins `lanes-index` connects as, made once per cluster (roles are +#: cluster-wide), members of the writer and the reader groups, with no +#: password: the cluster's socket trusts them. +LOGIN_WRITER, LOGIN_READER = "t273_register_writer", "t273_register_reader" + +#: The bootstrap's admin service and the switch's label, which the +#: configuration's `register_label=` names too (the declaration's `database=`). +ADMIN_SERVICE = "t273_admin" +LABEL = "t273" + +#: The operator lane (D24; F12), this workstation (Rule 10) and git's author +#: (D15), through git's own variables and no git configuration. +OPERATOR_LANE = "t273-operator" +WS = "ws-t273" +AUTHOR = "T273 operator <t273@example.invalid>" +OPERATOR_GIT = {"GIT_AUTHOR_NAME": "T273 operator", "GIT_AUTHOR_EMAIL": "t273@example.invalid", + "GIT_COMMITTER_NAME": "T273 operator", + "GIT_COMMITTER_EMAIL": "t273@example.invalid", + "GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": os.devnull} + +#: What AT-LR006's entries carry. +COMMIT_C, TREE_C, MARKER_COMMIT = "c" * 40, "d" * 40, "e" * 40 +ARGS_SHA256 = "a" * 64 +NOT_AFTER = "2100-01-01T00:00:00Z" +LANES_MD = ["# Lanes"] +STORE_UTC = "2026-11-11T10:00:00Z" +STORE_LINES = ("store=primary", f"database={LABEL}", f"import={COMMIT_C}", + f"lanes-tree={TREE_C}", f"utc={STORE_UTC}") + +#: The divergences the cases record, and who records them. +SHA_DIVERGED, SHA_MEANWHILE = "1" * 40, "2" * 40 +WS_MEANWHILE = "ws-t273-meanwhile" + +#: The configuration's own values (`c`, `n_a`), so neither is the default. +CONNECT_TIMEOUT, ADDRESSES = 3, 2 + +#: The functions that write, which "one transaction" counts. +WRITE_CALLS = ("commit_write(", "record_marker(", "switch_to_files(", "record_mirror_state(") + +#: The declaration's file, beside the configuration (D20; config.md section 6.1). +OUTAGE_FILE = "register-outage" + +#: The second session's `application_name`, which the case waits on. +HOLDER = "t273-holder" + + +def _private(path: Path, text: str) -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + path.chmod(0o600) + return path + + +def _said(proc) -> str: + return (f"exit {proc.returncode}\n--- stdout ---\n{(proc.stdout or '')[-3000:]}" + f"\n--- stderr ---\n{(proc.stderr or '')[-3000:]}") + + +def _render_git_half() -> list: + """The shipped `lanes-index`'s `RENDER_GIT_HALF = ` values, each line's + `True` or `False`; none where it cannot be read.""" + try: + return RENDER_GIT_HALF_LINE.findall(LANES_INDEX.read_bytes()) + except OSError: + return [] + + +#: T328'S CONSTANT SET (tasks:2511; lane 2, #165 6859084292; lane 3's sweep, +#: #165 6851829112). T304's own test reads the shipped `lanes-index`'s +#: `RENDER_GIT_HALF = ` line at collection, before its setup. With one True +#: line, T328's, each of its six ids skips with this reason, which never holds +#: `tests/pgcluster.py`'s `SKIP_TAG`, so no run counts it as a real-engine +#: skip. With one False line they run. Anything else fails at +#: `_constant_unset()`. +CONSTANT_SET = ( + "RENDER_GIT_HALF = True in the shipped lanes-index (lane 3's T328): the scratch-schema " + "rule this test checks ends with T328, and test 8's and AT-F1's cases carry steps 0 and 1 " + "on lanes_register") + + +def _constant_unset() -> None: + """The shipped `lanes-index` carries Q6(c)'s constant unset: the + scratch-schema rule this test checks holds only while it does.""" + found = _render_git_half() + assert found == [b"False"], ( + f"{LANES_INDEX} carries {found!r} for `RENDER_GIT_HALF = `, not one False line: T304's " + f"own test runs the shipped lanes-index with the constant unset (B10 tasks:1015), and " + f"lane 3's T328 sets it") + + +# ------------------------------------------------------------------ AT-LR006's entries +def _rendered(lines) -> str: + """The sha256 of a file of `lines`, LF-joined with a final LF, as + `render_file` renders it.""" + return hashlib.sha256(("\n".join(lines) + "\n").encode("utf-8")).hexdigest() + + +def _entry(kind: str, verb: str, **parts) -> dict: + """One `commit_write` entry: the journal object, `not_after`, and `parts`.""" + journal = {"kind": kind, "verb": verb, "lane": OPERATOR_LANE, "workstation": WS, + "author": AUTHOR, "message": f"t273: {kind}"} + journal.update(parts.pop("journal", {})) + return {"journal": journal, "not_after": NOT_AFTER, **parts} + + +def _import_entry() -> dict: + edits = [{"ord": 1, "op": "create", "path": "lanes/LANES.md"}] + edits += [{"ord": n, "op": "append", "path": "lanes/LANES.md", "new_text": text} + for n, text in enumerate(LANES_MD, start=2)] + return _entry("import", "import", journal={"git_commit": COMMIT_C, "git_tree": TREE_C}, + edits=edits, files=[{"path": "lanes/LANES.md", "present": True, + "sha256": _rendered(LANES_MD), "final_newline": True}]) + + +def _cutover_entry() -> dict: + edits = [{"ord": 1, "op": "create", "path": "lanes/STORE"}] + edits += [{"ord": n, "op": "append", "path": "lanes/STORE", "new_text": line} + for n, line in enumerate(STORE_LINES, start=2)] + return _entry("cutover", "cutover", edits=edits, + files=[{"path": "lanes/STORE", "present": True, + "sha256": _rendered(STORE_LINES), "final_newline": True}]) + + +def _write_entry(text: str) -> dict: + """A write that appends `text` to `lanes/LANES.md`.""" + return _entry("write", "log", journal={"args_sha256": ARGS_SHA256}, + edits=[{"ord": 1, "op": "append", "path": "lanes/LANES.md", "new_text": text}], + files=[{"path": "lanes/LANES.md", "present": True, + "sha256": _rendered([*LANES_MD, text]), "final_newline": True}]) + + +def _open_when_held(fifo: Path, proc: subprocess.Popen, seconds: float = 120): + """The FIFO's write end, opened once the shim holds a call on it; None + where `proc` ends, or the time runs out, first. Closing it releases the + call.""" + deadline = time.monotonic() + seconds + while time.monotonic() < deadline and proc.poll() is None: + try: + return os.open(str(fifo), os.O_WRONLY | os.O_NONBLOCK) + except OSError: + time.sleep(0.05) + return None + + +# ------------------------------------------------------------------ the register +class RollbackRegister: + """A database of the session cluster, from `template0`, bootstrapped by + `lanes-index bootstrap` for `SCRATCH` (T109; DEC-23), brought to `primary` + with the marker `present` by AT-LR006's route at head `k`, and section + 3.2's shim in front of the real `psql` for every `lanes-index` run here.""" + + def __init__(self, cluster, root: Path): + self.cluster, self.root = cluster, root + root.mkdir(parents=True, exist_ok=True) + name = f"t273_{uuid.uuid4().hex[:8]}" + cluster.psql(f"CREATE DATABASE {name} TEMPLATE template0;") + self.db = Database(cluster, name) + try: + self._bootstrap() + for login, group in ((LOGIN_WRITER, WRITER), (LOGIN_READER, READER)): + self.sql(f"DO $l$ BEGIN CREATE ROLE {login} LOGIN IN ROLE {group}; " + f"EXCEPTION WHEN duplicate_object THEN NULL; END $l$;") + self.k = self._to_primary() + except BaseException: + cluster.drop_database(name) + raise + self.shim = root / "shim" + self.shim.mkdir() + (self.shim / "psql").write_text(PSQL_SHIM, encoding="utf-8") + (self.shim / "psql").chmod(0o755) + self.arm([]) + (root / "operator").mkdir() + + def drop(self) -> None: + self.cluster.drop_database(self.db.name) + + # ---------------------------------------------------------------- the SQL side + def psql(self, script: str, role: str = None, appname: str = "t273") -> subprocess.CompletedProcess: + """One `psql` as the fixture's superuser, as `role` where one is named, + with the commit call's settings, so a refusal's first stderr line is + `ERROR: <SQLSTATE>: <message>`.""" + head = "\\set VERBOSITY verbose\n\\set SHOW_CONTEXT never\nSET client_encoding = 'UTF8';\n" + if role: + head += f"SET ROLE {role};\n" + return subprocess.run([self.db.psql_bin, "-X", "-q", "-A", "-t", "-v", "ON_ERROR_STOP=1"], + input=head + script, capture_output=True, encoding="utf-8", + errors="replace", env=self.db.env(appname=appname), timeout=120, + check=False) + + def sql(self, script: str, role: str = None) -> str: + proc = self.psql(script, role) + assert proc.returncode == 0, (f"psql{' as ' + role if role else ''} exited " + f"{proc.returncode}: {proc.stderr.strip()}\n{script}") + return proc.stdout.strip() + + def _bootstrap(self) -> None: + """`lanes-index bootstrap` through the admin service, with a + configuration that holds `register_schema=` `SCRATCH` alone.""" + home = self.root / "admin" + _private(home / ".pg_service.conf", + f"[{ADMIN_SERVICE}]\nhost={self.db.host}\nport={self.db.port}\n" + f"dbname={self.db.name}\nuser={SUPERUSER}\n") + conf = _private(self.root / "boot" / "lanes-index.conf", f"register_schema={SCRATCH}\n") + env = guard_strip_env(os.environ, strip=("XDG_",)) + env.update(HOME=str(home), XDG_CONFIG_HOME=str(home / ".config"), + XDG_STATE_HOME=str(self.root / "admin-state"), LANES_WORKSTATION=WS, + LANES_INDEX_CONFIG=str(conf)) + proc = subprocess.run([sys.executable, str(LANES_INDEX), "bootstrap", "--admin-service", + ADMIN_SERVICE, "--label", LABEL, "--repository", "opensoft/t273", + "--lane", OPERATOR_LANE, "--no-passwords"], + capture_output=True, encoding="utf-8", errors="replace", env=env, + timeout=300, stdin=subprocess.DEVNULL, check=False) + assert proc.returncode == 0, (f"the scratch schema's bootstrap (T109's DEC-23 rendering) " + f"failed:\n{_said(proc)}") + schemas = self.sql(f"SELECT string_agg(nspname, ',' ORDER BY nspname) FROM pg_namespace " + f"WHERE nspname IN ('{SCRATCH}', '{DEFAULT_SCHEMA}');") + assert schemas == SCRATCH, (f"the bootstrap for {SCRATCH} made the schemas {schemas!r}, " + f"not {SCRATCH} alone") + + def window(self) -> dict: + return json.loads(self.sql(f"SELECT to_jsonb(v) FROM {SCRATCH}.schema_version v;")) + + def commit(self, base: int, body: dict, what: str) -> int: + """The commit call as a writer sends it (section 1.3's step 3; AT-LR006's + fixture): one SERIALIZABLE transaction around `commit_write`, as + REGISTER-WRITER. Returns the entry's seq.""" + literal = json.dumps(body, ensure_ascii=True).replace("'", "''") + proc = self.psql(f"BEGIN ISOLATION LEVEL SERIALIZABLE;\n" + f"SELECT {SCRATCH}.commit_write({base}, '{uuid.uuid4()}'::uuid, " + f"{self.window()['version']}, '{self.switch()['generation']}'::uuid, " + f"'{literal}'::jsonb);\nCOMMIT;\n", WRITER) + assert proc.returncode == 0, f"{what}: commit_write refused it: {proc.stderr.strip()}" + return int(proc.stdout.strip().splitlines()[-1]) + + def _to_primary(self) -> int: + """AT-LR006's route (TP:4610-4615): an import, a cutover and + `record_marker`, then one write. Returns the head, `k`.""" + imported = self.commit(self.head(), _import_entry(), "the import") + cut = self.commit(imported, _cutover_entry(), "the cutover") + marker = self.sql(f"SELECT {SCRATCH}.record_marker({self.window()['version']}, {cut}, " + f"'{MARKER_COMMIT}', '{WS}');", WRITER) + assert marker == "present", f"record_marker answered {marker!r}, not present" + k = self.commit(cut, _write_entry("t273: a write after the cutover"), "the write") + switch = self.switch() + assert (switch["mode"], switch["marker_state"], k) == ("primary", "present", 2), ( + f"AT-LR006's route left the switch {switch} and the head {k}, not primary, present " + f"and 2") + return k + + def switch(self) -> dict: + return json.loads(self.sql(f"SELECT to_jsonb(s) FROM {SCRATCH}.register_switch s;")) + + def head(self) -> int: + return int(self.sql(f"SELECT seq FROM {SCRATCH}.register_head;")) + + def mirror(self) -> dict: + return json.loads(self.sql(f"SELECT to_jsonb(m) FROM {SCRATCH}.mirror_state m;")) + + def journal(self) -> list: + """Each entry's seq, kind and generated `operator` flag, by seq.""" + return json.loads(self.sql( + f"SELECT coalesce(jsonb_agg(jsonb_build_array(j.seq, j.kind, j.operator) " + f"ORDER BY j.seq), '[]') FROM {SCRATCH}.journal j;")) + + def state(self) -> dict: + """The switch whole, the head and the journal: what "does not move" compares.""" + return {"switch": self.switch(), "head": self.head(), "journal": self.journal()} + + def wait_sql(self, count_query: str, what: str, ceiling: float = 10.0) -> None: + """Poll `count_query` in 0.05 s steps under `ceiling` until it counts + one row or more.""" + end = time.monotonic() + ceiling + while time.monotonic() < end: + if self.sql(count_query) != "0": + return + time.sleep(0.05) + pytest.fail(f"{what}: not seen within {ceiling} s") + + # ---------------------------------------------------------------- lanes-index + def config(self, name: str, *, schema: str | None = SCRATCH, port: int | None = None) -> Path: + """A 0600 `lanes-index.conf` in a directory of its own: `mode=index`, + the URLs of the cluster's socket (at `port` where it is given), the + label, and `register_schema=` `schema` where it is not None.""" + where = (f"{quote(str(self.db.host), safe='')}:{self.db.port if port is None else port}" + f"/{self.db.name}?connect_timeout={CONNECT_TIMEOUT}") + lines = ["mode=index", f"register_url=postgresql://{LOGIN_WRITER}@{where}", + f"reader_url=postgresql://{LOGIN_READER}@{where}", + f"register_addresses={ADDRESSES}", f"register_label={LABEL}"] + if schema is not None: + lines.append(f"register_schema={schema}") + return _private(self.root / name / "lanes-index.conf", "\n".join(lines) + "\n") + + def env(self, conf: Path) -> dict: + """The operator lane's environment (D24): no inherited `PG*`, lane, + session, git or XDG variable; `LANES_LANE`, this workstation, git's + author, the configuration, and the shim first on `PATH`.""" + env = guard_strip_env(os.environ, strip=("GIT_", "XDG_", "EMAIL")) + env.update(HOME=str(self.root / "home"), XDG_STATE_HOME=str(self.root / "state"), + XDG_CONFIG_HOME=str(self.root / "config"), LANES_INDEX_CONFIG=str(conf), + LANES_LANE=OPERATOR_LANE, LANES_WORKSTATION=WS, + PATH=f"{self.shim}{os.pathsep}{os.environ.get('PATH', os.defpath)}", + **OPERATOR_GIT) + return env + + def argv(self) -> list: + return [sys.executable, str(LANES_INDEX), "rollback"] + + def rollback(self, conf: Path) -> subprocess.CompletedProcess: + """`lanes-index rollback`, the shipped one, in the operator's directory.""" + return subprocess.run(self.argv(), capture_output=True, encoding="utf-8", + errors="replace", env=self.env(conf), cwd=str(self.root / "operator"), + timeout=180, stdin=subprocess.DEVNULL, check=False) + + def arm(self, arms: list) -> None: + (self.shim / PSQL_SHIM_CONTROL).write_text( + json.dumps({"psql": self.db.psql_bin, "arms": arms}), encoding="utf-8") + + def calls(self) -> list: + """The shim's entries that carried a request, in call order.""" + log = self.shim / PSQL_SHIM_LOG + if not log.exists(): + return [] + entries = [json.loads(line) for line in log.read_text(encoding="utf-8").splitlines() + if line] + return [entry for entry in entries if entry.get("kind") != "version"] + + def writes(self) -> list: + """The calls that carried a function that writes (`WRITE_CALLS`).""" + return [c for c in self.calls() if any(w in c.get("sent", "") for w in WRITE_CALLS)] + + +@pytest.fixture +def rb_register(pg_cluster, tmp_path): + reg = RollbackRegister(pg_cluster, tmp_path / "reg") + try: + yield reg + finally: + reg.drop() + + +# =================================================================== T304's own test +def _diverged_refuses_2(reg: RollbackRegister) -> None: + proc = reg.psql(f"SELECT {SCRATCH}.record_mirror_state('{WS}', '{SHA_DIVERGED}', NULL);", + WRITER) + assert proc.returncode == 0, f"record_mirror_state refused the divergence: {proc.stderr}" + before = reg.state() + conf = reg.config("conf") + proc = reg.rollback(conf) + assert proc.returncode == 2, f"a rollback with a divergence recorded is not refused 2:\n{_said(proc)}" + assert f"diverged at {SHA_DIVERGED}" in proc.stderr, _said(proc) + for way in ("import --single", "render --revert"): + assert way in proc.stderr, f"the refusal does not name S2's way out {way!r}:\n{_said(proc)}" + assert reg.writes() == [], ( + f"step 0's database half did not refuse before step 1: a call that writes was sent: " + f"{[c.get('sent') for c in reg.writes()]}") + assert reg.state() == before, "the refused rollback moved the switch, the marker or the head" + assert not (conf.parent / OUTAGE_FILE).exists(), "the refused rollback declared the outage" + + +def _step_1_one_transaction(reg: RollbackRegister) -> None: + k = reg.k + proc = reg.rollback(reg.config("conf")) + switch = reg.switch() + assert (switch["mode"], switch["marker_state"]) == ("files", "removing"), ( + f"step 1 left the switch {switch}, not files with the marker removing:\n{_said(proc)}") + assert (switch["set_seq"], switch["marker_seq"]) == (k + 1, k + 1), ( + f"set_seq and marker_seq are not the rollback's own seq {k + 1}: {switch}") + assert reg.head() == k + 1, f"the head is {reg.head()}, not k+1 = {k + 1}:\n{_said(proc)}" + journal = reg.journal() + assert journal[-1] == [k + 1, "rollback", True], ( + f"the last entry is {journal[-1]}, not the operator's rollback entry at {k + 1}: {journal}") + assert [seq for seq, _kind, _operator in journal] == list(range(k + 2)), journal + edits = json.loads(reg.sql( + f"SELECT coalesce(jsonb_agg(jsonb_build_array(e.ord, e.op, e.path) ORDER BY e.ord), '[]') " + f"FROM {SCRATCH}.journal_edits e WHERE e.seq = {k + 1};")) + assert edits == [[1, "remove", "lanes/STORE"]], f"the rollback's entry's edits are {edits}" + files = json.loads(reg.sql( + f"SELECT coalesce(jsonb_agg(jsonb_build_array(f.path, f.present) ORDER BY f.path), '[]') " + f"FROM {SCRATCH}.journal_files f WHERE f.seq = {k + 1};")) + assert files == [["lanes/STORE", False]], f"the rollback's entry's files rows are {files}" + writes = reg.writes() + assert len(writes) == 1 and "commit_write(" in writes[0]["sent"], ( + f"not one call that writes, step 1's commit call: " + f"{[c.get('sent', '')[:300] for c in writes]}") + sent = writes[0]["sent"] + begin, call, end = (sent.find("BEGIN ISOLATION LEVEL SERIALIZABLE"), + sent.find("commit_write("), sent.rfind("COMMIT")) + assert 0 <= begin < call < end, ( + f"step 1's call is not one SERIALIZABLE transaction around commit_write: {sent[:600]}") + + +def _outage_declared_with_mirror_seq(reg: RollbackRegister) -> None: + k = reg.k + conf = reg.config("conf") + proc = reg.rollback(conf) + path = conf.parent / OUTAGE_FILE + assert path.exists(), (f"the rollback's start declared no outage beside its configuration " + f"({path}):\n{_said(proc)}") + lines = path.read_text(encoding="utf-8").splitlines() + fields = dict(line.split("=", 1) for line in lines) + assert lines[0] == "format=1", lines + assert (fields.get("kind"), fields.get("mirror-seq")) == ("rollback", str(k)), ( + f"the declaration is not marked as from a rollback with mirror-seq k = {k}: {lines}") + assert (fields.get("database"), fields.get("host")) == (LABEL, WS), lines + assert "until" not in fields, f"a rollback's declaration carries an expiry: {lines}" + assert "outage declared:" in proc.stdout, _said(proc) + + +def _lost_turn_rechecks_step_0(reg: RollbackRegister) -> None: + k = reg.k + before = reg.state() + fifo = reg.root / "hold.fifo" + os.mkfifo(str(fifo), 0o600) + # The rollback's second read, the second call carrying `diverged_sha`, is held. + reg.arm([{"mode": "hold", "fifo": str(fifo), "match": "diverged_sha", "call": 2}]) + holder = reg.db.session(appname=HOLDER) + proc, fd = None, None + try: + holder.stdin.write(f"BEGIN;\nSELECT seq FROM {SCRATCH}.register_head WHERE id = 1 " + f"FOR UPDATE;\n") + holder.stdin.flush() + reg.wait_sql(f"SELECT count(*) FROM pg_stat_activity WHERE application_name = '{HOLDER}' " + f"AND state = 'idle in transaction' AND backend_xid IS NOT NULL;", + "the second session's lock on the head row") + proc = subprocess.Popen(reg.argv(), stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, text=True, + env=reg.env(reg.config("conf")), cwd=str(reg.root / "operator")) + fd = _open_when_held(fifo, proc) + assert fd is not None, "the rollback never reached a second read: it did not lose its turn" + # Step 1's call has ended; the divergence is recorded and the row released at once. + out, err = holder.communicate( + input=(f"SET ROLE {WRITER};\nSELECT {SCRATCH}.record_mirror_state('{WS_MEANWHILE}', " + f"'{SHA_MEANWHILE}', NULL);\nCOMMIT;\n"), timeout=60) + assert holder.returncode == 0, f"the second session could not record the divergence: {err}" + assert reg.mirror()["diverged_sha"] == SHA_MEANWHILE, reg.mirror() + os.close(fd) + fd = None + out, err = proc.communicate(timeout=120) + finally: + if fd is not None: + os.close(fd) + for p in (proc, holder): + if p is not None and p.poll() is None: + p.kill() + p.wait() + ended = f"exit {proc.returncode}\n--- stdout ---\n{out[-3000:]}\n--- stderr ---\n{err[-3000:]}" + assert proc.returncode == 2, f"the rollback did not end 2 after its lost turn:\n{ended}" + assert "55P03" in err and "lost its turn" in err, ( + f"step 1 did not meet 55P03 at rollback's lock_timeout and go back:\n{ended}") + assert f"diverged at {SHA_MEANWHILE}" in err, ( + f"step 0 did not refuse the divergence recorded meanwhile:\n{ended}") + kinds = ["write" if any(w in c.get("sent", "") for w in WRITE_CALLS) else + "read" if "diverged_sha" in c.get("sent", "") else "other" for c in reg.calls()] + assert kinds == ["read", "write", "read"], ( + f"not step 0's read, step 1's one lost call, then step 0's read afresh: {kinds}") + after = reg.state() + assert after == before, f"the switch, the marker or the head moved: {before} -> {after}" + assert after["head"] == k + + +def _database_unreachable_69(reg: RollbackRegister) -> None: + port = reg.db.port + 1 + assert not (Path(reg.db.host) / f".s.PGSQL.{port}").exists() + before = reg.state() + conf = reg.config("unreachable", port=port) + proc = reg.rollback(conf) + assert proc.returncode == 69, f"a rollback that cannot reach the database is not 69:\n{_said(proc)}" + assert "could not be read" in proc.stderr, _said(proc) + assert reg.calls(), "the rollback sent no read, so it never met the database's silence" + assert reg.writes() == [], "a call that writes was sent" + assert reg.state() == before, "the switch, the marker or the head moved" + assert not (conf.parent / OUTAGE_FILE).exists(), "the failed rollback declared the outage" + + +def _not_a_scratch_schema_2(reg: RollbackRegister) -> None: + before = reg.state() + conf = reg.config("default-schema", schema=None) + proc = reg.rollback(conf) + assert proc.returncode == 2, (f"a rollback with register_schema= unset is not refused 2 " + f"while the constant is unset:\n{_said(proc)}") + assert f"register_schema={DEFAULT_SCHEMA}" in proc.stderr and "scratch schema" in proc.stderr, ( + f"the refusal does not name the default schema and the scratch-schema rule:\n{_said(proc)}") + assert reg.calls() == [], f"the refused rollback sent a request: {reg.calls()}" + assert reg.state() == before, "the switch, the marker or the head moved" + assert not (conf.parent / OUTAGE_FILE).exists(), "the refused rollback declared the outage" + + +T304_CASES = { + "diverged-refuses-2": _diverged_refuses_2, + "step-1-one-transaction": _step_1_one_transaction, + "outage-declared-with-mirror-seq": _outage_declared_with_mirror_seq, + "lost-turn-rechecks-step-0": _lost_turn_rechecks_step_0, + "database-unreachable-69": _database_unreachable_69, + "not-a-scratch-schema-2": _not_a_scratch_schema_2, +} + + +@pytest.mark.skipif(_render_git_half() == [b"True"], reason=CONSTANT_SET) +@pytest.mark.parametrize("case", list(T304_CASES)) +def test_rollback_steps_0_and_1_run_only_against_a_scratch_schema(rb_register, case): + """T304's own test (R-F10-34): steps 0 and 1 of the shipped `lanes-index + rollback`, the constant unset, on `SCRATCH` at `primary` with the marker + `present` and head `k`. Each id is in the module's docstring.""" + _constant_unset() + T304_CASES[case](rb_register) + + +# =================================================================== T273b: test 8, 4.2, AT-F1 +#: T273b: AT-8's test 8 (11), section 4.2 (2) and AT-F1 (7), as the test plan +#: (TP:1546-1734, TP:5447-5509, TP:7568-7609) and F13d's T273 bullet give them. +#: +#: THE ESTATE (TP:1592-1636). Test 7's cutover host, `CutoverRegister` in +#: `test_sql_register_import.py` (line W3a's T211j, merged into this line for +#: it, as AT-F2's cases build on it): the fixture register at C imported, ws1 +#: the operator lane's checkout (`LANES_LANE=repoA-2`, F12) running T203's +#: flipped copy, so that `rollback` takes `lanes_register` with the renderer's +#: git half; then the cutover, and two writes on primary from ws1, each +#: rendered, so `k` is the head, 3. Test 5's `git` wrapper and section 3.2's +#: shim are first on ws1's `PATH`. ws2, the missed workstation, is a clone of +#: its own with its own `$HOME` and a `mode=primary` configuration, lane +#: `repoW-1`, and a shim of its own. +#: +#: WHAT EACH WAITS FOR. Every estate case fails until lane 3's T327 (the +#: cutover's push and read-back, so the marker reads `present`), lane 4's +#: T415 and T416 (a write on primary, and its render's fork), lane 3's T321 to +#: T323 (the render), and T326 (step 0's fetch and steps 2 to 4). Of the +#: missed writer's ids, the eight `commit-*` also wait for lane 4's T420 +#: (D10's refusals on primary), and the other 40 for lane 1's T111 (AT-3's +#: line in check 4's 69); case (i) also waits for T417 (exit 3 and its +#: rerun). No id waits for lane 4's T421 or lane 5's T507: none runs the +#: guard, and with T421's merge reverted the `claim` ids fail as they do with +#: it (T273's Order, tasks:2512 at 204145ae; lane 2's RB15; lane 4, #165 +#: 6826679959). `test_a_rollback_entry_over_a_recorded_divergence_is_lr012` (direct +#: calls, lane 1's T107) and `test_rollback_exits_2_on_lr012_naming_the_ +#: divergence_and_both_ways_out` (a False copy on the scratch schema, T304) +#: need neither, and can pass on line R now. The four FP lost-turn ids need +#: no engine, and fail until T326, at their own assertion. +#: +#: READINGS, NOT FOUND IN A CONTRACT: +#: - "A fetch of `origin main`" is a `git fetch` whose arguments name +#: `origin`, logged by the wrapper; "between" two `psql` calls is read from +#: the wrapper's own count of the requests the shim or the fake had logged +#: when the fetch started, so no clock is shared. +#: - The held session of (g) and of T304's lost turn is the fixture's +#: superuser holding `register_head`'s row `FOR UPDATE`, not a writer +#: replaying a commit call: the rollback's call meets the same lock, and a +#: divergence recorded meanwhile then fails its `FOR SHARE` read of +#: `mirror_state` with 40001 in the same way. +#: - (g)'s `[last-error-only]` and AT-F1's retries read "the marker +#: `removing`" as step 1's state: where T326's steps 2 to 4 have run to +#: their end, the marker reads `absent` and the rollback exits 0, which the +#: case accepts too. +#: - (c)'s ids are `<verb>-<fetch>-<no_fetch>`, with `fetched` or +#: `not-fetched`, and `unset` or `no-fetch` for `LANES_NO_FETCH`. +#: - AT-F1's removal entry and rerun cases run on the clean estate, not after +#: a single-write import: what they check is step 1 and the rerun, which the +#: import does not change. +#: - (h)'s FP register is a clean estate at `Register-Seq: 1`: the import at +#: 0, whose images are the workspace's render set, and the cutover at 1, the +#: head, with no divergence. The fake answers from it every read a try makes +#: before step 1, T326's git half's two included (`HEAD_READ_MARK` and +#: `IMAGE_READ_MARK`), so each try's check passes and reaches step 1's lost +#: turn (lane 3's #165 6813528630). + +EM, DOT = chr(0x2014), chr(0xB7) +#: AT-3's line, which the missed writer's refusal carries (TP:1651-1652). +AT3_LINE = "this estate's register is SQL; configure `mode=primary`" +#: The missed workstation's lane: a LIVE row of test 7's fixture register. +MISSED_LANE = "repoW-1" +#: The object every `claim` case names, held by no lane at C. +CLAIMED = "opensoft/repoQ#8" +VERB_NAMES = ("set-row-state", "replace-in-row", "append-session-id", "append-line", "commit", + "claim") +MISSED_CASES = [f"{verb}-{fetch}-{no_fetch}" for verb in VERB_NAMES + for fetch in ("fetched", "not-fetched") for no_fetch in ("unset", "no-fetch")] +#: The text the `commit` case's hand edit changes in `MISSED_LANE`'s row. +ROW_TEXT = "its log has WORD lines" +#: A `Register-Seq` trailer. +REGISTER_SEQ = re.compile(r"^Register-Seq: ([0-9]+)$", re.M) +#: The rollback's read, and its step-1 call, as the shim and the fake see them. +READ_MARK, STEP_1_MARK = "diverged_sha", "commit_write(" +EXIT_BUSY = 75 +#: A push it cannot confirm (exit-codes.md's 3; ops:340). +EXIT_IN_DOUBT = 3 + + +def _imp(): + """`test_sql_register_import`: test 7's fixture register and cutover host.""" + import test_sql_register_import as module + return module + + +def _cut(): + """`test_sql_register_cutover`: AT-F2's fixture, `F2Register`, test 7's + cutover host with test 5's `git` wrapper, whose arms leave a push + unconfirmed, and `_first_reach`.""" + import test_sql_register_cutover as module + return module + + +def _script(path: Path, text: str) -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + path.chmod(0o755) + return path + + +def _jsonl(path: Path) -> list: + if not path.exists(): + return [] + return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line] + + +def _requests(log: Path) -> list: + """A `psql` log's entries that carried a request: never a `--version`.""" + return [entry for entry in _jsonl(log) if entry.get("kind") != "version"] + + +#: TEST 5'S `git` WRAPPER (TP:1060-1080), with what AT-8 needs: each call is +#: one JSON line of `git-wrapper.log`, its subcommand, its argv, its pid, and +#: `psql_before`, the number of requests the `psql` log named in the control +#: file held when it started. `hold`, `{"call": <subcommand>, "fifo": path}`, +#: blocks that call on the FIFO until the test closes its end. +GIT_WRAPPER = r'''#!/usr/bin/env -S python3 -I +import json, os, subprocess, sys +HERE = os.path.dirname(os.path.abspath(__file__)) +CONTROL = os.path.join(HERE, "git-wrapper.json") +LOG = os.path.join(HERE, "git-wrapper.log") +WITH_VALUE = {"-C", "-c", "--git-dir", "--work-tree", "--namespace", "--exec-path", + "--config-env"} + + +def subcommand(args): + i = 0 + while i < len(args): + if args[i] in WITH_VALUE: + i += 2 + elif args[i].startswith("-"): + i += 1 + else: + return args[i] + return "" + + +def requests(path): + try: + with open(path, encoding="utf-8") as handle: + return sum(1 for line in handle + if line.strip() and json.loads(line).get("kind") != "version") + except (OSError, ValueError): + return 0 + + +def log(record): + with open(LOG, "a", encoding="utf-8") as handle: + handle.write(json.dumps(record) + "\n") + + +def main(): + args = sys.argv[1:] + with open(CONTROL, encoding="utf-8") as handle: + control = json.load(handle) + sub = subcommand(args) + record = {"sub": sub, "argv": args, "pid": os.getpid(), + "psql_before": requests(control.get("psql_log") or "")} + hold = control.get("hold") + if hold and hold.get("call") == sub: + log(dict(record, outcome="held")) + with open(hold["fifo"], "rb") as fifo: + fifo.read() + rc = subprocess.run([control["git"]] + args).returncode + log(dict(record, outcome="ran", rc=rc)) + return rc + + +sys.exit(main()) +''' + + +def _real_git() -> str: + found = shutil.which("git") + assert found, "no git on PATH" + return found + + +def _lane_checkout(origin: Path, checkout: Path, lane: str, env: dict) -> Path: + """`<c>`, THE WRITE LANE'S OWN CHECKOUT (lane 3's batch g Q119, #165 + 6813027223): beside the checkout `workspace.yaml` names as W, at + `<W>-lanes/<lane>`, W being its real path, as `lane_checkout_path` puts + it (Amendment 23 S1). On primary a write reads its author, its pending + hand edits and its `repos.tsv` from there, and refuses 2 where it is not + there, "Nothing was sent" (B15 tasks:1154). A clone of W's own origin, as + `lane-checkout <lane> --create` makes one, made after the case's last + push from W, as LX's T253f and N2's T243f make theirs. One that is + already there is kept, so a register that makes its own keeps it.""" + real = Path(os.path.realpath(checkout)) + target = real.parent / f"{real.name}-lanes" / lane + if not target.exists(): + target.parent.mkdir(parents=True, exist_ok=True) + subprocess.run(["git", "clone", "-q", str(origin), str(target)], check=True, env=env, + capture_output=True, stdin=subprocess.DEVNULL) + return target + + +class MissedWorkstation: + """ws2, THE MISSED WORKSTATION (TP:1600-1604): a clone of origin of its + own, its own `$HOME` and `workspace.yaml`, a `mode=primary` + configuration naming the same database, lane `MISSED_LANE`, the flipped + copy's `lanes-edit.sh`, and a shim of its own first on `PATH`.""" + + def __init__(self, estate: "RollbackEstate", name: str): + reg = estate.reg + self.estate, self.root = estate, estate.root / name + self.home = self.root / "home" + agents = self.home / ".agents" + agents.mkdir(parents=True) + self.clone = self.home / "projects" / "wip" + subprocess.run(["git", "clone", "-q", str(reg.origin), str(self.clone)], check=True, + env=reg.env, capture_output=True, stdin=subprocess.DEVNULL) + # `MISSED_LANE`'s `<c>`, cloned with W: a ws2 kept behind the + # rollback's push keeps it behind too (Q119), and `fetch` moves both. + self.c = _lane_checkout(reg.origin, self.clone, MISSED_LANE, reg.env) + (agents / "workspace.yaml").write_text(f"repository: {reg.origin}\npath: {self.clone}\n", + encoding="utf-8") + self.conf = _private(self.root / "conf" / "lanes-index.conf", + reg.primary_conf.read_text(encoding="utf-8")) + self.shim = self.root / "shim" + _script(self.shim / "psql", PSQL_SHIM) + self.arm([]) + for d in ("state", "config", "tmp"): + (self.root / d).mkdir() + env = dict(reg.env) + env.pop("LANES_INDEX", None) + env.update(HOME=str(self.home), AGENT_PROTOCOL_ROOT=str(agents), + XDG_STATE_HOME=str(self.root / "state"), + XDG_CONFIG_HOME=str(self.root / "config"), TMPDIR=str(self.root / "tmp"), + CLAUDE_CONFIG_DIR=str(self.home / ".claude"), LANES_REPO=str(self.clone), + LANES_INDEX_CONFIG=str(self.conf), LANES_LANE=MISSED_LANE, + LANES_EDIT=str(reg.copy.parent / "lanes-edit.sh"), + PATH=f"{self.shim}{os.pathsep}{reg.env['PATH']}") + self.env = env + + def arm(self, arms: list) -> None: + """The shim's arms, with its log, ends and counters started afresh.""" + (self.shim / PSQL_SHIM_CONTROL).write_text( + json.dumps({"psql": self.estate.db.psql_bin, "arms": arms}), encoding="utf-8") + for name in (PSQL_SHIM_LOG, "psql-shim.ends"): + (self.shim / name).write_text("", encoding="utf-8") + (self.shim / "psql-shim.state").write_text("{}", encoding="utf-8") + + def git(self, *args: str) -> str: + proc = subprocess.run(["git", "-C", str(self.clone), *args], capture_output=True, + text=True, env=self.env, stdin=subprocess.DEVNULL, check=False) + assert proc.returncode == 0, f"git {' '.join(args)} in ws2: {proc.stderr}" + return proc.stdout + + def fetch(self) -> None: + self.git("fetch", "-q", "origin") + subprocess.run(["git", "-C", str(self.c), "fetch", "-q", "origin"], check=True, + env=self.env, capture_output=True, stdin=subprocess.DEVNULL) + + def edit(self, *args: str, env: dict | None = None) -> subprocess.CompletedProcess: + child = dict(self.env) + for key, value in (env or {}).items(): + if value is None: + child.pop(key, None) + else: + child[key] = value + return subprocess.run(["bash", str(self.estate.reg.copy.parent / "lanes-edit.sh"), + *args], capture_output=True, text=True, env=child, + cwd=str(self.clone), timeout=300, stdin=subprocess.DEVNULL) + + def snapshot(self) -> dict: + """ws2's HEAD, its index, its last-fetched tip, and the bytes of every + file under `lanes/` in its work tree.""" + lanes = {str(p.relative_to(self.clone)): hashlib.sha256(p.read_bytes()).hexdigest() + for p in sorted((self.clone / "lanes").rglob("*")) if p.is_file()} + return {"head": self.git("rev-parse", "HEAD").strip(), + "fetched": self.git("rev-parse", "refs/remotes/origin/main").strip(), + "index": hashlib.sha256(self.git("ls-files", "-s").encode()).hexdigest(), + "lanes": lanes} + + def hand_edit(self) -> bool: + """`commit`'s hand edit of `MISSED_LANE`'s row, left uncommitted.""" + path = self.clone / "lanes" / "LANES.md" + text = path.read_text(encoding="utf-8") + if ROW_TEXT not in text: + return False + path.write_text(text.replace(ROW_TEXT, ROW_TEXT + " by hand", 1), encoding="utf-8") + return True + + def undo_hand_edit(self) -> None: + self.git("checkout", "-q", "--", "lanes/LANES.md") + + +def _verb_args(verb: str) -> list: + """The verb's arguments, as lane `MISSED_LANE` writes them (each checked + in files mode on test 7's fixture register).""" + imp = _imp() + return { + "set-row-state": ["set-row-state", MISSED_LANE, f"PAUSED {DOT} test 8"], + "replace-in-row": ["replace-in-row", MISSED_LANE, ROW_TEXT, f"{ROW_TEXT}, test 8"], + "append-session-id": ["append-session-id", MISSED_LANE, f"harness `{imp.UUID_W1}`", + " (test 8)"], + "append-line": ["append-line", f"HOLD {EM} lane {MISSED_LANE} (Eagle), window w, " + f"2026-11-11T00:00:00Z: opensoft/repoQ main {imp.TIP_A} for test 8"], + "commit": ["commit", "test 8's hand edit"], + "claim": ["claim", CLAIMED, "--no-github"], + }[verb] + + +class RollbackEstate: + """TEST 8'S ESTATE (TP:1592-1636), on test 7's cutover host: see the + notes above T273b. `prepare()` makes the cutover and the writes; until + their tasks land it fails at its own assertion, naming them.""" + + def __init__(self, root: Path, db, *, writes: int = 2): + imp = _imp() + self.imp, self.db, self.root, self.writes = imp, db, root, writes + self.bin = root / "bin" + _script(self.bin / "git", GIT_WRAPPER) + _script(self.bin / "psql", PSQL_SHIM) + self.real_git = _real_git() + self.arm() + self.reg = imp.CutoverRegister(root / "ws1", db, extra_path=self.bin) + self.k = None + + # ------------------------------------------------------------ the wrapper and the shim + def arm(self, arms=(), hold: dict | None = None) -> None: + """The shim's arms and the wrapper's hold, each log started afresh.""" + (self.bin / PSQL_SHIM_CONTROL).write_text( + json.dumps({"psql": self.db.psql_bin, "arms": list(arms)}), encoding="utf-8") + for name in (PSQL_SHIM_LOG, "psql-shim.ends", "git-wrapper.log"): + (self.bin / name).write_text("", encoding="utf-8") + (self.bin / "psql-shim.state").write_text("{}", encoding="utf-8") + control = {"git": self.real_git, "psql_log": str(self.bin / PSQL_SHIM_LOG)} + if hold: + control["hold"] = hold + (self.bin / "git-wrapper.json").write_text(json.dumps(control), encoding="utf-8") + + def calls(self) -> list: + return _requests(self.bin / PSQL_SHIM_LOG) + + def git_calls(self) -> list: + return [c for c in _jsonl(self.bin / "git-wrapper.log") if c.get("outcome") == "ran" + or c.get("outcome") == "held"] + + # ------------------------------------------------------------ the database + def rows(self, sql: str) -> list: + return self.imp._rows(self.db, sql) + + def switch(self) -> dict: + return self.rows("SELECT * FROM register_switch")[0] + + def head(self) -> int: + return self.rows("SELECT seq FROM register_head")[0]["seq"] + + def journal(self) -> list: + return [[r["seq"], r["kind"], r["operator"]] + for r in self.rows("SELECT seq, kind, operator FROM journal ORDER BY seq")] + + def count(self) -> int: + return self.rows("SELECT count(*) AS n FROM journal")[0]["n"] + + def mirror(self) -> dict: + return self.rows("SELECT * FROM mirror_state")[0] + + def state(self) -> dict: + return {"switch": self.switch(), "head": self.head(), "journal": self.journal()} + + # ------------------------------------------------------------ origin + def store_on_origin(self) -> bool: + return "lanes/STORE" in self.reg.origin_git("ls-tree", "-r", "--name-only", + "refs/heads/main", "lanes/").split() + + def origin_seqs(self) -> list: + """Every `Register-Seq` on origin's `main`, oldest first.""" + out = self.reg.origin_git("log", "--reverse", "--format=%B%x00", "refs/heads/main") + return [int(s) for body in out.split("\0") for s in REGISTER_SEQ.findall(body)] + + # ------------------------------------------------------------ the commands + def prepare(self) -> None: + """The cutover, then `writes` writes on primary from ws1, each + rendered: `k` is the head. The operator lane's `<c>` is made after + the cutover's push from W, before the first write.""" + proc = self.reg.cutover() + assert proc.returncode == 0, f"the cutover (T116) failed:\n{_said(proc)}" + switch = self.switch() + assert (switch["mode"], switch["marker_state"]) == ("primary", "present"), ( + f"after the cutover the switch reads {switch['mode']} with the marker " + f"{switch['marker_state']}: the marker's push, read-back and record_marker are lane " + f"3's T327, so test 8's estate fails until it lands") + self.c = _lane_checkout(self.reg.origin, self.reg.ws, self.imp.OPERATOR, self.reg.env) + for n in range(1, self.writes + 1): + proc = self.reg.write(f"test 8: write {n}") + assert proc.returncode == 0, ( + f"write {n} on primary from ws1 failed (lane 4's T415 and T416):\n{_said(proc)}") + self.k = self.head() + assert self.reg.wait_for_seq(self.k), ( + f"no mirror commit carries Register-Seq: {self.k} (lane 3's T321 to T323): " + f"{self.reg.seqs_on_origin()}") + self.arm() + + def rollback(self, conf: Path | None = None, env: dict | None = None, + timeout: float = 300) -> subprocess.CompletedProcess: + """`lanes-index rollback` from ws1, as the operator lane, with ws1's + `mode=primary` configuration.""" + return self.reg.index("rollback", conf=conf or self.reg.primary_conf, env=env, + timeout=timeout) + + def popen_rollback(self) -> subprocess.Popen: + return self.reg.popen("rollback", conf=self.reg.primary_conf) + + def outage_file(self) -> Path: + return self.reg.primary_conf.parent / OUTAGE_FILE + + +def _estate(request, tmp_path: Path, *, stoppable: bool = False, prepare: bool = True): + """A `RollbackEstate` on a database of its own: the session cluster's, + or a `stoppable_cluster`'s where the case stops the database. The + database is dropped at the case's end.""" + cluster = request.getfixturevalue("stoppable_cluster" if stoppable else "pg_cluster") + name = cluster.new_database() + request.addfinalizer(lambda: cluster.drop_database(name) if cluster.ready() else None) + estate = RollbackEstate(tmp_path / "estate", Database(cluster, name)) + estate.cluster = cluster + if prepare: + estate.prepare() + return estate + + +def _origin_blob(reg, rev: str, path: str) -> bytes: + """`path` at `rev` in the bare origin, as bytes.""" + proc = subprocess.run(["git", f"--git-dir={reg.origin}", "show", f"{rev}:{path}"], + capture_output=True, env=reg.env, check=True, stdin=subprocess.DEVNULL) + return proc.stdout + + +def _assert_rolled_back(estate: RollbackEstate, proc) -> None: + """TEST 8 (a)'S ORACLE (TP:1638-1647): exit 0; the switch at `files` with + the marker `absent`; origin's last commit removes `lanes/STORE` and + carries the rollback entry's seq, `k+1`, the journal's last; and origin's + rendered paths equal a full render from SQL, byte for byte.""" + imp, reg = estate.imp, estate.reg + assert proc.returncode == 0, f"the rollback did not end 0:\n{_said(proc)}" + switch = estate.switch() + assert (switch["mode"], switch["marker_state"]) == ("files", "absent"), ( + f"the switch is {switch['mode']}/{switch['marker_state']}, not files/absent after " + f"record_marker confirmed the removal") + journal = estate.journal() + last = journal[-1] + assert last[1:] == ["rollback", True], f"the journal's last entry is {last}: {journal}" + tip = reg.origin_tip() + assert REGISTER_SEQ.findall(reg.origin_git("log", "-1", "--format=%B", tip)) == [str(last[0])], ( + f"origin's last commit does not carry Register-Seq: {last[0]}") + changed = reg.origin_git("diff-tree", "--no-commit-id", "--name-status", "-r", f"{tip}^", tip) + assert changed.split("\n") == ["D\tlanes/STORE", ""], ( + f"origin's last commit does not remove lanes/STORE alone: {changed!r}") + on_origin = {p: _origin_blob(reg, tip, p) + for p in reg.origin_git("ls-tree", "-r", "--name-only", tip, "lanes/").split() + if imp.RENDER_SET.match(p)} + from_sql = {p: b for p, b in imp._renders(estate.db).items() if imp.RENDER_SET.match(p)} + assert on_origin == from_sql, ( + f"origin's rendered paths differ from a full render from SQL: " + f"{sorted(set(on_origin) ^ set(from_sql))} or " + f"{sorted(p for p in on_origin if p in from_sql and on_origin[p] != from_sql[p])}") + + +# ------------------------------------------------------------------ (a), (b) +def test_rollback_leaves_files_byte_identical_marker_gone_and_sql_writes_refused(request, + tmp_path): + """Test 8 (a) (TP:1549-1550, :1638-1647): the rollback with the database + up, then a `mode=primary` write from ws1 exits 69, and `set-mode index` + on ws1, as Brett runs it at the rollback's step 5 (operations.md 2.3), + leaves ws1's configuration without `mode=primary`. Fails until T326, + T327, T321 to T323, T415 and T416.""" + estate = _estate(request, tmp_path) + proc = estate.rollback() + _assert_rolled_back(estate, proc) + count = estate.count() + wrote = estate.reg.write("test 8 (a): a write after the rollback") + assert wrote.returncode == 69, f"a mode=primary write after the rollback is not 69:\n{_said(wrote)}" + assert estate.count() == count, "the refused write journaled" + mode = estate.reg.index("set-mode", "index", conf=estate.reg.primary_conf) + assert mode.returncode == 0, f"set-mode index on ws1:\n{_said(mode)}" + lines = estate.reg.primary_conf.read_text(encoding="utf-8").splitlines() + assert "mode=primary" not in lines, f"ws1's configuration still says mode=primary: {lines}" + + +def test_rollback_with_the_database_stopped_is_refused_and_changes_neither_switch_nor_marker( + request, tmp_path): + """Test 8 (b) (TP:1551-1552, :1648-1655): with the database stopped + (`stoppable_cluster`), the rollback exits 69 and stops at its step 1; + after the restart the switch still reads `primary` with the marker + `present`, `lanes/STORE` is still on origin, ws1 is still + `mode=primary`, and no `register-outage` is beside ws1's configuration. + Fails until T327, T321 to T323, T415 and T416 (its estate).""" + estate = _estate(request, tmp_path, stoppable=True) + before = estate.switch() + estate.cluster.stop() + try: + proc = estate.rollback() + finally: + estate.cluster.start_again() + assert proc.returncode == 69, f"a rollback with the database stopped is not 69:\n{_said(proc)}" + assert not any(STEP_1_MARK in c.get("sent", "") for c in estate.calls()), ( + "a step-1 call was sent with the database stopped") + after = estate.switch() + assert (after["mode"], after["marker_state"]) == ("primary", "present"), after + assert after == before, f"the switch moved: {before} -> {after}" + assert estate.store_on_origin(), "lanes/STORE is no longer on origin" + assert "mode=primary" in estate.reg.primary_conf.read_text(encoding="utf-8").splitlines() + assert not estate.outage_file().exists(), "a rollback refused at its step 1 declared" + + +# ------------------------------------------------------------------ (c), (e) and the claim +def _missed_failures(estate: RollbackEstate, ws2: MissedWorkstation, verb: str, *, + no_fetch: bool, writer=None) -> list: + """TEST 8 (c)'S ORACLE (TP:1648-1667), as a list of what fails, empty + where it holds: the writer exits 69 with AT-3's line (`commit`: 2, with + nothing reaching SQL or `lanes/`); the journal's count is unchanged; and + ws2's HEAD, index, last-fetched tip and files under `lanes/` are + unchanged. `writer` stands in for ws2's `lanes-edit.sh` (case (e)).""" + edited = verb == "commit" and ws2.hand_edit() + try: + before, count = ws2.snapshot(), estate.count() + env = {"LANES_NO_FETCH": "1" if no_fetch else None} + proc = (writer or ws2.edit)(*_verb_args(verb), env=env) + failures = [] + want = 2 if verb == "commit" else 69 + if proc.returncode != want: + failures.append(f"{verb} exited {proc.returncode}, not {want}: {proc.stderr[-800:]}") + if verb != "commit" and AT3_LINE not in proc.stderr: + failures.append(f"{verb}'s stderr does not carry AT-3's line: {proc.stderr[-800:]}") + if estate.count() != count: + failures.append(f"{verb}: the journal's count moved from {count} to {estate.count()}") + if ws2.snapshot() != before: + failures.append(f"{verb}: ws2's HEAD, index, last-fetched tip or lanes/ files changed") + return failures + finally: + if edited: + ws2.undo_hand_edit() + + +@pytest.fixture(scope="module") +def missed_estate(pg_cluster, tmp_path_factory): + """Test 8's estate after a whole rollback, shared by (c)'s 24 ids, (e)'s + two stubs and the files-mode claim: ws2 cloned at the cutover's estate, + twice, one fetched after the rollback's push and one not. Where the + estate cannot be built or the rollback does not end 0, each case fails + with why.""" + name = pg_cluster.new_database() + shared = SimpleNamespace(problem=None) + try: + estate = RollbackEstate(tmp_path_factory.mktemp("missed"), Database(pg_cluster, name)) + estate.prepare() + ws2 = {fetch: MissedWorkstation(estate, f"ws2-{fetch}") + for fetch in ("fetched", "not-fetched")} + cached = estate.switch()["mode"] + proc = estate.rollback() + _assert_rolled_back(estate, proc) + ws2["fetched"].fetch() + shared = SimpleNamespace(problem=None, estate=estate, ws2=ws2, cached_mode=cached) + except AssertionError as exc: + shared = SimpleNamespace(problem=f"test 8's estate after a whole rollback: {exc}") + try: + yield shared + finally: + pg_cluster.drop_database(name) + + +def _ready(shared): + if shared.problem: + pytest.fail(shared.problem[:4000], pytrace=False) + return shared + + +@pytest.mark.parametrize("case", MISSED_CASES) +def test_a_missed_primary_writer_is_refused_after_rollback(missed_estate, case): + """Test 8 (c) (TP:1553-1561, :1656-1667): once the rollback has run to + its end, ws2, whose `mode=primary` was not cleared, exits 69 for each + verb (`commit`: 2), fetched or not, with `LANES_NO_FETCH=1` or without, + and changes nothing. Fails until T326, T327, T415, T420 and T421.""" + shared = _ready(missed_estate) + fetch = "not-fetched" if "-not-fetched-" in case else "fetched" + verb = case[:case.index(f"-{fetch}-")] + failures = _missed_failures(shared.estate, shared.ws2[fetch], verb, + no_fetch=case.endswith("-no-fetch")) + assert not failures, "\n".join(failures) + + +def _leak(estate: RollbackEstate, lane: str) -> subprocess.CompletedProcess: + """A stub's write: one journal row through the real `psql`, as the admin + under `SET ROLE lanes_register_owner`, since REGISTER-WRITER has no INSERT + and `commit_write` would refuse it LR002 (TP:1609-1616).""" + return estate.db.psql( + f"SET search_path TO {estate.imp.SCHEMA};\nSET ROLE lanes_register_owner;\n" + f"INSERT INTO journal (seq, base_seq, write_id, kind, verb, lane, workstation, author, " + f"message, args_sha256) SELECT max(seq) + 1, max(seq), '{uuid.uuid4()}'::uuid, 'write', " + f"'log', '{lane}', 'Eagle', 'stub <stub@example.invalid>', 'a stub writer''s leak', " + f"'{'b' * 64}' FROM journal;\n", check=False) + + +def _stub(estate: RollbackEstate, leaks) -> callable: + """A stub writer for (e): it writes `_leak`'s row and exits 0 where + `leaks()` says so, and otherwise refuses as the product does.""" + def writer(*args, env=None): + if leaks(): + written = _leak(estate, MISSED_LANE) + assert written.returncode == 0, ( + f"the stub could not write its row, so it models no leak: {written.stderr}") + return SimpleNamespace(returncode=0, stdout="", stderr="") + return SimpleNamespace(returncode=69, stdout="", stderr=AT3_LINE + "\n") + return writer + + +def test_the_rollback_oracle_fails_on_a_last_fetched_tip_writer(missed_estate): + """Test 8 (e), the first stub (TP:1562-1564, :1668-1670, Q4(b)(i)): a + writer that refuses only when its last-fetched tip lacks `lanes/STORE` + leaks on ws2's clone that has not fetched since the rollback's push, and + (c)'s oracle reports it. Fails until (c)'s estate can be built.""" + shared = _ready(missed_estate) + ws2 = shared.ws2["not-fetched"] + stub = _stub(shared.estate, lambda: subprocess.run( + ["git", "-C", str(ws2.clone), "cat-file", "-e", "refs/remotes/origin/main:lanes/STORE"], + env=ws2.env, capture_output=True).returncode == 0) + failures = _missed_failures(shared.estate, ws2, "append-line", no_fetch=False, writer=stub) + assert failures, "test 8's oracle passed a writer that leaks on its last-fetched tip" + + +def test_the_rollback_oracle_fails_on_a_switch_reset_when_the_database_returns(missed_estate): + """Test 8 (e), the second stub (TP:1562-1564, :1668-1670, Q4(b)(ii)): a + writer that checks the switch only when it first reconnects, and so + keeps the `primary` it read before the rollback, leaks, and (c)'s oracle + reports it. Fails until (c)'s estate can be built.""" + shared = _ready(missed_estate) + stub = _stub(shared.estate, lambda: shared.cached_mode == "primary") + failures = _missed_failures(shared.estate, shared.ws2["fetched"], "claim", no_fetch=True, + writer=stub) + assert failures, "test 8's oracle passed a writer that keeps the switch it first read" + + +def _claim_holders(estate: RollbackEstate) -> set: + """The lanes holding `CLAIMED`, across SQL's live claims and the files on + origin's `main` (a lane whose log's last line on it is `CLAIMED`).""" + rows = estate.rows(f"SELECT lane FROM object_holds WHERE lower(object) = lower('{CLAIMED}') " + f"AND verb IN ('CLAIMED', 'TAKEOVER') AND superseded_by IS NULL") + held = {r["lane"] for r in rows} + reg = estate.reg + for path in reg.origin_git("ls-tree", "-r", "--name-only", "refs/heads/main", + "lanes/log/").split(): + last = None + for line in reg.origin_git("show", f"refs/heads/main:{path}").splitlines(): + if CLAIMED.lower() in line.lower(): + last = line + if last and last.startswith("CLAIMED"): + match = re.match(r"CLAIMED \S+ lane ([^,\s]+),", last) + held.add(match.group(1) if match else path) + return held + + +def test_a_files_mode_claim_after_rollback_leaves_one_holder(missed_estate): + """Test 8 (c)'s last step (TP:1666-1667): after the missed writer's + cases, a files-mode `claim` of the same object on ws1 exits 0, and the + object has exactly one holder across SQL and the files. Fails until + (c)'s estate can be built.""" + shared = _ready(missed_estate) + operator = _imp().OPERATOR + proc = shared.estate.reg.edit("claim", CLAIMED, "--no-github", env={"LANES_LANE": operator}) + assert proc.returncode == 0, f"a files-mode claim on ws1 after the rollback:\n{_said(proc)}" + assert _claim_holders(shared.estate) == {operator}, _claim_holders(shared.estate) + + +# ------------------------------------------------------------------ section 4.2: the partition +def _partitioned_conf(estate: RollbackEstate) -> Path: + """ws1's configuration naming a fresh, empty socket directory (TP:1605).""" + empty = estate.root / "empty-socket" + empty.mkdir(exist_ok=True) + live = quote(str(estate.db.host), safe="") + text = estate.reg.primary_conf.read_text(encoding="utf-8").replace( + live, quote(str(empty), safe="")) + assert text != estate.reg.primary_conf.read_text(encoding="utf-8"), ( + "ws1's configuration does not name the cluster's socket directory") + return _private(estate.root / "partitioned" / "lanes-index.conf", text) + + +def test_rollback_from_a_partitioned_clone_is_refused_and_removes_no_marker(request, tmp_path): + """Section 4.2, while partitioned (TP:7579-7584): ws1's rollback, from a + configuration naming an empty socket directory, exits 69; the switch + reads `primary`; `lanes/STORE` is still on origin's `main`; and ws2's + writes exit 0, since the estate is still primary. Fails until T327, T415, + T416 and T421.""" + estate = _estate(request, tmp_path) + ws2 = MissedWorkstation(estate, "ws2") + proc = estate.rollback(conf=_partitioned_conf(estate)) + assert proc.returncode == 69, f"the partitioned rollback is not 69:\n{_said(proc)}" + switch = estate.switch() + assert (switch["mode"], switch["marker_state"]) == ("primary", "present"), switch + assert estate.store_on_origin(), "lanes/STORE left origin's main" + for verb in ("append-line", "claim"): + wrote = ws2.edit(*_verb_args(verb)) + assert wrote.returncode == 0, f"ws2's {verb} on the still-primary estate:\n{_said(wrote)}" + + +@pytest.fixture(scope="module") +def partitioned_estate(pg_cluster, tmp_path_factory): + """Section 4.2's estate after the partitioned rollback and the whole one: + ws1's rollback from the empty socket directory (69), then from its own + configuration to its end. ws2 cloned before, twice; one fetched after.""" + name = pg_cluster.new_database() + try: + estate = RollbackEstate(tmp_path_factory.mktemp("partition"), + Database(pg_cluster, name)) + estate.prepare() + ws2 = {fetch: MissedWorkstation(estate, f"ws2-{fetch}") + for fetch in ("fetched", "not-fetched")} + refused = estate.rollback(conf=_partitioned_conf(estate)) + assert refused.returncode == 69, f"the partitioned rollback:\n{_said(refused)}" + proc = estate.rollback() + _assert_rolled_back(estate, proc) + ws2["fetched"].fetch() + shared = SimpleNamespace(problem=None, estate=estate, ws2=ws2, + last=estate.journal()[-1][0]) + except AssertionError as exc: + shared = SimpleNamespace(problem=f"section 4.2's estate: {exc}") + try: + yield shared + finally: + pg_cluster.drop_database(name) + + +@pytest.mark.parametrize("case", MISSED_CASES) +def test_a_missed_writer_is_refused_once_the_partitioned_rollback_completes(partitioned_estate, + case): + """Section 4.2, after the rollback completes (TP:7585-7590): every ws2 + case exits 69 (`commit`: 2); the journal's count no longer changes; the + files equal a full render at the rollback's last seq; and every object + has one holder. Fails until T326, T327, T415, T420 and T421.""" + shared = _ready(partitioned_estate) + fetch = "not-fetched" if "-not-fetched-" in case else "fetched" + verb = case[:case.index(f"-{fetch}-")] + failures = _missed_failures(shared.estate, shared.ws2[fetch], verb, + no_fetch=case.endswith("-no-fetch")) + assert not failures, "\n".join(failures) + assert shared.estate.journal()[-1][0] == shared.last, "the journal moved past the rollback" + live = shared.estate.rows("SELECT object, count(*) AS n FROM object_holds WHERE verb IN " + "('CLAIMED', 'TAKEOVER') AND superseded_by IS NULL AND NOT exempt " + "GROUP BY object HAVING count(*) > 1") + assert live == [], f"an object has more than one holder: {live}" + + +# ------------------------------------------------------------------ (f), (g), (h), (i) +@pytest.mark.parametrize("stray", ["rendered-path", "register-seq-above-head"]) +def test_a_rollback_finds_a_stray_not_yet_recorded_records_it_and_exits_2(request, tmp_path, + stray): + """Test 8 (f) (TP:1565-1567, :1671-1679): a stray pushed to origin with no + write after it, so `diverged_sha` is NULL when the rollback starts, is + caught by its fetch right before its transaction: it exits 2 naming + `diverged at <sha>` and S2's two ways out, records the stray's sha, and + leaves the switch, the journal, the head and `lanes/STORE` as they were. + `[rendered-path]` changes a rendered path; `[register-seq-above-head]` + changes none and carries `Register-Seq: <h+10>`. Fails until T326.""" + estate = _estate(request, tmp_path) + reg = estate.reg + other = reg.other_clone("stray") + if stray == "rendered-path": + log = "lanes/log/repoB-1.md" + sha = reg.push_from(other, log, _origin_blob(reg, "refs/heads/main", log).decode("utf-8") + + "a stray line, pushed past the renderer\n", "a stray commit") + else: + h = estate.head() + target = other / "handoffs" / "stray.md" + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text("# a stray, outside the render set\n", encoding="utf-8") + for argv in (["add", "--", "handoffs/stray.md"], + ["commit", "-q", "-m", f"a stray commit\n\nRegister-Seq: {h + 10}"], + ["push", "-q", "origin", "HEAD:main"]): + subprocess.run(["git", "-C", str(other), *argv], check=True, env=reg.env, + capture_output=True, stdin=subprocess.DEVNULL) + sha = reg.origin_tip() + assert estate.mirror()["diverged_sha"] is None, "the stray was recorded before the rollback" + before, count = estate.state(), estate.count() + proc = estate.rollback() + assert proc.returncode == 2, f"[{stray}] the rollback is not 2:\n{_said(proc)}" + assert f"diverged at {sha}" in proc.stderr, _said(proc) + for way in ("import --single", "render --revert"): + assert way in proc.stderr, f"S2's way out {way!r} is not named:\n{_said(proc)}" + assert estate.mirror()["diverged_sha"] == sha, estate.mirror() + assert estate.state() == before and estate.count() == count, "the rollback wrote" + assert estate.store_on_origin(), "lanes/STORE left origin" + + +def _holder(db, appname: str) -> subprocess.Popen: + """The held session: the fixture's superuser holding `register_head`'s row + `FOR UPDATE`, in a transaction left open (see the readings).""" + holder = db.session(appname=appname) + holder.stdin.write("BEGIN;\nSELECT seq FROM lanes_register.register_head WHERE id = 1 " + "FOR UPDATE;\n") + holder.stdin.flush() + return holder + + +def _wait_for(db, query: str, what: str, ceiling: float = 20.0) -> None: + """Poll `query`, a count, in 0.05 s steps under `ceiling` until it counts + one row or more.""" + end = time.monotonic() + ceiling + while time.monotonic() < end: + if db.psql(query).stdout.strip() not in ("", "0"): + return + time.sleep(0.05) + pytest.fail(f"{what}: not seen within {ceiling} s") + + +def _locked(db, appname: str) -> str: + return (f"SELECT count(*) FROM pg_stat_activity WHERE datname = '{db.name}' AND " + f"application_name = '{appname}' AND wait_event_type = 'Lock';") + + +def _holding(db, appname: str) -> str: + return (f"SELECT count(*) FROM pg_stat_activity WHERE datname = '{db.name}' AND " + f"application_name = '{appname}' AND state = 'idle in transaction' AND " + f"backend_xid IS NOT NULL;") + + +def _record(db, ws: str, sha: str | None, error: str | None, + schema: str = "lanes_register") -> subprocess.CompletedProcess: + """`record_mirror_state` as REGISTER-WRITER, in a session of its own.""" + lit = (lambda v: "NULL" if v is None else "'" + v.replace("'", "''") + "'") + return db.psql(f"SET ROLE {WRITER};\nSELECT {schema}.record_mirror_state({lit(ws)}, " + f"{lit(sha)}, {lit(error)});\n", check=False) + + +@pytest.mark.parametrize("case", ["recorded", "last-error-only"]) +def test_a_rollback_goes_back_to_its_check_past_a_last_error_and_refuses_a_divergence_recorded_meanwhile( + request, tmp_path, case): + """Test 8 (g) (TP:1568-1572, :1680-1692): with the held session on the + head row and the rollback's call waiting on it (`wait_event_type = + 'Lock'`), the test records with `record_mirror_state`, then ends the held + session by `ROLLBACK`; the call's `FOR SHARE` on `mirror_state` raises + 40001, and the command goes back to its check. `[recorded]`: it exits 2 + with `diverged at <sha>`, the switch, marker and journal unchanged. + `[last-error-only]`: the check finds no divergence and the retry commits + at `k+1`, the journal's last. Fails until T326 and T327.""" + estate = _estate(request, tmp_path) + db, k, sha = estate.db, estate.k, "3" * 40 + before = estate.state() + holder = _holder(db, "t273-g-holder") + proc = None + try: + _wait_for(db, _holding(db, "t273-g-holder"), "the held session's lock on the head row") + proc = estate.popen_rollback() + _wait_for(db, _locked(db, "lanes-index"), "the rollback's call waiting on the head row") + recorded = _record(db, "ws-t273-g", sha if case == "recorded" else None, + None if case == "recorded" else "the push was refused") + assert recorded.returncode == 0, recorded.stderr + holder.communicate(input="ROLLBACK;\n", timeout=60) + out, err = proc.communicate(timeout=300) + finally: + for p in (proc, holder): + if p is not None and p.poll() is None: + p.kill() + p.wait() + ended = f"exit {proc.returncode}\n--- stdout ---\n{out}\n--- stderr ---\n{err}" + assert "40001" in err and "lost its turn" in err, f"[{case}] no 40001 sent it back:\n{ended}" + if case == "recorded": + assert proc.returncode == 2 and f"diverged at {sha}" in err, ended + assert estate.state() == before, "the refused rollback moved the switch or the journal" + else: + switch, journal = estate.switch(), estate.journal() + assert switch["mode"] == "files", f"the retry did not commit:\n{ended}" + assert journal[-1] == [k + 1, "rollback", True], journal + assert switch["marker_state"] == "removing" or ( + switch["marker_state"] == "absent" and proc.returncode == 0), ended + + +def _between(calls: list, git_calls: list, sub: str = "fetch") -> list: + """For each two step-1 calls in `calls` (the shim's or the fake's + requests), whether a read came between them, and whether a `git <sub>` + naming `origin` started between them.""" + steps = [n for n, c in enumerate(calls) if STEP_1_MARK in c.get("sent", c.get("stdin", ""))] + found = [] + for a, b in zip(steps, steps[1:]): + read = any(READ_MARK in calls[n].get("sent", calls[n].get("stdin", "")) + for n in range(a + 1, b)) + fetch = any(g["sub"] == sub and "origin" in g["argv"] and a + 1 <= g["psql_before"] <= b + for g in git_calls) + found.append((read, fetch)) + return found + + +def test_a_rollback_retries_a_lost_turn_on_a_fresh_k_through_its_check(request, tmp_path): + """Test 8 (h), RE (TP:1573-1576, :1693-1699): the shim holds the + rollback's step-1 call for a window, and ws2 commits one write in it. + The call gets LR001, the rollback reads the head afresh, runs its check + again and commits on the new head: its entry is seq `k+2`, the journal's + last; the shim's log shows two step-1 calls with a head read between + them, and the wrapper's a fetch of `origin main` between them. Fails + until T326, T327, T415 and T416.""" + estate = _estate(request, tmp_path) + ws2 = MissedWorkstation(estate, "ws2") + k = estate.k + estate.arm([{"mode": "window", "match": "commit_write", "call": 1, "ms": 8000}]) + proc = estate.popen_rollback() + try: + end = time.monotonic() + 60 + while not any(STEP_1_MARK in c.get("sent", "") for c in estate.calls()): + assert proc.poll() is None and time.monotonic() < end, ( + f"the rollback sent no step-1 call: {proc.poll()}") + time.sleep(0.05) + wrote = ws2.edit("log", "NOTED", f"lane:{MISSED_LANE}", "test 8 (h): in the window") + out, err = proc.communicate(timeout=300) + finally: + if proc.poll() is None: + proc.kill() + proc.wait() + ended = f"exit {proc.returncode}\n--- stdout ---\n{out}\n--- stderr ---\n{err}" + assert wrote.returncode == 0, f"ws2's write in the window:\n{_said(wrote)}" + assert "LR001" in err, f"the step-1 call did not get LR001:\n{ended}" + journal = estate.journal() + assert journal[-2:] == [[k + 1, "write", False], [k + 2, "rollback", True]], ( + f"the rollback's entry is not k+2 = {k + 2} after ws2's write: {journal}\n{ended}") + between = _between(estate.calls(), estate.git_calls()) + assert between and between[0] == (True, True), ( + f"two step-1 calls with a head read and a fetch of origin main between them: {between}") + + +#: The rollback's read as the fake answers it (FP): `_ROLLBACK_READS`' six +#: SELECTs, each a COPY's rows then the marker line: the window, the switch at +#: `primary` with the marker `present`, the head 1, the cutover's entry at it, +#: no divergence, and the database's clock. +NEXT = "\x1eLANES-INDEX-NEXT" + + +def _canned_read(version: int) -> str: + rows = [f"{version}\t{version}\t{version}", + f"primary\tpresent\t1\t{uuid.uuid4()}\t1", "1", f"cutover\t{uuid.uuid4()}", + "\\N\t\\N\t\\N", f"{time.time():.3f}"] + return "".join(f"{row}\n{NEXT}\n" for row in rows) + + +#: STEP 0'S GIT HALF AS THE FAKE ANSWERS IT (FP; lane 3's #165 6813528630, a +#: SHOULD from T326's builder). Right before step 1, T326 fetches `origin +#: main` and checks it as T322 recognises a divergence (B15 tasks:1546, "Step +#: 0's git half"). That makes two reads the rollback's own does not, each +#: answered by its own rule, placed before `READ_MARK`'s: +#: - T322's head read, after the fetch (`_render_read_head`, +#: `4353eb08:lanes-index:15025`): four SELECTs, the window, the head with +#: the switch, the resolved strays, and `mirror_state mir`'s `diverged_sha` +#: and `last_error`. That last SELECT holds `READ_MARK` too, so without a +#: rule of its own the fake gave it the rollback read's six answers, and +#: the head read failed: 69. Since T326's `01cd35c` the second SELECT also +#: reads the switch's `marker_state`, and any answer but those three fields +#: is refused (`ed8e7d2:lanes-index:14995`, `:15020-15023`; lane 3's #165 +#: 6814531692, a SHOULD from T326's fixer); +#: - T301's image read at `m` (`register_render_queries`, `:2265`): five +#: SELECTs, which T322's image half replays and compares with the render +#: set at the commit carrying `m` (`render_pass`, `:15377-15398`). No rule +#: matched it, so the fake answered nothing: 69. +#: Each mark is a text of that request alone among the case's requests. +HEAD_READ_MARK, IMAGE_READ_MARK = "FROM mirror_state mir", "FROM journal_files f" + + +def _copy_field(value) -> str: + """One field as `COPY ... TO STDOUT` writes it in TEXT format, which + `_pg_unescape` reads back: `\\N` for NULL, `t` or `f` for a boolean, and + a backslash, a tab, an LF or a CR escaped.""" + if value is None: + return "\\N" + if isinstance(value, bool): + return "t" if value else "f" + return (str(value).replace("\\", "\\\\").replace("\t", "\\t").replace("\n", "\\n") + .replace("\r", "\\r")) + + +def _copy_answer(selects: list) -> str: + """The fake's stdout for one request of SELECTs, as `_query_many` reads + it: each SELECT's rows, one line each, then the marker line.""" + return "".join("".join("\t".join(_copy_field(field) for field in row) + "\n" + for row in rows) + f"{NEXT}\n" for rows in selects) + + +def _canned_head_read(version: int) -> str: + """T322's head read as the fake answers it, from the same canned register + as `_canned_read`: the window, the head 1 with the switch at `primary` + and the marker `present` (T326's three fields), no resolved stray, and + neither a divergence nor a `last_error`.""" + return _copy_answer([[(version, version, version)], [(1, "primary", "present")], [], + [(None, None)]]) + + +def _image_lines(data: bytes) -> tuple: + """A file's lines, and whether it ends with an LF, as T301's + `register_image_bytes` joins them back into `data`.""" + text = data.decode("utf-8") + if not text: + return [], True + final = text.endswith("\n") + return (text[:-1] if final else text).split("\n"), final + + +def _canned_images(version: int, rendered: dict, store: bytes) -> str: + """T301's image read at seq 1 as the fake answers it: the import at 0, + whose `create` and `append` edits rebuild `rendered`, the render set at + the commit carrying `Register-Seq: 1` (`{path: bytes}`), each path proved + by its `journal_files` row; then the cutover's entry at 1, which adds + `lanes/STORE`, outside the render set. So the images at `m` are the + render set there, and T322's image half finds no divergence.""" + edits, files = [], [] + for seq, paths in ((0, rendered), (1, {"lanes/STORE": store})): + ordinal = 0 + for path in sorted(paths): + lines, final = _image_lines(paths[path]) + ordinal += 1 + edits.append((seq, ordinal, "create", path, None, None, None, None)) + for number, line in enumerate(lines, 1): + ordinal += 1 + edits.append((seq, ordinal, "append", path, number, None, line, None)) + files.append((seq, path, True, hashlib.sha256(paths[path]).hexdigest(), final)) + return _copy_answer([[(version, version, version)], [(1, 0)], + [(0, "import"), (1, "cutover")], edits, files]) + + +@pytest.mark.parametrize("code", ["40001", "40P01", "55P03", "LR001"]) +def test_a_rollback_goes_back_to_its_check_on_each_lost_turn_code(tmp_path, code): + """Test 8 (h), FP (TP:1700-1706): the register's fake `psql` answers the + rollback's reads, and step 0's git half's two, T322's head read and + T301's image read (`HEAD_READ_MARK`, `IMAGE_READ_MARK`), from a canned + register whose images at seq 1 are the workspace's render set there, and + every step-1 call with exit 3 and `ERROR: <code>: <message>`, and + `LANES_REGISTER_DEADLINE_S=6` ends the tries: the fake's log shows two + step-1 calls or more, each after the first preceded by a head read, and + the wrapper's a fetch of `origin main` between each two; the exit is 75 + (AT-D9's row holds its bound). Runs by T203's flipped copy, on a files + workspace whose origin carries the cutover's `lanes/STORE` at + `Register-Seq: 1`, the canned head. Needs no engine; fails until T326, + at its own assertion.""" + imp = _imp() + ws = imp.Workspace(tmp_path / "w", imp.SEED) + cutover = ws.commit({"lanes/STORE": "store=primary\ndatabase=register-test\n"}, + "LANES(repoA-2@Eagle): cutover\n\nRegister-Seq: 1") + copy = imp.flipped_indexer(tmp_path / "flip") + version = int(re.search(r"^REGISTER_SCHEMA_VERSION = ([0-9]+)$", + copy.read_text(encoding="utf-8"), re.M).group(1)) + bin_ = tmp_path / "bin" + _script(bin_ / "psql", REGISTER_FAKE_PSQL) + _script(bin_ / "git", GIT_WRAPPER) + log, answers = tmp_path / "psql.log", tmp_path / "answers.json" + answers.write_text(json.dumps([ + {"match": HEAD_READ_MARK, "stdout": _canned_head_read(version)}, + {"match": IMAGE_READ_MARK, "stdout": _canned_images( + version, ws.rendered(cutover), ws.blob(cutover, "lanes/STORE"))}, + {"match": READ_MARK, "stdout": _canned_read(version)}, + {"match": "commit_write", "exit": 3, + "stderr": f"ERROR: {code}: the test's lost turn ({code})\n"}]), encoding="utf-8") + (bin_ / "git-wrapper.json").write_text(json.dumps({"git": _real_git(), "psql_log": str(log)}), + encoding="utf-8") + passfile = _private(tmp_path / "secret" / "pgpass", + "127.0.0.1:55432:register_db:t273:not-a-secret\n") + url = "postgresql://t273@127.0.0.1:55432/register_db" + conf = _private(tmp_path / "conf" / "lanes-index.conf", "\n".join([ + "mode=primary", f"register_url={url}", f"register_passfile={passfile}", + f"reader_url={url}", f"reader_passfile={passfile}", "register_label=register-test", + ""])) + env = dict(ws.env, LANES_INDEX_CONFIG=str(conf), LANES_LANE=imp.OPERATOR, + LANES_REGISTER_DEADLINE_S="6", FAKE_PSQL_LOG=str(log), + FAKE_PSQL_ANSWERS=str(answers), LANES_EDIT=str(copy.parent / "lanes-edit.sh"), + PATH=f"{bin_}{os.pathsep}{ws.env['PATH']}") + proc = subprocess.run([sys.executable, str(copy), "rollback"], capture_output=True, + text=True, env=env, cwd=str(ws.wip), timeout=120, + stdin=subprocess.DEVNULL) + calls = _requests(log) + steps = [c for c in calls if STEP_1_MARK in c.get("stdin", "")] + assert proc.returncode == EXIT_BUSY, ( + f"[{code}] the tries did not end 75 at the deadline ({len(steps)} step-1 calls):\n" + f"{_said(proc)}") + assert len(steps) >= 2, f"[{code}] fewer than two step-1 calls: {len(steps)}" + between = _between(calls, [g for g in _jsonl(bin_ / "git-wrapper.log")]) + assert between and all(pair == (True, True) for pair in between), ( + f"[{code}] each two step-1 calls have a head read and a fetch of origin main " + f"between them: {between}") + + +def test_a_write_that_committed_before_the_rollback_is_found_by_its_rerun_after_it(request, + tmp_path): + """Test 8 (i) (TP:1577-1579, :1707-1716): ws2's write is lost after it + lands (the shim's `no-reconnect` as `after` on its commit call), so ws2 + exits 3 with its pending record; the rollback then runs to its end from + ws1; with the shim disarmed, the printed rerun on ws2 exits 0, not 69, + the journal holds one entry for its id, and ws2's next new write exits + 69. Fails until T326, T327, T415, T416, T417 and T420.""" + estate = _estate(request, tmp_path) + ws2 = MissedWorkstation(estate, "ws2") + ws2.arm([{"mode": "no-reconnect", "as": "after", "match": "commit_write", "call": 1}]) + lost = ws2.edit("log", "NOTED", f"lane:{MISSED_LANE}", "test 8 (i): lost after it lands") + assert lost.returncode == 3, f"ws2's lost write is not in doubt (3):\n{_said(lost)}" + rerun = re.search(r"LANES_WRITE_ID=([0-9a-f-]{36})", lost.stderr) + assert rerun, f"ws2 printed no rerun under the same id:\n{_said(lost)}" + write_id = rerun.group(1) + generation = re.search(r"LANES_WRITE_GENERATION=([0-9a-f-]{36})", lost.stderr) + rerun_env = {"LANES_WRITE_ID": write_id} + if generation: + rerun_env["LANES_WRITE_GENERATION"] = generation.group(1) + proc = estate.rollback() + _assert_rolled_back(estate, proc) + ws2.arm([]) + count = estate.count() + again = ws2.edit("log", "NOTED", f"lane:{MISSED_LANE}", "test 8 (i): lost after it lands", + env=rerun_env) + assert again.returncode == 0, f"the rerun is not 0 (the write id first, S1):\n{_said(again)}" + assert estate.count() == count, "the rerun journaled" + assert estate.rows(f"SELECT count(*) AS n FROM journal WHERE write_id = '{write_id}'") == \ + [{"n": 1}] + fresh = ws2.edit("log", "NOTED", f"lane:{MISSED_LANE}", "test 8 (i): a new write") + assert fresh.returncode == 69, f"ws2's next new write is not 69:\n{_said(fresh)}" + + +# ------------------------------------------------------------------ AT-F1 +def test_rollback_refuses_to_start_while_the_mirror_is_diverged(request, tmp_path): + """AT-F1, diverged (TP:5456-5459): test 6's diverged estate, a stray + commit on origin that a write's render recorded; `rollback` exits 2 + before step 1, naming the divergence and S2's two tools, and the switch + reads `primary` with the marker `present`, the journal and head unchanged, + and `lanes/STORE` still on origin. Fails until T322, T326 and T327.""" + estate = _estate(request, tmp_path) + reg = estate.reg + log = "lanes/log/repoB-1.md" + sha = reg.push_from(reg.other_clone("stray"), log, _origin_blob( + reg, "refs/heads/main", log).decode("utf-8") + "a stray line\n", "a stray commit") + wrote = reg.write("AT-F1: a write after the stray") + assert wrote.returncode == 0, _said(wrote) + deadline = time.monotonic() + 60 + while estate.mirror()["diverged_sha"] is None and time.monotonic() < deadline: + time.sleep(0.5) + assert estate.mirror()["diverged_sha"] == sha, ( + f"the render did not record the stray (T322): {estate.mirror()}") + estate.arm() + before = estate.state() + proc = estate.rollback() + assert proc.returncode == 2 and f"diverged at {sha}" in proc.stderr, _said(proc) + for way in ("import --single", "render --revert"): + assert way in proc.stderr, _said(proc) + assert not any(STEP_1_MARK in c.get("sent", "") for c in estate.calls()), "step 1 was sent" + assert estate.state() == before, "the refused rollback moved the switch, journal or head" + assert estate.store_on_origin() + + +def _held_at_push(estate: RollbackEstate): + """The rollback from ws1, held by the wrapper at its push: (the process, + the FIFO's write end), or a failure where it ends first.""" + fifo = estate.root / "push.fifo" + if not fifo.exists(): + os.mkfifo(str(fifo), 0o600) + estate.arm(hold={"call": "push", "fifo": str(fifo)}) + proc = estate.popen_rollback() + fd = _open_when_held(fifo, proc, 300) + if fd is None: + out, err = proc.communicate(timeout=60) + pytest.fail(f"the rollback never reached its push: exit {proc.returncode}\n{out}\n{err}") + return proc, fd + + +def _write_entry_now(estate: RollbackEstate, text: str) -> dict: + """A write appending `text` to `lanes/LANES.md` as SQL renders it now.""" + old = estate.imp._renders(estate.db)["lanes/LANES.md"] + new = old + text.encode("utf-8") + b"\n" + return {"journal": {"kind": "write", "verb": "log", "lane": _imp().OPERATOR, + "workstation": "Eagle", "author": AUTHOR, "message": "AT-F1: meanwhile", + "args_sha256": ARGS_SHA256}, + "not_after": NOT_AFTER, + "edits": [{"ord": 1, "op": "append", "path": "lanes/LANES.md", "new_text": text}], + "files": [{"path": "lanes/LANES.md", "present": True, + "sha256": hashlib.sha256(new).hexdigest(), "final_newline": True}]} + + +def test_the_marker_removal_entry_is_written_with_the_switch_in_step_1(request, tmp_path): + """AT-F1, the removal entry (TP:5460-5466): while the rollback is held at + its push, one snapshot shows the switch at `files` with the marker + `removing` and the removal entry, an operator entry, as the journal's + last seq `k+1`: both or neither; a write tried meanwhile fails LR002 and + journals nothing; on release the rollback ends with test 8 (a)'s oracle. + Fails until T326 and T327.""" + estate = _estate(request, tmp_path) + k = estate.k + proc, fd = _held_at_push(estate) + try: + seen = estate.rows( + "SELECT s.mode, s.marker_state, h.seq AS head, j.kind, j.operator FROM register_switch " + "s, register_head h JOIN journal j ON j.seq = h.seq")[0] + count = estate.count() + entry = json.dumps(_write_entry_now(estate, "AT-F1: a write meanwhile")).replace("'", "''") + gen = estate.switch()["generation"] + version = estate.rows("SELECT version FROM schema_version")[0]["version"] + tried = estate.db.psql( + f"\\set VERBOSITY verbose\nSET search_path TO lanes_register;\nSET ROLE {WRITER};\n" + f"BEGIN ISOLATION LEVEL SERIALIZABLE;\nSELECT commit_write({estate.head()}, " + f"'{uuid.uuid4()}'::uuid, {version}, '{gen}'::uuid, '{entry}'::jsonb);\nCOMMIT;\n", + check=False) + counted = estate.count() + finally: + os.close(fd) + out, err = proc.communicate(timeout=300) + assert seen == {"mode": "files", "marker_state": "removing", "head": k + 1, + "kind": "rollback", "operator": True}, f"one snapshot read {seen}" + assert tried.returncode != 0 and "LR002" in tried.stderr, ( + f"a write while the marker is removing is not LR002: {tried.stderr}") + assert counted == count, "the refused write journaled" + _assert_rolled_back(estate, SimpleNamespace(returncode=proc.returncode, stdout=out, + stderr=err)) + + +def test_a_rollback_rerun_resumes_after_its_own_entry(request, tmp_path): + """AT-F1, the rerun (TP:5467-5469): a rerun after a kill at the push + finds the marker `removing` and its own entry as the last seq, declares + first, and goes on from the render: it ends with test 8 (a)'s oracle, no + entry past `k+1`, and the declaration beside ws1's configuration. Fails + until T326 and T327.""" + estate = _estate(request, tmp_path) + k = estate.k + proc, fd = _held_at_push(estate) + held = [g for g in _jsonl(estate.bin / "git-wrapper.log") if g.get("outcome") == "held"] + for pid in [g["pid"] for g in held] + [proc.pid]: + try: + os.kill(pid, signal.SIGKILL) + except ProcessLookupError: + pass + proc.wait() + os.close(fd) + switch = estate.switch() + assert (switch["marker_state"], estate.journal()[-1]) == ("removing", [k + 1, "rollback", True]) + first = estate.outage_file() + if first.exists(): + os.replace(str(first), str(first.with_name(OUTAGE_FILE + ".first-run"))) + estate.arm() + again = estate.rollback() + assert "stands" in again.stdout and "step 2" in again.stdout, _said(again) + _assert_rolled_back(estate, again) + assert estate.journal()[-1][0] == k + 1, "the rerun wrote an entry of its own" + assert estate.outage_file().exists(), "the rerun did not declare first" + + +def test_a_rerun_after_an_unconfirmed_removal_and_a_files_mode_write_ends_0_with_the_marker_absent( + pg, tmp_path): + """AT-F2, "Unconfirmed", the rollback's removal push (B15 TP:5563-5566), with + ops:338's files-mode write between the 3 and the rerun (lane 3's #165 + 6814260122: T326's review, MUST-1, and its probe). On AT-F2's fixture, + after a clean cutover and `rollback --hold-marker`, the removal is pushed + and the read-back's fetch fails: `rollback` exits 3, the marker stays + `removing`, and origin's tip is the removal, with `lanes/STORE` gone and + `Register-Seq: k+1`. With the marker gone from origin, a files-mode write + lands on it (ops:338, "after it, a files-mode write lands"), a commit of + `lanes/LANES.md` from another clone, as the probe makes it. The rerun + reads origin back first (ops:340; B15 tasks:1549), finds its removal, and + ends 0: the switch reads `files` with the marker `absent`, it pushes + nothing, the write stays origin's tip, and no divergence is recorded. + Fails until T326's fix round, and T327 for the cutover's marker.""" + cut = _cut() + f2 = cut.F2Register(tmp_path / "e", pg) + reg, imp = f2.reg, f2.imp + cutover = reg.cutover(conf=f2.conf) + assert cutover.returncode == 0, f"[cutover] `cutover --import <C>` (T116):\n{_said(cutover)}" + switch = imp._switch(pg) + assert switch["marker_state"] == "present", ( + f"[cutover] the marker reads {switch['marker_state']}: the cutover's push, its read-back " + f"and record_marker are lane 3's T327") + k = imp._head(pg) + held = reg.index("rollback", "--hold-marker", conf=f2.conf) + assert held.returncode == 0, f"[hold-marker] `rollback --hold-marker` (T326):\n{_said(held)}" + f2.arm({"call": "fetch", "mode": "fail", "after_push": True}) + proc = reg.index("rollback", conf=f2.conf) + assert proc.returncode == EXIT_IN_DOUBT, ( + f"[3] the removal pushed, its read-back's fetch failed: not in doubt (T326):\n" + f"{_said(proc)}") + switch = imp._switch(pg) + assert (switch["mode"], switch["marker_state"]) == ("files", "removing"), f"[3] {switch}" + removal = reg.origin_tip() + assert REGISTER_SEQ.findall(reg.origin_git("log", "-1", "--format=%B", removal)) == [ + str(k + 1)], f"[3] origin's tip {removal} does not carry Register-Seq: {k + 1}" + assert "lanes/STORE" not in reg.origin_git("ls-tree", "-r", "--name-only", removal, + "lanes/"), "[3] the removal is not on origin" + f2.arm() + clone = reg.other_clone("files-mode") + path, line = "lanes/LANES.md", "a files-mode line, after the removal (ops:338)" + text = (clone / path).read_text(encoding="utf-8") + line + "\n" + wrote = reg.push_from(clone, path, text, "LANES(repoA-2@Raven): a files-mode write") + assert wrote != removal, "[files-mode write] it did not land on origin" + f2.arm() + rerun = reg.index("rollback", conf=f2.conf) + assert rerun.returncode == 0, ( + f"[rerun] after the 3 and a files-mode write, the rerun did not end 0: it reads origin " + f"back first and finds its removal (T326's fix round, MUST-1):\n{_said(rerun)}") + calls = f2.calls() + assert cut._first_reach(calls) == "fetch", f"[rerun] it reached origin first by: {calls}" + assert not any(c["sub"] == "push" for c in calls), "[rerun] the rerun pushed again" + switch = imp._switch(pg) + assert (switch["mode"], switch["marker_state"]) == ("files", "absent"), f"[rerun] {switch}" + assert reg.origin_tip() == wrote, "[rerun] the files-mode write is no longer origin's tip" + assert line in reg.origin_git("show", f"{wrote}:{path}"), "[rerun] the write's line is gone" + mirror = imp._rows(pg, "SELECT diverged_sha FROM mirror_state")[0] + assert mirror["diverged_sha"] is None, ( + f"[rerun] the files-mode write was recorded as a divergence: {mirror}") + + +def test_a_reimport_after_a_rollback_continues_the_journal(request, tmp_path): + """AT-F1, the re-import (TP:5470-5472): after the rollback, a re-import's + baseline takes `k+2` with base `k+1`, and a later cutover takes `k+3`, so + no `Register-Seq` repeats on `main`. Fails until T326 and T327.""" + estate = _estate(request, tmp_path) + reg, k = estate.reg, estate.k + _assert_rolled_back(estate, estate.rollback()) + reg.git("fetch", "-q", "origin") + tip = reg.origin_tip() + imported = reg.import_at(estate.db, tip, config=reg.index_conf) + assert imported.returncode == 0, _said(imported) + rows = estate.rows(f"SELECT seq, base_seq, kind FROM journal WHERE seq > {k + 1} ORDER BY seq") + assert rows == [{"seq": k + 2, "base_seq": k + 1, "kind": "import"}], rows + cut = reg.index("cutover", "--import", tip) + assert cut.returncode == 0, _said(cut) + assert estate.journal()[-1][:2] == [k + 3, "cutover"], estate.journal() + seqs = estate.origin_seqs() + assert len(seqs) == len(set(seqs)), f"a Register-Seq repeats on main: {seqs}" + + +def test_a_cutover_and_a_rollback_leave_exactly_two_operator_entries(request, tmp_path): + """AT-F1 (TP:5473-5475): over the life of one database, a cutover and then + a rollback leave exactly two journal rows with `operator` true, the + cutover's and the rollback's. Fails until T326 and T327.""" + estate = _estate(request, tmp_path) + _assert_rolled_back(estate, estate.rollback()) + operators = [[seq, kind] for seq, kind, operator in estate.journal() if operator] + assert operators == [[1, "cutover"], [estate.k + 1, "rollback"]], operators + + +# ------------------------------------------------------------------ AT-F1: LR012 +def _writer_session(db, appname: str) -> subprocess.Popen: + """A session as REGISTER-WRITER, with the commit call's settings.""" + session = db.session(appname=appname) + session.stdin.write(f"\\set VERBOSITY verbose\n\\set SHOW_CONTEXT never\n" + f"SET ROLE {WRITER};\n") + session.stdin.flush() + return session + + +def _rollback_call(reg: RollbackRegister, base: int, open_: bool = False) -> str: + """The rollback's commit call, by hand: one SERIALIZABLE transaction + around `commit_write` with a `rollback` entry; without its `COMMIT` where + `open_`.""" + body = _entry("rollback", "rollback", + edits=[{"ord": 1, "op": "remove", "path": "lanes/STORE"}], + files=[{"path": "lanes/STORE", "present": False}]) + literal = json.dumps(body, ensure_ascii=True).replace("'", "''") + call = (f"BEGIN ISOLATION LEVEL SERIALIZABLE;\nSELECT {SCRATCH}.commit_write({base}, " + f"'{uuid.uuid4()}'::uuid, {reg.window()['version']}, " + f"'{reg.switch()['generation']}'::uuid, '{literal}'::jsonb);\n") + return call if open_ else call + "COMMIT;\n" + + +def _mirror_text(reg: RollbackRegister) -> list: + return reg.sql(f"SELECT diverged_sha || '|' || found_utc::text || '|' || found_by_ws " + f"FROM {SCRATCH}.mirror_state;").split("|") + + +@pytest.mark.parametrize("case", ["recorded", "recorder-first", "last-error-only", + "rollback-first"]) +def test_a_rollback_entry_over_a_recorded_divergence_is_lr012(rb_register, case): + """AT-F1, LR012 in the transaction (TP:5476-5498), by direct calls as + REGISTER-WRITER on `primary` with the marker `present` (AT-LR006's route; + lane 1's T107): + * `[recorded]`: with a divergence recorded, the `rollback` entry gets + LR012 with lane 1's text and `mirror_state`'s values, and nothing + moves; + * `[recorder-first]`: `record_mirror_state`'s transaction open first, + the rollback's call waits on `mirror_state`, gets 40001 once it + commits, and its retry on the head read afresh gets LR012; + * `[last-error-only]`: the same with only `last_error` recorded: the + retry commits; + * `[rollback-first]`: the rollback's call open first, before its + `COMMIT`, `record_mirror_state` waits on the row until it ends; + * no session gets 40P01.""" + reg = rb_register + k, sha, ws = reg.k, "4" * 40, "ws-t273-f1" + record = f"SELECT {SCRATCH}.record_mirror_state('{ws}', " + ( + "NULL, 'the push was refused');\n" if case == "last-error-only" else f"'{sha}', NULL);\n") + said = [] + if case == "recorded": + assert reg.psql(record, WRITER).returncode == 0 + before = reg.state(), reg.mirror() + proc = reg.psql(_rollback_call(reg, k), WRITER) + said.append(proc.stderr) + utc = _mirror_text(reg)[1] + first = proc.stderr.strip().splitlines()[0] if proc.stderr.strip() else "" + assert first == (f"ERROR: LR012: rollback refused: diverged at {sha}, found {utc} by " + f"{ws}; resolve it first with import --single or render --revert " + f"(F1, S5)"), proc.stderr + assert (reg.state(), reg.mirror()) == before, "the refused entry moved something" + elif case in ("recorder-first", "last-error-only"): + recorder = _writer_session(reg.db, "t273-recorder") + call = None + try: + recorder.stdin.write("BEGIN;\n" + record) + recorder.stdin.flush() + reg.wait_sql(f"SELECT count(*) FROM pg_stat_activity WHERE application_name = " + f"'t273-recorder' AND state = 'idle in transaction' AND backend_xid IS " + f"NOT NULL;", "the recorder's open transaction") + call = _writer_session(reg.db, "t273-call") + call.stdin.write(_rollback_call(reg, k)) + call.stdin.flush() + reg.wait_sql(_locked(reg.db, "t273-call"), "the rollback's call waiting") + out, err = recorder.communicate(input="COMMIT;\n", timeout=60) + said.append(err) + assert recorder.returncode == 0, err + out, err = call.communicate(timeout=60) + said.append(err) + assert "40001" in err, f"the waiting call did not get 40001: {err}" + finally: + for p in (recorder, call): + if p is not None and p.poll() is None: + p.kill() + p.wait() + retry = reg.psql(_rollback_call(reg, reg.head()), WRITER) + said.append(retry.stderr) + if case == "recorder-first": + assert retry.returncode != 0 and "LR012" in retry.stderr, retry.stderr + assert reg.head() == k + else: + assert retry.returncode == 0, retry.stderr + assert reg.head() == k + 1 and reg.journal()[-1] == [k + 1, "rollback", True] + else: + call = _writer_session(reg.db, "t273-call") + recorder = None + try: + call.stdin.write(_rollback_call(reg, k, open_=True)) + call.stdin.flush() + reg.wait_sql(_holding(reg.db, "t273-call"), "the rollback's open call") + recorder = _writer_session(reg.db, "t273-recorder") + recorder.stdin.write(record) + recorder.stdin.flush() + reg.wait_sql(_locked(reg.db, "t273-recorder"), "record_mirror_state waiting") + assert reg.mirror()["diverged_sha"] is None, "the record did not wait" + out, err = call.communicate(input="COMMIT;\n", timeout=60) + said.append(err) + assert call.returncode == 0, err + out, err = recorder.communicate(timeout=60) + said.append(err) + assert recorder.returncode == 0, err + finally: + for p in (recorder, call): + if p is not None and p.poll() is None: + p.kill() + p.wait() + assert reg.journal()[-1] == [k + 1, "rollback", True] + assert reg.mirror()["diverged_sha"] == sha + assert not any("40P01" in text for text in said), f"a session got 40P01: {said}" + + +def test_rollback_exits_2_on_lr012_naming_the_divergence_and_both_ways_out(rb_register): + """AT-F1, LR012 through the command (TP:5499-5503): the shim holds + `lanes-index rollback`'s step-1 call after its divergence check has + passed, and the test records a divergence meanwhile; on release the call + gets LR012, and `rollback` exits 2 with `diverged at <sha>` and S2's two + ways out, writing nothing: the switch still reads `primary` with the + marker `present`. Runs a copy with the constant False on the scratch + schema, so it needs T304 alone.""" + reg = rb_register + sha = "5" * 40 + copy = flipped_copy(LANES_INDEX, reg.root / "false-copy", False) + fifo = reg.root / "step1.fifo" + os.mkfifo(str(fifo), 0o600) + reg.arm([{"mode": "hold", "fifo": str(fifo), "match": "commit_write", "call": 1}]) + before = reg.state() + proc = subprocess.Popen([sys.executable, str(copy), "rollback"], stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + env=reg.env(reg.config("conf")), cwd=str(reg.root / "operator")) + fd = None + try: + fd = _open_when_held(fifo, proc) + assert fd is not None, "the rollback's step-1 call was never held" + recorded = reg.psql(f"SELECT {SCRATCH}.record_mirror_state('ws-t273-lr012', '{sha}', " + f"NULL);", WRITER) + assert recorded.returncode == 0, recorded.stderr + os.close(fd) + fd = None + out, err = proc.communicate(timeout=120) + finally: + if fd is not None: + os.close(fd) + if proc.poll() is None: + proc.kill() + proc.wait() + ended = f"exit {proc.returncode}\n--- stdout ---\n{out}\n--- stderr ---\n{err}" + assert proc.returncode == 2, ended + assert "LR012" in err and f"diverged at {sha}" in err, ended + for way in ("import --single", "render --revert"): + assert way in err, ended + assert reg.state() == before, "the refused rollback wrote" + switch = reg.switch() + assert (switch["mode"], switch["marker_state"]) == ("primary", "present"), switch diff --git a/tests/test_sql_register_shape.py b/tests/test_sql_register_shape.py new file mode 100644 index 00000000..64fb0064 --- /dev/null +++ b/tests/test_sql_register_shape.py @@ -0,0 +1,80 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Feature 007's register shape (opensoft/openRepoTools#165): what each register +call looks like from outside, its argv, its credentials and its text. + +THIS MODULE TODAY holds test 2's FP case, lane 2's T241 (AT-2, the test plan's +lines 646-781; FR-018, FR-059): +`test_an_unreachable_store_is_69_naming_the_store_and_never_the_files[<verb>]`. +Lane 1's T106 and T111 select their own cases here by `sql_register_shape` +and their words (B10 tasks:275 and :399); those cases are other tasks', which +add them to this module. + +THE CASE runs each of S1's writes but `commit` as `lanes-edit.sh <verb>` on a +`mode=primary` workstation (`test_sql_register_writes.py`'s +`PrimaryWorkstation` and `WRITE_VERBS`), with T203's register fake first on +`PATH` answering every call that carries a request with `psql`'s exit 2 and +its "connection to server ... failed" text (AT-2, "Unreachable (FP)"). It +needs no engine, and fails until lane 4's L4-B3 (T415's attempt loop) lands, +by its own assertion: today's `lanes-edit.sh` writes the files whatever +`mode=` says. +""" + +from __future__ import annotations + +import re +import shutil + +import pytest + +from conftest import WINDOWS_SKIP +from test_sql_register_render import fake_calls, fake_psql_dir +from test_sql_register_writes import (PREPS, SECRET, WRITE_VERBS, PrimaryWorkstation, + unreachable_answers) + +pytestmark = [WINDOWS_SKIP, pytest.mark.skipif( + shutil.which("bash") is None or shutil.which("git") is None, + reason="the lane tooling is bash over git")] + +#: THE LANDING GATE'S TABLE (T280; `tests/sql_register_gate.py` reads it, and +#: T281 removes it in the last set): every id of this module waits for the +#: tasks T241's Order names, L4-B3's, L4-B4's and L4-B11's (tasks.md at +#: 204145ae). Lane 2's plan GP-24 wrote it (task sets 12b's rule 11). +SQL_REGISTER_GATE_TABLE = { + "*": ("T413", "T414", "T415", "T420"), # every id: the tasks all its rows share +} + +#: What a writer that fell back to the files, or offered to, would say: the +#: register's file paths as a target, or the files mode by name. None may +#: appear in a refusal on primary (P213-215: "nothing ever written to the +#: files instead"). +FILES_WORDS = re.compile(r"lanes/LANES\.md|lanes/log/|mode=files|files mode|files-mode" + r"|fall(ing)? ?back", re.I) + + +@pytest.mark.parametrize("verb", list(WRITE_VERBS)) +def test_an_unreachable_store_is_69_naming_the_store_and_never_the_files(tmp_path, verb): + """AT-2's FP oracle for the refusal's text (P213-214; contract section + 2.6): `lanes-edit.sh <verb>` on primary, with the database unreachable, + exits 69; stderr names the store, `psql`'s own first line with the socket + it tried, and the error, with no password, no `PGPASSWORD` and no URL; + it never names the files as a target or a fallback; no call follows the + failed one; and the files under `lanes/` are as they were.""" + ws = PrimaryWorkstation(tmp_path, prep=PREPS.get(verb)) + fake = fake_psql_dir(ws.fakebin, answers=unreachable_answers(ws.dead)) + ws.env.update(fake) + argv, lane = WRITE_VERBS[verb] + lanes_before = ws.git_state()[1] + proc = ws.run(argv, lane) + said = proc.stdout + proc.stderr + assert proc.returncode == 69, ( + f"lanes-edit.sh {verb} on primary exited {proc.returncode}, not 69, with the store " + f"unreachable (L4-B3, T415's attempt loop): {proc.stderr[-800:]}") + assert str(ws.dead) in proc.stderr and "connection to server" in proc.stderr, ( + f"stderr does not name the store and the error: {proc.stderr!r}") + assert SECRET not in said and "PGPASSWORD" not in said, "a credential reached the output" + assert not re.search(r"postgres(ql)?://", said), f"a URL reached the output: {said!r}" + assert not FILES_WORDS.search(proc.stderr), ( + f"the refusal names the files: {FILES_WORDS.search(proc.stderr).group(0)!r} in " + f"{proc.stderr!r}") + assert len(fake_calls(fake)) == 1, f"calls after the failed one: {fake_calls(fake)}" + assert ws.git_state()[1] == lanes_before, "a file under lanes/ changed" diff --git a/tests/test_sql_register_writes.py b/tests/test_sql_register_writes.py new file mode 100644 index 00000000..6231b8f8 --- /dev/null +++ b/tests/test_sql_register_writes.py @@ -0,0 +1,1065 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Feature 007's test 2 (AT-2; opensoft/openRepoTools#165): a register write +exits 69 when the database is unreachable, with nothing written. + +THIS MODULE holds test 2's storage-layer case, phase N (the test plan's +section 1.3; lane 2's T210): +`test_the_storage_layer_entry_exits_69_when_the_database_is_unreachable`; +and test 2's per-verb cases, its refused transactions, its partial failures +and S1's other tests, phase W, lane 2's T241 (see "phase W: T241" below), +with lane 3's reading 3 of T112, an image holding a CR or a NUL refused with +2 by `register commit`, and lane 3's Q35, `request-handoff`'s refusals before +its claim, 64 and never 2 (T241d). + +THE STORAGE-LAYER ENTRY is the managed projection writer's (design S4), driven +by the fake writer AT-1's part N drives it with, +`test_sql_register_render.py`'s `projection_entry`: one attempt of S1's loop, +`register snapshot --write-id new ... --tree <dir> --checkout <c>` (contract +section 3.2), then, on 0 alone, the attempt directory and `register commit` +(section 3.3), as the verb `managed-projection`. + +WHY THE 69 IS THE SNAPSHOT'S. With the database unreachable, the entry's first +call is a read, and a read that cannot reach its database is 69 (contract +section 2.7, "On a read"; section 3.2's exits; AT-2's outcome table, "no +connection at the first snapshot is 69"). `register commit` against an +unreachable database is 3, in doubt, never 69 (section 2.7, CO-5 and CO-6; +lane 1's T112 builds it so), so the entry never reaches it: the writer +abandons on a snapshot's 69 (section 3.3, "The caller's map"). The case fails +until L1-A9 (lane 1's T111, `register snapshot`) lands, and, for the flipped +copy, L1-A4 (T105's constant). + +THE FAULT, WITH NO ENGINE (AT-2's "Unreachable"): the configuration's +`register_url=` names a fresh, empty socket directory, and the `psql` first on +`PATH` is T203's register fake, which since T203b answers T106's `psql +--version` itself with 16.4 (logged as its own kind, and left out of +`fake_calls`), and every call that carries a request with `psql`'s own exit 2 +and its "connection to server ... failed" text, as the real `psql` answers an +empty socket directory. The fake's log is the oracle for what reached the store: +one call, the snapshot's, with no `commit_write` in it, the configured +password file and no `PGPASSWORD`, and no call after it (no retry that reads +as a write, and no fallback). With no request that reached a database, the +register's rows and the journal are unchanged; on the real engine, the +per-verb cases (T241) read them back by digest. +""" + +from __future__ import annotations + +import atexit +import hashlib +import json +import os +import re +import shutil +import subprocess +import tempfile +import time +import uuid +from pathlib import Path +from urllib.parse import quote + +import pytest + +from conftest import WINDOWS_SKIP +from pgcluster import Database +from sql_register_helpers import PSQL_SHIM, PSQL_SHIM_CONTROL, PSQL_SHIM_LOG +from test_sql_register_render import (AUTHOR, DOT, EM, LOGIN_READER, LOGIN_WRITER, SCHEMA, SEED, + SID_A1, SID_A2, TIP, WRITER, WS, Estate, _canonical_rows, + ensure_logins, fake_calls, fake_psql_dir, + flipped, git, import_to_primary, index_env, primary_config, + projection_entry, rows, run_index, sql, workspace) + +pytestmark = [WINDOWS_SKIP, pytest.mark.skipif( + shutil.which("bash") is None or shutil.which("git") is None, + reason="the lane tooling is bash over git")] + +#: THE LANDING GATE'S TABLE (T280; `tests/sql_register_gate.py` reads it, and +#: T281 removes it in the last set): the tasks each id of this module waits +#: for, by T210's and T241's Orders (tasks.md at 204145ae), keyed by function +#: or by one id, with T241's As built for `[log]`. Lane 2's plan GP-24 wrote +#: it (task sets 12b's rule 11). +SQL_REGISTER_GATE_TABLE = { + "test_a_failure_in_a_late_statement_leaves_journal_lines_and_head_unchanged": ("T413", "T414", "T415", "T420"), # T241; tasks:2324 + "test_a_hand_edit_commit_is_refused_on_primary": ("T413", "T414", "T415", "T420"), # T241; tasks:2324 + "test_a_pending_hand_edit_names_the_file_and_a_recovery_that_works": ("T413", "T414", "T415", "T420"), # T241; tasks:2324 + "test_a_queued_handoff_commit_is_still_published": ("T413", "T414", "T415", "T420"), # T241; tasks:2324 + "test_a_queued_lanes_commit_is_refused_as_a_divergence": ("T413", "T414", "T415", "T420"), # T241; tasks:2324 + "test_a_refused_write_leaves_no_lock": ("T413", "T414", "T415", "T420"), # T241; tasks:2324 + "test_a_write_goes_on_with_the_service_down": ("T413", "T414", "T415", "T420"), # T241; tasks:2324 + "test_an_image_holding_a_cr_or_a_nul_is_refused_with_2_and_nothing_sent": ("T112",), # T241; tasks:2324 + "test_each_direct_write_refuses_with_2_on_primary": ("T413", "T414", "T415", "T420"), # T241; tasks:2324 + "test_each_write_exits_69_when_the_database_is_unreachable": ("T413", "T414", "T415", "T420"), # T241; tasks:2324 + "test_each_write_exits_69_when_the_database_refuses_the_transaction": ("T413", "T414", "T415", "T420"), # T241; tasks:2324 + "test_each_write_exits_69_when_the_switch_is_not_primary": ("T413", "T414", "T415", "T420"), # T241; tasks:2324 + "test_request_handoff_refuses_64_never_2_on_primary": ("T413", "T414", "T415", "T420"), # T241; tasks:2324 + "test_the_storage_layer_entry_exits_69_when_the_database_is_unreachable": ("T105", "T107", "T108", "T111", "T112", "T227", "T301"), # T210; tasks:1951 + "test_a_failure_in_a_late_statement_leaves_journal_lines_and_head_unchanged[rename-lane]": ("T413", "T414", "T415", "T420", "T422"), # T241; tasks:2324 + "test_a_refused_write_leaves_no_lock[rename-lane]": ("T413", "T414", "T415", "T420", "T422"), # T241; tasks:2324 + "test_each_write_exits_69_when_the_switch_is_not_primary[log]": ("T412", "T413", "T414", "T415", "T417", "T420"), # T241; tasks:2322 +} + +#: Contract section 2.2's argv, exactly. +PSQL_ARGV = ["--no-psqlrc", "-X", "-q", "-A", "-t", "-v", "ON_ERROR_STOP=1", "-v", + "VERBOSITY=verbose", "-v", "SHOW_CONTEXT=never"] + +#: The writer's login and its password, which must never be printed. +WRITER_LOGIN = "lanes_w_t210" +SECRET = "t210-never-printed-0b5e" + +#: The session `request-handoff --force` writes its `PAUSED` for (`--session`). +#: Without it the verb refuses with 2, naming no uuid (`lanes-edit.sh`'s +#: `requester_uuid`, at a2073eae:10691), before it reaches any SQL, so a case +#: that expects the write's own refusal or 69 would fail by that usage refusal. +SID_REQUESTER = "bbbbbbbb-0007-4000-8000-00000000b007" + +#: What `_masked_path` keeps off a case's `PATH`: an installed `lanes-index`, +#: a real `psql`, and every `pg_` client that `postgresql-16` puts beside it. +_MASKED_NAMES = ("psql", "lanes-index") +_MASKED_PREFIX = "pg_" +#: `_masked_path`'s mirrors, built once per process: each masked directory's +#: real path, to its mirror under the one `l2-pathmask-` directory. +_PATH_MIRRORS: dict = {} +_PATH_MIRROR_ROOT: list = [] + + +def _masked_path() -> str: + """The caller's PATH with every directory kept, in its place, and each one + that holds a masked name swapped for a mirror of it without them. A real + `psql` or `pg_` client, or an installed `lanes-index`, is never what a + case runs; but dropping the directory that holds one drops what sits + beside it. On a GitHub runner, `postgresql-16`'s client package puts + `psql` in `/usr/bin` together with `git` and `bash`, and `/bin` links + there, so a filter that drops the directory leaves a case no `git` or + `bash` to run. The mirror is a directory of symlinks, one per entry, each + to the original entry's absolute path, the masked names left out. It is + built once per process, keyed by the directory's real path, under one + temporary directory that an `atexit` handler removes. A directory that + holds no masked name passes through unchanged, so where no `PATH` + directory holds one, the PATH is what the old filter gave; empty entries + are left out, as that filter left them.""" + kept = [] + for part in os.environ.get("PATH", "").split(os.pathsep): + if not part: + continue + real = os.path.realpath(part) + if real not in _PATH_MIRRORS: + try: + names = os.listdir(real) + except OSError: + names = [] + if not any(_is_masked(name) for name in names): + kept.append(part) + continue + _PATH_MIRRORS[real] = _path_mirror(real, names) + kept.append(_PATH_MIRRORS[real]) + return os.pathsep.join(kept) + + +def _is_masked(name: str) -> bool: + return name in _MASKED_NAMES or name.startswith(_MASKED_PREFIX) + + +def _path_mirror(real: str, names: list) -> str: + """`real`'s mirror: a new directory under the one `l2-pathmask-` + directory, holding a symlink to each entry of `real` but the masked.""" + if not _PATH_MIRROR_ROOT: + root = tempfile.mkdtemp(prefix="l2-pathmask-") + atexit.register(shutil.rmtree, root, ignore_errors=True) + _PATH_MIRROR_ROOT.append(root) + mirror = tempfile.mkdtemp(prefix=(os.path.basename(real) or "root") + "-", + dir=_PATH_MIRROR_ROOT[0]) + for name in names: + if not _is_masked(name): + os.symlink(os.path.join(real, name), os.path.join(mirror, name)) + return mirror + + +def test_the_storage_layer_entry_exits_69_when_the_database_is_unreachable(tmp_path): + """The storage-layer entry, called as AT-1's part N calls it, against a + `register_url=` whose socket directory is fresh and empty: it exits 69, + and stderr names the store and the error, `psql`'s own first line, which + names the socket, with no credential and no URL. The fake's log holds one + call, the snapshot's, sent with section 2.2's argv, as the configured + login, with the configured password file and no `PGPASSWORD`, and + carrying no `commit_write`; no call follows it. Nothing is written: no + scratch tree, no attempt directory beyond it, and the lane checkout's + HEAD, status, index and `origin/main` as they were (AT-2, "Unreachable + (RE), the storage-layer entry"; the delta spec's "Unreachable or refused + is exit 69 with nothing written").""" + dead = tmp_path / "dead" + dead.mkdir() + socket = dead / ".s.PGSQL.5432" + psql_error = (f'psql: error: connection to server on socket "{socket}" failed: ' + f"No such file or directory") + fake = fake_psql_dir(tmp_path / "fakebin", answers=[ + {"exit": 2, "stderr": psql_error + "\n\tIs the server running locally and accepting " + "connections on that socket?\n"}]) + estate = Estate(tmp_path / "estate") + copy = flipped(tmp_path) + conf_dir = tmp_path / "conf" + conf_dir.mkdir() + passfile = conf_dir / "pgpass" + passfile.write_text(f"*:*:*:{WRITER_LOGIN}:{SECRET}\n", encoding="utf-8") + passfile.chmod(0o600) + host = quote(dead.as_posix(), safe="") + conf = primary_config(conf_dir / "lanes-index.conf", + f"postgresql://{WRITER_LOGIN}@{host}:5432/lanes_t210", + f"postgresql://lanes_r_t210@{host}:5432/lanes_t210", passfile) + env = index_env(tmp_path, conf, estate.home, **fake) + env["PATH"] = str(tmp_path / "fakebin") + os.pathsep + _masked_path() + before = estate.state() + + done = projection_entry(copy, env, estate.checkout, tmp_path, "managed-projection", + "lanes-edit.sh managed-projection: test 2's storage-layer case") + snap = done["snapshot"] + said = snap.stdout + snap.stderr + assert done["code"] == 69, (f"the storage-layer entry exited {done['code']}, not 69: " + f"{snap.stderr}") + assert done["commit"] is None, "the entry went on to `register commit` after a 69" + + # THE ERROR AND THE STORE, WITHOUT CREDENTIALS (contract section 2.6). + assert psql_error in snap.stderr, f"stderr does not carry psql's error: {snap.stderr!r}" + assert SECRET not in said, "a password reached the output" + assert not re.search(r"postgres(ql)?://", said), f"a URL reached the output: {said!r}" + + # WHAT REACHED THE STORE: the snapshot's one call, and nothing after it. + calls = fake_calls(fake) + assert len(calls) == 1, f"{len(calls)} psql calls reached the store, not one: {calls}" + call = calls[0] + assert call["argv"] == PSQL_ARGV, call["argv"] + assert call["url"].startswith(f"postgresql://{WRITER_LOGIN}@"), call["url"] + assert call["passfile"] == str(passfile) and call["pgpassword"] is False, call + assert "commit_write" not in call["stdin"], "the snapshot's call carried a commit" + + # NOTHING WRITTEN: no scratch tree, and the lane checkout as it was. + tree = done["attempt"] / "tree" + assert not tree.exists() or not any(tree.iterdir()), "a scratch tree was built" + assert not (done["attempt"] / "snapshot").exists() + assert estate.state() == before, "the lane checkout changed" + + +# ============================================================ phase W: T241 +# +# TEST 2'S REFUSALS AND ITS PARTIAL FAILURE (lane 2's T241; AT-2, the test +# plan's lines 646-781; FR-018, FR-019, FR-026, FR-059). Each of S1's writes +# runs as `lanes-edit.sh <verb>` on a `mode=primary` workstation, from the +# flipped copy (T203's, `RENDER_GIT_HALF = True`) with `lanes-edit.sh` beside +# it, so the verb's `lanes-index` is that copy (CLI4.5 section 6's copy rule). +# +# THE VERBS are S1's writes but `commit` (the test plan's line 750): the +# fourteen arms of `lanes-edit.sh`'s write dispatch at a2073eae (`:16537`), +# `commit` left out, whose direct write is 2 (D10). Each runs once, with the +# argument list `WRITE_VERBS` gives it; `log` runs once, as `log NOTED`. +# +# NO ENGINE (FP): the database unreachable, as a fake `psql` (T203's register +# fake, which answers T106's `--version` itself) that exits 2 with `psql`'s own +# "connection to server ... failed" text; D10's refusals; the queued commits; +# `request-handoff`'s 64s before its claim. +# REAL ENGINE (RE, on `pg`, skipped without PostgreSQL 16 by T205's banner): +# the switch not `primary`, the refused GRANTs, the late statement, the lock, +# the pending hand edit and the service down, each over test 1's imported +# register (`import_to_primary`, AT-LR006's route). +# +# They fail until lane 4's L4-B3 (T415's attempt loop), L4-B4 and L4-B11 +# (T420, D10's refusals) land, each by its own assertion here: today's +# `lanes-edit.sh` writes the files whatever `mode=` says. +# +# R02 (lane 1, #165 6755590769; lane 3, 6755615338; F10-OWED items 35 and +# 37): after LR004, `register commit` re-reads once and never resends. No case +# here meets LR004; the refused-transaction and late-statement cases assert +# that a refused commit call is never sent again, so a resend under any +# refusal fails them. LR004's own cases are T221's (`lr004_on_an_edit`, +# `lr004_reloads_once`). +# +# LANE 3'S READING 3 OF T112 (#165 6755386771; F10-OWED item 31): the +# malformed-directory refusals are 2, with nothing sent. An image that holds a +# CR or a NUL is one, so its case below expects 2 and never 69; it needs no +# engine and no lane 4 code, and runs `register commit` directly. + +def _with_row(lane: str, sid: str, cell: str, log: str = None) -> dict: + """A prep: test 1's SEED with one more row in `LANES.md`'s table, after + repoA-2's, and the lane's log (its header, then `log`'s lines).""" + lanes = SEED["lanes/LANES.md"] + anchor = next(line for line in lanes.split("\n") if line.startswith("| `repoA-2` |")) + row = (f"| `{lane}` | harness `{sid}` | Eagle / test / brett | 2026-09-01T00:00Z | none " + f"| handoffs/{lane}.md | {cell} |") + header = f"# lane {lane} {EM} object log (lane-collision-protocol Amendment 7)\n" + return {"lanes/LANES.md": lanes.replace(anchor + "\n", anchor + "\n" + row + "\n", 1), + f"lanes/log/{lane}.md": header + (log or "")} + + +#: The starting state three verbs need, or they refuse for want of work (2): +#: `archive-rows <repo>` moves a repository's RETIRED rows; `retire-rows` +#: takes a dormant row, whose log has no lane-kind line and whose cell is not +#: a current state (`lanes-edit.sh:13316-13352` at a2073eae); and +#: `migrate-state-cells` migrates a diary cell, one that is not Amendment +#: 13(a)'s phrase. Each is committed and pushed before the case runs, and on +#: the real engine before the import. +PREPS = { + "archive-rows": _with_row( + "repoZ-2", "eeeeeeee-0002-4000-8000-00000000e002", + f"RETIRED {DOT} 2026-09-03T00:00:00Z {DOT} retired", + f"RETIRED {EM} lane repoZ-2, session eeeeeeee-0002-4000-8000-00000000e002@Eagle, " + f"2026-09-03T00:00:00Z, lane:repoZ-2 {EM} retired\n"), + "retire-rows": _with_row("repoA-4", "aaaaaaaa-0005-4000-8000-00000000a005", + f"MIGRATED {DOT} 2026-09-01T00:00:00Z {DOT} migrated"), + "migrate-state-cells": _with_row("repoA-5", "aaaaaaaa-0006-4000-8000-00000000a006", + f"parked 2026-09-01 {DOT} picked up 2026-09-02"), +} + +#: S1's writes but `commit`: {verb: (its arguments, the lane it writes as)}. +#: The argument forms are `lanes-edit.sh`'s usage lines at a2073eae. +WRITE_VERBS = { + "add-row": (["add-row", f"| `repoA-3` | harness `aaaaaaaa-0004-4000-8000-00000000a004` | " + f"Eagle / test / brett | 2026-11-10T00:00Z | none | handoffs/repoA-3.md | " + f"LIVE {DOT} 2026-11-10T00:00:00Z {DOT} test 2 |"], "repoA-2"), + "append-line": (["append-line", f"HOLD {EM} lane repoA-2 ({WS}), window w, " + f"2026-11-10T00:00:00Z: opensoft/repoB main {TIP} for test 2"], "repoA-2"), + "append-session-id": (["append-session-id", "repoA-2", f"harness `{SID_A2}`", + " (test 2)"], "repoA-2"), + "archive-rows": (["archive-rows", "repoZ", "--yes"], "repoA-2"), + "claim": (["claim", "opensoft/repoA#9", "--no-github"], "repoA-2"), + "log": (["log", "NOTED", "lane:repoA-2", "test 2's write"], "repoA-2"), + "migrate-state-cells": (["migrate-state-cells", "--yes"], "repoA-2"), + "release": (["release", "opensoft/repoA#7", "test 2", "--no-github"], "repoA-1"), + "rename-lane": (["rename-lane", "repoA-2", "repoA-3", "test 2", "--no-github"], "repoA-2"), + "replace-in-row": (["replace-in-row", "repoA-2", "parked", "parked for test 2"], "repoA-2"), + "request-handoff": (["request-handoff", "repoA-1", "--force", "test 2", "--session", + SID_REQUESTER], "repoA-2"), + "retire-rows": (["retire-rows", "repoA-4", "--reason", "test 2"], "repoA-2"), + "set-row-state": (["set-row-state", "repoA-2", f"PAUSED {DOT} test 2"], "repoA-2"), +} + +#: P11's writes that change several files (the test plan's lines 653-656). +LATE_WRITES = { + "LANDING": (["append-line", f"LANDING {EM} lane repoA-2, session {SID_A2}@{WS}, " + f"2026-11-10T00:00:00Z, PR #8 into opensoft/repoA main"], "repoA-2"), + "LANDED": (["append-line", f"LANDED {EM} lane repoA-1, session {SID_A1}@{WS}, " + f"2026-11-10T00:00:00Z, PR #7 into opensoft/repoA main {chr(0x2192)} " + f"abc1234"], "repoA-1"), + "rename-lane": WRITE_VERBS["rename-lane"], + "retire-rows": WRITE_VERBS["retire-rows"], + "archive-rows": WRITE_VERBS["archive-rows"], + "migrate-state-cells": WRITE_VERBS["migrate-state-cells"], +} + +#: EACH LATE WRITE'S LAST STRUCTURED ROW, AND HOW IT IS BROKEN (TP:686-690, +#: "its last structured row breaks a CHECK"; T241i): the `edit-entry` arm's +#: `field` and `value` for the last row of the last list the write's entry +#: carries, in the order `commit_write`'s step 7 applies them, `lanes`, +#: `log_lines`, `register_lines`, then `object_holds` (a2935aee:lanes-index:7282). +#: - A `LANDING` or `LANDED` that `append-line` writes changes `lanes/LANES.md` +#: alone: one `register_lines` row (lane 4's TRIAGE-W12 run 2 logged +#: LANDED's entry: `lanes`, `log_lines` and `object_holds` empty). +#: - `rename-lane`, `retire-rows` and `migrate-state-cells` end with the +#: `log_lines` rows of the lines they add to a log. +#: - `archive-rows` writes `lanes/LANES.md` and the archive alone: its last +#: row is the archived lane's `lanes` row. +#: The `register_lines` and `log_lines` rows lose their `workstation`, which +#: each table's primary CHECK requires (`mode = 'files' OR +#: coalesce(workstation, '') <> ''`, a2935aee:lanes-index:7122 and :7065); the +#: database stamps `mode`, so the row breaks it on primary alone. A `lanes` +#: row has no such CHECK, so it gets a `lane` that is not its key +#: (`lower(lane) = lane_key`, :7038). +LATE_ROWS = { + "LANDING": ("register_lines.-1.workstation", ""), + "LANDED": ("register_lines.-1.workstation", ""), + "rename-lane": ("log_lines.-1.workstation", ""), + "retire-rows": ("log_lines.-1.workstation", ""), + "archive-rows": ("lanes.-1.lane", "t241i-not-its-key"), + "migrate-state-cells": ("log_lines.-1.workstation", ""), +} + +#: AT-3's line, which a writer prints where the switch is not `primary`. +NOT_PRIMARY_LINE = "this estate's register is SQL; configure `mode=primary`" + +#: EACH WRITE LANE'S OWN CHECKOUT, `<c>` (T241e; B14 tasks:1142's T415 +#: bullets; R17). On primary a write reads its pending hand edits, its author +#: and the snapshot's `repos.tsv` from the checkout of the lane it writes for, +#: `<W>-lanes/<lane>`, and refuses with nothing sent where that is not there +#: (2, or 64 for `request-handoff`), since a clone would be D12's fetch. The +#: lanes these writes are for (`lanes-edit.sh`'s `write_lane_of`): repoA-1 and +#: repoA-2, as `LANES_LANE` or a verb's `<lane>`, and repoA-3, `add-row`'s new +#: row. `PrimaryWorkstation` makes `<c>` for each, unless a case asks for none. +WRITE_LANES = ("repoA-1", "repoA-2", "repoA-3") + + +class PrimaryWorkstation: + """A `mode=primary` workstation for `lanes-edit.sh`'s writes: the + files-mode workspace of test 1's sync case (`workspace`), at C, the + flipped copy with `lanes-edit.sh` beside it, and a `lanes-index.conf` + whose `register_url=` and `reader_url=` name `urls`, or a fresh, empty + socket directory, with a 0600 `register_passfile=`. `fakebin` is first on + `PATH`. Each lane in `checkouts` gets `<c>`, its own checkout, a clone of + origin made after the case's prep (`WRITE_LANES` by default).""" + + def __init__(self, tmp_path: Path, urls: tuple = None, fakebin: Path = None, + prep: dict = None, checkouts: tuple = WRITE_LANES): + self.fakebin = fakebin or tmp_path / "fakebin" + self.fakebin.mkdir(parents=True, exist_ok=True) + self.estate, self.env, _source = workspace(tmp_path / "ws", self.fakebin) + if prep: + self._prep(prep) + self.copy = flipped(tmp_path) + self.lanes_edit = self.copy.parent / "lanes-edit.sh" + conf_dir = tmp_path / "conf" + conf_dir.mkdir() + self.passfile = conf_dir / "pgpass" + self.passfile.write_text(f"*:*:*:{WRITER_LOGIN}:{SECRET}\n", encoding="utf-8") + self.passfile.chmod(0o600) + self.dead = tmp_path / "dead" + self.dead.mkdir() + host = quote(self.dead.as_posix(), safe="") + register_url, reader_url = urls or ( + f"postgresql://{WRITER_LOGIN}@{host}:5432/lanes_t241", + f"postgresql://lanes_r_t241@{host}:5432/lanes_t241") + self.conf = primary_config(conf_dir / "lanes-index.conf", register_url, reader_url, + self.passfile) + self.env.update(LANES_INDEX_CONFIG=str(self.conf)) + self.env.pop("LANES_INDEX", None) + for lane in checkouts: + self.make_lane_checkout(lane) + + def _prep(self, files: dict) -> None: + """`files` written over the checkout, committed and pushed, so the + case starts from them; C is that commit.""" + estate = self.estate + for path, text in files.items(): + (estate.checkout / path).parent.mkdir(parents=True, exist_ok=True) + (estate.checkout / path).write_bytes(text.encode("utf-8")) + git(estate.checkout, "add", "-A", env=estate.env) + git(estate.checkout, "commit", "-q", "-m", "C': the case's starting state", + env=estate.env) + git(estate.checkout, "push", "-q", "origin", "main", env=estate.env) + estate.files.update(files) + estate.c = git(estate.checkout, "rev-parse", "HEAD", env=estate.env).strip() + estate.lanes_tree = git(estate.checkout, "rev-parse", f"{estate.c}:lanes", + env=estate.env).strip() + + def lane_checkout(self, lane: str) -> Path: + """`<c>`, lane `lane`'s own register checkout, where `lanes-edit.sh`'s + `lane_checkout_path` puts it (Amendment 23 S1): `<W>-lanes/<lane>`, W + being the real path of `workspace.yaml`'s `path:`, this checkout.""" + real = Path(os.path.realpath(self.estate.checkout)) + return real.parent / f"{real.name}-lanes" / lane + + def make_lane_checkout(self, lane: str) -> Path: + """`<c>` for `lane`, a clone of W's origin, as `lane-checkout <lane> + --create` makes one.""" + target = self.lane_checkout(lane) + target.parent.mkdir(parents=True, exist_ok=True) + git(target.parent, "clone", "-q", str(self.estate.origin), str(target), + env=self.estate.env) + return target + + def run(self, argv: list, lane: str | None, **extra) -> subprocess.CompletedProcess: + """`lanes-edit.sh <argv>` in the checkout, as lane `lane` + (`LANES_LANE`), or with `LANES_LANE` unset where `lane` is None.""" + env = dict(self.env, **extra) + if lane is None: + env.pop("LANES_LANE", None) + else: + env["LANES_LANE"] = lane + return subprocess.run(["bash", str(self.lanes_edit), *argv], capture_output=True, + encoding="utf-8", errors="replace", env=env, timeout=120, + cwd=str(self.estate.checkout), check=False, + stdin=subprocess.DEVNULL) + + def git_state(self) -> tuple: + """AT-2's git oracle: the checkout's HEAD, status, index digest and + `origin/main`, the files under `lanes/`, and origin's refs.""" + lanes = self.estate.checkout / "lanes" + files = {p.relative_to(lanes).as_posix(): hashlib.sha256(p.read_bytes()).hexdigest() + for p in sorted(lanes.rglob("*")) if p.is_file()} + refs = git(self.estate.origin, "for-each-ref", "--format=%(refname) %(objectname)", + env=self.estate.env) + return self.estate.state(), files, refs + + +def unreachable_answers(dead: Path) -> list: + """The fake's answer for every call that carries a request: `psql`'s own + exit 2 and its text for an empty socket directory (AT-2, "Unreachable + (FP)").""" + socket = dead / ".s.PGSQL.5432" + return [{"exit": 2, "stderr": f'psql: error: connection to server on socket "{socket}" ' + f"failed: No such file or directory\n\tIs the server running " + f"locally and accepting connections on that socket?\n"}] + + +def _lock_files(ws: PrimaryWorkstation) -> list: + """The writers' mutexes left anywhere under the workspace: the lane + checkout's and any scratch tree's `.lanes-edit.lock` (`lanes-edit.sh`'s + `LOCK`, :1212 at a2073eae; `design.md` S1, step 2), and git's + `index.lock`.""" + root = ws.estate.root + return sorted(p.relative_to(root).as_posix() for p in root.rglob("*") + if p.name in (".lanes-edit.lock", "index.lock")) + + +# ------------------------------------------------------------ no engine (FP) + +@pytest.mark.parametrize("verb", list(WRITE_VERBS)) +def test_each_write_exits_69_when_the_database_is_unreachable(tmp_path, verb): + """AT-2, "Unreachable (FP)": with every `psql` call answered by `psql`'s + exit 2 and its "connection to server ... failed" text, `lanes-edit.sh + <verb>` on primary exits 69; stderr names the store and the error with + no credential and no URL; a read verb's stdout is empty; the fake's log + shows the writer connected with `register_url=`'s login and + `register_passfile=`, `PGPASSWORD` never set, and no call after the + failed one (no retry that reads as a write, no fallback); and git is as + it was (the checkout, the files under `lanes/`, origin's refs).""" + ws = PrimaryWorkstation(tmp_path, prep=PREPS.get(verb)) + fake = fake_psql_dir(ws.fakebin, answers=unreachable_answers(ws.dead)) + ws.env.update(fake) + argv, lane = WRITE_VERBS[verb] + before = ws.git_state() + proc = ws.run(argv, lane) + said = proc.stdout + proc.stderr + assert proc.returncode == 69, ( + f"lanes-edit.sh {verb} on primary exited {proc.returncode}, not 69, with the database " + f"unreachable (L4-B3, T415's attempt loop): {proc.stderr[-800:]}") + assert "connection to server" in proc.stderr, f"stderr names no error: {proc.stderr!r}" + assert SECRET not in said and not re.search(r"postgres(ql)?://", said), said + calls = fake_calls(fake) + assert len(calls) == 1, ( + f"{len(calls)} psql calls carried a request, not one: a call followed the failed one " + f"(a retry that reads as a write, or a fallback): {calls}") + for call in calls: + assert call["url"].startswith(f"postgresql://{WRITER_LOGIN}@"), call["url"] + assert call["passfile"] == str(ws.passfile) and call["pgpassword"] is False, call + assert ws.git_state() == before, "git changed: a write fell back to the files" + + +@pytest.mark.parametrize("write", ["commit-carry", "push-beyond-handoffs"]) +def test_each_direct_write_refuses_with_2_on_primary(tmp_path, write): + """D10, as T420 builds it at 1b (B10 tasks:1213-1231; R16): on primary, + `commit`'s carry form (a hand edit under `lanes/`, staged and committed by + `lanes-edit.sh commit`) and a push of a commit that changes a path + outside `handoffs/` (T420's backstop) each exit 2 before any SQL: the + fake's log holds no call that carries a request, the files under `lanes/` + are as they were, and origin's refs are unchanged. The captures and + `add-row`'s compensating commit do not exist at 1b (T420: "compensat" + matches nothing), so they have no id.""" + ws = PrimaryWorkstation(tmp_path) + fake = fake_psql_dir(ws.fakebin, answers=unreachable_answers(ws.dead)) + ws.env.update(fake) + checkout = ws.estate.checkout + if write == "commit-carry": + target = checkout / "lanes" / "LANES.md" + target.write_bytes(target.read_bytes() + b"a hand edit\n") + argv = ["commit", "a hand edit, carried"] + else: + (checkout / "notes.md").write_text("outside handoffs/\n", encoding="utf-8") + git(checkout, "add", "notes.md", env=ws.estate.env) + git(checkout, "commit", "-q", "-m", "a queued commit outside handoffs/", + env=ws.estate.env) + argv = ["commit", "publish the queued commit"] + refs = git(ws.estate.origin, "for-each-ref", "--format=%(refname) %(objectname)", + env=ws.estate.env) + lanes_before = {p: (checkout / p).read_bytes() for p in SEED if (checkout / p).exists()} + proc = ws.run(argv, "repoA-1") + assert proc.returncode == 2, ( + f"{write} on primary exited {proc.returncode}, not 2 (D10; L4-B11, T420): " + f"{proc.stderr[-800:]}") + assert fake_calls(fake) == [], f"a direct write reached SQL: {fake_calls(fake)}" + assert git(ws.estate.origin, "for-each-ref", "--format=%(refname) %(objectname)", + env=ws.estate.env) == refs, "origin moved" + if write == "push-beyond-handoffs": + assert {p: (checkout / p).read_bytes() for p in lanes_before} == lanes_before + + +def test_a_hand_edit_commit_is_refused_on_primary(tmp_path): + """GB section 4.3's D10 case (R29; R16): `lanes-edit.sh commit`'s carry + form, over a hand edit of `lanes/LANES.md`, exits 2 on primary, says the + register is SQL, reaches no SQL, and leaves the file, the index, HEAD and + origin as they were (the test plan's line 734).""" + ws = PrimaryWorkstation(tmp_path) + fake = fake_psql_dir(ws.fakebin, answers=unreachable_answers(ws.dead)) + ws.env.update(fake) + target = ws.estate.checkout / "lanes" / "LANES.md" + target.write_bytes(target.read_bytes() + b"a hand edit\n") + edited = target.read_bytes() + before = ws.estate.state() + proc = ws.run(["commit", "a hand edit"], "repoA-1") + assert proc.returncode == 2, ( + f"a hand-edit commit on primary exited {proc.returncode}, not 2 (D10; T420's carry " + f"form): {proc.stderr[-800:]}") + assert fake_calls(fake) == [], f"the refusal reached SQL: {fake_calls(fake)}" + assert target.read_bytes() == edited, "the hand edit was changed" + assert ws.estate.state() == before, "HEAD, the index or origin moved" + + +def _queue(ws: PrimaryWorkstation, path: str, text: str) -> str: + """A local commit, not pushed, that writes `path`. Returns its sha.""" + checkout = ws.estate.checkout + target = checkout / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(text.encode("utf-8")) + git(checkout, "add", "--", path, env=ws.estate.env) + git(checkout, "commit", "-q", "-m", f"queued: {path}", env=ws.estate.env) + return git(checkout, "rev-parse", "HEAD", env=ws.estate.env).strip() + + +def test_a_queued_handoff_commit_is_still_published(tmp_path): + """GB section 4.3's D10 case (R16): on primary, the publish act stays, + fenced to `handoffs/`. A queued local commit that writes only + `handoffs/repoA-1.md` is published by `lanes-edit.sh commit` with nothing + staged: it exits 0, origin's `main` is that commit, and no `psql` call is + made, since `commit` is exempt from the attempt loop (T420, review M2).""" + ws = PrimaryWorkstation(tmp_path) + fake = fake_psql_dir(ws.fakebin, answers=unreachable_answers(ws.dead)) + ws.env.update(fake) + sha = _queue(ws, "handoffs/repoA-1.md", "# repoA-1's handoff, queued\n") + proc = ws.run(["commit", "publish the queued commit"], "repoA-1") + assert proc.returncode == 0, ( + f"the publish act exited {proc.returncode} on primary (T420 keeps it): " + f"{proc.stderr[-800:]}") + assert git(ws.estate.origin, "rev-parse", "refs/heads/main", + env=ws.estate.env).strip() == sha, "the queued handoff commit was not published" + assert fake_calls(fake) == [], f"the publish act reached SQL: {fake_calls(fake)}" + + +def test_a_queued_lanes_commit_is_refused_as_a_divergence(tmp_path): + """GB section 4.3's D10 case (R16): on primary, a queued local commit that + writes under `lanes/` is refused by the publish act as a divergence: a + nonzero exit that names the divergence and the commit, no push (origin's + refs unchanged), no SQL, and the local commit left for the operator.""" + ws = PrimaryWorkstation(tmp_path) + fake = fake_psql_dir(ws.fakebin, answers=unreachable_answers(ws.dead)) + ws.env.update(fake) + refs = git(ws.estate.origin, "for-each-ref", "--format=%(refname) %(objectname)", + env=ws.estate.env) + lanes = ws.estate.checkout / "lanes" / "LANES.md" + sha = _queue(ws, "lanes/LANES.md", lanes.read_text(encoding="utf-8") + "queued\n") + proc = ws.run(["commit", "publish the queued commit"], "repoA-1") + assert proc.returncode == 2, ( + f"a queued lanes/ commit on primary exited {proc.returncode}, not 2 (T420's fence): " + f"{proc.stderr[-800:]}") + assert "diverge" in proc.stderr.lower() and sha[:7] in proc.stderr, proc.stderr + assert git(ws.estate.origin, "for-each-ref", "--format=%(refname) %(objectname)", + env=ws.estate.env) == refs, "origin moved" + assert git(ws.estate.checkout, "rev-parse", "HEAD", env=ws.estate.env).strip() == sha + assert fake_calls(fake) == [], f"the refusal reached SQL: {fake_calls(fake)}" + + +#: An image that breaks the register's text: a line holding a CR, and one +#: holding a NUL, each in `lanes/LANES.md`'s new image. +BAD_IMAGES = {"image-cr": "\r", "image-nul": "\0"} + + +@pytest.mark.parametrize("bad", list(BAD_IMAGES)) +def test_an_image_holding_a_cr_or_a_nul_is_refused_with_2_and_nothing_sent(tmp_path, bad): + """Lane 3's reading 3 of T112 (#165 6755386771; F10-OWED item 31; contract + section 3.3, "a listed file breaks its format ... 2"): `register commit` + over an attempt directory whose image of `lanes/LANES.md` holds a CR (the + line ends CRLF) or a NUL exits 2, never 69, before anything is sent: no + `psql` call at all, not even T106's `--version` probe, and the attempt + directory is as it was. Stderr names the image's path. No engine and no + lane 4 code: the directory is built by hand, in section 3.3's table.""" + copy = flipped(tmp_path) + fake = fake_psql_dir(tmp_path / "fakebin", answers=[{"exit": 3, "stderr": + "ERROR: XX000: never sent\n"}]) + estate = Estate(tmp_path / "estate") + conf_dir = tmp_path / "conf" + conf_dir.mkdir() + passfile = conf_dir / "pgpass" + passfile.write_text(f"*:*:*:{WRITER_LOGIN}:{SECRET}\n", encoding="utf-8") + passfile.chmod(0o600) + host = quote((tmp_path / "dead").as_posix(), safe="") + conf = primary_config(conf_dir / "lanes-index.conf", + f"postgresql://{WRITER_LOGIN}@{host}:5432/lanes_t241", + f"postgresql://lanes_r_t241@{host}:5432/lanes_t241", passfile) + env = index_env(tmp_path, conf, estate.home, **fake) + env["PATH"] = str(tmp_path / "fakebin") + os.pathsep + _masked_path() + + write_id, generation = str(uuid.uuid4()), str(uuid.uuid4()) + args_sha256 = hashlib.sha256(b"t241 " + bad.encode("ascii")).hexdigest() + not_after = str(int(time.time()) + 300) + attempt = tmp_path / "attempt" + path = "lanes/LANES.md" + old = SEED[path].encode("utf-8") + new = old + (f"HOLD {EM} lane repoA-2 ({WS}), window w, 2026-11-10T00:00:00Z: " + f"opensoft/repoB main {TIP} for a check{BAD_IMAGES[bad]}").encode("utf-8") + new += b"\n" + blob = lambda data: hashlib.sha1(b"blob %d\0" % len(data) + data).hexdigest() # noqa: E731 + (attempt / "images" / "lanes").mkdir(parents=True) + (attempt / "images" / path).write_bytes(new) + (attempt / "tree").mkdir() + (attempt / "snapshot").write_text( + f"format=1\nwrite_id={write_id}\ngeneration={generation}\nn=5\n" + f"not_after={not_after}\nclock={int(time.time())}\n", encoding="utf-8") + (attempt / "not_after").write_text(not_after + "\n", encoding="utf-8") + (attempt / "changes.tsv").write_text(f"M\t{path}\t{blob(old)}\t{blob(new)}\n", + encoding="utf-8") + (attempt / "files").write_text(_canonical_rows([("M", path, "", "")], {path: new}), + encoding="utf-8") + (attempt / "msg").write_text("lanes-edit.sh append-line: test 2's bad image\n", + encoding="utf-8") + (attempt / "author").write_text(AUTHOR + "\n", encoding="utf-8") + before = {p.relative_to(attempt).as_posix(): p.read_bytes() + for p in sorted(attempt.rglob("*")) if p.is_file()} + + proc = run_index(copy, ["register", "commit", "--write-id", write_id, "--generation", + generation, "--lane", "repoA-2", "--verb", "append-line", + "--args-sha256", args_sha256, "--workstation", WS, attempt], env) + assert proc.returncode != 69, ( + f"an image holding {bad[6:].upper()} gave 69; lane 3's reading 3 makes it 2: " + f"{proc.stderr}") + assert proc.returncode == 2, f"register commit exited {proc.returncode}: {proc.stderr}" + assert f"images/{path}" in proc.stderr, f"stderr names no image: {proc.stderr!r}" + log = Path(fake["FAKE_PSQL_LOG"]) + assert not log.exists() or log.read_text(encoding="utf-8") == "", ( + f"psql was called before the refusal: {log.read_text(encoding='utf-8')}") + assert {p.relative_to(attempt).as_posix(): p.read_bytes() + for p in sorted(attempt.rglob("*")) if p.is_file()} == before + + +# REQUEST-HANDOFF'S 64S (lane 2's T241d; R-F13c-23; lane 3's batch 8, #165 +# 6780753157, Q35 and its text change 5 for B14 tasks:1149; lane 4's +# questions, `QUESTIONS-L3-1110g-b-a5582b2d.md`, 35). On primary every write +# runs four checks before its claim (B14 tasks:1142's T415 bullets): it names +# its lane, the lane's own checkout `<c>` is there (`lanes-edit.sh +# lane-checkout <lane> --create` makes it; a write makes no clone, which +# would be D12's fetch), `LANES_LANE` is a lane name, and `LANES_NO_GIT=1` is +# not set. Each refuses with nothing sent: 2 for every verb but +# `request-handoff`, which refuses 64, never 2, since `lane` reads a 2 from it +# as "lane <L> is still bound elsewhere" (REV415b NIT 6's reason). `lane` +# calls it with no `LANES_LANE` (lane 4's question 35), and lane 3 rules that +# `lane` sets it (T432), and that the verb's refusal is 64 all the same. +# +# The write's lane is `request-handoff`'s `<lane>`, repoA-1, and its `<c>` is +# `<W>-lanes/repoA-1`. Every check but the id's own is met, so each id meets +# its own refusal and no other: `<c>` is made first, a clone of origin, but +# for `[missing-checkout]`. No engine; fails until lane 4's T415 takes Q35. +# +# Lane 3's batch c, Q67 (#165 6807881675; B15 text 5 for B14 tasks:1149 and +# text 7 for F13d:513), adds the two other refusals the primary branch makes +# before its claim: a pending hand edit of a rendered file in `<c>` +# (`pw_hand_edit_refuse`, `[hand-edit]`) and no author identity in `<c>` +# (`pw_author_read`, `[no-author]`). Each is 64 for `request-handoff`, by +# `pw_pre_rc`. They fail until lane 4's T415 takes Q67; the first four ids +# pass on lane 4's T415 `15af6b9c`. + +#: The arguments `WRITE_VERBS` gives `request-handoff`, and its `<lane>`. +REQUEST_HANDOFF_ARGV = WRITE_VERBS["request-handoff"][0] +REQUEST_HANDOFF_LANE = REQUEST_HANDOFF_ARGV[1] + +#: {id: (the arguments, `LANES_LANE` or None for it unset, what the run adds +#: to the environment, whether `<c>` is made first, what stderr names)}. +REQUEST_HANDOFF_64 = { + # No `<lane>`: the arm's own usage code (B14 tasks:1162). + "missing-lane": (["request-handoff"], "repoA-2", {}, True, "request-handoff <lane>"), + # B14 tasks:1149: refused "before the claim, naming it". + "no-git": (REQUEST_HANDOFF_ARGV, "repoA-2", {"LANES_NO_GIT": "1"}, True, "LANES_NO_GIT"), + # `pw_lane_given`: `LANES_LANE` unset, as `lane` calls the verb; B14 + # tasks:1142, "naming the command with it". + "lane-given": (REQUEST_HANDOFF_ARGV, None, {}, True, "LANES_LANE"), + # B14 tasks:1142: "naming `lanes-edit.sh lane-checkout <lane> --create`". + "missing-checkout": (REQUEST_HANDOFF_ARGV, "repoA-2", {}, False, + f"lane-checkout {REQUEST_HANDOFF_LANE} --create"), + # Q67, `pw_hand_edit_refuse`: Y:2459's refusal names each file. + "hand-edit": (REQUEST_HANDOFF_ARGV, "repoA-2", {}, True, "lanes/LANES.md"), + # Q67, `pw_author_read`: "no author identity in `<c>`" (B15 text 5). + "no-author": (REQUEST_HANDOFF_ARGV, "repoA-2", {}, True, "author identity"), +} + + +def _hand_edit_in_c(ws: PrimaryWorkstation, checkout: Path) -> None: + """A pending hand edit of a rendered file in `<c>`: a line appended to + its `lanes/LANES.md`, not committed (B14 tasks:1151, "looked for in the + lane checkout").""" + with open(checkout / "lanes" / "LANES.md", "a", encoding="utf-8") as handle: + handle.write("a hand edit in the lane's checkout, never committed\n") + + +def _no_author_in_c(ws: PrimaryWorkstation, checkout: Path) -> None: + """No author identity in `<c>`: the run loses the estate's `GIT_AUTHOR_*` + (and any `EMAIL`), and `<c>` sets `user.useConfigOnly`, so `git -C <c> + var GIT_AUTHOR_IDENT` gives none, whatever the host's name; the global + and system configurations are already empty (`git_env`).""" + for name in ("GIT_AUTHOR_NAME", "GIT_AUTHOR_EMAIL", "EMAIL"): + ws.env.pop(name, None) + git(checkout, "config", "user.useConfigOnly", "true", env=ws.estate.env) + + +#: What a `REQUEST_HANDOFF_64` id does to `<c>` before its run, where it does +#: anything. +REQUEST_HANDOFF_C_PREP = {"hand-edit": _hand_edit_in_c, "no-author": _no_author_in_c} + + +@pytest.mark.parametrize("refusal", list(REQUEST_HANDOFF_64)) +def test_request_handoff_refuses_64_never_2_on_primary(tmp_path, refusal): + """Lane 3's batch 8, Q35 (B15 text 5 for B14 tasks:1149): on primary, + `request-handoff` refuses 64, never 2, for its missing lane + (`[missing-lane]`, no `<lane>` at all), `LANES_NO_GIT=1` (`[no-git]`), + `pw_lane_given`'s refusal (`[lane-given]`, `LANES_LANE` unset), a + missing `<c>`, the lane's own checkout (`[missing-checkout]`), and, by + lane 3's batch c, Q67 (B15 text 7 for F13d:513), a pending hand edit of + a rendered file in `<c>` (`[hand-edit]`) and no author identity in + `<c>` (`[no-author]`), since `lane` reads a 2 from it as "lane <L> is + still bound elsewhere". Each is a refusal before the claim: stderr names + its cause, the fake's log holds no call that carries a request, git is + as it was, and no clone is made. The other writer verbs' `LANES_NO_GIT=1` + refusal stays 2 (B14 tasks:1149), and is not this case's. Its first four + ids fail until lane 4's T415 takes Q35, and pass on T415 `15af6b9c`; + `[missing-lane]` passes before it, since main's arm already refuses a + missing lane 64, and holds that code against a 2. `[hand-edit]` and + `[no-author]` fail until lane 4's T415 takes Q67.""" + argv, lane, extra, with_checkout, names = REQUEST_HANDOFF_64[refusal] + ws = PrimaryWorkstation(tmp_path, + checkouts=(REQUEST_HANDOFF_LANE,) if with_checkout else ()) + fake = fake_psql_dir(ws.fakebin, answers=unreachable_answers(ws.dead)) + ws.env.update(fake) + checkout = ws.lane_checkout(REQUEST_HANDOFF_LANE) + if refusal in REQUEST_HANDOFF_C_PREP: + REQUEST_HANDOFF_C_PREP[refusal](ws, checkout) + before = ws.git_state() + proc = ws.run(argv, lane, **extra) + assert proc.returncode != 2, ( + f"request-handoff on primary refused [{refusal}] with 2, which `lane` reads as 'lane " + f"{REQUEST_HANDOFF_LANE} is still bound elsewhere' (Q35, Q67; lane 4's T415): " + f"{proc.stderr[-800:]}") + assert proc.returncode == 64, ( + f"request-handoff on primary exited {proc.returncode} for [{refusal}], not 64 (Q35, " + f"Q67; lane 4's T415): {proc.stderr[-800:]}") + assert names in proc.stderr, f"stderr does not name {names!r}: {proc.stderr!r}" + assert fake_calls(fake) == [], f"the refusal reached SQL: {fake_calls(fake)}" + assert ws.git_state() == before, "git changed: the refusal wrote" + assert checkout.is_dir() == with_checkout, ( + f"the refusal {'removed' if with_checkout else 'made'} {checkout}: a write on primary " + f"makes no clone (D12)") + + +# ------------------------------------------------------------ real engine (RE) + +class RegisterWorkstation(PrimaryWorkstation): + """`PrimaryWorkstation` over the test's database: its workspace's C is + imported and brought to `primary` with the marker `present` (test 1's + `import_to_primary`), and `lanes-edit.sh` connects as this module's + logins, through T203's `psql` shim, first on `PATH`, which hands every + call to the cluster's `psql` until a case arms it.""" + + def __init__(self, pg, tmp_path: Path, prep: dict = None): + fakebin = tmp_path / "fakebin" + fakebin.mkdir(parents=True, exist_ok=True) + (fakebin / "psql").write_text(PSQL_SHIM, encoding="utf-8") + (fakebin / "psql").chmod(0o755) + (fakebin / PSQL_SHIM_CONTROL).write_text(json.dumps({"psql": pg.psql_bin}), + encoding="utf-8") + ensure_logins(pg) + super().__init__(tmp_path, (pg.url(LOGIN_WRITER), pg.url(LOGIN_READER)), fakebin, + prep) + self.pg = pg + import_to_primary(pg, self.estate) + + def arm(self, arms: list) -> None: + (self.fakebin / PSQL_SHIM_CONTROL).write_text( + json.dumps({"psql": self.pg.psql_bin, "arms": arms}), encoding="utf-8") + + def shim_calls(self) -> list: + log = self.fakebin / PSQL_SHIM_LOG + if not log.exists(): + return [] + entries = [json.loads(x) for x in log.read_text(encoding="utf-8").splitlines() if x] + return [e for e in entries if e.get("kind") != "version"] + + def db_digest(self) -> dict: + """Each register table, the journal and the head row, copied out in + a fixed order and digested (AT-2's database oracle).""" + tables = [r["t"] for r in rows(self.pg, f"SELECT table_name AS t FROM " + f"information_schema.tables WHERE table_schema " + f"= '{SCHEMA}' AND table_type = 'BASE TABLE' " + f"ORDER BY 1")] + return {t: rows(self.pg, f"SELECT md5(coalesce(string_agg(x::text, E'\\n' ORDER BY " + f"x::text), '')) AS d FROM {t} x")[0]["d"] for t in tables} + + def foreign_locks(self) -> list: + return rows(self.pg, "SELECT pid, locktype, mode FROM pg_locks WHERE pid <> " + "pg_backend_pid() AND pid IN (SELECT pid FROM pg_stat_activity " + "WHERE application_name NOT LIKE 't210%' AND backend_type = " + "'client backend')") + + +def _commit_calls(ws: RegisterWorkstation) -> list: + return [c for c in ws.shim_calls() if "commit_write(" in (c.get("stdin") or "")] + + +@pytest.mark.parametrize("verb", list(WRITE_VERBS)) +def test_each_write_exits_69_when_the_switch_is_not_primary(pg, tmp_path, verb): + """AT-2, "Refused: the switch" (P170-171): with the switch row set to + `files`, `lanes-edit.sh <verb>` exits 69, stderr carries AT-3's line, + the register's tables and git are unchanged, and no commit call is sent + twice.""" + ws = RegisterWorkstation(pg, tmp_path, PREPS.get(verb)) + sql(pg, f"UPDATE {SCHEMA}.register_switch SET mode = 'files', marker_state = 'absent';") + before_db, before_git = ws.db_digest(), ws.git_state() + argv, lane = WRITE_VERBS[verb] + proc = ws.run(argv, lane) + assert proc.returncode == 69, f"{verb} exited {proc.returncode}: {proc.stderr[-800:]}" + assert NOT_PRIMARY_LINE in proc.stderr, proc.stderr + assert ws.db_digest() == before_db and ws.git_state() == before_git + assert len(_commit_calls(ws)) <= 1, "a refused commit call was sent again" + + +@pytest.mark.parametrize("verb", list(WRITE_VERBS)) +def test_each_write_exits_69_when_the_database_refuses_the_transaction(pg, tmp_path, verb): + """AT-2, "Refused: a GRANT": with `EXECUTE` on `commit_write` revoked from + `lanes_register_writer`, the commit call fails with 42501 and the write + exits 69; then, with that restored and `SELECT` on `register_head` + revoked, the snapshot is refused and the write exits 69. Each time the + register's tables and git are unchanged, stderr names the store and the + error without credentials, and the refused commit call is never sent + again (R02: no resend).""" + ws = RegisterWorkstation(pg, tmp_path, PREPS.get(verb)) + argv, lane = WRITE_VERBS[verb] + signature = f"{SCHEMA}.commit_write(bigint, uuid, integer, uuid, jsonb)" + for revoke, grant, code in ( + (f"REVOKE EXECUTE ON FUNCTION {signature} FROM {WRITER};", + f"GRANT EXECUTE ON FUNCTION {signature} TO {WRITER};", "42501"), + (f"REVOKE SELECT ON {SCHEMA}.register_head FROM {WRITER};", + f"GRANT SELECT ON {SCHEMA}.register_head TO {WRITER};", "42501")): + sql(pg, revoke) + before_db, before_git, calls = ws.db_digest(), ws.git_state(), len(_commit_calls(ws)) + proc = ws.run(argv, lane) + sql(pg, grant) + assert proc.returncode == 69, f"{verb} exited {proc.returncode}: {proc.stderr[-800:]}" + assert code in proc.stderr and "postgresql://" not in proc.stderr, proc.stderr + assert ws.db_digest() == before_db and ws.git_state() == before_git + assert len(_commit_calls(ws)) - calls <= 1, "a refused commit call was sent again" + + +def _unarmed_control(pg, tmp_path: Path, write: str) -> None: + """THE CONTROL (T241j; lane 3's ruling, #165 6833755920): `write`, with no + arm, on an estate of its own in a database of its own on the same cluster, + made the way the armed case makes its own, must exit 0 on primary. Where + it does not, the write fails there by itself, and the armed case could + not tell its injected row's 23514 from the write's own, so the case fails + here, saying that it is the control.""" + name = pg.cluster.new_database() + try: + control = RegisterWorkstation(Database(pg.cluster, name), tmp_path / "control", + PREPS.get(write)) + argv, lane = LATE_WRITES[write] + proc = control.run(argv, lane) + finally: + pg.cluster.drop_database(name) + assert proc.returncode == 0, ( + f"THE CONTROL FAILED, NOT THE INJECTED ROW: {write} with no edit-entry arm, on an " + f"estate and a database of its own, exited {proc.returncode} on primary, so the " + f"armed case cannot show that a 23514 is its injected row's. Its stderr ends: " + f"{proc.stderr[-800:]}") + + +@pytest.mark.parametrize("write", list(LATE_WRITES)) +def test_a_failure_in_a_late_statement_leaves_journal_lines_and_head_unchanged(pg, tmp_path, + write): + """AT-2, "Partway" (P11; D6; TP:686-690): the shim's `edit-entry` rewrites + commit call 1's entry so that its last structured row breaks a CHECK, as + `LATE_ROWS` names it for each write: the transaction fails with 23514 + after the head row, the line edits and the earlier rows changed inside + it. The shim's log shows the arm applied to commit call 1 with no error, + so an arm the shim cannot apply fails here first, not as an exit 0 when + the next attempt commits unarmed. The write exits 69; the journal, the + line store and the head row are unchanged (each table's digest); git is + unchanged; the refused call is never sent again. + + NO WRITE HERE CARRIES A HOLD ROW (T241i; lane 4's #165 6827643168, item + 5): every log line these writes add, or carry through a rename, names a + lane's own object, `lane:<name>` (a LANDING or LANDED adds none), and + `register_hold_object` gives no hold for those + (a2935aee:lanes-index:11570), so T241b's + `object_holds.-1.exempt` found an empty list. Nor could a hold row's + `exempt` break a CHECK on a write: `commit_write` stores it only for an + import (`v_kind = 'import' AND coalesce(x.exempt, false)`, + a2935aee:lanes-index:7656). It needs T203d's shim, which names a list's + element by its index, a negative one from the list's end. + + THE CONTROL COMES FIRST (T241j; lane 3's ruling, #165 6833755920): the + same write, unarmed, on an estate and a database of its own, must exit + 0 (`_unarmed_control`). Where the write fails on primary by itself, its + own 23514 would pass this case for the injected row's, so the case fails + at the control instead. `[rename-lane]` and `[migrate-state-cells]` fail + there until their own causes are fixed, by a task lanes 4 and 1 name + (HW17: the renamed log's lines go out as unreadable `log_lines` rows + stamped primary, and migrated lines carry a time with no seconds).""" + _unarmed_control(pg, tmp_path, write) + ws = RegisterWorkstation(pg, tmp_path, PREPS.get(write)) + field, value = LATE_ROWS[write] + ws.arm([{"mode": "edit-entry", "match": "commit_write", "call": 1, + "field": field, "value": value}]) + before_db, before_git = ws.db_digest(), ws.git_state() + argv, lane = LATE_WRITES[write] + proc = ws.run(argv, lane) + commits = _commit_calls(ws) + assert commits and commits[0]["arms"] == ["edit-entry"] and "error" not in commits[0], \ + f"the shim did not rewrite {field} in commit call 1: " \ + f"{commits[0].get('error') if commits else 'no commit call'}" + assert proc.returncode == 69, f"{write} exited {proc.returncode}: {proc.stderr[-800:]}" + assert "23514" in proc.stderr, proc.stderr + assert ws.db_digest() == before_db and ws.git_state() == before_git + assert len(commits) == 1, "the failed commit call was sent again" + + +@pytest.mark.parametrize("verb", list(WRITE_VERBS)) +def test_a_refused_write_leaves_no_lock(pg, tmp_path, verb): + """AT-2's lock oracle: a write refused with the database unreachable (the + shim's `fail-match` on every call) leaves no mutex, neither the scratch + tree's nor the lane checkout's, and no scratch tree; once the fault is + removed, the same write made at once exits 0; and `pg_locks` shows no + lock held by another client backend.""" + ws = RegisterWorkstation(pg, tmp_path, PREPS.get(verb)) + ws.arm([{"mode": "fail-call", "from": 1}]) + argv, lane = WRITE_VERBS[verb] + proc = ws.run(argv, lane) + assert proc.returncode == 69, f"{verb} exited {proc.returncode}: {proc.stderr[-800:]}" + assert _lock_files(ws) == [], f"a mutex was left: {_lock_files(ws)}" + ws.arm([]) + again = ws.run(argv, lane) + assert again.returncode == 0, f"the write after the fault exited {again.returncode}: " \ + f"{again.stderr[-800:]}" + assert ws.foreign_locks() == [], ws.foreign_locks() + + +def test_a_pending_hand_edit_names_the_file_and_a_recovery_that_works(pg, tmp_path): + """P361-365 (TP:764-769 and Y:2505-2507, "in the writing lane's + checkout"; B14 tasks:1151, "It is looked for in the lane checkout"): with + a hand edit of `lanes/LANES.md` pending in the writing lane's own + checkout `<c>` (`<W>-lanes/<lane>`, which `RegisterWorkstation` makes), + a write refuses before its snapshot (the shim's log is empty), naming the + file and one recovery command, the one backticked `git` command in its + stderr; running that command in `<c>` leaves `<c>`'s `status --porcelain` + empty, and the next write exits 0. W's own checkout holds no edit: lane + 4's answer (#165 6808439918) puts the edit in `<c>`, and keeps this + oracle. It fails until lane 4's T415 round that prints that one command, + `git -C <c> restore --source=HEAD --staged --worktree -- <paths>`, in + backticks, with its read line holding none; T415 `15af6b9c` prints both + as plain notes.""" + ws = RegisterWorkstation(pg, tmp_path) + argv, lane = WRITE_VERBS["set-row-state"] + checkout = ws.lane_checkout(lane) + target = checkout / "lanes" / "LANES.md" + target.write_bytes(target.read_bytes() + b"a pending hand edit\n") + proc = ws.run(argv, lane) + assert proc.returncode != 0 and ws.shim_calls() == [], (proc.returncode, ws.shim_calls()) + assert "lanes/LANES.md" in proc.stderr, proc.stderr + commands = re.findall(r"`(git [^`]+)`", proc.stderr) + assert len(commands) == 1, f"the refusal names {len(commands)} recovery commands: " \ + f"{proc.stderr!r}" + subprocess.run(commands[0], shell=True, cwd=str(checkout), env=ws.estate.env, + check=True, capture_output=True) + assert git(checkout, "status", "--porcelain", env=ws.estate.env) == "" + assert ws.run(argv, lane).returncode == 0 + + +def test_a_write_goes_on_with_the_service_down(pg, tmp_path): + """Round 1's 4A: with no service started (no socket under the service's + directory), a write goes on through its own transaction (the journal + gains one entry) and never falls back to the files (the checkout's + `lanes/` unchanged).""" + ws = RegisterWorkstation(pg, tmp_path) + before = rows(pg, f"SELECT count(*) AS n FROM {SCHEMA}.journal")[0]["n"] + lanes_before = ws.git_state()[1] + argv, lane = WRITE_VERBS["log"] + proc = ws.run(argv, lane) + assert proc.returncode == 0, f"log exited {proc.returncode}: {proc.stderr[-800:]}" + assert rows(pg, f"SELECT count(*) AS n FROM {SCHEMA}.journal")[0]["n"] == before + 1 + assert ws.git_state()[1] == lanes_before, "the write fell back to the files"