@vibelord/lanes 1.7.7 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/README.md +13 -9
  2. package/package.json +1 -1
  3. package/payload/lanes/VERSION +1 -1
  4. package/payload/lanes/bin/lanes +26 -4
  5. package/payload/lanes/bin/lanes-site-serve +4 -8
  6. package/payload/lanes/bin-rs/BINARIES.json +17 -2
  7. package/payload/lanes/bin-rs/THIRD-PARTY-NOTICES +18953 -0
  8. package/payload/lanes/bin-rs/x86_64-unknown-linux-musl/lanes-hook +0 -0
  9. package/payload/lanes/bin-rs/x86_64-unknown-linux-musl/lanes-terminal +0 -0
  10. package/payload/lanes/client/lanes-launch +4 -2
  11. package/payload/lanes/container/lane-mcp +1 -1
  12. package/payload/lanes/container/lane_core.py +4 -3
  13. package/payload/lanes/docs/ARCHITECTURE.md +26 -4
  14. package/payload/lanes/docs/RUNBOOK.md +121 -52
  15. package/payload/lanes/docs/USERGUIDE.md +28 -0
  16. package/payload/lanes/install/lanes-host.service.in +25 -0
  17. package/payload/lanes/install/services.py +243 -0
  18. package/payload/lanes/libexec/agent_state.py +3 -1
  19. package/payload/lanes/libexec/attach.py +139 -21
  20. package/payload/lanes/libexec/cutover.py +24 -4
  21. package/payload/lanes/libexec/doctor_lanes2.py +3 -3
  22. package/payload/lanes/libexec/native.sh +2 -2
  23. package/payload/lanes/libexec/native_bin.py +595 -109
  24. package/payload/lanes/libexec/shadow.py +51 -3
  25. package/payload/lanes/libexec/sidebar_status.py +190 -80
  26. package/payload/lanes/libexec/update.py +12 -3
  27. package/payload/lanes/site/protocol.py +24 -9
  28. package/payload/lanes/site/relay.py +292 -0
  29. package/payload/lanes/site/server.py +31 -3
  30. package/payload/lanes/web/README.md +6 -6
  31. package/payload/lanes/web/directory.js +10 -8
  32. package/payload/lanes/web/generated/README.md +85 -21
  33. package/payload/lanes/web/generated/lanes2_protocol.d.mts +4190 -188
  34. package/payload/lanes/web/generated/lanes2_protocol.mjs +14218 -351
  35. package/payload/lanes/web/inbox.js +8 -6
  36. package/payload/manifest.json +22 -5
@@ -1,15 +1,17 @@
1
1
  #!/usr/bin/env python3
2
- """Lanes 2.0 native (Rust) binaries and flags on a host (lanes2 Round 1 H2; AR 7.3, 9.3, D9; RT 3.1, 3.2). Python 3 stdlib.
2
+ """Lanes 2.0 native (Rust) binaries and flags on a host (lanes2 Round 1 H2; AR 7.3, 9.3, 9.4, D9; RT 3.1, 3.2; final
3
+ contract decisions FC-R1, FC-R7, FC-G8, FC-G9, FC-E12, FC-X11). Python 3 stdlib.
3
4
 
4
5
  lanes rs install --from PATH --sha256 HEX
5
6
  place a locally built native binary (the development and offline route, mirroring `lanes studio-host
6
7
  install --from`). PATH is a regular executable file named after a native binary (BINARIES: the `[[bin]]`
7
- targets the lanes crates declare, lanes-terminal and lanes-hook). Refused before anything is written unless
8
- its sha256 is HEX (`--sha256` is required: nothing is placed on a digest nobody stated). Under the lock
9
- ~/.local/share/lanes/bin-rs/.lock it is copied to bin-rs/<name>-<sha12> (the copy hashed again before its
10
- rename), INSTALLED.json records that file, and only then is the link bin-rs/<name> pointed at it in one
11
- rename: a crash leaves the old link with its own record, never a link without one. Changes no flag and
12
- restarts nothing. Exit 0 installed, 2 usage, 3 refused (binary_mismatch, installed_malformed, busy)
8
+ targets the lanes crates declare, lanes-terminal and lanes-hook, or HOST_BINARY throttle-rc, the binary the
9
+ HOST component runs, FC-R1). Refused before anything is written unless its sha256 is HEX (`--sha256` is
10
+ required: nothing is placed on a digest nobody stated). Under the lock ~/.local/share/lanes/bin-rs/.lock it is
11
+ copied to bin-rs/<name>-<sha12> (the copy hashed again before its rename), INSTALLED.json records that file,
12
+ and only then is the link bin-rs/<name> pointed at it in one rename: a crash leaves the old link with its own
13
+ record, never a link without one. Changes no flag and restarts nothing. Exit 0 installed, 2 usage, 3 refused
14
+ (binary_mismatch, installed_malformed, busy)
13
15
  lanes rs uninstall NAME
14
16
  remove the link bin-rs/NAME under the same lock (the placed file and its record stay), so the release tree's
15
17
  own binary runs again, then remove every flags/native.* file whose binary no longer verifies (prune_flags).
@@ -19,30 +21,56 @@
19
21
  files beside it — every listed binary present, executable, with its size and sha256, nothing there the list
20
22
  does not name — and, without --tree, every binary `lanes rs install` linked; a `WARN` line names an install
21
23
  that runs instead of a shipped binary with other bytes. Exit 0 all match (or there is none), 3 a mismatch
24
+ lanes rs set COMPONENT off|shadow|on
25
+ the request (FC-G8): write site.conf's `LANES_RS_<COMPONENT>=<mode>` line atomically under the site.conf lock
26
+ (~/.config/lanes/.site.conf.lock), then print the `lanes rs apply` it needs. Changes no flag file. Exit 0, 2
27
+ usage, 3 refused (unknown_component; shadow_unsupported for a component without an AR 7.4 shadow step;
28
+ binary_absent or digest_mismatch for HOST shadow|on while no throttle-rc verifies, FC-R1; busy)
22
29
  lanes rs status
23
- each component's site.conf mode, its flag file and what runs (the verified native binary, or python). Exit 0
30
+ per component: the request and its source (`default`, the release default of this tree's VERSION, or
31
+ `site.conf`), the flag file, every cutover record of a host duty, and what runs. Exit 0
24
32
  lanes rs apply
25
- the one writer of the flag files: site.conf's LANES_RS_<COMPONENT>=off|shadow|on becomes the existence-only
26
- files $LANES_STATE/flags/native.<component> (on) and native.<component>.shadow (shadow), each only for a mode
27
- admit() accepts; every other native.* file is removed. Exit 0 every flag as asked, 3 a flag refused (kept off)
28
- or a LANES_RS_ line not understood, 2 usage
33
+ the one writer of the flag files: each component's request (site.conf, else the release default) becomes the
34
+ existence-only files $LANES_STATE/flags/native.<component> (on) and native.<component>.shadow (shadow), each
35
+ only for a mode admit() accepts; every other native.* file is removed. The feature switches (FC-E12) become
36
+ $LANES_STATE/flags/feature.<name> only when on. A host duty whose request (site.conf or the release default)
37
+ is `on`, with HOST `on` and a domain whose cutover record is not active for lanes-rs, is driven through
38
+ `throttle-rc lanes cutover <domain> --to lanes-rs` first (the H3 DomainFence; FC-R7, FC-G8: a host duty turns
39
+ on only through its fence, FC-G9); a duty whose request is `off` while a domain's record is active for lanes-rs
40
+ is driven back to that domain's legacy owner (the reverse fence, FC-G8's rollback). Then the units follow the
41
+ flags in both directions (install/services.py reconcile_units, AR 9.4, FC-R1): lanes-host.service is rendered
42
+ and enabled while HOST is shadow or on, disabled and removed otherwise; a Python twin whose duty flag
43
+ `lanes rs apply` wrote — the record active for lanes-rs (FC-R7) — is disabled, and a twin it disabled is
44
+ enabled and started again once that flag is gone. Exit 0 every flag as asked, 3 a requested flag refused (kept
45
+ off), a LANES_RS_ line not understood or a systemctl step that failed, 2 usage
29
46
  python3 libexec/native_bin.py verify-tree TREE [--state DIR] [--prune-flags]
30
47
  TREE's own binaries only (no share), for install/host-install.sh right before its commit and update.py's
31
48
  post-commit step `verify bin-rs`; --prune-flags then removes every flags/native.* file whose binary does not
32
- verify against TREE. Exit 0, 3 a mismatch (nothing pruned) or a flag file that could not be removed, 2 usage
33
-
34
- Components are AR 7.3's, and ROUTES (RT 12.4's first-party docs and enrolment routes, lane R2-ROUTES). Each runs one
35
- payload binary (COMPONENT_BINARY), or none yet: AGENTD and MCP have no crate that declares a binary (binary_absent),
36
- and STATUSD, VISIBILITY, NOTIFY, ECONOMY, SYNC, SITE, STORE and ROUTES are duties of the host coordinator, a Rust
37
- library the throttle-rc Studio Host composes (RT 3.1): RT 3.2 allows one host owner per state root and no lanesd beside
38
- an active Studio host, so no payload binary or unit serves them and their flags are refused (host_composed) until the
39
- cutover fence (lanes2 H3) activates them in that composition. A binary is used only
40
- when it verifies (resolve): first the `lanes rs install` link ~/.local/share/lanes/bin-rs/<name>, else the running
41
- tree's bin-rs/<target>/<name> against BINARIES.json; a candidate that exists but does not verify is refused, never
42
- passed over for the next. The shell readers' half (libexec/native.sh, for the view and sidebar hooks lane C7 owns)
43
- stops at the same first candidate. Every way `current` moves keeps the flags true to the tree it moves to:
44
- host-install.sh refuses a staged tree whose binaries do not verify and prunes the flags against it before its flip;
45
- update.py's rollback prunes them against the tree it rolls back to before its flip."""
49
+ verify against TREE (or, for HOST and its duties, whose throttle-rc does not verify). Exit 0, 3 a mismatch
50
+ (nothing pruned) or a flag file that could not be removed, 2 usage
51
+
52
+ Components are FC-X11's: AR 7.3's, CLIENT (RT 11.5's first-party CLI route, FC-G8), ROUTES (RT 12.4's first-party
53
+ routes), HOST (the process component, `throttle-rc lanes host`, FC-R1) and the duties ATTENTION and LIFECYCLE (FC-R7).
54
+ A payload component runs one payload binary (COMPONENT_BINARY), or none yet: AGENTD and MCP have no crate that declares
55
+ a binary (binary_absent). HOST runs throttle-rc, resolved from the `lanes rs install` link bin-rs/throttle-rc first,
56
+ then the `lanes studio-host install` selection ($LANES_SHARE/bin/throttle-rc with its throttle-rc.pin.json): its
57
+ shadow step is `--mode shadow`, admitted only where site.conf LANES_HOST_ROLE=owner; its on step is `--mode owner`
58
+ or `--mode aggregator` by that role; with no role it is refused owner_undeclared. The host duties (HOST_DUTIES) run
59
+ inside that composition (RT 3.2: one host owner per state root; no payload binary serves them, and no standalone
60
+ lanesd is built): a duty is refused host_absent while HOST is off; `shadow` is admitted only while HOST is shadow or
61
+ on and no cutover record of its domains exists (a shadow never takes one, FC-D7); `on` only while HOST is on and every
62
+ state domain of the duty (DUTY_DOMAINS, FC-R2's table) has an active $LANES_STATE/cutover/<domain>.json with owner
63
+ lanes-rs, otherwise cutover_pending. For a host duty the flag is a request and the cutover record is ownership: a
64
+ Python twin stands down on the record, never on a flag file alone. A missing request is the release default of the
65
+ tree's VERSION (RELEASE_DEFAULTS, FC-G9): every entry below 2.0.0 is all off; a default never turns on a component
66
+ apply refuses on this host, and a refused default is reported, not an exit 3. GATE_FLAG_SETS holds FC-X11's flag set
67
+ per integration gate as data. A binary is used only when it verifies (resolve): first the `lanes rs install` link
68
+ ~/.local/share/lanes/bin-rs/<name>, else the running tree's bin-rs/<target>/<name> against BINARIES.json; a candidate
69
+ that exists but does not verify is refused, never passed over for the next. The shell readers' half
70
+ (libexec/native.sh, for the view and sidebar hooks lane C7 owns) stops at the same first candidate. Every way
71
+ `current` moves keeps the flags true to the tree it moves to: host-install.sh refuses a staged tree whose binaries do
72
+ not verify and prunes the flags against it before its flip; update.py's rollback prunes them against the tree it rolls
73
+ back to before its flip."""
46
74
  import contextlib
47
75
  import fcntl
48
76
  import hashlib
@@ -53,6 +81,7 @@ import platform
53
81
  import re
54
82
  import secrets
55
83
  import shutil
84
+ import subprocess
56
85
  import sys
57
86
  import tempfile
58
87
  import time
@@ -60,29 +89,93 @@ import time
60
89
  import lanes_lib as L
61
90
 
62
91
  TARGETS = {'x86_64': 'x86_64-unknown-linux-musl'} # `uname -m` -> the target the payload ships binaries for
63
- # AR 7.3's strangler components, in its order, then `routes` (RT 12.4: the first-party docs and enrolment routes,
64
- # lanes2 Round 2 R2-ROUTES, crates/lanes-runtime/src/http/mode.rs reads its flag files): the `LANES_RS_<COMPONENT>` keys
65
- # (upper case) and the flag files (lower case). Every one ships `off`.
92
+ # FC-X11's components, in its order: AR 7.3's strangler components, CLIENT (RT 11.5, FC-G8), ROUTES (RT 12.4's
93
+ # first-party docs and enrolment routes; crates/lanes-runtime/src/http/mode.rs reads its flag files), HOST (the
94
+ # process component that runs `throttle-rc lanes host`, FC-R1) and the duties ATTENTION and LIFECYCLE (FC-R7): the
95
+ # `LANES_RS_<COMPONENT>` keys (upper case) and the flag files (lower case).
66
96
  COMPONENTS = ('signal', 'mcp', 'agentd', 'statusd', 'visibility', 'notify', 'economy', 'sync', 'site', 'store',
67
- 'relay', 'sidebar', 'key', 'routes')
68
- # The duties of the host coordinator (RT 3.1: a Rust library composed by throttle-rc; RT 3.2: one host owner, no lanesd
69
- # beside the Studio host): no payload binary runs them.
70
- HOST_DUTIES = frozenset({'statusd', 'visibility', 'notify', 'economy', 'sync', 'site', 'store', 'routes'})
97
+ 'relay', 'sidebar', 'key', 'client', 'routes', 'host', 'attention', 'lifecycle')
98
+ HOST = 'host'
99
+ # The host duties (FC-X11): run inside the throttle-rc composition that owns the state root (RT 3.2), never by a
100
+ # payload binary.
101
+ HOST_DUTIES = frozenset({'statusd', 'visibility', 'notify', 'economy', 'sync', 'site', 'store', 'routes', 'attention',
102
+ 'lifecycle'})
103
+ # FC-X11's duty-to-domain table (FC-R2's 2.0 domains): a duty is `on` only while every one of its domains has an
104
+ # active cutover record with owner lanes-rs. The records are keyed by domain ($LANES_STATE/cutover/<domain>.json).
105
+ DUTY_DOMAINS = {'statusd': ('observation', 'delivery'), 'visibility': ('visibility',), 'notify': ('notify',),
106
+ 'economy': ('economy',), 'sync': ('sync',), 'site': ('site',), 'routes': ('routes',),
107
+ 'attention': ('attention',), 'lifecycle': ('lifecycle',),
108
+ 'store': ('store', 'schedule', 'project', 'connectors')}
109
+ CANDIDATE = 'lanes-rs' # the cutover record's owner word for the lanes host
71
110
  # The payload binary a component runs: a `[[bin]]` target of the lanes crates. The Day-0 freeze (PR #626) declares
72
111
  # lanes-terminal (RT 4: the CLI, TUI and attachment relay — the relay as its `relay` mode with connection.py's
73
- # arguments, the sidebar as its `sidebar` mode, the hot keys lane C6's) and lanes-hook (RT 3.1: the hook emitter behind
74
- # lane-signal). A component absent here has no binary yet. test_flags pins every name against the crates' Cargo.toml
75
- # files; libexec/native.sh repeats them.
112
+ # arguments, the sidebar as its `sidebar` mode, the hot keys lane C6's, the first-party CLI route CLIENT, FC-G8) and
113
+ # lanes-hook (RT 3.1: the hook emitter behind lane-signal). A component absent here has no payload binary: HOST runs
114
+ # HOST_BINARY, a duty runs inside it, AGENTD and MCP have none yet. test_flags pins every name against the crates'
115
+ # Cargo.toml files; libexec/native.sh repeats them.
76
116
  COMPONENT_BINARY = {'signal': 'lanes-hook', 'relay': 'lanes-terminal', 'sidebar': 'lanes-terminal',
77
- 'key': 'lanes-terminal'}
78
- # AR 7.4: the components whose strangler row has a shadow step. `shadow` for a component with a binary but no shadow
79
- # step is refused (shadow_unsupported): a flag file that says shadow while nothing shadows is state no reader honours.
80
- SHADOW_STEP = frozenset({'mcp', 'agentd', 'statusd', 'visibility', 'notify', 'economy', 'sync', 'site', 'routes'})
117
+ 'key': 'lanes-terminal', 'client': 'lanes-terminal'}
118
+ HOST_BINARY = 'throttle-rc' # FC-R1: the binary HOST runs (`throttle-rc lanes host`)
119
+ # AR 7.4 and FC-X11: the components whose strangler row has a shadow step. `shadow` for any other component is refused
120
+ # (shadow_unsupported): a flag file that says shadow while nothing shadows is state no reader honours. ATTENTION and
121
+ # LIFECYCLE go from off straight to on, like SIGNAL, STORE, RELAY, SIDEBAR, KEY and CLIENT.
122
+ SHADOW_STEP = frozenset({'mcp', 'agentd', 'statusd', 'visibility', 'notify', 'economy', 'sync', 'site', 'routes',
123
+ 'host'})
81
124
  BINARIES = frozenset(COMPONENT_BINARY.values())
125
+ INSTALLABLE = BINARIES | {HOST_BINARY} # the names `lanes rs install` places
82
126
  MODES = ('off', 'shadow', 'on')
127
+ ROLES = ('owner', 'aggregator') # site.conf LANES_HOST_ROLE values HOST runs under
83
128
  KEY = re.compile(r'^LANES_RS_([A-Z][A-Z_]*)$')
84
129
  SETTINGS = frozenset({'LANES_RS_MCP_EXCLUDE'}) # AR 7.3: a LANES_RS_ key that is a setting, not a component
85
130
  FLAG_PREFIX = 'native.' # $LANES_STATE/flags/native.<component>[.shadow]
131
+ FEATURE_PREFIX = 'feature.' # $LANES_STATE/flags/feature.<name> (FC-E12)
132
+ # FC-E12: the seven Lanes 2.0 feature switches, off when absent. One grammar (switch()); the file name is the key
133
+ # lowercased, without LANES_ and with `_` as `-`. LANES_SITE_HOOK, LANES_TOPOLOGY, LANES_HOST_ROLE and
134
+ # LANES_STATUSD_SLICES are declarations, not switches.
135
+ FEATURE_SWITCHES = ('LANES_OPERATIONS', 'LANES_BUILD_WRITES', 'LANES_PLANNER', 'LANES_TOOL_REPAIR', 'LANES_PROJECTS',
136
+ 'LANES_CONNECTOR_GITHUB', 'LANES_CONNECTOR_LINEAR')
137
+ SWITCH_OFF = frozenset({'', 'off', '0', 'false', 'no'})
138
+ SWITCH_ON = frozenset({'on', '1', 'true', 'yes'})
139
+ # FC-G9's release defaults, keyed by lanes/VERSION: (the first VERSION an entry applies to, its on-set). Every entry
140
+ # below 2.0.0 is all off; 2.0.0 is N+1 for the whole set (FC-G9, with FC-X11's HOST, ATTENTION and LIFECYCLE). SITE
141
+ # is never on by default (an explicit request on an aggregator after the O-3 installed witness). The HOST default is
142
+ # `on` only where LANES_HOST_ROLE is owner or aggregator (admit() refuses it elsewhere, and a refused default stays
143
+ # off). lanes/VERSION may become 2.0.0 only where tests/unit/test_release_gate.py passes.
144
+ ON_SET_2_0_0 = frozenset({'signal', 'mcp', 'agentd', 'statusd', 'visibility', 'notify', 'economy', 'sync', 'store',
145
+ 'relay', 'sidebar', 'key', 'client', 'routes', 'host', 'attention', 'lifecycle'})
146
+ RELEASE_DEFAULTS = (((0, 0, 0), frozenset()),
147
+ ((2, 0, 0), ON_SET_2_0_0))
148
+ # FC-X11's flag set per integration gate, as data: (gate, component, mode, scope), in the order the gates run them.
149
+ # Every component of the 2.0.0 on-set that has a shadow step is shadowed by a row before its `on` row (FC-G9 condition
150
+ # 2); the composed rig and test_flags.ReleaseDefaults read this table. SITE has no row: it is never in the on-set.
151
+ GATE_FLAG_SETS = (
152
+ ('I1', 'host', 'shadow', 'one guest owner install; no duty in shadow (FC-D7, FC-R6)'),
153
+ ('after-I1', 'statusd', 'shadow', 'that guest, for the I2 24-hour shadow'),
154
+ ('after-I1', 'visibility', 'shadow', 'that guest, for the I2 24-hour shadow'),
155
+ ('after-I1', 'notify', 'shadow', 'that guest, for the I2 24-hour shadow'),
156
+ ('after-I1', 'economy', 'shadow', 'that guest, for the I2 24-hour shadow'),
157
+ ('after-I1', 'sync', 'shadow', 'that guest, for the I2 24-hour shadow'),
158
+ ('after-I1', 'routes', 'shadow', 'that guest, for the I2 24-hour shadow'),
159
+ ('I2', 'host', 'on', 'that guest (owner mode)'),
160
+ ('I2', 'statusd', 'on', 'that guest, through its fence'),
161
+ ('I2', 'visibility', 'on', 'that guest, through its fence'),
162
+ ('I2', 'notify', 'on', 'that guest, through its fence'),
163
+ ('I2', 'economy', 'on', 'that guest, through its fence'),
164
+ ('I2', 'sync', 'on', 'that guest, through its fence'),
165
+ ('I2', 'routes', 'on', 'that guest, through its fence'),
166
+ ('I2', 'store', 'on', 'that guest, through its fence'),
167
+ ('I3', 'client', 'on', 'one cohort'),
168
+ ('I3', 'sidebar', 'on', 'one cohort'),
169
+ ('I3', 'key', 'on', 'one cohort'),
170
+ ('I3', 'relay', 'on', 'one cohort'),
171
+ ('I3', 'signal', 'on', 'one cohort'),
172
+ ('I3', 'lifecycle', 'on', 'one cohort'),
173
+ ('I4', 'attention', 'on', 'the I4 cohort'),
174
+ ('I4', 'mcp', 'shadow', 'the I4 cohort, for the AR 7.6(b) 24-hour live-input replay'),
175
+ ('I4', 'agentd', 'shadow', 'the I4 cohort, for the AR 7.6(b) 24-hour live-input replay'),
176
+ ('I4', 'mcp', 'on', "the I4 cohort, per O-13's per-harness witness"),
177
+ ('I4', 'agentd', 'on', "the I4 cohort, per O-13's per-harness witness"),
178
+ )
86
179
  NAME = re.compile(r'^lanes-[a-z0-9][a-z0-9-]{0,39}$') # build-payload.mjs RS_NAME
87
180
  HEX64 = re.compile(r'^[0-9a-f]{64}$')
88
181
  COMMIT = re.compile(r'^[0-9a-f]{40}$')
@@ -93,9 +186,17 @@ INSTALLED = 'INSTALLED.json' # under $LANES_SHARE/b
93
186
  INSTALLED_SCHEMA = 'lanes.bin-rs-installed/1'
94
187
  LOCK = '.lock' # under $LANES_SHARE/bin-rs: install and uninstall hold it
95
188
  LOCK_WAIT = 10 # seconds an install or uninstall waits for the lock
189
+ SITE_LOCK = '.site.conf.lock' # beside site.conf: `lanes rs set` holds it while it writes
190
+ CUTOVER_TIMEOUT = 60 # seconds one `throttle-rc lanes cutover` may take in apply
191
+ # FC-R2's legacy owners of the domains whose owner is not lanes-py, until cutover.py's own table (host-root's
192
+ # LEGACY_OWNERS and legacy_owner, held to the Rust golden by test_cutover.LegacyOwnerTableParity) is on this tree:
193
+ # legacy_owner() asks cutover.py first and falls back here only while it has no table (deleted with that swap).
194
+ FALLBACK_LEGACY_OWNERS = {'attention': 'studio-host', 'store': 'none', 'schedule': 'none', 'project': 'none',
195
+ 'connectors': 'none'}
196
+ NO_LEGACY_OWNER = 'none' # a domain nobody owns before its first record
96
197
  NOT_EXECUTABLE = 'not executable'
97
198
  USAGE = ('usage: lanes rs install --from PATH --sha256 HEX | lanes rs uninstall NAME | lanes rs verify [--tree] | '
98
- 'lanes rs status | lanes rs apply')
199
+ 'lanes rs set COMPONENT off|shadow|on | lanes rs status | lanes rs apply')
99
200
  TREE_USAGE = 'usage: native_bin.py verify-tree TREE [--state DIR] [--prune-flags]'
100
201
 
101
202
 
@@ -125,23 +226,95 @@ def parse_flag_file(name):
125
226
  return (component, mode) if component in COMPONENTS else None
126
227
 
127
228
 
128
- def native_flags(conf):
129
- """site.conf facts ({key: value}, L.site_conf) -> ({component: mode} for every component, [problem]). A missing key
130
- is `off`; a value outside MODES is `off` with a problem; a LANES_RS_<X> naming no component is a problem and changes
131
- nothing (the key never becomes a flag file)."""
132
- modes, problems = {component: 'off' for component in COMPONENTS}, []
229
+ def parse_version(text):
230
+ """(major, minor, patch) of a lanes/VERSION text such as `1.7.5` or `2.0.0-rc.1` (a pre-release counts as its
231
+ release), or None when it is not one."""
232
+ found = re.match(r'^\s*(\d+)\.(\d+)\.(\d+)(?:[-+][0-9A-Za-z.+-]*)?\s*$', text or '')
233
+ return tuple(int(part) for part in found.groups()) if found else None
234
+
235
+
236
+ def tree_version(tree):
237
+ """The (major, minor, patch) of `tree`/VERSION, or (0, 0, 0) when it has none that parses (every default off)."""
238
+ try:
239
+ return parse_version((Path(tree) / 'VERSION').read_text()) or (0, 0, 0)
240
+ except OSError:
241
+ return (0, 0, 0)
242
+
243
+
244
+ def release_defaults(version):
245
+ """FC-G9: {component: 'on' | 'off'} for a lanes/VERSION (major, minor, patch): the newest RELEASE_DEFAULTS entry
246
+ at or below it."""
247
+ on_set = frozenset()
248
+ for first, entry in RELEASE_DEFAULTS:
249
+ if tuple(version) >= first:
250
+ on_set = entry
251
+ return {component: 'on' if component in on_set else 'off' for component in COMPONENTS}
252
+
253
+
254
+ def native_requests(conf, version=(0, 0, 0)):
255
+ """site.conf facts ({key: value}, L.site_conf) -> ({component: (mode, source)} for every component, [problem]).
256
+ A missing key is the release default of `version` (source `default`); a value outside MODES is `off` with a
257
+ problem (source `site.conf`); a LANES_RS_<X> naming no component is a problem and changes nothing (the key never
258
+ becomes a flag file)."""
259
+ defaults = release_defaults(version)
260
+ requests = {component: (defaults[component], 'default') for component in COMPONENTS}
261
+ problems = []
133
262
  for key in sorted(conf):
134
263
  found = KEY.match(key)
135
264
  if not found or key in SETTINGS:
136
265
  continue
137
266
  component, value = found.group(1).lower(), conf[key]
138
- if component not in modes:
267
+ if component not in requests:
139
268
  problems.append(f'{key}: unknown component (known: {" ".join(c.upper() for c in COMPONENTS)}); ignored')
140
269
  elif value not in MODES:
141
270
  problems.append(f'{key}={value}: not one of {"|".join(MODES)}; read as off')
271
+ requests[component] = ('off', 'site.conf')
142
272
  else:
143
- modes[component] = value
144
- return modes, problems
273
+ requests[component] = (value, 'site.conf')
274
+ return requests, problems
275
+
276
+
277
+ def native_flags(conf, version=(0, 0, 0)):
278
+ """native_requests without the sources -> ({component: mode}, [problem])."""
279
+ requests, problems = native_requests(conf, version)
280
+ return {component: mode for component, (mode, _source) in requests.items()}, problems
281
+
282
+
283
+ def switch(name, value):
284
+ """FC-E12's one grammar for a feature switch -> ('on' | 'off', problem or None): absent (None), empty, off, 0,
285
+ false, no are off; on, 1, true, yes are on (trimmed, case-insensitive); any other value is off with a
286
+ flag_value_invalid problem."""
287
+ word = (value or '').strip().lower()
288
+ if word in SWITCH_ON:
289
+ return 'on', None
290
+ if word in SWITCH_OFF:
291
+ return 'off', None
292
+ return 'off', f'flag_value_invalid: {name}={value}: not one of on|1|true|yes or off|0|false|no; read as off'
293
+
294
+
295
+ def feature_file(name):
296
+ """The flag file (under $LANES_STATE/flags) of the feature switch `name`: `LANES_CONNECTOR_GITHUB` ->
297
+ `feature.connector-github`."""
298
+ return FEATURE_PREFIX + name[len('LANES_'):].lower().replace('_', '-')
299
+
300
+
301
+ def feature_switches(conf):
302
+ """({switch name: 'on' | 'off'} for every FC-E12 switch, [problem]) from site.conf facts."""
303
+ states, problems = {}, []
304
+ for name in FEATURE_SWITCHES:
305
+ states[name], problem = switch(name, conf.get(name))
306
+ if problem:
307
+ problems.append(problem)
308
+ return states, problems
309
+
310
+
311
+ def doctor_problems(conf):
312
+ """`lanes doctor`'s lines for site.conf's Lanes 2.0 requests and switches -> [problem]: every feature switch value
313
+ refused flag_value_invalid (FC-E12: "doctor lists it") and every LANES_RS_ line `lanes rs apply` does not
314
+ understand (an unknown component, a mode outside off|shadow|on). `lanes rs status` and `apply` print the same."""
315
+ _requests, problems = native_requests(conf)
316
+ _switches, switch_problems = feature_switches(conf)
317
+ return problems + switch_problems
145
318
 
146
319
 
147
320
  def sha256_file(path):
@@ -304,7 +477,7 @@ def check_installed(share, name, files=None):
304
477
  def installed_names(share):
305
478
  """The native binaries `lanes rs install` linked under `share`: a bin-rs/<name> entry exists, whatever it is."""
306
479
  directory = Path(share) / 'bin-rs'
307
- return sorted(name for name in BINARIES if os.path.lexists(directory / name))
480
+ return sorted(name for name in INSTALLABLE if os.path.lexists(directory / name))
308
481
 
309
482
 
310
483
  def verify_installed(share):
@@ -365,16 +538,166 @@ def resolve(component, tree, share, machine=None):
365
538
  return (shipped, None) if problem is None else (None, f'{refusal_code(problem)}: {shipped}: {problem}')
366
539
 
367
540
 
368
- def admit(component, mode, tree, share, machine=None):
369
- """(path, None) when `component` may run natively in `mode` (on or shadow) from `tree`, else (None, reason): a host
370
- duty never (host_composed), a component without a binary never (binary_absent), `shadow` only with a shadow step
371
- (shadow_unsupported), and otherwise exactly when resolve() verifies its binary."""
372
- if component in HOST_DUTIES:
373
- return None, (f'host_composed: {component.upper()} is a duty of the host coordinator, which the throttle-rc '
374
- 'Studio Host composes (RT 3.1); no payload binary serves it and no second host owner starts '
375
- 'beside the Studio host (RT 3.2); its activation is the cutover fence (lanes2 H3)')
376
- if component in COMPONENT_BINARY and mode == 'shadow' and component not in SHADOW_STEP:
541
+ class Facts:
542
+ """What admission reads besides a payload binary: the state root (flags/, cutover/), the account home (site.conf),
543
+ site.conf's facts (LANES_HOST_ROLE), the share and the HOST mode in force — the effective mode apply is about to
544
+ write, or (None) the one the flag files hold and admit. The throttle-rc resolution is hashed once per Facts."""
545
+
546
+ def __init__(self, state, share, home=None, conf=None, host_mode=None):
547
+ self.state, self.share, self.home = Path(state), Path(share), home
548
+ self.conf = L.site_conf(home) if conf is None else conf
549
+ self.role = self.conf.get('LANES_HOST_ROLE')
550
+ self.host_mode = host_mode
551
+ self._host_binary = None
552
+
553
+ def host_binary(self):
554
+ if self._host_binary is None:
555
+ self._host_binary = resolve_host(self.share, self.state, self.home)
556
+ return self._host_binary
557
+
558
+ def host(self):
559
+ """The HOST mode in force: the given one, else the flag file present whose mode admit() still accepts."""
560
+ if self.host_mode is None:
561
+ present = set(flag_files(self.state))
562
+ self.host_mode = 'off'
563
+ for mode in ('on', 'shadow'):
564
+ if flag_file(HOST, mode) in present and admit_host(mode, self)[0] is not None:
565
+ self.host_mode = mode
566
+ break
567
+ return self.host_mode
568
+
569
+
570
+ def resolve_host(share, state=None, home=None):
571
+ """(path, None) of the verified throttle-rc HOST runs, or (None, reason): the `lanes rs install` link
572
+ bin-rs/throttle-rc first (checked as every install is), else the `lanes studio-host install` selection
573
+ ($LANES_SHARE/bin/throttle-rc against its throttle-rc.pin.json). A candidate that exists but does not verify is
574
+ refused, never passed over for the next (FC-R1)."""
575
+ installed = Path(share) / 'bin-rs' / HOST_BINARY
576
+ if os.path.lexists(installed):
577
+ problem = check_installed(share, HOST_BINARY)
578
+ return (installed, None) if problem is None else (None, f'{refusal_code(problem)}: {installed}: {problem}')
579
+ import studio_host as SH # libexec; the studio-host install's own verifier (the pin record's digest)
580
+ layout = SH.Layout(home if home is not None else Path.home(), share, state if state is not None else L.STATE)
581
+ word, detail, _record = SH.verify_installed(layout)
582
+ if word == 'verified':
583
+ return layout.binary, None
584
+ if word == 'absent':
585
+ return None, (f'binary_absent: no {HOST_BINARY} installed (lanes rs install --from PATH --sha256 HEX, or lanes '
586
+ 'studio-host install)')
587
+ return None, f'digest_mismatch: {detail}'
588
+
589
+
590
+ def cutover_record(state, domain):
591
+ """(record or None, problem or None) of $LANES_STATE/cutover/<domain>.json, read by cutover.py (the one journal
592
+ of record, FC-R2); an unreadable or malformed record is a problem, never read as absent."""
593
+ import cutover as CO # libexec; lanes2 H3's Python half
594
+ try:
595
+ return CO.read_record(state, domain), None
596
+ except CO.Refused as refused:
597
+ return None, refused.code
598
+
599
+
600
+ def admit_host(mode, facts):
601
+ """HOST in `mode` (FC-R1, FC-X11): `--mode shadow` only where LANES_HOST_ROLE=owner; `on` (`--mode owner` or
602
+ `--mode aggregator`) only with one of those roles; then exactly when throttle-rc verifies."""
603
+ if mode == 'shadow' and facts.role != 'owner':
604
+ return None, ('owner_undeclared: HOST\'s shadow step `throttle-rc lanes host --mode shadow` runs only on a '
605
+ 'guest owner install (site.conf LANES_HOST_ROLE=owner)')
606
+ if mode == 'on' and facts.role not in ROLES:
607
+ return None, ('owner_undeclared: HOST on runs `--mode owner` or `--mode aggregator` by site.conf '
608
+ 'LANES_HOST_ROLE, which declares neither')
609
+ return facts.host_binary()
610
+
611
+
612
+ def host_mode_word(mode, role):
613
+ """The `throttle-rc lanes host --mode` word for HOST in `mode` on a host with `role` (FC-X11), or None."""
614
+ if mode == 'shadow':
615
+ return 'shadow' if role == 'owner' else None
616
+ if mode == 'on':
617
+ return role if role in ROLES else None
618
+ return None
619
+
620
+
621
+ def role_refusal(component, role):
622
+ """The role refusal of a host duty on a host with `role` (FC-G8): STATUSD and SYNC only where LANES_HOST_ROLE=owner
623
+ (owner_undeclared), SITE only where it is aggregator (aggregator_required); None when the role admits it."""
624
+ upper = component.upper()
625
+ if component in ('statusd', 'sync') and role != 'owner':
626
+ return f'owner_undeclared: {upper} runs only on a guest owner install (site.conf LANES_HOST_ROLE=owner)'
627
+ if component == 'site' and role != 'aggregator':
628
+ return 'aggregator_required: SITE is the aggregator\'s duty (site.conf LANES_HOST_ROLE=aggregator)'
629
+ return None
630
+
631
+
632
+ def domain_active(state, domain):
633
+ """Whether $LANES_STATE/cutover/<domain>.json is active with owner lanes-rs (an unreadable record is not)."""
634
+ record, problem = cutover_record(state, domain)
635
+ return problem is None and record is not None and record['phase'] == 'active' and record['owner'] == CANDIDATE
636
+
637
+
638
+ def admit_duty(component, mode, facts):
639
+ """A host duty in `mode` (FC-X11): host_absent while HOST is off; `shadow` only while HOST is shadow or on with no
640
+ cutover record of its domains; `on` only while HOST is on and every domain's record is active with owner
641
+ lanes-rs, otherwise cutover_pending (with the record's phase)."""
642
+ upper = component.upper()
643
+ refused = role_refusal(component, facts.role)
644
+ if refused:
645
+ return None, refused
646
+ host = facts.host()
647
+ if host == 'off':
648
+ return None, (f'host_absent: {upper} is a duty of the lanes host (`throttle-rc lanes host`, FC-R1), and HOST '
649
+ 'is off (lanes rs set host shadow|on)')
650
+ path, reason = facts.host_binary()
651
+ if path is None:
652
+ return None, reason
653
+ domains = DUTY_DOMAINS[component]
654
+ if mode == 'shadow':
655
+ for domain in domains:
656
+ record, problem = cutover_record(facts.state, domain)
657
+ if record is not None or problem:
658
+ said = problem or f"phase {record['phase']}, owner {record['owner']}"
659
+ return None, (f'cutover_pending: cutover/{domain}.json exists ({said}); a shadow never takes a '
660
+ f'cutover record (FC-D7): set {upper} on, or off')
661
+ return path, None
662
+ if host != 'on':
663
+ return None, f'cutover_pending: {upper} is on only while HOST is on (HOST is {host})'
664
+ for domain in domains:
665
+ record, problem = cutover_record(facts.state, domain)
666
+ if problem:
667
+ return None, f'cutover_pending: cutover/{domain}.json: {problem}'
668
+ if record is None:
669
+ return None, f'cutover_pending: cutover/{domain}.json: no cutover (owner {legacy_owner(domain)})'
670
+ if record['phase'] != 'active' or record['owner'] != CANDIDATE:
671
+ return None, (f"cutover_pending: cutover/{domain}.json: phase {record['phase']}, owner "
672
+ f"{record['owner']} (on needs phase active, owner {CANDIDATE})")
673
+ return path, None
674
+
675
+
676
+ def legacy_owner(domain):
677
+ """FC-R2's legacy owner of a 2.0 domain with no record (studio-host for attention, none for the coordination
678
+ store's domains, lanes-py for the rest): cutover.py's one table (`cutover.legacy_owner`), else, while this tree's
679
+ cutover.py has none yet, FALLBACK_LEGACY_OWNERS."""
680
+ import cutover as CO # libexec; the one journal of record's Python half (FC-R2)
681
+ table = getattr(CO, 'legacy_owner', None)
682
+ if callable(table):
683
+ return table(domain)
684
+ return FALLBACK_LEGACY_OWNERS.get(domain, 'lanes-py')
685
+
686
+
687
+ def admit(component, mode, tree, share, machine=None, facts=None):
688
+ """(path, None) when `component` may run natively in `mode` (on or shadow), else (None, reason): `shadow` only with
689
+ a shadow step (shadow_unsupported), HOST by admit_host, a host duty by admit_duty (its path is the throttle-rc
690
+ binary that composes it), a component without a binary never (binary_absent), and otherwise exactly when resolve()
691
+ verifies its binary. `facts` (Facts) defaults to $LANES_STATE, $LANES_SHARE and this account's site.conf."""
692
+ if component not in COMPONENTS:
693
+ return None, f'unknown_component: {component}'
694
+ if mode == 'shadow' and component not in SHADOW_STEP:
377
695
  return None, f'shadow_unsupported: {component.upper()} has no shadow step (AR 7.4); set on or off'
696
+ facts = facts if facts is not None else Facts(L.STATE, share)
697
+ if component == HOST:
698
+ return admit_host(mode, facts)
699
+ if component in HOST_DUTIES:
700
+ return admit_duty(component, mode, facts)
378
701
  return resolve(component, tree, share, machine)
379
702
 
380
703
 
@@ -386,6 +709,15 @@ def flag_files(state):
386
709
  return []
387
710
 
388
711
 
712
+ def feature_files(state):
713
+ """The feature.* names present under `state`/flags (sorted; [] without the directory)."""
714
+ try:
715
+ return sorted(entry.name for entry in (Path(state) / 'flags').iterdir()
716
+ if entry.name.startswith(FEATURE_PREFIX))
717
+ except OSError:
718
+ return []
719
+
720
+
389
721
  def remove_flag(state, name, problems):
390
722
  """Remove `state`/flags/<name> -> True when it went; a failure is added to `problems` (a directory someone made
391
723
  there: reported, never followed)."""
@@ -399,79 +731,199 @@ def remove_flag(state, name, problems):
399
731
  return False
400
732
 
401
733
 
402
- def prune_flags(state, tree, share, machine=None):
734
+ def create_flag(flags, name):
735
+ """Create the empty flag file flags/<name> -> True when it did not exist (existence only, never rewritten)."""
736
+ if os.path.lexists(flags / name):
737
+ return False
738
+ os.close(os.open(flags / name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o644))
739
+ return True
740
+
741
+
742
+ def prune_flags(state, tree, share, machine=None, home=None):
403
743
  """Remove every flags/native.* file that `tree` and `share` do not admit -> ([(name, reason)] removed, [problem]).
404
- `tree` is the one `current` is about to name (host-install.sh, a rollback) or names (uninstall)."""
744
+ `tree` is the one `current` is about to name (host-install.sh, a rollback) or names (uninstall). HOST is judged
745
+ first, so a duty whose HOST flag goes goes with it (host_absent)."""
405
746
  removed, problems = [], []
747
+ facts = Facts(state, share, home)
406
748
  for name in flag_files(state):
407
749
  parsed = parse_flag_file(name)
408
750
  reason = ('no known component projects this file' if parsed is None
409
- else admit(parsed[0], parsed[1], tree, share, machine)[1])
751
+ else admit(parsed[0], parsed[1], tree, share, machine, facts)[1])
410
752
  if reason and remove_flag(state, name, problems):
411
753
  removed.append((name, reason))
412
754
  return removed, problems
413
755
 
414
756
 
415
- def apply_flags(state, conf, tree, share, machine=None):
416
- """`lanes rs apply`: make $LANES_STATE/flags/native.* say what site.conf `conf` asks for and admit() allows -> a
417
- report {modes, problems, refused: [(component, mode, reason)], created: [name], removed: [name]}. Existence only:
418
- a flag file is created empty and never rewritten; every native.* file outside the wanted set is removed."""
419
- modes, problems = native_flags(conf)
420
- effective, refused = dict(modes), []
421
- for component, mode in modes.items():
422
- if mode != 'off':
423
- path, reason = admit(component, mode, tree, share, machine)
424
- if path is None:
425
- refused.append((component, mode, reason))
426
- effective[component] = 'off'
757
+ def drive_cutover(binary, domain, state, to=CANDIDATE, timeout=CUTOVER_TIMEOUT):
758
+ """FC-R7, FC-G8: `throttle-rc lanes cutover <domain> --to <holder> --state <state>` (the H3 DomainFence; `--to
759
+ lanes-rs` forward, `--to <legacy owner>` the reverse fence) -> (exit status or None for a timeout, its last line).
760
+ The record it leaves is what admission reads next; nothing is assumed from the exit status alone."""
761
+ try:
762
+ done = subprocess.run([str(binary), 'lanes', 'cutover', domain, '--to', to, '--state', str(state)],
763
+ capture_output=True, text=True, timeout=timeout, stdin=subprocess.DEVNULL)
764
+ except subprocess.TimeoutExpired:
765
+ return None, f'did not finish within {timeout} s'
766
+ except OSError as error:
767
+ return 127, str(error.strerror or error)
768
+ lines = (done.stdout + done.stderr).strip().splitlines()
769
+ return done.returncode, lines[-1] if lines else ''
770
+
771
+
772
+ def apply_flags(state, conf, tree, share, machine=None, home=None, version=None, cutover=None):
773
+ """`lanes rs apply`: make $LANES_STATE/flags/native.* say what each request (site.conf, else the release default)
774
+ asks for and admit() allows, and flags/feature.* what the FC-E12 switches say -> a report {modes, sources,
775
+ problems, refused: [(component, mode, reason)], defaults_refused: [(component, mode, reason)], driven: [(domain,
776
+ to, rc, line)], created: [name], removed: [name]}. Existence only: a flag file is created empty and never
777
+ rewritten; every native.* and feature.* file outside the wanted set is removed. `cutover(binary, domain, state,
778
+ to)` drives a domain's fence (drive_cutover): forward for a duty requested `on` — by site.conf or by the release
779
+ default alike (FC-G8: a missing line is the release default; FC-G9: a host duty turns on only through its fence) —
780
+ whose role admits it, and back to the legacy owner for a duty requested `off` whose record is active for
781
+ lanes-rs."""
782
+ requests, problems = native_requests(conf, tree_version(tree) if version is None else version)
783
+ facts = Facts(state, share, home, conf)
784
+ effective, refused, defaults_refused, driven = {}, [], [], []
785
+ cutover = drive_cutover if cutover is None else cutover
786
+
787
+ def judge(component, mode, source):
788
+ path, reason = admit(component, mode, tree, share, machine, facts) if mode != 'off' else (None, None)
789
+ if mode != 'off' and path is None:
790
+ (refused if source == 'site.conf' else defaults_refused).append((component, mode, reason))
791
+ return 'off'
792
+ return mode
793
+
794
+ effective[HOST] = judge(HOST, *requests[HOST])
795
+ facts.host_mode = effective[HOST]
796
+ for component in COMPONENTS:
797
+ if component == HOST:
798
+ continue
799
+ mode, source = requests[component]
800
+ if component in HOST_DUTIES and role_refusal(component, facts.role) is None:
801
+ # FC-R7, FC-G8: the request drives the fence. `on` (site.conf or the release default: FC-G8's missing
802
+ # line is the default, and FC-G9's default turns a host duty on only through its fence) drives each
803
+ # domain not yet active for lanes-rs forward while HOST is on; `off` drives each domain still active for
804
+ # lanes-rs back to its legacy owner (the reverse fence of `lanes rs set <c> off && lanes rs apply`).
805
+ if mode == 'on' and facts.host_mode == 'on':
806
+ moves = [(domain, CANDIDATE) for domain in DUTY_DOMAINS[component] if not domain_active(state, domain)]
807
+ elif mode == 'off':
808
+ moves = [(domain, legacy_owner(domain)) for domain in DUTY_DOMAINS[component]
809
+ if domain_active(state, domain) and legacy_owner(domain) != NO_LEGACY_OWNER]
810
+ else:
811
+ moves = []
812
+ binary = facts.host_binary()[0] if moves else None
813
+ for domain, to in (moves if binary else []):
814
+ rc, line = cutover(binary, domain, state, to)
815
+ driven.append((domain, to, rc, line))
816
+ effective[component] = judge(component, mode, source)
427
817
  wanted = {flag_file(component, mode) for component, mode in effective.items() if mode != 'off'}
818
+ switches, switch_problems = feature_switches(conf)
819
+ problems += switch_problems
820
+ wanted_features = {feature_file(name) for name, value in switches.items() if value == 'on'}
428
821
  flags = Path(state) / 'flags'
429
822
  created, removed = [], []
430
- if wanted:
823
+ if wanted or wanted_features:
431
824
  flags.mkdir(parents=True, exist_ok=True)
432
- for name in sorted(wanted):
433
- if not os.path.lexists(flags / name):
434
- os.close(os.open(flags / name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o644))
825
+ for name in sorted(wanted | wanted_features):
826
+ if create_flag(flags, name):
435
827
  created.append(name)
436
- for name in flag_files(state):
437
- if name not in wanted and remove_flag(state, name, problems):
828
+ for name in flag_files(state) + feature_files(state):
829
+ if name not in wanted and name not in wanted_features and remove_flag(state, name, problems):
438
830
  removed.append(name)
439
- return {'modes': effective, 'problems': problems, 'refused': refused, 'created': created, 'removed': removed}
831
+ return {'modes': effective, 'sources': {c: requests[c][1] for c in COMPONENTS}, 'problems': problems,
832
+ 'refused': refused, 'defaults_refused': defaults_refused, 'driven': driven, 'created': created,
833
+ 'removed': removed, 'features': switches}
440
834
 
441
835
 
442
836
  def apply_lines(report):
443
- """`lanes rs apply`'s lines: the problems, refusals and changes, then one summary."""
837
+ """`lanes rs apply`'s lines: the problems, refusals, driven fences and changes, then one summary."""
444
838
  lines = [f'! {problem}' for problem in report['problems']]
445
839
  lines += [f'! LANES_RS_{component.upper()}={mode} refused, kept off: {reason}'
446
840
  for component, mode, reason in report['refused']]
841
+ lines += [f' {component.upper()} default {mode} not taken on this host, kept off: {reason}'
842
+ for component, mode, reason in report['defaults_refused']]
843
+ lines += [f"cutover {domain} --to {to}: {'timeout' if rc is None else f'exit {rc}'}"
844
+ + (f': {line}' if line else '') for domain, to, rc, line in report['driven']]
447
845
  lines += [f'flags/{name} created' for name in report['created']]
448
846
  lines += [f'flags/{name} removed' for name in report['removed']]
847
+ lines += report.get('units', [])
848
+ lines += [f'! {problem}' for problem in report.get('unit_problems', [])]
449
849
  lit = [f'{component.upper()}={mode}' for component, mode in report['modes'].items() if mode != 'off']
450
850
  lines.append(f"native flags: {' '.join(lit) if lit else 'every component off'}; a view or sidebar picks a change "
451
851
  'up when it starts again (lanes reload-views)')
452
852
  return lines
453
853
 
454
854
 
455
- def status_lines(state, conf, tree, share, machine=None):
456
- """`lanes rs status`: one line per component — site.conf's mode, the flag file, what runs — then the warnings."""
457
- modes, problems = native_flags(conf)
855
+ def status_lines(state, conf, tree, share, machine=None, home=None, version=None):
856
+ """`lanes rs status`: one line per component — the request and its source, the flag file, every cutover record
857
+ of a host duty, what runs — then the warnings."""
858
+ requests, problems = native_requests(conf, tree_version(tree) if version is None else version)
859
+ facts = Facts(state, share, home, conf)
458
860
  present = set(flag_files(state))
459
861
  lines = [f'! {problem}' for problem in problems]
460
- lines.append(f"{'component':<11} {'site.conf':<9} {'flag':<6} runs")
862
+ lines.append(f"{'component':<11} {'request':<8} {'source':<9} {'flag':<6} runs")
461
863
  for component in COMPONENTS:
462
- flag = next((mode for mode in ('on', 'shadow') if flag_file(component, mode) in present), 'off')
463
- runs = 'python'
864
+ mode, source = requests[component]
865
+ flag = next((m for m in ('on', 'shadow') if flag_file(component, m) in present), 'off')
866
+ runs = 'python' if component not in HOST_DUTIES and component != HOST else (
867
+ 'nothing' if component == HOST else legacy_runs(component))
464
868
  if flag != 'off':
465
- path, reason = admit(component, flag, tree, share, machine)
466
- runs = str(path) if path else f'python (the flag is no longer admitted: {reason})'
467
- if modes[component] != flag:
468
- runs += f'; site.conf says {modes[component]}: lanes rs apply'
469
- lines.append(f'{component.upper():<11} {modes[component]:<9} {flag:<6} {runs}')
869
+ path, reason = admit(component, flag, tree, share, machine, facts)
870
+ runs = (f'the lanes host ({path})' if component in HOST_DUTIES else str(path)) if path else \
871
+ f'{runs} (the flag is no longer admitted: {reason})'
872
+ if mode != flag:
873
+ runs += f'; the request is {mode}: lanes rs apply'
874
+ if component in HOST_DUTIES:
875
+ records = []
876
+ for domain in DUTY_DOMAINS[component]:
877
+ record, problem = cutover_record(state, domain)
878
+ records.append(f"{domain}={problem or (record['phase'] + '/' + record['owner'] if record else 'none')}")
879
+ runs += f"; cutover {' '.join(records)}"
880
+ lines.append(f'{component.upper():<11} {mode:<8} {source:<9} {flag:<6} {runs}')
470
881
  lines += [f'! flags/{name}: no known component projects it; lanes rs apply removes it'
471
882
  for name in sorted(present) if parse_flag_file(name) is None]
883
+ switches, switch_problems = feature_switches(conf)
884
+ lines += [f'! {problem}' for problem in switch_problems]
885
+ on = [name for name, value in switches.items() if value == 'on']
886
+ lines.append(f"feature switches: {' '.join(on) if on else 'every switch off'}")
472
887
  return lines + shadowing(tree, share, machine)
473
888
 
474
889
 
890
+ def legacy_runs(component):
891
+ """What runs a host duty while its domains have no record for the lanes host: their legacy owners."""
892
+ owners = sorted({legacy_owner(domain) for domain in DUTY_DOMAINS[component]})
893
+ return 'legacy ' + '+'.join(owners)
894
+
895
+
896
+ def set_request(home, component, mode, share=None, state=None):
897
+ """`lanes rs set COMPONENT MODE`: write site.conf's LANES_RS_<COMPONENT>=<mode> line atomically under the
898
+ site.conf lock (every earlier line naming the key goes; the file keeps its other lines and its mode bits) ->
899
+ the site.conf path. Refused before anything is written: usage, unknown_component, shadow_unsupported, and for
900
+ HOST shadow|on the refusal of resolve_host (FC-R1: binary_absent with neither the `lanes rs install` link nor the
901
+ `lanes studio-host install` selection; digest_mismatch for one that does not verify)."""
902
+ if mode not in MODES:
903
+ raise Refusal('usage', f'{USAGE} (a mode is one of {"|".join(MODES)})', 2)
904
+ if component not in COMPONENTS:
905
+ raise Refusal('unknown_component', f'{component.upper()} is no component (known: '
906
+ f'{" ".join(c.upper() for c in COMPONENTS)})')
907
+ if mode == 'shadow' and component not in SHADOW_STEP:
908
+ raise Refusal('shadow_unsupported', f'{component.upper()} has no shadow step (AR 7.4); set on or off')
909
+ if component == HOST and mode != 'off':
910
+ path, reason = resolve_host(L.SHARE if share is None else share, L.STATE if state is None else state, home)
911
+ if path is None:
912
+ code, _, said = reason.partition(': ')
913
+ raise Refusal(code, said or reason)
914
+ path = (Path(home) if home is not None else Path.home()) / L.SITE_CONF
915
+ path.parent.mkdir(parents=True, exist_ok=True)
916
+ key = f'LANES_RS_{component.upper()}'
917
+ with share_lock(path.parent, wait=None, name=SITE_LOCK, what='lanes rs set'):
918
+ try:
919
+ text, bits = path.read_text(), path.stat().st_mode & 0o777
920
+ except FileNotFoundError:
921
+ text, bits = '', 0o644
922
+ kept = [line for line in text.splitlines() if not line.startswith(key + '=')]
923
+ L.atomic_write(path, '\n'.join(kept + [f'{key}={mode}']) + '\n', bits)
924
+ return path
925
+
926
+
475
927
  def swap_link(link, target):
476
928
  """Point `link` at `target` (a name in the same directory) in one rename(2)."""
477
929
  temporary = link.parent / f'.{link.name}.{os.getpid()}.{secrets.token_hex(4)}'
@@ -485,11 +937,12 @@ def swap_link(link, target):
485
937
 
486
938
 
487
939
  @contextlib.contextmanager
488
- def share_lock(directory, wait=None):
489
- """The exclusive flock(2) on `directory`/.lock that install and uninstall hold while they change bin-rs/; another
490
- holder for longer than `wait` seconds (default LOCK_WAIT) refuses (busy)."""
940
+ def share_lock(directory, wait=None, name=LOCK, what='lanes rs install or uninstall'):
941
+ """The exclusive flock(2) on `directory`/<name> (.lock: install and uninstall hold it while they change bin-rs/;
942
+ SITE_LOCK: `lanes rs set` holds it while it rewrites site.conf); another holder for longer than `wait` seconds
943
+ (default LOCK_WAIT) refuses (busy)."""
491
944
  directory.mkdir(parents=True, exist_ok=True)
492
- descriptor = os.open(directory / LOCK, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_CLOEXEC, 0o600)
945
+ descriptor = os.open(directory / name, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_CLOEXEC, 0o600)
493
946
  try:
494
947
  deadline = time.monotonic() + (LOCK_WAIT if wait is None else wait)
495
948
  while True:
@@ -498,7 +951,7 @@ def share_lock(directory, wait=None):
498
951
  break
499
952
  except BlockingIOError:
500
953
  if time.monotonic() >= deadline:
501
- raise Refusal('busy', f'another lanes rs install or uninstall holds {directory / LOCK}')
954
+ raise Refusal('busy', f'another {what} holds {directory / name}')
502
955
  time.sleep(0.1)
503
956
  yield
504
957
  finally:
@@ -515,8 +968,8 @@ def install_local(share, source, expected):
515
968
  if not os.access(source, os.X_OK):
516
969
  raise Refusal('usage', f'{source} is not executable', 2)
517
970
  name = source.name
518
- if name not in BINARIES:
519
- raise Refusal('usage', f'{name} is not a native binary\'s name (one of {", ".join(sorted(BINARIES))})', 2)
971
+ if name not in INSTALLABLE:
972
+ raise Refusal('usage', f'{name} is not a native binary\'s name (one of {", ".join(sorted(INSTALLABLE))})', 2)
520
973
  actual, size = sha256_file(source)
521
974
  if actual != expected:
522
975
  raise Refusal('binary_mismatch', f'{source} hashed {actual}, not the --sha256 given; nothing installed')
@@ -550,8 +1003,8 @@ def install_local(share, source, expected):
550
1003
  def uninstall_local(share, name):
551
1004
  """`lanes rs uninstall NAME`: remove the link bin-rs/NAME -> True when it went, False when there was none. The
552
1005
  placed file and its INSTALLED.json record stay (no pruning yet); a later install of the same bytes reuses them."""
553
- if name not in BINARIES:
554
- raise Refusal('usage', f'{name} is not a native binary\'s name (one of {", ".join(sorted(BINARIES))})', 2)
1006
+ if name not in INSTALLABLE:
1007
+ raise Refusal('usage', f'{name} is not a native binary\'s name (one of {", ".join(sorted(INSTALLABLE))})', 2)
555
1008
  directory = Path(share) / 'bin-rs'
556
1009
  if not os.path.lexists(directory / name):
557
1010
  return False
@@ -611,9 +1064,22 @@ def tree_main(args, out, share=None):
611
1064
  return 0
612
1065
 
613
1066
 
614
- def main(args, out=None, tree=None, share=None, state=None, home=None, machine=None):
1067
+ def services_module():
1068
+ """This tree's install/services.py (the one renderer of user units)."""
1069
+ import importlib.util
1070
+ path = Path(__file__).resolve().parents[1] / 'install' / 'services.py'
1071
+ spec = importlib.util.spec_from_file_location('lanes_services_native', path)
1072
+ module = importlib.util.module_from_spec(spec)
1073
+ spec.loader.exec_module(module)
1074
+ return module
1075
+
1076
+
1077
+ def main(args, out=None, tree=None, share=None, state=None, home=None, machine=None, units=None, cutover=None,
1078
+ systemctl=None):
615
1079
  """`lanes rs …` (bin/lanes cmd_rs) -> exit status. `tree` defaults to the tree this code runs from (the installed
616
- release when run as `lanes`), `share`/`state` to $LANES_SHARE/$LANES_STATE, `home` to this account's (site.conf)."""
1080
+ release when run as `lanes`), `share`/`state` to $LANES_SHARE/$LANES_STATE, `home` to this account's (site.conf),
1081
+ `units` to the directory the user manager reads units from (install/services.py manager_unit_dir), `cutover` to
1082
+ drive_cutover and `systemctl` to install/services.py run_systemctl (tests record both)."""
617
1083
  out = sys.stdout if out is None else out
618
1084
  tree = L.REPO if tree is None else Path(tree)
619
1085
  share = L.SHARE if share is None else Path(share)
@@ -630,33 +1096,53 @@ def main(args, out=None, tree=None, share=None, state=None, home=None, machine=N
630
1096
  raise Refusal('usage', f'{USAGE} (both --from and --sha256 are required)', 2)
631
1097
  record = install_local(share, options['--from'], options['--sha256'])
632
1098
  print(f"installed {record['name']} {record['sha256'][:12]} at {share / 'bin-rs' / record['name']}; no flag "
633
- 'changed (site.conf LANES_RS_<COMPONENT>, then lanes rs apply)', file=out)
1099
+ 'changed (lanes rs set COMPONENT MODE, then lanes rs apply)', file=out)
634
1100
  return 0
635
1101
  if args[:1] == ['uninstall'] and len(args) == 2:
636
1102
  if not uninstall_local(share, args[1]):
637
1103
  print(f'{args[1]} is not installed under {share / "bin-rs"}; nothing changed', file=out)
638
1104
  return 0
639
1105
  print(f'uninstalled {args[1]}: where its flag stays on, the release tree\'s own binary runs', file=out)
640
- removed, problems = prune_flags(state, tree, share, machine)
1106
+ removed, problems = prune_flags(state, tree, share, machine, home)
641
1107
  for name, reason in removed:
642
1108
  print(f'flags/{name} removed: {reason}', file=out)
643
1109
  for problem in problems:
644
1110
  print(f'! {problem}', file=out)
1111
+ if any(parse_flag_file(name) == (HOST, mode) for name, _reason in removed for mode in ('on', 'shadow')):
1112
+ services = services_module()
1113
+ account = Path(home) if home is not None else Path.home()
1114
+ lines, unit_problems = services.reconcile_units(
1115
+ account, share, state, units if units is not None else services.manager_unit_dir(account),
1116
+ systemctl)
1117
+ for line in lines:
1118
+ print(line, file=out)
1119
+ for problem in unit_problems:
1120
+ print(f'! {problem}', file=out)
1121
+ problems += unit_problems
645
1122
  return 3 if problems else 0
646
1123
  if args in (['verify'], ['verify', '--tree']):
647
1124
  lines, rc = verify_lines(tree, share, args == ['verify', '--tree'], machine)
648
1125
  for line in lines:
649
1126
  print(line, file=out)
650
1127
  return rc
1128
+ if args[:1] == ['set'] and len(args) == 3:
1129
+ path = set_request(home, args[1].lower(), args[2], share, state)
1130
+ print(f'{path}: LANES_RS_{args[1].upper()}={args[2]}; no flag changed until lanes rs apply', file=out)
1131
+ return 0
651
1132
  if args == ['status']:
652
- for line in status_lines(state, L.site_conf(home), tree, share, machine):
1133
+ for line in status_lines(state, L.site_conf(home), tree, share, machine, home):
653
1134
  print(line, file=out)
654
1135
  return 0
655
1136
  if args == ['apply']:
656
- report = apply_flags(state, L.site_conf(home), tree, share, machine)
1137
+ report = apply_flags(state, L.site_conf(home), tree, share, machine, home, cutover=cutover)
1138
+ services = services_module()
1139
+ account = Path(home) if home is not None else Path.home()
1140
+ report['units'], report['unit_problems'] = services.reconcile_units(
1141
+ account, share, state, units if units is not None else services.manager_unit_dir(account),
1142
+ systemctl)
657
1143
  for line in apply_lines(report):
658
1144
  print(line, file=out)
659
- return 3 if report['problems'] or report['refused'] else 0
1145
+ return 3 if report['problems'] or report['refused'] or report['unit_problems'] else 0
660
1146
  raise Refusal('usage', USAGE, 2)
661
1147
  except Refusal as error:
662
1148
  print(f'lanes rs: {error}' if error.code == 'usage' else f'lanes rs: refused ({error.code}): {error}', file=out)