Skip to repository content1439 lines · 58.9 KB · text
tenant.openagents/omega
No repository description is available.
OpenAgents Git authority 2026-07-28T00:38:32.788Z Public web read
NIP-34 coordinate
30617:7649603503856e5148d571eac2766b288a8ff1e9e35d380337a1d2b0015b4f92:omegaMaintainersHidden in public view
References2 branches · 1 tag
Read-only clone
git clone https://openagents.com/git/tenant.openagents/omega.gitBrowse files
verify-omega-brand
1#!/usr/bin/env bash
2#
3# Omega brand gate (OMEGA-DELTA-0017, OMEGA-DELTA-0018, OMEGA-DELTA-0022,
4# OMEGA-DELTA-0031).
5#
6# Two modes:
7#
8# verify-omega-brand source tree
9# verify-omega-brand --app PATH a built Omega.app, before signing
10#
11# The packaged mode exists because a source-level check is not a packaging
12# check. 0.2.0-rc10 shipped thirteen Zed strings in a signed Info.plist and
13# three Zed logo marks in the status bar while every brand check on omega#16
14# passed, because those checks scanned the executable for three identity
15# literals and nothing had ever read Info.plist or looked at an asset.
16#
17# OMEGA-DELTA-0022 widened the inventories after 0.2.0-rc11 shipped Zed
18# artwork out of assets/images/ and a user-facing `zed:` command namespace,
19# both of which were outside OMEGA-DELTA-0018's scope while it reported green
20# about assets/icons/. The inventories here are derived from what decides what
21# ships -- the assets tree, the enums that name a path into it, and every gpui
22# action declaration -- rather than from a list of remembered places.
23#
24# OMEGA-DELTA-0031 closes the class OMEGA-DELTA-0022 named and could not
25# close: arbitrary user-facing prose. The previous string rule enforced the
26# compatibility allow-list's `blocked` claims, which is a written-down
27# denylist, so a NEW sentence naming Zed as the product passed until somebody
28# added it. This one inverts the default -- every brand-bearing prose literal
29# in a derived inventory must be classified in the policy, and an unclassified
30# one fails.
31#
32# Policy lives in script/omega-brand-gate.json and is shared with
33# crates/omega_deltas so the source and packaged sides cannot drift.
34
35set -euo pipefail
36
37script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
38repository_root="${OMEGA_BRAND_VERIFY_ROOT:-$(cd "${script_dir}/.." && pwd)}"
39
40APP_PATH=""
41while [[ $# -gt 0 ]]; do
42 case "$1" in
43 --app)
44 APP_PATH="${2:-}"
45 if [[ -z "${APP_PATH}" ]]; then
46 echo "error: --app needs a path to an Omega.app bundle." >&2
47 exit 2
48 fi
49 shift
50 ;;
51 -h|--help)
52 echo "Usage: ${0##*/} [--app PATH_TO_OMEGA_APP]"
53 exit 0
54 ;;
55 *)
56 echo "error: unknown argument: $1" >&2
57 exit 2
58 ;;
59 esac
60 shift
61done
62
63python3 - "${repository_root}" "${APP_PATH}" <<'PY'
64from __future__ import annotations
65
66import functools
67import hashlib
68import json
69import plistlib
70import re
71import sys
72from pathlib import Path
73
74ROOT = Path(sys.argv[1]).resolve()
75APP = Path(sys.argv[2]).resolve() if sys.argv[2] else None
76
77POLICY = json.loads((ROOT / "script/omega-brand-gate.json").read_text(encoding="utf-8"))
78WORDS = POLICY["brand"]["words"]
79SUBSTRINGS = [value.lower() for value in POLICY["brand"]["substrings"]]
80ICONS = POLICY["icons"]
81EMBEDDED = POLICY["embedded_assets"]
82ENUMS = POLICY["asset_name_enums"]
83ACTIONS = POLICY["actions"]
84PROSE = POLICY["prose"]
85ALLOWED_STEMS = set(ICONS["third_party_allowances"])
86STEM_TOKENS = [token.lower() for token in ICONS["forbidden_stem_tokens"]]
87VARIANT_TOKENS = ICONS["forbidden_variant_tokens"]
88REVIEWED_MARKS = ICONS["reviewed_marks"]
89
90failures: list[str] = []
91
92
93def fail(message: str) -> None:
94 failures.append(message)
95
96
97def brand_hits(text: str) -> list[str]:
98 """Competitor brand names in `text`.
99
100 Words match case-sensitively at ASCII alphanumeric boundaries so that
101 'authorized' and 'normalized' are not reported, which is what a lowercase
102 substring rule would do. Substrings match case-insensitively.
103 """
104 hits: list[str] = []
105 for word in WORDS:
106 for match in re.finditer(re.escape(word), text):
107 before = text[match.start() - 1] if match.start() else ""
108 after = text[match.end()] if match.end() < len(text) else ""
109 if before.isalnum() or after.isalnum():
110 continue
111 hits.append(word)
112 break
113 lowered = text.lower()
114 hits.extend(substring for substring in SUBSTRINGS if substring in lowered)
115 return hits
116
117
118def stem_is_forbidden(stem: str) -> bool:
119 if stem in ALLOWED_STEMS:
120 return False
121 lowered = stem.lower()
122 return any(token in lowered for token in STEM_TOKENS)
123
124
125# ---------------------------------------------------------------- source mode
126
127
128def check_info_plist_fragments() -> None:
129 """OMEGA-DELTA-0017, source side.
130
131 Every file in the fragment directory is merged into Info.plist by
132 cargo-bundle, so the directory is walked rather than a list of known
133 files, and every value is read rather than a list of known keys. A new
134 key carrying a competitor's name is caught the same as a known one.
135 """
136 directory = ROOT / POLICY["info_plist"]["fragment_dir"]
137 if not directory.is_dir():
138 fail(f"info plist fragment directory is missing: {directory}")
139 return
140 fragments = sorted(path for path in directory.iterdir() if path.is_file())
141 if not fragments:
142 fail(f"info plist fragment directory is empty: {directory}")
143 return
144 for path in fragments:
145 text = path.read_text(encoding="utf-8", errors="replace")
146 # Report the owning key where the fragment gives one, so the failure
147 # names the macOS dialog the string would appear in.
148 key = None
149 for match in re.finditer(r"<key>(.*?)</key>|<string>(.*?)</string>", text, re.S):
150 if match.group(1) is not None:
151 key = match.group(1).strip()
152 continue
153 value = match.group(2)
154 for hit in brand_hits(value):
155 where = f"{path.relative_to(ROOT)}:{key or '<unkeyed>'}"
156 fail(f"OMEGA-DELTA-0017: {where} value names {hit!r}: {value.strip()!r}")
157 # Belt and braces: catch a brand name in a key, comment or attribute,
158 # which the key/value pass above does not read.
159 for hit in brand_hits(re.sub(r"<string>.*?</string>", "", text, flags=re.S)):
160 fail(
161 f"OMEGA-DELTA-0017: {path.relative_to(ROOT)} names {hit!r} "
162 "outside a <string> value"
163 )
164
165
166def check_icon_inventory() -> None:
167 """OMEGA-DELTA-0018, source side.
168
169 assets/icons and the IconName enum are kept in bijection by the icons
170 crate's own tests, so scanning both is a complete inventory of every icon
171 that can ship.
172 """
173 asset_dir = ROOT / ICONS["asset_dir"]
174 stems = sorted(path.stem for path in asset_dir.glob("*.svg"))
175 if not stems:
176 fail(f"icon asset directory is empty: {asset_dir}")
177 for stem in stems:
178 if stem_is_forbidden(stem):
179 fail(
180 f"OMEGA-DELTA-0018: {ICONS['asset_dir']}/{stem}.svg carries a "
181 "competitor's name. Replace the artwork and the file name, or "
182 "record why it identifies somebody else's product in "
183 "script/omega-brand-gate.json."
184 )
185
186 enum_source = (ROOT / ICONS["enum_source"]).read_text(encoding="utf-8")
187 body = re.search(r"pub enum IconName \{\n(.*?)\n\}", enum_source, re.S)
188 if body is None:
189 fail(f"cannot find the IconName enum in {ICONS['enum_source']}")
190 return
191 variants = [line.strip().rstrip(",") for line in body.group(1).splitlines() if line.strip()]
192 if not variants:
193 fail("the IconName enum parsed as empty; this check would be vacuous")
194 for variant in variants:
195 stem = re.sub(r"(?<!^)(?=[A-Z])", "_", variant).lower()
196 if stem in ALLOWED_STEMS:
197 continue
198 if any(token in variant for token in VARIANT_TOKENS):
199 fail(
200 f"OMEGA-DELTA-0018: IconName::{variant} carries a competitor's "
201 "name. Renaming the file without renaming the variant leaves "
202 "the next rebase a name to restore the artwork under."
203 )
204
205 for relative, expected in sorted(REVIEWED_MARKS.items()):
206 path = ROOT / relative
207 if not path.is_file():
208 fail(f"OMEGA-DELTA-0018: reviewed Omega mark is missing: {relative}")
209 continue
210 actual = hashlib.sha256(path.read_bytes()).hexdigest()
211 if actual != expected:
212 fail(
213 f"OMEGA-DELTA-0018: {relative} is not the reviewed artwork "
214 f"({actual} != {expected}). A name check cannot see a logo. If "
215 "this change is deliberate, look at the rendered icon and "
216 "update the pin in script/omega-brand-gate.json."
217 )
218
219
220# ------------------------------------------- OMEGA-DELTA-0022, shared parsers
221
222
223@functools.lru_cache(maxsize=None)
224def rust_sources(root: Path) -> tuple[tuple[Path, str], ...]:
225 """Every Rust source under `root`, read once and cached."""
226 return tuple(
227 (path, path.read_text(encoding="utf-8", errors="replace"))
228 for path in sorted(root.rglob("*.rs"))
229 if "/target/" not in str(path)
230 )
231
232
233@functools.lru_cache(maxsize=None)
234def embed_folders() -> tuple[tuple[str, Path], ...]:
235 """Every `#[folder = "..."]` in the repository, as (declaring file, folder).
236
237 rust-embed resolves the path against CARGO_MANIFEST_DIR, so the base is the
238 crate root, not the directory the attribute is written in.
239 """
240 found: list[tuple[str, Path]] = []
241 for path, text in rust_sources(ROOT / EMBEDDED["embed_declaration_root"]):
242 matches = re.findall(r'#\[folder\s*=\s*"([^"]+)"\]', text)
243 if not matches:
244 continue
245 crate_root = next(
246 (parent for parent in path.parents if (parent / "Cargo.toml").is_file()),
247 path.parent,
248 )
249 for folder in matches:
250 found.append((str(path.relative_to(ROOT)), (crate_root / folder).resolve()))
251 return tuple(found)
252
253
254@functools.lru_cache(maxsize=None)
255def embedded_asset_inventory() -> tuple[str, ...]:
256 """Every file rust-embed can ship, repository-relative.
257
258 The asset tree plus every directory any `#[folder = ...]` in the repository
259 points at. Not a list of asset directories: rust-embed ships whole
260 directories, so the directories it names are the inventory, and a list of
261 the ones somebody remembered is how assets/images/zed_logo.svg reached a
262 signed, notarized 0.2.0-rc11 while OMEGA-DELTA-0018 reported assets/icons/
263 clean, truthfully.
264
265 Deriving the roots from the embed declarations rather than writing them
266 here means a rust-embed folder added tomorrow is inside the gate the day it
267 is added, instead of being outside it until somebody notices.
268 """
269 roots = [ROOT / EMBEDDED["asset_root"]]
270 roots.extend(folder for _source, folder in embed_folders())
271 files: set[str] = set()
272 for root in roots:
273 if not root.is_dir():
274 continue
275 for path in root.rglob("*"):
276 if path.is_file() and path.name != ".DS_Store":
277 try:
278 files.add(str(path.resolve().relative_to(ROOT)))
279 except ValueError:
280 continue
281 return tuple(sorted(files))
282
283
284def action_declarations() -> list[tuple[str, str, str]]:
285 """Every gpui action in the repository as (namespace, name, file).
286
287 There are exactly two ways to declare one, and both are read here, so this
288 is the complete set of `namespace: action name` labels the command palette
289 can display.
290 """
291 declarations: list[tuple[str, str, str]] = []
292 root = ROOT / ACTIONS["search_root"]
293 for path, text in rust_sources(root):
294 relative = str(path.relative_to(ROOT))
295 for match in re.finditer(r"(?:gpui::)?actions!\(\s*", text):
296 head = re.match(r"([A-Za-z_][A-Za-z0-9_]*)(\s*,\s*\[)", text[match.end() :])
297 if head is None:
298 continue
299 namespace = head.group(1)
300 start = match.end() + head.end(2)
301 depth, index = 1, start
302 while index < len(text) and depth:
303 if text[index] == "[":
304 depth += 1
305 elif text[index] == "]":
306 depth -= 1
307 index += 1
308 for line in text[start : index - 1].splitlines():
309 stripped = line.strip().rstrip(",")
310 if re.fullmatch(r"[A-Z][A-Za-z0-9]*", stripped):
311 declarations.append((namespace, stripped, relative))
312 for match in re.finditer(
313 r"#\[action\(([^)]*)\)\]"
314 r"(?:\s*#\[[^\]]*\])*\s*pub\s+(?:struct|enum)\s+([A-Za-z0-9_]+)",
315 text,
316 re.S,
317 ):
318 namespace = re.search(
319 r"namespace\s*=\s*([A-Za-z_][A-Za-z0-9_]*)", match.group(1)
320 )
321 if namespace is not None:
322 declarations.append((namespace.group(1), match.group(2), relative))
323 return declarations
324
325
326# --------------------------------------------------- OMEGA-DELTA-0022, source
327
328
329@functools.lru_cache(maxsize=None)
330def asset_path_directories() -> frozenset[str]:
331 """Leading path segment of every embedded asset, as rust-embed keys it."""
332 root = Path(EMBEDDED["asset_root"])
333 directories = set()
334 for relative in embedded_asset_inventory():
335 path = Path(relative)
336 if path.parts[0] == root.name and len(path.parts) > 2:
337 directories.add(path.parts[1])
338 return frozenset(directories)
339
340
341def check_embedded_assets() -> None:
342 """OMEGA-DELTA-0022, source side."""
343 inventory = embedded_asset_inventory()
344 allowed = set(EMBEDDED["third_party_allowances"])
345 tokens = [token.lower() for token in EMBEDDED["forbidden_path_tokens"]]
346 minimum = EMBEDDED["minimum_inventory"]
347 if len(inventory) < minimum:
348 fail(
349 f"OMEGA-DELTA-0022: only {len(inventory)} embeddable files were "
350 f"found, below the {minimum} floor. The walk broke and this check "
351 "is reporting green about nothing."
352 )
353 if not embed_folders():
354 fail(
355 "OMEGA-DELTA-0022: no rust-embed #[folder] declarations were found, "
356 "so the inventory is no longer derived from what decides what ships"
357 )
358 for relative in inventory:
359 if relative in allowed:
360 continue
361 if any(token in relative.lower() for token in tokens):
362 fail(
363 f"OMEGA-DELTA-0022: {relative} carries a competitor's name and "
364 "is inside a directory rust-embed ships. Replace the artwork "
365 "and the file name, or record why it identifies somebody "
366 "else's product in script/omega-brand-gate.json."
367 )
368
369
370def check_asset_name_enums() -> None:
371 """Every enum that turns an identifier into an embedded asset path.
372
373 Discovered from the source rather than listed, because listing is what let
374 VectorName sit outside OMEGA-DELTA-0018 while IconName was inside it.
375 """
376 tokens = ENUMS["forbidden_variant_tokens"]
377 allowed = set(ENUMS["third_party_allowances"])
378 directories = asset_path_directories()
379 discovered: dict[str, list[str]] = {}
380 for _path, text in rust_sources(ROOT / ENUMS["search_root"]):
381 named = {
382 match.group(1)
383 for match in re.finditer(r'format!\(\s*"([A-Za-z0-9_]+)/\{', text)
384 if match.group(1) in directories
385 }
386 if not named:
387 continue
388 for match in re.finditer(r"pub enum ([A-Za-z0-9_]+) \{\n(.*?)\n\}", text, re.S):
389 name, body = match.group(1), match.group(2)
390 variants = [
391 line.strip().rstrip(",")
392 for line in body.splitlines()
393 if re.fullmatch(r"[A-Z][A-Za-z0-9]*,?", line.strip())
394 ]
395 if variants:
396 discovered[name] = variants
397
398 for required in ENUMS["required_discoveries"]:
399 if required not in discovered:
400 fail(
401 f"OMEGA-DELTA-0022: the asset-name-enum discovery no longer "
402 f"finds {required}. The parser broke and this check is "
403 "reporting green about nothing."
404 )
405 for name, variants in sorted(discovered.items()):
406 if len(variants) < ENUMS["minimum_variants"]:
407 fail(f"OMEGA-DELTA-0022: {name} parsed as {len(variants)} variants")
408 for variant in variants:
409 if f"{name}::{variant}" in allowed:
410 continue
411 if any(token in variant for token in tokens):
412 fail(
413 f"OMEGA-DELTA-0022: {name}::{variant} names a competitor "
414 "and resolves to a shipped asset. Renaming the file without "
415 "renaming the identifier leaves the next rebase a name to "
416 "restore the artwork under."
417 )
418
419
420def check_action_labels() -> None:
421 """OMEGA-DELTA-0022. The command palette shows every action's name."""
422 declarations = action_declarations()
423 minimum = ACTIONS["minimum_inventory"]
424 if len(declarations) < minimum:
425 fail(
426 f"OMEGA-DELTA-0022: only {len(declarations)} action declarations "
427 f"were parsed, below the {minimum} floor; this check is vacuous"
428 )
429 labels = {f"{namespace}::{name}" for namespace, name, _ in declarations}
430 for required in ACTIONS["required_actions"]:
431 if required not in labels:
432 fail(
433 f"OMEGA-DELTA-0022: {required} is not in the parsed action set, "
434 "so the parser is not reading the declarations it claims to"
435 )
436 allowed = set(ACTIONS["third_party_allowances"])
437 namespace_tokens = [token.lower() for token in ACTIONS["forbidden_namespace_tokens"]]
438 name_tokens = ACTIONS["forbidden_name_tokens"]
439 for namespace, name, source in sorted(declarations):
440 if f"{namespace}::{name}" in allowed:
441 continue
442 if any(token in namespace.lower() for token in namespace_tokens):
443 fail(
444 f"OMEGA-DELTA-0022: the command palette would offer "
445 f"'{namespace}: ...' from {source}. An action namespace is a "
446 "user-facing label, not an internal seam."
447 )
448 if any(token in name for token in name_tokens):
449 fail(
450 f"OMEGA-DELTA-0022: the command palette would offer "
451 f"'{namespace}::{name}' from {source}, which names a competitor."
452 )
453
454
455# ------------------------------------------- OMEGA-DELTA-0031, prose inventory
456
457
458PROSE_CLASSIFIED = PROSE["classified"]
459PROSE_CORPUS = set(PROSE["corpus_files"])
460SUGAR_DOC_LINE = re.compile(r"^\s*(?:///|//!)(.*)$")
461# `#[doc = "..."]` and `#[cfg_attr(<predicate>, doc = "...")]` are doc comments
462# written the long way, and clap and schemars read them exactly the same. The
463# gate did not, which is why `~/Library/Application Support/Zed` was printed as
464# the data directory by `cli --help` in every candidate up to 0.2.0-rc14 while
465# this file reported green -- the line is a `cfg_attr`, and nothing here had
466# ever looked inside one (omega#89).
467# Either `#[... doc = "..."]` on one line, or the `doc = "..."` line of an
468# attribute written across several. Anchoring on the line start keeps a Rust
469# `let doc = "..."` binding out.
470ATTR_DOC_LINE = re.compile(r'^\s*(?:#\[.*?)?\bdoc\s*=\s*"((?:[^"\\]|\\.)*)"')
471
472
473def doc_line_body(line: str) -> str | None:
474 """The text of a doc comment, however it was spelled."""
475 match = SUGAR_DOC_LINE.match(line)
476 if match is not None:
477 return match.group(1)
478 match = ATTR_DOC_LINE.match(line)
479 if match is not None:
480 return match.group(1)
481 return None
482DERIVES_SCHEMA = re.compile(r"#\[derive\([^)]*JsonSchema")
483DERIVES_CLAP = re.compile(r"#\[derive\([^)]*(?:Parser|Args|Subcommand)|#\[command\(|clap::Parser")
484PLAIN_WORD = re.compile(r"[A-Za-z']+")
485
486
487def normalize_prose(text: str) -> str:
488 return " ".join(text.split())
489
490
491def is_prose(text: str) -> bool:
492 """Prose-shaped: three tokens or more, at least two plain alphabetic words.
493
494 The one judgement in the whole derivation. It keeps identifiers, asset
495 paths and header names out of a registry that would otherwise be mostly
496 noise, and it is deliberately loose: `Zed Plex Sans` is three words and is
497 in the inventory, classified, rather than quietly filtered away.
498 """
499 tokens = text.split()
500 if len(tokens) < 3:
501 return False
502 plain = 0
503 for token in tokens:
504 trimmed = token.strip(
505 "".join(
506 character
507 for character in set(token)
508 if not ("a" <= character.lower() <= "z") and character != "'"
509 )
510 )
511 if trimmed and PLAIN_WORD.fullmatch(trimmed):
512 plain += 1
513 return plain >= 2
514
515
516COMMAND_ARGUMENT = re.compile(
517 r"^(?:--?[A-Za-z0-9][-A-Za-z0-9_.]*" # a flag: -n, --existing
518 r"|[<\[{][^\s>\]}]*[>\]}]" # a placeholder: <path>, [FILE]
519 r"|\.{1,2}|[~./][^\s]*)$" # a path: ., .., ~/x, ./x, /x
520)
521
522
523def is_command_form(text: str) -> bool:
524 """A command line whose program name is a competitor's binary.
525
526 `is_prose` needs three tokens, so `zed --existing`, `zed --classic` and
527 `zed <path>` were invisible to it -- and all three shipped in the signed
528 `cli` of `0.2.0-rc16`, inside a panel that says "Omega window" and "Omega
529 settings" around them (omega#93). Substituting our own name leaves each one
530 true, so by the rule this gate is written around they are product claims.
531
532 This is the narrow shape only: a brand word standing in argv[0], followed
533 by flags, placeholders or paths. Counting every two-token literal beginning
534 with a brand word instead adds 8 more across the tree -- `Zed Pro`, `Zed
535 (Default)`, `Zed Repository` -- which are genuine references to somebody
536 else's product and would need classifying; counting a bare brand token adds
537 55. This shape adds exactly the three, which is why the gate can carry it.
538 """
539 tokens = text.split()
540 if len(tokens) < 2 or tokens[0] not in WORDS:
541 return False
542 return all(COMMAND_ARGUMENT.fullmatch(token) for token in tokens[1:])
543
544
545def is_user_facing_text(text: str) -> bool:
546 """Prose, or a command form. What the inventory admits."""
547 return is_prose(text) or is_command_form(normalize_prose(text))
548
549
550def rust_string_literals(text: str) -> list[tuple[int, str]]:
551 """(start line, contents) for every Rust string literal in `text`.
552
553 Raw strings and multi-line strings included, comments skipped. A regex over
554 single lines misses exactly the literals that carry the longest copy: the
555 OAuth callback page, the root-user warning and four provider error
556 messages are all multi-line.
557 """
558 out: list[tuple[int, str]] = []
559 index, length, line = 0, len(text), 1
560 while index < length:
561 char = text[index]
562 if char == "\n":
563 line += 1
564 index += 1
565 continue
566 if text.startswith("//", index):
567 while index < length and text[index] != "\n":
568 index += 1
569 continue
570 if text.startswith("/*", index):
571 depth, index = 1, index + 2
572 while index < length and depth:
573 if text.startswith("/*", index):
574 depth += 1
575 index += 2
576 elif text.startswith("*/", index):
577 depth -= 1
578 index += 2
579 else:
580 if text[index] == "\n":
581 line += 1
582 index += 1
583 continue
584 if char == "r" and index + 1 < length and text[index + 1] in '"#':
585 cursor = index + 1
586 hashes = 0
587 while cursor < length and text[cursor] == "#":
588 hashes += 1
589 cursor += 1
590 if cursor < length and text[cursor] == '"':
591 start_line, cursor = line, cursor + 1
592 close = '"' + "#" * hashes
593 end = text.find(close, cursor)
594 if end == -1:
595 break
596 body = text[cursor:end]
597 line += body.count("\n")
598 out.append((start_line, body))
599 index = end + len(close)
600 continue
601 if char == '"':
602 start_line = line
603 cursor, buffer = index + 1, []
604 while cursor < length:
605 if text[cursor] == "\\":
606 line += text.count("\n", cursor, cursor + 2)
607 buffer.append(text[cursor : cursor + 2])
608 cursor += 2
609 continue
610 if text[cursor] == '"':
611 break
612 if text[cursor] == "\n":
613 line += 1
614 buffer.append(text[cursor])
615 cursor += 1
616 out.append((start_line, "".join(buffer)))
617 index = cursor + 1
618 continue
619 if char == "'":
620 if text.startswith("\\", index + 1):
621 index += 4
622 elif index + 2 < length and text[index + 2] == "'":
623 index += 3
624 else:
625 index += 1
626 continue
627 index += 1
628 return out
629
630
631TEST_PATH = re.compile(r"(^|/)(tests?|benches|examples|fixtures)/|_tests?\.rs$")
632
633
634def cfg_test_lines(text: str) -> set[int]:
635 """Line numbers inside a `#[cfg(test)]` item, which a release does not build.
636
637 Over-excluding here would be a hole, so the packaged half below reads the
638 binary that was actually built and does not honour this at all.
639 """
640 out: set[int] = set()
641 lines = text.splitlines()
642 for start, line in enumerate(lines):
643 if not re.match(r"\s*#\[cfg\(\s*(?:any\([^)]*)?test", line):
644 continue
645 depth, opened = 0, False
646 for cursor in range(start, len(lines)):
647 depth += lines[cursor].count("{") - lines[cursor].count("}")
648 if "{" in lines[cursor]:
649 opened = True
650 out.add(cursor + 1)
651 if opened and depth <= 0:
652 break
653 return out
654
655
656def action_doc_lines(text: str) -> set[int]:
657 """Doc lines the keymap editor renders as an action's description."""
658 out: set[int] = set()
659 lines = text.splitlines()
660 for match in re.finditer(r"(?:gpui::)?actions!\(", text):
661 depth, index = 0, match.end() - 1
662 while index < len(text):
663 if text[index] == "(":
664 depth += 1
665 elif text[index] == ")":
666 depth -= 1
667 if depth == 0:
668 break
669 index += 1
670 out.update(
671 range(text.count("\n", 0, match.start()) + 1, text.count("\n", 0, index) + 2)
672 )
673 for index, line in enumerate(lines):
674 if "#[action(" not in line:
675 continue
676 cursor = index - 1
677 while cursor >= 0 and (
678 doc_line_body(lines[cursor]) is not None
679 or lines[cursor].strip().startswith("#[")
680 ):
681 if doc_line_body(lines[cursor]) is not None:
682 out.add(cursor + 1)
683 cursor -= 1
684 return out
685
686
687@functools.lru_cache(maxsize=None)
688def prose_inventory() -> tuple[tuple[tuple[str, str, int, str], ...], dict[str, int]]:
689 """Every brand-bearing prose literal that can reach a user, plus read counts.
690
691 The counts are the anti-vacuity guard. They measure what the scanners read,
692 not what they found, because a clean tree finds nothing and a broken parser
693 also finds nothing.
694 """
695 items: list[tuple[str, str, int, str]] = []
696 read = dict(rust_files=0, literals=0, schema_docs=0, action_docs=0, clap_docs=0, embedded=0)
697 for path, text in rust_sources(ROOT / PROSE["rust_root"]):
698 relative = str(path.relative_to(ROOT))
699 read["rust_files"] += 1
700 literals = rust_string_literals(text)
701 read["literals"] += len(literals)
702 lines = text.splitlines()
703 code = "\n".join("" if doc_line_body(line) is not None else line for line in lines)
704 schema = bool(DERIVES_SCHEMA.search(code))
705 clap = bool(DERIVES_CLAP.search(code))
706 actions = action_doc_lines(text)
707 for number, line in enumerate(lines, 1):
708 if doc_line_body(line) is None:
709 continue
710 if number in actions:
711 read["action_docs"] += 1
712 elif schema:
713 read["schema_docs"] += 1
714 elif clap:
715 read["clap_docs"] += 1
716 if not brand_hits(text):
717 continue
718 is_test_file = bool(TEST_PATH.search(relative))
719 skipped = set() if is_test_file else cfg_test_lines(text)
720 for number, body in literals:
721 if is_test_file or number in skipped:
722 continue
723 if brand_hits(body) and is_user_facing_text(body):
724 items.append(("rust_string", relative, number, normalize_prose(body)))
725 for number, line in enumerate(lines, 1):
726 if is_test_file or number in skipped:
727 continue
728 doc = doc_line_body(line)
729 if doc is None or not brand_hits(doc) or not is_user_facing_text(doc):
730 continue
731 if number in actions:
732 kind = "action_doc"
733 elif schema:
734 kind = "schema_doc"
735 elif clap:
736 kind = "clap_doc"
737 else:
738 continue
739 items.append((kind, relative, number, normalize_prose(doc)))
740
741 for relative in embedded_asset_inventory():
742 read["embedded"] += 1
743 try:
744 text = (ROOT / relative).read_text(encoding="utf-8")
745 except (OSError, UnicodeDecodeError):
746 continue
747 if not brand_hits(text):
748 continue
749 for number, line in enumerate(text.splitlines(), 1):
750 if brand_hits(line) and is_user_facing_text(line):
751 items.append(("asset", relative, number, normalize_prose(line)))
752 return tuple(items), read
753
754
755def check_prose_inventory() -> None:
756 """OMEGA-DELTA-0031, source side."""
757 items, read = prose_inventory()
758 floors = [
759 ("minimum_rust_files", read["rust_files"], "Rust sources"),
760 ("minimum_rust_string_literals", read["literals"], "Rust string literals"),
761 ("minimum_schema_doc_lines", read["schema_docs"], "settings-schema doc lines"),
762 ("minimum_action_doc_lines", read["action_docs"], "action doc lines"),
763 ("minimum_clap_doc_lines", read["clap_docs"], "--help doc lines"),
764 ("minimum_embedded_files", read["embedded"], "embedded asset files"),
765 ]
766 for key, actual, label in floors:
767 if actual < PROSE[key]:
768 fail(
769 f"OMEGA-DELTA-0031: only {actual} {label} were read, below the "
770 f"{PROSE[key]} floor. That parser broke, and a check that reads "
771 "nothing reports green about nothing."
772 )
773
774 unclassified: list[str] = []
775 for kind, relative, number, text in items:
776 if relative in PROSE_CORPUS or text in PROSE_CLASSIFIED:
777 continue
778 unclassified.append(f"{relative}:{number} [{kind}] {text[:160]!r}")
779 for entry in sorted(set(unclassified)):
780 fail(
781 f"OMEGA-DELTA-0031: unclassified brand-bearing prose at {entry}. "
782 "Substitute our own name: if the sentence stays true with 'Omega' "
783 "in it, the brand was standing where our product's name belongs -- "
784 "rewrite it. If it becomes false, it names somebody else's product "
785 "and belongs in prose.classified with a class and a reason."
786 )
787
788 present = {text for _kind, _relative, _number, text in items}
789 for text, entry in PROSE_CLASSIFIED.items():
790 if entry.get("packaged_only") or text in present:
791 continue
792 fail(
793 f"OMEGA-DELTA-0031: prose.classified records {text[:80]!r}, which is "
794 "no longer anywhere in the tree. Either the sentence was removed and "
795 "the entry should go with it, or a scanner stopped reading the "
796 "stream that used to find it."
797 )
798
799
800# -------------------------------------------------------------- packaged mode
801
802
803def walk_plist(value, path: str):
804 if isinstance(value, dict):
805 for key, item in value.items():
806 yield f"{path}.{key}" if path else key, key
807 yield from walk_plist(item, f"{path}.{key}" if path else key)
808 elif isinstance(value, (list, tuple)):
809 for index, item in enumerate(value):
810 yield from walk_plist(item, f"{path}[{index}]")
811 elif isinstance(value, str):
812 yield path, value
813
814
815def check_packaged_info_plist(app: Path) -> None:
816 """OMEGA-DELTA-0017, packaged side.
817
818 Reads the merged Info.plist that actually ships, walking every value
819 rather than a list of keys, because macOS renders these strings in its own
820 permission dialogs under our Developer ID signature.
821 """
822 plists = sorted(app.rglob("*.plist"))
823 info = app / "Contents/Info.plist"
824 if not info.is_file():
825 fail(f"packaged Info.plist is missing: {info}")
826 return
827 for path in plists:
828 try:
829 data = plistlib.loads(path.read_bytes())
830 except Exception as error: # noqa: BLE001 - report, do not swallow
831 fail(f"cannot parse packaged plist {path}: {error}")
832 continue
833 for key_path, text in walk_plist(data, ""):
834 for hit in brand_hits(text):
835 fail(
836 f"OMEGA-DELTA-0017: packaged {path.relative_to(app.parent)} "
837 f"{key_path} names {hit!r}: {text!r}"
838 )
839
840
841# ---------------------------------- OMEGA-DELTA-0038, every shipped executable
842
843
844MACHO_MAGIC = (
845 b"\xcf\xfa\xed\xfe", # 64-bit little-endian
846 b"\xce\xfa\xed\xfe", # 32-bit little-endian
847 b"\xca\xfe\xba\xbe", # universal
848 b"\xbe\xba\xfe\xca", # universal, byte-swapped
849)
850
851
852@functools.lru_cache(maxsize=None)
853def bundle_executables(app: Path) -> tuple[Path, ...]:
854 """Every Mach-O executable the bundle ships, found by walking it.
855
856 Not a list of binary names. `script/bundle-omega-rc` copies and signs
857 `cli` and `omega-identity-proof` into `Contents/MacOS` beside `omega`, and
858 every packaged check here used to open `Contents/MacOS/omega` and nothing
859 else. That is why `cli` shipped an uninstaller that deleted a competitor's
860 application and none of ours through two published prereleases (omega#88),
861 with the gate reporting green about the bundle: the defect was never in a
862 file any check opened.
863
864 A helper added to the bundle tomorrow is inside the gate the day it is
865 added, the same way rust-embed's `#[folder]` declarations made the asset
866 inventory derived rather than remembered.
867 """
868 found: list[Path] = []
869 for path in sorted(app.rglob("*")):
870 if path.is_symlink() or not path.is_file():
871 continue
872 try:
873 head = path.open("rb").read(4)
874 except OSError:
875 continue
876 if head in MACHO_MAGIC:
877 found.append(path)
878 return tuple(found)
879
880
881def main_binary(app: Path) -> Path:
882 return app / "Contents/MacOS/omega"
883
884
885def check_packaged_executable_inventory(app: Path) -> None:
886 """Anti-vacuity for the walk above, and for the bundle it walked."""
887 executables = bundle_executables(app)
888 if not executables:
889 fail(
890 "OMEGA-DELTA-0038: no Mach-O executable was found anywhere in "
891 f"{app}. The walk broke, and every packaged check below is "
892 "reporting green about nothing."
893 )
894 return
895 if main_binary(app) not in executables:
896 fail(
897 f"OMEGA-DELTA-0038: {main_binary(app)} is not among the "
898 "executables found in the bundle"
899 )
900 minimum = POLICY.get("packaged", {}).get("minimum_executables", 2)
901 if len(executables) < minimum:
902 fail(
903 f"OMEGA-DELTA-0038: only {len(executables)} executables were found "
904 f"in the bundle, below the {minimum} floor. A bundle that ships a "
905 "companion binary and a scan that sees one binary is exactly the "
906 "shape omega#88 shipped in."
907 )
908
909
910def printable_runs(data: bytes, minimum: int = 8):
911 """Every printable ASCII run in a binary, as (start offset, text)."""
912 for run in re.finditer(rb"[\x20-\x7e]{%d,}" % minimum, data):
913 yield run.start(), run.group(0).decode("ascii")
914
915
916def check_packaged_first_party_agent(app: Path) -> None:
917 """OMEGA-DELTA-0024, packaged side.
918
919 `first_party_agent.phrases` had been applied to nothing by either half of
920 this gate since it was written: `grep -c first_party_agent
921 script/verify-omega-brand` returned 0, and the only reader was a Rust test
922 over the source tree. A reviewer had to run it by hand against a package
923 every time, which is the same as not having it (omega#89).
924 """
925 agent = POLICY["first_party_agent"]
926 phrases = [phrase.lower() for phrase in agent["phrases"]]
927 symbols = agent.get("symbols", [])
928 if not phrases:
929 fail("OMEGA-DELTA-0024: first_party_agent.phrases is empty; check vacuous")
930 return
931 identity = agent["identity"]
932 carried = False
933 for binary in bundle_executables(app):
934 data = binary.read_bytes()
935 if identity.encode() in data:
936 carried = True
937 for _offset, blob in printable_runs(data):
938 lowered = blob.lower()
939 for phrase in phrases:
940 if phrase in lowered:
941 at = lowered.index(phrase)
942 window = blob[max(0, at - 60) : at + len(phrase) + 60]
943 fail(
944 f"OMEGA-DELTA-0024: packaged "
945 f"{binary.relative_to(app.parent)} presents somebody "
946 f"else's agent as the first-party one: ...{window}..."
947 )
948 for symbol in symbols:
949 if symbol.encode() in data:
950 fail(
951 f"OMEGA-DELTA-0024: packaged "
952 f"{binary.relative_to(app.parent)} still carries the "
953 f"symbol {symbol!r}"
954 )
955 if not carried:
956 fail(
957 f"OMEGA-DELTA-0024: no packaged executable carries {identity!r}, so "
958 "this scan found nothing because it read nothing"
959 )
960
961
962# ------------------------------- OMEGA-DELTA-0038, help as the user reads it
963
964
965HELP_SUBCOMMAND = re.compile(r"^\s{2,}([a-z][a-z0-9-]*)(?:\s|$)")
966
967
968def rendered_output(binary: Path, arguments: list[str]) -> str | None:
969 """Run the shipped binary and return what it printed, or None if it could
970 not be run at all."""
971 import subprocess
972
973 try:
974 completed = subprocess.run(
975 [str(binary), *arguments],
976 capture_output=True,
977 timeout=120,
978 check=False,
979 cwd="/",
980 env={"PATH": "/usr/bin:/bin", "HOME": "/nonexistent-omega-brand-gate"},
981 )
982 except (OSError, subprocess.SubprocessError):
983 return None
984 return (completed.stdout + completed.stderr).decode("utf-8", errors="replace")
985
986
987def help_subcommands(text: str) -> list[str]:
988 """Subcommand names out of a clap `Commands:` block."""
989 names: list[str] = []
990 inside = False
991 for line in text.splitlines():
992 if line.rstrip().endswith(":"):
993 inside = line.strip() in ("Commands:", "Subcommands:")
994 continue
995 if not inside:
996 continue
997 if not line.strip():
998 continue
999 match = HELP_SUBCOMMAND.match(line)
1000 if match and match.group(1) not in ("help",):
1001 names.append(match.group(1))
1002 return names
1003
1004
1005def help_units(text: str) -> list[str]:
1006 """What a person reads, as they read it: whole descriptions, not lines.
1007
1008 clap wraps a description to the terminal width, so the sentence the user
1009 sees arrives split across several lines. Reading line by line hid exactly
1010 the defect this gate was written for: `~/Library/Application Support/Zed`
1011 lands as `... location: \`~/Library/Application` on one line and
1012 `Support/Zed\`` on the next, and neither fragment is three words. Blocks
1013 are joined back before anything is judged, and the individual lines are
1014 kept too, so a short label is still read on its own.
1015 """
1016 units: list[str] = []
1017 block: list[str] = []
1018 for line in text.splitlines():
1019 stripped = line.strip()
1020 if stripped:
1021 units.append(stripped)
1022 block.append(stripped)
1023 continue
1024 if block:
1025 units.append(" ".join(block))
1026 block = []
1027 if block:
1028 units.append(" ".join(block))
1029 return units
1030
1031
1032def check_rendered_help(app: Path) -> None:
1033 """OMEGA-DELTA-0038. The `--help` a person actually sees.
1034
1035 Every other stream in OMEGA-DELTA-0031 reads *source*: the doc line, the
1036 literal, the schema comment. clap does not print source. It joins several
1037 doc lines into one sentence, resolves `cfg_attr` for the platform it was
1038 built for, prints the flag *name* beside the description, and lays the
1039 whole thing out at run time. Nothing had ever read that output, which is
1040 how `--zed <ZED>`, `Run zed in the foreground` and a `--user-data-dir`
1041 line naming the wrong product's data directory all shipped in
1042 `0.2.0-rc14` under a green gate (omega#89).
1043
1044 This runs the binaries that ship, with `--help`, and reads what comes back.
1045 Subcommands are enumerated from the output rather than listed, so a
1046 subcommand added tomorrow is read the day it is added.
1047 """
1048 executables = bundle_executables(app)
1049 if not executables:
1050 return
1051 rendered = 0
1052 for binary in executables:
1053 pending: list[list[str]] = [["--help"], ["--version"]]
1054 seen: set[tuple[str, ...]] = set()
1055 while pending:
1056 arguments = pending.pop(0)
1057 key = tuple(arguments)
1058 if key in seen:
1059 continue
1060 seen.add(key)
1061 text = rendered_output(binary, arguments)
1062 if text is None:
1063 continue
1064 rendered += 1
1065 if arguments[-1] == "--help":
1066 for name in help_subcommands(text):
1067 if len(arguments) < 4:
1068 pending.append([*arguments[:-1], name, "--help"])
1069 where = f"{binary.relative_to(app.parent)} {' '.join(arguments)}"
1070
1071 # A flag name, a value placeholder and a subcommand are labels, not
1072 # sentences, so the prose rule below cannot see them -- `--zed
1073 # <ZED>` is two tokens. They are read here on their own terms, the
1074 # way an action namespace is: the palette shows `omega: about`, and
1075 # `--help` shows `--zed`, and both are copy the user reads.
1076 for token in set(re.findall(r"--[A-Za-z0-9][A-Za-z0-9-]*", text)):
1077 if brand_hits(token):
1078 fail(
1079 f"OMEGA-DELTA-0038: `{where}` offers the option "
1080 f"{token!r}, which names a competitor. An option name is "
1081 "a user-facing label; renaming the description and "
1082 "leaving the flag is half a rename."
1083 )
1084 for token in set(re.findall(r"<([A-Za-z0-9_]+)>", text)):
1085 if brand_hits(token) or brand_hits(token.capitalize()):
1086 fail(
1087 f"OMEGA-DELTA-0038: `{where}` names the value "
1088 f"placeholder <{token}>, which carries a competitor's "
1089 "name."
1090 )
1091 if arguments[-1] == "--help":
1092 for name in help_subcommands(text):
1093 if brand_hits(name):
1094 fail(
1095 f"OMEGA-DELTA-0038: `{where}` offers the subcommand "
1096 f"{name!r}, which names a competitor."
1097 )
1098
1099 for stripped in help_units(text):
1100 if not brand_hits(stripped):
1101 continue
1102 normalized = normalize_prose(stripped)
1103 if normalized in PROSE_CLASSIFIED:
1104 continue
1105 if any(
1106 fragment in normalized
1107 for fragment in packaged_covering_fragments()
1108 ):
1109 continue
1110 if not is_prose(normalized):
1111 continue
1112 fail(
1113 f"OMEGA-DELTA-0038: `{where}` prints a line naming a "
1114 f"competitor: {normalized!r}. This is the sentence the user "
1115 "reads; clap builds it at run time out of doc lines the "
1116 "source scan sees separately, so fixing it means fixing the "
1117 "text, not the check."
1118 )
1119 minimum = POLICY.get("packaged", {}).get("minimum_rendered_invocations", 4)
1120 if rendered < minimum:
1121 fail(
1122 f"OMEGA-DELTA-0038: only {rendered} rendered outputs were read, "
1123 f"below the {minimum} floor. The binaries did not run, and a gate "
1124 "that reads nothing reports green about nothing."
1125 )
1126
1127
1128def check_packaged_icons(app: Path) -> None:
1129 """OMEGA-DELTA-0018, packaged side.
1130
1131 Icons are embedded into the executable by rust-embed, so the packaged app
1132 has no assets directory. Both the asset path literals and the raw SVG
1133 bytes survive in the binary, so this checks the names AND the artwork.
1134 """
1135 binary = main_binary(app)
1136 if not binary.is_file():
1137 fail(f"packaged Omega binary is missing: {binary}")
1138 return
1139 data = binary.read_bytes()
1140
1141 # The name rule runs over every executable in the bundle; the artwork pin
1142 # runs over the one that embeds the assets.
1143 embedded_anywhere: set[str] = set()
1144 for executable in bundle_executables(app):
1145 blob = executable.read_bytes()
1146 embedded = sorted(
1147 {match.decode() for match in re.findall(rb"icons/[A-Za-z0-9_]+\.svg", blob)}
1148 )
1149 embedded_anywhere.update(embedded)
1150 for relative in embedded:
1151 stem = relative[len("icons/") : -len(".svg")]
1152 if stem_is_forbidden(stem):
1153 fail(
1154 f"OMEGA-DELTA-0018: packaged "
1155 f"{executable.relative_to(app.parent)} embeds {relative}"
1156 )
1157 if not embedded_anywhere:
1158 fail(
1159 "no embedded icon asset paths were found in any packaged binary; "
1160 "this check would be vacuous"
1161 )
1162
1163 for relative, expected in sorted(REVIEWED_MARKS.items()):
1164 source = ROOT / relative
1165 if not source.is_file():
1166 fail(f"OMEGA-DELTA-0018: reviewed Omega mark is missing: {relative}")
1167 continue
1168 artwork = source.read_bytes()
1169 if hashlib.sha256(artwork).hexdigest() != expected:
1170 fail(f"OMEGA-DELTA-0018: {relative} is not the reviewed artwork")
1171 continue
1172 if artwork not in data:
1173 fail(
1174 f"OMEGA-DELTA-0018: the reviewed artwork for {relative} is not "
1175 "in the packaged binary. The package was built from different "
1176 "bytes than the ones that were reviewed."
1177 )
1178
1179
1180def check_packaged_assets_and_actions(app: Path) -> None:
1181 """OMEGA-DELTA-0022, packaged side.
1182
1183 Assets are embedded into the executable by rust-embed and action names are
1184 built at compile time, so both survive in the binary as strings. The asset
1185 directories searched for are derived from the assets tree rather than
1186 listed, so a directory added tomorrow is read the same way assets/images/
1187 now is -- it was the missing directory in rc11, not a missing rule.
1188 """
1189 binary = main_binary(app)
1190 if not binary.is_file():
1191 fail(f"packaged Omega binary is missing: {binary}")
1192 return
1193 data = binary.read_bytes()
1194
1195 root = Path(EMBEDDED["asset_root"])
1196 directories = sorted(asset_path_directories())
1197 if not directories:
1198 fail("OMEGA-DELTA-0022: no asset directories were derived; check vacuous")
1199 return
1200 allowed = [
1201 relative[len(f"{root}/") :]
1202 for relative in EMBEDDED["third_party_allowances"]
1203 if relative.startswith(f"{root}/")
1204 ]
1205 tokens = [token.lower() for token in EMBEDDED["forbidden_path_tokens"]]
1206 directory_group = "|".join(re.escape(name) for name in directories)
1207
1208 # Rust string tables have no separators, so a match runs on into the next
1209 # literal. The scan is anchored on the forbidden token rather than trying
1210 # to find where one path ends: a match is reported only when a competitor's
1211 # name is inside something shaped like an embedded asset path, and an
1212 # allowance is accepted as a prefix of the run-on match.
1213 if not re.search(rb"(?:" + directory_group.encode() + rb")/", data):
1214 fail(
1215 "OMEGA-DELTA-0022: no embedded asset paths were found in the "
1216 "packaged binary; this check would be vacuous"
1217 )
1218 token_group = "|".join(re.escape(token) for token in tokens)
1219 pattern = rf"(?:{directory_group})/[\w./-]*(?:{token_group})[\w./-]*".encode()
1220 for executable in bundle_executables(app):
1221 blob = executable.read_bytes()
1222 for match in sorted({found.decode() for found in re.findall(pattern, blob)}):
1223 if any(match.startswith(entry) for entry in allowed):
1224 continue
1225 fail(
1226 f"OMEGA-DELTA-0022: packaged "
1227 f"{executable.relative_to(app.parent)} embeds {match}"
1228 )
1229
1230 # Action labels, checked by presence of the current ones.
1231 #
1232 # A stripped binary's string table has no separators and no type
1233 # information: `zed::About` appears as `zed::AboutOpens`, and a Rust module
1234 # path like `zed_edit_prediction_delegate::ZedEditPredictionDelegate` is
1235 # indistinguishable from an action name. An exhaustive absence check over
1236 # that is noise, and a noisy gate gets deleted. The absence rule is enforced
1237 # on the source, where a declaration can actually be read; what the package
1238 # can prove is that the labels the source declares are the labels that were
1239 # built. 0.2.0-rc11 carries `zed::About` and not `omega::About`, so this
1240 # rejects it, and a package built from a reverted tree fails the same way.
1241 required = ACTIONS["required_actions"]
1242 if not required:
1243 fail("OMEGA-DELTA-0022: actions.required_actions is empty; check vacuous")
1244 for label in required:
1245 if label.encode() not in data:
1246 fail(
1247 f"OMEGA-DELTA-0022: packaged Omega does not carry the action "
1248 f"label {label!r}. The package was built from a tree that still "
1249 "declares a competitor's namespace, whatever the source scan "
1250 "above says about this checkout."
1251 )
1252
1253
1254
1255@functools.lru_cache(maxsize=None)
1256def packaged_covering_fragments() -> list[str]:
1257 """Classified prose as it survives compilation, normalized.
1258
1259 A classified entry is the literal as written; the binary holds the value.
1260 Three differences matter and each produced a false failure the first time
1261 it was hit: a `\\` line continuation joins two lines with no separator, a
1262 `\\n` becomes a real newline that splits the printable run in half, and a
1263 non-ASCII character does the same thing. The packaged scan matches
1264 `[\\x20-\\x7e]` runs, so an em-dash or a curly quote inside a classified
1265 sentence ends the run there. A sentence whose brand mention sits past such
1266 a character could never cover its own occurrence, and the gate reported an
1267 offender that had been correctly classified all along.
1268
1269 Splitting is conservative rather than permissive: coverage requires a
1270 fragment to *span* the brand occurrence, so shorter fragments cover less,
1271 never more.
1272 """
1273 fragments: list[str] = []
1274 for text in PROSE_CLASSIFIED:
1275 joined = text.replace("\\ ", " ")
1276 # A `{}` placeholder is not in the binary either: rustc splits a format
1277 # string at every placeholder and stores the pieces, so a classified
1278 # sentence written with one could never cover its own occurrence in the
1279 # string table. Splitting there is conservative in the same direction as
1280 # the rules above -- shorter fragments cover less, never more.
1281 for part in re.split(r"\\[nrt]|\{[^{}]*\}|[^\x20-\x7e]+", joined):
1282 part = normalize_prose(part)
1283 if part and brand_hits(part):
1284 fragments.append(part)
1285 return fragments
1286
1287
1288def normalized_with_offsets(text: str) -> tuple[str, list[int]]:
1289 """`normalize_prose(text)` plus the source index each output character came
1290 from, so a brand occurrence in the raw run can be located in the normalized
1291 one."""
1292 out: list[str] = []
1293 offsets: list[int] = []
1294 pending = False
1295 for index, char in enumerate(text):
1296 if char.isspace():
1297 pending = bool(out)
1298 continue
1299 if pending:
1300 out.append(" ")
1301 offsets.append(index)
1302 pending = False
1303 out.append(char)
1304 offsets.append(index)
1305 return "".join(out), offsets
1306
1307
1308def check_packaged_prose(app: Path) -> None:
1309 """OMEGA-DELTA-0031, packaged side.
1310
1311 Every brand-bearing prose literal in the executable that actually ships,
1312 read out of the binary rather than out of the tree it was supposedly built
1313 from. This half does not honour `#[cfg(test)]`, does not care which crate a
1314 string came from, and sees generated files: the licence attribution page is
1315 gitignored and exists only here.
1316
1317 A stripped string table has no separators, so a literal runs on into its
1318 neighbour. The scan is therefore anchored on each brand occurrence and
1319 reports one only when the brand sits in running text AND no classified
1320 sentence spans that position.
1321 """
1322 binary = main_binary(app)
1323 if not binary.is_file():
1324 fail(f"packaged Omega binary is missing: {binary}")
1325 return
1326
1327 covering = packaged_covering_fragments()
1328 if not covering:
1329 fail("OMEGA-DELTA-0031: no classified prose carries a brand; check vacuous")
1330 return
1331
1332 scanned, offenders = 0, set()
1333 main_scanned = 0
1334 for executable in bundle_executables(app):
1335 data = executable.read_bytes()
1336 before = scanned
1337 scanned, found = scan_binary_prose(data, covering, scanned)
1338 if executable == binary:
1339 main_scanned = scanned - before
1340 for window in found:
1341 offenders.add((str(executable.relative_to(app.parent)), window))
1342 if scanned == 0 or main_scanned == 0:
1343 fail(
1344 "OMEGA-DELTA-0031: no brand-bearing prose was found in the packaged "
1345 "binaries at all, not even the classified third-party references. "
1346 "The string scan broke; a clean package still carries those."
1347 )
1348 for where, window in sorted(offenders):
1349 fail(
1350 f"OMEGA-DELTA-0031: packaged {where} carries unclassified prose: "
1351 f"...{window}... The package was built from a tree that still "
1352 "presents a competitor as the product, whatever the source scan "
1353 "above says about this checkout."
1354 )
1355
1356
1357# A brand occurrence only counts as prose when it is written as a word in
1358# running text. `/Zed/` in a path list, `ENV=Zed` in a task-template
1359# placeholder and `X-Zed-Predict-Edits-Mode` in an HTTP header are all
1360# neighbours of real sentences in a stripped string table, and reporting them
1361# is how a gate earns the reputation that gets it deleted.
1362BEFORE_OK = set(" (\"'`\t*[|>\u2014-")
1363AFTER_OK = set(" .,:;!?)]}'\"`<>/\u2014\u2026\t-")
1364
1365
1366def scan_binary_prose(
1367 data: bytes, covering: list[str], scanned: int
1368) -> tuple[int, set[str]]:
1369 """Brand occurrences in one executable's string table that no classified
1370 sentence spans. Returns the running scanned count and the offenders."""
1371 offenders: set[str] = set()
1372 for run in re.finditer(rb"[\x20-\x7e]{8,}", data):
1373 blob = run.group(0).decode("ascii")
1374 if not any(word in blob for word in WORDS):
1375 continue
1376 flat, offsets = normalized_with_offsets(blob)
1377 for word in WORDS:
1378 for match in re.finditer(re.escape(word), blob):
1379 start, end = match.start(), match.end()
1380 before = blob[start - 1] if start else " "
1381 after = blob[end] if end < len(blob) else " "
1382 if before.isalnum() or after.isalnum():
1383 continue
1384 if before not in BEFORE_OK or after not in AFTER_OK:
1385 continue
1386 # A brand hyphenated on both sides is part of an identifier.
1387 if before == "-" and after == "-":
1388 continue
1389 window = blob[max(0, start - 90) : end + 90]
1390 if not is_prose(window):
1391 continue
1392 scanned += 1
1393 try:
1394 flat_start = offsets.index(start)
1395 except ValueError:
1396 continue
1397 flat_end = flat_start + (end - start)
1398 covered = False
1399 for fragment in covering:
1400 at = flat.find(fragment)
1401 while at != -1 and not covered:
1402 if at <= flat_start and flat_end <= at + len(fragment):
1403 covered = True
1404 at = flat.find(fragment, at + 1)
1405 if covered:
1406 break
1407 if not covered:
1408 offenders.add(normalize_prose(window))
1409 return scanned, offenders
1410
1411
1412check_info_plist_fragments()
1413check_icon_inventory()
1414check_embedded_assets()
1415check_asset_name_enums()
1416check_action_labels()
1417check_prose_inventory()
1418if APP is not None:
1419 if not APP.is_dir():
1420 fail(f"packaged application is missing: {APP}")
1421 else:
1422 check_packaged_executable_inventory(APP)
1423 check_packaged_info_plist(APP)
1424 check_packaged_icons(APP)
1425 check_packaged_assets_and_actions(APP)
1426 check_packaged_prose(APP)
1427 check_packaged_first_party_agent(APP)
1428 check_rendered_help(APP)
1429
1430if failures:
1431 print("Omega brand gate FAILED:", file=sys.stderr)
1432 for failure in failures:
1433 print(f" - {failure}", file=sys.stderr)
1434 raise SystemExit(1)
1435
1436scope = "source tree" if APP is None else f"source tree and {APP}"
1437print(f"Omega brand gate ok ({scope})")
1438PY
1439