@vibelord/lanes 1.7.3 → 1.7.5

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 (57) hide show
  1. package/README.md +9 -0
  2. package/package.json +1 -1
  3. package/payload/lanes/VERSION +1 -1
  4. package/payload/lanes/bin/lanes +128 -24
  5. package/payload/lanes/bin/lanes-site-serve +15 -0
  6. package/payload/lanes/bin-rs/BINARIES.json +5 -0
  7. package/payload/lanes/container/lane-mcp +108 -5
  8. package/payload/lanes/container/lane_core.py +116 -0
  9. package/payload/lanes/container/throttle-pulse +159 -14
  10. package/payload/lanes/docs/ARCHITECTURE.md +132 -13
  11. package/payload/lanes/docs/DESIGN.md +10 -8
  12. package/payload/lanes/docs/INSTALL.md +1 -1
  13. package/payload/lanes/docs/RUNBOOK.md +436 -8
  14. package/payload/lanes/docs/USERGUIDE.md +82 -9
  15. package/payload/lanes/install/host-install.sh +35 -4
  16. package/payload/lanes/libexec/adopt.py +364 -0
  17. package/payload/lanes/libexec/attach.py +35 -5
  18. package/payload/lanes/libexec/cutover.py +656 -0
  19. package/payload/lanes/libexec/docsd.py +12 -8
  20. package/payload/lanes/libexec/doctor_lanes2.py +284 -0
  21. package/payload/lanes/libexec/economy_poll.py +87 -2
  22. package/payload/lanes/libexec/gc_unregistered.py +407 -0
  23. package/payload/lanes/libexec/lanes_lib.py +474 -2
  24. package/payload/lanes/libexec/native.sh +38 -0
  25. package/payload/lanes/libexec/native_bin.py +670 -0
  26. package/payload/lanes/libexec/session_actions.py +85 -7
  27. package/payload/lanes/libexec/shadow.py +1311 -0
  28. package/payload/lanes/libexec/sidebar.py +252 -30
  29. package/payload/lanes/libexec/sidebar_status.py +373 -25
  30. package/payload/lanes/libexec/statusd.py +67 -3
  31. package/payload/lanes/libexec/tokens.py +99 -131
  32. package/payload/lanes/libexec/tokens.sh +1 -1
  33. package/payload/lanes/libexec/update.py +78 -8
  34. package/payload/lanes/libexec/users.py +282 -0
  35. package/payload/lanes/site/README.md +9 -0
  36. package/payload/lanes/site/conformance.py +280 -0
  37. package/payload/lanes/site/protocol.py +368 -0
  38. package/payload/lanes/site/server.py +314 -0
  39. package/payload/lanes/systemd/lanes-gc.service +1 -1
  40. package/payload/lanes/systemd/lanes-gc.timer +14 -3
  41. package/payload/lanes/tokens/README.md +156 -0
  42. package/payload/lanes/tokens/generate.py +930 -0
  43. package/payload/lanes/tokens/generated/parity.v1.tsv +489 -0
  44. package/payload/lanes/tokens/generated/tokens.resolved.json +835 -0
  45. package/payload/lanes/tokens/tokens.v1.json +763 -0
  46. package/payload/lanes/tokens/tokens.v1.schema.json +143 -0
  47. package/payload/lanes/web/Caddyfile +11 -0
  48. package/payload/lanes/web/README.md +253 -4
  49. package/payload/lanes/web/directory.css +95 -0
  50. package/payload/lanes/web/directory.js +951 -0
  51. package/payload/lanes/web/generated/README.md +107 -0
  52. package/payload/lanes/web/generated/lanes2_protocol.d.mts +1162 -0
  53. package/payload/lanes/web/generated/lanes2_protocol.mjs +2333 -0
  54. package/payload/lanes/web/inbox.js +1140 -0
  55. package/payload/lanes/web/mobile.js +35 -45
  56. package/payload/lanes/web/tokens.css +137 -0
  57. package/payload/manifest.json +7 -4
@@ -0,0 +1,930 @@
1
+ #!/usr/bin/env python3
2
+ """The Lanes semantic token generator (fan-out lane F1; integrated cockpit section 5.1, witness A26).
3
+
4
+ `tokens.v1.json` (beside this file) is the one hand-edited source. This script checks it — the revision bound to its
5
+ styling digest, every role in every tier, the contrast rules, the no-colour cues, the 7-bit ASCII twins — and derives
6
+ every client projection from it, so the same theme id/revision paints alike on every client:
7
+
8
+ lanes/tokens/generated/tokens.resolved.json the resolved table lanes/libexec/tokens.py reads (its only input)
9
+ lanes/tokens/generated/parity.v1.tsv the cross-client parity fixture: one fact per line, compared by the
10
+ Python, Rust and Swift suites against their own projection
11
+ lanes/web/tokens.css CSS custom properties, both variants, semantic aliases
12
+ crates/lanes-terminal/src/tokens/generated.rs the Rust/ANSI terminal projection (complete SGR per tier)
13
+ apps/throttle-ios/Sources/LanesKit/Tokens/LanesTokens.swift the Swift projection
14
+
15
+ `tokens.py` renders the older surfaces (the Zellij KDL theme, the phone CSS/JS, the shell sets, DESIGN.md, Ghostty,
16
+ the docs CSS) from the resolved table, between markers; `--write` regenerates them too and `--check` checks them.
17
+
18
+ python3 lanes/tokens/generate.py --write regenerate every projection and every marker block
19
+ python3 lanes/tokens/generate.py --check exit 1, with a diff, when any committed projection differs
20
+
21
+ The Rust and Swift outputs exist only in a repository checkout (in_checkout); in an installed or payload tree both
22
+ verbs handle the files inside lanes/ only and create nothing beside the tree. Every output is replaced atomically.
23
+ The source is refused when a projection would break: besides the rules above, a name that is not a legal, distinct
24
+ Rust and Swift identifier, and a number not in the one form every JSON encoder prints alike (the digest).
25
+
26
+ Standard library only; importable with no side effects (nothing is read until a function asks)."""
27
+ import copy
28
+ import difflib
29
+ import hashlib
30
+ import importlib.util
31
+ import json
32
+ import math
33
+ import os
34
+ import re
35
+ import sys
36
+ import tempfile
37
+ from pathlib import Path
38
+
39
+ TOKENS_DIR = Path(__file__).resolve().parent
40
+ LANES = TOKENS_DIR.parent
41
+ SOURCE_NAME = 'tokens.v1.json'
42
+ SCHEMA = 'lanes.tokens/1'
43
+ RESOLVED_SCHEMA = 'lanes.tokens.resolved/1'
44
+ PARITY_SCHEMA = 'lanes.tokens.parity/1'
45
+ # The styling digest covers the document except these keys and each tier's description (tokens.v1.schema.json).
46
+ META = ('schema', 'source', 'description', 'theme')
47
+ VARIANTS = ('dark', 'light')
48
+ TIERS = ('truecolor', '256', '16', 'palette16', 'none')
49
+ SGR_TIERS = ('truecolor', '256', '16', 'none') # the tiers a terminal emits as SGR
50
+ GLYPH_TABLES = ('agent', 'stream', 'marks', 'economy')
51
+ CUE_TEXT = ('name', 'reason', 'legend')
52
+ ESC = '\033'
53
+ BOLD, RESET = ESC + '[1m', ESC + '[0m'
54
+ # Output -> (base, path): `lanes` paths sit in every lanes tree (the npm payload too); `repo` paths only in a checkout.
55
+ OUTPUTS = {
56
+ 'resolved': ('lanes', 'tokens/generated/tokens.resolved.json'),
57
+ 'parity': ('lanes', 'tokens/generated/parity.v1.tsv'),
58
+ 'css': ('lanes', 'web/tokens.css'),
59
+ 'rust': ('repo', 'crates/lanes-terminal/src/tokens/generated.rs'),
60
+ 'swift': ('repo', 'apps/throttle-ios/Sources/LanesKit/Tokens/LanesTokens.swift'),
61
+ }
62
+ LANES_OUTPUTS = tuple(kind for kind, (base, _rel) in OUTPUTS.items() if base == 'lanes')
63
+ NOTICE = 'generated by lanes/tokens/generate.py from lanes/tokens/tokens.v1.json; do not edit by hand'
64
+
65
+
66
+ class TokenError(ValueError):
67
+ """The source breaks a rule the projections depend on; nothing is written."""
68
+
69
+
70
+ # ------------------------------------------------------------------ source
71
+ def load(lanes=LANES):
72
+ return json.loads((Path(lanes) / 'tokens' / SOURCE_NAME).read_text(encoding='utf-8'))
73
+
74
+
75
+ def styling_content(doc):
76
+ """The digested part of the document: everything but META and each tier's description."""
77
+ content = {k: copy.deepcopy(v) for k, v in doc.items() if k not in META}
78
+ for tier in content.get('tiers', {}).values():
79
+ if isinstance(tier, dict):
80
+ tier.pop('description', None)
81
+ return content
82
+
83
+
84
+ def styling_digest(doc):
85
+ """sha256 of the styling content: the document without META and without each tier's description, as JSON with
86
+ sorted keys, separators (',', ':') and UTF-8 text. Numbers take one form every JSON encoder agrees on: an integer
87
+ as an integer, a non-integral number in its shortest round-trip form; number_problems refuses an integral value
88
+ written as a float (Python prints 3.0 where JavaScript and Swift print 3, so the digests would differ)."""
89
+ canonical = json.dumps(styling_content(doc), sort_keys=True, separators=(',', ':'), ensure_ascii=False).encode('utf-8')
90
+ return hashlib.sha256(canonical).hexdigest()
91
+
92
+
93
+ HEX_COLOUR = re.compile(r'^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$')
94
+ SHADOW = re.compile(r'^(-?\d+)(?:px)? (-?\d+)(?:px)? (\d+)(?:px)? (#[0-9a-f]+)$')
95
+
96
+
97
+ def rgba(value):
98
+ """(r, g, b, a) as integers 0-255 for a CSS hex colour (#rgb, #rgba, #rrggbb, #rrggbbaa); None for anything else."""
99
+ if not isinstance(value, str) or not HEX_COLOUR.match(value):
100
+ return None
101
+ digits = value[1:]
102
+ if len(digits) in (3, 4):
103
+ digits = ''.join(c * 2 for c in digits)
104
+ channels = [int(digits[i:i + 2], 16) for i in range(0, len(digits), 2)]
105
+ return tuple(channels + [255] * (4 - len(channels)))
106
+
107
+
108
+ def shadow(value):
109
+ """(x, y, blur, (r, g, b, a)) for a `<x> <y> <blur> <hex>` CSS shadow; None for anything else."""
110
+ match = SHADOW.match(value) if isinstance(value, str) else None
111
+ if not match or rgba(match.group(4)) is None:
112
+ return None
113
+ return int(match.group(1)), int(match.group(2)), int(match.group(3)), rgba(match.group(4))
114
+
115
+
116
+ def xterm_rgb(index):
117
+ """The fixed RGB hex of an xterm-256 index from 16 up: the 6x6x6 cube and the 24-step grey ramp."""
118
+ if index >= 232:
119
+ grey = 8 + 10 * (index - 232)
120
+ return '#%02x%02x%02x' % (grey, grey, grey)
121
+ levels, cube = (0, 95, 135, 175, 215, 255), index - 16
122
+ return '#%02x%02x%02x' % (levels[cube // 36], levels[cube // 6 % 6], levels[cube % 6])
123
+
124
+
125
+ def luminance(hexval):
126
+ r, g, b = (c / 255 for c in rgba(hexval)[:3])
127
+ lin = [c / 12.92 if c <= 0.03928 else ((c + 0.055) / 1.055) ** 2.4 for c in (r, g, b)]
128
+ return 0.2126 * lin[0] + 0.7152 * lin[1] + 0.0722 * lin[2]
129
+
130
+
131
+ def contrast_ratio(fg, bg):
132
+ hi, lo = sorted((luminance(fg), luminance(bg)), reverse=True)
133
+ return (hi + 0.05) / (lo + 0.05)
134
+
135
+
136
+ def colour_of(doc, variant, role):
137
+ """The truecolor value a painted role paints: its own, or for a background role the role it takes."""
138
+ return doc['tiers']['truecolor'][variant][doc['backgrounds'].get(role, role)]
139
+
140
+
141
+ def resolve_ref(doc, variant, ref):
142
+ """A contrast reference (`truecolor:<role>`, `256:<painted role>`, `palette16:<slot>`) as an opaque hex colour."""
143
+ tier, _, key = ref.partition(':')
144
+ if tier == 'truecolor':
145
+ return doc['tiers']['truecolor'][variant][key]
146
+ if tier == '256':
147
+ return xterm_rgb(doc['tiers']['256'][variant][key])
148
+ return doc['tiers']['palette16'][variant][int(key)]
149
+
150
+
151
+ def glyph_of(doc, ref):
152
+ table, _, key = ref.partition('.')
153
+ return doc['glyphs'].get(table, {}).get(key)
154
+
155
+
156
+ def label_of(doc, ref):
157
+ table, _, key = ref.partition('.')
158
+ return doc['labels'].get(table, {}).get(key)
159
+
160
+
161
+ def problems(doc):
162
+ """Every rule a projection relies on, as messages ([] when the source is sound). The schema (tokens.v1.schema.json)
163
+ fixes the shape; these are the cross-references and measures a schema cannot state."""
164
+ out = []
165
+ theme, roles, painted, backgrounds = doc['theme'], doc['roles'], doc['painted_roles'], doc['backgrounds']
166
+ revisions = theme.get('revisions', {})
167
+ revision = theme.get('revision')
168
+ if not isinstance(revision, int) or isinstance(revision, bool):
169
+ out.append(f'theme revision {revision!r} is not an integer')
170
+ elif revisions.get(str(revision)) != styling_digest(doc):
171
+ out.append(f'theme revision {revision}: the styling content changed without a new revision '
172
+ f'(record {styling_digest(doc)} under a new revision)')
173
+ elif max(int(r) for r in revisions) != revision:
174
+ out.append(f'theme revision {revision} is not the newest recorded revision')
175
+ if list(doc['tiers']) != list(TIERS):
176
+ out.append(f'tiers {list(doc["tiers"])} != {list(TIERS)}')
177
+ if list(theme.get('variants', ())) != list(VARIANTS):
178
+ out.append(f'variants {theme.get("variants")} != {list(VARIANTS)}')
179
+ known = set(roles) | set(backgrounds)
180
+ for role, source in backgrounds.items():
181
+ if source not in roles:
182
+ out.append(f'background {role} takes {source}, which is no role')
183
+ for role in painted:
184
+ if role not in known:
185
+ out.append(f'painted role {role} is neither a role nor a background')
186
+ tiers = doc['tiers']
187
+ for variant in VARIANTS:
188
+ values = tiers['truecolor'].get(variant, {})
189
+ if list(values) != list(roles):
190
+ missing, extra = [r for r in roles if r not in values], [r for r in values if r not in roles]
191
+ out.append(f'truecolor {variant}: roles differ from roles (missing {missing}, extra {extra})')
192
+ for role, value in values.items():
193
+ if rgba(value) is None and shadow(value) is None:
194
+ out.append(f'truecolor {variant} {role}: {value!r} is neither a hex colour nor a shadow')
195
+ indexes = tiers['256'].get(variant, {})
196
+ if sorted(indexes) != sorted(painted):
197
+ out.append(f'256 {variant}: roles differ from painted roles (missing '
198
+ f'{[r for r in painted if r not in indexes]}, extra {[r for r in indexes if r not in painted]})')
199
+ slots = tiers['palette16'].get(variant, [])
200
+ if len(slots) != 16 or any(rgba(s) is None for s in slots):
201
+ out.append(f'palette16 {variant}: not sixteen hex colours')
202
+ for slot, role in tiers['palette16']['slot_roles'].items():
203
+ for variant in VARIANTS:
204
+ if tiers['palette16'][variant][int(slot)] != tiers['truecolor'][variant].get(role):
205
+ out.append(f'palette16 {variant} slot {slot} is not its role {role}')
206
+ sgr16 = tiers['16']['sgr']
207
+ if sorted(sgr16) != sorted(r for r in painted if r not in backgrounds):
208
+ out.append('16: the SGR table does not cover every painted foreground role')
209
+ for role in tiers['16']['dim_roles'] + tiers['none']['bold']:
210
+ if role not in painted:
211
+ out.append(f'16/none: {role} is not a painted role')
212
+ for table in GLYPH_TABLES:
213
+ for key, glyph in doc['glyphs'][table].items():
214
+ if glyph['tone'] not in painted:
215
+ out.append(f'glyph {table}.{key}: tone {glyph["tone"]} is not a painted role')
216
+ if not all(' ' <= c <= '~' for c in glyph['ascii']):
217
+ out.append(f'glyph {table}.{key}: ASCII twin {glyph["ascii"]!r} is not 7-bit printable')
218
+ for level, role in doc['text'].items():
219
+ if role not in roles:
220
+ out.append(f'text {level}: {role} is no role')
221
+ out += semantic_problems(doc)
222
+ out += contrast_problems(doc)
223
+ out += number_problems(styling_content(doc))
224
+ out += identifier_problems(doc)
225
+ projections = doc['projections']
226
+ for name in ('css_aliases', 'zellij_slots'):
227
+ out += [f'projection {name}: {alias} -> {role}, which is no role'
228
+ for alias, role in projections[name].items() if role not in roles]
229
+ out += [f'projection docs_roles: {role} is no role' for role in projections['docs_roles'] if role not in roles]
230
+ out += [f'projection sh_names: {role} is not a painted role' for role in projections['sh_names'] if role not in painted]
231
+ return out
232
+
233
+
234
+ def semantic_problems(doc):
235
+ """Every semantic state names a painted role and carries a cue that survives colour removal; states whose glyph
236
+ cues share a glyph table (one row slot) stay distinct in BOTH glyph modes; a glyph cue is drawn in the state's
237
+ own tone (unless the state is a background, whose glyph is the foreground on it)."""
238
+ out, painted, backgrounds = [], doc['painted_roles'], doc['backgrounds']
239
+ by_table = {}
240
+ for state, entry in doc['semantics'].items():
241
+ role = entry['role']
242
+ if role not in painted:
243
+ out.append(f'semantic {state}: role {role} is not a painted role')
244
+ if not entry['cues']:
245
+ out.append(f'semantic {state}: no cue survives colour removal')
246
+ for cue in entry['cues']:
247
+ (kind, ref), = cue.items()
248
+ if kind == 'glyph':
249
+ glyph = glyph_of(doc, ref)
250
+ if glyph is None:
251
+ out.append(f'semantic {state}: glyph cue {ref} names no glyph')
252
+ continue
253
+ if glyph['tone'] != role and role not in backgrounds:
254
+ out.append(f'semantic {state}: glyph {ref} is drawn in {glyph["tone"]}, not {role}')
255
+ by_table.setdefault(ref.partition('.')[0], []).append((state, glyph))
256
+ elif kind == 'label' and label_of(doc, ref) is None:
257
+ out.append(f'semantic {state}: label cue {ref} names no label')
258
+ elif kind == 'text' and ref not in CUE_TEXT:
259
+ out.append(f'semantic {state}: text cue {ref!r} is not one of {list(CUE_TEXT)}')
260
+ for table, members in by_table.items():
261
+ for mode in ('unicode', 'ascii'):
262
+ seen = {}
263
+ for state, glyph in members:
264
+ if glyph[mode] in seen and seen[glyph[mode]] != state:
265
+ out.append(f'semantic {seen[glyph[mode]]} and {state}: the same {mode} glyph {glyph[mode]!r} in '
266
+ f'the {table} slot, so colour alone tells them apart')
267
+ seen.setdefault(glyph[mode], state)
268
+ return out
269
+
270
+
271
+ def number_problems(value, where='content'):
272
+ """Every number in the digested content in the one form all JSON encoders print alike: an integral value written
273
+ as a float (`3.0`), a boolean where a number belongs aside, or a non-finite float is refused."""
274
+ if isinstance(value, dict):
275
+ return [p for key, item in value.items() for p in number_problems(item, f'{where}.{key}')]
276
+ if isinstance(value, list):
277
+ return [p for i, item in enumerate(value) for p in number_problems(item, f'{where}[{i}]')]
278
+ if isinstance(value, float) and (not math.isfinite(value) or value.is_integer()):
279
+ return [f'{where}: {value!r} is not in canonical number form (write an integral value as an integer, '
280
+ 'so every client recomputes the same digest)']
281
+ return []
282
+
283
+
284
+ # Identifiers the projections cannot use for a source name. Rust variants are UpperCamelCase, so only `Self` of its
285
+ # keywords can arise; Swift cases are lowerCamelCase, so every declaration, statement and expression keyword can,
286
+ # plus the members a String/CaseIterable enum already has.
287
+ RUST_RESERVED = frozenset(('Self',))
288
+ SWIFT_RESERVED = frozenset((
289
+ 'associatedtype', 'borrowing', 'class', 'consuming', 'deinit', 'enum', 'extension', 'fileprivate', 'func', 'import',
290
+ 'init', 'inout', 'internal', 'let', 'nonisolated', 'open', 'operator', 'private', 'precedencegroup', 'protocol',
291
+ 'public', 'rethrows', 'static', 'struct', 'subscript', 'typealias', 'var', 'break', 'case', 'catch', 'continue',
292
+ 'default', 'defer', 'do', 'else', 'fallthrough', 'for', 'guard', 'if', 'in', 'repeat', 'return', 'throw', 'switch',
293
+ 'where', 'while', 'as', 'await', 'false', 'is', 'nil', 'self', 'super', 'throws', 'true', 'try',
294
+ 'allCases', 'rawValue', 'hashValue'))
295
+ IDENTIFIER = re.compile(r'^[A-Za-z][A-Za-z0-9]*$')
296
+
297
+
298
+ def identifier_problems(doc):
299
+ """Every source name the Rust and Swift projections turn into an enum case is a plain identifier, not a reserved
300
+ word of that language, and distinct from its siblings after the case conversion (`a--b` and `a-b` both become
301
+ `aB`)."""
302
+ out = []
303
+ enums = {'Role': doc['roles'], 'Painted': doc['painted_roles'], 'TextLevel': list(doc['text']),
304
+ 'SemanticState': list(doc['semantics'])}
305
+ for enum, names in enums.items():
306
+ for language, upper, reserved in (('Rust', True, RUST_RESERVED), ('Swift', False, SWIFT_RESERVED)):
307
+ seen = {}
308
+ for name in names:
309
+ ident = camel(name, upper)
310
+ if not IDENTIFIER.match(ident):
311
+ out.append(f'{enum} {name!r}: the {language} identifier {ident!r} is not a plain identifier')
312
+ elif ident in reserved:
313
+ out.append(f'{enum} {name!r}: the {language} identifier {ident!r} is a reserved word')
314
+ if seen.get(ident, name) != name:
315
+ out.append(f'{enum} {seen[ident]!r} and {name!r}: both become the {language} identifier {ident!r}')
316
+ seen.setdefault(ident, name)
317
+ return out
318
+
319
+
320
+ def contrast_problems(doc):
321
+ out = []
322
+ for rule in doc['contrast']:
323
+ for variant in VARIANTS:
324
+ for fg in rule['fg']:
325
+ for bg in rule['bg']:
326
+ try:
327
+ a, b = resolve_ref(doc, variant, fg), resolve_ref(doc, variant, bg)
328
+ except (KeyError, IndexError, ValueError):
329
+ out.append(f'contrast {variant}: {fg} on {bg} names no colour')
330
+ continue
331
+ if rgba(a) is None or rgba(b) is None or rgba(a)[3] != 255 or rgba(b)[3] != 255:
332
+ out.append(f'contrast {variant}: {fg} on {bg} is not an opaque colour pair')
333
+ continue
334
+ ratio = contrast_ratio(a, b)
335
+ if ratio < rule['min']:
336
+ out.append(f'contrast {variant}: {fg} {a} on {bg} {b} is {ratio:.2f}:1, below {rule["min"]}:1')
337
+ return out
338
+
339
+
340
+ REQUIRED = ('theme', 'roles', 'painted_roles', 'backgrounds', 'vivid_tiers', 'tiers', 'glyph_modes', 'glyphs', 'labels',
341
+ 'text', 'semantics', 'contrast', 'projections')
342
+
343
+
344
+ def validate(doc):
345
+ missing = [key for key in REQUIRED if key not in doc]
346
+ if doc.get('schema') != SCHEMA or missing:
347
+ raise TokenError(f'lanes/tokens/tokens.v1.json: schema {doc.get("schema")!r} (want {SCHEMA}), missing {missing}')
348
+ found = problems(doc)
349
+ if found:
350
+ raise TokenError('lanes/tokens/tokens.v1.json:\n ' + '\n '.join(found))
351
+ return doc
352
+
353
+
354
+ # ------------------------------------------------------------------ resolution
355
+ def sgr(doc, tier, variant, role, dim16=ESC + '[90m'):
356
+ """The complete SGR escape a terminal emits for one painted role (tokens.py's sgr_table contract)."""
357
+ tiers, backgrounds = doc['tiers'], doc['backgrounds']
358
+ bold = BOLD if role in tiers['none']['bold'] else ''
359
+ layer = 48 if role in backgrounds else 38
360
+ if tier == 'none':
361
+ return bold
362
+ if tier == '16':
363
+ if role in backgrounds:
364
+ return ''
365
+ return dim16 if role in tiers['16']['dim_roles'] else f'{ESC}[{tiers["16"]["sgr"][role]}m'
366
+ if tier == '256':
367
+ return bold + f'{ESC}[{layer};5;{tiers["256"][variant][role]}m'
368
+ r, g, b, _a = rgba(colour_of(doc, variant, role))
369
+ return bold + f'{ESC}[{layer};2;{r};{g};{b}m'
370
+
371
+
372
+ def dim16_sgr(doc):
373
+ return {name: f'{ESC}[{code}m' for name, code in doc['tiers']['16']['dim_sgr'].items()}
374
+
375
+
376
+ def resolved(doc):
377
+ """The resolved table: the source's tables in the shapes tokens.py exposes, plus every SGR escape it emits."""
378
+ tiers, glyph = doc['tiers'], lambda table: {k: [g['unicode'], g['ascii'], g['tone']] for k, g in table.items()} # noqa: E731
379
+ return {
380
+ 'schema': RESOLVED_SCHEMA,
381
+ 'notice': NOTICE,
382
+ 'theme': {'id': doc['theme']['id'], 'revision': doc['theme']['revision'], 'digest': styling_digest(doc),
383
+ 'variants': list(VARIANTS), 'platform_names': doc['theme']['platform_names']},
384
+ 'tables': {
385
+ 'roles': doc['roles'], 'tokens': {v: tiers['truecolor'][v] for v in VARIANTS},
386
+ 'backgrounds': doc['backgrounds'], 'painted': doc['painted_roles'], 'vivid': doc['vivid_tiers'],
387
+ 'ansi16': tiers['16']['sgr'], 'xterm256': {v: tiers['256'][v] for v in VARIANTS},
388
+ 'palette16': {v: tiers['palette16'][v] for v in VARIANTS}, 'palette16_roles': tiers['palette16']['slot_roles'],
389
+ 'agent_glyphs': glyph(doc['glyphs']['agent']), 'glyphs': glyph(doc['glyphs']['stream']),
390
+ 'marks': glyph(doc['glyphs']['marks']), 'economy_tail': glyph(doc['glyphs']['economy']),
391
+ 'glyph_modes': doc['glyph_modes'], 'mobile_agent_labels': doc['labels']['mobile_agent'],
392
+ 'labels': doc['labels'], 'aliases': doc['projections']['css_aliases'],
393
+ 'zj': doc['projections']['zellij_slots'], 'docs_roles': doc['projections']['docs_roles'],
394
+ 'sh_names': doc['projections']['sh_names'], 'text': doc['text'], 'semantics': doc['semantics'],
395
+ 'contrast': doc['contrast'],
396
+ },
397
+ 'sgr': {
398
+ 'bold': BOLD, 'reset': RESET,
399
+ 'tiers': {tier: {v: {role: sgr(doc, tier, v, role) for role in doc['painted_roles']} for v in VARIANTS}
400
+ for tier in SGR_TIERS},
401
+ 'dim16': {'roles': tiers['16']['dim_roles'], **dim16_sgr(doc)},
402
+ },
403
+ }
404
+
405
+
406
+ def facts(doc):
407
+ """The parity facts: one tab-separated line per styling fact, in a fixed order. Every client projection derives
408
+ the lines of the kinds it carries from its own compiled values; equality with these is A26's comparison."""
409
+ tiers, out = doc['tiers'], []
410
+ theme = doc['theme']
411
+ out += [('theme', 'id', theme['id']), ('theme', 'revision', str(theme['revision'])),
412
+ ('theme', 'digest', styling_digest(doc))]
413
+ out += [('role', '%02d' % i, role) for i, role in enumerate(doc['roles'])]
414
+ out += [('painted', '%02d' % i, role) for i, role in enumerate(doc['painted_roles'])]
415
+ out += [('background', role, source) for role, source in doc['backgrounds'].items()]
416
+ out += [('vivid', tier) for tier in doc['vivid_tiers']]
417
+ out += [('text', level, role) for level, role in doc['text'].items()]
418
+ for variant in VARIANTS:
419
+ for role in doc['roles']:
420
+ value = tiers['truecolor'][variant][role]
421
+ out.append(('hex', variant, role, value))
422
+ if rgba(value) is not None:
423
+ out.append(('rgba', variant, role, ','.join(map(str, rgba(value)))))
424
+ else:
425
+ x, y, blur, colour = shadow(value)
426
+ out.append(('shadow', variant, role, ','.join(map(str, (x, y, blur) + colour))))
427
+ for tier in SGR_TIERS:
428
+ for variant in VARIANTS:
429
+ out += [('sgr', tier, variant, role, escape(sgr(doc, tier, variant, role))) for role in doc['painted_roles']]
430
+ faint = dim16_sgr(doc)['LANES_DIM=2']
431
+ for variant in VARIANTS:
432
+ out += [('sgr', '16-dim2', variant, role, escape(faint if role in tiers['16']['dim_roles'] else
433
+ sgr(doc, '16', variant, role))) for role in doc['painted_roles']]
434
+ for variant in VARIANTS:
435
+ out += [('xterm256', variant, role, str(tiers['256'][variant][role])) for role in doc['painted_roles']]
436
+ out += [('ansi16', role, code) for role, code in tiers['16']['sgr'].items()]
437
+ for variant in VARIANTS:
438
+ out += [('palette16', variant, '%02d' % i, value) for i, value in enumerate(tiers['palette16'][variant])]
439
+ out += [('palette16-role', '%02d' % int(slot), role) for slot, role in tiers['palette16']['slot_roles'].items()]
440
+ for table in GLYPH_TABLES:
441
+ out += [('glyph', table, key, g['unicode'], g['ascii'], g['tone']) for key, g in doc['glyphs'][table].items()]
442
+ out += [('label', table, key, text) for table, labels in doc['labels'].items() for key, text in labels.items()]
443
+ for state, entry in doc['semantics'].items():
444
+ out.append(('semantic', state, entry['role']))
445
+ out += [('cue', state) + next(iter(cue.items())) for cue in entry['cues']]
446
+ for rule in doc['contrast']:
447
+ for variant in VARIANTS:
448
+ out += [('contrast', variant, fg, bg, repr(float(rule['min']))) for fg in rule['fg'] for bg in rule['bg']]
449
+ for line in out:
450
+ if any('\t' in field or '\n' in field or not field for field in line):
451
+ raise TokenError(f'parity fact {line!r}: a field is empty or holds a tab or newline')
452
+ return out
453
+
454
+
455
+ def escape(sequence):
456
+ """An SGR escape as fixture text: ESC written as `\\e`, so the fixture stays printable."""
457
+ return sequence.replace(ESC, '\\e') if sequence else '-'
458
+
459
+
460
+ # ------------------------------------------------------------------ renderers
461
+ def render_resolved(doc):
462
+ return json.dumps(resolved(doc), indent=1, ensure_ascii=False) + '\n'
463
+
464
+
465
+ def render_parity(doc):
466
+ head = [f'# {PARITY_SCHEMA} - {NOTICE}.',
467
+ '# One styling fact per line, tab-separated: kind, keys, value. ESC is written \\e; an empty escape is -.',
468
+ '# Each client derives the lines of the kinds it carries from its own compiled values and must equal these.']
469
+ return '\n'.join(head + ['\t'.join(line) for line in facts(doc)]) + '\n'
470
+
471
+
472
+ def css_var(role):
473
+ return f'--lanes-{role}'
474
+
475
+
476
+ # tokens.css is a floor under every surface stylesheet: each selector sits in `:where()`, so it has zero specificity and
477
+ # any surface block that sets the same property (the phone's `html.lanes-mobile` block in mobile.css) wins whatever
478
+ # the load order. The variant follows the appearance authority the page already has: the phone shell's `data-zj-theme`
479
+ # (the principal's appearance, IC section 5.1; `light` paints light, any other value dark) and, on a page with no such
480
+ # authority, the system appearance. The phone shell (`html.lanes-mobile`) never takes the system appearance, even before
481
+ # its attribute is set: mobile.css paints it dark then. No second attribute contract.
482
+ CSS_ROOT = ':where(:root)'
483
+ CSS_SYSTEM_LIGHT = ':where(:root:not([data-zj-theme]):not(.lanes-mobile))'
484
+ CSS_DEVICE_LIGHT = ':where(:root[data-zj-theme="light"])'
485
+
486
+
487
+ def render_css(doc):
488
+ """Every role per variant as `--lanes-<role>`, the sixteen defined slots as `--lanes-ansi-<n>`, the theme id and
489
+ revision, the text hierarchy and the semantic states as aliases. Dark by default; light under the system's light
490
+ appearance on a page without an appearance authority, and always under `data-zj-theme="light"`. Zero
491
+ specificity throughout (CSS_ROOT and its siblings above)."""
492
+ tiers = doc['tiers']
493
+
494
+ def values(variant, indent):
495
+ lines = [f'{indent}{css_var(role)}: {tiers["truecolor"][variant][role]};' for role in doc['roles']]
496
+ lines += [f'{indent}--lanes-ansi-{i}: {value};' for i, value in enumerate(tiers['palette16'][variant])]
497
+ return lines + [f'{indent}color-scheme: {variant};']
498
+
499
+ theme = doc['theme']
500
+ out = [f'/* lanes/web/tokens.css - {NOTICE}.',
501
+ f' Theme {theme["id"]} revision {theme["revision"]} (styling sha256 {styling_digest(doc)}).',
502
+ ' Zero specificity: a surface stylesheet that sets the same property wins. Variant: data-zj-theme, else',
503
+ ' the system appearance (never on html.lanes-mobile). */',
504
+ CSS_ROOT + ' {', f' --lanes-theme-id: "{theme["id"]}";', f' --lanes-theme-revision: {theme["revision"]};']
505
+ out += values('dark', ' ') + ['}', '@media (prefers-color-scheme: light) {', f' {CSS_SYSTEM_LIGHT} {{']
506
+ out += values('light', ' ') + [' }', '}', CSS_DEVICE_LIGHT + ' {'] + values('light', ' ') + ['}']
507
+ out += [CSS_ROOT + ' {']
508
+ out += [f' --lanes-text-{level}: var({css_var(role)});' for level, role in doc['text'].items()]
509
+ out += [f' --lanes-state-{state}: var({css_var(doc["backgrounds"].get(entry["role"], entry["role"]))});'
510
+ for state, entry in doc['semantics'].items()]
511
+ out.append('}')
512
+ return '\n'.join(out) + '\n'
513
+
514
+
515
+ def camel(name, upper):
516
+ parts = re.split(r'[-_]', name)
517
+ head = parts[0].capitalize() if upper else parts[0]
518
+ return head + ''.join(p.capitalize() for p in parts[1:])
519
+
520
+
521
+ def rust_str(text):
522
+ out = []
523
+ for c in text:
524
+ if c == ESC:
525
+ out.append('\\x1b')
526
+ elif c in '"\\':
527
+ out.append('\\' + c)
528
+ elif ' ' <= c <= '~' or ord(c) > 127:
529
+ out.append(c)
530
+ else:
531
+ raise TokenError(f'no Rust literal form for {c!r}')
532
+ return '"' + ''.join(out) + '"'
533
+
534
+
535
+ RUST_TIERS = {'truecolor': 'Truecolor', '256': 'Xterm256', '16': 'Ansi16', 'none': 'NoColour'}
536
+
537
+
538
+ def rust_items(head, items, indent, tail=','):
539
+ """`head(items…)` (head '' for a tuple) the way rustfmt lays it out: on one line while the arguments fit its
540
+ 60-column call width and the line its 100 columns, else one argument per line with a trailing comma."""
541
+ inner = ', '.join(items)
542
+ line = f'{indent}{head}({inner}){tail}'
543
+ if len(inner) <= 60 and len(line) <= 100:
544
+ return [line]
545
+ return [f'{indent}{head}('] + [f'{indent} {item},' for item in items] + [f'{indent}){tail}']
546
+
547
+
548
+ def rust_enum(name, doc_line, variants, names):
549
+ """A fieldless enum with ALL, COUNT and name() (the source spelling)."""
550
+ out = [f'/// {doc_line}', '#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]', f'pub enum {name} {{']
551
+ out += [f' {v},' for v in variants]
552
+ out += ['}', '', f'impl {name} {{', f' /// Every {name}, in source order.']
553
+ if len(f' pub const ALL: [{name}; {len(variants)}] = [' + ', '.join(f'{name}::{v}' for v in variants) + '];') <= 100 \
554
+ and len(', '.join(f'{name}::{v}' for v in variants)) + 2 <= 60:
555
+ out.append(f' pub const ALL: [{name}; {len(variants)}] = [' + ', '.join(f'{name}::{v}' for v in variants) + '];')
556
+ else:
557
+ out.append(f' pub const ALL: [{name}; {len(variants)}] = [')
558
+ out += [f' {name}::{v},' for v in variants]
559
+ out.append(' ];')
560
+ out += [f' /// The number of {name} values.', f' pub const COUNT: usize = {len(variants)};', '',
561
+ ' /// The spelling the token source uses.', ' pub const fn name(self) -> &\'static str {',
562
+ ' match self {']
563
+ out += [f' {name}::{v} => {rust_str(n)},' for v, n in zip(variants, names)]
564
+ out += [' }', ' }', '}']
565
+ return out
566
+
567
+
568
+ def render_rust(doc):
569
+ tiers, theme = doc['tiers'], doc['theme']
570
+ roles, painted = doc['roles'], doc['painted_roles']
571
+ role_v = {r: camel(r, True) for r in roles}
572
+ painted_v = {r: camel(r, True) for r in painted}
573
+ out = [f'// @{NOTICE}.', '// Regenerate with `python3 lanes/tokens/generate.py --write`.', '',
574
+ '/// The theme id every client shares.', f'pub const THEME_ID: &str = {rust_str(theme["id"])};',
575
+ '/// The theme revision every client shares.', f'pub const THEME_REVISION: u32 = {theme["revision"]};',
576
+ '/// The sha256 of the revision\'s styling content (tokens.v1.schema.json).',
577
+ f'pub const THEME_DIGEST: &str = {rust_str(styling_digest(doc))};', '']
578
+ out += rust_enum('Variant', 'A theme variant.', [camel(v, True) for v in VARIANTS], VARIANTS) + ['']
579
+ out += rust_enum('Tier', 'A terminal colour tier (`palette16` is a defined palette, not an SGR tier).',
580
+ [RUST_TIERS[t] for t in SGR_TIERS], SGR_TIERS) + ['']
581
+ out += rust_enum('Role', 'A semantic colour role.', [role_v[r] for r in roles], roles) + ['']
582
+ out += rust_enum('Painted', 'A role the terminal paints: the foreground roles and the background roles.',
583
+ [painted_v[r] for r in painted], painted) + ['']
584
+ out += rust_enum('GlyphTable', 'A glyph table: one row slot each.', [camel(t, True) for t in GLYPH_TABLES],
585
+ GLYPH_TABLES) + ['']
586
+ out += rust_enum('TextLevel', 'A level of the text hierarchy.', [camel(t, True) for t in doc['text']],
587
+ list(doc['text'])) + ['']
588
+ states = list(doc['semantics'])
589
+ out += rust_enum('SemanticState', 'A semantic state every client shares.', [camel(s, True) for s in states],
590
+ states) + ['']
591
+ background_roles = ' | '.join(f'Painted::{painted_v[r]}' for r in painted if r in doc['backgrounds'])
592
+ dim_roles = ' | '.join(f'Painted::{painted_v[r]}' for r in tiers['16']['dim_roles'])
593
+ out += ['impl Painted {', ' /// Whether the role paints a background (`48;…`) rather than text (`38;…`).',
594
+ ' pub const fn is_background(self) -> bool {']
595
+ out += rust_items('matches!', ['self', background_roles], ' ', tail='')
596
+ out += [' }', '', ' /// The role whose truecolor value this painted role takes.',
597
+ ' pub const fn colour_role(self) -> Role {', ' match self {']
598
+ out += [f' Painted::{painted_v[r]} => Role::{role_v[doc["backgrounds"].get(r, r)]},' for r in painted]
599
+ out += [' }', ' }', '', ' /// Whether 16-colour mode paints the role with the dim escape.',
600
+ ' pub const fn is_dim16(self) -> bool {']
601
+ out += rust_items('matches!', ['self', dim_roles], ' ', tail='')
602
+ out += [' }', '}', '']
603
+ out += ['/// Every role\'s truecolor value per variant, in `Role::ALL` order (`HEX[variant][role]`).',
604
+ 'pub const HEX: [[(Role, &str); Role::COUNT]; Variant::COUNT] = [']
605
+ for variant in VARIANTS:
606
+ out.append(' [')
607
+ out += [f' (Role::{role_v[r]}, {rust_str(tiers["truecolor"][variant][r])}),' for r in roles]
608
+ out.append(' ],')
609
+ out += ['];', '', '/// The complete SGR escape per tier, variant and painted role, in `Painted::ALL` order.',
610
+ '/// 16-colour dim roles carry the default dim (`SGR_DIM16_DEFAULT`).',
611
+ 'pub const SGR: [[[(Painted, &str); Painted::COUNT]; Variant::COUNT]; Tier::COUNT] = [']
612
+ for tier in SGR_TIERS:
613
+ out.append(' [')
614
+ for variant in VARIANTS:
615
+ out.append(' [')
616
+ out += [f' (Painted::{painted_v[r]}, {rust_str(sgr(doc, tier, variant, r))}),' for r in painted]
617
+ out.append(' ],')
618
+ out.append(' ],')
619
+ dims = dim16_sgr(doc)
620
+ out += ['];', '', '/// Bold.', f'pub const SGR_BOLD: &str = {rust_str(BOLD)};', '/// Reset.',
621
+ f'pub const SGR_RESET: &str = {rust_str(RESET)};', '/// The 16-colour dim escape by default.',
622
+ f'pub const SGR_DIM16_DEFAULT: &str = {rust_str(dims["default"])};',
623
+ '/// The 16-colour dim escape under `LANES_DIM=2`.',
624
+ f'pub const SGR_DIM16_FAINT: &str = {rust_str(dims["LANES_DIM=2"])};', '',
625
+ '/// The fixed xterm-256 index per variant and painted role, in `Painted::ALL` order.',
626
+ 'pub const XTERM256: [[(Painted, u8); Painted::COUNT]; Variant::COUNT] = [']
627
+ for variant in VARIANTS:
628
+ out.append(' [')
629
+ out += [f' (Painted::{painted_v[r]}, {tiers["256"][variant][r]}),' for r in painted]
630
+ out.append(' ],')
631
+ out += ['];', '', '/// The 16-colour SGR parameter of each painted foreground role (the user\'s own palette).',
632
+ f'pub const ANSI16: [(Painted, &str); {len(tiers["16"]["sgr"])}] = [']
633
+ out += [f' (Painted::{painted_v[r]}, {rust_str(code)}),' for r, code in tiers['16']['sgr'].items()]
634
+ out += ['];', '', '/// Lanes\' own sixteen slots per variant (Zellij web client, Ghostty).',
635
+ 'pub const PALETTE16: [[(u8, &str); 16]; Variant::COUNT] = [']
636
+ for variant in VARIANTS:
637
+ out.append(' [')
638
+ out += [f' ({i}, {rust_str(v)}),' for i, v in enumerate(tiers['palette16'][variant])]
639
+ out.append(' ],')
640
+ slot_roles = tiers['palette16']['slot_roles']
641
+ out += ['];', '', '/// The slots that are a role.', f'pub const PALETTE16_ROLES: [(u8, Role); {len(slot_roles)}] = [']
642
+ out += [f' ({int(s)}, Role::{role_v[r]}),' for s, r in slot_roles.items()]
643
+ out += ['];', '', '/// A glyph and its ASCII twin, drawn in its tone.', '#[derive(Clone, Copy, Debug, PartialEq, Eq)]',
644
+ 'pub struct Glyph {', ' /// The key the source names it by.', ' pub key: &\'static str,',
645
+ ' /// The Unicode glyph.', ' pub unicode: &\'static str,',
646
+ ' /// The 7-bit ASCII twin (`LANES_GLYPHS=ascii`).', ' pub ascii: &\'static str,',
647
+ ' /// The painted role it is drawn in.', ' pub tone: Painted,', '}', '',
648
+ 'const fn glyph_entry(', ' key: &\'static str,', ' unicode: &\'static str,', ' ascii: &\'static str,',
649
+ ' tone: Painted,', ') -> Glyph {',
650
+ ' Glyph {', ' key,', ' unicode,', ' ascii,', ' tone,', ' }', '}', '']
651
+ for table in GLYPH_TABLES:
652
+ glyphs = doc['glyphs'][table]
653
+ out += [f'/// The `{table}` glyph table, in source order.',
654
+ f'pub const {table.upper()}_GLYPHS: [Glyph; {len(glyphs)}] = [']
655
+ for k, g in glyphs.items():
656
+ out += rust_items('glyph_entry', [rust_str(k), rust_str(g['unicode']), rust_str(g['ascii']),
657
+ f'Painted::{painted_v[g["tone"]]}'], ' ')
658
+ out += ['];', '']
659
+ labels = [(t, k, text) for t, table in doc['labels'].items() for k, text in table.items()]
660
+ out += ['/// Every label as (table, key, text).', f'pub const LABELS: [(&str, &str, &str); {len(labels)}] = [']
661
+ for t, k, text in labels:
662
+ out += rust_items('', [rust_str(t), rust_str(k), rust_str(text)], ' ')
663
+ out += ['];', '']
664
+ out += ['impl Tier {', ' /// Whether Lanes defines the colours of this tier (its palette is spent here).',
665
+ ' pub const fn is_vivid(self) -> bool {']
666
+ out += rust_items('matches!', ['self', ' | '.join(f'Tier::{RUST_TIERS[t]}' for t in doc['vivid_tiers'])], ' ',
667
+ tail='')
668
+ out += [' }', '}', '', 'impl GlyphTable {', ' /// The glyphs of this table, in source order.',
669
+ " pub const fn glyphs(self) -> &'static [Glyph] {", ' match self {']
670
+ out += [f' GlyphTable::{camel(t, True)} => &{t.upper()}_GLYPHS,' for t in GLYPH_TABLES]
671
+ out += [' }', ' }', '}', '', 'impl TextLevel {', ' /// The role this level of text paints.',
672
+ ' pub const fn role(self) -> Role {', ' match self {']
673
+ out += [f' TextLevel::{camel(level, True)} => Role::{role_v[r]},' for level, r in doc['text'].items()]
674
+ out += [' }', ' }', '}', '', 'impl SemanticState {', ' /// The painted role of this state.',
675
+ ' pub const fn role(self) -> Painted {', ' match self {']
676
+ out += [f' SemanticState::{camel(st, True)} => Painted::{painted_v[e["role"]]},'
677
+ for st, e in doc['semantics'].items()]
678
+ out += [' }', ' }', '}', '']
679
+ cues = [(s, k, ref) for s, e in doc['semantics'].items() for cue in e['cues'] for k, ref in cue.items()]
680
+ out += ['/// The no-colour cues of each semantic state as (state, kind, reference): kind `glyph`',
681
+ '/// (`<table>.<key>`), `label` (`<table>.<key>`) or `text` (`name`, `reason`, `legend`).',
682
+ f'pub const CUES: [(SemanticState, &str, &str); {len(cues)}] = [']
683
+ for s, k, ref in cues:
684
+ out += rust_items('', [f'SemanticState::{camel(s, True)}', rust_str(k), rust_str(ref)], ' ')
685
+ out.append('];')
686
+ return '\n'.join(out) + '\n'
687
+
688
+
689
+ def swift_str(text):
690
+ out = []
691
+ for c in text:
692
+ if c in '"\\':
693
+ out.append('\\' + c)
694
+ elif c == '\t':
695
+ out.append('\\t')
696
+ elif ' ' <= c <= '~' or ord(c) > 127:
697
+ out.append(c)
698
+ else:
699
+ raise TokenError(f'no Swift literal form for {c!r}')
700
+ return '"' + ''.join(out) + '"'
701
+
702
+
703
+ def swift_enum(name, doc_line, names, indent=' '):
704
+ out = [f'{indent}/// {doc_line}', f'{indent}public enum {name}: String, CaseIterable, Sendable {{']
705
+ for n in names:
706
+ case = camel(n, False)
707
+ out.append(f'{indent} case {case}' + (f' = {swift_str(n)}' if case != n else ''))
708
+ return out + [f'{indent}}}']
709
+
710
+
711
+ def render_swift(doc):
712
+ tiers, theme = doc['tiers'], doc['theme']
713
+ roles, painted = doc['roles'], doc['painted_roles']
714
+ out = [f'// {NOTICE}.', '// Regenerate with `python3 lanes/tokens/generate.py --write`.', '',
715
+ '/// The Lanes semantic design tokens (integrated cockpit section 5.1, witness A26): the shared theme id and',
716
+ '/// revision, every role in both variants, Lanes\' sixteen-slot palette, the glyph twins and labels, the text',
717
+ '/// hierarchy and the semantic states with the cues that carry them without colour. Foundation-free values;',
718
+ '/// the app maps them to SwiftUI colours. `LanesTokensParityTests` holds them to `parity.v1.tsv`.',
719
+ 'public enum LanesTokens {', ' /// The theme id every client shares.',
720
+ f' public static let themeID = {swift_str(theme["id"])}', ' /// The theme revision every client shares.',
721
+ f' public static let themeRevision = {theme["revision"]}',
722
+ ' /// The sha256 of the revision\'s styling content.',
723
+ f' public static let themeDigest = {swift_str(styling_digest(doc))}', '']
724
+ out += swift_enum('Variant', 'A theme variant.', VARIANTS) + ['']
725
+ out += swift_enum('Role', 'A semantic colour role.', roles) + ['']
726
+ out += swift_enum('Painted', 'A role the terminal paints; `selected` is a background.', painted) + ['']
727
+ out += swift_enum('TextLevel', 'A level of the text hierarchy.', list(doc['text'])) + ['']
728
+ out += swift_enum('SemanticState', 'A semantic state every client shares.', list(doc['semantics'])) + ['']
729
+ out += [' /// An sRGB colour, each channel 0-255.', ' public struct RGBA: Equatable, Sendable {',
730
+ ' public let red: Int', ' public let green: Int', ' public let blue: Int',
731
+ ' public let alpha: Int', '', ' public init(_ red: Int, _ green: Int, _ blue: Int, _ alpha: Int) {',
732
+ ' self.red = red', ' self.green = green', ' self.blue = blue',
733
+ ' self.alpha = alpha', ' }', ' }', '',
734
+ ' /// A drop shadow: offset, blur radius and colour.', ' public struct Shadow: Equatable, Sendable {',
735
+ ' public let x: Int', ' public let y: Int', ' public let blur: Int',
736
+ ' public let color: RGBA', ' }', '',
737
+ ' /// A glyph and its ASCII twin, drawn in its tone.', ' public struct Glyph: Equatable, Sendable {',
738
+ ' public let table: String', ' public let key: String', ' public let unicode: String',
739
+ ' public let ascii: String', ' public let tone: Painted', ' }', '',
740
+ ' /// A label: (table, key) -> text.', ' public struct Label: Equatable, Sendable {',
741
+ ' public let table: String', ' public let key: String', ' public let text: String', ' }', '',
742
+ ' /// A no-colour cue: kind `glyph`, `label` or `text`, and what it names.',
743
+ ' public struct Cue: Equatable, Sendable {', ' public let kind: String',
744
+ ' public let reference: String', ' }', '',
745
+ ' /// The source value of a role: a hex colour, or the CSS shadow of `shadow`.',
746
+ ' public static func hex(_ role: Role, in variant: Variant) -> String {', ' switch (variant, role) {']
747
+ for variant in VARIANTS:
748
+ out += [f' case (.{variant}, .{camel(r, False)}): return {swift_str(tiers["truecolor"][variant][r])}' for r in roles]
749
+ out += [' }', ' }', '', ' /// The colour of a role; nil for `shadow`, which is a shadow.',
750
+ ' public static func color(_ role: Role, in variant: Variant) -> RGBA? {', ' switch (variant, role) {']
751
+ for variant in VARIANTS:
752
+ for r in roles:
753
+ value = rgba(tiers['truecolor'][variant][r])
754
+ out.append(f' case (.{variant}, .{camel(r, False)}): return ' +
755
+ ('nil' if value is None else 'RGBA(%d, %d, %d, %d)' % value))
756
+ out += [' }', ' }', '', ' /// The `shadow` role.', ' public static func shadow(in variant: Variant) -> Shadow {',
757
+ ' switch variant {']
758
+ for variant in VARIANTS:
759
+ x, y, blur, colour = shadow(tiers['truecolor'][variant]['shadow'])
760
+ out.append(f' case .{variant}: return Shadow(x: {x}, y: {y}, blur: {blur}, color: RGBA(%d, %d, %d, %d))' % colour)
761
+ out += [' }', ' }', '', ' /// The role whose colour a painted role takes (`selected` takes the accent wash).',
762
+ ' public static func colorRole(_ painted: Painted) -> Role {', ' switch painted {']
763
+ out += [f' case .{camel(r, False)}: return .{camel(doc["backgrounds"].get(r, r), False)}' for r in painted]
764
+ out += [' }', ' }', '', ' /// Lanes\' sixteen slots (the terminal palette).',
765
+ ' public static func palette16(_ variant: Variant) -> [String] {', ' switch variant {']
766
+ for variant in VARIANTS:
767
+ out.append(f' case .{variant}:')
768
+ out.append(' return [')
769
+ out += [f' {swift_str(v)},' for v in tiers['palette16'][variant]]
770
+ out.append(' ]')
771
+ slot_roles = tiers['palette16']['slot_roles']
772
+ out += [' }', ' }', '', ' /// The slots that are a role.', ' public static let palette16Roles: [Int: Role] = [']
773
+ out += [f' {int(s)}: .{camel(r, False)},' for s, r in slot_roles.items()]
774
+ out += [' ]', '', ' /// Every glyph, in source order.', ' public static let glyphs: [Glyph] = [']
775
+ for table in GLYPH_TABLES:
776
+ out += [f' Glyph(table: {swift_str(table)}, key: {swift_str(k)}, unicode: {swift_str(g["unicode"])}, '
777
+ f'ascii: {swift_str(g["ascii"])}, tone: .{camel(g["tone"], False)}),' for k, g in doc['glyphs'][table].items()]
778
+ out += [' ]', '', ' /// Every label.', ' public static let labels: [Label] = [']
779
+ out += [f' Label(table: {swift_str(t)}, key: {swift_str(k)}, text: {swift_str(text)}),'
780
+ for t, table in doc['labels'].items() for k, text in table.items()]
781
+ out += [' ]', '', ' /// The role a text level paints.', ' public static func textRole(_ level: TextLevel) -> Role {',
782
+ ' switch level {']
783
+ out += [f' case .{camel(level, False)}: return .{camel(r, False)}' for level, r in doc['text'].items()]
784
+ out += [' }', ' }', '', ' /// The painted role of a semantic state.',
785
+ ' public static func role(for state: SemanticState) -> Painted {', ' switch state {']
786
+ out += [f' case .{camel(s, False)}: return .{camel(e["role"], False)}' for s, e in doc['semantics'].items()]
787
+ out += [' }', ' }', '', ' /// The cues that carry a semantic state without colour.',
788
+ ' public static func cues(for state: SemanticState) -> [Cue] {', ' switch state {']
789
+ for s, e in doc['semantics'].items():
790
+ cues = ', '.join(f'Cue(kind: {swift_str(k)}, reference: {swift_str(ref)})' for cue in e['cues'] for k, ref in cue.items())
791
+ out.append(f' case .{camel(s, False)}: return [{cues}]')
792
+ out += [' }', ' }', '}']
793
+ return '\n'.join(out) + '\n'
794
+
795
+
796
+ RENDERERS = {'resolved': render_resolved, 'parity': render_parity, 'css': render_css, 'rust': render_rust,
797
+ 'swift': render_swift}
798
+
799
+
800
+ def render_all(doc, kinds=None):
801
+ """{kind: text} for every output (or `kinds`); TokenError when the source breaks a rule."""
802
+ validate(doc)
803
+ return {kind: RENDERERS[kind](doc) for kind in (kinds or OUTPUTS)}
804
+
805
+
806
+ def output_path(kind, lanes=LANES):
807
+ base, rel = OUTPUTS[kind]
808
+ return (Path(lanes) if base == 'lanes' else Path(lanes).parent) / rel
809
+
810
+
811
+ def in_checkout(lanes=LANES):
812
+ """Whether the lanes tree sits in a repository checkout (its parent holds the workspace `Cargo.toml`), the only
813
+ place the `repo` outputs exist. An installed or payload tree (npm/lanes ships every tracked lanes/ file, this one
814
+ included) has only the `lanes` outputs, and nothing may be written beside it."""
815
+ return (Path(lanes).parent / 'Cargo.toml').is_file()
816
+
817
+
818
+ def present_kinds(lanes=LANES, kinds=None):
819
+ """The outputs this tree carries, of `kinds` (default every output): all of them in a checkout, the `lanes` ones
820
+ elsewhere."""
821
+ wanted = tuple(kinds or OUTPUTS)
822
+ return wanted if in_checkout(lanes) else tuple(kind for kind in wanted if OUTPUTS[kind][0] == 'lanes')
823
+
824
+
825
+ def skipped_note(lanes=LANES, kinds=None):
826
+ """The one-line note naming the `repo` outputs an installed tree leaves out ('' in a checkout)."""
827
+ skipped = [display(kind) for kind in (kinds or OUTPUTS) if kind not in present_kinds(lanes, kinds)]
828
+ return f'not a checkout (no Cargo.toml beside lanes/): skipped {", ".join(skipped)}\n' if skipped else ''
829
+
830
+
831
+ def display(kind):
832
+ base, rel = OUTPUTS[kind]
833
+ return 'lanes/' + rel if base == 'lanes' else rel
834
+
835
+
836
+ def atomic_write(path, text):
837
+ """Replace `path` with `text` through a sibling temporary file and os.replace, keeping the file's mode (0644 for a
838
+ new file): a reader that opens it meanwhile (tokens.py reads the resolved table at every sidebar and notify
839
+ start) sees the old bytes or the new ones, never a truncated file."""
840
+ path = Path(path)
841
+ try:
842
+ mode = path.stat().st_mode & 0o7777
843
+ except OSError:
844
+ mode = 0o644
845
+ fd, tmp = tempfile.mkstemp(prefix='.' + path.name + '.', dir=str(path.parent))
846
+ try:
847
+ with os.fdopen(fd, 'w', encoding='utf-8', newline='') as handle:
848
+ handle.write(text)
849
+ os.chmod(tmp, mode)
850
+ os.replace(tmp, path)
851
+ except BaseException:
852
+ try:
853
+ os.unlink(tmp)
854
+ except OSError:
855
+ pass
856
+ raise
857
+
858
+
859
+ def check(lanes=LANES, kinds=None, doc=None):
860
+ """The outputs (display paths) whose committed bytes differ from what the source generates; a missing output is
861
+ drift, not a skip. Outside a checkout only the `lanes` outputs are compared (present_kinds). Raises TokenError
862
+ when the source itself is unsound."""
863
+ rendered = render_all(load(lanes) if doc is None else doc, present_kinds(lanes, kinds))
864
+ drifted = []
865
+ for kind, text in rendered.items():
866
+ try:
867
+ current = output_path(kind, lanes).read_text(encoding='utf-8')
868
+ except OSError:
869
+ current = None
870
+ if current != text:
871
+ drifted.append(display(kind))
872
+ return drifted
873
+
874
+
875
+ def reader(lanes=LANES):
876
+ """lanes/libexec/tokens.py, loaded fresh (it reads the resolved table once, at import)."""
877
+ spec = importlib.util.spec_from_file_location('lanes_tokens_reader', Path(lanes) / 'libexec' / 'tokens.py')
878
+ module = importlib.util.module_from_spec(spec)
879
+ spec.loader.exec_module(module)
880
+ return module
881
+
882
+
883
+ def write(lanes=LANES):
884
+ """Write every output this tree carries (present_kinds) atomically, then the tokens.py marker blocks. Nothing is
885
+ created outside the lanes tree unless it sits in a checkout."""
886
+ rendered = render_all(load(lanes), present_kinds(lanes))
887
+ for kind, text in rendered.items():
888
+ path = output_path(kind, lanes)
889
+ path.parent.mkdir(parents=True, exist_ok=True)
890
+ if not path.exists() or path.read_text(encoding='utf-8') != text:
891
+ atomic_write(path, text)
892
+ tokens = reader(lanes)
893
+ return tokens.main(['--write'])
894
+
895
+
896
+ def main(argv):
897
+ lanes = LANES
898
+ if argv[:1] == ['--check']:
899
+ try:
900
+ doc = load(lanes)
901
+ drifted = check(lanes, doc=doc)
902
+ except TokenError as error:
903
+ sys.stderr.write(f'{error}\n')
904
+ return 1
905
+ sys.stderr.write(skipped_note(lanes))
906
+ rendered = render_all(doc, present_kinds(lanes))
907
+ for kind, text in rendered.items():
908
+ if display(kind) in drifted:
909
+ path = output_path(kind, lanes)
910
+ current = path.read_text(encoding='utf-8') if path.exists() else ''
911
+ sys.stdout.writelines(difflib.unified_diff(current.splitlines(True), text.splitlines(True),
912
+ display(kind), display(kind) + ' (generated)'))
913
+ marker_rc = 0 if drifted else reader(lanes).main(['--check'])
914
+ return 1 if drifted or marker_rc else 0
915
+ if argv[:1] == ['--write']:
916
+ try:
917
+ sys.stderr.write(skipped_note(lanes))
918
+ return write(lanes)
919
+ except TokenError as error:
920
+ sys.stderr.write(f'{error}\n')
921
+ return 1
922
+ if argv[:1] == ['--print'] and len(argv) == 2 and argv[1] in RENDERERS:
923
+ sys.stdout.write(render_all(load(lanes), [argv[1]])[argv[1]])
924
+ return 0
925
+ sys.stderr.write('usage: generate.py --write | --check | --print ' + '|'.join(RENDERERS) + '\n')
926
+ return 2
927
+
928
+
929
+ if __name__ == '__main__':
930
+ sys.exit(main(sys.argv[1:]))